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
da8ced8c0b50f921522d08b1e017c00b2229741b
10,917
cpp
C++
src/core/pointers.cpp
vanreeslab/murphy
01c9c56171fcee33cb3c1c93c25617ccf7b8ff83
[ "BSD-3-Clause" ]
1
2021-12-01T22:12:56.000Z
2021-12-01T22:12:56.000Z
src/core/pointers.cpp
vanreeslab/murphy
01c9c56171fcee33cb3c1c93c25617ccf7b8ff83
[ "BSD-3-Clause" ]
null
null
null
src/core/pointers.cpp
vanreeslab/murphy
01c9c56171fcee33cb3c1c93c25617ccf7b8ff83
[ "BSD-3-Clause" ]
null
null
null
// #include "pointers.hpp" // //============================================================================= // /** // * @brief return a write access to the data // * // * @param i0 the index in dimension 0 = X // * @param i1 the index in dimension 1 = Y // * @param i2 the index in dimension 2 = Z // * @param ida the dimension // * @param stride the stride // * @return real_t* // */ // real_t* __restrict__ data_ptr::Write(const bidx_t i0, const bidx_t i1, const bidx_t i2, const lda_t ida, const bidx_t stride) const noexcept { // m_assert(0 <= stride && stride <= M_STRIDE, "the stride = %d is wrong", stride); // //------------------------------------------------------------------------- // const bidx_t offset = i0 + stride * (i1 + stride * (i2 + stride * ida)); // real_t* data = (*this)(); // return data + offset; // //------------------------------------------------------------------------- // } // /** // * @brief @brief return a write access to the data // * // * see data_ptr::Write(const bidx_t i0, const bidx_t i1, const bidx_t i2, const lda_t ida, const bidx_t stride) // * // * @param i0 the index in dimension 0 = X // * @param i1 the index in dimension 1 = Y // * @param i2 the index in dimension 2 = Z // * @param ida the dimension // * @param layout the memory layout // * @return real_t* // */ // real_t* __restrict__ data_ptr::Write(const bidx_t i0, const bidx_t i1, const bidx_t i2, const lda_t ida, const m_ptr<const MemLayout>& layout) const noexcept { // //------------------------------------------------------------------------- // return this->Write(i0, i1, i2, ida, layout->stride()); // //------------------------------------------------------------------------- // } // // /** // // * @brief return a write access to the data starting in the position layout->start() // // * // // * @param layout // // * @param ida // // * @return real_t* // // */ // // real_t* data_ptr::Write(const m_ptr<const MemLayout>& layout, const lda_t ida) const { // // //------------------------------------------------------------------------- // // return this->Write(layout->start(0), layout->start(1), layout->start(2), ida, layout->stride()); // // //------------------------------------------------------------------------- // // } // /** // * @brief return a write access to the data in (0,0,0) // * // * @param ida the given dimension // * @param layout the memory layout // * @return const real_t* // */ // real_t* __restrict__ data_ptr::Write(const lda_t ida, const m_ptr<const MemLayout>& layout) const noexcept { // m_assert(0 <= layout->stride() && layout->stride() <= M_STRIDE, "the stride = %d is wrong", layout->stride()); // //------------------------------------------------------------------------- // const bidx_t offset = stride_ * stride_ * stride_ * ida; // real_t* data = (*this)(); // return data + offset; // //------------------------------------------------------------------------- // } // /** // * @brief return a read-only access to the data // * // * if i0 = 0, i1 = 0, i2 = 0, and ida = 0, the last argument is discarded // * // * @param i0 the index in dimension 0 = X // * @param i1 the index in dimension 1 = Y // * @param i2 the index in dimension 2 = Z // * @param ida the dimension // * @param stride the stride // * @return real_t* // */ // const real_t* __restrict__ data_ptr::Read(const bidx_t i0, const bidx_t i1, const bidx_t i2, const lda_t ida, const bidx_t stride) const noexcept { // m_assert(0 <= stride && stride <= M_STRIDE, "the stride = %d is wrong", stride); // //------------------------------------------------------------------------- // const bidx_t offset = i0 + stride_ * (i1 + stride_ * (i2 + stride_ * ida)); // return (*this)() + offset; // //------------------------------------------------------------------------- // } // /** // * @brief @brief return a read-only access to the data // * // * see data_ptr::Read(const bidx_t i0, const bidx_t i1, const bidx_t i2, const lda_t ida, const bidx_t stride) // * // * @param i0 the index in dimension 0 = X // * @param i1 the index in dimension 1 = Y // * @param i2 the index in dimension 2 = Z // * @param ida the dimension // * @param layout the memory layout // * @return real_t* // */ // const real_t* __restrict__ data_ptr::Read(const bidx_t i0, const bidx_t i1, const bidx_t i2, const lda_t ida, const m_ptr<const MemLayout>& layout) const noexcept { // //------------------------------------------------------------------------- // return this->Read(i0, i1, i2, ida, layout->stride()); // //------------------------------------------------------------------------- // } // /** // * @brief return a read-only access to the data in (0,0,0) // * // * @param ida the given dimension // * @param layout the memory layout // * @return const real_t* // */ // const real_t* __restrict__ data_ptr::Read(const lda_t ida, const m_ptr<const MemLayout>& layout) const noexcept { // m_assert(0 <= layout->stride() && layout->stride() <= M_STRIDE, "the stride = %d is wrong", layout->stride()); // //------------------------------------------------------------------------- // const bidx_t offset = stride_ * stride_ * stride_ * ida; // const real_t* data = (*this)(); // return data + offset; // //------------------------------------------------------------------------- // } // //============================================================================= // /** // * @brief return a read-only access to the data // * // * if i0 = 0, i1 = 0, i2 = 0, and ida = 0, the last argument is discarded // * // * @param i0 the index in dimension 0 = X // * @param i1 the index in dimension 1 = Y // * @param i2 the index in dimension 2 = Z // * @param ida the dimension // * @param layout the memory layout // * @return real_t* // */ // const real_t* __restrict__ const_data_ptr::Read(const bidx_t i0, const bidx_t i1, const bidx_t i2, const lda_t ida, const bidx_t stride) const noexcept { // m_assert(0 <= stride, "the stride = %d is wrong", stride); // //------------------------------------------------------------------------- // const bidx_t offset = i0 + stride_ * (i1 + stride_ * (i2 + stride_ * ida)); // const real_t* data = (*this)(); // return data + offset; // //------------------------------------------------------------------------- // } // /** // * @brief return a read-only access to the data // * // * @param i0 the index in dimension 0 = X // * @param i1 the index in dimension 1 = Y // * @param i2 the index in dimension 2 = Z // * @param ida the dimension // * @param layout the memory layout // * @return const real_t* // */ // const real_t* __restrict__ const_data_ptr::Read(const bidx_t i0, const bidx_t i1, const bidx_t i2, const lda_t ida, const m_ptr<const MemLayout>& layout) const noexcept { // m_assert(0 <= layout->stride(), "the stride = %d is wrong", layout->stride()); // //------------------------------------------------------------------------- // const bidx_t stride = layout->stride(); // const bidx_t offset = i0 + stride * (i1 + stride * (i2 + stride * ida)); // const real_t* data = (*this)(); // return data + offset; // //------------------------------------------------------------------------- // } // /** // * @brief return a read-only access to the data in (0,0,0) // * // * @param ida the given dimension // * @param layout the memory layout // * @return const real_t* // */ // const real_t* __restrict__ const_data_ptr::Read(const lda_t ida, const m_ptr<const MemLayout>& layout) const noexcept { // m_assert(0 <= layout->stride(), "the stride = %d is wrong", layout->stride()); // //------------------------------------------------------------------------- // const bidx_t offset = stride_ * stride_ * stride_ * ida; // const real_t* data = (*this)(); // return data + offset; // //------------------------------------------------------------------------- // } // //============================================================================= // /** // * @brief return a data_ptr that can be used to access the data, the returned data_ptr does not own the data // * // * @param ida the dimension // * @param gs the ghost size // * @param stride the stride // * @return data_ptr // */ // data_ptr mem_ptr::operator()(const lda_t ida, const bidx_t gs, const bidx_t stride) const noexcept { // m_assert(0 <= gs, "the gs = %d is wrong", gs); // m_assert(0 <= stride, "the stride = %d is wrong", stride); // //------------------------------------------------------------------------- // // get the offset and return a data_ptr to it // const bidx_t offset = gs + stride * (gs + stride * (gs + stride * ida)); // return data_ptr(this->m_ptr::operator()() + offset, stride, gs); // //------------------------------------------------------------------------- // } // /** // * @brief return a data_ptr that can be used to access the data, the returned data_ptr does not own the data // * // * @param ida the dimension // * @param layout the layout used to retrieve the dimension (if not ida = 0) // * @return data_ptr // */ // data_ptr mem_ptr::operator()(const lda_t ida, const m_ptr<const MemLayout>& layout) const noexcept { // m_assert(0 <= layout->gs(), "the gs = %d is wrong", layout->gs()); // m_assert(0 <= layout->stride(), "the stride = %d is wrong", layout->stride()); // //------------------------------------------------------------------------- // // get the offset and return a data_ptr to it // const bidx_t gs = layout->gs(); // const bidx_t stride = layout->stride(); // const bidx_t offset = gs + stride * (gs + stride * (gs + stride * ida)); // real_t* my_ptr = this->m_ptr::operator()() + offset; // return data_ptr(my_ptr, stride, gs); // //------------------------------------------------------------------------- // } // /** // * @brief return the mem_ptr for the given dimension // * // * @param ida the dimension // * @param layout the layout, only the stride is used here // * @return mem_ptr // */ // mem_ptr mem_ptr::shift_dim(const lda_t ida, const m_ptr<const MemLayout>& layout) const noexcept { // m_assert(0 <= layout->stride(), "the stride = %d is wrong", layout->stride()); // //------------------------------------------------------------------------- // // get the offset and return a data_ptr to it // const bidx_t stride = layout->stride(); // const bidx_t offset = stride * stride * stride * ida; // return mem_ptr(this->m_ptr::operator()() + offset); // //------------------------------------------------------------------------- // }
45.869748
173
0.48026
vanreeslab
da8dbf942ca4924ae4e1b66e3f8ee9801f97f1d5
54
cxx
C++
Software/CPU/myscrypt/build/cmake-3.12.3/Tests/SimpleInstallS2/lib3.cxx
duonglvtnaist/Multi-ROMix-Scrypt-Accelerator
9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8
[ "MIT" ]
64
2015-03-06T00:30:56.000Z
2022-03-24T13:26:53.000Z
Software/CPU/myscrypt/build/cmake-3.12.3/Tests/SimpleInstallS2/lib3.cxx
duonglvtnaist/Multi-ROMix-Scrypt-Accelerator
9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8
[ "MIT" ]
12
2020-12-15T08:30:19.000Z
2022-03-13T03:54:24.000Z
Software/CPU/myscrypt/build/cmake-3.12.3/Tests/SimpleInstallS2/lib3.cxx
duonglvtnaist/Multi-ROMix-Scrypt-Accelerator
9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8
[ "MIT" ]
40
2015-02-26T15:31:16.000Z
2022-03-03T23:23:37.000Z
#include "lib3.h" float Lib3Func() { return 2.0; }
7.714286
17
0.611111
duonglvtnaist
da967a87b0babaad96b1757ec934c50ed0e28c80
1,378
cpp
C++
src/shape_detector/src/reconfigure_parameter_manager.cpp
harrycomeon/ros_object_recognition
064d3cbac1ffc31cba48461ee08961f9da540a28
[ "MIT" ]
68
2018-09-25T13:46:29.000Z
2022-03-16T15:43:48.000Z
src/shape_detector/src/reconfigure_parameter_manager.cpp
harrycomeon/ros_object_recognition
064d3cbac1ffc31cba48461ee08961f9da540a28
[ "MIT" ]
1
2019-02-05T05:18:24.000Z
2020-02-16T15:36:33.000Z
src/shape_detector/src/reconfigure_parameter_manager.cpp
harrycomeon/ros_object_recognition
064d3cbac1ffc31cba48461ee08961f9da540a28
[ "MIT" ]
27
2018-11-02T06:31:43.000Z
2022-03-22T08:11:00.000Z
/** \file * \brief Implementation of the ReconfigureParameterManager class. */ // std. #include <functional> // bind(), placeholders #include <algorithm> // max() // Headers of this package. #include <shape_detector/reconfigure_parameter_manager.h> #include <shape_detector/shape_enum.h> namespace shape_detector { ReconfigureParameterManager::ReconfigureParameterManager() { reconfigure_callback_ = std::bind(&ReconfigureParameterManager::reconfigureCallback, this, std::placeholders::_1, std::placeholders::_2); reconfigure_server_.setCallback(reconfigure_callback_); } void ReconfigureParameterManager::reconfigureCallback( shape_detector::ParametersConfig& config, uint32_t) { setObjectName(config.object_name); setShape(static_cast<Shape>(config.shape)); // Groups do not work yet. // That's why we cannot write 'config.groups.Radii.min_radius'. config.max_radius = std::max(config.min_radius, config.max_radius); setMinRadius(config.min_radius); setMaxRadius(config.max_radius); setNormalDistanceWeight(config.normal_distance_weight); setDistanceThreshold(config.distance_threshold); setNumNearestNeighbors(config.num_nearest_neighbors); setMaxIterations(config.max_iterations); setOptimizeCoefficients(config.optimize_coefficients); } } // shape_detector
31.318182
86
0.75254
harrycomeon
da97c10aa8bcef4f262db68f43fe2a1dc466268d
956
cpp
C++
source/stdiooutputstream.cpp
bondadmin/bond
3fb698f0c8c4d92de088f87d17be2f41f1088c42
[ "MIT" ]
null
null
null
source/stdiooutputstream.cpp
bondadmin/bond
3fb698f0c8c4d92de088f87d17be2f41f1088c42
[ "MIT" ]
null
null
null
source/stdiooutputstream.cpp
bondadmin/bond
3fb698f0c8c4d92de088f87d17be2f41f1088c42
[ "MIT" ]
null
null
null
#include "bond/io/stdiooutputstream.h" #include "bond/systems/assert.h" namespace Bond { StdioOutputStream::StdioOutputStream(const char *fileName): mHandle(fileName, "wb"), mFile(mHandle.GetFile()) { if (!IsBound()) { BOND_FAIL_FORMAT(("Failed to open file '%s' for writing.", fileName)); } } void StdioOutputStream::Close() { // If we have a file, but not handle, close it explicitly, otherwise let the handle take care of it. if (IsBound() && !mHandle.IsBound()) { fclose(mFile); } mHandle = nullptr; mFile = nullptr; } Stream::pos_t StdioOutputStream::GetEndPosition() const { const auto pos = ftell(mFile); fseek(mFile, 0, SEEK_END); const auto end = ftell(mFile); fseek(mFile, pos, SEEK_SET); return pos_t(end); } StdioOutputStream &StdioOutputStream::operator=(StdioOutputStream &&other) { if (this != &other) { mHandle = move(other.mHandle); mFile = other.mFile; other.mFile = nullptr; } return *this; } }
18.384615
101
0.692469
bondadmin
da9d2da2646decffb7492d4e40f4fad84c113804
20
cpp
C++
Morpheus-Core/Source/Morppch.cpp
Red-Scarlet/Morpheus-Engine
f9ddc2ab4bac5f6f8b2f7334358c47dcc558eec4
[ "Apache-2.0" ]
2
2020-11-07T12:38:16.000Z
2020-11-21T01:36:49.000Z
Morpheus-Core/Source/Morppch.cpp
LegendaryDelta/Morpheus-Engine
f9ddc2ab4bac5f6f8b2f7334358c47dcc558eec4
[ "Apache-2.0" ]
null
null
null
Morpheus-Core/Source/Morppch.cpp
LegendaryDelta/Morpheus-Engine
f9ddc2ab4bac5f6f8b2f7334358c47dcc558eec4
[ "Apache-2.0" ]
null
null
null
#include "Morppch.h"
20
20
0.75
Red-Scarlet
daa69166317e2506f7ddf8f656c4c0ca3d2eaf66
2,401
cpp
C++
src/System/Utils.cpp
maddinat0r/cpp-gamemode-samp
ee36f3f322502f6faa997647d562bf25863e7791
[ "MIT" ]
1
2021-05-31T11:10:12.000Z
2021-05-31T11:10:12.000Z
src/System/Utils.cpp
maddinat0r/cpp-gamemode-samp
ee36f3f322502f6faa997647d562bf25863e7791
[ "MIT" ]
null
null
null
src/System/Utils.cpp
maddinat0r/cpp-gamemode-samp
ee36f3f322502f6faa997647d562bf25863e7791
[ "MIT" ]
1
2020-10-17T18:27:00.000Z
2020-10-17T18:27:00.000Z
#pragma warning (disable: 4244 4018) //coversion from `long` to `float`, possible loss of data #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/karma.hpp> #include <boost/thread/thread_pool.hpp> #include <type_traits> using namespace boost::spirit; #include <System/Utils.h> boost::basic_thread_pool g_ThreadPool; template<typename T> bool ConvertStrToData(const char *src, T &dest) { const char *first_it = src, *last_it = first_it + strlen(src); return qi::parse(first_it, last_it, typename std::conditional< std::is_floating_point<T>::value, qi::real_parser<T>, qi::int_parser<T> >::type(), dest); } template bool ConvertStrToData(const char *src, int &dest); template bool ConvertStrToData(const char *src, unsigned int &dest); template bool ConvertStrToData(const char *src, short &dest); template bool ConvertStrToData(const char *src, unsigned short &dest); template bool ConvertStrToData(const char *src, char &dest); template bool ConvertStrToData(const char *src, unsigned char &dest); template bool ConvertStrToData(const char *src, long long &dest); template bool ConvertStrToData(const char *src, unsigned long long &dest); template bool ConvertStrToData(const char *src, float &dest); template bool ConvertStrToData(const char *src, double &dest); template<typename T> bool ConvertDataToStr(T src, string &dest) { return karma::generate(std::back_inserter(dest), typename std::conditional< std::is_floating_point<T>::value, karma::real_generator<T>, typename std::conditional< std::is_signed<T>::value, karma::int_generator<T>, karma::uint_generator<T> >::type >::type(), src); } template bool ConvertDataToStr(int src, string &dest); template bool ConvertDataToStr(unsigned int src, string &dest); template bool ConvertDataToStr(short src, string &dest); template bool ConvertDataToStr(unsigned short src, string &dest); template bool ConvertDataToStr(char src, string &dest); template bool ConvertDataToStr(unsigned char src, string &dest); template bool ConvertDataToStr(long long src, string &dest); template bool ConvertDataToStr(unsigned long long src, string &dest); template bool ConvertDataToStr(float src, string &dest); template bool ConvertDataToStr(double src, string &dest); void ExecuteThreaded(std::function<void()> &&func) { g_ThreadPool.submit(std::move(func)); }
31.181818
94
0.750104
maddinat0r
daa789341385cdb9d6f358f81fd7859ae271308e
2,069
cpp
C++
vulkan-tools/tst/test-poc.cpp
m4c0/m4c0-stl
5e47439528faee466270706534143c87b4af8cbb
[ "MIT" ]
null
null
null
vulkan-tools/tst/test-poc.cpp
m4c0/m4c0-stl
5e47439528faee466270706534143c87b4af8cbb
[ "MIT" ]
null
null
null
vulkan-tools/tst/test-poc.cpp
m4c0/m4c0-stl
5e47439528faee466270706534143c87b4af8cbb
[ "MIT" ]
null
null
null
#include "m4c0/assets/stb_image.hpp" #include "m4c0/vulkan/buffer.hpp" #include "m4c0/vulkan/buffer_memory_bind.hpp" #include "m4c0/vulkan/command_buffer_list.hpp" #include "m4c0/vulkan/device_memory.hpp" #include "m4c0/vulkan/host_staged_image_buffer.hpp" #include "m4c0/vulkan/image.hpp" #include "m4c0/vulkan/image_memory_bind.hpp" #include "m4c0/vulkan/local_image.hpp" #include "m4c0/vulkan/logical_device.hpp" #include "m4c0/vulkan/queue_submit.hpp" #include "m4c0/vulkan/staged_image.hpp" #include "m4c0/vulkan/typed_semaphore.hpp" struct my_semaphore : public m4c0::vulkan::tools::typed_semaphore<my_semaphore> {}; struct other_semaphore : public m4c0::vulkan::tools::typed_semaphore<other_semaphore> {}; void use_my_semaphore(const my_semaphore * signal, const other_semaphore * wait) { m4c0::vulkan::actions::queue_submit().with_signal_semaphore(signal).with_wait_semaphore(wait).now(); } class bound_image { m4c0::vulkan::image img { /* ... */ }; m4c0::vulkan::device_memory mem { /* ... */ }; m4c0::vulkan::tools::image_memory_bind bind { &img, &mem }; }; class bound_buffer { m4c0::vulkan::buffer buf { /* ... */ }; m4c0::vulkan::device_memory mem { /* ... */ }; m4c0::vulkan::tools::buffer_memory_bind bind { &buf, &mem }; }; int main() { m4c0::vulkan::tools::logical_device d { "test-app", nullptr }; m4c0::vulkan::tools::local_image img { &d, 4, 3 }; auto asset = m4c0::assets::typed_stb_image<>::load_from_asset(nullptr, "texture", "png"); m4c0::vulkan::tools::host_staged_image_buffer stg { &d, asset }; m4c0::vulkan::tools::staged_image txt { &d, nullptr, "texture", "png" }; m4c0::vulkan::tools::primary_command_buffer_list<3> pcb { d.unified_queue_family() }; m4c0::vulkan::tools::secondary_command_buffer_list<3> scb { d.unified_queue_family() }; { auto pg = pcb.begin(0); txt.build_primary_command_buffer(pg.command_buffer()); // I feel like there should be some compiler-enforced way of setting the second only be achievable via the primary auto sg = scb.begin(0, nullptr, nullptr); } }
38.314815
118
0.721605
m4c0
daac04226e5e33f6a7eebd64cea5e49d186d287b
301
hpp
C++
lumino/Graphics/include/LuminoGraphics.hpp
lriki/Lumino
1a80430f4a83dbdfbe965b3d5b16064991b3edb0
[ "MIT" ]
30
2016-01-24T05:35:45.000Z
2020-03-03T09:54:27.000Z
lumino/Graphics/include/LuminoGraphics.hpp
lriki/Lumino
1a80430f4a83dbdfbe965b3d5b16064991b3edb0
[ "MIT" ]
35
2016-04-18T06:14:08.000Z
2020-02-09T15:51:58.000Z
lumino/Graphics/include/LuminoGraphics.hpp
lriki/Lumino
1a80430f4a83dbdfbe965b3d5b16064991b3edb0
[ "MIT" ]
5
2016-04-03T02:52:05.000Z
2018-01-02T16:53:06.000Z
#pragma once #include <LuminoGraphics/RHI/Shader.hpp> #include <LuminoGraphics/RHI/ShaderDescriptor.hpp> #include <LuminoGraphics/RHI/VertexLayout.hpp> #include <LuminoGraphics/RHI/VertexBuffer.hpp> #include <LuminoGraphics/RHI/SwapChain.hpp> #include <LuminoGraphics/RHI/GraphicsCommandBuffer.hpp>
33.444444
55
0.82392
lriki
daaf843c10a95d09460b96401cd665176b476ff6
9,430
tpp
C++
cml/mathlib/matrix/projection.tpp
egorodet/CML
e3fd8ccbe9775ff6e0e41fd6a274b557a80c9d1f
[ "BSL-1.0" ]
125
2015-07-22T11:39:51.000Z
2022-03-06T13:41:44.000Z
cml/mathlib/matrix/projection.tpp
egorodet/CML
e3fd8ccbe9775ff6e0e41fd6a274b557a80c9d1f
[ "BSL-1.0" ]
45
2015-06-03T15:50:08.000Z
2021-05-26T01:35:01.000Z
cml/mathlib/matrix/projection.tpp
egorodet/CML
e3fd8ccbe9775ff6e0e41fd6a274b557a80c9d1f
[ "BSL-1.0" ]
28
2015-06-03T09:26:26.000Z
2022-03-06T13:42:06.000Z
/* -*- C++ -*- ------------------------------------------------------------ @@COPYRIGHT@@ *-----------------------------------------------------------------------*/ /** @file */ #ifndef __CML_MATHLIB_MATRIX_PROJECTION_TPP #error "mathlib/matrix/projection.tpp not included correctly" #endif #include <cml/common/mpl/are_convertible.h> #include <cml/mathlib/matrix/size_checking.h> namespace cml { /* Orthographic projection functions: */ /** Build a matrix representing an orthographic projection, specified by * frustum bounds in l,r,b,t,n,f form, and with the given handedness and z * clipping range */ template<class Sub, class E> inline void matrix_orthographic( writable_matrix<Sub>& m, E left, E right, E bottom, E top, E n, E f, AxisOrientation handedness, ZClip z_clip ) { static_assert( cml::are_convertible<value_type_trait_of_t<Sub>, E>::value, "incompatible scalar types"); cml::check_minimum_size(m, int_c<4>(), int_c<4>()); /* Initialize: */ m.identity(); auto inv_width = E(1) / (right - left); auto inv_height = E(1) / (top - bottom); auto inv_depth = E(1) / (f - n); auto s = E(handedness == left_handed ? 1 : -1); if (z_clip == z_clip_neg_one) { m.set_basis_element(2,2, s * E(2) * inv_depth); m.set_basis_element(3,2, -(f + n) * inv_depth); } else { // z_clip.z_clip() == 0 m.set_basis_element(2,2, s * inv_depth); m.set_basis_element(3,2, -n * inv_depth); } m.set_basis_element(0,0, E(2) * inv_width ); m.set_basis_element(1,1, E(2) * inv_height ); m.set_basis_element(3,0, -(right + left) * inv_width ); m.set_basis_element(3,1, -(top + bottom) * inv_height); } template<class Sub, class E> inline void matrix_orthographic_LH( writable_matrix<Sub>& m, E left, E right, E bottom, E top, E n, E f, ZClip z_clip ) { matrix_orthographic(m, left, right, bottom, top, n, f, left_handed, z_clip); } template<class Sub, class E> inline void matrix_orthographic_RH( writable_matrix<Sub>& m, E left, E right, E bottom, E top, E n, E f, ZClip z_clip ) { matrix_orthographic(m, left, right, bottom, top, n, f, right_handed, z_clip); } template<class Sub, class E> inline void matrix_orthographic( writable_matrix<Sub>& m, E width, E height, E n, E f, AxisOrientation handedness, ZClip z_clip ) { auto half_width = width / E(2); auto half_height = height / E(2); matrix_orthographic(m, -half_width, half_width, -half_height, half_height, n, f, handedness, z_clip); } template<class Sub, class E> inline void matrix_orthographic_LH( writable_matrix<Sub>& m, E width, E height, E n, E f, ZClip z_clip ) { matrix_orthographic(m, width, height, n, f, left_handed, z_clip); } template<class Sub, class E> inline void matrix_orthographic_RH( writable_matrix<Sub>& m, E width, E height, E n, E f, ZClip z_clip ) { matrix_orthographic(m, width, height, n, f, right_handed, z_clip); } /* Perspective projection functions: */ template<class Sub, class E> inline void matrix_perspective( writable_matrix<Sub>& m, E left, E right, E bottom, E top, E n, E f, AxisOrientation handedness, ZClip z_clip ) { static_assert( cml::are_convertible<value_type_trait_of_t<Sub>, E>::value, "incompatible scalar types"); cml::check_minimum_size(m, int_c<4>(), int_c<4>()); /* Initialize: */ m.identity(); auto inv_width = E(1) / (right - left); auto inv_height = E(1) / (top - bottom); auto inv_depth = E(1) / (f - n); auto near2 = E(2) * n; auto s = E(handedness == left_handed ? 1 : -1); if (z_clip == z_clip_neg_one) { m.set_basis_element(2,2, s * (f + n) * inv_depth); m.set_basis_element(3,2, - E(2) * f * n * inv_depth); } else { // z_clip == z_clip_zero m.set_basis_element(2,2, s * f * inv_depth); m.set_basis_element(3,2, -s * n * m.basis_element(2,2)); } m.set_basis_element(0,0, near2 * inv_width ); m.set_basis_element(1,1, near2 * inv_height ); m.set_basis_element(2,0, -s * (right + left) * inv_width ); m.set_basis_element(2,1, -s * (top + bottom) * inv_height); m.set_basis_element(2,3, s ); m.set_basis_element(3,3, 0 ); } template<class Sub, class E> inline void matrix_perspective_LH( writable_matrix<Sub>& m, E left, E right, E bottom, E top, E n, E f, ZClip z_clip ) { matrix_perspective(m, left, right, bottom, top, n, f, left_handed, z_clip); } template<class Sub, class E> inline void matrix_perspective_RH( writable_matrix<Sub>& m, E left, E right, E bottom, E top, E n, E f, ZClip z_clip ) { matrix_perspective(m, left, right, bottom, top, n, f, right_handed, z_clip); } template<class Sub, class E> inline void matrix_perspective( writable_matrix<Sub>& m, E width, E height, E n, E f, AxisOrientation handedness, ZClip z_clip ) { auto half_width = width / E(2); auto half_height = height / E(2); matrix_perspective(m, -half_width, half_width, -half_height, half_height, n, f, handedness, z_clip); } template<class Sub, class E> inline void matrix_perspective_LH( writable_matrix<Sub>& m, E width, E height, E n, E f, ZClip z_clip ) { matrix_perspective(m, width, height, n, f, left_handed, z_clip); } template<class Sub, class E> inline void matrix_perspective_RH( writable_matrix<Sub>& m, E width, E height, E n, E f, ZClip z_clip ) { matrix_perspective(m, width, height, n, f, right_handed, z_clip); } template<class Sub, class E> inline void matrix_perspective_xfov( writable_matrix<Sub>& m, E xfov, E aspect, E n, E f, AxisOrientation handedness, ZClip z_clip ) { typedef scalar_traits<E> E_traits; /* Compute the view height from the field of view: */ auto width = E(2) * n * E_traits::tan(xfov / E(2)); matrix_perspective(m, width, width / aspect, n, f, handedness, z_clip); } template<class Sub, class E> inline void matrix_perspective_xfov_LH( writable_matrix<Sub>& m, E xfov, E aspect, E n, E f, ZClip z_clip ) { matrix_perspective_xfov(m, xfov, aspect, n, f, left_handed, z_clip); } template<class Sub, class E> inline void matrix_perspective_xfov_RH( writable_matrix<Sub>& m, E xfov, E aspect, E n, E f, ZClip z_clip ) { matrix_perspective_xfov(m, xfov, aspect, n, f, right_handed, z_clip); } template<class Sub, class E> inline void matrix_perspective_yfov( writable_matrix<Sub>& m, E yfov, E aspect, E n, E f, AxisOrientation handedness, ZClip z_clip ) { typedef scalar_traits<E> E_traits; /* Compute the view height from the field of view: */ auto height = E(2) * n * E_traits::tan(yfov / E(2)); matrix_perspective(m, height * aspect, height, n, f, handedness, z_clip); } template<class Sub, class E> inline void matrix_perspective_yfov_LH( writable_matrix<Sub>& m, E yfov, E aspect, E n, E f, ZClip z_clip ) { matrix_perspective_yfov(m, yfov, aspect, n, f, left_handed, z_clip); } template<class Sub, class E> inline void matrix_perspective_yfov_RH( writable_matrix<Sub>& m, E yfov, E aspect, E n, E f, ZClip z_clip ) { matrix_perspective_yfov(m, yfov, aspect, n, f, right_handed, z_clip); } } // namespace cml #if 0 // XXX INCOMPLETE XXX /* Build a viewport matrix * * Note: A viewport matrix is in a sense the opposite of an orthographics * projection matrix, and can be build by constructing and inverting the * latter. * * @todo: Need to look into D3D viewport conventions and see if this needs to * be adapted accordingly. */ template < typename E, class A, class B, class L > void matrix_viewport(matrix<E,A,B,L>& m, E left, E right, E bottom, E top, ZClip z_clip, E n = E(0), E f = E(1)) { matrix_orthographic_LH(m, left, right, bottom, top, n, f, z_clip); /* @todo: invert(m), when available */ m = inverse(m); } ////////////////////////////////////////////////////////////////////////////// // 3D picking volume ////////////////////////////////////////////////////////////////////////////// /* Build a pick volume matrix * * When post-concatenated with a projection matrix, the pick matrix modifies * the view volume to create a 'picking volume'. This volume corresponds to * a screen rectangle centered at (pick_x, pick_y) and with dimensions * pick_widthXpick_height. * * @todo: Representation of viewport between this function and * matrix_viewport() is inconsistent (position and dimensions vs. bounds). * Should this be addressed? */ template < typename E, class A, class B, class L > void matrix_pick( matrix<E,A,B,L>& m, E pick_x, E pick_y, E pick_width, E pick_height, E viewport_x, E viewport_y, E viewport_width, E viewport_height) { typedef matrix<E,A,B,L> matrix_type; typedef typename matrix_type::value_type value_type; /* Checking */ detail::CheckMatHomogeneous3D(m); identity_transform(m); value_type inv_width = value_type(1) / pick_width; value_type inv_height = value_type(1) / pick_height; m.set_basis_element(0,0,viewport_width*inv_width); m.set_basis_element(1,1,viewport_height*inv_height); m.set_basis_element(3,0, (viewport_width+value_type(2)*(viewport_x-pick_x))*inv_width); m.set_basis_element(3,1, (viewport_height+value_type(2)*(viewport_y-pick_y))*inv_height); } #endif // ------------------------------------------------------------------------- // vim:ft=cpp:sw=2
27.175793
79
0.651432
egorodet
dab0b773ff931f5cb9db379528722734a5e3a1e6
2,488
hh
C++
include/finalfusion-cxx/Embeddings.hh
finalfusion/finalfusion-cxx
46b48fdf0bf5ffddf5b005fc0755475c06ee41a3
[ "BlueOak-1.0.0" ]
1
2019-09-05T20:56:32.000Z
2019-09-05T20:56:32.000Z
include/finalfusion-cxx/Embeddings.hh
finalfusion/finalfusion-cxx
46b48fdf0bf5ffddf5b005fc0755475c06ee41a3
[ "BlueOak-1.0.0" ]
5
2019-08-31T16:47:51.000Z
2019-09-28T07:22:00.000Z
include/finalfusion-cxx/Embeddings.hh
finalfusion/finalfusion-cxx
46b48fdf0bf5ffddf5b005fc0755475c06ee41a3
[ "BlueOak-1.0.0" ]
null
null
null
#ifndef FINALFUSION_CXX_EMBEDDINGS_HH #define FINALFUSION_CXX_EMBEDDINGS_HH #include <string> #include <vector> #include "finalfusion.h" class EmbeddingsImpl; /** * Embeddings. */ class Embeddings { public: /** * Embeddings Constructor. * * @param filename path to embeddings. * @param mmap memmap embeddings. * @throws runtime_error if Embeddings could not be read. */ Embeddings(std::string const &filename, bool mmap); /** * Method to load Embeddings from a fastText file. * * @param filename path to embeddings. * @throws runtime_error if Embeddings could not be read. */ static Embeddings read_fasttext(std::string const &filename); /** * Method to load Embeddings from a text file. * * Read the word embeddings from a text stream. The text should contain one * word embedding per line in the following format: * * *word0 component_1 component_2 ... component_n* * * @param filename path to embeddings. * @throws runtime_error if Embeddings could not be read. */ static Embeddings read_text(std::string const &filename); /** * Method to load Embeddings from a text file with dimensions. * * Read the word embeddings from a text stream. The text must contain * as the first line the shape of the embedding matrix: * * *vocab_size n_components* * * The remainder of the stream should contain one word embedding per line in * the following format: * * *word0 component_1 component_2 ... component_n* * * @param filename path to embeddings. * @throws runtime_error if Embeddings could not be read. */ static Embeddings read_text_dims(std::string const &filename); /** * Method to load Embeddings from a word2vec binary file. * * Read the word embeddings from a file in word2vec binary format. * * @param filename path to embeddings. * @throws runtime_error if Embeddings could not be read. */ static Embeddings read_word2vec(std::string const &filename); virtual ~Embeddings(); /// Return embedding dimensionality. size_t dimensions(); /** * Embedding lookup * @param word the query word * @return the embedding. Empty if none could be found. */ std::vector<float> embedding(std::string const &word); private: // Private constructor for different formats. Embeddings(EmbeddingsImpl *embeddings_impl); std::shared_ptr<EmbeddingsImpl> embeddings_impl_; }; #endif // FINALFUSION_CXX_EMBEDDINGS_HH
26.468085
78
0.704984
finalfusion
dabaaeda0c63f05510a274c79837bf3404c87e9b
208
cpp
C++
KakaotalkAdConcealer.Native/Rect.cpp
Sharp0802/KakaotalkAdConcealer
8a590803cc8d9ba430ec1c8843d1ec0953ff849a
[ "MIT" ]
2
2021-07-24T12:13:17.000Z
2021-09-09T23:20:44.000Z
KakaotalkAdConcealer.Native/Rect.cpp
Sharp0802/KakaotalkAdConcealer
8a590803cc8d9ba430ec1c8843d1ec0953ff849a
[ "MIT" ]
null
null
null
KakaotalkAdConcealer.Native/Rect.cpp
Sharp0802/KakaotalkAdConcealer
8a590803cc8d9ba430ec1c8843d1ec0953ff849a
[ "MIT" ]
null
null
null
#include "Rect.h" using namespace KakaotalkAdConcealer::Native; Rect::Rect(const long top, const long left, const long bottom, const long right) : _top(top), _left(left), _bottom(bottom), _right(right) { }
26
80
0.740385
Sharp0802
dac2a4cb380b26d30d35488f8c96f7c52e7af6c9
5,691
cpp
C++
tests/test_jsonobject.cpp
AkashMelethil/json
3f66d5f16ce44dfbba520bc8b3359c501a48408e
[ "MIT" ]
null
null
null
tests/test_jsonobject.cpp
AkashMelethil/json
3f66d5f16ce44dfbba520bc8b3359c501a48408e
[ "MIT" ]
3
2022-03-10T19:01:19.000Z
2022-03-11T02:38:43.000Z
tests/test_jsonobject.cpp
justkash/json
3f66d5f16ce44dfbba520bc8b3359c501a48408e
[ "MIT" ]
null
null
null
#include <iostream> #include <catch2/catch.hpp> #include <json/jsonobject.hpp> using namespace json; SCENARIO("JSON object can be created successfully", "[object]") { WHEN("a json object is created using the string constructor") { JsonObject obj("{\"key\":\"value\"}"); THEN("the key value pair can be retrieved") { CHECK(obj.get_string("key").get_string() == "value"); } } } SCENARIO("Values can be retrieved from a JSON object given the key", "[object]") { WHEN("a JSON object is given with key value pairs") { JsonObject obj("{\ \"name\" : \"Akash\",\ \"age\" : 20,\ \"is_tall\" : false,\ \"car\" : null,\ \"numbers\" : [1, 2, 3],\ \"object\" : {\"hello\":\"world\"}}"); THEN("the key value pairs can be retrieved") { CHECK(obj.get_string("name").get_string() == "Akash"); CHECK(obj.get_number("age").get_int() == 20); CHECK(obj.get_boolean("is_tall").get_bool() == false); CHECK(obj.get_null("car").stringify() == "null"); CHECK(obj.get_array("numbers").get_number(0).get_int() == 1); CHECK(obj.get_object("object").get_string("hello").get_string() == "world"); } } } SCENARIO("Values can set for a JSON object given the key", "[object]") { WHEN("key value pairs are set on a JSON object") { JsonObject obj; obj.set("my_key", JsonString("hello")); obj.set("number_key", JsonNumber(3.14)); obj.set("mm_kay", JsonBoolean(true)); obj.set("they", JsonNull()); obj.set("took", JsonArray("[4, 5]")); obj.set("a_jbs", JsonObject()); THEN("the key value pairs can be retrieved") { CHECK(obj.get_string("my_key").get_string() == "hello"); CHECK(obj.get_number("number_key").get_double() == 3.14); CHECK(obj.get_boolean("mm_kay").get_bool() == true); CHECK(obj.get_null("they").stringify() == "null"); CHECK(obj.get_array("took").get_number(0).get_int() == 4); CHECK(obj.get_object("a_jbs").size() == 0); } } } SCENARIO("Existence of keys can be checked in a JSON object", "[object]") { GIVEN("an empty JSON object") { JsonObject obj; WHEN("the object is checked for a given key") { const auto has_key = obj.has_key("hello"); THEN("a false is returned") { CHECK(has_key == false); } } WHEN("a new value is set for a given key") { obj.set("hello", JsonString("world")); THEN("the key exists in the JSON object") { CHECK(obj.has_key("hello") == true); } } } GIVEN("a JSON object with a key value pair") { JsonObject obj("{\"key\":342}"); WHEN("the object is checked for the given key") { const auto has_key = obj.has_key("key"); THEN("a true is returned") { CHECK(has_key == true); } } } } SCENARIO("JSON objects can be checked for empty", "[object]") { GIVEN("an empty JSON object") { JsonObject obj; WHEN("the object is checked for empty") { const auto is_empty = obj.is_empty(); THEN("a true is returned") { CHECK(is_empty == true); } } WHEN("a new value is set for a given key") { obj.set("wer", JsonString("her")); THEN("a false is returned") { CHECK(obj.is_empty() == false); } } } } SCENARIO("key value pairs can be removed from JSON objects", "[object]") { GIVEN("a JSON object with one key value pair") { JsonObject obj("{\"key\": 123}"); WHEN("a key is removed") { obj.remove("key"); THEN("the object has a size of zero") { CHECK(obj.size() == 0); } } WHEN("a new key value pair is added and then removed") { obj.set("not", JsonNumber(3.12)); obj.remove("not"); THEN("the key no longer exists in the object") { obj.remove("not"); CHECK(obj.has_key("not") == false); } } } } SCENARIO("JSON objects can be stringified successfully", "[stringify, object]") { GIVEN("an empty JSON object") { const auto str = "{}"; JsonObject obj(str); WHEN("stringify is called on the object") { const auto stringified_str = obj.stringify(); THEN("a string representation is returned") { CHECK(stringified_str == str); } } } GIVEN("an object with key value pairs") { const auto str = "{\"nu\":1, \"na\":null, \"asd\":\"hello\"}"; JsonObject obj(str); WHEN("stringify is called on the object") { const auto stringified_str = obj.stringify(); THEN("a string representation is returned") { CHECK(stringified_str == str); } } } GIVEN("an object with key value pairs with a new added key") { const auto str = "{\"key\": \"value\"}"; JsonObject obj(str); obj.set("num", JsonNumber(23)); WHEN("stringify is called on the object") { const auto expected_str = "{\"key\": \"value\",\"num\":23}"; const auto stringified_str = obj.stringify(); THEN("a string representation is returned") { CHECK(stringified_str == expected_str); } } } }
30.762162
88
0.519065
AkashMelethil
dacb05a57d5c88936318f3dc7444d918efcbf67e
17,069
cpp
C++
src/learn_vk/vulkan_api.cpp
ref2401/cg
4654377f94fe54945c33156911ca25e807c96236
[ "MIT" ]
2
2019-04-02T14:19:01.000Z
2021-05-27T13:42:20.000Z
src/learn_vk/vulkan_api.cpp
ref2401/cg
4654377f94fe54945c33156911ca25e807c96236
[ "MIT" ]
4
2016-11-05T14:17:14.000Z
2017-03-30T15:03:37.000Z
src/learn_vk/vulkan_api.cpp
ref2401/cg
4654377f94fe54945c33156911ca25e807c96236
[ "MIT" ]
null
null
null
#include "learn_vk/vulkan_api.h" #include <cassert> #include <iostream> #include <vector> #include <windows.h> #include "cg/base/base.h" PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr; PFN_vkCreateInstance vkCreateInstance; PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties; PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties; PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices; PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties; PFN_vkGetPhysicalDeviceFeatures vkGetPhysicalDeviceFeatures; PFN_vkGetPhysicalDeviceQueueFamilyProperties vkGetPhysicalDeviceQueueFamilyProperties; PFN_vkCreateDevice vkCreateDevice; PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr; PFN_vkDestroyInstance vkDestroyInstance; namespace { template<typename Func_t> Func_t load_dll_func(void* dll, const char* func_name) { assert(dll); assert(func_name); FARPROC func = GetProcAddress(reinterpret_cast<HMODULE>(dll), func_name); ENFORCE(func, "Failed to load func: ", func_name); return reinterpret_cast<Func_t>(func); } template<typename Func_t> inline Func_t load_vk_instance_func(VkInstance instance, const char* func_name) { assert(func_name); PFN_vkVoidFunction func = vkGetInstanceProcAddr(instance, func_name); ENFORCE(func, "Failed to load vulkan func: ", func_name); return reinterpret_cast<Func_t>(func); } } // namespace namespace learn_vk { // ----- Vulkan_context ----- Vulkan_context::Vulkan_context(const char* app_name) { _vulkan_dll = LoadLibrary("vulkan-1.dll"); vkGetInstanceProcAddr = load_dll_func<PFN_vkGetInstanceProcAddr>(_vulkan_dll, "vkGetInstanceProcAddr"); vkCreateInstance = load_vk_instance_func<PFN_vkCreateInstance>(nullptr, "vkCreateInstance"); vkEnumerateInstanceExtensionProperties = load_vk_instance_func<PFN_vkEnumerateInstanceExtensionProperties>(nullptr, "vkEnumerateInstanceExtensionProperties"); vkEnumerateInstanceLayerProperties = load_vk_instance_func<PFN_vkEnumerateInstanceLayerProperties>(nullptr, "vkEnumerateInstanceLayerProperties"); init_vk_instance(app_name); vkEnumeratePhysicalDevices = load_vk_instance_func<PFN_vkEnumeratePhysicalDevices>(_vk_instance, "vkEnumeratePhysicalDevices"); vkGetPhysicalDeviceProperties = load_vk_instance_func<PFN_vkGetPhysicalDeviceProperties>(_vk_instance, "vkGetPhysicalDeviceProperties"); vkGetPhysicalDeviceFeatures = load_vk_instance_func<PFN_vkGetPhysicalDeviceFeatures>(_vk_instance, "vkGetPhysicalDeviceFeatures"); vkGetPhysicalDeviceQueueFamilyProperties = load_vk_instance_func<PFN_vkGetPhysicalDeviceQueueFamilyProperties>(_vk_instance, "vkGetPhysicalDeviceQueueFamilyProperties"); vkCreateDevice = load_vk_instance_func<PFN_vkCreateDevice>(_vk_instance, "vkCreateDevice"); vkGetDeviceProcAddr = load_vk_instance_func<PFN_vkGetDeviceProcAddr>(_vk_instance, "vkGetDeviceProcAddr"); vkDestroyInstance = load_vk_instance_func<PFN_vkDestroyInstance>(_vk_instance, "vkDestroyInstance"); print_physical_devices(); } Vulkan_context::~Vulkan_context() noexcept { FreeLibrary(reinterpret_cast<HMODULE>(_vulkan_dll)); _vulkan_dll = nullptr; } void Vulkan_context::init_vk_instance(const char* app_name) { VkApplicationInfo app_info = {}; app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; app_info.pApplicationName = app_name; app_info.applicationVersion = VK_MAKE_VERSION(1, 0, 0); app_info.pEngineName = "learn_vk engine"; app_info.engineVersion = VK_MAKE_VERSION(1, 0, 0); app_info.apiVersion = VK_API_VERSION_1_0; VkInstanceCreateInfo instance_info = {}; instance_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; instance_info.pApplicationInfo = &app_info; VkResult res = vkCreateInstance(&instance_info, nullptr, &_vk_instance); assert(res == VK_SUCCESS); } void Vulkan_context::print_physical_devices() { uint32_t physical_device_count = 0; VkResult res = vkEnumeratePhysicalDevices(_vk_instance, &physical_device_count, nullptr); assert(res == VK_SUCCESS); std::cout << "----- Physical devices -----" << std::endl; std::cout << "physical_device_count: " << physical_device_count << std::endl; std::vector<VkPhysicalDevice> physical_devices(physical_device_count); res = vkEnumeratePhysicalDevices(_vk_instance, &physical_device_count, physical_devices.data()); for (uint32_t i = 0; i < physical_device_count; ++i) { VkPhysicalDeviceProperties props; vkGetPhysicalDeviceProperties(physical_devices[i], &props); std::cout << "device #" << i << std::endl; physical_device_properties(props, std::cout); std::cout << std::endl; } } // ----- funcs ----- std::ostream& physical_device_limits_to_stream(const VkPhysicalDeviceLimits& limits, std::ostream& o) { o << "maxImageDimension1D: " << limits.maxImageDimension1D << std::endl << "maxImageDimension2D: " << limits.maxImageDimension2D << std::endl << "maxImageDimension3D: " << limits.maxImageDimension3D << std::endl << "maxImageDimensionCube: " << limits.maxImageDimensionCube << std::endl << "maxImageArrayLayers: " << limits.maxImageArrayLayers << std::endl << "maxTexelBufferElements: " << limits.maxTexelBufferElements << std::endl << "maxUniformBufferRange: " << limits.maxUniformBufferRange << std::endl << "maxStorageBufferRange: " << limits.maxStorageBufferRange << std::endl << "maxPushConstantsSize: " << limits.maxPushConstantsSize << std::endl << "maxMemoryAllocationCount: " << limits.maxMemoryAllocationCount << std::endl << "maxSamplerAllocationCount: " << limits.maxSamplerAllocationCount << std::endl << "bufferImageGranularity: " << limits.bufferImageGranularity << std::endl << "sparseAddressSpaceSize: " << limits.sparseAddressSpaceSize << std::endl << "maxBoundDescriptorSets: " << limits.maxBoundDescriptorSets << std::endl << "maxPerStageDescriptorSamplers: " << limits.maxPerStageDescriptorSamplers << std::endl << "maxPerStageDescriptorUniformBuffers: " << limits.maxPerStageDescriptorUniformBuffers << std::endl << "maxPerStageDescriptorStorageBuffers: " << limits.maxPerStageDescriptorStorageBuffers << std::endl << "maxPerStageDescriptorSampledImages: " << limits.maxPerStageDescriptorSampledImages << std::endl << "maxPerStageDescriptorStorageImages: " << limits.maxPerStageDescriptorStorageImages << std::endl << "maxPerStageDescriptorInputAttachments: " << limits.maxPerStageDescriptorInputAttachments << std::endl << "maxPerStageResources: " << limits.maxPerStageResources << std::endl << "maxDescriptorSetSamplers: " << limits.maxDescriptorSetSamplers << std::endl << "maxDescriptorSetUniformBuffers: " << limits.maxDescriptorSetUniformBuffers << std::endl << "maxDescriptorSetUniformBuffersDynamic: " << limits.maxDescriptorSetUniformBuffersDynamic << std::endl << "maxDescriptorSetStorageBuffers: " << limits.maxDescriptorSetStorageBuffers << std::endl << "maxDescriptorSetStorageBuffersDynamic: " << limits.maxDescriptorSetStorageBuffersDynamic << std::endl << "maxDescriptorSetSampledImages: " << limits.maxDescriptorSetSampledImages << std::endl << "maxDescriptorSetStorageImages: " << limits.maxDescriptorSetStorageImages << std::endl << "maxDescriptorSetInputAttachments: " << limits.maxDescriptorSetInputAttachments << std::endl << "maxVertexInputAttributes: " << limits.maxVertexInputAttributes << std::endl << "maxVertexInputBindings: " << limits.maxVertexInputBindings << std::endl << "maxVertexInputAttributeOffset: " << limits.maxVertexInputAttributeOffset << std::endl << "maxVertexInputBindingStride: " << limits.maxVertexInputBindingStride << std::endl << "maxVertexOutputComponents: " << limits.maxVertexOutputComponents << std::endl << "maxTessellationGenerationLevel: " << limits.maxTessellationGenerationLevel << std::endl << "maxTessellationPatchSize: " << limits.maxTessellationPatchSize << std::endl << "maxTessellationControlPerVertexInputComponents: " << limits.maxTessellationControlPerVertexInputComponents << std::endl << "maxTessellationControlPerVertexOutputComponents: " << limits.maxTessellationControlPerVertexOutputComponents << std::endl << "maxTessellationControlPerPatchOutputComponents: " << limits.maxTessellationControlPerPatchOutputComponents << std::endl << "maxTessellationControlTotalOutputComponents: " << limits.maxTessellationControlTotalOutputComponents << std::endl << "maxTessellationEvaluationInputComponents: " << limits.maxTessellationEvaluationInputComponents << std::endl << "maxTessellationEvaluationOutputComponents: " << limits.maxTessellationEvaluationOutputComponents << std::endl << "maxGeometryShaderInvocations: " << limits.maxGeometryShaderInvocations << std::endl << "maxGeometryInputComponents: " << limits.maxGeometryInputComponents << std::endl << "maxGeometryOutputComponents: " << limits.maxGeometryOutputComponents << std::endl << "maxGeometryOutputVertices: " << limits.maxGeometryOutputVertices << std::endl << "maxGeometryTotalOutputComponents: " << limits.maxGeometryTotalOutputComponents << std::endl << "maxFragmentInputComponents: " << limits.maxFragmentInputComponents << std::endl << "maxFragmentOutputAttachments: " << limits.maxFragmentOutputAttachments << std::endl << "maxFragmentDualSrcAttachments: " << limits.maxFragmentDualSrcAttachments << std::endl << "maxFragmentCombinedOutputResources: " << limits.maxFragmentCombinedOutputResources << std::endl << "maxComputeSharedMemorySize: " << limits.maxComputeSharedMemorySize << std::endl << "maxComputeWorkGroupCount: "; array_to_stream(limits.maxComputeWorkGroupCount, o) << std::endl << "maxComputeWorkGroupInvocations: " << limits.maxComputeWorkGroupInvocations << std::endl << "maxComputeWorkGroupSize: "; array_to_stream(limits.maxComputeWorkGroupSize, o) << std::endl << "subPixelPrecisionBits: " << limits.subPixelPrecisionBits << std::endl << "subTexelPrecisionBits: " << limits.subTexelPrecisionBits << std::endl << "mipmapPrecisionBits: " << limits.mipmapPrecisionBits << std::endl << "maxDrawIndexedIndexValue: " << limits.maxDrawIndexedIndexValue << std::endl << "maxDrawIndirectCount: " << limits.maxDrawIndirectCount << std::endl << "maxSamplerLodBias: " << limits.maxSamplerLodBias << std::endl << "maxSamplerAnisotropy: " << limits.maxSamplerAnisotropy << std::endl << "maxViewports: " << limits.maxViewports << std::endl << "maxViewportDimensions: "; array_to_stream(limits.maxViewportDimensions, o) << std::endl << "viewportBoundsRange: "; array_to_stream(limits.viewportBoundsRange, o) << std::endl << "viewportSubPixelBits: " << limits.viewportSubPixelBits << std::endl << "minMemoryMapAlignment: " << limits.minMemoryMapAlignment << std::endl << "minTexelBufferOffsetAlignment: " << limits.minTexelBufferOffsetAlignment << std::endl << "minUniformBufferOffsetAlignment: " << limits.minUniformBufferOffsetAlignment << std::endl << "minStorageBufferOffsetAlignment: " << limits.minStorageBufferOffsetAlignment << std::endl << "minTexelOffset: " << limits.minTexelOffset << std::endl << "maxTexelOffset: " << limits.maxTexelOffset << std::endl << "minTexelGatherOffset: " << limits.minTexelGatherOffset << std::endl << "maxTexelGatherOffset: " << limits.maxTexelGatherOffset << std::endl << "minInterpolationOffset: " << limits.minInterpolationOffset << std::endl << "maxInterpolationOffset: " << limits.maxInterpolationOffset << std::endl << "subPixelInterpolationOffsetBits: " << limits.subPixelInterpolationOffsetBits << std::endl << "maxFramebufferWidth: " << limits.maxFramebufferWidth << std::endl << "maxFramebufferHeight: " << limits.maxFramebufferHeight << std::endl << "maxFramebufferLayers: " << limits.maxFramebufferLayers << std::endl << "framebufferColorSampleCounts: "; sample_count_flags_to_stream(limits.framebufferColorSampleCounts, o) << std::endl << "framebufferDepthSampleCounts: "; sample_count_flags_to_stream(limits.framebufferDepthSampleCounts, o) << std::endl << "framebufferStencilSampleCounts: "; sample_count_flags_to_stream(limits.framebufferStencilSampleCounts, o) << std::endl << "framebufferNoAttachmentsSampleCounts: "; sample_count_flags_to_stream(limits.framebufferNoAttachmentsSampleCounts, o) << std::endl << "maxColorAttachments: " << limits.maxColorAttachments << std::endl << "sampledImageColorSampleCounts: "; sample_count_flags_to_stream(limits.sampledImageColorSampleCounts, o) << std::endl << "sampledImageIntegerSampleCounts: "; sample_count_flags_to_stream(limits.sampledImageIntegerSampleCounts, o) << std::endl << "sampledImageDepthSampleCounts: "; sample_count_flags_to_stream(limits.sampledImageDepthSampleCounts, o) << std::endl << "sampledImageStencilSampleCounts: "; sample_count_flags_to_stream(limits.sampledImageStencilSampleCounts, o) << std::endl << "storageImageSampleCounts: "; sample_count_flags_to_stream(limits.storageImageSampleCounts, o) << std::endl << "maxSampleMaskWords: " << limits.maxSampleMaskWords << std::endl << "timestampComputeAndGraphics: " << limits.timestampComputeAndGraphics << std::endl << "timestampPeriod: " << limits.timestampPeriod << std::endl << "maxClipDistances: " << limits.maxClipDistances << std::endl << "maxCullDistances: " << limits.maxCullDistances << std::endl << "maxCombinedClipAndCullDistances: " << limits.maxCombinedClipAndCullDistances << std::endl << "discreteQueuePriorities: " << limits.discreteQueuePriorities << std::endl << "pointSizeRange: "; array_to_stream(limits.pointSizeRange, o) << std::endl << "lineWidthRange: "; array_to_stream(limits.lineWidthRange, o) << std::endl << "pointSizeGranularity: " << limits.pointSizeGranularity << std::endl << "lineWidthGranularity: " << limits.lineWidthGranularity << std::endl << "strictLines: " << limits.strictLines << std::endl << "standardSampleLocations: " << limits.standardSampleLocations << std::endl << "optimalBufferCopyOffsetAlignment: " << limits.optimalBufferCopyOffsetAlignment << std::endl << "optimalBufferCopyRowPitchAlignment: " << limits.optimalBufferCopyRowPitchAlignment << std::endl << "nonCoherentAtomSize: " << limits.nonCoherentAtomSize; return o; } std::ostream& physical_device_properties(const VkPhysicalDeviceProperties& props, std::ostream& o) { o << "apiVersion: " << props.apiVersion << std::endl << "driverVersion: " << props.driverVersion << std::endl << "vendorID: " << props.vendorID << std::endl << "deviceID: " << props.deviceID << std::endl << "deviceType: "; physical_device_type_to_stream(props.deviceType, o) << std::endl << "deviceName: " << props.deviceName[VK_MAX_PHYSICAL_DEVICE_NAME_SIZE] << std::endl << "pipelineCacheUUID: "; array_to_stream(props.pipelineCacheUUID, o) << std::endl << "limits --- " << std::endl; physical_device_limits_to_stream(props.limits, o) << std::endl << "---" << std::endl << "sparseProperties --- " << std::endl; physical_device_sparce_properties(props.sparseProperties, o) << std::endl << "---" << std::endl; return o; } std::ostream& physical_device_sparce_properties(const VkPhysicalDeviceSparseProperties& props, std::ostream& o) { o << "residencyStandard2DBlockShape: " << props.residencyStandard2DBlockShape << std::endl << "residencyStandard2DMultisampleBlockShape: " << props.residencyStandard2DMultisampleBlockShape << std::endl << "residencyStandard3DBlockShape: " << props.residencyStandard3DBlockShape << std::endl << "residencyAlignedMipSize: " << props.residencyAlignedMipSize << std::endl << "residencyNonResidentStrict: " << props.residencyNonResidentStrict << std::endl; return o; } std::ostream& physical_device_type_to_stream(const VkPhysicalDeviceType& type, std::ostream& o) { switch (type) { case VK_PHYSICAL_DEVICE_TYPE_OTHER: o << "VK_PHYSICAL_DEVICE_TYPE_OTHER"; break; case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: o << "VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU"; break; case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: o << "VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU"; break; case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: o << "VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU"; break; case VK_PHYSICAL_DEVICE_TYPE_CPU: o << "VK_PHYSICAL_DEVICE_TYPE_CPU"; break; } return o; } std::ostream& sample_count_flags_to_stream(const VkSampleCountFlags& flags, std::ostream& o) { switch (flags) { case VK_SAMPLE_COUNT_1_BIT: o << "VK_SAMPLE_COUNT_1_BIT"; break; case VK_SAMPLE_COUNT_2_BIT: o << "VK_SAMPLE_COUNT_2_BIT"; break; case VK_SAMPLE_COUNT_4_BIT: o << "VK_SAMPLE_COUNT_4_BIT"; break; case VK_SAMPLE_COUNT_8_BIT: o << "VK_SAMPLE_COUNT_8_BIT"; break; case VK_SAMPLE_COUNT_16_BIT: o << "VK_SAMPLE_COUNT_16_BIT"; break; case VK_SAMPLE_COUNT_32_BIT: o << "VK_SAMPLE_COUNT_32_BIT"; break; case VK_SAMPLE_COUNT_64_BIT: o << "VK_SAMPLE_COUNT_64_BIT"; break; } return o; } } // namespace learn_vk
58.858621
171
0.761849
ref2401
dad0cc8ef1367aa12421376f718f794ad6fdf299
52,413
cpp
C++
codemp/botlib/be_ai_goal.cpp
xScooper/Makermod
ccf9e10f441503d7b12094168c542a3696ceb314
[ "MIT" ]
11
2015-09-27T22:53:26.000Z
2021-12-25T05:04:12.000Z
codemp/botlib/be_ai_goal.cpp
xScooper/Makermod
ccf9e10f441503d7b12094168c542a3696ceb314
[ "MIT" ]
1
2016-02-14T14:28:39.000Z
2017-01-11T13:03:39.000Z
codemp/botlib/be_ai_goal.cpp
xScooper/Makermod
ccf9e10f441503d7b12094168c542a3696ceb314
[ "MIT" ]
11
2015-10-19T15:37:24.000Z
2022-02-07T05:00:20.000Z
/***************************************************************************** * name: be_ai_goal.c * * desc: goal AI * * $Archive: /MissionPack/code/botlib/be_ai_goal.c $ * $Author: Ttimo $ * $Revision: 14 $ * $Modtime: 4/13/01 4:45p $ * $Date: 4/13/01 4:45p $ * *****************************************************************************/ #include "../game/q_shared.h" #include "l_utils.h" #include "l_libvar.h" #include "l_memory.h" #include "l_log.h" #include "l_script.h" #include "l_precomp.h" #include "l_struct.h" #include "aasfile.h" #include "../game/botlib.h" #include "../game/be_aas.h" #include "be_aas_funcs.h" #include "be_interface.h" #include "be_ai_weight.h" #include "../game/be_ai_goal.h" #include "../game/be_ai_move.h" //#define DEBUG_AI_GOAL #ifdef RANDOMIZE #define UNDECIDEDFUZZY #endif //RANDOMIZE #define DROPPEDWEIGHT //minimum avoid goal time #define AVOID_MINIMUM_TIME 10 //default avoid goal time #define AVOID_DEFAULT_TIME 30 //avoid dropped goal time #define AVOID_DROPPED_TIME 10 // #define TRAVELTIME_SCALE 0.01 //item flags #define IFL_NOTFREE 1 //not in free for all #define IFL_NOTTEAM 2 //not in team play #define IFL_NOTSINGLE 4 //not in single player #define IFL_NOTBOT 8 //bot should never go for this #define IFL_ROAM 16 //bot roam goal //location in the map "target_location" typedef struct maplocation_s { vec3_t origin; int areanum; char name[MAX_EPAIRKEY]; struct maplocation_s *next; } maplocation_t; //camp spots "info_camp" typedef struct campspot_s { vec3_t origin; int areanum; char name[MAX_EPAIRKEY]; float range; float weight; float wait; float random; struct campspot_s *next; } campspot_t; //FIXME: these are game specific typedef enum { GT_FFA, // free for all GT_HOLOCRON, // holocron match GT_JEDIMASTER, // jedi master GT_DUEL, // one on one tournament GT_POWERDUEL, GT_SINGLE_PLAYER, // single player tournament //-- team games go after this -- GT_TEAM, // team deathmatch GT_SIEGE, // siege GT_CTF, // capture the flag GT_CTY, GT_MAX_GAME_TYPE }; typedef int gametype_t; typedef struct levelitem_s { int number; //number of the level item int iteminfo; //index into the item info int flags; //item flags float weight; //fixed roam weight vec3_t origin; //origin of the item int goalareanum; //area the item is in vec3_t goalorigin; //goal origin within the area int entitynum; //entity number float timeout; //item is removed after this time struct levelitem_s *prev, *next; } levelitem_t; typedef struct iteminfo_s { char classname[32]; //classname of the item char name[MAX_STRINGFIELD]; //name of the item char model[MAX_STRINGFIELD]; //model of the item int modelindex; //model index int type; //item type int index; //index in the inventory float respawntime; //respawn time vec3_t mins; //mins of the item vec3_t maxs; //maxs of the item int number; //number of the item info } iteminfo_t; #define ITEMINFO_OFS(x) (int)&(((iteminfo_t *)0)->x) fielddef_t iteminfo_fields[] = { {"name", ITEMINFO_OFS(name), FT_STRING}, {"model", ITEMINFO_OFS(model), FT_STRING}, {"modelindex", ITEMINFO_OFS(modelindex), FT_INT}, {"type", ITEMINFO_OFS(type), FT_INT}, {"index", ITEMINFO_OFS(index), FT_INT}, {"respawntime", ITEMINFO_OFS(respawntime), FT_FLOAT}, {"mins", ITEMINFO_OFS(mins), FT_FLOAT|FT_ARRAY, 3}, {"maxs", ITEMINFO_OFS(maxs), FT_FLOAT|FT_ARRAY, 3}, {0, 0, 0} }; structdef_t iteminfo_struct = { sizeof(iteminfo_t), iteminfo_fields }; typedef struct itemconfig_s { int numiteminfo; iteminfo_t *iteminfo; } itemconfig_t; //goal state typedef struct bot_goalstate_s { struct weightconfig_s *itemweightconfig; //weight config int *itemweightindex; //index from item to weight // int client; //client using this goal state int lastreachabilityarea; //last area with reachabilities the bot was in // bot_goal_t goalstack[MAX_GOALSTACK]; //goal stack int goalstacktop; //the top of the goal stack // int avoidgoals[MAX_AVOIDGOALS]; //goals to avoid float avoidgoaltimes[MAX_AVOIDGOALS]; //times to avoid the goals } bot_goalstate_t; bot_goalstate_t *botgoalstates[MAX_CLIENTS + 1]; // bk001206 - FIXME: init? //item configuration itemconfig_t *itemconfig = NULL; // bk001206 - init //level items levelitem_t *levelitemheap = NULL; // bk001206 - init levelitem_t *freelevelitems = NULL; // bk001206 - init levelitem_t *levelitems = NULL; // bk001206 - init int numlevelitems = 0; //map locations maplocation_t *maplocations = NULL; // bk001206 - init //camp spots campspot_t *campspots = NULL; // bk001206 - init //the game type int g_gametype = 0; // bk001206 - init //additional dropped item weight libvar_t *droppedweight = NULL; // bk001206 - init //======================================================================== // // Parameter: - // Returns: - // Changes Globals: - //======================================================================== bot_goalstate_t *BotGoalStateFromHandle(int handle) { if (handle <= 0 || handle > MAX_CLIENTS) { botimport.Print(PRT_FATAL, "goal state handle %d out of range\n", handle); return NULL; } //end if if (!botgoalstates[handle]) { botimport.Print(PRT_FATAL, "invalid goal state %d\n", handle); return NULL; } //end if return botgoalstates[handle]; } //end of the function BotGoalStateFromHandle //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotInterbreedGoalFuzzyLogic(int parent1, int parent2, int child) { bot_goalstate_t *p1, *p2, *c; p1 = BotGoalStateFromHandle(parent1); p2 = BotGoalStateFromHandle(parent2); c = BotGoalStateFromHandle(child); InterbreedWeightConfigs(p1->itemweightconfig, p2->itemweightconfig, c->itemweightconfig); } //end of the function BotInterbreedingGoalFuzzyLogic //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotSaveGoalFuzzyLogic(int goalstate, char *filename) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); //WriteWeightConfig(filename, gs->itemweightconfig); } //end of the function BotSaveGoalFuzzyLogic //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotMutateGoalFuzzyLogic(int goalstate, float range) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); EvolveWeightConfig(gs->itemweightconfig); } //end of the function BotMutateGoalFuzzyLogic //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== itemconfig_t *LoadItemConfig(char *filename) { int max_iteminfo; token_t token; char path[MAX_PATH]; source_t *source; itemconfig_t *ic; iteminfo_t *ii; max_iteminfo = (int) LibVarValue("max_iteminfo", "256"); if (max_iteminfo < 0) { botimport.Print(PRT_ERROR, "max_iteminfo = %d\n", max_iteminfo); max_iteminfo = 256; LibVarSet( "max_iteminfo", "256" ); } strncpy( path, filename, MAX_PATH ); PC_SetBaseFolder(BOTFILESBASEFOLDER); source = LoadSourceFile( path ); if( !source ) { botimport.Print( PRT_ERROR, "counldn't load %s\n", path ); return NULL; } //end if //initialize item config ic = (itemconfig_t *) GetClearedHunkMemory(sizeof(itemconfig_t) + max_iteminfo * sizeof(iteminfo_t)); ic->iteminfo = (iteminfo_t *) ((char *) ic + sizeof(itemconfig_t)); ic->numiteminfo = 0; //parse the item config file while(PC_ReadToken(source, &token)) { if (!strcmp(token.string, "iteminfo")) { if (ic->numiteminfo >= max_iteminfo) { SourceError(source, "more than %d item info defined\n", max_iteminfo); FreeMemory(ic); FreeSource(source); return NULL; } //end if ii = &ic->iteminfo[ic->numiteminfo]; Com_Memset(ii, 0, sizeof(iteminfo_t)); if (!PC_ExpectTokenType(source, TT_STRING, 0, &token)) { FreeMemory(ic); FreeMemory(source); return NULL; } //end if StripDoubleQuotes(token.string); strncpy(ii->classname, token.string, sizeof(ii->classname)-1); if (!ReadStructure(source, &iteminfo_struct, (char *) ii)) { FreeMemory(ic); FreeSource(source); return NULL; } //end if ii->number = ic->numiteminfo; ic->numiteminfo++; } //end if else { SourceError(source, "unknown definition %s\n", token.string); FreeMemory(ic); FreeSource(source); return NULL; } //end else } //end while FreeSource(source); // if (!ic->numiteminfo) botimport.Print(PRT_WARNING, "no item info loaded\n"); botimport.Print(PRT_MESSAGE, "loaded %s\n", path); return ic; } //end of the function LoadItemConfig //=========================================================================== // index to find the weight function of an iteminfo // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int *ItemWeightIndex(weightconfig_t *iwc, itemconfig_t *ic) { int *index, i; //initialize item weight index index = (int *) GetClearedMemory(sizeof(int) * ic->numiteminfo); for (i = 0; i < ic->numiteminfo; i++) { index[i] = FindFuzzyWeight(iwc, ic->iteminfo[i].classname); if (index[i] < 0) { Log_Write("item info %d \"%s\" has no fuzzy weight\r\n", i, ic->iteminfo[i].classname); } //end if } //end for return index; } //end of the function ItemWeightIndex //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void InitLevelItemHeap(void) { int i, max_levelitems; if (levelitemheap) FreeMemory(levelitemheap); max_levelitems = (int) LibVarValue("max_levelitems", "256"); levelitemheap = (levelitem_t *) GetClearedMemory(max_levelitems * sizeof(levelitem_t)); for (i = 0; i < max_levelitems-1; i++) { levelitemheap[i].next = &levelitemheap[i + 1]; } //end for levelitemheap[max_levelitems-1].next = NULL; // freelevelitems = levelitemheap; } //end of the function InitLevelItemHeap //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== levelitem_t *AllocLevelItem(void) { levelitem_t *li; li = freelevelitems; if (!li) { botimport.Print(PRT_FATAL, "out of level items\n"); return NULL; } //end if // freelevelitems = freelevelitems->next; Com_Memset(li, 0, sizeof(levelitem_t)); return li; } //end of the function AllocLevelItem //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void FreeLevelItem(levelitem_t *li) { li->next = freelevelitems; freelevelitems = li; } //end of the function FreeLevelItem //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void AddLevelItemToList(levelitem_t *li) { if (levelitems) levelitems->prev = li; li->prev = NULL; li->next = levelitems; levelitems = li; } //end of the function AddLevelItemToList //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void RemoveLevelItemFromList(levelitem_t *li) { if (li->prev) li->prev->next = li->next; else levelitems = li->next; if (li->next) li->next->prev = li->prev; } //end of the function RemoveLevelItemFromList //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotFreeInfoEntities(void) { maplocation_t *ml, *nextml; campspot_t *cs, *nextcs; for (ml = maplocations; ml; ml = nextml) { nextml = ml->next; FreeMemory(ml); } //end for maplocations = NULL; for (cs = campspots; cs; cs = nextcs) { nextcs = cs->next; FreeMemory(cs); } //end for campspots = NULL; } //end of the function BotFreeInfoEntities //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotInitInfoEntities(void) { char classname[MAX_EPAIRKEY]; maplocation_t *ml; campspot_t *cs; int ent, numlocations, numcampspots; BotFreeInfoEntities(); // numlocations = 0; numcampspots = 0; for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) { if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue; //map locations if (!strcmp(classname, "target_location")) { ml = (maplocation_t *) GetClearedMemory(sizeof(maplocation_t)); AAS_VectorForBSPEpairKey(ent, "origin", ml->origin); AAS_ValueForBSPEpairKey(ent, "message", ml->name, sizeof(ml->name)); ml->areanum = AAS_PointAreaNum(ml->origin); ml->next = maplocations; maplocations = ml; numlocations++; } //end if //camp spots else if (!strcmp(classname, "info_camp")) { cs = (campspot_t *) GetClearedMemory(sizeof(campspot_t)); AAS_VectorForBSPEpairKey(ent, "origin", cs->origin); //cs->origin[2] += 16; AAS_ValueForBSPEpairKey(ent, "message", cs->name, sizeof(cs->name)); AAS_FloatForBSPEpairKey(ent, "range", &cs->range); AAS_FloatForBSPEpairKey(ent, "weight", &cs->weight); AAS_FloatForBSPEpairKey(ent, "wait", &cs->wait); AAS_FloatForBSPEpairKey(ent, "random", &cs->random); cs->areanum = AAS_PointAreaNum(cs->origin); if (!cs->areanum) { botimport.Print(PRT_MESSAGE, "camp spot at %1.1f %1.1f %1.1f in solid\n", cs->origin[0], cs->origin[1], cs->origin[2]); FreeMemory(cs); continue; } //end if cs->next = campspots; campspots = cs; //AAS_DrawPermanentCross(cs->origin, 4, LINECOLOR_YELLOW); numcampspots++; } //end else if } //end for if (bot_developer) { botimport.Print(PRT_MESSAGE, "%d map locations\n", numlocations); botimport.Print(PRT_MESSAGE, "%d camp spots\n", numcampspots); } //end if } //end of the function BotInitInfoEntities //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotInitLevelItems(void) { int i, spawnflags, value; char classname[MAX_EPAIRKEY]; vec3_t origin, end; int ent, goalareanum; itemconfig_t *ic; levelitem_t *li; bsp_trace_t trace; //initialize the map locations and camp spots BotInitInfoEntities(); //initialize the level item heap InitLevelItemHeap(); levelitems = NULL; numlevelitems = 0; // ic = itemconfig; if (!ic) return; //if there's no AAS file loaded if (!AAS_Loaded()) return; //update the modelindexes of the item info for (i = 0; i < ic->numiteminfo; i++) { //ic->iteminfo[i].modelindex = AAS_IndexFromModel(ic->iteminfo[i].model); if (!ic->iteminfo[i].modelindex) { Log_Write("item %s has modelindex 0", ic->iteminfo[i].classname); } //end if } //end for for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) { if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue; // spawnflags = 0; AAS_IntForBSPEpairKey(ent, "spawnflags", &spawnflags); // for (i = 0; i < ic->numiteminfo; i++) { if (!strcmp(classname, ic->iteminfo[i].classname)) break; } //end for if (i >= ic->numiteminfo) { Log_Write("entity %s unknown item\r\n", classname); continue; } //end if //get the origin of the item if (!AAS_VectorForBSPEpairKey(ent, "origin", origin)) { botimport.Print(PRT_ERROR, "item %s without origin\n", classname); continue; } //end else // goalareanum = 0; //if it is a floating item if (spawnflags & 1) { //if the item is not floating in water if (!(AAS_PointContents(origin) & CONTENTS_WATER)) { VectorCopy(origin, end); end[2] -= 32; trace = AAS_Trace(origin, ic->iteminfo[i].mins, ic->iteminfo[i].maxs, end, -1, CONTENTS_SOLID|CONTENTS_PLAYERCLIP); //if the item not near the ground if (trace.fraction >= 1) { //if the item is not reachable from a jumppad goalareanum = AAS_BestReachableFromJumpPadArea(origin, ic->iteminfo[i].mins, ic->iteminfo[i].maxs); Log_Write("item %s reachable from jumppad area %d\r\n", ic->iteminfo[i].classname, goalareanum); //botimport.Print(PRT_MESSAGE, "item %s reachable from jumppad area %d\r\n", ic->iteminfo[i].classname, goalareanum); if (!goalareanum) continue; } //end if } //end if } //end if li = AllocLevelItem(); if (!li) return; // li->number = ++numlevelitems; li->timeout = 0; li->entitynum = 0; // li->flags = 0; AAS_IntForBSPEpairKey(ent, "notfree", &value); if (value) li->flags |= IFL_NOTFREE; AAS_IntForBSPEpairKey(ent, "notteam", &value); if (value) li->flags |= IFL_NOTTEAM; AAS_IntForBSPEpairKey(ent, "notsingle", &value); if (value) li->flags |= IFL_NOTSINGLE; AAS_IntForBSPEpairKey(ent, "notbot", &value); if (value) li->flags |= IFL_NOTBOT; if (!strcmp(classname, "item_botroam")) { li->flags |= IFL_ROAM; AAS_FloatForBSPEpairKey(ent, "weight", &li->weight); } //end if //if not a stationary item if (!(spawnflags & 1)) { if (!AAS_DropToFloor(origin, ic->iteminfo[i].mins, ic->iteminfo[i].maxs)) { botimport.Print(PRT_MESSAGE, "%s in solid at (%1.1f %1.1f %1.1f)\n", classname, origin[0], origin[1], origin[2]); } //end if } //end if //item info of the level item li->iteminfo = i; //origin of the item VectorCopy(origin, li->origin); // if (goalareanum) { li->goalareanum = goalareanum; VectorCopy(origin, li->goalorigin); } //end if else { //get the item goal area and goal origin li->goalareanum = AAS_BestReachableArea(origin, ic->iteminfo[i].mins, ic->iteminfo[i].maxs, li->goalorigin); if (!li->goalareanum) { botimport.Print(PRT_MESSAGE, "%s not reachable for bots at (%1.1f %1.1f %1.1f)\n", classname, origin[0], origin[1], origin[2]); } //end if } //end else // AddLevelItemToList(li); } //end for botimport.Print(PRT_MESSAGE, "found %d level items\n", numlevelitems); } //end of the function BotInitLevelItems //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotGoalName(int number, char *name, int size) { levelitem_t *li; if (!itemconfig) return; // for (li = levelitems; li; li = li->next) { if (li->number == number) { strncpy(name, itemconfig->iteminfo[li->iteminfo].name, size-1); name[size-1] = '\0'; return; } //end for } //end for strcpy(name, ""); return; } //end of the function BotGoalName //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotResetAvoidGoals(int goalstate) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); if (!gs) return; Com_Memset(gs->avoidgoals, 0, MAX_AVOIDGOALS * sizeof(int)); Com_Memset(gs->avoidgoaltimes, 0, MAX_AVOIDGOALS * sizeof(float)); } //end of the function BotResetAvoidGoals //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotDumpAvoidGoals(int goalstate) { int i; bot_goalstate_t *gs; char name[32]; gs = BotGoalStateFromHandle(goalstate); if (!gs) return; for (i = 0; i < MAX_AVOIDGOALS; i++) { if (gs->avoidgoaltimes[i] >= AAS_Time()) { BotGoalName(gs->avoidgoals[i], name, 32); Log_Write("avoid goal %s, number %d for %f seconds", name, gs->avoidgoals[i], gs->avoidgoaltimes[i] - AAS_Time()); } //end if } //end for } //end of the function BotDumpAvoidGoals //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotAddToAvoidGoals(bot_goalstate_t *gs, int number, float avoidtime) { int i; for (i = 0; i < MAX_AVOIDGOALS; i++) { //if the avoid goal is already stored if (gs->avoidgoals[i] == number) { gs->avoidgoals[i] = number; gs->avoidgoaltimes[i] = AAS_Time() + avoidtime; return; } //end if } //end for for (i = 0; i < MAX_AVOIDGOALS; i++) { //if this avoid goal has expired if (gs->avoidgoaltimes[i] < AAS_Time()) { gs->avoidgoals[i] = number; gs->avoidgoaltimes[i] = AAS_Time() + avoidtime; return; } //end if } //end for } //end of the function BotAddToAvoidGoals //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotRemoveFromAvoidGoals(int goalstate, int number) { int i; bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); if (!gs) return; //don't use the goals the bot wants to avoid for (i = 0; i < MAX_AVOIDGOALS; i++) { if (gs->avoidgoals[i] == number && gs->avoidgoaltimes[i] >= AAS_Time()) { gs->avoidgoaltimes[i] = 0; return; } //end if } //end for } //end of the function BotRemoveFromAvoidGoals //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== float BotAvoidGoalTime(int goalstate, int number) { int i; bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); if (!gs) return 0; //don't use the goals the bot wants to avoid for (i = 0; i < MAX_AVOIDGOALS; i++) { if (gs->avoidgoals[i] == number && gs->avoidgoaltimes[i] >= AAS_Time()) { return gs->avoidgoaltimes[i] - AAS_Time(); } //end if } //end for return 0; } //end of the function BotAvoidGoalTime //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotSetAvoidGoalTime(int goalstate, int number, float avoidtime) { bot_goalstate_t *gs; levelitem_t *li; gs = BotGoalStateFromHandle(goalstate); if (!gs) return; if (avoidtime < 0) { if (!itemconfig) return; // for (li = levelitems; li; li = li->next) { if (li->number == number) { avoidtime = itemconfig->iteminfo[li->iteminfo].respawntime; if (!avoidtime) avoidtime = AVOID_DEFAULT_TIME; if (avoidtime < AVOID_MINIMUM_TIME) avoidtime = AVOID_MINIMUM_TIME; BotAddToAvoidGoals(gs, number, avoidtime); return; } //end for } //end for return; } //end if else { BotAddToAvoidGoals(gs, number, avoidtime); } //end else } //end of the function BotSetAvoidGoalTime //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotGetLevelItemGoal(int index, char *name, bot_goal_t *goal) { levelitem_t *li; if (!itemconfig) return -1; li = levelitems; if (index >= 0) { for (; li; li = li->next) { if (li->number == index) { li = li->next; break; } //end if } //end for } //end for for (; li; li = li->next) { // if (g_gametype == GT_SINGLE_PLAYER) { if (li->flags & IFL_NOTSINGLE) continue; } else if (g_gametype >= GT_TEAM) { if (li->flags & IFL_NOTTEAM) continue; } else { if (li->flags & IFL_NOTFREE) continue; } if (li->flags & IFL_NOTBOT) continue; // if (!Q_stricmp(name, itemconfig->iteminfo[li->iteminfo].name)) { goal->areanum = li->goalareanum; VectorCopy(li->goalorigin, goal->origin); goal->entitynum = li->entitynum; VectorCopy(itemconfig->iteminfo[li->iteminfo].mins, goal->mins); VectorCopy(itemconfig->iteminfo[li->iteminfo].maxs, goal->maxs); goal->number = li->number; goal->flags = GFL_ITEM; if (li->timeout) goal->flags |= GFL_DROPPED; //botimport.Print(PRT_MESSAGE, "found li %s\n", itemconfig->iteminfo[li->iteminfo].name); return li->number; } //end if } //end for return -1; } //end of the function BotGetLevelItemGoal //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotGetMapLocationGoal(char *name, bot_goal_t *goal) { maplocation_t *ml; vec3_t mins = {-8, -8, -8}, maxs = {8, 8, 8}; for (ml = maplocations; ml; ml = ml->next) { if (!Q_stricmp(ml->name, name)) { goal->areanum = ml->areanum; VectorCopy(ml->origin, goal->origin); goal->entitynum = 0; VectorCopy(mins, goal->mins); VectorCopy(maxs, goal->maxs); return qtrue; } //end if } //end for return qfalse; } //end of the function BotGetMapLocationGoal //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotGetNextCampSpotGoal(int num, bot_goal_t *goal) { int i; campspot_t *cs; vec3_t mins = {-8, -8, -8}, maxs = {8, 8, 8}; if (num < 0) num = 0; i = num; for (cs = campspots; cs; cs = cs->next) { if (--i < 0) { goal->areanum = cs->areanum; VectorCopy(cs->origin, goal->origin); goal->entitynum = 0; VectorCopy(mins, goal->mins); VectorCopy(maxs, goal->maxs); return num+1; } //end if } //end for return 0; } //end of the function BotGetNextCampSpotGoal //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotFindEntityForLevelItem(levelitem_t *li) { int ent, modelindex; itemconfig_t *ic; aas_entityinfo_t entinfo; vec3_t dir; ic = itemconfig; if (!itemconfig) return; for (ent = AAS_NextEntity(0); ent; ent = AAS_NextEntity(ent)) { //get the model index of the entity modelindex = AAS_EntityModelindex(ent); // if (!modelindex) continue; //get info about the entity AAS_EntityInfo(ent, &entinfo); //if the entity is still moving if (entinfo.origin[0] != entinfo.lastvisorigin[0] || entinfo.origin[1] != entinfo.lastvisorigin[1] || entinfo.origin[2] != entinfo.lastvisorigin[2]) continue; // if (ic->iteminfo[li->iteminfo].modelindex == modelindex) { //check if the entity is very close VectorSubtract(li->origin, entinfo.origin, dir); if (VectorLength(dir) < 30) { //found an entity for this level item li->entitynum = ent; } //end if } //end if } //end for } //end of the function BotFindEntityForLevelItem //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== //NOTE: enum entityType_t in bg_public.h #define ET_ITEM 2 void BotUpdateEntityItems(void) { int ent, i, modelindex; vec3_t dir; levelitem_t *li, *nextli; aas_entityinfo_t entinfo; itemconfig_t *ic; //timeout current entity items if necessary for (li = levelitems; li; li = nextli) { nextli = li->next; //if it is a item that will time out if (li->timeout) { //timeout the item if (li->timeout < AAS_Time()) { RemoveLevelItemFromList(li); FreeLevelItem(li); } //end if } //end if } //end for //find new entity items ic = itemconfig; if (!itemconfig) return; // for (ent = AAS_NextEntity(0); ent; ent = AAS_NextEntity(ent)) { if (AAS_EntityType(ent) != ET_ITEM) continue; //get the model index of the entity modelindex = AAS_EntityModelindex(ent); // if (!modelindex) continue; //get info about the entity AAS_EntityInfo(ent, &entinfo); //FIXME: don't do this //skip all floating items for now //if (entinfo.groundent != ENTITYNUM_WORLD) continue; //if the entity is still moving if (entinfo.origin[0] != entinfo.lastvisorigin[0] || entinfo.origin[1] != entinfo.lastvisorigin[1] || entinfo.origin[2] != entinfo.lastvisorigin[2]) continue; //check if the entity is already stored as a level item for (li = levelitems; li; li = li->next) { //if the level item is linked to an entity if (li->entitynum && li->entitynum == ent) { //the entity is re-used if the models are different if (ic->iteminfo[li->iteminfo].modelindex != modelindex) { //remove this level item RemoveLevelItemFromList(li); FreeLevelItem(li); li = NULL; break; } //end if else { if (entinfo.origin[0] != li->origin[0] || entinfo.origin[1] != li->origin[1] || entinfo.origin[2] != li->origin[2]) { VectorCopy(entinfo.origin, li->origin); //also update the goal area number li->goalareanum = AAS_BestReachableArea(li->origin, ic->iteminfo[li->iteminfo].mins, ic->iteminfo[li->iteminfo].maxs, li->goalorigin); } //end if break; } //end else } //end if } //end for if (li) continue; //try to link the entity to a level item for (li = levelitems; li; li = li->next) { //if this level item is already linked if (li->entitynum) continue; // if (g_gametype == GT_SINGLE_PLAYER) { if (li->flags & IFL_NOTSINGLE) continue; } else if (g_gametype >= GT_TEAM) { if (li->flags & IFL_NOTTEAM) continue; } else { if (li->flags & IFL_NOTFREE) continue; } //if the model of the level item and the entity are the same if (ic->iteminfo[li->iteminfo].modelindex == modelindex) { //check if the entity is very close VectorSubtract(li->origin, entinfo.origin, dir); if (VectorLength(dir) < 30) { //found an entity for this level item li->entitynum = ent; //if the origin is different if (entinfo.origin[0] != li->origin[0] || entinfo.origin[1] != li->origin[1] || entinfo.origin[2] != li->origin[2]) { //update the level item origin VectorCopy(entinfo.origin, li->origin); //also update the goal area number li->goalareanum = AAS_BestReachableArea(li->origin, ic->iteminfo[li->iteminfo].mins, ic->iteminfo[li->iteminfo].maxs, li->goalorigin); } //end if #ifdef DEBUG Log_Write("linked item %s to an entity", ic->iteminfo[li->iteminfo].classname); #endif //DEBUG break; } //end if } //end else } //end for if (li) continue; //check if the model is from a known item for (i = 0; i < ic->numiteminfo; i++) { if (ic->iteminfo[i].modelindex == modelindex) { break; } //end if } //end for //if the model is not from a known item if (i >= ic->numiteminfo) continue; //allocate a new level item li = AllocLevelItem(); // if (!li) continue; //entity number of the level item li->entitynum = ent; //number for the level item li->number = numlevelitems + ent; //set the item info index for the level item li->iteminfo = i; //origin of the item VectorCopy(entinfo.origin, li->origin); //get the item goal area and goal origin li->goalareanum = AAS_BestReachableArea(li->origin, ic->iteminfo[i].mins, ic->iteminfo[i].maxs, li->goalorigin); //never go for items dropped into jumppads if (AAS_AreaJumpPad(li->goalareanum)) { FreeLevelItem(li); continue; } //end if //time this item out after 30 seconds //dropped items disappear after 30 seconds li->timeout = AAS_Time() + 30; //add the level item to the list AddLevelItemToList(li); //botimport.Print(PRT_MESSAGE, "found new level item %s\n", ic->iteminfo[i].classname); } //end for /* for (li = levelitems; li; li = li->next) { if (!li->entitynum) { BotFindEntityForLevelItem(li); } //end if } //end for*/ } //end of the function BotUpdateEntityItems //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotDumpGoalStack(int goalstate) { int i; bot_goalstate_t *gs; char name[32]; gs = BotGoalStateFromHandle(goalstate); if (!gs) return; for (i = 1; i <= gs->goalstacktop; i++) { BotGoalName(gs->goalstack[i].number, name, 32); Log_Write("%d: %s", i, name); } //end for } //end of the function BotDumpGoalStack //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotPushGoal(int goalstate, bot_goal_t *goal) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); if (!gs) return; if (gs->goalstacktop >= MAX_GOALSTACK-1) { botimport.Print(PRT_ERROR, "goal heap overflow\n"); BotDumpGoalStack(goalstate); return; } //end if gs->goalstacktop++; Com_Memcpy(&gs->goalstack[gs->goalstacktop], goal, sizeof(bot_goal_t)); } //end of the function BotPushGoal //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotPopGoal(int goalstate) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); if (!gs) return; if (gs->goalstacktop > 0) gs->goalstacktop--; } //end of the function BotPopGoal //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotEmptyGoalStack(int goalstate) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); if (!gs) return; gs->goalstacktop = 0; } //end of the function BotEmptyGoalStack //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotGetTopGoal(int goalstate, bot_goal_t *goal) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); if (!gs) return qfalse; if (!gs->goalstacktop) return qfalse; Com_Memcpy(goal, &gs->goalstack[gs->goalstacktop], sizeof(bot_goal_t)); return qtrue; } //end of the function BotGetTopGoal //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotGetSecondGoal(int goalstate, bot_goal_t *goal) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); if (!gs) return qfalse; if (gs->goalstacktop <= 1) return qfalse; Com_Memcpy(goal, &gs->goalstack[gs->goalstacktop-1], sizeof(bot_goal_t)); return qtrue; } //end of the function BotGetSecondGoal //=========================================================================== // pops a new long term goal on the goal stack in the goalstate // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotChooseLTGItem(int goalstate, vec3_t origin, int *inventory, int travelflags) { int areanum, t, weightnum; float weight, bestweight, avoidtime; iteminfo_t *iteminfo; itemconfig_t *ic; levelitem_t *li, *bestitem; bot_goal_t goal; bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); if (!gs) return qfalse; if (!gs->itemweightconfig) return qfalse; //get the area the bot is in areanum = BotReachabilityArea(origin, gs->client); //if the bot is in solid or if the area the bot is in has no reachability links if (!areanum || !AAS_AreaReachability(areanum)) { //use the last valid area the bot was in areanum = gs->lastreachabilityarea; } //end if //remember the last area with reachabilities the bot was in gs->lastreachabilityarea = areanum; //if still in solid if (!areanum) return qfalse; //the item configuration ic = itemconfig; if (!itemconfig) return qfalse; //best weight and item so far bestweight = 0; bestitem = NULL; Com_Memset(&goal, 0, sizeof(bot_goal_t)); //go through the items in the level for (li = levelitems; li; li = li->next) { if (g_gametype == GT_SINGLE_PLAYER) { if (li->flags & IFL_NOTSINGLE) continue; } else if (g_gametype >= GT_TEAM) { if (li->flags & IFL_NOTTEAM) continue; } else { if (li->flags & IFL_NOTFREE) continue; } if (li->flags & IFL_NOTBOT) continue; //if the item is not in a possible goal area if (!li->goalareanum) continue; //FIXME: is this a good thing? added this for items that never spawned into the game (f.i. CTF flags in obelisk) if (!li->entitynum && !(li->flags & IFL_ROAM)) continue; //get the fuzzy weight function for this item iteminfo = &ic->iteminfo[li->iteminfo]; weightnum = gs->itemweightindex[iteminfo->number]; if (weightnum < 0) continue; #ifdef UNDECIDEDFUZZY weight = FuzzyWeightUndecided(inventory, gs->itemweightconfig, weightnum); #else weight = FuzzyWeight(inventory, gs->itemweightconfig, weightnum); #endif //UNDECIDEDFUZZY #ifdef DROPPEDWEIGHT //HACK: to make dropped items more attractive if (li->timeout) weight += droppedweight->value; #endif //DROPPEDWEIGHT //use weight scale for item_botroam if (li->flags & IFL_ROAM) weight *= li->weight; // if (weight > 0) { //get the travel time towards the goal area t = AAS_AreaTravelTimeToGoalArea(areanum, origin, li->goalareanum, travelflags); //if the goal is reachable if (t > 0) { //if this item won't respawn before we get there avoidtime = BotAvoidGoalTime(goalstate, li->number); if (avoidtime - t * 0.009 > 0) continue; // weight /= (float) t * TRAVELTIME_SCALE; // if (weight > bestweight) { bestweight = weight; bestitem = li; } //end if } //end if } //end if } //end for //if no goal item found if (!bestitem) { /* //if not in lava or slime if (!AAS_AreaLava(areanum) && !AAS_AreaSlime(areanum)) { if (AAS_RandomGoalArea(areanum, travelflags, &goal.areanum, goal.origin)) { VectorSet(goal.mins, -15, -15, -15); VectorSet(goal.maxs, 15, 15, 15); goal.entitynum = 0; goal.number = 0; goal.flags = GFL_ROAM; goal.iteminfo = 0; //push the goal on the stack BotPushGoal(goalstate, &goal); // #ifdef DEBUG botimport.Print(PRT_MESSAGE, "chosen roam goal area %d\n", goal.areanum); #endif //DEBUG return qtrue; } //end if } //end if */ return qfalse; } //end if //create a bot goal for this item iteminfo = &ic->iteminfo[bestitem->iteminfo]; VectorCopy(bestitem->goalorigin, goal.origin); VectorCopy(iteminfo->mins, goal.mins); VectorCopy(iteminfo->maxs, goal.maxs); goal.areanum = bestitem->goalareanum; goal.entitynum = bestitem->entitynum; goal.number = bestitem->number; goal.flags = GFL_ITEM; if (bestitem->timeout) goal.flags |= GFL_DROPPED; if (bestitem->flags & IFL_ROAM) goal.flags |= GFL_ROAM; goal.iteminfo = bestitem->iteminfo; //if it's a dropped item if (bestitem->timeout) { avoidtime = AVOID_DROPPED_TIME; } //end if else { avoidtime = iteminfo->respawntime; if (!avoidtime) avoidtime = AVOID_DEFAULT_TIME; if (avoidtime < AVOID_MINIMUM_TIME) avoidtime = AVOID_MINIMUM_TIME; } //end else //add the chosen goal to the goals to avoid for a while BotAddToAvoidGoals(gs, bestitem->number, avoidtime); //push the goal on the stack BotPushGoal(goalstate, &goal); // return qtrue; } //end of the function BotChooseLTGItem //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotChooseNBGItem(int goalstate, vec3_t origin, int *inventory, int travelflags, bot_goal_t *ltg, float maxtime) { int areanum, t, weightnum, ltg_time; float weight, bestweight, avoidtime; iteminfo_t *iteminfo; itemconfig_t *ic; levelitem_t *li, *bestitem; bot_goal_t goal; bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); if (!gs) return qfalse; if (!gs->itemweightconfig) return qfalse; //get the area the bot is in areanum = BotReachabilityArea(origin, gs->client); //if the bot is in solid or if the area the bot is in has no reachability links if (!areanum || !AAS_AreaReachability(areanum)) { //use the last valid area the bot was in areanum = gs->lastreachabilityarea; } //end if //remember the last area with reachabilities the bot was in gs->lastreachabilityarea = areanum; //if still in solid if (!areanum) return qfalse; // if (ltg) ltg_time = AAS_AreaTravelTimeToGoalArea(areanum, origin, ltg->areanum, travelflags); else ltg_time = 99999; //the item configuration ic = itemconfig; if (!itemconfig) return qfalse; //best weight and item so far bestweight = 0; bestitem = NULL; Com_Memset(&goal, 0, sizeof(bot_goal_t)); //go through the items in the level for (li = levelitems; li; li = li->next) { if (g_gametype == GT_SINGLE_PLAYER) { if (li->flags & IFL_NOTSINGLE) continue; } else if (g_gametype >= GT_TEAM) { if (li->flags & IFL_NOTTEAM) continue; } else { if (li->flags & IFL_NOTFREE) continue; } if (li->flags & IFL_NOTBOT) continue; //if the item is in a possible goal area if (!li->goalareanum) continue; //FIXME: is this a good thing? added this for items that never spawned into the game (f.i. CTF flags in obelisk) if (!li->entitynum && !(li->flags & IFL_ROAM)) continue; //get the fuzzy weight function for this item iteminfo = &ic->iteminfo[li->iteminfo]; weightnum = gs->itemweightindex[iteminfo->number]; if (weightnum < 0) continue; // #ifdef UNDECIDEDFUZZY weight = FuzzyWeightUndecided(inventory, gs->itemweightconfig, weightnum); #else weight = FuzzyWeight(inventory, gs->itemweightconfig, weightnum); #endif //UNDECIDEDFUZZY #ifdef DROPPEDWEIGHT //HACK: to make dropped items more attractive if (li->timeout) weight += droppedweight->value; #endif //DROPPEDWEIGHT //use weight scale for item_botroam if (li->flags & IFL_ROAM) weight *= li->weight; // if (weight > 0) { //get the travel time towards the goal area t = AAS_AreaTravelTimeToGoalArea(areanum, origin, li->goalareanum, travelflags); //if the goal is reachable if (t > 0 && t < maxtime) { //if this item won't respawn before we get there avoidtime = BotAvoidGoalTime(goalstate, li->number); if (avoidtime - t * 0.009 > 0) continue; // weight /= (float) t * TRAVELTIME_SCALE; // if (weight > bestweight) { t = 0; if (ltg && !li->timeout) { //get the travel time from the goal to the long term goal t = AAS_AreaTravelTimeToGoalArea(li->goalareanum, li->goalorigin, ltg->areanum, travelflags); } //end if //if the travel back is possible and doesn't take too long if (t <= ltg_time) { bestweight = weight; bestitem = li; } //end if } //end if } //end if } //end if } //end for //if no goal item found if (!bestitem) return qfalse; //create a bot goal for this item iteminfo = &ic->iteminfo[bestitem->iteminfo]; VectorCopy(bestitem->goalorigin, goal.origin); VectorCopy(iteminfo->mins, goal.mins); VectorCopy(iteminfo->maxs, goal.maxs); goal.areanum = bestitem->goalareanum; goal.entitynum = bestitem->entitynum; goal.number = bestitem->number; goal.flags = GFL_ITEM; if (bestitem->timeout) goal.flags |= GFL_DROPPED; if (bestitem->flags & IFL_ROAM) goal.flags |= GFL_ROAM; goal.iteminfo = bestitem->iteminfo; //if it's a dropped item if (bestitem->timeout) { avoidtime = AVOID_DROPPED_TIME; } //end if else { avoidtime = iteminfo->respawntime; if (!avoidtime) avoidtime = AVOID_DEFAULT_TIME; if (avoidtime < AVOID_MINIMUM_TIME) avoidtime = AVOID_MINIMUM_TIME; } //end else //add the chosen goal to the goals to avoid for a while BotAddToAvoidGoals(gs, bestitem->number, avoidtime); //push the goal on the stack BotPushGoal(goalstate, &goal); // return qtrue; } //end of the function BotChooseNBGItem //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotTouchingGoal(vec3_t origin, bot_goal_t *goal) { int i; vec3_t boxmins, boxmaxs; vec3_t absmins, absmaxs; vec3_t safety_maxs = {0, 0, 0}; //{4, 4, 10}; vec3_t safety_mins = {0, 0, 0}; //{-4, -4, 0}; AAS_PresenceTypeBoundingBox(PRESENCE_NORMAL, boxmins, boxmaxs); VectorSubtract(goal->mins, boxmaxs, absmins); VectorSubtract(goal->maxs, boxmins, absmaxs); VectorAdd(absmins, goal->origin, absmins); VectorAdd(absmaxs, goal->origin, absmaxs); //make the box a little smaller for safety VectorSubtract(absmaxs, safety_maxs, absmaxs); VectorSubtract(absmins, safety_mins, absmins); for (i = 0; i < 3; i++) { if (origin[i] < absmins[i] || origin[i] > absmaxs[i]) return qfalse; } //end for return qtrue; } //end of the function BotTouchingGoal //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotItemGoalInVisButNotVisible(int viewer, vec3_t eye, vec3_t viewangles, bot_goal_t *goal) { aas_entityinfo_t entinfo; bsp_trace_t trace; vec3_t middle; if (!(goal->flags & GFL_ITEM)) return qfalse; // VectorAdd(goal->mins, goal->mins, middle); VectorScale(middle, 0.5, middle); VectorAdd(goal->origin, middle, middle); // trace = AAS_Trace(eye, NULL, NULL, middle, viewer, CONTENTS_SOLID); //if the goal middle point is visible if (trace.fraction >= 1) { //the goal entity number doesn't have to be valid //just assume it's valid if (goal->entitynum <= 0) return qfalse; // //if the entity data isn't valid AAS_EntityInfo(goal->entitynum, &entinfo); //NOTE: for some wacko reason entities are sometimes // not updated //if (!entinfo.valid) return qtrue; if (entinfo.ltime < AAS_Time() - 0.5) return qtrue; } //end if return qfalse; } //end of the function BotItemGoalInVisButNotVisible //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotResetGoalState(int goalstate) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); if (!gs) return; Com_Memset(gs->goalstack, 0, MAX_GOALSTACK * sizeof(bot_goal_t)); gs->goalstacktop = 0; BotResetAvoidGoals(goalstate); } //end of the function BotResetGoalState //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotLoadItemWeights(int goalstate, char *filename) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); if (!gs) return BLERR_CANNOTLOADITEMWEIGHTS; //load the weight configuration gs->itemweightconfig = ReadWeightConfig(filename); if (!gs->itemweightconfig) { botimport.Print(PRT_FATAL, "couldn't load weights\n"); return BLERR_CANNOTLOADITEMWEIGHTS; } //end if //if there's no item configuration if (!itemconfig) return BLERR_CANNOTLOADITEMWEIGHTS; //create the item weight index gs->itemweightindex = ItemWeightIndex(gs->itemweightconfig, itemconfig); //everything went ok return BLERR_NOERROR; } //end of the function BotLoadItemWeights //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotFreeItemWeights(int goalstate) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); if (!gs) return; if (gs->itemweightconfig) FreeWeightConfig(gs->itemweightconfig); if (gs->itemweightindex) FreeMemory(gs->itemweightindex); } //end of the function BotFreeItemWeights //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotAllocGoalState(int client) { int i; for (i = 1; i <= MAX_CLIENTS; i++) { if (!botgoalstates[i]) { botgoalstates[i] = (struct bot_goalstate_s *)GetClearedMemory(sizeof(bot_goalstate_t)); botgoalstates[i]->client = client; return i; } //end if } //end for return 0; } //end of the function BotAllocGoalState //======================================================================== // // Parameter: - // Returns: - // Changes Globals: - //======================================================================== void BotFreeGoalState(int handle) { if (handle <= 0 || handle > MAX_CLIENTS) { botimport.Print(PRT_FATAL, "goal state handle %d out of range\n", handle); return; } //end if if (!botgoalstates[handle]) { botimport.Print(PRT_FATAL, "invalid goal state handle %d\n", handle); return; } //end if BotFreeItemWeights(handle); FreeMemory(botgoalstates[handle]); botgoalstates[handle] = NULL; } //end of the function BotFreeGoalState //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int BotSetupGoalAI(void) { char *filename; //check if teamplay is on g_gametype = LibVarValue("g_gametype", "0"); //item configuration file filename = LibVarString("itemconfig", "items.c"); //load the item configuration itemconfig = LoadItemConfig(filename); if (!itemconfig) { botimport.Print(PRT_FATAL, "couldn't load item config\n"); return BLERR_CANNOTLOADITEMCONFIG; } //end if // droppedweight = LibVar("droppedweight", "1000"); //everything went ok return BLERR_NOERROR; } //end of the function BotSetupGoalAI //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void BotShutdownGoalAI(void) { int i; if (itemconfig) FreeMemory(itemconfig); itemconfig = NULL; if (levelitemheap) FreeMemory(levelitemheap); levelitemheap = NULL; freelevelitems = NULL; levelitems = NULL; numlevelitems = 0; BotFreeInfoEntities(); for (i = 1; i <= MAX_CLIENTS; i++) { if (botgoalstates[i]) { BotFreeGoalState(i); } //end if } //end for } //end of the function BotShutdownGoalAI
29.021595
123
0.58268
xScooper
dad50216154f752e4a380839952b4e180a0ae33f
6,390
cpp
C++
TriangleSection/Util/FileUtil.cpp
WalterWhiteCSU/triangleDomain
ca497d86df3317ddc3453677a023b1fa7a581991
[ "MIT" ]
null
null
null
TriangleSection/Util/FileUtil.cpp
WalterWhiteCSU/triangleDomain
ca497d86df3317ddc3453677a023b1fa7a581991
[ "MIT" ]
null
null
null
TriangleSection/Util/FileUtil.cpp
WalterWhiteCSU/triangleDomain
ca497d86df3317ddc3453677a023b1fa7a581991
[ "MIT" ]
null
null
null
// // Created by WalterWhite on 2021/6/7. // #include "FileUtil.h" #include <iostream> #include <string> #include <sstream> #include <fstream> // rapidjson #include <rapidjson/document.h> #include <rapidjson/writer.h> #include <rapidjson/stringbuffer.h> #include <rapidjson/filewritestream.h> #include <rapidjson/prettywriter.h> #include <rapidjson/filereadstream.h> namespace TriangleDomain { std::vector<std::vector<SamplingData>> FileUtil::ReadImage(std::string fileName) { std::vector<std::vector<SamplingData>> result; cv::Mat image; image = cv::imread(fileName, cv::IMREAD_GRAYSCALE); if (image.data == nullptr) { std::cerr << "Failed To Read Image!" << std::endl; return result; } //显示图片 // cv::imshow("Origin Image", image); // cv::waitKey(); int row = image.rows; int col = image.cols; for (int i = 0; i < row; ++i) { std::vector<SamplingData> model; for (int j = 0; j < col; ++j) { model.push_back(SamplingData(new Point(i + 0.5f, j + 0.5f), image.at<uchar>(i, j))); // model.push_back(SamplingData(new Point(i + 0.5f, j + 0.5f), 0.f)); } result.push_back(model); } return result; } void FileUtil::ShowReconstructionImage(std::vector<std::vector<SamplingData>> reconstructionImage) { int row = reconstructionImage.size(); int col = reconstructionImage[0].size(); cv::Mat image(row, col, CV_8UC1); for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { image.at<uchar>(i, j) = reconstructionImage[i][j].getValue(); } } // cv::imshow("Reconstruction Image0", image); // cv::waitKey(); } void FileUtil::SaveImageBySampleData(std::vector<SamplingData> dataList, int imgSize, std::string path) { cv::Mat image(imgSize, imgSize, CV_8UC1); for (auto model: dataList) { image.at<uchar>(model.getPoint()->getX(), model.getPoint()->getY()) = model.getValue(); } cv::imwrite(path, image); } void FileUtil::SaveFittingInfo(std::vector<FittingInfo> data, std::string path) { std::string filePath = path + "\\data.json"; std::cerr << "Write" << std::endl; rapidjson::Document doc; doc.SetObject(); rapidjson::Document::AllocatorType &allocator = doc.GetAllocator(); int i = 1; // 对每一条数据进行读取 for (const auto model: data) { rapidjson::Value jModel(rapidjson::kArrayType); jModel.SetObject(); // 写入点集 rapidjson::Value pointList(rapidjson::kArrayType); for (const auto point:model.getPointList()) { pointList.PushBack(point.getX(), allocator); pointList.PushBack(point.getY(), allocator); } jModel.AddMember("PointList", pointList, allocator); // 写入面积坐标 rapidjson::Value areaList(rapidjson::kArrayType); for (const auto area:model.getAreaPointList()) { areaList.PushBack(area.getU(), allocator); areaList.PushBack(area.getV(), allocator); areaList.PushBack(area.getW(), allocator); } jModel.AddMember("AreaList", areaList, allocator); // 写入三角形 rapidjson::Value triangle(rapidjson::kArrayType); triangle.PushBack(model.getTriangle().getVertexA()->getX(), allocator); triangle.PushBack(model.getTriangle().getVertexA()->getY(), allocator); triangle.PushBack(model.getTriangle().getVertexB()->getX(), allocator); triangle.PushBack(model.getTriangle().getVertexB()->getY(), allocator); triangle.PushBack(model.getTriangle().getVertexC()->getX(), allocator); triangle.PushBack(model.getTriangle().getVertexC()->getY(), allocator); jModel.AddMember("Triangle", triangle, allocator); // 写入拟合参数 rapidjson::Value fittingList(rapidjson::kArrayType); for (const auto fitting:model.getFittingParam()) { fittingList.PushBack(fitting, allocator); } jModel.AddMember("Fitting", fittingList, allocator); // 写入定位 rapidjson::Value location(rapidjson::kArrayType); for (const auto loc:model.getTriangleLocation()) { location.PushBack(loc, allocator); } jModel.AddMember("Location", location, allocator); // 写入误差 rapidjson::Value error(rapidjson::kArrayType); error.PushBack(model.getError(), allocator); jModel.AddMember("Error", error, allocator); doc.AddMember("ele", jModel, allocator); } // 写文件 FILE *fp = fopen(filePath.c_str(), "w"); char writeBuffer[65535]; rapidjson::FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer)); rapidjson::PrettyWriter<rapidjson::FileWriteStream> writer(os); doc.Accept(writer); fclose(fp); } void FileUtil::SaveImage(std::vector<std::vector<std::vector<SamplingData>>> imageList, std::string path) { int i = 1; for (const auto image:imageList) { cv::Mat imageMat(image.size(), image[0].size(), CV_8UC1); for (size_t row = 0; row < image.size(); row++) { for (size_t col = 0; col < image[row].size(); col++) { imageMat.at<uchar>(image[row][col].getPoint()->getX(), image[row][col].getPoint()->getY()) = image[row][col].getValue(); } } std::string filePath = path + "\\" + std::to_string(i) + ".jpg"; cv::imwrite(filePath, imageMat); i++; } } void FileUtil::WriteTiCSV(std::vector<std::vector<std::string>> src, std::string filePath) { std::ofstream outFile; outFile.open(filePath, std::ios::out); for (const auto dataRow:src) { for (size_t i = 0; i < dataRow.size() - 1; i++) { outFile << dataRow[i] << ","; } outFile << dataRow[dataRow.size() - 1] << std::endl; } outFile.close(); } }
35.5
111
0.561189
WalterWhiteCSU
dae30cb754a4aff9b9578191483fd1a1f0fa4501
416
hpp
C++
src/serca_higg.hpp
anupgp/astron
5ef1b113b5025f5e0477a1fb2b5202fadbc5335c
[ "MIT" ]
null
null
null
src/serca_higg.hpp
anupgp/astron
5ef1b113b5025f5e0477a1fb2b5202fadbc5335c
[ "MIT" ]
null
null
null
src/serca_higg.hpp
anupgp/astron
5ef1b113b5025f5e0477a1fb2b5202fadbc5335c
[ "MIT" ]
null
null
null
// Time-stamp: <2019-01-04 13:50:34 macbookair> // Units: all SI units - seconds, Volts, Ampere, Meters, Simenes, Farads // Ref: higgins2006; bartol2015 #ifndef SERCA_HIGG_HPP_INCLUDED #define SERCA_HIGG_HPP_INCLUDED #include "data_types.hpp" #include "include/new_insilico.hpp" class serca_higg { public: static void current(state_type &variables, state_type &dxdt, const double t, unsigned index); }; #endif
23.111111
95
0.762019
anupgp
dae41734f4bf849448ab4a61ed2ef7c2b9b10de6
315
cpp
C++
bit_manipulation/first.cpp
sahilduhan/Learn-C-plus-plus
80dba2ee08b36985deb297293a0318da5d6ace94
[ "RSA-MD" ]
null
null
null
bit_manipulation/first.cpp
sahilduhan/Learn-C-plus-plus
80dba2ee08b36985deb297293a0318da5d6ace94
[ "RSA-MD" ]
null
null
null
bit_manipulation/first.cpp
sahilduhan/Learn-C-plus-plus
80dba2ee08b36985deb297293a0318da5d6ace94
[ "RSA-MD" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int bit_test(int n, int pos) { return ((n & (1 << pos)) != 0); } int set_bit(int n, int pos) { return ((n | (1 << pos))); } int clear_bit(int n, int pos) { return ; } int main() { cout << bit_test(5, 2) << " "; cout << set_bit(5, 1); return 0; }
15.75
35
0.526984
sahilduhan
daead5746a200b0abff2aa59ef5a0795bd404be7
37
cpp
C++
src/mqqrl_6.cpp
mganger/quantum-multiple-q-learning
08d6c010cd9082b58f79bdc2da45a1cd6d1f512f
[ "MIT" ]
1
2019-12-27T20:59:00.000Z
2019-12-27T20:59:00.000Z
src/mqqrl_6.cpp
mganger/quantum-multiple-q-learning
08d6c010cd9082b58f79bdc2da45a1cd6d1f512f
[ "MIT" ]
null
null
null
src/mqqrl_6.cpp
mganger/quantum-multiple-q-learning
08d6c010cd9082b58f79bdc2da45a1cd6d1f512f
[ "MIT" ]
null
null
null
#include "mqqrl.h" MAIN(mqqrl< 6 >)
12.333333
19
0.621622
mganger
daebd619f89f16e31af2ba1cc08b787262e69632
11,247
cpp
C++
opencv_src/modules/features2d/src/img_align/Settings.cpp
10dimensions/imgalign
99f18a15a06855dc5ba764679a1d75bfd0d2e782
[ "MIT" ]
163
2019-06-04T02:00:58.000Z
2022-03-26T14:23:10.000Z
opencv_src/modules/features2d/src/img_align/Settings.cpp
shadowzhougit/imgalign
99f18a15a06855dc5ba764679a1d75bfd0d2e782
[ "MIT" ]
8
2019-11-03T10:16:58.000Z
2022-03-16T17:00:14.000Z
opencv_src/modules/features2d/src/img_align/Settings.cpp
shadowzhougit/imgalign
99f18a15a06855dc5ba764679a1d75bfd0d2e782
[ "MIT" ]
29
2019-01-08T05:43:58.000Z
2022-03-24T00:07:03.000Z
#include "Settings.h" #include <numeric> #include "EnumTypes.h" #include "LogUtils.h" namespace imgalign { Settings::Settings() { init(); } void Settings::init() { paramValuesExt = { { eImageCap, { 300000.0f, "imageCap" } }, { eImageCapInput, { 350000.0f, "imageCapInput" } }, { eOpenCvType, { 812.0f, "OpenCvType" } }, { eSift_featuresN, { 0.0f, "Sift_featuresN" } }, { eSift_octaveLayersN, { 3.0f, "Sift_octaveLayersN" } }, { eSift_contrastThresh, { 0.04f, "Sift_contrastThresh" } }, { eSift_edgeThresh, { 10.0f, "Sift_edgeThresh" } }, { eSift_sigma, { 1.6f, "Sift_sigma" } }, { eSurf_hessianThresh, { 100.0f, "Surf_hessianThresh" } }, { eSurf_octavesN, { 4.0f, "Surf_octavesN" } }, { eSurf_octaveLayersN, { 3.0f, "Surf_octaveLayersN" } }, { eSurf_extended, { 0.0f, "Surf_extended" } }, { eOrb_featuresN, { 500.0f, "Orb_featuresN" } }, { eOrb_scale, { 1.2f, "Orb_scale" } }, { eOrb_levelsN, { 8.0f, "Orb_levelsN" } }, { eOrb_edgeThresh, { 31.0f, "Orb_edgeThresh" } }, { eOrb_patchSize, { 31.0f, "Orb_patchSize" } }, { eBrisk_thresh, { 30.0f, "Brisk_thresh" } }, { eBrisk_octavesN, { 3.0f, "Brisk_octavesN" } }, { eBrisk_patternScale, { 1.0f, "Brisk_patternScale" } }, { eKaze_thresh, { 0.001f, "Kaze_thresh" } }, { eKaze_octavesN, { 4.0f , "Kaze_octavesN" } }, { eKaze_octaveLayersN, { 4.0f, "Kaze_octaveLayersN" } }, { eAkaze_thresh, { 0.001f, "Akaze_thresh" } }, { eAkaze_octavesN, { 4.0f, "Akaze_octavesN" } }, { eAkaze_octaveLayersN, { 4.0f, "Akaze_octaveLayersN" } }, { eMatchFilterSpreadAuto, { 1.0f, "MatchFilterSpreadAuto" } }, { eMatchFilterSpreadFactor, { 2.2f, "MatchFilterSpreadFactor" } }, { eMatchFilterMinMatchesToRetain, { 300.0f, "MatchFilterMinMatchesToRetain" } }, { eMatchFilterMaxMatchesToRetain, { 800.0f, "MatchFilterMaxMatchesToRetain" } }, { eFloodFillTolerance, { 10.0f, "FloodFillTolerance" } }, { eAlignSelectionOverlay, { (float)0.0f, "AlignSelectionOverlay" } }, { eLogInfoEnabled, { (float)0.0f, "LogInfoEnabled" } }, { eLogErrorEnabled, { (float)1.0f, "LogErrorEnabled" } }, { eLogAssertEnabled, { (float)1.0f, "LogAssertEnabled" } }, { eLogExternEnabled, { (float)0.0f, "LogExternEnabled" } }, { eDetType, { (float)eDetType_sift, "DetType" } }, { eDesType, { (float)eDesType_sift, "DesType" } }, { eMatcherType, { (float)eMatcherType_auto, "MatcherType" } }, { eTransformFinderType, { (float)eTransformFinderType_ransac, "TransformFinderType" } }, { eStitch_projection, { (float)eStitch_projectionTypeSpherical, "Stitch_projection" } }, { eStitch_projection2, { (float)eStitch_projectionTypeSpherical, "Stitch_projection2" } }, { eStitch_seamBlend, { 1.0f, "Stitch_seamBlend" } }, { eStitch_colorTransfer, { 0.0f, "Stitch_colorTransfer" } }, { eStitch_viewAngle1, { 45.0f, "Stitch_viewAngle1" } }, { eStitch_yaw1, { 0.0f, "Stitch_yaw1" } }, { eStitch_pitch1, { 0.0f, "Stitch_pitch1" } }, { eStitch_viewAngle2, { 45.0f, "viewAngle2" } }, { eStitch_yaw2, { 0.0f, "Stitch_yaw2" } }, { eStitch_pitch2, { 0.0f, "Stitch_pitch2" } }, { eStitch_yaw2Auto, { 1.0f, "Yaw 2 auto" } }, { eStitch_pitch2Auto, { 1.0f, "Pitch 2 auto" } }, { eMultiStitch_seamFinderType, { (float)eSeamFinderType_Vornoi, "MultiStitch_seamFinderType" } }, { eMultiStitch_projection, { (float)eStitch_projectionTypeSpherical, "MultiStitch_projection" } }, { eMultiStitch_rectifyPerspective, { 0.0f, "MultiStitch_rectifyPerspective" } }, { eMultiStitch_camEstimate, { 1.0f, "eMultiStitch_camEstimate" } }, { eMultiStitch_bundleAdjustType, { (float)eBundleAdjustType_rayBlacklist, "MultiStitch_bundleAdjustType" } }, { eMultiStitch_waveCorrection, { (float)eWaveCorrectionType_H, "MultiStitch_waveCorrection" } }, { eMultiStitch_seamBlend, { 1.0f, "MultiStitch_seamBlend" } }, { eMultiStitch_colorTransfer, { 0.0f, "MultiStitch_colorTransfer" } }, { eMultiStitch_calcImageOrder, { 1.0f, "MultiStitch_calcImageOrder" } }, { eMultiStitch_calcCenterImage, { 1.0f, "MultiStitch_calcCenterImage" } }, { eMultiStitch_warpFirst, { 0.0f, "MultiStitch_warpFirst" } }, { eMultiStitch_confidenceThresh, { 0.4f, "MultiStitch_confidenceThresh" } }, { eMultiStitch_confidenceThreshCam, { 1.2f, "MultiStitch_confidenceThreshCam" } }, { eMultiStitch_confidenceThreshCamManual, { 0.0f, "MultiStitch_confidenceThreshCamAuto" } }, { eMultiStitch_inputImagesMatchReach, { 0.0f, "MultiStitch_inputImagesMatchReach" } }, { eMultiStitch_exposureCompensator, { 0.0f, "MultiStitch_exposureCompensator" } }, //{ eMultiStitch_blendType, { (float)eBlendType_multiBand, "MultiStitch_blendType"}}, { eMultiStitch_blendStrength, { 5.0f, "MultiStitch_blendStrength" } }, { eMultiStitch_rectifyStretch, { 0.0f, "MultiStitch_rectifyStretch" } }, { eMultiStitch_maxRectangle, { 0.0f, "MultiStitch_crop" } }, { eMultiStitch_limitResultPreview, { 800000.0f, "MultiStitch_limitResultPreview" } }, { eMultiStitch_limitInputView, { 100000.0f, "MultiStitch_limitInputView" } }, { eMultiStitch_disposeInputImages, { 0.0f, "MultiStitch_disposeInputImages" } }, { eMultiStitch_limitLiveStitchingPreview, { 200000.0f, "MultiStitch_limitLiveStitchingPreview" } }, { eMultiStitch_preserveAlphaChannelValue, { 0.0f, "MultiStitch_preserveAlphaChannelValue" } }, { eMultiStitch_liveUpdateCycle, { 5.0f, "MultiStitch_liveUpdateCycle" } } }; } DetType Settings::getDetType(ParamType eDetType) { switch(eDetType) { case eDetType_sift: return DetType::DET_SIFT; case eDetType_surf: return DetType::DET_SURF; case eDetType_orb: return DetType::DET_ORB; case eDetType_brisk: return DetType::DET_BRISK; case eDetType_kaze: return DetType::DET_KAZE; case eDetType_akaze: return DetType::DET_AKAZE; default: return DetType::DET_SIFT; } } DetType Settings::getDetType() const { return Settings::getDetType((ParamType)((int)getValue(eDetType))); } DesType Settings::getDesType() const { switch((int)getValue(eDesType)) { case eDesType_sift: return DesType::DES_SIFT; case eDesType_surf: return DesType::DES_SURF; case eDesType_orb: return DesType::DES_ORB; case eDesType_brisk: return DesType::DES_BRISK; case eDesType_freak: return DesType::DES_FREAK; case eDesType_kaze: return DesType::DES_KAZE; case eDesType_akaze: return DesType::DES_AKAZE; default: return DesType::DES_SIFT; } } MatcherType Settings::getMatcherType() const { switch((int)getValue(eMatcherType)) { case eMatcherType_flann: return MatcherType::FLANN; case eMatcherType_bfhamming: return MatcherType::BF; case eMatcherType_bfhamming2: return MatcherType::BF2; case eMatcherType_auto: return MatcherType::AUTO; default: return MatcherType::AUTO; } } TransformFinderType Settings::getTransformFinderType() const { switch((int)getValue(eTransformFinderType)) { case eTransformFinderType_ransac: return TransformFinderType::TFT_RANSAC; case eTransformFinderType_rho: return TransformFinderType::TFT_RHO; case eTransformFinderType_lmeds: return TransformFinderType::TFT_LMEDS; default: return TransformFinderType::TFT_RANSAC; } } BundleAdjustType Settings::getBundleAdjustType() const { switch((int)getValue(eMultiStitch_bundleAdjustType)) { case eBundleAdjustType_none: return BundleAdjustType::BAT_NONE; case eBundleAdjustType_ray: return BundleAdjustType::BAT_RAY; case eBundleAdjustType_rayBlacklist: return BundleAdjustType::BAT_RAYBLACKLIST; case eBundleAdjustType_rayConfidenceStep: return BundleAdjustType::BAT_RAYCONFIDENCESTEP; case eBundleAdjustType_rayMinTiles: return BundleAdjustType::BAT_RAYMINTILES; case eBundleAdjustType_reproj: return BundleAdjustType::BAT_REPROJ; case eBundleAdjustType_reprojCap200: return BundleAdjustType::BAT_REPROJCAP200; case eBundleAdjustType_reprojMinTiles: return BundleAdjustType::BAT_REPROJMINTILES; case eBundleAdjustType_reprojNoCam: return BundleAdjustType::BAT_REPROJNOCAM; case eBundleAdjustType_reprojNoCamCap200: return BundleAdjustType::BAT_REPROJNOCAMCAP200; default: return BundleAdjustType::BAT_RAY; } } // BlendType Settings::getBlendType() const // { // switch((int)getValue(eMultiStitch_blendType)) { // case eBlendType_none: // return BlendType::BT_NONE; // case eBlendType_multiBand: // return BlendType::BT_MULTIBAND; // case eBlendType_feather: // return BlendType::BT_FEATHER; // default: // return BlendType::BT_MULTIBAND; // } // } SeamFinderType Settings::getSeamFinderType() const { switch((int)getValue(eMultiStitch_seamFinderType)) { case eSeamFinderType_Graphcut: return SeamFinderType::SFT_GRAPHCUT; case eSeamFinderType_Vornoi: default: { return SeamFinderType::SFT_VORNOI; } } } WaveCorrectType Settings::getWaveCorrectType() const { switch((int)getValue(eMultiStitch_waveCorrection)) { case eWaveCorrectionType_A: return WaveCorrectType::WCT_AUTO; case eWaveCorrectionType_N: return WaveCorrectType::WCT_NONE; case eWaveCorrectionType_H: return WaveCorrectType::WCT_H; case eWaveCorrectionType_V: return WaveCorrectType::WCT_V; default: { return WaveCorrectType::WCT_AUTO; } } } float Settings::getValue(ParamType type) const { auto it = paramValuesExt.find(type); if(it == paramValuesExt.end()) { throw std::logic_error("Params::getValue: unknown parameter"); } return it->second.value; } void Settings::setValues( const std::vector<int> &paramTypes, const std::vector<float> &_paramValues) { if(paramTypes.size() != _paramValues.size()) { throw std::logic_error("Settings::setValues: count of types and values dont match"); } init(); for(size_t i = 0; i < paramTypes.size(); ++i) { if( (ParamType)paramTypes[i] == eCompareDetType || (ParamType)paramTypes[i] == eCompareImageType || (ParamType)paramTypes[i] == eFloodFillTolerance || (ParamType)paramTypes[i] == eAlignSelectionOverlay || (ParamType)paramTypes[i] == eImageCapInput) { continue; } auto it = this->paramValuesExt.find((ParamType)paramTypes[i]); if(it == this->paramValuesExt.end()) { throw std::logic_error( "Settings::setvalues: param with id " + std::to_string(paramTypes[i]) + " not found"); } this->paramValuesExt[(ParamType)paramTypes[i]].value = _paramValues[i]; } } void Settings::logParams() const { for(const auto &p : paramValuesExt) { LogUtils::getLog() << p.second.name << ": " << p.second.value << std::endl; } } }
39.882979
115
0.676358
10dimensions
daebd8b31412c47e1cd43a7a3d6a807c4ff1d6e2
2,332
cc
C++
packages/Utils/cxx11/tstLambda.cc
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
19
2015-06-04T09:02:41.000Z
2021-04-27T19:32:55.000Z
packages/Utils/cxx11/tstLambda.cc
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
null
null
null
packages/Utils/cxx11/tstLambda.cc
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
5
2016-10-05T20:48:28.000Z
2021-06-21T12:00:54.000Z
//----------------------------------*-C++-*----------------------------------// /*! * \file Utils/cxx11/tstLambda.cc * \author Thomas M. Evans * \date Wed May 14 10:58:36 2014 * \brief Lambda testing. * \note Copyright (C) 2014 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// #include <vector> #include <algorithm> #include <string> #include "gtest/utils_gtest.hh" //---------------------------------------------------------------------------// // Test Helpers //---------------------------------------------------------------------------// //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// TEST(Lambda, function1) { std::vector<int> x = {10, 22, 31, 44, 56}; // find first odd auto i = std::find_if(std::begin(x), std::end(x), [](int n){ return n % 2 == 1; }); EXPECT_EQ(31, *i); // find first even i = std::find_if(std::begin(x), std::end(x), [](int n){ return n % 2 == 0; }); EXPECT_EQ(10, *i); } //---------------------------------------------------------------------------// TEST(Lambda, function2) { std::vector<int> x = {10, 22, 31, 44, 56}; auto y = x; // add 1 to data auto f = [](int n) { return n + 1; }; std::transform(std::begin(x), std::end(x), std::begin(y), f); int n = 0; for (const auto &m : y) { EXPECT_EQ(x[n] + 1, m); ++n; } } //---------------------------------------------------------------------------// TEST(Lambda, sort) { using std::string; std::vector<string> x = {"Hello", "Goodbye", "You", "Mined", "Whoa"}; // sort on first letter auto s = [](const string &a, const string &b) { return a.back() < b.back(); }; std::sort(x.begin(), x.end(), s); EXPECT_EQ("Whoa", x[0]); EXPECT_EQ("Mined", x[1]); EXPECT_EQ("Goodbye", x[2]); EXPECT_EQ("Hello", x[3]); EXPECT_EQ("You", x[4]); } //---------------------------------------------------------------------------// // end of tstLambda.cc //---------------------------------------------------------------------------//
27.435294
79
0.337907
GCZhang
daedf6b624780fc9e57d9e86cff2778ec1b877e6
276
cpp
C++
adder/half_adder.cpp
michaelbarrett/systemc
8eacbd98321c19f868818ed2e72dc30d25a20bba
[ "Unlicense" ]
null
null
null
adder/half_adder.cpp
michaelbarrett/systemc
8eacbd98321c19f868818ed2e72dc30d25a20bba
[ "Unlicense" ]
null
null
null
adder/half_adder.cpp
michaelbarrett/systemc
8eacbd98321c19f868818ed2e72dc30d25a20bba
[ "Unlicense" ]
null
null
null
//================================= // Function: Half Adder // File Name: half_adder.cpp //================================= #include "half_adder.h" //concurrent method prc_half_adder of the half adder void half_adder :: prc_half_adder() { sum = a ^ b; carry = a & b; }
23
52
0.507246
michaelbarrett
daeef00d83c7adc3031fa0a200470cd39c76d037
1,079
cpp
C++
Tools/InspectorPlugin/Log.cpp
Manuzor/ezEngine
876ad33ef21c6b986bb9bb333b2a3cbfed2be5ef
[ "CC-BY-3.0" ]
null
null
null
Tools/InspectorPlugin/Log.cpp
Manuzor/ezEngine
876ad33ef21c6b986bb9bb333b2a3cbfed2be5ef
[ "CC-BY-3.0" ]
null
null
null
Tools/InspectorPlugin/Log.cpp
Manuzor/ezEngine
876ad33ef21c6b986bb9bb333b2a3cbfed2be5ef
[ "CC-BY-3.0" ]
1
2020-03-08T04:55:16.000Z
2020-03-08T04:55:16.000Z
#include <PCH.h> #include <Foundation/Communication/Telemetry.h> #include <Foundation/Logging/Log.h> namespace ezLogWriter { /// \brief This log-writer will broadcast all messages through ezTelemetry, such that external applications can display the log messages. class Telemetry { public: /// \brief Register this at ezLog to broadcast all log messages through ezTelemetry. static void LogMessageHandler(const ezLoggingEventData& eventData) { ezTelemetryMessage msg; msg.SetMessageID('LOG', 'MSG'); msg.GetWriter() << (ezInt16) eventData.m_EventType; msg.GetWriter() << (ezUInt16) eventData.m_uiIndentation; msg.GetWriter() << eventData.m_szTag; msg.GetWriter() << eventData.m_szText; ezTelemetry::Broadcast(ezTelemetry::Reliable, msg); } }; } void AddLogWriter() { ezGlobalLog::AddLogWriter(&ezLogWriter::Telemetry::LogMessageHandler); } void RemoveLogWriter() { ezGlobalLog::RemoveLogWriter(&ezLogWriter::Telemetry::LogMessageHandler); } EZ_STATICLINK_FILE(InspectorPlugin, InspectorPlugin_Log);
26.317073
139
0.733086
Manuzor
daf61643fa28a1da594f5e4a4023e362362f8029
412
cc
C++
main.cc
vycezhong/bandwidth-benchmark
67e51b673b7cb463e2703e70f090387c90404ee3
[ "MIT" ]
1
2021-06-09T08:33:52.000Z
2021-06-09T08:33:52.000Z
main.cc
vycezhong/bandwidth-benchmark
67e51b673b7cb463e2703e70f090387c90404ee3
[ "MIT" ]
null
null
null
main.cc
vycezhong/bandwidth-benchmark
67e51b673b7cb463e2703e70f090387c90404ee3
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstring> #include <string> extern void GPUBandwidthBenchmark(std::size_t); extern void CPUBandwidthBenchmark(std::size_t); int main(int argc, char* argv[]) { std::size_t size = 100; if (argc == 2) { size = std::stol(argv[1]); // MB } printf("Transfer Size = %lu MB\n", size); size *= 1e6; GPUBandwidthBenchmark(size); CPUBandwidthBenchmark(size); return 0; }
19.619048
47
0.665049
vycezhong
dafaffb77c2aaec065ac75127617015800d67767
462
cpp
C++
nmslib/nms.cpp
psvvsp/NonMaximumSuppression
35e151042320952909a53086d368fdae0fceda7d
[ "MIT" ]
null
null
null
nmslib/nms.cpp
psvvsp/NonMaximumSuppression
35e151042320952909a53086d368fdae0fceda7d
[ "MIT" ]
null
null
null
nmslib/nms.cpp
psvvsp/NonMaximumSuppression
35e151042320952909a53086d368fdae0fceda7d
[ "MIT" ]
null
null
null
#include "nms.h" #include "nms_impl.h" NMS::NMS() { m_impl = new NMS_impl(); } NMS::~NMS() { delete m_impl; } bool NMS::doIt( const std::vector<Box>& boxesIn, const std::vector<real>& scoresIn, real threshold, std::vector<Box>& boxesOut, std::vector<real>& scoresOut) { return m_impl->doIt(boxesIn, scoresIn, threshold, boxesOut, scoresOut); } bool NMS::init(size_t boxesCountMax) { return m_impl->init(boxesCountMax); }
16.5
75
0.649351
psvvsp
970421c4ffcb44e6f201e630996b8ef22cfbfb8d
1,080
cpp
C++
src/satform.cpp
AssortedFantasy/SATSolver
9cfce772938a8835970e59391346def1859cffc8
[ "MIT" ]
2
2019-04-30T17:36:10.000Z
2022-03-14T01:34:58.000Z
src/satform.cpp
AssortedFantasy/SATSolver
9cfce772938a8835970e59391346def1859cffc8
[ "MIT" ]
null
null
null
src/satform.cpp
AssortedFantasy/SATSolver
9cfce772938a8835970e59391346def1859cffc8
[ "MIT" ]
null
null
null
#include "satform.h" void reduce_associative(expression* a) { // Reduce the associative Components of this mathCore::recursive_combine_and(a); mathCore::recursive_combine_or(a); mathCore::recursive_combine_xor(a); mathCore::recursive_combine_equiv(a); } /* Everything is AND, OR and Negated Variables */ void standard_form_raw(expression * a) { reduce_associative(a); mathCore::recursive_standardize(a); // Now you should be able to do this well mathCore::combine_and(a); mathCore::combine_or(a); } /* In reduced form */ void standard_form(expression* a) { reduce_associative(a); mathCore::recursive_standardize(a); // Now you should be able to do this well mathCore::combine_and(a); mathCore::combine_or(a); mathCore::recursive_idempotent(a); } void dual_standard(expression * a) { mathCore::dual(a); standard_form(a); } void negated_standard(expression* a) { mathCore::negate(a); standard_form(a); } void CNF_FORM(expression* a) { standard_form(a); mathCore::to_CNF(a); } void DNF_FORM(expression* a) { standard_form(a); mathCore::to_DNF(a); }
19.636364
45
0.738889
AssortedFantasy
9705a8519202bf9964c508cbf20a41f94f9f4646
2,062
cpp
C++
src/txt.cpp
nfsu/pkm_iv
df661cbbd1f7b3d5c25b853aefa01f58b2150a51
[ "MIT" ]
null
null
null
src/txt.cpp
nfsu/pkm_iv
df661cbbd1f7b3d5c25b853aefa01f58b2150a51
[ "MIT" ]
null
null
null
src/txt.cpp
nfsu/pkm_iv
df661cbbd1f7b3d5c25b853aefa01f58b2150a51
[ "MIT" ]
null
null
null
#include "txt.hpp" #include <algorithm> namespace pkm_iv { //Shout outs to PPRE once again Txt Txt::parse(Buffer b) { Buffer beg = b.clone(); FINALLY(beg.dealloc();); auto head = b.consume<TxtHeader>(); u16 key = u16(head.seed * 0x2FD); List<TxtEntry> stArr; for (usz i = 0; i < head.num; ++i) { //Simple decryption TxtStringHeaderKey txt{ u16(key * (i + 1)), b.consume<u32>(), b.consume<u32>() }; //Decrypt Buffer atOff = beg.offset(txt.offset), atOffBeg = atOff; u16 keyj = u16(0x91bd3 * (i + 1)); for (usz j = 0; j < txt.size; ++j) { atOff.consume<NinChar>() ^= keyj; keyj = u16(keyj + 0x493D); } //Create string WString str; str.reserve(txt.size); bool compression{}; //Check if compression and then process str NinChar c = atOffBeg.consume<NinChar>(); List<NinChar> temp; u32 cache{}, shift{}; if (c != 0xF100) goto processStr; //Compression; basically it stores a bitset of 9 instead of the full 16 bits while ((c = atOffBeg.consume<NinChar>()) != u16_MAX) { cache |= u32(c) << shift; shift += 15; do { shift -= 9; if ((c = cache & 0x1FF) != 0x1FF) temp.push_back(c); else temp.push_back(u16_MAX); cache >>= 9; } while(shift >= 9); } atOffBeg = Buffer(temp.size() * sizeof(NinChar), (u8*) temp.data()); compression = true; processStr: do { static_assert(sizeof(NinChar) == 2, "NinChar expected to = 2"); if (c == u16_MAX - 1) { //Encoded instruction in text u16 kind = atOffBeg.consume<u16>(); u16 argc = atOffBeg.consume<u16>(); WString stringifiedCmd = L"VAR(" + std::to_wstring(kind); for (u16 l = 0; l < argc; ++l) stringifiedCmd += L"," + std::to_wstring(l); str += stringifiedCmd + L")"; continue; } str += stringify(c); } while ((c = atOffBeg.consume<NinChar>()) != u16_MAX); stArr.push_back(TxtEntry(u16(i), compression, str)); } return Txt{ .header = head, .data = stArr }; } }
18.247788
79
0.575655
nfsu
8ccbbbf9cb1b558605c90df0b5a825efddd03ce4
1,788
cpp
C++
uva/uva11925/save1.cpp
oklen/my-soluation
56d6c32f0a328332b090f9d633365b75605f4616
[ "MIT" ]
null
null
null
uva/uva11925/save1.cpp
oklen/my-soluation
56d6c32f0a328332b090f9d633365b75605f4616
[ "MIT" ]
null
null
null
uva/uva11925/save1.cpp
oklen/my-soluation
56d6c32f0a328332b090f9d633365b75605f4616
[ "MIT" ]
null
null
null
//#include <iostream> //#include <deque> //#include <queue> //using namespace std; //int main() //{ // int n; // while(scanf("%d",&n)&&n){ // deque<int> nd;int nn,mx = -1,cnt=0,mi = 0xfffffff; // for(int i = 0;i<n;++i){ // scanf("%d",&nn); // mx = max(mx,nn); // mi = min(mi,nn); // nd.push_back(nn); // } // mx+=1;//Additional mx // nd.push_back(mx); // queue<char> od; // while(true){ // if(nd.at(0)>nd.at(1)&&nd.front()!=mx) // { // cnt = nd.at(0);nd.at(0) = nd.at(1); // nd.at(1) = cnt;cnt=0; // while(!od.empty()){ // printf("%c",od.front()); // od.pop(); // } // printf("1"); // } // else{ // if(nd.front()!=mx) // od.push('2'); // else cnt = 0; // if(cnt!=0||nd.at(0)==mi) // ++cnt; // nd.push_back(nd.front());nd.pop_front(); // } // if(cnt>=(nd.size()-1))break; // } // while(od.size()){printf("%c",od.front());od.pop();} // printf("\n"); //// for(int i = 0;i<nd.size();++i) //// cout << nd[i] << " "; //// cout << endl; // bool sorted = true; // for(int i = 2;i<nd.size();++i){ // if(nd[i-1]>nd[i]){ // sorted =false; // cout << i << " "<< nd.size() << endl; // break; // } // } // if(sorted) cout << "Yes!" <<endl; // else cout << "Wrong!" <<endl; // } // return 0; //}
30.305085
63
0.32047
oklen
8ccbeb104dcdc8d88ab844e90055f1c60e25daa7
1,139
cpp
C++
src/MainWindow.cpp
oneminute/Penmanship
f1f7d8606954aa872f0e26b6d090a4fafa16c4f4
[ "MIT" ]
null
null
null
src/MainWindow.cpp
oneminute/Penmanship
f1f7d8606954aa872f0e26b6d090a4fafa16c4f4
[ "MIT" ]
null
null
null
src/MainWindow.cpp
oneminute/Penmanship
f1f7d8606954aa872f0e26b6d090a4fafa16c4f4
[ "MIT" ]
null
null
null
#include "MainWindow.h" #include <ui/ui_MainWindow.h> #include "EditGraphicsViewer.h" #include "EditGraphicsScene.h" #include "CellItem.h" MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) , m_ui(new Ui::MainWindow) { m_ui->setupUi(this); m_viewer = new EditGraphicsViewer(this); m_scene = qobject_cast<EditGraphicsScene*>(m_viewer->scene()); m_viewer->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); m_viewer->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); setCentralWidget(m_viewer); connect(m_ui->actionPrint, &QAction::triggered, this, &MainWindow::onActionPrint); connect(m_ui->actionAddCell, &QAction::triggered, this, &MainWindow::onActionAddCell); connect(m_ui->actionGenerate, &QAction::triggered, this, &MainWindow::onActionGenerate); } MainWindow::~MainWindow() { } void MainWindow::onActionPrint(bool checked) { m_viewer->print(); } void MainWindow::onActionAddCell(bool checked) { CellItem* item = new CellItem(20, 20, 60, 60); m_scene->addItem(item); } void MainWindow::onActionGenerate(bool checked) { m_scene->generateCells(); }
25.311111
92
0.730465
oneminute
8cce7e10bab58a703f3b81e93900e17fa39e9a2b
1,072
cpp
C++
tests/test_function.cpp
te9yie/cpp-t9
40edf781aef2a3bcf0c46b3c37735d909253c8e4
[ "MIT" ]
null
null
null
tests/test_function.cpp
te9yie/cpp-t9
40edf781aef2a3bcf0c46b3c37735d909253c8e4
[ "MIT" ]
null
null
null
tests/test_function.cpp
te9yie/cpp-t9
40edf781aef2a3bcf0c46b3c37735d909253c8e4
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <t9/function.h> namespace { class Counter { private: int count_ = 0; public: int tick() { return ++count_; } int tick(int n) { count_ += n; return count_; } int get() const { return count_; } }; inline int twice(int x) { return x * x; } } // namespace TEST(FunctionTest, Ctor) { Counter counter; const t9::Function<int()> f(&counter, &Counter::tick); EXPECT_EQ(0, counter.get()); EXPECT_EQ(1, f()); EXPECT_EQ(1, counter.get()); EXPECT_EQ(2, f()); EXPECT_EQ(2, counter.get()); } TEST(FunctionTest, Ctor2) { Counter counter; const t9::Function<int(int)> f(&counter, &Counter::tick); EXPECT_EQ(0, counter.get()); EXPECT_EQ(2, f(2)); EXPECT_EQ(2, counter.get()); } TEST(FunctionTest, Assign) { using Func = t9::Function<int(int)>; Func f1; EXPECT_FALSE(f1); f1.reset(twice); EXPECT_TRUE(f1); EXPECT_EQ(4, f1(2)); } TEST(FunctionTest, Clear) { using Func = t9::Function<int(int)>; Func f1(twice); EXPECT_TRUE(f1); EXPECT_EQ(4, f1(2)); f1.reset(); EXPECT_FALSE(f1); }
19.142857
59
0.630597
te9yie
8cd2beb5b8f15541e768f24ccb3fa0153a145374
467
cpp
C++
Baekjoon/3986.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
Baekjoon/3986.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
Baekjoon/3986.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
#include <iostream> #include <stack> #include <string> using namespace std; int main(void) { int N, ans = 0; cin >> N; while (N--) { string str; stack<char> st; cin >> str; int len = str.length(); for (int i = 0; i < len; i++) { char c = str[i]; if (st.size() > (len - i)) break; if (st.size() == 0) st.push(c); else if (st.top() == c) st.pop(); else st.push(c); } if (st.size() == 0) ans++; } cout << ans; }
13.735294
31
0.490364
Twinparadox
8cdc05eaf11f515ee06c6fe7f51b5188bd9a997f
1,499
cpp
C++
leetcode/problems/medium/62-unique-paths.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/medium/62-unique-paths.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/medium/62-unique-paths.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Unique Paths A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? Above is a 7 x 3 grid. How many possible unique paths are there? Example 1: Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right Example 2: Input: m = 7, n = 3 Output: 28 Constraints: 1 <= m, n <= 100 It's guaranteed that the answer will be less than or equal to 2 * 10 ^ 9. */ class Solution { public: int uniquePaths(int m, int n) { // store how many ways to reach arr[m][n] int dp[m][n]; // for col=0, there is only one way to reach for(int i=0;i<m;i++) dp[i][0]=1; // for row=0, there is only one way to reach for(int j=0;j<n;j++) dp[0][j]=1; // traverse the rest of the cells for(int i=1;i<m;i++){ for(int j=1;j<n;j++){ // since the possible move is either from the top and from the left // so combine them together : dp[i-1][j] (from the top) + dp[i][j-1] (from the left) dp[i][j]= dp[i-1][j]+dp[i][j-1]; } } return dp[m-1][n-1]; } };
28.283019
171
0.592395
wingkwong
8cdd6df1ceba4ac36a4b12121036f8d7ad680216
21,430
cpp
C++
source/test/test.cpp
xiaobodu/breeze
e74f0cd680274fd431118104d1fdb45926da6328
[ "Apache-2.0" ]
1
2020-08-13T08:10:15.000Z
2020-08-13T08:10:15.000Z
source/test/test.cpp
xiaobodu/breeze
e74f0cd680274fd431118104d1fdb45926da6328
[ "Apache-2.0" ]
null
null
null
source/test/test.cpp
xiaobodu/breeze
e74f0cd680274fd431118104d1fdb45926da6328
[ "Apache-2.0" ]
1
2017-04-30T14:25:25.000Z
2017-04-30T14:25:25.000Z
/* * breeze License * Copyright (C) 2014-2016 YaweiZhang <yawei.zhang@foxmail.com>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //! 测试 #include <common.h> #include <utls.h> #include <balance.h> using namespace zsummer::log4z; using namespace zsummer::mysql; int checkString(); int checkFile(); int checkTime(); int checkFloat(); int checkBalance(); int checkRandom(); #define TestUtls(func) do \ { \ LOGA("begin " << #func); \ double now = getFloatNowTime(); \ int ret = func(); \ if (ret == 0) \ { \ LOGA("end " << #func << ", used second=" <<getFloatNowTime() - now); \ } \ else \ { \ LOGE("end " << #func << ", used second=" <<getFloatNowTime() - now << ", ret=" << ret); \ return ret; \ } \ } while (false) int main(int argc, char* argv[]) { #ifndef _WIN32 //! linux下需要屏蔽的一些信号 signal( SIGHUP, SIG_IGN ); signal( SIGALRM, SIG_IGN ); signal( SIGPIPE, SIG_IGN ); signal( SIGXCPU, SIG_IGN ); signal( SIGXFSZ, SIG_IGN ); signal( SIGPROF, SIG_IGN ); signal( SIGVTALRM, SIG_IGN ); signal( SIGQUIT, SIG_IGN ); signal( SIGCHLD, SIG_IGN); setenv("TZ", "GMT-8", 1); #else //system("chcp 65001"); #endif srand((ui32)time(NULL)); ILog4zManager::getPtr()->start(); SessionManager::getRef().start(); checkBalance(); auto ret =getHostByName("github.com", 3389); LOGA("getHostByName=" << ret); std::tuple<double, int, std::string> kvv = splitTupleString<double, int, std::string>("1.0:2:aha", ":", ""); LOGA("1=" << std::get<0>(kvv) << ", 2=" << std::get<1>(kvv) << ", 3=" << std::get<2>(kvv)); LOGI("0second" << formatDateTimeString(0)); LOGI("now" << formatDateTimeString(getNowTime())); LOGA("version released by " << __DATE__ << " " << __TIME__); TestUtls(checkString); TestUtls(checkFile); TestUtls(checkFloat); TestUtls(checkBalance); TestUtls(checkRandom); TestUtls(checkTime); LOGA("check all success."); sleepMillisecond(3000); return 0; } int checkString() { std::string t1 = "%^&123^=&"; auto ret = splitString<std::string>(t1, "=", "&%^"); if (ret.size() != 2) { return 1; } if (ret.front() != "123") { return 2; } if (!ret.back().empty()) { return 3; } if (splitString<std::string>("==", "==", "adf123").size() != 2) { return 4; } if (true) { std::vector<int> array = { 1,2,3,4 }; std::string dstString = mergeToString(array, ","); if (dstString.length() != 7) { return 5; } dstString.clear(); for (auto i : array) { mergeToString(dstString, ",", i); } if (dstString.length() != 7) { return 6; } auto now = getFloatNowTime(); for (int i=0; i<10000; i++) { auto v = splitDictString<int, short, float, std::string>("1|2|3|a,|||,2|2|3|a,|||,3|2|3|a,|||,4|2|3|a,|||,5|2|3|a,|||,6|2|3|a,|||,7|2|3|a,|||,8|2|3|a,|||,8|2|3|a,|||,", ",", "|", " "); std::get<0>(v.begin()->second) = 0; } LOGA("splitDictString used time=" << getFloatNowTime() - now); } if (!compareStringIgnCase("Fad123123", "fAd123123")) { return 7; } if (compareStringIgnCase("1234", "123", true)) { return 8; } if (!compareStringIgnCase("a123", "A1234", true)) { return 9; } if (compareStringIgnCase("a123", "A1234", false)) { return 10; } if (strcmp(toUpperString("aaaa").c_str(), "AAAA") != 0) { return 11; } if (strcmp(toLowerString("AAAA").c_str(), "aaaa") != 0) { return 12; } if (!isEqual(fromString<float>("0.1", 0.0), 0.1, 1e-5)) { return 13; } if (!isEqual(fromString<double>("1e-1", 0.0), 0.1)) { return 14; } if (fromString<int>("-1", 0) != -1) { return 15; } if (fromString<unsigned long long>("18446744073709551615", 0) != 18446744073709551615U) { return 16; } if (!compareStringWildcard("", "")) { return 17; } if (!compareStringWildcard("", "*")) { return 18; } if (!compareStringWildcard("afda*fa", "*")) { return 19; } if (!compareStringWildcard("a---bc-e-bc-----------e", "a*bc***e*e")) { return 21; } if (compareStringWildcard("a---bc-e-bc-----------e-", "a*bc***e*e")) { return 22; } if (true) { double now = getFloatNowTime(); for (int i = 0; i < 10 * 10000; i++) { if (fromString<unsigned long long>("18446744073709551615", 0) != 18446744073709551615U) { return 16; } if (fromString<long long>("-8446744073709551615", 0) != -8446744073709551615L) { return 16; } } LOGD("fromString used time=" << (getFloatNowTime() - now)); for (int i = 0; i < 10 * 10000; i++) { } LOGD("toString used time=" << (getFloatNowTime() - now)); } if (true) { double now = getFloatNowTime(); for (int i = 0; i < 10 * 10000; i++) { compareStringWildcard("a---bc-e-bc-----------e", "a*bc***e*e"); } LOGD("compareStringWildcard used time=" << (getFloatNowTime() - now)); } if (subStringFront("aa/bb/cc", "/") != "aa") { return 25; } if (subStringBack("aa/bb/cc", "/") != "cc") { return 26; } if (subStringWithoutFront("aa/bb/cc", "/") != "bb/cc") { return 27; } if (subStringWithoutBack("aa/bb/cc", "/") != "aa/bb") { return 28; } if (true) { //蓝天and҉😌 char org[] = { (char)0xe8, (char)0x93, (char)0x9d, (char)0xe5, (char)0xa4, (char)0xa9, (char)0x61, (char)0x6e, (char)0x64, (char)0xd2, (char)0x89, (char)0xf0, (char)0x9f, (char)0x98, (char)0x8c, (char)0x00 }; if (getCharUTF8Count(org) != 7) { return 29; } if (getCharASCIICount(org) != 3) { return 30; } if (getCharNoASCIICount(org) != 4) { return 31; } if (!hadIllegalChar(org)) { return 32; } } return 0; } int checkFile() { std::string content = "1234567890"; std::string path = "./log2/log3/"; std::string filename = "aaaa"; std::string md5 = "e807f1fcf82d132f9bb018ca6738a19F"; if (isDirectory(path)) { return 1; } if (!createDirectory(path)) { return 2; } if (!isDirectory(path)) { return 3; } writeFileContent(path + filename, content.c_str(), content.length(), false); if (!accessFile(path + filename)) { return 4; } content.clear(); size_t lastSize = 0; do { std::string str = readFileContent(path + filename, true, 4, lastSize); lastSize += str.length(); content += str; if (str.length() < 4) { break; } } while (true); MD5Data d; d << content; std::string mmd5 = d.genMD5(); if (!compareStringIgnCase(toUpperString(mmd5), toLowerString(md5))) { return 5; } if (!compareStringIgnCase(toUpperString(genFileMD5(path + filename)), toLowerString(md5))) { return 6; } if (!removeFile(path + filename)) { return 7; } if (!removeDir(path)) { return 8; } if (accessFile(path + filename)) { return 9; } return 0; } int checkTime() { double now = getFloatNowTime(); double snow = getFloatSteadyNowTime(); long long nowt = getNowTick(); long long nowst = getNowSteadyTick(); time_t nowts = getNowTime(); sleepMillisecond(3000); now = getFloatNowTime() - now - 3.0; snow = getFloatSteadyNowTime() - snow - 3.0; nowt = getNowTick() - nowt - 3000; nowst = getNowSteadyTick() - nowst - 3000; nowts = getNowTime() - nowts -3; if (now > 1 || snow > 1 || nowt >1000 || nowst >1000 || nowts > 1) { LOGE("now =" << now << ", snow=" << snow << ", nowt=" << nowt << ", nowst=" << nowst << ", nowts=" << nowts); return 1; } LOGI(formatDateString(getNowTime()) << " " << formatTimeString(getNowTime())); LOGI(formatDateTimeString(getNowTime())); //2015周四/2016周五 time_t dt2015 = 1451577599; time_t dt2016 = 1451577600; if (isSameDay(dt2015, dt2016) || isSameMonth(dt2015, dt2016) || isSameYear(dt2015, dt2016)) { return 2; } if (!isSameDay(dt2015, dt2016, -1) || !isSameMonth(dt2015, dt2016, -1) || !isSameYear(dt2015, dt2016, -1)) { return 3; } if (!isSameWeak(dt2015, dt2016) || isSameWeak(dt2015+3*24*3600, dt2016 + 3*24+3600)) { return 4; } if (!isSameWeak(dt2015+3*24*3600+1, dt2015+3*24*3600+3)) { return 5; } if (distanceDays(1451577599, 1451577599+1) != 1) { return 6; } if (distanceDays(1451577599, 1451577599 + 1+24*3600) != 2) { return 7; } if (distanceDays(1451577599, 1451577599 +1 - 24 * 3600) != 0) { return 7; } if (getUTCTimeFromLocalString("2015/12/31 23:59:59") != 1451577599) { return 8; } if (getUTCTimeFromLocalString(" 31-12-2015 23:59 ") != 1451577599 - 59) { return 9; } if (getUTCTimeFromLocalString("12-2015 23:59") != 1451577599 - (31-1)*24*3600 - 59) { return 10; } if (getUTCTimeFromLocalString("20151231") != 1451577599 - 24 * 3600 + 1) { return 10; } //hypothesis server is GMT+9, unknown client time area, utc second is 1451577599, in client get server's localtime. if (gettm(1451577599 + (9 * 3600 - getTZZoneOffset())).tm_hour != 0) { return 12; } if (getSecondFromTimeString("1:2:3") != 1*3600 + 2*60 + 3) { return 15; } if (true) { int bit = 0; bit = setBitFlag(bit, 1); bit = setBitFlag(bit, 2); if (!getBitFlag(bit, 1)) { return 16; } bit = setBitFlag(bit, 1, false); if (getBitFlag(bit, 1)) { return 17; } if (!getBitFlag(bit, 2)) { return 18; } bit = setBitFlag(bit, 2, false); if (bit != 0) { return 19; } } if (pruning(1, 2,3) != 2) { return 19; } if (pruning(4, 2, 3) != 3) { return 20; } if (true) { time_t now = getUTCTime(); time_t scd = getDaySecond(now); tm ts = gettm(now); if (scd != ts.tm_hour * 3600 + ts.tm_min*60 + ts.tm_sec) { return 21; } } return 0; } int checkFloat() { if (isZero(POINT_DOUBLE)) { return 1; } if (!isZero(0.0)) { return 2; } if(isZero(POINT_DOUBLE*1.00000000001)) { return 3; } if (isZero(POINT_DOUBLE*-1.00000000001)) { return 4; } if (!isZero(POINT_DOUBLE * 0.999999999)) { return 5; } if (!isZero(POINT_DOUBLE * -0.999999999)) { return 6; } if (!isEqual(0.0, 0.0)) { return 7; } if (isEqual(0.0, POINT_DOUBLE)) { return 8; } if (isEqual(0.0, POINT_DOUBLE*0.999999)) { return 9; } if (isEqual(0.0, POINT_DOUBLE*-0.999999)) { return 10; } if (!isEqual(POINT_DOUBLE, POINT_DOUBLE)) { return 11; } if (isEqual(POINT_DOUBLE*1E55, POINT_DOUBLE*1E55 + POINT_DOUBLE*1E55*POINT_DOUBLE*1.1)) { return 12; } if (!isEqual(POINT_DOUBLE*1E55, POINT_DOUBLE*1E55 + (POINT_DOUBLE*1E55*POINT_DOUBLE)*0.99999)) { return 13; } if (isEqual(POINT_DOUBLE*1E-55, POINT_DOUBLE*1E-55 + POINT_DOUBLE*1E-55*POINT_DOUBLE*1.1)) { return 14; } if (!isEqual(POINT_DOUBLE*1E-55, POINT_DOUBLE*1E-55 - (POINT_DOUBLE*1E-55*POINT_DOUBLE)*0.99999)) { return 15; } if (!isEqual(getDistance(1.0, -1.0), 2.0)) { return 16; } if (!isEqual(getDistance(1.0, 0.0, 2.0, 0.0), 1.0)) { return 17; } if (!isEqual(getRadian(0.0, 0.0, 1.0, 0.0), 0.0)) { return 18; } if (!isEqual(getRadian(0.0, 0.0, -1.0, 0.0), PI)) { return 19; } if (!isEqual(std::get<1>(getFarPoint(0.0, 0.0, PI/2.0*3.0, 1.0)), -1.0)) { return 20; } if (!isEqual(std::get<1>(getFarOffset(0.0, 0.0, 0.0, -2.0, 1.0)), -1.0)) { return 21; } if (!isEqual(std::get<1>(getFarOffset(0.0, 0.0, 0.0, 2.0, 1.0)), 1.0)) { return 22; } if (!isEqual(std::get<0>(rotatePoint(0.0, 0.0, PI/2.0, 1.0, PI/2.0)), -1.0)) { return 25; } if (!isEqual(std::get<1>(rotatePoint(0.0, 0.0, PI / 2.0, 1.0, PI)), -1.0)) { return 26; } if (!isEqual(calcELORatingUpper(1500, 1800, 1), 1527, 1E0)) { return 27; } if (true) { double now = getFloatNowTime(); volatile double f = 0.0; for (int i = 0; i < 100 * 10000; i++) { f = isEqual(1e55, 1e55); } f = 0.0; LOGD("isEqual used time=" << (getFloatNowTime() - now) << f); } if (true) { double owner = 2500; double dst = 2500; for (int i = 0; i < 10; i++) { double newOwner = owner + calcELORatingUpper(owner, dst, 1); double newDst = dst + calcELORatingUpper(dst, owner, -1); LOGD("owner[" << newOwner << ":" << 1.0 - (newOwner - owner) / 32 << "] , dst[" << newDst << ":" << (newDst - dst) / -32 << "]"); owner = newOwner; dst = newDst; } } return 0; } int checkBalance() { Balance<ui32> balance; balance.enableNode(1); balance.enableNode(2); balance.enableNode(3); for (unsigned i = 0; i < 12 ; ++i) { balance.pickNode(1, 1); } if (balance.getBalanceDeviation() > 1+1) { return 1; } for (unsigned i = 0; i < 20000; ++i) { balance.pickNode(50, 1); } if (balance.getBalanceDeviation() > 50 + 1) { return 2; } balance.disableNode(3); balance.enableNode(4); for (unsigned i = 0; i < 20000; ++i) { balance.pickNode(50, 1); } if (balance.getBalanceDeviation() > 50 + 1) { return 3; } for (unsigned i = 0; i < 20000; ++i) { balance.pickNode(1, 1); } if (balance.getBalanceDeviation() > 1 + 1) { return 4; } LOGD( balance.getBalanceStatus()); return 0; } int checkRandom() { if (true) { int sum1 = 0; int sum50 = 0; int sum100 = 0; int loop = 10000 * 10; for (int i = 0; i < loop; i++) { unsigned int rr = realRand(1000, 2000); if (rr < 1000 || rr > 2000) { return 1; } double rrf = realRandF(100.234, 200.999); if (rrf < 100.234 || rrf > 200.999) { return 2; } unsigned int rd = realRand(1, 100); if (rd == 1) { sum1++; } if (rd == 50) { sum50++; } if (rd == 100) { sum100++; } } LOGD("realRand 1-100. 1=" << sum1 << ", 50=" << sum50 << ", sum100=" << sum100); if (abs(sum1 - loop/100) > loop/100*20/100 || abs(sum50 - loop / 100) > loop / 100 * 20 / 100 || abs(sum100 - loop / 100) > loop / 100 * 20 / 100 ) { return 2; } } std::vector<int> cards; if (true) { cards.push_back(100); cards.push_back(200); auto ret = raffle(cards.begin(), cards.end(), 2, false, [](std::vector<int>::iterator iter) {return *iter; }); if (ret.size() != 2) { return 3; } ret = raffle(cards.begin(), cards.end(), 2, true, [](std::vector<int>::iterator iter) {return *iter; }); if (ret.size() != 2 || ret.front() == ret.back()) { return 4; } ret = raffle(cards.begin(), cards.end(), 3, false, [](std::vector<int>::iterator iter) {return *iter; }); if (ret.size() != 3) { return 5; } ret = raffle(cards.begin(), cards.end(), 3, true, [](std::vector<int>::iterator iter) {return *iter; }); if (ret.size() != 2) { return 6; } //weight is 0 ret = raffle(cards.begin(), cards.end(), 3, false, [](std::vector<int>::iterator iter) {return 0; }); if (ret.size() != 0) { return 7; } //pound is empty ret = raffle(cards.end(), cards.end(), 3, false, [](std::vector<int>::iterator iter) {return *iter; }); if (ret.size() != 0) { return 8; } ret = raffle(cards.begin(), cards.end(), 3, true, [](std::vector<int>::iterator iter) {return 0; }); if (ret.size() != 0) { return 9; } //pound is empty ret = raffle(cards.end(), cards.end(), 3, true, [](std::vector<int>::iterator iter) {return *iter; }); if (ret.size() != 0) { return 10; } } cards.clear(); for (int i = 100; i > 0; i--) { cards.push_back(i); } if (true) { int loopCount = 1*10000; int takeCount = 10; double sumRaffle = 0.0;// sumRaffle ≈ (1/100)*loopCount*10 double sumRaffleWeight = 0.0; //sumRaffleWeight ≈ (100/5050)*loopCount*10 for (int i = 0; i < loopCount; i++) { auto ret = raffle(cards.begin(), cards.end(), takeCount, false); for (auto v : ret) { if (*v == 100) { sumRaffle += 1.0; break; } } ret = raffle(cards.begin(), cards.end(), takeCount, false, [](std::vector<int>::iterator iter){return *iter; }); for (auto v : ret) { if (*v == 100) { sumRaffleWeight += 1.0; break; } } } auto diff = fabs(sumRaffle - loopCount* (1.0 / 100.0)*takeCount); auto target = loopCount* (1.0 / 100.0)*takeCount * 0.2; LOGD("diff=" << diff << ", target=" << target); if (fabs(sumRaffle - loopCount* (1.0 / 100.0)*takeCount) > loopCount* (1.0 / 100.0)*takeCount * 0.2) { return 11; } diff = fabs(sumRaffleWeight - loopCount* (100.0 / 5050.0)*takeCount); target = loopCount* (1.0 / 5050.0)*takeCount * 0.2; LOGD("diff=" << diff << ", target=" << target); if (fabs(sumRaffleWeight - loopCount *(100.0 / 5050.0)*takeCount) > loopCount *(100.0 / 5050.0)*takeCount * 0.2) { return 12; } } if (true) { std::vector<std::pair<int, double>> cards; for (int i=1; i<=100; i++) { cards.push_back(std::make_pair(i, i / 100.0)); } int loop = 10000; int takeCount = 10; int sum1 = 0; //sum 1 ≈ 0.01 * 10000*10 int sum50 = 0; //sum 50 ≈ 0.5*10000*10 int sum100 = 0; //sum 100 = 10000*10 for (int i=0; i<loop; i++) { auto ret = raffle(cards.begin(), cards.end(), takeCount, [](std::vector<std::pair<int, double>>::iterator iter) {return iter->second; }); for (auto iter : ret) { if (iter->first == 1) { sum1++; } else if (iter->first == 50) { sum50++; } else if (iter->first == 100) { sum100++; } } } LOGD("sum1=" << sum1 << ", sum50=" << sum50 << ", sum100=" << sum100); if (sum100 != loop*takeCount) { return 20; } if (abs(sum1 - loop*takeCount/100) > (loop*takeCount/100*20/100)) { return 21; } if (abs(sum50 - loop*takeCount / 2) > (loop*takeCount / 2 * 20 / 100)) { return 22; } } return 0; }
25.152582
237
0.480681
xiaobodu
8ce07dfcb8bc3b858dd7feea86e801fe5c042ecd
2,726
cpp
C++
alvr/server/cpp/tools/drmdevice.cpp
N00byKing/ALVR
230199e1efa6acb9fa37fa5ae53206052e9ac48f
[ "BSD-3-Clause" ]
null
null
null
alvr/server/cpp/tools/drmdevice.cpp
N00byKing/ALVR
230199e1efa6acb9fa37fa5ae53206052e9ac48f
[ "BSD-3-Clause" ]
null
null
null
alvr/server/cpp/tools/drmdevice.cpp
N00byKing/ALVR
230199e1efa6acb9fa37fa5ae53206052e9ac48f
[ "BSD-3-Clause" ]
null
null
null
#include "drmdevice.h" #include "drm.h" #include <cstdint> #include <string.h> #include <errno.h> #include <xf86drm.h> #include <xf86drmMode.h> #include <fcntl.h> #include <functional> #include <stdio.h> #include <unistd.h> #include <stdexcept> #include <poll.h> class Defer { public: Defer(std::function<void()> fn): fn(fn){} ~Defer() {if (fn) fn();} void cancel() {fn = std::function<void()>();} private: std::function<void()> fn; }; DRMDevice::DRMDevice(int width, int height) { drmDevicePtr devices[16]; int count = drmGetDevices(devices, 16); Defer d([&](){drmFreeDevices(devices, count);}); for (int i = 0 ; i < count ; ++i) { for (int node = 0 ; node < DRM_NODE_MAX ; ++node) { if (*devices[i]->nodes[node]) { int fd = open(devices[i]->nodes[node], O_RDWR); if (fd == -1) { perror("open drm failed"); continue; } Defer close_fd([=](){close(fd);}); drmSetClientCap(fd, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1); auto planes = drmModeGetPlaneResources(fd); if (not planes) { perror("drmModeGetPlaneResources failed"); continue; } Defer dplane([&](){drmModeFreePlaneResources(planes);}); for (int plane = 0 ; plane < planes->count_planes ; ++plane) { auto planeptr = drmModeGetPlane(fd, planes->planes[plane]); Defer d([&](){drmModeFreePlane(planeptr);}); if (planeptr->crtc_id) { auto crtc = drmModeGetCrtc(fd, planeptr->crtc_id); Defer d([&](){drmModeFreeCrtc(crtc);}); if (crtc and crtc->width == width and crtc->height == height) { device = devices[i]->nodes[node]; crtc_id = planeptr->crtc_id; this->fd = fd; close_fd.cancel(); return; } } } } } } throw std::runtime_error("failed to find KMS device matching " + std::to_string(width) + "x" + std::to_string(height)); } void DRMDevice::waitVBlank(volatile bool &exiting) { uint64_t queued_seq; uint64_t current_seq = 0; drmCrtcQueueSequence(fd, crtc_id, DRM_CRTC_SEQUENCE_RELATIVE, 1, &queued_seq, uintptr_t(&current_seq)); drmEventContext handlers{ .version = 4, .sequence_handler = DRMDevice::sequence_handler }; while (current_seq < queued_seq and not exiting) { pollfd pfd[1]; pfd[0] = pollfd{.fd = fd, .events = POLLIN, .revents = 0}; int c = poll(pfd, 1, 10); if (c < 0) { throw std::runtime_error(std::string("poll failed: ") + strerror(errno)); } if (c == 1) { drmHandleEvent(fd, &handlers); } } } void DRMDevice::sequence_handler(int /*fd*/, uint64_t sequence, uint64_t /*ns*/, uint64_t user_data) { uint64_t *seq = (uint64_t*)user_data; *seq = sequence; } DRMDevice::~DRMDevice() { if(fd != -1) { close(fd); } }
22.716667
120
0.625459
N00byKing
8ce616dcec0f547993450a1415d483571286ecad
765
cpp
C++
wxfred2/editors/dlgReinforcementsPicker.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
307
2015-04-10T13:27:32.000Z
2022-03-21T03:30:38.000Z
wxfred2/editors/dlgReinforcementsPicker.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
2,231
2015-04-27T10:47:35.000Z
2022-03-31T19:22:37.000Z
wxfred2/editors/dlgReinforcementsPicker.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
282
2015-01-05T12:16:57.000Z
2022-03-28T04:45:11.000Z
/* * Created by Ian "Goober5000" Warfield and "z64555" for the FreeSpace2 Source * Code Project. * * You may not sell or otherwise commercially exploit the source or things you * create based on the source. */ #include "editors/dlgReinforcementsPicker.h" #include "base/wxFRED_base.h" #include <wx/wx.h> // Public Members: dlgReinforcementsPicker::dlgReinforcementsPicker( wxWindow* parent ) : fredBase::dlgReinforcementsPicker(parent) { } // Protected Members: // Handlers for dlgReinforcementsPicker void dlgReinforcementsPicker::OnClose( wxCloseEvent& event ) { Destroy(); } void dlgReinforcementsPicker::OnOK( wxCommandEvent& event ) { Hide(); } void dlgReinforcementsPicker::OnCancel( wxCommandEvent& event ) { Hide(); } // Private Members:
20.131579
79
0.750327
trgswe
8ce67ffd5e196fa8a155fb0f235fd8cf36e0cd78
348
hpp
C++
nek/type_traits/void_t.hpp
nekko1119/nek
be43faf5c541fa067ab1e1bcb7a43ebcfefe34e7
[ "BSD-3-Clause" ]
null
null
null
nek/type_traits/void_t.hpp
nekko1119/nek
be43faf5c541fa067ab1e1bcb7a43ebcfefe34e7
[ "BSD-3-Clause" ]
null
null
null
nek/type_traits/void_t.hpp
nekko1119/nek
be43faf5c541fa067ab1e1bcb7a43ebcfefe34e7
[ "BSD-3-Clause" ]
null
null
null
#ifndef NEK_TYPE_TRAITS_VOID_T_HPP #define NEK_TYPE_TRAITS_VOID_T_HPP namespace nek { // workaround http://cpplover.blogspot.jp/2014/03/2014-02-post-issaquah-n3910-n3919.html template <class...> struct voider { using type = void; }; template <class ...T> using void_t = typename voider<T...>::type; } #endif
19.333333
92
0.66954
nekko1119
8ce81839dfc090465b5b7c738af79a9237e45a44
5,732
cpp
C++
src/hssh/global_topological/global_path_segment.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
3
2020-03-05T23:56:14.000Z
2021-02-17T19:06:50.000Z
src/hssh/global_topological/global_path_segment.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-07T01:23:47.000Z
2021-03-07T01:23:47.000Z
src/hssh/global_topological/global_path_segment.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-03T07:54:16.000Z
2021-03-03T07:54:16.000Z
/* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ /** * \file global_path_segment.cpp * \author Collin Johnson * * Definition of GlobalPathSegment. */ #include "hssh/global_topological/global_path_segment.h" #include "hssh/global_topological/global_location.h" #include "hssh/global_topological/global_path.h" namespace vulcan { namespace hssh { bool operator!=(const Lambda& lhs, const Lambda& rhs) { return (lhs.x != rhs.x) || (lhs.y != rhs.y) || (lhs.theta != rhs.theta); } GlobalPathSegment::GlobalPathSegment(Id id, const GlobalTransition& plus, const GlobalTransition& minus, const Lambda& lambda, const GlobalTransitionSequence& left, const GlobalTransitionSequence& right, bool isExplored) : id_(id) , plusTransition_(plus) , minusTransition_(minus) , leftSequence_(left) , rightSequence_(right) , initialLambda_(lambda) , haveExploredLambda_(isExplored) { initialLambda_ = lambda; lambdas_.push_back(lambda); std::cout << "Path segment: " << id_ << " Set initial lambda: (" << initialLambda_.x << ',' << initialLambda_.y << ',' << initialLambda_.theta << ")\n"; } GlobalPathSegment::GlobalPathSegment(Id id, const GlobalTransition& plus, const GlobalTransition& minus, const GlobalTransitionSequence& left, const GlobalTransitionSequence& right) : GlobalPathSegment(id, plus, minus, Lambda(), left, right, false) { } // Operator overloads bool GlobalPathSegment::operator==(const GlobalPathSegment& rhs) { return (plusTransition_ == rhs.plusTransition_) && (minusTransition_ == rhs.minusTransition_); } bool GlobalPathSegment::operator!=(const GlobalPathSegment& rhs) { return !operator==(rhs); } GlobalPathSegment GlobalPathSegment::reverse(void) const { // Reversing means the plus and minus ends switch and the left and right transition sequence switch sides and // have the order of destinations reversed GlobalPathSegment reversed(id_, minusTransition_, plusTransition_, initialLambda_.invert(), rightSequence_.reverse(), leftSequence_.reverse(), haveExploredLambda_); // Copy over the other measured lambdas as well for (size_t n = 1; n < lambdas_.size(); ++n) { reversed.addLambda(lambdas_[n].invert()); } return reversed; } bool GlobalPathSegment::replaceTransition(const GlobalTransition& oldTrans, const GlobalTransition& newTrans) { if (oldTrans == minusTransition_) { minusTransition_ = newTrans; return true; } else if (oldTrans == plusTransition_) { plusTransition_ = newTrans; return true; } // Try replacing it in one of the sequences, since it wasn't an end transition -- transitions are globally unique // so it can't be on the left and right side! return leftSequence_.replaceTransition(oldTrans, newTrans) || rightSequence_.replaceTransition(oldTrans, newTrans); } GlobalLocation GlobalPathSegment::locationOnSegment(const GlobalTransition& entry) const { auto direction = TopoDirection::null; // If the area is entered from the plus direction, heading in minus direction. if (entry == plusTransition_) { direction = TopoDirection::minus; } // If entered from minus, then heading to plus else if (entry == minusTransition_) { direction = TopoDirection::plus; } // Otherwise, entered from a sequence, so there's no direction return GlobalLocation(id_, entry, direction); } void GlobalPathSegment::addLambda(const Lambda& lambda) { if (isFrontier()) { initialLambda_ = lambda; lambdas_[0] = lambda; std::cout << "Path segment: " << id_ << " Replaced initial frontier lambda: (" << initialLambda_.x << ',' << initialLambda_.y << ',' << initialLambda_.theta << ")\n"; } if (!isFrontier()) { if (!haveExploredLambda_) { lambdas_[0] = lambda; initialLambda_ = lambda; haveExploredLambda_ = true; std::cout << "Path segment " << id_ << ": Replaced lambda with explored lambda.\n"; } else if (lambdas_.back() != lambda) { lambdas_.push_back(lambda); } std::cout << "Path segment " << id_ << " lambdas:\n"; for (auto& l : lambdas_) { std::cout << "(" << l.x << ',' << l.y << ',' << l.theta << ")\n"; } } // lambdas_[0] = lambda; // initialLambda_.merge(lambda); lambdas_[0] = initialLambda_; } GlobalTransition opposite_end(const GlobalPathSegment& segment, const GlobalTransition& end) { if (segment.plusTransition() == end) { return segment.minusTransition(); } else if (segment.minusTransition() == end) { return segment.plusTransition(); } // The given transition wasn't actually an end! else { return GlobalTransition(); } } } // namespace hssh } // namespace vulcan
32.384181
119
0.611479
anuranbaka
8ce8577b9ec0fa4064daadf501ab173f30170e14
8,079
cc
C++
src/amberscript/parser_debug_test.cc
gnl21/amber
dabae26164714abf951c6815a2b4513260f7c6a4
[ "Apache-2.0" ]
161
2018-11-14T12:04:08.000Z
2022-03-31T01:08:21.000Z
src/amberscript/parser_debug_test.cc
gnl21/amber
dabae26164714abf951c6815a2b4513260f7c6a4
[ "Apache-2.0" ]
545
2018-11-14T03:52:30.000Z
2022-03-30T11:23:12.000Z
src/amberscript/parser_debug_test.cc
gnl21/amber
dabae26164714abf951c6815a2b4513260f7c6a4
[ "Apache-2.0" ]
59
2018-11-13T22:09:02.000Z
2022-01-26T22:25:29.000Z
// Copyright 2020 The Amber Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or parseried. // See the License for the specific language governing permissions and // limitations under the License. #include <sstream> #include "gtest/gtest.h" #include "src/amberscript/parser.h" #include "src/shader_data.h" namespace amber { namespace amberscript { namespace { class ThreadEventRecorder : public debug::Thread { std::stringstream& events; std::string indent = " "; public: explicit ThreadEventRecorder(std::stringstream& ev) : events(ev) {} void StepOver() override { events << indent << "STEP_OVER" << std::endl; } void StepIn() override { events << indent << "STEP_IN" << std::endl; } void StepOut() override { events << indent << "STEP_OUT" << std::endl; } void Continue() override { events << indent << "CONTINUE" << std::endl; } void ExpectLocation(const debug::Location& location, const std::string& line) override { events << indent << "EXPECT LOCATION \"" << location.file << "\" " << location.line; if (!line.empty()) { events << " \"" << line << "\""; } events << std::endl; } void ExpectCallstack( const std::vector<debug::StackFrame>& callstack) override { events << indent << "EXPECT CALLSTACK"; for (auto& frame : callstack) { events << indent << " " << frame.name << " " << frame.location.file << ":" << frame.location.line << " " << std::endl; } events << std::endl; } void ExpectLocal(const std::string& name, int64_t value) override { events << indent << "EXPECT LOCAL \"" << name << "\" EQ " << value << std::endl; } void ExpectLocal(const std::string& name, double value) override { events << indent << "EXPECT LOCAL \"" << name << "\" EQ " << value << std::endl; } void ExpectLocal(const std::string& name, const std::string& value) override { events << indent << "EXPECT LOCAL \"" << name << "\" EQ \"" << value << "\"" << std::endl; } }; class EventRecorder : public debug::Events { public: std::stringstream events; void record(const std::shared_ptr<const debug::ThreadScript>& script) { ThreadEventRecorder thread{events}; script->Run(&thread); } void BreakOnComputeGlobalInvocation( uint32_t x, uint32_t y, uint32_t z, const std::shared_ptr<const debug::ThreadScript>& script) override { events << "THREAD GLOBAL_INVOCATION_ID " << x << " " << y << " " << z << std::endl; record(script); events << "END" << std::endl; } void BreakOnVertexIndex( uint32_t index, const std::shared_ptr<const debug::ThreadScript>& script) override { events << "THREAD VERTEX_INDEX " << index << std::endl; record(script); events << "END" << std::endl; } void BreakOnFragmentWindowSpacePosition( uint32_t x, uint32_t y, const std::shared_ptr<const debug::ThreadScript>& script) override { events << "THREAD FRAGMENT_WINDOW_SPACE_POSITION " << x << " " << y << std::endl; record(script); events << "END" << std::endl; } }; } // namespace using AmberScriptParserTest = testing::Test; TEST_F(AmberScriptParserTest, DebugEventsScript) { std::string dbg = R"(THREAD GLOBAL_INVOCATION_ID 1 2 3 EXPECT LOCATION "compute.hlsl" 2 STEP_IN EXPECT LOCAL "one" EQ 1 STEP_OUT EXPECT LOCAL "pi" EQ 3.14 STEP_OVER EXPECT LOCAL "cat" EQ "meow" CONTINUE END THREAD VERTEX_INDEX 2 EXPECT LOCATION "vertex.hlsl" 2 " dog:woof cat:meow duck:quack" END THREAD FRAGMENT_WINDOW_SPACE_POSITION 4 5 EXPECT LOCATION "fragment.hlsl" 42 CONTINUE END )"; std::string in = R"( SHADER compute dbg_compute GLSL void main() {} END PIPELINE compute my_pipeline ATTACH dbg_compute END DEBUG my_pipeline 2 4 5 )" + dbg + "END"; Parser parser; Result r = parser.Parse(in); ASSERT_TRUE(r.IsSuccess()) << r.Error(); auto script = parser.GetScript(); const auto& commands = script->GetCommands(); ASSERT_EQ(1U, commands.size()); auto* cmd = commands[0].get(); ASSERT_TRUE(cmd->IsCompute()); auto* compute = cmd->AsCompute(); EXPECT_EQ(2U, compute->GetX()); EXPECT_EQ(4U, compute->GetY()); EXPECT_EQ(5U, compute->GetZ()); EventRecorder event_recorder; compute->GetDebugScript()->Run(&event_recorder); EXPECT_EQ(dbg, event_recorder.events.str()); auto& shaders = compute->GetPipeline()->GetShaders(); ASSERT_EQ(1U, shaders.size()); EXPECT_EQ(true, shaders[0].GetEmitDebugInfo()); } TEST_F(AmberScriptParserTest, DebugEmitDebugInfoVertex) { std::string dbg = R"()"; std::string in = R"( SHADER vertex dbg_vertex GLSL void main() {} END SHADER fragment dbg_fragment GLSL void main() {} END BUFFER position_buf DATA_TYPE R8G8_SNORM DATA 1 1 2 2 3 3 END PIPELINE graphics my_pipeline ATTACH dbg_vertex ATTACH dbg_fragment VERTEX_DATA position_buf LOCATION 0 END DEBUG my_pipeline DRAW_ARRAY AS TRIANGLE_LIST START_IDX 0 COUNT 1 THREAD VERTEX_INDEX 100 END END)"; Parser parser; Result r = parser.Parse(in); ASSERT_TRUE(r.IsSuccess()) << r.Error(); auto script = parser.GetScript(); const auto& commands = script->GetCommands(); ASSERT_EQ(1U, commands.size()); auto* cmd = commands[0].get(); ASSERT_TRUE(cmd->IsDrawArrays()); auto* draw = cmd->AsDrawArrays(); for (auto& shader : draw->GetPipeline()->GetShaders()) { bool expect_debug_info = shader.GetShaderType() == kShaderTypeVertex; EXPECT_EQ(expect_debug_info, shader.GetEmitDebugInfo()) << "Emit debug info for shader type " << shader.GetShaderType(); } } TEST_F(AmberScriptParserTest, DebugEmitDebugInfoFragment) { std::string dbg = R"()"; std::string in = R"( SHADER vertex dbg_vertex GLSL void main() {} END SHADER fragment dbg_fragment GLSL void main() {} END BUFFER position_buf DATA_TYPE R8G8_SNORM DATA 1 1 2 2 3 3 END PIPELINE graphics my_pipeline ATTACH dbg_vertex ATTACH dbg_fragment VERTEX_DATA position_buf LOCATION 0 END DEBUG my_pipeline DRAW_ARRAY AS TRIANGLE_LIST START_IDX 0 COUNT 1 THREAD FRAGMENT_WINDOW_SPACE_POSITION 1 2 END END)"; Parser parser; Result r = parser.Parse(in); ASSERT_TRUE(r.IsSuccess()) << r.Error(); auto script = parser.GetScript(); const auto& commands = script->GetCommands(); ASSERT_EQ(1U, commands.size()); auto* cmd = commands[0].get(); ASSERT_TRUE(cmd->IsDrawArrays()); auto* draw = cmd->AsDrawArrays(); for (auto& shader : draw->GetPipeline()->GetShaders()) { bool expect_debug_info = shader.GetShaderType() == kShaderTypeFragment; EXPECT_EQ(expect_debug_info, shader.GetEmitDebugInfo()) << "Emit debug info for shader type " << shader.GetShaderType(); } } TEST_F(AmberScriptParserTest, DebugEmitNoDebugInfo) { std::string dbg = R"()"; std::string in = R"( SHADER vertex dbg_vertex GLSL void main() {} END SHADER fragment dbg_fragment GLSL void main() {} END BUFFER position_buf DATA_TYPE R8G8_SNORM DATA 1 1 2 2 3 3 END PIPELINE graphics my_pipeline ATTACH dbg_vertex ATTACH dbg_fragment VERTEX_DATA position_buf LOCATION 0 END RUN my_pipeline DRAW_ARRAY AS TRIANGLE_LIST START_IDX 0 COUNT 1 )"; Parser parser; Result r = parser.Parse(in); ASSERT_TRUE(r.IsSuccess()) << r.Error(); auto script = parser.GetScript(); const auto& commands = script->GetCommands(); ASSERT_EQ(1U, commands.size()); auto* cmd = commands[0].get(); ASSERT_TRUE(cmd->IsDrawArrays()); auto* draw = cmd->AsDrawArrays(); for (auto& shader : draw->GetPipeline()->GetShaders()) { EXPECT_EQ(false, shader.GetEmitDebugInfo()); } } } // namespace amberscript } // namespace amber
27.20202
80
0.674588
gnl21
8cf0bd8a0ba7d60fda190434473e0ccb70ed8844
12,874
cpp
C++
Game/Source/Mesh/Mesh.cpp
Crewbee/Pokemon-Clone-DX12
188bdde03d5078899a1532305a87d15c611c6c13
[ "CC0-1.0" ]
null
null
null
Game/Source/Mesh/Mesh.cpp
Crewbee/Pokemon-Clone-DX12
188bdde03d5078899a1532305a87d15c611c6c13
[ "CC0-1.0" ]
null
null
null
Game/Source/Mesh/Mesh.cpp
Crewbee/Pokemon-Clone-DX12
188bdde03d5078899a1532305a87d15c611c6c13
[ "CC0-1.0" ]
null
null
null
#include "GamePCH.h" #include "Mesh/Mesh.h" #include "Mesh.h" Mesh::Mesh() { m_VBO = 0; m_pShader = 0; m_DebugShader = 0; m_MyTexture = 0; m_PrimitiveType = -1; m_NumVerts = 0; IsDebug = false; } Mesh::~Mesh() { glDeleteBuffers(1, &m_VBO); delete m_CanvasVerts; m_CanvasVerts = nullptr; } void SetUniform1f(GLuint shader, const char* uniformName, float value) { GLint loc = glGetUniformLocation(shader, uniformName); if (loc != -1) { glUniform1f(loc, value); } } void SetUniform2f(GLuint shader, const char* uniformName, vec2 value) { GLint loc = glGetUniformLocation(shader, uniformName); if (loc != -1) { glUniform2f(loc, value.x, value.y); } } void Mesh::Draw(vec2 objectPos, float objectAngle, vec2 objectScale, vec2 cameraPos, vec2 projectionScale, GLuint aTexture, vec2 aUVscale, vec2 aUVoffset) { //TEXTURES ARE GLuint assert(m_PrimitiveType != -1); assert(m_NumVerts != 0); assert(m_pShader != 0); assert(m_pShader->GetProgram() != 0); // Bind buffer and set up attributes. glBindBuffer(GL_ARRAY_BUFFER, m_VBO); GLint loc = glGetAttribLocation(m_pShader->GetProgram(), "a_Position"); if (loc != -1) { glVertexAttribPointer(loc, 2, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)offsetof(VertexFormat, m_Pos)); glEnableVertexAttribArray(loc); } loc = glGetAttribLocation(m_pShader->GetProgram(), "a_Color"); if (loc != -1) { glVertexAttribPointer(loc, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(VertexFormat), (void*)offsetof(VertexFormat, m_Color)); glEnableVertexAttribArray(loc); } loc = glGetAttribLocation(m_pShader->GetProgram(), "a_UVCoord"); if(loc != -1) { glVertexAttribPointer(loc, 2, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)offsetof(VertexFormat, m_UV)); glEnableVertexAttribArray(loc); } // Set up shader. GLuint shader = m_pShader->GetProgram(); glUseProgram(shader); // Set up uniforms. SetUniform2f(shader, "u_ObjectScale", objectScale); SetUniform1f(shader, "u_ObjectAngleRadians", objectAngle / 180.0f * PI); SetUniform2f(shader, "u_ObjectPosition", objectPos); SetUniform2f(shader, "u_CameraTranslation", cameraPos * -1); SetUniform2f(shader, "u_ProjectionScale", projectionScale); glActiveTexture(GL_TEXTURE0 + 8); glBindTexture(GL_TEXTURE_2D, aTexture); GLuint texture = glGetUniformLocation(m_pShader->GetProgram(), "u_TextureSampler"); glUniform1i(texture, 8); SetUniform2f(shader, "u_UVScale", aUVscale); SetUniform2f(shader, "u_UVOffset", aUVoffset); CheckForGLErrors(); // Draw. glDrawArrays(m_PrimitiveType, 0, m_NumVerts); if (IsDebug == true) { DebugDraw(objectPos, objectAngle, objectScale, cameraPos, projectionScale); } CheckForGLErrors(); } void Mesh::DrawCanvas(vec2 cameraPos, vec2 projectionScale, GLuint aTexture) { //TEXTURES ARE GLuint assert(m_PrimitiveType != -1); assert(m_NumVerts != 0); assert(m_pShader != 0); assert(m_pShader->GetProgram() != 0); // Bind buffer and set up attributes. glBindBuffer(GL_ARRAY_BUFFER, m_VBO); GLint loc = glGetAttribLocation(m_pShader->GetProgram(), "a_Position"); if (loc != -1) { glVertexAttribPointer(loc, 2, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)offsetof(VertexFormat, m_Pos)); glEnableVertexAttribArray(loc); } loc = glGetAttribLocation(m_pShader->GetProgram(), "a_Color"); if (loc != -1) { glVertexAttribPointer(loc, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(VertexFormat), (void*)offsetof(VertexFormat, m_Color)); glEnableVertexAttribArray(loc); } loc = glGetAttribLocation(m_pShader->GetProgram(), "a_UVCoord"); if (loc != -1) { glVertexAttribPointer(loc, 2, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)offsetof(VertexFormat, m_UV)); glEnableVertexAttribArray(loc); } // Set up shader. GLuint shader = m_pShader->GetProgram(); glUseProgram(shader); // Set up uniforms. SetUniform2f(shader, "u_ObjectScale", 1); SetUniform1f(shader, "u_ObjectAngleRadians", 0 / 180.0f * PI); SetUniform2f(shader, "u_ObjectPosition", vec2(0.0f, 0.0f)); SetUniform2f(shader, "u_CameraTranslation", cameraPos * -1); SetUniform2f(shader, "u_ProjectionScale", projectionScale); glActiveTexture(GL_TEXTURE0 + 8); glBindTexture(GL_TEXTURE_2D, aTexture); GLuint texture = glGetUniformLocation(m_pShader->GetProgram(), "u_TextureSampler"); glUniform1i(texture, 8); SetUniform2f(shader, "u_UVScale", vec2(1.0f, 1.0f)); SetUniform2f(shader, "u_UVOffset", vec2(0.0f, 0.0f)); CheckForGLErrors(); // Draw. glDrawArrays(m_PrimitiveType, 0, m_NumVerts); if (IsDebug == true) { DebugDraw(vec2(0.0f, 0.0f), 0 / 180.0f * PI, 1, cameraPos, projectionScale); } CheckForGLErrors(); } void Mesh::DebugDraw(vec2 objectPos, float objectAngle, vec2 objectScale, vec2 camPos, vec2 projScale) { //TEXTURES ARE GLuint assert(m_PrimitiveType != -1); assert(m_NumVerts != 0); assert(m_DebugShader != 0); assert(m_DebugShader->GetProgram() != 0); // Bind buffer and set up attributes. glBindBuffer(GL_ARRAY_BUFFER, m_VBO); GLint loc = glGetAttribLocation(m_DebugShader->GetProgram(), "a_Position"); if (loc != -1) { glVertexAttribPointer(loc, 2, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)offsetof(VertexFormat, m_Pos)); glEnableVertexAttribArray(loc); } loc = glGetAttribLocation(m_DebugShader->GetProgram(), "a_Color"); if (loc != -1) { glVertexAttribPointer(loc, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(VertexFormat), (void*)offsetof(VertexFormat, m_Color)); glEnableVertexAttribArray(loc); } // Set up shader. GLuint shader = m_DebugShader->GetProgram(); glUseProgram(shader); // Set up uniforms. SetUniform2f(shader, "u_ObjectScale", objectScale); SetUniform1f(shader, "u_ObjectAngleRadians", objectAngle / 180.0f * PI); SetUniform2f(shader, "u_ObjectPosition", objectPos); SetUniform2f(shader, "u_CameraTranslation", camPos * -1); SetUniform2f(shader, "u_ProjectionScale", projScale); glDrawArrays(GL_LINE_LOOP, 0, m_NumVerts); } void Mesh::GenerateTriangle() { // ATM this can only be called once, so we assert if it's called again with a VBO already allocated. assert(m_VBO == 0); // Vertex info for a diamond. VertexFormat vertexAttributes[] = { VertexFormat(vec2(0.0f, 1.0f), MyColor(255, 255, 255, 255), vec2(0.5f, 1.0f)), VertexFormat(vec2(-0.5f, -1.0f), MyColor(255, 255, 255, 255), vec2(0.25f, 0.0f)), VertexFormat(vec2(0.5f, -1.0f), MyColor(255, 255, 255, 255), vec2(0.75f, 0.0f)), }; // Gen and fill buffer with our attributes. glGenBuffers(1, &m_VBO); glBindBuffer(GL_ARRAY_BUFFER, m_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(VertexFormat) * 3, vertexAttributes, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); m_PrimitiveType = GL_TRIANGLES; m_NumVerts = 3; // Check for errors. CheckForGLErrors(); } void Mesh::GenerateCircle() { // ATM this can only be called once, so we assert if it's called again with a VBO already allocated. assert(m_VBO == 0); // Vertex position info for a diamond. VertexFormat vertexAttributes[] = { VertexFormat(vec2(0.0f, 1.0f), MyColor(0, 255, 0, 255), vec2(0.5f, 1.0f)), VertexFormat(vec2(-1.0f, 0.0f), MyColor(0, 255, 0, 255), vec2(0.0f, 0.5f)), VertexFormat(vec2(1.0f, 0.0f), MyColor(0, 255, 0, 255), vec2(1.0f, 0.5f)), VertexFormat(vec2(0.0f, -1.0f), MyColor(0, 255, 0, 255), vec2(0.5f, 0.0f)), }; // Gen and fill buffer with our attributes. glGenBuffers(1, &m_VBO); glBindBuffer(GL_ARRAY_BUFFER, m_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(VertexFormat) * 4, vertexAttributes, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); m_PrimitiveType = GL_TRIANGLE_STRIP; m_NumVerts = 4; // Check for errors. CheckForGLErrors(); } void Mesh::GeneratePolygon(float radius, int vertices, char r, char g, char b, char a) { // ATM this can only be called once, so we assert if it's called again with a VBO already allocated assert(m_VBO == 0); p_MyRadius = radius; p_MyWidth = radius * 2; p_MyHeight = radius * 2; std::vector<float> m_Circle; float x = 0.0f; float y = 0.0f; int num_floats = (vertices + 2) * 2; m_Circle.push_back(x); m_Circle.push_back(y); for (int i = 1; i <= vertices; i++) { x = -(radius * cos(i * (2.0f * PI / vertices))); y = -(radius * sin(i * (2.0f * PI / vertices))); m_Circle.push_back(x); m_Circle.push_back(y); m_Circle.push_back(r); m_Circle.push_back(g); m_Circle.push_back(b); m_Circle.push_back(a); } x = -(radius * cos(1 * (2.0f * PI / vertices))); y = -(radius * sin(1 * (2.0f * PI / vertices))); m_Circle.push_back(x); m_Circle.push_back(y); m_Circle.push_back(r); m_Circle.push_back(g); m_Circle.push_back(b); m_Circle.push_back(a); /*for (int i = 0; i < m_Circle.size(); i++); { }*/ // Generate and fill buffer with our attributes. glGenBuffers(1, &m_VBO); glBindBuffer(GL_ARRAY_BUFFER, m_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * m_Circle.size(), &m_Circle.front(), GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); m_PrimitiveType = GL_TRIANGLE_FAN; m_NumVerts = vertices + 2; // Check for errors. CheckForGLErrors(); } void Mesh::GenerateFrameMesh() { assert(m_VBO == 0); VertexFormat vertexAttributes[] = { VertexFormat(vec2(0.0f, 0.0f), MyColor(0, 255, 0, 255), vec2(0.0f, 0.0f)), VertexFormat(vec2(0.0f, 1.0f), MyColor(0, 255, 0, 255), vec2(0.0f, 1.0f)), VertexFormat(vec2(1.0f, 1.0f), MyColor(0, 255, 0, 255), vec2(1.0f, 1.0f)), VertexFormat(vec2(1.0f, 0.0f), MyColor(0, 255, 0, 255), vec2(1.0f, 0.0f)), }; // Gen and fill buffer with our attributes. glGenBuffers(1, &m_VBO); glBindBuffer(GL_ARRAY_BUFFER, m_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(VertexFormat) * 4, vertexAttributes, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); m_PrimitiveType = GL_TRIANGLE_FAN; m_NumVerts = 4; } void Mesh::GenerateTileMesh() { assert(m_VBO == 0); VertexFormat vertexAttributes[] = { VertexFormat(vec2(0.0f, 0.0f), MyColor(255, 255, 255, 255), vec2(0.0f, 0.0f)), VertexFormat(vec2(0.0f, 1.0f), MyColor(255, 255, 255, 255), vec2(0.0f, 1.0f)), VertexFormat(vec2(1.0f, 1.0f), MyColor(255, 255, 255, 255), vec2(1.0f, 1.0f)), VertexFormat(vec2(1.0f, 0.0f), MyColor(255, 255, 255, 255), vec2(1.0f, 0.0f)), }; // Gen and fill buffer with our attributes. glGenBuffers(1, &m_VBO); glBindBuffer(GL_ARRAY_BUFFER, m_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(VertexFormat) * 4, vertexAttributes, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); m_PrimitiveType = GL_TRIANGLE_FAN; m_NumVerts = 4; } void Mesh::GenerateWildTileMesh() { assert(m_VBO == 0); VertexFormat vertexAttributes[] = { VertexFormat(vec2(0.0f, 0.0f), MyColor(255, 0, 0, 255), vec2(0.0f, 0.0f)), VertexFormat(vec2(0.0f, 1.0f), MyColor(255, 0, 0, 255), vec2(0.0f, 1.0f)), VertexFormat(vec2(1.0f, 1.0f), MyColor(255, 0, 0, 255), vec2(1.0f, 1.0f)), VertexFormat(vec2(1.0f, 0.0f), MyColor(255, 0, 0, 255), vec2(1.0f, 0.0f)), }; // Gen and fill buffer with our attributes. glGenBuffers(1, &m_VBO); glBindBuffer(GL_ARRAY_BUFFER, m_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(VertexFormat) * 4, vertexAttributes, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); m_PrimitiveType = GL_LINE_LOOP; m_NumVerts = 4; } void Mesh::GenerateTextureMesh(vec2 aSize) { assert(m_VBO == 0); VertexFormat vertexAttributes[] = { VertexFormat(vec2(0.0f, 0.0f), MyColor(255, 255, 255, 255), vec2(0.0f, 0.0f)), VertexFormat(vec2(0.0f, aSize.y), MyColor(255, 255, 255, 255), vec2(0.0f, 1.0f)), VertexFormat(vec2(aSize.x, aSize.y), MyColor(255, 255, 255, 255), vec2(1.0f, 1.0f)), VertexFormat(vec2(aSize.x, 0.0f), MyColor(255, 255, 255, 255), vec2(1.0f, 0.0f)), }; // Gen and fill buffer with our attributes. glGenBuffers(1, &m_VBO); glBindBuffer(GL_ARRAY_BUFFER, m_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(VertexFormat) * 4, vertexAttributes, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); m_PrimitiveType = GL_TRIANGLE_FAN; m_NumVerts = 4; } void Mesh::GenerateDebugMesh() { assert(m_VBO == 0); VertexFormat vertexAttributes[] = { VertexFormat(vec2(0.0f, 1.0f), MyColor(255, 255, 255, 255), vec2(0.0f, 1.0f)), VertexFormat(vec2(1.0f, 1.0f), MyColor(255, 255, 255, 255), vec2(1.0f, 1.0f)), VertexFormat(vec2(1.0f, 0.0f), MyColor(255, 255, 255, 255), vec2(1.0f, 0.0f)), VertexFormat(vec2(0.0f, 0.0f), MyColor(255, 255, 255, 255), vec2(0.0f, 0.0f)), }; glGenBuffers(1, &m_VBO); glBindBuffer(GL_ARRAY_BUFFER, m_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(VertexFormat) * 4, vertexAttributes, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); m_NumVerts = 4; } void Mesh::GenterateCanvasMesh(int aSize) { assert(m_VBO == 0); glGenBuffers(1, &m_VBO); glBindBuffer(GL_ARRAY_BUFFER, m_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(VertexFormat) * aSize, &m_CanvasVerts->front(), GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); m_PrimitiveType = GL_TRIANGLE_STRIP; m_NumVerts = aSize; }
28.608889
154
0.706385
Crewbee
8cfb4bcbe814c5d99179d03013264c2e30941531
1,236
cpp
C++
coding/codeforces/1352_F.cpp
aguilarpgc/coding-preparation
00547d499adda5a6cdbe90acae8a0e88a2d8d69e
[ "MIT" ]
4
2021-04-11T23:55:54.000Z
2022-03-07T20:06:33.000Z
coding/codeforces/1352_F.cpp
aguilarpgc/coding-preparation
00547d499adda5a6cdbe90acae8a0e88a2d8d69e
[ "MIT" ]
null
null
null
coding/codeforces/1352_F.cpp
aguilarpgc/coding-preparation
00547d499adda5a6cdbe90acae8a0e88a2d8d69e
[ "MIT" ]
null
null
null
//#include <bits/stdc++.h> #include <iostream> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); int t,n0,n1,n2; cin >> t; while(t--) { cin >> n0 >> n1 >> n2; if(n1 != 0 && n1 % 2 == 0) { for (int i=0; i<n0; i++) { cout << "0"; } for (int i=0; i<n1/2; i++) { cout << "01"; } if (n2 != 0) { for (int i=0; i<n2; i++) { cout << "1"; } } cout << "0"; } else { for (int i=0; i<n0; i++) { cout << "0"; } if (n1 != 0) { for (int i=0; i<(n1+1)/2; i++) { cout << "01"; } } else if(n0 != 0){ cout << "0"; } if (n2 != 0) { for (int i=0; i<n2; i++) { cout << "1"; } if(n1 == 0) { cout << "1"; } } } cout << endl; } return 0; }
20.6
48
0.233819
aguilarpgc
8cfccde61a7ae78891597b2c8c90d4dfc9599cc0
571
cpp
C++
src/main.cpp
vg132/dreamcast-tetris-2
1390da9766a835c3ee62aabba770acee9f2e68fa
[ "BSD-3-Clause" ]
2
2019-08-09T18:36:47.000Z
2020-04-14T21:03:26.000Z
src/main.cpp
vg132/dreamcast-tetris-2
1390da9766a835c3ee62aabba770acee9f2e68fa
[ "BSD-3-Clause" ]
null
null
null
src/main.cpp
vg132/dreamcast-tetris-2
1390da9766a835c3ee62aabba770acee9f2e68fa
[ "BSD-3-Clause" ]
1
2022-01-02T07:51:21.000Z
2022-01-02T07:51:21.000Z
#include <kos.h> #include "tetris.hpp" pvr_init_params_t params = { /* Enable opaque and translucent polygons with size 16 */ {PVR_BINSIZE_16, PVR_BINSIZE_0, PVR_BINSIZE_16, PVR_BINSIZE_0, PVR_BINSIZE_0}, /* Vertex buffer size 512K */ 512 * 1024 }; #ifdef _TETRIS_DEBUG_ extern uint8 romdisk[]; KOS_INIT_ROMDISK(romdisk); #endif int main(int argc, char **argv) { dbglog(DBG_INFO, "--main()\n"); pvr_init (&params); CTetris *t(NULL); int ret(0); //malloc_stats(); t=new CTetris(); ret=t->Start(); delete t; //malloc_stats(); return(ret); }
17.84375
64
0.677758
vg132
ea08b451a1625fab887ceaec8b378f583727a602
325
cpp
C++
WPFTencentQQ/CipherLib/Md5.cpp
alex2ching/QQConnector
e688274e466b91acdbc724a1458b3aeedb04079d
[ "MIT" ]
10
2020-09-07T14:18:33.000Z
2022-01-15T16:39:25.000Z
WPFTencentQQ/CipherLib/Md5.cpp
alex2ching/QQConnector
e688274e466b91acdbc724a1458b3aeedb04079d
[ "MIT" ]
null
null
null
WPFTencentQQ/CipherLib/Md5.cpp
alex2ching/QQConnector
e688274e466b91acdbc724a1458b3aeedb04079d
[ "MIT" ]
5
2021-04-19T02:15:58.000Z
2022-02-05T14:55:57.000Z
#include "StdAfx.h" #include "Md5.h" #include <openssl\md5.h> CMd5::CMd5(void) { } CMd5::~CMd5(void) { } void CMd5::GetMd5(unsigned char *szMd5,size_t len,unsigned char *szData,size_t size) { if(len<0x10) return; MD5_CTX c; MD5_Init(&c); MD5_Update(&c, szData, size); MD5_Final(szMd5,&c); }
14.130435
85
0.624615
alex2ching
ea0a28a9d2716606d254382be5446bf8880bb40e
1,860
cpp
C++
Code/Libraries/Workbench/src/PEs/wbpestatmod.cpp
kas1e/Eldritch
032b4ac52f7508c89efa407d6fe60f40c6281fd9
[ "Zlib" ]
null
null
null
Code/Libraries/Workbench/src/PEs/wbpestatmod.cpp
kas1e/Eldritch
032b4ac52f7508c89efa407d6fe60f40c6281fd9
[ "Zlib" ]
null
null
null
Code/Libraries/Workbench/src/PEs/wbpestatmod.cpp
kas1e/Eldritch
032b4ac52f7508c89efa407d6fe60f40c6281fd9
[ "Zlib" ]
null
null
null
#include "core.h" #include "wbpestatmod.h" #include "configmanager.h" #include "Components/wbcompstatmod.h" #include "wbparamevaluatorfactory.h" WBPEStatMod::WBPEStatMod() : m_StatName(), m_EntityPE(nullptr) {} WBPEStatMod::~WBPEStatMod() { SafeDelete(m_EntityPE); } /*virtual*/ void WBPEStatMod::InitializeFromDefinition( const SimpleString& DefinitionName) { WBPEUnaryOp::InitializeFromDefinition(DefinitionName); MAKEHASH(DefinitionName); STATICHASH(StatName); m_StatName = ConfigManager::GetHash(sStatName, HashedString::NullString, sDefinitionName); STATICHASH(EntityPE); m_EntityPE = WBParamEvaluatorFactory::Create( ConfigManager::GetString(sEntityPE, "", sDefinitionName)); } /*virtual*/ void WBPEStatMod::Evaluate( const WBParamEvaluator::SPEContext& Context, WBParamEvaluator::SEvaluatedParam& EvaluatedParam) const { ASSERT(Context.m_Entity); WBParamEvaluator::SEvaluatedParam EntityValue; m_EntityPE->Evaluate(Context, EntityValue); WBEntity* const pEntity = EntityValue.GetEntity(); WBCompStatMod* const pStatMod = SAFE_GET_WBCOMP(pEntity, StatMod); WBParamEvaluator::SEvaluatedParam Value; m_Input->Evaluate(Context, Value); ASSERT(Value.m_Type == WBParamEvaluator::EPT_Int || Value.m_Type == WBParamEvaluator::EPT_Float); if (Value.m_Type == WBParamEvaluator::EPT_Int) { EvaluatedParam.m_Type = WBParamEvaluator::EPT_Int; EvaluatedParam.m_Int = pStatMod ? static_cast<int>(pStatMod->ModifyFloat( Value.GetFloat(), m_StatName)) : Value.m_Int; } else { EvaluatedParam.m_Type = WBParamEvaluator::EPT_Float; EvaluatedParam.m_Float = pStatMod ? pStatMod->ModifyFloat(Value.GetFloat(), m_StatName) : Value.GetFloat(); } }
34.444444
77
0.702151
kas1e
ea14fe683331d3c2bdcecc864dc2cc00c0fb2871
27,318
hpp
C++
src/tissot_bg_writer.hpp
barendgehrels/tissot
b0d983a57bcd4d283c0f4ef8d23abea2e2893c3f
[ "BSL-1.0" ]
1
2015-05-17T11:15:43.000Z
2015-05-17T11:15:43.000Z
src/tissot_bg_writer.hpp
barendgehrels/tissot
b0d983a57bcd4d283c0f4ef8d23abea2e2893c3f
[ "BSL-1.0" ]
null
null
null
src/tissot_bg_writer.hpp
barendgehrels/tissot
b0d983a57bcd4d283c0f4ef8d23abea2e2893c3f
[ "BSL-1.0" ]
null
null
null
#ifndef TISSOT_WRITER_HPP #define TISSOT_WRITER_HPP // Tissot, converts projecton source code (Proj4) to Boost.Geometry // (or potentially other source code) // // Copyright (c) 2015 Barend Gehrels, Amsterdam, the Netherlands. // // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/foreach.hpp> #include <sstream> namespace boost { namespace geometry { namespace proj4converter { class proj4_writer_cpp_bg { public : proj4_writer_cpp_bg(projection_properties& projpar , std::string const& group , std::vector<epsg_entry> const& epsg_entries , std::ostream& str) : m_projpar(projpar) , stream(str) , m_epsg_entries(epsg_entries) , projection_group(group) , hpp("BOOST_GEOMETRY_PROJECTIONS_" + boost::to_upper_copy(projection_group) + "_HPP") { } void write() { stream << "#ifndef " << hpp << std::endl << "#define " << hpp << std::endl << std::endl; write_copyright(); write_header(); write_begin_impl(); { write_consts(); write_extra_structs(); if (m_projpar.parstruct_first) { write_proj_par_struct(); } write_prefix(); if (! m_projpar.parstruct_first) { write_proj_par_struct(); } write_impl_classes(); write_postfix(); write_setup(); } write_end_impl(); write_classes(); write_wrappers(); write_end(); } private : std::ostream& stream; template <typename Container> void write_endl_if_filled(Container const& c) { if (! c.empty()) { stream << std::endl; } } void write_copyright_file(std::string const& filename) { std::ifstream cr_file (filename.c_str()); if (cr_file.is_open()) { while (! cr_file.eof() ) { std::string line; std::getline(cr_file, line); stream << line << std::endl; } cr_file.close(); } } void write_copyright() { write_copyright_file("../src/tissot_bg_copyright_header1.txt"); stream << "// Last updated version of proj: 4.9.1" << std::endl << std::endl; stream << "// Original copyright notice:" << std::endl << std::endl; if (! m_projpar.first_comments.empty()) { BOOST_FOREACH(std::string const& s, m_projpar.first_comments) { stream << "// " << s << std::endl; } stream << std::endl; } write_copyright_file("../src/tissot_bg_copyright_header2.txt"); } void write_header() { BOOST_FOREACH(std::string const& s, m_projpar.extra_includes) { stream << "#include <" << s << ">" << std::endl; } write_endl_if_filled(m_projpar.extra_includes); stream << include_projections << "/impl/base_static.hpp>" << std::endl << include_projections << "/impl/base_dynamic.hpp>" << std::endl << include_projections << "/impl/projects.hpp>" << std::endl << include_projections << "/impl/factory_entry.hpp>" << std::endl ; BOOST_FOREACH(std::string const& s, m_projpar.extra_proj_includes) { stream << include_projections << "/proj/" << s << ">" << std::endl; } BOOST_FOREACH(std::string const& s, m_projpar.extra_impl_includes) { stream << include_projections << "/impl/" << s << ">" << std::endl; } if (use_epsg()) { stream << std::endl; stream << include_projections << "/epsg_traits.hpp>" << std::endl; } stream << std::endl; stream << "namespace boost { namespace geometry { namespace projections" << std::endl << "{" << std::endl; if (! m_projpar.forward_declarations.empty()) { stream << std::endl << tab1 << m_projpar.forward_declarations << std::endl << std::endl; } } void write_begin_impl() { stream << tab1 << "#ifndef DOXYGEN_NO_DETAIL" << std::endl << tab1 << "namespace detail { namespace " << projection_group << std::endl << tab1 << "{" << std::endl << std::endl; } void write_extra_structs() { BOOST_FOREACH(std::string const& s, m_projpar.extra_structs) { stream << tab3 << s << std::endl; } write_endl_if_filled(m_projpar.extra_structs); std::string ts = m_projpar.template_struct; if (! ts.empty()) { stream << tab3 << "template <"; if (ts == "<Cartesian>") { stream << "typename Cartesian"; } else if (ts == "<Geographic, Cartesian>") { stream << "typename Geographic, typename Cartesian"; } else if (ts == "<Geographic, Cartesian, Parameters>") { stream << "typename Geographic, typename Cartesian, typename Parameters"; } stream << ">" << std::endl; } } void write_proj_par_struct() { if (! m_projpar.proj_parameters.empty()) { stream << tab3 << "struct par_" << projection_group << std::endl << tab3 << "{" << std::endl; for (std::vector<std::string>::const_iterator it = m_projpar.proj_parameters.begin(); it != m_projpar.proj_parameters.end(); ++it) { stream << tab4 << *it << std::endl; } stream << tab3 << "};" << std::endl << std::endl; } } void write_consts() { BOOST_FOREACH(macro_or_const const& con, m_projpar.defined_consts) { stream << tab3 << "static const " << con.type << " " << con.name << " = " << con.value << ";" << std::endl; } write_endl_if_filled(m_projpar.defined_consts); BOOST_FOREACH(macro_or_const const& macro, m_projpar.defined_macros) { stream << tab3 << "#define " << macro.name << " " << macro.value << std::endl; } write_endl_if_filled(m_projpar.defined_macros); } std::string preceded(std::string const& tab, std::string const& line) const { if (line.empty()) { return line; } return tab + line; } void write_prefix() { BOOST_FOREACH(std::string const& line, m_projpar.inlined_functions) { stream << preceded(tab3, line) << std::endl; } write_endl_if_filled(m_projpar.inlined_functions); } void write_postfix() { if (m_projpar.setup_functions.size() > 0 && ! m_projpar.setup_function_line.empty() ) { if (! m_projpar.proj_parameters.empty()) { // Modify the setup function: add project parameter std::string tag = "Parameters& par"; std::string::size_type loc = m_projpar.setup_function_line.find(tag); if (loc != std::string::npos) { m_projpar.setup_function_line.insert(loc + tag.length(), ", par_" + projection_group + "& proj_parm"); } } stream << tab3 << "template <typename Parameters>" << std::endl << tab3 << m_projpar.setup_function_line << std::endl << tab3 << "{" << std::endl; BOOST_FOREACH(std::string const& line, m_projpar.setup_functions) { stream << preceded(tab3, line) << std::endl; } stream << std::endl << std::endl; } } void write_impl_classes() { std::string current_model; std::string current_subgroup; for (size_t i = 0; i < m_projpar.projections.size(); i++) { projection const& proj = m_projpar.projections[i]; if (proj.model != current_model || proj.subgroup != current_subgroup) { std::string name = "base_" + proj.subgroup + "_" + proj.model; std::string tbase = "base_t_f"; if (proj.has_inverse) { tbase += "i"; // base_fi } tbase += "<" + name + "<Geographic, Cartesian, Parameters>," + "\n" + tab5 + " Geographic, Cartesian, Parameters>"; stream << tab3 << "// template class, using CRTP to implement forward/inverse" << std::endl << tab3 << "template <typename Geographic, typename Cartesian, typename Parameters>" << std::endl << tab3 << "struct " << name << " : public " << tbase << std::endl << tab3 << "{" << std::endl << std::endl; // for GCC (probably standard) typedefs again are necessary stream //<< tab4 << "typedef typename " << tbase << "::geographic_type geographic_type;" << std::endl //<< tab4 << "typedef typename " << tbase << "::cartesian_type cartesian_type;" << std::endl << tab4 << " typedef double geographic_type;" << std::endl << tab4 << " typedef double cartesian_type;" << std::endl << std::endl; // optional project specific parameter variable if (! m_projpar.proj_parameters.empty()) { stream << tab4 << "par_" << projection_group << m_projpar.template_struct << " m_proj_parm;" << std::endl; } stream << std::endl // constructor << tab4 << "inline " << name << "(const Parameters& par)" << std::endl << tab5 << ": " << tbase << "(*this, par)"; BOOST_FOREACH(std::string const& s, m_projpar.extra_member_initialization_list) { stream << ", " << s; } stream << " {}" << std::endl << std::endl; } if (proj.model != current_model) { BOOST_FOREACH(std::string const& s, proj.preceding_lines) { stream << tab4 << s << std::endl; } write_endl_if_filled(proj.preceding_lines); } if (proj.direction == "special_factors") { stream << tab4 << "#ifdef SPECIAL_FACTORS_NOT_CONVERTED" << std::endl; } stream << tab4 << "inline void "; if (proj.direction == "forward") { stream << "fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y"; } else if (proj.direction == "inverse") { stream << "inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat"; } else if (proj.direction == "special_factors") { stream << "fac(Geographic lp, Factors &fac"; } else { stream << proj.direction << "("; } stream << ") const" << std::endl << tab4 << "{" << std::endl; for (size_t j = 0; j < proj.lines.size(); j++) { stream << preceded(tab4, proj.lines[j]) << std::endl; } stream << tab4 << "}" << std::endl; BOOST_FOREACH(std::string const& line, proj.trailing_lines) { stream << preceded(tab4, line) << std::endl; } if (proj.direction == "special_factors") { stream << tab4 << "#endif" << std::endl; } // End of class if (i == m_projpar.projections.size() - 1 || m_projpar.projections[i + 1].model != m_projpar.projections[i].model) { stream << tab3 << "};" << std::endl; } stream << std::endl; current_model = proj.model; current_subgroup = proj.subgroup; } } bool use_epsg() const { BOOST_FOREACH(derived const& der, m_projpar.derived_projections) { BOOST_FOREACH(epsg_entry const& entry, m_epsg_entries) { if (entry.prj_name == der.name) { return true; } } } return false; } void write_setup() { BOOST_FOREACH(derived const& der, m_projpar.derived_projections) { stream << tab3 << "// " << der.description << std::endl << tab3 << "template <"; std::string ts = m_projpar.template_struct; if (! ts.empty()) { stream << "typename "; if (ts == "<Cartesian>") stream << "Cartesian"; else if (ts == "<Geographic, Cartesian>" || ts == "<Geographic, Cartesian, Parameters>") stream << "Geographic, typename Cartesian"; stream << ", "; } stream << "typename Parameters>" << std::endl << tab3 << (m_projpar.setup_return_type.empty() ? "void" : m_projpar.setup_return_type) << " setup_" << der.name << "(Parameters& par"; if (! m_projpar.proj_parameters.empty()) { stream << ", par_" << projection_group << m_projpar.template_struct << "& proj_parm"; } stream << m_projpar.setup_extra_parameters << ")" << std::endl << tab3 << "{" << std::endl; BOOST_FOREACH(std::string const& s, der.constructor_lines) { std::string line = s; if (boost::starts_with(boost::trim_copy(line), "setup") && ! m_projpar.proj_parameters.empty()) { // Insert second parameter if necessary. boost::replace_all(line, "par,", "par, proj_parm,"); boost::replace_all(line, "par)", "par, proj_parm)"); if (boost::starts_with(line, "setup")) { line = tab1 + line; } } stream << preceded(tab3, line) << std::endl; } stream << tab3 << "}" << std::endl << std::endl; } } void write_end_impl() { stream << tab2 << "}} // namespace detail::" << projection_group << std::endl << tab1 << "#endif // doxygen" << std::endl << std::endl; } void write_end() { stream << "}}} // namespace boost::geometry::projections" << std::endl << std::endl << "#endif // " << hpp << std::endl << std::endl; } void write_classes() { BOOST_FOREACH(derived const& der, m_projpar.derived_projections) { BOOST_FOREACH(model const& mod, der.models) { std::string name = der.name + "_" + mod.name; if (mod.subgroup != projection_group) { name = mod.subgroup + "_" + mod.name; } if (m_projpar.valid) { std::string base = "detail::" + projection_group + "::base_" + mod.subgroup + "_" + mod.name + "<Geographic, Cartesian, Parameters>"; // Doxygen comments stream << tab1 << "/*!" << std::endl << tab2 << "\\brief " << der.description << " projection" << std::endl << tab2 << "\\ingroup projections" << std::endl << tab2 << "\\tparam Geographic latlong point type" << std::endl << tab2 << "\\tparam Cartesian xy point type" << std::endl << tab2 << "\\tparam Parameters parameter type" << std::endl ; if (! der.parsed_characteristics.empty()) { stream << tab2 << "\\par Projection characteristics" << std::endl; BOOST_FOREACH(std::string const& ch, der.parsed_characteristics) { stream << tab2 << " - " << ch << std::endl; } } if (! der.parsed_parameters.empty()) { stream << tab2 << "\\par Projection parameters" << std::endl; BOOST_FOREACH(parameter const& p, der.parsed_parameters) { stream << tab2 << " - " << p.name; if (! p.explanation.empty()) { stream << ": " << p.explanation; } if (! p.type.empty()) { stream << " (" << p.type << ")"; } stream << std::endl; } } stream << tab2 << "\\par Example" << std::endl << tab2 << "\\image html ex_" << der.name << ".gif" << std::endl << tab1 << "*/" << std::endl; // Class itself stream << tab1 << "template <typename Geographic, typename Cartesian, typename Parameters = parameters>" << std::endl << tab1 << "struct " << name << " : public " << base << std::endl << tab1 << "{" << std::endl << tab2 << "inline " << name << "(const Parameters& par) : " << base << "(par)" << std::endl << tab2 << "{" << std::endl << tab3 << "detail::" << projection_group << "::setup_" << der.name << "(this->m_par"; if (! m_projpar.proj_parameters.empty()) { stream << ", this->m_proj_parm"; } stream << ");" << std::endl << tab2 << "}" << std::endl << tab1 << "};" << std::endl << std::endl; } } } } void write_wrappers() { stream << tab1 << "#ifndef DOXYGEN_NO_DETAIL" << std::endl << tab1 << "namespace detail" << std::endl << tab1 << "{" << std::endl << std::endl; std::string templates = "template <typename Geographic, typename Cartesian, typename Parameters>"; // TEMP: get model from below // TODO: get model from epsg-parameter std::string epsg_model = ""; // Create factory entries // This complicated piece has // - to decide to take either "ellipsoid" or "spheroid" based on the input parameter // - to decide if it is the forward or forward/reverse model stream << tab2 << "// Factory entry(s)" << std::endl; BOOST_FOREACH(derived const& der, m_projpar.derived_projections) { stream << tab2 << templates << std::endl << tab2 << "class " << der.name << "_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>" << std::endl << tab2 << "{" << std::endl << tab3 << "public :" << std::endl << tab4 << "virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const" << std::endl << tab4 << "{" << std::endl; if (! m_projpar.setup_extra_code.empty()) { BOOST_FOREACH(std::string const& s, m_projpar.setup_extra_code) { stream << preceded(tab5, s) << std::endl; } } std::string tab = tab5; // Add tab and check of models are correct (TODO: move to separate check source) if (der.models.size() > 1u) { tab += tab1; BOOST_FOREACH(model const& mod, der.models) { BOOST_ASSERT(! mod.condition.empty()); } } else { BOOST_FOREACH(model const& mod, der.models) { BOOST_ASSERT(mod.condition.empty()); } } BOOST_FOREACH(model const& mod, der.models) { if (! mod.condition.empty()) { stream << tab5 << mod.condition << std::endl; } std::string base = "base_v_f"; if (mod.has_inverse) { base += "i"; } std::string name = der.name + "_" + mod.name; stream << tab << "return new " << base << "<" << name << "<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);" << std::endl; if (epsg_model.empty()) { epsg_model = mod.name; } } stream << tab4 << "}" << std::endl << tab2 << "};" << std::endl << std::endl; } // Create "PRJ_init" function for registration at factory stream << tab2 << templates << std::endl << tab2 << "inline void " << projection_group << "_init(detail::base_factory<Geographic, Cartesian, Parameters>& factory)" << std::endl << tab2 << "{" << std::endl; BOOST_FOREACH(derived const& der, m_projpar.derived_projections) { stream << tab3 << "factory.add_to_factory(\"" << der.name << "\", new " << der.name << "_entry<Geographic, Cartesian, Parameters>);" << std::endl; } stream << tab2 << "}" << std::endl << std::endl; stream << tab1 << "} // namespace detail" << std::endl; // Create EPSG specializations if (use_epsg()) { stream << tab1 << "// Create EPSG specializations" << std::endl << tab1 << "// (Proof of Concept, only for some)" << std::endl << std::endl; BOOST_FOREACH(derived const& der, m_projpar.derived_projections) { BOOST_FOREACH(epsg_entry const& entry, m_epsg_entries) { if (entry.prj_name == der.name) { stream << tab1 << "template<typename LatLongRadian, typename Cartesian, typename Parameters>" << std::endl << tab1 << "struct epsg_traits<" << entry.epsg_code << ", LatLongRadian, Cartesian, Parameters>" << std::endl << tab1 << "{" << std::endl // TODO, model, see above << tab2 << "typedef " << der.name << "_" << epsg_model << "<LatLongRadian, Cartesian, Parameters> type;" << std::endl << tab2 << "static inline std::string par()" << std::endl << tab2 << "{" << std::endl << tab3 << "return \"" << entry.parameters << "\";" << std::endl << tab2 << "}" << std::endl << tab1 << "};" << std::endl << std::endl << std::endl; } } } } stream << tab1 << "#endif // doxygen" << std::endl << std::endl; } projection_properties& m_projpar; std::vector<epsg_entry> const& m_epsg_entries; std::string projection_group; std::string hpp; }; }}} // namespace boost::geometry::proj4converter #endif // TISSOT_WRITER_HPP
38.694051
152
0.416795
barendgehrels
ea15a1bc7e01f25fe00addcaaba6ed2af8655c4f
799
cpp
C++
OpenKattis/trik.cpp
MFathirIrhas/ProgrammingChallenges
8c67bd71212a1941e5bcc0463095285859afa04d
[ "MIT" ]
3
2020-10-19T10:03:20.000Z
2021-12-18T20:39:31.000Z
OpenKattis/trik.cpp
MFathirIrhas/ProgrammingChallenges
8c67bd71212a1941e5bcc0463095285859afa04d
[ "MIT" ]
null
null
null
OpenKattis/trik.cpp
MFathirIrhas/ProgrammingChallenges
8c67bd71212a1941e5bcc0463095285859afa04d
[ "MIT" ]
null
null
null
/* * Author: Muhammad Fathir Irhas */ #include <iostream> #include <stdio.h> #include <string.h> using namespace std; int Process(char *input){ int pos = 1; for(int i=0;i<strlen(input);i++){ if(pos == 1){ if(*(input+i) == 'A'){ pos = 2; }else if(*(input+i) == 'B'){ pos = 1; }else if(*(input+i) == 'C'){ pos = 3; } }else if(pos == 2){ if(*(input+i) == 'A'){ pos = 1; }else if(*(input+i) == 'B'){ pos = 3; }else if(*(input+i) == 'C'){ pos = 2; } }else if(pos == 3){ if(*(input+i) == 'A'){ pos = 3; }else if(*(input+i) == 'B'){ pos = 2; }else if(*(input+i) == 'C'){ pos = 1; } } } return pos; } int main(){ char input[50]; cin >> input; char *p = &input[0]; cout<< Process(p); cout<<"\n"; return 0; }
15.98
34
0.460576
MFathirIrhas
ea1b459975a9df68a5ffcc52fa24e46b64997406
1,655
cpp
C++
src/gui/randomWidget.cpp
nicovanbentum/Raekor
131e68490aa119213467ef295d3bfb94e5dd7046
[ "MIT" ]
6
2019-07-16T05:39:18.000Z
2022-02-17T10:10:18.000Z
src/gui/randomWidget.cpp
nicovanbentum/Raekor
131e68490aa119213467ef295d3bfb94e5dd7046
[ "MIT" ]
null
null
null
src/gui/randomWidget.cpp
nicovanbentum/Raekor
131e68490aa119213467ef295d3bfb94e5dd7046
[ "MIT" ]
null
null
null
#include "pch.h" #include "randomWidget.h" #include "editor.h" #include "renderer.h" namespace Raekor { RandomWidget::RandomWidget(Editor* editor) : IWidget(editor, "Random") {} void RandomWidget::draw() { auto& renderer = IWidget::renderer(); ImGui::Begin(title.c_str()); ImGui::SetItemDefaultFocus(); if (ImGui::Checkbox("Vsync", (bool*)(&renderer.settings.vsync))) { SDL_GL_SetSwapInterval(renderer.settings.vsync); } ImGui::SameLine(); if (ImGui::Checkbox("TAA", (bool*)(&renderer.settings.enableTAA))) { renderer.frameNr = 0; } ImGui::NewLine(); ImGui::Separator(); ImGui::Text("Voxel Cone Tracing"); ImGui::DragFloat("Range", &renderer.voxelize->worldSize, 0.05f, 1.0f, FLT_MAX, "%.2f"); ImGui::NewLine(); ImGui::Separator(); ImGui::Text("Shadow Mapping"); ImGui::Separator(); if (ImGui::DragFloat("Bias constant", &renderer.shadowMaps->settings.depthBiasConstant, 0.01f, 0.0f, FLT_MAX, "%.2f")) {} if (ImGui::DragFloat("Bias slope factor", &renderer.shadowMaps->settings.depthBiasSlope, 0.01f, 0.0f, FLT_MAX, "%.2f")) {} if (ImGui::DragFloat("Cascade lambda", &renderer.shadowMaps->settings.cascadeSplitLambda, 0.0001f, 0.0f, 1.0f, "%.4f")) { renderer.shadowMaps->updatePerspectiveConstants(editor->getViewport()); } ImGui::DragFloat3("Bloom threshold", glm::value_ptr(renderer.deferShading->settings.bloomThreshold), 0.01f, 0.0f, 10.0f, "%.3f"); float fov = editor->getViewport().getCamera().getFOV(); if (ImGui::DragFloat("Camera FOV", &fov, 1.0f, 5.0f, 105.0f, "%.2f", 1.0f)) { } ImGui::End(); } } // raekor
30.090909
133
0.649547
nicovanbentum
ea220e4fd57daddc0ff15f4d1361aec64c42e4ac
349
cpp
C++
UVa/568 - Just the Facts.cpp
geniustanley/problem-solving
2b83c5c8197fa8fe2277367027b392a2911d4a28
[ "Apache-2.0" ]
1
2018-11-21T07:36:16.000Z
2018-11-21T07:36:16.000Z
UVa/568 - Just the Facts.cpp
geniustanley/problem-solving
2b83c5c8197fa8fe2277367027b392a2911d4a28
[ "Apache-2.0" ]
null
null
null
UVa/568 - Just the Facts.cpp
geniustanley/problem-solving
2b83c5c8197fa8fe2277367027b392a2911d4a28
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> int digit[10005]; int main(void) { digit[1] = 1; for(int i = 2; i <= 10000; i++) { digit[i] = digit[i-1]*i; //printf("%d %d\n", i, digit[i]); while(!(digit[i]%10)) digit[i] /= 10; digit[i] %= 100000; } int n; while(EOF != scanf("%d", &n)) printf("%5d -> %d\n", n, digit[n]%10); return 0; }
18.368421
41
0.47851
geniustanley
ea254dd86a29851d53bb3886ff8427b0edaac36e
438
cpp
C++
m04/m04-01.cpp
dvcchern/CS200
333df210e70757da7cec481314b1a1e734fd03ed
[ "MIT" ]
4
2020-02-14T23:54:05.000Z
2022-01-30T18:29:06.000Z
m04/m04-01.cpp
dvcchern/CS200
333df210e70757da7cec481314b1a1e734fd03ed
[ "MIT" ]
null
null
null
m04/m04-01.cpp
dvcchern/CS200
333df210e70757da7cec481314b1a1e734fd03ed
[ "MIT" ]
6
2020-02-24T07:06:47.000Z
2022-02-03T02:46:46.000Z
#include<iostream> using namespace std; class Base { int x; public: Base() { cout << "Base Default" << endl; } Base(int x) : x(x) { cout << "Base Parameterize" << endl; } }; class Derived : public Base{ int y; public: Derived() : Base() { cout << "Derived Default" << endl; } Derived(int y, int x) : Base(x), y(y) { cout << "Derived Parameterize" << endl; } }; int main() { Derived d; Derived d2(1,2); }
20.857143
85
0.56621
dvcchern
ea298259be253e50590f3b38b32d8b53afce353e
545
cpp
C++
etc/config/src/INSTANTIATE_DEFAULT_ARGS.cpp
Hower91/Apache-C-Standard-Library-4.2.x
4d9011d60dbb38b3ff80dcfe54dccd3a4647d9d3
[ "Apache-2.0" ]
null
null
null
etc/config/src/INSTANTIATE_DEFAULT_ARGS.cpp
Hower91/Apache-C-Standard-Library-4.2.x
4d9011d60dbb38b3ff80dcfe54dccd3a4647d9d3
[ "Apache-2.0" ]
null
null
null
etc/config/src/INSTANTIATE_DEFAULT_ARGS.cpp
Hower91/Apache-C-Standard-Library-4.2.x
4d9011d60dbb38b3ff80dcfe54dccd3a4647d9d3
[ "Apache-2.0" ]
null
null
null
// checking if default args are instantiated #if defined (_RWSTD_USE_CONFIG) # include "config.h" #endif // _RWSTD_USE_CONFIG template <class T> struct A { void foo (const T& = T ()) { } }; struct B { private: B () { } }; #ifndef _RWSTD_NO_EXPLICIT_INSTANTIATION // 14.7.2, p9 - an explicit instantiation does not constitute // a use of a default argument template class A<B>; #else // if defined (_RWSTD_NO_EXPLICIT_INSTANTIATION) void foo () { &A<int>::foo; } #endif // _RWSTD_NO_EXPLICIT_INSTANTIATION
16.515152
61
0.669725
Hower91
ea32b13065b063741a229013f19b8b47b185be07
1,708
cpp
C++
leetcode/2020/july/practice/uniquePaths-2.cpp
pol-alok/Solvify
c0f3913420a4a3a3faa34848038a3cc942628b08
[ "MIT" ]
null
null
null
leetcode/2020/july/practice/uniquePaths-2.cpp
pol-alok/Solvify
c0f3913420a4a3a3faa34848038a3cc942628b08
[ "MIT" ]
null
null
null
leetcode/2020/july/practice/uniquePaths-2.cpp
pol-alok/Solvify
c0f3913420a4a3a3faa34848038a3cc942628b08
[ "MIT" ]
2
2021-02-23T06:54:22.000Z
2021-02-28T15:37:23.000Z
#include <iostream> #include <vector> using namespace std; class Solution { public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { ios_base::sync_with_stdio(false); cin.tie(nullptr); int r = obstacleGrid.size(), c = obstacleGrid[0].size(); vector<vector<int>> dp(r,vector<int>(c)); if(obstacleGrid.size()==1 && obstacleGrid[0].size()==1) { if(obstacleGrid[0][0]==1) return 0; else return 1; } if(obstacleGrid.size()==1 && obstacleGrid[0].size()==2) { if(obstacleGrid[0][0]==0 && obstacleGrid[0][1]==0) return 1; else return 0; } if(obstacleGrid.size()==2 && obstacleGrid[0].size()==1) { if(obstacleGrid[0][0]==0 && obstacleGrid[1][0]==0) return 1; else return 0; } if(obstacleGrid[r-1][c-1]==0) { if(obstacleGrid[r-2][c-1]==0) dp[r-2][c-1] =1; else dp[r-2][c-1] =0; if(obstacleGrid[r-1][c-2]==0) dp[r-1][c-2] =1; else dp[r-1][c-2] =0; } else { dp[r-2][c-1] =0; dp[r-1][c-2] =0; } for(int i=r-2; i>=0; --i) { for(int j=c-2; j>=0; --j) { if(obstacleGrid[i][j]==1) { dp[i][j] = 0; } else { dp[i][j] = dp[i+1][j]+dp[i][j+1]; } } } //return dfs(m,n); return dp[0][0]; } }; int main() { Solution solution; vector<vector<int>> arr { {0, 0, 0}, {0, 1, 0}, {0, 0, 0} }; cout<<solution.uniquePathsWithObstacles(arr); return 0; }
28.949153
74
0.446721
pol-alok
ea3623119be47018fd1c2da976a97a5559c8a125
1,031
cpp
C++
test/lseek.cpp
range3/GekkoFS
5be5f63aea4678a918fe93c6cbc6e82c9fb5cfd2
[ "MIT" ]
31
2019-11-25T02:04:13.000Z
2022-01-23T11:39:06.000Z
test/lseek.cpp
range3/GekkoFS
5be5f63aea4678a918fe93c6cbc6e82c9fb5cfd2
[ "MIT" ]
5
2020-11-20T03:40:33.000Z
2022-01-23T16:38:47.000Z
test/lseek.cpp
range3/GekkoFS
5be5f63aea4678a918fe93c6cbc6e82c9fb5cfd2
[ "MIT" ]
6
2020-04-30T14:53:01.000Z
2022-01-17T06:23:44.000Z
#include <iostream> #include <fcntl.h> #include <unistd.h> #include <cstring> #include <limits> using namespace std; int main(int argc, char* argv[]) { string mountdir = "/tmp/mountdir"; string f = mountdir + "/file"; int fd; fd = open(f.c_str(), O_WRONLY | O_CREAT, 0777); if(fd < 0){ cerr << "Error opening file (write): " << strerror(errno) << endl; return -1; } off_t pos = static_cast<off_t>(numeric_limits<int>::max()) + 1; off_t ret = lseek(fd, pos, SEEK_SET); if(ret == -1) { cerr << "Error seeking file: " << strerror(errno) << endl; return -1; } if(ret != pos) { cerr << "Error seeking file: unexpected returned position " << ret << endl; return -1; } if(close(fd) != 0){ cerr << "Error closing file" << endl; return -1; } /* Remove test file */ ret = remove(f.c_str()); if(ret != 0){ cerr << "Error removing file: " << strerror(errno) << endl; return -1; }; }
22.911111
83
0.535403
range3
ea3a48cfabee0d2bc7ea51032b89a727c091c39b
7,584
cpp
C++
SDK/ARKSurvivalEvolved_DroppedItemGeneric_HoneyLure_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_DroppedItemGeneric_HoneyLure_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_DroppedItemGeneric_HoneyLure_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
// ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_DroppedItemGeneric_HoneyLure_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.IsDinoInConsumeRange // () // Parameters: // class AActor* Dino (Parm, ZeroConstructor, IsPlainOldData) // class APrimalDinoAIController* DinoAI (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ADroppedItemGeneric_HoneyLure_C::IsDinoInConsumeRange(class AActor* Dino, class APrimalDinoAIController* DinoAI) { static auto fn = UObject::FindObject<UFunction>("Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.IsDinoInConsumeRange"); ADroppedItemGeneric_HoneyLure_C_IsDinoInConsumeRange_Params params; params.Dino = Dino; params.DinoAI = DinoAI; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.SetMovePointNearLure // () // Parameters: // class APrimalDinoCharacter* DinoToMove (Parm, ZeroConstructor, IsPlainOldData) // class APrimalDinoAIController* DinoAI (Parm, ZeroConstructor, IsPlainOldData) void ADroppedItemGeneric_HoneyLure_C::SetMovePointNearLure(class APrimalDinoCharacter* DinoToMove, class APrimalDinoAIController* DinoAI) { static auto fn = UObject::FindObject<UFunction>("Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.SetMovePointNearLure"); ADroppedItemGeneric_HoneyLure_C_SetMovePointNearLure_Params params; params.DinoToMove = DinoToMove; params.DinoAI = DinoAI; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.Can Dino Consume Bait // () // Parameters: // class APrimalDinoCharacter* InputPin (Parm, ZeroConstructor, IsPlainOldData) // bool OutputPin (Parm, OutParm, ZeroConstructor, IsPlainOldData) void ADroppedItemGeneric_HoneyLure_C::Can_Dino_Consume_Bait(class APrimalDinoCharacter* InputPin, bool* OutputPin) { static auto fn = UObject::FindObject<UFunction>("Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.Can Dino Consume Bait"); ADroppedItemGeneric_HoneyLure_C_Can_Dino_Consume_Bait_Params params; params.InputPin = InputPin; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (OutputPin != nullptr) *OutputPin = params.OutputPin; } // Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.BPPostInitializeComponents // () void ADroppedItemGeneric_HoneyLure_C::BPPostInitializeComponents() { static auto fn = UObject::FindObject<UFunction>("Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.BPPostInitializeComponents"); ADroppedItemGeneric_HoneyLure_C_BPPostInitializeComponents_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.UserConstructionScript // () void ADroppedItemGeneric_HoneyLure_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.UserConstructionScript"); ADroppedItemGeneric_HoneyLure_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.Dissolve__FinishedFunc // () void ADroppedItemGeneric_HoneyLure_C::Dissolve__FinishedFunc() { static auto fn = UObject::FindObject<UFunction>("Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.Dissolve__FinishedFunc"); ADroppedItemGeneric_HoneyLure_C_Dissolve__FinishedFunc_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.Dissolve__UpdateFunc // () void ADroppedItemGeneric_HoneyLure_C::Dissolve__UpdateFunc() { static auto fn = UObject::FindObject<UFunction>("Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.Dissolve__UpdateFunc"); ADroppedItemGeneric_HoneyLure_C_Dissolve__UpdateFunc_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.ReceiveBeginPlay // () void ADroppedItemGeneric_HoneyLure_C::ReceiveBeginPlay() { static auto fn = UObject::FindObject<UFunction>("Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.ReceiveBeginPlay"); ADroppedItemGeneric_HoneyLure_C_ReceiveBeginPlay_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.UpdateBait // () void ADroppedItemGeneric_HoneyLure_C::UpdateBait() { static auto fn = UObject::FindObject<UFunction>("Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.UpdateBait"); ADroppedItemGeneric_HoneyLure_C_UpdateBait_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.DestroyBait // () void ADroppedItemGeneric_HoneyLure_C::DestroyBait() { static auto fn = UObject::FindObject<UFunction>("Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.DestroyBait"); ADroppedItemGeneric_HoneyLure_C_DestroyBait_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.AttractCreatures // () void ADroppedItemGeneric_HoneyLure_C::AttractCreatures() { static auto fn = UObject::FindObject<UFunction>("Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.AttractCreatures"); ADroppedItemGeneric_HoneyLure_C_AttractCreatures_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.ExecuteUbergraph_DroppedItemGeneric_HoneyLure // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void ADroppedItemGeneric_HoneyLure_C::ExecuteUbergraph_DroppedItemGeneric_HoneyLure(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function DroppedItemGeneric_HoneyLure.DroppedItemGeneric_HoneyLure_C.ExecuteUbergraph_DroppedItemGeneric_HoneyLure"); ADroppedItemGeneric_HoneyLure_C_ExecuteUbergraph_DroppedItemGeneric_HoneyLure_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
30.704453
167
0.779008
2bite
ea3cf557bf7313ecd87b916856fa935505d334e5
797
hpp
C++
core/graphics/impl/2D/Point.hpp
UnknownBugs/TUGUI
1daece0c753aa255eca88c16ab87996aefbe8523
[ "MIT" ]
7
2021-11-25T01:34:36.000Z
2022-01-12T17:07:21.000Z
core/graphics/impl/2D/Point.hpp
UnknownBugs/TUGUI
1daece0c753aa255eca88c16ab87996aefbe8523
[ "MIT" ]
23
2021-11-25T07:10:18.000Z
2022-03-03T15:28:36.000Z
core/graphics/impl/2D/Point.hpp
UnknownBugs/TUGUI
1daece0c753aa255eca88c16ab87996aefbe8523
[ "MIT" ]
13
2021-11-25T01:34:41.000Z
2021-12-27T09:36:43.000Z
#ifndef __POINT__HPP__TUGUI #define __POINT__HPP__TUGUI #include <libs/TMATH/tmath.hpp> #include <libs/std/initializer_list.hpp> #include <core/painter/PaintInterface.hpp> #include <core/painter/impl/colors/color.hpp> namespace TUGUI { class Point : public PaintInterface, public TMATH::HomoCoordinates<2 + 1> { public: Point(uint32_t x, uint32_t y) : TMATH::HomoCoordinates<2 + 1>(x, y, 1) { } Point(const TMATH::Vector<double, 2 + 1> &hc) { // TODO: *this = hc is Error ? // becase of HomoCoordinates haven't assignment operator for (uint32_t i = 0; i < 3; i++) { (*this)[i] = hc[i]; } } void paint(PaintEngine &pe) const { pe.drawPixel((*this)[0], (*this)[1]); } }; // Point }; // TUGUI #endif //__POINT__HPP__TUGUI
26.566667
78
0.633626
UnknownBugs
ea3d3e703a48f6ce932d12ed06a1471f539f58e2
18,308
cpp
C++
src/register.cpp
jizhuoran/ROCdbgapi_with_wave_-manipulate
4373a5a1e2c3a1e4beff80ee7572841a368bd704
[ "MIT" ]
null
null
null
src/register.cpp
jizhuoran/ROCdbgapi_with_wave_-manipulate
4373a5a1e2c3a1e4beff80ee7572841a368bd704
[ "MIT" ]
null
null
null
src/register.cpp
jizhuoran/ROCdbgapi_with_wave_-manipulate
4373a5a1e2c3a1e4beff80ee7572841a368bd704
[ "MIT" ]
null
null
null
/* Copyright (c) 2019-2020 Advanced Micro Devices, Inc. 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 "register.h" #include "architecture.h" #include "debug.h" #include "displaced_stepping.h" #include "initialization.h" #include "logging.h" #include "process.h" #include "queue.h" #include "utils.h" #include "wave.h" #include <cstdint> #include <iterator> #include <map> #include <optional> #include <utility> namespace amd::dbgapi { /* Register class. */ bool register_class_t::contains (amdgpu_regnum_t regnum) const { auto it = m_register_map.upper_bound (regnum); if (it == m_register_map.begin ()) return false; std::advance (it, -1); return regnum >= it->first && regnum <= it->second; } std::set<amdgpu_regnum_t> register_class_t::register_set () const { std::set<amdgpu_regnum_t> all_registers; for (auto interval : m_register_map) for (amdgpu_regnum_t regnum = interval.first; regnum <= interval.second; ++regnum) all_registers.insert (regnum); return all_registers; } amd_dbgapi_status_t register_class_t::get_info (amd_dbgapi_register_class_info_t query, size_t value_size, void *value) const { switch (query) { case AMD_DBGAPI_REGISTER_CLASS_INFO_ARCHITECTURE: return utils::get_info (value_size, value, architecture ().id ()); case AMD_DBGAPI_REGISTER_CLASS_INFO_NAME: return utils::get_info (value_size, value, name ()); } return AMD_DBGAPI_STATUS_ERROR_INVALID_ARGUMENT; } } /* namespace amd::dbgapi */ using namespace amd::dbgapi; amd_dbgapi_status_t AMD_DBGAPI amd_dbgapi_architecture_register_class_get_info ( amd_dbgapi_register_class_id_t register_class_id, amd_dbgapi_register_class_info_t query, size_t value_size, void *value) { TRY; TRACE (register_class_id, query, value_size); if (!detail::is_initialized) return AMD_DBGAPI_STATUS_ERROR_NOT_INITIALIZED; const register_class_t *register_class = find (register_class_id); if (!register_class) return AMD_DBGAPI_STATUS_ERROR_INVALID_REGISTER_CLASS_ID; return register_class->get_info (query, value_size, value); CATCH; } amd_dbgapi_status_t AMD_DBGAPI amd_dbgapi_architecture_register_class_list ( amd_dbgapi_architecture_id_t architecture_id, size_t *register_class_count, amd_dbgapi_register_class_id_t **register_classes) { TRY; TRACE (architecture_id); if (!detail::is_initialized) return AMD_DBGAPI_STATUS_ERROR_NOT_INITIALIZED; const architecture_t *architecture = architecture_t::find (architecture_id); if (!architecture) return AMD_DBGAPI_STATUS_ERROR_INVALID_ARCHITECTURE_ID; if (!register_class_count || !register_classes) return AMD_DBGAPI_STATUS_ERROR_INVALID_ARGUMENT; size_t count = architecture->count<register_class_t> (); amd_dbgapi_register_class_id_t *class_ids = static_cast<amd_dbgapi_register_class_id_t *> ( allocate_memory (count * sizeof (amd_dbgapi_register_class_id_t))); if (count && !class_ids) return AMD_DBGAPI_STATUS_ERROR_CLIENT_CALLBACK; *register_class_count = count; *register_classes = class_ids; for (auto &&register_class : architecture->range<register_class_t> ()) *class_ids++ = register_class.id (); return AMD_DBGAPI_STATUS_SUCCESS; CATCH; } amd_dbgapi_status_t AMD_DBGAPI amd_dbgapi_register_get_info (amd_dbgapi_register_id_t register_id, amd_dbgapi_register_info_t query, size_t value_size, void *value) { TRY; TRACE (register_id, query, value_size); if (!detail::is_initialized) return AMD_DBGAPI_STATUS_ERROR_NOT_INITIALIZED; auto regnum = architecture_t::register_id_to_regnum (register_id); const architecture_t *architecture = architecture_t::register_id_to_architecture (register_id); if (!architecture || !regnum) return AMD_DBGAPI_STATUS_ERROR_INVALID_REGISTER_ID; if (!value) return AMD_DBGAPI_STATUS_ERROR_INVALID_ARGUMENT; switch (query) { case AMD_DBGAPI_REGISTER_INFO_ARCHITECTURE: return utils::get_info (value_size, value, architecture->id ()); case AMD_DBGAPI_REGISTER_INFO_NAME: { auto name = architecture->register_name (*regnum); if (!name) return AMD_DBGAPI_STATUS_ERROR_INVALID_REGISTER_ID; return utils::get_info (value_size, value, *name); } case AMD_DBGAPI_REGISTER_INFO_TYPE: { auto type = architecture->register_type (*regnum); if (!type) return AMD_DBGAPI_STATUS_ERROR_INVALID_REGISTER_ID; return utils::get_info (value_size, value, *type); } case AMD_DBGAPI_REGISTER_INFO_SIZE: { auto size = architecture->register_size (*regnum); if (!size) return AMD_DBGAPI_STATUS_ERROR_INVALID_REGISTER_ID; return utils::get_info (value_size, value, *size); } default: return AMD_DBGAPI_STATUS_ERROR_INVALID_ARGUMENT; } CATCH; } amd_dbgapi_status_t AMD_DBGAPI amd_dbgapi_architecture_register_list ( amd_dbgapi_architecture_id_t architecture_id, size_t *register_count, amd_dbgapi_register_id_t **registers) { TRY; TRACE (architecture_id); if (!detail::is_initialized) return AMD_DBGAPI_STATUS_ERROR_NOT_INITIALIZED; const architecture_t *architecture = architecture_t::find (architecture_id); if (!architecture) return AMD_DBGAPI_STATUS_ERROR_INVALID_ARCHITECTURE_ID; if (!register_count || !registers) return AMD_DBGAPI_STATUS_ERROR_INVALID_ARGUMENT; auto arch_registers = architecture->register_set (); auto *retval = static_cast<amd_dbgapi_register_id_t *> (allocate_memory ( arch_registers.size () * sizeof (amd_dbgapi_register_id_t))); if (!retval) return AMD_DBGAPI_STATUS_ERROR_CLIENT_CALLBACK; size_t count = 0; for (auto it = arch_registers.begin (); it != arch_registers.end (); ++it) retval[count++] = architecture->regnum_to_register_id (*it); *register_count = count; *registers = retval; return AMD_DBGAPI_STATUS_SUCCESS; CATCH; } amd_dbgapi_status_t AMD_DBGAPI amd_dbgapi_register_is_in_register_class ( amd_dbgapi_register_class_id_t register_class_id, amd_dbgapi_register_id_t register_id, amd_dbgapi_register_class_state_t *register_class_state) { TRY; TRACE (register_class_id, register_id); if (!detail::is_initialized) return AMD_DBGAPI_STATUS_ERROR_NOT_INITIALIZED; const register_class_t *register_class = find (register_class_id); if (!register_class) return AMD_DBGAPI_STATUS_ERROR_INVALID_REGISTER_CLASS_ID; auto regnum = architecture_t::register_id_to_regnum (register_id); const architecture_t *architecture = architecture_t::register_id_to_architecture (register_id); if (!regnum || !architecture) return AMD_DBGAPI_STATUS_ERROR_INVALID_REGISTER_ID; if (!register_class_state) return AMD_DBGAPI_STATUS_ERROR_INVALID_ARGUMENT; if (*architecture != register_class->architecture ()) return AMD_DBGAPI_STATUS_ERROR_INVALID_ARGUMENT_COMPATIBILITY; *register_class_state = register_class->contains (*regnum) ? AMD_DBGAPI_REGISTER_CLASS_STATE_MEMBER : AMD_DBGAPI_REGISTER_CLASS_STATE_NOT_MEMBER; return AMD_DBGAPI_STATUS_SUCCESS; CATCH; } amd_dbgapi_status_t AMD_DBGAPI amd_dbgapi_dwarf_register_to_register ( amd_dbgapi_architecture_id_t architecture_id, uint64_t dwarf_register, amd_dbgapi_register_id_t *register_id) { TRY; TRACE (architecture_id, dwarf_register); if (!detail::is_initialized) return AMD_DBGAPI_STATUS_ERROR_NOT_INITIALIZED; const architecture_t *architecture = architecture_t::find (architecture_id); if (!architecture) return AMD_DBGAPI_STATUS_ERROR_INVALID_ARCHITECTURE_ID; if (!register_id) return AMD_DBGAPI_STATUS_ERROR_INVALID_ARGUMENT; amdgpu_regnum_t regnum; /* See https://llvm.org/docs/AMDGPUUsage.html#register-mapping. */ if (dwarf_register == 1) { regnum = amdgpu_regnum_t::exec_32; } else if (dwarf_register == 17) { regnum = amdgpu_regnum_t::exec_64; } else if (dwarf_register == 16) { regnum = amdgpu_regnum_t::pc; } else if (dwarf_register >= 32 && dwarf_register <= 95) { /* Scalar registers 0-63. */ regnum = amdgpu_regnum_t::first_sgpr + (dwarf_register - 32); } else if (dwarf_register == 128) { regnum = amdgpu_regnum_t::status; } else if (dwarf_register == 512) { regnum = amdgpu_regnum_t::vcc_32; } else if (dwarf_register == 768) { regnum = amdgpu_regnum_t::vcc_64; } else if (dwarf_register >= 1088 && dwarf_register <= 1129) { /* Scalar registers 64-105. */ regnum = amdgpu_regnum_t::first_sgpr + (dwarf_register - 1024); } else if (dwarf_register >= 1536 && dwarf_register <= 1791) { /* Vector registers 0-255 (wave32). */ regnum = amdgpu_regnum_t::first_vgpr_32 + (dwarf_register - 1536); } else if (dwarf_register >= 2048 && dwarf_register <= 2303) { /* Accumulation Vector registers 0-255 (wave32). */ regnum = amdgpu_regnum_t::first_accvgpr_32 + (dwarf_register - 2048); } else if (dwarf_register >= 2560 && dwarf_register <= 2815) { /* Vector registers 0-255 (wave64). */ regnum = amdgpu_regnum_t::first_vgpr_64 + (dwarf_register - 2560); } else if (dwarf_register >= 3072 && dwarf_register <= 3327) { /* Accumulation Vector registers 0-255 (wave64). */ regnum = amdgpu_regnum_t::first_accvgpr_64 + (dwarf_register - 3072); } else return AMD_DBGAPI_STATUS_ERROR_INVALID_ARGUMENT_COMPATIBILITY; if (!architecture->register_size (regnum)) return AMD_DBGAPI_STATUS_ERROR_INVALID_ARGUMENT_COMPATIBILITY; *register_id = architecture->regnum_to_register_id (regnum); return AMD_DBGAPI_STATUS_SUCCESS; CATCH; } amd_dbgapi_status_t AMD_DBGAPI amd_dbgapi_read_register (amd_dbgapi_wave_id_t wave_id, amd_dbgapi_register_id_t register_id, amd_dbgapi_size_t offset, amd_dbgapi_size_t value_size, void *value) { TRY; TRACE (wave_id, register_id, offset, value_size); if (!detail::is_initialized) return AMD_DBGAPI_STATUS_ERROR_NOT_INITIALIZED; wave_t *wave = find (wave_id); if (!wave) return AMD_DBGAPI_STATUS_ERROR_INVALID_WAVE_ID; auto regnum = architecture_t::register_id_to_regnum (register_id); const architecture_t *architecture = architecture_t::register_id_to_architecture (register_id); if (!regnum || !architecture) return AMD_DBGAPI_STATUS_ERROR_INVALID_REGISTER_ID; if (wave->state () != AMD_DBGAPI_WAVE_STATE_STOP) return AMD_DBGAPI_STATUS_ERROR_WAVE_NOT_STOPPED; if (!value) return AMD_DBGAPI_STATUS_ERROR_INVALID_ARGUMENT; if (*architecture != wave->architecture ()) return AMD_DBGAPI_STATUS_ERROR_INVALID_ARGUMENT_COMPATIBILITY; std::optional<scoped_queue_suspend_t> suspend; if (!wave->is_register_cached (*regnum)) { suspend.emplace (wave->queue (), "read register"); /* Look for the wave_id again, the wave may have exited. */ if (!(wave = find (wave_id))) return AMD_DBGAPI_STATUS_ERROR_INVALID_WAVE_ID; } wave->read_register (*regnum, offset, value_size, value); return AMD_DBGAPI_STATUS_SUCCESS; CATCH; } amd_dbgapi_status_t AMD_DBGAPI amd_dbgapi_write_register (amd_dbgapi_wave_id_t wave_id, amd_dbgapi_register_id_t register_id, amd_dbgapi_size_t offset, amd_dbgapi_size_t value_size, const void *value) { TRY; TRACE (wave_id, register_id, offset, value_size); if (!detail::is_initialized) return AMD_DBGAPI_STATUS_ERROR_NOT_INITIALIZED; wave_t *wave = find (wave_id); if (!wave) return AMD_DBGAPI_STATUS_ERROR_INVALID_WAVE_ID; auto regnum = architecture_t::register_id_to_regnum (register_id); const architecture_t *architecture = architecture_t::register_id_to_architecture (register_id); if (!regnum || !architecture) return AMD_DBGAPI_STATUS_ERROR_INVALID_REGISTER_ID; if (wave->state () != AMD_DBGAPI_WAVE_STATE_STOP) return AMD_DBGAPI_STATUS_ERROR_WAVE_NOT_STOPPED; /* FIXME: Enable this check when the FIXME below is removed. * * / * Is displaced stepping active? * / * if (wave->displaced_stepping ()) * return AMD_DBGAPI_STATUS_ERROR_DISPLACED_STEPPING_ACTIVE; */ if (!value) return AMD_DBGAPI_STATUS_ERROR_INVALID_ARGUMENT; if (*architecture != wave->architecture ()) return AMD_DBGAPI_STATUS_ERROR_INVALID_ARGUMENT_COMPATIBILITY; /* FIXME: This is a hack to work around a misbehaving gdb. To cancel a displaced stepping operation, gdb resets the pc to the original location instead of calling amd_dbgapi_displaced_stepping_complete. We detect this condition here, and complete the aborted displaced stepping. */ if (*regnum == amdgpu_regnum_t::pc && wave->displaced_stepping () && offset == 0 && value_size == sizeof (uint64_t) && *(uint64_t *)(value) != wave->displaced_stepping ()->to ()) { scoped_queue_suspend_t suspend (wave->queue (), "displaced stepping complete"); wave->displaced_stepping_complete (); } std::optional<scoped_queue_suspend_t> suspend; if (!wave->is_register_cached (*regnum) /* Write-through needs to update the memory as well as the cache, so we always need to suspend the queue. */ || wave_t::register_cache_policy == wave_t::register_cache_policy_t::write_through) { suspend.emplace (wave->queue (), "write register"); /* Look for the wave_id again, the wave may have exited. */ if (!(wave = find (wave_id))) return AMD_DBGAPI_STATUS_ERROR_INVALID_WAVE_ID; } wave->write_register (*regnum, offset, value_size, value); return AMD_DBGAPI_STATUS_SUCCESS; CATCH; } amd_dbgapi_status_t AMD_DBGAPI amd_dbgapi_wave_register_exists (amd_dbgapi_wave_id_t wave_id, amd_dbgapi_register_id_t register_id, amd_dbgapi_register_exists_t *exists) { TRY; TRACE (wave_id, register_id); if (!detail::is_initialized) return AMD_DBGAPI_STATUS_ERROR_NOT_INITIALIZED; wave_t *wave = find (wave_id); if (!wave) return AMD_DBGAPI_STATUS_ERROR_INVALID_WAVE_ID; auto regnum = architecture_t::register_id_to_regnum (register_id); const architecture_t *architecture = architecture_t::register_id_to_architecture (register_id); if (!regnum || !architecture) return AMD_DBGAPI_STATUS_ERROR_INVALID_REGISTER_ID; if (!exists) return AMD_DBGAPI_STATUS_ERROR_INVALID_ARGUMENT; if (*architecture != wave->architecture ()) return AMD_DBGAPI_STATUS_ERROR_INVALID_ARGUMENT_COMPATIBILITY; *exists = wave->is_register_available (*regnum) ? AMD_DBGAPI_REGISTER_PRESENT : AMD_DBGAPI_REGISTER_ABSENT; return AMD_DBGAPI_STATUS_SUCCESS; CATCH; } amd_dbgapi_status_t AMD_DBGAPI amd_dbgapi_wave_register_list (amd_dbgapi_wave_id_t wave_id, size_t *register_count, amd_dbgapi_register_id_t **registers) { TRY; TRACE (wave_id); if (!detail::is_initialized) return AMD_DBGAPI_STATUS_ERROR_NOT_INITIALIZED; wave_t *wave = find (wave_id); if (!wave) return AMD_DBGAPI_STATUS_ERROR_INVALID_WAVE_ID; if (!registers || !register_count) return AMD_DBGAPI_STATUS_ERROR_INVALID_ARGUMENT; auto architecture_registers = wave->architecture ().register_set (); auto *retval = static_cast<amd_dbgapi_register_id_t *> (allocate_memory ( architecture_registers.size () * sizeof (amd_dbgapi_register_id_t))); if (!retval) return AMD_DBGAPI_STATUS_ERROR_CLIENT_CALLBACK; size_t count = 0; for (auto &&regnum : architecture_registers) if (wave->is_register_available (regnum)) retval[count++] = wave->architecture ().regnum_to_register_id (regnum); *register_count = count; *registers = retval; return AMD_DBGAPI_STATUS_SUCCESS; CATCH; } amd_dbgapi_status_t AMD_DBGAPI amd_dbgapi_prefetch_register (amd_dbgapi_wave_id_t wave_id, amd_dbgapi_register_id_t register_id, amd_dbgapi_size_t register_count) { TRY; TRACE (wave_id, register_id, register_count); if (!detail::is_initialized) return AMD_DBGAPI_STATUS_ERROR_NOT_INITIALIZED; wave_t *wave = find (wave_id); if (!wave) return AMD_DBGAPI_STATUS_ERROR_INVALID_WAVE_ID; auto regnum = architecture_t::register_id_to_regnum (register_id); const architecture_t *architecture = architecture_t::register_id_to_architecture (register_id); if (!regnum || !architecture) return AMD_DBGAPI_STATUS_ERROR_INVALID_REGISTER_ID; if (wave->state () != AMD_DBGAPI_WAVE_STATE_STOP) return AMD_DBGAPI_STATUS_ERROR_WAVE_NOT_STOPPED; if (*architecture != wave->architecture ()) return AMD_DBGAPI_STATUS_ERROR_INVALID_ARGUMENT_COMPATIBILITY; return AMD_DBGAPI_STATUS_SUCCESS; CATCH; }
30.361526
79
0.724711
jizhuoran
ea3d71a39dca9cfee7bf04af221521b3bced1e76
438
cpp
C++
framework/platform/bpl/linux/bpl_dhcp.cpp
ydx-coder/prplMesh
6401b15c31c563f9e00ce6ff1b5513df3d39f157
[ "BSD-2-Clause-Patent" ]
null
null
null
framework/platform/bpl/linux/bpl_dhcp.cpp
ydx-coder/prplMesh
6401b15c31c563f9e00ce6ff1b5513df3d39f157
[ "BSD-2-Clause-Patent" ]
null
null
null
framework/platform/bpl/linux/bpl_dhcp.cpp
ydx-coder/prplMesh
6401b15c31c563f9e00ce6ff1b5513df3d39f157
[ "BSD-2-Clause-Patent" ]
1
2022-02-01T20:52:12.000Z
2022-02-01T20:52:12.000Z
/* SPDX-License-Identifier: BSD-2-Clause-Patent * * Copyright (c) 2019 Intel Corporation * * This code is subject to the terms of the BSD+Patent license. * See LICENSE file for more details. */ #include <bpl/bpl_dhcp.h> namespace beerocks { namespace bpl { int dhcp_mon_start(dhcp_mon_cb cb) { return -2; } int dhcp_mon_handle_event() { return 0; } int dhcp_mon_stop() { return 0; } } // namespace bpl } // namespace beerocks
19.909091
63
0.710046
ydx-coder
ea405edfdb443c7241ae1718fe5d1de8652a8f96
1,126
cpp
C++
leetcode.com/0514 Freedom Trail/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0514 Freedom Trail/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0514 Freedom Trail/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <algorithm> #include <iostream> #include <queue> #include <set> #include <vector> using namespace std; class Solution { public: int findRotateSteps(string ring, string key) { vector<int> m[26]; int len_r = ring.length(), len_k = key.length(); for (int i = 0; i < len_r; ++i) m[ring[i] - 'a'].push_back(i); vector<pair<int, int>> *cur = new vector<pair<int, int>>(); cur->emplace_back(0, 0); // steps, idx for (int i = 0; i < len_k; ++i) { vector<pair<int, int>> *tmp = new vector<pair<int, int>>(); for (int idx : m[key[i] - 'a']) tmp->emplace_back(INT32_MAX, idx); #define DIS(a, b) \ (a < b ? min(b - a, len_r + a - b) : min(a - b, len_r + b - a)) for (auto itc = cur->begin(); itc != cur->end(); ++itc) { for (auto itt = tmp->begin(); itt != tmp->end(); ++itt) { int dis = DIS(itt->second, itc->second) + 1; if (itt->first > dis + itc->first) itt->first = dis + itc->first; } } delete cur; cur = tmp; } int res = min_element(cur->begin(), cur->end())->first; delete cur; return res; } };
28.15
75
0.539076
sky-bro
ea43e3060238b79aa21b122027e26e7022f35a6c
105
cpp
C++
Codeforces/rockethon14/test.cpp
s9v/toypuct
68e65e6da5922af340de72636a9a4f136454c70d
[ "MIT" ]
null
null
null
Codeforces/rockethon14/test.cpp
s9v/toypuct
68e65e6da5922af340de72636a9a4f136454c70d
[ "MIT" ]
null
null
null
Codeforces/rockethon14/test.cpp
s9v/toypuct
68e65e6da5922af340de72636a9a4f136454c70d
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int b; cin >> b; cout << *&b; return 0; }
8.076923
20
0.561905
s9v
ea492f0aded594fccc9ab24304073ed6ff3d23f8
3,944
cpp
C++
WorldEditor/ViewTexture.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
1
2022-02-14T15:46:44.000Z
2022-02-14T15:46:44.000Z
WorldEditor/ViewTexture.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
null
null
null
WorldEditor/ViewTexture.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
2
2022-01-10T22:17:06.000Z
2022-01-17T09:34:08.000Z
// ViewTexture.cpp : implementation file // #include "stdafx.h" #include "WorldEditor.h" #include "ViewTexture.h" #ifdef _DEBUG #undef new #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CViewTexture CViewTexture::CViewTexture() { m_pViewPort = NULL; m_pDrawPort = NULL; } CViewTexture::~CViewTexture() { } BEGIN_MESSAGE_MAP(CViewTexture, CWnd) //{{AFX_MSG_MAP(CViewTexture) ON_WM_PAINT() ON_WM_LBUTTONDOWN() ON_WM_LBUTTONDBLCLK() ON_WM_CONTEXTMENU() ON_COMMAND(ID_RECREATE_TEXTURE, OnRecreateTexture) ON_WM_DESTROY() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CViewTexture message handlers void CViewTexture::OnPaint() { { CPaintDC dc(this); // device context for painting } // skip if already drawing extern BOOL _bInTestGame; if( _bInTestGame) return; CWnd *pwndRect = GetParent()->GetDlgItem( IDC_PREVIEW_FRAME); if( pwndRect != NULL) { CRect rectBorder; pwndRect->GetWindowRect( rectBorder); GetParent()->ScreenToClient( rectBorder); MoveWindow( rectBorder); } if( (m_pViewPort == NULL) && (m_pDrawPort == NULL) ) { // initialize canvas for active texture button _pGfx->CreateWindowCanvas( m_hWnd, &m_pViewPort, &m_pDrawPort); } // if there is a valid drawport, and the drawport can be locked if(m_pDrawPort != NULL) { m_pDrawPort->SetAsCurrent(); PIX pixWidth = m_pDrawPort->GetWidth(); PIX pixHeight = m_pDrawPort->GetHeight(); PIXaabbox2D rectPict; rectPict = PIXaabbox2D( PIX2D(0, 0), PIX2D(m_pDrawPort->GetWidth(), m_pDrawPort->GetHeight())); // clear texture area to black m_pDrawPort->Fill( C_BLACK | CT_OPAQUE); // erase z-buffer m_pDrawPort->FillZBuffer(ZBUF_BACK); CTextureObject toTexture; try { toTexture.SetData_t( m_strTexture); } catch( char *strError) { (void) strError; } if( toTexture.GetData() != NULL) { m_pDrawPort->PutTexture( &toTexture, rectPict); } else { // type text saying none selected m_pDrawPort->SetFont( theApp.m_pfntSystem); m_pDrawPort->SetTextAspect( 1.0f); m_pDrawPort->SetTextScaling( 0.5f); m_pDrawPort->PutTextC( m_strTexture, pixWidth/2, pixHeight*1/3-10); } // if there is a valid viewport if (m_pViewPort!=NULL) { // swap it m_pViewPort->SwapBuffers(); } } } void CViewTexture::OnLButtonDown(UINT nFlags, CPoint point) { if( !GetParent()->GetDlgItem( IDC_PREVIEW_FRAME)->IsWindowEnabled()) { return; } HGLOBAL hglobal = CreateHDrop( m_strTexture); m_DataSource.CacheGlobalData( CF_HDROP, hglobal); m_DataSource.DoDragDrop( DROPEFFECT_COPY); CWnd::OnLButtonDown(nFlags, point); } void CViewTexture::OnLButtonDblClk(UINT nFlags, CPoint point) { OnRecreateTexture(); CWnd::OnLButtonDblClk(nFlags, point); } void CViewTexture::OnContextMenu(CWnd* pWnd, CPoint point) { CMenu menu; if( menu.LoadMenu(IDR_THUMBNAIL_TEXTURE_POPUP)) { CMenu* pPopup = menu.GetSubMenu(0); pPopup->TrackPopupMenu( TPM_LEFTBUTTON | TPM_RIGHTBUTTON | TPM_LEFTALIGN, point.x, point.y, this); } } void CViewTexture::OnRecreateTexture() { CTextureObject toTexture; try { toTexture.SetData_t( m_strTexture); } catch( char *strError) { (void) strError; } if( toTexture.GetData() != NULL) { _EngineGUI.CreateTexture( CTString(m_strTexture)); CWorldEditorDoc *pDoc = theApp.GetDocument(); if( pDoc != NULL) { pDoc->UpdateAllViews( NULL); } } } void CViewTexture::OnDestroy() { CWnd::OnDestroy(); if( m_pViewPort != NULL) { _pGfx->DestroyWindowCanvas( m_pViewPort); m_pViewPort = NULL; } m_pViewPort = NULL; m_pDrawPort = NULL; }
21.911111
86
0.648327
openlastchaos
35736f5c08a45b924638c49126661933b4062428
4,165
cpp
C++
Classes/BeeSpawner.cpp
JLouhela/jumpy-demo
8ccb6c98b42e38284eb9d1d884460ccb3c7b1629
[ "MIT" ]
null
null
null
Classes/BeeSpawner.cpp
JLouhela/jumpy-demo
8ccb6c98b42e38284eb9d1d884460ccb3c7b1629
[ "MIT" ]
null
null
null
Classes/BeeSpawner.cpp
JLouhela/jumpy-demo
8ccb6c98b42e38284eb9d1d884460ccb3c7b1629
[ "MIT" ]
null
null
null
/// Copyright (c) 2019 Joni Louhela /// /// 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 "BeeSpawner.h" #include <cstdint> #include "ZOrders.h" namespace { Bee* getAvailableBee(BeeSpawner::BeeContainer& bees) { for (auto& bee : bees) { if (bee.getState() == BeeState::inactive) { // Shortcut: should be tied to spawn, but this means // bee should offer functionality to spawn after certain time. bee.activate(); return &bee; } } return nullptr; } } // namespace bool BeeSpawner::spawnBees() { BeeCycles::BeeCyclePair cyclePair; float beeSpawnCycle{0.0f}; // Sync bees to music if (!m_cycleInitialized) { beeSpawnCycle = (BeeCycle::cycleLength - (BeeCycle::beatLength)) / 1000.0f; cyclePair = m_cycles.getInitialCycles(); m_cycleInitialized = true; } else { beeSpawnCycle = BeeCycle::cycleLength / 1000.0f; cyclePair = m_cycles.getRandomCycles(); // cyclePair = m_cycles.getDevCycles(); } const auto& snareCycle = m_cycles.getSnare(cyclePair.snareIndex); const auto& bassCycle = m_cycles.getBass(cyclePair.bassIndex); scheduleSpawn(snareCycle.getCycle(), snareCycle.getDirection()); scheduleSpawn(bassCycle.getCycle(), bassCycle.getDirection()); // Schedule new spawn auto delayAction = cocos2d::DelayTime::create(beeSpawnCycle); auto callback = cocos2d::CallFunc::create([this]() { spawnBees(); }); m_actionNode->runAction(cocos2d::Sequence::create(delayAction, callback, nullptr)); return true; } void BeeSpawner::spawnBee(float y, Direction dir) { auto bee = getAvailableBee(m_beeContainer); if (!bee) { cocos2d::log("No free bees to spawn"); return; } const auto visibleSize{cocos2d::Director::getInstance()->getVisibleSize()}; static constexpr float xOffset = -40.0f; const float x = (dir == Direction::left) ? (visibleSize.width - xOffset) : xOffset; bee->spawn(cocos2d::Vec2{x, y}, dir); } void BeeSpawner::scheduleSpawn(const std::vector<BeeSpawn>& spawns, Direction dir) { for (const auto& spawn : spawns) { auto delayAction = cocos2d::DelayTime::create(spawn.timeFromCycleStart / 1000.0f); auto callback = cocos2d::CallFunc::create([this, &spawn, dir]() { spawnBee(spawn.y, dir); }); m_actionNode->runAction(cocos2d::Sequence::create(delayAction, callback, nullptr)); } } bool BeeSpawner::init(cocos2d::Scene& scene, b2World& world) { // Before modifications to scene, check if any bunny was not initialized properly Bee_id id{0}; for (auto& bee : m_beeContainer) { if (!bee.init(id++, world)) { return false; } } m_actionNode = cocos2d::Node::create(); scene.addChild(m_actionNode); for (const auto& bee : m_beeContainer) { scene.addChild(bee.getSprite(), ZOrder::bee); } return true; } void BeeSpawner::stop() { for (auto& bee : m_beeContainer) { bee.dispose(); } m_actionNode->cleanup(); m_cycleInitialized = false; }
34.708333
91
0.67539
JLouhela
3576800f2efd1d54080a8c32bf9531c3dd50f848
1,131
hpp
C++
TZK_Objects/HPP/CfgMaterials_HighContrast.hpp
Darker1990/Project-TZK-Since2.12
3f1162b51f1f24f41b1000e97102be537d162b76
[ "MIT" ]
null
null
null
TZK_Objects/HPP/CfgMaterials_HighContrast.hpp
Darker1990/Project-TZK-Since2.12
3f1162b51f1f24f41b1000e97102be537d162b76
[ "MIT" ]
null
null
null
TZK_Objects/HPP/CfgMaterials_HighContrast.hpp
Darker1990/Project-TZK-Since2.12
3f1162b51f1f24f41b1000e97102be537d162b76
[ "MIT" ]
null
null
null
#define SHADOWLVL 0.5 class CfgMaterials { // *** DEFAULT DEFINITIONS OVERRIDE *** class Water { ambient[] = {SHADOWLVL,SHADOWLVL,SHADOWLVL,1}; diffuse[] = {0.13,0.15,0.065,1.0}; forcedDiffuse[] = {0.0264,0.03,0.013,0}; specular[] = {0.5,0.5,0.5,0}; specularPower = 4; emmisive[] = {0,0,0,0}; }; class Terrain { ambient[] = {SHADOWLVL,SHADOWLVL,SHADOWLVL,1}; diffuse[] = {1,1,1,1}; forcedDiffuse[] = {0,0,0,0}; specular[] = {0.1,0.1,0.1,0}; specularPower = 3; emmisive[] = {0,0,0,0}; }; class SpecularGlass { ambient[] = {0.9,0.9,0.9,1}; diffuse[] = {1,1,1,1}; forcedDiffuse[] = {0.5,0.5,0.5,1}; specular[] = {1,1,1,1}; specularPower = 900; emmisive[] = {0,0,0,0}; }; class Metal { ambient[] = {SHADOWLVL,SHADOWLVL,SHADOWLVL,1}; diffuse[] = {1,1,1,1}; forcedDiffuse[] = {0,0,0,0}; specular[] = {0.3,0.3,0.3,1}; specularPower = 300; emmisive[] = {0,0,0,0}; }; class RifleMetal { ambient[] = {SHADOWLVL,SHADOWLVL,SHADOWLVL,1}; diffuse[] = {1,1,1,1}; forcedDiffuse[] = {0,0,0,0}; specular[] = {0.3,0.3,0.3,1}; specularPower = 900; emmisive[] = {0,0,0,0}; }; };
24.586957
48
0.57206
Darker1990
3577e7aecad6bafb6b3056b3ac3745344717eece
145
cpp
C++
jee.cpp
razat2199/IOSD-MAIT-HacktoberFest-Meetup-2019
d534b2d648e0345129f778f23609059feeeff673
[ "Apache-2.0" ]
9
2021-09-15T09:48:49.000Z
2021-12-28T09:52:18.000Z
jee.cpp
razat2199/IOSD-MAIT-HacktoberFest-Meetup-2019
d534b2d648e0345129f778f23609059feeeff673
[ "Apache-2.0" ]
3
2019-10-07T04:35:44.000Z
2020-12-07T23:18:41.000Z
jee.cpp
razat2199/IOSD-MAIT-HacktoberFest-Meetup-2019
d534b2d648e0345129f778f23609059feeeff673
[ "Apache-2.0" ]
54
2019-10-04T10:45:52.000Z
2021-06-09T09:57:52.000Z
cout<<"jee is not tough but a different exam which all can't crack.watch super 30 recommended"; cout<<"hello this is just for learning purpose.";
72.5
95
0.765517
razat2199
357ed0082155ff9b6c85f2172921c87940dea30e
3,478
cpp
C++
export/release/windows/obj/src/lime/text/harfbuzz/_HBLanguage/HBLanguage_Impl_.cpp
bobisdabbing/Vs-The-United-Lands-stable
0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5
[ "MIT" ]
null
null
null
export/release/windows/obj/src/lime/text/harfbuzz/_HBLanguage/HBLanguage_Impl_.cpp
bobisdabbing/Vs-The-United-Lands-stable
0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5
[ "MIT" ]
null
null
null
export/release/windows/obj/src/lime/text/harfbuzz/_HBLanguage/HBLanguage_Impl_.cpp
bobisdabbing/Vs-The-United-Lands-stable
0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5
[ "MIT" ]
null
null
null
// Generated by Haxe 4.1.5 #include <hxcpp.h> #ifndef INCLUDED_lime__internal_backend_native_NativeCFFI #include <lime/_internal/backend/native/NativeCFFI.h> #endif #ifndef INCLUDED_lime_text_harfbuzz__HBLanguage_HBLanguage_Impl_ #include <lime/text/harfbuzz/_HBLanguage/HBLanguage_Impl_.h> #endif HX_LOCAL_STACK_FRAME(_hx_pos_ea4d32685afb113e_10__new,"lime.text.harfbuzz._HBLanguage.HBLanguage_Impl_","_new",0x28591bba,"lime.text.harfbuzz._HBLanguage.HBLanguage_Impl_._new","lime/text/harfbuzz/HBLanguage.hx",10,0x01dc06e5) namespace lime{ namespace text{ namespace harfbuzz{ namespace _HBLanguage{ void HBLanguage_Impl__obj::__construct() { } Dynamic HBLanguage_Impl__obj::__CreateEmpty() { return new HBLanguage_Impl__obj; } void *HBLanguage_Impl__obj::_hx_vtable = 0; Dynamic HBLanguage_Impl__obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< HBLanguage_Impl__obj > _hx_result = new HBLanguage_Impl__obj(); _hx_result->__construct(); return _hx_result; } bool HBLanguage_Impl__obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x1f86dfa1; } ::Dynamic HBLanguage_Impl__obj::_new(::String language){ HX_STACKFRAME(&_hx_pos_ea4d32685afb113e_10__new) HXDLIN( 10) ::Dynamic this1; HXLINE( 13) if (::hx::IsNotNull( language )) { HXLINE( 15) this1 = ( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_hb_language_from_string(language)) ); } else { HXLINE( 19) this1 = ( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_hb_language_get_default()) ); } HXLINE( 10) return this1; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(HBLanguage_Impl__obj,_new,return ) HBLanguage_Impl__obj::HBLanguage_Impl__obj() { } bool HBLanguage_Impl__obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"_new") ) { outValue = _new_dyn(); return true; } } return false; } #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo *HBLanguage_Impl__obj_sMemberStorageInfo = 0; static ::hx::StaticInfo *HBLanguage_Impl__obj_sStaticStorageInfo = 0; #endif ::hx::Class HBLanguage_Impl__obj::__mClass; static ::String HBLanguage_Impl__obj_sStaticFields[] = { HX_("_new",61,15,1f,3f), ::String(null()) }; void HBLanguage_Impl__obj::__register() { HBLanguage_Impl__obj _hx_dummy; HBLanguage_Impl__obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("lime.text.harfbuzz._HBLanguage.HBLanguage_Impl_",b5,f8,a9,ae); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &HBLanguage_Impl__obj::__GetStatic; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(HBLanguage_Impl__obj_sStaticFields); __mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = ::hx::TCanCast< HBLanguage_Impl__obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = HBLanguage_Impl__obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = HBLanguage_Impl__obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace lime } // end namespace text } // end namespace harfbuzz } // end namespace _HBLanguage
34.098039
226
0.762507
bobisdabbing
35854777eac8b0291e6b642caf52b9775e8c685a
1,162
cpp
C++
4_sort_0_1_2/4_Dutch_flag_algo.cpp
ManthanChoudhury/450_dsa
b776490a30d1039e2b1f3a42b7879d8d34ddce73
[ "Apache-2.0" ]
1
2021-03-11T00:17:39.000Z
2021-03-11T00:17:39.000Z
4_sort_0_1_2/4_Dutch_flag_algo.cpp
ManthanChoudhury/450_dsa
b776490a30d1039e2b1f3a42b7879d8d34ddce73
[ "Apache-2.0" ]
null
null
null
4_sort_0_1_2/4_Dutch_flag_algo.cpp
ManthanChoudhury/450_dsa
b776490a30d1039e2b1f3a42b7879d8d34ddce73
[ "Apache-2.0" ]
null
null
null
// { Driver Code Starts #include<bits/stdc++.h> using namespace std; void sort012(int[],int); int main() { int t; cin >> t; while(t--){ int n; cin >>n; int a[n]; for(int i=0;i<n;i++){ cin >> a[i]; } sort012(a, n); for(int i=0;i<n;i++){ cout << a[i] << " "; } cout << endl; } return 0; } // } Driver Code Ends void sort012(int a[], int n) { int low = 0; int mid =0; int high = n -1; int temp; while (mid<=high) { if(a[mid] == 0){ temp = a[low]; a[low]= a[mid]; a[mid] = temp; low++; mid++; //!alternative //*swap(a[low++],a[mid++]); } else if (a[mid] == 1) { mid++; } else { temp = a[mid]; a[mid] = a[high]; a[high] = temp; high--; //!swap(a[mid],a[high--]); } } }
16.138889
40
0.303787
ManthanChoudhury
35893fb1c278ccd377860a42100d78011654bf45
579
cpp
C++
hello.cpp
wheel0012/Horner-algo
288267e67a285a92d965f5c2a2f8fd149adf6f90
[ "Unlicense" ]
null
null
null
hello.cpp
wheel0012/Horner-algo
288267e67a285a92d965f5c2a2f8fd149adf6f90
[ "Unlicense" ]
null
null
null
hello.cpp
wheel0012/Horner-algo
288267e67a285a92d965f5c2a2f8fd149adf6f90
[ "Unlicense" ]
null
null
null
#include <iostream> #include <string.h> class Tools { public: Tools() { } void Split(char* str) { std::cout<<strlen(str)<<std::endl; for(int i = 0; i< strlen(str); i++) { std::cout<<str[i]<<std::endl; } std::cout<<"\n"<<std::endl; //str[0] } }; int main() { Tools tools; char *str = (char *)malloc(sizeof(char) * 200); std::cin.getline(str, sizeof(*str)); fflush(stdin); //std::cout << "hello, world!" << std::endl; tools.Split(str); getchar(); return 0; }
18.09375
51
0.481865
wheel0012
3589c3b6f385168fedf2e731e748d226a469cc2e
2,113
hpp
C++
capo/construct.hpp
mutouyun/capo
d90528cf5bb59bdf76cdf94dfa6a55bcb1bfdc13
[ "MIT" ]
58
2015-03-22T03:26:07.000Z
2022-03-30T05:15:22.000Z
capo/construct.hpp
mutouyun/capo
d90528cf5bb59bdf76cdf94dfa6a55bcb1bfdc13
[ "MIT" ]
1
2019-03-07T12:32:41.000Z
2019-03-16T15:01:55.000Z
capo/construct.hpp
mutouyun/capo
d90528cf5bb59bdf76cdf94dfa6a55bcb1bfdc13
[ "MIT" ]
21
2015-02-27T06:44:56.000Z
2022-03-05T15:53:30.000Z
/* The Capo Library Code covered by the MIT License Author: mutouyun (http://orzz.org) */ #pragma once #include <new> // placement new #include <utility> // std::forward #include <cstddef> // size_t namespace capo { //////////////////////////////////////////////////////////////// /// Construct an object, just like placement new //////////////////////////////////////////////////////////////// namespace detail_construct { template <typename T> struct impl { template <typename... P> static T* construct(T* p, P&&... args) { return ::new (p) T(std::forward<P>(args)...); } }; template <typename T, size_t N> struct impl<T[N]> { using type = T[N]; template <typename... P> static type* construct(type* p, P&&... args) { for (size_t i = 0; i < N; ++i) impl<T>::construct((*p) + i, std::forward<P>(args)...); return p; } }; } template <typename T, typename... P> T* construct(T* p, P&&... args) { return detail_construct::impl<T>::construct(p, std::forward<P>(args)...); } template <typename T, typename... P> T* construct(void* p, P&&... args) { return construct(static_cast<T*>(p), std::forward<P>(args)...); } //////////////////////////////////////////////////////////////// /// Destruct an object, but not free the memory //////////////////////////////////////////////////////////////// namespace detail_destruct { template <typename T> struct impl { static void destruct(T* p) { reinterpret_cast<T*>(p)->~T(); } }; template <typename T, size_t N> struct impl<T[N]> { using type = T[N]; static void destruct(type* p) { for (size_t i = 0; i < N; ++i) impl<T>::destruct((*p) + i); } }; } template <typename T> void destruct(T* p) { return detail_destruct::impl<T>::destruct(p); } template <typename T> void destruct(void* p) { destruct(static_cast<T*>(p)); } } // namespace capo
21.561224
77
0.471368
mutouyun
358d40594ff2238018899f70ffd82c915d584f32
742
cpp
C++
playground/main.cpp
MoustaphaSaad/tethys
205be8060bdcadbca111d8222686e3b121cc90b7
[ "BSD-3-Clause" ]
4
2019-10-20T16:57:18.000Z
2019-12-30T09:34:02.000Z
playground/main.cpp
MoustaphaSaad/tethys
205be8060bdcadbca111d8222686e3b121cc90b7
[ "BSD-3-Clause" ]
null
null
null
playground/main.cpp
MoustaphaSaad/tethys
205be8060bdcadbca111d8222686e3b121cc90b7
[ "BSD-3-Clause" ]
1
2019-11-02T19:08:26.000Z
2019-11-02T19:08:26.000Z
#include <mn/IO.h> #include <mn/Library.h> #include <ffi.h> #include <ffi/FFI.h> extern "C" int myadd(int a, int b) { return a + b; } int main(int, char**) { auto l = mn::library_open(""); auto f = mn::library_proc(l, "myadd"); mn::print("{}, {}\n", l, f); mn::library_close(l); mn::print("Hello, World!"); ffi_cif cif; ffi_type* arg_types[2]; void* arg_values[2]; ffi_arg ret; int arg1 = 1; int arg2 = 2; arg_types[0] = &ffi_type_sint; arg_values[0] = &arg1; arg_types[1] = &ffi_type_sint; arg_values[1] = &arg2; auto dbg = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &ffi_type_sint, arg_types); mn::print("ffi_prep_cif = {}\n", dbg); ffi_call(&cif, FFI_FN(myadd), &ret, arg_values); mn::print("{}\n", ret); return 0; }
19.526316
78
0.62938
MoustaphaSaad
3590fb222e5b8f6f814e9026b8ef356eb2a5c419
946
cpp
C++
codeforces/A - Yet Another Dividing into Teams/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/A - Yet Another Dividing into Teams/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/A - Yet Another Dividing into Teams/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: * kzvd4729 created: Oct/22/2019 20:38 * solution_verdict: Accepted language: GNU C++14 * run_time: 30 ms memory_used: 3900 KB * problem: https://codeforces.com/contest/1249/problem/A ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6; int aa[N+2]; int main() { ios_base::sync_with_stdio(0);cin.tie(0); int q;cin>>q; while(q--) { int n;cin>>n; for(int i=1;i<=n;i++)cin>>aa[i]; sort(aa+1,aa+n+1); int f=1; for(int i=2;i<=n;i++) if(aa[i]-aa[i-1]==1)f=2; cout<<f<<"\n"; } return 0; }
35.037037
111
0.363636
kzvd4729
359381646aad150d93bbcfed18f01342ef88b04c
1,476
hpp
C++
src/symbol.hpp
Stazer/zlisp
43df64fd5941dd650e35cd93aa6f44b544f2da86
[ "MIT" ]
null
null
null
src/symbol.hpp
Stazer/zlisp
43df64fd5941dd650e35cd93aa6f44b544f2da86
[ "MIT" ]
2
2019-07-21T19:43:18.000Z
2019-07-21T19:46:08.000Z
src/symbol.hpp
Stazer/zlisp
43df64fd5941dd650e35cd93aa6f44b544f2da86
[ "MIT" ]
null
null
null
#pragma once #include <unordered_map> #include <unordered_set> #include <cstdint> #include <vector> #include <iosfwd> #include <string> #include <ostream> struct symbol { symbol(const std::string& str); symbol(const char* str); symbol(const symbol& s); symbol(symbol&& s); ~symbol() noexcept; symbol& operator=(const std::string& str); symbol& operator=(const char* str); symbol& operator=(const symbol& s); symbol& operator=(symbol&& s); friend std::ostream& operator<<(std::ostream& os, const symbol& s); const std::string& get_string() const; std::uint_fast32_t get_hash() const; private: static std::string& lookup_or_emplace(std::uint_fast32_t hash, const char* str); private: thread_local static std::unordered_map<std::uint_fast32_t, std::string> symbols; std::uint_fast32_t hash; }; struct symbol_hasher { std::size_t operator()(symbol symb) const { return symb.get_hash(); } }; struct symbol_comparer { bool operator()(symbol lhs, symbol rhs) const { return lhs.get_hash() == rhs.get_hash(); } }; template<class T> using symbol_map = std::unordered_map<symbol, T, symbol_hasher, symbol_comparer, std::allocator<std::pair<symbol, T>>>; using symbol_set = std::unordered_set<symbol, symbol_hasher, symbol_comparer, std::allocator<symbol>>; bool operator==(const symbol& a, const symbol& b); bool operator!=(const symbol& a, const symbol& b); std::ostream& operator<<(std::ostream& os, const std::vector<symbol>& symbs);
26.357143
119
0.716802
Stazer
359778960c0ac3dc9d8e895e31b34f89b2e6677c
2,044
cpp
C++
src/walker.cpp
nantha007/walker
ad705a5801888dea1459280326dc20e8580f1ba2
[ "MIT" ]
null
null
null
src/walker.cpp
nantha007/walker
ad705a5801888dea1459280326dc20e8580f1ba2
[ "MIT" ]
null
null
null
src/walker.cpp
nantha007/walker
ad705a5801888dea1459280326dc20e8580f1ba2
[ "MIT" ]
null
null
null
/** * MIT License * Copyright (c) 2018 Nantha Kumar Sunder * * 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. */ /** * @file walker.cpp * @brief A program for walker * @author Nantha Kumar Sunder * @copyright 2018 */ #include "include/walker.h" #include "sensor_msgs/LaserScan.h" #include "geometry_msgs/Twist.h" /** * @brief Subscriber Node for topic scan call back function * @param val dist vector from sensor_msgs * @return none */ void walker::walkerCallback(const sensor_msgs::LaserScan::ConstPtr& val) { float minValue; minValue = val->ranges[0]; // Finding the min value of the val vector for (const auto& temp : val->ranges) { if (minValue > temp) { minValue = temp; } } dist = minValue; // if the distance is less than 1 then, robot has to be change course if (dist < 2) { checkDist = 1; } else { checkDist = 0; } } /** * @brief function to get the value of the distance * @param none * @return dist */ float walker::getDist() { return dist; }
32.444444
81
0.713307
nantha007
35980febdc0c2227769327da687214cb05299a60
4,119
hpp
C++
SDK/ARKSurvivalEvolved_Task_ShakeOffBasedPlayers_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_Task_ShakeOffBasedPlayers_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_Task_ShakeOffBasedPlayers_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Task_ShakeOffBasedPlayers_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Task_ShakeOffBasedPlayers.Task_ShakeOffBasedPlayers_C // 0x0088 (0x0100 - 0x0078) class UTask_ShakeOffBasedPlayers_C : public UBTTask_BlueprintBase { public: class AForestKaiju_Character_BP_C* ForestKaijuChar; // 0x0078(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData) struct FBlackboardKeySelector ShakeOffPlayers; // 0x0080(0x0028) (Edit, BlueprintVisible) class AForestKaiju_AIController_BP_C* FK_AIC; // 0x00A8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData) class AActor* K2Node_Event_OwnerActor2; // 0x00B0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) class AForestKaiju_AIController_BP_C* K2Node_DynamicCast_AsForestKaiju_AIController_BP_C; // 0x00B8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool K2Node_DynamicCast_CastSuccess; // 0x00C0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData00[0x7]; // 0x00C1(0x0007) MISSED OFFSET class APawn* CallFunc_GetControllerPawn_ReturnValue; // 0x00C8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) class AForestKaiju_Character_BP_C* K2Node_DynamicCast_AsForestKaiju_Character_BP_C; // 0x00D0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool K2Node_DynamicCast2_CastSuccess; // 0x00D8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData01[0x3]; // 0x00D9(0x0003) MISSED OFFSET float CallFunc_PlayAnimEx_ReturnValue; // 0x00DC(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) class UAnimMontage* CallFunc_GetCurrentMontage_ReturnValue; // 0x00E0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) class AActor* K2Node_Event_OwnerActor; // 0x00E8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_IsValid_ReturnValue; // 0x00F0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData02[0x7]; // 0x00F1(0x0007) MISSED OFFSET double CallFunc_GetGameTimeInSeconds_ReturnValue; // 0x00F8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Task_ShakeOffBasedPlayers.Task_ShakeOffBasedPlayers_C"); return ptr; } void MaybeCutGrapplingHooks(); void ReceiveExecute(class AActor** OwnerActor); void ReceiveAbort(class AActor** OwnerActor); void ExecuteUbergraph_Task_ShakeOffBasedPlayers(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
69.813559
231
0.590192
2bite
359814abe32bf22c6d44dc60701f59e4556ec47f
2,836
cpp
C++
ql/methods/finitedifferences/stepconditions/fdmsimpleswingcondition.cpp
quantosaurosProject/quantLib
84b49913d3940cf80d6de8f70185867373f45e8d
[ "BSD-3-Clause" ]
null
null
null
ql/methods/finitedifferences/stepconditions/fdmsimpleswingcondition.cpp
quantosaurosProject/quantLib
84b49913d3940cf80d6de8f70185867373f45e8d
[ "BSD-3-Clause" ]
null
null
null
ql/methods/finitedifferences/stepconditions/fdmsimpleswingcondition.cpp
quantosaurosProject/quantLib
84b49913d3940cf80d6de8f70185867373f45e8d
[ "BSD-3-Clause" ]
1
2022-03-29T05:44:27.000Z
2022-03-29T05:44:27.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2010 Klaus Spanderen This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include <ql/methods/finitedifferences/operators/fdmlinearoplayout.hpp> #include <ql/methods/finitedifferences/stepconditions/fdmsimpleswingcondition.hpp> namespace QuantLib { FdmSimpleSwingCondition::FdmSimpleSwingCondition( const std::vector<Time> & exerciseTimes, const boost::shared_ptr<FdmMesher>& mesher, const boost::shared_ptr<FdmInnerValueCalculator>& calculator, Size swingDirection) : exerciseTimes_ (exerciseTimes), mesher_ (mesher), calculator_ (calculator), swingDirection_(swingDirection) { } void FdmSimpleSwingCondition::applyTo(Array& a, Time t) const { const std::vector<Time>::const_iterator iter = std::find(exerciseTimes_.begin(), exerciseTimes_.end(), t); if (iter != exerciseTimes_.end()) { Array retVal= a; const Size d = std::distance(iter, exerciseTimes_.end()); const boost::shared_ptr<FdmLinearOpLayout> layout=mesher_->layout(); const FdmLinearOpIterator endIter = layout->end(); for (FdmLinearOpIterator iter = layout->begin(); iter != endIter; ++iter) { const std::vector<Size>& coor = iter.coordinates(); const Size exerciseValue = coor[swingDirection_]; if (exerciseValue > 0) { const Real cashflow = calculator_->innerValue(iter, t); const Real currentValue = a[iter.index()]; const Real valueMinusOneExRight = a[layout->neighbourhood(iter, swingDirection_, -1)]; if ( currentValue < cashflow + valueMinusOneExRight || exerciseValue >= d ) { retVal[iter.index()] = cashflow + valueMinusOneExRight; } } } a = retVal; } } }
39.943662
82
0.608956
quantosaurosProject
35a2fa164c0b41bba1c63ad4b0ac64cd167b6775
1,239
cpp
C++
nd-coursework/books/cpp/FoundationsOfQtDev/Chapter01/Listing1_22-24.cpp
crdrisko/nd-grad
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
1
2020-09-26T12:38:55.000Z
2020-09-26T12:38:55.000Z
nd-coursework/books/cpp/FoundationsOfQtDev/Chapter01/Listing1_22-24.cpp
crdrisko/nd-research
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
null
null
null
nd-coursework/books/cpp/FoundationsOfQtDev/Chapter01/Listing1_22-24.cpp
crdrisko/nd-research
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
null
null
null
// Copyright (c) 2007 Johan Thelin. Some rights reserved. // Licensed under the Freeware License. See the LICENSE file in the project root for more information. // // Name: Listing1_22-24.cpp // Author: crdrisko // Date: 08/02/2021-11:02:49 // Description: Mapping and Hashing (pt 2) #include <iostream> #include <vector> #include <QHash> #include <QString> // Listing 1-22: A class holding name and number class Person { public: Person(const QString& name, const QString& number); const QString& name() const; const QString& number() const; private: QString m_name, m_number; }; bool operator==(const Person& a, const Person& b) { return (a.name() == b.name()) && (a.number() == b.number()); } uint qHash(const Person& key) { return qHash(key.name()) ^ qHash(key.number()); } // Listing 1-24: Hashing the Person class int main() { QHash<Person, int> hash; hash[Person("Anders", "8447070")] = 10; hash[Person("Micke", "7728433")] = 20; qDebug() << hash.value(Person("Anders", "8447070")); // 10 qDebug() << hash.value(Person("Anders", "8447071")); // 0 qDebug() << hash.value(Person("Micke", "7728433")); // 20 qDebug() << hash.value(Person("Mickael", "7728433")); // 0 }
27.533333
114
0.641646
crdrisko
35a5eaa99def6522de193575bfc961b95172d070
1,578
hh
C++
include/nauths/npl/pp/array_cat.hh
nicuveo/NPL
1338729524708165a953d7ccf9b5de7b68d28588
[ "MIT" ]
null
null
null
include/nauths/npl/pp/array_cat.hh
nicuveo/NPL
1338729524708165a953d7ccf9b5de7b68d28588
[ "MIT" ]
null
null
null
include/nauths/npl/pp/array_cat.hh
nicuveo/NPL
1338729524708165a953d7ccf9b5de7b68d28588
[ "MIT" ]
null
null
null
// // Copyright Antoine Leblanc 2010 - 2015 // Distributed under the MIT license. // // http://nauths.fr // http://github.com/nicuveo // mailto://antoine.jp.leblanc@gmail.com // #ifndef NPL_PP_ARRAY_CAT_HH_ # define NPL_PP_ARRAY_CAT_HH_ //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH // Includes # include <boost/preprocessor/array/push_back.hpp> # include <boost/preprocessor/array/pop_front.hpp> # include <boost/preprocessor/array/elem.hpp> # include <boost/preprocessor/tuple/elem.hpp> # include <boost/preprocessor/tuple/elem.hpp> # include <boost/preprocessor/while.hpp> # include <boost/preprocessor/cat.hpp> //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH // Declarations /* ** Concatenates two PP_ARRAYs. ** _D variant uses the next available PP_WHILE iteration ** For examples, see unit tests below. */ # define NPL_PP_ARRAY_CAT( A1, A2) NPL_PP_AC_1( BOOST_PP_WHILE(NPL_PP_AC_PRED, NPL_PP_AC_OP, (A1, A2))) # define NPL_PP_ARRAY_CAT_D(D, A1, A2) NPL_PP_AC_1(BOOST_PP_CAT(BOOST_PP_WHILE_, D)(NPL_PP_AC_PRED, NPL_PP_AC_OP, (A1, A2))) //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH // Implementation # define NPL_PP_AC_1(S) BOOST_PP_TUPLE_ELEM(2, 0, S) # define NPL_PP_AC_2(S) BOOST_PP_TUPLE_ELEM(2, 1, S) # define NPL_PP_AC_PRED(D, S) BOOST_PP_ARRAY_SIZE(NPL_PP_AC_2(S)) # define NPL_PP_AC_OP( D, S) (BOOST_PP_ARRAY_PUSH_BACK(NPL_PP_AC_1(S), BOOST_PP_ARRAY_ELEM(0, NPL_PP_AC_2(S))), BOOST_PP_ARRAY_POP_FRONT(NPL_PP_AC_2(S))) #endif /* !NPL_PP_ARRAY_CAT_HH_ */
29.773585
154
0.775032
nicuveo
35a6c48e751611041e5d19bc8cd466f40cf856df
1,560
cpp
C++
src/policy/consistency.cpp
kaiyuhou/neo
e75e42d7654afcd4606ceb7f60d122cc9aec44af
[ "NCSA" ]
null
null
null
src/policy/consistency.cpp
kaiyuhou/neo
e75e42d7654afcd4606ceb7f60d122cc9aec44af
[ "NCSA" ]
null
null
null
src/policy/consistency.cpp
kaiyuhou/neo
e75e42d7654afcd4606ceb7f60d122cc9aec44af
[ "NCSA" ]
null
null
null
#include "policy/consistency.hpp" #include "model-access.hpp" #include "model.h" std::string ConsistencyPolicy::to_string() const { std::string ret = "consistency of "; for (Policy *p : correlated_policies) { ret += p->to_string() + ", "; } ret.pop_back(); ret.pop_back(); return ret; } void ConsistencyPolicy::init(State *state) { set_violated(state, false); set_comm(state, 0); set_num_comms(state, 1); set_correlated_policy_idx(state, 0); correlated_policies[state->correlated_policy_idx]->init(state); } int ConsistencyPolicy::check_violation(State *state) { correlated_policies[state->correlated_policy_idx]->check_violation(state); if (state->choice_count == 0) { // for the first subpolicy, store the verification result if (state->correlated_policy_idx == 0) { result = state->violated; } // check for consistency if (state->violated != result) { state->violated = true; state->choice_count = 0; return POL_NULL; } // next subpolicy if ((size_t)state->correlated_policy_idx + 1 < correlated_policies.size()) { ++state->correlated_policy_idx; state->choice_count = 1; correlated_policies[state->correlated_policy_idx]->init(state); return POL_INIT_FWD; } else { // we have checked all the subpolicies state->violated = false; state->choice_count = 0; } } return POL_NULL; }
27.368421
84
0.614103
kaiyuhou
35ad24c999909f4d96a861eb2046915116140caf
213
hpp
C++
gearoenix/render/mesh/gx-rnd-msh-type.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
35
2018-01-07T02:34:38.000Z
2022-02-09T05:19:03.000Z
gearoenix/render/mesh/gx-rnd-msh-type.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
111
2017-09-20T09:12:36.000Z
2020-12-27T12:52:03.000Z
gearoenix/render/mesh/gx-rnd-msh-type.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
5
2020-02-11T11:17:37.000Z
2021-01-08T17:55:43.000Z
#ifndef GEAROENIX_RENDER_MESH_TYPE_HPP #define GEAROENIX_RENDER_MESH_TYPE_HPP #include "../../core/gx-cr-types.hpp" namespace gearoenix::render::mesh { enum struct Type : core::TypeId { Basic = 1, }; } #endif
21.3
38
0.741784
Hossein-Noroozpour
35bb9b74c7e9a279758891f2ce60375cb7bade04
1,559
cpp
C++
bin/test-ok/3.cpp
badforlabor/tolua-
15ae5789ef2a6295eb5af6c26f927a7572ec9864
[ "MIT" ]
8
2016-05-17T08:26:49.000Z
2021-05-16T22:33:59.000Z
bin/test-ok/3.cpp
badforlabor/tolua-
15ae5789ef2a6295eb5af6c26f927a7572ec9864
[ "MIT" ]
null
null
null
bin/test-ok/3.cpp
badforlabor/tolua-
15ae5789ef2a6295eb5af6c26f927a7572ec9864
[ "MIT" ]
6
2017-05-04T01:21:15.000Z
2021-04-20T12:21:14.000Z
/* ** Lua binding: tconstant ** Generated automatically by tolua++-1.0.92 on 01/05/16 18:22:51. */ #ifndef __cplusplus #include "stdlib.h" #endif #include "string.h" #include "tolua++.h" /* Exported function */ TOLUA_API int tolua_tconstant_open (lua_State* tolua_S); #include "tconstant.h" /* function to register type */ static void tolua_reg_types (lua_State* tolua_S) { tolua_usertype(tolua_S,"A"); } /* Open function */ TOLUA_API int tolua_tconstant_open (lua_State* tolua_S) { tolua_open(tolua_S); tolua_reg_types(tolua_S); tolua_module(tolua_S,NULL,0); tolua_beginmodule(tolua_S,NULL); tolua_constant(tolua_S,"FIRST",FIRST); tolua_constant(tolua_S,"SECOND",SECOND); tolua_constant(tolua_S,"ONE",ONE); tolua_constant(tolua_S,"TWO",TWO); tolua_module(tolua_S,"M",0); tolua_beginmodule(tolua_S,"M"); tolua_constant(tolua_S,"FIRST",M_FIRST); tolua_constant(tolua_S,"SECOND",M_SECOND); tolua_constant(tolua_S,"ONE",M_ONE); tolua_constant(tolua_S,"TWO",M_TWO); tolua_endmodule(tolua_S); tolua_cclass(tolua_S,"A","A","",NULL); tolua_beginmodule(tolua_S,"A"); tolua_constant(tolua_S,"FIRST",FIRST); tolua_constant(tolua_S,"SECOND",SECOND); tolua_constant(tolua_S,"ONE",A::ONE); tolua_constant(tolua_S,"TWO",A::TWO); tolua_endmodule(tolua_S); tolua_endmodule(tolua_S); return 1; } #if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 501 TOLUA_API int luaopen_tconstant (lua_State* tolua_S) { return tolua_tconstant_open(tolua_S); }; #endif
25.983333
67
0.708146
badforlabor
35c10f6d6b53b35c243fe75e2ebaa813ae6fadc1
143
hh
C++
src/turing-digital-module-widget.hh
Chaircrusher/skylights-vcv
04c66539824f8e4b4de4da824f2090470e8494ec
[ "BSD-3-Clause" ]
16
2019-02-09T19:54:26.000Z
2019-11-20T16:29:03.000Z
src/turing-digital-module-widget.hh
Chaircrusher/skylights-vcv
04c66539824f8e4b4de4da824f2090470e8494ec
[ "BSD-3-Clause" ]
15
2019-03-04T19:44:38.000Z
2019-08-10T03:33:33.000Z
src/turing-digital-module-widget.hh
Chaircrusher/skylights-vcv
04c66539824f8e4b4de4da824f2090470e8494ec
[ "BSD-3-Clause" ]
5
2019-05-09T10:52:54.000Z
2021-12-03T17:37:56.000Z
#pragma once #include "skylights.hh" struct turing_digital_module_widget : ModuleWidget { turing_digital_module_widget(Module *module); };
17.875
52
0.797203
Chaircrusher
35c2a5c6e9e225789bd6e8dce8bd96e9b98973ad
1,333
cpp
C++
c1/dualpal.cpp
rodrigods/usaco
8d95fd6a285e4f6f61199b9bef6af93fb087f63e
[ "Apache-2.0" ]
null
null
null
c1/dualpal.cpp
rodrigods/usaco
8d95fd6a285e4f6f61199b9bef6af93fb087f63e
[ "Apache-2.0" ]
null
null
null
c1/dualpal.cpp
rodrigods/usaco
8d95fd6a285e4f6f61199b9bef6af93fb087f63e
[ "Apache-2.0" ]
null
null
null
/* ID: rodrigo40 PROG: dualpal LANG: C++ */ #include <iostream> #include <fstream> #include <string> #include <algorithm> using namespace std; bool isPalindrome(string str) { int l = 0; int r = str.length() - 1; while (l < r) { if (str[l] != str[r]) { return false; } l++; r--; } return true; } char numberToChar(int number) { return '0' + number; } string convertToBase(int number, int base) { string result = ""; while (number > 0) { result += numberToChar(number % base); number /= base; } reverse(result.begin(), result.end()); return result; } int main() { ofstream fout ("dualpal.out"); ifstream fin ("dualpal.in"); int n, s; fin >> n >> s; int candidate = s + 1; int counter = 0; while (counter < n) { int palindromeCounter = 0; for (int i = 2; i <= 10; i++) { string candidateInBase = convertToBase(candidate, i); if (isPalindrome(candidateInBase)) { palindromeCounter++; } if (palindromeCounter >= 2) { break; } } if (palindromeCounter >= 2) { fout << candidate << endl; counter++; } candidate++; } return 0; }
19.042857
65
0.498875
rodrigods
35c7229cb86b9597a6f3c5175052eed6a1f11b65
1,793
cc
C++
Codeforces/353 Division 2/Problem D/D.cc
VastoLorde95/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
170
2017-07-25T14:47:29.000Z
2022-01-26T19:16:31.000Z
Codeforces/353 Division 2/Problem D/D.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
null
null
null
Codeforces/353 Division 2/Problem D/D.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
55
2017-07-28T06:17:33.000Z
2021-10-31T03:06:22.000Z
#include <bits/stdc++.h> #define sd(x) scanf("%d",&x) #define sd2(x,y) scanf("%d%d",&x,&y) #define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z) #define fi first #define se second #define pb push_back #define mp make_pair #define foreach(it, v) for(__typeof((v).begin()) it=(v).begin(); it != (v).end(); ++it) #define meta __FUNCTION__,__LINE__ #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout); using namespace std; template<typename S, typename T> ostream& operator<<(ostream& out,pair<S,T> const& p){out<<'('<<p.fi<<", "<<p.se<<')';return out;} template<typename T> ostream& operator<<(ostream& out,vector<T> const& v){ int l=v.size();for(int i=0;i<l-1;i++)out<<v[i]<<' ';if(l>0)out<<v[l-1];return out;} void tr(){cout << endl;} template<typename S, typename ... Strings> void tr(S x, const Strings&... rest){cout<<x<<' ';tr(rest...);} typedef long long ll; typedef pair<int,int> pii; const int N = 100100; set<pii> s; int l[N]; int r[N]; int n; int a[N]; int p[N]; int main(){ sd(n); for(int i = 1; i <= n; i++){ sd(a[i]); } s.insert(mp(a[1], 1)); set<pii>::iterator i1, i2; for(int i = 2; i <= n; i++){ i1 = s.upper_bound(mp(a[i], 0)); if(i1 == s.begin()){ // bigger l[i1->se] = i; p[i] = i1->se; } else{ i2 = i1; i2--; // i1 is just bigger // i2 is just smaller int x = -1, y = -1; if(i1 != s.end()){ x = i1->se; } y = i2->se; if(x == -1){ r[y] = i; p[i] = y; } else{ if(l[x] > 0){ r[y] = i; p[i] = y; } else{ l[x] = i; p[i] = x; } } } s.insert(mp(a[i], i)); } for(int i = 2; i <= n; i++){ printf("%d ", a[p[i]]); } puts(""); return 0; }
17.93
97
0.524819
VastoLorde95
35cb0eb3786696c1bde643ee55aba3041fbb309a
6,240
cpp
C++
src/module/usModuleResource.cpp
azriel91/CppMicroServices
13080ed60791940a6e0aef38fe5d89d53d97fb41
[ "Apache-2.0" ]
1
2021-06-27T05:11:08.000Z
2021-06-27T05:11:08.000Z
src/module/usModuleResource.cpp
azriel91/CppMicroServices
13080ed60791940a6e0aef38fe5d89d53d97fb41
[ "Apache-2.0" ]
3
2017-08-20T22:10:51.000Z
2017-09-04T12:48:40.000Z
src/module/usModuleResource.cpp
MoonLightDE/mlde.l.cppmicroservices
cf471b30539d7e1a138d6308b2b249fe19df2302
[ "Apache-2.0" ]
2
2020-10-27T06:51:00.000Z
2020-10-27T06:51:01.000Z
/*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics 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 "usModuleResource.h" #include "usAtomicInt_p.h" #include "usModuleResourceTree_p.h" #include <string> US_BEGIN_NAMESPACE class ModuleResourcePrivate { public: ModuleResourcePrivate() : associatedResourceTree(NULL) , node(-1) , size(0) , data(NULL) , isFile(false) , isCompressed(false) , ref(1) {} std::string fileName; std::string path; std::string filePath; std::vector<ModuleResourceTree*> resourceTrees; const ModuleResourceTree* associatedResourceTree; int node; int32_t size; const unsigned char* data; unsigned char* uncompressedData; mutable std::vector<std::string> children; bool isFile; bool isCompressed; /** * Reference count for implicitly shared private implementation. */ AtomicInt ref; }; ModuleResource::ModuleResource() : d(new ModuleResourcePrivate) { } ModuleResource::ModuleResource(const ModuleResource &resource) : d(resource.d) { d->ref.Ref(); } ModuleResource::ModuleResource(const std::string& _file, ModuleResourceTree* associatedResourceTree, const std::vector<ModuleResourceTree*>& resourceTrees) : d(new ModuleResourcePrivate) { d->resourceTrees = resourceTrees; d->associatedResourceTree = associatedResourceTree; std::string file = _file; if (file.empty()) file = "/"; if (file[0] != '/') file = std::string("/") + file; std::size_t index = file.find_last_of('/'); if (index < file.size()-1) { d->fileName = file.substr(index+1); } std::string rawPath = file.substr(0,index+1); // remove duplicate / std::string::value_type lastChar = 0; for (std::size_t i = 0; i < rawPath.size(); ++i) { if (rawPath[i] == '/' && lastChar == '/') { continue; } lastChar = rawPath[i]; d->path.push_back(lastChar); } d->filePath = d->path + d->fileName; d->node = d->associatedResourceTree->FindNode(GetResourcePath()); if (d->node != -1) { d->isFile = !d->associatedResourceTree->IsDir(d->node); if (d->isFile) { d->data = d->associatedResourceTree->GetData(d->node, &d->size); d->isCompressed = d->associatedResourceTree->IsCompressed(d->node); } } } ModuleResource::~ModuleResource() { if (!d->ref.Deref()) delete d; } ModuleResource& ModuleResource::operator =(const ModuleResource& resource) { ModuleResourcePrivate* curr_d = d; d = resource.d; d->ref.Ref(); if (!curr_d->ref.Deref()) delete curr_d; return *this; } bool ModuleResource::operator <(const ModuleResource& resource) const { return this->GetResourcePath() < resource.GetResourcePath(); } bool ModuleResource::operator ==(const ModuleResource& resource) const { return d->associatedResourceTree == resource.d->associatedResourceTree && this->GetResourcePath() == resource.GetResourcePath(); } bool ModuleResource::operator !=(const ModuleResource &resource) const { return !(*this == resource); } bool ModuleResource::IsValid() const { return d->associatedResourceTree && d->associatedResourceTree->IsValid() && d->node > -1; } bool ModuleResource::IsCompressed() const { return d->isCompressed; } ModuleResource::operator bool_type() const { return IsValid() ? &ModuleResource::d : NULL; } std::string ModuleResource::GetName() const { return d->fileName; } std::string ModuleResource::GetPath() const { return d->path; } std::string ModuleResource::GetResourcePath() const { return d->filePath; } std::string ModuleResource::GetBaseName() const { return d->fileName.substr(0, d->fileName.find_first_of('.')); } std::string ModuleResource::GetCompleteBaseName() const { return d->fileName.substr(0, d->fileName.find_last_of('.')); } std::string ModuleResource::GetSuffix() const { std::size_t index = d->fileName.find_last_of('.'); return index < d->fileName.size()-1 ? d->fileName.substr(index+1) : std::string(""); } std::string ModuleResource::GetCompleteSuffix() const { std::size_t index = d->fileName.find_first_of('.'); return index < d->fileName.size()-1 ? d->fileName.substr(index+1) : std::string(""); } bool ModuleResource::IsDir() const { return !d->isFile; } bool ModuleResource::IsFile() const { return d->isFile; } std::vector<std::string> ModuleResource::GetChildren() const { if (d->isFile || !IsValid()) return d->children; if (!d->children.empty()) return d->children; bool indexPastAssociatedResTree = false; for (std::size_t i = 0; i < d->resourceTrees.size(); ++i) { if (d->resourceTrees[i] == d->associatedResourceTree) { indexPastAssociatedResTree = true; d->associatedResourceTree->GetChildren(d->node, d->children); } else if (indexPastAssociatedResTree) { int nodeIndex = d->resourceTrees[i]->FindNode(GetPath()); if (nodeIndex > -1) { d->resourceTrees[i]->GetChildren(d->node, d->children); } } } return d->children; } int ModuleResource::GetSize() const { return d->size; } const unsigned char* ModuleResource::GetData() const { if (!IsValid()) return NULL; return d->data; } std::size_t ModuleResource::Hash() const { using namespace US_HASH_FUNCTION_NAMESPACE; return US_HASH_FUNCTION(std::string, this->GetResourcePath()); } US_END_NAMESPACE US_USE_NAMESPACE std::ostream& operator<<(std::ostream& os, const ModuleResource& resource) { return os << resource.GetResourcePath(); }
22.941176
100
0.668269
azriel91
35d0bc7a119465d0510618a90389426afec39671
5,323
cpp
C++
src/Camera.cpp
jamino/SoftShadows
75684963496c7f51179cdd48b3a65a1cc410404e
[ "0BSD" ]
1
2019-08-20T21:48:34.000Z
2019-08-20T21:48:34.000Z
src/Camera.cpp
jamino/SoftShadows
75684963496c7f51179cdd48b3a65a1cc410404e
[ "0BSD" ]
null
null
null
src/Camera.cpp
jamino/SoftShadows
75684963496c7f51179cdd48b3a65a1cc410404e
[ "0BSD" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2012, Ben Lane // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION // OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /////////////////////////////////////////////////////////////////////////////// #include "Precomp.hpp" #include "Common.hpp" #include "Camera.hpp" #include "Scene.hpp" #include "ShaderProgram.hpp" Camera::Camera() // Initialise stuff to zero. : m_Yaw ( 0.0f ) , m_Pitch ( 0.0f ) { // Initialise more stuff to zero. m_Position.setZero(); m_ViewMatrix.setIdentity(); // Construct the initial view matrix. Should just be identity. ConstructViewMatrix(); // Setup a default perspective projection. Set both FOVs to 90. Probably // not that useful, should probably be overridden in user code. SetInfinitePerspectiveProjection( pi< float >() / 2.0f, pi< float >() / 2.0f, 0.1f ); } void Camera::SetPerspectiveProjectionCommon( const float horizFov, const float vertFov, const float zNear, const float matrixValue22 ) { // Standard perspective projection matrix stuff here. The only difference // is how we handle the third row when we do infinite projection. See Eric // Lengyel's Gamasutra article "The Mechanics of Robust Stencil Shadows" // (http://www.gamasutra.com/view/feature/2942/the_mechanics_of_robust_stencil_.php). m_ProjectionMatrix.setIdentity(); m_ProjectionMatrix( 0, 0 ) = 1.0f / tan( horizFov / 2.0f ); m_ProjectionMatrix( 1, 1 ) = 1.0f / tan( vertFov / 2.0f ); m_ProjectionMatrix( 2, 2 ) = matrixValue22; m_ProjectionMatrix( 2, 3 ) = -( 1.0f + matrixValue22 ) * zNear; m_ProjectionMatrix( 3, 2 ) = 1.0f; m_ProjectionMatrix( 3, 3 ) = 0.0f; } void Camera::SetPerspectiveProjection( const float horizFov, const float vertFov, const float zNear, const float zFar ) { SetPerspectiveProjectionCommon( horizFov, vertFov, zNear, zFar / ( zFar - zNear ) ); } void Camera::SetInfinitePerspectiveProjection( const float horizFov, const float vertFov, const float zNear ) { // As above, the (2, 2) matrix component is usually zFar / (zFar - zNear). // In the limit as zFar goes to infinity, this goes to 1 (ie zNear becomes // negligible). SetPerspectiveProjectionCommon( horizFov, vertFov, zNear, 1.0f ); } void Camera::Move( const Vector3f & translation ) { // Update position and reconstruct the view matrix. m_Position += translation; ConstructViewMatrix(); } void Camera::Look( const float yaw, const float pitch ) { // Update yaw and pitch. Clamping yaw within 0..2pi maintains precision // without loss of generality. m_Yaw = fmod( m_Yaw + yaw, 2.0f * pi< float >() ); m_Pitch += pitch; // Clamp pitch so that we can't go upside down. const float maxPitch = pi< float >() * 80.0f / 180.0f; if( m_Pitch > maxPitch ) m_Pitch = maxPitch; else if( m_Pitch < -maxPitch ) m_Pitch = -maxPitch; // Need to reconstruct the view matrix. ConstructViewMatrix(); } void Camera::ConstructViewMatrix() { // Standard stuff for constructing a translation-rotation matrix. m_ViewMatrix( 0, 0 ) = cos( m_Yaw ); m_ViewMatrix( 0, 1 ) = 0.0f; m_ViewMatrix( 0, 2 ) = -sin( m_Yaw ); m_ViewMatrix( 1, 0 ) = -sin( m_Pitch ) * sin( m_Yaw ); m_ViewMatrix( 1, 1 ) = cos( m_Pitch ); m_ViewMatrix( 1, 2 ) = -sin( m_Pitch ) * cos( m_Yaw ); m_ViewMatrix( 2, 0 ) = cos( m_Pitch ) * sin( m_Yaw ); m_ViewMatrix( 2, 1 ) = sin( m_Pitch ); m_ViewMatrix( 2, 2 ) = cos( m_Pitch ) * cos( m_Yaw ); m_ViewMatrix.translation() = m_ViewMatrix.linear() * ( -m_Position ); } void Camera::Render() { // Clear the colour and depth buffers before we start drawing. Because we // are doing deferred rendering, this also clears all planes of the // geometry buffer. // TODO: This step should probably be done by the viewport or an // intermediate framebuffer object. glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // Set OpenGL matrices. glMatrixMode( GL_PROJECTION ); glLoadMatrixf( m_ProjectionMatrix.data() ); glMatrixMode( GL_MODELVIEW ); glLoadMatrixf( m_ViewMatrix.data() ); // Render objects in the scene. GetScene().m_RootNode.Render( m_ViewMatrix ); } // TODO: Merge this with the regular Render method above. void Camera::RenderShadowVolumes() { // Clear the shadow buffer. glClear( GL_COLOR_BUFFER_BIT ); // Set OpenGL matrices. glMatrixMode( GL_PROJECTION ); glLoadMatrixf( m_ProjectionMatrix.data() ); glMatrixMode( GL_MODELVIEW ); glLoadMatrixf( m_ViewMatrix.data() ); // Render shadow volumes cast by objects in the scene. GetScene().m_RootNode.RenderShadowVolumes( m_ViewMatrix ); }
31.128655
86
0.685516
jamino
35d1bdf2324522e34a1a2b15db5d2c19822c20a2
6,119
cpp
C++
testing/unittests/jlibtests.cpp
emuharemagic/HPCC-Platform
bbd5423b25f6ba2d675521c8917f9ecfa97dace5
[ "Apache-2.0" ]
1
2020-08-01T19:54:56.000Z
2020-08-01T19:54:56.000Z
testing/unittests/jlibtests.cpp
emuharemagic/HPCC-Platform
bbd5423b25f6ba2d675521c8917f9ecfa97dace5
[ "Apache-2.0" ]
null
null
null
testing/unittests/jlibtests.cpp
emuharemagic/HPCC-Platform
bbd5423b25f6ba2d675521c8917f9ecfa97dace5
[ "Apache-2.0" ]
null
null
null
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems. 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. ############################################################################## */ /* * Jlib regression tests * */ #ifdef _USE_CPPUNIT #include "jsem.hpp" #include "jfile.hpp" #include "jdebug.hpp" #include "sockfile.hpp" #include "unittests.hpp" class JlibSemTest : public CppUnit::TestFixture { public: CPPUNIT_TEST_SUITE(JlibSemTest); CPPUNIT_TEST(testSetup); CPPUNIT_TEST(testSimple); CPPUNIT_TEST(testCleanup); CPPUNIT_TEST_SUITE_END(); protected: void testSetup() { } void testCleanup() { } void testTimedAvailable(Semaphore & sem) { unsigned now = msTick(); sem.wait(100); unsigned taken = msTick() - now; //Shouldn't cause a reschedule, definitely shouldn't wait for 100s ASSERT(taken < 5); } void testTimedElapsed(Semaphore & sem, unsigned time) { unsigned now = msTick(); sem.wait(time); unsigned taken = msTick() - now; ASSERT(taken >= time && taken < 2*time); } void testSimple() { //Some very basic semaphore tests. Semaphore sem; sem.signal(); sem.wait(); testTimedElapsed(sem, 100); sem.signal(); testTimedAvailable(sem); sem.reinit(2); sem.wait(); testTimedAvailable(sem); testTimedElapsed(sem, 5); } }; CPPUNIT_TEST_SUITE_REGISTRATION( JlibSemTest ); CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( JlibSemTest, "JlibSemTest" ); /* =========================================================== */ class JlibFileIOTest : public CppUnit::TestFixture { unsigned rs, nr10pct, nr150pct; char *record; StringBuffer tmpfile; StringBuffer server; CPPUNIT_TEST_SUITE( JlibFileIOTest ); CPPUNIT_TEST(testIOSmall); CPPUNIT_TEST(testIORemote); CPPUNIT_TEST(testIOLarge); CPPUNIT_TEST_SUITE_END(); public: JlibFileIOTest() { HardwareInfo hdwInfo; getHardwareInfo(hdwInfo); rs = 65536; unsigned nr = (unsigned)(1024.0 * (1024.0 * (double)hdwInfo.totalMemory / (double)rs)); nr10pct = nr / 10; nr150pct = (unsigned)((double)nr * 1.5); record = (char *)malloc(rs); for (int i=0;i<rs;i++) record[i] = 'a'; record[rs-1] = '\n'; tmpfile.set("JlibFileIOTest.txt"); server.set("."); // server.set("192.168.1.18"); } ~JlibFileIOTest() { free(record); } protected: void testIO(unsigned nr, SocketEndpoint *ep) { IFile *ifile; IFileIO *ifileio; unsigned fsize = (unsigned)(((double)nr * (double)rs) / (1024.0 * 1024.0)); fflush(NULL); fprintf(stdout,"\n"); fflush(NULL); for(int j=0; j<2; j++) { if (j==0) fprintf(stdout, "File size: %d (MB) Cache, ", fsize); else fprintf(stdout, "\nFile size: %d (MB) Nocache, ", fsize); if (ep != NULL) { ifile = createRemoteFile(*ep, tmpfile); fprintf(stdout, "Remote: (%s)\n", server.toCharArray()); } else { ifile = createIFile(tmpfile); fprintf(stdout, "Local:\n"); } ifile->remove(); unsigned st = msTick(); IFEflags extraFlags = IFEcache; if (j==1) extraFlags = IFEnocache; ifileio = ifile->open(IFOcreate, extraFlags); unsigned iter = nr / 40; __int64 pos = 0; for (int i=0;i<nr;i++) { ifileio->write(pos, rs, record); pos += rs; if ((i % iter) == 0) { fprintf(stdout,"."); fflush(NULL); } } ifileio->close(); double rsec = (double)(msTick() - st)/1000.0; unsigned iorate = (unsigned)((double)fsize / rsec); fprintf(stdout, "\nwrite - elapsed time = %6.2f (s) iorate = %4d (MB/s)\n", rsec, iorate); st = msTick(); extraFlags = IFEcache; if (j==1) extraFlags = IFEnocache; ifileio = ifile->open(IFOread, extraFlags); pos = 0; for (int i=0;i<nr;i++) { ifileio->read(pos, rs, record); pos += rs; if ((i % iter) == 0) { fprintf(stdout,"."); fflush(NULL); } } ifileio->close(); rsec = (double)(msTick() - st)/1000.0; iorate = (unsigned)((double)fsize / rsec); fprintf(stdout, "\nread -- elapsed time = %6.2f (s) iorate = %4d (MB/s)\n", rsec, iorate); ifileio->Release(); ifile->remove(); ifile->Release(); } } void testIOSmall() { testIO(nr10pct, NULL); } void testIOLarge() { testIO(nr150pct, NULL); } void testIORemote() { SocketEndpoint ep; ep.set(server, 7100); testIO(nr10pct, &ep); } }; CPPUNIT_TEST_SUITE_REGISTRATION( JlibFileIOTest ); CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( JlibFileIOTest, "JlibFileIOTest" ); #endif // _USE_CPPUNIT
25.60251
102
0.511195
emuharemagic
35e4ba0dc1860954c0571cfef994903bc6be2a69
6,832
cpp
C++
iotvideo/src/v20201215/model/DataForward.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
iotvideo/src/v20201215/model/DataForward.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
iotvideo/src/v20201215/model/DataForward.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/iotvideo/v20201215/model/DataForward.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Iotvideo::V20201215::Model; using namespace std; DataForward::DataForward() : m_productIdHasBeenSet(false), m_forwardAddrHasBeenSet(false), m_statusHasBeenSet(false), m_createTimeHasBeenSet(false), m_updateTimeHasBeenSet(false), m_dataChoseHasBeenSet(false) { } CoreInternalOutcome DataForward::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("ProductId") && !value["ProductId"].IsNull()) { if (!value["ProductId"].IsString()) { return CoreInternalOutcome(Core::Error("response `DataForward.ProductId` IsString=false incorrectly").SetRequestId(requestId)); } m_productId = string(value["ProductId"].GetString()); m_productIdHasBeenSet = true; } if (value.HasMember("ForwardAddr") && !value["ForwardAddr"].IsNull()) { if (!value["ForwardAddr"].IsString()) { return CoreInternalOutcome(Core::Error("response `DataForward.ForwardAddr` IsString=false incorrectly").SetRequestId(requestId)); } m_forwardAddr = string(value["ForwardAddr"].GetString()); m_forwardAddrHasBeenSet = true; } if (value.HasMember("Status") && !value["Status"].IsNull()) { if (!value["Status"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `DataForward.Status` IsInt64=false incorrectly").SetRequestId(requestId)); } m_status = value["Status"].GetInt64(); m_statusHasBeenSet = true; } if (value.HasMember("CreateTime") && !value["CreateTime"].IsNull()) { if (!value["CreateTime"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `DataForward.CreateTime` IsInt64=false incorrectly").SetRequestId(requestId)); } m_createTime = value["CreateTime"].GetInt64(); m_createTimeHasBeenSet = true; } if (value.HasMember("UpdateTime") && !value["UpdateTime"].IsNull()) { if (!value["UpdateTime"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `DataForward.UpdateTime` IsInt64=false incorrectly").SetRequestId(requestId)); } m_updateTime = value["UpdateTime"].GetInt64(); m_updateTimeHasBeenSet = true; } if (value.HasMember("DataChose") && !value["DataChose"].IsNull()) { if (!value["DataChose"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `DataForward.DataChose` IsInt64=false incorrectly").SetRequestId(requestId)); } m_dataChose = value["DataChose"].GetInt64(); m_dataChoseHasBeenSet = true; } return CoreInternalOutcome(true); } void DataForward::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_productIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ProductId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_productId.c_str(), allocator).Move(), allocator); } if (m_forwardAddrHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ForwardAddr"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_forwardAddr.c_str(), allocator).Move(), allocator); } if (m_statusHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Status"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_status, allocator); } if (m_createTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CreateTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_createTime, allocator); } if (m_updateTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "UpdateTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_updateTime, allocator); } if (m_dataChoseHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DataChose"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_dataChose, allocator); } } string DataForward::GetProductId() const { return m_productId; } void DataForward::SetProductId(const string& _productId) { m_productId = _productId; m_productIdHasBeenSet = true; } bool DataForward::ProductIdHasBeenSet() const { return m_productIdHasBeenSet; } string DataForward::GetForwardAddr() const { return m_forwardAddr; } void DataForward::SetForwardAddr(const string& _forwardAddr) { m_forwardAddr = _forwardAddr; m_forwardAddrHasBeenSet = true; } bool DataForward::ForwardAddrHasBeenSet() const { return m_forwardAddrHasBeenSet; } int64_t DataForward::GetStatus() const { return m_status; } void DataForward::SetStatus(const int64_t& _status) { m_status = _status; m_statusHasBeenSet = true; } bool DataForward::StatusHasBeenSet() const { return m_statusHasBeenSet; } int64_t DataForward::GetCreateTime() const { return m_createTime; } void DataForward::SetCreateTime(const int64_t& _createTime) { m_createTime = _createTime; m_createTimeHasBeenSet = true; } bool DataForward::CreateTimeHasBeenSet() const { return m_createTimeHasBeenSet; } int64_t DataForward::GetUpdateTime() const { return m_updateTime; } void DataForward::SetUpdateTime(const int64_t& _updateTime) { m_updateTime = _updateTime; m_updateTimeHasBeenSet = true; } bool DataForward::UpdateTimeHasBeenSet() const { return m_updateTimeHasBeenSet; } int64_t DataForward::GetDataChose() const { return m_dataChose; } void DataForward::SetDataChose(const int64_t& _dataChose) { m_dataChose = _dataChose; m_dataChoseHasBeenSet = true; } bool DataForward::DataChoseHasBeenSet() const { return m_dataChoseHasBeenSet; }
27.111111
141
0.682084
suluner
35e572c0b33c1cd8a1798256e47699556dd581db
1,397
cc
C++
src/map/Map.cc
kallentu/pathos
1914edbccc98baef79d98fb065119230072ac40d
[ "MIT" ]
7
2019-05-09T15:38:55.000Z
2021-12-07T03:13:29.000Z
src/map/Map.cc
kallentu/pathos
1914edbccc98baef79d98fb065119230072ac40d
[ "MIT" ]
1
2019-06-20T03:01:18.000Z
2019-06-20T03:01:18.000Z
src/map/Map.cc
kallentu/pathos
1914edbccc98baef79d98fb065119230072ac40d
[ "MIT" ]
null
null
null
#include "map/Map.h" #include "map/Ground.h" #include "map/MapObject.h" #include "map/Wall.h" #include "view/curses/MapView.h" #include <memory> #include <vector> using namespace Pathos; Map::Map(size_t y, size_t x) { // Walls added for the corners of the map // Initial fill with default MapObjects (ground) for (size_t i = 0; i <= y; i++) { std::vector<std::unique_ptr<MapObject>> row; for (size_t j = 0; j <= x; j++) { // Top or bottom row // Start or end of row if (i == 0 || i == y || j == 0 || j == x) { row.push_back(std::make_unique<Wall>()); } else { row.push_back(std::make_unique<Ground>()); } } map.push_back(std::move(row)); } } MapObject *Map::get(size_t y, size_t x) { MapObject *obj; if (y < map.size() && x < map[0].size()) { obj = map[y][x].get(); } return obj; } size_t Map::getHeight() const { if (!map.empty()) { return map.size(); } else { return 0; } } size_t Map::getWidth() const { if (!map.empty() || !map[0].empty()) { return map[0].size(); } else { return 0; } } void Map::addObjectToPosition(std::unique_ptr<MapObject> m, size_t y, size_t x) { map[y][x].reset(); map[y][x] = std::move(m); } void Map::removeObjectFromPosition(size_t y, size_t x) { map[y][x].reset(); map[y][x] = std::make_unique<Ground>(); }
20.850746
69
0.561203
kallentu
e3081c492fce81bfb255d751ffb60b93eaae1f65
2,219
inl
C++
c++/Ail/URL.inl
aamshukov/miscellaneous
6fc0d2cb98daff70d14f87b2dfc4e58e61d2df60
[ "MIT" ]
null
null
null
c++/Ail/URL.inl
aamshukov/miscellaneous
6fc0d2cb98daff70d14f87b2dfc4e58e61d2df60
[ "MIT" ]
null
null
null
c++/Ail/URL.inl
aamshukov/miscellaneous
6fc0d2cb98daff70d14f87b2dfc4e58e61d2df60
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////// //...................................................................................... // This is a part of AI Library [Arthur's Interfaces Library]. . // 1998-2001 Arthur Amshukov . //...................................................................................... // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND . // DO NOT REMOVE MY NAME AND THIS NOTICE FROM THE SOURCE . //...................................................................................... //////////////////////////////////////////////////////////////////////////////////////// #ifndef __URL_INL__ #define __URL_INL__ #pragma once __BEGIN_NAMESPACE__ //////////////////////////////////////////////////////////////////////////////////////// // class URL // ----- --- __INLINE__ bool URL::operator == (const URL& _other) const { return StrCompareWithEsc(URL_, _other.URL_) == 0; } __INLINE__ bool URL::operator == (const tchar* _url) const { return StrCompareWithEsc(URL_, _url) == 0; } __INLINE__ bool URL::operator != (const URL& _other) const { return !operator == (_other); } __INLINE__ bool URL::operator != (const tchar* _url) const { return !operator == (_url); } __INLINE__ URL::operator tchar* () { return URL_; } __INLINE__ URL::operator const tchar* () const { return static_cast<const tchar*>(URL_); } __INLINE__ bool URL::IsURL() const { // actually should return true if only we have <URL:><...>, but ... return true; } __INLINE__ String<> URL::GetURL() const { return URL_; } __INLINE__ void URL::SetURL(const tchar* _url) { URL_ = _url; // Correct(); } __INLINE__ String<> URL::GetHost() const { return String<>(); } __INLINE__ ushort URL::GetPort() const { return 0; } __INLINE__ ulong URL::Hash() const { return ElfHashBytes(reinterpret_cast<byte*>(const_cast<tchar*>(URL_.GetData()))); } //////////////////////////////////////////////////////////////////////////////////////// __END_NAMESPACE__ #endif // __URL_INL__
26.105882
88
0.452907
aamshukov
e309ef09be7edd6cca89caa5a3af15f9f25771fa
12,986
cpp
C++
src/cbs/components/RubiksCube/RubiksCube.cpp
Nerovski/RubiksCube
a8ac27e50544a44a1790d0a6f1af07be05768454
[ "MIT" ]
6
2020-06-27T10:29:40.000Z
2021-04-13T14:19:23.000Z
src/cbs/components/RubiksCube/RubiksCube.cpp
Nerovski/RubiksCube
a8ac27e50544a44a1790d0a6f1af07be05768454
[ "MIT" ]
null
null
null
src/cbs/components/RubiksCube/RubiksCube.cpp
Nerovski/RubiksCube
a8ac27e50544a44a1790d0a6f1af07be05768454
[ "MIT" ]
3
2021-05-30T05:32:24.000Z
2022-01-18T01:53:24.000Z
#include "RubiksCube.h" #include "Tasks.h" RubiksCube::RubiksCube() : m_Front { { { 0, 0, 0 }, { 0, 0, 1 }, { 0, 0, 2 }, { 0, 1, 2 }, { 0, 2, 2 }, { 0, 2, 1 }, { 0, 2, 0 }, { 0, 1, 0 } }, { 0, 1, 1 }, { glm::vec3(1.0f, 0.0f, 0.0f) }, { 'F' } } , m_Back { { { 2, 0, 2 }, { 2, 0, 1 }, { 2, 0, 0 }, { 2, 1, 0 }, { 2, 2, 0 }, { 2, 2, 1 }, { 2, 2, 2 }, { 2, 1, 2 } }, { 2, 1, 1 }, { glm::vec3(-1.0f, 0.0f, 0.0f) }, { 'B' } } , m_Left { { {2, 0, 0}, {1, 0, 0}, {0, 0, 0}, {0, 1, 0}, {0, 2, 0}, {1, 2, 0}, {2, 2, 0}, {2, 1, 0} }, { 1, 1, 0 }, { glm::vec3(0.0f, 0.0f, 1.0f) }, { 'L' } } , m_Right { { {0, 0, 2}, {1, 0, 2}, {2, 0, 2}, {2, 1, 2}, {2, 2, 2}, {1, 2, 2}, {0, 2, 2}, {0, 1, 2} }, { 1, 1, 2 }, { glm::vec3(0.0f, 0.0f, -1.0f) }, { 'R' } } , m_Up { { {2, 0, 0}, {2, 0, 1}, {2, 0, 2}, {1, 0, 2}, {0, 0, 2}, {0, 0, 1}, {0, 0, 0}, {1, 0, 0} }, { 1, 0, 1 }, { glm::vec3(0.0f, 1.0f, 0.0f) }, { 'U' } } , m_Down { { {1, 2, 2}, {2, 2, 2}, {2, 2, 1}, {2, 2, 0}, {1, 2, 0}, {0, 2, 0}, {0, 2, 1}, {0, 2, 2} }, { 1, 2, 1 }, { glm::vec3(0.0f, -1.0f, 0.0f) }, { 'D' } } { for (int matrix = 0; matrix < 3; matrix++) { m_Cube.emplace_back(); for (int row = 0; row < 3; row++) { m_Cube[matrix].emplace_back(); m_Cube[matrix][row].reserve(3); } } } void RubiksCube::MakeConnectors(MessageManager& message_manager) { message_manager.Make(this, TasksSignaturesOut); } void RubiksCube::Initialize() { const glm::mat4* root_model = &Object().Root().ModelOut.Value(); // Front face // First row m_Cube[0][0].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 1.0f, 1.0f), Cubie::EColor::BLUE, Cubie::EColor::RED, Cubie::EColor::BLACK, Cubie::EColor::WHITE)); m_Cube[0][0].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 1.0f, 0.0f), Cubie::EColor::BLUE, Cubie::EColor::BLACK, Cubie::EColor::BLACK, Cubie::EColor::WHITE)); m_Cube[0][0].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 1.0f, -1.0f), Cubie::EColor::BLUE, Cubie::EColor::BLACK, Cubie::EColor::ORANGE, Cubie::EColor::WHITE)); // Second row m_Cube[0][1].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 0.0f, 1.0f), Cubie::EColor::BLUE, Cubie::EColor::RED)); m_Cube[0][1].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 0.0f, 0.0f), Cubie::EColor::BLUE)); m_Cube[0][1].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 0.0f, -1.0f), Cubie::EColor::BLUE, Cubie::EColor::BLACK, Cubie::EColor::ORANGE)); // Third row m_Cube[0][2].emplace_back(new Cubie(root_model, glm::vec3(1.0f, -1.0f, 1.0f), Cubie::EColor::BLUE, Cubie::EColor::RED, Cubie::EColor::BLACK, Cubie::EColor::BLACK, Cubie::EColor::YELLOW)); m_Cube[0][2].emplace_back(new Cubie(root_model, glm::vec3(1.0f, -1.0f, 0.0f), Cubie::EColor::BLUE, Cubie::EColor::BLACK, Cubie::EColor::BLACK, Cubie::EColor::BLACK, Cubie::EColor::YELLOW)); m_Cube[0][2].emplace_back(new Cubie(root_model, glm::vec3(1.0f, -1.0f, -1.0f), Cubie::EColor::BLUE, Cubie::EColor::BLACK, Cubie::EColor::ORANGE, Cubie::EColor::BLACK, Cubie::EColor::YELLOW)); // Back face // First row m_Cube[2][0].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 1.0f, -1.0f), Cubie::EColor::GREEN, Cubie::EColor::BLACK, Cubie::EColor::RED, Cubie::EColor::WHITE)); m_Cube[2][0].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 1.0f, 0.0f), Cubie::EColor::GREEN, Cubie::EColor::BLACK, Cubie::EColor::BLACK, Cubie::EColor::WHITE)); m_Cube[2][0].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 1.0f, 1.0f), Cubie::EColor::GREEN, Cubie::EColor::ORANGE, Cubie::EColor::BLACK, Cubie::EColor::WHITE)); // Second row m_Cube[2][1].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 0.0f, -1.0f), Cubie::EColor::GREEN, Cubie::EColor::BLACK, Cubie::EColor::RED)); m_Cube[2][1].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 0.0f, 0.0f), Cubie::EColor::GREEN)); m_Cube[2][1].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 0.0f, 1.0f), Cubie::EColor::GREEN, Cubie::EColor::ORANGE)); // Third row m_Cube[2][2].emplace_back(new Cubie(root_model, glm::vec3(1.0f, -1.0f, -1.0f), Cubie::EColor::GREEN, Cubie::EColor::BLACK, Cubie::EColor::RED, Cubie::EColor::BLACK, Cubie::EColor::YELLOW)); m_Cube[2][2].emplace_back(new Cubie(root_model, glm::vec3(1.0f, -1.0f, 0.0f), Cubie::EColor::GREEN, Cubie::EColor::BLACK, Cubie::EColor::BLACK, Cubie::EColor::BLACK, Cubie::EColor::YELLOW)); m_Cube[2][2].emplace_back(new Cubie(root_model, glm::vec3(1.0f, -1.0f, 1.0f), Cubie::EColor::GREEN, Cubie::EColor::ORANGE, Cubie::EColor::BLACK, Cubie::EColor::BLACK, Cubie::EColor::YELLOW)); for (auto row = m_Cube[2].begin(); row != m_Cube[2].end(); row++) { for (auto cubie = row->begin(); cubie != row->end(); cubie++) { (*cubie)->RotateAround(180.0f, glm::vec3(0.0f, 1.0f, 0.0f)); } } // Middle face // First row m_Cube[1][0].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 0.0f, 1.0f), Cubie::EColor::WHITE, Cubie::EColor::RED))->RotateAround(90.0f, glm::vec3(0.0f, 0.0f, 1.0f));; m_Cube[1][0].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 0.0f, 0.0f), Cubie::EColor::WHITE))->RotateAround(90.0f, glm::vec3(0.0f, 0.0f, 1.0f));; m_Cube[1][0].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 0.0f, -1.0f), Cubie::EColor::WHITE, Cubie::EColor::BLACK, Cubie::EColor::ORANGE))->RotateAround(90.0f, glm::vec3(0.0f, 0.0f, 1.0f));; // Second row m_Cube[1][1].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 0.0f, 0.0f), Cubie::EColor::RED))->RotateAround(-90.0f, glm::vec3(0.0f, 1.0f, 0.0f)); m_Cube[1][1].emplace_back(new Cubie(root_model, glm::vec3(0.0f, 0.0f, 0.0f), Cubie::EColor::BLACK)); // Hidden cubie in the center m_Cube[1][1].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 0.0f, 0.0f), Cubie::EColor::ORANGE))->RotateAround(90.0f, glm::vec3(0.0f, 1.0f, 0.0f)); // Third row m_Cube[1][2].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 0.0f, 1.0f), Cubie::EColor::YELLOW, Cubie::EColor::RED))->RotateAround(-90.0f, glm::vec3(0.0f, 0.0f, 1.0f)); m_Cube[1][2].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 0.0f, 0.0f), Cubie::EColor::YELLOW))->RotateAround(-90.0f, glm::vec3(0.0f, 0.0f, 1.0f)); m_Cube[1][2].emplace_back(new Cubie(root_model, glm::vec3(1.0f, 0.0f, -1.0f), Cubie::EColor::YELLOW, Cubie::EColor::BLACK, Cubie::EColor::ORANGE))->RotateAround(-90.0f, glm::vec3(0.0f, 0.0f, 1.0f)); // Register draw calls for all cubies for (auto matrix = m_Cube.begin(); matrix != m_Cube.end(); matrix++) { for (auto row = matrix->begin(); row != matrix->end(); row++) { for (auto cube = row->begin(); cube != row->end(); cube++) { Object().Scene().RegisterDrawCall(*cube); } } } RegisterUpdateCall(); } void RubiksCube::Update() { // Collect next task if (g_Input.KeyHold(GLFW_KEY_LEFT_SHIFT) && g_Input.KeyPressed(GLFW_KEY_F)) { RotateFace(EFace::FRONT, ERotation::COUNTER_CLOCKWISE); } else if (g_Input.KeyPressed(GLFW_KEY_F)) { RotateFace(EFace::FRONT, ERotation::CLOCKWISE); } else if (g_Input.KeyHold(GLFW_KEY_LEFT_SHIFT) && g_Input.KeyPressed(GLFW_KEY_B)) { RotateFace(EFace::BACK, ERotation::COUNTER_CLOCKWISE); } else if (g_Input.KeyPressed(GLFW_KEY_B)) { RotateFace(EFace::BACK, ERotation::CLOCKWISE); } else if (g_Input.KeyHold(GLFW_KEY_LEFT_SHIFT) && g_Input.KeyPressed(GLFW_KEY_L)) { RotateFace(EFace::LEFT, ERotation::COUNTER_CLOCKWISE); } else if (g_Input.KeyPressed(GLFW_KEY_L)) { RotateFace(EFace::LEFT, ERotation::CLOCKWISE); } else if (g_Input.KeyHold(GLFW_KEY_LEFT_SHIFT) && g_Input.KeyPressed(GLFW_KEY_R)) { RotateFace(EFace::RIGHT, ERotation::COUNTER_CLOCKWISE); } else if (g_Input.KeyPressed(GLFW_KEY_R)) { RotateFace(EFace::RIGHT, ERotation::CLOCKWISE); } else if (g_Input.KeyHold(GLFW_KEY_LEFT_SHIFT) && g_Input.KeyPressed(GLFW_KEY_U)) { RotateFace(EFace::UP, ERotation::COUNTER_CLOCKWISE); } else if (g_Input.KeyPressed(GLFW_KEY_U)) { RotateFace(EFace::UP, ERotation::CLOCKWISE); } else if (g_Input.KeyHold(GLFW_KEY_LEFT_SHIFT) && g_Input.KeyPressed(GLFW_KEY_D)) { RotateFace(EFace::DOWN, ERotation::COUNTER_CLOCKWISE); } else if (g_Input.KeyPressed(GLFW_KEY_D)) { RotateFace(EFace::DOWN, ERotation::CLOCKWISE); } else if (g_Input.KeyHold(GLFW_KEY_LEFT_SHIFT) && g_Input.KeyPressed(GLFW_KEY_X)) { RotateCube(EDirection::RIGHT, ERotation::COUNTER_CLOCKWISE); } else if (g_Input.KeyPressed(GLFW_KEY_X)) { RotateCube(EDirection::RIGHT, ERotation::CLOCKWISE); } else if (g_Input.KeyHold(GLFW_KEY_LEFT_SHIFT) && g_Input.KeyPressed(GLFW_KEY_Y)) { RotateCube(EDirection::UP, ERotation::COUNTER_CLOCKWISE); } else if (g_Input.KeyPressed(GLFW_KEY_Y)) { RotateCube(EDirection::UP, ERotation::CLOCKWISE); } else if (g_Input.KeyHold(GLFW_KEY_LEFT_SHIFT) && g_Input.KeyPressed(GLFW_KEY_Z)) { RotateCube(EDirection::FRONT, ERotation::COUNTER_CLOCKWISE); } else if (g_Input.KeyPressed(GLFW_KEY_Z)) { RotateCube(EDirection::FRONT, ERotation::CLOCKWISE); } // Update deque of tasks if (!m_Tasks.empty()) { if (!m_Tasks.front()->Finished()) { m_Tasks.front()->Progress(g_Time.FixedDeltaTime()); } else { m_Tasks.pop_front(); UpdateTextRenderer(); } } } void RubiksCube::Destroy() { for (auto matrix = m_Cube.begin(); matrix != m_Cube.end(); matrix++) { for (auto row = matrix->begin(); row != matrix->end(); row++) { for (auto cube = row->begin(); cube != row->end(); cube++) { Object().Scene().UnregisterDrawCall(*cube); delete *cube; } } } } void RubiksCube::RotateFace(EFace face, ERotation rotation) { Face& face_to_rotate = [&]() -> Face& { switch (face) { case EFace::FRONT: return m_Front; case EFace::BACK: return m_Back; case EFace::UP: return m_Up; case EFace::DOWN: return m_Down; case EFace::LEFT: return m_Left; default: // case EFace::RIGHT return m_Right; }; }(); m_Tasks.emplace_back(std::make_unique<FaceRotation>(*this, face_to_rotate, rotation, 90.0f, FACE_ROTATION_SPEED)); UpdateTextRenderer(); } void RubiksCube::RotateCube(EDirection direction, ERotation rotation) { m_Tasks.emplace_back(std::make_unique<CubeRotation>(*this, &Object().Root(), direction, rotation, CUBE_ROTATION_SPEED)); UpdateTextRenderer(); } void RubiksCube::Randomize(unsigned int moves) { if (m_Tasks.size() > 0) { // Finish current task m_Tasks.front()->Progress(1.0f); m_Tasks.clear(); } std::default_random_engine generator; std::uniform_int_distribution<int> distribution(0, 5); for (unsigned int i = 0; i < moves; i++) { // 50% chances for clockwise and 50% chances for counter-clockwise rotation auto rn = distribution(generator); ERotation rotation = rn % 2 == 0 ? ERotation::CLOCKWISE : ERotation::COUNTER_CLOCKWISE; // Each face has equal chance to be choosen rn = distribution(generator); switch (rn) { case 0: RotateFace(EFace::FRONT, rotation); break; case 1: RotateFace(EFace::BACK, rotation); break; case 2: RotateFace(EFace::UP, rotation); break; case 3: RotateFace(EFace::DOWN, rotation); break; case 4: RotateFace(EFace::LEFT, rotation); break; case 5: RotateFace(EFace::RIGHT, rotation); break; } } } void RubiksCube::UpdateTextRenderer() { std::string message; message.reserve(m_Tasks.size() * 2); for (auto it = m_Tasks.begin(); it != m_Tasks.end(); it++) { message += ' ' + (*it)->Signature(); } TasksSignaturesOut.Send(message); }
40.9653
202
0.56815
Nerovski
e30dc3f86621a61a237131a5324ebc1f40b3caaf
418
cpp
C++
Chromatics.cpp
DoooReyn/chromatic4cpp
31a7e31cd331728ad65280d5d57556c3bd0a8605
[ "MIT" ]
1
2017-02-18T20:50:41.000Z
2017-02-18T20:50:41.000Z
Chromatics.cpp
DoooReyn/chromatic4cpp
31a7e31cd331728ad65280d5d57556c3bd0a8605
[ "MIT" ]
4
2017-02-18T11:51:01.000Z
2017-02-19T17:19:19.000Z
Chromatics.cpp
DoooReyn/chromatic4cpp
31a7e31cd331728ad65280d5d57556c3bd0a8605
[ "MIT" ]
null
null
null
// // Chromatics.cpp // Playground // // Created by Reyn-Mac on 2017/2/18. // Copyright © 2017年 Reyn-Mac. All rights reserved. // #include "Chromatics.hpp" unsigned char Chromatic::getColorVecFromHex(string hex) { if(hex.size() == 0) return 0; int nhigh = StringUtils::hex01(hex.at(0)) * 16; if(hex.size() == 1) return nhigh; int nlow = StringUtils::hex01(hex.at(1)); return nhigh + nlow; }
22
55
0.641148
DoooReyn
e312392584cad7896cf39cc8afdc4a33e8352531
96
cpp
C++
Vulkan/src/Vulkan/Core/Time.cpp
ilkeraktug/Vulkan
b736ba2e01dc8fdfd1aaf3dec334882f7467263f
[ "MIT" ]
null
null
null
Vulkan/src/Vulkan/Core/Time.cpp
ilkeraktug/Vulkan
b736ba2e01dc8fdfd1aaf3dec334882f7467263f
[ "MIT" ]
null
null
null
Vulkan/src/Vulkan/Core/Time.cpp
ilkeraktug/Vulkan
b736ba2e01dc8fdfd1aaf3dec334882f7467263f
[ "MIT" ]
null
null
null
#include "pch.h" #include "Time.h" float Time::deltaTime = 0.0f; float Time::m_LastTime = 0.0f;
19.2
30
0.6875
ilkeraktug
e31242d2de6d33f5a5bc57748211451ea5e4f456
194
cpp
C++
src/lexer/utils.cpp
YavaCoco/Hydrogen
ce7baf19e1fa1d705de99e86b4f116c30d737aa2
[ "MIT" ]
1
2022-01-22T00:57:49.000Z
2022-01-22T00:57:49.000Z
src/lexer/utils.cpp
YavaCoco/Hydrogen
ce7baf19e1fa1d705de99e86b4f116c30d737aa2
[ "MIT" ]
null
null
null
src/lexer/utils.cpp
YavaCoco/Hydrogen
ce7baf19e1fa1d705de99e86b4f116c30d737aa2
[ "MIT" ]
null
null
null
#include <lexer.hpp> namespace hyc::lex { // open parentheses/braces/brackets int lexer::open_pbck() { return m_openps.size() + m_openbks.size() + m_openbcs.size(); } }
17.636364
69
0.618557
YavaCoco
e312e63baa70dbe0945e9462625a4cec5708ffcb
7,968
cpp
C++
src/UI/UiElement.cpp
Strife-AI/Strife.Engine
6b83e762f28acb3f4440d5b7763beccfd08dfc8f
[ "NCSA" ]
12
2020-12-27T22:13:58.000Z
2021-03-14T09:03:02.000Z
src/UI/UiElement.cpp
Strife-AI/Strife.Engine
6b83e762f28acb3f4440d5b7763beccfd08dfc8f
[ "NCSA" ]
10
2021-01-14T15:14:31.000Z
2021-05-24T22:01:09.000Z
src/UI/UiElement.cpp
Strife-AI/Strife.Engine
6b83e762f28acb3f4440d5b7763beccfd08dfc8f
[ "NCSA" ]
null
null
null
#include "UiElement.hpp" #include "Camera.hpp" #include "UI.hpp" void UiElement::RemoveChild(UiElementPtr child) { auto position = std::find(_children.begin(), _children.end(), child); if (position != _children.end()) { _children.erase(position); RequireReformat(); } } void UiElement::RemoveAllChildren() { if (!_children.empty()) { _children.clear(); RequireReformat(); } } void UiElement::SetRelativePosition(Vector2 offset) { if (offset != _positioning.relativeOffset.XY()) { _positioning.relativeOffset = _positioning.relativeOffset.SetXY(offset); RequireReformat(); } } std::shared_ptr<BackgroundStyle> BackgroundStyle::FromNineSlice(StringId resourceId) { auto style = std::make_shared<BackgroundStyle>(); //style->BackgroundNineSlice(ResourceManager::GetResource<NineSlice>(resourceId)); return style; } std::shared_ptr<BackgroundStyle> BackgroundStyle::FromSprite(StringId resourceId) { auto style = std::make_shared<BackgroundStyle>(); //style->BackgroundSprite(ResourceManager::GetResource<Sprite>(resourceId)); return style; } UiElementPtr UiElement::AddExistingChild(UiElementPtr element) { _children.push_back(element); element->_parent = this; RequireReformat(); return element; } void UiElement::LinkCircular(const std::initializer_list<UiElementPtr>& elements) { auto data = elements.begin(); for(int i = 0; i < elements.size(); ++i) { data[i]->prev = i != 0 ? data[i - 1] : data[elements.size() - 1]; data[i]->next = data[(i + 1) % elements.size()]; } } // TODO: This method is essentially duplicated. I need a way to convert a const vector to an initializer list void UiElement::LinkCircular(const std::vector<UiElementPtr>& elements) { auto data = elements.begin(); for (int i = 0; i < elements.size(); ++i) { data[i]->prev = i != 0 ? data[i-1] : data[elements.size() -1]; data[i]->next = data[(i + 1) % elements.size()]; } } void UiElement::RequireReformat() { MarkFormattingDirty(); MarkAbsolutePositionDirty(); } void UiElement::DoUpdate(Input* input, float deltaTime) { } Vector2 UiElement::GetSize() { EnforceUpdatedLayout(); return _size; } bool UiElement::PointInsideElement(Vector2 point) { switch (_shape) { case UiElementShape::Rectangle: return GetAbsoluteBounds().ContainsPoint(point); case UiElementShape::Circle: { auto bounds = GetAbsoluteBounds(); auto size = bounds.Size(); auto maxAxis = Max(size.x, size.y) / 2; return (point - bounds.GetCenter()).LengthSquared() < maxAxis * maxAxis; } default: return false; } } Rectangle UiElement::GetRelativeBounds() { return Rectangle( _positioning.relativeOffset.XY(), GetSize()); } Rectangle UiElement::GetAbsoluteBounds() { return Rectangle( GetAbsolutePosition().XY(), GetSize()); } void UiElement::SetIsEnabled(bool isEnabled) { _isEnabled = isEnabled; RequireReformat(); } void UiElement::Update(Input* input, float deltaTime) { DoUpdate(input, deltaTime); for (auto& child : _children) { child->Update(input, deltaTime); } } void UiElement::Render(Renderer* renderer) { EnforceUpdatedLayout(); #if false if (_backgroundStyle != nullptr) { auto bounds = GetAbsoluteBounds(); switch (_backgroundStyle->type) { case BackgroundType::Colored: renderer->RenderRectangle( bounds, _backgroundStyle->color, _absolutePosition.z); break; case BackgroundType::NineSlice: renderer->RenderNineSlice( _backgroundStyle->nineSlice.Value(), bounds, _absolutePosition.z); break; case BackgroundType::Sprite: renderer->RenderSprite( _backgroundStyle->sprite.Value(), bounds.TopLeft(), _absolutePosition.z, bounds.Size() / _backgroundStyle->sprite->Bounds().Size()); break; default: break; } } #endif //renderer->RenderRectangleOutline(GetAbsoluteBounds(), Color::Red(), 0); DoRendering(renderer); for (auto& child : _children) { child->Render(renderer); } } UiElementPtr UiElement::FindHoveredElement(Vector2 mousePosition, UiElementPtr self) { for(auto child : self->_children) { auto result = FindHoveredElement(mousePosition, child); if(result != nullptr) { return result; } } if(self->isHoverable && self->PointInsideElement(mousePosition)) { return self; } else { return nullptr; } } UiElement* UiElement::SetBackgroundStyle(std::shared_ptr<BackgroundStyle> style) { _backgroundStyle = style; return this; } UiElement* UiElement::SetAlign(int alignFlags) { _positioning.alignFlags = alignFlags; RequireReformat(); return this; } void UiElement::SetShape(UiElementShape shape) { _shape = shape; RequireReformat(); } void UiElement::SetRelativeDepth(float depth) { _positioning.relativeOffset.z = depth; MarkAbsolutePositionDirty(); } UiElement* UiElement::GetRootElement() { auto element = this; while (element->_parent != nullptr) { element = element->_parent; } return element; } Vector3 UiElement::GetAbsolutePosition() { if (_absolutePositionDirty) { if (_parent != nullptr) { _parent->EnforceUpdatedLayout(); auto newPosition = (_parent->GetAbsolutePosition() + _positioning.relativeOffset); _absolutePosition = newPosition.SetXY(newPosition.XY().Floor().AsVectorOfType<float>()); ; } _absolutePositionDirty = false; } return _absolutePosition; } void UiElement::SetFixedSize(Vector2 size) { _size = size; _sizing = ElementSizing::Fixed; RequireReformat(); } void UiElement::UpdateSize() { if (_sizing == ElementSizing::Fixed) { return; } Rectangle bounds(Vector2::Zero(), Vector2::Zero()); for (auto& child : _children) { auto childBounds = Rectangle( Vector2::Zero(), child->GetSize()); if (!child->_positioning.HasXAlignment()) { childBounds = childBounds.AddPosition( Vector2(child->_positioning.relativeOffset.x, 0)); } if (!child->_positioning.HasYAlignment()) { childBounds = childBounds.AddPosition( Vector2(0, child->_positioning.relativeOffset.y)); } bounds = bounds.Union(childBounds); } _size = bounds.Size(); } void UiElement::DoFormatting() { for (auto child : _children) { int flags = child->_positioning.alignFlags; auto elementBounds = child->GetRelativeBounds(); auto position = elementBounds.TopLeft(); if (flags & AlignLeft) position.x = 0; else if (flags & AlignRight) position.x = _size.x - elementBounds.Width(); else if (flags & AlignCenterX) position.x = _size.x / 2 - elementBounds.Width() / 2; if (flags & AlignTop) position.y = 0; else if (flags & AlignBottom) position.y = _size.y - elementBounds.Height(); else if (flags & AlignCenterY) position.y = _size.y / 2 - elementBounds.Height() / 2; child->SetRelativeOffsetInternal(position); } } void UiElement::SetRelativeOffsetInternal(Vector2 offset) { if (offset != _positioning.relativeOffset.XY()) { _positioning.relativeOffset = _positioning.relativeOffset.SetXY(offset); MarkAbsolutePositionDirty(); } }
22.636364
109
0.619478
Strife-AI
e317b8d606c9e2559b622971d2eb880dd333c651
1,396
cc
C++
python_bindings.cc
JackMaguire/RobotsAsAGraph
23208be8cfc34cd1f4db9f3cb7b680286e690f07
[ "MIT" ]
null
null
null
python_bindings.cc
JackMaguire/RobotsAsAGraph
23208be8cfc34cd1f4db9f3cb7b680286e690f07
[ "MIT" ]
null
null
null
python_bindings.cc
JackMaguire/RobotsAsAGraph
23208be8cfc34cd1f4db9f3cb7b680286e690f07
[ "MIT" ]
null
null
null
//g++ python_bindings.cc -o robots_core$(python3-config --extension-suffix) -O3 -Wall -Wextra -Iinclude -Iextern/RobotsCore/extern/pybind11/include -std=c++17 -fPIC $(python3 -m pybind11 --includes) -shared -Iextern/RobotsCore/include/ #include "deserialize.hh" #define RC_EXPAND_PYMODULE #include "core_python_bindings.hh" //PYBIND11_MODULE(robots_train, m) { //m.doc() = "GNN Training of the Robots game"; py::module m_train = m.def_submodule( "train" ); m_train.def( "make_tensors", &make_tensors ); m_train.def( "deserialize", &deserialize ); m_train.def( "Key2SC", &Key2SC ); py::class_< Tensors > tensors( m_train, "Tensors" ); tensors.def_readonly( "input_tensors", &Tensors::input_tensors ); tensors.def_readonly( "output_tensor", &Tensors::output_tensor ); py::enum_< Key >( m_train, "Key" ) .value( "Q", Key::Q ) .value( "W", Key::W ) .value( "E", Key::E ) .value( "A", Key::A ) .value( "S", Key::S ) .value( "D", Key::D ) .value( "Z", Key::Z ) .value( "X", Key::X ) .value( "C", Key::C ) .value( "T", Key::T ) .value( "SPACE", Key::SPACE ) .value( "DELETE", Key::DELETE ) .value( "NONE", Key::NONE ); py::class_< DataPoint > dp( m_train, "DataPoint" ); dp.def_readonly( "game", &DataPoint::game ); dp.def_readonly( "key", &DataPoint::key ); dp.def_readonly( "level", &DataPoint::level ); }
30.347826
235
0.626791
JackMaguire
e31f7bc7a885b2f1066f920a505d15af345f84e3
4,233
cpp
C++
src/Services/NotificationService/NotificationService.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
39
2016-04-21T03:25:26.000Z
2022-01-19T14:16:38.000Z
src/Services/NotificationService/NotificationService.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
23
2016-06-28T13:03:17.000Z
2022-02-02T10:11:54.000Z
src/Services/NotificationService/NotificationService.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
14
2016-06-22T20:45:37.000Z
2021-07-05T12:25:19.000Z
#include "NotificationService.h" #include "Interface/ThreadServiceInterface.h" #include "Interface/LoggerServiceInterface.h" #include "Kernel/Assertion.h" #include "Kernel/AssertionMemoryPanic.h" #include "Kernel/Logger.h" #include "Kernel/DocumentHelper.h" #include "Kernel/MixinDebug.h" #include "Config/Algorithm.h" ////////////////////////////////////////////////////////////////////////// SERVICE_FACTORY( NotificationService, Mengine::NotificationService ); ////////////////////////////////////////////////////////////////////////// namespace Mengine { ////////////////////////////////////////////////////////////////////////// NotificationService::NotificationService() { } ////////////////////////////////////////////////////////////////////////// NotificationService::~NotificationService() { } ////////////////////////////////////////////////////////////////////////// bool NotificationService::_initializeService() { for( uint32_t index = 0; index != MENGINE_NOTIFICATOR_MAX_COUNT; ++index ) { NotificationArea & area = m_areas[index]; if( area.initialize( index ) == false ) { return false; } } SERVICE_WAIT( ThreadServiceInterface, [this]() { for( uint32_t index = 0; index != MENGINE_NOTIFICATOR_MAX_COUNT; ++index ) { NotificationArea & area = m_areas[index]; ThreadMutexInterfacePtr mutex = THREAD_SERVICE() ->createMutex( MENGINE_DOCUMENT_FACTORABLE ); MENGINE_ASSERTION_MEMORY_PANIC( mutex ); area.setMutex( mutex ); } return true; } ); SERVICE_LEAVE( ThreadServiceInterface, [this]() { for( uint32_t index = 0; index != MENGINE_NOTIFICATOR_MAX_COUNT; ++index ) { NotificationArea & area = m_areas[index]; area.setMutex( nullptr ); } } ); return true; } ////////////////////////////////////////////////////////////////////////// void NotificationService::_finalizeService() { for( uint32_t index = 0; index != MENGINE_NOTIFICATOR_MAX_COUNT; ++index ) { NotificationArea & area = m_areas[index]; area.finalize(); } } ////////////////////////////////////////////////////////////////////////// void NotificationService::addObserver( uint32_t _id, Observable * _observer, const ObserverCallableInterfacePtr & _callable, const DocumentPtr & _doc ) { MENGINE_ASSERTION_FATAL( _id < MENGINE_NOTIFICATOR_MAX_COUNT ); NotificationArea & area = m_areas[_id]; area.addObserver( _observer, _callable, _doc ); } ////////////////////////////////////////////////////////////////////////// void NotificationService::removeObserver( uint32_t _id, Observable * _observer ) { MENGINE_ASSERTION_FATAL( _id < MENGINE_NOTIFICATOR_MAX_COUNT ); NotificationArea & area = m_areas[_id]; area.removeObserver( _observer ); } ////////////////////////////////////////////////////////////////////////// bool NotificationService::hasObserver( Observable * _observer ) const { for( uint32_t index = 0; index != MENGINE_NOTIFICATOR_MAX_COUNT; ++index ) { const NotificationArea & area = m_areas[index]; if( area.hasObserver( _observer ) == true ) { return true; } } return false; } ////////////////////////////////////////////////////////////////////////// bool NotificationService::visitObservers( uint32_t _id, const LambdaObserver & _lambda ) { MENGINE_ASSERTION_FATAL( _id < MENGINE_NOTIFICATOR_MAX_COUNT ); NotificationArea & area = m_areas[_id]; bool successful = area.visitObservers( _lambda ); return successful; } ////////////////////////////////////////////////////////////////////////// }
34.137097
156
0.46799
irov
e31ff11040827b2d4431ccbf0a5f97e7212bbc3a
1,397
cpp
C++
kattis/ceiling/ceiling.cpp
pi-guy-in-the-sky/competitive-programming
e079f6caf07b5de061ea4f56218f9b577e49a965
[ "MIT" ]
null
null
null
kattis/ceiling/ceiling.cpp
pi-guy-in-the-sky/competitive-programming
e079f6caf07b5de061ea4f56218f9b577e49a965
[ "MIT" ]
null
null
null
kattis/ceiling/ceiling.cpp
pi-guy-in-the-sky/competitive-programming
e079f6caf07b5de061ea4f56218f9b577e49a965
[ "MIT" ]
1
2020-10-25T05:46:57.000Z
2020-10-25T05:46:57.000Z
#include <iostream> #include <unordered_map> #include <string> using namespace std; struct node { int n; node* left = nullptr; node* right = nullptr; }; string traverse(node* root, int depth) { if (root == nullptr) return ""; string ans; ans += traverse(root->left, depth + 1); ans += char(depth); ans += traverse(root->right, depth + 1); return ans; } void insert(node* root, int n) { if (n > root->n) { if (root->right == nullptr) { node* temp = new node; temp->n = n; root->right = temp; } else { insert(root->right, n); } } else if (n < root->n) { if (root->left == nullptr) { node* temp = new node; temp->n = n; root->left = temp; } else { insert(root->left, n); } } } int main() { int trees, nodes, t; cin >> trees >> nodes; unordered_map<string, int> designs; for (int i = 0; i < trees; i++) { node* n = new node; n->n = -1; for (int j = 0; j < nodes; j++) { cin >> t; insert(n, t); } string s = traverse(n, 0); designs[s]++; } int total; for (auto i : designs) { total++; } cout << total << endl; }
17.683544
44
0.435934
pi-guy-in-the-sky
e321a4e23afd384010e8cff78aa651118c22eb09
17,656
cpp
C++
source/tool/toolSettings/effects/TSet_Effects.cpp
chromaScript/chroma.io
c484354df6f3c84a049ffadfe37c677c0ccb6390
[ "MIT" ]
null
null
null
source/tool/toolSettings/effects/TSet_Effects.cpp
chromaScript/chroma.io
c484354df6f3c84a049ffadfe37c677c0ccb6390
[ "MIT" ]
null
null
null
source/tool/toolSettings/effects/TSet_Effects.cpp
chromaScript/chroma.io
c484354df6f3c84a049ffadfe37c677c0ccb6390
[ "MIT" ]
null
null
null
#include "../../../include/tool/ToolSettings.h" #include "../../../include/input/keys.h" #include "../../../include/math/Color.h" class CFunction; #include "../../../include/cscript/CInterpreter.h" #include "../../../include/cscript/CObject.h" #include "../../../include/tool/Tool.h" #include <glm.hpp> #include <gtx/rotate_vector.hpp> #include <string> #include <vector> #include <memory> #include <random> #include "../../../include/tool/toolSettings/effects/TSet_Effects.h" //////////////////////////////////////////////////////////////// // Effects Settings //////////////////////////////////////////////////////////////// // 81 - Fill , 82 - Gradient, 83 - Posterize, 84 - Invert, 85 - Threshold, 86 - Bright/Contrast // 87 - HSV TSet_Effects::TSet_Effects() // 8000 { this->type = TSetType::effects; this->isEnabled = false; this->effectsOrdering[0] = 0; // 8098 subSig 0 - 15 this->effectsOrdering[1] = 0; this->effectsOrdering[2] = 0; this->effectsOrdering[3] = 0; this->effectsOrdering[4] = 0; this->effectsOrdering[5] = 0; this->effectsOrdering[6] = 0; this->effectsOrdering[7] = 0; this->effectsOrdering[8] = 0; this->effectsOrdering[9] = 0; this->effectsOrdering[10] = 0; this->effectsOrdering[11] = 0; this->effectsOrdering[12] = 0; this->effectsOrdering[13] = 0; this->effectsOrdering[14] = 0; this->effectsOrdering[15] = 0; updateEffectsCount(false); this->fill.isEnabled = false; // 8010 this->gradient.isEnabled = false; // 8011 this->posterize.isEnabled = false; // 8012 this->invert.isEnabled = false; // 8013 this->threshold.isEnabled = false; // 8014 this->brightContrast.isEnabled = false; // 8015 this->hsv.isEnabled = false; // 8016 this->power.isEnabled = false; // 8017 this->modulo.isEnabled = false; // 8018 this->blur.isEnabled = false; // 8024 this->totalBlend = 1.0f; // 8050 this->totalMask_alphaCenter = 0.5f; // 8051 this->totalMask_alphaRange = 1.0f; // 8052 } std::shared_ptr<CObject> TSet_Effects::putProperty( std::shared_ptr<CInterpreter> interpreter, std::shared_ptr<Tool> owner, int settingsSig, int subSig, std::shared_ptr<CObject> object, bool isGet, bool asPercentage, bool asString) { if (settingsSig == 8098) { if (subSig >= 0 && subSig <= 15) { if (!isGet) { effectsOrdering[(size_t)subSig] = objectToFX_int(object, false); updateEffectsCount(false); } else { if (asString) { return std::make_shared<CObject>( makeSettingString(effectsOrdering[(size_t)subSig], settingsSig, subSig, "effectsOrdering" + std::to_string(subSig))); } return std::make_shared<CObject>(intToFX_string(effectsOrdering[(size_t)subSig])); } } else if (subSig == -2) { if (!isGet) { for (int i = 0; i < 15; i++) { if (effectsOrdering[i] == 0) { int fxSig = objectToFX_int(object, false); effectsOrdering[(size_t)i] = fxSig; switch (fxSig) { case 81: fill.isEnabled = true; break; case 82: gradient.isEnabled = true; break; case 83: posterize.isEnabled = true; break; case 84: invert.isEnabled = true; break; case 85: threshold.isEnabled = true; break; case 86: brightContrast.isEnabled = true; break; case 87: hsv.isEnabled = true; break; case 90: power.isEnabled = true; break; case 91: modulo.isEnabled = true; break; case 95: blur.isEnabled = true; break; } updateEffectsCount(false); break; } } } } else { if (!isGet) { if (object.get()->objType.type == CLiteralTypes::_CString) { std::string objStr = std::get<std::string>(object.get()->obj); std::vector<std::string> strVec = stringVec_fromCommaSeparated(objStr, true); if (strVec.size() != 0) { std::vector<std::shared_ptr<CObject>> strObjVec; for (std::string str : strVec) { strObjVec.push_back(std::make_shared<CObject>(str)); } std::shared_ptr<CObject> vecObj = std::make_shared<CObject>( CLiteralTypes::_CString_Array, std::make_shared<std::vector<std::shared_ptr<CObject>>>(strObjVec)); objectToFX_int(vecObj, true); } } else { objectToFX_int(object, true); } updateEffectsCount(true); } else { if (asString) { std::vector<std::string> effectsStrVec; for (int i = 0; i < 15; i++) { if (effectsOrdering[i] == 0) { continue; } effectsStrVec.push_back(intToFX_string(effectsOrdering[i])); } return std::make_shared<CObject>( makeSettingString(effectsStrVec, settingsSig, subSig, "effectsOrdering")); } std::vector<std::shared_ptr<CObject>> effectsStrObj; for (int i = 0; i < 15; i++) { if (effectsOrdering[i] == 0) { continue; } effectsStrObj.push_back(std::make_shared<CObject>(intToFX_string(effectsOrdering[i]))); } return std::make_shared<CObject>(CLiteralTypes::_CString_Array, std::make_shared<std::vector<std::shared_ptr<CObject>>>(effectsStrObj)); } } } else if (settingsSig >= 8010 && settingsSig <= 8049) { if (settingsSig == 8010) { if (isGet) { if (asString) { return std::make_shared<CObject>(makeSettingString(fill.isEnabled, settingsSig, subSig, "fill_isEnabled")); } return std::make_shared<CObject>(fill.isEnabled); } else { fill.isEnabled = std::get<bool>(object.get()->obj); } } else if (settingsSig == 8011) { if (isGet) { if (asString) { return std::make_shared<CObject>(makeSettingString(gradient.isEnabled, settingsSig, subSig, "gradient_isEnabled")); } return std::make_shared<CObject>(gradient.isEnabled); } else { gradient.isEnabled = std::get<bool>(object.get()->obj); } } else if (settingsSig == 8012) { if (isGet) { if (asString) { return std::make_shared<CObject>(makeSettingString(posterize.isEnabled, settingsSig, subSig, "posterize_isEnabled")); } return std::make_shared<CObject>(posterize.isEnabled); } else { posterize.isEnabled = std::get<bool>(object.get()->obj); } } else if (settingsSig == 8013) { if (isGet) { if (asString) { return std::make_shared<CObject>(makeSettingString(invert.isEnabled, settingsSig, subSig, "invert_isEnabled")); } return std::make_shared<CObject>(invert.isEnabled); } else { invert.isEnabled = std::get<bool>(object.get()->obj); } } else if (settingsSig == 8014) { if (isGet) { if (asString) { return std::make_shared<CObject>(makeSettingString(threshold.isEnabled, settingsSig, subSig, "threshold_isEnabled")); } return std::make_shared<CObject>(threshold.isEnabled); } else { threshold.isEnabled = std::get<bool>(object.get()->obj); } } else if (settingsSig == 8015) { if (isGet) { if (asString) { return std::make_shared<CObject>(makeSettingString(brightContrast.isEnabled, settingsSig, subSig, "brightContrast_isEnabled")); } return std::make_shared<CObject>(brightContrast.isEnabled); } else { brightContrast.isEnabled = std::get<bool>(object.get()->obj); } } else if (settingsSig == 8016) { if (isGet) { if (asString) { return std::make_shared<CObject>(makeSettingString(hsv.isEnabled, settingsSig, subSig, "hsv_isEnabled")); } return std::make_shared<CObject>(hsv.isEnabled); } else { hsv.isEnabled = std::get<bool>(object.get()->obj); } } else if (settingsSig == 8017) { if (isGet) { if (asString) { return std::make_shared<CObject>(makeSettingString(power.isEnabled, settingsSig, subSig, "power_isEnabled")); } return std::make_shared<CObject>(power.isEnabled); } else { power.isEnabled = std::get<bool>(object.get()->obj); } } else if (settingsSig == 8018) { if (isGet) { if (asString) { return std::make_shared<CObject>(makeSettingString(modulo.isEnabled, settingsSig, subSig, "modulo_isEnabled")); } return std::make_shared<CObject>(modulo.isEnabled); } else { modulo.isEnabled = std::get<bool>(object.get()->obj); } } else if (settingsSig == 8024) { if (isGet) { if (asString) { return std::make_shared<CObject>(makeSettingString(blur.isEnabled, settingsSig, subSig, "blur_isEnabled")); } return std::make_shared<CObject>(blur.isEnabled); } else { blur.isEnabled = std::get<bool>(object.get()->obj); } } } else if (settingsSig >= 8050 && settingsSig <= 8069) { if (settingsSig == 8050) { if (isGet) { if (asString) { return std::make_shared<CObject>(makeSettingString(totalBlend, settingsSig, subSig, "totalBlend")); } if (asPercentage) { return std::make_shared<CObject>(double( percentRange_cubedInvert(totalBlend, 0.0f, 1.0f, true))); } else { return std::make_shared<CObject>(double(totalBlend)); } } else { if (asPercentage) { totalBlend = percentRange_cubedInvert( (float)std::get<double>(object.get()->obj), 0.0f, 1.0f, false); } else { totalBlend = clampf((float)std::get<double>(object.get()->obj), 0.0f, 1.0f); } } } else if (settingsSig == 8051) { if (isGet) { if (asString) { return std::make_shared<CObject>(makeSettingString(totalMask_alphaCenter, settingsSig, subSig, "totalMask_alphaCenter")); } if (asPercentage) { return std::make_shared<CObject>(double( percentRange(totalMask_alphaCenter, 0.0f, 1.0f, true))); } else { return std::make_shared<CObject>(double(totalMask_alphaCenter)); } } else { if (asPercentage) { totalMask_alphaCenter = percentRange( (float)std::get<double>(object.get()->obj), 0.0f, 1.0f, false); } else { totalMask_alphaCenter = clampf((float)std::get<double>(object.get()->obj), 0.0f, 1.0f); } } } else if (settingsSig == 8052) { if (isGet) { if (asString) { return std::make_shared<CObject>(makeSettingString(totalMask_alphaRange, settingsSig, subSig, "totalMask_alphaRange")); } if (asPercentage) { return std::make_shared<CObject>(double( percentRange(totalMask_alphaRange, 0.0f, 1.0f, true))); } else { return std::make_shared<CObject>(double(totalMask_alphaRange)); } } else { if (asPercentage) { totalMask_alphaRange = percentRange( (float)std::get<double>(object.get()->obj), 0.0f, 1.0f, false); } else { totalMask_alphaRange = clampf((float)std::get<double>(object.get()->obj), 0.0f, 1.0f); } } } } if (settingsSig >= 8300 && settingsSig <= 8399) { return posterize.putProperty(interpreter, owner, settingsSig, subSig, object, isGet, asPercentage, asString); } else if (settingsSig >= 8400 && settingsSig <= 8499) { return invert.putProperty(interpreter, owner, settingsSig, subSig, object, isGet, asPercentage, asString); } else if (settingsSig >= 8600 && settingsSig <= 8699) { return brightContrast.putProperty(interpreter, owner, settingsSig, subSig, object, isGet, asPercentage, asString); } else if (settingsSig >= 8700 && settingsSig <= 8799) { return hsv.putProperty(interpreter, owner, settingsSig, subSig, object, isGet, asPercentage, asString); } else if (settingsSig >= 9000 && settingsSig <= 9099) { return power.putProperty(interpreter, owner, settingsSig, subSig, object, isGet, asPercentage, asString); } else if (settingsSig >= 9100 && settingsSig <= 9199) { return modulo.putProperty(interpreter, owner, settingsSig, subSig, object, isGet, asPercentage, asString); } else if (settingsSig >= 9500 && settingsSig <= 9599) { return blur.putProperty(interpreter, owner, settingsSig, subSig, object, isGet, asPercentage, asString); } if (asString) { return std::make_shared<CObject>(makeSettingString(isEnabled, settingsSig, subSig, "NULL")); } return std::make_shared<CObject>(nullptr); } TSetControl_Node* TSet_Effects::getControlNode(int settingSig, int subSig) { return nullptr; } TSetController* TSet_Effects::getController(int settingSig, int subSig) { return nullptr; } TSetGraph* TSet_Effects::getGraph(int settingSig, int subSig) { return nullptr; } TSetNoise* TSet_Effects::getNoise(int settingSig, int subSig) { return nullptr; } void TSet_Effects::initializeData(CColor FGColor, CColor BGColor, int tipSize) { updateEffectsOrdering(true); updateEffectsCount(false); if (fill.isEnabled) { fill.initializeData(FGColor, BGColor, tipSize); } if (gradient.isEnabled) { gradient.initializeData(FGColor, BGColor, tipSize); } if (brightContrast.isEnabled) { brightContrast.initializeData(FGColor, BGColor); } if (hsv.isEnabled) { hsv.initializeData(FGColor, BGColor); } } std::vector<int> TSet_Effects::getOrdering_vec() { std::vector<int> outVec; for (int i = 0; i < 16; i++) { outVec.push_back(effectsOrdering[i]); } return outVec; } void TSet_Effects::updateEffectsOrdering(bool removeZero) { std::vector<int> newOrder; for (int i = 0; i < 16; i++) { switch (effectsOrdering[i]) { case 81: newOrder.push_back(81 * ((removeZero) ? fill.isEnabled : 1)); break; case 82: newOrder.push_back(82 * ((removeZero) ? gradient.isEnabled : 1)); break; case 83: newOrder.push_back(83 * ((removeZero) ? posterize.isEnabled : 1)); break; case 84: newOrder.push_back(84 * ((removeZero) ? invert.isEnabled : 1)); break; case 85: newOrder.push_back(85 * ((removeZero) ? threshold.isEnabled : 1)); break; case 86: newOrder.push_back(86 * ((removeZero) ? brightContrast.isEnabled : 1)); break; case 87: newOrder.push_back(87 * ((removeZero) ? hsv.isEnabled : 1)); break; case 90: newOrder.push_back(90 * ((removeZero) ? power.isEnabled : 1)); break; case 91: newOrder.push_back(91 * ((removeZero) ? modulo.isEnabled : 1)); break; case 95: newOrder.push_back(95 * ((removeZero) ? blur.isEnabled : 1)); break; default: newOrder.push_back(0); } effectsOrdering[i] = 0; } int copyPos = 0; for (int newVal : newOrder) { if (newVal != 0) { effectsOrdering[copyPos] = newVal; copyPos++; } } } void TSet_Effects::updateEffectsCount(bool checkVisible) { int count = 0; for (int i = 0; i < 16; i++) { if (effectsOrdering[i] != 0) { if (checkVisible) { switch (effectsOrdering[i]) { case 81: if (!fill.isEnabled) { effectsOrdering[i] = 0; } else { count++; } break; case 82: if (!gradient.isEnabled) { effectsOrdering[i] = 0; } else { count++; } break; case 83: if (!posterize.isEnabled) { effectsOrdering[i] = 0; } else { count++; } break; case 84: if (!invert.isEnabled) { effectsOrdering[i] = 0; } else { count++; } break; case 85: if (!threshold.isEnabled) { effectsOrdering[i] = 0; } else { count++; } break; case 86: if (!brightContrast.isEnabled) { effectsOrdering[i] = 0; } else { count++; } break; case 87: if (!hsv.isEnabled) { effectsOrdering[i] = 0; } else { count++; } break; case 90: if (!power.isEnabled) { effectsOrdering[i] = 0; } else { count++; } break; case 91: if (!modulo.isEnabled) { effectsOrdering[i] = 0; } else { count++; } break; case 95: if (!blur.isEnabled) { effectsOrdering[i] = 0; } else { count++; } break; } } else { count++; } } } effectsCount = clampi(count, 0, 16); } int TSet_Effects::objectToFX_int(std::shared_ptr<CObject> object, bool isArraySet) { if (object.get()->objType.type == CLiteralTypes::_CString_Array && isArraySet) { std::vector<std::shared_ptr<CObject>> vec; if (object.get()->obj.index() != 0) { vec = *std::get<std::shared_ptr<std::vector<std::shared_ptr<CObject>>>>(object.get()->obj); } for (int c = 0; c < 16; c++) { if (c < vec.size()) { effectsOrdering[c] = objectToFX_int(vec[c], false); } else { effectsOrdering[c] = 0; } } return 0; } else if (object.get()->objType.type == CLiteralTypes::_CNumber_Array && isArraySet) { int i = 0; std::vector<std::shared_ptr<CObject>> vec = *std::get<std::shared_ptr<std::vector<std::shared_ptr<CObject>>>>(object.get()->obj); for (std::shared_ptr<CObject> obj : vec) { effectsOrdering[i] = (int)std::get<double>(obj.get()->obj); i++; } return 0; } else if (object.get()->objType.type == CLiteralTypes::_CString) { std::string objStr = std::get<std::string>(object.get()->obj); stringToLower(objStr); if (objStr.find("fill") != std::string::npos) { return 81; } if (objStr.find("gradient") != std::string::npos) { return 82; } if (objStr.find("posterize") != std::string::npos) { return 83; } if (objStr.find("invert") != std::string::npos) { return 84; } if (objStr.find("threshold") != std::string::npos) { return 85; } if (objStr.find("power") != std::string::npos) { return 90; } if (objStr.find("modulo") != std::string::npos) { return 91; } if (objStr.find("blur") != std::string::npos) { return 95; } if (objStr.find("hsv") != std::string::npos || objStr.find("huesat") != std::string::npos) { return 87; } if (objStr.find("bright") != std::string::npos || objStr.find("contrast") != std::string::npos || objStr.find("brightness") != std::string::npos || objStr.find("brightcontrast") != std::string::npos) { return 86; } } else if (object.get()->objType.type == CLiteralTypes::_CNumber) { return (int)std::get<double>(object.get()->obj); } return 0; } std::string TSet_Effects::intToFX_string(int effectsSig) { switch (effectsSig) { case 81: return "fill"; break; case 82: return "gradient"; break; case 83: return "posterize"; break; case 84: return "invert"; break; case 85: return "threshold"; break; case 86: return "brightcontrast"; break; case 87: return "hsv"; break; case 90: return "power"; break; case 91: return "modulo"; break; case 95: return "blur"; break; } return ""; }
32.940299
149
0.649411
chromaScript
e328c8e786d0fdff885335a27bb7196783d9730c
768
cpp
C++
algorithm/hw11v2.cpp
scott306lr/coding_exercise
2bca11a1e68b468d6c5422f8cec2eb9e090664f7
[ "MIT" ]
null
null
null
algorithm/hw11v2.cpp
scott306lr/coding_exercise
2bca11a1e68b468d6c5422f8cec2eb9e090664f7
[ "MIT" ]
null
null
null
algorithm/hw11v2.cpp
scott306lr/coding_exercise
2bca11a1e68b468d6c5422f8cec2eb9e090664f7
[ "MIT" ]
null
null
null
//#include <bits/stdc++.h> #include <iostream> #include <vector> #include <algorithm> #include <map> #include <unordered_map> #include <queue> using namespace std; typedef pair<int,int> pii; int n; string inpu; int dp[7001][7001]; int main(){ cin.tie(0), cout.sync_with_stdio(0); cin >> n ; cin >> inpu; for(int i=0; i<n; ++i) dp[i][i]=1; for(int len=2; len<=n; ++len){ //try bottom-up for(int i=0; i+len-1<n; ++i){ int j=i+len-1; if( inpu[i]==inpu[j] ) dp[i][j] = max(dp[i][j], dp[i+2][j-2]+2); dp[i][j] = max(dp[i][j],max( dp[i+1][j] , dp[i][j-1] )); } } //cout<< dp[0][n-1]; // for (int i = 0; i < n; ++i) // { // for (int j = 0; j < n; ++j) // { // cout<<dp[i][j]<<" "; // } // cout<<endl; // } cout<< dp[0][n-1]; }
17.860465
67
0.50651
scott306lr
e32d7b824fbdec67073908ec6c0473bc2e92d48b
178
hpp
C++
include/kbrica.hpp
ktnyt/KBriCA
1167d3ac08daae2858388a7e4db745c6e65fd3c7
[ "MIT" ]
null
null
null
include/kbrica.hpp
ktnyt/KBriCA
1167d3ac08daae2858388a7e4db745c6e65fd3c7
[ "MIT" ]
null
null
null
include/kbrica.hpp
ktnyt/KBriCA
1167d3ac08daae2858388a7e4db745c6e65fd3c7
[ "MIT" ]
null
null
null
#ifndef __KBRICA_HPP__ #define __KBRICA_HPP__ #include "kbrica/buffer.hpp" #include "kbrica/component.hpp" #include "kbrica/functor.hpp" #include "kbrica/scheduler.hpp" #endif
17.8
31
0.786517
ktnyt
e32ec57092453a85db34f74630d5d7e470a2b474
5,803
hpp
C++
src/pyprx/utilities/spaces/space_py.hpp
aravindsiv/ML4KP
064015a7545e1713cbcad3e79807b5cec0849f54
[ "MIT" ]
3
2021-05-31T11:28:03.000Z
2021-05-31T13:49:30.000Z
src/pyprx/utilities/spaces/space_py.hpp
aravindsiv/ML4KP
064015a7545e1713cbcad3e79807b5cec0849f54
[ "MIT" ]
1
2021-09-03T09:39:32.000Z
2021-12-10T22:17:56.000Z
src/pyprx/utilities/spaces/space_py.hpp
aravindsiv/ML4KP
064015a7545e1713cbcad3e79807b5cec0849f54
[ "MIT" ]
2
2021-09-03T09:17:45.000Z
2021-10-04T15:52:58.000Z
#include <iostream> #include <boost/python.hpp> #include <boost/python/copy_const_reference.hpp> #include <boost/python/return_value_policy.hpp> #include "prx/utilities/spaces/space.hpp" // #include "prx/simulation/plants/two_link_acrobot.hpp" // #include "prx/simulation/plant.hpp" using namespace boost::python; int get_dim_wrapper(prx::space_point_t p) { return p -> get_dim(); } double space_point_get_item(prx::space_point_t& pt, int i) { INDEX_CHECK(i, pt -> get_dim(), "space_point" ) return pt -> at(i); } void space_point_set_item(prx::space_point_t& pt, int i, double val) { INDEX_CHECK(i, pt -> get_dim(), "space_point" ) pt -> at(i) = val; } // object init_distance_function() prx::distance_function_t init_distance_function() { prx::distance_function_t default_df = [](const prx::space_point_t& s1, const prx::space_point_t& s2) { return sqrt((s1->at(0)-s2->at(0))*(s1->at(0)-s2->at(0))+ (s1->at(1)-s2->at(1))*(s1->at(1)-s2->at(1))); }; // return boost::python::make_function(default_df); return default_df; } struct distance_function_wrapper : prx::distance_function_t, wrapper<prx::distance_function_t> { }; // void set_distance_function(prx::distance_function_t& self, boost::python::object obj) // { // self = // } // spam& self, boost::python::object object prx::distance_function_t get_df(PyObject* x) { std::function<double (const prx::space_point_t&, const prx::space_point_t&)> new_df = [x](const prx::space_point_t& s1, const prx::space_point_t& s2) { return call<double>(x, s1, s2); }; return new_df; } BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(space_t_print_point_overloads, prx::space_t::print_point, 1, 2) BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(space_t_print_memory_overloads, prx::space_t::print_memory, 0, 1) void (prx::space_t::*enforce_bounds0)() const = &prx::space_t::enforce_bounds; void (prx::space_t::*enforce_bounds1)(const prx::space_point_t&) const = &prx::space_t::enforce_bounds; void (prx::space_t::*integrate_0)(const prx::space_point_t&, const prx::space_t*, double) = &prx::space_t::integrate; void (prx::space_t::*integrate_1)(const prx::space_t*, double) = &prx::space_t::integrate; void pyprx_utilities_spaces_space() { // typedef std::shared_ptr<space_snapshot_t> space_point_t; class_<prx::space_point_t>("space_point", no_init) .def("__len__", &get_dim_wrapper) .def("__getitem__", &space_point_get_item) .def("__setitem__", &space_point_set_item) // .def("assign", &list_assign<double>) .def("__str__", &prx_to_str<prx::space_point_t>) .def("__repr__", &prx_print<prx::space_point_t>) // .def(str(self)) ; enum_<prx::space_t::topology_t>("topology") .value("EUCLIDEAN", prx::space_t::topology_t::EUCLIDEAN) .value("ROTATIONAL", prx::space_t::topology_t::ROTATIONAL) .value("DISCRETE", prx::space_t::topology_t::DISCRETE) .export_values() ; class_<prx::distance_function_t>("distance_function") .def("__call__", &prx::distance_function_t::operator() ) .def("default", make_function(&init_distance_function, default_call_policies())).staticmethod("default") .def("set_df", &get_df).staticmethod("set_df") .def("__setattr__", &get_df) ; class_<prx::space_t, std::shared_ptr<prx::space_t>>("space_t", init<std::string, std::vector<double*>, std::string>()) .def("__init__", make_constructor(&init_as_ptr<prx::space_t,std::string,std::vector<double*>>, default_call_policies(), (args("topology"), args("addresses")) )) .def("__init__", make_constructor(&init_as_ptr<prx::space_t,const std::vector<const prx::space_t*>>, default_call_policies(), (args("spaces")) )) .def("set_bounds", &prx::space_t::set_bounds) .def("make_point", &prx::space_t::make_point) .def("clone_point", &prx::space_t::clone_point) .def("enforce_bounds", enforce_bounds0) .def("enforce_bounds", enforce_bounds1) .def("at", &prx::space_t::at, return_value_policy<copy_non_const_reference>()) .def("__getitem__", &prx::space_t::at, return_value_policy<copy_non_const_reference>()) .def("get_dimension", &prx::space_t::get_dimension) .def("copy_to_point", &prx::space_t::copy_to_point) .def("copy_from_point", &prx::space_t::copy_from_point) // .def("copy_from_vector", &prx::space_t::copy_from_vector) .def("copy_point", &prx::space_t::copy_point) .def("copy_point_from_vector", &prx::space_t::copy_point_from_vector) .def("copy_vector_from_point", &prx::space_t::copy_vector_from_point) .def("is_point_in_space", &prx::space_t::is_point_in_space) .def("split_point", &prx::space_t::split_point) .def("print_memory", &prx::space_t::print_memory, space_t_print_memory_overloads()) .def("print_point", &prx::space_t::print_point, space_t_print_point_overloads()) .def("equal_points", &prx::space_t::equal_points) .def("get_dimension", &prx::space_t::get_dimension) .def("satisfies_bounds", &prx::space_t::satisfies_bounds) .def("sample", &prx::space_t::sample) .def("get_space_name", &prx::space_t::get_space_name) // .def("get_lower_bound", &prx::space_t::get_lower_bound) // .def("get_upper_bound", &prx::space_t::get_upper_bound) .def("get_bounds", &prx::space_t::get_bounds) .def("integrate", integrate_0) .def("integrate", integrate_1) .def("interpolate", &prx::space_t::interpolate) // .def("", &prx::space_t::) // .def("", &prx::space_t::) // .def("", &prx::space_t::) // .def("", &prx::space_t::) ; }
41.45
168
0.666552
aravindsiv
e33a75ec8cce99e873e1abb44118b03437549e92
2,232
hpp
C++
bootloader/bootloader32/src/Bootloader32.hpp
Rzuwik/FunnyOS
a93a45babf575d08cf2704a8394ac1455f3ad4db
[ "MIT" ]
null
null
null
bootloader/bootloader32/src/Bootloader32.hpp
Rzuwik/FunnyOS
a93a45babf575d08cf2704a8394ac1455f3ad4db
[ "MIT" ]
null
null
null
bootloader/bootloader32/src/Bootloader32.hpp
Rzuwik/FunnyOS
a93a45babf575d08cf2704a8394ac1455f3ad4db
[ "MIT" ]
null
null
null
#ifndef FUNNYOS_BOOTLOADER_BOOTLOADER32_SRC_BOOTLOADER32_HPP #define FUNNYOS_BOOTLOADER_BOOTLOADER32_SRC_BOOTLOADER32_HPP #include <FunnyOS/Bootparams/Parameters.hpp> #include <FunnyOS/Misc/MemoryAllocator/StaticMemoryAllocator.hpp> namespace FunnyOS::Bootloader32 { /** * 32-bit implementation of BootloaderType */ class Bootloader { public: /** * Returns the whole bootparams structure. * * @return the whole the whole bootparams structure */ [[nodiscard]] Bootparams::Parameters& GetBootloaderParameters(); /** * Bootloader entry point */ [[noreturn]] void Main(); /** * Prints the error in BIG RED TEXT with some additional debugging information and halts the execution. * * @param[in] details error details */ [[noreturn]] F_NEVER_INLINE void Panic(const char* details); /** * Halts the CPU */ [[noreturn]] void Halt(); /** * Returns the reference for the memory allocator used by the bootloader. */ [[nodiscard]] Misc::MemoryAllocator::StaticMemoryAllocator& GetAllocator(); /** * Returns whether or not the bootloader should pause and wait for use input before jumping to kernel. * * @return whether or not the bootloader should pause and wait for use input before jumping to kernel */ [[nodiscard]] bool IsPauseBeforeBoot() const; /** * Sets whether or not the bootloader should pause and wait for use input before jumping to kernel. * * @param pauseBeforeBoot whether or not to pause */ void SetPauseBeforeBoot(bool pauseBeforeBoot); public: /** * Gets the global instance of the Bootloader class. * * @return the global instance of the Bootloader class */ static Bootloader& Get(); private: Misc::MemoryAllocator::StaticMemoryAllocator m_allocator{}; bool m_pauseBeforeBoot = false; }; } // namespace FunnyOS::Bootloader32 #endif // FUNNYOS_BOOTLOADER_BOOTLOADER32_SRC_BOOTLOADER32_HPP
30.575342
111
0.625448
Rzuwik
e34283713e63805eb7842b2bfc5a72bab85d211a
819
cpp
C++
src/array19.lib/array19/Array.test.cpp
Fettpet/co-cpp19
928a835c4f66032aa88ce01df7899da86d37df22
[ "MIT" ]
8
2020-05-31T16:13:13.000Z
2022-01-12T08:52:42.000Z
src/array19.lib/array19/Array.test.cpp
Fettpet/co-cpp19
928a835c4f66032aa88ce01df7899da86d37df22
[ "MIT" ]
null
null
null
src/array19.lib/array19/Array.test.cpp
Fettpet/co-cpp19
928a835c4f66032aa88ce01df7899da86d37df22
[ "MIT" ]
2
2020-07-21T10:58:28.000Z
2021-07-26T06:52:05.000Z
#include "Array.h" using namespace array19; void constexpr_Array_test() { constexpr auto a = Array{1, 2, 3}; static_assert(a.count == 3); static_assert(a[1] == 2); constexpr auto s = [&] { auto s = 0; for (auto v : a) s += v; return s; }(); static_assert(s == 6); } void empty_Array_test() { constexpr auto a = Array<int, 0>{}; static_assert(a.count == 0); static_assert(a.isEmpty()); constexpr auto s = [&] { auto s = 0; for (auto v : a) s += v; return s; }(); static_assert(s == 0); } void mutable_Array_test() { constexpr auto ca = [] { auto a = Array{1, 2, 3}; a.amend()[1] = 5; return a; }(); static_assert(ca == Array{1, 5, 3}); }
19.5
41
0.481074
Fettpet
e34313b102e444a8e0b1c760606586592d5d38a7
2,227
cpp
C++
Server/src/orm/QueryBuilder.cpp
Vyraax/Linguini
f89ba9d030fea289347d9c99758231c86e3dbec0
[ "MIT" ]
3
2021-04-19T20:38:54.000Z
2021-09-13T12:17:35.000Z
Server/src/orm/QueryBuilder.cpp
Vyraax/Linguini
f89ba9d030fea289347d9c99758231c86e3dbec0
[ "MIT" ]
null
null
null
Server/src/orm/QueryBuilder.cpp
Vyraax/Linguini
f89ba9d030fea289347d9c99758231c86e3dbec0
[ "MIT" ]
1
2021-09-13T12:17:36.000Z
2021-09-13T12:17:36.000Z
#include "QueryBuilder.h" #include "../application/Model.h" std::string QueryBuilder::createTable(Model* model) { std::string str = "CREATE TABLE IF NOT EXISTS " + Utils::upper(model->name) + " (\n"; std::vector<std::string> fields; for (auto field : model->schema) { std::string out = " `" + field.name + '`'; switch (field.type) { case Field::Type::INTEGER: { out += " INT(" + std::to_string(field.size > 0 ? field.size : 11) + ")"; break; } case Field::Type::STRING: { out += " VARCHAR(" + std::to_string(field.size > 0 ? field.size : 255) + ")"; break; } case Field::Type::DATETIME: { out += " DATETIME"; break; } case Field::Type::CHAR: { out += " CHAR"; break; } case Field::Type::FLOAT: { out += " FLOAT"; break; } case Field::Type::TEXT: { out += " TEXT"; break; } } if (field.primary) out += " PRIMARY KEY"; if (field.not_null) out += " NOT NULL"; else out += " DEFAULT NULL"; if (field.increment) out += " AUTO_INCREMENT"; fields.push_back(out); } str += Utils::join(fields, ",\n"); str += "\n);"; try { ORM::fetch(model->name, str.c_str()); } catch (std::exception& e) { ORM::logger.error("ORM", e.what()); } return std::string(); } std::vector<std::string> QueryBuilder::columnsToString() { std::vector<std::string> lines; for (auto it = this->columns.begin(); it != this->columns.end(); ++it) { std::string value = ORM::getAnyValue(it->second); for (auto function : this->sql_functions) if (value.find(function + '(') != std::string::npos) value = value.substr(1, value.size() - 2); lines.push_back(Utils::join({ '`' + it->first + '`', value }, " = ")); } return lines; } std::string QueryBuilder::parametersToString(const Object& parameters, bool selector, const std::string& delimiter) { std::stringstream stream; unsigned int count = 0; auto it = parameters.begin(); for (; it != parameters.end(); ++it) { stream << "`" + this->table_alias + "`.`" + it->first + "`"; if (!selector) stream << " = " << ORM::getAnyValue(it->second); if (count >= 0 && count < parameters.size() - 1) stream << ' ' + delimiter + ' '; count++; } return stream.str(); }
21.209524
115
0.5815
Vyraax
e34354ea40541f841beec5f72f7cbe0833cc1773
807
hpp
C++
include/disccord/rest/models/create_dm_channel_args.hpp
FiniteReality/disccord
1b89cde8031a1d6f9d43fa8f39dbc0959c8639ff
[ "MIT" ]
44
2016-09-19T15:28:25.000Z
2018-08-09T13:17:40.000Z
include/disccord/rest/models/create_dm_channel_args.hpp
FiniteReality/disccord
1b89cde8031a1d6f9d43fa8f39dbc0959c8639ff
[ "MIT" ]
44
2016-11-03T17:27:30.000Z
2017-12-10T16:17:31.000Z
include/disccord/rest/models/create_dm_channel_args.hpp
FiniteReality/disccord
1b89cde8031a1d6f9d43fa8f39dbc0959c8639ff
[ "MIT" ]
13
2016-11-01T00:17:20.000Z
2018-08-03T19:51:16.000Z
#ifndef _create_dm_channel_args_hpp_ #define _create_dm_channel_args_hpp_ #include <disccord/models/model.hpp> namespace disccord { namespace rest { namespace models { class create_dm_channel_args : public disccord::models::model { public: create_dm_channel_args(uint64_t recipient_id); virtual ~create_dm_channel_args(); uint64_t get_recipient_id(); protected: virtual void encode_to( std::unordered_map<std::string, web::json::value>& info ) override; private: uint64_t recipient_id; }; } } } #endif /* _create_dm_channel_args_hpp_ */
24.454545
79
0.536555
FiniteReality