hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
e9e19b9fe9823a14ad2f4b9741f0ce517bd24ab5
471
hpp
C++
Engine/Include/Sapphire/Maths/Space/TrComps.hpp
SapphireSuite/Sapphire
f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47
[ "MIT" ]
2
2020-03-18T09:06:21.000Z
2020-04-09T00:07:56.000Z
Engine/Include/Sapphire/Maths/Space/TrComps.hpp
SapphireSuite/Sapphire
f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47
[ "MIT" ]
null
null
null
Engine/Include/Sapphire/Maths/Space/TrComps.hpp
SapphireSuite/Sapphire
f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47
[ "MIT" ]
null
null
null
// Copyright 2020 Sapphire development team. All Rights Reserved. #pragma once #ifndef SAPPHIRE_MATHS_TR_COMPS_GUARD #define SAPPHIRE_MATHS_TR_COMPS_GUARD #include <Core/Types/Int.hpp> namespace Sa { enum class TrComp : uint8 { None = 0, Position = 1 << 0, Rotation = 1 << 1, Scale = 1 << 2, // === Groups === PR = Position | Rotation, PS = Position | Scale, RS = Rotation | Scale, PRS = Position | Rotation | Scale, }; } #endif // GUARD
13.852941
65
0.649682
SapphireSuite
e9e2430d410fb5da9fcd33d9f7e3b3ddd6adee8c
8,588
hpp
C++
engine/engine/core/buffers/buffer.hpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
1
2020-04-14T13:55:16.000Z
2020-04-14T13:55:16.000Z
engine/engine/core/buffers/buffer.hpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
4
2020-09-25T22:34:29.000Z
2022-02-09T23:45:12.000Z
engine/engine/core/buffers/buffer.hpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
1
2022-01-28T16:37:51.000Z
2022-01-28T16:37:51.000Z
/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. */ #pragma once #include <memory> #include <type_traits> #include <utility> #include "engine/core/allocator/allocators.hpp" #include "engine/core/buffers/traits.hpp" #include "engine/core/byte.hpp" namespace isaac { // ------------------------------------------------------------------------------------------------- namespace detail { // A simple pointer which can be tagged. This is used for example to differentiate between a pointer // to host memory and a pointer to device memory. template <typename K, typename Tag = byte> class TaggedPointer { public: using value_t = std::remove_cv_t<K>; using const_pointer_t = TaggedPointer<const value_t, Tag>; using pointer_t = TaggedPointer<value_t, Tag>; using tag_t = Tag; // Standard constructor TaggedPointer(K* data = nullptr) : data_(data) {} // Default copy TaggedPointer(const TaggedPointer& other) = default; TaggedPointer& operator=(const TaggedPointer& other) = default; // Move will set source to nullptr TaggedPointer(TaggedPointer&& other) { *this = std::move(other); } TaggedPointer& operator=(TaggedPointer&& other) { data_ = other.data_; other.data_ = nullptr; return *this; } // Sets the actual pointer TaggedPointer& operator=(K* other) { data_ = other; return *this; } // Gets the actual pointer K* get() const { return data_; } operator K*() const { return data_; } private: K* data_; }; } // namespace detail // ------------------------------------------------------------------------------------------------- namespace detail { // Base class for Buffer and BufferView which provides storage for the memory pointer // and corresponding dimensions. template <typename Pointer> class BufferBase { public: using pointer_t = Pointer; BufferBase() : pointer_(nullptr), size_(0) {} BufferBase(Pointer pointer, size_t size) : pointer_(std::move(pointer)), size_(size) {} // pointer to the first row const Pointer& pointer() const { return pointer_; } // The total size of the buffer in bytes size_t size() const { return size_; } // A pointer to the first byte of the buffer. auto begin() const { return pointer_.get(); } // A pointer behind the last byte of the buffer. auto end() const { return begin() + size(); } protected: Pointer pointer_; size_t size_; }; } // namespace detail // ------------------------------------------------------------------------------------------------- // A buffer which owns its memory template <typename Pointer, typename Allocator> class Buffer : public detail::BufferBase<Pointer> { public: using mutable_view_t = detail::BufferBase<typename Pointer::pointer_t>; using const_view_t = detail::BufferBase<typename Pointer::const_pointer_t>; Buffer() : handle_(nullptr, Deleter{0}) {} // Allocates memory for `size` bytes. Buffer(size_t size) : detail::BufferBase<Pointer>(nullptr, size), handle_(Allocator::Allocate(size), Deleter{size}) { // 1) Initialize the base class with a nullptr, the number of rows, and the desired stride. // 2) Allocate memory and store it in the unique pointer used as handle. This will also change // the stride stored in the base class to the actual stride chosen by the allocator. // 3) Get a pointer to the allocated memory and store it in the base class so that calls to // pointer() actually work. this->pointer_ = handle_.get(); } Buffer(Buffer&& buffer) : detail::BufferBase<Pointer>(nullptr, buffer.size_), handle_(std::move(buffer.handle_)) { this->pointer_ = handle_.get(); buffer.pointer_ = nullptr; buffer.size_ = 0; } Buffer& operator=(Buffer&& buffer) { this->handle_ = std::move(buffer.handle_); this->pointer_ = this->handle_.get(); this->size_ = buffer.size_; buffer.pointer_ = nullptr; buffer.size_ = 0; return *this; } void resize(size_t desired_size) { if (desired_size == this->size()) return; *this = Buffer<Pointer, Allocator>(desired_size); } // Disowns the pointer from the buffer. The user is now responsible for deallocation. // WARNING: This is dangerous as the wrong allocator might be called. byte* release() { byte* pointer = handle_.release(); this->pointer_ = nullptr; return pointer; } // Creates a view which provides read and write access from this buffer object. mutable_view_t view() { return mutable_view_t(this->pointer_, this->size_, this->stride_); } const_view_t view() const { return const_view_t(typename Pointer::const_pointer_t(this->pointer_.get()), this->size_); } // Creates a view which only provides read access from this buffer object. const_view_t const_view() const { return const_view_t(typename Pointer::const_pointer_t(this->pointer_.get()), this->size_); } private: // A deleter object for the unique pointer to free allocated memory struct Deleter { size_t size; void operator()(byte* pointer) { if (size == 0) return; Allocator::Deallocate(pointer, size); } }; // A unique pointer is used to handle the allocator and to make this object non-copyable. using handle_t = std::unique_ptr<byte, Deleter>; // Memory handle used to automatically deallocate memory and to disallow copy semantics. handle_t handle_; }; // ------------------------------------------------------------------------------------------------- // A pointer to host memory template <typename K> using HostPointer = detail::TaggedPointer<K, std::integral_constant<BufferStorageMode, BufferStorageMode::Host>>; // A host buffer with stride which owns its memory using CpuBuffer = Buffer<HostPointer<byte>, CpuAllocator>; // A host buffer with stride which does not own its memory using CpuBufferView = detail::BufferBase<HostPointer<byte>>; // A host buffer with stride which does not own its memory and provides only read access using CpuBufferConstView = detail::BufferBase<HostPointer<const byte>>; template <> struct BufferTraits<Buffer<HostPointer<byte>, CpuAllocator>> { static constexpr BufferStorageMode kStorageMode = BufferStorageMode::Host; static constexpr bool kIsMutable = true; static constexpr bool kIsOwning = true; using buffer_view_t = CpuBufferView; using buffer_const_view_t = CpuBufferConstView; }; template <typename K> struct BufferTraits<detail::BufferBase<HostPointer<K>>> { static constexpr BufferStorageMode kStorageMode = BufferStorageMode::Host; static constexpr bool kIsMutable = !std::is_const<K>::value; static constexpr bool kIsOwning = false; using buffer_view_t = CpuBufferView; using buffer_const_view_t = CpuBufferConstView; }; // ------------------------------------------------------------------------------------------------- // A pointer to CUDA memory template <typename K> using CudaPointer = detail::TaggedPointer<K, std::integral_constant<BufferStorageMode, BufferStorageMode::Cuda>>; // A CUDA buffer with stride which owns its memory using CudaBuffer = Buffer<CudaPointer<byte>, CudaAllocator>; // A CUDA buffer with stride which does not own its memory using CudaBufferView = detail::BufferBase<CudaPointer<byte>>; // A CUDA buffer with stride which does not own its memory and provides only read access using CudaBufferConstView = detail::BufferBase<CudaPointer<const byte>>; template <> struct BufferTraits<Buffer<CudaPointer<byte>, CudaAllocator>> { static constexpr BufferStorageMode kStorageMode = BufferStorageMode::Cuda; static constexpr bool kIsMutable = true; static constexpr bool kIsOwning = true; using buffer_view_t = CudaBufferView; using buffer_const_view_t = CudaBufferConstView; }; template <typename K> struct BufferTraits<detail::BufferBase<CudaPointer<K>>> { static constexpr BufferStorageMode kStorageMode = BufferStorageMode::Cuda; static constexpr bool kIsMutable = !std::is_const<K>::value; static constexpr bool kIsOwning = false; using buffer_view_t = CudaBufferView; using buffer_const_view_t = CudaBufferConstView; }; // ------------------------------------------------------------------------------------------------- } // namespace isaac
34.079365
100
0.680135
ddr95070
e9e773d1fcbe1bbdfaadbcbae3b45b1baf2afd37
803
ipp
C++
include/network/protocol/http/client/connection_manager.ipp
iBeacons/cpp-netlib
9d03a037e465df96a98c1db5f3e50a865f501b64
[ "BSL-1.0" ]
1
2017-04-11T17:27:38.000Z
2017-04-11T17:27:38.000Z
include/network/protocol/http/client/connection_manager.ipp
iBeacons/cpp-netlib
9d03a037e465df96a98c1db5f3e50a865f501b64
[ "BSL-1.0" ]
null
null
null
include/network/protocol/http/client/connection_manager.ipp
iBeacons/cpp-netlib
9d03a037e465df96a98c1db5f3e50a865f501b64
[ "BSL-1.0" ]
null
null
null
// Copyright 2011 Dean Michael Berris <[email protected]>. // Copyright 2011 Google, 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 NETWORK_PROTOCOL_HTTP_CLIENT_CONNECTION_MANAGER_IPP_20111103 #define NETWORK_PROTOCOL_HTTP_CLIENT_CONNECTION_MANAGER_IPP_20111103 #include <network/protocol/http/client/connection_manager.hpp> #include <network/detail/debug.hpp> namespace network { namespace http { connection_manager::~connection_manager() { NETWORK_MESSAGE("connection_manager::~connection_manager()"); // default implementation, for linkage only. } } // namespace http } // namespace network #endif /* NETWORK_PROTOCOL_HTTP_CLIENT_CONNECTION_MANAGER_IPP_20111103 */
33.458333
73
0.801993
iBeacons
e9ee1d5b06d1784ea7b044621adae46fbb1b4c7f
459
hpp
C++
module/ngx_http_java_module/ngx_http_java_module.hpp
webcpp/hinginx
b380df41df5cd4763fba2a01a0fa0738bf6e5d4d
[ "BSD-2-Clause" ]
null
null
null
module/ngx_http_java_module/ngx_http_java_module.hpp
webcpp/hinginx
b380df41df5cd4763fba2a01a0fa0738bf6e5d4d
[ "BSD-2-Clause" ]
null
null
null
module/ngx_http_java_module/ngx_http_java_module.hpp
webcpp/hinginx
b380df41df5cd4763fba2a01a0fa0738bf6e5d4d
[ "BSD-2-Clause" ]
null
null
null
#pragma once extern "C" { #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> } #include <regex> #include <memory> #include "java.hpp" static std::shared_ptr<std::regex> java_uri_re = nullptr; static std::shared_ptr<hi::java> java_engine = nullptr; typedef struct { ngx_str_t class_path; ngx_str_t options; ngx_str_t servlet; ngx_str_t uri_pattern; ngx_int_t expires; ngx_int_t version; } ngx_http_java_loc_conf_t;
17.653846
57
0.727669
webcpp
e9f4462d7dcf69b6cdb7b0f0cd6fffc36658416c
3,755
hpp
C++
src/tools/log.hpp
otgaard/zap
d50e70b5baf5f0fbf7a5a98d80c4d1bcc6166215
[ "MIT" ]
8
2016-04-24T21:02:59.000Z
2021-11-14T20:37:17.000Z
src/tools/log.hpp
otgaard/zap
d50e70b5baf5f0fbf7a5a98d80c4d1bcc6166215
[ "MIT" ]
null
null
null
src/tools/log.hpp
otgaard/zap
d50e70b5baf5f0fbf7a5a98d80c4d1bcc6166215
[ "MIT" ]
1
2018-06-09T19:51:38.000Z
2018-06-09T19:51:38.000Z
/* Created by Darren Otgaar on 2016/03/05. http://www.github.com/otgaard/zap */ #ifndef ZAP_LOG_HPP #define ZAP_LOG_HPP #include <mutex> #include <memory> #include <sstream> #include <iostream> #include <functional> #include <core/core.hpp> #if !defined(_WIN32) const char* const LOG_RESET = "\033[0m"; const char* const LOG_BLACK = "\033[30m"; const char* const LOG_RED = "\033[31m"; const char* const LOG_GREEN = "\033[32m"; const char* const LOG_YELLOW = "\033[33m"; const char* const LOG_BLUE = "\033[34m"; const char* const LOG_MAGENTA = "\033[35m"; const char* const LOG_CYAN = "\033[36m"; const char* const LOG_WHITE = "\033[37m"; const char* const LOG_BOLDBLACK = "\033[1m\033[30m"; const char* const LOG_BOLDRED = "\033[1m\033[31m"; const char* const LOG_BOLDGREEN = "\033[1m\033[32m"; const char* const LOG_BOLDYELLOW = "\033[1m\033[33m"; const char* const LOG_BOLDBLUE = "\033[1m\033[34m"; const char* const LOG_BOLDMAGENTA = "\033[1m\033[35m"; const char* const LOG_BOLDCYAN = "\033[1m\033[36m"; const char* const LOG_BOLDWHITE = "\033[1m\033[37m"; #else const char* const LOG_RESET = ""; const char* const LOG_BLACK = ""; const char* const LOG_RED = ""; const char* const LOG_GREEN = ""; const char* const LOG_YELLOW = ""; const char* const LOG_BLUE = ""; const char* const LOG_MAGENTA = ""; const char* const LOG_CYAN = ""; const char* const LOG_WHITE = ""; const char* const LOG_BOLDBLACK = ""; const char* const LOG_BOLDRED = ""; const char* const LOG_BOLDGREEN = ""; const char* const LOG_BOLDYELLOW = ""; const char* const LOG_BOLDBLUE = ""; const char* const LOG_BOLDMAGENTA = ""; const char* const LOG_BOLDCYAN = ""; const char* const LOG_BOLDWHITE = ""; #endif namespace zap { namespace tools { enum class log_level : uint8_t { LL_DEBUG, LL_WARNING, LL_ERROR }; inline void def_cleanup_fnc(std::ostream* stream) { UNUSED(stream); } class logger { public: using cleanup_fnc = std::function<void(std::ostream*)>; logger(std::ostream* ostream_ptr, cleanup_fnc fnc=def_cleanup_fnc) : fnc_(fnc), ostream_(ostream_ptr), sstream_("") { } virtual ~logger() { if(fnc_) fnc_(ostream_); } template<log_level level, typename... Args> void print(Args... args) { std::unique_lock<std::mutex> lock(lock_); switch(level) { case log_level::LL_DEBUG: sstream_ << "<DEBUG>:"; break; case log_level::LL_ERROR: sstream_ << "<ERROR>:" << LOG_BOLDRED; break; case log_level::LL_WARNING: sstream_ << "<WARNING>:" << LOG_BOLDYELLOW; break; } print_i(args...); } private: void print_i() { (*ostream_) << sstream_.rdbuf() << LOG_RESET << std::endl; } template<typename T, typename... Args> void print_i(T first, Args... rest) { sstream_ << first << " "; print_i(rest...); } cleanup_fnc fnc_; std::ostream* ostream_; std::stringstream sstream_; std::mutex lock_; }; }} static zap::tools::logger default_log(&std::cout); #if defined(LOGGING_ENABLED) #define LOG default_log.print<zap::tools::log_level::LL_DEBUG> #define LOG_ERR default_log.print<zap::tools::log_level::LL_ERROR> #define LOG_WARN default_log.print<zap::tools::log_level::LL_WARNING> #else //!LOGGING_ENABLED #define LOG(...) do {} while (0) //#define LOG_ERR(...) #define LOG_ERR default_log.print<zap::tools::log_level::LL_ERROR> #define LOG_WARN(...) do {} while (0) #endif //!LOGGING_ENABLED #endif //ZAP_LOG_HPP
33.230088
110
0.621039
otgaard
1800a88c6a34573069996679dd42487ce4aac0a4
2,520
hpp
C++
modules/scene_manager/include/nav_msgs/srv/set_map__response__rosidl_typesupport_opensplice_cpp.hpp
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
modules/scene_manager/include/nav_msgs/srv/set_map__response__rosidl_typesupport_opensplice_cpp.hpp
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
3
2019-11-14T12:20:06.000Z
2020-08-07T13:51:10.000Z
modules/scene_manager/include/nav_msgs/srv/set_map__response__rosidl_typesupport_opensplice_cpp.hpp
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
// generated from // rosidl_typesupport_opensplice_cpp/resource/msg__rosidl_typesupport_opensplice_cpp.hpp.em // generated code does not contain a copyright notice #ifndef NAV_MSGS__SRV__SET_MAP__RESPONSE__ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_HPP_ #define NAV_MSGS__SRV__SET_MAP__RESPONSE__ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_HPP_ #include "nav_msgs/srv/set_map__response__struct.hpp" #include "nav_msgs/srv/dds_opensplice/ccpp_SetMap_Response_.h" #include "rosidl_generator_c/message_type_support_struct.h" #include "rosidl_typesupport_interface/macros.h" #include "nav_msgs/msg/rosidl_typesupport_opensplice_cpp__visibility_control.h" namespace DDS { class DomainParticipant; class DataReader; class DataWriter; } // namespace DDS namespace nav_msgs { namespace srv { namespace typesupport_opensplice_cpp { ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_PUBLIC_nav_msgs extern void register_type__SetMap_Response( DDS::DomainParticipant * participant, const char * type_name); ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_PUBLIC_nav_msgs extern void convert_ros_message_to_dds( const nav_msgs::srv::SetMap_Response & ros_message, nav_msgs::srv::dds_::SetMap_Response_ & dds_message); ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_PUBLIC_nav_msgs extern void publish__SetMap_Response( DDS::DataWriter * topic_writer, const void * untyped_ros_message); ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_PUBLIC_nav_msgs extern void convert_dds_message_to_ros( const nav_msgs::srv::dds_::SetMap_Response_ & dds_message, nav_msgs::srv::SetMap_Response & ros_message); ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_PUBLIC_nav_msgs extern bool take__SetMap_Response( DDS::DataReader * topic_reader, bool ignore_local_publications, void * untyped_ros_message, bool * taken); ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_EXPORT_nav_msgs const char * serialize__SetMap_Response( const void * untyped_ros_message, void * serialized_data); ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_EXPORT_nav_msgs const char * deserialize__SetMap_Response( const uint8_t * buffer, unsigned length, void * untyped_ros_message); } // namespace typesupport_opensplice_cpp } // namespace srv } // namespace nav_msgs #ifdef __cplusplus extern "C" { #endif ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_PUBLIC_nav_msgs const rosidl_message_type_support_t * ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_opensplice_cpp, nav_msgs, srv, SetMap_Response)(); #ifdef __cplusplus } #endif #endif // NAV_MSGS__SRV__SET_MAP__RESPONSE__ROSIDL_TYPESUPPORT_OPENSPLICE_CPP_HPP_
27.096774
121
0.846825
Omnirobotic
18013dd6c8dc8cf0aa00540f743c54b5c61b9a94
901
cpp
C++
src/main/cpp/Autonomous/Steps/TimedDrive.cpp
FRCTeam16/TMW2021OMB
5ac92a1ac2030d2913c18ba7a55450a4b46abbc7
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/Autonomous/Steps/TimedDrive.cpp
FRCTeam16/TMW2021OMB
5ac92a1ac2030d2913c18ba7a55450a4b46abbc7
[ "BSD-3-Clause" ]
9
2022-01-24T17:02:09.000Z
2022-01-24T17:02:11.000Z
src/main/cpp/Autonomous/Steps/TimedDrive.cpp
FRCTeam16/TMW2021OMB
5ac92a1ac2030d2913c18ba7a55450a4b46abbc7
[ "BSD-3-Clause" ]
1
2022-02-20T02:09:17.000Z
2022-02-20T02:09:17.000Z
#include "Autonomous/Steps/TimedDrive.h" #include "Robot.h" #include "Util/RampUtil.h" bool TimedDrive::Run(std::shared_ptr<World> world) { const double currentTime = world->GetClock(); if (startTime < 0) { startTime = currentTime; Robot::driveBase->UseOpenLoopDrive(); Robot::driveBase->SetTargetAngle(angle); std::cout << "TimedDrive(" << angle << ", " << ySpeed << ", " << xSpeed << ", " << timeToDrive << ", " << useGyro << ")\n"; } const double elapsed = currentTime - startTime; if (elapsed > timeToDrive) { return true; } else { // const double twist = (useTwist) ? Robot::driveBase->GetTwistControlOutput() : 0.0; double y = ySpeed; if (rampUpTime > 0) { y = RampUtil::RampUp(ySpeed, elapsed, rampUpTime); } crab->Update( (float) Robot::driveBase->GetTwistControlOutput(), (float) y, (float) xSpeed, useGyro); return false; } }
25.742857
87
0.63374
FRCTeam16
18037e0167f3a34a25ee74d5e4da2b275d5d72bd
506
inl
C++
Refureku/Library/Include/Public/Refureku/TypeInfo/Archetypes/Template/ClassTemplate.inl
jsoysouvanh/Refureku
7548cb3b196793119737a51c1cedc136aa60d3ee
[ "MIT" ]
143
2020-04-07T21:38:21.000Z
2022-03-30T01:06:33.000Z
Refureku/Library/Include/Public/Refureku/TypeInfo/Archetypes/Template/ClassTemplate.inl
jsoysouvanh/Refureku
7548cb3b196793119737a51c1cedc136aa60d3ee
[ "MIT" ]
7
2021-03-30T07:26:21.000Z
2022-03-28T16:31:02.000Z
Refureku/Library/Include/Public/Refureku/TypeInfo/Archetypes/Template/ClassTemplate.inl
jsoysouvanh/Refureku
7548cb3b196793119737a51c1cedc136aa60d3ee
[ "MIT" ]
11
2020-06-06T09:45:12.000Z
2022-01-25T17:17:55.000Z
/** * Copyright (c) 2021 Julien SOYSOUVANH - All Rights Reserved * * This file is part of the Refureku library project which is released under the MIT License. * See the README.md file for full license details. */ template <std::size_t ArgsCount> ClassTemplateInstantiation const* ClassTemplate::getTemplateInstantiation(TemplateArgument const* (&args)[ArgsCount]) const noexcept { if constexpr (ArgsCount > 0) { return getTemplateInstantiation(&args[0], ArgsCount); } else { return nullptr; } }
26.631579
132
0.756917
jsoysouvanh
1805dd093a477beba6418965c96f7860355a4e63
2,944
cpp
C++
libraries/chain/wast_to_wasm.cpp
yinchengtsinghua/EOSIOChineseCPP
dceabf6315ab8c9a064c76e943b2b44037165a85
[ "MIT" ]
21
2019-01-23T04:17:48.000Z
2021-11-15T10:50:33.000Z
libraries/chain/wast_to_wasm.cpp
jiege1994/EOSIOChineseCPP
dceabf6315ab8c9a064c76e943b2b44037165a85
[ "MIT" ]
1
2019-08-06T07:53:54.000Z
2019-08-13T06:51:29.000Z
libraries/chain/wast_to_wasm.cpp
jiege1994/EOSIOChineseCPP
dceabf6315ab8c9a064c76e943b2b44037165a85
[ "MIT" ]
11
2019-01-24T07:47:43.000Z
2020-10-29T02:18:20.000Z
//此源码被清华学神尹成大魔王专业翻译分析并修改 //尹成QQ77025077 //尹成微信18510341407 //尹成所在QQ群721929980 //尹成邮箱 [email protected] //尹成毕业于清华大学,微软区块链领域全球最有价值专家 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 /* *@文件 *@eos/license中定义的版权 **/ #include <eosio/chain/wast_to_wasm.hpp> #include <Inline/BasicTypes.h> #include <IR/Module.h> #include <IR/Validate.h> #include <WAST/WAST.h> #include <WASM/WASM.h> #include <Runtime/Runtime.h> #include <sstream> #include <iomanip> #include <fc/exception/exception.hpp> #include <eosio/chain/exceptions.hpp> namespace eosio { namespace chain { std::vector<uint8_t> wast_to_wasm( const std::string& wast ) { std::stringstream ss; try { IR::Module module; std::vector<WAST::Error> parse_errors; WAST::parseModule(wast.c_str(),wast.size(),module,parse_errors); if(parse_errors.size()) { //打印任何分析错误; ss << "Error parsing WebAssembly text file:" << std::endl; for(auto& error : parse_errors) { ss << ":" << error.locus.describe() << ": " << error.message.c_str() << std::endl; ss << error.locus.sourceLine << std::endl; ss << std::setw(error.locus.column(8)) << "^" << std::endl; } EOS_ASSERT( false, wasm_exception, "error parsing wast: ${msg}", ("msg",ss.str()) ); } for(auto sectionIt = module.userSections.begin();sectionIt != module.userSections.end();++sectionIt) { if(sectionIt->name == "name") { module.userSections.erase(sectionIt); break; } } try { //序列化WebAssembly模块。 Serialization::ArrayOutputStream stream; WASM::serialize(stream,module); return stream.getBytes(); } catch(const Serialization::FatalSerializationException& exception) { ss << "Error serializing WebAssembly binary file:" << std::endl; ss << exception.message << std::endl; EOS_ASSERT( false, wasm_exception, "error converting to wasm: ${msg}", ("msg",ss.get()) ); } catch(const IR::ValidationException& e) { ss << "Error validating WebAssembly binary file:" << std::endl; ss << e.message << std::endl; EOS_ASSERT( false, wasm_exception, "error converting to wasm: ${msg}", ("msg",ss.get()) ); } } FC_CAPTURE_AND_RETHROW( (wast) ) } ///WestytotoWASM std::string wasm_to_wast( const std::vector<uint8_t>& wasm, bool strip_names ) { return wasm_to_wast( wasm.data(), wasm.size(), strip_names ); } //WasmithtoWaster std::string wasm_to_wast( const uint8_t* data, uint64_t size, bool strip_names ) { try { IR::Module module; Serialization::MemoryInputStream stream((const U8*)data,size); WASM::serialize(stream,module); if(strip_names) module.userSections.clear(); //将模块打印到WAST。 return WAST::print(module); } FC_CAPTURE_AND_RETHROW() } //WasmithtoWaster } } //EOSIO:链
32.351648
106
0.631114
yinchengtsinghua
180d3973f99e8ca145b1117d02ee90392b76c118
1,696
cpp
C++
Laborator8/Project1/Project1/Source.cpp
GeorgeDenis/oop-2022
45b026f762a85c4e683f413b5c785b7e8541de04
[ "MIT" ]
null
null
null
Laborator8/Project1/Project1/Source.cpp
GeorgeDenis/oop-2022
45b026f762a85c4e683f413b5c785b7e8541de04
[ "MIT" ]
null
null
null
Laborator8/Project1/Project1/Source.cpp
GeorgeDenis/oop-2022
45b026f762a85c4e683f413b5c785b7e8541de04
[ "MIT" ]
1
2022-02-23T16:38:17.000Z
2022-02-23T16:38:17.000Z
#define _CRT_SECURE_NO_WARNINGS #include <string> #include <map> #include <cstdio> #include <iostream> #include <queue> using namespace std; bool Comparare(pair<string, int>& stanga, pair<string, int>& dreapta) { if (stanga.second != dreapta.second) return stanga.second < dreapta.second; else { return stanga.first.compare(dreapta.first) > 0; } } int main() { FILE* f = fopen("H:\\PROGRAMAREORIENTATEOBIECT\\Fork\\oop-2022\\Laborator8\\Project1\\Project1\\Text.txt", "r"); if (f == nullptr) { printf("Eroare!!\n"); exit(1); } string sir; char subsir[4096]; while (!feof(f)) { auto text = fread(subsir, 1, sizeof(subsir), f); sir.append(subsir, text); } fclose(f); for (int i = 0; i < sir.size(); i++) sir[i] = tolower(sir[i]); map<string, int> m; int poz = 0; int start = 0; int pozitie = sir.find_first_of(" ,?!.", poz); string cuvant; while (pozitie != string::npos) { cuvant = sir.substr(start, pozitie - start); m[cuvant]++; poz = pozitie + 1; start = sir.find_first_not_of(" ,?!.", poz); poz = start; pozitie = sir.find_first_of(" ,?!.", poz); } priority_queue<pair<string, int>, vector<pair<string, int>>, decltype(&Comparare)> queue(Comparare); map<string, int>::iterator it = m.begin(); while (it != m.end()) { pair<string, int> p; p.first = it->first; p.second = it->second; queue.push(p); it++; } while (!queue.empty()) { cout << queue.top().first << " => " << queue.top().second << "\n"; queue.pop(); } return 0; }
27.803279
116
0.551887
GeorgeDenis
180d5d3920f5966139b418540bceb4a9fdcb0a55
1,005
cpp
C++
evias/core/ro_container.cpp
evias/evias
5b5d4c16404f855c3234afa05b11c339a3ebb4cb
[ "BSD-3-Clause" ]
1
2015-10-31T03:18:02.000Z
2015-10-31T03:18:02.000Z
evias/core/ro_container.cpp
evias/evias
5b5d4c16404f855c3234afa05b11c339a3ebb4cb
[ "BSD-3-Clause" ]
null
null
null
evias/core/ro_container.cpp
evias/evias
5b5d4c16404f855c3234afa05b11c339a3ebb4cb
[ "BSD-3-Clause" ]
null
null
null
#include "ro_container.cpp" using namespace evias::core; evias::core::readOnlyContainer::readOnlyContainer() : _dataPointer(0), _dataSize(0) { } evias::core::readOnlyContainer::readOnlyContainer(const Container* copy) : _dataPointer(copy->getData()), _dataSize(copy->getSize()) { } evias::core::readOnlyContainer::readOnlyContainer(const uint8_t* pointer, uint64_t size) : _dataPointer(pointer), _dataSize(size) { } evias::core::readOnlyContainer::readOnlyContainer(const void* pointer, uint64_t size) : _dataPointer(reinterpret_cast<const uint8_t*> (pointer)), _dataSize(size) { } evias::core::readOnlyContainer::~readOnlyContainer() { } Container* evias::core::readOnlyContainer::getCopy() const { return new readOnlyContainer(this->getData(), this->getSize()); } const uint8_t* evias::core::readOnlyContainer::getData() const { return _dataPointer; } uint64_t evias::core::readOnlyContainer::getSize() const { return _dataSize; }
20.1
88
0.715423
evias
180f1e49d0102a23cdbcbe6d013dc76e3c430b66
2,557
cpp
C++
MaterialLib/FractureModels/CreateMohrCoulomb.cpp
HaibingShao/ogs6_ufz
d4acfe7132eaa2010157122da67c7a4579b2ebae
[ "BSD-4-Clause" ]
null
null
null
MaterialLib/FractureModels/CreateMohrCoulomb.cpp
HaibingShao/ogs6_ufz
d4acfe7132eaa2010157122da67c7a4579b2ebae
[ "BSD-4-Clause" ]
null
null
null
MaterialLib/FractureModels/CreateMohrCoulomb.cpp
HaibingShao/ogs6_ufz
d4acfe7132eaa2010157122da67c7a4579b2ebae
[ "BSD-4-Clause" ]
null
null
null
/** * \copyright * Copyright (c) 2012-2017, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include "CreateMohrCoulomb.h" #include "ProcessLib/Utils/ProcessUtils.h" // required for findParameter #include "MohrCoulomb.h" namespace MaterialLib { namespace Fracture { template <int DisplacementDim> std::unique_ptr<FractureModelBase<DisplacementDim>> createMohrCoulomb( std::vector<std::unique_ptr<ProcessLib::ParameterBase>> const& parameters, BaseLib::ConfigTree const& config) { //! \ogs_file_param{material__solid__constitutive_relation__type} config.checkConfigParameter("type", "MohrCoulomb"); DBUG("Create MohrCoulomb material"); auto& Kn = ProcessLib::findParameter<double>( //! \ogs_file_param_special{material__solid__constitutive_relation__MohrCoulomb__normal_stiffness} config, "normal_stiffness", parameters, 1); auto& Ks = ProcessLib::findParameter<double>( //! \ogs_file_param_special{material__solid__constitutive_relation__MohrCoulomb__shear_stiffness} config, "shear_stiffness", parameters, 1); auto& friction_angle = ProcessLib::findParameter<double>( //! \ogs_file_param_special{material__solid__constitutive_relation__MohrCoulomb__friction_angle} config, "friction_angle", parameters, 1); auto& dilatancy_angle = ProcessLib::findParameter<double>( //! \ogs_file_param_special{material__solid__constitutive_relation__MohrCoulomb__dilatancy_angle} config, "dilatancy_angle", parameters, 1); auto& cohesion = ProcessLib::findParameter<double>( //! \ogs_file_param_special{material__solid__constitutive_relation__MohrCoulomb__cohesion} config, "cohesion", parameters, 1); typename MohrCoulomb<DisplacementDim>::MaterialProperties mp{ Kn, Ks, friction_angle, dilatancy_angle, cohesion}; return std::unique_ptr<MohrCoulomb<DisplacementDim>>{ new MohrCoulomb<DisplacementDim>{mp}}; } template std::unique_ptr<FractureModelBase<2>> createMohrCoulomb( std::vector<std::unique_ptr<ProcessLib::ParameterBase>> const& parameters, BaseLib::ConfigTree const& config); template std::unique_ptr<FractureModelBase<3>> createMohrCoulomb( std::vector<std::unique_ptr<ProcessLib::ParameterBase>> const& parameters, BaseLib::ConfigTree const& config); } // namespace Fracture } // namespace MaterialLib
35.027397
106
0.746187
HaibingShao
1826e5671918e7fb8faa820ab9cde99cdbf92dbe
1,255
cpp
C++
Source/Life/AI/Perceptions/UtilityAiFindNearestActorPerception.cpp
PsichiX/Unreal-Systems-Architecture
fb2ccb243c8e79b0890736d611db7ba536937a93
[ "Apache-2.0" ]
5
2022-02-09T21:19:03.000Z
2022-03-03T01:53:03.000Z
Source/Life/AI/Perceptions/UtilityAiFindNearestActorPerception.cpp
PsichiX/Unreal-Systems-Architecture
fb2ccb243c8e79b0890736d611db7ba536937a93
[ "Apache-2.0" ]
null
null
null
Source/Life/AI/Perceptions/UtilityAiFindNearestActorPerception.cpp
PsichiX/Unreal-Systems-Architecture
fb2ccb243c8e79b0890736d611db7ba536937a93
[ "Apache-2.0" ]
null
null
null
#include "Life/AI/Perceptions/UtilityAiFindNearestActorPerception.h" #include "Systems/Public/Iterator.h" #include "Life/AI/Reasoner/UtilityAiMemory.h" struct Meta { float DistanceSquared = 0; AActor* Actor = nullptr; }; void UUtilityAiFindNearestActorPerception::Perceive(AActor* Actor, USystemsWorld& Systems, FUtilityAiMemory& Memory) const { const auto Position = Actor->GetActorLocation(); if (auto* ActorsList = Memory.Access(this->SourceMemoryProperty).AsArray()) { const auto Found = IterStd(*ActorsList) .FilterMap<Meta>( [&](auto& Value) { auto* OtherActor = Value.CastObject<AActor>(); if (IsValid(OtherActor)) { const auto OtherPosition = OtherActor->GetActorLocation(); const auto DistanceSquared = FVector::DistSquared(Position, OtherPosition); return TOptional<Meta>({DistanceSquared, OtherActor}); } return TOptional<Meta>(); }) .ComparedBy([](const auto& A, const auto& B) { return A.DistanceSquared < B.DistanceSquared; }); if (Found.IsSet()) { Memory.Access(this->TargetMemoryProperty) = Found.GetValue().Actor; } } }
26.702128
76
0.631873
PsichiX
1826f405a781f2bb0b1730fcdc0cb166cadc0a56
3,468
cpp
C++
Sourcecode/private/mx/core/YesNoNumber.cpp
Webern/MxOld
822f5ccc92363ddff118e3aa3a048c63be1e857e
[ "MIT" ]
45
2019-04-16T19:55:08.000Z
2022-02-14T02:06:32.000Z
Sourcecode/private/mx/core/YesNoNumber.cpp
Webern/MxOld
822f5ccc92363ddff118e3aa3a048c63be1e857e
[ "MIT" ]
70
2019-04-07T22:45:21.000Z
2022-03-03T15:35:59.000Z
Sourcecode/private/mx/core/YesNoNumber.cpp
Webern/MxOld
822f5ccc92363ddff118e3aa3a048c63be1e857e
[ "MIT" ]
21
2019-05-13T13:59:06.000Z
2022-03-25T02:21:05.000Z
// MusicXML Class Library // Copyright (c) by Matthew James Briggs // Distributed under the MIT License // self #include "mx/core/YesNoNumber.h" // std #include <sstream> #include <type_traits> namespace mx { namespace core { template<class> inline constexpr bool always_false_v = false; YesNoNumber::YesNoNumber() : myValue{ YesNo::yes } { } YesNoNumber::YesNoNumber( YesNo value ) : myValue{ value } { } YesNoNumber::YesNoNumber( Decimal value ) : myValue{ std::move( value ) } { } YesNoNumber::YesNoNumber( const std::string& value ) : YesNoNumber{} { parse( value ); } bool YesNoNumber::getIsYesNo() const { return myValue.index() == 0; } bool YesNoNumber::getIsDecimal() const { return myValue.index() == 1; } void YesNoNumber::setYesNo( YesNo value ) { myValue.emplace<YesNo>( value ); } void YesNoNumber::setDecimal( Decimal value ) { myValue.emplace<Decimal>( value ); } YesNo YesNoNumber::getValueYesNo() const { auto result = YesNo::yes; std::visit([&](auto&& arg) { using T = std::decay_t<decltype(arg)>; if constexpr( std::is_same_v<T, YesNo> ) result = arg; else if constexpr( std::is_same_v<T, Decimal> ) result = YesNo::yes; else static_assert(always_false_v<T>, "non-exhaustive visitor!"); }, myValue); return result; } Decimal YesNoNumber::getValueDecimal() const { auto result = Decimal{}; std::visit([&](auto&& arg) { using T = std::decay_t<decltype(arg)>; if constexpr( std::is_same_v<T, YesNo> ) result = Decimal{}; else if constexpr( std::is_same_v<T, Decimal> ) result = arg; else static_assert(always_false_v<T>, "non-exhaustive visitor!"); }, myValue); return result; } bool YesNoNumber::parse( const std::string& value ) { const auto yesNo = tryParseYesNo( value ); if( yesNo ) { setYesNo( *yesNo ); return true; } auto decimal = Decimal{}; if( decimal.parse( value ) ) { setDecimal( decimal ); return true; } return false; } std::string toString( const YesNoNumber& value ) { std::stringstream ss; toStream( ss, value ); return ss.str(); } std::ostream& toStream( std::ostream& os, const YesNoNumber& value ) { if( value.getIsYesNo() ) { toStream( os, value.getValueYesNo() ); } if( value.getIsDecimal() ) { toStream( os, value.getValueDecimal() ); } return os; } std::ostream& operator<<( std::ostream& os, const YesNoNumber& value ) { return toStream( os, value ); } } }
25.313869
80
0.467705
Webern
182b750d61a9fbf8a654b567071e8ad243a5df41
9,357
cpp
C++
modules/mojo/input/native/keyinfo.cpp
D-a-n-i-l-o/wonkey
6c9129a12fb622b971468ee5cc7adbedadd372ff
[ "Zlib" ]
109
2021-01-06T20:27:33.000Z
2022-03-07T19:28:50.000Z
modules/mojo/input/native/keyinfo.cpp
D-a-n-i-l-o/wonkey
6c9129a12fb622b971468ee5cc7adbedadd372ff
[ "Zlib" ]
4
2021-01-08T20:25:05.000Z
2021-06-08T05:36:48.000Z
modules/mojo/input/native/keyinfo.cpp
D-a-n-i-l-o/wonkey
6c9129a12fb622b971468ee5cc7adbedadd372ff
[ "Zlib" ]
11
2021-01-14T17:20:42.000Z
2021-08-08T18:46:42.000Z
#include "keyinfo.h" #include <SDL.h> wxKeyInfo wxKeyInfos[]={ "0",SDL_SCANCODE_0,SDLK_0, "1",SDL_SCANCODE_1,SDLK_1, "2",SDL_SCANCODE_2,SDLK_2, "3",SDL_SCANCODE_3,SDLK_3, "4",SDL_SCANCODE_4,SDLK_4, "5",SDL_SCANCODE_5,SDLK_5, "6",SDL_SCANCODE_6,SDLK_6, "7",SDL_SCANCODE_7,SDLK_7, "8",SDL_SCANCODE_8,SDLK_8, "9",SDL_SCANCODE_9,SDLK_9, "A",SDL_SCANCODE_A,SDLK_a, "AC Back",SDL_SCANCODE_AC_BACK,SDLK_AC_BACK, "AC Bookmarks",SDL_SCANCODE_AC_BOOKMARKS,SDLK_AC_BOOKMARKS, "AC Forward",SDL_SCANCODE_AC_FORWARD,SDLK_AC_FORWARD, "AC Home",SDL_SCANCODE_AC_HOME,SDLK_AC_HOME, "AC Refresh",SDL_SCANCODE_AC_REFRESH,SDLK_AC_REFRESH, "AC Search",SDL_SCANCODE_AC_SEARCH,SDLK_AC_SEARCH, "AC Stop",SDL_SCANCODE_AC_STOP,SDLK_AC_STOP, "Again",SDL_SCANCODE_AGAIN,SDLK_AGAIN, "AltErase",SDL_SCANCODE_ALTERASE,SDLK_ALTERASE, "'",SDL_SCANCODE_APOSTROPHE,SDLK_QUOTE, "Application",SDL_SCANCODE_APPLICATION,SDLK_APPLICATION, "AudioMute",SDL_SCANCODE_AUDIOMUTE,SDLK_AUDIOMUTE, "AudioNext",SDL_SCANCODE_AUDIONEXT,SDLK_AUDIONEXT, "AudioPlay",SDL_SCANCODE_AUDIOPLAY,SDLK_AUDIOPLAY, "AudioPrev",SDL_SCANCODE_AUDIOPREV,SDLK_AUDIOPREV, "AudioStop",SDL_SCANCODE_AUDIOSTOP,SDLK_AUDIOSTOP, "B",SDL_SCANCODE_B,SDLK_b, "\\",SDL_SCANCODE_BACKSLASH,SDLK_BACKSLASH, "Backspace",SDL_SCANCODE_BACKSPACE,SDLK_BACKSPACE, "BrightnessDown",SDL_SCANCODE_BRIGHTNESSDOWN,SDLK_BRIGHTNESSDOWN, "BrightnessUp",SDL_SCANCODE_BRIGHTNESSUP,SDLK_BRIGHTNESSUP, "C",SDL_SCANCODE_C,SDLK_c, "Calculator",SDL_SCANCODE_CALCULATOR,SDLK_CALCULATOR, "Cancel",SDL_SCANCODE_CANCEL,SDLK_CANCEL, "CapsLock",SDL_SCANCODE_CAPSLOCK,SDLK_CAPSLOCK, "Clear",SDL_SCANCODE_CLEAR,SDLK_CLEAR, "Clear / Again",SDL_SCANCODE_CLEARAGAIN,SDLK_CLEARAGAIN, ",",SDL_SCANCODE_COMMA,SDLK_COMMA, "Computer",SDL_SCANCODE_COMPUTER,SDLK_COMPUTER, "Copy",SDL_SCANCODE_COPY,SDLK_COPY, "CrSel",SDL_SCANCODE_CRSEL,SDLK_CRSEL, "CurrencySubUnit",SDL_SCANCODE_CURRENCYSUBUNIT,SDLK_CURRENCYSUBUNIT, "CurrencyUnit",SDL_SCANCODE_CURRENCYUNIT,SDLK_CURRENCYUNIT, "Cut",SDL_SCANCODE_CUT,SDLK_CUT, "D",SDL_SCANCODE_D,SDLK_d, "DecimalSeparator",SDL_SCANCODE_DECIMALSEPARATOR,SDLK_DECIMALSEPARATOR, "Delete",SDL_SCANCODE_DELETE,SDLK_DELETE, "DisplaySwitch",SDL_SCANCODE_DISPLAYSWITCH,SDLK_DISPLAYSWITCH, "Down",SDL_SCANCODE_DOWN,SDLK_DOWN, "E",SDL_SCANCODE_E,SDLK_e, "Eject",SDL_SCANCODE_EJECT,SDLK_EJECT, "End",SDL_SCANCODE_END,SDLK_END, "=",SDL_SCANCODE_EQUALS,SDLK_EQUALS, "Escape",SDL_SCANCODE_ESCAPE,SDLK_ESCAPE, "Execute",SDL_SCANCODE_EXECUTE,SDLK_EXECUTE, "ExSel",SDL_SCANCODE_EXSEL,SDLK_EXSEL, "F",SDL_SCANCODE_F,SDLK_f, "F1",SDL_SCANCODE_F1,SDLK_F1, "F10",SDL_SCANCODE_F10,SDLK_F10, "F11",SDL_SCANCODE_F11,SDLK_F11, "F12",SDL_SCANCODE_F12,SDLK_F12, "F13",SDL_SCANCODE_F13,SDLK_F13, "F14",SDL_SCANCODE_F14,SDLK_F14, "F15",SDL_SCANCODE_F15,SDLK_F15, "F16",SDL_SCANCODE_F16,SDLK_F16, "F17",SDL_SCANCODE_F17,SDLK_F17, "F18",SDL_SCANCODE_F18,SDLK_F18, "F19",SDL_SCANCODE_F19,SDLK_F19, "F2",SDL_SCANCODE_F2,SDLK_F2, "F20",SDL_SCANCODE_F20,SDLK_F20, "F21",SDL_SCANCODE_F21,SDLK_F21, "F22",SDL_SCANCODE_F22,SDLK_F22, "F23",SDL_SCANCODE_F23,SDLK_F23, "F24",SDL_SCANCODE_F24,SDLK_F24, "F3",SDL_SCANCODE_F3,SDLK_F3, "F4",SDL_SCANCODE_F4,SDLK_F4, "F5",SDL_SCANCODE_F5,SDLK_F5, "F6",SDL_SCANCODE_F6,SDLK_F6, "F7",SDL_SCANCODE_F7,SDLK_F7, "F8",SDL_SCANCODE_F8,SDLK_F8, "F9",SDL_SCANCODE_F9,SDLK_F9, "Find",SDL_SCANCODE_FIND,SDLK_FIND, "G",SDL_SCANCODE_G,SDLK_g, "`",SDL_SCANCODE_GRAVE,SDLK_BACKQUOTE, "H",SDL_SCANCODE_H,SDLK_h, "Help",SDL_SCANCODE_HELP,SDLK_HELP, "Home",SDL_SCANCODE_HOME,SDLK_HOME, "I",SDL_SCANCODE_I,SDLK_i, "Insert",SDL_SCANCODE_INSERT,SDLK_INSERT, "J",SDL_SCANCODE_J,SDLK_j, "K",SDL_SCANCODE_K,SDLK_k, "KBDIllumDown",SDL_SCANCODE_KBDILLUMDOWN,SDLK_KBDILLUMDOWN, "KBDIllumToggle",SDL_SCANCODE_KBDILLUMTOGGLE,SDLK_KBDILLUMTOGGLE, "KBDIllumUp",SDL_SCANCODE_KBDILLUMUP,SDLK_KBDILLUMUP, "Keypad 0",SDL_SCANCODE_KP_0,SDLK_KP_0, "Keypad 00",SDL_SCANCODE_KP_00,SDLK_KP_00, "Keypad 000",SDL_SCANCODE_KP_000,SDLK_KP_000, "Keypad 1",SDL_SCANCODE_KP_1,SDLK_KP_1, "Keypad 2",SDL_SCANCODE_KP_2,SDLK_KP_2, "Keypad 3",SDL_SCANCODE_KP_3,SDLK_KP_3, "Keypad 4",SDL_SCANCODE_KP_4,SDLK_KP_4, "Keypad 5",SDL_SCANCODE_KP_5,SDLK_KP_5, "Keypad 6",SDL_SCANCODE_KP_6,SDLK_KP_6, "Keypad 7",SDL_SCANCODE_KP_7,SDLK_KP_7, "Keypad 8",SDL_SCANCODE_KP_8,SDLK_KP_8, "Keypad 9",SDL_SCANCODE_KP_9,SDLK_KP_9, "Keypad A",SDL_SCANCODE_KP_A,SDLK_KP_A, "Keypad &",SDL_SCANCODE_KP_AMPERSAND,SDLK_KP_AMPERSAND, "Keypad @",SDL_SCANCODE_KP_AT,SDLK_KP_AT, "Keypad B",SDL_SCANCODE_KP_B,SDLK_KP_B, "Keypad Backspace",SDL_SCANCODE_KP_BACKSPACE,SDLK_KP_BACKSPACE, "Keypad Binary",SDL_SCANCODE_KP_BINARY,SDLK_KP_BINARY, "Keypad C",SDL_SCANCODE_KP_C,SDLK_KP_C, "Keypad Clear",SDL_SCANCODE_KP_CLEAR,SDLK_KP_CLEAR, "Keypad ClearEntry",SDL_SCANCODE_KP_CLEARENTRY,SDLK_KP_CLEARENTRY, "Keypad :",SDL_SCANCODE_KP_COLON,SDLK_KP_COLON, "Keypad ,",SDL_SCANCODE_KP_COMMA,SDLK_KP_COMMA, "Keypad D",SDL_SCANCODE_KP_D,SDLK_KP_D, "Keypad &&",SDL_SCANCODE_KP_DBLAMPERSAND,SDLK_KP_DBLAMPERSAND, "Keypad ||",SDL_SCANCODE_KP_DBLVERTICALBAR,SDLK_KP_DBLVERTICALBAR, "Keypad Decimal",SDL_SCANCODE_KP_DECIMAL,SDLK_KP_DECIMAL, "Keypad /",SDL_SCANCODE_KP_DIVIDE,SDLK_KP_DIVIDE, "Keypad E",SDL_SCANCODE_KP_E,SDLK_KP_E, "Keypad Enter",SDL_SCANCODE_KP_ENTER,SDLK_KP_ENTER, "Keypad =",SDL_SCANCODE_KP_EQUALS,SDLK_KP_EQUALS, "Keypad = (AS400)",SDL_SCANCODE_KP_EQUALSAS400,SDLK_KP_EQUALSAS400, "Keypad !",SDL_SCANCODE_KP_EXCLAM,SDLK_KP_EXCLAM, "Keypad F",SDL_SCANCODE_KP_F,SDLK_KP_F, "Keypad >",SDL_SCANCODE_KP_GREATER,SDLK_KP_GREATER, "Keypad #",SDL_SCANCODE_KP_HASH,SDLK_KP_HASH, "Keypad Hexadecimal",SDL_SCANCODE_KP_HEXADECIMAL,SDLK_KP_HEXADECIMAL, "Keypad {",SDL_SCANCODE_KP_LEFTBRACE,SDLK_KP_LEFTBRACE, "Keypad (",SDL_SCANCODE_KP_LEFTPAREN,SDLK_KP_LEFTPAREN, "Keypad <",SDL_SCANCODE_KP_LESS,SDLK_KP_LESS, "Keypad MemAdd",SDL_SCANCODE_KP_MEMADD,SDLK_KP_MEMADD, "Keypad MemClear",SDL_SCANCODE_KP_MEMCLEAR,SDLK_KP_MEMCLEAR, "Keypad MemDivide",SDL_SCANCODE_KP_MEMDIVIDE,SDLK_KP_MEMDIVIDE, "Keypad MemMultiply",SDL_SCANCODE_KP_MEMMULTIPLY,SDLK_KP_MEMMULTIPLY, "Keypad MemRecall",SDL_SCANCODE_KP_MEMRECALL,SDLK_KP_MEMRECALL, "Keypad MemStore",SDL_SCANCODE_KP_MEMSTORE,SDLK_KP_MEMSTORE, "Keypad MemSubtract",SDL_SCANCODE_KP_MEMSUBTRACT,SDLK_KP_MEMSUBTRACT, "Keypad -",SDL_SCANCODE_KP_MINUS,SDLK_KP_MINUS, "Keypad *",SDL_SCANCODE_KP_MULTIPLY,SDLK_KP_MULTIPLY, "Keypad Octal",SDL_SCANCODE_KP_OCTAL,SDLK_KP_OCTAL, "Keypad %",SDL_SCANCODE_KP_PERCENT,SDLK_KP_PERCENT, "Keypad .",SDL_SCANCODE_KP_PERIOD,SDLK_KP_PERIOD, "Keypad +",SDL_SCANCODE_KP_PLUS,SDLK_KP_PLUS, "Keypad +/-",SDL_SCANCODE_KP_PLUSMINUS,SDLK_KP_PLUSMINUS, "Keypad ^",SDL_SCANCODE_KP_POWER,SDLK_KP_POWER, "Keypad }",SDL_SCANCODE_KP_RIGHTBRACE,SDLK_KP_RIGHTBRACE, "Keypad )",SDL_SCANCODE_KP_RIGHTPAREN,SDLK_KP_RIGHTPAREN, "Keypad Space",SDL_SCANCODE_KP_SPACE,SDLK_KP_SPACE, "Keypad Tab",SDL_SCANCODE_KP_TAB,SDLK_KP_TAB, "Keypad |",SDL_SCANCODE_KP_VERTICALBAR,SDLK_KP_VERTICALBAR, "Keypad XOR",SDL_SCANCODE_KP_XOR,SDLK_KP_XOR, "L",SDL_SCANCODE_L,SDLK_l, "Left Alt",SDL_SCANCODE_LALT,SDLK_LALT, "Left Ctrl",SDL_SCANCODE_LCTRL,SDLK_LCTRL, "Left",SDL_SCANCODE_LEFT,SDLK_LEFT, "[",SDL_SCANCODE_LEFTBRACKET,SDLK_LEFTBRACKET, "Left GUI",SDL_SCANCODE_LGUI,SDLK_LGUI, "Left Shift",SDL_SCANCODE_LSHIFT,SDLK_LSHIFT, "M",SDL_SCANCODE_M,SDLK_m, "Mail",SDL_SCANCODE_MAIL,SDLK_MAIL, "MediaSelect",SDL_SCANCODE_MEDIASELECT,SDLK_MEDIASELECT, "Menu",SDL_SCANCODE_MENU,SDLK_MENU, "-",SDL_SCANCODE_MINUS,SDLK_MINUS, "ModeSwitch",SDL_SCANCODE_MODE,SDLK_MODE, "Mute",SDL_SCANCODE_MUTE,SDLK_MUTE, "N",SDL_SCANCODE_N,SDLK_n, "Numlock",SDL_SCANCODE_NUMLOCKCLEAR,SDLK_NUMLOCKCLEAR, "O",SDL_SCANCODE_O,SDLK_o, "Oper",SDL_SCANCODE_OPER,SDLK_OPER, "Out",SDL_SCANCODE_OUT,SDLK_OUT, "P",SDL_SCANCODE_P,SDLK_p, "PageDown",SDL_SCANCODE_PAGEDOWN,SDLK_PAGEDOWN, "PageUp",SDL_SCANCODE_PAGEUP,SDLK_PAGEUP, "Paste",SDL_SCANCODE_PASTE,SDLK_PASTE, "Pause",SDL_SCANCODE_PAUSE,SDLK_PAUSE, ".",SDL_SCANCODE_PERIOD,SDLK_PERIOD, "Power",SDL_SCANCODE_POWER,SDLK_POWER, "PrintScreen",SDL_SCANCODE_PRINTSCREEN,SDLK_PRINTSCREEN, "Prior",SDL_SCANCODE_PRIOR,SDLK_PRIOR, "Q",SDL_SCANCODE_Q,SDLK_q, "R",SDL_SCANCODE_R,SDLK_r, "Right Alt",SDL_SCANCODE_RALT,SDLK_RALT, "Right Ctrl",SDL_SCANCODE_RCTRL,SDLK_RCTRL, "Return",SDL_SCANCODE_RETURN,SDLK_RETURN, "Return",SDL_SCANCODE_RETURN2,SDLK_RETURN2, "Right GUI",SDL_SCANCODE_RGUI,SDLK_RGUI, "Right",SDL_SCANCODE_RIGHT,SDLK_RIGHT, "]",SDL_SCANCODE_RIGHTBRACKET,SDLK_RIGHTBRACKET, "Right Shift",SDL_SCANCODE_RSHIFT,SDLK_RSHIFT, "S",SDL_SCANCODE_S,SDLK_s, "ScrollLock",SDL_SCANCODE_SCROLLLOCK,SDLK_SCROLLLOCK, "Select",SDL_SCANCODE_SELECT,SDLK_SELECT, ";",SDL_SCANCODE_SEMICOLON,SDLK_SEMICOLON, "Separator",SDL_SCANCODE_SEPARATOR,SDLK_SEPARATOR, "/",SDL_SCANCODE_SLASH,SDLK_SLASH, "Sleep",SDL_SCANCODE_SLEEP,SDLK_SLEEP, "Space",SDL_SCANCODE_SPACE,SDLK_SPACE, "Stop",SDL_SCANCODE_STOP,SDLK_STOP, "SysReq",SDL_SCANCODE_SYSREQ,SDLK_SYSREQ, "T",SDL_SCANCODE_T,SDLK_t, "Tab",SDL_SCANCODE_TAB,SDLK_TAB, "ThousandsSeparator",SDL_SCANCODE_THOUSANDSSEPARATOR,SDLK_THOUSANDSSEPARATOR, "U",SDL_SCANCODE_U,SDLK_u, "Undo",SDL_SCANCODE_UNDO,SDLK_UNDO, "",SDL_SCANCODE_UNKNOWN,SDLK_UNKNOWN, "Up",SDL_SCANCODE_UP,SDLK_UP, "V",SDL_SCANCODE_V,SDLK_v, "VolumeDown",SDL_SCANCODE_VOLUMEDOWN,SDLK_VOLUMEDOWN, "VolumeUp",SDL_SCANCODE_VOLUMEUP,SDLK_VOLUMEUP, "W",SDL_SCANCODE_W,SDLK_w, "WWW",SDL_SCANCODE_WWW,SDLK_WWW, "X",SDL_SCANCODE_X,SDLK_x, "Y",SDL_SCANCODE_Y,SDLK_y, "Z",SDL_SCANCODE_Z,SDLK_z, 0,0,0 };
41.039474
77
0.84354
D-a-n-i-l-o
182baeda498d90c07dd31f944315c68ea155bf34
7,217
cpp
C++
Src/Reader.cpp
craflin/md2tex
ee813151f5427cea61fa3ea045cea13f594cb58f
[ "Apache-2.0" ]
null
null
null
Src/Reader.cpp
craflin/md2tex
ee813151f5427cea61fa3ea045cea13f594cb58f
[ "Apache-2.0" ]
null
null
null
Src/Reader.cpp
craflin/md2tex
ee813151f5427cea61fa3ea045cea13f594cb58f
[ "Apache-2.0" ]
null
null
null
#include "Reader.hpp" #include <nstd/File.hpp> #include <nstd/Error.hpp> #include <nstd/Document/Xml.hpp> #include "InputData.hpp" bool Reader::read(const String& inputFile, InputData& inputData) { inputData.inputFile = inputFile; if(File::extension(inputFile).compareIgnoreCase("md") == 0) { InputData::Component& component = inputData.document.append(InputData::Component()); component.type = InputData::Component::mdType; component.filePath = inputFile; File file; if(!file.open(component.filePath)) return _errorString = String::fromPrintf("Could not open file '%s': %s", (const char*)component.filePath, (const char*)Error::getErrorString()), false; if(!file.readAll(component.value)) return _errorString = String::fromPrintf("Could not read file '%s': %s", (const char*)component.filePath, (const char*)Error::getErrorString()), false; return true; } Xml::Parser xmlParser; Xml::Element xmlFile; if(!xmlParser.load(inputFile, xmlFile)) return _errorLine = xmlParser.getErrorLine(), _errorColumn = xmlParser.getErrorColumn(), _errorString = xmlParser.getErrorString(), false; if(xmlFile.type != "umdoc") return _errorLine = xmlParser.getErrorLine(), _errorColumn = xmlParser.getErrorColumn(), _errorString = "Expected element 'umdoc'", false; inputData.className = *xmlFile.attributes.find("class"); bool documentRead = false; for(List<Xml::Variant>::Iterator i = xmlFile.content.begin(), end = xmlFile.content.end(); i != end; ++i) { const Xml::Variant& variant = *i; if(!variant.isElement()) continue; const Xml::Element& element = variant.toElement(); if(documentRead) return _errorLine = element.line, _errorColumn = element.column, _errorString = String::fromPrintf("Unexpected element '%s'", (const char*)element.type), false; if(element.type == "tex") { String filePath = *element.attributes.find("file"); File file; if(!filePath.isEmpty()) { String data; if(!file.open(filePath)) return _errorLine = element.line, _errorColumn = element.column, _errorString = String::fromPrintf("Could not open file '%s': %s", (const char*)filePath, (const char*)Error::getErrorString()), false; if(!file.readAll(data)) return _errorLine = element.line, _errorColumn = element.column, _errorString = String::fromPrintf("Could not read file '%s': %s", (const char*)filePath, (const char*)Error::getErrorString()), false; inputData.headerTexFiles.append(data); } for(List<Xml::Variant>::Iterator i = element.content.begin(), end = element.content.end(); i != end; ++i) inputData.headerTexFiles.append(i->toString()); } else if(element.type == "set") inputData.variables.append(*element.attributes.find("name"), *element.attributes.find("value")); else if(element.type == "environment") { InputData::Environment& environment = inputData.environments.append(*element.attributes.find("name"), InputData::Environment()); environment.verbatim = element.attributes.find("verbatim")->toBool(); environment.command = *element.attributes.find("command"); } else if(element.type == "document") { for(List<Xml::Variant>::Iterator i = element.content.begin(), end = element.content.end(); i != end; ++i) { const Xml::Variant& variant = *i; if(!variant.isElement()) continue; const Xml::Element& element = variant.toElement(); if(element.type == "tex" || element.type == "md") { InputData::Component& component = inputData.document.append(InputData::Component()); component.type = element.type == "md" ? InputData::Component::mdType : InputData::Component::texType; component.filePath = *element.attributes.find("file"); if(!component.filePath.isEmpty()) { File file; if(!file.open(component.filePath)) return _errorLine = element.line, _errorColumn = element.column, _errorString = String::fromPrintf("Could not open file '%s': %s", (const char*)component.filePath, (const char*)Error::getErrorString()), false; if(!file.readAll(component.value)) return _errorLine = element.line, _errorColumn = element.column, _errorString = String::fromPrintf("Could not read file '%s': %s", (const char*)component.filePath, (const char*)Error::getErrorString()), false; } for(List<Xml::Variant>::Iterator i = element.content.begin(), end = element.content.end(); i != end; ++i) component.value.append(i->toString()); } else if(element.type == "toc" || element.type == "tableOfContents") { InputData::Component& component = inputData.document.append(InputData::Component()); component.type = InputData::Component::texTableOfContentsType; } else if(element.type == "lof" || element.type == "listOfFigures") { InputData::Component& component = inputData.document.append(InputData::Component()); component.type = InputData::Component::texListOfFiguresType; } else if(element.type == "lot" || element.type == "listOfTables") { InputData::Component& component = inputData.document.append(InputData::Component()); component.type = InputData::Component::texListOfTablesType; } else if(element.type == "break" || element.type == "newPage" || element.type == "pageBreak") { InputData::Component& component = inputData.document.append(InputData::Component()); component.type = InputData::Component::texNewPageType; } else if(element.type == "pdf") { InputData::Component& component = inputData.document.append(InputData::Component()); component.type = InputData::Component::pdfType; component.filePath = *element.attributes.find("file"); } else if(element.type == "part") { InputData::Component& component = inputData.document.append(InputData::Component()); component.type = InputData::Component::texPartType; component.value = *element.attributes.find("title"); } else if(element.type == "environment") { InputData::Environment& environment = inputData.environments.append(*element.attributes.find("name"), InputData::Environment()); environment.verbatim = element.attributes.find("verbatim")->toBool(); environment.command = *element.attributes.find("command"); } else if(element.type == "set") inputData.variables.append(*element.attributes.find("name"), *element.attributes.find("value")); else return _errorLine = element.line, _errorColumn = element.column, _errorString = String::fromPrintf("Unexpected element '%s'", (const char*)element.type), false; } documentRead = true; } else return _errorLine = element.line, _errorColumn = element.column, _errorString = String::fromPrintf("Unexpected element '%s'", (const char*)element.type), false; } return true; }
49.431507
223
0.651656
craflin
183005e1ac1b6fe93255b485f6550f4df62974c4
940
ipp
C++
freeflow/sdn/request.ipp
flowgrammable/freeflow-legacy
c5cd77495d44fe3a9e48a2e06fbb44f7418d388e
[ "Apache-2.0" ]
1
2017-07-30T04:18:29.000Z
2017-07-30T04:18:29.000Z
freeflow/sdn/request.ipp
flowgrammable/freeflow-legacy
c5cd77495d44fe3a9e48a2e06fbb44f7418d388e
[ "Apache-2.0" ]
null
null
null
freeflow/sdn/request.ipp
flowgrammable/freeflow-legacy
c5cd77495d44fe3a9e48a2e06fbb44f7418d388e
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2013-2014 Flowgrammable, LLC. // // 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. namespace freeflow { inline Request_data::Request_data(const Disconnect_request& x) : disconnect(x) { } inline Request_data::Request_data(const Terminate_request& x) : terminate(x) { } template<typename T> inline Request::Request(Application* a, const T& x) : app(a), type(x.Kind), data(x) { } } // namespace freeflow
30.322581
70
0.729787
flowgrammable
1835de201ce5637e1a52e6fba2c78b2ed804ffc6
1,732
hpp
C++
src/ivorium_graphics/Animation/Connectors/Cooldown_Connector.hpp
ivorne/ivorium
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
[ "Apache-2.0" ]
3
2021-02-26T02:59:09.000Z
2022-02-08T16:44:21.000Z
src/ivorium_graphics/Animation/Connectors/Cooldown_Connector.hpp
ivorne/ivorium
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
[ "Apache-2.0" ]
null
null
null
src/ivorium_graphics/Animation/Connectors/Cooldown_Connector.hpp
ivorne/ivorium
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Transform_ConnectorI.hpp" #include "../Animation/AnimNode.hpp" #include "../../Defs.hpp" #include <ivorium_core/ivorium_core.hpp> #include <cmath> namespace iv { /** This connector changes value of child node at most at given rate. Slows down changes of target - change will not be applied before specified time passes after previous change. This consumes changes that are overriden by a following change before the cooldown times out. This has two cooldowns - which one is selected depends on if the next value his greater or lesser than the current value. */ template< class T > class Cooldown_Connector : public Transform_ConnectorI< T, T > { public: using Transform_ConnectorI< T, T >::instance; ClientMarker cm; //----------------------------- Cooldown_Connector ------------------------------------------------------------------- Cooldown_Connector( Instance * inst ); //-------------------------- configuration ----------------------------------------------------- Cooldown_Connector< T > * cooldown_increasing( Anim_float ); Anim_float cooldown_increasing(); Cooldown_Connector< T > * cooldown_decreasing( Anim_float ); Anim_float cooldown_decreasing(); //----------------------------- AnimConnector ------------------------------------------------------ virtual void UpdatePass_Down() override; virtual void UpdatePass_Up() override; private: Anim_float _cooldown_increasing; Anim_float _cooldown_decreasing; Anim_float _time; }; } #include "Cooldown_Connector.inl"
35.346939
125
0.56582
ivorne
183a11e9f6e0c5fd5a67ff0be320e96838534ac3
20,992
cpp
C++
libakumuli/page.cpp
vladon/Akumuli
c45672a23b929ccb3a5743cc5e9aae980c160eb0
[ "Apache-2.0" ]
null
null
null
libakumuli/page.cpp
vladon/Akumuli
c45672a23b929ccb3a5743cc5e9aae980c160eb0
[ "Apache-2.0" ]
null
null
null
libakumuli/page.cpp
vladon/Akumuli
c45672a23b929ccb3a5743cc5e9aae980c160eb0
[ "Apache-2.0" ]
1
2021-09-22T07:11:13.000Z
2021-09-22T07:11:13.000Z
/** * Copyright (c) 2013 Eugene Lazin <[email protected]> * * 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 <cstring> #include <cassert> #include <algorithm> #include <mutex> #include <apr_time.h> #include "timsort.hpp" #include "page.h" #include "compression.h" #include "akumuli_def.h" #include "search.h" #include "buffer_cache.h" #include <random> #include <iostream> #include <boost/crc.hpp> namespace Akumuli { // Page // ---- PageHeader::PageHeader(uint32_t count, uint64_t length, uint32_t page_id, uint32_t numpages) : version(0) , count(0) , next_offset(0) , open_count(0) , close_count(0) , page_id(page_id) , numpages(numpages) , length(length - sizeof(PageHeader)) { } uint32_t PageHeader::get_page_id() const { return page_id; } uint32_t PageHeader::get_numpages() const { return numpages; } uint32_t PageHeader::get_open_count() const { return open_count; } uint32_t PageHeader::get_close_count() const { return close_count; } void PageHeader::set_open_count(uint32_t cnt) { open_count = cnt; } void PageHeader::set_close_count(uint32_t cnt) { close_count = cnt; } void PageHeader::create_checkpoint() { checkpoint = count; } bool PageHeader::restore() { if (count != checkpoint) { count = checkpoint; return true; } return false; } aku_EntryIndexRecord* PageHeader::page_index(int index) { char* ptr = payload + length - sizeof(aku_EntryIndexRecord); aku_EntryIndexRecord* entry = reinterpret_cast<aku_EntryIndexRecord*>(ptr); entry -= index; return entry; } const aku_EntryIndexRecord* PageHeader::page_index(int index) const { const char* ptr = payload + length - sizeof(aku_EntryIndexRecord); const aku_EntryIndexRecord* entry = reinterpret_cast<const aku_EntryIndexRecord*>(ptr); entry -= index; return entry; } std::pair<aku_EntryIndexRecord, int> PageHeader::index_to_offset(uint32_t index) const { if (index > count) { return std::make_pair(aku_EntryIndexRecord(), AKU_EBAD_ARG); } return std::make_pair(*page_index(index), AKU_SUCCESS); } uint32_t PageHeader::get_entries_count() const { return count; } size_t PageHeader::get_free_space() const { auto begin = payload + next_offset; auto end = (payload + length) - count*sizeof(aku_EntryIndexRecord); assert(end >= payload); return end - begin; } void PageHeader::reuse() { count = 0; checkpoint = 0; count = 0; open_count++; next_offset = 0; } void PageHeader::close() { close_count++; } aku_Status PageHeader::add_entry( const aku_ParamId param , const aku_Timestamp timestamp , const aku_MemRange &range ) { if (count != 0) { // Require >= timestamp if (timestamp < page_index(count - 1)->timestamp) { return AKU_EBAD_ARG; } } const auto SPACE_REQUIRED = sizeof(aku_Entry) // entry header + range.length // data size (in bytes) + sizeof(aku_EntryIndexRecord); // offset inside page_index const auto ENTRY_SIZE = sizeof(aku_Entry) + range.length; if (!range.length) { return AKU_EBAD_DATA; } if (SPACE_REQUIRED > get_free_space()) { return AKU_EOVERFLOW; } char* free_slot = payload + next_offset; aku_Entry* entry = reinterpret_cast<aku_Entry*>(free_slot); entry->param_id = param; entry->length = range.length; memcpy((void*)&entry->value, range.address, range.length); page_index(count)->offset = next_offset; page_index(count)->timestamp = timestamp; next_offset += ENTRY_SIZE; count++; return AKU_SUCCESS; } aku_Status PageHeader::add_chunk(const aku_MemRange range, const uint32_t free_space_required, uint32_t* out_offset) { const auto SPACE_REQUIRED = range.length + free_space_required, SPACE_NEEDED = range.length; if (get_free_space() < SPACE_REQUIRED) { return AKU_EOVERFLOW; } *out_offset = next_offset; char* free_slot = payload + next_offset; memcpy((void*)free_slot, range.address, SPACE_NEEDED); next_offset += SPACE_NEEDED; return AKU_SUCCESS; } aku_Status PageHeader::complete_chunk(const UncompressedChunk& data) { CompressedChunkDesc desc; Rand rand; aku_Timestamp first_ts; aku_Timestamp last_ts; struct Writer : ChunkWriter { PageHeader *header; char* begin; char* end; Writer(PageHeader *h) : header(h) {} virtual aku_MemRange allocate() { size_t bytes_free = header->get_free_space(); char* data = header->payload + header->next_offset; begin = data; return {(void*)data, (uint32_t)bytes_free}; } virtual aku_Status commit(size_t bytes_written) { if (bytes_written < header->get_free_space()) { header->next_offset += bytes_written; end = begin + bytes_written; return AKU_SUCCESS; } return AKU_EOVERFLOW; } }; Writer writer(this); // Write compressed data aku_Status status = CompressionUtil::encode_chunk(&desc.n_elements, &first_ts, &last_ts, &writer, data); if (status != AKU_SUCCESS) { return status; } // Calculate checksum of the new compressed data boost::crc_32_type checksum; checksum.process_block(writer.begin, writer.end); desc.checksum = checksum.checksum(); desc.begin_offset = writer.begin - payload; desc.end_offset = writer.end - payload; aku_MemRange head = {&desc, sizeof(desc)}; status = add_entry(AKU_CHUNK_BWD_ID, first_ts, head); if (status != AKU_SUCCESS) { return status; } status = add_entry(AKU_CHUNK_FWD_ID, last_ts, head); if (status != AKU_SUCCESS) { return status; } return status; } const aku_Timestamp PageHeader::read_timestamp_at(uint32_t index) const { return page_index(index)->timestamp; } const aku_Entry *PageHeader::read_entry_at(uint32_t index) const { if (index < count) { auto offset = page_index(index)->offset; return read_entry(offset); } return 0; } const aku_Entry *PageHeader::read_entry(uint32_t offset) const { auto ptr = payload + offset; auto entry_ptr = reinterpret_cast<const aku_Entry*>(ptr); return entry_ptr; } const void* PageHeader::read_entry_data(uint32_t offset) const { return payload + offset; } int PageHeader::get_entry_length_at(int entry_index) const { auto entry_ptr = read_entry_at(entry_index); if (entry_ptr) { return entry_ptr->length; } return 0; } int PageHeader::get_entry_length(uint32_t offset) const { auto entry_ptr = read_entry(offset); if (entry_ptr) { return entry_ptr->length; } return 0; } int PageHeader::copy_entry_at(int index, aku_Entry *receiver) const { auto entry_ptr = read_entry_at(index); if (entry_ptr) { size_t size = entry_ptr->length + sizeof(aku_Entry); if (entry_ptr->length > receiver->length) { return -1*entry_ptr->length; } memcpy((void*)receiver, (void*)entry_ptr, size); return entry_ptr->length; } return 0; } int PageHeader::copy_entry(uint32_t offset, aku_Entry *receiver) const { auto entry_ptr = read_entry(offset); if (entry_ptr) { if (entry_ptr->length > receiver->length) { return -1*entry_ptr->length; } memcpy((void*)receiver, (void*)entry_ptr, entry_ptr->length); return entry_ptr->length; } return 0; } SearchStats& get_global_search_stats() { static SearchStats stats; return stats; } namespace { struct ChunkHeaderSearcher : InterpolationSearch<ChunkHeaderSearcher> { UncompressedChunk const& header; ChunkHeaderSearcher(UncompressedChunk const& h) : header(h) {} // Interpolation search supporting functions bool read_at(aku_Timestamp* out_timestamp, uint32_t ix) const { if (ix < header.timestamps.size()) { *out_timestamp = header.timestamps[ix]; return true; } return false; } bool is_small(SearchRange range) const { return false; } SearchStats& get_search_stats() { return get_global_search_stats(); } }; } struct SearchAlgorithm : InterpolationSearch<SearchAlgorithm> { const PageHeader *page_; std::shared_ptr<QP::IQueryProcessor> query_; std::shared_ptr<ChunkCache> cache_; const uint32_t MAX_INDEX_; const bool IS_BACKWARD_; const aku_Timestamp key_; const aku_Timestamp lowerbound_; const aku_Timestamp upperbound_; SearchRange range_; SearchAlgorithm(PageHeader const* page, std::shared_ptr<QP::IQueryProcessor> query, std::shared_ptr<ChunkCache> cache) : page_(page) , query_(query) , cache_(cache) , MAX_INDEX_(page->get_entries_count()) , IS_BACKWARD_(query->direction() == AKU_CURSOR_DIR_BACKWARD) , key_(IS_BACKWARD_ ? query->upperbound() : query->lowerbound()) , lowerbound_(query->lowerbound()) , upperbound_(query->upperbound()) { if (MAX_INDEX_) { range_.begin = 0u; range_.end = MAX_INDEX_ - 1; } else { range_.begin = 0u; range_.end = 0u; } } bool fast_path() { if (!MAX_INDEX_) { return true; } if (key_ > page_->page_index(range_.end)->timestamp || key_ < page_->page_index(range_.begin)->timestamp) { // Shortcut for corner cases if (key_ > page_->page_index(range_.end)->timestamp) { if (IS_BACKWARD_) { range_.begin = range_.end; return false; } else { // return empty result return true; } } else if (key_ < page_->page_index(range_.begin)->timestamp) { if (!IS_BACKWARD_) { range_.end = range_.begin; return false; } else { // return empty result return true; } } } return false; } // Interpolation search supporting functions bool read_at(aku_Timestamp* out_timestamp, uint32_t ix) const { if (ix < page_->get_entries_count()) { *out_timestamp = page_->page_index(ix)->timestamp; return true; } return false; } bool is_small(SearchRange range) const { auto ps = get_page_size(); auto b = align_to_page(reinterpret_cast<void const*>(page_->read_entry_at(range.begin)), ps); auto e = align_to_page(reinterpret_cast<void const*>(page_->read_entry_at(range.end)), ps); return b == e; } SearchStats& get_search_stats() { return get_global_search_stats(); } bool interpolation() { if (!run(key_, &range_)) { query_->set_error(AKU_ENOT_FOUND); return false; } return true; } void binary_search() { // TODO: use binary search from stdlib uint64_t steps = 0ul; if (range_.begin == range_.end) { return; } uint32_t probe_index = 0u; while (range_.end >= range_.begin) { steps++; probe_index = range_.begin + ((range_.end - range_.begin) / 2u); if (probe_index >= MAX_INDEX_) { query_->set_error(AKU_EOVERFLOW); range_.begin = range_.end = MAX_INDEX_; return; } auto probe = page_->page_index(probe_index)->timestamp; if (probe == key_) { // found break; } else if (probe < key_) { range_.begin = probe_index + 1u; // change min index to search upper subarray if (range_.begin >= MAX_INDEX_) { // we hit the upper bound of the array break; } } else { range_.end = probe_index - 1u; // change max index to search lower subarray if (range_.end == ~0u) { // we hit the lower bound of the array break; } } } range_.begin = probe_index; range_.end = probe_index; auto& stats = get_global_search_stats(); std::lock_guard<std::mutex> guard(stats.mutex); auto& bst = stats.stats.bstats; bst.n_times += 1; bst.n_steps += steps; } bool scan_compressed_entries(uint32_t current_index, aku_Entry const* probe_entry, bool binary_search=false) { aku_Status status = AKU_SUCCESS; std::shared_ptr<UncompressedChunk> chunk_header, header; auto npages = page_->get_numpages(); // This needed to prevent key collision auto nopens = page_->get_open_count(); // between old and new page data, when auto pageid = page_->get_page_id(); // page is reallocated. auto key = std::make_tuple(npages*nopens + pageid, current_index); if (cache_ && cache_->contains(key)) { // Fast path header = cache_->get(key); } else { chunk_header.reset(new UncompressedChunk()); header.reset(new UncompressedChunk()); auto pdesc = reinterpret_cast<CompressedChunkDesc const*>(&probe_entry->value[0]); auto pbegin = (const unsigned char*)page_->read_entry_data(pdesc->begin_offset); auto pend = (const unsigned char*)page_->read_entry_data(pdesc->end_offset); auto probe_length = pdesc->n_elements; boost::crc_32_type checksum; checksum.process_block(pbegin, pend); if (checksum.checksum() != pdesc->checksum) { AKU_PANIC("File damaged!"); } status = CompressionUtil::decode_chunk(chunk_header.get(), pbegin, pend, probe_length); if (status != AKU_SUCCESS) { AKU_PANIC("Can't decode chunk"); } // TODO: depending on a query type we can use chunk order or convert back to time-order. // If we extract evertyhing it is better to convert to time order. If we picking some // parameter ids it is better to check if this ids present in a chunk and extract values // in chunk order and only after that - convert results to time-order. // Convert from chunk order to time order if (!CompressionUtil::convert_from_chunk_order(*chunk_header, header.get())) { AKU_PANIC("Bad chunk"); } if (cache_) { cache_->put(key, header); } } int start_pos = 0; if (IS_BACKWARD_) { start_pos = static_cast<int>(header->timestamps.size() - 1); } bool probe_in_time_range = true; auto queryproc = query_; auto page = page_; auto put_entry = [&header, queryproc, page] (uint32_t i) { aku_PData pdata; pdata.type = AKU_PAYLOAD_FLOAT; pdata.float64 = header->values.at(i); pdata.size = sizeof(aku_Sample); aku_Sample result = { header->timestamps.at(i), header->paramids.at(i), pdata, }; return queryproc->put(result); }; if (IS_BACKWARD_) { for (int i = static_cast<int>(start_pos); i >= 0; i--) { probe_in_time_range = lowerbound_ <= header->timestamps[i] && upperbound_ >= header->timestamps[i]; if (probe_in_time_range) { if (!put_entry(i)) { probe_in_time_range = false; break; } } else { probe_in_time_range = lowerbound_ <= header->timestamps[i]; if (!probe_in_time_range) { break; } } } } else { auto end_pos = (int)header->timestamps.size(); for (auto i = start_pos; i != end_pos; i++) { probe_in_time_range = lowerbound_ <= header->timestamps[i] && upperbound_ >= header->timestamps[i]; if (probe_in_time_range) { if (!put_entry(i)) { probe_in_time_range = false; break; } } else { probe_in_time_range = upperbound_ >= header->timestamps[i]; if (!probe_in_time_range) { break; } } } } return probe_in_time_range; } std::tuple<uint64_t, uint64_t> scan_impl(uint32_t probe_index) { int index_increment = IS_BACKWARD_ ? -1 : 1; while (true) { auto current_index = probe_index; probe_index += index_increment; auto probe_offset = page_->page_index(current_index)->offset; auto probe_time = page_->page_index(current_index)->timestamp; auto probe_entry = page_->read_entry(probe_offset); auto probe = probe_entry->param_id; bool proceed = false; if (probe == AKU_CHUNK_FWD_ID && IS_BACKWARD_ == false) { proceed = scan_compressed_entries(current_index, probe_entry, false); } else if (probe == AKU_CHUNK_BWD_ID && IS_BACKWARD_ == true) { proceed = scan_compressed_entries(current_index, probe_entry, false); } else { proceed = IS_BACKWARD_ ? lowerbound_ <= probe_time : upperbound_ >= probe_time; } if (!proceed || probe_index >= MAX_INDEX_) { // When scanning forward probe_index will be equal to MAX_INDEX_ at the end of the page // When scanning backward probe_index will be equal to ~0 (probe_index > MAX_INDEX_) // at the end of the page break; } } return std::make_tuple(0ul, 0ul); } void scan() { if (range_.begin != range_.end) { query_->set_error(AKU_EGENERAL); return; } if (range_.begin >= MAX_INDEX_) { query_->set_error(AKU_EOVERFLOW); return; } auto sums = scan_impl(range_.begin); auto& stats = get_global_search_stats(); { std::lock_guard<std::mutex> guard(stats.mutex); stats.stats.scan.fwd_bytes += std::get<0>(sums); stats.stats.scan.bwd_bytes += std::get<1>(sums); } } }; void PageHeader::search(std::shared_ptr<QP::IQueryProcessor> query, std::shared_ptr<ChunkCache> cache) const { SearchAlgorithm search_alg(this, query, cache); if (search_alg.fast_path() == false) { if (search_alg.interpolation()) { search_alg.binary_search(); search_alg.scan(); } } } void PageHeader::get_stats(aku_StorageStats* rcv_stats) { uint64_t used_space = 0, free_space = 0, n_entries = 0; auto all = length; auto free = get_free_space(); used_space = all - free; free_space = free; n_entries = count; rcv_stats->free_space += free_space; rcv_stats->used_space += used_space; rcv_stats->n_entries += n_entries; rcv_stats->n_volumes += 1; } void PageHeader::get_search_stats(aku_SearchStats* stats, bool reset) { auto& gstats = get_global_search_stats(); std::lock_guard<std::mutex> guard(gstats.mutex); memcpy( reinterpret_cast<void*>(stats) , reinterpret_cast<void*>(&gstats.stats) , sizeof(aku_SearchStats)); if (reset) { memset(reinterpret_cast<void*>(&gstats.stats), 0, sizeof(aku_SearchStats)); } } } // namepsace
31.614458
122
0.58608
vladon
183c1e2d937ce1c624a715fce3d36848893944f0
1,075
cpp
C++
src/titanic/model/AlternativeMachine.cpp
LaroyenneG/Fuzzy-Logic
0d2911c02b5bd4eedcca42925e7e35c5dd450bf8
[ "Apache-2.0" ]
null
null
null
src/titanic/model/AlternativeMachine.cpp
LaroyenneG/Fuzzy-Logic
0d2911c02b5bd4eedcca42925e7e35c5dd450bf8
[ "Apache-2.0" ]
null
null
null
src/titanic/model/AlternativeMachine.cpp
LaroyenneG/Fuzzy-Logic
0d2911c02b5bd4eedcca42925e7e35c5dd450bf8
[ "Apache-2.0" ]
null
null
null
#include "AlternativeMachine.h" namespace model { AlternativeMachine::AlternativeMachine() : Engine(ALTERNATIVE_DEFAULT_PROPELLER_DIAMETER / 2.0, ALTERNATIVE_DEFAULT_PROPELLER_WEIGHT, ALTERNATIVE_DEFAULT_MAX_POWER, ALTERNATIVE_DEFAULT_MAX_SPEED, ALTERNATIVE_DEFAULT_FRICTION, ALTERNATIVE_DEFAULT_POWER_STEP, ALTERNATIVE_DEFAULT_BLADE_NUMBER) { } std::string AlternativeMachine::getName() const { return std::string(ALTERNATIVE_DEFAULT_ENGINE_NAME); } double AlternativeMachine::powerStepFunction(double _powerStep, double time, double _power, double _desiredPower) const { static const int SLEEP_NUMBER = 3; if (_power < _desiredPower && fabs(_power) < pow(10, -SLEEP_NUMBER)) { _powerStep /= pow(10, SLEEP_NUMBER); } else if (_power > _desiredPower && fabs(_power) < pow(10, -SLEEP_NUMBER)) { _powerStep /= pow(10, SLEEP_NUMBER); } return Engine::powerStepFunction(_powerStep, time, _power, _desiredPower); } }
34.677419
118
0.685581
LaroyenneG
183d00a9783887b9081c3b3756936046cbc55051
552
cpp
C++
Conversion.cpp
dabbertorres/unicode
a886097339711371e178a8e39dbc4bc33370d0c1
[ "MIT" ]
1
2018-04-24T12:03:34.000Z
2018-04-24T12:03:34.000Z
Conversion.cpp
dabbertorres/utf8
a886097339711371e178a8e39dbc4bc33370d0c1
[ "MIT" ]
1
2016-09-13T01:36:24.000Z
2016-09-13T01:36:24.000Z
Conversion.cpp
dabbertorres/unicode
a886097339711371e178a8e39dbc4bc33370d0c1
[ "MIT" ]
null
null
null
#include "Conversion.hpp" #include <memory> namespace dbr { namespace unicode { utf32::ImmutableString toUTF32(const utf8::ImmutableString& str) { auto* data = str.data(); auto len = utf8::characterLength(data); auto out = std::make_unique<utf32::Char[]>(len); for(auto i = 0u; i < len; ++i) { std::size_t seqLen = 0; out[i] = utf8::decode(data, seqLen); data += seqLen; } return{out.get()}; } utf8::ImmutableString toUTF8(const utf32::ImmutableString& /*str*/) { // TODO return{}; } } }
16.235294
69
0.603261
dabbertorres
183d46b469eaad5abd7c23a99133ffd19a75a17b
118
cc
C++
code/snip_overflow_tle.cc
xry111/2019-summer-lecture-debug
ee9800750050cf724bd001c5f511dd0445a82cfe
[ "CC-BY-4.0" ]
3
2019-09-08T11:41:34.000Z
2020-11-14T12:20:57.000Z
code/snip_overflow_tle.cc
xry111/2019-summer-lecture-debug
ee9800750050cf724bd001c5f511dd0445a82cfe
[ "CC-BY-4.0" ]
2
2021-09-14T09:40:40.000Z
2021-09-19T13:22:10.000Z
code/snip_overflow_tle.cc
xry111/2019-summer-lecture-debug
ee9800750050cf724bd001c5f511dd0445a82cfe
[ "CC-BY-4.0" ]
null
null
null
int a, b, ans = 0; scanf("%d%d", &a, &b); for (int i = a; i <= b; i++) ans += foo(i); printf("%d\n", ans); return 0;
16.857143
28
0.457627
xry111
183e619df94fdd7eb005fd72e5033c9ab8ff2266
5,527
hpp
C++
3rdparty/libprocess/src/mpsc_linked_queue.hpp
zagrev/mesos
eefec152dffc4977183089b46fbfe37dbd19e9d7
[ "Apache-2.0" ]
4,537
2015-01-01T03:26:40.000Z
2022-03-31T03:07:00.000Z
3rdparty/libprocess/src/mpsc_linked_queue.hpp
zagrev/mesos
eefec152dffc4977183089b46fbfe37dbd19e9d7
[ "Apache-2.0" ]
227
2015-01-29T02:21:39.000Z
2022-03-29T13:35:50.000Z
3rdparty/libprocess/src/mpsc_linked_queue.hpp
zagrev/mesos
eefec152dffc4977183089b46fbfe37dbd19e9d7
[ "Apache-2.0" ]
1,992
2015-01-05T12:29:19.000Z
2022-03-31T03:07:07.000Z
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License #ifndef __MPSC_LINKED_QUEUE_HPP__ #define __MPSC_LINKED_QUEUE_HPP__ #include <atomic> #include <functional> #include <glog/logging.h> namespace process { // This queue is a C++ port of the MpscLinkedQueue of JCTools, but limited to // the core methods: // https://github.com/JCTools/JCTools/blob/master/jctools-core/src/main/java/org/jctools/queues/MpscLinkedQueue.java // // which is a Java port of the MPSC algorithm as presented in following article: // http://www.1024cores.net/home/lock-free-algorithms/queues/non-intrusive-mpsc-node-based-queue // // The queue has following properties: // Producers are wait-free (one atomic exchange per enqueue) // Consumer is // - lock-free // - mostly wait-free, except when consumer reaches the end of the queue // and producer enqueued a new node, but did not update the next pointer // on the old node, yet template <typename T> class MpscLinkedQueue { private: template <typename E> struct Node { public: explicit Node(E* element = nullptr) : element(element) {} E* element; std::atomic<Node<E>*> next = ATOMIC_VAR_INIT(nullptr); }; public: MpscLinkedQueue() { tail = new Node<T>(); head.store(tail); } ~MpscLinkedQueue() { while (auto element = dequeue()) { delete element; } delete tail; } // Multi producer safe. void enqueue(T* element) { // A `nullptr` is used to denote an empty queue when doing a // `dequeue()` so producers can't use it as an element. CHECK_NOTNULL(element); auto newNode = new Node<T>(element); // Exchange is guaranteed to only give the old value to one // producer, so this is safe and wait-free. auto oldhead = head.exchange(newNode, std::memory_order_acq_rel); // At this point if this thread context switches out we may block // the consumer from doing a dequeue (see below). Eventually we'll // unblock the consumer once we run again and execute the next // line of code. oldhead->next.store(newNode, std::memory_order_release); } // Single consumer only. T* dequeue() { auto currentTail = tail; // Check and see if there is an actual element linked from `tail` // since we use `tail` as a "stub" rather than the actual element. auto nextTail = currentTail->next.load(std::memory_order_acquire); // There are three possible cases here: // // (1) The queue is empty. // (2) The queue appears empty but a producer is still enqueuing // so let's wait for it and then dequeue. // (3) We have something to dequeue. // // Start by checking if the queue is or appears empty. if (nextTail == nullptr) { // Now check if the queue is actually empty or just appears // empty. If it's actually empty then return `nullptr` to denote // emptiness. if (head.load(std::memory_order_relaxed) == tail) { return nullptr; } // Another thread already inserted a new node, but did not // connect it to the tail, yet, so we spin-wait. At this point // we are not wait-free anymore. do { nextTail = currentTail->next.load(std::memory_order_acquire); } while (nextTail == nullptr); } CHECK_NOTNULL(nextTail); // Set next pointer of current tail to null to disconnect it // from the queue. currentTail->next.store(nullptr, std::memory_order_release); auto element = nextTail->element; nextTail->element = nullptr; tail = nextTail; delete currentTail; return element; } // Single consumer only. // // TODO(drexin): Provide C++ style iteration so someone can just use // the `std::for_each()`. template <typename F> void for_each(F&& f) { auto end = head.load(); auto node = tail; for (;;) { node = node->next.load(); // We are following the linked structure until we reach the end // node. There is a race with new nodes being added, so we limit // the traversal to the last node at the time we started. if (node == nullptr) { return; } f(node->element); if (node == end) { return; } } } // Single consumer only. bool empty() { return tail->next.load(std::memory_order_relaxed) == nullptr && head.load(std::memory_order_relaxed) == tail; } private: // TODO(drexin): Programatically get the cache line size. // // We align head to 64 bytes (x86 cache line size) to guarantee // it to be put on a new cache line. This is to prevent false // sharing with other objects that could otherwise end up on // the same cache line as this queue. We also align tail to // avoid false sharing with head and add padding after tail // to avoid false sharing with other objects. alignas(64) std::atomic<Node<T>*> head; alignas(64) Node<T>* tail; char pad[64 - sizeof(Node<T>*)]; }; } // namespace process { #endif // __MPSC_LINKED_QUEUE_HPP__
29.55615
116
0.666908
zagrev
183f69fee2cdc3929bd87a080dbf16710817c42c
4,857
cpp
C++
packages/monte_carlo/core/test/tstAdjointKleinNishinaSamplingTypeHelpers.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/monte_carlo/core/test/tstAdjointKleinNishinaSamplingTypeHelpers.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/monte_carlo/core/test/tstAdjointKleinNishinaSamplingTypeHelpers.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_AdjointKleinNishinaSamplingType.hpp //! \author Alex Robinson //! \brief Adjoint Klein-Nishina sampling type helper function unit tests //! //---------------------------------------------------------------------------// // Std Lib Includes #include <iostream> #include <sstream> // FRENSIE Includes #include "MonteCarlo_AdjointKleinNishinaSamplingType.hpp" #include "Utility_UnitTestHarnessWithMain.hpp" #include "ArchiveTestHelpers.hpp" //---------------------------------------------------------------------------// // Testing Types //---------------------------------------------------------------------------// typedef TestArchiveHelper::TestArchives TestArchives; //---------------------------------------------------------------------------// // Tests. //---------------------------------------------------------------------------// // Check that a sampling type can be converted to a string FRENSIE_UNIT_TEST( AdjointKleinNishinaSamplingType, toString ) { std::string sampling_name = Utility::toString( MonteCarlo::TWO_BRANCH_REJECTION_ADJOINT_KN_SAMPLING ); FRENSIE_CHECK_EQUAL( sampling_name, "Two Branch Rejection Adjoint Klein-Nishina Sampling" ); sampling_name = Utility::toString( MonteCarlo::THREE_BRANCH_LIN_MIXED_ADJOINT_KN_SAMPLING ); FRENSIE_CHECK_EQUAL( sampling_name, "Three Branch Lin Mixed Adjoint Klein-Nishina Sampling" ); sampling_name = Utility::toString( MonteCarlo::THREE_BRANCH_INVERSE_MIXED_ADJOINT_KN_SAMPLING ); FRENSIE_CHECK_EQUAL( sampling_name, "Three Branch Log Mixed Adjoint Klein-Nishina Sampling" ); } //---------------------------------------------------------------------------// // Check that a sampling type can be placed in a stream FRENSIE_UNIT_TEST( AdjointKleinNishinaSamplingType, ostream_operator ) { std::ostringstream oss; oss << MonteCarlo::TWO_BRANCH_REJECTION_ADJOINT_KN_SAMPLING; FRENSIE_CHECK_EQUAL( oss.str(), "Two Branch Rejection Adjoint Klein-Nishina Sampling" ); oss.str( "" ); oss.clear(); oss << MonteCarlo::THREE_BRANCH_LIN_MIXED_ADJOINT_KN_SAMPLING; FRENSIE_CHECK_EQUAL( oss.str(), "Three Branch Lin Mixed Adjoint Klein-Nishina Sampling" ); oss.str( "" ); oss.clear(); oss << MonteCarlo::THREE_BRANCH_INVERSE_MIXED_ADJOINT_KN_SAMPLING; FRENSIE_CHECK_EQUAL( oss.str(), "Three Branch Log Mixed Adjoint Klein-Nishina Sampling" ); } //---------------------------------------------------------------------------// // Check that a sampling type can be archived FRENSIE_UNIT_TEST_TEMPLATE_EXPAND( AdjointKleinNishinaSamplingType, archive, TestArchives ) { FETCH_TEMPLATE_PARAM( 0, RawOArchive ); FETCH_TEMPLATE_PARAM( 1, RawIArchive ); typedef typename std::remove_pointer<RawOArchive>::type OArchive; typedef typename std::remove_pointer<RawIArchive>::type IArchive; std::string archive_base_name( "test_adjoint_kn_sampling_type" ); std::ostringstream archive_ostream; { std::unique_ptr<OArchive> oarchive; createOArchive( archive_base_name, archive_ostream, oarchive ); MonteCarlo::AdjointKleinNishinaSamplingType type_1 = MonteCarlo::TWO_BRANCH_REJECTION_ADJOINT_KN_SAMPLING; MonteCarlo::AdjointKleinNishinaSamplingType type_2 = MonteCarlo::THREE_BRANCH_LIN_MIXED_ADJOINT_KN_SAMPLING; MonteCarlo::AdjointKleinNishinaSamplingType type_3 = MonteCarlo::THREE_BRANCH_INVERSE_MIXED_ADJOINT_KN_SAMPLING; FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP( type_1 ) ); FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP( type_2 ) ); FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP( type_3 ) ); } // Copy the archive ostream to an istream std::istringstream archive_istream( archive_ostream.str() ); // Load the archived distributions std::unique_ptr<IArchive> iarchive; createIArchive( archive_istream, iarchive ); MonteCarlo::AdjointKleinNishinaSamplingType type_1, type_2, type_3; FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP( type_1 ) ); FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP( type_2 ) ); FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP( type_3 ) ); iarchive.reset(); FRENSIE_CHECK_EQUAL( type_1, MonteCarlo::TWO_BRANCH_REJECTION_ADJOINT_KN_SAMPLING ); FRENSIE_CHECK_EQUAL( type_2, MonteCarlo::THREE_BRANCH_LIN_MIXED_ADJOINT_KN_SAMPLING ); FRENSIE_CHECK_EQUAL( type_3, MonteCarlo::THREE_BRANCH_INVERSE_MIXED_ADJOINT_KN_SAMPLING ); } //---------------------------------------------------------------------------// // end MonteCarlo_AdjointKleinNishinaSamplingType.hpp //---------------------------------------------------------------------------//
38.244094
98
0.646695
bam241
1841dc01afabd4ea7b689d52988926927bed8374
4,199
cpp
C++
Main alarm box/MainAlarm/TimerMode.cpp
nicholas-p1/LightAlarm
3528a196edcba485cefac7a57adffb4e6434b97c
[ "MIT" ]
null
null
null
Main alarm box/MainAlarm/TimerMode.cpp
nicholas-p1/LightAlarm
3528a196edcba485cefac7a57adffb4e6434b97c
[ "MIT" ]
null
null
null
Main alarm box/MainAlarm/TimerMode.cpp
nicholas-p1/LightAlarm
3528a196edcba485cefac7a57adffb4e6434b97c
[ "MIT" ]
null
null
null
#include "Arduino.h" #include "TimerMode.h" #include "IMode.h" #include "ILogger.h" #include "UserIO.h" TimerMode::TimerMode(ILogger *_logger, UserIO *_io) : logger{_logger}, io(_io), isEnabled{false}, isPaused{false}, IMode("Timer mode") {} void TimerMode::resetAll() { timeAtStartMS = 0; timerDurationMS = 0; isEnabled = false; isPaused = false; } byte TimerMode::getNumberOfOptions() const { return numberOfOptions; } void TimerMode::displayTimeLeft() const { io->setCursor(0, 0); if (isEnabled) { const unsigned long timeLeftMS = isPaused ? (timeAtStartMS + timerDurationMS - timeAtPauseStartMS) : (timeAtStartMS + timerDurationMS - millis()); int secondsLeft = (int)((timeLeftMS / 1000UL) % 60UL); int minutesLeft = (int)((timeLeftMS / (1000UL * 60UL)) % 60UL); int hoursLeft = (int)(timeLeftMS / (1000UL * 60UL * 60UL)); io->print(F("Time left: ")); io->printDigits(hoursLeft, true); io->printDigits(minutesLeft); io->printDigits(secondsLeft); } else { io->print(F("No timer set")); } } void TimerMode::displayOptions() { const unsigned long displayOptionsIntervalMS PROGMEM = 2000; //display different timer mode options unsigned long currentTimerMillis = millis(); if ((unsigned long)(currentTimerMillis - previousTimerMillis) >= displayOptionsIntervalMS) { //don't want to clear first row as used to display time left io->clearRow(1); io->clearRow(2); io->clearRow(3); io->setCursor(0, 1); io->print("Select one (#=Quit):"); for (int i{2}; i < 4 && currentDisplayedOption < numberOfOptions; i++) { String optionName = optionNames[currentDisplayedOption]; io->setCursor(0, i); io->print(optionName); currentDisplayedOption++; } //check if need to rollover to first option if (currentDisplayedOption >= numberOfOptions) { currentDisplayedOption = 0; } previousTimerMillis = currentTimerMillis; //restart display option interval } } byte TimerMode::selectOption() { byte option = io->selectOption(numberOfOptions); if (option) { currentDisplayedOption = 0; //make sure to start with displaying first option when displayOptions() is entered again } return option; } void TimerMode::executeOption(int selectedOption) { switch (selectedOption) { case 1: //set new timer //blocking operation setNewTimer(); break; case 2: //disable timer disableTimer(); break; case 3: //pause timer pauseTimer(); break; case 4: //resume timer resumeTimer(); break; case 5: //restart timer restartTimer(); break; default: logger->logError(F("Tried to execute non-existing timer option"), F("TimerMode, executeOption")); break; } previousTimerMillis = 0; //eliminate any possible delay } void TimerMode::setNewTimer() { io->clearScreen(); io->setCursor(0, 0); io->print(F("Entering timer time")); int *durations = io->getHoursMinutesSeconds(); if (!durations) { return; } int hours{durations[0]}, minutes{durations[1]}, seconds{durations[2]}; delete[] durations; isEnabled = true; timeAtStartMS = millis(); timerDurationMS = (hours * 60UL * 60UL * 1000UL + minutes * 60UL * 1000UL + seconds * 1000UL); } void TimerMode::disableTimer() { resetAll(); } void TimerMode::pauseTimer() { if (!isEnabled || isPaused) { logger->logError(F("Tried to pause already paused or disabled timer"), F("TimerMode, pauseTimer")); return; } isPaused = true; timeAtPauseStartMS = millis(); } void TimerMode::resumeTimer() { if (!isEnabled || !isPaused) { logger->logError(F("Tried to resume non-paused timer"), F("TimerMode, resumeTimer")); return; } timerDurationMS += millis() - timeAtPauseStartMS; //icnrease duration by pause time isPaused = false; } void TimerMode::restartTimer() { timeAtStartMS = millis(); } bool TimerMode::hasTimerFinished() const { //also considers rare case of millis() overflow if (isEnabled && !isPaused && (unsigned long)(millis() - timeAtStartMS) >= timerDurationMS) { return true; } else { return false; } }
23.723164
150
0.663253
nicholas-p1
1842316ff2cf1820289cd7b10b7efa8223b2cb5b
3,566
cpp
C++
Source/10.0.18362.0/ucrt/stdlib/bsearch.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
2
2021-01-27T10:19:30.000Z
2021-02-09T06:24:30.000Z
Source/10.0.18362.0/ucrt/stdlib/bsearch.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
null
null
null
Source/10.0.18362.0/ucrt/stdlib/bsearch.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
1
2021-01-27T10:19:36.000Z
2021-01-27T10:19:36.000Z
// // bsearch.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. // // Defines bsearch(), which performs a binary search over an array. // #include <corecrt_internal.h> #include <search.h> #ifdef _M_CEE #define __fileDECL __clrcall #else #define __fileDECL __cdecl #endif /*** *char *bsearch() - do a binary search on an array * *Purpose: * Does a binary search of a sorted array for a key. * *Entry: * const char *key - key to search for * const char *base - base of sorted array to search * unsigned int num - number of elements in array * unsigned int width - number of bytes per element * int (*compare)() - pointer to function that compares two array * elements, returning neg when #1 < #2, pos when #1 > #2, and * 0 when they are equal. Function is passed pointers to two * array elements. * *Exit: * if key is found: * returns pointer to occurrence of key in array * if key is not found: * returns nullptr * *Exceptions: * Input parameters are validated. Refer to the validation section of the function. * *******************************************************************************/ #ifdef __USE_CONTEXT #define __COMPARE(context, p1, p2) (*compare)(context, p1, p2) #else #define __COMPARE(context, p1, p2) (*compare)(p1, p2) #endif #ifndef _M_CEE extern "C" #endif _CRT_SECURITYSAFECRITICAL_ATTRIBUTE #ifdef __USE_CONTEXT void* __fileDECL bsearch_s( void const* const key, void const* const base, size_t num, size_t const width, int (__fileDECL* const compare)(void*, void const*, void const*), void* const context ) #else // __USE_CONTEXT void* __fileDECL bsearch( void const* const key, void const* const base, size_t num, size_t const width, int (__fileDECL* const compare)(void const*, void const*) ) #endif // __USE_CONTEXT { _VALIDATE_RETURN(base != nullptr || num == 0, EINVAL, nullptr); _VALIDATE_RETURN(width > 0, EINVAL, nullptr); _VALIDATE_RETURN(compare != nullptr, EINVAL, nullptr); char const* lo = reinterpret_cast<char const*>(base); char const* hi = reinterpret_cast<char const*>(base) + (num - 1) * width; // Reentrancy diligence: Save (and unset) global-state mode to the stack before making callout to 'compare' __crt_state_management::scoped_global_state_reset saved_state; // We allow a nullptr key here because it breaks some older code and because // we do not dereference this ourselves so we can't be sure that it's a // problem for the comparison function while (lo <= hi) { size_t const half = num / 2; if (half != 0) { char const* const mid = lo + (num & 1 ? half : (half - 1)) * width; int const result = __COMPARE(context, key, mid); if (result == 0) { return const_cast<void*>(static_cast<void const*>(mid)); } else if (result < 0) { hi = mid - width; num = num & 1 ? half : half - 1; } else { lo = mid + width; num = half; } } else if (num != 0) { return __COMPARE(context, key, lo) ? nullptr : const_cast<void*>(static_cast<void const*>(lo)); } else { break; } } return nullptr; } #undef __COMPARE
28.07874
111
0.579361
825126369
18485249c4aeacdef37195d8192a339a60b0b808
24,156
hh
C++
tests/Titon/Route/RouterTest.hh
ciklon-z/framework
cbf44729173d3a83b91a2b0a217c6b3827512e44
[ "BSD-2-Clause" ]
206
2015-01-02T20:01:12.000Z
2021-04-15T09:49:56.000Z
tests/Titon/Route/RouterTest.hh
ciklon-z/framework
cbf44729173d3a83b91a2b0a217c6b3827512e44
[ "BSD-2-Clause" ]
44
2015-01-02T06:03:43.000Z
2017-11-20T18:29:06.000Z
tests/Titon/Route/RouterTest.hh
titon/framework
cbf44729173d3a83b91a2b0a217c6b3827512e44
[ "BSD-2-Clause" ]
27
2015-01-03T05:51:29.000Z
2022-02-21T13:50:40.000Z
<?hh namespace Titon\Route; use Titon\Cache\Storage\MemoryStorage; use Titon\Test\Stub\Route\FilterStub; use Titon\Test\Stub\Route\TestRouteStub; use Titon\Test\TestCase; use Titon\Utility\State\Get; use Titon\Utility\State\Server; use Titon\Context\Depository; /** * @property \Titon\Route\Router $object */ class RouterTest extends TestCase { protected function setUp(): void { parent::setUp(); $container = Depository::getInstance(); $container->singleton('Titon\Route\Router'); $this->object = $router = Depository::getInstance()->make('Titon\Route\Router'); invariant($router instanceof Router, 'Must be a Router.'); $container->register('Titon\Route\UrlBuilder')->with($router); $this->object->map('action.ext', new TestRouteStub('/{module}/{controller}/{action}.{ext}', 'Module\Controller@action')); $this->object->map('action', new TestRouteStub('/{module}/{controller}/{action}', 'Module\Controller@action')); $this->object->map('controller', new TestRouteStub('/{module}/{controller}', 'Module\Controller@action')); $this->object->map('module', new TestRouteStub('/{module}', 'Module\Controller@action')); $this->object->map('root', new TestRouteStub('/', 'Module\Controller@action')); } protected function tearDown(): void { Depository::getInstance() ->remove('Titon\Route\Router') ->remove('Titon\Route\UrlBuilder'); } public function testBuildAction(): void { $this->assertEquals('Controller@action', Router::buildAction(shape('class' => 'Controller', 'action' => 'action'))); } public function testCaching(): void { $storage = new MemoryStorage(); $route1 = new Route('/{module}', 'Module\Controller@action'); $route2 = new Route('/', 'Module\Controller@action'); $router1 = new Router(); $router1->setStorage($storage); $router1->map('module', $route1); $router1->map('root', $route2); $this->assertFalse($storage->has('routes')); $router1->match('/'); $this->assertTrue($storage->has('routes')); // Now load another instance $router2 = new Router(); $router2->setStorage($storage); $this->assertEquals(Map {}, $router2->getRoutes()); $router2->map('root', new Route('/foobar', 'Module\Controller@action')); $router2->match('/'); $this->assertEquals(Map {'module' => $route1, 'root' => $route2}, $router2->getRoutes()); // The previous routes should be overwritten $this->assertEquals('/', $router2->getRoute('root')->getPath()); } public function testFilters(): void { $stub = new FilterStub(); $this->object->filter('test', $stub); $this->object->filterCallback('test2', () ==> {}); $this->assertEquals(inst_meth($stub, 'filter'), $this->object->getFilter('test')); $this->assertEquals(Vector {'test', 'test2'}, $this->object->getFilters()->keys()); // Filtering is passed to routes $this->object->map('f1', (new Route('/f1', 'Controller@action'))->addFilter('test2')); $this->object->group(($router, $group) ==> { $group->setFilters(Vector {'test'}); $router->map('f2', new Route('/f2', 'Controller@action')); }); $this->object->map('f3', new Route('/f3', 'Controller@action')); $routes = $this->object->getRoutes(); $this->assertEquals(Vector {'test2'}, $routes['f1']->getFilters()); $this->assertEquals(Vector {'test'}, $routes['f2']->getFilters()); $this->assertEquals(Vector {}, $routes['f3']->getFilters()); } /** * @expectedException \Titon\Route\Exception\MissingFilterException */ public function testFilterMissingKey(): void { $this->object->getFilter('fakeKey'); } public function testFilterIsTriggered(): void { $router = new Router(); $count = 0; $router->filterCallback('test', function($router, $route) use (&$count) { $count++; }); $router->map('f1', (new Route('/f1', 'Controller@action'))->addFilter('test')); $router->group(($router, $group) ==> { $group->setFilters(Vector {'test'}); $router->map('f2', new Route('/f2', 'Controller@action')); }); $router->map('f3', new Route('/f3', 'Controller@action')); $router->match('/f1'); $this->assertEquals(1, $count); $router->match('/f2'); $this->assertEquals(2, $count); $router->match('/f3'); $this->assertEquals(2, $count); } /** * @expectedException \Exception */ public function testFilterCanThrowException(): void { $this->object->filterCallback('test', () ==> { throw new \Exception('Filter error!'); }); $this->object->map('root', (new Route('/', 'Controller@action'))->addFilter('test')); $this->object->match('/'); } public function testGroupPrefixing(): void { $this->object->group(($router, $group) ==> { $group->setPrefix('/pre/'); $router->map('group1', new Route('/group-1', 'Controller@action')); $router->map('group2', new Route('/group-2', 'Controller@action')); }); $this->object->map('solo', new Route('/solo', 'Controller@action')); $routes = $this->object->getRoutes(); $this->assertEquals('/', $routes['root']->getPath()); $this->assertEquals('/pre/group-1', $routes['group1']->getPath()); $this->assertEquals('/pre/group-2', $routes['group2']->getPath()); $this->assertEquals('/solo', $routes['solo']->getPath()); } public function testGroupSuffixing(): void { $this->object->group(($router, $group) ==> { $group->setSuffix('/post/'); $router->map('group1', new Route('/group-1', 'Controller@action')); $router->map('group2', new Route('/group-2', 'Controller@action')); }); $this->object->map('solo', new Route('/solo', 'Controller@action')); $routes = $this->object->getRoutes(); $this->assertEquals('/', $routes['root']->getPath()); $this->assertEquals('/group-1/post', $routes['group1']->getPath()); $this->assertEquals('/group-2/post', $routes['group2']->getPath()); $this->assertEquals('/solo', $routes['solo']->getPath()); } public function testGroupSecure(): void { $this->object->group(($router, $group) ==> { $group->setSecure(true); $router->map('group1', new Route('/group-1', 'Controller@action')); $router->map('group2', new Route('/group-2', 'Controller@action')); }); $this->object->map('solo', new Route('/solo', 'Controller@action')); $routes = $this->object->getRoutes(); $this->assertEquals(false, $routes['root']->getSecure()); $this->assertEquals(true, $routes['group1']->getSecure()); $this->assertEquals(true, $routes['group2']->getSecure()); $this->assertEquals(false, $routes['solo']->getSecure()); } public function testGroupPatterns(): void { $this->object->group(($router, $group) ==> { $group->setPrefix('<token>'); $group->addPattern('token', '([abcd]+)'); $router->map('group1', new Route('/group-1', 'Controller@action')); $router->map('group2', (new Route('/group-2', 'Controller@action'))->addPattern('foo', '(bar|baz)')); }); $this->object->map('solo', new Route('/solo', 'Controller@action')); $routes = $this->object->getRoutes(); $this->assertEquals('/', $routes['root']->getPath()); $this->assertEquals('/<token>/group-1', $routes['group1']->getPath()); $this->assertEquals('/<token>/group-2', $routes['group2']->getPath()); $this->assertEquals('/solo', $routes['solo']->getPath()); $this->assertEquals(Map {}, $routes['root']->getPatterns()); $this->assertEquals(Map {'token' => '([abcd]+)'}, $routes['group1']->getPatterns()); $this->assertEquals(Map {'foo' => '(bar|baz)', 'token' => '([abcd]+)'}, $routes['group2']->getPatterns()); $this->assertEquals(Map {}, $routes['solo']->getPatterns()); } public function testGroupConditions(): void { $cond1 = () ==> {}; $cond2 = () ==> {}; $this->object->group(($router, $group) ==> { $group->setConditions(Vector {$cond1, $cond2}); $router->map('group1', new Route('/group-1', 'Controller@action')); $router->map('group2', new Route('/group-2', 'Controller@action')); }); $this->object->map('solo', new Route('/solo', 'Controller@action')); $routes = $this->object->getRoutes(); $this->assertEquals(Vector {}, $routes['root']->getConditions()); $this->assertEquals(Vector {$cond1, $cond2}, $routes['group1']->getConditions()); $this->assertEquals(Vector {$cond1, $cond2}, $routes['group2']->getConditions()); $this->assertEquals(Vector {}, $routes['solo']->getConditions()); } public function testGroupNesting(): void { $this->object->group(($router, $group1) ==> { $group1->setPrefix('/pre/'); $router->map('group1', new Route('/group-1', 'Controller@action')); $router->group(($router, $group2) ==> { $group2->setSuffix('/post'); $router->map('group2', new Route('/group-2', 'Controller@action')); }); }); $this->object->map('solo', new Route('/solo', 'Controller@action')); $routes = $this->object->getRoutes(); $this->assertEquals('/', $routes['root']->getPath()); $this->assertEquals('/pre/group-1', $routes['group1']->getPath()); $this->assertEquals('/pre/group-2/post', $routes['group2']->getPath()); $this->assertEquals('/solo', $routes['solo']->getPath()); } public function testGroupNestingInherits(): void { $this->object->group(($router, $group1) ==> { $group1->setFilters(Vector {'foo'})->setMethods(Vector {'get'}); $router->map('group1', new Route('/group-1', 'Controller@action')); $router->group(($router, $group2) ==> { $group2->setFilters(Vector {'bar'}); $router->map('group2', new Route('/group-2', 'Controller@action')); $router->group(($router, $group3) ==> { $group3->setMethods(Vector {'post'}); $router->map('group3', new Route('/group-3', 'Controller@action')); }); }); }); $routes = $this->object->getRoutes(); $this->assertEquals(Vector {'foo'}, $routes['group1']->getFilters()); $this->assertEquals(Vector {'foo', 'bar'}, $routes['group2']->getFilters()); $this->assertEquals(Vector {'foo', 'bar'}, $routes['group3']->getFilters()); $this->assertEquals(Vector {'get'}, $routes['group1']->getMethods()); $this->assertEquals(Vector {'get'}, $routes['group2']->getMethods()); $this->assertEquals(Vector {'get', 'post'}, $routes['group3']->getMethods()); } public function testHttpMapping(): void { $this->object->map('url1', new Route('/url', 'Controller@action')); $this->object->get('url2', new Route('/url', 'Controller@action')); $this->object->post('url3', new Route('/url', 'Controller@action')); $this->object->put('url4', new Route('/url', 'Controller@action')); $this->object->delete('url5', new Route('/url', 'Controller@action')); $this->object->head('url6', new Route('/url', 'Controller@action')); $this->object->options('url7', new Route('/url', 'Controller@action')); $this->object->http('url8', Vector {'get', 'post'}, new Route('/url', 'Controller@action')); $routes = $this->object->getRoutes(); $this->assertEquals(Vector {}, $routes['url1']->getMethods()); $this->assertEquals(Vector {'get'}, $routes['url2']->getMethods()); $this->assertEquals(Vector {'post'}, $routes['url3']->getMethods()); $this->assertEquals(Vector {'put'}, $routes['url4']->getMethods()); $this->assertEquals(Vector {'delete'}, $routes['url5']->getMethods()); $this->assertEquals(Vector {'head'}, $routes['url6']->getMethods()); $this->assertEquals(Vector {'options'}, $routes['url7']->getMethods()); $this->assertEquals(Vector {'get', 'post'}, $routes['url8']->getMethods()); } public function testLoopMatch(): void { $route = $this->object->match('/'); $this->assertEquals('/', $route->getPath()); $this->assertEquals($route, $this->object->current()); $route = $this->object->match('/users'); $this->assertEquals('/{module}', $route->getPath()); $route = $this->object->match('/users/profile'); $this->assertEquals('/{module}/{controller}', $route->getPath()); $route = $this->object->match('/users/profile/view'); $this->assertEquals('/{module}/{controller}/{action}', $route->getPath()); $route = $this->object->match('/users/profile/view.json'); $this->assertEquals('/{module}/{controller}/{action}.{ext}', $route->getPath()); } /** * @expectedException \Titon\Route\Exception\NoMatchException */ public function testLoopMatchNoMatch(): void { $this->object->match('/path~tilde'); } public function testParseAction(): void { $this->assertEquals(shape( 'class' => 'Controller', 'action' => 'action' ), Router::parseAction('Controller@action')); $this->assertEquals(shape( 'class' => 'Controller', 'action' => 'foo' ), Router::parseAction('Controller@foo')); $this->assertEquals(shape( 'class' => 'Module\Controller', 'action' => 'index' ), Router::parseAction('Module\Controller@index')); $this->assertEquals(shape( 'class' => 'Module\Controller_With_Underscores', 'action' => 'index' ), Router::parseAction('Module\Controller_With_Underscores@index')); $this->assertEquals(shape( 'class' => 'Module\Controller_With_Numbers123', 'action' => 'index' ), Router::parseAction('Module\Controller_With_Numbers123@index')); $this->assertEquals(shape( 'class' => 'Module\Controller', 'action' => 'action' ), Router::parseAction('Module\Controller@action')); $this->assertEquals(shape( 'class' => 'Module\Controller', 'action' => 'multiWordAction' ), Router::parseAction('Module\Controller@multiWordAction')); $this->assertEquals(shape( 'class' => 'Module\Controller', 'action' => 'action_with_underscores' ), Router::parseAction('Module\Controller@action_with_underscores')); } /** * @expectedException \Titon\Route\Exception\InvalidRouteActionException */ public function testParseActionInvalidRoute(): void { Router::parseAction('Broken+Route'); } public function testPrgMapping(): void { $this->object->prg('prg', (new Route('/foo', 'Controller@action'))->addFilter('auth')); $routes = $this->object->getRoutes(); // Keys $this->assertFalse(isset($routes['prg'])); $this->assertTrue(isset($routes['prg.get'])); $this->assertTrue(isset($routes['prg.post'])); // Paths $this->assertEquals('/foo', $routes['prg.get']->getPath()); $this->assertEquals('/foo', $routes['prg.post']->getPath()); // Action $this->assertEquals(shape('class' => 'Controller', 'action' => 'getAction'), $routes['prg.get']->getAction()); $this->assertEquals(shape('class' => 'Controller', 'action' => 'postAction'), $routes['prg.post']->getAction()); // Method $this->assertEquals(Vector {'get'}, $routes['prg.get']->getMethods()); $this->assertEquals(Vector {'post'}, $routes['prg.post']->getMethods()); // Filters should be cloned also $this->assertEquals(Vector {'auth'}, $routes['prg.get']->getFilters()); $this->assertEquals(Vector {'auth'}, $routes['prg.post']->getFilters()); } public function testResourceMap(): void { $this->assertEquals(Map { 'list' => 'index', 'create' => 'create', 'read' => 'read', 'update' => 'update', 'delete' => 'delete' }, $this->object->getResourceMap()); $this->object->setResourceMap(Map { 'create' => 'add', 'read' => 'view', 'update' => 'edit', 'delete' => 'remove' }); $this->assertEquals(Map { 'list' => 'index', 'create' => 'add', 'read' => 'view', 'update' => 'edit', 'delete' => 'remove' }, $this->object->getResourceMap()); } public function testResourceMapping(): void { $this->object->resource('rest', new Route('/rest', 'Api\Rest@action')); $routes = $this->object->getRoutes(); // Keys $this->assertFalse(isset($routes['rest'])); $this->assertTrue(isset($routes['rest.list'])); $this->assertTrue(isset($routes['rest.create'])); $this->assertTrue(isset($routes['rest.read'])); $this->assertTrue(isset($routes['rest.update'])); $this->assertTrue(isset($routes['rest.delete'])); // Paths $this->assertEquals('/rest', $routes['rest.list']->getPath()); $this->assertEquals('/rest', $routes['rest.create']->getPath()); $this->assertEquals('/rest/{id}', $routes['rest.read']->getPath()); $this->assertEquals('/rest/{id}', $routes['rest.update']->getPath()); $this->assertEquals('/rest/{id}', $routes['rest.delete']->getPath()); // Action $this->assertEquals(shape('class' => 'Api\Rest', 'action' => 'index'), $routes['rest.list']->getAction()); $this->assertEquals(shape('class' => 'Api\Rest', 'action' => 'create'), $routes['rest.create']->getAction()); $this->assertEquals(shape('class' => 'Api\Rest', 'action' => 'read'), $routes['rest.read']->getAction()); $this->assertEquals(shape('class' => 'Api\Rest', 'action' => 'update'), $routes['rest.update']->getAction()); $this->assertEquals(shape('class' => 'Api\Rest', 'action' => 'delete'), $routes['rest.delete']->getAction()); // Method $this->assertEquals(Vector {'get'}, $routes['rest.list']->getMethods()); $this->assertEquals(Vector {'post'}, $routes['rest.create']->getMethods()); $this->assertEquals(Vector {'get'}, $routes['rest.read']->getMethods()); $this->assertEquals(Vector {'put', 'post'}, $routes['rest.update']->getMethods()); $this->assertEquals(Vector {'delete', 'post'}, $routes['rest.delete']->getMethods()); } public function testRouteStubs(): void { $route = new Route('/', 'Controller@action'); $router = new Router(); $router->map('key', $route); $this->assertEquals($route, $router->getRoute('key')); $this->assertEquals(Map {'key' => $route}, $router->getRoutes()); } /** * @expectedException \Titon\Route\Exception\MissingRouteException */ public function testRouteStubsMissingKey(): void { $this->object->getRoute('fakeKey'); } public function testWireClassMapping(): void { $this->object->wire('Titon\Test\Stub\Route\RouteAnnotatedStub'); $routes = $this->object->getRoutes(); // Keys $this->assertFalse(isset($routes['parent'])); $this->assertTrue(isset($routes['parent.list'])); $this->assertTrue(isset($routes['parent.create'])); $this->assertTrue(isset($routes['parent.read'])); $this->assertTrue(isset($routes['parent.update'])); $this->assertTrue(isset($routes['parent.delete'])); // Paths $this->assertEquals('/controller', $routes['parent.list']->getPath()); $this->assertEquals('/controller', $routes['parent.create']->getPath()); $this->assertEquals('/controller/{id}', $routes['parent.read']->getPath()); $this->assertEquals('/controller/{id}', $routes['parent.update']->getPath()); $this->assertEquals('/controller/{id}', $routes['parent.delete']->getPath()); // Action $this->assertEquals(shape('class' => 'Titon\Test\Stub\Route\RouteAnnotatedStub', 'action' => 'index'), $routes['parent.list']->getAction()); $this->assertEquals(shape('class' => 'Titon\Test\Stub\Route\RouteAnnotatedStub', 'action' => 'create'), $routes['parent.create']->getAction()); $this->assertEquals(shape('class' => 'Titon\Test\Stub\Route\RouteAnnotatedStub', 'action' => 'read'), $routes['parent.read']->getAction()); $this->assertEquals(shape('class' => 'Titon\Test\Stub\Route\RouteAnnotatedStub', 'action' => 'update'), $routes['parent.update']->getAction()); $this->assertEquals(shape('class' => 'Titon\Test\Stub\Route\RouteAnnotatedStub', 'action' => 'delete'), $routes['parent.delete']->getAction()); // Method $this->assertEquals(Vector {'get'}, $routes['parent.list']->getMethods()); $this->assertEquals(Vector {'post'}, $routes['parent.create']->getMethods()); $this->assertEquals(Vector {'get'}, $routes['parent.read']->getMethods()); $this->assertEquals(Vector {'put', 'post'}, $routes['parent.update']->getMethods()); $this->assertEquals(Vector {'delete', 'post'}, $routes['parent.delete']->getMethods()); } public function testWireMethodMapping(): void { $this->object->wire('Titon\Test\Stub\Route\RouteAnnotatedStub'); $routes = $this->object->getRoutes(); // Keys $this->assertTrue(isset($routes['foo'])); $this->assertTrue(isset($routes['bar'])); $this->assertTrue(isset($routes['baz'])); $this->assertTrue(isset($routes['qux'])); // Paths $this->assertEquals('/foo', $routes['foo']->getPath()); $this->assertEquals('/bar', $routes['bar']->getPath()); $this->assertEquals('/baz', $routes['baz']->getPath()); $this->assertEquals('/qux', $routes['qux']->getPath()); // Action $this->assertEquals(shape('class' => 'Titon\Test\Stub\Route\RouteAnnotatedStub', 'action' => 'foo'), $routes['foo']->getAction()); $this->assertEquals(shape('class' => 'Titon\Test\Stub\Route\RouteAnnotatedStub', 'action' => 'bar'), $routes['bar']->getAction()); $this->assertEquals(shape('class' => 'Titon\Test\Stub\Route\RouteAnnotatedStub', 'action' => 'baz'), $routes['baz']->getAction()); $this->assertEquals(shape('class' => 'Titon\Test\Stub\Route\RouteAnnotatedStub', 'action' => 'qux'), $routes['qux']->getAction()); // Method $this->assertEquals(Vector {}, $routes['foo']->getMethods()); $this->assertEquals(Vector {'post'}, $routes['bar']->getMethods()); $this->assertEquals(Vector {'get'}, $routes['baz']->getMethods()); $this->assertEquals(Vector {'put', 'post'}, $routes['qux']->getMethods()); // Filter $this->assertEquals(Vector {}, $routes['foo']->getFilters()); $this->assertEquals(Vector {}, $routes['bar']->getFilters()); $this->assertEquals(Vector {'auth', 'guest'}, $routes['baz']->getFilters()); $this->assertEquals(Vector {}, $routes['qux']->getFilters()); // Pattern $this->assertEquals(Map {}, $routes['foo']->getPatterns()); $this->assertEquals(Map {}, $routes['bar']->getPatterns()); $this->assertEquals(Map {}, $routes['baz']->getPatterns()); $this->assertEquals(Map {'id' => '[1-8]+'}, $routes['qux']->getPatterns()); } }
41.864818
151
0.569382
ciklon-z
1849d981ceba91e60cfe1f51ab8e262572a514cf
2,779
cc
C++
Lacewing/src/cxx/filter2.cc
SortaCore/bluewing-cpp-server
14fa85d7493cde2a62cc84183032f5d240dc3743
[ "MIT" ]
2
2021-07-17T21:08:47.000Z
2021-07-25T08:50:27.000Z
Lacewing/src/cxx/filter2.cc
SortaCore/bluewing-cpp-server
14fa85d7493cde2a62cc84183032f5d240dc3743
[ "MIT" ]
null
null
null
Lacewing/src/cxx/filter2.cc
SortaCore/bluewing-cpp-server
14fa85d7493cde2a62cc84183032f5d240dc3743
[ "MIT" ]
2
2019-09-08T10:00:42.000Z
2020-11-11T20:49:38.000Z
/* vim: set et ts=3 sw=3 ft=cpp: * * Copyright (C) 2012, 2013 James McLaughlin et al. 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 THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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 "../common.h" filter lacewing::filter_new () { return (filter) lw_filter_new (); } void lacewing::filter_delete (lacewing::filter filter) { lw_filter_delete ((lw_filter) filter); } void _filter::local (address addr) { lw_filter_set_local ((lw_filter) this, (lw_addr) addr); } void _filter::remote (address addr) { lw_filter_set_remote ((lw_filter) this, (lw_addr) addr); } address _filter::local () { return (address) lw_filter_local ((lw_filter) this); } address _filter::remote () { return (address) lw_filter_remote ((lw_filter) this); } long _filter::local_port () { return lw_filter_local_port ((lw_filter) this); } void _filter::local_port (long port) { lw_filter_set_local_port ((lw_filter) this, port); } long _filter::remote_port () { return lw_filter_remote_port ((lw_filter) this); } void _filter::remote_port (long port) { lw_filter_set_remote_port ((lw_filter) this, port); } bool _filter::reuse () { return lw_filter_reuse ((lw_filter) this); } void _filter::reuse (bool reuse) { lw_filter_set_reuse ((lw_filter) this, reuse); } bool _filter::ipv6 () { return lw_filter_ipv6 ((lw_filter) this); } void _filter::ipv6 (bool ipv6) { lw_filter_set_ipv6 ((lw_filter) this, ipv6); } void * _filter::tag () { return lw_filter_tag ((lw_filter) this); } void _filter::tag (void * tag) { lw_filter_set_tag ((lw_filter) this, tag); }
24.8125
77
0.738035
SortaCore
184c55598661b95d8dff818e631ad839701b49fd
1,677
hpp
C++
libs/core/include/core/containers/set_difference.hpp
devjsc/ledger
5681480faf6e2aeee577f149c17745d6ab4d4ab3
[ "Apache-2.0" ]
1
2019-09-11T09:46:04.000Z
2019-09-11T09:46:04.000Z
libs/core/include/core/containers/set_difference.hpp
devjsc/ledger
5681480faf6e2aeee577f149c17745d6ab4d4ab3
[ "Apache-2.0" ]
null
null
null
libs/core/include/core/containers/set_difference.hpp
devjsc/ledger
5681480faf6e2aeee577f149c17745d6ab4d4ab3
[ "Apache-2.0" ]
1
2019-09-19T12:38:46.000Z
2019-09-19T12:38:46.000Z
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //------------------------------------------------------------------------------ #include <algorithm> #include <iterator> #include <unordered_map> #include <unordered_set> namespace fetch { template <typename K> std::unordered_set<K> operator-(std::unordered_set<K> const &lhs, std::unordered_set<K> const &rhs) { std::unordered_set<K> result; std::copy_if(lhs.begin(), lhs.end(), std::inserter(result, result.begin()), [&rhs](K const &item) { return rhs.find(item) == rhs.end(); }); return result; } template <typename K, typename V, typename H> std::unordered_set<K, H> operator-(std::unordered_set<K, H> const & lhs, std::unordered_map<K, V, H> const &rhs) { std::unordered_set<K> result; std::copy_if(lhs.begin(), lhs.end(), std::inserter(result, result.begin()), [&rhs](K const &item) { return rhs.find(item) == rhs.end(); }); return result; } } // namespace fetch
32.882353
99
0.601073
devjsc
1850257d868f83544e8335089ad0962fbf99dc43
2,640
cpp
C++
source/Transcriptome_geneCountsAddAlign.cpp
Gavin-Lijy/STAR
4571190968fc134aa4bd0d4d7065490253b1a4c5
[ "MIT" ]
1,315
2015-01-07T02:03:15.000Z
2022-03-30T09:48:17.000Z
source/Transcriptome_geneCountsAddAlign.cpp
Gavin-Lijy/STAR
4571190968fc134aa4bd0d4d7065490253b1a4c5
[ "MIT" ]
1,429
2015-01-08T00:09:17.000Z
2022-03-31T08:12:14.000Z
source/Transcriptome_geneCountsAddAlign.cpp
Gavin-Lijy/STAR
4571190968fc134aa4bd0d4d7065490253b1a4c5
[ "MIT" ]
495
2015-01-23T20:00:45.000Z
2022-03-31T13:24:50.000Z
#include "Transcriptome.h" #include "serviceFuns.cpp" void Transcriptome::geneCountsAddAlign(uint nA, Transcript **aAll, vector<int32> &gene1) { gene1.assign(quants->geneCounts.nType,-1); if (nA>1) { quants->geneCounts.cMulti++; } else { Transcript& a=*aAll[0];//one unique alignment only int64 e1=-1; for (int ib=a.nExons-1; ib>=0; ib--) {//scan through all blocks of the alignments uint64 g1=a.exons[ib][EX_G]+a.exons[ib][EX_L]-1;//end of the block // if ((uint)ib==a.nExons-1) // {//binary search for the first time: end of the block among the starts of exons e1=binarySearch1a<uint64>(g1, exG.s, (int32) exG.nEx); // } else // {//simple backwards scan // while (e1>=0 && exG.s[e1]>g1) // {//stop when exon start is less than block end // --e1; // }; // }; while (e1>=0 && exG.eMax[e1]>=a.exons[ib][EX_G]) {//these exons may overlap this block if (exG.e[e1]>=a.exons[ib][EX_G]) {//this exon overlaps the block uint str1=(uint)exG.str[e1]-1; for (int itype=0; itype<quants->geneCounts.nType; itype++) { //str1<2 (i.e. strand=0) requirement means that genes w/o strand will accept reads from both strands if ( itype==1 && a.Str!=str1 && str1<2) continue; //same strand if ( itype==2 && a.Str==str1 && str1<2) continue; //reverse strand if (gene1.at(itype)==-1) {//first gene overlapping this read gene1[itype]=exG.g[e1]; } else if (gene1.at(itype)==-2) { continue;//this align was already found to be ambig for this strand } else if (gene1.at(itype)!=(int32)exG.g[e1]) {//another gene overlaps this read gene1[itype]=-2;//mark ambiguous };//otherwise it's the same gene }; }; --e1;// go to the previous exon }; }; for (int itype=0; itype<quants->geneCounts.nType; itype++) { if (gene1.at(itype)==-1) { quants->geneCounts.cNone[itype]++; } else if (gene1.at(itype)==-2) { quants->geneCounts.cAmbig[itype]++; } else { quants->geneCounts.gCount[itype][gene1.at(itype)]++; }; }; }; };
41.25
125
0.481061
Gavin-Lijy
185136c00cc13479752b2120e562a951fd07c971
1,542
cpp
C++
src/repeater_firing_result.cpp
skybaboon/dailycashmanager
0b022cc230a8738d5d27a799728da187e22f17f8
[ "Apache-2.0" ]
4
2016-07-05T07:42:07.000Z
2020-07-15T15:27:22.000Z
src/repeater_firing_result.cpp
skybaboon/dailycashmanager
0b022cc230a8738d5d27a799728da187e22f17f8
[ "Apache-2.0" ]
1
2020-05-07T20:58:21.000Z
2020-05-07T20:58:21.000Z
src/repeater_firing_result.cpp
skybaboon/dailycashmanager
0b022cc230a8738d5d27a799728da187e22f17f8
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2014 Matthew Harvey * * 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 "repeater_firing_result.hpp" #include <boost/date_time/gregorian/gregorian.hpp> #include <sqloxx/id.hpp> using sqloxx::Id; namespace gregorian = boost::gregorian; namespace dcm { RepeaterFiringResult::RepeaterFiringResult ( Id p_draft_journal_id, gregorian::date const& p_firing_date, bool p_successful ): m_draft_journal_id(p_draft_journal_id), m_firing_date(p_firing_date), m_successful(p_successful) { } Id RepeaterFiringResult::draft_journal_id() const { return m_draft_journal_id; } gregorian::date RepeaterFiringResult::firing_date() const { return m_firing_date; } bool RepeaterFiringResult::successful() const { return m_successful; } void RepeaterFiringResult::mark_as_successful() { m_successful = true; return; } bool operator<(RepeaterFiringResult const& lhs, RepeaterFiringResult const& rhs) { return lhs.firing_date() < rhs.firing_date(); } } // namespace dcm
21.71831
75
0.748379
skybaboon
4c75092335ad9deed6540605874af80c92dc45d4
7,375
cpp
C++
Game/Client/WXCore/Core/TerrainTileOptimized.cpp
hackerlank/SourceCode
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
[ "MIT" ]
4
2021-07-31T13:56:01.000Z
2021-11-13T02:55:10.000Z
Game/Client/WXCore/Core/TerrainTileOptimized.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
null
null
null
Game/Client/WXCore/Core/TerrainTileOptimized.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
7
2021-08-31T14:34:23.000Z
2022-01-19T08:25:58.000Z
#include "TerrainTileOptimized.h" #include "Terrain.h" #include "TerrainTileRenderable.h" #include <OgreSceneManager.h> #include <OgreSceneNode.h> namespace WX { class TerrainTileOptimizedRenderable : public TerrainTileRenderable { public: TerrainTileOptimizedRenderable(TerrainTile *parent) : TerrainTileRenderable(parent) { } ~TerrainTileOptimizedRenderable() { // Only vertex data need to delete delete mRenderOp.vertexData; } }; //----------------------------------------------------------------------- TerrainTileOptimized::TerrainTileOptimized(Ogre::SceneNode* parent, Terrain *owner, int xbase, int zbase, int xsize, int zsize) : TerrainTile(parent, owner, xbase, zbase, xsize, zsize) , mRenderables() , mGeometryOutOfDate(true) { } TerrainTileOptimized::~TerrainTileOptimized() { destoryGeometry(); } //----------------------------------------------------------------------- const String& TerrainTileOptimized::getMovableType(void) const { static const String type = "TerrainTileOptimized"; return type; } void TerrainTileOptimized::_updateRenderQueue(Ogre::RenderQueue* queue) { if (mGeometryOutOfDate) { createGeometry(mOwner->getData(), mXBase, mZBase, mXSize, mZSize); } queueRenderables(queue, mRenderables); } //----------------------------------------------------------------------- void TerrainTileOptimized::destoryGeometry(void) { destroyRenderables(mRenderables); mGeometryOutOfDate = true; } void TerrainTileOptimized::createGeometry(TerrainData* data, int xbase, int zbase, int xsize, int zsize) { destoryGeometry(); // build the material backet map MaterialBucketMap materialBucketMap; buildMaterialBucketMap(materialBucketMap); // statistic number grids for each layer size_t numGridsOfLayer[2] = { 0 }; for (MaterialBucketMap::const_iterator im = materialBucketMap.begin(); im != materialBucketMap.end(); ++im) { numGridsOfLayer[im->second.layerIndex] += im->second.grids.size(); } bool includeLightmap = mOwner->_isLightmapUsed(); // create vertex buffer and lock it Ogre::VertexData vertexDatas[2]; Ogre::HardwareVertexBufferSharedPtr buffers[2]; float* pBuffers[2] = { NULL }; for (size_t layerIndex = 0; layerIndex < 2; ++layerIndex) { if (!numGridsOfLayer[layerIndex]) continue; enum { MAIN_BINDING, }; Ogre::VertexDeclaration* decl = vertexDatas[layerIndex].vertexDeclaration; Ogre::VertexBufferBinding* bind = vertexDatas[layerIndex].vertexBufferBinding; vertexDatas[layerIndex].vertexStart = 0; vertexDatas[layerIndex].vertexCount = numGridsOfLayer[layerIndex] * 4; size_t offset = 0; size_t texCoordSet = 0; // positions decl->addElement(MAIN_BINDING, offset, Ogre::VET_FLOAT3, Ogre::VES_POSITION); offset += 3 * sizeof(float); // normals decl->addElement(MAIN_BINDING, offset, Ogre::VET_FLOAT3, Ogre::VES_NORMAL); offset += 3 * sizeof(float); // texture layer 0 decl->addElement(MAIN_BINDING, offset, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES, texCoordSet++); offset += 2 * sizeof(float); // texture layer 1 if (layerIndex == 1) { decl->addElement(MAIN_BINDING, offset, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES, texCoordSet++); offset += 2 * sizeof(float); } // light-map layer if (includeLightmap) { decl->addElement(MAIN_BINDING, offset, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES, texCoordSet++); offset += 2 * sizeof(float); } buffers[layerIndex] = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer( decl->getVertexSize(MAIN_BINDING), vertexDatas[layerIndex].vertexCount, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY); bind->setBinding(MAIN_BINDING, buffers[layerIndex]); pBuffers[layerIndex] = static_cast<float*>(buffers[layerIndex]->lock(Ogre::HardwareBuffer::HBL_DISCARD)); } Real xscale = 1.0 / xsize; Real zscale = 1.0 / zsize; // build renderables, group by material size_t vertexStarts[2] = { 0 }; for (MaterialBucketMap::const_iterator im = materialBucketMap.begin(); im != materialBucketMap.end(); ++im) { TerrainTileOptimizedRenderable* renderable = new TerrainTileOptimizedRenderable(this); mRenderables.push_back(renderable); const MaterialBucket* mb = &im->second; size_t layerIndex = mb->layerIndex; size_t numQuads = mb->grids.size(); size_t vertexCount = numQuads * 4; renderable->mMaterial = mb->material; // Clone vertex data but shared vertex buffers Ogre::VertexData* vertexData = vertexDatas[layerIndex].clone(false); vertexData->vertexStart = vertexStarts[layerIndex]; vertexData->vertexCount = vertexCount; renderable->mRenderOp.vertexData = vertexData; renderable->mRenderOp.operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST; renderable->mRenderOp.useIndexes = true; renderable->mRenderOp.indexData = mOwner->_getIndexData(numQuads); float* pFloat = pBuffers[layerIndex]; for (GridIdList::const_iterator igrid = mb->grids.begin(); igrid != mb->grids.end(); ++igrid) { size_t grid = *igrid; const TerrainData::GridInfo& gridInfo = data->mGridInfos[grid]; const TerrainData::Corner* corners = gridInfo.getCorners(); int x = grid % data->mXSize; int z = grid / data->mXSize; // NB: Store the quad vertices in clockwise order, index data will // take care with this. for (size_t i = 0; i < 4; ++i) { Ogre::Vector3 v; std::pair<Real, Real> t; TerrainData::Corner corner = corners[i]; // position v = data->_getPosition((x+(corner&1)), (z+(corner>>1))); *pFloat++ = v.x; *pFloat++ = v.y; *pFloat++ = v.z; // normal v = data->_getNormal((x+(corner&1)), (z+(corner>>1))); *pFloat++ = v.x; *pFloat++ = v.y; *pFloat++ = v.z; // layer 0 t = mOwner->_getPixmapCorner(gridInfo.layers[0], corner, gridInfo.flags); *pFloat++ = t.first; *pFloat++ = t.second; // layer 1 if (gridInfo.layers[1].pixmapId) { t = mOwner->_getPixmapCorner(gridInfo.layers[1], corner, gridInfo.flags); *pFloat++ = t.first; *pFloat++ = t.second; } // light-map if (includeLightmap) { *pFloat++ = xscale * (x - xbase + (corner&1)); *pFloat++ = zscale * (z - zbase + (corner>>1)); } } } pBuffers[layerIndex] = pFloat; vertexStarts[layerIndex] += vertexCount; } // unlock vertex buffer for (size_t layerIndex = 0; layerIndex < 2; ++layerIndex) { if (!buffers[layerIndex].isNull()) buffers[layerIndex]->unlock(); } mGeometryOutOfDate = false; } }
33.220721
115
0.599729
hackerlank
4c7c38d24cae81840f1295d3a38f43b657403330
531
cpp
C++
code/tst/utility/array.cpp
shossjer/fimbulwinter
d894e4bddb5d2e6dc31a8112d245c6a1828604e3
[ "0BSD" ]
3
2020-04-29T14:55:58.000Z
2020-08-20T08:43:24.000Z
code/tst/utility/array.cpp
shossjer/fimbulwinter
d894e4bddb5d2e6dc31a8112d245c6a1828604e3
[ "0BSD" ]
1
2022-03-12T11:37:46.000Z
2022-03-12T20:17:38.000Z
code/tst/utility/array.cpp
shossjer/fimbulwinter
d894e4bddb5d2e6dc31a8112d245c6a1828604e3
[ "0BSD" ]
null
null
null
#include "utility/array.hpp" #include <catch2/catch.hpp> #include <array> TEST_CASE( "array_span", "[utility]" ) { auto myarray = std::array<int, 7>{{1, 2, 3, 4, 5, 6, 7}}; auto myarrayspan = utility::make_array_span(myarray); (void)myarrayspan; // fix warning about not being used // auto myhalfspan = make_array_span<3>(myarrayspan.begin() + 2); // iterator_traits: // * access the underlaying type? //auto kjhs = utility::array_span<int, 3>{myarray.begin() + 2}; //(void)kjhs; // fix warning about not being used }
26.55
66
0.677966
shossjer
4c8621d6bb1d223d9f320ca6ca26b110b62eefe1
13,059
cpp
C++
dali/internal/imaging/tizen/native-image-source-impl-tizen.cpp
Coquinho/dali-adaptor
a8006aea66b316a5eb710e634db30f566acda144
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
dali/internal/imaging/tizen/native-image-source-impl-tizen.cpp
Coquinho/dali-adaptor
a8006aea66b316a5eb710e634db30f566acda144
[ "Apache-2.0", "BSD-3-Clause" ]
2
2020-10-19T13:45:40.000Z
2020-12-10T20:21:03.000Z
dali/internal/imaging/tizen/native-image-source-impl-tizen.cpp
expertisesolutions/dali-adaptor
810bf4dea833ea7dfbd2a0c82193bc0b3b155011
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2020 Samsung Electronics 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. * */ // CLASS HEADER #include <dali/internal/imaging/tizen/native-image-source-impl-tizen.h> // EXTERNAL INCLUDES #include <dali/integration-api/debug.h> #include <dali/integration-api/gl-defines.h> #include <cstring> #include <tbm_surface_internal.h> // INTERNAL INCLUDES #include <dali/internal/graphics/common/egl-image-extensions.h> #include <dali/internal/graphics/gles/egl-graphics.h> #include <dali/internal/adaptor/common/adaptor-impl.h> #include <dali/integration-api/adaptor-framework/render-surface-interface.h> namespace Dali { namespace Internal { namespace Adaptor { namespace { const char* FRAGMENT_PREFIX = "#extension GL_OES_EGL_image_external:require\n"; const char* SAMPLER_TYPE = "samplerExternalOES"; tbm_format FORMATS_BLENDING_REQUIRED[] = { TBM_FORMAT_ARGB4444, TBM_FORMAT_ABGR4444, TBM_FORMAT_RGBA4444, TBM_FORMAT_BGRA4444, TBM_FORMAT_RGBX5551, TBM_FORMAT_BGRX5551, TBM_FORMAT_ARGB1555, TBM_FORMAT_ABGR1555, TBM_FORMAT_RGBA5551, TBM_FORMAT_BGRA5551, TBM_FORMAT_ARGB8888, TBM_FORMAT_ABGR8888, TBM_FORMAT_RGBA8888, TBM_FORMAT_BGRA8888, TBM_FORMAT_ARGB2101010, TBM_FORMAT_ABGR2101010, TBM_FORMAT_RGBA1010102, TBM_FORMAT_BGRA1010102 }; const int NUM_FORMATS_BLENDING_REQUIRED = 18; } using Dali::Integration::PixelBuffer; NativeImageSourceTizen* NativeImageSourceTizen::New( uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource ) { NativeImageSourceTizen* image = new NativeImageSourceTizen( width, height, depth, nativeImageSource ); DALI_ASSERT_DEBUG( image && "NativeImageSource allocation failed." ); if( image ) { image->Initialize(); } return image; } NativeImageSourceTizen::NativeImageSourceTizen( uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource ) : mWidth( width ), mHeight( height ), mOwnTbmSurface( false ), mTbmSurface( NULL ), mTbmFormat( 0 ), mBlendingRequired( false ), mColorDepth( depth ), mEglImageKHR( NULL ), mEglGraphics( NULL ), mEglImageExtensions( NULL ), mSetSource( false ), mMutex(), mIsBufferAcquired( false ) { DALI_ASSERT_ALWAYS( Adaptor::IsAvailable() ); GraphicsInterface* graphics = &( Adaptor::GetImplementation( Adaptor::Get() ).GetGraphicsInterface() ); mEglGraphics = static_cast<EglGraphics *>(graphics); mTbmSurface = GetSurfaceFromAny( nativeImageSource ); if( mTbmSurface != NULL ) { tbm_surface_internal_ref( mTbmSurface ); mBlendingRequired = CheckBlending( tbm_surface_get_format( mTbmSurface ) ); mWidth = tbm_surface_get_width( mTbmSurface ); mHeight = tbm_surface_get_height( mTbmSurface ); } } void NativeImageSourceTizen::Initialize() { if( mTbmSurface != NULL || mWidth == 0 || mHeight == 0 ) { return; } tbm_format format = TBM_FORMAT_RGB888; int depth = 0; switch( mColorDepth ) { case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT: { format = TBM_FORMAT_ARGB8888; depth = 32; break; } case Dali::NativeImageSource::COLOR_DEPTH_8: { format = TBM_FORMAT_C8; depth = 8; break; } case Dali::NativeImageSource::COLOR_DEPTH_16: { format = TBM_FORMAT_RGB565; depth = 16; break; } case Dali::NativeImageSource::COLOR_DEPTH_24: { format = TBM_FORMAT_RGB888; depth = 24; break; } case Dali::NativeImageSource::COLOR_DEPTH_32: { format = TBM_FORMAT_ARGB8888; depth = 32; break; } default: { DALI_LOG_WARNING( "Wrong color depth.\n" ); return; } } // set whether blending is required according to pixel format based on the depth /* default pixel format is RGB888 If depth = 8, Pixel::A8; If depth = 16, Pixel::RGB565; If depth = 32, Pixel::RGBA8888 */ mBlendingRequired = ( depth == 32 || depth == 8 ); mTbmSurface = tbm_surface_create( mWidth, mHeight, format ); mOwnTbmSurface = true; } tbm_surface_h NativeImageSourceTizen::GetSurfaceFromAny( Any source ) const { if( source.Empty() ) { return NULL; } if( source.GetType() == typeid( tbm_surface_h ) ) { return AnyCast< tbm_surface_h >( source ); } else { return NULL; } } void NativeImageSourceTizen::DestroySurface() { if( mTbmSurface ) { if( mIsBufferAcquired ) { ReleaseBuffer(); } if( mOwnTbmSurface ) { if( tbm_surface_destroy( mTbmSurface ) != TBM_SURFACE_ERROR_NONE ) { DALI_LOG_ERROR( "Failed to destroy tbm_surface\n" ); } } else { tbm_surface_internal_unref( mTbmSurface ); } } } NativeImageSourceTizen::~NativeImageSourceTizen() { DestroySurface(); } Any NativeImageSourceTizen::GetNativeImageSource() const { return Any( mTbmSurface ); } bool NativeImageSourceTizen::GetPixels(std::vector<unsigned char>& pixbuf, unsigned& width, unsigned& height, Pixel::Format& pixelFormat) const { Dali::Mutex::ScopedLock lock( mMutex ); if( mTbmSurface != NULL ) { tbm_surface_info_s surface_info; if( tbm_surface_map( mTbmSurface, TBM_SURF_OPTION_READ, &surface_info) != TBM_SURFACE_ERROR_NONE ) { DALI_LOG_ERROR( "Fail to map tbm_surface\n" ); width = 0; height = 0; return false; } tbm_format format = surface_info.format; uint32_t stride = surface_info.planes[0].stride; unsigned char* ptr = surface_info.planes[0].ptr; width = mWidth; height = mHeight; size_t lineSize; size_t offset; size_t cOffset; switch( format ) { case TBM_FORMAT_RGB888: { lineSize = width*3; pixelFormat = Pixel::RGB888; pixbuf.resize( lineSize*height ); unsigned char* bufptr = &pixbuf[0]; for( unsigned int r = 0; r < height; ++r, bufptr += lineSize ) { for( unsigned int c = 0; c < width; ++c ) { cOffset = c*3; offset = cOffset + r*stride; *(bufptr+cOffset) = ptr[offset+2]; *(bufptr+cOffset+1) = ptr[offset+1]; *(bufptr+cOffset+2) = ptr[offset]; } } break; } case TBM_FORMAT_RGBA8888: { lineSize = width*4; pixelFormat = Pixel::RGBA8888; pixbuf.resize( lineSize*height ); unsigned char* bufptr = &pixbuf[0]; for( unsigned int r = 0; r < height; ++r, bufptr += lineSize ) { for( unsigned int c = 0; c < width; ++c ) { cOffset = c*4; offset = cOffset + r*stride; *(bufptr+cOffset) = ptr[offset+3]; *(bufptr+cOffset+1) = ptr[offset+2]; *(bufptr+cOffset+2) = ptr[offset+1]; *(bufptr+cOffset+3) = ptr[offset]; } } break; } case TBM_FORMAT_ARGB8888: { lineSize = width*4; pixelFormat = Pixel::RGBA8888; pixbuf.resize( lineSize*height ); unsigned char* bufptr = &pixbuf[0]; for( unsigned int r = 0; r < height; ++r, bufptr += lineSize ) { for( unsigned int c = 0; c < width; ++c ) { cOffset = c*4; offset = cOffset + r*stride; *(bufptr+cOffset) = ptr[offset+2]; *(bufptr+cOffset+1) = ptr[offset+1]; *(bufptr+cOffset+2) = ptr[offset]; *(bufptr+cOffset+3) = ptr[offset+3]; } } break; } default: { DALI_ASSERT_ALWAYS( 0 && "Tbm surface has unsupported pixel format.\n" ); return false; } } if( tbm_surface_unmap( mTbmSurface ) != TBM_SURFACE_ERROR_NONE ) { DALI_LOG_ERROR( "Fail to unmap tbm_surface\n" ); } return true; } DALI_LOG_WARNING( "TBM surface does not exist.\n" ); width = 0; height = 0; return false; } void NativeImageSourceTizen::SetSource( Any source ) { Dali::Mutex::ScopedLock lock( mMutex ); DestroySurface(); mOwnTbmSurface = false; mTbmSurface = GetSurfaceFromAny( source ); if( mTbmSurface != NULL ) { mSetSource = true; tbm_surface_internal_ref( mTbmSurface ); mBlendingRequired = CheckBlending( tbm_surface_get_format( mTbmSurface ) ); mWidth = tbm_surface_get_width( mTbmSurface ); mHeight = tbm_surface_get_height( mTbmSurface ); } } bool NativeImageSourceTizen::IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth ) { uint32_t* formats; uint32_t formatNum; tbm_format format = TBM_FORMAT_RGB888; switch( colorDepth ) { case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT: { format = TBM_FORMAT_ARGB8888; break; } case Dali::NativeImageSource::COLOR_DEPTH_8: { format = TBM_FORMAT_C8; break; } case Dali::NativeImageSource::COLOR_DEPTH_16: { format = TBM_FORMAT_RGB565; break; } case Dali::NativeImageSource::COLOR_DEPTH_24: { format = TBM_FORMAT_RGB888; break; } case Dali::NativeImageSource::COLOR_DEPTH_32: { format = TBM_FORMAT_ARGB8888; break; } } if( tbm_surface_query_formats( &formats, &formatNum ) ) { for( unsigned int i = 0; i < formatNum; i++ ) { if( formats[i] == format ) { free( formats ); return true; } } } free( formats ); return false; } bool NativeImageSourceTizen::CreateResource() { // casting from an unsigned int to a void *, which should then be cast back // to an unsigned int in the driver. EGLClientBuffer eglBuffer = reinterpret_cast< EGLClientBuffer >(mTbmSurface); if( !eglBuffer || !tbm_surface_internal_is_valid( mTbmSurface ) ) { return false; } mEglImageExtensions = mEglGraphics->GetImageExtensions(); DALI_ASSERT_DEBUG( mEglImageExtensions ); mEglImageKHR = mEglImageExtensions->CreateImageKHR( eglBuffer ); return mEglImageKHR != NULL; } void NativeImageSourceTizen::DestroyResource() { Dali::Mutex::ScopedLock lock( mMutex ); if( mEglImageKHR ) { mEglImageExtensions->DestroyImageKHR(mEglImageKHR); mEglImageKHR = NULL; } } uint32_t NativeImageSourceTizen::TargetTexture() { mEglImageExtensions->TargetTextureKHR(mEglImageKHR); return 0; } void NativeImageSourceTizen::PrepareTexture() { Dali::Mutex::ScopedLock lock( mMutex ); if( mSetSource ) { void* eglImage = mEglImageKHR; if( CreateResource() ) { TargetTexture(); } mEglImageExtensions->DestroyImageKHR( eglImage ); mSetSource = false; } } const char* NativeImageSourceTizen::GetCustomFragmentPrefix() const { return FRAGMENT_PREFIX; } const char* NativeImageSourceTizen::GetCustomSamplerTypename() const { return SAMPLER_TYPE; } int NativeImageSourceTizen::GetTextureTarget() const { return GL_TEXTURE_EXTERNAL_OES; } Any NativeImageSourceTizen::GetNativeImageHandle() const { return GetNativeImageSource(); } bool NativeImageSourceTizen::SourceChanged() const { return false; } bool NativeImageSourceTizen::CheckBlending( tbm_format format ) { if( mTbmFormat != format ) { for(int i = 0; i < NUM_FORMATS_BLENDING_REQUIRED; ++i) { if( format == FORMATS_BLENDING_REQUIRED[i] ) { mBlendingRequired = true; break; } } mTbmFormat = format; } return mBlendingRequired; } uint8_t* NativeImageSourceTizen::AcquireBuffer( uint16_t& width, uint16_t& height, uint16_t& stride ) { Dali::Mutex::ScopedLock lock( mMutex ); if( mTbmSurface != NULL ) { tbm_surface_info_s info; if( tbm_surface_map( mTbmSurface, TBM_SURF_OPTION_READ, &info) != TBM_SURFACE_ERROR_NONE ) { DALI_LOG_ERROR( "Fail to map tbm_surface\n" ); width = 0; height = 0; return NULL; } tbm_surface_internal_ref( mTbmSurface ); mIsBufferAcquired = true; stride = info.planes[0].stride; width = mWidth; height = mHeight; return info.planes[0].ptr; } return NULL; } bool NativeImageSourceTizen::ReleaseBuffer() { Dali::Mutex::ScopedLock lock( mMutex ); bool ret = false; if( mTbmSurface != NULL ) { ret = ( tbm_surface_unmap( mTbmSurface ) == TBM_SURFACE_ERROR_NONE ); if( !ret ) { DALI_LOG_ERROR( "Fail to unmap tbm_surface\n" ); } tbm_surface_internal_unref( mTbmSurface ); mIsBufferAcquired = false; } return ret; } } // namespace Adaptor } // namespace internal } // namespace Dali
23.657609
152
0.65832
Coquinho
4c8b57362fcf4c2b8573a0eea0588030b6d23f26
940
hpp
C++
include/Module/Decoder/Turbo/Decoder_turbo_std.hpp
FredrikBlomgren/aff3ct
fa616bd923b2dcf03a4cf119cceca51cf810d483
[ "MIT" ]
315
2016-06-21T13:32:14.000Z
2022-03-28T09:33:59.000Z
include/Module/Decoder/Turbo/Decoder_turbo_std.hpp
a-panella/aff3ct
61509eb756ae3725b8a67c2d26a5af5ba95186fb
[ "MIT" ]
153
2017-01-17T03:51:06.000Z
2022-03-24T15:39:26.000Z
include/Module/Decoder/Turbo/Decoder_turbo_std.hpp
a-panella/aff3ct
61509eb756ae3725b8a67c2d26a5af5ba95186fb
[ "MIT" ]
119
2017-01-04T14:31:58.000Z
2022-03-21T08:34:16.000Z
/*! * \file * \brief Class module::Decoder_turbo_std. */ #ifndef DECODER_TURBO_NAIVE_HPP #define DECODER_TURBO_NAIVE_HPP #include "Module/Interleaver/Interleaver.hpp" #include "Module/Decoder/Decoder_SISO.hpp" #include "Module/Decoder/Turbo/Decoder_turbo.hpp" namespace aff3ct { namespace module { template <typename B = int, typename R = float> class Decoder_turbo_std : public Decoder_turbo<B,R> { public: Decoder_turbo_std(const int& K, const int& N, const int& n_ite, const Decoder_SISO<B,R> &siso_n, const Decoder_SISO<B,R> &siso_i, const Interleaver<R> &pi, const bool buffered_encoding = true); virtual ~Decoder_turbo_std() = default; virtual Decoder_turbo_std<B,R>* clone() const; protected: virtual int _decode_siho(const R *Y_N, B *V_K, const size_t frame_id); }; } } #endif /* DECODER_TURBO_NAIVE_HPP */
25.405405
71
0.667021
FredrikBlomgren
4c8d334444a7d507f32a37789da0a5c4e52b0128
17,762
cpp
C++
export/windows/cpp/obj/src/openfl/_legacy/utils/ArrayBufferView.cpp
TinyPlanetStudios/Project-Crash-Land
365f196be4212602d32251566f26b53fb70693f6
[ "MIT" ]
null
null
null
export/windows/cpp/obj/src/openfl/_legacy/utils/ArrayBufferView.cpp
TinyPlanetStudios/Project-Crash-Land
365f196be4212602d32251566f26b53fb70693f6
[ "MIT" ]
null
null
null
export/windows/cpp/obj/src/openfl/_legacy/utils/ArrayBufferView.cpp
TinyPlanetStudios/Project-Crash-Land
365f196be4212602d32251566f26b53fb70693f6
[ "MIT" ]
null
null
null
// Generated by Haxe 3.3.0 #include <hxcpp.h> #ifndef INCLUDED_Std #include <Std.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_openfl__legacy_utils_ArrayBufferView #include <openfl/_legacy/utils/ArrayBufferView.h> #endif #ifndef INCLUDED_openfl__legacy_utils_ByteArray #include <openfl/_legacy/utils/ByteArray.h> #endif #ifndef INCLUDED_openfl__legacy_utils_IDataInput #include <openfl/_legacy/utils/IDataInput.h> #endif #ifndef INCLUDED_openfl__legacy_utils_IDataOutput #include <openfl/_legacy/utils/IDataOutput.h> #endif #ifndef INCLUDED_openfl__legacy_utils_IMemoryRange #include <openfl/_legacy/utils/IMemoryRange.h> #endif namespace openfl{ namespace _legacy{ namespace utils{ void ArrayBufferView_obj::__construct( ::Dynamic lengthOrBuffer,hx::Null< Int > __o_byteOffset, ::Dynamic length){ Int byteOffset = __o_byteOffset.Default(0); HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","new",0xc608e72f,"openfl._legacy.utils.ArrayBufferView.new","openfl/_legacy/utils/ArrayBufferView.hx",24,0xb2044664) HX_STACK_THIS(this) HX_STACK_ARG(lengthOrBuffer,"lengthOrBuffer") HX_STACK_ARG(byteOffset,"byteOffset") HX_STACK_ARG(length,"length") HXLINE( 26) Bool _hx_tmp = ::Std_obj::is(lengthOrBuffer,hx::ClassOf< ::Int >()); HXDLIN( 26) if (_hx_tmp) { HXLINE( 28) this->byteLength = ::Std_obj::_hx_int(lengthOrBuffer); HXLINE( 29) this->byteOffset = (int)0; HXLINE( 30) Int _hx_tmp1 = ::Std_obj::_hx_int(lengthOrBuffer); HXDLIN( 30) this->buffer = ::openfl::_legacy::utils::ByteArray_obj::__new(_hx_tmp1); } else { HXLINE( 34) this->buffer = lengthOrBuffer; HXLINE( 36) Bool _hx_tmp2 = hx::IsNull( this->buffer ); HXDLIN( 36) if (_hx_tmp2) { HXLINE( 38) HX_STACK_DO_THROW(HX_("Invalid input buffer",3f,39,2d,2c)); } HXLINE( 42) this->byteOffset = byteOffset; HXLINE( 44) if ((byteOffset > this->buffer->length)) { HXLINE( 46) HX_STACK_DO_THROW(HX_("Invalid starting position",80,e7,c8,7a)); } HXLINE( 50) Bool _hx_tmp3 = hx::IsNull( length ); HXDLIN( 50) if (_hx_tmp3) { HXLINE( 52) this->byteLength = (this->buffer->length - byteOffset); } else { HXLINE( 56) this->byteLength = length; HXLINE( 58) if (((this->byteLength + byteOffset) > this->buffer->length)) { HXLINE( 60) HX_STACK_DO_THROW(HX_("Invalid buffer length",fd,68,79,28)); } } } HXLINE( 68) this->buffer->bigEndian = false; HXLINE( 71) this->bytes = this->buffer->b; } Dynamic ArrayBufferView_obj::__CreateEmpty() { return new ArrayBufferView_obj; } hx::ObjectPtr< ArrayBufferView_obj > ArrayBufferView_obj::__new( ::Dynamic lengthOrBuffer,hx::Null< Int > __o_byteOffset, ::Dynamic length) { hx::ObjectPtr< ArrayBufferView_obj > _hx_result = new ArrayBufferView_obj(); _hx_result->__construct(lengthOrBuffer,__o_byteOffset,length); return _hx_result; } Dynamic ArrayBufferView_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< ArrayBufferView_obj > _hx_result = new ArrayBufferView_obj(); _hx_result->__construct(inArgs[0],inArgs[1],inArgs[2]); return _hx_result; } static ::openfl::_legacy::utils::IMemoryRange_obj _hx_openfl__legacy_utils_ArrayBufferView__hx_openfl__legacy_utils_IMemoryRange= { ( ::openfl::_legacy::utils::ByteArray (hx::Object::*)())&::openfl::_legacy::utils::ArrayBufferView_obj::getByteBuffer, ( Int (hx::Object::*)())&::openfl::_legacy::utils::ArrayBufferView_obj::getStart, ( Int (hx::Object::*)())&::openfl::_legacy::utils::ArrayBufferView_obj::getLength, }; void *ArrayBufferView_obj::_hx_getInterface(int inHash) { switch(inHash) { case (int)0x0ecba48c: return &_hx_openfl__legacy_utils_ArrayBufferView__hx_openfl__legacy_utils_IMemoryRange; } #ifdef HXCPP_SCRIPTABLE return super::_hx_getInterface(inHash); #else return 0; #endif } ::openfl::_legacy::utils::ByteArray ArrayBufferView_obj::getByteBuffer(){ HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","getByteBuffer",0x3010f1ed,"openfl._legacy.utils.ArrayBufferView.getByteBuffer","openfl/_legacy/utils/ArrayBufferView.hx",79,0xb2044664) HX_STACK_THIS(this) HXLINE( 79) return this->buffer; } HX_DEFINE_DYNAMIC_FUNC0(ArrayBufferView_obj,getByteBuffer,return ) Float ArrayBufferView_obj::getFloat32(Int position){ HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","getFloat32",0x59ee0856,"openfl._legacy.utils.ArrayBufferView.getFloat32","openfl/_legacy/utils/ArrayBufferView.hx",87,0xb2044664) HX_STACK_THIS(this) HX_STACK_ARG(position,"position") HXLINE( 87) Int _hx_tmp = (position + this->byteOffset); HXDLIN( 87) return ::__hxcpp_memory_get_float(this->bytes,_hx_tmp); } HX_DEFINE_DYNAMIC_FUNC1(ArrayBufferView_obj,getFloat32,return ) Int ArrayBufferView_obj::getInt16(Int position){ HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","getInt16",0x25f27bef,"openfl._legacy.utils.ArrayBufferView.getInt16","openfl/_legacy/utils/ArrayBufferView.hx",99,0xb2044664) HX_STACK_THIS(this) HX_STACK_ARG(position,"position") HXLINE( 99) Int _hx_tmp = (position + this->byteOffset); HXDLIN( 99) return ::__hxcpp_memory_get_i16(this->bytes,_hx_tmp); } HX_DEFINE_DYNAMIC_FUNC1(ArrayBufferView_obj,getInt16,return ) Int ArrayBufferView_obj::getInt32(Int position){ HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","getInt32",0x25f27da9,"openfl._legacy.utils.ArrayBufferView.getInt32","openfl/_legacy/utils/ArrayBufferView.hx",111,0xb2044664) HX_STACK_THIS(this) HX_STACK_ARG(position,"position") HXLINE( 111) Int _hx_tmp = (position + this->byteOffset); HXDLIN( 111) return ::__hxcpp_memory_get_i32(this->bytes,_hx_tmp); } HX_DEFINE_DYNAMIC_FUNC1(ArrayBufferView_obj,getInt32,return ) Int ArrayBufferView_obj::getLength(){ HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","getLength",0x0ee2ba2b,"openfl._legacy.utils.ArrayBufferView.getLength","openfl/_legacy/utils/ArrayBufferView.hx",122,0xb2044664) HX_STACK_THIS(this) HXLINE( 122) return this->byteLength; } HX_DEFINE_DYNAMIC_FUNC0(ArrayBufferView_obj,getLength,return ) ::Dynamic ArrayBufferView_obj::getNativePointer(){ HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","getNativePointer",0xd6cecd41,"openfl._legacy.utils.ArrayBufferView.getNativePointer","openfl/_legacy/utils/ArrayBufferView.hx",130,0xb2044664) HX_STACK_THIS(this) HXLINE( 130) return this->buffer->getNativePointer(); } HX_DEFINE_DYNAMIC_FUNC0(ArrayBufferView_obj,getNativePointer,return ) Int ArrayBufferView_obj::getStart(){ HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","getStart",0xebdd5ebd,"openfl._legacy.utils.ArrayBufferView.getStart","openfl/_legacy/utils/ArrayBufferView.hx",140,0xb2044664) HX_STACK_THIS(this) HXLINE( 140) return this->byteOffset; } HX_DEFINE_DYNAMIC_FUNC0(ArrayBufferView_obj,getStart,return ) Int ArrayBufferView_obj::getUInt8(Int position){ HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","getUInt8",0xf64839d9,"openfl._legacy.utils.ArrayBufferView.getUInt8","openfl/_legacy/utils/ArrayBufferView.hx",148,0xb2044664) HX_STACK_THIS(this) HX_STACK_ARG(position,"position") HXLINE( 148) Int _hx_tmp = (position + this->byteOffset); HXDLIN( 148) return ::__hxcpp_memory_get_byte(this->bytes,_hx_tmp); } HX_DEFINE_DYNAMIC_FUNC1(ArrayBufferView_obj,getUInt8,return ) void ArrayBufferView_obj::setFloat32(Int position,Float value){ HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","setFloat32",0x5d6ba6ca,"openfl._legacy.utils.ArrayBufferView.setFloat32","openfl/_legacy/utils/ArrayBufferView.hx",160,0xb2044664) HX_STACK_THIS(this) HX_STACK_ARG(position,"position") HX_STACK_ARG(value,"value") HXLINE( 160) Int _hx_tmp = (position + this->byteOffset); HXDLIN( 160) ::__hxcpp_memory_set_float(this->bytes,_hx_tmp,value); } HX_DEFINE_DYNAMIC_FUNC2(ArrayBufferView_obj,setFloat32,(void)) void ArrayBufferView_obj::setInt16(Int position,Int value){ HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","setInt16",0xd44fd563,"openfl._legacy.utils.ArrayBufferView.setInt16","openfl/_legacy/utils/ArrayBufferView.hx",172,0xb2044664) HX_STACK_THIS(this) HX_STACK_ARG(position,"position") HX_STACK_ARG(value,"value") HXLINE( 172) Int _hx_tmp = (position + this->byteOffset); HXDLIN( 172) ::__hxcpp_memory_set_i16(this->bytes,_hx_tmp,value); } HX_DEFINE_DYNAMIC_FUNC2(ArrayBufferView_obj,setInt16,(void)) void ArrayBufferView_obj::setInt32(Int position,Int value){ HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","setInt32",0xd44fd71d,"openfl._legacy.utils.ArrayBufferView.setInt32","openfl/_legacy/utils/ArrayBufferView.hx",184,0xb2044664) HX_STACK_THIS(this) HX_STACK_ARG(position,"position") HX_STACK_ARG(value,"value") HXLINE( 184) Int _hx_tmp = (position + this->byteOffset); HXDLIN( 184) ::__hxcpp_memory_set_i32(this->bytes,_hx_tmp,value); } HX_DEFINE_DYNAMIC_FUNC2(ArrayBufferView_obj,setInt32,(void)) void ArrayBufferView_obj::setUInt8(Int position,Int value){ HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","setUInt8",0xa4a5934d,"openfl._legacy.utils.ArrayBufferView.setUInt8","openfl/_legacy/utils/ArrayBufferView.hx",196,0xb2044664) HX_STACK_THIS(this) HX_STACK_ARG(position,"position") HX_STACK_ARG(value,"value") HXLINE( 196) Int _hx_tmp = (position + this->byteOffset); HXDLIN( 196) ::__hxcpp_memory_set_byte(this->bytes,_hx_tmp,value); } HX_DEFINE_DYNAMIC_FUNC2(ArrayBufferView_obj,setUInt8,(void)) ::String ArrayBufferView_obj::invalidDataIndex; ArrayBufferView_obj::ArrayBufferView_obj() { } void ArrayBufferView_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(ArrayBufferView); HX_MARK_MEMBER_NAME(buffer,"buffer"); HX_MARK_MEMBER_NAME(byteOffset,"byteOffset"); HX_MARK_MEMBER_NAME(byteLength,"byteLength"); HX_MARK_MEMBER_NAME(bytes,"bytes"); HX_MARK_END_CLASS(); } void ArrayBufferView_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(buffer,"buffer"); HX_VISIT_MEMBER_NAME(byteOffset,"byteOffset"); HX_VISIT_MEMBER_NAME(byteLength,"byteLength"); HX_VISIT_MEMBER_NAME(bytes,"bytes"); } hx::Val ArrayBufferView_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"bytes") ) { return hx::Val( bytes); } break; case 6: if (HX_FIELD_EQ(inName,"buffer") ) { return hx::Val( buffer); } break; case 8: if (HX_FIELD_EQ(inName,"getInt16") ) { return hx::Val( getInt16_dyn()); } if (HX_FIELD_EQ(inName,"getInt32") ) { return hx::Val( getInt32_dyn()); } if (HX_FIELD_EQ(inName,"getStart") ) { return hx::Val( getStart_dyn()); } if (HX_FIELD_EQ(inName,"getUInt8") ) { return hx::Val( getUInt8_dyn()); } if (HX_FIELD_EQ(inName,"setInt16") ) { return hx::Val( setInt16_dyn()); } if (HX_FIELD_EQ(inName,"setInt32") ) { return hx::Val( setInt32_dyn()); } if (HX_FIELD_EQ(inName,"setUInt8") ) { return hx::Val( setUInt8_dyn()); } break; case 9: if (HX_FIELD_EQ(inName,"getLength") ) { return hx::Val( getLength_dyn()); } break; case 10: if (HX_FIELD_EQ(inName,"byteOffset") ) { return hx::Val( byteOffset); } if (HX_FIELD_EQ(inName,"byteLength") ) { return hx::Val( byteLength); } if (HX_FIELD_EQ(inName,"getFloat32") ) { return hx::Val( getFloat32_dyn()); } if (HX_FIELD_EQ(inName,"setFloat32") ) { return hx::Val( setFloat32_dyn()); } break; case 13: if (HX_FIELD_EQ(inName,"getByteBuffer") ) { return hx::Val( getByteBuffer_dyn()); } break; case 16: if (HX_FIELD_EQ(inName,"getNativePointer") ) { return hx::Val( getNativePointer_dyn()); } } return super::__Field(inName,inCallProp); } bool ArrayBufferView_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp) { switch(inName.length) { case 16: if (HX_FIELD_EQ(inName,"invalidDataIndex") ) { outValue = invalidDataIndex; return true; } } return false; } hx::Val ArrayBufferView_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"bytes") ) { bytes=inValue.Cast< ::Array< unsigned char > >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"buffer") ) { buffer=inValue.Cast< ::openfl::_legacy::utils::ByteArray >(); return inValue; } break; case 10: if (HX_FIELD_EQ(inName,"byteOffset") ) { byteOffset=inValue.Cast< Int >(); return inValue; } if (HX_FIELD_EQ(inName,"byteLength") ) { byteLength=inValue.Cast< Int >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } bool ArrayBufferView_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 16: if (HX_FIELD_EQ(inName,"invalidDataIndex") ) { invalidDataIndex=ioValue.Cast< ::String >(); return true; } } return false; } void ArrayBufferView_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_HCSTRING("buffer","\x00","\xbd","\x94","\xd0")); outFields->push(HX_HCSTRING("byteOffset","\xbb","\x20","\x44","\x38")); outFields->push(HX_HCSTRING("byteLength","\x0e","\x1e","\x0c","\x77")); outFields->push(HX_HCSTRING("bytes","\x6b","\x08","\x98","\xbd")); super::__GetFields(outFields); }; #if HXCPP_SCRIPTABLE static hx::StorageInfo ArrayBufferView_obj_sMemberStorageInfo[] = { {hx::fsObject /*::openfl::_legacy::utils::ByteArray*/ ,(int)offsetof(ArrayBufferView_obj,buffer),HX_HCSTRING("buffer","\x00","\xbd","\x94","\xd0")}, {hx::fsInt,(int)offsetof(ArrayBufferView_obj,byteOffset),HX_HCSTRING("byteOffset","\xbb","\x20","\x44","\x38")}, {hx::fsInt,(int)offsetof(ArrayBufferView_obj,byteLength),HX_HCSTRING("byteLength","\x0e","\x1e","\x0c","\x77")}, {hx::fsObject /*Array< unsigned char >*/ ,(int)offsetof(ArrayBufferView_obj,bytes),HX_HCSTRING("bytes","\x6b","\x08","\x98","\xbd")}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo ArrayBufferView_obj_sStaticStorageInfo[] = { {hx::fsString,(void *) &ArrayBufferView_obj::invalidDataIndex,HX_HCSTRING("invalidDataIndex","\x91","\x8a","\x9d","\x3b")}, { hx::fsUnknown, 0, null()} }; #endif static ::String ArrayBufferView_obj_sMemberFields[] = { HX_HCSTRING("buffer","\x00","\xbd","\x94","\xd0"), HX_HCSTRING("byteOffset","\xbb","\x20","\x44","\x38"), HX_HCSTRING("byteLength","\x0e","\x1e","\x0c","\x77"), HX_HCSTRING("bytes","\x6b","\x08","\x98","\xbd"), HX_HCSTRING("getByteBuffer","\x5e","\xa2","\x0b","\x05"), HX_HCSTRING("getFloat32","\x45","\x17","\x6a","\x39"), HX_HCSTRING("getInt16","\x1e","\xa1","\xf7","\x1d"), HX_HCSTRING("getInt32","\xd8","\xa2","\xf7","\x1d"), HX_HCSTRING("getLength","\x1c","\x1e","\x5e","\x1b"), HX_HCSTRING("getNativePointer","\x70","\x39","\x53","\x7a"), HX_HCSTRING("getStart","\xec","\x83","\xe2","\xe3"), HX_HCSTRING("getUInt8","\x08","\x5f","\x4d","\xee"), HX_HCSTRING("setFloat32","\xb9","\xb5","\xe7","\x3c"), HX_HCSTRING("setInt16","\x92","\xfa","\x54","\xcc"), HX_HCSTRING("setInt32","\x4c","\xfc","\x54","\xcc"), HX_HCSTRING("setUInt8","\x7c","\xb8","\xaa","\x9c"), ::String(null()) }; static void ArrayBufferView_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(ArrayBufferView_obj::__mClass,"__mClass"); HX_MARK_MEMBER_NAME(ArrayBufferView_obj::invalidDataIndex,"invalidDataIndex"); }; #ifdef HXCPP_VISIT_ALLOCS static void ArrayBufferView_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(ArrayBufferView_obj::__mClass,"__mClass"); HX_VISIT_MEMBER_NAME(ArrayBufferView_obj::invalidDataIndex,"invalidDataIndex"); }; #endif hx::Class ArrayBufferView_obj::__mClass; static ::String ArrayBufferView_obj_sStaticFields[] = { HX_HCSTRING("invalidDataIndex","\x91","\x8a","\x9d","\x3b"), ::String(null()) }; void ArrayBufferView_obj::__register() { hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_HCSTRING("openfl._legacy.utils.ArrayBufferView","\xbd","\x23","\x44","\x5c"); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &ArrayBufferView_obj::__GetStatic; __mClass->mSetStaticField = &ArrayBufferView_obj::__SetStatic; __mClass->mMarkFunc = ArrayBufferView_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(ArrayBufferView_obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(ArrayBufferView_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< ArrayBufferView_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = ArrayBufferView_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = ArrayBufferView_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = ArrayBufferView_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } void ArrayBufferView_obj::__boot() { { HX_STACK_FRAME("openfl._legacy.utils.ArrayBufferView","boot",0x79da6283,"openfl._legacy.utils.ArrayBufferView.boot","openfl/_legacy/utils/ArrayBufferView.hx",18,0xb2044664) HXLINE( 18) invalidDataIndex = HX_("Invalid data index",45,2f,02,8f); } } } // end namespace openfl } // end namespace _legacy } // end namespace utils
41.990544
210
0.721371
TinyPlanetStudios
4c8f76cf36d62c885082b9dcf6bfc294222323c3
3,367
cpp
C++
src/brylageo.cpp
KPO-2020-2021/zad5_3-KrystianCyga
e978ed7964bc863771d08a5dce2af491766249b4
[ "Unlicense" ]
null
null
null
src/brylageo.cpp
KPO-2020-2021/zad5_3-KrystianCyga
e978ed7964bc863771d08a5dce2af491766249b4
[ "Unlicense" ]
null
null
null
src/brylageo.cpp
KPO-2020-2021/zad5_3-KrystianCyga
e978ed7964bc863771d08a5dce2af491766249b4
[ "Unlicense" ]
null
null
null
#include "../inc/brylageo.hh" #define FOLDER_WLASCIWY "../BrylyWzorcowe/" #define FOLDER_ROBOCZY "../datasets/" #define WZORZEC_SZESCIAN "../BrylyWzorcowe/szescian.dat" #define WZORZEC_ROTOR "../BrylyWzorcowe/graniastoslup6.dat" #include <fstream> brylageo::brylageo() { skala[0] = 1; skala[1] = 1; skala[2] = 2; } brylageo::brylageo(vector3d polozenie, double kat, const vector3d skala2) { skala = skala2; trans = polozenie; Orientacji_stopnie = kat; } void brylageo::pobierz_nazwe_wzorca(const std::string nazwa1){ NazwaWzorcowego=nazwa1; } void brylageo::pobierz_nazwe_final(const std::string nazwa2){ NazwaWyjsciowego=nazwa2; } void brylageo::skaluj(vector3d &skala2) { skala2[0] *= skala[0]; skala2[1] *= skala[1]; skala2[2] *= skala[2]; } void brylageo::ObrocWzgledemOsiOZ(double kat, vector3d &Polozenie) { vector3d wynik; double rad = kat * M_PI / 180; wynik[0] = Polozenie[0] * cos(rad) - Polozenie[1] * sin(rad); wynik[1] = Polozenie[0] * sin(rad) + Polozenie[1] * cos(rad); Polozenie[0] = wynik[0]; Polozenie[1] = wynik[1]; } void brylageo::TransformujWspolrzednePunktu(vector3d &Polozenie) { vector3d wynik; ObrocWzgledemOsiOZ(Orientacji_stopnie, Polozenie); skaluj(Polozenie); wynik = Polozenie + trans; Polozenie = wynik; } bool brylageo::wczytajbryle() { std::ifstream Plik_BrylaWzorcowa(NazwaWzorcowego); if (!Plik_BrylaWzorcowa.is_open()) { std::cerr << std::endl << " Blad otwarcia do odczytu pliku: " << NazwaWzorcowego << std::endl << std::endl; return false; } vector3d PoTrans; long unsigned int index = 0; wierzcholki.reserve(17); for (unsigned int nrWierz = 0; nrWierz < NumerWierzcholka;++nrWierz) { Plik_BrylaWzorcowa >> PoTrans; TransformujWspolrzednePunktu(PoTrans); ++index; if (wierzcholki.size() < index) wierzcholki.push_back(PoTrans); else wierzcholki[index] = PoTrans; } index = 0; return true; } void brylageo::ustaw_wielkosc(vector3d &tmp){ if (wierzcholki.size() == 0) { wielkosc[0][0] = 1000; wielkosc[0][1] = 1000; } if (tmp[0] < wielkosc[0][0]) wielkosc[0][0] = tmp[0]; if (tmp[0] > wielkosc[1][0]) wielkosc[1][0] = tmp[0]; if (tmp[1] < wielkosc[0][1]) wielkosc[0][1] = tmp[1]; if (tmp[1] > wielkosc[1][1]) wielkosc[1][1] = tmp[1]; } bool brylageo::zapiszbryle() { skala[0] = 1; skala[1] = 1; skala[2] = 1; std::ofstream PLIK(NazwaWyjsciowego); if (!PLIK.is_open()) { std::cerr << std::endl << " Blad otwarcia do odczytu pliku: " << NazwaWyjsciowego << std::endl << std::endl; return false; } vector3d PoTrans; int index = 0; { for (unsigned int nrWierz = 0; nrWierz < NumerWierzcholka; ++nrWierz) { PoTrans = wierzcholki[nrWierz]; TransformujWspolrzednePunktu(PoTrans); ustaw_wielkosc(PoTrans); PLIK << std::fixed << PoTrans << std::endl; ++index; if (index == 4) { index = 0; PLIK << std::endl; } } PLIK << std::endl; } return !PLIK.fail(); }
23.711268
89
0.582418
KPO-2020-2021
4c91fcba34fa734d0b1a3dbd18f4299bc4fd87f4
42,011
hpp
C++
fem/fespace.hpp
Arthur-laurent312/mfem
913361dd0db723d07e9c7492102f8b887acabc48
[ "BSD-3-Clause" ]
null
null
null
fem/fespace.hpp
Arthur-laurent312/mfem
913361dd0db723d07e9c7492102f8b887acabc48
[ "BSD-3-Clause" ]
null
null
null
fem/fespace.hpp
Arthur-laurent312/mfem
913361dd0db723d07e9c7492102f8b887acabc48
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #ifndef MFEM_FESPACE #define MFEM_FESPACE #include "../config/config.hpp" #include "../linalg/sparsemat.hpp" #include "../mesh/mesh.hpp" #include "fe_coll.hpp" #include "restriction.hpp" #include <iostream> #include <unordered_map> namespace mfem { /** @brief The ordering method used when the number of unknowns per mesh node (vector dimension) is bigger than 1. */ class Ordering { public: /// %Ordering methods: enum Type { byNODES, /**< loop first over the nodes (inner loop) then over the vector dimension (outer loop); symbolically it can be represented as: XXX...,YYY...,ZZZ... */ byVDIM /**< loop first over the vector dimension (inner loop) then over the nodes (outer loop); symbolically it can be represented as: XYZ,XYZ,XYZ,... */ }; template <Type Ord> static inline int Map(int ndofs, int vdim, int dof, int vd); template <Type Ord> static void DofsToVDofs(int ndofs, int vdim, Array<int> &dofs); }; template <> inline int Ordering::Map<Ordering::byNODES>(int ndofs, int vdim, int dof, int vd) { MFEM_ASSERT(dof < ndofs && -1-dof < ndofs && 0 <= vd && vd < vdim, ""); return (dof >= 0) ? dof+ndofs*vd : dof-ndofs*vd; } template <> inline int Ordering::Map<Ordering::byVDIM>(int ndofs, int vdim, int dof, int vd) { MFEM_ASSERT(dof < ndofs && -1-dof < ndofs && 0 <= vd && vd < vdim, ""); return (dof >= 0) ? vd+vdim*dof : -1-(vd+vdim*(-1-dof)); } /// Constants describing the possible orderings of the DOFs in one element. enum class ElementDofOrdering { /// Native ordering as defined by the FiniteElement. /** This ordering can be used by tensor-product elements when the interpolation from the DOFs to quadrature points does not use the tensor-product structure. */ NATIVE, /// Lexicographic ordering for tensor-product FiniteElements. /** This ordering can be used only with tensor-product elements. */ LEXICOGRAPHIC }; // Forward declarations class NURBSExtension; class BilinearFormIntegrator; class QuadratureSpace; class QuadratureInterpolator; class FaceQuadratureInterpolator; /** @brief Class FiniteElementSpace - responsible for providing FEM view of the mesh, mainly managing the set of degrees of freedom. */ class FiniteElementSpace { friend class InterpolationGridTransfer; friend class PRefinementTransferOperator; friend void Mesh::Swap(Mesh &, bool); protected: /// The mesh that FE space lives on (not owned). Mesh *mesh; /// Associated FE collection (not owned). const FiniteElementCollection *fec; /// %Vector dimension (number of unknowns per degree of freedom). int vdim; /** Type of ordering of the vector dofs when #vdim > 1. - Ordering::byNODES - first nodes, then vector dimension, - Ordering::byVDIM - first vector dimension, then nodes */ Ordering::Type ordering; /// Number of degrees of freedom. Number of unknowns is #ndofs * #vdim. int ndofs; /** Polynomial order for each element. If empty, all elements are assumed to be of the default order (fec->GetOrder()). */ Array<char> elem_order; int nvdofs, nedofs, nfdofs, nbdofs; int uni_fdof; ///< # of single face DOFs if all faces uniform; -1 otherwise int *bdofs; ///< internal DOFs of elements if mixed/var-order; NULL otherwise /** Variable order spaces only: DOF assignments for edges and faces, see docs in MakeDofTable. For constant order spaces the tables are empty. */ Table var_edge_dofs; Table var_face_dofs; ///< NOTE: also used for spaces with mixed faces /** Additional data for the var_*_dofs tables: individual variant orders (these are basically alternate J arrays for var_edge/face_dofs). */ Array<char> var_edge_orders, var_face_orders; // precalculated DOFs for each element, boundary element, and face mutable Table *elem_dof; // owned (except in NURBS FE space) mutable Table *bdr_elem_dof; // owned (except in NURBS FE space) mutable Table *face_dof; // owned; in var-order space contains variant 0 DOFs Array<int> dof_elem_array, dof_ldof_array; NURBSExtension *NURBSext; int own_ext; mutable Array<int> face_to_be; // NURBS FE space only /** Matrix representing the prolongation from the global conforming dofs to a set of intermediate partially conforming dofs, e.g. the dofs associated with a "cut" space on a non-conforming mesh. */ mutable SparseMatrix *cP; // owned /// Conforming restriction matrix such that cR.cP=I. mutable SparseMatrix *cR; // owned /// A version of the conforming restriction matrix for variable-order spaces. mutable SparseMatrix *cR_hp; // owned mutable bool cP_is_set; /// Transformation to apply to GridFunctions after space Update(). OperatorHandle Th; /// The element restriction operators, see GetElementRestriction(). mutable OperatorHandle L2E_nat, L2E_lex; /// The face restriction operators, see GetFaceRestriction(). using key_face = std::tuple<bool, ElementDofOrdering, FaceType, L2FaceValues>; struct key_hash { std::size_t operator()(const key_face& k) const { return std::get<0>(k) + 2 * (int)std::get<1>(k) + 4 * (int)std::get<2>(k) + 8 * (int)std::get<3>(k); } }; using map_L2F = std::unordered_map<const key_face,Operator*,key_hash>; mutable map_L2F L2F; mutable Array<QuadratureInterpolator*> E2Q_array; mutable Array<FaceQuadratureInterpolator*> E2IFQ_array; mutable Array<FaceQuadratureInterpolator*> E2BFQ_array; /** Update counter, incremented every time the space is constructed/updated. Used by GridFunctions to check if they are up to date with the space. */ long sequence; /** Mesh sequence number last seen when constructing the space. The space needs updating if Mesh::GetSequence() is larger than this. */ long mesh_sequence; /// True if at least one element order changed (variable-order space only). bool orders_changed; bool relaxed_hp; // see SetRelaxedHpConformity() void UpdateNURBS(); void Construct(); void Destroy(); void BuildElementToDofTable() const; void BuildBdrElementToDofTable() const; void BuildFaceToDofTable() const; /** @brief Generates partial face_dof table for a NURBS space. The table is only defined for exterior faces that coincide with a boundary. */ void BuildNURBSFaceToDofTable() const; /// Bit-mask representing a set of orders needed by an edge/face. typedef std::uint64_t VarOrderBits; static constexpr int MaxVarOrder = 8*sizeof(VarOrderBits) - 1; /// Return the minimum order (least significant bit set) in the bit mask. static int MinOrder(VarOrderBits bits); /// Return element order: internal version of GetElementOrder without checks. int GetElementOrderImpl(int i) const; /** In a variable order space, calculate a bitmask of polynomial orders that need to be represented on each edge and face. */ void CalcEdgeFaceVarOrders(Array<VarOrderBits> &edge_orders, Array<VarOrderBits> &face_orders) const; /** Build the table var_edge_dofs (or var_face_dofs) in a variable order space; return total edge/face DOFs. */ int MakeDofTable(int ent_dim, const Array<int> &entity_orders, Table &entity_dofs, Array<char> *var_ent_order); /// Search row of a DOF table for a DOF set of size 'ndof', return first DOF. int FindDofs(const Table &var_dof_table, int row, int ndof) const; /** In a variable order space, return edge DOFs associated with a polynomial order that has 'ndof' degrees of freedom. */ int FindEdgeDof(int edge, int ndof) const { return FindDofs(var_edge_dofs, edge, ndof); } /// Similar to FindEdgeDof, but used for mixed meshes too. int FindFaceDof(int face, int ndof) const { return FindDofs(var_face_dofs, face, ndof); } int FirstFaceDof(int face, int variant = 0) const { return uni_fdof >= 0 ? face*uni_fdof : var_face_dofs.GetRow(face)[variant];} /// Return number of possible DOF variants for edge/face (var. order spaces). int GetNVariants(int entity, int index) const; /// Helper to encode a sign flip into a DOF index (for Hcurl/Hdiv shapes). static inline int EncodeDof(int entity_base, int idx) { return (idx >= 0) ? (entity_base + idx) : (-1-(entity_base + (-1-idx))); } /// Helpers to remove encoded sign from a DOF static inline int DecodeDof(int dof) { return (dof >= 0) ? dof : (-1 - dof); } static inline int DecodeDof(int dof, double& sign) { return (dof >= 0) ? (sign = 1, dof) : (sign = -1, (-1 - dof)); } /// Helper to get vertex, edge or face DOFs (entity=0,1,2 resp.). int GetEntityDofs(int entity, int index, Array<int> &dofs, Geometry::Type master_geom = Geometry::INVALID, int variant = 0) const; // Get degenerate face DOFs: see explanation in method implementation. int GetDegenerateFaceDofs(int index, Array<int> &dofs, Geometry::Type master_geom, int variant) const; int GetNumBorderDofs(Geometry::Type geom, int order) const; /// Calculate the cP and cR matrices for a nonconforming mesh. void BuildConformingInterpolation() const; static void AddDependencies(SparseMatrix& deps, Array<int>& master_dofs, Array<int>& slave_dofs, DenseMatrix& I, int skipfirst = 0); static bool DofFinalizable(int dof, const Array<bool>& finalized, const SparseMatrix& deps); void AddEdgeFaceDependencies(SparseMatrix &deps, Array<int>& master_dofs, const FiniteElement *master_fe, Array<int> &slave_dofs, int slave_face, const DenseMatrix *pm) const; /// Replicate 'mat' in the vector dimension, according to vdim ordering mode. void MakeVDimMatrix(SparseMatrix &mat) const; /// GridFunction interpolation operator applicable after mesh refinement. class RefinementOperator : public Operator { const FiniteElementSpace* fespace; DenseTensor localP[Geometry::NumGeom]; Table* old_elem_dof; // Owned. public: /** Construct the operator based on the elem_dof table of the original (coarse) space. The class takes ownership of the table. */ RefinementOperator(const FiniteElementSpace* fespace, Table *old_elem_dof/*takes ownership*/, int old_ndofs); RefinementOperator(const FiniteElementSpace *fespace, const FiniteElementSpace *coarse_fes); virtual void Mult(const Vector &x, Vector &y) const; virtual void MultTranspose(const Vector &x, Vector &y) const; virtual ~RefinementOperator(); }; /// Derefinement operator, used by the friend class InterpolationGridTransfer. class DerefinementOperator : public Operator { const FiniteElementSpace *fine_fes; // Not owned. DenseTensor localR[Geometry::NumGeom]; Table *coarse_elem_dof; // Owned. Table coarse_to_fine; Array<int> coarse_to_ref_type; Array<Geometry::Type> ref_type_to_geom; Array<int> ref_type_to_fine_elem_offset; public: DerefinementOperator(const FiniteElementSpace *f_fes, const FiniteElementSpace *c_fes, BilinearFormIntegrator *mass_integ); virtual void Mult(const Vector &x, Vector &y) const; virtual ~DerefinementOperator(); }; /** This method makes the same assumptions as the method: void GetLocalRefinementMatrices( const FiniteElementSpace &coarse_fes, Geometry::Type geom, DenseTensor &localP) const which is defined below. It also assumes that the coarse fes and this have the same vector dimension, vdim. */ SparseMatrix *RefinementMatrix_main(const int coarse_ndofs, const Table &coarse_elem_dof, const DenseTensor localP[]) const; void GetLocalRefinementMatrices(Geometry::Type geom, DenseTensor &localP) const; void GetLocalDerefinementMatrices(Geometry::Type geom, DenseTensor &localR) const; /** Calculate explicit GridFunction interpolation matrix (after mesh refinement). NOTE: consider using the RefinementOperator class instead of the fully assembled matrix, which can take a lot of memory. */ SparseMatrix* RefinementMatrix(int old_ndofs, const Table* old_elem_dof); /// Calculate GridFunction restriction matrix after mesh derefinement. SparseMatrix* DerefinementMatrix(int old_ndofs, const Table* old_elem_dof); /** @brief Return in @a localP the local refinement matrices that map between fespaces after mesh refinement. */ /** This method assumes that this->mesh is a refinement of coarse_fes->mesh and that the CoarseFineTransformations of this->mesh are set accordingly. Another assumption is that the FEs of this use the same MapType as the FEs of coarse_fes. Finally, it assumes that the spaces this and coarse_fes are NOT variable-order spaces. */ void GetLocalRefinementMatrices(const FiniteElementSpace &coarse_fes, Geometry::Type geom, DenseTensor &localP) const; /// Help function for constructors + Load(). void Constructor(Mesh *mesh, NURBSExtension *ext, const FiniteElementCollection *fec, int vdim = 1, int ordering = Ordering::byNODES); /// Updates the internal mesh pointer. @warning @a new_mesh must be /// <b>topologically identical</b> to the existing mesh. Used if the address /// of the Mesh object has changed, e.g. in @a Mesh::Swap. virtual void UpdateMeshPointer(Mesh *new_mesh); /// Resize the elem_order array on mesh change. void UpdateElementOrders(); public: /** @brief Default constructor: the object is invalid until initialized using the method Load(). */ FiniteElementSpace(); /** @brief Copy constructor: deep copy all data from @a orig except the Mesh, the FiniteElementCollection, ans some derived data. */ /** If the @a mesh or @a fec pointers are NULL (default), then the new FiniteElementSpace will reuse the respective pointers from @a orig. If any of these pointers is not NULL, the given pointer will be used instead of the one used by @a orig. @note The objects pointed to by the @a mesh and @a fec parameters must be either the same objects as the ones used by @a orig, or copies of them. Otherwise, the behavior is undefined. @note Derived data objects, such as the conforming prolongation and restriction matrices, and the update operator, will not be copied, even if they are created in the @a orig object. */ FiniteElementSpace(const FiniteElementSpace &orig, Mesh *mesh = NULL, const FiniteElementCollection *fec = NULL); FiniteElementSpace(Mesh *mesh, const FiniteElementCollection *fec, int vdim = 1, int ordering = Ordering::byNODES) { Constructor(mesh, NULL, fec, vdim, ordering); } /// Construct a NURBS FE space based on the given NURBSExtension, @a ext. /** @note If the pointer @a ext is NULL, this constructor is equivalent to the standard constructor with the same arguments minus the NURBSExtension, @a ext. */ FiniteElementSpace(Mesh *mesh, NURBSExtension *ext, const FiniteElementCollection *fec, int vdim = 1, int ordering = Ordering::byNODES) { Constructor(mesh, ext, fec, vdim, ordering); } /// Returns the mesh inline Mesh *GetMesh() const { return mesh; } const NURBSExtension *GetNURBSext() const { return NURBSext; } NURBSExtension *GetNURBSext() { return NURBSext; } NURBSExtension *StealNURBSext(); bool Conforming() const { return mesh->Conforming(); } bool Nonconforming() const { return mesh->Nonconforming(); } /// Sets the order of the i'th finite element. /** By default, all elements are assumed to be of fec->GetOrder(). Once SetElementOrder is called, the space becomes a variable order space. */ void SetElementOrder(int i, int p); /// Returns the order of the i'th finite element. int GetElementOrder(int i) const; /// Return the maximum polynomial order. int GetMaxElementOrder() const { return IsVariableOrder() ? elem_order.Max() : fec->GetOrder(); } /// Returns true if the space contains elements of varying polynomial orders. bool IsVariableOrder() const { return elem_order.Size(); } /// The returned SparseMatrix is owned by the FiniteElementSpace. const SparseMatrix *GetConformingProlongation() const; /// The returned SparseMatrix is owned by the FiniteElementSpace. const SparseMatrix *GetConformingRestriction() const; /** Return a version of the conforming restriction matrix for variable-order spaces with complex hp interfaces, where some true DOFs are not owned by any elements and need to be interpolated from higher order edge/face variants (see also @a SetRelaxedHpConformity()). */ /// The returned SparseMatrix is owned by the FiniteElementSpace. const SparseMatrix *GetHpConformingRestriction() const; /// The returned Operator is owned by the FiniteElementSpace. virtual const Operator *GetProlongationMatrix() const { return GetConformingProlongation(); } /// Return an operator that performs the transpose of GetRestrictionOperator /** The returned operator is owned by the FiniteElementSpace. In serial this is the same as GetProlongationMatrix() */ virtual const Operator *GetRestrictionTransposeOperator() const { return GetConformingProlongation(); } /// An abstract operator that performs the same action as GetRestrictionMatrix /** In some cases this is an optimized matrix-free implementation. The returned operator is owned by the FiniteElementSpace. */ virtual const Operator *GetRestrictionOperator() const { return GetConformingRestriction(); } /// The returned SparseMatrix is owned by the FiniteElementSpace. virtual const SparseMatrix *GetRestrictionMatrix() const { return GetConformingRestriction(); } /// The returned SparseMatrix is owned by the FiniteElementSpace. virtual const SparseMatrix *GetHpRestrictionMatrix() const { return GetHpConformingRestriction(); } /// Return an Operator that converts L-vectors to E-vectors. /** An L-vector is a vector of size GetVSize() which is the same size as a GridFunction. An E-vector represents the element-wise discontinuous version of the FE space. The layout of the E-vector is: ND x VDIM x NE, where ND is the number of degrees of freedom, VDIM is the vector dimension of the FE space, and NE is the number of the mesh elements. The parameter @a e_ordering describes how the local DOFs in each element should be ordered, see ElementDofOrdering. For discontinuous spaces, the element restriction corresponds to a permutation of the degrees of freedom, implemented by the L2ElementRestriction class. The returned Operator is owned by the FiniteElementSpace. */ const Operator *GetElementRestriction(ElementDofOrdering e_ordering) const; /// Return an Operator that converts L-vectors to E-vectors on each face. virtual const Operator *GetFaceRestriction( ElementDofOrdering e_ordering, FaceType, L2FaceValues mul = L2FaceValues::DoubleValued) const; /** @brief Return a QuadratureInterpolator that interpolates E-vectors to quadrature point values and/or derivatives (Q-vectors). */ /** An E-vector represents the element-wise discontinuous version of the FE space and can be obtained, for example, from a GridFunction using the Operator returned by GetElementRestriction(). All elements will use the same IntegrationRule, @a ir as the target quadrature points. */ const QuadratureInterpolator *GetQuadratureInterpolator( const IntegrationRule &ir) const; /** @brief Return a QuadratureInterpolator that interpolates E-vectors to quadrature point values and/or derivatives (Q-vectors). */ /** An E-vector represents the element-wise discontinuous version of the FE space and can be obtained, for example, from a GridFunction using the Operator returned by GetElementRestriction(). The target quadrature points in the elements are described by the given QuadratureSpace, @a qs. */ const QuadratureInterpolator *GetQuadratureInterpolator( const QuadratureSpace &qs) const; /** @brief Return a FaceQuadratureInterpolator that interpolates E-vectors to quadrature point values and/or derivatives (Q-vectors). */ const FaceQuadratureInterpolator *GetFaceQuadratureInterpolator( const IntegrationRule &ir, FaceType type) const; /// Returns the polynomial degree of the i'th finite element. /** NOTE: it is recommended to use GetElementOrder in new code. */ int GetOrder(int i) const { return GetElementOrder(i); } /** Return the order of an edge. In a variable order space, return the order of a specific variant, or -1 if there are no more variants. */ int GetEdgeOrder(int edge, int variant = 0) const; /// Returns the polynomial degree of the i'th face finite element int GetFaceOrder(int face, int variant = 0) const; /// Returns vector dimension. inline int GetVDim() const { return vdim; } /// Returns number of degrees of freedom. inline int GetNDofs() const { return ndofs; } /// Return the number of vector dofs, i.e. GetNDofs() x GetVDim(). inline int GetVSize() const { return vdim * ndofs; } /// Return the number of vector true (conforming) dofs. virtual int GetTrueVSize() const { return GetConformingVSize(); } /// Returns the number of conforming ("true") degrees of freedom /// (if the space is on a nonconforming mesh with hanging nodes). int GetNConformingDofs() const; int GetConformingVSize() const { return vdim * GetNConformingDofs(); } /// Return the ordering method. inline Ordering::Type GetOrdering() const { return ordering; } const FiniteElementCollection *FEColl() const { return fec; } /// Number of all scalar vertex dofs int GetNVDofs() const { return nvdofs; } /// Number of all scalar edge-interior dofs int GetNEDofs() const { return nedofs; } /// Number of all scalar face-interior dofs int GetNFDofs() const { return nfdofs; } /// Returns number of vertices in the mesh. inline int GetNV() const { return mesh->GetNV(); } /// Returns number of elements in the mesh. inline int GetNE() const { return mesh->GetNE(); } /// Returns number of faces (i.e. co-dimension 1 entities) in the mesh. /** The co-dimension 1 entities are those that have dimension 1 less than the mesh dimension, e.g. for a 2D mesh, the faces are the 1D entities, i.e. the edges. */ inline int GetNF() const { return mesh->GetNumFaces(); } /// Returns number of boundary elements in the mesh. inline int GetNBE() const { return mesh->GetNBE(); } /// Returns the number of faces according to the requested type. /** If type==Boundary returns only the "true" number of boundary faces contrary to GetNBE() that returns "fake" boundary faces associated to visualization for GLVis. Similarly, if type==Interior, the "fake" boundary faces associated to visualization are counted as interior faces. */ inline int GetNFbyType(FaceType type) const { return mesh->GetNFbyType(type); } /// Returns the type of element i. inline int GetElementType(int i) const { return mesh->GetElementType(i); } /// Returns the vertices of element i. inline void GetElementVertices(int i, Array<int> &vertices) const { mesh->GetElementVertices(i, vertices); } /// Returns the type of boundary element i. inline int GetBdrElementType(int i) const { return mesh->GetBdrElementType(i); } /// Returns ElementTransformation for the @a i-th element. ElementTransformation *GetElementTransformation(int i) const { return mesh->GetElementTransformation(i); } /** @brief Returns the transformation defining the @a i-th element in the user-defined variable @a ElTr. */ void GetElementTransformation(int i, IsoparametricTransformation *ElTr) { mesh->GetElementTransformation(i, ElTr); } /// Returns ElementTransformation for the @a i-th boundary element. ElementTransformation *GetBdrElementTransformation(int i) const { return mesh->GetBdrElementTransformation(i); } int GetAttribute(int i) const { return mesh->GetAttribute(i); } int GetBdrAttribute(int i) const { return mesh->GetBdrAttribute(i); } /// Returns indices of degrees of freedom of element 'elem'. virtual void GetElementDofs(int elem, Array<int> &dofs) const; /// Returns indices of degrees of freedom for boundary element 'bel'. virtual void GetBdrElementDofs(int bel, Array<int> &dofs) const; /** @brief Returns the indices of the degrees of freedom for the specified face, including the DOFs for the edges and the vertices of the face. */ /** In variable order spaces, multiple variants of DOFs can be returned. See @a GetEdgeDofs for more details. @return Order of the selected variant, or -1 if there are no more variants.*/ virtual int GetFaceDofs(int face, Array<int> &dofs, int variant = 0) const; /** @brief Returns the indices of the degrees of freedom for the specified edge, including the DOFs for the vertices of the edge. */ /** In variable order spaces, multiple sets of DOFs may exist on an edge, corresponding to the different polynomial orders of incident elements. The 'variant' parameter is the zero-based index of the desired DOF set. The variants are ordered from lowest polynomial degree to the highest. @return Order of the selected variant, or -1 if there are no more variants. */ int GetEdgeDofs(int edge, Array<int> &dofs, int variant = 0) const; void GetVertexDofs(int i, Array<int> &dofs) const; void GetElementInteriorDofs(int i, Array<int> &dofs) const; void GetFaceInteriorDofs(int i, Array<int> &dofs) const; int GetNumElementInteriorDofs(int i) const; void GetEdgeInteriorDofs(int i, Array<int> &dofs) const; void DofsToVDofs(Array<int> &dofs, int ndofs = -1) const; void DofsToVDofs(int vd, Array<int> &dofs, int ndofs = -1) const; int DofToVDof(int dof, int vd, int ndofs = -1) const; int VDofToDof(int vdof) const { return (ordering == Ordering::byNODES) ? (vdof%ndofs) : (vdof/vdim); } static void AdjustVDofs(Array<int> &vdofs); /// Returns indexes of degrees of freedom in array dofs for i'th element. void GetElementVDofs(int i, Array<int> &vdofs) const; /// Returns indexes of degrees of freedom for i'th boundary element. void GetBdrElementVDofs(int i, Array<int> &vdofs) const; /// Returns indexes of degrees of freedom for i'th face element (2D and 3D). void GetFaceVDofs(int i, Array<int> &vdofs) const; /// Returns indexes of degrees of freedom for i'th edge. void GetEdgeVDofs(int i, Array<int> &vdofs) const; void GetVertexVDofs(int i, Array<int> &vdofs) const; void GetElementInteriorVDofs(int i, Array<int> &vdofs) const; void GetEdgeInteriorVDofs(int i, Array<int> &vdofs) const; /// (@deprecated) Use the Update() method if the space or mesh changed. MFEM_DEPRECATED void RebuildElementToDofTable(); /** @brief Reorder the scalar DOFs based on the element ordering. The new ordering is constructed as follows: 1) loop over all elements as ordered in the Mesh; 2) for each element, assign new indices to all of its current DOFs that are still unassigned; the new indices we assign are simply the sequence `0,1,2,...`; if there are any signed DOFs their sign is preserved. */ void ReorderElementToDofTable(); /** @brief Return a reference to the internal Table that stores the lists of scalar dofs, for each mesh element, as returned by GetElementDofs(). */ const Table &GetElementToDofTable() const { return *elem_dof; } /** @brief Return a reference to the internal Table that stores the lists of scalar dofs, for each boundary mesh element, as returned by GetBdrElementDofs(). */ const Table &GetBdrElementToDofTable() const { if (!bdr_elem_dof) { BuildBdrElementToDofTable(); } return *bdr_elem_dof; } /** @brief Return a reference to the internal Table that stores the lists of scalar dofs, for each face in the mesh, as returned by GetFaceDofs(). In this context, "face" refers to a (dim-1)-dimensional mesh entity. */ /** @note In the case of a NURBS space, the rows corresponding to interior faces will be empty. */ const Table &GetFaceToDofTable() const { if (!face_dof) { BuildFaceToDofTable(); } return *face_dof; } /** @brief Initialize internal data that enables the use of the methods GetElementForDof() and GetLocalDofForDof(). */ void BuildDofToArrays(); /// Return the index of the first element that contains dof @a i. /** This method can be called only after setup is performed using the method BuildDofToArrays(). */ int GetElementForDof(int i) const { return dof_elem_array[i]; } /// Return the local dof index in the first element that contains dof @a i. /** This method can be called only after setup is performed using the method BuildDofToArrays(). */ int GetLocalDofForDof(int i) const { return dof_ldof_array[i]; } /** @brief Returns pointer to the FiniteElement in the FiniteElementCollection associated with i'th element in the mesh object. */ virtual const FiniteElement *GetFE(int i) const; /** @brief Returns pointer to the FiniteElement in the FiniteElementCollection associated with i'th boundary face in the mesh object. */ const FiniteElement *GetBE(int i) const; /** @brief Returns pointer to the FiniteElement in the FiniteElementCollection associated with i'th face in the mesh object. Faces in this case refer to the MESHDIM-1 primitive so in 2D they are segments and in 1D they are points.*/ const FiniteElement *GetFaceElement(int i) const; /** @brief Returns pointer to the FiniteElement in the FiniteElementCollection associated with i'th edge in the mesh object. */ const FiniteElement *GetEdgeElement(int i, int variant = 0) const; /// Return the trace element from element 'i' to the given 'geom_type' const FiniteElement *GetTraceElement(int i, Geometry::Type geom_type) const; /** @brief Mark degrees of freedom associated with boundary elements with the specified boundary attributes (marked in 'bdr_attr_is_ess'). For spaces with 'vdim' > 1, the 'component' parameter can be used to restricts the marked vDOFs to the specified component. */ virtual void GetEssentialVDofs(const Array<int> &bdr_attr_is_ess, Array<int> &ess_vdofs, int component = -1) const; /** @brief Get a list of essential true dofs, ess_tdof_list, corresponding to the boundary attributes marked in the array bdr_attr_is_ess. For spaces with 'vdim' > 1, the 'component' parameter can be used to restricts the marked tDOFs to the specified component. */ virtual void GetEssentialTrueDofs(const Array<int> &bdr_attr_is_ess, Array<int> &ess_tdof_list, int component = -1); /** @brief Get a list of all boundary true dofs, @a boundary_dofs. For spaces with 'vdim' > 1, the 'component' parameter can be used to restricts the marked tDOFs to the specified component. Equivalent to FiniteElementSpace::GetEssentialTrueDofs with all boundary attributes marked as essential. */ void GetBoundaryTrueDofs(Array<int> &boundary_dofs, int component = -1); /// Convert a Boolean marker array to a list containing all marked indices. static void MarkerToList(const Array<int> &marker, Array<int> &list); /** @brief Convert an array of indices (list) to a Boolean marker array where all indices in the list are marked with the given value and the rest are set to zero. */ static void ListToMarker(const Array<int> &list, int marker_size, Array<int> &marker, int mark_val = -1); /** @brief For a partially conforming FE space, convert a marker array (nonzero entries are true) on the partially conforming dofs to a marker array on the conforming dofs. A conforming dofs is marked iff at least one of its dependent dofs is marked. */ void ConvertToConformingVDofs(const Array<int> &dofs, Array<int> &cdofs); /** @brief For a partially conforming FE space, convert a marker array (nonzero entries are true) on the conforming dofs to a marker array on the (partially conforming) dofs. A dof is marked iff it depends on a marked conforming dofs, where dependency is defined by the ConformingRestriction matrix; in other words, a dof is marked iff it corresponds to a marked conforming dof. */ void ConvertFromConformingVDofs(const Array<int> &cdofs, Array<int> &dofs); /** @brief Generate the global restriction matrix from a discontinuous FE space to the continuous FE space of the same polynomial degree. */ SparseMatrix *D2C_GlobalRestrictionMatrix(FiniteElementSpace *cfes); /** @brief Generate the global restriction matrix from a discontinuous FE space to the piecewise constant FE space. */ SparseMatrix *D2Const_GlobalRestrictionMatrix(FiniteElementSpace *cfes); /** @brief Construct the restriction matrix from the FE space given by (*this) to the lower degree FE space given by (*lfes) which is defined on the same mesh. */ SparseMatrix *H2L_GlobalRestrictionMatrix(FiniteElementSpace *lfes); /** @brief Construct and return an Operator that can be used to transfer GridFunction data from @a coarse_fes, defined on a coarse mesh, to @a this FE space, defined on a refined mesh. */ /** It is assumed that the mesh of this FE space is a refinement of the mesh of @a coarse_fes and the CoarseFineTransformations returned by the method Mesh::GetRefinementTransforms() of the refined mesh are set accordingly. The Operator::Type of @a T can be set to request an Operator of the set type. Currently, only Operator::MFEM_SPARSEMAT and Operator::ANY_TYPE (matrix-free) are supported. When Operator::ANY_TYPE is requested, the choice of the particular Operator sub-class is left to the method. This method also works in parallel because the transfer operator is local to the MPI task when the input is a synchronized ParGridFunction. */ void GetTransferOperator(const FiniteElementSpace &coarse_fes, OperatorHandle &T) const; /** @brief Construct and return an Operator that can be used to transfer true-dof data from @a coarse_fes, defined on a coarse mesh, to @a this FE space, defined on a refined mesh. This method calls GetTransferOperator() and multiplies the result by the prolongation operator of @a coarse_fes on the right, and by the restriction operator of this FE space on the left. The Operator::Type of @a T can be set to request an Operator of the set type. In serial, the supported types are: Operator::MFEM_SPARSEMAT and Operator::ANY_TYPE (matrix-free). In parallel, the supported types are: Operator::Hypre_ParCSR and Operator::ANY_TYPE. Any other type is treated as Operator::ANY_TYPE: the operator representation choice is made by this method. */ virtual void GetTrueTransferOperator(const FiniteElementSpace &coarse_fes, OperatorHandle &T) const; /** @brief Reflect changes in the mesh: update number of DOFs, etc. Also, calculate GridFunction transformation operator (unless want_transform is false). Safe to call multiple times, does nothing if space already up to date. */ virtual void Update(bool want_transform = true); /// Get the GridFunction update operator. const Operator* GetUpdateOperator() { Update(); return Th.Ptr(); } /// Return the update operator in the given OperatorHandle, @a T. void GetUpdateOperator(OperatorHandle &T) { T = Th; } /** @brief Set the ownership of the update operator: if set to false, the Operator returned by GetUpdateOperator() must be deleted outside the FiniteElementSpace. */ /** The update operator ownership is automatically reset to true when a new update operator is created by the Update() method. */ void SetUpdateOperatorOwner(bool own) { Th.SetOperatorOwner(own); } /// Specify the Operator::Type to be used by the update operators. /** The default type is Operator::ANY_TYPE which leaves the choice to this class. The other currently supported option is Operator::MFEM_SPARSEMAT which is only guaranteed to be honored for a refinement update operator. Any other type will be treated as Operator::ANY_TYPE. @note This operation destroys the current update operator (if owned). */ void SetUpdateOperatorType(Operator::Type tid) { Th.SetType(tid); } /// Free the GridFunction update operator (if any), to save memory. virtual void UpdatesFinished() { Th.Clear(); } /** Return update counter, similar to Mesh::GetSequence(). Used by GridFunction to check if it is up to date with the space. */ long GetSequence() const { return sequence; } /// Return whether or not the space is discontinuous (L2) bool IsDGSpace() const { return dynamic_cast<const L2_FECollection*>(fec) != NULL; } /** In variable order spaces on nonconforming (NC) meshes, this function controls whether strict conformity is enforced in cases where coarse edges/faces have higher polynomial order than their fine NC neighbors. In the default (strict) case, the coarse side polynomial order is reduced to that of the lowest order fine edge/face, so all fine neighbors can interpolate the coarse side exactly. If relaxed == true, some discontinuities in the solution in such cases are allowed and the coarse side is not restricted. For an example, see https://github.com/mfem/mfem/pull/1423#issuecomment-621340392 */ void SetRelaxedHpConformity(bool relaxed = true) { relaxed_hp = relaxed; orders_changed = true; // force update Update(false); } /// Save finite element space to output stream @a out. void Save(std::ostream &out) const; /** @brief Read a FiniteElementSpace from a stream. The returned FiniteElementCollection is owned by the caller. */ FiniteElementCollection *Load(Mesh *m, std::istream &input); virtual ~FiniteElementSpace(); }; /// Class representing the storage layout of a QuadratureFunction. /** Multiple QuadratureFunction%s can share the same QuadratureSpace. */ class QuadratureSpace { protected: friend class QuadratureFunction; // Uses the element_offsets. Mesh *mesh; int order; int size; const IntegrationRule *int_rule[Geometry::NumGeom]; int *element_offsets; // scalar offsets; size = number of elements + 1 // protected functions // Assuming mesh and order are set, construct the members: int_rule, // element_offsets, and size. void Construct(); public: /// Create a QuadratureSpace based on the global rules from #IntRules. QuadratureSpace(Mesh *mesh_, int order_) : mesh(mesh_), order(order_) { Construct(); } /// Read a QuadratureSpace from the stream @a in. QuadratureSpace(Mesh *mesh_, std::istream &in); virtual ~QuadratureSpace() { delete [] element_offsets; } /// Return the total number of quadrature points. int GetSize() const { return size; } /// Return the order of the quadrature rule(s) used by all elements. int GetOrder() const { return order; } /// Returns the mesh inline Mesh *GetMesh() const { return mesh; } /// Returns number of elements in the mesh. inline int GetNE() const { return mesh->GetNE(); } /// Get the IntegrationRule associated with mesh element @a idx. const IntegrationRule &GetElementIntRule(int idx) const { return *int_rule[mesh->GetElementBaseGeometry(idx)]; } /// Write the QuadratureSpace to the stream @a out. void Save(std::ostream &out) const; }; inline bool UsesTensorBasis(const FiniteElementSpace& fes) { return dynamic_cast<const mfem::TensorBasisElement *>(fes.GetFE(0))!=nullptr; } } #endif
44.268704
86
0.696627
Arthur-laurent312
4c94a7815ce8cc4d812f29577d9773c5fb983e8f
2,454
cpp
C++
Leetcode Top Interview Questions/solutions/Intersection of Two Linked Lists.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
5
2021-08-10T18:47:49.000Z
2021-08-21T15:42:58.000Z
Leetcode Top Interview Questions/solutions/Intersection of Two Linked Lists.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
2
2022-02-25T13:36:46.000Z
2022-02-25T14:06:44.000Z
Leetcode Top Interview Questions/solutions/Intersection of Two Linked Lists.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
1
2021-08-11T06:36:42.000Z
2021-08-11T06:36:42.000Z
/* Intersection of Two Linked Lists =============================== Write a program to find the node at which the intersection of two singly linked lists begins. Example 1: Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 Output: Reference of the node with value = 8 Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. Example 2: Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 Output: Reference of the node with value = 2 Input Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. Example 3: Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 Output: null Input Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null. Notes: If the two linked lists have no intersection at all, return null. The linked lists must retain their original structure after the function returns. You may assume there are no cycles anywhere in the entire linked structure. Each value on each linked list is in the range [1, 10^9]. Your code should preferably run in O(n) time and use only O(1) memory. */ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode *ans = NULL; auto temp = headA; while (temp) { temp->val *= (-1); temp = temp->next; } temp = headB; while (temp) { if (temp->val < 0) { ans = temp; break; } temp = temp->next; } temp = headA; while (temp) { temp->val *= (-1); temp = temp->next; } return ans; } };
32.289474
307
0.649959
Akshad7829
4c95eabae144be335da77ddf4d4002b5c8fbf95d
4,955
cpp
C++
src/Particles/FlexiblePatchyRod.cpp
mtortora/chiralDFT
d5ea5e940d6bc72d96fd9728d042de1e09d3ef85
[ "MIT" ]
2
2018-01-03T09:33:09.000Z
2019-06-14T13:29:37.000Z
src/Particles/FlexiblePatchyRod.cpp
mtortora/chiralDFT
d5ea5e940d6bc72d96fd9728d042de1e09d3ef85
[ "MIT" ]
null
null
null
src/Particles/FlexiblePatchyRod.cpp
mtortora/chiralDFT
d5ea5e940d6bc72d96fd9728d042de1e09d3ef85
[ "MIT" ]
null
null
null
// =================================================================== /** * Flexible patchy rod derived particle class. * Particle model from http://dx.doi.org/10.1039/c7sm02077e */ // =================================================================== /* * FlexiblePatchyRod.cpp: Version 1.0 * Created 18/12/2017 by Maxime Tortora */ // =================================================================== #include <fstream> #include "Particles/FlexiblePatchyRod.hpp" template<typename number> FlexiblePatchyRod<number>::FlexiblePatchyRod() { this->N_DELTA_L = 2; // WCA/LJ parameters EPSILON_WCA_ = 1.; E_CUT_ = 20.; D_BACK_ = 1. * this->SIGMA_R; R_BACK_ = pow(2., 1./6) * this->SIGMA_R; D_PATCH_ = 0.1 * D_BACK_; R_PATCH_ = 2.5 * this->SIGMA_R; D_LB_ = (D_BACK_+D_PATCH_)/2.; R_LB_ = (R_BACK_+R_PATCH_)/2.; } // ============================ /* Build particle model */ // ============================ template<typename number> void FlexiblePatchyRod<number>::Build(int mpi_rank) { uint N_TOT; // Load configurations from trajectory files on master thread if ( mpi_rank == MPI_MASTER ) { ArrayX<uint> Sizes_bck; ArrayX<uint> Sizes_ptc; ArrayX<uint> Types; ArrayX<number> Charges; std::string DATA_PATH = __DATA_PATH; std::string file_bck = DATA_PATH + "/bck.in"; std::string file_ptc = DATA_PATH + "/ptc.in"; Utils<number>::Load(file_bck, &Backbones, &Charges, &Types, &Sizes_bck); Utils<number>::Load(file_ptc, &Patches, &Charges, &Types, &Sizes_ptc); if ( (Backbones.size() == 0) || (Patches.size() == 0) ) throw std::runtime_error("Unreadable input file(s)"); if ( (Sizes_bck != Sizes_ptc).all() ) throw std::runtime_error("Incompatible backbone/patch input files"); N_BCK = Sizes_bck(0); N_TOT = Sizes_bck.sum(); N_CONF_ = Sizes_bck.size(); if ( (Sizes_bck != N_BCK).any() ) throw std::runtime_error("Found configurations of multiple sizes in backbone file"); } // Broadcast data to slave threads MPI_Bcast(&N_BCK, 1, Utils<uint>().MPI_type, MPI_MASTER, MPI_COMM_WORLD); MPI_Bcast(&N_TOT, 1, Utils<uint>().MPI_type, MPI_MASTER, MPI_COMM_WORLD); MPI_Bcast(&N_CONF_, 1, Utils<uint>().MPI_type, MPI_MASTER, MPI_COMM_WORLD); if ( mpi_rank != MPI_MASTER ) { Backbones.resize(3, N_TOT); Patches .resize(3, N_TOT); } MPI_Bcast(Backbones.data(), Backbones.size(), Utils<number>().MPI_type, MPI_MASTER, MPI_COMM_WORLD); MPI_Bcast(Patches .data(), Patches .size(), Utils<number>().MPI_type, MPI_MASTER, MPI_COMM_WORLD); (this->BVH).Forest.resize(N_CONF_); for ( uint idx_conf_ = 0; idx_conf_ < N_CONF_; ++idx_conf_ ) { // Set center of masses to the origin and main axes to e_z Matrix3X<number> Backbone = Matrix3X<number>::Map(Backbones.data() + 3 * idx_conf_*N_BCK, 3, N_BCK); Matrix3X<number> Patch = Matrix3X<number>::Map(Patches .data() + 3 * idx_conf_*N_BCK, 3, N_BCK); Vector3<number> Center_of_mass = Backbone.rowwise().mean(); Backbone = Backbone.colwise() - Center_of_mass; Patch = Patch .colwise() - Center_of_mass; Matrix33<number> Rot = Utils<number>::PCA(Backbone); Backbone = Rot.transpose() * Backbone; Patch = Rot.transpose() * Patch; // Build root bounding volumes number z_inf = Patch.row(2).minCoeff(); number z_sup = Patch.row(2).maxCoeff(); number r_max = Patch.block(0, 0, 2, N_BCK).colwise().norm().maxCoeff(); number z_max = fmax(std::abs(z_inf),std::abs(z_sup)); this->Hull = &(this->BVH).Forest[idx_conf_]; this->Hull->l_xh = r_max + R_PATCH_/2.; this->Hull->l_yh = r_max + R_PATCH_/2.; this->Hull->l_zh = z_max + R_PATCH_/2.; this->Hull->l_cr = r_max + R_PATCH_/2.; this->Hull->l_ch = z_max; Backbones.block(0, N_BCK*idx_conf_, 3, N_BCK) = Backbone; Patches .block(0, N_BCK*idx_conf_, 3, N_BCK) = Patch; } if ( this->id_ == 1 ) LogTxt("Loaded particle trajectory file: %d configurations, %d interaction sites", N_CONF_, 2*N_TOT); this->R_INTEG = 2*Patches.colwise().norm().maxCoeff() + R_PATCH_; this->V_INTEG = CUB(2.*this->R_INTEG) * 16.*pow(PI, 6); this->V0 = 11.76167; this->V_EFF = 11.76167; } template class FlexiblePatchyRod<float>; template class FlexiblePatchyRod<double>;
36.433824
127
0.539859
mtortora
4c994842752b45e22246872205f35a3e2e111d41
10,896
cpp
C++
CloakEngine/DX12Device.cpp
Bizzarrus/CloakEngine
0890eaada76b91be89702d2a6ec2dcf9b2901fb9
[ "BSD-2-Clause" ]
null
null
null
CloakEngine/DX12Device.cpp
Bizzarrus/CloakEngine
0890eaada76b91be89702d2a6ec2dcf9b2901fb9
[ "BSD-2-Clause" ]
null
null
null
CloakEngine/DX12Device.cpp
Bizzarrus/CloakEngine
0890eaada76b91be89702d2a6ec2dcf9b2901fb9
[ "BSD-2-Clause" ]
null
null
null
#include "stdafx.h" #if CHECK_OS(WINDOWS,10) #include "Implementation/Rendering/DX12/Device.h" #include "Implementation/Rendering/DX12/Casting.h" #include "Implementation/Rendering/DX12/Resource.h" #include "Implementation/Rendering/DX12/ColorBuffer.h" #include "Implementation/Rendering/DX12/RootSignature.h" namespace CloakEngine { namespace Impl { namespace Rendering { namespace DX12 { namespace Device_v1 { CLOAK_CALL Device::Device(In const GraphicDevice& dev12) { DEBUG_NAME(Device); m_dev12 = dev12; } CLOAK_CALL Device::~Device() { } uint32_t CLOAK_CALL_THIS Device::GetDescriptorHandleIncrementSize(In HEAP_TYPE type) const { return static_cast<uint32_t>(m_dev12.V0->GetDescriptorHandleIncrementSize(Casting::CastForward(type))); } void CLOAK_CALL_THIS Device::CreateConstantBufferView(In const CBV_DESC& desc, In_opt const API::Rendering::CPU_DESCRIPTOR_HANDLE& cpuHandle) const { D3D12_CONSTANT_BUFFER_VIEW_DESC rd = Casting::CastForward(desc); m_dev12.V0->CreateConstantBufferView(&rd, Casting::CastForward(cpuHandle)); } void CLOAK_CALL_THIS Device::CreateShaderResourceView(In IResource* rsc, In const SRV_DESC& desc, In_opt const API::Rendering::CPU_DESCRIPTOR_HANDLE& cpuHandle) { Resource* res = nullptr; if (rsc!=nullptr && SUCCEEDED(rsc->QueryInterface(CE_QUERY_ARGS(&res)))) { D3D12_SHADER_RESOURCE_VIEW_DESC rd = Casting::CastForward(desc); m_dev12.V0->CreateShaderResourceView(res->m_data, &rd, Casting::CastForward(cpuHandle)); res->Release(); } } void CLOAK_CALL_THIS Device::CreateRenderTargetView(In IResource* rsc, In const RTV_DESC& desc, In_opt const API::Rendering::CPU_DESCRIPTOR_HANDLE& cpuHandle) { Resource* res = nullptr; if (rsc != nullptr && SUCCEEDED(rsc->QueryInterface(CE_QUERY_ARGS(&res)))) { D3D12_RENDER_TARGET_VIEW_DESC rd = Casting::CastForward(desc); m_dev12.V0->CreateRenderTargetView(res->m_data, &rd, Casting::CastForward(cpuHandle)); res->Release(); } } void CLOAK_CALL_THIS Device::CreateUnorderedAccessView(In IResource* rsc, In_opt IResource* byteAddress, In const UAV_DESC& desc, In_opt const API::Rendering::CPU_DESCRIPTOR_HANDLE& cpuHandle) { Resource* res = nullptr; if (rsc != nullptr && SUCCEEDED(rsc->QueryInterface(CE_QUERY_ARGS(&res)))) { D3D12_UNORDERED_ACCESS_VIEW_DESC rd = Casting::CastForward(desc); Resource* ba = nullptr; if (byteAddress != nullptr && SUCCEEDED(byteAddress->QueryInterface(CE_QUERY_ARGS(&ba)))) { m_dev12.V0->CreateUnorderedAccessView(res->m_data, ba->m_data, &rd, Casting::CastForward(cpuHandle)); ba->Release(); } else { m_dev12.V0->CreateUnorderedAccessView(res->m_data, nullptr, &rd, Casting::CastForward(cpuHandle)); } res->Release(); } } void CLOAK_CALL_THIS Device::CreateDepthStencilView(In IResource* rsc, In const DSV_DESC& desc, In_opt const API::Rendering::CPU_DESCRIPTOR_HANDLE& cpuHandle) { Resource* res = nullptr; if (rsc != nullptr && SUCCEEDED(rsc->QueryInterface(CE_QUERY_ARGS(&res)))) { D3D12_DEPTH_STENCIL_VIEW_DESC rd = Casting::CastForward(desc); m_dev12.V0->CreateDepthStencilView(res->m_data, &rd, Casting::CastForward(cpuHandle)); res->Release(); } } void CLOAK_CALL_THIS Device::CreateSampler(In const API::Rendering::SAMPLER_DESC& desc, In API::Rendering::CPU_DESCRIPTOR_HANDLE handle) { D3D12_SAMPLER_DESC d; d.Filter = Casting::CastForward(desc.Filter); d.AddressU = Casting::CastForward(desc.AddressU); d.AddressV = Casting::CastForward(desc.AddressV); d.AddressW = Casting::CastForward(desc.AddressW); d.MipLODBias = desc.MipLODBias; d.MaxAnisotropy = desc.MaxAnisotropy; d.ComparisonFunc = Casting::CastForward(desc.CompareFunction); for (size_t a = 0; a < 4; a++) { d.BorderColor[a] = desc.BorderColor[a]; } d.MinLOD = desc.MinLOD; d.MaxLOD = desc.MaxLOD; m_dev12.V0->CreateSampler(&d, Casting::CastForward(handle)); } void CLOAK_CALL_THIS Device::CopyDescriptorsSimple(In UINT numDescriptors, In const API::Rendering::CPU_DESCRIPTOR_HANDLE& dstStart, In const API::Rendering::CPU_DESCRIPTOR_HANDLE& srcStart, In HEAP_TYPE heap) { m_dev12.V0->CopyDescriptorsSimple(numDescriptors, Casting::CastForward(dstStart), Casting::CastForward(srcStart), Casting::CastForward(heap)); } void CLOAK_CALL_THIS Device::CopyDescriptors(In UINT numDstRanges, In_reads(numDstRanges) const API::Rendering::CPU_DESCRIPTOR_HANDLE* dstRangeStarts, In_reads_opt(numDstRanges) const UINT* dstRangeSizes, In UINT numSrcRanges, In_reads(numSrcRanges) const API::Rendering::CPU_DESCRIPTOR_HANDLE* srcRangeStarts, In_reads_opt(numSrcRanges) const UINT* srcRangeSizes, In HEAP_TYPE heap) { D3D12_CPU_DESCRIPTOR_HANDLE* dstRange = NewArray(D3D12_CPU_DESCRIPTOR_HANDLE, numDstRanges); D3D12_CPU_DESCRIPTOR_HANDLE* srcRange = NewArray(D3D12_CPU_DESCRIPTOR_HANDLE, numSrcRanges); for (UINT a = 0; a < numDstRanges; a++) { dstRange[a] = Casting::CastForward(dstRangeStarts[a]); } for (UINT a = 0; a < numSrcRanges; a++) { srcRange[a] = Casting::CastForward(srcRangeStarts[a]); } m_dev12.V0->CopyDescriptors(numDstRanges, dstRange, dstRangeSizes, numSrcRanges, srcRange, srcRangeSizes, Casting::CastForward(heap)); DeleteArray(dstRange); DeleteArray(srcRange); } HRESULT CLOAK_CALL_THIS Device::CreateRootSignature(In const void* data, In size_t dataSize, In REFIID riid, Out void** ppvObject) { const UINT nodeCount = m_dev12.V0->GetNodeCount(); return m_dev12.V0->CreateRootSignature(nodeCount == 1 ? 0 : ((1 << nodeCount) - 1), data, dataSize, riid, ppvObject); } HRESULT CLOAK_CALL_THIS Device::CreateCommandQueue(In const D3D12_COMMAND_QUEUE_DESC& desc, In REFIID riid, Out void** ppvObject) { CLOAK_ASSUME((desc.NodeMask == 0) == (m_dev12.V0->GetNodeCount() == 1)); return m_dev12.V0->CreateCommandQueue(&desc, riid, ppvObject); } HRESULT CLOAK_CALL_THIS Device::CreateFence(In uint64_t value, In D3D12_FENCE_FLAGS flags, In REFIID riid, Out void** ppvObject) { return m_dev12.V0->CreateFence(value, flags, riid, ppvObject); } HRESULT CLOAK_CALL_THIS Device::CreateCommandList(In UINT node, In D3D12_COMMAND_LIST_TYPE type, In ID3D12CommandAllocator* alloc, In REFIID riid, Out void** ppvObject) { return m_dev12.V0->CreateCommandList(node, type, alloc, nullptr, riid, ppvObject); } HRESULT CLOAK_CALL_THIS Device::CreateCommandAllocator(In D3D12_COMMAND_LIST_TYPE type, In REFIID riid, Out void** ppvObject) { return m_dev12.V0->CreateCommandAllocator(type, riid, ppvObject); } HRESULT CLOAK_CALL_THIS Device::CreateCommittedResource(In const D3D12_HEAP_PROPERTIES& heap, In D3D12_HEAP_FLAGS heapFlags, In const D3D12_RESOURCE_DESC& desc, In D3D12_RESOURCE_STATES state, In_opt const D3D12_CLEAR_VALUE* clearValue, In REFIID riid, Out void** ppvObject) { CLOAK_ASSUME((heap.CreationNodeMask == 0) == (m_dev12.V0->GetNodeCount() == 1) && heap.CreationNodeMask == heap.VisibleNodeMask); return m_dev12.V0->CreateCommittedResource(&heap, heapFlags, &desc, state, clearValue, riid, ppvObject); } HRESULT CLOAK_CALL_THIS Device::CreateDescriptorHeap(In const D3D12_DESCRIPTOR_HEAP_DESC& desc, REFIID riid, void** ppvObject) { CLOAK_ASSUME((desc.NodeMask == 0) == (m_dev12.V0->GetNodeCount() == 1)); return m_dev12.V0->CreateDescriptorHeap(&desc, riid, ppvObject); } HRESULT CLOAK_CALL_THIS Device::CreateComputePipelineState(In const D3D12_COMPUTE_PIPELINE_STATE_DESC& desc, REFIID riid, void** ppvObject) { CLOAK_ASSUME((desc.NodeMask == 0) == (m_dev12.V0->GetNodeCount() == 1)); return m_dev12.V0->CreateComputePipelineState(&desc, riid, ppvObject); } HRESULT CLOAK_CALL_THIS Device::CreateGraphicsPipelineState(In const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, REFIID riid, void** ppvObject) { CLOAK_ASSUME((desc.NodeMask == 0) == (m_dev12.V0->GetNodeCount() == 1)); return m_dev12.V0->CreateGraphicsPipelineState(&desc, riid, ppvObject); } HRESULT CLOAK_CALL_THIS Device::CreatePipelineState(In D3D12_PIPELINE_STATE_DESC& desc, REFIID riid, void** ppvObject) { if (m_dev12.V2 != nullptr) { D3D12_PIPELINE_STATE_STREAM_DESC d; d.pPipelineStateSubobjectStream = &desc; d.SizeInBytes = sizeof(desc); return m_dev12.V2->CreatePipelineState(&d, riid, ppvObject); } else { //TODO } return E_FAIL; } HRESULT CLOAK_CALL_THIS Device::CreateQueryHeap(In const D3D12_QUERY_HEAP_DESC& desc, REFIID riid, void** ppvObject) { CLOAK_ASSUME((desc.NodeMask == 0) == (m_dev12.V0->GetNodeCount() == 1)); return m_dev12.V0->CreateQueryHeap(&desc, riid, ppvObject); } void CLOAK_CALL_THIS Device::GetCopyableFootprints(In const D3D12_RESOURCE_DESC& resourceDesc, In UINT firstSubresource, In UINT numSubresources, In UINT64 baseOffset, Out_writes(numSubresources) D3D12_PLACED_SUBRESOURCE_FOOTPRINT* layouts, Out_writes(numSubresources) UINT* numRows, Out_writes(numSubresources) UINT64* rowSizeInBytes, Out_opt UINT64* totalBytes) { m_dev12.V0->GetCopyableFootprints(&resourceDesc, firstSubresource, numSubresources, baseOffset, layouts, numRows, rowSizeInBytes, totalBytes); } Use_annotations HRESULT STDMETHODCALLTYPE Device::QueryInterface(REFIID riid, void** ppvObject) { if (ppvObject == nullptr) { return E_INVALIDARG; } *ppvObject = nullptr; bool got = false; if (riid == __uuidof(ID3D12Device)) { *ppvObject = static_cast<ID3D12Device*>(m_dev12.V0.Get()); m_dev12.V0->AddRef(); got = true; } else if (riid == __uuidof(Impl::Rendering::DX12::Device_v1::Device)) { *ppvObject = static_cast<Impl::Rendering::DX12::Device_v1::Device*>(this); AddRef(); got = true; } else if (riid == __uuidof(Impl::Rendering::Device_v1::IDevice)) { *ppvObject = static_cast<Impl::Rendering::Device_v1::IDevice*>(this); AddRef(); got = true; } else { got = SavePtr::iQueryInterface(riid, ppvObject); if (got) { AddRef(); } } return got ? S_OK : E_NOINTERFACE; } } } } } } #endif
51.63981
389
0.687133
Bizzarrus
4c99c6f18b421a3a060af9c410e3c7df700aa39b
1,079
cpp
C++
plugins/glib/src/application/models/CollectionData.cpp
winterdl/kinoko
9cb040e2efcbe08377826c4bb7518cfd0ced0564
[ "MIT" ]
119
2020-09-22T07:40:55.000Z
2022-03-28T18:28:02.000Z
plugins/glib/src/application/models/CollectionData.cpp
winterdl/kinoko
9cb040e2efcbe08377826c4bb7518cfd0ced0564
[ "MIT" ]
32
2021-07-19T12:03:00.000Z
2022-03-25T06:39:04.000Z
plugins/glib/src/application/models/CollectionData.cpp
winterdl/kinoko
9cb040e2efcbe08377826c4bb7518cfd0ced0564
[ "MIT" ]
14
2021-07-16T14:38:35.000Z
2022-03-06T00:25:37.000Z
// // Created by gen on 7/24/20. // #include <nlohmann/json.hpp> #include "CollectionData.h" #include "../utils/JSON.h" using namespace gs; CollectionData::CollectionData() : flag(0) { } gc::Array CollectionData::all(const std::string &type) { return CollectionData::query()->equal("type", type)->sortBy("identifier")->results(); } gc::Array CollectionData::findBy(const std::string &type, const std::string &sort, int page, int page_count) { return CollectionData::query()->equal("type", type)->sortBy(sort)->offset(page * page_count)->limit(page_count)->results(); } gc::Ref<CollectionData> CollectionData::find(const std::string &type, const std::string &key) { gc::Array arr = CollectionData::query()->equal("type", type)->andQ()->equal("key", key)->results(); if (arr->size()) return arr->get(0); return gc::Ref<CollectionData>::null(); } void CollectionData::setJSONData(const gc::Variant &data) { if (data) { nlohmann::json json = JSON::serialize(data); setData(json.dump()); } else { setData(""); } }
29.972222
127
0.652456
winterdl
4c9d053b22563ca5ceb2eeba5beb612158ee5331
625
cpp
C++
car_inher.cpp
ishansheth/ModernCpp-Exercises
c33d63ea9e6fe3115fbac51304a75292f32998cd
[ "MIT" ]
null
null
null
car_inher.cpp
ishansheth/ModernCpp-Exercises
c33d63ea9e6fe3115fbac51304a75292f32998cd
[ "MIT" ]
null
null
null
car_inher.cpp
ishansheth/ModernCpp-Exercises
c33d63ea9e6fe3115fbac51304a75292f32998cd
[ "MIT" ]
null
null
null
#include <iostream> class car { public: car(const std::string& name) : name(name) {} void all_info() const { std::cout<< "car name:"<<name<<std::endl; } protected: std::string name; }; class truck : public car { public: truck(const std::String& name, double weight): car(name), weight(weight) {} void all_info() { std::cout<< "truck : My name is " << name <<std::endl; std::cout<< "I can carry "<< weight<< std::endl; } protected: double weight; }; int main(int argc, char* arhv[]) { truck robur("Robur L04",2.5); robur.all_info(); }
15.625
75
0.5584
ishansheth
4ca1ae89c3c0a8c805c8c2154f31bd65dc173363
4,566
cpp
C++
test/allocator/wary_ptr/test_wary_ptr_two_ptrs.cpp
bi-ts/dst
d68d4cfb7509a2f65c8120d88cbc198874343f30
[ "BSL-1.0" ]
null
null
null
test/allocator/wary_ptr/test_wary_ptr_two_ptrs.cpp
bi-ts/dst
d68d4cfb7509a2f65c8120d88cbc198874343f30
[ "BSL-1.0" ]
null
null
null
test/allocator/wary_ptr/test_wary_ptr_two_ptrs.cpp
bi-ts/dst
d68d4cfb7509a2f65c8120d88cbc198874343f30
[ "BSL-1.0" ]
1
2021-09-03T10:48:56.000Z
2021-09-03T10:48:56.000Z
// Copyright Maksym V. Bilinets 2015 - 2020. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt ) #include <dst/allocator/wary_ptr.h> #include <dst/allocator/detail/wary_ptr_factory.h> #include "tester_wary_ptr.h" #include <gtest/gtest.h> #include <cstdint> // std::int64_t using namespace dst; namespace { class Test_wary_ptr_two_ptrs : public ::testing::Test, public dst::test::Tester_wary_ptr { public: Test_wary_ptr_two_ptrs() : ptr_1(detail::wary_ptr_factory::create_associated_ptr(values, elements_num)) , ptr_2(ptr_1) { ++++ptr_2; // shift by two } ~Test_wary_ptr_two_ptrs() noexcept(true) { neutralize(ptr_2); neutralize(ptr_1); } static const std::size_t elements_num = 3; std::int64_t values[elements_num]; dst::wary_ptr<std::int64_t> ptr_1; dst::wary_ptr<std::int64_t> ptr_2; }; } /// @fn wary_ptr<T>::operator==(const wary_ptr<U>& other) const /// @test @b Test_wary_ptr_two_ptrs.equality_test <br> /// Tests if: /// * Two different pointers do not compare equal. /// * Pointers compare equal to themselves. /// * An associated and a loose pointer compare equal if they point to /// the same memory location. TEST_F(Test_wary_ptr_two_ptrs, equality_test) { wary_ptr<std::int64_t> loose_ptr = wary_ptr<std::int64_t>::pointer_to(values[0]); EXPECT_FALSE(ptr_1 == ptr_2); EXPECT_FALSE(ptr_2 == ptr_1); EXPECT_TRUE(ptr_1 == ptr_1); EXPECT_TRUE(ptr_2 == ptr_2); EXPECT_TRUE(ptr_1 == loose_ptr); } /// @fn wary_ptr<T>::operator!=(const wary_ptr<U>& other) const /// @test @b Test_wary_ptr_two_ptrs.inequality_test <br> /// Uses operator!=() to tests if: /// * Two different pointers compare inequal. /// * Pointers do not compare inequal to themselves. TEST_F(Test_wary_ptr_two_ptrs, inequality_test) { EXPECT_TRUE(ptr_1 != ptr_2); EXPECT_TRUE(ptr_2 != ptr_1); EXPECT_FALSE(ptr_1 != ptr_1); EXPECT_FALSE(ptr_2 != ptr_2); } /// @fn wary_ptr<T>::operator<(const wary_ptr<U>& other) const /// @test @b Test_wary_ptr_two_ptrs.operator_less <br> /// Tests operator<() comparing: /// * Two different pointers. /// * The same pointer with itself. TEST_F(Test_wary_ptr_two_ptrs, operator_less) { EXPECT_TRUE(ptr_1 < ptr_2); EXPECT_FALSE(ptr_2 < ptr_1); EXPECT_FALSE(ptr_1 < ptr_1); EXPECT_FALSE(ptr_2 < ptr_2); } /// @fn wary_ptr<T>::operator>(const wary_ptr<U>& other) const /// @test @b Test_wary_ptr_two_ptrs.operator_greater <br> /// Tests operator>() comparing: /// * Two different pointers. /// * The same pointer with itself. TEST_F(Test_wary_ptr_two_ptrs, operator_greater) { EXPECT_FALSE(ptr_1 > ptr_2); EXPECT_TRUE(ptr_2 > ptr_1); EXPECT_FALSE(ptr_1 > ptr_1); EXPECT_FALSE(ptr_2 > ptr_2); } /// @fn wary_ptr<T>::operator<=(const wary_ptr<U>& other) const /// @test @b Test_wary_ptr_two_ptrs.operator_less_eq <br> /// Tests operator<=() comparing: /// * Two different pointers. /// * The same pointer with itself. TEST_F(Test_wary_ptr_two_ptrs, operator_less_eq) { EXPECT_TRUE(ptr_1 <= ptr_2); EXPECT_FALSE(ptr_2 <= ptr_1); EXPECT_TRUE(ptr_1 <= ptr_1); EXPECT_TRUE(ptr_2 <= ptr_2); } /// @fn wary_ptr<T>::operator>=(const wary_ptr<U>& other) const /// @test @b Test_wary_ptr_two_ptrs.operator_greater_eq <br> /// Tests operator>=() comparing: /// * Two different pointers. /// * The same pointer with itself. TEST_F(Test_wary_ptr_two_ptrs, operator_greater_eq) { EXPECT_FALSE(ptr_1 >= ptr_2); EXPECT_TRUE(ptr_2 >= ptr_1); EXPECT_TRUE(ptr_1 >= ptr_1); EXPECT_TRUE(ptr_2 >= ptr_2); } /// @fn dst::wary_ptr::operator+() /// @test @b Test_wary_ptr_two_ptrs.operator_plus <br> /// Uses operator+() to shift pointer. TEST_F(Test_wary_ptr_two_ptrs, operator_plus) { auto ptr = ptr_1 + 2; EXPECT_EQ(ptr_2, ptr); } /// @fn dst::wary_ptr::operator-(std::ptrdiff_t) const /// @test @b Test_wary_ptr_two_ptrs.operator_minus <br> /// Uses operator-() to shift pointer. TEST_F(Test_wary_ptr_two_ptrs, operator_minus) { auto ptr = ptr_2 - 2; EXPECT_EQ(ptr_1, ptr); } /// @fn dst::wary_ptr::operator-(const wary_ptr<T>&) const /// @test @b Test_wary_ptr_two_ptrs.difference <br> /// Uses operator-() to calculate difference between pointers. TEST_F(Test_wary_ptr_two_ptrs, difference) { EXPECT_EQ(2, ptr_2 - ptr_1); EXPECT_EQ(-2, ptr_1 - ptr_2); }
27.841463
80
0.681997
bi-ts
4ca769de97d0bfa30c935718b70d2c02387b0b0f
6,811
cpp
C++
MLPP/LogReg/LogReg.cpp
KangLin/MLPP
abd2dba6076c98aa2e1c29fb3198b74a3f28f8fe
[ "MIT" ]
927
2021-12-03T07:02:25.000Z
2022-03-30T07:37:23.000Z
MLPP/LogReg/LogReg.cpp
DJofOUC/MLPP
6940fc1fbcb1bc16fe910c90a32d9e4db52e264f
[ "MIT" ]
7
2022-02-13T22:38:08.000Z
2022-03-07T01:00:32.000Z
MLPP/LogReg/LogReg.cpp
DJofOUC/MLPP
6940fc1fbcb1bc16fe910c90a32d9e4db52e264f
[ "MIT" ]
132
2022-01-13T02:19:04.000Z
2022-03-23T19:23:56.000Z
// // LogReg.cpp // // Created by Marc Melikyan on 10/2/20. // #include "LogReg.hpp" #include "Activation/Activation.hpp" #include "LinAlg/LinAlg.hpp" #include "Regularization/Reg.hpp" #include "Utilities/Utilities.hpp" #include "Cost/Cost.hpp" #include <iostream> #include <random> namespace MLPP{ LogReg::LogReg(std::vector<std::vector<double>> inputSet, std::vector<double> outputSet, std::string reg, double lambda, double alpha) : inputSet(inputSet), outputSet(outputSet), n(inputSet.size()), k(inputSet[0].size()), reg(reg), lambda(lambda), alpha(alpha) { y_hat.resize(n); weights = Utilities::weightInitialization(k); bias = Utilities::biasInitialization(); } std::vector<double> LogReg::modelSetTest(std::vector<std::vector<double>> X){ return Evaluate(X); } double LogReg::modelTest(std::vector<double> x){ return Evaluate(x); } void LogReg::gradientDescent(double learning_rate, int max_epoch, bool UI){ LinAlg alg; Reg regularization; double cost_prev = 0; int epoch = 1; forwardPass(); while(true){ cost_prev = Cost(y_hat, outputSet); std::vector<double> error = alg.subtraction(y_hat, outputSet); // Calculating the weight gradients weights = alg.subtraction(weights, alg.scalarMultiply(learning_rate/n, alg.mat_vec_mult(alg.transpose(inputSet), error))); weights = regularization.regWeights(weights, lambda, alpha, reg); // Calculating the bias gradients bias -= learning_rate * alg.sum_elements(error) / n; forwardPass(); if(UI) { Utilities::CostInfo(epoch, cost_prev, Cost(y_hat, outputSet)); Utilities::UI(weights, bias); } epoch++; if(epoch > max_epoch) { break; } } } void LogReg::MLE(double learning_rate, int max_epoch, bool UI){ LinAlg alg; Reg regularization; double cost_prev = 0; int epoch = 1; forwardPass(); while(true){ cost_prev = Cost(y_hat, outputSet); std::vector<double> error = alg.subtraction(outputSet, y_hat); // Calculating the weight gradients weights = alg.addition(weights, alg.scalarMultiply(learning_rate/n, alg.mat_vec_mult(alg.transpose(inputSet), error))); weights = regularization.regWeights(weights, lambda, alpha, reg); // Calculating the bias gradients bias += learning_rate * alg.sum_elements(error) / n; forwardPass(); if(UI) { Utilities::CostInfo(epoch, cost_prev, Cost(y_hat, outputSet)); Utilities::UI(weights, bias); } epoch++; if(epoch > max_epoch) { break; } } } void LogReg::SGD(double learning_rate, int max_epoch, bool UI){ LinAlg alg; Reg regularization; double cost_prev = 0; int epoch = 1; while(true){ std::random_device rd; std::default_random_engine generator(rd()); std::uniform_int_distribution<int> distribution(0, int(n - 1)); int outputIndex = distribution(generator); double y_hat = Evaluate(inputSet[outputIndex]); cost_prev = Cost({y_hat}, {outputSet[outputIndex]}); double error = y_hat - outputSet[outputIndex]; // Weight updation weights = alg.subtraction(weights, alg.scalarMultiply(learning_rate * error, inputSet[outputIndex])); weights = regularization.regWeights(weights, lambda, alpha, reg); // Bias updation bias -= learning_rate * error; y_hat = Evaluate({inputSet[outputIndex]}); if(UI) { Utilities::CostInfo(epoch, cost_prev, Cost({y_hat}, {outputSet[outputIndex]})); Utilities::UI(weights, bias); } epoch++; if(epoch > max_epoch) { break; } } forwardPass(); } void LogReg::MBGD(double learning_rate, int max_epoch, int mini_batch_size, bool UI){ LinAlg alg; Reg regularization; double cost_prev = 0; int epoch = 1; // Creating the mini-batches int n_mini_batch = n/mini_batch_size; auto [inputMiniBatches, outputMiniBatches] = Utilities::createMiniBatches(inputSet, outputSet, n_mini_batch); while(true){ for(int i = 0; i < n_mini_batch; i++){ std::vector<double> y_hat = Evaluate(inputMiniBatches[i]); cost_prev = Cost(y_hat, outputMiniBatches[i]); std::vector<double> error = alg.subtraction(y_hat, outputMiniBatches[i]); // Calculating the weight gradients weights = alg.subtraction(weights, alg.scalarMultiply(learning_rate/outputMiniBatches[i].size(), alg.mat_vec_mult(alg.transpose(inputMiniBatches[i]), error))); weights = regularization.regWeights(weights, lambda, alpha, reg); // Calculating the bias gradients bias -= learning_rate * alg.sum_elements(error) / outputMiniBatches[i].size(); y_hat = Evaluate(inputMiniBatches[i]); if(UI) { Utilities::CostInfo(epoch, cost_prev, Cost(y_hat, outputMiniBatches[i])); Utilities::UI(weights, bias); } } epoch++; if(epoch > max_epoch) { break; } } forwardPass(); } double LogReg::score(){ Utilities util; return util.performance(y_hat, outputSet); } void LogReg::save(std::string fileName){ Utilities util; util.saveParameters(fileName, weights, bias); } double LogReg::Cost(std::vector <double> y_hat, std::vector<double> y){ Reg regularization; class Cost cost; return cost.LogLoss(y_hat, y) + regularization.regTerm(weights, lambda, alpha, reg); } std::vector<double> LogReg::Evaluate(std::vector<std::vector<double>> X){ LinAlg alg; Activation avn; return avn.sigmoid(alg.scalarAdd(bias, alg.mat_vec_mult(X, weights))); } double LogReg::Evaluate(std::vector<double> x){ LinAlg alg; Activation avn; return avn.sigmoid(alg.dot(weights, x) + bias); } // sigmoid ( wTx + b ) void LogReg::forwardPass(){ y_hat = Evaluate(inputSet); } }
34.055
175
0.569079
KangLin
4cb6b6bf6ec32e29ff5e6f6a96db16f3be0a3cf4
3,614
cc
C++
archetype/Serialization.cc
gitosaurus/archetype
849cd50e653adab6e5ca6f23d5350217a8a4d025
[ "MIT" ]
6
2015-05-04T17:18:54.000Z
2021-01-24T16:23:56.000Z
archetype/Serialization.cc
gitosaurus/archetype
849cd50e653adab6e5ca6f23d5350217a8a4d025
[ "MIT" ]
null
null
null
archetype/Serialization.cc
gitosaurus/archetype
849cd50e653adab6e5ca6f23d5350217a8a4d025
[ "MIT" ]
null
null
null
// // Serialization.cpp // archetype // // Created by Derek Jones on 6/15/14. // Copyright (c) 2014 Derek Jones. All rights reserved. // // For Windows #define _SCL_SECURE_NO_WARNINGS #include <stdexcept> #include <algorithm> #include <iterator> #include <sstream> #include "Serialization.hh" using namespace std; namespace archetype { const Storage::Byte SignBit = 0x01; const Storage::Byte MoreBit = 0x80; const Storage::Byte PayloadBits = 0x7F; const Storage::Byte FirstBytePayloadBits = 0x3F; int Storage::readInteger() { int bytes_left = remaining(); if (not bytes_left) { throw invalid_argument("No more bytes remaining; cannot read an integer"); } Byte byte; read(&byte, sizeof(byte)); bool more = static_cast<bool>(byte & MoreBit); byte &= ~MoreBit; // The sign bit is the very first bit deserialized. // Note it for this number and shift it off. bool negative = (byte & SignBit); byte >>= 1; int bits = 6; int result = byte; while (more) { if (not read(&byte, sizeof(byte))) { throw invalid_argument("End of storage in the middle of a continued integer"); } int next_part = (byte & PayloadBits); next_part <<= bits; result |= next_part; more = static_cast<bool>(byte & MoreBit); bits += 7; } return negative ? -result : result; } void Storage::writeInteger(int value) { bool negative = value < 0; if (negative) { value = -value; } int bits = 6; Byte byte = (value & FirstBytePayloadBits); byte <<= 1; if (negative) { byte |= SignBit; } else { byte &= ~SignBit; } do { value >>= bits; if (value) { byte |= MoreBit; } write(&byte, sizeof(byte)); bits = 7; byte = (value & PayloadBits); } while (value); } Storage& operator<<(Storage& out, int value) { out.writeInteger(value); return out; } Storage& operator>>(Storage& in, int& value) { value = in.readInteger(); return in; } Storage& operator<<(Storage& out, std::string value) { int size = static_cast<int>(value.size()); out << size; out.write(reinterpret_cast<const Storage::Byte*>(value.data()), size); return out; } Storage& operator>>(Storage& in, std::string& value) { int size; in >> size; value.resize(size); int bytes_read = in.read(reinterpret_cast<Storage::Byte*>(&value[0]), size); if (bytes_read != size) { ostringstream out; out << "Could not fully read string declared as " << size << " bytes; " << "only read " << bytes_read; throw invalid_argument(out.str()); } return in; } MemoryStorage::MemoryStorage(): seekIndex_{0} { } int MemoryStorage::remaining() const { return int(bytes_.size() - seekIndex_); } int MemoryStorage::read(Byte *buf, int nbytes) { int bytes_read = min(nbytes, remaining()); auto cursor = bytes_.begin() + seekIndex_; copy(cursor, cursor + bytes_read, buf); seekIndex_ += bytes_read; return bytes_read; } void MemoryStorage::write(const Byte *buf, int nbytes) { copy(buf, buf + nbytes, back_inserter(bytes_)); } }
27.587786
94
0.546486
gitosaurus
4cb9f755ecff148bd0501ffe24efe666f03d10c5
1,213
hpp
C++
graph/chromatic-number.hpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
69
2020-11-06T05:21:42.000Z
2022-03-29T03:38:35.000Z
graph/chromatic-number.hpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
21
2020-07-25T04:47:12.000Z
2022-02-01T14:39:29.000Z
graph/chromatic-number.hpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
9
2020-11-06T11:55:10.000Z
2022-03-20T04:45:31.000Z
#pragma once #include <cstdint> #include <utility> #include <vector> using namespace std; namespace ChromaticNumberImpl { using i64 = int64_t; template <uint32_t mod> int calc(int n, vector<pair<int, int>> hist) { for (int c = 1; c <= n; c++) { i64 sm = 0; for (auto& [i, x] : hist) sm += (x = i64(x) * i % mod); if (sm % mod != 0) return c; } return n; } } // namespace ChromaticNumberImpl template <typename G> __attribute__((target("avx2"))) int ChromaticNumber(G& g) { int n = g.size(); vector<int> adj(n), dp(1 << n); for (int i = 0; i < n; i++) for (auto& j : g[i]) adj[i] |= 1 << j, adj[j] |= 1 << i; dp[0] = 1; for (int i = 1; i < (1 << n); i++) { int j = __builtin_ctz(i); int k = i & (i - 1); dp[i] = dp[k] + dp[k & ~adj[j]]; } vector<int> memo((1 << n) + 1); for (int i = 0; i < (1 << n); i++) memo[dp[i]] += __builtin_parity(i) ? -1 : 1; vector<pair<int, int>> hist; for (int i = 1; i <= (1 << n); i++) if (memo[i]) hist.emplace_back(i, memo[i]); return min(ChromaticNumberImpl::calc<1000000021>(n, hist), ChromaticNumberImpl::calc<1000000033>(n, hist)); } /** * @brief 彩色数 * @docs docs/graph/chromatic-number.md */
25.808511
61
0.546579
NachiaVivias
4cbb2b3efc81a9b50ba7e07e5013cbd99199e4da
4,983
cpp
C++
TestTravelingSalesman.cpp
sormo/geneticAlgorithm
c69eafa757bfead611663afb6403394e65cbb616
[ "MIT" ]
null
null
null
TestTravelingSalesman.cpp
sormo/geneticAlgorithm
c69eafa757bfead611663afb6403394e65cbb616
[ "MIT" ]
null
null
null
TestTravelingSalesman.cpp
sormo/geneticAlgorithm
c69eafa757bfead611663afb6403394e65cbb616
[ "MIT" ]
null
null
null
#include <fstream> #include <iostream> #include <cmath> #include <map> #include <chrono> #include "json.hpp" #include "BinaryGASolver.h" #include "Common.h" using json = nlohmann::json; #define POPULATION_SIZE 300 #define MUTATION_PROBABILITY 0.01 #define CROSSOVER_FACTOR 0.75 #define MAX_NUMBER_OF_GENERATIONS 15000 using DistancesMap = std::map<std::pair<size_t, size_t>, double>; double ComputeDistance(const std::vector<uint8_t> & chromosome, const DistancesMap & distances) { double totalDistance = 0.0; for (size_t i = 1; i < chromosome.size(); ++i) totalDistance += distances.at({ chromosome[i - 1], chromosome[i] }); totalDistance += distances.at({ chromosome.back(), chromosome[0] }); return totalDistance; } struct EvaluateTravelingSalesman { BinaryGA::EvaluationResult operator()(uint32_t generation, const std::vector<uint8_t> & chromosome) { if (generation != currentGeneration) { std::cout << "\rGeneration " << std::fixed << generation; std::cout << " current minimum: " << std::fixed << std::setprecision(2) << currentDistance; std::cout << " optimal minimum: " << std::fixed << std::setprecision(2) << optimalDistance; //currentDistance = std::numeric_limits<double>::max(); currentGeneration = generation; } double distance = ComputeDistance(chromosome, distances); if (distance < currentDistance) { currentDistance = distance; currentSolution = chromosome; } return fabs(currentDistance - optimalDistance) < 0.1 ? BinaryGA::EvaluationResult::ObjectiveReached : BinaryGA::EvaluationResult::ContinueProcessing; } std::map<std::pair<size_t, size_t>, double> & distances; double optimalDistance; uint32_t currentGeneration = 0; double currentDistance = std::numeric_limits<double>::max(); std::vector<uint8_t> currentSolution; }; std::string ConvertSolutionToString(const std::vector<uint8_t> & solution, const DistancesMap & distances) { std::stringstream str; for (size_t i = 0; i < solution.size(); ++i) str << (size_t)solution[i] << " -> "; str << (size_t)solution[0]; str << " = " << std::fixed << std::setprecision(3) << ComputeDistance(solution, distances); return str.str(); } void TestTravelingSalesman() { std::cout << "Traveling salesman" << std::endl; std::ifstream file("data\\travelingSalesman.json"); json jsonProblems; file >> jsonProblems; BinaryGA::Definition<uint8_t> definition; definition.parentSelection = BinaryGA::ParentSelectionType::Ranked; definition.mutation = BinaryGA::MutationType::Swap; definition.crossover = BinaryGA::CrossoverType::Ordered; definition.populationSize = POPULATION_SIZE; definition.mutationProbability = MUTATION_PROBABILITY; definition.crossoverFactor = CROSSOVER_FACTOR; definition.maxNumberOfGenerations = MAX_NUMBER_OF_GENERATIONS; for (size_t i = 0; i < jsonProblems["problems"].size(); ++i) { std::cout << "Problem: " << i << std::endl; std::cout << "Generation 0"; // read problem double optimalDistance = jsonProblems["problems"][i]["optimal"]; std::vector<Common::Point> points; for (auto point : jsonProblems["problems"][i]["points"]) points.push_back({ point["x"], point["y"] }); // precompute distances std::map<std::pair<size_t, size_t>, double> distances; for (size_t i = 0; i < points.size(); ++i) { for (size_t j = i + 1; j < points.size(); ++j) { double distance = Common::Distance(points[i], points[j]); distances[{i, j}] = distance; distances[{j, i}] = distance; } } // prepare seed std::vector<uint8_t> seed; for (uint8_t i = 0; i < points.size(); ++i) seed.push_back(i); definition.initializationCustomCallback = [&seed](size_t) -> std::vector<uint8_t> { std::random_shuffle(std::begin(seed), std::end(seed)); return seed; }; definition.numberOfGenes = seed.size(); // solve definition.computeFitness = [&distances](const std::vector<uint8_t> & chromosome) -> double { return 1.0 / ComputeDistance(chromosome, distances); }; EvaluateTravelingSalesman evaluate{ distances, optimalDistance }; definition.evaluate = std::ref(evaluate); auto startTime = std::chrono::high_resolution_clock::now(); auto solution = BinaryGA::Solve(definition); std::chrono::duration<double, std::milli> solveDuration = std::chrono::high_resolution_clock::now() - startTime; std::cout << std::endl << "Generation " << evaluate.currentGeneration << " (" << solveDuration.count() << "ms)" << std::endl; if (!solution.empty()) { std::cout << "Optimal solution found: " << std::endl; std::cout << ConvertSolutionToString(solution, distances) << std::endl; } else { std::cout << "Best found solution: " << std::endl; std::cout << ConvertSolutionToString(evaluate.currentSolution, distances) << " "; std::cout << std::fixed << std::setprecision(2); std::cout << (optimalDistance / (double)ComputeDistance(evaluate.currentSolution, distances)) * 100.0 << "%" << std::endl; } } std::cout << std::endl; }
32.357143
127
0.693157
sormo
4cbc6a6435fb02e95017c88dcce968fd9614a896
731
cpp
C++
配套代码/L059/REV_059/REV_059.cpp
zmrbak/ReverseAnalysis
994fdc61c8af2eecc2a065a6f5ee0aacf371e836
[ "MIT" ]
35
2019-11-19T03:12:09.000Z
2022-02-18T08:38:53.000Z
配套代码/L059/REV_059/REV_059.cpp
zmrbak/ReverseAnalysis
994fdc61c8af2eecc2a065a6f5ee0aacf371e836
[ "MIT" ]
null
null
null
配套代码/L059/REV_059/REV_059.cpp
zmrbak/ReverseAnalysis
994fdc61c8af2eecc2a065a6f5ee0aacf371e836
[ "MIT" ]
22
2019-08-03T17:07:17.000Z
2022-02-18T08:38:55.000Z
// REV_059.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <iostream> uint64_t f() { return 0x1234567890ABCDEF; } uint64_t f_add(uint64_t a, uint64_t b) { return a + b; } uint64_t f_sub(uint64_t a, uint64_t b) { return a - b; } uint64_t f_multi(uint64_t a, uint64_t b) { return a * b; } uint64_t f_div(uint64_t a, uint64_t b) { return a / b; } uint64_t f_left(uint64_t a, uint64_t b) { return a << b; } uint64_t f_right(uint64_t a, uint64_t b) { return a >> b; } int main() { printf("Hello World!\n"); uint64_t a = f(); printf("%lld\n",a); printf("%I64d\n", a); printf("Hello World 1!\n"); a = f_add(0x11111111FFFFFFFF,0x22222222EEEEEEEE); printf("%lld\n", a); }
14.057692
53
0.614227
zmrbak
4cc093252fc67a14c5155b461029119f5beb30c9
1,386
cpp
C++
engine/src/Util/Logger.cpp
kyle-piddington/MoonEngine
243cce7988ee089d0fc51d817e2736501e019702
[ "MIT", "BSD-3-Clause" ]
5
2017-01-20T00:23:23.000Z
2018-07-17T07:48:04.000Z
engine/src/Util/Logger.cpp
kyle-piddington/MoonEngine
243cce7988ee089d0fc51d817e2736501e019702
[ "MIT", "BSD-3-Clause" ]
null
null
null
engine/src/Util/Logger.cpp
kyle-piddington/MoonEngine
243cce7988ee089d0fc51d817e2736501e019702
[ "MIT", "BSD-3-Clause" ]
2
2017-01-24T05:09:37.000Z
2021-02-18T14:42:00.000Z
#include "Logger.h" #include <iostream> #include <string> using namespace MoonEngine; std::ostream * Logger::_logStream; LogLevel Logger::_logLevel = ERROR; void Logger::ProvideErrorStream(std::ostream * str) { _logStream = str; } void Logger::SetLogLevel(LogLevel level) { _logLevel = level; } void Logger::Log(LogLevel lv, std::string log, std::string file, int line) { if (lv <= _logLevel) { std::ostream * stream = &std::cerr; if (_logStream != nullptr) { stream = _logStream; } switch (lv) { case FATAL_ERROR: (*stream) << "[!FATAL ERROR!]: "; break; case ERROR: (*stream) << "[ERROR]: "; break; case WARN: (*stream) << "[WARN]: "; break; case GAME: (*stream) << "[GAME]: "; break; case INFO: (*stream) << "[INFO]: "; break; default: (*stream) << "[Log]: "; break; } if (file != "") { file = file.substr(file.find_last_of("\\/") + 1, file.length()); file = " @" + file; } if(line == -1) (*stream) << log << file << std::endl; else (*stream) << log << file << "[" << line << "]" << std::endl; } }
22.721311
74
0.445166
kyle-piddington
4cc1853c9c123c7dac466c8c05cb8c9a68f42780
318
hpp
C++
include/vm/vm.hpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
14
2020-04-14T17:00:56.000Z
2021-08-30T08:29:26.000Z
include/vm/vm.hpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
27
2020-12-27T16:00:44.000Z
2021-08-01T13:12:14.000Z
include/vm/vm.hpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
1
2020-05-29T18:33:37.000Z
2020-05-29T18:33:37.000Z
#pragma once #include "novasm/executable.hpp" #include "vm/exec_state.hpp" #include "vm/platform_interface.hpp" namespace vm { // Execute the given program. Will block until the execution is complete. auto run(const novasm::Executable* executable, PlatformInterface* iface) noexcept -> ExecState; } // namespace vm
26.5
95
0.77044
BastianBlokland
4cc1c75ffb236182b3e61f008634bd0a329b9242
14,737
cpp
C++
src/textures.cpp
FAETHER/VEther
081f0df2c4279c21e1d55bfc336a43bc96b5f1c3
[ "MIT" ]
3
2019-12-07T23:57:47.000Z
2019-12-31T19:46:41.000Z
src/textures.cpp
FAETHER/VEther
081f0df2c4279c21e1d55bfc336a43bc96b5f1c3
[ "MIT" ]
null
null
null
src/textures.cpp
FAETHER/VEther
081f0df2c4279c21e1d55bfc336a43bc96b5f1c3
[ "MIT" ]
null
null
null
#include "textures.h" #include "control.h" #include "render.h" #include "zone.h" #include "lodepng.h" #include "flog.h" #include <math.h> /* { GVAR: logical_device -> startup.cpp GVAR: max2DTex_size -> startup.cpp GVAR: descriptor_pool -> control.cpp GVAR: command_buffer -> control.cpp GVAR: staging_buffers - > control.cpp GVAR: current_staging_buffer -> control.cpp GVAR: tex_dsl -> control.cpp GVAR: number_of_swapchain_images -> swapchain.cpp } */ VkDescriptorSet tex_descriptor_sets[20]; static VkImage v_image[20]; static int current_tex_ds_index = 0; static unsigned char palette[768]; static unsigned int data[256]; static VkSampler point_sampler = VK_NULL_HANDLE; namespace textures { static unsigned* TexMgr8to32(unsigned char *in, int pixels, unsigned int *usepal) { int i; unsigned *out, *data; out = data = (unsigned *) zone::Hunk_Alloc(pixels*4); for (i = 0; i < pixels; i++) *out++ = usepal[*in++]; return data; } unsigned char* Tex8to32(unsigned char* image, int l) { unsigned int *usepal = data; image = (unsigned char*)TexMgr8to32(image, l, usepal); return image; } void InitSamplers() { trace("Initializing samplers"); VkResult err; if (point_sampler == VK_NULL_HANDLE) { VkSamplerCreateInfo sampler_create_info; memset(&sampler_create_info, 0, sizeof(sampler_create_info)); sampler_create_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; sampler_create_info.magFilter = VK_FILTER_NEAREST; sampler_create_info.minFilter = VK_FILTER_NEAREST; sampler_create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; sampler_create_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; sampler_create_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; sampler_create_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; sampler_create_info.mipLodBias = 0.0f; sampler_create_info.maxAnisotropy = 1.0f; sampler_create_info.minLod = 0; sampler_create_info.maxLod = 0.25f; err = vkCreateSampler(logical_device, &sampler_create_info, nullptr, &point_sampler); if (err != VK_SUCCESS) fatal("vkCreateSampler failed"); /* sampler_create_info.anisotropyEnable = VK_TRUE; sampler_create_info.maxAnisotropy = logical_device_properties.limits.maxSamplerAnisotropy; err = vkCreateSampler(logical_device, &sampler_create_info, nullptr, &vulkan_globals.point_aniso_sampler); if (err != VK_SUCCESS) printf("vkCreateSampler failed"); GL_SetObjectName((uint64_t)vulkan_globals.point_aniso_sampler, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT, "point_aniso"); sampler_create_info.magFilter = VK_FILTER_LINEAR; sampler_create_info.minFilter = VK_FILTER_LINEAR; sampler_create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; sampler_create_info.anisotropyEnable = VK_FALSE; sampler_create_info.maxAnisotropy = 1.0f; err = vkCreateSampler(logical_device, &sampler_create_info, nullptr, &vulkan_globals.linear_sampler); if (err != VK_SUCCESS) printf("vkCreateSampler failed"); sampler_create_info.anisotropyEnable = VK_TRUE; sampler_create_info.maxAnisotropy = logical_device_properties.limits.maxSamplerAnisotropy; err = vkCreateSampler(logical_device, &sampler_create_info, nullptr, &vulkan_globals.linear_aniso_sampler); if (err != VK_SUCCESS) printf("vkCreateSampler failed"); */ } } void TexDeinit() { vkDestroySampler(logical_device, point_sampler, nullptr); for(int i = 0; i<current_tex_ds_index; i++) { vkDestroyImage(logical_device, v_image[i], nullptr); //vkDestroyImageView(logical_device, imageViews[number_of_swapchain_images+i+1], nullptr); } } void SetFilterModes(int tex_index, VkImageView *imgView) { VkDescriptorImageInfo image_info; memset(&image_info, 0, sizeof(image_info)); image_info.imageView = *imgView; image_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; image_info.sampler = point_sampler; VkWriteDescriptorSet texture_write; memset(&texture_write, 0, sizeof(texture_write)); texture_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; texture_write.dstSet = tex_descriptor_sets[tex_index]; texture_write.dstBinding = 0; texture_write.dstArrayElement = 0; texture_write.descriptorCount = 1; texture_write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; texture_write.pImageInfo = &image_info; vkUpdateDescriptorSets(logical_device, 1, &texture_write, 0, nullptr); } void GenerateColorPalette() { unsigned char* dst = palette; for(int i = 0; i < 256; i++) { unsigned char r = 127 * (1 + sin(5 * i * 6.28318531 / 16)); unsigned char g = 127 * (1 + sin(2 * i * 6.28318531 / 16)); unsigned char b = 127 * (1 + sin(3 * i * 6.28318531 / 16)); // unsigned char a = 63 * (1 + std::sin(8 * i * 6.28318531 / 16)) + 128; /*alpha channel of the palette (tRNS chunk)*/ *dst++ = r; *dst++ = g; *dst++ = b; //*dst++ = a; } dst = (unsigned char*)data; unsigned char* src = palette; for (int i = 0; i < 256; i++) { *dst++ = *src++; *dst++ = *src++; *dst++ = *src++; *dst++ = 255; } } void UpdateTexture(unsigned char* image, int w, int h, int index) { //SetFilterModes(index, &imageViews[imageViewCount-1]); unsigned char* staging_memory = control::StagingBufferDigress((w*h*4), 4); zone::Q_memcpy(staging_memory, image, (w * h * 4)); VkBufferImageCopy regions = {}; regions.bufferOffset = staging_buffers[current_staging_buffer].current_offset; regions.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; regions.imageSubresource.layerCount = 1; regions.imageSubresource.mipLevel = 0; regions.imageOffset = {0, 0, 0}; regions.imageExtent.width = w; regions.imageExtent.height = h; regions.imageExtent.depth = 1; control::SetCommandBuffer(current_staging_buffer); VkImageMemoryBarrier image_memory_barrier; memset(&image_memory_barrier, 0, sizeof(image_memory_barrier)); image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; image_memory_barrier.image = v_image[index]; image_memory_barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; image_memory_barrier.subresourceRange.baseMipLevel = 0; image_memory_barrier.subresourceRange.levelCount = 1; image_memory_barrier.subresourceRange.baseArrayLayer = 0; image_memory_barrier.subresourceRange.layerCount = 1; image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; image_memory_barrier.srcAccessMask = 0; image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); vkCmdCopyBufferToImage(command_buffer, staging_buffers[current_staging_buffer].buffer, v_image[index], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &regions); image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); control::SetCommandBuffer(0); control::SubmitStagingBuffer(); } void UploadTexture(unsigned char* image, int w, int h, VkFormat format) { VkDescriptorSetAllocateInfo dsai; memset(&dsai, 0, sizeof(dsai)); dsai.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; dsai.descriptorPool = descriptor_pool; dsai.descriptorSetCount = 1; dsai.pSetLayouts = &tex_dsl; vkAllocateDescriptorSets(logical_device, &dsai, &tex_descriptor_sets[current_tex_ds_index]); v_image[current_tex_ds_index] = render::Create2DImage(format, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, w, h); VkMemoryRequirements memory_requirements; vkGetImageMemoryRequirements(logical_device, v_image[current_tex_ds_index], &memory_requirements); int mem_type = control::MemoryTypeFromProperties(memory_requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0); try_again: ; VkDeviceSize aligned_offset; vram_heap* heap = control::VramHeapDigress(memory_requirements.size, memory_requirements.alignment, &aligned_offset); if(!heap) { if(current_tex_ds_index > 0) { //1st allocation - OK. Do not warn. warn("Failed to align the memory"); } control::VramHeapAllocate((VkDeviceSize)1073741824, mem_type); goto try_again; } VK_CHECK(vkBindImageMemory(logical_device, v_image[current_tex_ds_index], heap->memory, aligned_offset)); //render::CreateImageViews(1, &v_image[current_tex_ds_index], VK_FORMAT_R8G8B8A8_UNORM, 0, 1); VkImageViewCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; createInfo.format = format; createInfo.components.r = VK_COMPONENT_SWIZZLE_R; createInfo.components.g = VK_COMPONENT_SWIZZLE_G; createInfo.components.b = VK_COMPONENT_SWIZZLE_B; createInfo.components.a = VK_COMPONENT_SWIZZLE_A; createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; createInfo.subresourceRange.baseMipLevel = 0; createInfo.subresourceRange.levelCount = 1; createInfo.subresourceRange.layerCount = 1; createInfo.image = v_image[current_tex_ds_index]; VK_CHECK(vkCreateImageView(logical_device, &createInfo, 0, &imageViews[imageViewCount++])); SetFilterModes(current_tex_ds_index, &imageViews[imageViewCount-1]); // p("%d", current_staging_buffer); unsigned char* staging_memory = control::StagingBufferDigress((w*h*4), 4); zone::Q_memcpy(staging_memory, image, (w * h * 4)); VkBufferImageCopy regions = {}; regions.bufferOffset = staging_buffers[current_staging_buffer].current_offset; regions.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; regions.imageSubresource.layerCount = 1; regions.imageSubresource.mipLevel = 0; regions.imageOffset = {0, 0, 0}; regions.imageExtent.width = w; regions.imageExtent.height = h; regions.imageExtent.depth = 1; control::SetCommandBuffer(current_staging_buffer); VkImageMemoryBarrier image_memory_barrier; memset(&image_memory_barrier, 0, sizeof(image_memory_barrier)); image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; image_memory_barrier.image = v_image[current_tex_ds_index]; image_memory_barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; image_memory_barrier.subresourceRange.baseMipLevel = 0; image_memory_barrier.subresourceRange.levelCount = 1; image_memory_barrier.subresourceRange.baseArrayLayer = 0; image_memory_barrier.subresourceRange.layerCount = 1; image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; image_memory_barrier.srcAccessMask = 0; image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); vkCmdCopyBufferToImage(command_buffer, staging_buffers[current_staging_buffer].buffer, v_image[current_tex_ds_index], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &regions); image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); control::SetCommandBuffer(0); control::SubmitStagingBuffer(); current_tex_ds_index++; } void FsLoadPngTexture(const char* filename) { ASSERT(filename, "Null pointer passed into FsLoadPngTexture"); // Load file and decode image. unsigned char mem[sizeof(std::vector<unsigned char>)]; std::vector<unsigned char>* image = new (mem) std::vector<unsigned char>; unsigned width, height; unsigned error = lodepng::decode(*image, width, height, filename); if(error != 0) { fatal("Error %s : %s",error,lodepng_error_text(error)); startup::debug_pause(); } unsigned int* usepal = data; unsigned char* img = (unsigned char*)TexMgr8to32(image->data(), (width * height), usepal); UploadTexture(img, width, height, VK_FORMAT_R8G8B8A8_UNORM); } bool SampleTexture() { int mark = zone::Hunk_LowMark(); //generate some image const unsigned w = 511; const unsigned h = 511; unsigned char* image = reinterpret_cast<unsigned char*>(zone::Hunk_Alloc(w * h)); for(unsigned y = 0; y < h; y++) for(unsigned x = 0; x < w; x++) { size_t byte_index = (y * w + x); // printf("%d ", byte_index); // bool byte_half = (y * w + x) % 2 == 1; int color = (int)(4 * ((1 + sin(2.0 * 6.28318531 * x / (double)w)) + (1 + sin(2.0 * 6.28318531 * y / (double)h))) ); image[byte_index] |= (unsigned char)(color << (0)); } unsigned int *usepal = data; image = (unsigned char*)TexMgr8to32(image, (w * h), usepal); UploadTexture(image, w, h, VK_FORMAT_R8G8B8A8_UNORM); zone::Hunk_FreeToLowMark(mark); return true; } bool SampleTextureUpdate() { int mark = zone::Hunk_LowMark(); //generate some image const unsigned w = 511; const unsigned h = 511; unsigned char* image = reinterpret_cast<unsigned char*>(zone::Hunk_Alloc(w * h)); for(unsigned y = 0; y < h; y++) for(unsigned x = 0; x < w; x++) { size_t byte_index = (y * w + x); // printf("%d ", byte_index); // bool byte_half = (y * w + x) % 2 == 1; int color = (int)(4 * ((1 + sin(frametime * 6.28318531 * x / (double)w)) + (1 + sin(time1 * 6.28318531 * y / (double)h))) ); image[byte_index] |= (unsigned char)(color << (0)); } unsigned int *usepal = data; image = (unsigned char*)TexMgr8to32(image, (w * h), usepal); UpdateTexture(image, w, h, 0); zone::Hunk_FreeToLowMark(mark); return true; } } //namespace tex
37.214646
171
0.749406
FAETHER
4cc5ba098e996643ef66ad4eee7ec3c262ac765f
3,281
cpp
C++
source/LibFgWin/FgGuiWinSelect.cpp
maamountki/FaceGenBaseLibrary
0c647920e913354028ed09fff3293555e84d2b94
[ "MIT" ]
null
null
null
source/LibFgWin/FgGuiWinSelect.cpp
maamountki/FaceGenBaseLibrary
0c647920e913354028ed09fff3293555e84d2b94
[ "MIT" ]
null
null
null
source/LibFgWin/FgGuiWinSelect.cpp
maamountki/FaceGenBaseLibrary
0c647920e913354028ed09fff3293555e84d2b94
[ "MIT" ]
null
null
null
// // Copyright (c) 2015 Singular Inversions Inc. (facegen.com) // Use, modification and distribution is subject to the MIT License, // see accompanying file LICENSE.txt or facegen.com/base_library_license.txt // // Authors: Andrew Beatty // Created: Oct 14, 2011 // #include "stdafx.h" #include "FgGuiApiSelect.hpp" #include "FgGuiWin.hpp" #include "FgThrowWindows.hpp" #include "FgBounds.hpp" #include "FgDefaultVal.hpp" #include "FgMetaFormat.hpp" #include "FgAlgs.hpp" using namespace std; struct FgGuiWinSelect : public FgGuiOsBase { FgGuiApiSelect m_api; vector<FgPtr<FgGuiOsBase> > m_panes; size_t m_currPane; // Which one is Windows currently displaying ? FgVect2I m_lo,m_sz; FgString m_store; FgGuiWinSelect(const FgGuiApiSelect & api) : m_api(api) { FGASSERT(api.wins.size() > 0); m_panes.resize(api.wins.size()); for (size_t ii=0; ii<m_panes.size(); ++ii) m_panes[ii] = api.wins[ii]->getInstance(); } virtual void create(HWND parentHwnd,int,const FgString & store,DWORD extStyle,bool visible) { m_store = store; for (size_t ii=0; ii<m_panes.size(); ++ii) m_panes[ii]->create(parentHwnd,int(ii),m_store+"_"+fgToStr(ii),extStyle,false); m_currPane = g_gg.getVal(m_api.selection); if (visible) m_panes[m_currPane]->showWindow(true); } virtual void destroy() { for (size_t ii=0; ii<m_panes.size(); ++ii) m_panes[ii]->destroy(); } virtual FgVect2UI getMinSize() const { FgVect2UI max(0); for (size_t ii=0; ii<m_panes.size(); ++ii) max = fgMax(max,m_panes[ii]->getMinSize()); return max; } virtual FgVect2B wantStretch() const { FgVect2B ret(false,false); for (size_t ii=0; ii<m_panes.size(); ++ii) ret = fgOr(ret,m_panes[ii]->wantStretch()); return ret; } virtual void updateIfChanged() { if (g_gg.dg.update(m_api.updateNodeIdx)) { size_t currPane = g_gg.getVal(m_api.selection); if (currPane != m_currPane) { m_panes[m_currPane]->showWindow(false); m_currPane = currPane; m_panes[m_currPane]->showWindow(true); // Only previously current pane was last updated for size, plus the // MoveWindow call will refresh the screen (ShowWindow doesn't): m_panes[m_currPane]->moveWindow(m_lo,m_sz); } } m_panes[m_currPane]->updateIfChanged(); } virtual void moveWindow(FgVect2I lo,FgVect2I sz) { if (sz[0] * sz[1] > 0) { m_lo = lo; m_sz = sz; m_panes[m_currPane]->moveWindow(lo,sz); } } virtual void showWindow(bool s) {m_panes[m_currPane]->showWindow(s); } virtual void saveState() { for (size_t ii=0; ii<m_panes.size(); ++ii) m_panes[ii]->saveState(); } }; FgPtr<FgGuiOsBase> fgGuiGetOsInstance(const FgGuiApiSelect & api) {return FgPtr<FgGuiOsBase>(new FgGuiWinSelect(api)); }
28.042735
98
0.579092
maamountki
4cd2aaef96e5d2b5b7b3ecaf267bdfb15bbbe044
372
hpp
C++
Source/Maths/Matrices/Matrix3x4.hpp
KingKiller100/kLibrary
37971acd3c54f9ea0decdf78b13e47c935d4bbf0
[ "Apache-2.0" ]
null
null
null
Source/Maths/Matrices/Matrix3x4.hpp
KingKiller100/kLibrary
37971acd3c54f9ea0decdf78b13e47c935d4bbf0
[ "Apache-2.0" ]
null
null
null
Source/Maths/Matrices/Matrix3x4.hpp
KingKiller100/kLibrary
37971acd3c54f9ea0decdf78b13e47c935d4bbf0
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Matrix.hpp" namespace kmaths { template<class T> using Matrix3x4 = Matrix<T, 3, 4>; using Matrix3x4s = Matrix3x4 < int >; // 3 rows - 4 columns - signed integer using Matrix3x4f = Matrix3x4 < float >; // 3 rows - 4 columns - floating point using Matrix3x4d = Matrix3x4 < double >; // 3 rows - 4 columns - double floating point }
26.571429
89
0.666667
KingKiller100
4cd5c85f1aa53aa82449174f646a9b0428af3cf0
795
cpp
C++
source/random.cpp
in1tiate/OoT3D_Randomizer
baa1f4a0f4a2e1aadec9547120b29d1617211f45
[ "MIT" ]
133
2020-08-25T20:27:08.000Z
2022-03-28T04:38:44.000Z
source/random.cpp
in1tiate/OoT3D_Randomizer
baa1f4a0f4a2e1aadec9547120b29d1617211f45
[ "MIT" ]
112
2020-11-27T18:51:33.000Z
2022-03-28T21:58:21.000Z
source/random.cpp
in1tiate/OoT3D_Randomizer
baa1f4a0f4a2e1aadec9547120b29d1617211f45
[ "MIT" ]
57
2020-08-24T08:54:39.000Z
2022-03-27T18:08:51.000Z
#include "random.hpp" #include <random> static bool init = false; static std::mt19937_64 generator; //Initialize with seed specified void Random_Init(uint32_t seed) { init = true; generator = std::mt19937_64{seed}; } //Returns a random integer in range [min, max-1] uint32_t Random(int min, int max) { if (!init) { //No seed given, get a random number from device to seed const auto seed = static_cast<uint32_t>(std::random_device{}()); Random_Init(seed); } std::uniform_int_distribution<uint32_t> distribution(min, max-1); return distribution(generator); } //Returns a random floating point number in [0.0, 1.0] double RandomDouble() { std::uniform_real_distribution<double> distribution(0.0, 1.0); return distribution(generator); }
26.5
72
0.69434
in1tiate
4cd8d8b7eef22d3bb218a925ec6800d1a496803d
3,944
cpp
C++
Abzynt/Abzynt/sdk/config/config.cpp
patrykkolodziej/Abzynt-Cheat
862c72514f868fe24728ae83278647bcc3092180
[ "MIT" ]
14
2019-04-11T19:09:26.000Z
2021-03-27T06:18:02.000Z
Abzynt/Abzynt/sdk/config/config.cpp
patrykkolodziej/Abzynt-Cheat
862c72514f868fe24728ae83278647bcc3092180
[ "MIT" ]
2
2019-05-01T09:19:31.000Z
2019-08-23T01:20:20.000Z
Abzynt/Abzynt/sdk/config/config.cpp
patrykkolodziej/Abzynt-Cheat
862c72514f868fe24728ae83278647bcc3092180
[ "MIT" ]
7
2019-04-16T12:49:30.000Z
2020-09-27T01:53:49.000Z
#include "config.hpp" c_config g_config("config.json"); c_config::c_config(const std::string config_path) { char current_path[MAX_PATH] = ""; GetModuleFileNameA(NULL, current_path, MAX_PATH); PathRemoveFileSpecA(current_path); PathAddBackslashA(current_path); path += config_path; } void c_config::save() { std::ofstream out(path); if (!out.is_open()) { return; } Json::Value save; save["Abzynt - Config"]["Triggerbot"] = settings.triggerbot; save["Abzynt - Config"]["GlowESP"] = settings.glowesp; save["Abzynt - Config"]["ClrRender"] = settings.clrrender; save["Abzynt - Config"]["Glow Enemy Colors"][0] = settings.glow_enemy_colors[0]; save["Abzynt - Config"]["Glow Enemy Colors"][1] = settings.glow_enemy_colors[1]; save["Abzynt - Config"]["Glow Enemy Colors"][2] = settings.glow_enemy_colors[2]; save["Abzynt - Config"]["Glow Team Colors"][0] = settings.glow_team_colors[0]; save["Abzynt - Config"]["Glow Team Colors"][1] = settings.glow_team_colors[1]; save["Abzynt - Config"]["Glow Team Colors"][2] = settings.glow_team_colors[2]; save["Abzynt - Config"]["Clr Enemy Colors"][0] = settings.clr_enemy_colors[0]; save["Abzynt - Config"]["Clr Enemy Colors"][1] = settings.clr_enemy_colors[1]; save["Abzynt - Config"]["Clr Enemy Colors"][2] = settings.clr_enemy_colors[2]; save["Abzynt - Config"]["Clr Team Colors"][0] = settings.clr_team_colors[0]; save["Abzynt - Config"]["Clr Team Colors"][1] = settings.clr_team_colors[1]; save["Abzynt - Config"]["Clr Team Colors"][2] = settings.clr_team_colors[2]; save["Abzynt - Config"]["Triggerbot Key"] = settings.triggerbot_key; save["Abzynt - Config"]["Autopistol"] = settings.autopistol; save["Abzynt - Config"]["Noflash"] = settings.noflash; save["Abzynt - Config"]["Fovchanger"] = settings.fovchanger; save["Abzynt - Config"]["Fovchanger Amount"] = settings.fovchanger_amount; save["Abzynt - Config"]["Radarhack"] = settings.radarhack; out << save; out.close(); } void c_config::load() { std::ifstream in(path); if (!in.good()) { save(); } if (!in.is_open()) { return; } Json::Value load; in >> load; settings.triggerbot = load["Abzynt - Config"]["Triggerbot"].asBool(); settings.glowesp = load["Abzynt - Config"]["GlowESP"].asBool(); settings.clrrender = load["Abzynt - Config"]["ClrRender"].asBool(); settings.glow_enemy_colors[0] = load["Abzynt - Config"]["Glow Enemy Colors"][0].asFloat(); settings.glow_enemy_colors[1] = load["Abzynt - Config"]["Glow Enemy Colors"][1].asFloat(); settings.glow_enemy_colors[2] = load["Abzynt - Config"]["Glow Enemy Colors"][2].asFloat(); settings.glow_team_colors[0] = load["Abzynt - Config"]["Glow Team Colors"][0].asFloat(); settings.glow_team_colors[1] = load["Abzynt - Config"]["Glow Team Colors"][1].asFloat(); settings.glow_team_colors[2] = load["Abzynt - Config"]["Glow Team Colors"][2].asFloat(); settings.clr_enemy_colors[0] = load["Abzynt - Config"]["Clr Enemy Colors"][0].asFloat(); settings.clr_enemy_colors[1] = load["Abzynt - Config"]["Clr Enemy Colors"][1].asFloat(); settings.clr_enemy_colors[2] = load["Abzynt - Config"]["Clr Enemy Colors"][2].asFloat(); settings.clr_team_colors[0] = load["Abzynt - Config"]["Clr Team Colors"][0].asFloat(); settings.clr_team_colors[1] = load["Abzynt - Config"]["Clr Team Colors"][1].asFloat(); settings.clr_team_colors[2] = load["Abzynt - Config"]["Clr Team Colors"][2].asFloat(); settings.triggerbot_key = load["Abzynt - Config"]["Triggerbot Key"].asInt(); settings.autopistol = load["Abzynt - Config"]["Autopistol"].asBool(); settings.fovchanger = load["Abzynt - Config"]["Fovchanger"].asBool(); settings.noflash = load["Abzynt - Config"]["Noflash"].asBool(); settings.fovchanger_amount = load["Abzynt - Config"]["Fovchanger Amount"].asInt(); settings.radarhack = load["Abzynt - Config"]["Radarhack"].asBool(); in.close(); }
41.957447
92
0.677485
patrykkolodziej
4cdfe1d286d6b6ce88b3dabe4b1aa97096b91d33
9,033
cpp
C++
cpp/lib/graph/functional_graph.cpp
KATO-Hiro/atcoder-1
c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2
[ "MIT" ]
null
null
null
cpp/lib/graph/functional_graph.cpp
KATO-Hiro/atcoder-1
c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2
[ "MIT" ]
null
null
null
cpp/lib/graph/functional_graph.cpp
KATO-Hiro/atcoder-1
c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll = long long; // -------------------------------------------------------- #define FOR(i,l,r) for (ll i = (l); i < (r); ++i) #define REP(i,n) FOR(i,0,n) #define BIT(b,i) (((b)>>(i)) & 1) // -------------------------------------------------------- // References: // <https://usaco.guide/CPH.pdf#page=164> // <https://usaco.guide/problems/cses-1160-planets-queries-ii/solution> struct FunctionalGraph { int N, K; vector<pair<int,ll>> f; // 頂点 u から出る有向辺 vector<vector<pair<int,ll>>> Gr; // 逆辺グラフ vector<int> comp; // 頂点 u が属する連結成分の番号 vector<int> root; // 頂点 u が属する木の根(サイクルに属する頂点は自身が根) int cc_id = 0; // 連携成分の番号用 // サイクル vector<int> cycle_length; // i 番目の連結成分に含まれるサイクル長 vector<int> cycle_weight; // i 番目の連結成分に含まれるサイクル総距離 vector<int> cycle_dist_e; // サイクル上の頂点 u における辺数の累積和 vector<ll> cycle_dist_w; // サイクル上の頂点 u における距離の累積和 // 木(複数存在することに注意) vector<vector<int>> parent; // parent[k][u]: 頂点 u から 2^k 回親を辿って到達する頂点 (根を越えたら -1) vector<int> depth; // depth[u] := 頂点 u の根からの深さ vector<ll> dist; // dist[u] := 頂点 u の根からの距離 (パス上の重みの総和) FunctionalGraph(int n) : N(n) { f.resize(N); Gr.resize(N); comp.resize(N,-1); root.resize(N,-1); cycle_dist_e.resize(N,0); cycle_dist_w.resize(N,0); K = 1; while ((1<<K) <= N) { K++; } parent.resize(K, vector<int>(N)); depth.resize(N); dist.resize(N,0); } void add_edge(int u, int v, ll w) { assert(0 <= u && u < N); assert(0 <= v && v < N); f[u] = {v, w}; Gr[v].push_back({u, w}); } // Functional Graph におけるサイクル検出 (Floyd's cycle-finding algorithm) // (サイクルに属する頂点の一つ, サイクル長) のペアを返す pair<int,int> _cycle_detection(int x) { int a = f[x].first; int b = f[f[x].first].first; while (a != b) { a = f[a].first; b = f[f[b].first].first; } b = f[a].first; int length = 1; while (a != b) { b = f[b].first; length++; } return make_pair(a, length); } void build() { // 連結成分分解とサイクル検出 for (int s = 0; s < N; s++) if (root[s] == -1) { // サイクル検出 auto [x, length] = _cycle_detection(s); cycle_length.push_back(length); // サイクル上の頂点をチェック int r = x; for (int i = 0; i < length; i++) { root[r] = r; r = f[r].first; } // 木上の頂点をチェック r = x; ll sum_w = 0; for (int i = 0; i < length; i++) { auto dfs = [&](auto self, int u) -> void { root[u] = r; comp[u] = cc_id; for (auto [v, _] : Gr[u]) if (root[v] == -1) { self(self, v); } }; dfs(dfs, r); sum_w += f[r].second; r = f[r].first; cycle_dist_w[r] = sum_w; cycle_dist_e[r] = i + 1; } cc_id++; cycle_weight.push_back(sum_w); } // 木の初期化 for (int r = 0; r < N; r++) if (root[r] == r) { auto dfs = [&](auto self, int u, int p, int d, ll sum_w) -> void { parent[0][u] = p; depth[u] = d; dist[u] = sum_w; for (auto [v, w] : Gr[u]) if (u != v && root[v] == r) { self(self, v, u, d+1, sum_w + w); } }; dfs(dfs, r, -1, 0, 0); } // ダブリング (木に属する頂点のみ対象) for (int k = 1; k < K; k++) { for (int u = 0; u < N; u++) { if (parent[k-1][u] < 0) { parent[k][u] = -1; } else { parent[k][u] = parent[k-1][parent[k-1][u]]; } } } } // 連結成分ごとの頂点リストを返す vector<vector<int>> groups() { vector<vector<int>> g(cc_id); for (int u = 0; u < N; u++) { g[comp[u]].push_back(u); } return g; } // 頂点 u がサイクルに属しているか判定(木の根もサイクルに属するとみなされる) bool on_cycle(int u) { assert(0 <= u && u < N); return (root[u] == u); } // 頂点 u, v が同じ連結成分に属しているか判定 bool same_comp(int u, int v) { assert(0 <= u && u < N); assert(0 <= v && v < N); return (comp[u] == comp[v]); } // 頂点 u, v が同じ木に属しているか判定 bool same_tree(int u, int v) { assert(0 <= u && u < N); assert(0 <= v && v < N); return (root[u] == root[v]); } // 頂点 u, v が同じサイクルに属しているか判定 bool same_cycle(int u, int v) { assert(0 <= u && u < N); assert(0 <= v && v < N); return (same_comp(u, v) && on_cycle(u) && on_cycle(v)); } // 頂点 u から深さ d だけ親を辿る (level-ancestor) // 辿った先が木上にあることを想定している // - d <= depth[u] int la(int u, int d) { assert(0 <= u && u < N); for (int k = K-1; 0 <= k; k--) if (BIT(d, k)) { u = parent[k][u]; } return u; } // 頂点 u, v の LCA // 同じ木に属することを想定している // - same_tree(u, v) == true int lca(int u, int v) { assert(0 <= u && u < N); assert(0 <= v && v < N); if (depth[u] < depth[v]) swap(u, v); // depth[u] >= depth[v] u = la(u, depth[u] - depth[v]); // (u, v) の深さを揃える if (u == v) return u; for (int k = K-1; 0 <= k; k--) { if (parent[k][u] != parent[k][v]) { u = parent[k][u]; v = parent[k][v]; } } return parent[0][u]; } // (u -> v) パス間の辺数 // パスが存在しない場合は -1 を返す int distance_e(int u, int v) { assert(0 <= u && u < N); assert(0 <= v && v < N); if (!same_comp(u, v)) return -1; // 連結成分が異なる場合は到達不可能 int res = 0; if (same_tree(u, v)) { // 同じ木に属する res = (lca(u, v) == v ? _distance_e_tree(u, v) : -1); } else if (on_cycle(u) && on_cycle(v)) { // 同じサイクルに属する res = _distance_e_cycle(u, v); } else if (!on_cycle(u) && on_cycle(v)) { // 木からサイクルへ res = _distance_e_tree(u, root[u]) + _distance_e_cycle(root[u], v); } else if (on_cycle(u) && !on_cycle(v)) { // サイクルから木へ res = -1; } else if (!on_cycle(u) && !on_cycle(v)) { // 別々の木に属する res = -1; } else { assert(false); } return res; } // (u -> v) パス間の距離 // パスが存在しない場合は -1 を返す ll distance_w(int u, int v) { assert(0 <= u && u < N); assert(0 <= v && v < N); if (!same_comp(u, v)) return -1; // 連結成分が異なる場合は到達不可能 ll res = 0; if (same_tree(u, v)) { // 同じ木に属する res = (lca(u, v) == v ? _distance_w_tree(u, v) : -1); } else if (on_cycle(u) && on_cycle(v)) { // 同じサイクルに属する res = _distance_w_cycle(u, v); } else if (!on_cycle(u) && on_cycle(v)) { // 木からサイクルへ res = _distance_w_tree(u, root[u]) + _distance_w_cycle(root[u], v); } else if (on_cycle(u) && !on_cycle(v)) { // サイクルから木へ res = -1; } else if (!on_cycle(u) && !on_cycle(v)) { // 別々の木に属する res = -1; } else { assert(false); } return res; } // 木における (u -> v) パス間の辺数 // パスが存在することを想定している // - same_tree(u, v) == true // - lca(u, v) == v int _distance_e_tree(int u, int v) { assert(0 <= u && u < N); assert(0 <= v && v < N); return depth[u] - depth[v]; } // サイクルにおける (u -> v) パス間の辺数 // パスが存在することを想定している // - same_cycle(u, v) == true int _distance_e_cycle(int u, int v) { assert(0 <= u && u < N); assert(0 <= v && v < N); int length = cycle_length[comp[u]]; return (cycle_dist_e[v] - cycle_dist_e[u] + length) % length; } // 木における (u -> v) パス間の距離 // パスが存在することを想定している // - same_tree(u, v) == true // - lca(u, v) == v ll _distance_w_tree(int u, int v) { assert(0 <= u && u < N); assert(0 <= v && v < N); return dist[u] - dist[v]; } // サイクルにおける (u -> v) パス間の距離 // パスが存在することを想定している // - same_cycle(u, v) == true ll _distance_w_cycle(int u, int v) { assert(0 <= u && u < N); assert(0 <= v && v < N); ll weight = cycle_weight[comp[u]]; return (cycle_dist_w[v] - cycle_dist_w[u] + weight) % weight; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout << fixed << setprecision(15); ll N, Q; cin >> N >> Q; FunctionalGraph fg(N); REP(u,N) { ll v; cin >> v; v--; fg.add_edge(u, v, 1); } fg.build(); while (Q--) { ll a, b; cin >> a >> b; a--; b--; ll ans = fg.distance_e(a, b); cout << ans << '\n'; } return 0; } // Verify: https://cses.fi/problemset/task/1160
28.951923
86
0.435736
KATO-Hiro
4ce2aac2db35d7c362099463fc83d8e3ab73049c
52,453
cpp
C++
syn/core/grm_parser.cpp
asmwarrior/syncpp
df34b95b308d7f2e6479087d629017efa7ab9f1f
[ "Apache-2.0" ]
1
2019-02-08T02:23:56.000Z
2019-02-08T02:23:56.000Z
syn/core/grm_parser.cpp
asmwarrior/syncpp
df34b95b308d7f2e6479087d629017efa7ab9f1f
[ "Apache-2.0" ]
null
null
null
syn/core/grm_parser.cpp
asmwarrior/syncpp
df34b95b308d7f2e6479087d629017efa7ab9f1f
[ "Apache-2.0" ]
1
2020-12-02T02:37:40.000Z
2020-12-02T02:37:40.000Z
/* * Copyright 2014 Anton Karmanov * * 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. */ //Grammar Parser implementation. #include <algorithm> #include <cctype> #include <fstream> #include <iostream> #include <iterator> #include <map> #include <sstream> #include <stdexcept> #include <string> #include <vector> #include "bnf.h" #include "commons.h" #include "syn.h" #include "ebnf__imp.h" #include "grm_parser.h" #include "grm_parser_impl.h" #include "lrtables.h" #include "raw_bnf.h" #include "util.h" #include "util_mptr.h" namespace ns = synbin; namespace ebnf = ns::ebnf; namespace prs = ns::grm_parser; namespace raw = ns::raw_bnf; namespace util = ns::util; using std::unique_ptr; using util::MPtr; using util::MContainer; using util::MHeap; using util::MRoot; using syn::ProductionStack; // //GrammarParsingResult // ns::GrammarParsingResult::GrammarParsingResult( unique_ptr<MRoot<ebnf::Grammar>> grammar_root, unique_ptr<MHeap> const_heap) : m_grammar_root(std::move(grammar_root)), m_const_heap(std::move(const_heap)) {} MPtr<ebnf::Grammar> ns::GrammarParsingResult::get_grammar() const { return m_grammar_root->ptr(); } MHeap* ns::GrammarParsingResult::get_const_heap() const { return m_const_heap.get(); } // //(Parser code) // namespace { using syn::Shift; using syn::Goto; using syn::Reduce; using syn::State; class ActionContext; //typedef ActionResult (ActionContext::*SyntaxAction)(ProductionResult& pr); enum class SyntaxRule; //A derived class is used instead of typedef to avoid "decorated name length exceeded..." warning. class RawTraits : public ns::BnfTraits<raw::NullType, prs::Tokens::E, SyntaxRule>{}; typedef ns::LRTables<RawTraits> LRTbl; typedef LRTbl::State LRState; typedef LRTbl::Shift LRShift; typedef LRTbl::Goto LRGoto; typedef raw::RawBnfParser<RawTraits> RawPrs; typedef RawPrs::RawTr RawTr; typedef RawPrs::RawRule RawRule; typedef ns::BnfGrammar<RawTraits> BnfGrm; // //SyntaxRule // enum class SyntaxRule { NONE, Grammar__DeclarationList, DeclarationList__Declaration, DeclarationList__DeclarationList_Declaration, Declaration__TypeDeclaration, Declaration__TerminalDeclaration, Declaration__NonterminalDeclaration, Declaration__CustomTerminalTypeDeclaration, TypeDeclaration__KWTYPE_NAME_CHSEMICOLON, TerminalDeclaration__KWTOKEN_NAME_TypeOpt_CHSEMICOLON, NonterminalDeclaration__AtOpt_NAME_TypeOpt_CHCOLON_SyntaxOrExpression_CHSEMICOLON, CustomTerminalTypeDeclaration__KWTOKEN_STRING_Type_CHSEMICOLON, AtOpt__CHAT, AtOpt__, TypeOpt__Type, TypeOpt__, Type__CHOBRACE_NAME_CHCBRACE, SyntaxOrExpression__SyntaxAndExpressionList, SyntaxAndExpressionList__SyntaxAndExpression, SyntaxAndExpressionList__SyntaxAndExpressionList_CHOR_SyntaxAndExpression, SyntaxAndExpression__SyntaxElementListOpt_TypeOpt, SyntaxElementListOpt__SyntaxElementList, SyntaxElementListOpt__, SyntaxElementList__SyntaxElement, SyntaxElementList__SyntaxElementList_SyntaxElement, SyntaxElement__NameSyntaxElement, SyntaxElement__ThisSyntaxElement, NameSyntaxElement__NAME_CHEQ_SyntaxTerm, NameSyntaxElement__SyntaxTerm, ThisSyntaxElement__KWTHIS_CHEQ_SyntaxTerm, SyntaxTerm__PrimarySyntaxTerm, SyntaxTerm__AdvanvedSyntaxTerm, PrimarySyntaxTerm__NameSyntaxTerm, PrimarySyntaxTerm__StringSyntaxTerm, PrimarySyntaxTerm__NestedSyntaxTerm, NameSyntaxTerm__NAME, StringSyntaxTerm__STRING, NestedSyntaxTerm__TypeOpt_CHOPAREN_SyntaxOrExpression_CHCPAREN, AdvanvedSyntaxTerm__ZeroOneSyntaxTerm, AdvanvedSyntaxTerm__ZeroManySyntaxTerm, AdvanvedSyntaxTerm__OneManySyntaxTerm, AdvanvedSyntaxTerm__ConstSyntaxTerm, ZeroOneSyntaxTerm__PrimarySyntaxTerm_CHQUESTION, ZeroManySyntaxTerm__LoopBody_CHASTERISK, OneManySyntaxTerm__LoopBody_CHPLUS, LoopBody__SimpleLoopBody, LoopBody__AdvancedLoopBody, SimpleLoopBody__PrimarySyntaxTerm, AdvancedLoopBody__CHOPAREN_SyntaxOrExpression_CHCOLON_SyntaxOrExpression_CHCPAREN, AdvancedLoopBody__CHOPAREN_SyntaxOrExpression_CHCPAREN, ConstSyntaxTerm__CHLT_ConstExpression_CHGT, ConstExpression__IntegerConstExpression, ConstExpression__StringConstExpression, ConstExpression__BooleanConstExpression, ConstExpression__NativeConstExpression, IntegerConstExpression__NUMBER, StringConstExpression__STRING, BooleanConstExpression__KWFALSE, BooleanConstExpression__KWTRUE, NativeConstExpression__NativeQualificationOpt_NativeName_NativeReferencesOpt, NativeQualificationOpt__NativeQualification, NativeQualificationOpt__, NativeQualification__NAME_CHCOLONCOLON, NativeQualification__NativeQualification_NAME_CHCOLONCOLON, NativeReferencesOpt__NativeReferences, NativeReferencesOpt__, NativeReferences__NativeReference, NativeReferences__NativeReferences_NativeReference, NativeName__NativeVariableName, NativeName__NativeFunctionName, NativeVariableName__NAME, NativeFunctionName__NAME_CHOPAREN_ConstExpressionListOpt_CHCPAREN, ConstExpressionListOpt__ConstExpressionList, ConstExpressionListOpt__, ConstExpressionList__ConstExpression, ConstExpressionList__ConstExpressionList_CHCOMMA_ConstExpression, NativeReference__CHDOT_NativeName, NativeReference__CHMINUSGT_NativeName, LAST }; const syn::InternalAction ACTION_FIRST = static_cast<syn::InternalAction>(SyntaxRule::NONE); const syn::InternalAction ACTION_LAST = static_cast<syn::InternalAction>(SyntaxRule::LAST); // //ActionContext // class ActionContext { NONCOPYABLE(ActionContext); MHeap* const m_managed_heap; const MPtr<MContainer<ebnf::Object>> m_managed_container; MHeap* const m_const_managed_heap; const MPtr<MContainer<ebnf::Object>> m_const_managed_container; std::vector<const syn::StackElement*> m_stack_vector; template<class T> MPtr<T> manage(T* object) { return m_managed_container->add(object); } template<class T> MPtr<T> manage_spec(T* value) { return m_managed_heap->add_object(value); } template<class T> MPtr<T> manage_const(T* value) { return m_const_managed_container->add(value); } template<class T> MPtr<T> manage_const_spec(T* value) { return m_const_managed_heap->add_object(value); } private: static SyntaxRule syntax_rule(const syn::StackElement_Nt* nt) { syn::InternalAction action = nt->action(); if (action <= ACTION_FIRST || action >= ACTION_LAST) { throw std::logic_error("syntax_rule(): Illegal state"); } return static_cast<SyntaxRule>(action); } static std::exception illegal_state() { throw std::logic_error("illegal state"); } static bool is_rule(const ProductionStack& stack, SyntaxRule rule, std::size_t len) { if (rule != syntax_rule(stack.get_nt())) return false; if (len != stack.size()) throw illegal_state(); return true; } static void check_rule(const ProductionStack& stack, SyntaxRule rule, std::size_t len) { if (!is_rule(stack, rule, len)) throw illegal_state(); } static ns::FilePos tk_pos(const syn::StackElement* node) { const syn::StackElement_Value* val = node->as_value(); return *static_cast<const ns::FilePos*>(val->value()); } static ns::syntax_number tk_number(const syn::StackElement* node) { const syn::StackElement_Value* val = node->as_value(); return *static_cast<const ns::syntax_number*>(val->value()); } static ns::syntax_string tk_string(const syn::StackElement* node) { const syn::StackElement_Value* val = node->as_value(); return *static_cast<const ns::syntax_string*>(val->value()); } public: ActionContext(MHeap* managed_heap, MHeap* const_managed_heap) : m_managed_heap(managed_heap), m_managed_container(managed_heap->create_container<ebnf::Object>()), m_const_managed_heap(const_managed_heap), m_const_managed_container(const_managed_heap->create_container<ebnf::Object>()) {} private: typedef std::vector<MPtr<ebnf::Declaration>> DeclVector; typedef std::vector<MPtr<ebnf::SyntaxExpression>> SyntaxExprVector; typedef std::vector<MPtr<const ebnf::ConstExpression>> ConstExprVector; typedef std::vector<MPtr<const ebnf::NativeReference>> NativeRefVector; typedef std::vector<ns::syntax_string> StrVector; MPtr<ebnf::RawType> nt_Type(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::Type__CHOBRACE_NAME_CHCBRACE, 3); ns::syntax_string name = tk_string(stack[1]); return manage(new ebnf::RawType(name)); } MPtr<ebnf::RawType> nt_TypeOpt(const syn::StackElement* node) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::TypeOpt__Type == rule) { assert(1 == stack.size()); return nt_Type(stack[0]); } else if (SyntaxRule::TypeOpt__ == rule) { assert(0 == stack.size()); return MPtr<ebnf::RawType>(); } else { throw illegal_state(); } } MPtr<ebnf::IntegerConstExpression> nt_IntegerConstExpression(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::IntegerConstExpression__NUMBER, 1); const ns::syntax_number number = tk_number(stack[0]); return manage_const(new ebnf::IntegerConstExpression(number)); } MPtr<ebnf::StringConstExpression> nt_StringConstExpression(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::StringConstExpression__STRING, 1); ns::syntax_string string = tk_string(stack[0]); return manage_const(new ebnf::StringConstExpression(string)); } MPtr<ebnf::BooleanConstExpression> nt_BooleanConstExpression(const syn::StackElement* node) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); assert(1 == stack.size()); bool value; const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::BooleanConstExpression__KWTRUE == rule) { value = true; } else if (SyntaxRule::BooleanConstExpression__KWFALSE == rule) { value = false; } else { throw illegal_state(); } return manage_const(new ebnf::BooleanConstExpression(value)); } void nt_NativeQualification(const syn::StackElement* node, MPtr<StrVector> lst) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::NativeQualification__NAME_CHCOLONCOLON == rule) { assert(2 == stack.size()); lst->push_back(tk_string(stack[0])); } else if (SyntaxRule::NativeQualification__NativeQualification_NAME_CHCOLONCOLON == rule) { assert(3 == stack.size()); nt_NativeQualification(stack[0], lst); lst->push_back(tk_string(stack[1])); } else { throw illegal_state(); } } MPtr<const StrVector> nt_NativeQualificationOpt(const syn::StackElement* node) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); MPtr<StrVector> lst = manage_const_spec(new StrVector()); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::NativeQualificationOpt__NativeQualification == rule) { assert(1 == stack.size()); nt_NativeQualification(stack[0], lst); } else if (SyntaxRule::NativeQualificationOpt__ == rule) { assert(0 == stack.size()); } else { throw illegal_state(); } return lst; } MPtr<ebnf::NativeReference> nt_NativeReference(const syn::StackElement* node) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::NativeReference__CHDOT_NativeName == rule) { assert(2 == stack.size()); MPtr<const ebnf::NativeName> name = nt_NativeName(stack[1]); return manage_const(new ebnf::NativeReferenceReference(name)); } else if (SyntaxRule::NativeReference__CHMINUSGT_NativeName == rule) { assert(2 == stack.size()); MPtr<const ebnf::NativeName> name = nt_NativeName(stack[1]); return manage_const(new ebnf::NativePointerReference(name)); } else { throw illegal_state(); } } void nt_NativeReferences(const syn::StackElement* node, MPtr<NativeRefVector> lst) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::NativeReferences__NativeReference == rule) { assert(1 == stack.size()); lst->push_back(nt_NativeReference(stack[0])); } else if (SyntaxRule::NativeReferences__NativeReferences_NativeReference == rule) { assert(3 == stack.size()); nt_NativeReferences(stack[0], lst); lst->push_back(nt_NativeReference(stack[2])); } else { throw illegal_state(); } } MPtr<const NativeRefVector> nt_NativeReferencesOpt(const syn::StackElement* node) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); MPtr<NativeRefVector> lst = manage_const_spec(new NativeRefVector()); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::NativeReferencesOpt__NativeReferences == rule) { assert(1 == stack.size()); nt_NativeReferences(stack[0], lst); } else if (SyntaxRule::NativeReferencesOpt__ == rule) { assert(0 == stack.size()); } else { throw illegal_state(); } return lst; } MPtr<ebnf::NativeVariableName> nt_NativeVariableName(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::NativeVariableName__NAME, 1); const ns::syntax_string name = tk_string(stack[0]); return manage_const(new ebnf::NativeVariableName(name)); } MPtr<ebnf::NativeFunctionName> nt_NativeFunctionName(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::NativeFunctionName__NAME_CHOPAREN_ConstExpressionListOpt_CHCPAREN, 4); const ns::syntax_string name = tk_string(stack[0]); MPtr<const ConstExprVector> expressions = nt_ConstExpressionListOpt(stack[2]); return manage_const(new ebnf::NativeFunctionName(name, expressions)); } MPtr<ebnf::NativeName> nt_NativeName(const syn::StackElement* node) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); assert(1 == stack.size()); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::NativeName__NativeVariableName == rule) { return nt_NativeVariableName(stack[0]); } else if (SyntaxRule::NativeName__NativeFunctionName == rule) { return nt_NativeFunctionName(stack[0]); } else { throw illegal_state(); } } void nt_ConstExpressionList(const syn::StackElement* node, MPtr<ConstExprVector> lst) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::ConstExpressionList__ConstExpression == rule) { assert(1 == stack.size()); lst->push_back(nt_ConstExpression(stack[0])); } else if (SyntaxRule::ConstExpressionList__ConstExpressionList_CHCOMMA_ConstExpression == rule) { assert(3 == stack.size()); nt_ConstExpressionList(stack[0], lst); lst->push_back(nt_ConstExpression(stack[2])); } else { throw illegal_state(); } } MPtr<const ConstExprVector> nt_ConstExpressionListOpt(const syn::StackElement* node) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); MPtr<ConstExprVector> lst = manage_const_spec(new ConstExprVector()); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::ConstExpressionListOpt__ConstExpressionList == rule) { assert(1 == stack.size()); nt_ConstExpressionList(stack[0], lst); } else if (SyntaxRule::ConstExpressionListOpt__ == rule) { assert(0 == stack.size()); } else { throw illegal_state(); } return lst; } MPtr<ebnf::NativeConstExpression> nt_NativeConstExpression(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::NativeConstExpression__NativeQualificationOpt_NativeName_NativeReferencesOpt, 3); MPtr<const StrVector> qualifications = nt_NativeQualificationOpt(stack[0]); MPtr<const ebnf::NativeName> name = nt_NativeName(stack[1]); MPtr<const NativeRefVector> references = nt_NativeReferencesOpt(stack[2]); return manage_const(new ebnf::NativeConstExpression(qualifications, name, references)); } MPtr<ebnf::ConstExpression> nt_ConstExpression(const syn::StackElement* node) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); assert(1 == stack.size()); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::ConstExpression__IntegerConstExpression == rule) { return nt_IntegerConstExpression(stack[0]); } else if (SyntaxRule::ConstExpression__StringConstExpression == rule) { return nt_StringConstExpression(stack[0]); } else if (SyntaxRule::ConstExpression__BooleanConstExpression == rule) { return nt_BooleanConstExpression(stack[0]); } else if (SyntaxRule::ConstExpression__NativeConstExpression == rule) { return nt_NativeConstExpression(stack[0]); } else { throw illegal_state(); } } MPtr<ebnf::NameSyntaxExpression> nt_NameSyntaxTerm(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::NameSyntaxTerm__NAME, 1); ns::syntax_string name = tk_string(stack[0]); return manage(new ebnf::NameSyntaxExpression(name)); } MPtr<ebnf::StringSyntaxExpression> nt_StringSyntaxTerm(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::StringSyntaxTerm__STRING, 1); ns::syntax_string name = tk_string(stack[0]); return manage(new ebnf::StringSyntaxExpression(name)); } MPtr<ebnf::SyntaxExpression> nt_NestedSyntaxTerm(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::NestedSyntaxTerm__TypeOpt_CHOPAREN_SyntaxOrExpression_CHCPAREN, 4); MPtr<const ebnf::RawType> type = nt_TypeOpt(stack[0]); MPtr<ebnf::SyntaxExpression> expression = nt_SyntaxOrExpression(stack[2]); if (type.get()) expression = manage(new ebnf::CastSyntaxExpression(type, expression)); return expression; } MPtr<ebnf::SyntaxExpression> nt_PrimarySyntaxTerm(const syn::StackElement* node) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); assert(1 == stack.size()); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::PrimarySyntaxTerm__NameSyntaxTerm == rule) { return nt_NameSyntaxTerm(stack[0]); } else if (SyntaxRule::PrimarySyntaxTerm__StringSyntaxTerm == rule) { return nt_StringSyntaxTerm(stack[0]); } else if (SyntaxRule::PrimarySyntaxTerm__NestedSyntaxTerm == rule) { return nt_NestedSyntaxTerm(stack[0]); } else { throw illegal_state(); } } MPtr<ebnf::SyntaxExpression> nt_ZeroOneSyntaxTerm(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::ZeroOneSyntaxTerm__PrimarySyntaxTerm_CHQUESTION, 2); MPtr<ebnf::SyntaxExpression> sub_expression = nt_PrimarySyntaxTerm(stack[0]); return manage(new ebnf::ZeroOneSyntaxExpression(sub_expression)); } MPtr<ebnf::LoopBody> nt_SimpleLoopBody(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::SimpleLoopBody__PrimarySyntaxTerm, 1); MPtr<ebnf::SyntaxExpression> expression = nt_PrimarySyntaxTerm(stack[0]); return manage(new ebnf::LoopBody(expression, MPtr<ebnf::SyntaxExpression>(), ns::FilePos())); } MPtr<ebnf::LoopBody> nt_AdvancedLoopBody(const syn::StackElement* node) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::AdvancedLoopBody__CHOPAREN_SyntaxOrExpression_CHCOLON_SyntaxOrExpression_CHCPAREN == rule) { assert(5 == stack.size()); MPtr<ebnf::SyntaxExpression> expression = nt_SyntaxOrExpression(stack[1]); ns::FilePos separator_pos = tk_pos(stack[2]); MPtr<ebnf::SyntaxExpression> separator = nt_SyntaxOrExpression(stack[3]); return manage(new ebnf::LoopBody(expression, separator, separator_pos)); } else if (SyntaxRule::AdvancedLoopBody__CHOPAREN_SyntaxOrExpression_CHCPAREN == rule) { assert(3 == stack.size()); MPtr<ebnf::SyntaxExpression> expression = nt_SyntaxOrExpression(stack[1]); return manage(new ebnf::LoopBody(expression, MPtr<ebnf::SyntaxExpression>(), ns::FilePos())); } else { throw illegal_state(); } } MPtr<ebnf::LoopBody> nt_LoopBody(const syn::StackElement* node) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); assert(1 == stack.size()); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::LoopBody__SimpleLoopBody == rule) { return nt_SimpleLoopBody(stack[0]); } else if (SyntaxRule::LoopBody__AdvancedLoopBody == rule) { return nt_AdvancedLoopBody(stack[0]); } else { throw illegal_state(); } } MPtr<ebnf::ZeroManySyntaxExpression> nt_ZeroManySyntaxTerm(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::ZeroManySyntaxTerm__LoopBody_CHASTERISK, 2); MPtr<ebnf::LoopBody> body = nt_LoopBody(stack[0]); return manage(new ebnf::ZeroManySyntaxExpression(body)); } MPtr<ebnf::OneManySyntaxExpression> nt_OneManySyntaxTerm(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::OneManySyntaxTerm__LoopBody_CHPLUS, 2); MPtr<ebnf::LoopBody> body = nt_LoopBody(stack[0]); return manage(new ebnf::OneManySyntaxExpression(body)); } MPtr<ebnf::ConstSyntaxExpression> nt_ConstSyntaxTerm(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::ConstSyntaxTerm__CHLT_ConstExpression_CHGT, 3); MPtr<const ebnf::ConstExpression> const_expression = nt_ConstExpression(stack[1]); return manage(new ebnf::ConstSyntaxExpression(const_expression)); } MPtr<ebnf::SyntaxExpression> nt_AdvanvedSyntaxTerm(const syn::StackElement* node) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); assert(1 == stack.size()); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::AdvanvedSyntaxTerm__ZeroOneSyntaxTerm == rule) { return nt_ZeroOneSyntaxTerm(stack[0]); } else if (SyntaxRule::AdvanvedSyntaxTerm__ZeroManySyntaxTerm == rule) { return nt_ZeroManySyntaxTerm(stack[0]); } else if (SyntaxRule::AdvanvedSyntaxTerm__OneManySyntaxTerm == rule) { return nt_OneManySyntaxTerm(stack[0]); } else if (SyntaxRule::AdvanvedSyntaxTerm__ConstSyntaxTerm == rule) { return nt_ConstSyntaxTerm(stack[0]); } else { throw illegal_state(); } } MPtr<ebnf::SyntaxExpression> nt_SyntaxTerm(const syn::StackElement* node) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); assert(1 == stack.size()); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::SyntaxTerm__PrimarySyntaxTerm == rule) { return nt_PrimarySyntaxTerm(stack[0]); } else if (SyntaxRule::SyntaxTerm__AdvanvedSyntaxTerm == rule) { return nt_AdvanvedSyntaxTerm(stack[0]); } else { throw illegal_state(); } } MPtr<ebnf::SyntaxExpression> nt_NameSyntaxElement(const syn::StackElement* node) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::NameSyntaxElement__NAME_CHEQ_SyntaxTerm == rule) { assert(3 == stack.size()); const ns::syntax_string name = tk_string(stack[0]); MPtr<ebnf::SyntaxExpression> expression = nt_SyntaxTerm(stack[2]); return manage(new ebnf::NameSyntaxElement(expression, name)); } else if (SyntaxRule::NameSyntaxElement__SyntaxTerm == rule) { assert(1 == stack.size()); return nt_SyntaxTerm(stack[0]); } else { throw illegal_state(); } } MPtr<ebnf::ThisSyntaxElement> nt_ThisSyntaxElement(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::ThisSyntaxElement__KWTHIS_CHEQ_SyntaxTerm, 3); ns::FilePos pos = tk_pos(stack[0]); MPtr<ebnf::SyntaxExpression> expression = nt_SyntaxTerm(stack[2]); return manage(new ebnf::ThisSyntaxElement(pos, expression)); } MPtr<ebnf::SyntaxExpression> nt_SyntaxElement(const syn::StackElement* node) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); assert(1 == stack.size()); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::SyntaxElement__NameSyntaxElement == rule) { return nt_NameSyntaxElement(stack[0]); } else if (SyntaxRule::SyntaxElement__ThisSyntaxElement == rule) { return nt_ThisSyntaxElement(stack[0]); } else { throw illegal_state(); } } void nt_SyntaxElementList(const syn::StackElement* node, MPtr<SyntaxExprVector> lst) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::SyntaxElementList__SyntaxElement == rule) { assert(1 == stack.size()); lst->push_back(nt_SyntaxElement(stack[0])); } else if (SyntaxRule::SyntaxElementList__SyntaxElementList_SyntaxElement == rule) { assert(2 == stack.size()); nt_SyntaxElementList(stack[0], lst); lst->push_back(nt_SyntaxElement(stack[1])); } else { throw illegal_state(); } } MPtr<SyntaxExprVector> nt_SyntaxElementListOpt(const syn::StackElement* node) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); MPtr<SyntaxExprVector> lst = manage_const_spec(new SyntaxExprVector()); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::SyntaxElementListOpt__SyntaxElementList == rule) { assert(1 == stack.size()); nt_SyntaxElementList(stack[0], lst); } else if (SyntaxRule::SyntaxElementListOpt__ == rule) { assert(0 == stack.size()); } else { throw illegal_state(); } return lst; } MPtr<ebnf::SyntaxExpression> nt_SyntaxAndExpression(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::SyntaxAndExpression__SyntaxElementListOpt_TypeOpt, 2); MPtr<SyntaxExprVector> expressions = nt_SyntaxElementListOpt(stack[0]); MPtr<const ebnf::RawType> type = nt_TypeOpt(stack[1]); MPtr<ebnf::SyntaxExpression> expression; if (expressions->empty() && !type.get()) { expression = manage(new ebnf::EmptySyntaxExpression()); } else if (1 == expressions->size() && !type.get()) { SyntaxExprVector& vector = *expressions; MPtr<ebnf::SyntaxExpression> expr = (*expressions)[0]; expression = (*expressions)[0]; expressions->clear(); } else { expression = manage(new ebnf::SyntaxAndExpression(expressions, type)); } return expression; } void nt_SyntaxAndExpressionList(const syn::StackElement* node, MPtr<SyntaxExprVector> lst) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::SyntaxAndExpressionList__SyntaxAndExpression == rule) { assert(1 == stack.size()); lst->push_back(nt_SyntaxAndExpression(stack[0])); } else if (SyntaxRule::SyntaxAndExpressionList__SyntaxAndExpressionList_CHOR_SyntaxAndExpression == rule) { assert(3 == stack.size()); nt_SyntaxAndExpressionList(stack[0], lst); lst->push_back(nt_SyntaxAndExpression(stack[2])); } else { throw illegal_state(); } } MPtr<ebnf::SyntaxExpression> nt_SyntaxOrExpression(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::SyntaxOrExpression__SyntaxAndExpressionList, 1); MPtr<SyntaxExprVector> expressions = manage_const_spec(new SyntaxExprVector()); nt_SyntaxAndExpressionList(stack[0], expressions); MPtr<ebnf::SyntaxExpression> expression; if (expressions->empty()) { expression = manage(new ebnf::EmptySyntaxExpression()); } else if (1 == expressions->size()) { expression = (*expressions)[0]; expressions->clear(); } else { expression = manage(new ebnf::SyntaxOrExpression(expressions)); } return expression; } MPtr<ebnf::TypeDeclaration> nt_TypeDeclaration(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::TypeDeclaration__KWTYPE_NAME_CHSEMICOLON, 3); const ns::syntax_string name = tk_string(stack[1]); return manage(new ebnf::TypeDeclaration(name)); } MPtr<ebnf::TerminalDeclaration> nt_TerminalDeclaration(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::TerminalDeclaration__KWTOKEN_NAME_TypeOpt_CHSEMICOLON, 4); const ns::syntax_string name = tk_string(stack[1]); MPtr<ebnf::RawType> raw_type = nt_TypeOpt(stack[2]); return manage(new ebnf::TerminalDeclaration(name, raw_type)); } bool nt_AtOpt(const syn::StackElement* node) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::AtOpt__CHAT == rule) { assert(1 == stack.size()); return true; } else if (SyntaxRule::AtOpt__ == rule) { assert(0 == stack.size()); return false; } else { throw illegal_state(); } } MPtr<ebnf::NonterminalDeclaration> nt_NonterminalDeclaration(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::NonterminalDeclaration__AtOpt_NAME_TypeOpt_CHCOLON_SyntaxOrExpression_CHSEMICOLON, 6); bool start = nt_AtOpt(stack[0]); const ns::syntax_string name = tk_string(stack[1]); MPtr<const ebnf::RawType> type = nt_TypeOpt(stack[2]); MPtr<ebnf::SyntaxExpression> expression = nt_SyntaxOrExpression(stack[4]); return manage(new ebnf::NonterminalDeclaration(start, name, expression, type)); } MPtr<ebnf::Declaration> nt_CustomTerminalTypeDeclaration(const syn::StackElement* node) { ProductionStack stack(m_stack_vector, node); check_rule(stack, SyntaxRule::CustomTerminalTypeDeclaration__KWTOKEN_STRING_Type_CHSEMICOLON, 4); const ns::syntax_string str = tk_string(stack[1]); MPtr<ebnf::RawType> raw_type = nt_Type(stack[2]); if (str.get_string().str() != "") { throw prs::ParserException("Empty string literal is expected", str.pos()); } return manage(new ebnf::CustomTerminalTypeDeclaration(raw_type)); } MPtr<ebnf::Declaration> nt_Declaration(const syn::StackElement* node) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); assert(1 == stack.size()); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::Declaration__TypeDeclaration == rule) { return nt_TypeDeclaration(stack[0]); } else if (SyntaxRule::Declaration__TerminalDeclaration == rule) { return nt_TerminalDeclaration(stack[0]); } else if (SyntaxRule::Declaration__NonterminalDeclaration == rule) { return nt_NonterminalDeclaration(stack[0]); } else if (SyntaxRule::Declaration__CustomTerminalTypeDeclaration == rule) { return nt_CustomTerminalTypeDeclaration(stack[0]); } else { throw illegal_state(); } } void nt_DeclarationList(const syn::StackElement* node, MPtr<DeclVector> lst) { const syn::StackElement_Nt* nt = node->as_nt(); ProductionStack stack(m_stack_vector, nt); const SyntaxRule rule = syntax_rule(nt); if (SyntaxRule::DeclarationList__Declaration == rule) { assert(1 == stack.size()); lst->push_back(nt_Declaration(stack[0])); } else if (SyntaxRule::DeclarationList__DeclarationList_Declaration == rule) { assert(2 == stack.size()); nt_DeclarationList(stack[0], lst); lst->push_back(nt_Declaration(stack[1])); } else { throw illegal_state(); } } public: MPtr<ebnf::Grammar> nt_Grammar(const syn::StackElement_Nt* nt) { ProductionStack stack(m_stack_vector, nt); check_rule(stack, SyntaxRule::Grammar__DeclarationList, 1); MPtr<DeclVector> declarations = manage_const_spec(new DeclVector()); nt_DeclarationList(stack[0], declarations); return manage(new ebnf::Grammar(declarations)); } }; const RawTr g_raw_tokens[] = { { "NAME", prs::Tokens::NAME }, { "NUMBER", prs::Tokens::NUMBER }, { "STRING", prs::Tokens::STRING }, { "KW_CLASS", prs::Tokens::KW_CLASS }, { "KW_THIS", prs::Tokens::KW_THIS }, { "KW_TOKEN", prs::Tokens::KW_TOKEN }, { "KW_TYPE", prs::Tokens::KW_TYPE }, { "KW_FALSE", prs::Tokens::KW_FALSE }, { "KW_TRUE", prs::Tokens::KW_TRUE }, { "CH_SEMICOLON", prs::Tokens::CH_SEMICOLON }, { "CH_AT", prs::Tokens::CH_AT }, { "CH_COLON", prs::Tokens::CH_COLON }, { "CH_OBRACE", prs::Tokens::CH_OBRACE }, { "CH_CBRACE", prs::Tokens::CH_CBRACE }, { "CH_OR", prs::Tokens::CH_OR }, { "CH_EQ", prs::Tokens::CH_EQ }, { "CH_OPAREN", prs::Tokens::CH_OPAREN }, { "CH_CPAREN", prs::Tokens::CH_CPAREN }, { "CH_QUESTION", prs::Tokens::CH_QUESTION }, { "CH_ASTERISK", prs::Tokens::CH_ASTERISK }, { "CH_PLUS", prs::Tokens::CH_PLUS }, { "CH_LT", prs::Tokens::CH_LT }, { "CH_GT", prs::Tokens::CH_GT }, { "CH_COLON_COLON", prs::Tokens::CH_COLON_COLON }, { "CH_COMMA", prs::Tokens::CH_COMMA }, { "CH_DOT", prs::Tokens::CH_DOT }, { "CH_MINUS_GT", prs::Tokens::CH_MINUS_GT }, { 0, prs::Tokens::E(0) } }; const RawRule g_raw_rules[] = { { "Grammar", SyntaxRule::NONE }, { "DeclarationList", SyntaxRule::Grammar__DeclarationList }, { "DeclarationList", SyntaxRule::NONE }, { "Declaration", SyntaxRule::DeclarationList__Declaration }, { "DeclarationList Declaration", SyntaxRule::DeclarationList__DeclarationList_Declaration }, { "Declaration", SyntaxRule::NONE }, { "TypeDeclaration", SyntaxRule::Declaration__TypeDeclaration }, { "TerminalDeclaration", SyntaxRule::Declaration__TerminalDeclaration }, { "NonterminalDeclaration", SyntaxRule::Declaration__NonterminalDeclaration }, { "CustomTerminalTypeDeclaration", SyntaxRule::Declaration__CustomTerminalTypeDeclaration }, { "TypeDeclaration", SyntaxRule::NONE }, { "KW_TYPE NAME CH_SEMICOLON", SyntaxRule::TypeDeclaration__KWTYPE_NAME_CHSEMICOLON }, { "TerminalDeclaration", SyntaxRule::NONE }, { "KW_TOKEN NAME TypeOpt CH_SEMICOLON", SyntaxRule::TerminalDeclaration__KWTOKEN_NAME_TypeOpt_CHSEMICOLON }, { "NonterminalDeclaration", SyntaxRule::NONE }, { "AtOpt NAME TypeOpt CH_COLON SyntaxOrExpression CH_SEMICOLON", SyntaxRule::NonterminalDeclaration__AtOpt_NAME_TypeOpt_CHCOLON_SyntaxOrExpression_CHSEMICOLON }, { "CustomTerminalTypeDeclaration", SyntaxRule::NONE }, { "KW_TOKEN STRING Type CH_SEMICOLON", SyntaxRule::CustomTerminalTypeDeclaration__KWTOKEN_STRING_Type_CHSEMICOLON }, { "AtOpt", SyntaxRule::NONE }, { "CH_AT", SyntaxRule::AtOpt__CHAT }, { "", SyntaxRule::AtOpt__ }, { "TypeOpt", SyntaxRule::NONE }, { "Type", SyntaxRule::TypeOpt__Type }, { "", SyntaxRule::TypeOpt__ }, { "Type", SyntaxRule::NONE }, { "CH_OBRACE NAME CH_CBRACE", SyntaxRule::Type__CHOBRACE_NAME_CHCBRACE }, { "SyntaxOrExpression", SyntaxRule::NONE }, { "SyntaxAndExpressionList", SyntaxRule::SyntaxOrExpression__SyntaxAndExpressionList }, { "SyntaxAndExpressionList", SyntaxRule::NONE }, { "SyntaxAndExpression", SyntaxRule::SyntaxAndExpressionList__SyntaxAndExpression }, { "SyntaxAndExpressionList CH_OR SyntaxAndExpression", SyntaxRule::SyntaxAndExpressionList__SyntaxAndExpressionList_CHOR_SyntaxAndExpression }, { "SyntaxAndExpression", SyntaxRule::NONE }, { "SyntaxElementListOpt TypeOpt", SyntaxRule::SyntaxAndExpression__SyntaxElementListOpt_TypeOpt }, { "SyntaxElementListOpt", SyntaxRule::NONE }, { "SyntaxElementList", SyntaxRule::SyntaxElementListOpt__SyntaxElementList }, { "", SyntaxRule::SyntaxElementListOpt__ }, { "SyntaxElementList", SyntaxRule::NONE }, { "SyntaxElement", SyntaxRule::SyntaxElementList__SyntaxElement }, { "SyntaxElementList SyntaxElement", SyntaxRule::SyntaxElementList__SyntaxElementList_SyntaxElement }, { "SyntaxElement", SyntaxRule::NONE }, { "NameSyntaxElement", SyntaxRule::SyntaxElement__NameSyntaxElement }, { "ThisSyntaxElement", SyntaxRule::SyntaxElement__ThisSyntaxElement }, { "NameSyntaxElement", SyntaxRule::NONE }, { "NAME CH_EQ SyntaxTerm", SyntaxRule::NameSyntaxElement__NAME_CHEQ_SyntaxTerm }, { "SyntaxTerm", SyntaxRule::NameSyntaxElement__SyntaxTerm }, { "ThisSyntaxElement", SyntaxRule::NONE }, { "KW_THIS CH_EQ SyntaxTerm", SyntaxRule::ThisSyntaxElement__KWTHIS_CHEQ_SyntaxTerm }, { "SyntaxTerm", SyntaxRule::NONE }, { "PrimarySyntaxTerm", SyntaxRule::SyntaxTerm__PrimarySyntaxTerm }, { "AdvanvedSyntaxTerm", SyntaxRule::SyntaxTerm__AdvanvedSyntaxTerm }, { "PrimarySyntaxTerm", SyntaxRule::NONE }, { "NameSyntaxTerm", SyntaxRule::PrimarySyntaxTerm__NameSyntaxTerm }, { "StringSyntaxTerm", SyntaxRule::PrimarySyntaxTerm__StringSyntaxTerm }, { "NestedSyntaxTerm", SyntaxRule::PrimarySyntaxTerm__NestedSyntaxTerm }, { "NameSyntaxTerm", SyntaxRule::NONE }, { "NAME", SyntaxRule::NameSyntaxTerm__NAME }, { "StringSyntaxTerm", SyntaxRule::NONE }, { "STRING", SyntaxRule::StringSyntaxTerm__STRING }, { "NestedSyntaxTerm", SyntaxRule::NONE }, { "TypeOpt CH_OPAREN SyntaxOrExpression CH_CPAREN", SyntaxRule::NestedSyntaxTerm__TypeOpt_CHOPAREN_SyntaxOrExpression_CHCPAREN }, { "AdvanvedSyntaxTerm", SyntaxRule::NONE }, { "ZeroOneSyntaxTerm", SyntaxRule::AdvanvedSyntaxTerm__ZeroOneSyntaxTerm }, { "ZeroManySyntaxTerm", SyntaxRule::AdvanvedSyntaxTerm__ZeroManySyntaxTerm }, { "OneManySyntaxTerm", SyntaxRule::AdvanvedSyntaxTerm__OneManySyntaxTerm }, { "ConstSyntaxTerm", SyntaxRule::AdvanvedSyntaxTerm__ConstSyntaxTerm }, { "ZeroOneSyntaxTerm", SyntaxRule::NONE }, { "PrimarySyntaxTerm CH_QUESTION", SyntaxRule::ZeroOneSyntaxTerm__PrimarySyntaxTerm_CHQUESTION }, { "ZeroManySyntaxTerm", SyntaxRule::NONE }, { "LoopBody CH_ASTERISK", SyntaxRule::ZeroManySyntaxTerm__LoopBody_CHASTERISK }, { "OneManySyntaxTerm", SyntaxRule::NONE }, { "LoopBody CH_PLUS", SyntaxRule::OneManySyntaxTerm__LoopBody_CHPLUS }, { "LoopBody", SyntaxRule::NONE }, { "SimpleLoopBody", SyntaxRule::LoopBody__SimpleLoopBody }, { "AdvancedLoopBody", SyntaxRule::LoopBody__AdvancedLoopBody }, { "SimpleLoopBody", SyntaxRule::NONE }, { "PrimarySyntaxTerm", SyntaxRule::SimpleLoopBody__PrimarySyntaxTerm }, { "AdvancedLoopBody", SyntaxRule::NONE }, { "CH_OPAREN SyntaxOrExpression CH_COLON SyntaxOrExpression CH_CPAREN", SyntaxRule::AdvancedLoopBody__CHOPAREN_SyntaxOrExpression_CHCOLON_SyntaxOrExpression_CHCPAREN }, { "CH_OPAREN SyntaxOrExpression CH_CPAREN", SyntaxRule::AdvancedLoopBody__CHOPAREN_SyntaxOrExpression_CHCPAREN }, { "ConstSyntaxTerm", SyntaxRule::NONE }, { "CH_LT ConstExpression CH_GT", SyntaxRule::ConstSyntaxTerm__CHLT_ConstExpression_CHGT }, { "ConstExpression", SyntaxRule::NONE }, { "IntegerConstExpression", SyntaxRule::ConstExpression__IntegerConstExpression }, { "StringConstExpression", SyntaxRule::ConstExpression__StringConstExpression }, { "BooleanConstExpression", SyntaxRule::ConstExpression__BooleanConstExpression }, { "NativeConstExpression", SyntaxRule::ConstExpression__NativeConstExpression }, { "IntegerConstExpression", SyntaxRule::NONE }, { "NUMBER", SyntaxRule::IntegerConstExpression__NUMBER }, { "StringConstExpression", SyntaxRule::NONE }, { "STRING", SyntaxRule::StringConstExpression__STRING }, { "BooleanConstExpression", SyntaxRule::NONE }, { "KW_FALSE", SyntaxRule::BooleanConstExpression__KWFALSE }, { "KW_TRUE", SyntaxRule::BooleanConstExpression__KWTRUE }, { "NativeConstExpression", SyntaxRule::NONE }, { "NativeQualificationOpt NativeName NativeReferencesOpt", SyntaxRule::NativeConstExpression__NativeQualificationOpt_NativeName_NativeReferencesOpt }, { "NativeQualificationOpt", SyntaxRule::NONE }, { "NativeQualification", SyntaxRule::NativeQualificationOpt__NativeQualification }, { "", SyntaxRule::NativeQualificationOpt__ }, { "NativeQualification", SyntaxRule::NONE }, { "NAME CH_COLON_COLON", SyntaxRule::NativeQualification__NAME_CHCOLONCOLON }, { "NativeQualification NAME CH_COLON_COLON", SyntaxRule::NativeQualification__NativeQualification_NAME_CHCOLONCOLON }, { "NativeReferencesOpt", SyntaxRule::NONE }, { "NativeReferences", SyntaxRule::NativeReferencesOpt__NativeReferences }, { "", SyntaxRule::NativeReferencesOpt__ }, { "NativeReferences", SyntaxRule::NONE }, { "NativeReference", SyntaxRule::NativeReferences__NativeReference }, { "NativeReferences NativeReference", SyntaxRule::NativeReferences__NativeReferences_NativeReference }, { "NativeName", SyntaxRule::NONE }, { "NativeVariableName", SyntaxRule::NativeName__NativeVariableName }, { "NativeFunctionName", SyntaxRule::NativeName__NativeFunctionName }, { "NativeVariableName", SyntaxRule::NONE }, { "NAME", SyntaxRule::NativeVariableName__NAME }, { "NativeFunctionName", SyntaxRule::NONE }, { "NAME CH_OPAREN ConstExpressionListOpt CH_CPAREN", SyntaxRule::NativeFunctionName__NAME_CHOPAREN_ConstExpressionListOpt_CHCPAREN }, { "ConstExpressionListOpt", SyntaxRule::NONE }, { "ConstExpressionList", SyntaxRule::ConstExpressionListOpt__ConstExpressionList }, { "", SyntaxRule::ConstExpressionListOpt__ }, { "ConstExpressionList", SyntaxRule::NONE }, { "ConstExpression", SyntaxRule::ConstExpressionList__ConstExpression }, { "ConstExpressionList CH_COMMA ConstExpression", SyntaxRule::ConstExpressionList__ConstExpressionList_CHCOMMA_ConstExpression }, { "NativeReference", SyntaxRule::NONE }, { "CH_DOT NativeName", SyntaxRule::NativeReference__CHDOT_NativeName }, { "CH_MINUS_GT NativeName", SyntaxRule::NativeReference__CHMINUSGT_NativeName }, { nullptr, SyntaxRule::NONE } }; // //CoreTables // class CoreTables { NONCOPYABLE(CoreTables); std::vector<State> m_states; std::vector<Shift> m_shifts; std::vector<Goto> m_gotos; std::vector<Reduce> m_reduces; State* m_start_state; MHeap m_managed_heap; public: CoreTables( std::vector<State>::size_type state_count, std::vector<Shift>::size_type shift_count, std::vector<Goto>::size_type goto_count, std::vector<Reduce>::size_type reduce_count, const LRState* lr_start_state) : m_states(state_count), m_shifts(shift_count), m_gotos(goto_count), m_reduces(reduce_count) { m_start_state = &m_states[lr_start_state->get_index()]; } std::vector<State>::iterator get_states_begin() { return m_states.begin(); } std::vector<Shift>::iterator get_shifts_begin() { return m_shifts.begin(); } std::vector<Goto>::iterator get_gotos_begin() { return m_gotos.begin(); } std::vector<Reduce>::iterator get_reduces_begin() { return m_reduces.begin(); } const std::vector<State>& get_states() const { return m_states; } const std::vector<Reduce>& get_reduces() const { return m_reduces; } const State* get_start_state() const { return m_start_state; } MHeap& get_managed_heap() { return m_managed_heap; } }; // //TransformShift // class TransformShift : public std::unary_function<const LRShift, Shift> { const std::vector<State>& m_states; public: explicit TransformShift(const std::vector<State>& states) : m_states(states) {} Shift operator()(const LRShift lr_shift) const { Shift core_shift; core_shift.assign(&m_states[lr_shift.get_state()->get_index()], lr_shift.get_tr()->get_tr_obj()); return core_shift; } }; // //TransformGoto // class TransformGoto : public std::unary_function<const LRGoto, Goto> { const std::vector<State>& m_states; public: explicit TransformGoto(const std::vector<State>& states) : m_states(states) {} Goto operator()(const LRGoto lr_goto) const { Goto core_goto; core_goto.assign(&m_states[lr_goto.get_state()->get_index()], lr_goto.get_nt()->get_nt_index()); return core_goto; } }; // //TransformReduce // class TransformReduce : public std::unary_function<const BnfGrm::Pr*, Reduce> { public: TransformReduce(){} Reduce operator()(const BnfGrm::Pr* pr) { Reduce core_reduce; if (pr) { syn::InternalAction action = static_cast<syn::InternalAction>(pr->get_pr_obj()); core_reduce.assign(pr->get_elements().size(), pr->get_nt()->get_nt_index(), action); } else { core_reduce.assign(0, 0, syn::ACCEPT_ACTION); } return core_reduce; } }; // //TransformState // //This class is implemented not like a standard functor, because it has to be used by pointer, not by value. class TransformState { const TransformShift m_transform_shift; const TransformGoto m_transform_goto; const TransformReduce m_transform_reduce; Shift m_null_shift; Goto m_null_goto; Reduce m_null_reduce; std::vector<Shift>::iterator m_shift_it; std::vector<Goto>::iterator m_goto_it; std::vector<Reduce>::iterator m_reduce_it; public: explicit TransformState(CoreTables* core_tables) : m_transform_shift(core_tables->get_states()), m_transform_goto(core_tables->get_states()) { m_null_shift.assign(nullptr, 0); m_null_goto.assign(nullptr, 0); m_null_reduce.assign(0, 0, syn::NULL_ACTION); m_shift_it = core_tables->get_shifts_begin(); m_goto_it = core_tables->get_gotos_begin(); m_reduce_it = core_tables->get_reduces_begin(); } State::SymType get_sym_type(const BnfGrm::Sym* sym) { //If the symbol is NULL, the type does not matter, because this is either a start state, //or a final one (goto by the extended nonterminal), if (!sym) return State::sym_none; if (const BnfGrm::Tr* tr = sym->as_tr()) { prs::Tokens::E token = tr->get_tr_obj(); if (prs::Tokens::NAME == token || prs::Tokens::STRING == token || prs::Tokens::NUMBER == token) { //This set of tokens must correspond to the set of tokens for which a value is created //in InternalScanner. return State::sym_tk_value; } else { return State::sym_none; } } else { //Assuming that if the symbol is not a nonterminal, then it is a terminal. return State::sym_nt; } } State transform(const LRState* lrstate) { State core_state; const BnfGrm::Sym* sym = lrstate->get_sym(); State::SymType sym_type = get_sym_type(sym); bool is_nt = sym && sym->as_nt(); core_state.assign(lrstate->get_index(), &*m_shift_it, &*m_goto_it, &*m_reduce_it, sym_type); m_shift_it = std::transform( lrstate->get_shifts().begin(), lrstate->get_shifts().end(), m_shift_it, m_transform_shift); *m_shift_it++ = m_null_shift; m_goto_it = std::transform( lrstate->get_gotos().begin(), lrstate->get_gotos().end(), m_goto_it, m_transform_goto); *m_goto_it++ = m_null_goto; m_reduce_it = std::transform( lrstate->get_reduces().begin(), lrstate->get_reduces().end(), m_reduce_it, m_transform_reduce); *m_reduce_it++ = m_null_reduce; return core_state; } }; unique_ptr<CoreTables> create_core_tables(const BnfGrm* bnf_grammar, const LRTbl* lrtables) { const std::vector<const LRState*>& lrstates = lrtables->get_states(); //Calculate counts. std::vector<Shift>::size_type shift_count = 0; std::vector<Goto>::size_type goto_count = 0; std::vector<Goto>::size_type reduce_count = 0; for (const LRState* lrstate : lrstates) { shift_count += lrstate->get_shifts().size() + 1; goto_count += lrstate->get_gotos().size() + 1; reduce_count += lrstate->get_reduces().size() + 1; } //Determine start state. //There must be one and only one start state. const LRState* lr_start_state = lrtables->get_start_states()[0].second; //Create empty tables. unique_ptr<CoreTables> core_tables(new CoreTables( lrstates.size(), shift_count, goto_count, reduce_count, lr_start_state)); //Transform states. //Here the function object is not passed directly to std::transform(), because the object must be //used by pointer, not by value (because the object has a state). TransformState transform_state(core_tables.get()); std::transform( lrtables->get_states().begin(), lrtables->get_states().end(), core_tables->get_states_begin(), std::bind1st(std::mem_fun(&TransformState::transform), &transform_state)); return core_tables; } // //InternalScanner // class InternalScanner : public syn::ScannerInterface { NONCOPYABLE(InternalScanner); syn::Pool<ns::FilePos> m_pos_pool; syn::Pool<ns::syntax_number> m_number_pool; syn::Pool<ns::syntax_string> m_string_pool; prs::Scanner& m_scanner; prs::TokenRecord m_token_record; public: InternalScanner( prs::Scanner& scanner) : m_scanner(scanner), m_number_pool(200), m_string_pool(100) {} std::pair<syn::InternalTk, const void*> scan() override { m_scanner.scan_token(&m_token_record); const void* value = nullptr; if (prs::Tokens::NAME == m_token_record.token || prs::Tokens::STRING == m_token_record.token) { value = m_string_pool.allocate(m_token_record.v_string); } else if (prs::Tokens::NUMBER == m_token_record.token) { value = m_number_pool.allocate(m_token_record.v_number); } else { value = m_pos_pool.allocate(ns::FilePos(m_scanner.file_name(), m_token_record.pos)); } return std::make_pair(m_token_record.token, value); } bool fire_syntax_error(const char* message) { throw prs::ParserException(message, ns::FilePos(m_scanner.file_name(), m_token_record.pos)); } }; } // //parse_grammar() // unique_ptr<ns::GrammarParsingResult> prs::parse_grammar(std::istream& in, const util::String& file_name) { //Create BNF grammar. unique_ptr<const BnfGrm> bnf_grammar = RawPrs::raw_grammar_to_bnf(g_raw_tokens, g_raw_rules, SyntaxRule::NONE); //Create LR tables. std::vector<const BnfGrm::Nt*> start_nts; start_nts.push_back(bnf_grammar->get_nonterminals()[0]); unique_ptr<const LRTbl> lrtables = ns::create_LR_tables(*bnf_grammar.get(), start_nts, false); //Create managed heap. unique_ptr<MHeap> managed_heap(new MHeap()); unique_ptr<MHeap> const_managed_heap(new MHeap()); //Create core tables. unique_ptr<const CoreTables> core_tables(create_core_tables(bnf_grammar.get(), lrtables.get())); //Parse. prs::Scanner scanner(in, file_name); InternalScanner internal_scanner(scanner); MPtr<ebnf::Grammar> grammar_mptr; try { std::unique_ptr<syn::ParserInterface> parser = syn::ParserInterface::create(); syn::StackElement_Nt* root_element = parser->parse( core_tables->get_start_state(), internal_scanner, static_cast<syn::InternalTk>(Tokens::END_OF_FILE) ); ActionContext action_context(managed_heap.get(), const_managed_heap.get()); grammar_mptr = action_context.nt_Grammar(root_element); } catch (const syn::SynSyntaxError&) { throw internal_scanner.fire_syntax_error("Syntax error"); } catch (const syn::SynLexicalError&) { throw internal_scanner.fire_syntax_error("Lexical error"); } catch (const syn::SynError&) { throw std::runtime_error("Unable to parse grammar"); } //Return result. std::unique_ptr<util::MRoot<ebnf::Grammar>> grammar_root(new util::MRoot<ebnf::Grammar>(grammar_mptr)); grammar_root->add_heap(std::move(managed_heap)); return make_unique1<GrammarParsingResult>(std::move(grammar_root), std::move(const_managed_heap)); }
35.779673
119
0.739138
asmwarrior
4ce4b03fc07e7bd088be5cb5037af11bab8a3cb2
2,146
hh
C++
neb/inc/com/centreon/broker/neb/downtime_map.hh
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
40
2015-03-10T07:55:39.000Z
2021-06-11T10:13:56.000Z
neb/inc/com/centreon/broker/neb/downtime_map.hh
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
297
2015-04-30T10:02:04.000Z
2022-03-09T13:31:54.000Z
neb/inc/com/centreon/broker/neb/downtime_map.hh
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
29
2015-08-03T10:04:15.000Z
2021-11-25T12:21:00.000Z
/* ** Copyright 2009-2013 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : [email protected] */ #ifndef CCB_NEB_DOWNTIME_MAP_HH #define CCB_NEB_DOWNTIME_MAP_HH #include <unordered_map> #include "com/centreon/broker/misc/pair.hh" #include "com/centreon/broker/namespace.hh" #include "com/centreon/broker/neb/downtime.hh" #include "com/centreon/broker/neb/node_id.hh" CCB_BEGIN() namespace neb { /** * @class downtime_map downtime_map.hh * "com/centreon/broker/neb/downtime_map.hh" * @brief Map of downtimes. */ class downtime_map { public: downtime_map(); downtime_map(downtime_map const& other); downtime_map& operator=(downtime_map const& other); virtual ~downtime_map(); uint32_t get_new_downtime_id(); std::list<downtime> get_all_downtimes_of_node(node_id id) const; std::list<downtime> get_all_recurring_downtimes_of_node(node_id id) const; void delete_downtime(downtime const& dwn); void add_downtime(downtime const& dwn); downtime* get_downtime(uint32_t internal_id); bool is_recurring(uint32_t internal_id) const; std::list<downtime> get_all_recurring_downtimes() const; std::list<downtime> get_all_downtimes() const; bool spawned_downtime_exist(uint32_t parent_id) const; private: uint32_t _actual_downtime_id; std::unordered_map<uint32_t, downtime> _downtimes; std::unordered_multimap<node_id, uint32_t> _downtime_id_by_nodes; std::unordered_map<uint32_t, downtime> _recurring_downtimes; std::unordered_multimap<node_id, uint32_t> _recurring_downtime_id_by_nodes; }; } // namespace neb CCB_END() #endif // !CCB_NEB_DOWNTIME_MAP_HH
32.515152
77
0.770736
centreon-lab
4ce63cde6592cfc58aee4772fc5e52f4f52659df
229
cpp
C++
point.cpp
Unicorn3D/Analyst
25261a601c97a64bffd3926c125dc441ffdbb661
[ "MIT" ]
1
2016-06-16T07:08:54.000Z
2016-06-16T07:08:54.000Z
point.cpp
Unicorn3D/Analyst
25261a601c97a64bffd3926c125dc441ffdbb661
[ "MIT" ]
null
null
null
point.cpp
Unicorn3D/Analyst
25261a601c97a64bffd3926c125dc441ffdbb661
[ "MIT" ]
null
null
null
#include "point.h" point::point() { } point::point(float lat, float lng) { this->lat = lat; this->lng = lng; } void point::write(QJsonObject &json) const { json["lat"] = this->lat; json["lng"] = this->lng; }
11.45
42
0.572052
Unicorn3D
4ceb3c3726b0bcc22f9208e1cc63b0c9b09a20d0
3,009
cpp
C++
GraphManager/shared/DrRef.cpp
TheWhiteEagle/Dryad
ad28579dd8303925befc6502633949850b7ca550
[ "Apache-2.0" ]
242
2015-01-04T08:08:04.000Z
2022-03-31T02:00:14.000Z
GraphManager/shared/DrRef.cpp
TheWhiteEagle/Dryad
ad28579dd8303925befc6502633949850b7ca550
[ "Apache-2.0" ]
2
2015-04-30T07:44:42.000Z
2015-05-19T06:24:31.000Z
GraphManager/shared/DrRef.cpp
TheWhiteEagle/Dryad
ad28579dd8303925befc6502633949850b7ca550
[ "Apache-2.0" ]
50
2015-01-13T20:39:53.000Z
2022-01-09T20:42:34.000Z
/* Copyright (c) Microsoft Corporation 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 THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ #include "DrShared.h" #ifdef _MANAGED #else #define DRREF_MAGIC_CONSTRUCTOR_VALUE (-666) #ifdef _DEBUG_DRREF std::set<DrRefCounter*> DrRefCounter::s_refsAllocated; std::map<void*,DrRefCounter*> DrRefCounter::s_arrayStorage; CRITICAL_SECTION DrRefCounter::s_debugCS; #endif DrRefCounter::DrRefCounter() : m_iRefCount( DRREF_MAGIC_CONSTRUCTOR_VALUE ) { #ifdef _DEBUG_DRREF EnterCriticalSection(&s_debugCS); bool inserted = s_refsAllocated.insert(this).second; DrAssert(inserted); LeaveCriticalSection(&s_debugCS); #endif } DrRefCounter::~DrRefCounter() { DrAssert(m_iRefCount == 0); #ifdef _DEBUG_DRREF DrAssert(m_holders.empty()); EnterCriticalSection(&s_debugCS); size_t nRemoved = s_refsAllocated.erase(this); DrAssert(nRemoved == 1); LeaveCriticalSection(&s_debugCS); #endif } void DrRefCounter::FreeMemory() // Called when the refcount becomes zero. { delete this; } #ifdef _DEBUG_DRREF void DrRefCounter::IncRef(void* h) { EnterCriticalSection(&s_debugCS); ++m_iRefCount; if (m_iRefCount <= 1) { // this is the first assignment of a newly constructed object */ DrAssert(m_iRefCount == (DRREF_MAGIC_CONSTRUCTOR_VALUE + 1)); m_iRefCount = 1; } bool inserted = m_holders.insert(h).second; DrAssert(inserted); DrAssert(m_holders.size() == (size_t) m_iRefCount); LeaveCriticalSection(&s_debugCS); } #else void DrRefCounter::IncRef() { LONG i; i = InterlockedIncrement(&m_iRefCount); if (i <= 1) { // this is the first assignment of a newly constructed object */ DrAssert(i == (DRREF_MAGIC_CONSTRUCTOR_VALUE + 1)); m_iRefCount = 1; } } #endif #ifdef _DEBUG_DRREF void DrRefCounter::DecRef(void* h) { EnterCriticalSection(&s_debugCS); DrAssert(m_holders.size() == (size_t) m_iRefCount); size_t nRemoved = m_holders.erase(h); DrAssert(nRemoved == 1); --m_iRefCount; if (m_iRefCount <= 0) { DrAssert(m_iRefCount == 0); FreeMemory(); } LeaveCriticalSection(&s_debugCS); } #else void DrRefCounter::DecRef() { LONG i; i = InterlockedDecrement(&m_iRefCount); if (i <= 0) { DrAssert(i == 0); FreeMemory(); } } #endif void DrInterfaceRefBase::AssertTypeCast() { DrLogA("Type cast failed"); } #endif
23.880952
100
0.699236
TheWhiteEagle
4cf026b586614503a05d7e51c2ecb3e9b6737920
2,843
hpp
C++
src/Evolution/Systems/NewtonianEuler/PrimitiveFromConservative.hpp
GAcuna001/spectre
645a7f203b2ced1b1205e346d3abaf2adaf0e6ba
[ "MIT" ]
null
null
null
src/Evolution/Systems/NewtonianEuler/PrimitiveFromConservative.hpp
GAcuna001/spectre
645a7f203b2ced1b1205e346d3abaf2adaf0e6ba
[ "MIT" ]
null
null
null
src/Evolution/Systems/NewtonianEuler/PrimitiveFromConservative.hpp
GAcuna001/spectre
645a7f203b2ced1b1205e346d3abaf2adaf0e6ba
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include <cstddef> #include "DataStructures/Tensor/TypeAliases.hpp" #include "Evolution/Systems/NewtonianEuler/TagsDeclarations.hpp" // IWYU pragma: keep #include "PointwiseFunctions/Hydro/EquationsOfState/EquationOfState.hpp" // IWYU pragma: keep #include "PointwiseFunctions/Hydro/Tags.hpp" #include "Utilities/TMPL.hpp" // IWYU pragma: no_forward_declare EquationsOfState::EquationOfState // IWYU pragma: no_forward_declare NewtonianEuler::Tags::EnergyDensity // IWYU pragma: no_forward_declare NewtonianEuler::Tags::MassDensity // IWYU pragma: no_forward_declare NewtonianEuler::Tags::MassDensityCons // IWYU pragma: no_forward_declare NewtonianEuler::Tags::MomentumDensity // IWYU pragma: no_forward_declare NewtonianEuler::Tags::Pressure // IWYU pragma: no_forward_declare NewtonianEuler::Tags::SpecificInternalEnergy // IWYU pragma: no_forward_declare NewtonianEuler::Tags::Velocity // IWYU pragma: no_forward_declare hydro::Tags::EquationOfStateBase /// \cond namespace gsl { template <typename T> class not_null; } // namespace gsl class DataVector; /// \endcond // IWYU pragma: no_forward_declare Tensor namespace NewtonianEuler { /*! * \brief Compute the primitive variables from the conservative variables. * * \f{align*} * v^i &= \frac{S^i}{\rho} \\ * \epsilon &= \frac{e}{\rho} - \frac{1}{2}\frac{S^2}{\rho^2} * \f} * * where \f$v^i\f$ is the velocity, \f$\epsilon\f$ is the specific * internal energy, \f$e\f$ is the energy density, \f$\rho\f$ * is the mass density, \f$S^i\f$ is the momentum density, and * \f$S^2\f$ is the momentum density squared. * * This routine also returns the mass density as a primitive, and the pressure * from a generic equation of state \f$p = p(\rho, \epsilon)\f$. */ template <size_t Dim> struct PrimitiveFromConservative { using return_tags = tmpl::list<Tags::MassDensity<DataVector>, Tags::Velocity<DataVector, Dim>, Tags::SpecificInternalEnergy<DataVector>, Tags::Pressure<DataVector>>; using argument_tags = tmpl::list<Tags::MassDensityCons, Tags::MomentumDensity<Dim>, Tags::EnergyDensity, hydro::Tags::EquationOfStateBase>; template <size_t ThermodynamicDim> static void apply( gsl::not_null<Scalar<DataVector>*> mass_density, gsl::not_null<tnsr::I<DataVector, Dim>*> velocity, gsl::not_null<Scalar<DataVector>*> specific_internal_energy, gsl::not_null<Scalar<DataVector>*> pressure, const Scalar<DataVector>& mass_density_cons, const tnsr::I<DataVector, Dim>& momentum_density, const Scalar<DataVector>& energy_density, const EquationsOfState::EquationOfState<false, ThermodynamicDim>& equation_of_state) noexcept; }; } // namespace NewtonianEuler
36.922078
94
0.730918
GAcuna001
4cf4105a46744bc1e966fc799296dfbba60826df
3,997
cpp
C++
src/SignalOperation/KeySampler.cpp
Lut1n/QuasarBell
c5b5052ac1db94d0a97fd07e512883a9fd244fd5
[ "MIT" ]
2
2021-01-31T10:06:33.000Z
2021-03-10T13:20:15.000Z
src/SignalOperation/KeySampler.cpp
Lut1n/QuasarBell
c5b5052ac1db94d0a97fd07e512883a9fd244fd5
[ "MIT" ]
null
null
null
src/SignalOperation/KeySampler.cpp
Lut1n/QuasarBell
c5b5052ac1db94d0a97fd07e512883a9fd244fd5
[ "MIT" ]
null
null
null
#include "SignalOperation/KeySampler.hpp" #include <iostream> #include <string> #include "imgui.h" #include "Json/Json.hpp" //-------------------------------------------------------------- KeySampler::KeySampler() { _hasCustomData = true; makeOutput("value", BaseOperationDataType::Float); makeProperty("count", BaseOperationDataType::Int, &count); makeProperty("interpo", BaseOperationDataType::Int, &interpo); keys.resize(1,{0.f,1.f}); } //-------------------------------------------------------------- bool KeySampler::sample(size_t index, qb::PcmBuilderVisitor& visitor) { // t.dstOp = this; qb::OperationData& data = visitor.data; auto output = getOutput(0); data.type = output->type; float& t = visitor.time.t; int index1 = -1; int index2 = -1; for(size_t i=0; i<keys.size(); ++i) { int j = (int)(keys.size()-1-i); if(keys[i].first <= t) index1 = (int)i; if(keys[j].first >= t) index2 = (int)j; } if(index1 == -1 && index2 == -1) data.fvec[0] = 0.0; else if(index1 == -1) data.fvec[0] = keys[index2].second; else if(index2 == -1) data.fvec[0] = keys[index1].second; else if(index1 == index2) data.fvec[0] = keys[index1].second; else { float x = (t-keys[index1].first) / (keys[index2].first-keys[index1].first); data.fvec[0] = keys[index1].second + interpolate(x) * (keys[index2].second-keys[index1].second); } return true; } //-------------------------------------------------------------- float KeySampler::interpolate(float x) { if (interpo == Interpo::Flat) return 0; else if (interpo == Interpo::Linear) return x; else if (interpo == Interpo::Cubic) return x * x * (3.f - 2.f * x); return x; } //-------------------------------------------------------------- void KeySampler::saveCustomData(JsonValue& json) { auto& jArray = json.setPath("key-values"); int index = 0; for (auto kv : keys) { jArray.setPath(index, 0).set(kv.first); jArray.setPath(index, 1).set(kv.second); index++; } } //-------------------------------------------------------------- void KeySampler::loadCustomData(JsonValue& json) { auto& jArray = json.setPath("key-values"); count = (int)jArray.count(); keys.resize(jArray.count()); int index = 0; for(auto& jkv : jArray.array.values) { keys[index] = {(float)jkv.setPath(0).getNumeric(),(float) jkv.setPath(1).getNumeric()}; index++; } } //-------------------------------------------------------------- void KeySampler::uiProperties() { constexpr size_t typeCount = 3; constexpr std::array<const char*, typeCount> typeNames = {"flat", "linear", "cubic"}; if (ImGui::Button(typeNames[interpo])) { interpo = (interpo+1) % typeCount; dirty(); } if (ImGui::InputInt("count", &count)) { if (count < 1) count = 1; if (count > 10) count = 10; keys.resize(count); dirty(); } ImGui::Columns(2); ImGui::Text("Time"); ImGui::NextColumn(); ImGui::Text("Value"); ImGui::NextColumn(); ImGui::Separator(); int index = 0; for(auto& kv : keys) { std::string keytext = std::string("##key") + std::to_string(index); std::string valtext = std::string("##val") + std::to_string(index); if (ImGui::InputFloat(keytext.c_str(), &kv.first)) dirty(); ImGui::NextColumn(); if (ImGui::InputFloat(valtext.c_str(), &kv.second)) dirty(); ImGui::NextColumn(); index++; } ImGui::Columns(1); ImGui::Separator(); ImGui::Text("Preview"); preview.compute(this); ImGui::PlotLines("##preview", preview.data.data(), 32, 0, NULL, FLT_MAX, FLT_MAX, ImVec2(0, 60.0f)); }
30.052632
105
0.504128
Lut1n
4cf47eebe814d6cd8b406fc93172bcbfcf6d1d08
6,073
cpp
C++
src/ML/Graphics/Image.cpp
Gurman8r/ML
171e7865291f3fd9ea748d59f9d4bdb4e2a6eed1
[ "MIT" ]
3
2019-10-09T19:03:05.000Z
2019-12-15T14:22:38.000Z
src/ML/Graphics/Image.cpp
Gurman8r/ML
171e7865291f3fd9ea748d59f9d4bdb4e2a6eed1
[ "MIT" ]
null
null
null
src/ML/Graphics/Image.cpp
Gurman8r/ML
171e7865291f3fd9ea748d59f9d4bdb4e2a6eed1
[ "MIT" ]
null
null
null
#include <ML/Graphics/Image.hpp> #include <ML/Core/Debug.hpp> #define STB_IMAGE_IMPLEMENTATION #include <stb/stb_image.h> /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ namespace ml { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ static inline Image generate_default_image() { Image img { vec2u{ 512, 512 }, 4 }; for (uint32_t y = 0; y < img.height(); y++) { for (uint32_t x = 0; x < img.width(); x++) { img.setPixel(x, y, (((y < img.height() / 2) && (x < img.width() / 2)) || ((y >= img.height() / 2) && (x >= img.width() / 2)) ? Color(Color(0.1f).rgb(), 1.0) : (((y >= img.height() / 2) || (x >= img.width() / 2)) ? Colors::magenta : Colors::green ))); } } return img; } const Image Image::Default { generate_default_image() }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ Image::Image() : Image { vec2u { NULL } } { } Image::Image(vec2u const & size) : Image { size, 4 } { } Image::Image(vec2u const & size, uint32_t channels) : Image { size, Pixels(), channels } { } Image::Image(vec2u const & size, Pixels const & pixels) : Image { size, pixels, 4 } { } Image::Image(vec2u const & size, Pixels const & pixels, uint32_t channels) : m_size { size } , m_pixels { pixels } , m_channels { channels } { if (const uint32_t c { this->capacity() }) { if (m_pixels.empty() || (m_pixels.size() != c)) { m_pixels.resize(c); } } } Image::Image(String const & filename) : Image { filename, false } { } Image::Image(String const & filename, bool flip_v) : Image { filename, flip_v, 0 } { } Image::Image(String const & filename, bool flip_v, uint32_t req_comp) : Image {} { this->loadFromFile(filename, flip_v, req_comp); } Image::Image(Image const & copy) : Image {} { this->update(copy.m_size, copy.m_channels, copy.m_pixels); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ bool Image::dispose() { if (!m_pixels.empty()) { Pixels().swap(m_pixels); } m_size = { 0, 0 }; m_channels = 0; return !(*this); } bool Image::loadFromFile(String const & filename) { return loadFromFile(filename, true); } bool Image::loadFromFile(String const & filename, bool flip_v) { return loadFromFile(filename, flip_v, 0); } bool Image::loadFromFile(String const & filename, bool flip_v, uint32_t req_comp) { stbi_set_flip_vertically_on_load(flip_v); if (byte_t * data = stbi_load( filename.c_str(), (int32_t *)(&m_size[0]), (int32_t *)(&m_size[1]), (int32_t *)(&m_channels), req_comp )) { update({ data, data + capacity() }); stbi_image_free(data); return (*this); } return dispose(); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ Image & Image::update(vec2u const & size, Color32 const & color) { return update(size, channels(), color); } Image & Image::update(Color32 const & color) { return update(size(), channels(), color); } Image & Image::update(vec2u const & size, uint32_t channels, Color32 const & color) { if (size[0] && size[1] && channels) { m_size = size; m_channels = channels; m_pixels.resize(capacity()); iterator it { begin() }; while (it != end()) { if (m_channels >= 1) *it++ = color[0]; if (m_channels >= 2) *it++ = color[1]; if (m_channels >= 3) *it++ = color[2]; if (m_channels >= 4) *it++ = color[3]; } return (*this); } dispose(); return (*this); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ Image & Image::update(vec2u const & size, Pixels const & pixels) { return update(size, m_channels, pixels); } Image & Image::update(Pixels const & pixels) { return update(m_size, m_channels, pixels); } Image & Image::update(vec2u const & size, uint32_t channels, Pixels const & pixels) { if (!pixels.empty() && (pixels.size() == (size[0] * size[1] * channels))) { m_size = size; m_channels = channels; m_pixels.assign(pixels.begin(), pixels.end()); return (*this); } dispose(); return (*this); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ Image & Image::flipHorizontally() { if (*this) { const uint32_t cols { width() * channels() }; for (uint32_t y = 0; y < height(); ++y) { iterator lhs { begin() + y * cols }; iterator rhs { begin() + (y + 1) * cols - channels() }; for (uint32_t x = 0; x < width() / 2; ++x) { std::swap_ranges(lhs, lhs + channels(), rhs); lhs += channels(); rhs -= channels(); } } } return (*this); } Image & Image::flipVertically() { if (*this) { const uint32_t cols { width() * channels() }; iterator top { begin() }; iterator bot { end() - cols }; for (uint32_t y = 0; y < height() / 2; ++y) { std::swap_ranges(top, top + cols, bot); top += cols; bot -= cols; } } return (*this); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ Color32 Image::getPixel(uint32_t x, uint32_t y) const { Color32 temp { Colors::clear }; const size_t i { (x + y * m_size[0]) * m_channels }; if (i < capacity()) { const_iterator it { cbegin() + i }; if (m_channels >= 1) temp[0] = *(it + 0); if (m_channels >= 2) temp[1] = *(it + 1); if (m_channels >= 3) temp[2] = *(it + 2); if (m_channels >= 4) temp[3] = *(it + 3); } return temp; } Image & Image::setPixel(uint32_t x, uint32_t y, Color32 const & color) { const size_t i { (x + y * m_size[0]) * m_channels }; if (i < capacity()) { iterator it { begin() + i }; if (m_channels >= 1) *it++ = color[0]; if (m_channels >= 2) *it++ = color[1]; if (m_channels >= 3) *it++ = color[2]; if (m_channels >= 4) *it++ = color[3]; } return (*this); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ }
22.916981
84
0.503376
Gurman8r
e07cfb66e6048da2a26e32e0aa88f53c6b7541cb
5,683
cpp
C++
DemoApps/Shared/VulkanWillemsMeshDemoAppExperimental/source/Shared/VulkanWillemsMeshDemoAppExperimental/VulkanMeshLoaderAssimp.cpp
alejandrolozano2/OpenGL_DemoFramework
5fd85f05c98cc3d0c0a68bac438035df8cabaee7
[ "MIT", "BSD-3-Clause" ]
3
2019-01-19T20:21:24.000Z
2021-08-10T02:11:32.000Z
DemoApps/Shared/VulkanWillemsMeshDemoAppExperimental/source/Shared/VulkanWillemsMeshDemoAppExperimental/VulkanMeshLoaderAssimp.cpp
alejandrolozano2/OpenGL_DemoFramework
5fd85f05c98cc3d0c0a68bac438035df8cabaee7
[ "MIT", "BSD-3-Clause" ]
null
null
null
DemoApps/Shared/VulkanWillemsMeshDemoAppExperimental/source/Shared/VulkanWillemsMeshDemoAppExperimental/VulkanMeshLoaderAssimp.cpp
alejandrolozano2/OpenGL_DemoFramework
5fd85f05c98cc3d0c0a68bac438035df8cabaee7
[ "MIT", "BSD-3-Clause" ]
1
2021-08-10T02:11:33.000Z
2021-08-10T02:11:33.000Z
/* * Mesh loader for creating Vulkan resources from models loaded with ASSIMP * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ // Based on a code by Sascha Willems from https://github.com/SaschaWillems/Vulkan // Recreated as a DemoFramework freestyle window sample by Freescale (2016) // This class simulates the functionality found in VulkanMeshLoader to make it easier // to port samples. It is not a straight port, but it has instead been converted to // follow the RAII principle used in this framework #include <Shared/VulkanWillemsMeshDemoAppExperimental/VulkanMeshLoaderAssimp.hpp> #include <Shared/VulkanWillemsDemoAppExperimental/Config.hpp> #include <FslBase/Exceptions.hpp> #include <FslBase/IO/File.hpp> #include <FslDemoApp/Base/Service/Content/IContentManager.hpp> #include <FslGraphics/Texture/Texture.hpp> #include <RapidVulkan/Buffer.hpp> #include <RapidVulkan/Check.hpp> #include <RapidVulkan/Fence.hpp> #include <algorithm> #include <cstring> #include <utility> namespace Fsl { //using namespace Vulkan; namespace Willems { namespace { const IO::Path ToAbsolutePath(const IO::Path& trustedAbsPath, const IO::Path& notTrustedRelativePath) { assert(!trustedAbsPath.IsEmpty()); // Do a lot of extra validation if (notTrustedRelativePath.IsEmpty()) throw std::invalid_argument(std::string("path is invalid: ") + notTrustedRelativePath.ToAsciiString()); if (IO::Path::IsPathRooted(notTrustedRelativePath)) throw std::invalid_argument(std::string("not a relative path: ") + notTrustedRelativePath.ToAsciiString()); if (notTrustedRelativePath.Contains("..")) throw std::invalid_argument(std::string("\"..\" not allowed in the relative path: ") + notTrustedRelativePath.ToAsciiString()); return IO::Path::Combine(trustedAbsPath, notTrustedRelativePath); } } VulkanMeshLoaderAssimp::VulkanMeshLoaderAssimp(const std::shared_ptr<IContentManager>& contentManager) : VulkanMeshLoader(contentManager) { if (!contentManager) throw std::invalid_argument("contentManager can not be null"); } VulkanMeshLoaderAssimp::~VulkanMeshLoaderAssimp() { } void VulkanMeshLoaderAssimp::LoadMeshNow(const std::string& relativePath, std::vector<MeshEntry>& rEntries, Dimension& rDim) { LoadMeshNow(relativePath, DefaultFlags, rEntries, rDim); } void VulkanMeshLoaderAssimp::LoadMeshNow(const std::string& relativePath, const int flags, std::vector<MeshEntry>& rEntries, Dimension& rDim) { const IO::Path absPath(ToAbsolutePath(GetContentPath(), relativePath)); auto pScene = Importer.ReadFile(absPath.ToAsciiString().c_str(), flags); if (! pScene) throw NotSupportedException(std::string("Could not read file: ") + absPath.ToAsciiString()); rEntries.clear(); rEntries.resize(pScene->mNumMeshes); // Read in all meshes in the scene uint32_t numVertices = 0; for (std::size_t i = 0; i < rEntries.size(); ++i) { rEntries[i].VertexBase = numVertices; numVertices += pScene->mMeshes[i]->mNumVertices; const aiMesh* paiMesh = pScene->mMeshes[i]; InitMesh(rEntries[i], paiMesh, pScene, rDim); } } void VulkanMeshLoaderAssimp::InitMesh(MeshEntry& rMeshEntry, const aiMesh*const pAiMesh, const aiScene*const pScene, Dimension& rDim) { assert(pAiMesh != nullptr); assert(pScene != nullptr); rMeshEntry.MaterialIndex = pAiMesh->mMaterialIndex; aiColor3D pColor(0.f, 0.f, 0.f); pScene->mMaterials[pAiMesh->mMaterialIndex]->Get(AI_MATKEY_COLOR_DIFFUSE, pColor); aiVector3D Zero3D(0.0f, 0.0f, 0.0f); rMeshEntry.Vertices.clear(); rMeshEntry.Vertices.resize(pAiMesh->mNumVertices); for (unsigned int i = 0; i < pAiMesh->mNumVertices; i++) { aiVector3D* pPos = &(pAiMesh->mVertices[i]); aiVector3D* pNormal = &(pAiMesh->mNormals[i]); aiVector3D* pTexCoord = (pAiMesh->HasTextureCoords(0)) ? &(pAiMesh->mTextureCoords[0][i]) : &Zero3D; aiVector3D* pTangent = (pAiMesh->HasTangentsAndBitangents()) ? &(pAiMesh->mTangents[i]) : &Zero3D; aiVector3D* pBiTangent = (pAiMesh->HasTangentsAndBitangents()) ? &(pAiMesh->mBitangents[i]) : &Zero3D; Vertex v( glm::vec3(pPos->x, -pPos->y, pPos->z), glm::vec2(pTexCoord->x, pTexCoord->y), glm::vec3(pNormal->x, pNormal->y, pNormal->z), glm::vec3(pTangent->x, pTangent->y, pTangent->z), glm::vec3(pBiTangent->x, pBiTangent->y, pBiTangent->z), glm::vec3(pColor.r, pColor.g, pColor.b) ); rDim.max.x = std::max(pPos->x, rDim.max.x); rDim.max.y = std::max(pPos->y, rDim.max.y); rDim.max.z = std::max(pPos->z, rDim.max.z); rDim.min.x = std::min(pPos->x, rDim.min.x); rDim.min.y = std::min(pPos->y, rDim.min.y); rDim.min.z = std::min(pPos->z, rDim.min.z); rMeshEntry.Vertices[i] = v; } rDim.size = rDim.max - rDim.min; uint32_t indexBase = static_cast<uint32_t>(rMeshEntry.Indices.size()); for (unsigned int i = 0; i < pAiMesh->mNumFaces; i++) { const aiFace& Face = pAiMesh->mFaces[i]; if (Face.mNumIndices == 3) { rMeshEntry.Indices.push_back(indexBase + Face.mIndices[0]); rMeshEntry.Indices.push_back(indexBase + Face.mIndices[1]); rMeshEntry.Indices.push_back(indexBase + Face.mIndices[2]); } } } } }
36.429487
145
0.665846
alejandrolozano2
e086d715be6ca76019b03df22548778482286e4f
1,428
cpp
C++
Inheritance/main.cpp
clemaitre58/LessonsCpp
a385b30c9ca970f0be68a781a55cfe409058aa05
[ "MIT" ]
null
null
null
Inheritance/main.cpp
clemaitre58/LessonsCpp
a385b30c9ca970f0be68a781a55cfe409058aa05
[ "MIT" ]
null
null
null
Inheritance/main.cpp
clemaitre58/LessonsCpp
a385b30c9ca970f0be68a781a55cfe409058aa05
[ "MIT" ]
5
2020-04-11T20:19:27.000Z
2020-04-14T04:20:19.000Z
#include <iostream> #include "inheritance.hpp" int main() { inheritance::Parent my_parent; my_parent.set_a(1); my_parent.set_b(2); my_parent.set_c(3); std::cout << "My parent a attribute value : " << my_parent.get_a() << std::endl; std::cout << "My parent b attribute value : " << my_parent.get_b() << std::endl; std::cout << "My parent c attribute value : " << my_parent.get_c() << std::endl; inheritance::Child1 my_child1; my_child1.set_a(4); my_child1.set_b(5); my_child1.set_c(6); my_child1.set_d(7); std::cout << "My child1 a attribute value : " << my_child1.get_a() << std::endl; std::cout << "My child1 b attribute value : " << my_child1.get_b() << std::endl; std::cout << "My child1 c attribute value : " << my_child1.get_c() << std::endl; std::cout << "My child1 d attribute value : " << my_child1.get_d() << std::endl; //my_child1.b = 12; inheritance::Child2 my_child2; my_child2.set_d(8); // my_child2.set_a(5); // my_child2.set_b(6); // my_child2.set_b(7); // std::cout << "My child1 a attribute value : " << my_child2.get_a() << std::endl; // std::cout << "My child1 b attribute value : " << my_child2.get_b() << std::endl; // std::cout << "My child1 c attribute value : " << my_child2.get_c() << std::endl; std::cout << "My child1 d attribute value : " << my_child2.get_d() << std::endl; return 0; }
31.733333
86
0.606443
clemaitre58
e095c0362c30f50b3a670b8c390383232eefd4ed
37,013
cpp
C++
source_code/system_fpl/source_code/calculation/section_fpl/mechanisms/dike/Fpl_Seepage_Calculator_Dike.cpp
dabachma/ProMaIDes_src
3fa6263c46f89abbdb407f2e1643843d54eb6ccc
[ "BSD-3-Clause" ]
null
null
null
source_code/system_fpl/source_code/calculation/section_fpl/mechanisms/dike/Fpl_Seepage_Calculator_Dike.cpp
dabachma/ProMaIDes_src
3fa6263c46f89abbdb407f2e1643843d54eb6ccc
[ "BSD-3-Clause" ]
null
null
null
source_code/system_fpl/source_code/calculation/section_fpl/mechanisms/dike/Fpl_Seepage_Calculator_Dike.cpp
dabachma/ProMaIDes_src
3fa6263c46f89abbdb407f2e1643843d54eb6ccc
[ "BSD-3-Clause" ]
null
null
null
#include "source_code\Fpl_Headers_Precompiled.h" //#include "Fpl_Seepage_Calculator_Dike.h" //Default constructor Fpl_Seepage_Calculator_Dike::Fpl_Seepage_Calculator_Dike(void){ this->ptr_waterside_cub=NULL; this->ptr_landside_cub=NULL; this->ptr_cubature=NULL; this->seepage_calc_max=_fpl_max_waterlevel_seepage::kozeny; this->seepage_calc_min=_fpl_min_waterlevel_seepage::water_base; Sys_Memory_Count::self()->add_mem(sizeof(Fpl_Seepage_Calculator_Dike),_sys_system_modules::FPL_SYS);//count the memory } //Default destructor Fpl_Seepage_Calculator_Dike::~Fpl_Seepage_Calculator_Dike(void){ Sys_Memory_Count::self()->minus_mem(sizeof(Fpl_Seepage_Calculator_Dike),_sys_system_modules::FPL_SYS);//count the memory } //___________ //public //Set the pointer to waterside cubature; void Fpl_Seepage_Calculator_Dike::set_ptr_waterside_cub(Fpl_Cub_Dike_Waterside *cub){ this->ptr_waterside_cub=cub; } //Set the pointer to landside cubature; void Fpl_Seepage_Calculator_Dike::set_ptr_landside_cub(Fpl_Cub_Dike_Landside *cub){ this->ptr_landside_cub=cub; } //Set the pointer to the cubature void Fpl_Seepage_Calculator_Dike::set_ptr_cubature(Geo_Polysegment *cubature){ this->ptr_cubature=cubature; } //Calculate new waterlevels of the seepage line void Fpl_Seepage_Calculator_Dike::calculate_waterlevel_seepage_line(const double water_level, Fpl_Seepage_Line_Point_List *ascending, Fpl_Seepage_Line_Point_List *descending, const bool for_output){ if(this->seepage_calc_max==_fpl_max_waterlevel_seepage::one_third_waterlevel){ this->calculate_seepage_line_land_one_third(water_level, ascending, for_output); this->calculate_seepage_line_land_one_third(water_level, descending, for_output); if(this->seepage_calc_min==_fpl_min_waterlevel_seepage::one_third_mid_waterlevel){ this->calculate_seepage_line_mid_water_one_third(water_level, descending, for_output); } else{ this->calculate_seepage_line_mid_water_base(water_level, descending, for_output); } } else if(this->seepage_calc_max==_fpl_max_waterlevel_seepage::kozeny){ try{ this->calculate_seepage_line_land_kozeny(water_level, ascending, for_output); this->calculate_seepage_line_land_kozeny(water_level, descending, for_output); } catch(Error msg){ throw msg; } if(this->seepage_calc_min==_fpl_min_waterlevel_seepage::one_third_mid_waterlevel){ this->calculate_seepage_line_mid_water_one_third(water_level, descending, for_output); } else{ this->calculate_seepage_line_mid_water_base(water_level, descending, for_output); } } else { this->calculate_seepage_line_land_base(water_level, ascending, for_output); this->calculate_seepage_line_land_base(water_level, descending, for_output); if(this->seepage_calc_min==_fpl_min_waterlevel_seepage::one_third_mid_waterlevel){ this->calculate_seepage_line_mid_water_one_third(water_level, descending, for_output); } else{ this->calculate_seepage_line_mid_water_base(water_level, descending, for_output); } } } //Input the control parameters per database table void Fpl_Seepage_Calculator_Dike::set_input(QSqlDatabase *ptr_database, const bool frc_sim, const bool output){ if(output==true){ ostringstream cout; cout <<"Set the control parameters of the seepage calculation... " << endl ; Sys_Common_Output::output_fpl->output_txt(&cout,false); } //mysql query with the table_model QSqlTableModel model(0,*ptr_database); int number_result=0; //the table is set the name and the column names try{ Fpl_Mc_Sim::set_table(ptr_database); } catch(Error msg){ throw msg; } //give the complet table of control parameters FPL model.setTable(Fpl_Mc_Sim::table->get_table_name().c_str()); //set the query Data_Base::database_request(&model); number_result=model.rowCount(); //read out the results //the set of the name-column has to match to this parameter //output if(number_result>0){ //read out from the search result string buffer; for(int i=0; i< number_result; i++){ buffer=model.record(i).value((Fpl_Mc_Sim::table->get_column_name(fpl_label::control_name)).c_str()).toString().toStdString(); if(buffer==fpl_seepage_method::seepage_maximum){ this->seepage_calc_max=Fpl_Seepage_Calculator_Dike::convert_txt2seepagetype_max_waterlevel( model.record(i).value((Fpl_Mc_Sim::table->get_column_name(fpl_label::control_value)).c_str()).toString().toStdString()); } else if(buffer==fpl_seepage_method::seepage_minimum){ this->seepage_calc_min=Fpl_Seepage_Calculator_Dike::convert_txt2seepagetype_min_waterlevel( model.record(i).value((Fpl_Mc_Sim::table->get_column_name(fpl_label::control_value)).c_str()).toString().toStdString()); } } } if(frc_sim==true && this->seepage_calc_min==_fpl_min_waterlevel_seepage::one_third_mid_waterlevel){ Warning msg=this->set_warning(0); msg.output_msg(1); this->seepage_calc_min=_fpl_min_waterlevel_seepage::water_base; } } //Output the control parameters of the seepage calculation to display/console void Fpl_Seepage_Calculator_Dike::output_members(void){ Sys_Common_Output::output_fpl->reset_prefix_was_outputed(); ostringstream cout; cout << "SEEPAGE-CALCULATION " << endl; cout << " Method for the maximum waterlevel : " << Fpl_Seepage_Calculator_Dike::convert_seepagetype_max_waterlevel2txt(this->seepage_calc_max) << endl; cout << " Method for the minimum waterlevel : " << Fpl_Seepage_Calculator_Dike::convert_seepagetype_min_waterlevel2txt(this->seepage_calc_min) << endl; Sys_Common_Output::output_fpl->output_txt(cout.str(),false); } //Convert a string into seepage type at maximum waterlevel (_fpl_max_waterlevel_seepage) (static) _fpl_max_waterlevel_seepage Fpl_Seepage_Calculator_Dike::convert_txt2seepagetype_max_waterlevel(const string txt){ _fpl_max_waterlevel_seepage type; string buffer=txt; functions::clean_string(&buffer); functions::convert_string2lower_case(&buffer); if(buffer==fpl_label::seepage_max_base_land){ type=_fpl_max_waterlevel_seepage::land_base; } else if(buffer==fpl_label::seepage_max_one_third){ type=_fpl_max_waterlevel_seepage::one_third_waterlevel; } else if(buffer==fpl_label::seepage_max_kozeny){ type=_fpl_max_waterlevel_seepage::kozeny; } else{ Error msg; msg.set_msg("Fpl_Seepage_Calculator_Dike::convert_txt2seepagetype_max_waterlevel(const string txt)", "Can not convert this seepage maximum waterlevel type", "Check the given type", 1, false); ostringstream info; info << "seepage maximum waterlevel type: " << txt << endl; info << "Possible types: "<< endl; info << " "<<fpl_label::seepage_max_base_land << endl; info << " "<<fpl_label::seepage_max_one_third << endl; info << " "<<fpl_label::seepage_max_kozeny << endl; msg.make_second_info(info.str()); throw msg; } return type; } //Convert a seepage type at maximum waterlevel (_fpl_max_waterlevel_seepage) into a string (static) string Fpl_Seepage_Calculator_Dike::convert_seepagetype_max_waterlevel2txt(const _fpl_max_waterlevel_seepage type){ string buffer; switch(type){ case _fpl_max_waterlevel_seepage::land_base: buffer=fpl_label::seepage_max_base_land; break; case _fpl_max_waterlevel_seepage::one_third_waterlevel: buffer=fpl_label::seepage_max_one_third; break; case _fpl_max_waterlevel_seepage::kozeny: buffer=fpl_label::seepage_max_kozeny; break; default: buffer=label::unknown_type; } return buffer; } //Convert a string into seepage type at minimum waterlevel (_fpl_min_waterlevel_seepage) (static) _fpl_min_waterlevel_seepage Fpl_Seepage_Calculator_Dike::convert_txt2seepagetype_min_waterlevel(const string txt){ _fpl_min_waterlevel_seepage type; string buffer=txt; functions::clean_string(&buffer); functions::convert_string2lower_case(&buffer); if(buffer==fpl_label::seepage_min_base_land){ type=_fpl_min_waterlevel_seepage::water_base; } else if(buffer==fpl_label::seepage_min_one_third){ type=_fpl_min_waterlevel_seepage::one_third_mid_waterlevel; } else{ Error msg; msg.set_msg("Fpl_Seepage_Calculator_Dike::convert_txt2seepagetype_min_waterlevel(const string txt)", "Can not convert this seepage minimum waterlevel type", "Check the given type", 1, false); ostringstream info; info << "Seepage minimum waterlevel type: " << txt << endl; info << "Possible types: "<< endl; info << " "<<fpl_label::seepage_min_base_land << endl; info << " "<<fpl_label::seepage_min_one_third << endl; msg.make_second_info(info.str()); throw msg; } return type; } //Convert a seepage type at minimum waterlevel (_fpl_min_waterlevel_seepage) into a string (static) string Fpl_Seepage_Calculator_Dike::convert_seepagetype_min_waterlevel2txt(const _fpl_min_waterlevel_seepage type){ string buffer; switch(type){ case _fpl_min_waterlevel_seepage::water_base: buffer=fpl_label::seepage_min_base_land; break; case _fpl_min_waterlevel_seepage::one_third_mid_waterlevel: buffer=fpl_label::seepage_min_one_third; break; default: buffer=label::unknown_type; } return buffer; } //Write the default value of the control parameters into the database table (static) void Fpl_Seepage_Calculator_Dike::set_predefined_data2control_table(QSqlDatabase *ptr_database, QSqlQuery *model, int *id_glob, ostringstream *fix_string){ try{ Fpl_Mc_Sim::set_table(ptr_database); } catch(Error msg){ throw msg; } ostringstream total; //Keystring for calculation method for maximum waterlevel ostringstream query_string; query_string << " VALUES ( "; query_string << *id_glob << " , " ; query_string <<"'"<< fpl_seepage_method::seepage_maximum <<"'"<< " , " ; query_string <<"'"<< fpl_label::seepage_max_one_third << "' , " ; query_string << "'Calculation method for the maximum waterlevel: "<< fpl_label::seepage_max_base_land <<", "<<fpl_label::seepage_max_kozeny<<", "<<fpl_label::seepage_max_kozeny <<"' ) "; total <<fix_string->str() << query_string.str(); Data_Base::database_request(model, total.str(), ptr_database); total.str(""); query_string.str(""); (*id_glob)++; //Keystring for calculation method for minimum waterlevel query_string << " VALUES ( "; query_string << *id_glob << " , " ; query_string <<"'"<< fpl_seepage_method::seepage_minimum <<"'"<< " , " ; query_string <<"'"<< fpl_label::seepage_min_base_land << "' , " ; query_string << "'Calculation method for the minimum waterlevel: "<< fpl_label::seepage_min_base_land <<", "<<fpl_label::seepage_min_one_third <<"(just for deterministic calculation)' ) "; total <<fix_string->str() << query_string.str(); Data_Base::database_request(model, total.str(), ptr_database); total.str(""); query_string.str(""); (*id_glob)++; } //_________ //private //Calculate the seepage line: horizontal void Fpl_Seepage_Calculator_Dike::calculate_seepage_line_horizontal(double h_rel, Fpl_Seepage_Line_Point_List *point_list, const bool for_output){ if(h_rel>this->ptr_waterside_cub->get_ptr_last_point()->get_ycoordinate()){ h_rel=this->ptr_waterside_cub->get_ptr_last_point()->get_ycoordinate(); } if(h_rel<0.0){ h_rel=0.0; } //waterlevel is below landside dike base=> horizontal line if(h_rel<this->ptr_landside_cub->get_ptr_last_point()->get_ycoordinate()){ //find the interception point with waterside Geo_Segment buffer; buffer.set_coordinates(0.0,h_rel,this->ptr_landside_cub->get_ptr_last_point()->get_xcoordinate(),h_rel); _geo_interception_point buff_point_water; buff_point_water.interception_point.set_point_name(label::interception_point); for(int i=this->ptr_waterside_cub->get_number_segments()-1; i>=0; i--){ buffer.calc_interception(this->ptr_waterside_cub->get_segment(i),&buff_point_water); if(buff_point_water.interception_flag==true){ break; } } if(for_output==true){ point_list->add_new_point(buff_point_water.interception_point.get_xcoordinate(),buff_point_water.interception_point.get_ycoordinate(),true, this->ptr_cubature); } //descending waterlevel =>take a horizontal line for(int i=0; i< point_list->get_number_points(); i++){ //left or right of the dike body if(point_list->get_list_point(i)->get_x_coordinate()<buff_point_water.interception_point.get_xcoordinate()){ point_list->get_list_point(i)->set_waterlevel(h_rel); point_list->get_list_point(i)->set_inside_dike_body_flag(false); } //inbetween (dike body) else{ point_list->get_list_point(i)->set_waterlevel(h_rel); point_list->get_list_point(i)->set_inside_dike_body_flag(true); } } } //waterlevel horizontal else{ //find the interception point with waterside Geo_Segment buffer; buffer.set_coordinates(0.0,h_rel,this->ptr_landside_cub->get_ptr_last_point()->get_xcoordinate(),h_rel); _geo_interception_point buff_point_water; buff_point_water.interception_point.set_point_name(label::interception_point); for(int i=this->ptr_waterside_cub->get_number_segments()-1; i>=0; i--){ buffer.calc_interception(this->ptr_waterside_cub->get_segment(i),&buff_point_water); if(buff_point_water.interception_flag==true){ break; } } _geo_interception_point buff_point_land; buff_point_land.interception_point.set_point_name(label::interception_point); for(int i=0; i< this->ptr_landside_cub->get_number_segments(); i++){ buffer.calc_interception(this->ptr_landside_cub->get_segment(i),&buff_point_land); if(buff_point_land.interception_flag==true){ break; } } for(int i=0; i< point_list->get_number_points(); i++){ //left or right of the dike body if(point_list->get_list_point(i)->get_x_coordinate()<buff_point_water.interception_point.get_xcoordinate() || point_list->get_list_point(i)->get_x_coordinate()>buff_point_land.interception_point.get_xcoordinate()){ point_list->get_list_point(i)->set_waterlevel(h_rel); point_list->get_list_point(i)->set_inside_dike_body_flag(false); } //inbetween (dike body) else{ point_list->get_list_point(i)->set_waterlevel(h_rel); point_list->get_list_point(i)->set_inside_dike_body_flag(true); } } } } //Calculate the seepage line to the mid: one third of the waterlevel at the crest mid at the waterside to waterlevel at crest mid; the rest have to be calculated before void Fpl_Seepage_Calculator_Dike::calculate_seepage_line_mid_water_one_third(double h_rel, Fpl_Seepage_Line_Point_List *point_list, const bool for_output){ if(h_rel>this->ptr_waterside_cub->get_ptr_last_point()->get_ycoordinate()){ h_rel=this->ptr_waterside_cub->get_ptr_last_point()->get_ycoordinate(); } if(h_rel<0.0){ h_rel=0.0; } Fpl_Seepage_Line_Point *mid_point; mid_point=point_list->get_list_point(0); //find the interception point with waterside Geo_Segment buffer; buffer.set_coordinates(0.0,mid_point->get_waterlevel()*1.0/3.0,mid_point->get_x_coordinate(),mid_point->get_waterlevel()*1.0/3.0); _geo_interception_point buff_point_real_water; buff_point_real_water.interception_point.set_point_name(label::interception_point); for(int i=0; i<this->ptr_waterside_cub->get_number_segments(); i++){ buffer.calc_interception(this->ptr_waterside_cub->get_segment(i),&buff_point_real_water); if(buff_point_real_water.interception_flag==true){ break; } } buffer.set_coordinates(buff_point_real_water.interception_point.get_xcoordinate(),buff_point_real_water.interception_point.get_ycoordinate(), mid_point->get_x_coordinate(),mid_point->get_waterlevel()); if(for_output==true){ point_list->add_new_point(buff_point_real_water.interception_point.get_xcoordinate(),buff_point_real_water.interception_point.get_ycoordinate(),true, this->ptr_cubature); mid_point=point_list->get_list_point(0); } double deltay=mid_point->get_waterlevel()-buff_point_real_water.interception_point.get_ycoordinate(); double deltax=mid_point->get_x_coordinate()-buff_point_real_water.interception_point.get_xcoordinate(); for(int i=0; i< point_list->get_number_points(); i++){ //left of the waterside interception if(point_list->get_list_point(i)->get_x_coordinate()<buff_point_real_water.interception_point.get_xcoordinate()){ point_list->get_list_point(i)->set_waterlevel(buff_point_real_water.interception_point.get_ycoordinate()); point_list->get_list_point(i)->set_inside_dike_body_flag(true); } //right of the mid point else if(point_list->get_list_point(i)->get_x_coordinate()> mid_point->get_x_coordinate()){ //do nothing it has to be set before } //inbetween else{ double y=buff_point_real_water.interception_point.get_ycoordinate()+(point_list->get_list_point(i)->get_x_coordinate()-buff_point_real_water.interception_point.get_xcoordinate())* deltay/deltax; if(y<=point_list->get_list_point(i)->get_y_coordinate_cubature()){ point_list->get_list_point(i)->set_waterlevel(y); } else{ point_list->get_list_point(i)->set_waterlevel(point_list->get_list_point(i)->get_y_coordinate_cubature()); } point_list->get_list_point(i)->set_inside_dike_body_flag(true); } } } //Calculate the seepage line to the mid: base point at the waterside to the waterlevel at the crest mid; the rest have to be calculated before void Fpl_Seepage_Calculator_Dike::calculate_seepage_line_mid_water_base(double h_rel, Fpl_Seepage_Line_Point_List *point_list, const bool ){ if(h_rel>this->ptr_waterside_cub->get_ptr_last_point()->get_ycoordinate()){ h_rel=this->ptr_waterside_cub->get_ptr_last_point()->get_ycoordinate(); } if(h_rel<0.0){ h_rel=0.0; } Fpl_Seepage_Line_Point *mid_point; mid_point=point_list->get_list_point(0); //find the interception point with waterside Geo_Segment buffer; buffer.set_coordinates(0.0,0.0,mid_point->get_x_coordinate(),mid_point->get_waterlevel()); _geo_interception_point buff_point_water; buff_point_water.interception_point.set_point_name(label::interception_point); for(int i=this->ptr_waterside_cub->get_number_segments()-1; i>=0; i--){ buffer.calc_interception(this->ptr_waterside_cub->get_segment(i),&buff_point_water); if(buff_point_water.interception_flag==true){ break; } } double deltay=mid_point->get_waterlevel()-buff_point_water.interception_point.get_ycoordinate(); double deltax=mid_point->get_x_coordinate()-buff_point_water.interception_point.get_xcoordinate(); for(int i=0; i< point_list->get_number_points(); i++){ //left of the waterside if(point_list->get_list_point(i)->get_x_coordinate()<0.0){ point_list->get_list_point(i)->set_waterlevel(0.0); point_list->get_list_point(i)->set_inside_dike_body_flag(true); } //right of the mid point else if(point_list->get_list_point(i)->get_x_coordinate()> mid_point->get_x_coordinate()){ //do nothing it has to be set before } //inbetween else{ double y=buff_point_water.interception_point.get_ycoordinate()+(point_list->get_list_point(i)->get_x_coordinate()-buff_point_water.interception_point.get_xcoordinate())* deltay/deltax; if(y<=point_list->get_list_point(i)->get_y_coordinate_cubature()){ point_list->get_list_point(i)->set_waterlevel(y); } else{ point_list->get_list_point(i)->set_waterlevel(point_list->get_list_point(i)->get_y_coordinate_cubature()); } point_list->get_list_point(i)->set_inside_dike_body_flag(true); } } } //Output the seepage line: to the landside base point void Fpl_Seepage_Calculator_Dike::calculate_seepage_line_land_base(double h_rel, Fpl_Seepage_Line_Point_List *point_list, const bool for_output){ if(h_rel>this->ptr_waterside_cub->get_ptr_last_point()->get_ycoordinate()){ h_rel=this->ptr_waterside_cub->get_ptr_last_point()->get_ycoordinate(); } if(h_rel<0.0){ h_rel=0.0; } //waterlevel is below landside dike base=> horizontal line if(h_rel<this->ptr_landside_cub->get_ptr_last_point()->get_ycoordinate()){ this->calculate_seepage_line_horizontal(h_rel, point_list,for_output); } //waterlevel is above landside dike base else{ //find the interception point with waterside Geo_Segment buffer; buffer.set_coordinates(0.0,h_rel,this->ptr_landside_cub->get_ptr_last_point()->get_xcoordinate(),h_rel); _geo_interception_point buff_point_water; buff_point_water.interception_point.set_point_name(label::interception_point); for(int i=0; i<this->ptr_waterside_cub->get_number_segments(); i++){ buffer.calc_interception(this->ptr_waterside_cub->get_segment(i),&buff_point_water); if(buff_point_water.interception_flag==true){ break; } } if(for_output==true){ point_list->add_new_point(buff_point_water.interception_point.get_xcoordinate(),buff_point_water.interception_point.get_ycoordinate(),true, this->ptr_cubature); } //find the interception point with landside buffer.set_coordinates(buff_point_water.interception_point.get_xcoordinate(),buff_point_water.interception_point.get_ycoordinate(),this->ptr_landside_cub->get_ptr_last_point()->get_xcoordinate(),this->ptr_landside_cub->get_ptr_last_point()->get_ycoordinate()); _geo_interception_point buff_point_land; buff_point_land.interception_point.set_point_name(label::interception_point); for(int i=0; i<this->ptr_landside_cub->get_number_segments(); i++){ buffer.calc_interception(this->ptr_landside_cub->get_segment(i),&buff_point_land); if(buff_point_land.interception_flag==true){ break; } } if(for_output==true){ point_list->add_new_point(buff_point_land.interception_point.get_xcoordinate(),buff_point_land.interception_point.get_ycoordinate(),true, this->ptr_cubature); } double deltay=buff_point_water.interception_point.get_ycoordinate()-buff_point_land.interception_point.get_ycoordinate(); double deltax=buff_point_land.interception_point.get_xcoordinate()-buff_point_water.interception_point.get_xcoordinate(); double h_buff=0.0; for(int i=0; i< point_list->get_number_points(); i++){ //left of the waterside base if(point_list->get_list_point(i)->get_x_coordinate()<buff_point_water.interception_point.get_xcoordinate()){ h_buff=h_rel; point_list->get_list_point(i)->set_waterlevel(h_buff); } //right of the landside base else if(point_list->get_list_point(i)->get_x_coordinate()> buff_point_land.interception_point.get_xcoordinate()){ h_buff=buff_point_land.interception_point.get_ycoordinate(); point_list->get_list_point(i)->set_waterlevel(h_buff); if(h_buff<=point_list->get_list_point(i)->get_y_coordinate_cubature()){ point_list->get_list_point(i)->set_waterlevel(h_buff); } else{ point_list->get_list_point(i)->set_waterlevel(point_list->get_list_point(i)->get_y_coordinate_cubature()); } } //inbetween else{ h_buff=h_rel-(point_list->get_list_point(i)->get_x_coordinate()-buff_point_water.interception_point.get_xcoordinate())* deltay/deltax; if(h_buff<=point_list->get_list_point(i)->get_y_coordinate_cubature()){ point_list->get_list_point(i)->set_waterlevel(h_buff); } else{ point_list->get_list_point(i)->set_waterlevel(point_list->get_list_point(i)->get_y_coordinate_cubature()); } } point_list->get_list_point(i)->set_inside_dike_body_flag(true); } } } //Output the seepage line: to the landside one third of the waterlevel void Fpl_Seepage_Calculator_Dike::calculate_seepage_line_land_one_third(double h_rel, Fpl_Seepage_Line_Point_List *point_list, const bool for_output){ if(h_rel>this->ptr_waterside_cub->get_ptr_last_point()->get_ycoordinate()){ h_rel=this->ptr_waterside_cub->get_ptr_last_point()->get_ycoordinate(); } if(h_rel<0.0){ h_rel=0.0; } //waterlevel is below landside dike base=> horizontal line if(h_rel<this->ptr_landside_cub->get_ptr_last_point()->get_ycoordinate()){ this->calculate_seepage_line_horizontal(h_rel, point_list,for_output); } //waterlevel is above landside dike base else{ //find the interception point with waterside Geo_Segment buffer; buffer.set_coordinates(0.0,h_rel,this->ptr_landside_cub->get_ptr_last_point()->get_xcoordinate(),h_rel); _geo_interception_point buff_point_water; buff_point_water.interception_point.set_point_name(label::interception_point); for(int i=0; i<this->ptr_waterside_cub->get_number_segments(); i++){ buffer.calc_interception(this->ptr_waterside_cub->get_segment(i),&buff_point_water); if(buff_point_water.interception_flag==true){ break; } } if(for_output==true){ point_list->add_new_point(buff_point_water.interception_point.get_xcoordinate(),buff_point_water.interception_point.get_ycoordinate(),true, this->ptr_cubature); } //find the interception point with landside: first horizontal line at 1/3 of the waterlevel buffer.set_coordinates(buff_point_water.interception_point.get_xcoordinate(),buff_point_water.interception_point.get_ycoordinate()*1.0/3.0+this->ptr_landside_cub->get_ptr_last_point()->get_ycoordinate()*2.0/3.0, this->ptr_landside_cub->get_ptr_last_point()->get_xcoordinate(),buff_point_water.interception_point.get_ycoordinate()*1.0/3.0+this->ptr_landside_cub->get_ptr_last_point()->get_ycoordinate()*2.0/3.0); _geo_interception_point buff_point_land; buff_point_land.interception_point.set_point_name(label::interception_point); for(int i=0; i<this->ptr_landside_cub->get_number_segments(); i++){ buffer.calc_interception(this->ptr_landside_cub->get_segment(i),&buff_point_land); if(buff_point_land.interception_flag==true){ break; } } //find the interception point with landside: second line waterlevel to 1/3 of the waterlevel buffer.set_coordinates(buff_point_water.interception_point.get_xcoordinate(),buff_point_water.interception_point.get_ycoordinate(),buff_point_land.interception_point.get_xcoordinate(),buff_point_land.interception_point.get_ycoordinate()); for(int i=0; i<this->ptr_landside_cub->get_number_segments(); i++){ buffer.calc_interception(this->ptr_landside_cub->get_segment(i),&buff_point_land); if(buff_point_land.interception_flag==true){ break; } } if(for_output==true){ point_list->add_new_point(buff_point_land.interception_point.get_xcoordinate(),buff_point_land.interception_point.get_ycoordinate(),true, this->ptr_cubature); } double deltay=buff_point_water.interception_point.get_ycoordinate()-buff_point_land.interception_point.get_ycoordinate(); double deltax=buff_point_land.interception_point.get_xcoordinate()-buff_point_water.interception_point.get_xcoordinate(); double h_buff=0.0; for(int i=0; i< point_list->get_number_points(); i++){ //left of the waterside base if(point_list->get_list_point(i)->get_x_coordinate()<buff_point_water.interception_point.get_xcoordinate()){ h_buff=h_rel; point_list->get_list_point(i)->set_waterlevel(h_buff); } //right of the landside base else if(point_list->get_list_point(i)->get_x_coordinate()>buff_point_land.interception_point.get_xcoordinate()){ h_buff=buff_point_land.interception_point.get_ycoordinate(); point_list->get_list_point(i)->set_waterlevel(h_buff); if(h_buff<=point_list->get_list_point(i)->get_y_coordinate_cubature()){ point_list->get_list_point(i)->set_waterlevel(h_buff); } else{ point_list->get_list_point(i)->set_waterlevel(point_list->get_list_point(i)->get_y_coordinate_cubature()); } } //inbetween else{ h_buff=h_rel-(point_list->get_list_point(i)->get_x_coordinate()-buff_point_water.interception_point.get_xcoordinate())* deltay/deltax; if(h_buff<=point_list->get_list_point(i)->get_y_coordinate_cubature()){ point_list->get_list_point(i)->set_waterlevel(h_buff); } else{ point_list->get_list_point(i)->set_waterlevel(point_list->get_list_point(i)->get_y_coordinate_cubature()); } } point_list->get_list_point(i)->set_inside_dike_body_flag(true); } } } //Calculate the seepage line: to the landside after the Kozeny void Fpl_Seepage_Calculator_Dike::calculate_seepage_line_land_kozeny(double h_rel, Fpl_Seepage_Line_Point_List *point_list, const bool for_output){ if(h_rel>this->ptr_waterside_cub->get_ptr_last_point()->get_ycoordinate()){ h_rel=this->ptr_waterside_cub->get_ptr_last_point()->get_ycoordinate(); } if(h_rel<0.0){ h_rel=0.0; } //waterlevel is below landside dike base=> horizontal line if(h_rel<this->ptr_landside_cub->get_ptr_last_point()->get_ycoordinate()){ this->calculate_seepage_line_horizontal(h_rel, point_list, for_output); } //waterlevel is above landside dike base else{ //find the interception point with waterside Geo_Segment buffer; Geo_Point *land_point; land_point=this->ptr_landside_cub->get_ptr_last_point(); buffer.set_coordinates(0.0,h_rel,this->ptr_landside_cub->get_ptr_last_point()->get_xcoordinate(),h_rel); _geo_interception_point buff_point_water; buff_point_water.interception_point.set_point_name(label::interception_point); int index_segment_water=0; for(int i=0; i<this->ptr_waterside_cub->get_number_segments(); i++){ buffer.calc_interception(this->ptr_waterside_cub->get_segment(i),&buff_point_water); if(buff_point_water.interception_flag==true){ index_segment_water=i; break; } } if(for_output==true){ point_list->add_new_point(buff_point_water.interception_point.get_xcoordinate(),buff_point_water.interception_point.get_ycoordinate(),true, this->ptr_cubature); } double s=0.0; bool interception=false; double h_drei=0.0; double l_strich=0.0; int index_segment_land=0; double c1=0.0; double c2=0.0; double c3=0.0; int counter=this->ptr_landside_cub->get_number_segments()-1; index_segment_land=counter; Geo_Point_List sq_interception; do{ interception=false; //coordinate of the water base point is (0/0) s=buff_point_water.interception_point.get_xcoordinate(); c1=pow((h_rel-land_point->get_ycoordinate()),2.0); c3=(buff_point_water.interception_point.get_xcoordinate()-0.3*s); double l=this->ptr_landside_cub->get_segment(counter)->point2.get_xcoordinate()-buff_point_water.interception_point.get_xcoordinate(); double d=l+0.3*s; double y_null=pow((c1+pow(d,2.0)),0.5)-d; double beta_land=_Geo_Geometrie::rad_to_grad(atan(abs(this->ptr_landside_cub->get_segment(counter)->get_gradient()))); double a=0.0; h_drei=0.0; if(beta_land<30.0){ a=pow(d,2.0)-pow((h_rel-land_point->get_ycoordinate()),2.0)*pow(1.0/tan(_Geo_Geometrie::grad_to_rad(beta_land)),2.0); if(a<0.0){ interception=true; counter--; if(counter<0){ Error msg=this->set_error(1); throw msg; } land_point=&(this->ptr_landside_cub->get_segment(counter)->point2); continue; } a=pow((pow((h_rel-land_point->get_ycoordinate()),2.0)+pow(d,2.0)),0.5)-(pow(a,0.5)); if(a>this->ptr_landside_cub->get_segment(counter)->get_distance()){ interception=true; counter--; if(counter<0){ Error msg=this->set_error(1); throw msg; } land_point=&(this->ptr_landside_cub->get_segment(counter)->point2); continue; } } else{ //approximated with a line a=y_null/(1.0-cos(_Geo_Geometrie::grad_to_rad(beta_land)))*(0.00256*beta_land+0.53); } h_drei=a*sin(_Geo_Geometrie::grad_to_rad(beta_land)); l_strich=d-h_drei*1.0/abs(this->ptr_landside_cub->get_segment(counter)->get_gradient()); c2=(c1-pow(h_drei,2.0))/l_strich; //check interception with landside; if there is one, change the relevant segment /*for(int i=0; i< counter ;i++){ this->ptr_landside_cub->get_segment(i)->calc_interception_square_root(&sq_interception,c1,c2,c3, land_point->get_ycoordinate()); if(sq_interception.get_number_points()>0){ interception=true; counter=i; land_point=&this->ptr_landside_cub->get_segment(counter)->point2; break; } }*/ } while(interception==true); if(for_output==true){ point_list->add_new_point(this->ptr_landside_cub->get_segment(counter)->point2.get_xcoordinate()-h_drei/abs(this->ptr_landside_cub->get_segment(counter)->get_gradient()),0.0,true, this->ptr_cubature); } double x_buff=0.0; double y_buff=0.0; Geo_Point buffer_point; buffer_point.set_point_coordinate(buff_point_water.interception_point.get_xcoordinate()+h_rel*this->ptr_waterside_cub->get_segment(index_segment_water)->get_gradient(),0.0); buffer.set_points(&buff_point_water.interception_point, &buffer_point); buffer.calc_interception_square_root(&sq_interception,c1,c2,c3, land_point->get_ycoordinate()); if(sq_interception.get_number_points()==0){ Error msg=this->set_error(0); throw msg; } else{ buffer.set_points(&buff_point_water.interception_point, sq_interception.get_ptr_point_max_y()); if(for_output==true){ point_list->add_new_point(sq_interception.get_ptr_point_max_y()->get_xcoordinate(),sq_interception.get_ptr_point_max_y()->get_ycoordinate(),true, this->ptr_cubature); } } /*for(int i=0; i< point_list->get_number_points(); i++){ cout << point_list->get_list_point(i)->get_x_coordinate() << " "<<endl; }*/ for(int i=0; i< point_list->get_number_points(); i++){ x_buff=point_list->get_list_point(i)->get_x_coordinate(); //left of the waterside base if(x_buff<buff_point_water.interception_point.get_xcoordinate()){ point_list->get_list_point(i)->set_waterlevel(h_rel); point_list->get_list_point(i)->set_inside_dike_body_flag(true); } //right of the landside base else if(x_buff>this->ptr_landside_cub->get_segment(index_segment_land)->point2.get_xcoordinate()){ point_list->get_list_point(i)->set_waterlevel(this->ptr_landside_cub->get_segment(index_segment_land)->point2.get_ycoordinate()); point_list->get_list_point(i)->set_inside_dike_body_flag(true); } //use a straight line else if(x_buff<=buffer.point2.get_xcoordinate()){ y_buff=buffer.get_gradient()*x_buff+buffer.get_y_interception(); point_list->get_list_point(i)->set_waterlevel(y_buff); point_list->get_list_point(i)->set_inside_dike_body_flag(true); } //inbetween else{ double h_buff=0.0; y_buff=c2; x_buff=x_buff-c3; y_buff=y_buff*(x_buff); if(c1>=y_buff){ y_buff=pow(c1-y_buff,0.5); if(y_buff>=h_drei-constant::meter_epsilon){ h_buff=y_buff+land_point->get_ycoordinate(); } else{ if(i==0){ Error msg=this->set_error(2); throw msg; } h_buff=point_list->get_list_point(i-1)->get_waterlevel(); } } else{ if(i==0){ Error msg=this->set_error(2); throw msg; } h_buff=point_list->get_list_point(i-1)->get_waterlevel(); } if(h_buff<=point_list->get_list_point(i)->get_y_coordinate_cubature()){ point_list->get_list_point(i)->set_waterlevel(h_buff); } else{ point_list->get_list_point(i)->set_waterlevel(point_list->get_list_point(i)->get_y_coordinate_cubature()); } point_list->get_list_point(i)->set_inside_dike_body_flag(true); } } } } //Set warning(s) Warning Fpl_Seepage_Calculator_Dike::set_warning(const int warn_type){ string place="Fpl_Seepage_Calculator_Dike::"; string help; string reason; string reaction; int type=0; Warning msg; stringstream info; switch (warn_type){ case 0://method is not applicable place.append("set_input(QSqlDatabase *ptr_database, const bool frc_sim, const bool output)") ; reason="The method of 1/3 for the waterside seepage line calculation is not applicable in a frc-calculation"; reaction="Method is changed to the base point method"; help= "Seepage calculation method (waterside)"; type=7; break; default: place.append("set_warning(const int warn_type)"); reason ="Unknown flag!"; help="Check the flags"; type=5; } msg.set_msg(place,reason,help,reaction,type); msg.make_second_info(info.str()); return msg; }; //set the error Error Fpl_Seepage_Calculator_Dike::set_error(const int err_type){ string place="Fpl_Seepage_Calculator_Dike::"; string help; string reason; int type=0; bool fatal=false; stringstream info; Error msg; switch (err_type){ case 0://no interception found place.append("calculate_seepage_line_land_kozeny(double h_rel, Fpl_Seepage_Line_Point_List *point_list)"); reason="Can not find any interception between the starting line and the Kozeny parabola"; help="Check the code"; type=6; break; case 1://land side to flat place.append("calculate_seepage_line_land_kozeny(double h_rel, Fpl_Seepage_Line_Point_List *point_list)"); reason="Can not find any interception between the Kozeny parabola and the land side cubatur; it is to flat"; help="Check the land side cubature"; type=11; break; case 2://land side to flat place.append("calculate_seepage_line_land_kozeny(double h_rel, Fpl_Seepage_Line_Point_List *point_list)"); reason="There is no point in list before i=0"; help="Check the code"; type=11; break; default: place.append("set_error(const int err_type)"); reason ="Unknown flag!"; help="Check the flags"; type=6; } msg.set_msg(place, reason, help, type, fatal); msg.make_second_info(info.str()); return msg; }
39.884698
262
0.764947
dabachma
e0a00fc1c7dc3aa77dd5dd692eb750da571331c4
2,136
cc
C++
source/src/Analysis/OverlayEstimator/TreeProcessor.cc
rete/Baboon
e5b2cfe6b9e5b5a41c2c68feda84b8df109eb086
[ "FSFAP" ]
null
null
null
source/src/Analysis/OverlayEstimator/TreeProcessor.cc
rete/Baboon
e5b2cfe6b9e5b5a41c2c68feda84b8df109eb086
[ "FSFAP" ]
null
null
null
source/src/Analysis/OverlayEstimator/TreeProcessor.cc
rete/Baboon
e5b2cfe6b9e5b5a41c2c68feda84b8df109eb086
[ "FSFAP" ]
null
null
null
/// \file TreeProcessor.cc /* * * TreeProcessor.cc source template generated by fclass * Creation date : ven. mai 3 2013 * Copyright (c) CNRS , IPNL * * All Right Reserved. * Use and copying of these libraries and preparation of derivative works * based upon these libraries are permitted. Any copy of these libraries * must include this copyright notice. * * @author : rete */ #include "Analysis/OverlayEstimator/TreeProcessor.hh" namespace baboon { TreeProcessor::TreeProcessor( TTree *t ) { treeWrapper = new InputTTreeWrapper(t); } TreeProcessor::~TreeProcessor() { delete treeWrapper; } void TreeProcessor::Loop() { TH1 *purity1Histo = new TH1D("purity1Histo","",100,0,100); TH1 *purity2Histo = new TH1D("purity2Histo","",100,0,100); TH1 *contamination1Histo = new TH1D("contamination1Histo","",100,0,100); TH1 *contamination2Histo = new TH1D("contamination2Histo","",100,0,100); int nbOfEntries = treeWrapper->GetNbOfEntries(); for ( int jentry=0 ; jentry<nbOfEntries; jentry++ ) { EstimatorVars tempVars; treeWrapper->LoadEntry(jentry); bool showersFound; treeWrapper->GetValue("showersFound",showersFound); if( !showersFound ) continue; treeWrapper->GetValue("contamination1",tempVars.contamination1); treeWrapper->GetValue("contamination2",tempVars.contamination2); treeWrapper->GetValue("purity1",tempVars.purity1); treeWrapper->GetValue("purity2",tempVars.purity2); estimatorMeans.algorithmEfficiency++; purity1Histo->Fill(tempVars.purity1*100); purity2Histo->Fill(tempVars.purity2*100); contamination1Histo->Fill(tempVars.contamination1*100); contamination2Histo->Fill(tempVars.contamination2*100); } estimatorMeans.algorithmEfficiency /= double(nbOfEntries); estimatorMeans.contamination1 = contamination1Histo->GetMean(); estimatorMeans.contamination2 = contamination2Histo->GetMean(); estimatorMeans.purity1 = purity1Histo->GetMean(); estimatorMeans.purity2 = purity2Histo->GetMean(); delete purity1Histo; delete purity2Histo; delete contamination1Histo; delete contamination2Histo; } } // namespace
28.105263
74
0.742509
rete
e0a0463fb6b548ea1917d880d9df81d6be1553d2
673
cpp
C++
cpp/july/day_19_Add Binary.cpp
kashyapvinay/leetcode-challenge
750b0056cb547dc5266d142a9a5048ebd50d8ae3
[ "MIT" ]
1
2020-06-01T11:35:46.000Z
2020-06-01T11:35:46.000Z
cpp/july/day_19_Add Binary.cpp
kashyapvinay/leetcode-challenge
750b0056cb547dc5266d142a9a5048ebd50d8ae3
[ "MIT" ]
null
null
null
cpp/july/day_19_Add Binary.cpp
kashyapvinay/leetcode-challenge
750b0056cb547dc5266d142a9a5048ebd50d8ae3
[ "MIT" ]
null
null
null
class Solution { public: string addBinary(string a, string b) { string res = ""; int i = 0, j, c, s; reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); c = 0; while(i < a.size() || i < b.size()){ s = c; if(i < a.size()){ s += a[i] == '1' ? 1 : 0; } if(i < b.size()){ s += b[i] == '1' ? 1 : 0; } c = s / 2; s = s % 2; res += s ? '1' : '0'; i++; } if(c){ res += '1'; } reverse(res.begin(), res.end()); return res; } };
23.206897
44
0.294205
kashyapvinay
e0a06b63d3b458bbbfe2303704913d618734eae6
2,558
cpp
C++
PID_Autotune/lib/QuadEnc/QuadEnc.cpp
PassionForRobotics/DeadReconQuadratureEncoder
d112ea1eb3cd3014347cb88ee593babddd72b353
[ "MIT" ]
null
null
null
PID_Autotune/lib/QuadEnc/QuadEnc.cpp
PassionForRobotics/DeadReconQuadratureEncoder
d112ea1eb3cd3014347cb88ee593babddd72b353
[ "MIT" ]
null
null
null
PID_Autotune/lib/QuadEnc/QuadEnc.cpp
PassionForRobotics/DeadReconQuadratureEncoder
d112ea1eb3cd3014347cb88ee593babddd72b353
[ "MIT" ]
null
null
null
#include <Arduino.h> #include "QuadEnc.h" #include <DeadReckoner.h> #define SPEED_COMPUTE_INTERVAL (10.0) #define ENCODER_PULSES_PER_REV (334) #define SPEED_MUTIPLIER (9000.0) // To match output QuadEncoder::QuadEncoder(int _pin_1, int _pin_2)//, float _radius, float _separation, int _ticks_per_rev, int _compute_interval) { this->pin_1_ = _pin_1; this->pin_2_ = _pin_2; //this->radius_ = _radius; //this->separation_ = _separation; //this->ticks_per_rev_ = _ticks_per_rev; //this->compute_interval_ = _compute_interval; } volatile void QuadEncoder::pulseA(void) { // Test transition this->pastA_ = digitalRead(this->pin_1_) == HIGH; // and adjust counter + if A leads B position_ += (this->pastA_ == this->pastB_) ? +1 : -1; } volatile void QuadEncoder::pulseB(void) { // Test transition this->pastB_ = digitalRead(this->pin_2_) == HIGH; // and adjust counter + if A leads B position_ += (this->pastA_ == this->pastB_) ? +1 : -1; } volatile void QuadEncoder::updateRPM(void) { if (millis() - this->prev_speed_compute_time_ > SPEED_COMPUTE_INTERVAL) { this->prev_speed_compute_time_ = millis(); long long int ticks = (double) this->position_; double delta_pos = ((double)ticks - (double)this->last_position_)/((double)ENCODER_PULSES_PER_REV); this->last_position_ = ticks; this->meas_rps_ = ticks%ENCODER_PULSES_PER_REV; this->rp10millis_ = (double)delta_pos/(double)SPEED_COMPUTE_INTERVAL; this->rps_ = this->rp10millis_*100.0; this->rpm_ = this->rps_*60.0; } } void QuadEncoder::begin( void (*isr_cb_A)(void), void (*isr_cb_B)(void) ) { pinMode(this->pin_1_, INPUT); //turn on pullup resistor //digitalWrite(encoder0PinA, HIGH); //ONLY FOR SOME ENCODER(MAGNETIC)!!!! pinMode(this->pin_2_, INPUT); //turn on pullup resistor //digitalWrite(encoder0PinB, HIGH); //ONLY FOR SOME ENCODER(MAGNETIC)!!!! //pastA_ = (bool)digitalRead(this->pin_1_); //initial value of channel A; //pastB_ = (bool)digitalRead(this->pin_2_); //and channel B //To speed up even more, you may define manually the ISRs // encoder A channel on interrupt 0 (Arduino's pin 2) attachInterrupt(digitalPinToInterrupt(this->pin_1_), isr_cb_A, RISING); // encoder B channel pin on interrupt 1 (Arduino's pin 3) attachInterrupt(digitalPinToInterrupt(this->pin_2_), isr_cb_B, CHANGE); } void QuadEncoder::reset(int _v) { position_ = _v; }
27.804348
130
0.666927
PassionForRobotics
e0a15e7e55f505dd57d84fd8639e330a8a3e04af
334
cpp
C++
leetcode/126. Word Ladder II/main.cpp
joycse06/LeetCode-1
ad105bd8c5de4a659c2bbe6b19f400b926c82d93
[ "Fair" ]
1
2021-02-11T01:23:10.000Z
2021-02-11T01:23:10.000Z
leetcode/126. Word Ladder II/main.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
null
null
null
leetcode/126. Word Ladder II/main.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
1
2021-03-25T17:11:14.000Z
2021-03-25T17:11:14.000Z
#include "../+Helper/Helper.h" #include "s2.cpp" #include <cstdio> int main() { Solution s; unordered_set<string> d{"hot","cog","dot","dog","hit","lot","log"}; string a = "hit"; string b = "cog"; auto v = s.findLadders(a, b, d); for (auto vv : v) { for (auto s : vv) { cout << s << ","; } cout << endl; } return 0; }
18.555556
68
0.54491
joycse06
e0a9be48a2c317e296d85914fe77faa0f2a48d69
7,639
cpp
C++
cdl/InputLogger.cpp
RetroReversing/libRetroReversing
b0a029b76c92e38340550a5a21e2a0d2f6cb10db
[ "MIT" ]
8
2020-01-20T18:56:14.000Z
2022-01-16T02:00:49.000Z
cdl/InputLogger.cpp
RetroReversing/libRetroReversing
b0a029b76c92e38340550a5a21e2a0d2f6cb10db
[ "MIT" ]
9
2020-05-18T12:02:20.000Z
2022-02-13T05:41:37.000Z
cdl/InputLogger.cpp
RetroReversing/libRetroReversing
b0a029b76c92e38340550a5a21e2a0d2f6cb10db
[ "MIT" ]
4
2020-03-19T22:36:40.000Z
2021-07-05T02:53:09.000Z
#include "CDL.hpp" #include <queue> #include "../include/libRR.h" struct retro_input_descriptor desc[64]; int total_input_buttons=0; std::queue<unsigned long long> button_history; std::queue<unsigned long long> playback_button_history; // Should append is for when you were playing back a history and it reached the end and then you added more input bool libRR_should_append_history = false; void libRR_setInputDescriptor(struct retro_input_descriptor* descriptor, int total) { // printf("libRR_setInputDescriptor \n"); total_input_buttons = total; for (int i=0; i<total_input_buttons; i++) { // Copy libretro input descriptors to our own state desc[i] = { descriptor[i].port, descriptor[i].device, descriptor[i].index, descriptor[i].id, descriptor[i].description }; } } bool libRR_alreadyWarnedAboutEndOfLog = false; // // playback_fake_input_state_cb - plays back input // int lastPlayedBackFrame = 0; bool savePowerMode = true; int16_t playback_fake_input_state_cb(unsigned port, unsigned device, unsigned index, unsigned id) { // printf("playback_fake_input_state_cb\n"); if(port > 0) { // printf("We only support Port 0 (player 1)\n"); return 0; } if (playback_button_history.empty()) { if (!libRR_alreadyWarnedAboutEndOfLog) { printf("WARNING: button history was empty: probably at the end\n"); libRR_alreadyWarnedAboutEndOfLog = true; libRR_display_message("Ready to take new button input"); } libRR_should_append_history = true; libRR_should_playback_input = false; return 0; } // This can be called multiple times per frame, so we need to only pop it when the frame has changed int16_t button_state = playback_button_history.front(); if (RRCurrentFrame > lastPlayedBackFrame) { playback_button_history.pop(); if (button_state>0) { if (!savePowerMode) { libRR_display_message("Playback Pressed: %d",button_state); } } lastPlayedBackFrame = RRCurrentFrame; } if (id == RETRO_DEVICE_ID_JOYPAD_MASK) { return button_state; } return button_state & 1 << id; } retro_input_state_t libRR_playback() { return playback_fake_input_state_cb; } // // libRR_playback_next_input_state - only use when you can't use playback_fake_input_state_cb due to no bitmask support // unsigned long long libRR_playback_next_input_state() { if (playback_button_history.empty()) { printf("WARNING: button history was empty: probably at the end\n"); libRR_should_append_history = true; return 0; } unsigned long long button_state = playback_button_history.front(); playback_button_history.pop(); std::cout << "\nPlayed back:" << button_state; return button_state; } // // # libRR_log_input_state_bitmask - this is the prefered solution to use in a core if possible // void libRR_log_input_state_bitmask(retro_input_state_t input_cb) { int16_t ret = input_cb( 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_MASK ); button_history.push(ret); // printf("Logging input state frame:%d result:%d \n", RRCurrentFrame, ret); } retro_input_state_t libRR_handle_input(retro_input_state_t input_cb) { if (libRR_should_playback_input) { return libRR_playback(); } libRR_log_input_state_bitmask(input_cb); return input_cb; } // // # log_input_state - only use this if you can't use libRR_log_input_state_bitmask // void log_input_state(retro_input_state_t input_cb) { unsigned long long frameInputBitField = 0; for (int i=0; i<total_input_buttons; i++) { // printf("Logging button number: %d %d \n", i, desc[i].id); if (input_cb(desc[i].port, desc[i].device, desc[i].index, desc[i].id) != 0) { frameInputBitField |= 1ULL << desc[i].id; } } button_history.push(frameInputBitField); // printf("Logging input state frame:%d result:%d \n", RRCurrentFrame, frameInputBitField); } // max_number is used if you want to only save up to a particular frame number void libRR_resave_button_state_to_file(string filename, int max_number, json changes) { std::fstream output_file; // read the state before we open it as an output file printf("libRR_resave_button_state_to_file max_number: %d\n", max_number); libRR_read_button_state_from_file(filename, 0); output_file = std::fstream(filename, std::ios::out | std::ios::binary); int frame_number = 0; while (!playback_button_history.empty()) { unsigned long long button_state = playback_button_history.front(); // check for changes via the UI if (changes.contains(to_string(frame_number))) { unsigned long long newValue = changes[to_string(frame_number)]; printf("We have a change for frame number: %d value: %d \n", frame_number, newValue); output_file.write(reinterpret_cast<char*>(&newValue),sizeof(unsigned long long)); } else { output_file.write(reinterpret_cast<char*>(&button_state),sizeof(unsigned long long)); } playback_button_history.pop(); if (frame_number == max_number) { printf("Resaving button log, found Max value %d \n", frame_number); break; } frame_number++; } output_file.close(); libRR_read_button_state_from_file(filename, RRCurrentFrame); printf("End of libRR_resave_button_state_to_file\n"); } extern string current_playthrough_directory; string libRR_change_input_buttons(json changes) { libRR_resave_button_state_to_file(current_playthrough_directory+"button_log.bin", -1, changes); return "Success"; } // // # libRR_save_button_state_to_file - save all the keys pressed to a file // void libRR_save_button_state_to_file(string filename) { std::fstream output_file; // read the state before we open it as an output file printf("libRR_save_button_state_to_file\n"); // first read the whole file right from the start (frame 0) libRR_read_button_state_from_file(filename, 0); output_file = std::fstream(filename, std::ios::out | std::ios::binary); if (libRR_should_append_history) { // Use was playing back a history and now added additional logging printf("\n\n\nAppending history to previous\n\n\n"); while (!playback_button_history.empty()) { unsigned long long button_state = playback_button_history.front(); output_file.write(reinterpret_cast<char*>(&button_state),sizeof(unsigned long long)); playback_button_history.pop(); } } while (!button_history.empty()) { // std::cout << ' ' << button_history.front(); unsigned long long button_state = button_history.front(); output_file.write(reinterpret_cast<char*>(&button_state),sizeof(unsigned long long)); button_history.pop(); } output_file.close(); } // // # libRR_read_button_state_from_file - loads the buffer of input key presses to be run each frame // void libRR_read_button_state_from_file(string filename, int start_frame) { printf("libRR_read_button_state_from_file start frame: %d\n", start_frame); std::ifstream myfile(filename, std::ios_base::in | std::ios::binary); unsigned long long frameInputBitField = 255; lastPlayedBackFrame = 0; int loading_frame = 0; playback_button_history = {}; while (myfile.read(reinterpret_cast<char*>(&frameInputBitField), sizeof(unsigned long long))) { if (loading_frame >= start_frame) { // std::cout << ' ' << frameInputBitField; playback_button_history.push(frameInputBitField); } loading_frame++; } printf("Finished Reading input state frame:%d size:%d \n", start_frame, playback_button_history.size()); }
36.550239
127
0.716586
RetroReversing
e0a9d2102a913327888cdfaa8be0df079a3fedd5
2,886
cpp
C++
src/business/plate_recognition_worker.cpp
lvnux/midden
261e2661690e9212ccb90dc64a02fde40f6ce1a7
[ "MIT" ]
1
2021-06-13T14:13:31.000Z
2021-06-13T14:13:31.000Z
src/business/plate_recognition_worker.cpp
lvnux/midden
261e2661690e9212ccb90dc64a02fde40f6ce1a7
[ "MIT" ]
null
null
null
src/business/plate_recognition_worker.cpp
lvnux/midden
261e2661690e9212ccb90dc64a02fde40f6ce1a7
[ "MIT" ]
null
null
null
#include "plate_recognition_worker.h" #include "thread_macro.h" #include "user_thread_macro.h" #include "log.h" #include "car_http_thread.h" #include "general.h" #include "car_algo/pd_api.h" PlateRecognitionWorker* PlateRecognitionWorker::inst_ = new PlateRecognitionWorker(); PlateRecognitionWorker::PlateRecognitionWorker() { } PlateRecognitionWorker::~PlateRecognitionWorker() { } PlateRecognitionWorker* PlateRecognitionWorker::get_instance() { return inst_; } bool PlateRecognitionWorker::init(int gpu_index) { log_info("PD_Init on gpu [%d]", gpu_index); int ret = PD_Init(gpu_index); if (0 != ret) { log_error("PD_Init failed, ret [%d]", ret); return false; } return true; } void PlateRecognitionWorker::put_data(BaseMsg* msg) { que_.put_data(msg); } void PlateRecognitionWorker::run() { BaseMsg* msg = NULL; while (true) { msg = que_.get_data(); if (NULL == msg) { usleep(1000 * 10); } else { dispose(msg); delete msg; } } } void PlateRecognitionWorker::dispose(BaseMsg* msg) { if (NULL == msg) { return; } switch (msg->msg_type) { case MSG_TYPE_PLATE_RECOGNITION_REQUEST: { recognize_plate(msg); break; } case MSG_TYPE_HTTP_RESPONSE: { break; } case MSG_TYPE_TIMEOUT: { break; } default: { log_error("msg_type[%d] is invalied.", msg->msg_type); break; } } return; } void PlateRecognitionWorker::recognize_plate(BaseMsg* msg) { PlateRecognitionRequestMsg* request_msg = (PlateRecognitionRequestMsg*)msg; log_debug("get pic heigth: [%d], width: [%d], name: [%s]", request_msg->height, request_msg->width, request_msg->name.c_str()); std::string desc = "SUCCESS"; std::string plate_num; int64 start_detect_time = get_cur_microsecond(); int ret = -1; try { ret = PD_Detect(request_msg->height, request_msg->width, request_msg->img_data, plate_num, request_msg->name); if (0 != ret) { log_error("PD_Detect failed, ret [%d]", ret); plate_num = ""; desc = "PD_Detect failed"; } } catch(...) { log_error("PD_Detect cause exception"); plate_num = ""; desc = "PD_Detect failed"; } log_info("PD_Detect cost [%d]ms, ret [%d], plate_num [%s]", get_cur_microsecond() - start_detect_time, ret, plate_num.c_str()); PlateRecognitionResponseMsg* response_msg = new PlateRecognitionResponseMsg(); response_msg->msg_type = MSG_TYPE_PLATE_RECOGNITION_RESPONSE; response_msg->msg_sn = request_msg->msg_sn; response_msg->receive_time = request_msg->receive_time; response_msg->code = ret; response_msg->desc = desc; response_msg->plate_num = plate_num; CarHttpThread::get_instance()->put_data(response_msg); }
20.614286
112
0.646916
lvnux
e0aaac1f8352e2bc5057754bb2354cf49b9d6651
2,964
cpp
C++
docs/rgba_example.cpp
Clemapfel/jluna
5768f4b8520f28e219788d28c8e84418257c5994
[ "MIT" ]
102
2022-02-06T02:54:32.000Z
2022-03-30T12:56:07.000Z
docs/rgba_example.cpp
Clemapfel/jluna
5768f4b8520f28e219788d28c8e84418257c5994
[ "MIT" ]
9
2022-02-04T21:21:39.000Z
2022-03-18T20:44:08.000Z
docs/rgba_example.cpp
Clemapfel/jluna
5768f4b8520f28e219788d28c8e84418257c5994
[ "MIT" ]
6
2022-03-07T07:15:36.000Z
2022-03-14T14:56:29.000Z
// // Copyright 2022 Clemens Cords // Created on 19.04.22 by clem ([email protected]) // // this file summarizes all code from the usertype section of the manual // see: https://github.com/Clemapfel/jluna/blob/master/docs/manual.md#usertypes // #include <jluna.hpp> using namespace jluna; // define RGBA struct RGBA { float _red; // field _red float _green; // field _green float _blue; // field _blue float _alpha; // field _alpha // ctor RGBA(float r, float g, float b) : _red(r), _green(g), _blue(b), _alpha(1) {} // default ctor (required by jluna::Usertype) RGBA() : _red(0), _green(0), _blue(0), _alpha(1) {} }; // enable as usertype at compile time set_usertype_enabled(RGBA); int main() { jluna::initialize(); // add fields // field _red Usertype<RGBA>::add_property<float>( "_red", // name [](RGBA& in) -> float {return in._red;}, // boxing behavior [](RGBA& out, float in) -> void {out._red = in;} // unboxing behvaior ); // field _green Usertype<RGBA>::add_property<float>( "_green", [](RGBA& in) -> float {return in._green;}, [](RGBA& out, float in) -> void {out._green = in;} ); // field _blue Usertype<RGBA>::add_property<float>( "_blue", [](RGBA& in) -> float {return in._blue;}, [](RGBA& out, float in) -> void {out._blue = in;} ); // field _alpha Usertype<RGBA>::add_property<float>( "_alpha", [](RGBA& in) -> float {return in._alpha;}, [](RGBA& out, float in) -> void {out._alpha = in;} ); // julia-only field _value Usertype<RGBA>::add_property<float>( "_value", // name // boxing routine: compute value from red, green and blue [](RGBA& in) -> float { float max = 0; for (auto v : {in._red, in._green, in._blue}) max = std::max(v, max); return max; } ); // implement Usertype<RGBA>::implement(); // add additional ctor Main.safe_eval(R"( function RGBA(r, g, b, a) ::RGBA out = RGBA() out._red = r out._green = g out._blue = b out._alpha = a out._value = max(r, g, b, a) return out end )"); // usage Main.create_or_assign("jl_rgba", RGBA(0.75, 0.5, 0.1)); Main.safe_eval("println(jl_rgba)"); RGBA cpp_rgba = Main.safe_eval("return RGBA(0.5, 0.5, 0.3, 1.0)"); std::cout << "unboxed: " std::cout << cpp_rgba._red << " "; std::cout << cpp_rgba._green << " "; std::cout << cpp_rgba._blue << " "; // output: // // [JULIA][LOG] initialization successful. // RGBA(0.75f0, 0.5f0, 0.1f0, 1.0f0, 0.75f0) // unboxed: 0.5 0.5 0.3 // Process finished with exit code 0 // return 0; }
24.907563
79
0.528677
Clemapfel
e0b1b92ea8cff348c184bfbe43f1f860b58a6a59
1,459
cpp
C++
src/widgets/progressbar.cpp
BusyStudent/Btk
27b23aa77e4fbcc48bdfe566ce7cae46183c289c
[ "MIT" ]
2
2021-06-19T08:21:38.000Z
2021-08-15T21:37:30.000Z
src/widgets/progressbar.cpp
BusyStudent/Btk
27b23aa77e4fbcc48bdfe566ce7cae46183c289c
[ "MIT" ]
null
null
null
src/widgets/progressbar.cpp
BusyStudent/Btk
27b23aa77e4fbcc48bdfe566ce7cae46183c289c
[ "MIT" ]
1
2021-04-03T14:27:39.000Z
2021-04-03T14:27:39.000Z
#include "../build.hpp" #include <Btk/progressbar.hpp> #include <Btk/render.hpp> #include <Btk/themes.hpp> #include <algorithm> namespace Btk{ ProgressBar::ProgressBar(){ set_value(0); } ProgressBar::~ProgressBar() = default; void ProgressBar::draw(Renderer &render){ FRect fixed_rect = rect; fixed_rect.y += 1; fixed_rect.w -= 1; fixed_rect.h -= 1; render.begin_path(); render.rect(rect); render.fill_color(theme()[Theme::Button]); render.fill(); render.begin_path(); render.rect(rect); render.stroke_color(theme()[Theme::Border]); render.stroke(); //Draw the next boarder render.begin_path(); FRect r = rect; r.w = r.w / 100.0f * value; render.rect(r); render.fill_color(theme()[Theme::Highlight]); render.fill(); //Draw text if(display_value){ render.begin_path(); render.text_align(TextAlign::Middle | TextAlign::Center); render.text_size(theme().font_size()); render.fill_color(theme()[Theme::Text]); } render.text(rect.center(),value_text); render.fill(); } void ProgressBar::set_value(float v){ v = std::clamp(v,0.0f,100.0f); value_text = u8format("%.2f%%",v); value = v; _signal_value_changed(v); redraw(); } }
24.316667
69
0.550377
BusyStudent
e0be66b22e477c83ea8920fe5f97a10bb5098d84
2,406
cpp
C++
src/state/city.cpp
sstanfield/hexGame
99edad55703846992d3f64ad4cf9d146d57ca625
[ "Zlib" ]
null
null
null
src/state/city.cpp
sstanfield/hexGame
99edad55703846992d3f64ad4cf9d146d57ca625
[ "Zlib" ]
null
null
null
src/state/city.cpp
sstanfield/hexGame
99edad55703846992d3f64ad4cf9d146d57ca625
[ "Zlib" ]
null
null
null
/* Copyright (c) 2015-2016 Steven Stanfield This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "city.h" #include <cstdlib> namespace hexgame { namespace state { struct CityManager::CityContext { std::vector<City::u_ptr> cities; uint cityPos; }; CityManager::CityManager() : _ctx(std::make_unique<CityContext>()) { } CityManager::~CityManager() = default; const City& CityManager::newCity(std::string name, uint row, uint col, uint walls) { City::u_ptr c = std::make_unique<City>(); c->name = name; c->row = row; c->col = col; c->walls = walls; c->side = Side::Side_Grey; c->id = _ctx->cities.size(); _ctx->cities.push_back(std::move(c)); return *_ctx->cities[c->id]; } void CityManager::addCityProd(uint id, std::string basename, uint time, uint cost, uint upkeep, uint strength, uint movement) { UnitProd::u_ptr up = std::make_unique<UnitProd>(); up->basename = basename; up->time = time; up->cost = cost; up->upkeep = upkeep; up->strength = strength; up->movement = movement; _ctx->cities.at(id)->units.push_back(std::move(up)); } uint CityManager::numCities() const { return _ctx->cities.size(); } const City* CityManager::getCity(uint id) const { return _ctx->cities.at(id).get(); } const City* CityManager::firstCity() { City *c = nullptr; _ctx->cityPos = 0; if (_ctx->cityPos < _ctx->cities.size()) c = _ctx->cities[_ctx->cityPos].get(); return c; } const City* CityManager::nextCity() { City *c = nullptr; _ctx->cityPos++; if (_ctx->cityPos < _ctx->cities.size()) c = _ctx->cities[_ctx->cityPos].get(); return c; } } //state } // hexgame
24.55102
82
0.704489
sstanfield
e0c34532ae1ce2cd3841d45edc2aad9d860e5731
1,206
hpp
C++
Tests/UnitTests/Helper/Include/UTH/Config.hpp
SapphireSuite/Engine
f29821853aec6118508f31d3e063e83e603f52dd
[ "MIT" ]
1
2022-01-20T23:17:18.000Z
2022-01-20T23:17:18.000Z
Tests/UnitTests/Helper/Include/UTH/Config.hpp
SapphireSuite/Engine
f29821853aec6118508f31d3e063e83e603f52dd
[ "MIT" ]
null
null
null
Tests/UnitTests/Helper/Include/UTH/Config.hpp
SapphireSuite/Engine
f29821853aec6118508f31d3e063e83e603f52dd
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Sapphire's Suite. All Rights Reserved. #pragma once #ifndef SAPPHIRE_UTH_CONFIG_GUARD #define SAPPHIRE_UTH_CONFIG_GUARD #include <SA/Core/Support/ModuleAPI.hpp> /** * \file UTH/Config.hpp * * \brief Sapphire Engine UnitTestHelper module config file. * * \ingroup UTH * \{ */ #if defined(SA_UnitTestHelper_EXPORTS) /// Sapphire Engine API import/export preprocessor. #define SA_UTH_API SA_MODUE_EXPORT #else /// Sapphire Engine API import/export preprocessor. #define SA_UTH_API SA_MODUE_IMPORT #endif #ifndef SA_UTH_EXIT_ON_FAILURE /** * \brief Wether to exit program on failure or continue next tests. * Can be defined within cmake options or before including the header. */ #define SA_UTH_EXIT_ON_FAILURE 0 #endif #ifndef SA_UTH_EXIT_PAUSE /** * \brief Whether to pause program on exit. * Always disabled in continuous integration (define SA_CI). */ #define SA_UTH_EXIT_PAUSE 0 #endif namespace Sa { /// Unit Test Helper module main namespace. namespace UTH { /// UTH Internal classes implementations. namespace Intl { } } } /** * \defgroup UTH UnitTestHelper * Sapphire Engine Unit Test Helper module. */ /** \} */ #endif // GUARD
16.08
70
0.733002
SapphireSuite
e0c89c9d0cb63d330787e21583f63bedea61b48f
1,851
cpp
C++
test/auto/ListModel/ListModelTester.cpp
ericzh86/ModelsModule
e1f263420e5e54ac280d1c61485ccb6a0a625129
[ "MIT" ]
8
2019-12-11T08:52:37.000Z
2021-08-04T03:42:55.000Z
test/auto/ListModel/ListModelTester.cpp
ericzh86/ModelsModule
e1f263420e5e54ac280d1c61485ccb6a0a625129
[ "MIT" ]
null
null
null
test/auto/ListModel/ListModelTester.cpp
ericzh86/ModelsModule
e1f263420e5e54ac280d1c61485ccb6a0a625129
[ "MIT" ]
1
2020-04-16T07:07:50.000Z
2020-04-16T07:07:50.000Z
#include "ListModelTester.h" #include "ListModelTester_p.h" #include <QAbstractItemModelTester> // class ListModelTester ListModelTester::ListModelTester(Internal::QCxxListModel *model, QObject *parent) : QObject(parent ? parent : model) , d_ptr(new ListModelTesterPrivate()) { d_ptr->q_ptr = this; Q_CHECK_PTR(model); new QAbstractItemModelTester(model, this); connect(model, &Internal::QCxxListModel::countChanged, this, &ListModelTester::onCountChanged); connect(model, &Internal::QCxxListModel::dataChanged, this, &ListModelTester::onDataChanged); } ListModelTester::~ListModelTester() { } int ListModelTester::count() const { Q_D(const ListModelTester); return d->count; } void ListModelTester::resetCount() { Q_D(ListModelTester); d->count = 0; } void ListModelTester::onCountChanged() { Q_D(ListModelTester); ++d->count; } int ListModelTester::changedSize() const { Q_D(const ListModelTester); return d->changedList.count(); } bool ListModelTester::isChanged(int index, int from, int to) const { Q_D(const ListModelTester); ListModelChanged changed = d->changedList.at(index); return ((from == changed.first) && (to == changed.second)); } void ListModelTester::resetChangedList() { Q_D(ListModelTester); d->changedList.clear(); } void ListModelTester::onDataChanged(const QModelIndex &tl, const QModelIndex &br, const QVector<int> &roles) { Q_D(ListModelTester); Q_UNUSED(roles); Q_ASSERT(tl.column() == 0); Q_ASSERT(br.column() == 0); d->changedList.append(ListModelChanged(tl.row(), br.row())); } // class ListModelTesterPrivate ListModelTesterPrivate::ListModelTesterPrivate() : q_ptr(nullptr) , model(nullptr) , count(0) { } ListModelTesterPrivate::~ListModelTesterPrivate() { }
19.691489
108
0.698541
ericzh86
e0cb366fd7ae6f2844eec0447288d324a9619fa0
25,763
hpp
C++
trng/special_functions.hpp
mminutoli/trng4
1ef58a7027242d395f4407d0ce0fe42e4904f9bf
[ "BSD-3-Clause" ]
null
null
null
trng/special_functions.hpp
mminutoli/trng4
1ef58a7027242d395f4407d0ce0fe42e4904f9bf
[ "BSD-3-Clause" ]
null
null
null
trng/special_functions.hpp
mminutoli/trng4
1ef58a7027242d395f4407d0ce0fe42e4904f9bf
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2000-2021, Heiko Bauke // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDERS 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. #if !(defined TRNG_SPECIAL_FUNCTIONS_HPP) #define TRNG_SPECIAL_FUNCTIONS_HPP #include <trng/cuda.hpp> #include <trng/limits.hpp> #include <trng/math.hpp> #include <trng/constants.hpp> #include <trng/utility.hpp> #include <cerrno> #include <algorithm> #include <ciso646> namespace trng { namespace math { TRNG_CUDA_ENABLE inline float ln_Gamma(float x) { return ::std::lgamma(x); } TRNG_CUDA_ENABLE inline double ln_Gamma(double x) { return ::std::lgamma(x); } #if !(defined __CUDA_ARCH__) inline long double ln_Gamma(long double x) { return ::std::lgamma(x); } #endif TRNG_CUDA_ENABLE inline float Gamma(float x) { return ::std::tgamma(x); } TRNG_CUDA_ENABLE inline double Gamma(double x) { return ::std::tgamma(x); } #if !(defined __CUDA_ARCH__) inline long double Gamma(long double x) { return ::std::tgamma(x); } #endif // --- Beta function ----------------------------------------------- namespace detail { template<typename T> T Beta(T x, T y) { static const T ln_max{ln(std::numeric_limits<T>::max())}; if (x <= 0 or y <= 0) { #if !(defined __CUDA_ARCH__) errno = EDOM; #endif return std::numeric_limits<T>::signaling_NaN(); } const T z{x + y}; if (z * ln(z) - z > ln_max) // less accurate but avoids overflow return exp(ln_Gamma(x) + ln_Gamma(y) - ln_Gamma(z)); return Gamma(x) / Gamma(z) * Gamma(y); } } // namespace detail TRNG_CUDA_ENABLE inline float Beta(float x, float y) { return detail::Beta(x, y); } TRNG_CUDA_ENABLE inline double Beta(double x, double y) { return detail::Beta(x, y); } #if !(defined __CUDA_ARCH__) inline long double Beta(long double x, long double y) { return detail::Beta(x, y); } #endif // --- ln of binomial coefficient ---------------------------------- TRNG_CUDA_ENABLE inline float ln_binomial(float n, float m) { return ln_Gamma(n + 1) - ln_Gamma(m + 1) - ln_Gamma(n - m + 1); } TRNG_CUDA_ENABLE inline double ln_binomial(double n, double m) { return ln_Gamma(n + 1) - ln_Gamma(m + 1) - ln_Gamma(n - m + 1); } #if !(defined __CUDA_ARCH__) inline long double ln_binomial(long double n, long double m) { return ln_Gamma(n + 1) - ln_Gamma(m + 1) - ln_Gamma(n - m + 1); } #endif // --- Pochhammer function ----------------------------------------- inline float Pochhammer(float x, float a) { return exp(ln_Gamma(x + a) - ln_Gamma(x)); } inline double Pochhammer(double x, double a) { return exp(ln_Gamma(x + a) - ln_Gamma(x)); } #if !(defined __CUDA_ARCH__) inline long double Pochhammer(long double x, long double a) { return exp(ln_Gamma(x + a) - ln_Gamma(x)); } #endif // --- incomplete Gamma functions ---------------------------------- namespace detail { // compute incomplete Gamma function // // gamma(a, x) = Int(exp(-t)*t^(a-1), t=0..x) // // or // // P(a, x) = gamma(a, x) / Gamma(a) // // by series expansion, see "Numerical Recipes" by W. H. Press et al., 3rd edition template<typename T, bool by_Gamma_a> TRNG_CUDA_ENABLE T GammaP_ser(T a, T x) { const int itmax{64}; const T eps{4 * numeric_limits<T>::epsilon()}; if (x < eps) return T{0}; T xx{1 / a}, n{a}, sum{xx}; int i{0}; do { ++n; ++i; xx *= x / n; sum += xx; } while (abs(xx) > eps * abs(sum) and i < itmax); #if __cplusplus >= 201703L if constexpr (by_Gamma_a) #else if (by_Gamma_a) #endif return exp(-x + a * ln(x) - ln_Gamma(a)) * sum; else return exp(-x + a * ln(x)) * sum; } // compute complementary incomplete Gamma function // // Gamma(a, x) = Int(exp(-t)*t^(a-1), t=x..oo) // // or // // Q(a, x) = Gamma(a, x) / Gamma(a) = 1 - P(a, x) // // by continued fraction, see "Numerical Recipes" by W. H. Press et al., 3rd edition template<typename T, bool by_Gamma_a> TRNG_CUDA_ENABLE T GammaQ_cf(T a, T x) { const T itmax{64}; const T eps{4 * numeric_limits<T>::epsilon()}; const T min{4 * numeric_limits<T>::min()}; // set up for evaluating continued fraction by modified Lentz's method T del, bi{x + 1 - a}, ci{1 / min}, di{1 / bi}, h{di}, i{0}; do { // iterate ++i; T ai{-i * (i - a)}; bi += 2; di = ai * di + bi; if (abs(di) < min) di = min; ci = bi + ai / ci; if (abs(ci) < min) ci = min; di = 1 / di; del = di * ci; h *= del; } while ((abs(del - 1) > eps) and i < itmax); #if __cplusplus >= 201703L if constexpr (by_Gamma_a) #else if (by_Gamma_a) #endif return exp(-x + a * ln(x) - ln_Gamma(a)) * h; else return exp(-x + a * ln(x)) * h; } // P(a, x) and gamma(a, x) template<typename T, bool by_Gamma_a> TRNG_CUDA_ENABLE T GammaP(T a, T x) { if (x < 0 or a <= 0) return numeric_limits<T>::signaling_NaN(); #if __cplusplus >= 201703L if constexpr (by_Gamma_a) { #else if (by_Gamma_a) { #endif if (x < a + 1) return GammaP_ser<T, true>(a, x); return 1 - GammaQ_cf<T, true>(a, x); } else { if (x < a + 1) return GammaP_ser<T, false>(a, x); return Gamma(a) - GammaQ_cf<T, false>(a, x); } } // Q(a, x) and Gamma(a, x) template<typename T, bool by_Gamma_a> TRNG_CUDA_ENABLE T GammaQ(T a, T x) { if (x < 0 or a <= 0) return numeric_limits<T>::signaling_NaN(); #if __cplusplus >= 201703L if constexpr (by_Gamma_a) { #else if (by_Gamma_a) { #endif if (x < a + 1) return T{1} - GammaP_ser<T, true>(a, x); return GammaQ_cf<T, true>(a, x); } else { if (x < a + 1) return Gamma(a) - GammaP_ser<T, false>(a, x); return GammaQ_cf<T, false>(a, x); } } } // namespace detail // P(x, a) TRNG_CUDA_ENABLE inline float GammaP(float a, float x) { return detail::GammaP<float, true>(a, x); } TRNG_CUDA_ENABLE inline double GammaP(double a, double x) { return detail::GammaP<double, true>(a, x); } #if !(defined __CUDA_ARCH__) inline long double GammaP(long double a, long double x) { return detail::GammaP<long double, true>(a, x); } #endif // Q(x, a) TRNG_CUDA_ENABLE inline float GammaQ(float a, float x) { return detail::GammaQ<float, true>(a, x); } TRNG_CUDA_ENABLE inline double GammaQ(double a, double x) { return detail::GammaQ<double, true>(a, x); } #if !(defined __CUDA_ARCH__) inline long double GammaQ(long double a, long double x) { return detail::GammaQ<long double, true>(a, x); } #endif // gamma(x, a) TRNG_CUDA_ENABLE inline float inc_gamma(float a, float x) { return detail::GammaP<float, false>(a, x); } TRNG_CUDA_ENABLE inline double inc_gamma(double a, double x) { return detail::GammaP<double, false>(a, x); } #if !(defined __CUDA_ARCH__) inline long double inc_gamma(long double a, long double x) { return detail::GammaP<long double, false>(a, x); } #endif // Gamma(x, a) TRNG_CUDA_ENABLE inline float inc_Gamma(float a, float x) { return detail::GammaQ<float, false>(a, x); } TRNG_CUDA_ENABLE inline double inc_Gamma(double a, double x) { return detail::GammaQ<double, false>(a, x); } #if !(defined __CUDA_ARCH__) inline long double inc_Gamma(long double a, long double x) { return detail::GammaQ<long double, false>(a, x); } #endif namespace detail { // compute inverse of the incomplete Gamma function p = P(a, x), see "Numerical Recipes" // by W. H. Press et al., 3rd edition template<typename T> TRNG_CUDA_ENABLE T inv_GammaP(T a, T p) { const T eps{sqrt(numeric_limits<T>::epsilon())}; T a1{a - 1}; T glna{ln_Gamma(a)}; T lna1{ln(a1)}; T afac{exp(a1 * (lna1 - 1) - glna)}; T x; // initial guess if (a > T{1}) { const T pp{p < T{1} / T{2} ? p : 1 - p}; const T t = {sqrt(-2 * ln(pp))}; x = (T{2.30753} + t * T{0.27061}) / (1 + t * (T{0.99229} + t * T{0.04481})) - t; x = p < T{1} / T{2} ? -x : x; x = utility::max(T{1} / T{1000}, a * pow(1 - 1 / (9 * a) - x / (3 * sqrt(a)), T{3})); } else { const T t{1 - a * (T{0.253} + a * T{0.12})}; x = p < t ? pow(p / t, 1 / a) : 1 - ln1p(-(p - t) / (1 - t)); } // refinement by Halley's method for (int i{0}; i < 32; ++i) { if (x <= 0) { x = 0; break; } const T err{GammaP<T, true>(a, x) - p}; T t; if (a > 1) t = afac * exp(-(x - a1) + a1 * (ln(x) - lna1)); else t = exp(-x + a1 * ln(x) - glna); const T u{err / t}; t = u / (1 - utility::min(T{1}, u * ((a - 1) / x - 1)) / 2); x -= t; x = x <= 0 ? (x + t) / 2 : x; if (abs(t) < eps * x) break; } return x; } } // namespace detail // inverse of GammaP TRNG_CUDA_ENABLE inline float inv_GammaP(float a, float p) { return detail::inv_GammaP(a, p); } // inverse of GammaP TRNG_CUDA_ENABLE inline double inv_GammaP(double a, double p) { return detail::inv_GammaP(a, p); } // inverse of GammaP #if !(defined __CUDA_ARCH__) inline long double inv_GammaP(long double a, long double p) { return detail::inv_GammaP(a, p); } #endif // --- regularized incomplete Beta function ------------------------ // see Applied Statistics (1973), vol.22, no.3, pp.409--411 // algorithm AS 63 namespace detail { template<typename T> TRNG_CUDA_ENABLE T Beta_I(T x, T p, T q, T norm) { if (p <= 0 or q <= 0 or x < 0 or x > 1) { #if !(defined __CUDA_ARCH__) errno = EDOM; #endif return numeric_limits<T>::quiet_NaN(); } const T eps{4 * numeric_limits<T>::epsilon()}; T psq{p + q}, cx{1 - x}; const bool flag{p < psq * x}; if (flag) { // use I(x, p, q) = 1 - I(1 - x, q, p) utility::swap(x, cx); utility::swap(p, q); } T term{1}, i{1}, y{1}, rx{x / cx}, temp{q - i}; int s{static_cast<int>(q + cx * psq)}; if (s == 0) rx = x; while (true) { term *= temp * rx / (p + i); y += term; temp = abs(term); if (temp <= eps and temp <= eps * y) break; ++i; --s; if (s >= 0) { temp = q - i; if (s == 0) rx = x; } else { temp = psq; psq++; } } y *= exp(p * ln(x) + (q - 1) * ln(cx)) / p / norm; return flag ? 1 - y : y; } } // namespace detail TRNG_CUDA_ENABLE inline float Beta_I(float x, float p, float q, float norm) { return detail::Beta_I(x, p, q, norm); } TRNG_CUDA_ENABLE inline float Beta_I(float x, float p, float q) { return detail::Beta_I(x, p, q, Beta(p, q)); } TRNG_CUDA_ENABLE inline double Beta_I(double x, double p, double q, double norm) { return detail::Beta_I(x, p, q, norm); } TRNG_CUDA_ENABLE inline double Beta_I(double x, double p, double q) { return detail::Beta_I(x, p, q, Beta(p, q)); } #if !(defined __CUDA_ARCH__) inline long double Beta_I(long double x, long double p, long double q, long double norm) { return detail::Beta_I(x, p, q, norm); } inline long double Beta_I(long double x, long double p, long double q) { return detail::Beta_I(x, p, q, Beta(p, q)); } #endif // --- inverse of regularized incomplete Beta function ------------- namespace detail { template<typename T> TRNG_CUDA_ENABLE inline T inv_Beta_I(T x, T p, T q, T norm) { if (x < numeric_limits<T>::epsilon()) return 0; if (1 - x < numeric_limits<T>::epsilon()) return 1; // solve via Newton method T y{0}; if (2 * p >= 1 and 2 * q >= 1) y = (3 * p - 1) / (3 * p + 3 * q - 2); // the approximate median else { // following initial guess given in "Numerical Recipes" by W. H. Press et al., 3rd // edition const T lnp{ln(p / (p + q))}; const T lnq{ln(q / (p + q))}; const T t{exp(p * lnp) / p}; const T u{exp(q * lnq) / q}; const T w{t + u}; if (x < t / w) y = pow(p * w * x, 1 / p); else y = 1 - pow(q * w * (1 - x), 1 / q); } for (int i{0}; i < numeric_limits<T>::digits; ++i) { const T f{Beta_I(y, p, q, norm) - x}; const T df{pow(1 - y, q - 1) * pow(y, p - 1) / norm}; T dy(f / df); if (abs(f / y) < 2 * numeric_limits<T>::epsilon()) break; // avoid overshooting while (y - dy <= 0 or y - dy >= 1) dy *= T{3} / T{4}; y -= dy; } return y; } } // namespace detail TRNG_CUDA_ENABLE inline float inv_Beta_I(float x, float p, float q, float norm) { return detail::inv_Beta_I(x, p, q, norm); } TRNG_CUDA_ENABLE inline float inv_Beta_I(float x, float p, float q) { return detail::inv_Beta_I(x, p, q, Beta(p, q)); } TRNG_CUDA_ENABLE inline double inv_Beta_I(double x, double p, double q, double norm) { return detail::inv_Beta_I(x, p, q, norm); } TRNG_CUDA_ENABLE inline double inv_Beta_I(double x, double p, double q) { return detail::inv_Beta_I(x, p, q, Beta(p, q)); } #if !(defined __CUDA_ARCH__) inline long double inv_Beta_I(long double x, long double p, long double q, long double norm) { return detail::inv_Beta_I(x, p, q, norm); } inline long double inv_Beta_I(long double x, long double p, long double q) { return detail::inv_Beta_I(x, p, q, Beta(p, q)); } #endif // --- error function and complementary error function-------------- using ::std::erf; using ::std::erfc; // --- normal distribution function ------------------------------- TRNG_CUDA_ENABLE inline float Phi(float x) { x *= constants<float>::one_over_sqrt_2; if (x < -0.6744897501960817f * constants<float>::one_over_sqrt_2) return 0.5f * erfc(-x); if (x > +0.6744897501960817f * constants<float>::one_over_sqrt_2) return 1.0f - 0.5f * erfc(x); return 0.5f + 0.5f * erf(x); } TRNG_CUDA_ENABLE inline double Phi(double x) { x *= constants<double>::one_over_sqrt_2; if (x < -0.6744897501960817 * constants<double>::one_over_sqrt_2) return 0.5 * erfc(-x); if (x > +0.6744897501960817 * constants<double>::one_over_sqrt_2) return 1.0 - 0.5 * erfc(x); return 0.5 + 0.5 * erf(x); } #if !(defined __CUDA_ARCH__) inline long double Phi(long double x) { x *= constants<long double>::one_over_sqrt_2; if (x < -0.6744897501960817l * constants<long double>::one_over_sqrt_2) return 0.5l * erfc(-x); if (x > +0.6744897501960817l * constants<long double>::one_over_sqrt_2) return 1.0l - 0.5l * erfc(x); return 0.5l + 0.5l * erf(x); } #endif // --- inverse of normal distribution function -------------------- // this function is based on an approximation by Peter J. Acklam // see http://home.online.no/~pjacklam/notes/invnorm/ or // https://web.archive.org/web/20151030215612/http://home.online.no/~pjacklam/notes/invnorm/ // for details namespace detail { template<typename T> struct inv_Phi_traits { static constexpr T a[6]{ static_cast<T>(-3.969683028665376e+01l), static_cast<T>(2.209460984245205e+02l), static_cast<T>(-2.759285104469687e+02l), static_cast<T>(1.383577518672690e+02l), static_cast<T>(-3.066479806614716e+01l), static_cast<T>(2.506628277459239e+00l)}; static constexpr T b[5]{ static_cast<T>(-5.447609879822406e+01l), static_cast<T>(1.615858368580409e+02l), static_cast<T>(-1.556989798598866e+02l), static_cast<T>(6.680131188771972e+01l), static_cast<T>(-1.328068155288572e+01l)}; static constexpr T c[6]{ static_cast<T>(-7.784894002430293e-03l), static_cast<T>(-3.223964580411365e-01l), static_cast<T>(-2.400758277161838e+00l), static_cast<T>(-2.549732539343734e+00l), static_cast<T>(4.374664141464968e+00l), static_cast<T>(2.938163982698783e+00l)}; static constexpr T d[4]{ static_cast<T>(7.784695709041462e-03l), static_cast<T>(3.224671290700398e-01l), static_cast<T>(2.445134137142996e+00l), static_cast<T>(3.754408661907416e+00l)}; static constexpr T x_low = static_cast<T>(0.02425l); static constexpr T x_high = static_cast<T>(1.0l - 0.02425l); static constexpr T one_half = static_cast<T>(0.5l); }; template<typename T> constexpr T inv_Phi_traits<T>::a[6]; template<typename T> constexpr T inv_Phi_traits<T>::b[5]; template<typename T> constexpr T inv_Phi_traits<T>::c[6]; template<typename T> constexpr T inv_Phi_traits<T>::d[4]; // --------------------------------------------------------------- template<typename T> TRNG_CUDA_ENABLE T inv_Phi_approx(T x) { using traits = inv_Phi_traits<T>; if (x < 0 or x > 1) { #if !(defined __CUDA_ARCH__) errno = EDOM; #endif return numeric_limits<T>::quiet_NaN(); } if (x == 0) return -numeric_limits<T>::infinity(); if (x == 1) return numeric_limits<T>::infinity(); if (x < traits::x_low) { // rational approximation for lower region const T q{sqrt(-2 * ln(x))}; return (((((traits::c[0] * q + traits::c[1]) * q + traits::c[2]) * q + traits::c[3]) * q + traits::c[4]) * q + traits::c[5]) / ((((traits::d[0] * q + traits::d[1]) * q + traits::d[2]) * q + traits::d[3]) * q + 1); } else if (x < traits::x_high) { // rational approximation for central region const T q{x - traits::one_half}; const T r{q * q}; return (((((traits::a[0] * r + traits::a[1]) * r + traits::a[2]) * r + traits::a[3]) * r + traits::a[4]) * r + traits::a[5]) * q / (((((traits::b[0] * r + traits::b[1]) * r + traits::b[2]) * r + traits::b[3]) * r + traits::b[4]) * r + 1); } else { // rational approximation for upper region const T q{sqrt(-2 * ln1p(-x))}; return -(((((traits::c[0] * q + traits::c[1]) * q + traits::c[2]) * q + traits::c[3]) * q + traits::c[4]) * q + traits::c[5]) / ((((traits::d[0] * q + traits::d[1]) * q + traits::d[2]) * q + traits::d[3]) * q + 1); } } template<typename T> TRNG_CUDA_ENABLE T inv_Phi(T x) { using traits = inv_Phi_traits<T>; T y{inv_Phi_approx(x)}; // refinement by Halley rational method if (isfinite(y)) { const T e{(Phi(y) - x)}; const T u{e * constants<T>::sqrt_2pi * exp(y * y * traits::one_half)}; y -= u / (1 + y * u * traits::one_half); } // T is a floating point number type with more than 80 bits, a 2nd iteration is // required to reach full machine precision #if __cplusplus >= 201703L if constexpr (sizeof(T) > 10) { #else #if _MSC_VER #pragma warning(push) #pragma warning(disable : 4127) #endif if (sizeof(T) > 10) { #if _MSC_VER #pragma warning(pop) #endif #endif if (isfinite(y)) { const T e{(Phi(y) - x)}; const T u{e * constants<T>::sqrt_2pi * exp(y * y * traits::one_half)}; y -= u / (1 + y * u * traits::one_half); } } return y; } template<typename T> TRNG_CUDA_ENABLE T inv_erf(T x) { T y{inv_Phi_approx((x + 1) / 2) * constants<T>::one_over_sqrt_2}; // refinement by Halley rational method if (isfinite(y)) { const T e{erf(y) - x}; const T u{e * (constants<T>::sqrt_pi_over_2) * exp(y * y)}; y -= u / (1 + y * u); } // T is a floating point number type with more than 80 bits, a 2nd iteration is // required to reach full machine precision #if __cplusplus >= 201703L if constexpr (sizeof(T) > 10) { #else #if _MSC_VER #pragma warning(push) #pragma warning(disable : 4127) #endif if (sizeof(T) > 10) { #if _MSC_VER #pragma warning(pop) #endif #endif if (isfinite(y)) { const T e{erf(y) - x}; const T u{e * (constants<T>::sqrt_pi_over_2) * exp(y * y)}; y -= u / (1 + y * u); } } return y; } template<typename T> TRNG_CUDA_ENABLE T inv_erfc(T x) { // step size in the Halley step is proportional to erfc, use symmetry to increase // numerical accuracy const bool flag{x > 1}; if (flag) x = -(x - 1) + 1; T y{-inv_Phi_approx(x / 2) * constants<T>::one_over_sqrt_2}; // refinement by Halley rational method if (isfinite(y)) { const T e{erfc(y) - x}; const T u{-e * (constants<T>::sqrt_pi_over_2) * exp(y * y)}; y -= u / (1 + y * u); } // T is a floating point number type with more than 80 bits, a 2nd iteration is // required to reach full machine precision #if __cplusplus >= 201703L if constexpr (sizeof(T) > 10) { #else #if _MSC_VER #pragma warning(push) #pragma warning(disable : 4127) #endif if (sizeof(T) > 10) { #if _MSC_VER #pragma warning(pop) #endif #endif if (isfinite(y)) { const T e{erfc(y) - x}; const T u{-e * (constants<T>::sqrt_pi_over_2) * exp(y * y)}; y -= u / (1 + y * u); } } return flag ? -y : y; } } // namespace detail TRNG_CUDA_ENABLE inline float inv_Phi(float x) { return detail::inv_Phi<float>(x); } TRNG_CUDA_ENABLE inline double inv_Phi(double x) { return detail::inv_Phi<double>(x); } #if !(defined __CUDA_ARCH__) inline long double inv_Phi(long double x) { return detail::inv_Phi<long double>(x); } #endif // --- inverse of error function ---------------------------------- TRNG_CUDA_ENABLE inline float inv_erf(float x) { return detail::inv_erf(x); } TRNG_CUDA_ENABLE inline double inv_erf(double x) { return detail::inv_erf(x); } #if !(defined __CUDA_ARCH__) inline long double inv_erf(long double x) { return detail::inv_erf(x); } #endif // --- inverse of complementary error function -------------------- TRNG_CUDA_ENABLE inline float inv_erfc(float x) { return detail::inv_erfc(x); } TRNG_CUDA_ENABLE inline double inv_erfc(double x) { return detail::inv_erfc(x); } #if !(defined __CUDA_ARCH__) inline long double inv_erfc(long double x) { return detail::inv_erfc(x); } #endif } // namespace math } // namespace trng #endif
32.324969
96
0.539922
mminutoli
e0cc0f854c7d5aea69285822c51d07e14dfecbcd
2,135
cpp
C++
polymorphism/cpp/volatility.cpp
DonatienB/cpp_dauphine
530f9e62054675de0c075496e8695491988298e3
[ "BSD-3-Clause" ]
null
null
null
polymorphism/cpp/volatility.cpp
DonatienB/cpp_dauphine
530f9e62054675de0c075496e8695491988298e3
[ "BSD-3-Clause" ]
null
null
null
polymorphism/cpp/volatility.cpp
DonatienB/cpp_dauphine
530f9e62054675de0c075496e8695491988298e3
[ "BSD-3-Clause" ]
null
null
null
#include "volatility.hpp" #include <iostream> namespace dauphine { /***************************** * volatility implementation * *****************************/ volatility::volatility(const std::string& name) : m_name(name) { std::cout << "volatility constructor" << std::endl; } volatility::~volatility() { std::cout << "volatility destructor" << std::endl; } const std::string& volatility::underlying_name() const { return m_name; } /************************************* * implied_volatility implementation * *************************************/ implied_volatility::implied_volatility(const std::string& name, const std::vector<double>& vol) : volatility(name), m_volatility(vol) { std::cout << "implied_volatility constructor" << std::endl; } implied_volatility::~implied_volatility() { std::cout << "implied_volatility destructor" << std::endl; } double implied_volatility::get_volatility(size_t index) const { return m_volatility[index]; } /************************************ * bumped_volatility implementation * ************************************/ bumped_volatility::bumped_volatility(volatility* vol, double bump) : volatility(vol->underlying_name()), p_volatility(vol), m_bump(bump) { std::cout << "bumped_volatility constructor" << std::endl; } bumped_volatility::~bumped_volatility() { std::cout << "bumped_volatility destructor" << std::endl; } double bumped_volatility::get_volatility(size_t index) const { return p_volatility->get_volatility(index) + m_bump; } /********************************** * make_volatility implementation * **********************************/ volatility* make_volatility(const std::string& ud, const std::vector<double>& vol) { return new implied_volatility(ud, vol); } volatility* make_volatility(volatility* vol, double bump) { return new bumped_volatility(vol, bump); } }
26.036585
99
0.545667
DonatienB
e0d15de572b1b9628e0974d02df5dcef9fb20fcd
7,416
cpp
C++
Hash3/Hash3/Hash.cpp
Phetlada/learn-Cplusplus
3e33a4fd6553bc36eec7a7be02db75c327401df7
[ "MIT" ]
null
null
null
Hash3/Hash3/Hash.cpp
Phetlada/learn-Cplusplus
3e33a4fd6553bc36eec7a7be02db75c327401df7
[ "MIT" ]
null
null
null
Hash3/Hash3/Hash.cpp
Phetlada/learn-Cplusplus
3e33a4fd6553bc36eec7a7be02db75c327401df7
[ "MIT" ]
null
null
null
#include<iomanip> #include<iostream> #include<string> #include<vector> using namespace std; template <class HashedObj> class HashTable { public: explicit HashTable(const HashedObj & notFound, int size = 31); HashTable(const HashTable & rhs) : currentSize(rhs.currentSize), ITEM_NOT_FOUND(rhs.ITEM_NOT_FOUND), array(rhs.array) {} HashedObj find(HashedObj & x); void makeEmpty(); void insert( HashedObj & x); void remove( HashedObj & x); const HashTable & operator=(const HashTable & rhs); enum EntryType { ACTIVE, EMPTY, DELETED }; // void create(int size); int nextPrime(int size); int beforePrime(int size); void printTable(); private: struct HashEntry { HashedObj element; EntryType info; HashEntry(const HashedObj & e = HashedObj(), EntryType i = EMPTY) : element(e), info(i) { } }; vector<HashEntry> array; int currentSize; const HashedObj ITEM_NOT_FOUND; bool isActive(int currentPos) const; int findPos(HashedObj & x); void rehash(); int hash(int x, int tableSize); int hash2(int x); }; //consturctor template <class HashedObj> HashTable <HashedObj>::HashTable(const HashedObj & notFound, int size) : ITEM_NOT_FOUND(notFound), array(nextPrime(size)) { makeEmpty(); } //create table template <class HashedObj> void HashTable <HashedObj>::create(int size){ array.resize(size); makeEmpty(); } template <class HashedObj> void HashTable <HashedObj>::makeEmpty() { currentSize = 0; for (int i = 0; i<array.size(); i++){ array[i].element = 0; array[i].info = EMPTY; } } template <class HashedObj> bool HashTable <HashedObj>::isActive( int currentPos) const { return array[ currentPos ].info == ACTIVE; } template <class HashedObj> int HashTable <HashedObj>::nextPrime(int size){ int prime = 0; while(size % 2 == 0 || size == 2) size++; for(int i = 1; i <= size; i++) { if(size % i == 0) prime++; } if(prime == 2) return size; else return nextPrime(size+2); } template <class HashedObj> int HashTable <HashedObj>::beforePrime(int size){ int prime = 0; while(size % 2 == 0) size--; for(int i = 1; i <= size; i++) { if(size % i == 0) prime++; } if(prime == 2) return size; else return beforePrime(size-2); } template <class HashedObj> int HashTable <HashedObj>::hash(int x, int tableSize){ return x % tableSize; } template <class HashedObj> int HashTable <HashedObj>::hash2(int x){ int r = beforePrime(array.size()-1); return r - (x % r); } template <class HashedObj> int HashTable <HashedObj>::findPos( HashedObj & x ) { int collisionNum = 0; int currentPos = hash(x, array.size()); while( array[ currentPos ].info != EMPTY && array[ currentPos ].element != x){ currentPos = ( hash(x, array.size()) + (++collisionNum * hash2(x)) ) % array.size(); if(currentPos >= array.size()) currentPos -= array.size(); } return currentPos; } template <class HashedObj> void HashTable <HashedObj>::insert( HashedObj & x) { int currentPos = findPos(x); if( isActive( currentPos ) ) return; array[currentPos] = HashEntry(x, ACTIVE); if (++currentSize > (array.size() * 0.7)) rehash(); } template <class HashedObj> void HashTable <HashedObj>::rehash(){ vector<HashEntry> oldTable = array; array.resize(nextPrime(2 * oldTable.size())); makeEmpty(); for (int i = 0; i < oldTable.size(); i++) if (oldTable[i].info == ACTIVE) insert(oldTable[i].element); } template <class HashedObj> void HashTable <HashedObj>::remove(HashedObj & x) { int currentPos = findPos( x ); if( isActive( currentPos ) ) array[ currentPos ].info = DELETED; currentSize--; } template <class HashedObj> HashedObj HashTable <HashedObj>::find(HashedObj & x) { int currentPos = findPos( x ); if( isActive( currentPos ) ) return array[ currentPos ].element; else return ITEM_NOT_FOUND; } template <class HashedObj> void HashTable <HashedObj>::printTable(){ cout << setfill('=') << "\t" << setw(43) << "" << endl << setfill(' '); cout << "\t[ " << setw(4) << "N0." << " ]" << setw(5); cout << "\t[ " << setw(7) << "Element" << " ]" << setw(5); cout << "\t[ " << setw(7) << "Status" << " ]" << endl; cout << setfill('=') << "\t" << setw(43) << "" << endl << setfill(' '); for(int i = 0; i < array.size(); i++){ string status = (array[i].info == 0)? "ACTIVE" : (array[i].info == 1)? "EMPTY" : "DELETED"; cout << "\t[ " << setw(4) << i << " ]" << setw(5); cout << "\t[ " << setw(7) << array[i].element << " ]" << setw(5); cout << "\t[ " << setw(7) << status << " ]" << endl; } } void main(){ const int ITEM_NOT_FOUND = -999; HashTable <int> a(ITEM_NOT_FOUND); string choice; bool exit = false; bool createTable = false; do{ system("cls"); cout << "===============================\n"; cout << ".:: [ Hashing ] ::.\n"; cout << "===============================\n"; cout << " 1.) Create Hash Table\n"; cout << " 2.) Insert\n"; cout << " 3.) Print\n"; cout << " 4.) Remove\n"; cout << " 5.) Find\n"; cout << " 6.) Quit\n"; cout <<"Enter Choice : "; cin >> choice; switch(choice[0]) { case '1': int tableSize; if(!createTable) { do{ cout << "\nEnter TableSize (1 - 30): "; cin >> tableSize; }while(tableSize > 30 || tableSize < 1); a.create(a.nextPrime(tableSize)); cout << "Prime Number After " << tableSize; cout << " is " << a.nextPrime(tableSize) << endl; cout << "\nCreate Hash Table Sucessful . . ." << endl; createTable = true; } else cout << "\nYou already have Hash Table !!" << endl; system("pause"); break; case '2': int insertNum; if(createTable){ cout << "\nEnter Element to insert : "; cin >> insertNum; if(a.find(insertNum) != ITEM_NOT_FOUND) { cout << "\n" << insertNum << " are already in the table" << endl; } else{ a.insert(insertNum); cout << "\nInsert " << insertNum << " is Sucessful . . ." << endl; } } else cout << "\nHash Table is unready !!" << endl; system("pause"); break; case '3': if(createTable){ cout << setfill('=') << "\t" << setw(43) << "" << endl << setfill(' '); cout << "\t.:: Hash Table ::." << endl; a.printTable(); } else cout << "\nHash Table is unready !!" << endl; system("pause"); break; case '4': int removeNum; if(createTable){ cout << "\nEnter Element to Remove : "; cin >> removeNum; if(a.find(removeNum) != ITEM_NOT_FOUND){ a.remove(removeNum); cout << "\nRemove " << removeNum << " is Sucessful . . ." << endl; } else cout << "\nElement not found" << endl; } else cout << "\nHash Table is unready !!" << endl; system("pause"); break; case '5': int findNum, found; if(createTable){ cout << "\nEnter Element to Find : "; cin >> findNum; found = a.find(findNum); if(found == ITEM_NOT_FOUND) cout << "\nElement not found" << endl; else cout << "\nFound " << findNum << " in Hash Table" << endl; } else cout << "\nHash Table is unready !!" << endl; cout << endl; system("pause"); break; case '6': exit = true; cout << "\nClose Program . . ." << endl; break; default: cout << "\nNot Choice in menu. Please Try again." << endl; system("pause"); break; } }while(!exit); }
22.818462
79
0.582255
Phetlada
e0d7a69bd29a4914c38ab3ec02f9798a15a3648a
2,692
cpp
C++
examples/cpp/example_s2.cpp
JeremyBYU/FastGaussianAccumulator
995c1cb53485212bc2c71dad3ed3834caaa1f45b
[ "MIT" ]
4
2020-10-20T15:54:00.000Z
2021-09-05T22:24:57.000Z
examples/cpp/example_s2.cpp
JeremyBYU/GaussianAccumulator
995c1cb53485212bc2c71dad3ed3834caaa1f45b
[ "MIT" ]
1
2021-06-09T03:32:14.000Z
2021-06-09T03:32:14.000Z
examples/cpp/example_s2.cpp
JeremyBYU/GaussianAccumulator
995c1cb53485212bc2c71dad3ed3834caaa1f45b
[ "MIT" ]
1
2021-04-13T09:24:30.000Z
2021-04-13T09:24:30.000Z
#include <random> #include <cmath> #include <chrono> #include <vector> #include <iostream> #include "FastGA.hpp" #include "Hilbert/Hilbert.hpp" #include <cinttypes> #include <cstdint> #include <cstdio> #include "s2/s2earth.h" #include "s2/s1chord_angle.h" #include "s2/s2closest_point_query.h" #include "s2/s2point_index.h" #include "s2/s2testing.h" int main(int argc, char const *argv[]) { auto GA = FastGA::GaussianAccumulatorOpt(4, 100.0); FastGA::MatX3d normals = {{0.99177847, -0.11935933, -0.04613903}, {1, 1, 1}, {-1, 0, 0}, {0, 0 , 1}, {1, 0, 0}, {0, 1, 0}, {0, -1, 0}}; // S2PointIndex<int> s2_index; // for(size_t i = 0; i < GA.buckets.size(); i++) // { // auto &bucket_normal = GA.buckets[i].normal; // S2Point s2_point(bucket_normal[0], bucket_normal[1], bucket_normal[2]); // s2_index.Add(s2_point, i); // } // S2ClosestPointQuery<int> query(&s2_index); // query.mutable_options()->set_max_results(1); // Query Points for (size_t i =0; i < normals.size(); i++) { auto &normal = normals[i]; S2Point s2_point(normal[0], normal[1], normal[2]); S2CellId s2_id(s2_point); auto id = s2_id.id(); auto nano_id = NanoS2ID::S2CellId(normal); double pu = 0.0; double pv = 0.0; auto face_s2 = S2::XYZtoFaceUV(s2_point, &pu, &pv); auto st_u = S2::UVtoST(pu); auto st_v = S2::UVtoST(pv); auto ij_u = S2::STtoIJ(st_u); auto ij_v = S2::STtoIJ(st_v); std::cout << "S2 - ID " << id << ";Face: " << face_s2 << "; u:" << pu << " ;v: " << pv << "; st_u:" << st_u << " ; st_v: " << st_v << "; ij_u:" << ij_u << " ; ij_v: " << ij_v << std::endl; face_s2 = NanoS2ID::XYZtoFaceUV(normal, &pu, &pv); st_u = NanoS2ID::UVtoST(pu); st_v = NanoS2ID::UVtoST(pv); ij_u = NanoS2ID::STtoIJ(st_u); ij_v = NanoS2ID::STtoIJ(st_v); std::cout << "Nano S2 - ID " << nano_id << ";Face: " << face_s2 << "; u:" << pu << " ;v: " << pv << "; st_u:" << st_u << " ; st_v: " << st_v << "; ij_u:" << ij_u << " ; ij_v: " << ij_v << std::endl; // S2ClosestPointQuery<int>::PointTarget target(s2_point); // auto results = query.FindClosestPoints(&target); // // std::cout << "Result Size: " << results.size() << std::endl; // if (results.size() > 0) // { // auto bucket_point = results[0].point(); // std::cout << "Looking for: " << normal << "; S2ID is: " << id << "; NanoS2ID is: " << nano_id << "; Found " << bucket_point.x() << ", " << bucket_point.y() << ", " << bucket_point.z() << std::endl; // } } return 0; }
39.014493
213
0.537519
JeremyBYU
e0d7ac4366277a63c3e040b69b48ac81c7ca9e2e
670
cpp
C++
01_simplest_programs/guessnumber.cpp
zaychenko-sergei/cpp_intro
6f1786b18950bf47ee385c97084f3516734e5199
[ "MIT" ]
1
2021-03-05T01:14:00.000Z
2021-03-05T01:14:00.000Z
01_simplest_programs/guessnumber.cpp
zaychenko-sergei/cpp_intro
6f1786b18950bf47ee385c97084f3516734e5199
[ "MIT" ]
null
null
null
01_simplest_programs/guessnumber.cpp
zaychenko-sergei/cpp_intro
6f1786b18950bf47ee385c97084f3516734e5199
[ "MIT" ]
2
2015-01-13T11:25:07.000Z
2021-04-29T12:58:51.000Z
#include <stdio.h> #include <stdlib.h> #include <time.h> int main () { time_t currentTime; time( & currentTime ); srand( ( unsigned ) currentTime ); const int numberToGuess = rand() % 100; int userInput; int steps = 0; do { printf( "Try to guess the number within [ 0 : 99 ]: " ); scanf( "%d", &userInput ); ++ steps; if ( userInput > numberToGuess ) printf( "Too big\n" ); else if ( userInput < numberToGuess ) printf( "Too small\n" ); } while ( userInput != numberToGuess ); printf( "Right guess! Completed in %d steps.\n", steps ); return 0; }
20.9375
64
0.537313
zaychenko-sergei
e0df631bb5eacd0a9c41369dbe29293f02b1dd49
5,093
cxx
C++
src/par/src/MLPart/mlpart/HGraph/subHGraph.cxx
JayjeetAtGithub/OpenROAD
751d7860e2e2929a3b3f8a163c79d843f252ad5b
[ "BSD-3-Clause" ]
null
null
null
src/par/src/MLPart/mlpart/HGraph/subHGraph.cxx
JayjeetAtGithub/OpenROAD
751d7860e2e2929a3b3f8a163c79d843f252ad5b
[ "BSD-3-Clause" ]
1
2021-08-20T07:50:34.000Z
2021-08-20T07:50:34.000Z
src/par/src/MLPart/mlpart/HGraph/subHGraph.cxx
JayjeetAtGithub/OpenROAD
751d7860e2e2929a3b3f8a163c79d843f252ad5b
[ "BSD-3-Clause" ]
2
2021-06-27T09:48:36.000Z
2021-07-23T08:08:01.000Z
/************************************************************************** *** *** Copyright (c) 1995-2000 Regents of the University of California, *** Andrew E. Caldwell, Andrew B. Kahng and Igor L. Markov *** Copyright (c) 2000-2007 Regents of the University of Michigan, *** Saurabh N. Adya, Jarrod A. Roy, David A. Papa and *** Igor L. Markov *** *** Contact author(s): [email protected], [email protected] *** Original Affiliation: UCLA, Computer Science Department, *** Los Angeles, CA 90095-1596 USA *** *** 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. *** *** ***************************************************************************/ // class derived from HyperGraph with Constructor from // nodes/edges of another HGraph. #ifdef _MSC_VER #pragma warning(disable : 4786) #endif #include <HGraph/subHGraph.h> #include <iomanip> using std::cout; using std::endl; using std::setw; using std::vector; SubHGraph::SubHGraph(const HGraphFixed& origHGraph, const vector<const HGFNode*>& nonTerminals, const vector<const HGFNode*>& terminals, const vector<const HGFEdge*>& nets, bool clearTerminalAreas, bool ignoreSize1Nets, unsigned threshold) : HGraphFixed(nonTerminals.size() + terminals.size()), newNodeToOrig(nonTerminals.size() + terminals.size(), UINT_MAX), // newEdgeToOrig(nets.size(), UINT_MAX), newEdgeToOrig(0), _clearTerminalAreas(clearTerminalAreas), _ignoreSize1Nets(ignoreSize1Nets), _threshold(threshold) { _numTerminals = terminals.size(); // _nodeNames = vector<string>(_nodes.size(), string() ); newEdgeToOrig = new Mapping(nets.size(), UINT_MAX); // the HGraph constructor produces the HG nodes with // id's 0->numTerminals + numNonTerminals - 1 in the default // constructor. // setup a mapping from Cluster::_index to HGFNode::mIndex // put the terminal nodes first.. unsigned i, p; for (p = 0, i = 0; p < terminals.size(); p++, i++) addTerminal(origHGraph, *(terminals[p]), i); for (p = 0; p < nonTerminals.size(); p++, i++) addNode(origHGraph, *(nonTerminals[p]), i); vector<const HGFEdge*>::const_iterator e; for (e = nets.begin(), i = 0; e != nets.end(); e++, i++) { if (_ignoreSize1Nets && (*e)->getDegree() < 2) continue; if (threshold > 0 && (*e)->getDegree() >= threshold) continue; HGFEdge& newEdge = addNewEdge(**e); itHGFNodeLocal n; for (n = (*e)->nodesBegin(); n != (*e)->nodesEnd(); n++) { OrigToNewMap::iterator ndItr = origNodeToNew.find((*n)->getIndex()); unsigned hgNodeIdx = (*ndItr).second; #ifdef SIGNAL_DIRECTIONS if ((*e)->isNodeSrc(*n)) addSrc(getNodeByIdx(hgNodeIdx), newEdge); else if ((*e)->isNodeSnk(*n)) addSnk(getNodeByIdx(hgNodeIdx), newEdge); else addSrcSnk(getNodeByIdx(hgNodeIdx), newEdge); #else addSrcSnk(getNodeByIdx(hgNodeIdx), newEdge); #endif } } finalize(); clearNameMaps(); clearNames(); } SubHGraph::~SubHGraph() {} void SubHGraph::printNodeMap() const { cout << endl << "*****************" << endl << "Node's HASH_MAP" << endl; OrigToNewMap::const_iterator m; unsigned* toprint; toprint = reinterpret_cast<unsigned*>(&m); unsigned i = 0; for (m = origNodeToNew.begin(); m != origNodeToNew.end(); m++) { if (i++ % 5 == 0) { if (i) cout << "\n"; cout << " "; } cout << setw(4) << (*m).first << ":" << setw(4) << (*m).second << endl; } cout << "*********************" << "done printing" << endl; }
41.406504
239
0.572943
JayjeetAtGithub
e0dfacd64f22906c454e38b0f0aa630fa73afad6
2,436
cpp
C++
C++/UCIApp3/UCIApp3/UCIApp3.cpp
MuscleNrd/Student-Self-Completed
87c20c4cbd561554eb112047660b698d58711cdc
[ "MIT" ]
null
null
null
C++/UCIApp3/UCIApp3/UCIApp3.cpp
MuscleNrd/Student-Self-Completed
87c20c4cbd561554eb112047660b698d58711cdc
[ "MIT" ]
null
null
null
C++/UCIApp3/UCIApp3/UCIApp3.cpp
MuscleNrd/Student-Self-Completed
87c20c4cbd561554eb112047660b698d58711cdc
[ "MIT" ]
null
null
null
// UCIApp3.cpp : Defines the entry point for the console application. // #include "stdafx.h" template <class T> class setList { private: struct setListNode { T info; setListNode* next; setListNode() : next(0) {} //setListNode(const T& newinfo) : info(newinfo), next(0) {} setListNode(T& newinfo, setListNode *newnext = 0) :info(newinfo), next(newnext) {} static void deleteSetList(setListNode *S) { if (S != NULL) { deleteSetList(S->next); } } }; setListNode *buf; int itemCount; void init() { itemCount = 0; buf = new setListNode(); } public: setList() : buf(0), itemCount(0) {} //setList(initializer_list<T> s) //: buf(new setListNode) { uninitialized_copy(s.begin(), s.end(), buf);} setList(const setList<T>& aSet) { init(); *this = aSet; } void insert(const T& newEntry) { setListNode* nextListNode = new setListNode(); nextListNode->info = newEntry; nextListNode->next = buf; buf = nextListNode; itemCount++; } //int getSize() {return itemCount;} class setListIter { typedef setListIter iterator; typedef ptrdiff_t difference_type; typedef size_t size_type; typedef T value_type; typedef T* ptr; typedef T& reference; private: setList ibuf; public: setListIter(setList p) : ibuf(p) {} // setListIter(const setList<T>& SL) setListIter& operator++() { ibuf.buf = ibuf.buf->next; return *this; } setListIter operator++(int postfix) { setListIter temp = ibuf; ibuf++; return temp; } setListIter operator=(const setListIter& rhs) { ibuf = rhs.ibuf; return *this; } bool operator==(const setListIter& rhs) { return ibuf->info == rhs.ibuf->info; } bool operator!=(const setListIter& rhs) { return ibuf.buf->info != rhs.ibuf.buf->info; } ptr operator->() { return ibuf; } reference operator*() { return ibuf.buf->info; } }; setListIter find(const T& val) const; setListIter begin() { return setListIter(*this); } setListIter end() { while (buf->next != NULL) { buf++; } return *this; } ~setList() { buf->deleteSetList(buf); } }; using namespace std; int main() { setList<int> A; A.insert(1); A.insert(2); for (int i = 3; i <= 10; i++) A.insert(i); setList<int> B; for (int i = 20; i <= 40; i++) B.insert(i); setList<int> C(B); for (setList<int>::setListIter it = A.begin(); it != A.end(); ++it) cout << *it << endl; return 0; }
16.459459
90
0.626847
MuscleNrd
e0e0900842540fe857d203c84206d53231838295
7,474
cpp
C++
CocosNet/CCNetDelegate.cpp
leecjson/CocosNet
e762999aa6c0be276bc6d3eb0b511e921b792f36
[ "MIT" ]
8
2018-11-29T02:07:44.000Z
2020-12-24T09:34:06.000Z
CocosNet/CCNetDelegate.cpp
leecjson/CocosNet
e762999aa6c0be276bc6d3eb0b511e921b792f36
[ "MIT" ]
null
null
null
CocosNet/CCNetDelegate.cpp
leecjson/CocosNet
e762999aa6c0be276bc6d3eb0b511e921b792f36
[ "MIT" ]
4
2019-01-14T13:33:14.000Z
2020-06-06T06:42:50.000Z
/**************************************************************************** Copyright (c) 2014 Lijunlin - Jason lee Created by Lijunlin - Jason lee on 2014 [email protected] http://www.cocos2d-x.org 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 "CCNetDelegate.h" NS_CC_BEGIN CCNetDelegate::CCNetDelegate() : m_fSoTimeout(SOCKET_SOTIMEOUT) , m_eStatus(eSocketIoClosed) , m_fConnectingDuration(0.0f) , m_bRunSchedule(false) { } CCNetDelegate::~CCNetDelegate() { m_oSocket.ccClose(); while(!m_lSendBuffers.empty()) { CC_SAFE_DELETE_ARRAY(m_lSendBuffers.front().pBuffer); m_lSendBuffers.pop_front(); } } void CCNetDelegate::setInetAddress(const CCInetAddress& oInetAddress) { m_oInetAddress = oInetAddress; } const CCInetAddress& CCNetDelegate::getInetAddress() const { return m_oInetAddress; } void CCNetDelegate::setSoTimeout(float fSoTimeout) { m_fSoTimeout = fSoTimeout; } float CCNetDelegate::getSoTimeout() const { return m_fSoTimeout; } void CCNetDelegate::send(char* pBuffer, unsigned int uLen) { if( !pBuffer || uLen == 0 || !isConnected() ) return; #if USING_PACKAGE_HEAD_LENGTH CCBuffer* pBuf = new CCBuffer(pBuffer, uLen); pBuf->autorelease(); send(pBuf); #else char* pTemp = new char[uLen]; memcpy(pTemp, pBuffer, uLen); _SENDBUFFER tBuf; tBuf.pBuffer = pTemp; tBuf.nLength = (int)uLen; tBuf.nOffset = 0; m_lSendBuffers.push_back(tBuf); #endif } void CCNetDelegate::send(CCBuffer* pBuffer) { if( pBuffer->empty() || !isConnected() ) return; #if USING_PACKAGE_HEAD_LENGTH unsigned int u_len = pBuffer->length(); pBuffer->moveRight(sizeof(unsigned int)); pBuffer->moveWriterIndexToFront(); pBuffer->writeUInt(u_len); #endif pBuffer->moveReaderIndexToFront(); char* pData = pBuffer->readWholeData(); int nLength = (int)pBuffer->length(); pBuffer->moveReaderIndexToFront(); _SENDBUFFER tBuf; tBuf.pBuffer = pData; tBuf.nLength = nLength; tBuf.nOffset = 0; m_lSendBuffers.push_back(tBuf); } bool CCNetDelegate::isConnected() { return m_eStatus == eSocketConnected; } bool CCNetDelegate::connect() { if( m_eStatus != eSocketConnected && m_eStatus != eSocketConnecting ) { m_oSocket.setInetAddress(m_oInetAddress); if( m_oSocket.ccConnect() ) { registerScheduler(); m_eStatus = eSocketConnecting; return true; } else { m_oSocket.ccClose(); m_eStatus = eSocketConnectFailed; onExceptionCaught(eSocketConnectFailed); } } return false; } void CCNetDelegate::disconnect() { if( m_eStatus == eSocketConnected ) { unregisterScheduler(); m_oSocket.ccDisconnect(); m_eStatus = eSocketDisconnected; onDisconnected(); } } void CCNetDelegate::close() { if( m_eStatus == eSocketConnected ) { unregisterScheduler(); m_oSocket.ccClose(); m_eStatus = eSocketIoClosed; onDisconnected(); } } void CCNetDelegate::runSchedule(float dt) { switch( m_eStatus ) { case eSocketConnecting: { switch( m_oSocket.ccIsConnected() ) { case eSocketConnected: { m_eStatus = eSocketConnected; onConnected(); } break; case eSocketConnectFailed: { unregisterScheduler(); m_oSocket.ccClose(); m_eStatus = eSocketConnectFailed; onExceptionCaught(eSocketConnectFailed); } break; case eSocketConnecting: { if( m_fConnectingDuration > m_fSoTimeout ) { unregisterScheduler(); m_oSocket.ccDisconnect(); m_eStatus = eSocketDisconnected; onConnectTimeout(); m_fConnectingDuration = 0.0f; } else { m_fConnectingDuration += dt; } } break; default: break; } } break; case eSocketConnected: { #if HANDLE_ON_SINGLE_FRAME while( m_oSocket.ccIsReadable() ) #else if( m_oSocket.ccIsReadable() ) #endif { if( this->runRead() ) return; } #if HANDLE_ON_SINGLE_FRAME while( m_oSocket.ccIsWritable() && !m_lSendBuffers.empty() ) #else if( m_oSocket.ccIsWritable() && !m_lSendBuffers.empty() ) #endif { if( this->runWrite() ) return; } } break; default: break; } } bool CCNetDelegate::runRead() { int nRet = m_oSocket.ccRead(m_pReadBuffer, SOCKET_READ_BUFFER_SIZE); if( nRet == eSocketIoError || nRet == eSocketIoClosed ) { unregisterScheduler(); m_oSocket.ccClose(); m_eStatus = eSocketIoClosed; onDisconnected(); return true; } else { #if 1 CCLOG("CCSOCKET READ %d", nRet); #endif m_oReadBuffer.writeData(m_pReadBuffer, (unsigned int)nRet); #if USING_PACKAGE_HEAD_LENGTH while( m_oReadBuffer.isReadable(sizeof(int)) ) { m_oReadBuffer.moveReaderIndexToFront(); int n_head_len = m_oReadBuffer.readInt(); if( n_head_len <= 0 ) { CCLOGERROR("invalidate head length"); m_oReadBuffer.moveLeft(sizeof(int)); } int n_content_len = (int)m_oReadBuffer.length(); if( n_content_len - (int)(sizeof(int)) >= n_head_len ) { m_oReadBuffer.moveLeft(sizeof(unsigned int)); CCBuffer* pData = m_oReadBuffer.readData(n_head_len); m_oReadBuffer.moveLeft(n_head_len); m_oReadBuffer.moveReaderIndexToFront(); m_oReadBuffer.moveWriterIndexToBack(); onMessageReceived(*pData); } else { break; } } #else CCBuffer* pData = (CCBuffer*) m_oReadBuffer.copy(); pData->autorelease(); m_oReadBuffer.clear(); onMessageReceived(*pData); #endif } return false; } bool CCNetDelegate::runWrite() { _SENDBUFFER& tBuffer = m_lSendBuffers.front(); int nRet = m_oSocket.ccWrite(tBuffer.pBuffer + tBuffer.nOffset, tBuffer.nLength - tBuffer.nOffset); #if 1 CCLOG("CCSOCKET WRITE %d", nRet); #endif if( nRet == eSocketIoError ) { unregisterScheduler(); m_oSocket.ccClose(); m_eStatus = eSocketIoClosed; onDisconnected(); return true; } else if( nRet == tBuffer.nLength - tBuffer.nOffset ) { CC_SAFE_DELETE_ARRAY(tBuffer.pBuffer); m_lSendBuffers.pop_front(); } else { tBuffer.nOffset += nRet; } return false; } void CCNetDelegate::registerScheduler() { if( m_bRunSchedule ) return; CCDirector::sharedDirector()->getScheduler()->scheduleSelector( schedule_selector(CCNetDelegate::runSchedule), this, 0.0f, false ); m_bRunSchedule = true; } void CCNetDelegate::unregisterScheduler() { if( !m_bRunSchedule ) return; CCDirector::sharedDirector()->getScheduler()->unscheduleSelector( schedule_selector(CCNetDelegate::runSchedule), this ); m_bRunSchedule = false; } NS_CC_END
21.601156
100
0.701766
leecjson
e0e3a3f3e1e98ff3452f99a0064ce44d6eca3529
703
cpp
C++
tests/multiArray.cpp
Oparilames/aNDAr-library
304e4923a3777b73d63964460a859896583b8a3d
[ "MIT" ]
null
null
null
tests/multiArray.cpp
Oparilames/aNDAr-library
304e4923a3777b73d63964460a859896583b8a3d
[ "MIT" ]
1
2022-03-31T17:07:07.000Z
2022-03-31T17:07:07.000Z
tests/multiArray.cpp
Oparilames/aNDAr-library
304e4923a3777b73d63964460a859896583b8a3d
[ "MIT" ]
null
null
null
#include <aNDAr/multiDimensionalArray.hpp> using namespace aNDAr; int main(){ using T = multiDimensionalArray<int,3,3,3>; using C = multiDimensionalArray<char,3,3,3>; {T ar{};} {T ar(5);} /// {T ar(initialisationMethod::incrementFrom,1);} // 2022 {T ar{initialisationMethod::decrementFrom,1};} {T ar(initialisationMethod::incrementFrom,10,2);} {T ar(initialiseByIncrementFrom,10,2);} {T ar(aNDAr::incrementFrom,10,2);} {C ar("ThisIsATestThisIsATest!!!!!");} {C ar(aNDAr::incrementFrom,'a');} return EXIT_SUCCESS; } /* LANG=en g++ -Wfatal-errors -std=c++20 -O2 -I./src -I./include tests/multiArray.cpp -o ./bin/Test_multiArray && ./bin/Test_multiArray */
33.47619
132
0.664296
Oparilames
e0e3d1b6e8b7d7c1456019b81cd135f4e2c532e0
32,257
cpp
C++
DumpDWG/maps.cpp
MadhukarMoogala/RealDWGInstallerWithWix
ad7734ec2e968bb192b4d0a827d60647066df6a6
[ "MIT" ]
11
2018-08-03T19:22:03.000Z
2021-12-16T15:33:00.000Z
DumpDWG/maps.cpp
MadhukarMoogala/RealDWGInstallerWithWix
ad7734ec2e968bb192b4d0a827d60647066df6a6
[ "MIT" ]
null
null
null
DumpDWG/maps.cpp
MadhukarMoogala/RealDWGInstallerWithWix
ad7734ec2e968bb192b4d0a827d60647066df6a6
[ "MIT" ]
6
2019-01-10T09:16:23.000Z
2021-12-08T16:29:24.000Z
// ////////////////////////////////////////////////////////////////////////////// // // Copyright 2018 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk license // agreement provided at the time of installation or download, or which // otherwise accompanies this software in either electronic or hard copy form. // ////////////////////////////////////////////////////////////////////////////// // // MAPS.CPP // // DESCRIPTION: // // Port of MFC maps. // ///////////////////////////////////////////////////////////////////////////// // // Implementation of parmeterized Map // ///////////////////////////////////////////////////////////////////////////// #define DEBUG_NEW new #include "assert.h" #ifdef _DEBUG #define ASSERT(a) assert(a) #else #define ASSERT(a) #endif #ifdef AFX_COLL2_SEG #pragma code_seg(AFX_COLL2_SEG) #endif #include "wtypes.h" #include "maps.h" IMPLEMENT_DYNAMIC(CMapWordToPtr, CObject) #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif #define new DEBUG_NEW ///////////////////////////////////////////////////////////////////////////// CMapWordToPtr::CMapWordToPtr(int nBlockSize) { ASSERT(nBlockSize > 0); m_pHashTable = NULL; m_nHashTableSize = RX_HASHTABLESIZE; // default size m_nCount = 0; m_pFreeList = NULL; m_pBlocks = NULL; m_nBlockSize = nBlockSize; } inline UINT_PTR CMapWordToPtr::HashKey(WORD key) const { // Default identity hash, works for most primitive values. return ((DWORD_PTR)key) >> 4; } void CMapWordToPtr::InitHashTable(UINT_PTR nHashSize) // // Used to force allocation of a hash table or to override the default // hash table size of (which is fairly small). { ASSERT_VALID(this); ASSERT(m_nCount == 0); ASSERT(nHashSize > 0); // If had a hash table, get rid of it. if (m_pHashTable != NULL) delete [] m_pHashTable; m_pHashTable = NULL; m_pHashTable = new CAssoc* [nHashSize]; memset(m_pHashTable, 0, sizeof(CAssoc*) * nHashSize); m_nHashTableSize = nHashSize; } void CMapWordToPtr::RemoveAll() { ASSERT_VALID(this); if (m_pHashTable != NULL) { // Free hash table. delete [] m_pHashTable; m_pHashTable = NULL; } m_nCount = 0; m_pFreeList = NULL; m_pBlocks->FreeDataChain(); m_pBlocks = NULL; } CMapWordToPtr::~CMapWordToPtr() { RemoveAll(); ASSERT(m_nCount == 0); } ///////////////////////////////////////////////////////////////////////////// // Assoc helpers // same as CList implementation except we store CAssoc's not CNode's // and CAssoc's are singly linked all the time CMapWordToPtr::CAssoc* CMapWordToPtr::NewAssoc() { if (m_pFreeList == NULL) { // Add another block. CPlex* newBlock = CPlex::Create(m_pBlocks, m_nBlockSize, sizeof(CMapWordToPtr::CAssoc)); // Chain them into free list. CMapWordToPtr::CAssoc* pAssoc = (CMapWordToPtr::CAssoc*) newBlock->data(); // Free in reverse order to make it easier to debug. pAssoc += m_nBlockSize - 1; for (int i = m_nBlockSize-1; i >= 0; i--, pAssoc--) { pAssoc->pNext = m_pFreeList; m_pFreeList = pAssoc; } } ASSERT(m_pFreeList != NULL); // we must have something CMapWordToPtr::CAssoc* pAssoc = m_pFreeList; m_pFreeList = m_pFreeList->pNext; m_nCount++; ASSERT(m_nCount > 0); // Make sure we don't overflow. memset(&pAssoc->key, 0, sizeof(WORD)); memset(&pAssoc->value, 0, sizeof(void*)); return pAssoc; } void CMapWordToPtr::FreeAssoc(CMapWordToPtr::CAssoc* pAssoc) { pAssoc->pNext = m_pFreeList; m_pFreeList = pAssoc; m_nCount--; ASSERT(m_nCount >= 0); // Make sure we don't underflow. } CMapWordToPtr::CAssoc* CMapWordToPtr::GetAssocAt(WORD key, UINT_PTR& nHash) const // Find association (or return NULL). { nHash = HashKey(key) % m_nHashTableSize; if (m_pHashTable == NULL) return NULL; // See if it exists. CAssoc* pAssoc; for (pAssoc = m_pHashTable[nHash]; pAssoc != NULL; pAssoc = pAssoc->pNext) { if (pAssoc->key == key) return pAssoc; } return NULL; } ///////////////////////////////////////////////////////////////////////////// BOOL CMapWordToPtr::Lookup(WORD key, void*& rValue) const { ASSERT_VALID(this); UINT_PTR nHash; CAssoc* pAssoc = GetAssocAt(key, nHash); if (pAssoc == NULL) return FALSE; // Not in map. rValue = pAssoc->value; return TRUE; } void*& CMapWordToPtr::operator[](WORD key) { ASSERT_VALID(this); UINT_PTR nHash; CAssoc* pAssoc; if ((pAssoc = GetAssocAt(key, nHash)) == NULL) { if (m_pHashTable == NULL) InitHashTable(m_nHashTableSize); // It doesn't exist, add a new Association. pAssoc = NewAssoc(); pAssoc->nHashValue = nHash; pAssoc->key = key; // 'pAssoc->value' is a constructed object, nothing more // Put into hash table. pAssoc->pNext = m_pHashTable[nHash]; m_pHashTable[nHash] = pAssoc; } return pAssoc->value; // return new reference } BOOL CMapWordToPtr::RemoveKey(WORD key) // Remove key - return TRUE if removed. { ASSERT_VALID(this); if (m_pHashTable == NULL) return FALSE; // nothing in the table CAssoc** ppAssocPrev; ppAssocPrev = &m_pHashTable[HashKey(key) % m_nHashTableSize]; CAssoc* pAssoc; for (pAssoc = *ppAssocPrev; pAssoc != NULL; pAssoc = pAssoc->pNext) { if (pAssoc->key == key) { // Remove it. *ppAssocPrev = pAssoc->pNext; // Remove from list. FreeAssoc(pAssoc); return TRUE; } ppAssocPrev = &pAssoc->pNext; } return FALSE; // Not found. } ///////////////////////////////////////////////////////////////////////////// // Iterating void CMapWordToPtr::GetNextAssoc(RXPOSITION& rNextPosition, WORD& rKey, void*& rValue) const { ASSERT_VALID(this); ASSERT(m_pHashTable != NULL); // never call on empty map CAssoc* pAssocRet = (CAssoc*)rNextPosition; ASSERT(pAssocRet != NULL); if (pAssocRet == (CAssoc*) BEFORE_START_RXPOSITION) { // Find the first association. for (UINT nBucket = 0; nBucket < m_nHashTableSize; nBucket++) if ((pAssocRet = m_pHashTable[nBucket]) != NULL) break; ASSERT(pAssocRet != NULL); // Must find something. } // Find next association. ASSERT(AfxIsValidAddress(pAssocRet, sizeof(CAssoc))); CAssoc* pAssocNext; if ((pAssocNext = pAssocRet->pNext) == NULL) { // Go to next bucket. for (UINT_PTR nBucket = pAssocRet->nHashValue + 1; nBucket < m_nHashTableSize; nBucket++) if ((pAssocNext = m_pHashTable[nBucket]) != NULL) break; } rNextPosition = (RXPOSITION) pAssocNext; // Fill in return data. rKey = pAssocRet->key; rValue = pAssocRet->value; } ///////////////////////////////////////////////////////////////////////////// // Serialization ///////////////////////////////////////////////////////////////////////////// // Diagnostics #ifdef _DEBUG void CMapWordToPtr::Dump(CDumpContext& dc) const { ASSERT_VALID(this); #define MAKESTRING(x) #x AFX_DUMP1(dc, "a " MAKESTRING(CMapWordToPtr) " with ", m_nCount); AFX_DUMP0(dc, " elements"); #undef MAKESTRING if (dc.GetDepth() > 0) { // Dump in format "[key] -> value". RXPOSITION pos = GetStartPosition(); WORD key; void* val; AFX_DUMP0(dc, "\n"); while (pos != NULL) { GetNextAssoc(pos, key, val); AFX_DUMP1(dc, "\n\t[", key); AFX_DUMP1(dc, "] = ", val); } } } void CMapWordToPtr::AssertValid() const { CObject::AssertValid(); ASSERT(m_nHashTableSize > 0); ASSERT(m_nCount == 0 || m_pHashTable != NULL); // Non-empty map should have hash table. } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // // Implementation of parmeterized Map // ///////////////////////////////////////////////////////////////////////////// #ifdef AFX_COLL2_SEG #pragma code_seg(AFX_COLL2_SEG) #endif IMPLEMENT_DYNAMIC(CMapPtrToWord, CObject) #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif #define new DEBUG_NEW ///////////////////////////////////////////////////////////////////////////// CMapPtrToWord::CMapPtrToWord(int nBlockSize) { ASSERT(nBlockSize > 0); m_pHashTable = NULL; m_nHashTableSize = RX_HASHTABLESIZE; // default size m_nCount = 0; m_pFreeList = NULL; m_pBlocks = NULL; m_nBlockSize = nBlockSize; } inline UINT_PTR CMapPtrToWord::HashKey(void* key) const { // Default identity hash - works for most primitive values. return UINT_PTR(DWORD_PTR(key)>>4); } void CMapPtrToWord::InitHashTable(UINT_PTR nHashSize) // // Used to force allocation of a hash table or to override the default // hash table size of (which is fairly small). { ASSERT_VALID(this); ASSERT(m_nCount == 0); ASSERT(nHashSize > 0); // if had a hash table - get rid of it if (m_pHashTable != NULL) delete [] m_pHashTable; m_pHashTable = NULL; m_pHashTable = new CAssoc* [nHashSize]; memset(m_pHashTable, 0, sizeof(CAssoc*) * nHashSize); m_nHashTableSize = nHashSize; } void CMapPtrToWord::RemoveAll() { ASSERT_VALID(this); if (m_pHashTable != NULL) { // free hash table delete [] m_pHashTable; m_pHashTable = NULL; } m_nCount = 0; m_pFreeList = NULL; m_pBlocks->FreeDataChain(); m_pBlocks = NULL; } CMapPtrToWord::~CMapPtrToWord() { RemoveAll(); ASSERT(m_nCount == 0); } ///////////////////////////////////////////////////////////////////////////// // Assoc helpers // same as CList implementation except we store CAssoc's not CNode's // and CAssoc's are singly linked all the time CMapPtrToWord::CAssoc* CMapPtrToWord::NewAssoc() { if (m_pFreeList == NULL) { // add another block CPlex* newBlock = CPlex::Create(m_pBlocks, m_nBlockSize, sizeof(CMapPtrToWord::CAssoc)); // chain them into free list CMapPtrToWord::CAssoc* pAssoc = (CMapPtrToWord::CAssoc*) newBlock->data(); // free in reverse order to make it easier to debug pAssoc += m_nBlockSize - 1; for (int i = m_nBlockSize-1; i >= 0; i--, pAssoc--) { pAssoc->pNext = m_pFreeList; m_pFreeList = pAssoc; } } ASSERT(m_pFreeList != NULL); // we must have something CMapPtrToWord::CAssoc* pAssoc = m_pFreeList; m_pFreeList = m_pFreeList->pNext; m_nCount++; ASSERT(m_nCount > 0); // make sure we don't overflow memset(&pAssoc->key, 0, sizeof(void*)); memset(&pAssoc->value, 0, sizeof(WORD)); return pAssoc; } void CMapPtrToWord::FreeAssoc(CMapPtrToWord::CAssoc* pAssoc) { pAssoc->pNext = m_pFreeList; m_pFreeList = pAssoc; m_nCount--; ASSERT(m_nCount >= 0); // make sure we don't underflow } CMapPtrToWord::CAssoc* CMapPtrToWord::GetAssocAt(void* key, UINT_PTR& nHash) const // find association (or return NULL) { nHash = HashKey(key) % m_nHashTableSize; if (m_pHashTable == NULL) return NULL; // see if it exists CAssoc* pAssoc; for (pAssoc = m_pHashTable[nHash]; pAssoc != NULL; pAssoc = pAssoc->pNext) { if (pAssoc->key == key) return pAssoc; } return NULL; } ///////////////////////////////////////////////////////////////////////////// BOOL CMapPtrToWord::Lookup(void* key, WORD& rValue) const { ASSERT_VALID(this); UINT_PTR nHash; CAssoc* pAssoc = GetAssocAt(key, nHash); if (pAssoc == NULL) return FALSE; // not in map rValue = pAssoc->value; return TRUE; } WORD& CMapPtrToWord::operator[](void* key) { ASSERT_VALID(this); UINT_PTR nHash; CAssoc* pAssoc; if ((pAssoc = GetAssocAt(key, nHash)) == NULL) { if (m_pHashTable == NULL) InitHashTable(m_nHashTableSize); // it doesn't exist, add a new Association pAssoc = NewAssoc(); pAssoc->nHashValue = nHash; pAssoc->key = key; // 'pAssoc->value' is a constructed object, nothing more // put into hash table pAssoc->pNext = m_pHashTable[nHash]; m_pHashTable[nHash] = pAssoc; } return pAssoc->value; // return new reference } BOOL CMapPtrToWord::RemoveKey(void* key) // remove key - return TRUE if removed { ASSERT_VALID(this); if (m_pHashTable == NULL) return FALSE; // nothing in the table CAssoc** ppAssocPrev; ppAssocPrev = &m_pHashTable[HashKey(key) % m_nHashTableSize]; CAssoc* pAssoc; for (pAssoc = *ppAssocPrev; pAssoc != NULL; pAssoc = pAssoc->pNext) { if (pAssoc->key == key) { // remove it *ppAssocPrev = pAssoc->pNext; // remove from list FreeAssoc(pAssoc); return TRUE; } ppAssocPrev = &pAssoc->pNext; } return FALSE; // not found } ///////////////////////////////////////////////////////////////////////////// // Iterating void CMapPtrToWord::GetNextAssoc(RXPOSITION& rNextPosition, void*& rKey, WORD& rValue) const { ASSERT_VALID(this); ASSERT(m_pHashTable != NULL); // never call on empty map CAssoc* pAssocRet = (CAssoc*)rNextPosition; ASSERT(pAssocRet != NULL); if (pAssocRet == (CAssoc*) BEFORE_START_RXPOSITION) { // find the first association for (UINT nBucket = 0; nBucket < m_nHashTableSize; nBucket++) if ((pAssocRet = m_pHashTable[nBucket]) != NULL) break; ASSERT(pAssocRet != NULL); // must find something } // find next association ASSERT(AfxIsValidAddress(pAssocRet, sizeof(CAssoc))); CAssoc* pAssocNext; if ((pAssocNext = pAssocRet->pNext) == NULL) { // go to next bucket for (UINT_PTR nBucket = pAssocRet->nHashValue + 1; nBucket < m_nHashTableSize; nBucket++) if ((pAssocNext = m_pHashTable[nBucket]) != NULL) break; } rNextPosition = (RXPOSITION) pAssocNext; // fill in return data rKey = pAssocRet->key; rValue = pAssocRet->value; } ///////////////////////////////////////////////////////////////////////////// // Serialization ///////////////////////////////////////////////////////////////////////////// // Diagnostics #ifdef _DEBUG void CMapPtrToWord::Dump(CDumpContext& dc) const { ASSERT_VALID(this); #define MAKESTRING(x) #x AFX_DUMP1(dc, "a " MAKESTRING(CMapPtrToWord) " with ", m_nCount); AFX_DUMP0(dc, " elements"); #undef MAKESTRING if (dc.GetDepth() > 0) { // Dump in format "[key] -> value" RXPOSITION pos = GetStartPosition(); void* key; WORD val; AFX_DUMP0(dc, "\n"); while (pos != NULL) { GetNextAssoc(pos, key, val); AFX_DUMP1(dc, "\n\t[", key); AFX_DUMP1(dc, "] = ", val); } } } void CMapPtrToWord::AssertValid() const { CObject::AssertValid(); ASSERT(m_nHashTableSize > 0); ASSERT(m_nCount == 0 || m_pHashTable != NULL); // non-empty map should have hash table } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // // Implementation of parmeterized Map // ///////////////////////////////////////////////////////////////////////////// #ifdef AFX_COLL2_SEG #pragma code_seg(AFX_COLL2_SEG) #endif IMPLEMENT_DYNAMIC(CMapPtrToPtr, CObject) #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif #define new DEBUG_NEW ///////////////////////////////////////////////////////////////////////////// CMapPtrToPtr::CMapPtrToPtr(int nBlockSize) { ASSERT(nBlockSize > 0); m_pHashTable = NULL; m_nHashTableSize = RX_HASHTABLESIZE; // default size m_nCount = 0; m_pFreeList = NULL; m_pBlocks = NULL; m_nBlockSize = nBlockSize; } inline UINT_PTR CMapPtrToPtr::HashKey(void* key) const { // default identity hash - works for most primitive values return UINT_PTR(DWORD_PTR(key)>>4); } void CMapPtrToPtr::InitHashTable(UINT_PTR nHashSize) // // Used to force allocation of a hash table or to override the default // hash table size of (which is fairly small) { ASSERT_VALID(this); ASSERT(m_nCount == 0); ASSERT(nHashSize > 0); // if had a hash table - get rid of it if (m_pHashTable != NULL) delete [] m_pHashTable; m_pHashTable = NULL; m_pHashTable = new CAssoc* [nHashSize]; memset(m_pHashTable, 0, sizeof(CAssoc*) * nHashSize); m_nHashTableSize = nHashSize; } void CMapPtrToPtr::RemoveAll() { ASSERT_VALID(this); if (m_pHashTable != NULL) { // free hash table delete [] m_pHashTable; m_pHashTable = NULL; } m_nCount = 0; m_pFreeList = NULL; m_pBlocks->FreeDataChain(); m_pBlocks = NULL; } CMapPtrToPtr::~CMapPtrToPtr() { RemoveAll(); ASSERT(m_nCount == 0); } ///////////////////////////////////////////////////////////////////////////// // Assoc helpers // same as CList implementation except we store CAssoc's not CNode's // and CAssoc's are singly linked all the time CMapPtrToPtr::CAssoc* CMapPtrToPtr::NewAssoc() { if (m_pFreeList == NULL) { // add another block CPlex* newBlock = CPlex::Create(m_pBlocks, m_nBlockSize, sizeof(CMapPtrToPtr::CAssoc)); // chain them into free list CMapPtrToPtr::CAssoc* pAssoc = (CMapPtrToPtr::CAssoc*) newBlock->data(); // free in reverse order to make it easier to debug pAssoc += m_nBlockSize - 1; for (int i = m_nBlockSize-1; i >= 0; i--, pAssoc--) { pAssoc->pNext = m_pFreeList; m_pFreeList = pAssoc; } } ASSERT(m_pFreeList != NULL); // we must have something CMapPtrToPtr::CAssoc* pAssoc = m_pFreeList; m_pFreeList = m_pFreeList->pNext; m_nCount++; ASSERT(m_nCount > 0); // make sure we don't overflow memset(&pAssoc->key, 0, sizeof(void*)); memset(&pAssoc->value, 0, sizeof(void*)); return pAssoc; } void CMapPtrToPtr::FreeAssoc(CMapPtrToPtr::CAssoc* pAssoc) { pAssoc->pNext = m_pFreeList; m_pFreeList = pAssoc; m_nCount--; ASSERT(m_nCount >= 0); // make sure we don't underflow } CMapPtrToPtr::CAssoc* CMapPtrToPtr::GetAssocAt(void* key, UINT_PTR& nHash) const // find association (or return NULL) { nHash = HashKey(key) % m_nHashTableSize; if (m_pHashTable == NULL) return NULL; // see if it exists CAssoc* pAssoc; for (pAssoc = m_pHashTable[nHash]; pAssoc != NULL; pAssoc = pAssoc->pNext) { if (pAssoc->key == key) return pAssoc; } return NULL; } ///////////////////////////////////////////////////////////////////////////// BOOL CMapPtrToPtr::Lookup(void* key, void*& rValue) const { ASSERT_VALID(this); UINT_PTR nHash; CAssoc* pAssoc = GetAssocAt(key, nHash); if (pAssoc == NULL) return FALSE; // not in map rValue = pAssoc->value; return TRUE; } void*& CMapPtrToPtr::operator[](void* key) { ASSERT_VALID(this); UINT_PTR nHash; CAssoc* pAssoc; if ((pAssoc = GetAssocAt(key, nHash)) == NULL) { if (m_pHashTable == NULL) InitHashTable(m_nHashTableSize); // it doesn't exist, add a new Association pAssoc = NewAssoc(); pAssoc->nHashValue = nHash; pAssoc->key = key; // 'pAssoc->value' is a constructed object, nothing more // put into hash table pAssoc->pNext = m_pHashTable[nHash]; m_pHashTable[nHash] = pAssoc; } return pAssoc->value; // return new reference } BOOL CMapPtrToPtr::RemoveKey(void* key) // remove key - return TRUE if removed { ASSERT_VALID(this); if (m_pHashTable == NULL) return FALSE; // nothing in the table CAssoc** ppAssocPrev; ppAssocPrev = &m_pHashTable[HashKey(key) % m_nHashTableSize]; CAssoc* pAssoc; for (pAssoc = *ppAssocPrev; pAssoc != NULL; pAssoc = pAssoc->pNext) { if (pAssoc->key == key) { // remove it *ppAssocPrev = pAssoc->pNext; // remove from list FreeAssoc(pAssoc); return TRUE; } ppAssocPrev = &pAssoc->pNext; } return FALSE; // not found } ///////////////////////////////////////////////////////////////////////////// // Iterating void CMapPtrToPtr::GetNextAssoc(RXPOSITION& rNextPosition, void*& rKey, void*& rValue) const { ASSERT_VALID(this); ASSERT(m_pHashTable != NULL); // never call on empty map CAssoc* pAssocRet = (CAssoc*)rNextPosition; ASSERT(pAssocRet != NULL); if (pAssocRet == (CAssoc*) BEFORE_START_RXPOSITION) { // find the first association for (UINT nBucket = 0; nBucket < m_nHashTableSize; nBucket++) if ((pAssocRet = m_pHashTable[nBucket]) != NULL) break; ASSERT(pAssocRet != NULL); // must find something } // find next association ASSERT(AfxIsValidAddress(pAssocRet, sizeof(CAssoc))); CAssoc* pAssocNext; if ((pAssocNext = pAssocRet->pNext) == NULL) { // go to next bucket for (UINT_PTR nBucket = pAssocRet->nHashValue + 1; nBucket < m_nHashTableSize; nBucket++) if ((pAssocNext = m_pHashTable[nBucket]) != NULL) break; } rNextPosition = (RXPOSITION) pAssocNext; // fill in return data rKey = pAssocRet->key; rValue = pAssocRet->value; } ///////////////////////////////////////////////////////////////////////////// // Serialization ///////////////////////////////////////////////////////////////////////////// // Diagnostics #ifdef _DEBUG void CMapPtrToPtr::Dump(CDumpContext& dc) const { ASSERT_VALID(this); #define MAKESTRING(x) #x AFX_DUMP1(dc, "a " MAKESTRING(CMapPtrToPtr) " with ", m_nCount); AFX_DUMP0(dc, " elements"); #undef MAKESTRING if (dc.GetDepth() > 0) { // Dump in format "[key] -> value" RXPOSITION pos = GetStartPosition(); void* key; void* val; AFX_DUMP0(dc, "\n"); while (pos != NULL) { GetNextAssoc(pos, key, val); AFX_DUMP1(dc, "\n\t[", key); AFX_DUMP1(dc, "] = ", val); } } } void CMapPtrToPtr::AssertValid() const { CObject::AssertValid(); ASSERT(m_nHashTableSize > 0); ASSERT(m_nCount == 0 || m_pHashTable != NULL); // non-empty map should have hash table } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // // Implementation of parmeterized Map from CString to value // ///////////////////////////////////////////////////////////////////////////// #include <string.h> #ifdef AFX_COLL2_SEG #pragma code_seg(AFX_COLL2_SEG) #endif IMPLEMENT_SERIAL(CMapStringToOb, CObject, 0) #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif #define new DEBUG_NEW const char *afxEmptyString = ""; extern const char *afxEmptyString; // for creating empty key strings ///////////////////////////////////////////////////////////////////////////// CMapStringToOb::CMapStringToOb(int nBlockSize) { ASSERT(nBlockSize > 0); m_pHashTable = NULL; m_nHashTableSize = RX_HASHTABLESIZE; // default size m_nCount = 0; m_pFreeList = NULL; m_pBlocks = NULL; m_nBlockSize = nBlockSize; } inline UINT_PTR CMapStringToOb::HashKey(const char* key) const { UINT_PTR nHash = 0; while (*key) nHash = (nHash<<5) + nHash + *key++; return nHash; } void CMapStringToOb::InitHashTable(UINT_PTR nHashSize) // // Used to force allocation of a hash table or to override the default // hash table size of (which is fairly small) { ASSERT_VALID(this); ASSERT(m_nCount == 0); ASSERT(nHashSize > 0); // if had a hash table - get rid of it if (m_pHashTable != NULL) delete [] m_pHashTable; m_pHashTable = NULL; m_pHashTable = new CAssoc* [nHashSize]; memset(m_pHashTable, 0, sizeof(CAssoc*) * nHashSize); m_nHashTableSize = nHashSize; } void CMapStringToOb::RemoveAll() { ASSERT_VALID(this); if (m_pHashTable != NULL) { // destroy elements for (UINT nHash = 0; nHash < m_nHashTableSize; nHash++) { CAssoc* pAssoc; for (pAssoc = m_pHashTable[nHash]; pAssoc != NULL; pAssoc = pAssoc->pNext) { delete pAssoc->key; // free up string data } } // free hash table delete [] m_pHashTable; m_pHashTable = NULL; } m_nCount = 0; m_pFreeList = NULL; m_pBlocks->FreeDataChain(); m_pBlocks = NULL; } CMapStringToOb::~CMapStringToOb() { RemoveAll(); ASSERT(m_nCount == 0); } ///////////////////////////////////////////////////////////////////////////// // Assoc helpers // same as CList implementation except we store CAssoc's not CNode's // and CAssoc's are singly linked all the time CMapStringToOb::CAssoc* CMapStringToOb::NewAssoc() { if (m_pFreeList == NULL) { // add another block CPlex* newBlock = CPlex::Create(m_pBlocks, m_nBlockSize, sizeof(CMapStringToOb::CAssoc)); // chain them into free list CMapStringToOb::CAssoc* pAssoc = (CMapStringToOb::CAssoc*) newBlock->data(); // free in reverse order to make it easier to debug pAssoc += m_nBlockSize - 1; for (int i = m_nBlockSize-1; i >= 0; i--, pAssoc--) { pAssoc->pNext = m_pFreeList; m_pFreeList = pAssoc; } } ASSERT(m_pFreeList != NULL); // we must have something CMapStringToOb::CAssoc* pAssoc = m_pFreeList; m_pFreeList = m_pFreeList->pNext; m_nCount++; ASSERT(m_nCount > 0); // make sure we don't overflow // memcpy(&pAssoc->key, &afxEmptyString, sizeof(CString)); pAssoc->key = NULL; memset(&pAssoc->value, 0, sizeof(CObject*)); return pAssoc; } void CMapStringToOb::FreeAssoc(CMapStringToOb::CAssoc* pAssoc) { delete pAssoc->key; // free up string data pAssoc->key = NULL; pAssoc->pNext = m_pFreeList; m_pFreeList = pAssoc; m_nCount--; ASSERT(m_nCount >= 0); // make sure we don't underflow } CMapStringToOb::CAssoc* CMapStringToOb::GetAssocAt(const char* key, UINT_PTR& nHash) const // find association (or return NULL) { nHash = HashKey(key) % m_nHashTableSize; if (m_pHashTable == NULL) return NULL; // see if it exists CAssoc* pAssoc; for (pAssoc = m_pHashTable[nHash]; pAssoc != NULL; pAssoc = pAssoc->pNext) { if (!strcmp(pAssoc->key,key)) return pAssoc; } return NULL; } ///////////////////////////////////////////////////////////////////////////// BOOL CMapStringToOb::Lookup(const char* key, CObject*& rValue) const { ASSERT_VALID(this); UINT_PTR nHash; CAssoc* pAssoc = GetAssocAt(key, nHash); if (pAssoc == NULL) return FALSE; // not in map rValue = pAssoc->value; return TRUE; } CObject*& CMapStringToOb::operator[](const char* key) { ASSERT_VALID(this); UINT_PTR nHash; CAssoc* pAssoc; if ((pAssoc = GetAssocAt(key, nHash)) == NULL) { if (m_pHashTable == NULL) InitHashTable(m_nHashTableSize); // it doesn't exist, add a new Association pAssoc = NewAssoc(); pAssoc->nHashValue = nHash; const size_t nKeySize = strlen(key)+1; pAssoc->key = new char [nKeySize]; strcpy_s(pAssoc->key, nKeySize, key); // 'pAssoc->value' is a constructed object, nothing more // put into hash table pAssoc->pNext = m_pHashTable[nHash]; m_pHashTable[nHash] = pAssoc; } return pAssoc->value; // return new reference } BOOL CMapStringToOb::RemoveKey(const char* key) // remove key - return TRUE if removed { ASSERT_VALID(this); if (m_pHashTable == NULL) return FALSE; // nothing in the table CAssoc** ppAssocPrev; ppAssocPrev = &m_pHashTable[HashKey(key) % m_nHashTableSize]; CAssoc* pAssoc; for (pAssoc = *ppAssocPrev; pAssoc != NULL; pAssoc = pAssoc->pNext) { if (pAssoc->key == key) { // remove it *ppAssocPrev = pAssoc->pNext; // remove from list FreeAssoc(pAssoc); return TRUE; } ppAssocPrev = &pAssoc->pNext; } return FALSE; // not found } ///////////////////////////////////////////////////////////////////////////// // Iterating void CMapStringToOb::GetNextAssoc(RXPOSITION& rNextPosition, char *& rKey, CObject*& rValue) const { ASSERT_VALID(this); ASSERT(m_pHashTable != NULL); // never call on empty map CAssoc* pAssocRet = (CAssoc*)rNextPosition; ASSERT(pAssocRet != NULL); if (pAssocRet == (CAssoc*) BEFORE_START_RXPOSITION) { // find the first association for (UINT nBucket = 0; nBucket < m_nHashTableSize; nBucket++) if ((pAssocRet = m_pHashTable[nBucket]) != NULL) break; ASSERT(pAssocRet != NULL); // must find something } // find next association ASSERT(AfxIsValidAddress(pAssocRet, sizeof(CAssoc))); CAssoc* pAssocNext; if ((pAssocNext = pAssocRet->pNext) == NULL) { // go to next bucket for (UINT_PTR nBucket = pAssocRet->nHashValue + 1; nBucket < m_nHashTableSize; nBucket++) if ((pAssocNext = m_pHashTable[nBucket]) != NULL) break; } rNextPosition = (RXPOSITION) pAssocNext; // fill in return data rKey = pAssocRet->key; rValue = pAssocRet->value; } ///////////////////////////////////////////////////////////////////////////// // Diagnostics #ifdef _DEBUG void CMapStringToOb::Dump(CDumpContext& dc) const { ASSERT_VALID(this); #define MAKESTRING(x) #x AFX_DUMP1(dc, "A " MAKESTRING(CMapStringToOb) " with ", m_nCount); AFX_DUMP0(dc, " elements\n"); #undef MAKESTRING if (dc.GetDepth() > 0) { // Dump in format "[key] -> value" AFX_DUMP0(dc, "\n"); RXPOSITION pos = GetStartPosition(); CString key; CObject* val; while (pos != NULL) { GetNextAssoc(pos, key, val); AFX_DUMP1(dc, "\n\t[", key); AFX_DUMP1(dc, "] = ", val); } } } void CMapStringToOb::AssertValid() const { CObject::AssertValid(); ASSERT(m_nHashTableSize > 0); ASSERT(m_nCount == 0 || m_pHashTable != NULL); // non-empty map should have hash table } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // Collection support #ifdef AFX_COLL_SEG #pragma code_seg(AFX_COLL_SEG) #endif #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif #define new DEBUG_NEW CPlex* CPlex::Create(CPlex*& pHead, UINT nMax, UINT cbElement) { ASSERT(nMax > 0 && cbElement > 0); CPlex* p = (CPlex*) new BYTE[sizeof(CPlex) + nMax * cbElement]; // may throw exception p->nMax = nMax; p->nCur = 0; p->pNext = pHead; pHead = p; // change head (adds in reverse order for simplicity) return p; } void CPlex::FreeDataChain() // free this one and links { CPlex* p = this; while (p != NULL) { BYTE* bytes = (BYTE*) p; CPlex* pNextt = p->pNext; delete bytes; p = pNextt; } }
24.813077
96
0.561026
MadhukarMoogala
e0e8c70b6b068e99814f9bcec6f25ba7633c35e0
15,007
cpp
C++
source/GameLib/RaceMotionData.cpp
beetle2k/Metin2Client
114f492b71fcc90e8f5010c5b35b9fddb51639ca
[ "MIT" ]
13
2018-08-27T19:06:54.000Z
2021-11-12T05:44:04.000Z
source/GameLib/RaceMotionData.cpp
stempomzeskas/Metin2Client
114f492b71fcc90e8f5010c5b35b9fddb51639ca
[ "MIT" ]
null
null
null
source/GameLib/RaceMotionData.cpp
stempomzeskas/Metin2Client
114f492b71fcc90e8f5010c5b35b9fddb51639ca
[ "MIT" ]
15
2018-10-25T14:28:10.000Z
2022-03-25T14:05:09.000Z
#include "StdAfx.h" #include "../EffectLib/EffectManager.h" #include "FlyingObjectManager.h" #include "RaceMotionData.h" CDynamicPool<CRaceMotionData> CRaceMotionData::ms_kPool; void CRaceMotionData::CreateSystem(UINT uCapacity) { ms_kPool.Create(uCapacity); } void CRaceMotionData::DestroySystem() { ms_kPool.Clear(); } CRaceMotionData* CRaceMotionData::New() { return ms_kPool.Alloc(); } void CRaceMotionData::Delete(CRaceMotionData* pkData) { pkData->Destroy(); ms_kPool.Free(pkData); } void CRaceMotionData::SetName(UINT eName) { m_eName=eName; switch (m_eName) { case NAME_NONE: SetType(TYPE_NONE); break; case NAME_WAIT: case NAME_INTRO_WAIT: case NAME_STOP: SetType(TYPE_WAIT); break; case NAME_WALK: case NAME_RUN: SetType(TYPE_MOVE); break; case NAME_DAMAGE: case NAME_DAMAGE_BACK: SetType(TYPE_DAMAGE); break; case NAME_DAMAGE_FLYING: case NAME_DAMAGE_FLYING_BACK: SetType(TYPE_KNOCKDOWN); break; case NAME_STAND_UP: case NAME_STAND_UP_BACK: SetType(TYPE_STANDUP); break; case NAME_SPAWN: case NAME_CHANGE_WEAPON: case NAME_INTRO_SELECTED: case NAME_INTRO_NOT_SELECTED: case NAME_SPECIAL_1: case NAME_SPECIAL_2: case NAME_SPECIAL_3: case NAME_SPECIAL_4: case NAME_SPECIAL_5: case NAME_SPECIAL_6: case NAME_CLAP: case NAME_DANCE_1: case NAME_DANCE_2: case NAME_DANCE_3: case NAME_DANCE_4: case NAME_DANCE_5: case NAME_DANCE_6: case NAME_CONGRATULATION: case NAME_FORGIVE: case NAME_ANGRY: case NAME_ATTRACTIVE: case NAME_SAD: case NAME_SHY: case NAME_CHEERUP: case NAME_BANTER: case NAME_JOY: case NAME_CHEERS_1: case NAME_CHEERS_2: case NAME_KISS_WITH_WARRIOR: case NAME_KISS_WITH_ASSASSIN: case NAME_KISS_WITH_SURA: case NAME_KISS_WITH_SHAMAN: case NAME_FRENCH_KISS_WITH_WARRIOR: case NAME_FRENCH_KISS_WITH_ASSASSIN: case NAME_FRENCH_KISS_WITH_SURA: case NAME_FRENCH_KISS_WITH_SHAMAN: case NAME_SLAP_HIT_WITH_WARRIOR: case NAME_SLAP_HIT_WITH_ASSASSIN: case NAME_SLAP_HIT_WITH_SURA: case NAME_SLAP_HIT_WITH_SHAMAN: case NAME_SLAP_HURT_WITH_WARRIOR: case NAME_SLAP_HURT_WITH_ASSASSIN: case NAME_SLAP_HURT_WITH_SURA: case NAME_SLAP_HURT_WITH_SHAMAN: case NAME_DIG: SetType(TYPE_EVENT); break; case NAME_DEAD: case NAME_DEAD_BACK: SetType(TYPE_DIE); break; case NAME_NORMAL_ATTACK: SetType(TYPE_ATTACK); break; case NAME_COMBO_ATTACK_1: case NAME_COMBO_ATTACK_2: case NAME_COMBO_ATTACK_3: case NAME_COMBO_ATTACK_4: case NAME_COMBO_ATTACK_5: case NAME_COMBO_ATTACK_6: case NAME_COMBO_ATTACK_7: case NAME_COMBO_ATTACK_8: SetType(TYPE_COMBO); break; case NAME_FISHING_THROW: case NAME_FISHING_WAIT: case NAME_FISHING_REACT: case NAME_FISHING_CATCH: case NAME_FISHING_FAIL: case NAME_FISHING_STOP: SetType(TYPE_FISHING); break; default: if (eName>=NAME_SKILL && eName<=NAME_SKILL+SKILL_NUM) SetType(TYPE_SKILL); else TraceError("CRaceMotionData::SetName - UNKNOWN NAME %d", eName); break; } } void CRaceMotionData::SetType(UINT eType) { m_eType=eType; switch (m_eType) { case TYPE_ATTACK: case TYPE_COMBO: case TYPE_SKILL: m_isLock=TRUE; break; default: m_isLock=FALSE; break; } } UINT CRaceMotionData::GetType() const { return m_eType; } bool CRaceMotionData::IsLock() const { return m_isLock ? true : false; } int CRaceMotionData::GetLoopCount() const { return m_iLoopCount; } float CRaceMotionData::GetMotionDuration() { return m_fMotionDuration; } void CRaceMotionData::SetMotionDuration(float fDuration) { m_fMotionDuration = fDuration; } // Combo BOOL CRaceMotionData::IsComboInputTimeData() const { return m_isComboMotion; } float CRaceMotionData::GetComboInputStartTime() const { assert(m_isComboMotion); return m_ComboInputData.fInputStartTime; } float CRaceMotionData::GetNextComboTime() const { assert(m_isComboMotion); return m_ComboInputData.fNextComboTime; } float CRaceMotionData::GetComboInputEndTime() const { assert(m_isComboMotion); return m_ComboInputData.fInputEndTime; } // Attacking BOOL CRaceMotionData::isAttackingMotion() const { return m_isAttackingMotion; } const NRaceData::TMotionAttackData * CRaceMotionData::GetMotionAttackDataPointer() const { return & m_MotionAttackData; } const NRaceData::TMotionAttackData & CRaceMotionData::GetMotionAttackDataReference() const { assert(m_isAttackingMotion); return m_MotionAttackData; } BOOL CRaceMotionData::HasSplashMotionEvent() const { return m_hasSplashEvent; } // Skill BOOL CRaceMotionData::IsCancelEnableSkill() const { return m_bCancelEnableSkill; } // Loop BOOL CRaceMotionData::IsLoopMotion() const { return m_isLoopMotion; } float CRaceMotionData::GetLoopStartTime() const { return m_fLoopStartTime; } float CRaceMotionData::GetLoopEndTime() const { return m_fLoopEndTime; } // Motion Event Data DWORD CRaceMotionData::GetMotionEventDataCount() const { return m_MotionEventDataVector.size(); } BOOL CRaceMotionData::GetMotionEventDataPointer(BYTE byIndex, const CRaceMotionData::TMotionEventData ** c_ppData) const { if (byIndex >= m_MotionEventDataVector.size()) return FALSE; *c_ppData = m_MotionEventDataVector[byIndex]; return TRUE; } BOOL CRaceMotionData::GetMotionAttackingEventDataPointer(BYTE byIndex, const CRaceMotionData::TMotionAttackingEventData ** c_ppData) const { if (byIndex >= m_MotionEventDataVector.size()) return FALSE; const CRaceMotionData::TMotionEventData * pData = m_MotionEventDataVector[byIndex]; const CRaceMotionData::TMotionAttackingEventData * pAttackingEvent = (const CRaceMotionData::TMotionAttackingEventData *)pData; if (MOTION_EVENT_TYPE_SPECIAL_ATTACKING == pAttackingEvent->iType) return FALSE; *c_ppData = pAttackingEvent; return TRUE; } int CRaceMotionData::GetEventType(DWORD dwIndex) const { if (dwIndex >= m_MotionEventDataVector.size()) return MOTION_EVENT_TYPE_NONE; return m_MotionEventDataVector[dwIndex]->iType; } float CRaceMotionData::GetEventStartTime(DWORD dwIndex) const { if (dwIndex >= m_MotionEventDataVector.size()) return 0.0f; return m_MotionEventDataVector[dwIndex]->fStartingTime; } const NSound::TSoundInstanceVector * CRaceMotionData::GetSoundInstanceVectorPointer() const { return &m_SoundInstanceVector; } void CRaceMotionData::SetAccumulationPosition(const TPixelPosition & c_rPos) { m_accumulationPosition = c_rPos; m_isAccumulationMotion = TRUE; } bool CRaceMotionData::LoadMotionData(const char * c_szFileName) { const float c_fFrameTime = 1.0f / g_fGameFPS; CTextFileLoader* pkTextFileLoader=CTextFileLoader::Cache(c_szFileName); if (!pkTextFileLoader) return false; CTextFileLoader& rkTextFileLoader=*pkTextFileLoader; if (rkTextFileLoader.IsEmpty()) return false; rkTextFileLoader.SetTop(); if (!rkTextFileLoader.GetTokenString("motionfilename", &m_strMotionFileName)) return false; if (!rkTextFileLoader.GetTokenFloat("motionduration", &m_fMotionDuration)) return false; CTokenVector * pTokenVector; if (rkTextFileLoader.GetTokenVector("accumulation", &pTokenVector)) { if (pTokenVector->size() != 3) { TraceError("CRaceMotioNData::LoadMotionData : syntax error on accumulation, vector size %d", pTokenVector->size()); return false; } TPixelPosition pos(atof(pTokenVector->at(0).c_str()), atof(pTokenVector->at(1).c_str()), atof(pTokenVector->at(2).c_str())); SetAccumulationPosition(pos); } std::string strNodeName; for (DWORD i = 0; i < rkTextFileLoader.GetChildNodeCount(); ++i) { CTextFileLoader::CGotoChild GotoChild(&rkTextFileLoader, i); rkTextFileLoader.GetCurrentNodeName(&strNodeName); if (0 == strNodeName.compare("comboinputdata")) { m_isComboMotion = TRUE; if (!rkTextFileLoader.GetTokenFloat("preinputtime", &m_ComboInputData.fInputStartTime)) return false; if (!rkTextFileLoader.GetTokenFloat("directinputtime", &m_ComboInputData.fNextComboTime)) return false; if (!rkTextFileLoader.GetTokenFloat("inputlimittime", &m_ComboInputData.fInputEndTime)) return false; } else if (0 == strNodeName.compare("attackingdata")) { m_isAttackingMotion = TRUE; if (!NRaceData::LoadMotionAttackData(rkTextFileLoader, &m_MotionAttackData)) return false; } else if (0 == strNodeName.compare("loopdata")) { m_isLoopMotion = TRUE; if (!rkTextFileLoader.GetTokenInteger("motionloopcount", &m_iLoopCount)) { m_iLoopCount = -1; } if (!rkTextFileLoader.GetTokenInteger("loopcancelenable", &m_bCancelEnableSkill)) { m_bCancelEnableSkill = FALSE; } if (!rkTextFileLoader.GetTokenFloat("loopstarttime", &m_fLoopStartTime)) return false; if (!rkTextFileLoader.GetTokenFloat("loopendtime", &m_fLoopEndTime)) return false; } else if (0 == strNodeName.compare("motioneventdata")) { DWORD dwMotionEventDataCount; if (!rkTextFileLoader.GetTokenDoubleWord("motioneventdatacount", &dwMotionEventDataCount)) continue; stl_wipe(m_MotionEventDataVector); m_MotionEventDataVector.resize(dwMotionEventDataCount, NULL); for (DWORD j = 0; j < m_MotionEventDataVector.size(); ++j) { if (!rkTextFileLoader.SetChildNode("event", j)) return false; int iType; if (!rkTextFileLoader.GetTokenInteger("motioneventtype", &iType)) return false; TMotionEventData * pData = NULL; switch(iType) { case MOTION_EVENT_TYPE_FLY: pData = new TMotionFlyEventData; break; case MOTION_EVENT_TYPE_EFFECT: pData = new TMotionEffectEventData; break; case MOTION_EVENT_TYPE_SCREEN_WAVING: pData = new TScreenWavingEventData; break; case MOTION_EVENT_TYPE_SPECIAL_ATTACKING: pData = new TMotionAttackingEventData; m_hasSplashEvent = TRUE; break; case MOTION_EVENT_TYPE_SOUND: pData = new TMotionSoundEventData; break; case MOTION_EVENT_TYPE_CHARACTER_SHOW: pData = new TMotionCharacterShowEventData; break; case MOTION_EVENT_TYPE_CHARACTER_HIDE: pData = new TMotionCharacterHideEventData; break; case MOTION_EVENT_TYPE_WARP: pData = new TMotionWarpEventData; break; case MOTION_EVENT_TYPE_EFFECT_TO_TARGET: pData = new TMotionEffectToTargetEventData; break; default: assert(!" CRaceMotionData::LoadMotionData - Strange Event Type"); return false; break; } m_MotionEventDataVector[j] = pData; m_MotionEventDataVector[j]->Load(rkTextFileLoader); m_MotionEventDataVector[j]->iType = iType; if (!rkTextFileLoader.GetTokenFloat("startingtime", &m_MotionEventDataVector[j]->fStartingTime)) return false; m_MotionEventDataVector[j]->dwFrame = (m_MotionEventDataVector[j]->fStartingTime / c_fFrameTime); rkTextFileLoader.SetParentNode(); } } } std::string strSoundFileNameTemp=c_szFileName; strSoundFileNameTemp = CFileNameHelper::NoExtension(strSoundFileNameTemp); strSoundFileNameTemp+= ".mss"; if (strSoundFileNameTemp.length() > 13) { const char * c_szHeader = &strSoundFileNameTemp[13]; m_strSoundScriptDataFileName = "sound/"; m_strSoundScriptDataFileName += c_szHeader; LoadSoundScriptData(m_strSoundScriptDataFileName.c_str()); } return true; } #ifdef WORLD_EDITOR bool CRaceMotionData::SaveMotionData(const char * c_szFileName) { FILE * File; SetFileAttributes(c_szFileName, FILE_ATTRIBUTE_NORMAL); File = fopen(c_szFileName, "w"); if (!File) { TraceError("CRaceMotionData::SaveMotionData : cannot open file for writing (filename: %s)", c_szFileName); return false; } fprintf(File, "ScriptType MotionData\n"); fprintf(File, "\n"); fprintf(File, "MotionFileName \"%s\"\n", m_strMotionFileName.c_str()); fprintf(File, "MotionDuration %f\n", m_fMotionDuration); if (m_isAccumulationMotion) fprintf(File, "Accumulation %.2f\t%.2f\t%.2f\n", m_accumulationPosition.x, m_accumulationPosition.y, m_accumulationPosition.z); fprintf(File, "\n"); if (m_isComboMotion) { fprintf(File, "Group ComboInputData\n"); fprintf(File, "{\n"); fprintf(File, " PreInputTime %f\n", m_ComboInputData.fInputStartTime); fprintf(File, " DirectInputTime %f\n", m_ComboInputData.fNextComboTime); fprintf(File, " InputLimitTime %f\n", m_ComboInputData.fInputEndTime); fprintf(File, "}\n"); fprintf(File, "\n"); } if (m_isAttackingMotion) { fprintf(File, "Group AttackingData\n"); fprintf(File, "{\n"); NRaceData::SaveMotionAttackData(File, 1, m_MotionAttackData); fprintf(File, "}\n"); fprintf(File, "\n"); } if (m_isLoopMotion) { fprintf(File, "Group LoopData\n"); fprintf(File, "{\n"); fprintf(File, " MotionLoopCount %d\n", m_iLoopCount); fprintf(File, " LoopCancelEnable %d\n", m_bCancelEnableSkill); fprintf(File, " LoopStartTime %f\n", m_fLoopStartTime); fprintf(File, " LoopEndTime %f\n", m_fLoopEndTime); fprintf(File, "}\n"); fprintf(File, "\n"); } if (!m_MotionEventDataVector.empty()) { fprintf(File, "Group MotionEventData\n"); fprintf(File, "{\n"); fprintf(File, " MotionEventDataCount %d\n", m_MotionEventDataVector.size()); for (DWORD j = 0; j < m_MotionEventDataVector.size(); ++j) { TMotionEventData * c_pData = m_MotionEventDataVector[j]; fprintf(File, " Group Event%02d\n", j); fprintf(File, " {\n"); fprintf(File, " MotionEventType %d\n", c_pData->iType); fprintf(File, " StartingTime %f\n", c_pData->fStartingTime); c_pData->Save(File, 2); fprintf(File, " }\n"); } fprintf(File, "}\n"); } fclose(File); return true; } #endif bool CRaceMotionData::LoadSoundScriptData(const char * c_szFileName) { NSound::TSoundDataVector SoundDataVector; if (!NSound::LoadSoundInformationPiece(c_szFileName, SoundDataVector)) { return false; } NSound::DataToInstance(SoundDataVector, &m_SoundInstanceVector); return true; } const char * CRaceMotionData::GetMotionFileName() const { return m_strMotionFileName.c_str(); } const char * CRaceMotionData::GetSoundScriptFileName() const { return m_strSoundScriptDataFileName.c_str(); } void CRaceMotionData::Initialize() { m_iLoopCount = 0; m_fMotionDuration = 0.0f; m_accumulationPosition.x = 0.0f; m_accumulationPosition.y = 0.0f; m_accumulationPosition.z = 0.0f; m_fLoopStartTime = 0.0f; m_fLoopEndTime = 0.0f; m_isAccumulationMotion = FALSE; m_isComboMotion = FALSE; m_isLoopMotion = FALSE; m_isAttackingMotion = FALSE; m_bCancelEnableSkill = FALSE; m_hasSplashEvent = FALSE; m_isLock = FALSE; m_eType=TYPE_NONE; m_eName=NAME_NONE; m_MotionEventDataVector.clear(); m_SoundInstanceVector.clear(); } void CRaceMotionData::Destroy() { stl_wipe(m_MotionEventDataVector); Initialize(); } CRaceMotionData::CRaceMotionData() { Initialize(); } CRaceMotionData::~CRaceMotionData() { Destroy(); }
24.283172
139
0.738589
beetle2k
e0ecddff9542367d0ac444c99ed054e6e5a29875
1,199
hpp
C++
include/asioext/detail/chrono.hpp
zweistein-frm2/asio-extensions
bafea77c48d674930405cb7f93bdfe65539abc39
[ "BSL-1.0" ]
17
2018-04-13T00:38:55.000Z
2022-01-21T08:38:36.000Z
include/asioext/detail/chrono.hpp
zweistein-frm2/asio-extensions
bafea77c48d674930405cb7f93bdfe65539abc39
[ "BSL-1.0" ]
4
2017-03-16T03:34:38.000Z
2020-05-08T00:05:51.000Z
include/asioext/detail/chrono.hpp
zweistein-frm2/asio-extensions
bafea77c48d674930405cb7f93bdfe65539abc39
[ "BSL-1.0" ]
5
2017-09-06T15:56:04.000Z
2021-09-14T07:38:02.000Z
/// @copyright Copyright (c) 2017 Tim Niederhausen ([email protected]) /// 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 ASIOEXT_DETAIL_CHRONO_HPP #define ASIOEXT_DETAIL_CHRONO_HPP #include "asioext/detail/config.hpp" #if ASIOEXT_HAS_PRAGMA_ONCE # pragma once #endif #include "asioext/chrono.hpp" #include "asioext/detail/cstdint.hpp" #include <ctime> ASIOEXT_NS_BEGIN namespace detail { template <class RepIn, class PeriodIn, class RepOut, class PeriodOut> ASIOEXT_CONSTEXPR14 bool safe_duration_cast( const chrono::duration<RepIn, PeriodIn>& in, chrono::duration<RepOut, PeriodOut>& out) ASIOEXT_NOEXCEPT; template <class Duration, class FirstDuration, class SecondDuration> bool decompose_time(const Duration& in, FirstDuration& first, SecondDuration& second) ASIOEXT_NOEXCEPT; template <class Duration, class FirstDuration, class SecondDuration> bool compose_time(const FirstDuration& first, const SecondDuration& second, Duration& out) ASIOEXT_NOEXCEPT; } ASIOEXT_NS_END #include "asioext/detail/impl/chrono.hpp" #endif
26.644444
75
0.765638
zweistein-frm2
e0ee282577ff44a28cbc0d6dc40e72db7788f70e
2,862
cpp
C++
ClasificadoresSensor/GeneradorDatosEntrenamiento/main.cpp
mrcportillo/Guda
12be3c7d80d25fb041ac2a61ecf8b3f9be43eb23
[ "MIT" ]
null
null
null
ClasificadoresSensor/GeneradorDatosEntrenamiento/main.cpp
mrcportillo/Guda
12be3c7d80d25fb041ac2a61ecf8b3f9be43eb23
[ "MIT" ]
null
null
null
ClasificadoresSensor/GeneradorDatosEntrenamiento/main.cpp
mrcportillo/Guda
12be3c7d80d25fb041ac2a61ecf8b3f9be43eb23
[ "MIT" ]
null
null
null
// prueba6.cpp : Defines the entry point for the console application. // // practica6.c - creacion y visualizacion de una imagen usando OpenCV // // Robotica y Vision por Computador #include "cv.h" // incluye las definiciones de OpenCV #include "cvaux.h" // Stuff. #include "highgui.h" // incluye highGUI. Necesario para crear ventanas de visualizacion #include <stdio.h> #include <math.h> #include <stdlib.h> #include <iostream> #include <fstream> using namespace std; int dato1 = 5; #define PI 3.14159265 char c ; int dato; int x,y; float xx1,yy1; float dx=(230-161); float dy=(302-161); float ro=0.0; float alfa=atan2(dx,dy)*180/PI; float delta=0; bool detecta1=false; bool detecta2=false; CvCapture* capture = NULL; IplImage *cuadro; IplImage *imagen; int main(void) { CvScalar s; CvScalar color = CV_RGB(0,120,0); char texto[100]; int vector[180]; float temp=0.0; int conta=0; CvFont font; cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 0, 1, CV_AA); cvNamedWindow( "Transito", CV_WINDOW_AUTOSIZE ); capture = cvCaptureFromAVI( "/home/mrc/ProyectosQt/Guda/ClasificadoresSensor/GeneradorDatosEntrenamiento/ca1.avi" ); dato= (int) cvGetCaptureProperty(capture,CV_CAP_PROP_FRAME_COUNT); ofstream fs("/home/mrc/ProyectosQt/Guda/ClasificadoresSensor/GeneradorDatosEntrenamiento/samples.txt"); while(1) { imagen = cvQueryFrame(capture); cuadro = cvCreateImage( cvGetSize(imagen), IPL_DEPTH_8U, 3 ); cvSmooth( imagen, cuadro, CV_GAUSSIAN, 5, 5 ); sprintf( texto, "%d %d", x,y); cvPutText( cuadro, texto, cvPoint(x,y),&font,cvScalar(0,255,0)); cvCircle(cuadro,cvPoint(x,y),20,cvScalar(255,255,255),1,8); for(delta=0.0;delta<180;delta++) { vector[(int)delta]=0.0; } temp=100; for(delta=-100;delta<80;delta=delta+15) { for(ro=40;ro<120;ro=ro+7) { xx1=230+cos(delta*PI/180)*ro/sin(alfa*PI/180); yy1=302+sin(delta*PI/180)*ro/cos(alfa*PI/180); cvCircle(cuadro,cvPoint((int)xx1,(int)yy1),4,cvScalar(255,255,255),1,8); cvFloodFill( cuadro, cvPoint((int)xx1,(int)yy1), color, cvScalarAll(5.0), cvScalarAll(5.0), NULL, 4, NULL ); s=cvGet2D(cuadro,(int)yy1-1,(int)xx1-1); if((int)s.val[1]!=120) break; } vector[(int)(temp+delta)]=(int)ro; } cvShowImage( "Transito", cuadro); if( !cuadro ) break; c= cvWaitKey(0); if(c == 27) { fs.close(); break; } else if(c != ' '){ for(conta=0;conta<180;conta=conta+15) { fs << vector[conta] <<" "; } fs << c <<endl; } } cvReleaseCapture( &capture ); cvDestroyWindow( "Ejemplo0" ); return 0; }
29.8125
124
0.605521
mrcportillo
e0f173909783178ef17e264ac572d9f5f83cc624
25,081
cpp
C++
examples/0400-stl-template-classes/cib/__zz_cib_bidirectional_iterator.h.cpp
satya-das/cib
369333ea58b0530b8789a340e21096ba7d159d0e
[ "MIT" ]
30
2018-03-05T17:35:29.000Z
2022-03-17T18:59:34.000Z
examples/0400-stl-template-classes/cib/__zz_cib_bidirectional_iterator.h.cpp
satya-das/cib
369333ea58b0530b8789a340e21096ba7d159d0e
[ "MIT" ]
2
2016-05-26T04:47:13.000Z
2019-02-15T05:17:43.000Z
examples/0400-stl-template-classes/cib/__zz_cib_bidirectional_iterator.h.cpp
satya-das/cib
369333ea58b0530b8789a340e21096ba7d159d0e
[ "MIT" ]
5
2019-02-15T05:09:22.000Z
2021-04-14T12:10:16.000Z
#include "C.h" #include "__zz_cib_stl-helpers/__zz_cib_bidirectional_iterator.h" #include "__zz_cib_Example-class-down-cast.h" #include "__zz_cib_Example-delegate-helper.h" #include "__zz_cib_Example-generic.h" #include "__zz_cib_Example-ids.h" #include "__zz_cib_Example-type-converters.h" #include "__zz_cib_Example-mtable-helper.h" #include "__zz_cib_Example-proxy-mgr.h" namespace __zz_cib_ { using namespace ::__zz_cib_stl_helpers; template <> struct __zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >> : public ::__zz_cib_stl_helpers::bidirectional_iterator<::C const > { using __zz_cib_Delegatee = __zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >>; using __zz_cib_AbiType = __zz_cib_Delegatee*; using ::__zz_cib_stl_helpers::bidirectional_iterator<::C const >::bidirectional_iterator; static __zz_cib_AbiType __zz_cib_decl __zz_cib_Copy_0(const __zz_cib_Delegatee* __zz_cib_obj) { return new __zz_cib_Delegatee(*__zz_cib_obj); } static void __zz_cib_decl __zz_cib_Delete_1(__zz_cib_Delegatee* __zz_cib_obj) { delete __zz_cib_obj; } static __zz_cib_AbiType __zz_cib_decl __zz_cib_New_2() { return new __zz_cib_Delegatee(); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >::reference> __zz_cib_decl __zz_cib_OperatorMul_3(const __zz_cib_Delegatee* __zz_cib_obj) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >::reference>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C const >::operator*() ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >::pointer> __zz_cib_decl __zz_cib_OperatorArrow_4(const __zz_cib_Delegatee* __zz_cib_obj) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >::pointer>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C const >::operator->() ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >&> __zz_cib_decl __zz_cib_OperatorInc_5(__zz_cib_Delegatee* __zz_cib_obj) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >&>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C const >::operator++() ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >> __zz_cib_decl __zz_cib_OperatorInc_6(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<int> __zz_cib_param0) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C const >::operator++( __zz_cib_::__zz_cib_FromAbiType<int>(__zz_cib_param0) ) ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >&> __zz_cib_decl __zz_cib_OperatorDec_7(__zz_cib_Delegatee* __zz_cib_obj) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >&>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C const >::operator--() ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >> __zz_cib_decl __zz_cib_OperatorDec_8(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<int> __zz_cib_param0) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C const >::operator--( __zz_cib_::__zz_cib_FromAbiType<int>(__zz_cib_param0) ) ); } static __zz_cib_AbiType_t<bool> __zz_cib_decl __zz_cib_OperatorCmpEq_9(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::__zz_cib_stl_helpers::bidirectional_iterator<::C const >&> rhs) { return __zz_cib_ToAbiType<bool>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C const >::operator==( __zz_cib_::__zz_cib_FromAbiType<const ::__zz_cib_stl_helpers::bidirectional_iterator<::C const >&>(rhs) ) ); } static __zz_cib_AbiType_t<bool> __zz_cib_decl __zz_cib_OperatorNotEq_10(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::__zz_cib_stl_helpers::bidirectional_iterator<::C const >&> rhs) { return __zz_cib_ToAbiType<bool>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C const >::operator!=( __zz_cib_::__zz_cib_FromAbiType<const ::__zz_cib_stl_helpers::bidirectional_iterator<::C const >&>(rhs) ) ); } }; } namespace __zz_cib_ { namespace __zz_cib_Class256 { using namespace ::__zz_cib_stl_helpers; namespace __zz_cib_Class269 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable() { static const __zz_cib_MTableEntry methodArray[] = { reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >>::__zz_cib_Copy_0), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >>::__zz_cib_Delete_1), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >>::__zz_cib_New_2), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >>::__zz_cib_OperatorMul_3), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >>::__zz_cib_OperatorArrow_4), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >>::__zz_cib_OperatorInc_5), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >>::__zz_cib_OperatorInc_6), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >>::__zz_cib_OperatorDec_7), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >>::__zz_cib_OperatorDec_8), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >>::__zz_cib_OperatorCmpEq_9), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C const >>::__zz_cib_OperatorNotEq_10) }; static const __zz_cib_MethodTable methodTable = { methodArray, 11 }; return &methodTable; } }}} namespace __zz_cib_ { using namespace ::__zz_cib_stl_helpers; template <> struct __zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >> : public ::__zz_cib_stl_helpers::bidirectional_iterator<::C* const > { using __zz_cib_Delegatee = __zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >>; using __zz_cib_AbiType = __zz_cib_Delegatee*; using ::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >::bidirectional_iterator; static __zz_cib_AbiType __zz_cib_decl __zz_cib_Copy_0(const __zz_cib_Delegatee* __zz_cib_obj) { return new __zz_cib_Delegatee(*__zz_cib_obj); } static void __zz_cib_decl __zz_cib_Delete_1(__zz_cib_Delegatee* __zz_cib_obj) { delete __zz_cib_obj; } static __zz_cib_AbiType __zz_cib_decl __zz_cib_New_2() { return new __zz_cib_Delegatee(); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >::reference> __zz_cib_decl __zz_cib_OperatorMul_3(const __zz_cib_Delegatee* __zz_cib_obj) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >::reference>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >::operator*() ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >::pointer> __zz_cib_decl __zz_cib_OperatorArrow_4(const __zz_cib_Delegatee* __zz_cib_obj) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >::pointer>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >::operator->() ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >&> __zz_cib_decl __zz_cib_OperatorInc_5(__zz_cib_Delegatee* __zz_cib_obj) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >&>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >::operator++() ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >> __zz_cib_decl __zz_cib_OperatorInc_6(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<int> __zz_cib_param0) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >::operator++( __zz_cib_::__zz_cib_FromAbiType<int>(__zz_cib_param0) ) ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >&> __zz_cib_decl __zz_cib_OperatorDec_7(__zz_cib_Delegatee* __zz_cib_obj) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >&>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >::operator--() ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >> __zz_cib_decl __zz_cib_OperatorDec_8(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<int> __zz_cib_param0) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >::operator--( __zz_cib_::__zz_cib_FromAbiType<int>(__zz_cib_param0) ) ); } static __zz_cib_AbiType_t<bool> __zz_cib_decl __zz_cib_OperatorCmpEq_9(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >&> rhs) { return __zz_cib_ToAbiType<bool>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >::operator==( __zz_cib_::__zz_cib_FromAbiType<const ::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >&>(rhs) ) ); } static __zz_cib_AbiType_t<bool> __zz_cib_decl __zz_cib_OperatorNotEq_10(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >&> rhs) { return __zz_cib_ToAbiType<bool>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >::operator!=( __zz_cib_::__zz_cib_FromAbiType<const ::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >&>(rhs) ) ); } }; } namespace __zz_cib_ { namespace __zz_cib_Class256 { using namespace ::__zz_cib_stl_helpers; namespace __zz_cib_Class274 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable() { static const __zz_cib_MTableEntry methodArray[] = { reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >>::__zz_cib_Copy_0), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >>::__zz_cib_Delete_1), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >>::__zz_cib_New_2), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >>::__zz_cib_OperatorMul_3), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >>::__zz_cib_OperatorArrow_4), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >>::__zz_cib_OperatorInc_5), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >>::__zz_cib_OperatorInc_6), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >>::__zz_cib_OperatorDec_7), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >>::__zz_cib_OperatorDec_8), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >>::__zz_cib_OperatorCmpEq_9), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C* const >>::__zz_cib_OperatorNotEq_10) }; static const __zz_cib_MethodTable methodTable = { methodArray, 11 }; return &methodTable; } }}} namespace __zz_cib_ { using namespace ::__zz_cib_stl_helpers; template <> struct __zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>> : public ::__zz_cib_stl_helpers::bidirectional_iterator<::C*> { using __zz_cib_Delegatee = __zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>>; using __zz_cib_AbiType = __zz_cib_Delegatee*; using ::__zz_cib_stl_helpers::bidirectional_iterator<::C*>::bidirectional_iterator; static __zz_cib_AbiType __zz_cib_decl __zz_cib_Copy_0(const __zz_cib_Delegatee* __zz_cib_obj) { return new __zz_cib_Delegatee(*__zz_cib_obj); } static void __zz_cib_decl __zz_cib_Delete_1(__zz_cib_Delegatee* __zz_cib_obj) { delete __zz_cib_obj; } static __zz_cib_AbiType __zz_cib_decl __zz_cib_New_2() { return new __zz_cib_Delegatee(); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>::reference> __zz_cib_decl __zz_cib_OperatorMul_3(const __zz_cib_Delegatee* __zz_cib_obj) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>::reference>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C*>::operator*() ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>::pointer> __zz_cib_decl __zz_cib_OperatorArrow_4(const __zz_cib_Delegatee* __zz_cib_obj) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>::pointer>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C*>::operator->() ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>&> __zz_cib_decl __zz_cib_OperatorInc_5(__zz_cib_Delegatee* __zz_cib_obj) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>&>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C*>::operator++() ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>> __zz_cib_decl __zz_cib_OperatorInc_6(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<int> __zz_cib_param0) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C*>::operator++( __zz_cib_::__zz_cib_FromAbiType<int>(__zz_cib_param0) ) ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>&> __zz_cib_decl __zz_cib_OperatorDec_7(__zz_cib_Delegatee* __zz_cib_obj) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>&>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C*>::operator--() ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>> __zz_cib_decl __zz_cib_OperatorDec_8(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<int> __zz_cib_param0) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C*>::operator--( __zz_cib_::__zz_cib_FromAbiType<int>(__zz_cib_param0) ) ); } static __zz_cib_AbiType_t<bool> __zz_cib_decl __zz_cib_OperatorCmpEq_9(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::__zz_cib_stl_helpers::bidirectional_iterator<::C*>&> rhs) { return __zz_cib_ToAbiType<bool>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C*>::operator==( __zz_cib_::__zz_cib_FromAbiType<const ::__zz_cib_stl_helpers::bidirectional_iterator<::C*>&>(rhs) ) ); } static __zz_cib_AbiType_t<bool> __zz_cib_decl __zz_cib_OperatorNotEq_10(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::__zz_cib_stl_helpers::bidirectional_iterator<::C*>&> rhs) { return __zz_cib_ToAbiType<bool>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C*>::operator!=( __zz_cib_::__zz_cib_FromAbiType<const ::__zz_cib_stl_helpers::bidirectional_iterator<::C*>&>(rhs) ) ); } }; } namespace __zz_cib_ { namespace __zz_cib_Class256 { using namespace ::__zz_cib_stl_helpers; namespace __zz_cib_Class273 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable() { static const __zz_cib_MTableEntry methodArray[] = { reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>>::__zz_cib_Copy_0), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>>::__zz_cib_Delete_1), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>>::__zz_cib_New_2), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>>::__zz_cib_OperatorMul_3), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>>::__zz_cib_OperatorArrow_4), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>>::__zz_cib_OperatorInc_5), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>>::__zz_cib_OperatorInc_6), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>>::__zz_cib_OperatorDec_7), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>>::__zz_cib_OperatorDec_8), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>>::__zz_cib_OperatorCmpEq_9), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C*>>::__zz_cib_OperatorNotEq_10) }; static const __zz_cib_MethodTable methodTable = { methodArray, 11 }; return &methodTable; } }}} namespace __zz_cib_ { using namespace ::__zz_cib_stl_helpers; template <> struct __zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C>> : public ::__zz_cib_stl_helpers::bidirectional_iterator<::C> { using __zz_cib_Delegatee = __zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C>>; using __zz_cib_AbiType = __zz_cib_Delegatee*; using ::__zz_cib_stl_helpers::bidirectional_iterator<::C>::bidirectional_iterator; static __zz_cib_AbiType __zz_cib_decl __zz_cib_Copy_0(const __zz_cib_Delegatee* __zz_cib_obj) { return new __zz_cib_Delegatee(*__zz_cib_obj); } static void __zz_cib_decl __zz_cib_Delete_1(__zz_cib_Delegatee* __zz_cib_obj) { delete __zz_cib_obj; } static __zz_cib_AbiType __zz_cib_decl __zz_cib_New_2() { return new __zz_cib_Delegatee(); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C>::reference> __zz_cib_decl __zz_cib_OperatorMul_3(const __zz_cib_Delegatee* __zz_cib_obj) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C>::reference>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C>::operator*() ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C>::pointer> __zz_cib_decl __zz_cib_OperatorArrow_4(const __zz_cib_Delegatee* __zz_cib_obj) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C>::pointer>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C>::operator->() ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C>&> __zz_cib_decl __zz_cib_OperatorInc_5(__zz_cib_Delegatee* __zz_cib_obj) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C>&>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C>::operator++() ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C>> __zz_cib_decl __zz_cib_OperatorInc_6(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<int> __zz_cib_param0) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C>>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C>::operator++( __zz_cib_::__zz_cib_FromAbiType<int>(__zz_cib_param0) ) ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C>&> __zz_cib_decl __zz_cib_OperatorDec_7(__zz_cib_Delegatee* __zz_cib_obj) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C>&>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C>::operator--() ); } static __zz_cib_AbiType_t<::__zz_cib_stl_helpers::bidirectional_iterator<::C>> __zz_cib_decl __zz_cib_OperatorDec_8(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<int> __zz_cib_param0) { return __zz_cib_ToAbiType<::__zz_cib_stl_helpers::bidirectional_iterator<::C>>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C>::operator--( __zz_cib_::__zz_cib_FromAbiType<int>(__zz_cib_param0) ) ); } static __zz_cib_AbiType_t<bool> __zz_cib_decl __zz_cib_OperatorCmpEq_9(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::__zz_cib_stl_helpers::bidirectional_iterator<::C>&> rhs) { return __zz_cib_ToAbiType<bool>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C>::operator==( __zz_cib_::__zz_cib_FromAbiType<const ::__zz_cib_stl_helpers::bidirectional_iterator<::C>&>(rhs) ) ); } static __zz_cib_AbiType_t<bool> __zz_cib_decl __zz_cib_OperatorNotEq_10(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::__zz_cib_stl_helpers::bidirectional_iterator<::C>&> rhs) { return __zz_cib_ToAbiType<bool>( __zz_cib_obj->::__zz_cib_stl_helpers::bidirectional_iterator<::C>::operator!=( __zz_cib_::__zz_cib_FromAbiType<const ::__zz_cib_stl_helpers::bidirectional_iterator<::C>&>(rhs) ) ); } }; } namespace __zz_cib_ { namespace __zz_cib_Class256 { using namespace ::__zz_cib_stl_helpers; namespace __zz_cib_Class268 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable() { static const __zz_cib_MTableEntry methodArray[] = { reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C>>::__zz_cib_Copy_0), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C>>::__zz_cib_Delete_1), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C>>::__zz_cib_New_2), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C>>::__zz_cib_OperatorMul_3), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C>>::__zz_cib_OperatorArrow_4), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C>>::__zz_cib_OperatorInc_5), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C>>::__zz_cib_OperatorInc_6), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C>>::__zz_cib_OperatorDec_7), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C>>::__zz_cib_OperatorDec_8), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C>>::__zz_cib_OperatorCmpEq_9), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::__zz_cib_stl_helpers::bidirectional_iterator<::C>>::__zz_cib_OperatorNotEq_10) }; static const __zz_cib_MethodTable methodTable = { methodArray, 11 }; return &methodTable; } }}}
66.704787
202
0.79008
satya-das
e0f298ee5f5c25ba3cb97af084526bc0d2ea8ada
950
cpp
C++
Trees/diameter_of_BT.cpp
jatin-code21/DSA-CP-
e29e1fd7ab4860a4eb46d11f6a42a285be1216cb
[ "MIT" ]
5
2021-12-28T01:48:46.000Z
2022-02-18T05:57:10.000Z
Trees/diameter_of_BT.cpp
jatin-code21/DSA-CP-
e29e1fd7ab4860a4eb46d11f6a42a285be1216cb
[ "MIT" ]
null
null
null
Trees/diameter_of_BT.cpp
jatin-code21/DSA-CP-
e29e1fd7ab4860a4eb46d11f6a42a285be1216cb
[ "MIT" ]
null
null
null
// Diameter is the longest path betweeen any 2 nodes; // It is not necessary that it will pass through root; #include <bits/stdc++.h> using namespace std; class TreeNode { public: int data; TreeNode *left,*right; TreeNode(int val) { data = val; left = right = NULL; } }; int height(TreeNode *root, int &diameter) { if (root == NULL) return 0; int lh = height(root->left, diameter); int rh = height(root->right, diameter); diameter = max(diameter, lh + rh); return max(lh, rh) + 1; } int diameterOfBt(TreeNode *root) { int diameter = 0; height(root, diameter); return diameter; } int main() { TreeNode *root = new TreeNode(5); root->left = new TreeNode(8); root->right = new TreeNode(3); root->left->left = new TreeNode(21); root->left->right = new TreeNode(15); root->right->right = new TreeNode(23); cout << diameterOfBt(root); } // This is the optimized way of finding the diameter with Time Complexity -> O(N);
18.627451
82
0.668421
jatin-code21
e0f29da9409cec332f9026ae61f9640b6f1e19e2
234
cpp
C++
src/dbc.cpp
SoultatosStefanos/dbc
aa9c787cd383c8b8f110f779ad0978e4512c7811
[ "MIT" ]
1
2021-09-08T11:41:58.000Z
2021-09-08T11:41:58.000Z
src/dbc.cpp
SoultatosStefanos/dbc
aa9c787cd383c8b8f110f779ad0978e4512c7811
[ "MIT" ]
null
null
null
src/dbc.cpp
SoultatosStefanos/dbc
aa9c787cd383c8b8f110f779ad0978e4512c7811
[ "MIT" ]
null
null
null
/** * @file dbc.cpp * @author Soultatos Stefanos ([email protected]) * @brief Includes the dbc header for linking purposes. * @version 3.0 * @date 2021-10-29 * * @copyright Copyright (c) 2021 * */ #include "dbc/dbc.hpp"
21.272727
55
0.67094
SoultatosStefanos
804108c1d686266a438f95572009bc04f2b7682f
1,062
cpp
C++
src/problems/51-100/91/problem91.cpp
abeccaro/project-euler
c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3
[ "MIT" ]
1
2019-12-25T10:17:15.000Z
2019-12-25T10:17:15.000Z
src/problems/51-100/91/problem91.cpp
abeccaro/project-euler
c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3
[ "MIT" ]
null
null
null
src/problems/51-100/91/problem91.cpp
abeccaro/project-euler
c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3
[ "MIT" ]
null
null
null
// // Created by Alex Beccaro on 28/02/18. // #include "problem91.hpp" namespace problems { bool problem91::has_right_angle(uint32_t x1, uint32_t y1, uint32_t x2, uint32_t y2) { // check right angle in origin if (y2 == 0 && x1 == 0) return true; // cross product int dx = x1 - x2; int dy = y1 - y2; if (dx * x2 + dy * y2 == 0) return true; if (dx * x1 + dy * y1 == 0) return true; return false; } uint32_t problem91::solve(uint32_t max_x, uint32_t max_y) { uint32_t result = 0; for (uint32_t x1 = 0; x1 <= max_x; x1++) for (uint32_t y1 = 0; y1 <= max_y; y1++) { if (x1 == 0 && y1 == 0) continue; for (uint32_t x2 = x1; x2 <= max_x; x2++) for (uint32_t y2 = x2 == x1 ? y1 + 1 : 0; y2 <= max_y; y2++) if (has_right_angle(x1, y1, x2, y2)) ++result; } return result; } }
26.55
89
0.450094
abeccaro
8044935b81414a4f2a0cd031ed2cfb9fa25a8729
2,182
cpp
C++
tests/atomic_test.cpp
xiyou-linuxer/demo
e1176dde72be50732e39e289d91a0c14ece964d7
[ "MIT" ]
7
2019-04-26T03:49:55.000Z
2019-04-27T10:03:00.000Z
tests/atomic_test.cpp
xiyou-linuxer/demo
e1176dde72be50732e39e289d91a0c14ece964d7
[ "MIT" ]
null
null
null
tests/atomic_test.cpp
xiyou-linuxer/demo
e1176dde72be50732e39e289d91a0c14ece964d7
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "atomic.hpp" using namespace Demo; TEST(TEST_ATOMIC_INT32, ONLY_TEST) { AtomicInt32 refCount; ASSERT_EQ(0, refCount.get()); ASSERT_EQ(1, refCount.incrementAndGet()); ASSERT_EQ(2, refCount.incrementAndGet()); ASSERT_EQ(3, refCount.incrementAndGet()); ASSERT_EQ(2, refCount.decrementAndGet()); ASSERT_EQ(1, refCount.decrementAndGet()); ASSERT_EQ(0, refCount.decrementAndGet()); ASSERT_EQ(0, refCount.getAndSet(10)); ASSERT_EQ(10, refCount.get()); ASSERT_EQ(10, refCount.getAndSet(0)); ASSERT_EQ(0, refCount.get()); ASSERT_EQ(0, refCount.getAndAdd(5)); ASSERT_EQ(5, refCount.get()); ASSERT_EQ(5, refCount.getAndAdd(-5)); ASSERT_EQ(0, refCount.get()); ASSERT_EQ(5, refCount.addAndGet(5)); ASSERT_EQ(0, refCount.addAndGet(-5)); refCount.add(5); ASSERT_EQ(5, refCount.get()); refCount.add(-5); ASSERT_EQ(0, refCount.get()); refCount.increment(); ASSERT_EQ(1, refCount.get()); refCount.decrement(); ASSERT_EQ(0, refCount.get()); } TEST(TEST_ATOMIC_INT64, ONLY_TEST) { AtomicInt64 refCount; ASSERT_EQ(0, refCount.get()); ASSERT_EQ(1, refCount.incrementAndGet()); ASSERT_EQ(2, refCount.incrementAndGet()); ASSERT_EQ(3, refCount.incrementAndGet()); ASSERT_EQ(2, refCount.decrementAndGet()); ASSERT_EQ(1, refCount.decrementAndGet()); ASSERT_EQ(0, refCount.decrementAndGet()); ASSERT_EQ(0, refCount.getAndSet(10)); ASSERT_EQ(10, refCount.get()); ASSERT_EQ(10, refCount.getAndSet(0)); ASSERT_EQ(0, refCount.get()); ASSERT_EQ(0, refCount.getAndAdd(5)); ASSERT_EQ(5, refCount.get()); ASSERT_EQ(5, refCount.getAndAdd(-5)); ASSERT_EQ(0, refCount.get()); ASSERT_EQ(5, refCount.addAndGet(5)); ASSERT_EQ(0, refCount.addAndGet(-5)); refCount.add(5); ASSERT_EQ(5, refCount.get()); refCount.add(-5); ASSERT_EQ(0, refCount.get()); refCount.increment(); ASSERT_EQ(1, refCount.get()); refCount.decrement(); ASSERT_EQ(0, refCount.get()); } int main(int argc, char *argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
25.97619
45
0.665445
xiyou-linuxer
8045fefca3d7b3e52a78a4a2fd3f39d1e076d441
1,032
cc
C++
leetcode/0664-strange-printer.cc
Magic07/online-judge-solutions
02a289dd7eb52d7eafabc97bd1a043213b65f70a
[ "MIT" ]
null
null
null
leetcode/0664-strange-printer.cc
Magic07/online-judge-solutions
02a289dd7eb52d7eafabc97bd1a043213b65f70a
[ "MIT" ]
null
null
null
leetcode/0664-strange-printer.cc
Magic07/online-judge-solutions
02a289dd7eb52d7eafabc97bd1a043213b65f70a
[ "MIT" ]
null
null
null
#include <string> using namespace std; class Solution { public: int calulateDp(const string& s, int dp[100][100], int start, int end) { if (dp[start][end] != 0) { return dp[start][end]; } if (start == end) { dp[start][start] = 1; return 1; } else { int c[3] = {INT_MAX, INT_MAX, INT_MAX}; if (s[end] == s[start] || s[end] == s[end - 1]) { c[0] = calulateDp(s, dp, start, end - 1); } else if (s[start] == s[start + 1] || s[start] == s[end]) { c[1] = calulateDp(s, dp, start + 1, end); } else { for (int i = start; i < end; i++) { c[2] = min(c[2], calulateDp(s, dp, start, i) + calulateDp(s, dp, i + 1, end)); } } dp[start][end] = *std::min_element(c, c + 3); return dp[start][end]; } } int strangePrinter(string s) { if (s.size() == 0) { return 0; } int dp[100][100]; memset(dp, 0, sizeof(dp)); return calulateDp(s, dp, 0, s.size() - 1); } };
26.461538
73
0.471899
Magic07
8052159598068b8e0bbbb02a47268bb16136196d
255
cpp
C++
Hashes/SHA2_Functions.cpp
r4yan2/OpenPGP
0299d96ee3b60d1d29b2d59f43610603a1135a5e
[ "MIT" ]
20
2016-01-10T13:53:41.000Z
2022-01-28T02:09:07.000Z
Hashes/SHA2_Functions.cpp
m0n0ph1/Hashes
4764d88bc71b4905141a208ab38f475cdc547f13
[ "MIT" ]
1
2020-07-13T17:48:10.000Z
2020-07-18T21:03:41.000Z
Hashes/SHA2_Functions.cpp
m0n0ph1/Hashes
4764d88bc71b4905141a208ab38f475cdc547f13
[ "MIT" ]
10
2017-05-15T16:25:59.000Z
2022-02-03T15:31:11.000Z
#include "SHA2_Functions.h" uint64_t Ch(const uint64_t & m, const uint64_t & n, const uint64_t & o){ return (m & n) ^ (~m & o); } uint64_t Maj(const uint64_t & m, const uint64_t & n, const uint64_t & o){ return (m & n) ^ (m & o) ^ (n & o); }
23.181818
74
0.584314
r4yan2
8053b00e6296f9ab891935053bf782d1f6e8d8f6
1,194
cpp
C++
src/bliss.cpp
yunseo-h68/bliss
1eaafd7bbc117f3b39f0900956db7ab7b085d941
[ "MIT" ]
1
2020-07-27T06:20:32.000Z
2020-07-27T06:20:32.000Z
src/bliss.cpp
yunseo-h68/bliss
1eaafd7bbc117f3b39f0900956db7ab7b085d941
[ "MIT" ]
null
null
null
src/bliss.cpp
yunseo-h68/bliss
1eaafd7bbc117f3b39f0900956db7ab7b085d941
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> #include <string> #include "bliss.h" static std::string parse_option_name(const char* str) { int i = 0; std::string name = ""; while (str[i] == '-') i++; for (int j = 0; str[i+j] != '\0'; j++) { name += str[i+j]; } return name; } int bliss_run(BlissApp* app, int argc, char* argv[]) { int check = 0; if (argc == 1) { app->Exec(); } for (int i = 1; i < argc; i++) { std::string name; if (strlen(argv[i]) >= 2 && argv[i][0] == '-') { name = parse_option_name(argv[i]); BlissOption* option_tmp = NULL; if (argv[i][1] != '-') { option_tmp = app->GetOptionByNameShort(name); } else if (argv[i][2] != '-') { option_tmp = app->GetOptionByName(name); } if (option_tmp == NULL) { std::cout << "NOT FOUND OPTION: " << argv[i] << "\n"; continue; } option_tmp->Exec(); check = 1; continue; } BlissCommand* subcommand_tmp = app->GetSubcommandByName(argv[i]); if (subcommand_tmp == NULL) { std::cout << "NOT FOUND SUBCOMMAND: " << argv[i] << "\n"; if (!check && i == argc - 1) { return -1; } continue; } check = 1; subcommand_tmp -> Exec(); } delete app; return 0; }
20.947368
67
0.552764
yunseo-h68
8057815b4c971e0c90a11fafb826a004b8553bb9
16,115
cpp
C++
src/cui-1.0.4/PJADV/PJADV.cpp
MaiReo/crass
11579527090faecab27f98b1e221172822928f57
[ "BSD-3-Clause" ]
1
2021-07-21T00:58:45.000Z
2021-07-21T00:58:45.000Z
src/cui-1.0.4/PJADV/PJADV.cpp
MaiReo/crass
11579527090faecab27f98b1e221172822928f57
[ "BSD-3-Clause" ]
null
null
null
src/cui-1.0.4/PJADV/PJADV.cpp
MaiReo/crass
11579527090faecab27f98b1e221172822928f57
[ "BSD-3-Clause" ]
null
null
null
#include <windows.h> #include <tchar.h> #include <crass_types.h> #include <acui.h> #include <cui.h> #include <package.h> #include <resource.h> #include <cui_error.h> #include <stdio.h> #include <utility.h> /* 接口数据结构: 表示cui插件的一般信息 */ struct acui_information PJADV_cui_information = { _T("ぼとむれす"), /* copyright */ _T("PajamasSoft Adventure Engine"), /* system */ _T(".dat .pak .epa .bin"), /* package */ _T("1.0.1"), /* revision */ _T("痴汉公贼"), /* author */ _T("2008-1-25 0:19"), /* date */ NULL, /* notion */ ACUI_ATTRIBUTE_LEVEL_DEVELOP }; /* 所有的封包特定的数据结构都要放在这个#pragma段里 */ #pragma pack (1) typedef struct { s8 magic[12]; /* "GAMEDAT PACK" or "GAMEDAT PAC2" */ u32 index_entries; } pack_header_t; typedef struct { u32 offset; u32 length; } pack_entry_t; /* archive.dat提取出来后有个graphic.def,里面详细定义了每个图像的用途。 */ /* mode的用途是: * 立绘图的人物,通常只有表情变化。因此让mode==2的图是表情图,在它的epa * 中记录完整图的epa文件名,并记录下在原图中的位置 */ /* epa解压后最终都会转换为32位位图,没有α字段的图的Alpha填0xff */ typedef struct { s8 magic[2]; /* "EP" */ u8 version; /* must be 0x01 */ u8 mode; /* 0x01, have no XY */ u8 color_type; /* 0 - 8bit without alpha; 1 - 24 bit; 2 - 32bit; 4 - 8bit width alpha */ u8 unknown0; /* only used in 8bit */ // ??(8bits模式下有用:0 - 默认256;非0 - 实际的颜色数) u8 unknown1; /* only used in 8bit */ // ??(8bits模式下有用:0 - 默认256;非0 - 实际的??) u8 reserved; u32 width; u32 height; } epa1_header_t; // 0 - with palette; 4 - without palette typedef struct { s8 magic[2]; /* "EP" */ u8 version; /* must be 0x01 */ u8 mode; /* 0x02, have XY */ u8 color_type; /* 0 - 8bit without alpha; 1 - 24 bit; 2 - 32bit; 3 - 16 BIT; 4 - 8bit width alpha */ u8 unknown0; /* only used in 8bit */ // ??(8bits模式下有用:0 - 默认256;非0 - 实际的颜色数) u8 unknown1; /* only used in 8bit */ // ??(8bits模式下有用:0 - 默认256;非0 - 实际的??) u8 reserved; u32 width; u32 height; u32 X; /* 贴图坐标(左上角) */ u32 Y; s8 name[32]; } epa2_header_t; #pragma pack () typedef struct { union { epa1_header_t epa1; epa2_header_t epa2; }; } epa_header_t; typedef struct { s8 name[MAX_PATH]; u32 offset; u32 length; } my_pack_entry_t; static void *my_malloc(DWORD len) { return malloc(len); } static int epa_decompress(BYTE *uncompr, DWORD *max_uncomprlen, BYTE *compr, DWORD comprlen, u32 width) { unsigned int curbyte = 0; unsigned int uncomprlen = *max_uncomprlen; unsigned int act_uncomprlen = 0; unsigned int step_table[16]; step_table[0] = 0; step_table[1] = 1; step_table[2] = width; step_table[3] = width + 1; step_table[4] = 2; step_table[5] = width - 1; step_table[6] = width * 2; step_table[7] = 3; step_table[8] = (width + 1) * 2; step_table[9] = width + 2; step_table[10] = width * 2 + 1; step_table[11] = width * 2 - 1; step_table[12] = (width - 1) * 2 ; step_table[13] = width - 2; step_table[14] = width * 3; step_table[15] = 4; /* 这里千万不要心血来潮的用memcpy(),原因是memecpy()会根据src和dst * 的位置进行“正确”拷贝。但这个拷贝实际上在这里却是不正确的 */ while (act_uncomprlen < uncomprlen) { u8 flag; unsigned int copy_bytes; if (curbyte >= comprlen) return -1; flag = compr[curbyte++]; if (!(flag & 0xf0)) { copy_bytes = flag; if (curbyte + copy_bytes > comprlen) return -1; if (act_uncomprlen + copy_bytes > uncomprlen) return -1; for (unsigned int i = 0; i < copy_bytes; i++) uncompr[act_uncomprlen++] = compr[curbyte++]; } else { BYTE *src; if (flag & 8) { if (curbyte >= comprlen) return -1; copy_bytes = ((flag & 7) << 8) + compr[curbyte++]; } else copy_bytes = flag & 7; if (act_uncomprlen + copy_bytes > uncomprlen) return -1; src = &uncompr[act_uncomprlen] - step_table[flag >> 4]; for (unsigned int i = 0; i < copy_bytes; i++) uncompr[act_uncomprlen++] = *src++; } } *max_uncomprlen = act_uncomprlen; return 0; } /********************* dat *********************/ /* 封包匹配回调函数 */ static int PJADV_dat_match(struct package *pkg) { s8 magic[12]; if (pkg->pio->open(pkg, IO_READONLY)) return -CUI_EOPEN; if (pkg->pio->read(pkg, magic, sizeof(magic))) { pkg->pio->close(pkg); return -CUI_EREAD; } if (memcmp(magic, "GAMEDAT PACK", sizeof(magic)) && memcmp(magic, "GAMEDAT PAC2", sizeof(magic))) { pkg->pio->close(pkg); return -CUI_EMATCH; } return 0; } /* 封包索引目录提取函数 */ static int PJADV_dat_extract_directory(struct package *pkg, struct package_directory *pkg_dir) { pack_header_t pack_header; my_pack_entry_t *index_buffer; BYTE *raw_index_buffer; unsigned int raw_index_buffer_length, name_length, entry_size; u32 offset; unsigned int i; if (pkg->pio->seek(pkg, 0, IO_SEEK_SET)) return -CUI_ESEEK; if (pkg->pio->read(pkg, &pack_header, sizeof(pack_header))) return -CUI_EREAD; if (!strncmp(pack_header.magic, "GAMEDAT PACK", sizeof(pack_header.magic))) name_length = 16; else if (!strncmp(pack_header.magic, "GAMEDAT PAC2", sizeof(pack_header.magic))) name_length = 32; entry_size = name_length + sizeof(pack_entry_t); raw_index_buffer_length = entry_size * pack_header.index_entries; raw_index_buffer = (BYTE *)malloc(raw_index_buffer_length); if (!raw_index_buffer) return -CUI_EMEM; if (pkg->pio->read(pkg, raw_index_buffer, raw_index_buffer_length)) { free(raw_index_buffer); return -CUI_EREAD; } index_buffer = (my_pack_entry_t *)malloc(sizeof(my_pack_entry_t) * pack_header.index_entries); if (!index_buffer) { free(raw_index_buffer); return -CUI_EMEM; } offset = sizeof(pack_header) + raw_index_buffer_length; for (i = 0; i < pack_header.index_entries; i++) { my_pack_entry_t *my_entry = &index_buffer[i]; BYTE *name = raw_index_buffer + i * name_length; pack_entry_t *entry = (pack_entry_t *)(raw_index_buffer + pack_header.index_entries * name_length + i * sizeof(pack_entry_t)); strncpy(my_entry->name, (char *)name, name_length); my_entry->name[name_length] = 0; my_entry->length = entry->length; my_entry->offset = entry->offset + offset; } free(raw_index_buffer); pkg_dir->index_entries = pack_header.index_entries; pkg_dir->directory = index_buffer; pkg_dir->directory_length = pack_header.index_entries * sizeof(my_pack_entry_t); pkg_dir->index_entry_length = sizeof(my_pack_entry_t); return 0; } /* 封包索引项解析函数 */ static int PJADV_dat_parse_resource_info(struct package *pkg, struct package_resource *pkg_res) { my_pack_entry_t *my_pack_entry; my_pack_entry = (my_pack_entry_t *)pkg_res->actual_index_entry; strcpy(pkg_res->name, my_pack_entry->name); pkg_res->name_length = -1; /* -1表示名称以NULL结尾 */ pkg_res->raw_data_length = my_pack_entry->length; pkg_res->actual_data_length = 0; /* 数据都是明文 */ pkg_res->offset = my_pack_entry->offset; return 0; } /* 封包资源提取函数 */ static int PJADV_dat_extract_resource(struct package *pkg, struct package_resource *pkg_res) { pkg_res->raw_data = malloc(pkg_res->raw_data_length); if (!pkg_res->raw_data) return -CUI_EMEM; if (pkg->pio->readvec(pkg, pkg_res->raw_data, pkg_res->raw_data_length, pkg_res->offset, IO_SEEK_SET)) { free(pkg_res->raw_data); pkg_res->raw_data = NULL; return -CUI_EREADVEC; } return 0; } /* 资源保存函数 */ static int PJADV_dat_save_resource(struct resource *res, struct package_resource *pkg_res) { if (res->rio->create(res)) return -CUI_ECREATE; if (pkg_res->raw_data && pkg_res->raw_data_length) { if (res->rio->write(res, pkg_res->raw_data, pkg_res->raw_data_length)) { res->rio->close(res); return -CUI_EWRITE; } } res->rio->close(res); return 0; } /* 封包资源释放函数 */ static void PJADV_dat_release_resource(struct package *pkg, struct package_resource *pkg_res) { if (pkg_res->raw_data) { free(pkg_res->raw_data); pkg_res->raw_data = NULL; } } /* 封包卸载函数 */ static void PJADV_dat_release(struct package *pkg, struct package_directory *pkg_dir) { if (pkg_dir->directory) { free(pkg_dir->directory); pkg_dir->directory = NULL; } pkg->pio->close(pkg); } /* 封包处理回调函数集合 */ static cui_ext_operation PJADV_dat_operation = { PJADV_dat_match, /* match */ PJADV_dat_extract_directory, /* extract_directory */ PJADV_dat_parse_resource_info, /* parse_resource_info */ PJADV_dat_extract_resource, /* extract_resource */ PJADV_dat_save_resource, /* save_resource */ PJADV_dat_release_resource, /* release_resource */ PJADV_dat_release /* release */ }; /********************* epa *********************/ /* 封包匹配回调函数 */ static int PJADV_epa_match(struct package *pkg) { s8 magic[2]; u8 ver; if (pkg->pio->open(pkg, IO_READONLY)) return -CUI_EOPEN; if (pkg->pio->read(pkg, magic, sizeof(magic))) { pkg->pio->close(pkg); return -CUI_EREAD; } if (strncmp(magic, "EP", sizeof(magic))) { pkg->pio->close(pkg); return -CUI_EMATCH; } if (pkg->pio->read(pkg, &ver, 1)) { pkg->pio->close(pkg); return -CUI_EREAD; } if (ver != 1) { pkg->pio->close(pkg); return -CUI_EMATCH; } return 0; } /* 封包资源提取函数 */ static int PJADV_epa_extract_resource(struct package *pkg, struct package_resource *pkg_res) { epa_header_t epa_header; u8 mode; u32 color_type, width, height; unsigned int compr_offset; BYTE *uncompr, *compr, *palette; u32 raw_length; DWORD uncomprlen, comprlen, act_uncomprlen, palette_length; unsigned int pixel_bytes; int have_alpha; if (pkg->pio->read(pkg, &mode, 1)) return -CUI_EREAD; if (mode != 1 && mode != 2) return -CUI_EMATCH; if (pkg->pio->length_of(pkg, &raw_length)) return -CUI_ELEN; if (pkg->pio->seek(pkg, 0, IO_SEEK_SET)) return -CUI_ESEEK; if (mode == 1) { if (pkg->pio->read(pkg, &epa_header.epa1, sizeof(epa_header.epa1))) return -CUI_EREAD; width = epa_header.epa1.width; height = epa_header.epa1.height; color_type = epa_header.epa1.color_type; compr_offset = sizeof(epa_header.epa1); } else { if (pkg->pio->read(pkg, &epa_header.epa2, sizeof(epa_header.epa2))) return -CUI_EREAD; width = epa_header.epa2.width; height = epa_header.epa2.height; color_type = epa_header.epa2.color_type; compr_offset = sizeof(epa_header.epa2); } have_alpha = 0; switch (color_type) { case 0: pixel_bytes = 1; palette_length = 768; break; case 1: pixel_bytes = 3; palette_length = 0; break; case 2: pixel_bytes = 4; palette_length = 0; break; // case 3: // pixel_bytes = 2; // palette_length = 0; // break; case 4: pixel_bytes = 1; // 实际解压时候,比case0的情况多出height * width的数据,这段数据就是α palette_length = 768; have_alpha = 1; break; default: return -CUI_EMATCH; } if (palette_length) { palette = (BYTE *)malloc(palette_length); if (!palette) return -CUI_EMEM; if (pkg->pio->readvec(pkg, palette, palette_length, compr_offset, IO_SEEK_SET)) { free(palette); return -CUI_EREADVEC; } } else palette = NULL; uncomprlen = width * height * pixel_bytes; uncompr = (BYTE *)malloc(uncomprlen); if (!uncompr) { free(palette); return -CUI_EMEM; } comprlen = raw_length - compr_offset - palette_length; compr = (BYTE *)malloc(comprlen); if (!compr) { free(uncompr); free(palette); return -CUI_EMEM; } if (pkg->pio->readvec(pkg, compr, comprlen, compr_offset + palette_length, IO_SEEK_SET)) { free(compr); free(uncompr); free(palette); return -CUI_EREADVEC; } act_uncomprlen = uncomprlen; if (epa_decompress(uncompr, &act_uncomprlen, compr, comprlen, width)) { free(compr); free(uncompr); free(palette); return -CUI_EUNCOMPR; } free(compr); if (act_uncomprlen != uncomprlen) { free(uncompr); free(palette); return -CUI_EUNCOMPR; } /* 将RGBA数据重新整理 */ if (pixel_bytes > 1) { BYTE *tmp = (BYTE *)malloc(uncomprlen); if (!tmp) { free(uncompr); free(palette); return -CUI_EMEM; } unsigned int line_len = width * pixel_bytes; unsigned int i = 0; for (unsigned int p = 0; p < pixel_bytes; p++) { for (unsigned int y = 0; y < height; y++) { BYTE *line = &tmp[y * line_len]; for (unsigned int x = 0; x < width; x++) { BYTE *pixel = &line[x * pixel_bytes]; pixel[p] = uncompr[i++]; } } } free(uncompr); uncompr = tmp; } if (pixel_bytes == 2) { if (MyBuildBMP16File(uncompr, uncomprlen, width, height, (BYTE **)&pkg_res->actual_data, &pkg_res->actual_data_length, RGB555, NULL, my_malloc)) { free(uncompr); free(palette); return -CUI_EMEM; } } else if (MyBuildBMPFile(uncompr, uncomprlen, palette, palette_length, width, 0 - height, pixel_bytes * 8, (BYTE **)&pkg_res->actual_data, &pkg_res->actual_data_length, my_malloc)) { free(uncompr); free(palette); return -CUI_EMEM; } free(uncompr); free(palette); pkg_res->raw_data = NULL; pkg_res->raw_data_length = raw_length; return 0; } /* 资源保存函数 */ static int PJADV_epa_save_resource(struct resource *res, struct package_resource *pkg_res) { if (res->rio->create(res)) return -CUI_ECREATE; if (pkg_res->actual_data && pkg_res->actual_data_length) { if (res->rio->write(res, pkg_res->actual_data, pkg_res->actual_data_length)) { res->rio->close(res); return -CUI_EWRITE; } } res->rio->close(res); return 0; } /* 封包资源释放函数 */ static void PJADV_epa_release_resource(struct package *pkg, struct package_resource *pkg_res) { if (pkg_res->actual_data) { free(pkg_res->actual_data); pkg_res->actual_data = NULL; } } /* 封包卸载函数 */ static void PJADV_epa_release(struct package *pkg, struct package_directory *pkg_dir) { pkg->pio->close(pkg); } /* 封包处理回调函数集合 */ static cui_ext_operation PJADV_epa_operation = { PJADV_epa_match, /* match */ NULL, /* extract_directory */ NULL, /* parse_resource_info */ PJADV_epa_extract_resource, /* extract_resource */ PJADV_epa_save_resource, /* save_resource */ PJADV_epa_release_resource, /* release_resource */ PJADV_epa_release /* release */ }; /********************* textdata.bin *********************/ /* 封包匹配回调函数 */ static int PJADV_bin_match(struct package *pkg) { s8 magic[12]; if (lstrcmp(pkg->name, _T("textdata.bin"))) return -CUI_EMATCH; if (pkg->pio->open(pkg, IO_READONLY)) return -CUI_EOPEN; if (pkg->pio->read(pkg, magic, sizeof(magic))) { pkg->pio->close(pkg); return -CUI_EREAD; } if (!strncmp(magic, "PJADV_TF0001", 12)) { pkg->pio->close(pkg); return -CUI_EMATCH; } return 0; } /* 封包资源提取函数 */ static int PJADV_bin_extract_resource(struct package *pkg, struct package_resource *pkg_res) { u32 scenario_size; BYTE *scenario; if (pkg->pio->length_of(pkg, &scenario_size)) return -CUI_ELEN; scenario = (BYTE *)malloc(scenario_size); if (!scenario) return -CUI_EMEM; if (pkg->pio->readvec(pkg, scenario, scenario_size, 0, IO_SEEK_SET)) { free(scenario); return -CUI_EREAD; } BYTE xor = 0xc5; for (DWORD i = 0; i < scenario_size; i++) { scenario[i] ^= xor; xor += 0x5c; } pkg_res->raw_data = NULL; pkg_res->raw_data_length = scenario_size; pkg_res->actual_data = scenario; pkg_res->actual_data_length = scenario_size; return 0; } /* 封包处理回调函数集合 */ static cui_ext_operation PJADV_bin_operation = { PJADV_bin_match, /* match */ NULL, /* extract_directory */ NULL, /* parse_resource_info */ PJADV_bin_extract_resource, /* extract_resource */ PJADV_epa_save_resource, /* save_resource */ PJADV_epa_release_resource, /* release_resource */ PJADV_epa_release /* release */ }; /* 接口函数: 向cui_core注册支持的封包类型 */ int CALLBACK PJADV_register_cui(struct cui_register_callback *callback) { /* 注册cui插件支持的扩展名、资源放入扩展名、处理回调函数和封包属性 */ if (callback->add_extension(callback->cui, _T(".dat"), NULL, NULL, &PJADV_dat_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_DIR)) return -1; if (callback->add_extension(callback->cui, _T(".pak"), NULL, NULL, &PJADV_dat_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_DIR)) return -1; if (callback->add_extension(callback->cui, _T(".epa"), _T(".bmp"), NULL, &PJADV_epa_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_RES)) return -1; if (callback->add_extension(callback->cui, _T(".bin"), _T(".bin.out"), NULL, &PJADV_bin_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_RES)) return -1; return 0; } }
24.016393
102
0.670555
MaiReo