hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6ea5479684aea0946f1f98de049a17fedcbb670c | 193 | cc | C++ | test/check_module.cc | respu/libposix | 27681383e5d3e19687d7fba23d97166beeeece13 | [
"Unlicense"
] | 2 | 2015-11-05T09:08:04.000Z | 2016-02-09T23:26:00.000Z | test/check_module.cc | yggchan/libposix | 27681383e5d3e19687d7fba23d97166beeeece13 | [
"Unlicense"
] | null | null | null | test/check_module.cc | yggchan/libposix | 27681383e5d3e19687d7fba23d97166beeeece13 | [
"Unlicense"
] | null | null | null | /* This is free and unencumbered software released into the public domain. */
#include "catch.hpp"
#include <posix++/module.h> /* for posix::module */
TEST_CASE("test_module") {
// TODO
}
| 19.3 | 77 | 0.683938 | respu |
6ea7712832a3df3014e2fcb66d4768d8068e545e | 737 | cpp | C++ | week2/man_dog.cpp | aviiciii/iitb-exercises | e078e28fceb87eecc747272abd410e7279b22a97 | [
"MIT"
] | null | null | null | week2/man_dog.cpp | aviiciii/iitb-exercises | e078e28fceb87eecc747272abd410e7279b22a97 | [
"MIT"
] | null | null | null | week2/man_dog.cpp | aviiciii/iitb-exercises | e078e28fceb87eecc747272abd410e7279b22a97 | [
"MIT"
] | null | null | null | #include <simplecpp>
main_program {
initCanvas("Man and Dog", 700, 700);
//draw axes
Turtle t;
t.right(90); t.forward(350);
t.right(180); t.forward(700);
t.right(180); t.forward(350);
t.right(90); t.forward(350);
t.right(180); t.forward(750);
Text tx1(400,365,"50");
Text tx2(450,365,"100");
Text tx3(500,365,"150");
Text tx4(550,365,"200");
Text tx5(600,365,"250");
Text tx6(650,365,"300");
wait(4);
Turtle t1, t2;
t1.setColor(COLOR("blue"));
t2.setColor(COLOR("red"));
t2.forward(300); t2.right(180);
wait(4);
repeat(50){
t1.forward(3);
t2.forward(6);
}
wait(5);
}
| 17.547619 | 41 | 0.506106 | aviiciii |
6ea88e63a74886932f19c68bba323ffcf6270374 | 1,497 | hpp | C++ | include/d_log_wrapper.hpp | domenn/cppcommonutil | 8f8f071a274a57e4d1bcf7f09935a08175c1204e | [
"Unlicense"
] | null | null | null | include/d_log_wrapper.hpp | domenn/cppcommonutil | 8f8f071a274a57e4d1bcf7f09935a08175c1204e | [
"Unlicense"
] | null | null | null | include/d_log_wrapper.hpp | domenn/cppcommonutil | 8f8f071a274a57e4d1bcf7f09935a08175c1204e | [
"Unlicense"
] | null | null | null | #pragma once
#ifdef D_USING_SPDLOG
#include <d_spdlog/spd_logging.hpp>
// Map level names ...
#ifdef TRACE
#define VERBOSE TRACE
#endif
#define WARNING WARN
#define WARNING WARN
#define D_ANY_LOG_DEFAULT_IMPL(level, ...) SPDLOG_##level(__VA_ARGS__)
#define D_LOG_DEFAULT(level, ...) D_ANY_LOG_DEFAULT_IMPL(level, __VA_ARGS__)
#define D_LOG(level, namestr, ...) SPDLOG_LOGGER_##level(spdl::get(namestr), __VA_ARGS__)
#define D_LOGT(namestr, ...) SPDLOG_LOGGER_TRACE(spdl::get(namestr), __VA_ARGS__)
#define D_LOGD(namestr, ...) SPDLOG_LOGGER_DEBUG(spdl::get(namestr), __VA_ARGS__)
#define D_LOGI(namestr, ...) SPDLOG_LOGGER_INFO(spdl::get(namestr), __VA_ARGS__)
#define D_LOGW(namestr, ...) SPDLOG_LOGGER_WARN(spdl::get(namestr), __VA_ARGS__)
#define D_LOGE(namestr, ...) SPDLOG_LOGGER_ERROR(spdl::get(namestr), __VA_ARGS__)
#define D_LOGF(namestr, ...) SPDLOG_LOGGER_CRITICAL(spdl::get(namestr), __VA_ARGS__)
#define D_DLOGT(...) SPDLOG_TRACE(__VA_ARGS__)
#define D_DLOGD(...) SPDLOG_DEBUG(__VA_ARGS__)
#define D_DLOGI(...) SPDLOG_INFO(__VA_ARGS__)
#define D_DLOGW(...) SPDLOG_WARN(__VA_ARGS__)
#define D_DLOGE(...) SPDLOG_ERROR(__VA_ARGS__)
#define D_DLOGF(...) SPDLOG_CRITICAL(__VA_ARGS__)
#elif defined(D_USING_PLOG)
// NOTE: Untested. Probably doesn't work.
#define D_LOG_DEFAULT(level, ...) PLOG_##level << fmt::format(__VA_ARGS__);
#define D_LOG(level, namestr, ...) PLOG_##level << namestr ": " << fmt::format(__VA_ARGS__);
#else
#define D_LOG(...)
#define D_LOG_DEFAULT(...)
#endif | 37.425 | 92 | 0.751503 | domenn |
6eaee1da4a9c9996e5d31d6381316472ce63e492 | 2,958 | cc | C++ | src/lib/eval/tests/dependency_unittest.cc | svenauhagen/kea | 8a575ad46dee1487364fad394e7a325337200839 | [
"Apache-2.0"
] | 2 | 2020-11-02T19:38:10.000Z | 2020-11-02T19:38:13.000Z | src/lib/eval/tests/dependency_unittest.cc | jxiaobin/kea | 1987a50a458921f9e5ac84cb612782c07f3b601d | [
"Apache-2.0"
] | null | null | null | src/lib/eval/tests/dependency_unittest.cc | jxiaobin/kea | 1987a50a458921f9e5ac84cb612782c07f3b601d | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <config.h>
#include <eval/dependency.h>
#include <eval/eval_context.h>
#include <eval/token.h>
#include <dhcp/pkt4.h>
#include <dhcp/pkt6.h>
#include <dhcp/dhcp4.h>
#include <dhcp/dhcp6.h>
#include <dhcp/option_string.h>
#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp>
#include <gtest/gtest.h>
using namespace std;
using namespace isc::dhcp;
namespace {
/// @brief Test fixture for testing dependency.
///
/// This class provides several convenience objects to be used during testing
/// of the dependcy of classification expressions.
class DependencyTest : public ::testing::Test {
public:
/// @brief Reset expression and result.
~DependencyTest() {
e_.reset();
result_ = false;
}
ExpressionPtr e_; ///< An expression
bool result_; ///< A decision
};
// This checks the null expression: it should return false.
TEST_F(DependencyTest, nullExpr) {
TokenPtr token;
ASSERT_NO_THROW(result_ = dependOnClass(token, "foobar"));
EXPECT_FALSE(result_);
ASSERT_NO_THROW(result_ = dependOnClass(e_, "foobar"));
EXPECT_FALSE(result_);
}
// This checks the empty expression: it should return false.
TEST_F(DependencyTest, emptyExpr) {
e_.reset(new Expression());
ASSERT_NO_THROW(result_ = dependOnClass(e_, "foobar"));
EXPECT_FALSE(result_);
}
// This checks the { "true" } expression: it should return false.
TEST_F(DependencyTest, trueExpr) {
TokenPtr ttrue;
ASSERT_NO_THROW(ttrue.reset(new TokenString("true")));
ASSERT_NO_THROW(result_ = dependOnClass(ttrue, "foobar"));
EXPECT_FALSE(result_);
e_.reset(new Expression());
e_->push_back(ttrue);
ASSERT_NO_THROW(result_ = dependOnClass(e_, "foobar"));
EXPECT_FALSE(result_);
}
// This checks the { member('not-matching') } expression:
// it should return false.
TEST_F(DependencyTest, notMatching) {
TokenPtr notmatching;
ASSERT_NO_THROW(notmatching.reset(new TokenMember("not-matching")));
ASSERT_NO_THROW(result_ = dependOnClass(notmatching, "foobar"));
EXPECT_FALSE(result_);
e_.reset(new Expression());
e_->push_back(notmatching);
ASSERT_NO_THROW(result_ = dependOnClass(e_, "foobar"));
EXPECT_FALSE(result_);
}
// This checks the { member('foobar') } expression: it should return true.
TEST_F(DependencyTest, matching) {
TokenPtr matching;
ASSERT_NO_THROW(matching.reset(new TokenMember("foobar")));
ASSERT_NO_THROW(result_ = dependOnClass(matching, "foobar"));
EXPECT_TRUE(result_);
e_.reset(new Expression());
e_->push_back(matching);
result_ = false;
ASSERT_NO_THROW(result_ = dependOnClass(e_, "foobar"));
EXPECT_TRUE(result_);
}
};
| 29.878788 | 77 | 0.707235 | svenauhagen |
6eafdf3962cc7ba4f332c235594b6d890a07ce85 | 51,637 | hpp | C++ | Tools/RegistersGenerator/STM32F303/FieldValues/dma2fieldvalues.hpp | snorkysnark/CortexLib | 0db035332ebdfbebf21ca36e5e04b78a5a908a49 | [
"MIT"
] | 22 | 2019-09-07T22:38:01.000Z | 2022-01-31T21:35:55.000Z | Tools/RegistersGenerator/STM32F303/FieldValues/dma2fieldvalues.hpp | snorkysnark/CortexLib | 0db035332ebdfbebf21ca36e5e04b78a5a908a49 | [
"MIT"
] | null | null | null | Tools/RegistersGenerator/STM32F303/FieldValues/dma2fieldvalues.hpp | snorkysnark/CortexLib | 0db035332ebdfbebf21ca36e5e04b78a5a908a49 | [
"MIT"
] | 9 | 2019-09-22T11:26:24.000Z | 2022-03-21T10:53:15.000Z | /*******************************************************************************
* Filename : dma2fieldvalues.hpp
*
* Details : Enumerations related with DMA2 peripheral. This header file is
* auto-generated for STM32F303 device.
*
*
*******************************************************************************/
#if !defined(DMA2ENUMS_HPP)
#define DMA2ENUMS_HPP
#include "fieldvalue.hpp" //for FieldValues
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_GIF1_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_GIF1_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_GIF1_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_TCIF1_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_TCIF1_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_TCIF1_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_HTIF1_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_HTIF1_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_HTIF1_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_TEIF1_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_TEIF1_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_TEIF1_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_GIF2_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_GIF2_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_GIF2_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_TCIF2_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_TCIF2_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_TCIF2_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_HTIF2_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_HTIF2_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_HTIF2_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_TEIF2_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_TEIF2_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_TEIF2_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_GIF3_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_GIF3_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_GIF3_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_TCIF3_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_TCIF3_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_TCIF3_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_HTIF3_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_HTIF3_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_HTIF3_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_TEIF3_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_TEIF3_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_TEIF3_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_GIF4_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_GIF4_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_GIF4_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_TCIF4_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_TCIF4_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_TCIF4_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_HTIF4_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_HTIF4_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_HTIF4_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_TEIF4_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_TEIF4_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_TEIF4_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_GIF5_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_GIF5_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_GIF5_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_TCIF5_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_TCIF5_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_TCIF5_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_HTIF5_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_HTIF5_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_HTIF5_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_TEIF5_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_TEIF5_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_TEIF5_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_GIF6_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_GIF6_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_GIF6_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_TCIF6_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_TCIF6_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_TCIF6_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_HTIF6_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_HTIF6_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_HTIF6_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_TEIF6_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_TEIF6_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_TEIF6_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_GIF7_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_GIF7_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_GIF7_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_TCIF7_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_TCIF7_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_TCIF7_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_HTIF7_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_HTIF7_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_HTIF7_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_ISR_TEIF7_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_ISR_TEIF7_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_ISR_TEIF7_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CGIF1_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CGIF1_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CGIF1_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CTCIF1_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CTCIF1_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CTCIF1_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CHTIF1_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CHTIF1_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CHTIF1_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CTEIF1_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CTEIF1_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CTEIF1_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CGIF2_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CGIF2_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CGIF2_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CTCIF2_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CTCIF2_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CTCIF2_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CHTIF2_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CHTIF2_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CHTIF2_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CTEIF2_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CTEIF2_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CTEIF2_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CGIF3_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CGIF3_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CGIF3_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CTCIF3_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CTCIF3_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CTCIF3_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CHTIF3_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CHTIF3_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CHTIF3_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CTEIF3_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CTEIF3_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CTEIF3_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CGIF4_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CGIF4_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CGIF4_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CTCIF4_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CTCIF4_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CTCIF4_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CHTIF4_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CHTIF4_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CHTIF4_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CTEIF4_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CTEIF4_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CTEIF4_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CGIF5_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CGIF5_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CGIF5_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CTCIF5_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CTCIF5_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CTCIF5_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CHTIF5_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CHTIF5_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CHTIF5_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CTEIF5_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CTEIF5_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CTEIF5_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CGIF6_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CGIF6_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CGIF6_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CTCIF6_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CTCIF6_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CTCIF6_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CHTIF6_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CHTIF6_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CHTIF6_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CTEIF6_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CTEIF6_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CTEIF6_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CGIF7_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CGIF7_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CGIF7_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CTCIF7_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CTCIF7_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CTCIF7_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CHTIF7_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CHTIF7_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CHTIF7_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_IFCR_CTEIF7_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_IFCR_CTEIF7_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_IFCR_CTEIF7_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR1_EN_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR1_EN_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR1_EN_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR1_TCIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR1_TCIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR1_TCIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR1_HTIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR1_HTIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR1_HTIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR1_TEIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR1_TEIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR1_TEIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR1_DIR_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR1_DIR_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR1_DIR_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR1_CIRC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR1_CIRC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR1_CIRC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR1_PINC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR1_PINC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR1_PINC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR1_MINC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR1_MINC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR1_MINC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR1_PSIZE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR1_PSIZE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR1_PSIZE_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR1_PSIZE_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR1_PSIZE_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR1_MSIZE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR1_MSIZE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR1_MSIZE_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR1_MSIZE_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR1_MSIZE_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR1_PL_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR1_PL_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR1_PL_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR1_PL_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR1_PL_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR1_MEM2MEM_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR1_MEM2MEM_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR1_MEM2MEM_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CNDTR1_NDT_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CPAR1_PA_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CMAR1_MA_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR2_EN_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR2_EN_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR2_EN_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR2_TCIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR2_TCIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR2_TCIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR2_HTIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR2_HTIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR2_HTIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR2_TEIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR2_TEIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR2_TEIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR2_DIR_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR2_DIR_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR2_DIR_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR2_CIRC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR2_CIRC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR2_CIRC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR2_PINC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR2_PINC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR2_PINC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR2_MINC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR2_MINC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR2_MINC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR2_PSIZE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR2_PSIZE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR2_PSIZE_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR2_PSIZE_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR2_PSIZE_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR2_MSIZE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR2_MSIZE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR2_MSIZE_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR2_MSIZE_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR2_MSIZE_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR2_PL_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR2_PL_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR2_PL_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR2_PL_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR2_PL_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR2_MEM2MEM_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR2_MEM2MEM_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR2_MEM2MEM_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CNDTR2_NDT_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CPAR2_PA_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CMAR2_MA_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR3_EN_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR3_EN_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR3_EN_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR3_TCIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR3_TCIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR3_TCIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR3_HTIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR3_HTIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR3_HTIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR3_TEIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR3_TEIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR3_TEIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR3_DIR_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR3_DIR_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR3_DIR_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR3_CIRC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR3_CIRC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR3_CIRC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR3_PINC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR3_PINC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR3_PINC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR3_MINC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR3_MINC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR3_MINC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR3_PSIZE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR3_PSIZE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR3_PSIZE_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR3_PSIZE_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR3_PSIZE_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR3_MSIZE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR3_MSIZE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR3_MSIZE_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR3_MSIZE_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR3_MSIZE_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR3_PL_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR3_PL_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR3_PL_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR3_PL_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR3_PL_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR3_MEM2MEM_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR3_MEM2MEM_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR3_MEM2MEM_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CNDTR3_NDT_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CPAR3_PA_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CMAR3_MA_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR4_EN_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR4_EN_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR4_EN_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR4_TCIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR4_TCIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR4_TCIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR4_HTIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR4_HTIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR4_HTIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR4_TEIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR4_TEIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR4_TEIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR4_DIR_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR4_DIR_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR4_DIR_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR4_CIRC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR4_CIRC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR4_CIRC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR4_PINC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR4_PINC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR4_PINC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR4_MINC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR4_MINC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR4_MINC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR4_PSIZE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR4_PSIZE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR4_PSIZE_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR4_PSIZE_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR4_PSIZE_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR4_MSIZE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR4_MSIZE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR4_MSIZE_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR4_MSIZE_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR4_MSIZE_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR4_PL_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR4_PL_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR4_PL_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR4_PL_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR4_PL_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR4_MEM2MEM_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR4_MEM2MEM_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR4_MEM2MEM_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CNDTR4_NDT_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CPAR4_PA_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CMAR4_MA_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR5_EN_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR5_EN_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR5_EN_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR5_TCIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR5_TCIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR5_TCIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR5_HTIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR5_HTIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR5_HTIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR5_TEIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR5_TEIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR5_TEIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR5_DIR_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR5_DIR_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR5_DIR_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR5_CIRC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR5_CIRC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR5_CIRC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR5_PINC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR5_PINC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR5_PINC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR5_MINC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR5_MINC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR5_MINC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR5_PSIZE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR5_PSIZE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR5_PSIZE_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR5_PSIZE_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR5_PSIZE_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR5_MSIZE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR5_MSIZE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR5_MSIZE_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR5_MSIZE_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR5_MSIZE_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR5_PL_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR5_PL_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR5_PL_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR5_PL_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR5_PL_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR5_MEM2MEM_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR5_MEM2MEM_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR5_MEM2MEM_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CNDTR5_NDT_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CPAR5_PA_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CMAR5_MA_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR6_EN_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR6_EN_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR6_EN_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR6_TCIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR6_TCIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR6_TCIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR6_HTIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR6_HTIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR6_HTIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR6_TEIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR6_TEIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR6_TEIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR6_DIR_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR6_DIR_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR6_DIR_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR6_CIRC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR6_CIRC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR6_CIRC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR6_PINC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR6_PINC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR6_PINC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR6_MINC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR6_MINC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR6_MINC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR6_PSIZE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR6_PSIZE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR6_PSIZE_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR6_PSIZE_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR6_PSIZE_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR6_MSIZE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR6_MSIZE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR6_MSIZE_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR6_MSIZE_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR6_MSIZE_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR6_PL_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR6_PL_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR6_PL_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR6_PL_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR6_PL_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR6_MEM2MEM_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR6_MEM2MEM_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR6_MEM2MEM_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CNDTR6_NDT_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CPAR6_PA_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CMAR6_MA_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR7_EN_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR7_EN_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR7_EN_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR7_TCIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR7_TCIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR7_TCIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR7_HTIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR7_HTIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR7_HTIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR7_TEIE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR7_TEIE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR7_TEIE_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR7_DIR_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR7_DIR_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR7_DIR_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR7_CIRC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR7_CIRC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR7_CIRC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR7_PINC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR7_PINC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR7_PINC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR7_MINC_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR7_MINC_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR7_MINC_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR7_PSIZE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR7_PSIZE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR7_PSIZE_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR7_PSIZE_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR7_PSIZE_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR7_MSIZE_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR7_MSIZE_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR7_MSIZE_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR7_MSIZE_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR7_MSIZE_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR7_PL_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR7_PL_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR7_PL_Values, BaseType, 1U> ;
using Value2 = FieldValue<DMA2_CCR7_PL_Values, BaseType, 2U> ;
using Value3 = FieldValue<DMA2_CCR7_PL_Values, BaseType, 3U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CCR7_MEM2MEM_Values: public RegisterField<Reg, offset, size, AccessMode>
{
using Value0 = FieldValue<DMA2_CCR7_MEM2MEM_Values, BaseType, 0U> ;
using Value1 = FieldValue<DMA2_CCR7_MEM2MEM_Values, BaseType, 1U> ;
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CNDTR7_NDT_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CPAR7_PA_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType>
struct DMA2_CMAR7_MA_Values: public RegisterField<Reg, offset, size, AccessMode>
{
} ;
#endif //#if !defined(DMA2ENUMS_HPP)
| 45.176728 | 92 | 0.77979 | snorkysnark |
6eb647f73cc60626fb0f350f18b6c837d8563a49 | 5,008 | cc | C++ | vs/src/model/ModifyGroupRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | vs/src/model/ModifyGroupRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | vs/src/model/ModifyGroupRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/vs/model/ModifyGroupRequest.h>
using AlibabaCloud::Vs::Model::ModifyGroupRequest;
ModifyGroupRequest::ModifyGroupRequest() :
RpcServiceRequest("vs", "2018-12-12", "ModifyGroup")
{
setMethod(HttpRequest::Method::Post);
}
ModifyGroupRequest::~ModifyGroupRequest()
{}
int ModifyGroupRequest::getCaptureVideo()const
{
return captureVideo_;
}
void ModifyGroupRequest::setCaptureVideo(int captureVideo)
{
captureVideo_ = captureVideo;
setParameter("CaptureVideo", std::to_string(captureVideo));
}
std::string ModifyGroupRequest::getDescription()const
{
return description_;
}
void ModifyGroupRequest::setDescription(const std::string& description)
{
description_ = description;
setParameter("Description", description);
}
bool ModifyGroupRequest::getEnabled()const
{
return enabled_;
}
void ModifyGroupRequest::setEnabled(bool enabled)
{
enabled_ = enabled;
setParameter("Enabled", enabled ? "true" : "false");
}
std::string ModifyGroupRequest::getCaptureOssPath()const
{
return captureOssPath_;
}
void ModifyGroupRequest::setCaptureOssPath(const std::string& captureOssPath)
{
captureOssPath_ = captureOssPath;
setParameter("CaptureOssPath", captureOssPath);
}
std::string ModifyGroupRequest::getPushDomain()const
{
return pushDomain_;
}
void ModifyGroupRequest::setPushDomain(const std::string& pushDomain)
{
pushDomain_ = pushDomain;
setParameter("PushDomain", pushDomain);
}
int ModifyGroupRequest::getCaptureImage()const
{
return captureImage_;
}
void ModifyGroupRequest::setCaptureImage(int captureImage)
{
captureImage_ = captureImage;
setParameter("CaptureImage", std::to_string(captureImage));
}
std::string ModifyGroupRequest::getId()const
{
return id_;
}
void ModifyGroupRequest::setId(const std::string& id)
{
id_ = id;
setParameter("Id", id);
}
std::string ModifyGroupRequest::getShowLog()const
{
return showLog_;
}
void ModifyGroupRequest::setShowLog(const std::string& showLog)
{
showLog_ = showLog;
setParameter("ShowLog", showLog);
}
std::string ModifyGroupRequest::getPlayDomain()const
{
return playDomain_;
}
void ModifyGroupRequest::setPlayDomain(const std::string& playDomain)
{
playDomain_ = playDomain;
setParameter("PlayDomain", playDomain);
}
std::string ModifyGroupRequest::getOutProtocol()const
{
return outProtocol_;
}
void ModifyGroupRequest::setOutProtocol(const std::string& outProtocol)
{
outProtocol_ = outProtocol;
setParameter("OutProtocol", outProtocol);
}
int ModifyGroupRequest::getCaptureInterval()const
{
return captureInterval_;
}
void ModifyGroupRequest::setCaptureInterval(int captureInterval)
{
captureInterval_ = captureInterval;
setParameter("CaptureInterval", std::to_string(captureInterval));
}
long ModifyGroupRequest::getOwnerId()const
{
return ownerId_;
}
void ModifyGroupRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setParameter("OwnerId", std::to_string(ownerId));
}
std::string ModifyGroupRequest::getInProtocol()const
{
return inProtocol_;
}
void ModifyGroupRequest::setInProtocol(const std::string& inProtocol)
{
inProtocol_ = inProtocol;
setParameter("InProtocol", inProtocol);
}
bool ModifyGroupRequest::getLazyPull()const
{
return lazyPull_;
}
void ModifyGroupRequest::setLazyPull(bool lazyPull)
{
lazyPull_ = lazyPull;
setParameter("LazyPull", lazyPull ? "true" : "false");
}
std::string ModifyGroupRequest::getName()const
{
return name_;
}
void ModifyGroupRequest::setName(const std::string& name)
{
name_ = name;
setParameter("Name", name);
}
std::string ModifyGroupRequest::getCallback()const
{
return callback_;
}
void ModifyGroupRequest::setCallback(const std::string& callback)
{
callback_ = callback;
setParameter("Callback", callback);
}
std::string ModifyGroupRequest::getRegion()const
{
return region_;
}
void ModifyGroupRequest::setRegion(const std::string& region)
{
region_ = region;
setParameter("Region", region);
}
std::string ModifyGroupRequest::getCaptureOssBucket()const
{
return captureOssBucket_;
}
void ModifyGroupRequest::setCaptureOssBucket(const std::string& captureOssBucket)
{
captureOssBucket_ = captureOssBucket;
setParameter("CaptureOssBucket", captureOssBucket);
}
| 21.964912 | 82 | 0.741014 | iamzken |
6eb8e526605af71564eb43da9d58f483a10d949e | 636 | cpp | C++ | practice2/client.cpp | MaxHonggg/professional_boost | 6fff73d3b9832644068dc8fe0443be813c7237b4 | [
"BSD-2-Clause"
] | 47 | 2016-05-20T08:49:47.000Z | 2022-01-03T01:17:07.000Z | practice2/client.cpp | MaxHonggg/professional_boost | 6fff73d3b9832644068dc8fe0443be813c7237b4 | [
"BSD-2-Clause"
] | null | null | null | practice2/client.cpp | MaxHonggg/professional_boost | 6fff73d3b9832644068dc8fe0443be813c7237b4 | [
"BSD-2-Clause"
] | 37 | 2016-07-25T04:52:08.000Z | 2022-02-14T03:55:08.000Z | // Copyright (c) 2016
// Author: Chrono Law
#include <std.hpp>
//using namespace std;
using std::cout;
using std::endl;
using std::vector;
using std::string;
#include <boost/asio.hpp>
using namespace boost;
using namespace boost::asio;
int main()
{
cout << "client start" << endl;
io_service ios;
ip::tcp::socket sock(ios);
ip::tcp::endpoint ep(
ip::address::from_string("127.0.0.1"), 6677);
sock.connect(ep);
string str("hello world");
sock.write_some(buffer(str));
vector<char> v(100, 0);
size_t n = sock.read_some(buffer(v));
cout << "recv "<< n << " :" << v.data() << endl;
};
| 19.272727 | 53 | 0.611635 | MaxHonggg |
6eba7e03dfbf14404f71672278184027b9ddb131 | 1,214 | cpp | C++ | 1_two_sum/1_two_sum.cpp | ttiimm2214/leetcode | 489c76bf374e2116bcac6ece5efe901db62a5ce1 | [
"MIT"
] | null | null | null | 1_two_sum/1_two_sum.cpp | ttiimm2214/leetcode | 489c76bf374e2116bcac6ece5efe901db62a5ce1 | [
"MIT"
] | null | null | null | 1_two_sum/1_two_sum.cpp | ttiimm2214/leetcode | 489c76bf374e2116bcac6ece5efe901db62a5ce1 | [
"MIT"
] | null | null | null | /*
* Leetcode 1 Two Sum
*
* Compile: g++ 1_two_sum.cpp -o result
* Execute: ./result
*/
// Given an array of integers, return indices of the two numbers such that they add up to a specific target.
//You may assume that each input would have exactly one solution, and you may not use the same element twice.
//Example:
//Given nums = [2, 7, 11, 15], target = 9,
//Because nums[0] + nums[1] = 2 + 7 = 9,
//return [0, 1].
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int main(){
//test case num = [2, 7, 11, 15] target = 9
vector<int> result;
vector<int> nums;
unordered_map<int,int> mapping;
int TARGET = 9;
int remain;
nums.push_back(2);
nums.push_back(7);
nums.push_back(11);
nums.push_back(15);
int SIZE = nums.size();
// solution
for (int i = 0; i < nums.size(); i++){
mapping[nums[i]]= i;
}
for(int i = 0; i < nums.size(); i++){
remain = TARGET - nums [i];
if (mapping.find(remain)!=mapping.end()&& mapping[remain] != i){
result.push_back(i);
result.push_back(mapping[remain]);
break;
}
}
// output for leetcode
// return result;
// output
for (int i = 0; i < result.size(); i++){
cout<< result [i]<< endl;
}
}
| 19.901639 | 109 | 0.62603 | ttiimm2214 |
6ebb7b44214339adb3e5ecfc9b4ff5b7746ff7cf | 2,372 | cc | C++ | power_manager/common/clock.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 5 | 2019-01-19T15:38:48.000Z | 2021-10-06T03:59:46.000Z | power_manager/common/clock.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2021-04-02T17:35:07.000Z | 2021-04-02T17:35:07.000Z | power_manager/common/clock.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2020-11-04T22:31:45.000Z | 2020-11-04T22:31:45.000Z | // Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "power_manager/common/clock.h"
#include <time.h>
namespace power_manager {
namespace {
// TODO(abhishekbh): Copied from Chrome's //base/time/time_now_posix.cc. Make
// upstream code available via libchrome and use it here:
// http://crbug.com/166153.
int64_t ConvertTimespecToMicros(const struct timespec& ts) {
// On 32-bit systems, the calculation cannot overflow int64_t.
// 2**32 * 1000000 + 2**64 / 1000 < 2**63
if (sizeof(ts.tv_sec) <= 4 && sizeof(ts.tv_nsec) <= 8) {
int64_t result = ts.tv_sec;
result *= base::Time::kMicrosecondsPerSecond;
result += (ts.tv_nsec / base::Time::kNanosecondsPerMicrosecond);
return result;
} else {
base::CheckedNumeric<int64_t> result(ts.tv_sec);
result *= base::Time::kMicrosecondsPerSecond;
result += (ts.tv_nsec / base::Time::kNanosecondsPerMicrosecond);
return result.ValueOrDie();
}
}
// TODO(abhishekbh): Copied from Chrome's //base/time/time_now_posix.cc. Make
// upstream code available via libchrome and use it here:
// http://crbug.com/166153.
// Returns count of |clk_id|. Retuns 0 if |clk_id| isn't present on the system.
int64_t ClockNow(clockid_t clk_id) {
struct timespec ts;
if (clock_gettime(clk_id, &ts) != 0) {
NOTREACHED() << "clock_gettime(" << clk_id << ") failed.";
return 0;
}
return ConvertTimespecToMicros(ts);
}
} // namespace
Clock::Clock() {}
Clock::~Clock() {}
base::TimeTicks Clock::GetCurrentTime() {
if (!current_time_for_testing_.is_null()) {
current_time_for_testing_ += time_step_for_testing_;
return current_time_for_testing_;
}
return base::TimeTicks::Now();
}
base::TimeTicks Clock::GetCurrentBootTime() {
if (!current_boot_time_for_testing_.is_null()) {
current_boot_time_for_testing_ += time_step_for_testing_;
return current_boot_time_for_testing_;
}
return base::TimeTicks() +
base::TimeDelta::FromMicroseconds(ClockNow(CLOCK_BOOTTIME));
}
base::Time Clock::GetCurrentWallTime() {
if (!current_wall_time_for_testing_.is_null()) {
current_wall_time_for_testing_ += time_step_for_testing_;
return current_wall_time_for_testing_;
}
return base::Time::Now();
}
} // namespace power_manager
| 31.210526 | 79 | 0.713744 | strassek |
6ebca9349b196a6c969ab88a9d8fcf7ba15d2933 | 2,764 | cc | C++ | usr/src/cmd/audio/utilities/AudioDebug.cc | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/cmd/audio/utilities/AudioDebug.cc | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/cmd/audio/utilities/AudioDebug.cc | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | 1 | 2020-12-30T00:04:16.000Z | 2020-12-30T00:04:16.000Z | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 1993-2001 by Sun Microsystems, Inc.
* All rights reserved.
*/
// XXX - all this either goes away or gets repackaged
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <AudioDebug.h>
// Global debugging level variable
int Audio_debug;
// Get debug level
int
GetDebug()
{
return (Audio_debug);
}
// Set debug level
void
SetDebug(
int val) // new level
{
Audio_debug = val;
}
// Default error printing routine
Boolean
AudioStderrMsg(
const Audio* cp, // object pointer
AudioError code, // error code
AudioSeverity sev, // error severity
const char *str) // additional message string
{
int id;
char *name;
id = cp->getid();
switch (sev) {
default:
name = cp->GetName();
break;
case InitMessage: // virtual function table not ready
case InitFatal:
name = cp->Audio::GetName();
break;
}
switch (sev) {
case InitMessage:
case Message:
if (Audio_debug > 1)
(void) fprintf(stderr, _MGET_("%d: %s (%s) %s\n"),
id, str, name, code.msg());
return (TRUE);
case Warning:
(void) fprintf(stderr, _MGET_("Warning: %s: %s %s\n"),
name, code.msg(), str);
if (Audio_debug > 2)
abort();
return (TRUE);
case Error:
(void) fprintf(stderr, _MGET_("Error: %s: %s %s\n"),
name, code.msg(), str);
if (Audio_debug > 1)
abort();
return (FALSE);
case Consistency:
(void) fprintf(stderr,
_MGET_("Audio Consistency Error: %s: %s %s\n"),
name, str, code.msg());
if (Audio_debug > 0)
abort();
return (FALSE);
case InitFatal:
case Fatal:
(void) fprintf(stderr,
_MGET_("Audio Internal Error: %s: %s %s\n"),
name, str, code.msg());
if (Audio_debug > 0)
abort();
return (FALSE);
}
return (TRUE);
}
#ifdef DEBUG
void
AudioDebugMsg(
int level,
char *fmt,
...)
{
va_list ap;
if (Audio_debug >= level) {
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
}
}
#endif
| 21.426357 | 70 | 0.662446 | AsahiOS |
6ec404498eb171bc328a030cf8df021cae51df05 | 8,477 | cpp | C++ | src/Texture.cpp | Derjik/VaubanEngine | 19792aeb7fe838c6b85d00270d15a2805f6fb9d5 | [
"0BSD"
] | 2 | 2018-10-09T14:31:12.000Z | 2018-10-26T08:47:59.000Z | src/Texture.cpp | Derjik/VaubanEngine | 19792aeb7fe838c6b85d00270d15a2805f6fb9d5 | [
"0BSD"
] | null | null | null | src/Texture.cpp | Derjik/VaubanEngine | 19792aeb7fe838c6b85d00270d15a2805f6fb9d5 | [
"0BSD"
] | null | null | null | #include <SDL2/SDL_render.h>
#include <VBN/Surface.hpp>
#include <VBN/Texture.hpp>
#include <VBN/Logging.hpp>
#include <VBN/Exceptions.hpp>
/*!
* The main constructor for this class is private, external callers should use
* the "from...()" factories instead.
*
* @param rawTexture SDL_Texture raw pointer to encapsulate in the internal
* std::unique_ptr (assuming ownership)
* @throws Exception nullptr passed for rawTexture parameter
*/
Texture::Texture(SDL_Texture * rawTexture) :
_rawTexture(rawTexture, &SDL_DestroyTexture),
_pixelFormat(0),
_access(0),
_width(0),
_height(0)
{
// Check input parameters
if(rawTexture == nullptr)
THROW(Exception, "Received nullptr 'rawTexture'");
// Acquire SDL_Texture metrics
SDL_QueryTexture(
_rawTexture.get(),
&_pixelFormat,
&_access,
&_width,
&_height);
// Add a special, "global" clip matching the whole surface
_clips.emplace("", SDL_Rect{ 0, 0, _width, _height });
// Log
VERBOSE(SDL_LOG_CATEGORY_APPLICATION,
"Build Texture %p (SDL_Texture %p)",
this,
_rawTexture.get());
}
Texture::Texture(Texture && other) :
_rawTexture(std::move(other._rawTexture)),
_clips(std::move(other._clips)),
_pixelFormat(std::move(other._pixelFormat)),
_access(std::move(other._access)),
_width(std::move(other._width)),
_height(std::move(other._height))
{
VERBOSE(SDL_LOG_CATEGORY_APPLICATION,
"Move Texture %p (SDL_Texture %p) into new Texture %p",
&other,
_rawTexture.get(),
this);
}
Texture & Texture::operator=(Texture && other)
{
//! @todo Leak check below
this->_rawTexture = std::move(other._rawTexture);
this->_clips = std::move(other._clips);
this->_pixelFormat = std::move(other._pixelFormat);
this->_access = std::move(other._access);
this->_width = std::move(other._width);
this->_height = std::move(other._height);
VERBOSE(SDL_LOG_CATEGORY_APPLICATION,
"Move (assign) Texture %p (SDL_Texture %p) into Texture %p",
&other,
_rawTexture.get(),
this);
return (*this);
}
Texture::~Texture(void)
{
VERBOSE(SDL_LOG_CATEGORY_APPLICATION,
"Delete Texture %p (SDL_Texture %p)",
this,
_rawTexture.get());
}
SDL_Texture * Texture::getSDLTexture(void)
{
return _rawTexture.get();
}
int Texture::getWidth(void) const
{
return _width;
}
int Texture::getHeight(void) const
{
return _height;
}
int Texture::getAccess(void) const
{
return _access;
}
Uint32 Texture::getPixelFormat(void) const
{
return _pixelFormat;
}
void Texture::setColorAlphaMod(SDL_Color const & color)
{
if(SDL_SetTextureColorMod(_rawTexture.get(),
color.r,
color.g,
color.b))
ERROR(SDL_LOG_CATEGORY_ERROR,
"Failed to set color and alpha : SDL error '%s'",
SDL_GetError());
}
SDL_Color Texture::getColorAlphaMod(void) const
{
SDL_Color rgba{0,0,0,0};
if(SDL_GetTextureColorMod(_rawTexture.get(),
&rgba.r,
&rgba.g,
&rgba.b))
ERROR(SDL_LOG_CATEGORY_ERROR,
"Failed to get color mod : SDL erorr '%s'",
SDL_GetError());
if(SDL_GetTextureAlphaMod(_rawTexture.get(),
&rgba.a))
ERROR(SDL_LOG_CATEGORY_ERROR,
"Failed to get alpha mod : SDL error '%s'",
SDL_GetError());
return rgba;
}
/*!
* @param ttfManager Shared reference on a valid TrueTypeFontManager from
* which to extract the TrueTypeFont to use
* @param renderer Raw pointer to the SDL_Renderer to use
* @param text Latin1-encoded string to print
* @param textFontName Font name
* @param textSize Font size
* @param textColor Font color
* @returns A newly created Texture instance containing the
* text render
* @throws Exception Invalid input parameters, Surface instantiation
* or conversion error
*/
Texture Texture::fromLatin1Text(
std::shared_ptr<TrueTypeFontManager> ttfManager,
SDL_Renderer * renderer,
std::string const & text,
std::string const & textFontName,
int const textSize,
SDL_Color const & textColor)
{
// Check input parameters
if (!ttfManager)
THROW(Exception, "Received nullptr 'ttfManager'");
if (renderer == nullptr)
THROW(Exception, "Received nullptr 'renderer'");
if (textFontName.empty())
THROW(Exception, "Received empty 'textFontName'");
if (textSize <= 0)
THROW(Exception, "Received textSize <= 0");
// Instantiate Text Surface
Surface textSurface(
Surface::fromLatin1Text(
ttfManager,
text,
textFontName,
textSize,
textColor));
// Attempt conversion to Texture
return Texture::fromSurface(renderer, textSurface);
}
/*!
* @param ttfManager Shared reference on a valid TrueTypeFontManager from
* which to extract the TrueTypeFont to use
* @param renderer Raw pointer to the SDL_Renderer to use
* @param text UTF-8-encoded string to print
* @param textFontName Font name
* @param textSize Font size
* @param textColor Font color
* @returns A newly created Texture instance containing the
* text render
* @throws Exception Invalid input parameters, Surface instantiation
* or conversion error
*/
Texture Texture::fromUTF8Text(
std::shared_ptr<TrueTypeFontManager> ttfManager,
SDL_Renderer * renderer,
std::string const & text,
std::string const & textFontName,
int const textSize,
SDL_Color const & textColor)
{
// Check input parameters
if (!ttfManager)
THROW(Exception, "Received nullptr 'ttfManager'");
if (renderer == nullptr)
THROW(Exception, "Received nullptr 'renderer'");
if (textFontName.empty())
THROW(Exception, "Received empty 'textFontName'");
if (textSize <= 0)
THROW(Exception, "Received textSize <= 0");
// Instantiate Text Surface
Surface textSurface(
Surface::fromUTF8Text(
ttfManager,
text,
textFontName,
textSize,
textColor));
// Attempt conversion to Texture
return Texture::fromSurface(renderer, textSurface);
}
/*!
* @param renderer Raw pointer to the SDL_Renderer to use
* @param surface Reference to the Surface instance to convert
* @returns A newly created Texture built from the input Surface
* contents
* @throws Exception Invalid input parameters or SDL_Surface to SDL_Texture
* conversion error
*/
Texture Texture::fromSurface(
SDL_Renderer * renderer,
Surface & surface)
{
// Check input parameters
if (renderer == nullptr)
THROW(Exception, "Received nullptr 'renderer'");
// Attempt SDL_Surface to SDL_Texture conversion
SDL_Texture * rawTexture =
SDL_CreateTextureFromSurface(renderer, surface.getSurface());
// Check for failure
if (rawTexture == nullptr)
THROW(Exception,
"Cannot instantiate SDL_Texture : SDL error '%s'",
SDL_GetError());
// Return encapsulated Texture
return Texture(rawTexture);
}
/*!
* @param renderer Raw pointer to the SDL_Renderer to use
* @param format Pixel format
* @param access Access mode
* @param width Width
* @param height Height
* @returns A blank Texture created from input parameters
* @throws Invalid input parameters or SDL error
*/
Texture Texture::fromScratch(
SDL_Renderer * renderer,
Uint32 const format,
int const access,
int const width,
int const height)
{
// Check input parameters
if (renderer == nullptr)
THROW(Exception, "Received nullptr 'renderer'");
if (width <= 0)
THROW(Exception, "Received 'width' <= 0");
if (height <= 0)
THROW(Exception, "Received 'height' <= 0");
// Attempt SDL_Texture creation from scratch
SDL_Texture * rawTexture = SDL_CreateTexture(
renderer,
format,
access,
width,
height);
// Check for failure
if(rawTexture == nullptr)
THROW(Exception,
"Cannot instantiate SDL_Texture : SDL error '%s'",
SDL_GetError());
// Return encapsulated Texture
return Texture(rawTexture);
}
/*!
* @param name Human-readable name to associate with the clipping
* rectangle
* @param clip SDL_Rect representing the clipping area
* @throws Exception Invalid input parameters
*/
void Texture::addClip(
std::string const & name,
SDL_Rect const & clip)
{
// Check input parameters
if (name.empty())
THROW(Exception, "Received empty 'name'");
if(_clips.find(name) != _clips.end())
THROW(Exception,
"Cannot override existing clip '%s'",
name);
// Store
_clips.emplace(name, clip);
}
/*!
* @param name Human-readable name of the wanted clip
* @returns Raw pointer to the SDL_Rect clip if it exists, nullptr
* otherwise
*/
SDL_Rect * Texture::getClip(std::string const & name)
{
// Clip lookup
auto clipIterator = _clips.find(name);
if (clipIterator == _clips.end()) /* Miss */
return nullptr;
else
return (&clipIterator->second); /* Hit */
} | 25.079882 | 78 | 0.712634 | Derjik |
6ec43651f8966c1614c10321433a605ce8824730 | 5,111 | cpp | C++ | Source/GUI/Qt/editsheet.cpp | kieranjol/MediaInfo-1 | f4e5ae0c009d59009e52bfb2094e04c4094c99d8 | [
"BSD-2-Clause"
] | 1 | 2017-12-16T20:49:14.000Z | 2017-12-16T20:49:14.000Z | Source/GUI/Qt/editsheet.cpp | kieranjol/MediaInfo-1 | f4e5ae0c009d59009e52bfb2094e04c4094c99d8 | [
"BSD-2-Clause"
] | null | null | null | Source/GUI/Qt/editsheet.cpp | kieranjol/MediaInfo-1 | f4e5ae0c009d59009e52bfb2094e04c4094c99d8 | [
"BSD-2-Clause"
] | null | null | null | /* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
#include "translate.h"
#include "editsheet.h"
#include "_Automated/ui_editsheet.h"
#include "sheet.h"
#include "columneditsheet.h"
#include "QtGui/QHBoxLayout"
#include "QtGui/QLabel"
#include "QtGui/QLineEdit"
#include "QtGui/QSpinBox"
#include "QtGui/QPushButton"
#include "QtGui/QToolButton"
#include "QtGui/QSizePolicy"
#include "QtGui/QComboBox"
EditSheet::EditSheet(Sheet* s, Core* C, QWidget *parent) :
QDialog(parent),
ui(new Ui::EditSheet)
{
ui->setupUi(this);
this->sheet = s;
this->C = C;
initDisplay();
refreshDisplay();
connect(ui->pushButton,SIGNAL(clicked()),SLOT(addColumn()));
ui->checkBoxAdapt->setChecked(s->getAdaptColumns());
}
EditSheet::~EditSheet()
{
delete ui;
}
void EditSheet::initDisplay() {
ui->lineEdit->setText(sheet->getName());
for(int i=0;i<sheet->getNbColumns();i++) {
ui->vboxLayout->addLayout(createColumn(sheet->getColumn(i)));
emit newPos(ui->vboxLayout->count());
}
ui->tableWidget->setRowCount(1);
}
void EditSheet::refreshDisplay() {
qDebug() << ui->vboxLayout->count() << " columns :";
ui->tableWidget->setColumnCount(ui->vboxLayout->count());
for(int i=0;i<ui->vboxLayout->count();++i) {
//column c = sheet->getColumn(i);
qDebug() << i << " : " << ((QLineEdit*)ui->vboxLayout->itemAt(i)->layout()->itemAt(0)->widget())->text();
if(!ui->checkBoxAdapt)
ui->tableWidget->setColumnWidth(i,((QSpinBox*)ui->vboxLayout->itemAt(i)->layout()->itemAt(1)->widget())->value());
if(ui->tableWidget->horizontalHeaderItem(i))
ui->tableWidget->horizontalHeaderItem(i)->setText(((QLineEdit*)ui->vboxLayout->itemAt(i)->layout()->itemAt(0)->widget())->text());
else {
QTableWidgetItem* header = new QTableWidgetItem(((QLineEdit*)ui->vboxLayout->itemAt(i)->layout()->itemAt(0)->widget())->text());
ui->tableWidget->setHorizontalHeaderItem(i,header);
}
}
if(ui->checkBoxAdapt)
ui->tableWidget->resizeColumnsToContents();
}
QLayout* EditSheet::createColumn(column c) {
ColumnEditSheet* col = new ColumnEditSheet(c,ui->vboxLayout->count(),ui->vboxLayout->count()+1,C);
connect(col,SIGNAL(somethingChanged()),SLOT(refreshDisplay()));
connect(col,SIGNAL(moveMeUp(int)),SLOT(upCol(int)));
connect(col,SIGNAL(moveMeDown(int)),SLOT(downCol(int)));
connect(col,SIGNAL(removeMe(int)),SLOT(delCol(int)));
connect(this,SIGNAL(switchPos(int,int,int)),col,SLOT(posSwitched(int,int,int)));
connect(this,SIGNAL(deletePos(int,int)),col,SLOT(posRemoved(int,int)));
connect(this,SIGNAL(newPos(int)),col,SLOT(posChanged(int)));
connect(ui->checkBoxAdapt,SIGNAL(toggled(bool)),col->widthBox(),SLOT(setDisabled(bool)));
col->widthBox()->setDisabled(ui->checkBoxAdapt->isChecked());
#if QT_VERSION >= 0x403000
col->setContentsMargins(0,0,0,0);
#endif
col->setSpacing(0);
col->setMargin(0);
return col;
}
void EditSheet::upCol(int i) {
if(i>0) {
ui->vboxLayout->insertLayout(i-1,((QLayout*)ui->vboxLayout->takeAt(i)));
emit switchPos(i,i-1,ui->vboxLayout->count());
}
}
void EditSheet::downCol(int i) {
if(i<ui->vboxLayout->count()-1) {
ui->vboxLayout->insertLayout(i+1,((QLayout*)ui->vboxLayout->takeAt(i)));
emit switchPos(i,i+1,ui->vboxLayout->count());
}
}
void EditSheet::delCol(int i) {
ColumnEditSheet* c = (ColumnEditSheet*)ui->vboxLayout->takeAt(i);
delete c;
emit deletePos(i,ui->vboxLayout->count());
}
void EditSheet::addColumn() {
column c;
c.name = Tr("CompleteName");
c.width = 50;
c.stream = Stream_General;
c.key = "CompleteName";
ui->vboxLayout->addLayout(createColumn(c));
emit newPos(ui->vboxLayout->count());
refreshDisplay();
}
void EditSheet::changeEvent(QEvent *e)
{
QDialog::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void EditSheet::apply() {
sheet->resetColumns();
for(int i=0;i<ui->vboxLayout->count();++i) {
column c;
c.name = ((QLineEdit*)ui->vboxLayout->itemAt(i)->layout()->itemAt(0)->widget())->text();
c.width = ((QSpinBox*)ui->vboxLayout->itemAt(i)->layout()->itemAt(1)->widget())->value();
c.stream = (stream_t)((QComboBox*)ui->vboxLayout->itemAt(i)->layout()->itemAt(2)->widget())->itemData(((QComboBox*)ui->vboxLayout->itemAt(i)->layout()->itemAt(2)->widget())->currentIndex()).toInt();
c.key = ((QComboBox*)ui->vboxLayout->itemAt(i)->layout()->itemAt(3)->widget())->itemData(((QComboBox*)ui->vboxLayout->itemAt(i)->layout()->itemAt(3)->widget())->currentIndex()).toString();
sheet->addColumn(c);
}
sheet->setName(ui->lineEdit->text().toStdString().c_str());
sheet->setAdaptColumns(ui->checkBoxAdapt->isChecked());
}
| 34.768707 | 206 | 0.643514 | kieranjol |
6ec447129489d64b92aeb18f535e9c5e18325ffa | 7,132 | cpp | C++ | kernel/process/thread.cpp | USN484259/COFUOS | a751c3ab1a24f634ae33b5ddced55c184c8f9381 | [
"MIT"
] | 1 | 2022-03-03T09:57:56.000Z | 2022-03-03T09:57:56.000Z | kernel/process/thread.cpp | USN484259/COFUOS | a751c3ab1a24f634ae33b5ddced55c184c8f9381 | [
"MIT"
] | null | null | null | kernel/process/thread.cpp | USN484259/COFUOS | a751c3ab1a24f634ae33b5ddced55c184c8f9381 | [
"MIT"
] | 1 | 2022-01-22T14:19:24.000Z | 2022-01-22T14:19:24.000Z | #include "thread.hpp"
#include "core_state.hpp"
#include "constant.hpp"
#include "memory/include/vm.hpp"
#include "process.hpp"
#include "pe64.hpp"
#include "dev/include/timer.hpp"
#include "lock_guard.hpp"
#include "assert.hpp"
using namespace UOS;
id_gen<dword> thread::new_id;
//initial thread
thread::thread(initial_thread_tag, process* p) : id(new_id()), state(RUNNING), critical(0), priority(scheduler::kernel_priority), slice(scheduler::max_slice), ps(p) {
assert(ps && id == 0);
krnl_stk_top = 0; //???
krnl_stk_reserved = pe_kernel->stk_reserve;
}
thread::thread(process* p, procedure entry, const qword* args, qword stk_size) : id(new_id()), state(READY), critical(0), priority(this_core().this_thread()->get_priority()), slice(scheduler::max_slice), ps(p), krnl_stk_reserved(align_down(stk_size,PAGE_SIZE)) {
IF_assert;
assert(ps && krnl_stk_reserved >= PAGE_SIZE);
lock_guard<spin_lock> guard(objlock);
auto va = vm.reserve(0,2 + krnl_stk_reserved/PAGE_SIZE);
if (!va)
bugcheck("vm.reserve failed with 0x%x pages",krnl_stk_reserved);
krnl_stk_top = va + PAGE_SIZE + krnl_stk_reserved;
auto res = vm.commit(krnl_stk_top - PAGE_SIZE,1);
if (!res)
bugcheck("vm.commit failed @ %p",krnl_stk_top - PAGE_SIZE);
gpr.rbp = krnl_stk_top;
gpr.rsp = krnl_stk_top - 0x30;
gpr.ss = SEG_KRNL_SS;
gpr.cs = SEG_KRNL_CS;
gpr.rip = reinterpret_cast<qword>(entry);
gpr.rflags = 0x202; //IF
gpr.rcx = args[0];
gpr.rdx = args[1];
gpr.r8 = args[2];
gpr.r9 = args[3];
#ifdef PS_TEST
dbgprint("new thread $%d @ %p",id,this);
#endif
ready_queue.put(this);
}
thread::~thread(void){
if (state != STOPPED)
bugcheck("deleting non-stop thread #%d @ %p",id,this);
// if (hold_lock)
// bugcheck("deleting thread #%d @ %p while holding lock %x",id,this,hold_lock);
#ifdef PS_TEST
dbgprint("deleted thread #%d @ %p",id,this);
#endif
if (sse){
//flush FPU state from this core
this_core core;
if (core.fpu_owner() == this){
core.fpu_owner(nullptr);
}
//TODO remove FPU context from all processor core
delete sse;
}
if (user_stk_top){
// if (!get_process()->vspace->release(user_stk_top - user_stk_reserved - PAGE_SIZE,1 + user_stk_reserved/PAGE_SIZE))
// bugcheck("vspace->release failed @ %p",user_stk_top - user_stk_reserved);
get_process()->vspace->release(user_stk_top - user_stk_reserved - PAGE_SIZE,1 + user_stk_reserved/PAGE_SIZE);
}
if (!vm.release(krnl_stk_top - krnl_stk_reserved - PAGE_SIZE,2 + krnl_stk_reserved/PAGE_SIZE))
bugcheck("vm.release failed @ %p",krnl_stk_top - krnl_stk_reserved);
}
REASON thread::wait(qword us,wait_callback func){
if (state == STOPPED){
if (func){
func();
}
return PASSED;
}
return waitable::wait(us,func);
}
bool thread::set_priority(byte val){
if (val >= scheduler::max_priority)
return false;
priority = val;
return true;
}
bool thread::set_state(thread::STATE st, qword arg, waitable* obj){
IF_assert;
assert(objlock.is_locked());
if (state == STOPPED){
return false;
}
switch(st){
case READY:
if (state == WAITING){
//arg as reason
switch(arg){
case REASON::ABANDON:
assert(wait_for);
wait_for->cancel(this);
//fall through
case REASON::NOTIFY:
assert(wait_for);
if (timer_ticket)
timer.cancel(timer_ticket);
break;
case REASON::TIMEOUT:
assert(timer_ticket);
if (wait_for)
wait_for->cancel(this);
break;
default:
assert(false);
}
reason = (REASON)arg;
wait_for = nullptr;
timer_ticket = 0;
}
break;
case RUNNING:
assert(state == READY);
break;
case WAITING:
assert(state == RUNNING);
//arg as timer_ticket, obj as wait_for
assert(arg || obj);
assert(wait_for == nullptr && timer_ticket == 0);
wait_for = obj;
timer_ticket = arg;
break;
default:
bugcheck("thread::set_state bad state @ %p",this);
}
state = st;
return true;
}
bool thread::relax(void){
interrupt_guard<void> ig;
auto res = waitable::relax();
if (!res){
ps->erase(this);
}
return res;
}
void thread::manage(void*){
IF_assert;
waitable::manage();
++ref_count;
assert(ref_count == 2);
}
void thread::on_stop(void){
IF_assert;
assert(objlock.is_locked());
assert(state == thread::STOPPED);
assert(wait_for == nullptr && timer_ticket == 0);
/*
if (hold_lock){
if (hold_lock & HOLD_VSPACE){
auto vspace = get_process()->vspace;
assert(vspace->is_locked() && !vspace->is_exclusive());
vspace->unlock();
}
if (hold_lock & HOLD_HANDLE){
auto& ht = get_process()->handles;
assert(ht.is_locked() && !ht.is_exclusive());
ht.unlock();
}
hold_lock = 0;
}
*/
gc.put(this);
objlock.unlock();
}
void thread::on_gc(void){
interrupt_guard<spin_lock> guard(objlock);
guard.drop();
notify();
ps->on_exit();
relax();
}
void thread::save_sse(void){
if (!sse){
sse = new SSE_context;
}
assert((qword)sse == align_down((qword)sse, sizeof(sse)));
fxsave(sse);
}
void thread::load_sse(void){
if (sse){
fxrstor(sse);
}
else{
fpu_init();
}
}
void thread::hold(void){
interrupt_guard<spin_lock> guard(objlock);
assert(critical == 0);
critical = CRITICAL;
}
void thread::drop(void){
{
interrupt_guard<spin_lock> guard(objlock);
assert(critical & CRITICAL);
critical &= ~CRITICAL;
if (0 == (critical & KILL))
return;
assert(state == RUNNING);
state = STOPPED;
}
interrupt_guard<void> ig;
core_manager::preempt(true);
bugcheck("failed to escape @ %p",this);
}
void thread::sleep(qword us){
this_core core;
thread* this_thread = core.this_thread();
interrupt_guard<void> ig;
if (this_thread->has_context())
bugcheck("sleep called in IRQ @ %p",this_thread);
if (us == 0){
this_thread->put_slice(scheduler::max_slice);
core_manager::preempt(true);
return;
}
thread* next_thread;
bool need_gc = false;
do{
next_thread = ready_queue.get();
if (!next_thread)
bugcheck("no ready thread");
next_thread->lock();
if (next_thread->set_state(thread::RUNNING))
break;
next_thread->on_stop();
need_gc = true;
}while(true);
if (need_gc)
gc.signal();
this_thread->lock();
auto ticket = timer.wait(us,on_timer,this_thread);
if (!this_thread->set_state(thread::WAITING,ticket,nullptr)){
timer.cancel(ticket);
}
this_thread->unlock();
core.switch_to(next_thread);
}
void thread::kill(thread* th){
#ifdef PS_TEST
dbgprint("killing thread %d @ %p",th->id,th);
#endif
this_core core;
thread* this_thread = core.this_thread();
bool kill_self = (this_thread == th);
interrupt_guard<void> ig;
{
lock_guard<thread> guard(*th);
if (th->critical & CRITICAL){
assert(this_thread != th);
th->critical |= KILL;
return;
}
//th->set_state(STOPPED);
auto state = th->state;
th->state = STOPPED;
assert(!kill_self || state == RUNNING);
if (state == WAITING){
if (th->wait_for){
th->wait_for->cancel(th);
th->wait_for = nullptr;
}
if (th->timer_ticket){
timer.cancel(th->timer_ticket);
th->timer_ticket = 0;
}
if (!kill_self){
guard.drop();
th->on_stop();
gc.signal();
}
}
}
if (kill_self){
core_manager::preempt(true);
bugcheck("failed to escape @ %p",th);
}
}
| 23.23127 | 262 | 0.671761 | USN484259 |
6ec5ebf72f798a370e0143c6238fdf7759f09726 | 1,346 | cpp | C++ | src/test_distribution.cpp | inesc-tec-robotics/carlos_controller | ffcc45f24dd534bb953d5bd4a47badd3d3d5223d | [
"BSD-3-Clause"
] | null | null | null | src/test_distribution.cpp | inesc-tec-robotics/carlos_controller | ffcc45f24dd534bb953d5bd4a47badd3d3d5223d | [
"BSD-3-Clause"
] | null | null | null | src/test_distribution.cpp | inesc-tec-robotics/carlos_controller | ffcc45f24dd534bb953d5bd4a47badd3d3d5223d | [
"BSD-3-Clause"
] | null | null | null |
#include <mission_ctrl_msgs/generateStudDistributionAction.h>
#include <mission_ctrl_msgs/mission_ctrl_defines.h>
#include <actionlib/client/simple_action_client.h>
typedef actionlib::SimpleActionClient<mission_ctrl_msgs::generateStudDistributionAction> Client;
void finishedHnd(const actionlib::SimpleClientGoalState& state,
const mission_ctrl_msgs::generateStudDistributionResultConstPtr& result)
{
fprintf(stdout, "Action finished in state %s\n", state.toString().c_str());
fprintf(stdout, "Error: %s\n", result->error_string.c_str());
for(int i=0; i<result->positions.size(); i++){
fprintf(stdout, "/tasks/test_task/studs/stud_%d/x: %f\n", i+1, result->positions[i].x);
fprintf(stdout, "/tasks/test_task/studs/stud_%d/y: %f\n", i+1, result->positions[i].y);
}
ros::shutdown();
}
void activeHnd()
{
fprintf(stdout, "Goal active\n");
}
void feedbackHnd(const mission_ctrl_msgs::generateStudDistributionFeedbackConstPtr& feedback)
{
fprintf(stdout, "Feedback executed\n");
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "test_generate_distribution");
Client client(CARLOS_DISTRIBUTION_ACTION, true);
client.waitForServer();
mission_ctrl_msgs::generateStudDistributionGoal goal;
goal.side = 1;
client.sendGoal(goal, &finishedHnd, &activeHnd, &feedbackHnd);
ros::spin();
return 0;
}
| 28.638298 | 96 | 0.746657 | inesc-tec-robotics |
6ecad6eb9fe81c9b4f19eb409116b3f286fb4bd7 | 1,062 | cpp | C++ | PlayerData.cpp | GracefulComet/Graceful-Engine | cc3e4dd6da0a13904d062ebbc21c198c8b42aac6 | [
"MIT"
] | null | null | null | PlayerData.cpp | GracefulComet/Graceful-Engine | cc3e4dd6da0a13904d062ebbc21c198c8b42aac6 | [
"MIT"
] | null | null | null | PlayerData.cpp | GracefulComet/Graceful-Engine | cc3e4dd6da0a13904d062ebbc21c198c8b42aac6 | [
"MIT"
] | null | null | null | #include "PlayerData.h"
PlayerMSG::PlayerMSG(PlayerAction action, ID target, ID sender )
:msg(target,sender,MSGTYPE::Player) {
m_action = action;
}
void PlayerMSG::update(void* Variables){
auto &mybod = *reinterpret_cast<b2Body*>(Variables);
switch( m_action){
case PlayerAction::Idle:
break;
case PlayerAction::WalkLeft :
mybod.ApplyLinearImpulse( b2Vec2(-500,0), mybod.GetWorldCenter(), true);
mybod.ApplyForce( b2Vec2(-500000,0), mybod.GetWorldCenter(), true);
break;
case PlayerAction::WalkRight:
mybod.ApplyLinearImpulse( b2Vec2(500 ,0), mybod.GetWorldCenter(), true);
mybod.ApplyForce( b2Vec2(500000, 0), mybod.GetWorldCenter(), true);
break;
case PlayerAction::Jump:
mybod.ApplyLinearImpulse( b2Vec2(0,-50000), mybod.GetWorldCenter(), true);
mybod.ApplyLinearImpulse( b2Vec2(0,-50000), mybod.GetWorldCenter(), true);
mybod.ApplyLinearImpulse( b2Vec2(0,-50000), mybod.GetWorldCenter(), true);
break;
case PlayerAction::Crouch:
break;
case PlayerAction::SlowToStop:
break;
default :
break;
}
}
| 22.125 | 76 | 0.720339 | GracefulComet |
6ecae98fe9c4d2ee70fbbef1b6186b1fc18708bb | 5,758 | cpp | C++ | src/3rdParty/ogdf-2020/src/ogdf/basic/graph_generators/deterministic.cpp | MichaelTiernan/qvge | aff978d8592e07e24af4b8bab7c3204a7e7fb3fb | [
"MIT"
] | 3 | 2021-09-14T08:11:37.000Z | 2022-03-04T15:42:07.000Z | src/3rdParty/ogdf-2020/src/ogdf/basic/graph_generators/deterministic.cpp | MichaelTiernan/qvge | aff978d8592e07e24af4b8bab7c3204a7e7fb3fb | [
"MIT"
] | 2 | 2021-12-04T17:09:53.000Z | 2021-12-16T08:57:25.000Z | src/3rdParty/ogdf-2020/src/ogdf/basic/graph_generators/deterministic.cpp | MichaelTiernan/qvge | aff978d8592e07e24af4b8bab7c3204a7e7fb3fb | [
"MIT"
] | 2 | 2021-06-22T08:21:54.000Z | 2021-07-07T06:57:22.000Z | /** \file
* \brief Implementation of some graph generators
*
* \author Carsten Gutwenger, Markus Chimani
*
* \par License:
* This file is part of the Open Graph Drawing Framework (OGDF).
*
* \par
* Copyright (C)<br>
* See README.md in the OGDF root directory for details.
*
* \par
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* Version 2 or 3 as published by the Free Software Foundation;
* see the file LICENSE.txt included in the packaging of this file
* for details.
*
* \par
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* \par
* You should have received a copy of the GNU General Public
* License along with this program; if not, see
* http://www.gnu.org/copyleft/gpl.html
*/
#include <ogdf/basic/graph_generators/deterministic.h>
#include <ogdf/basic/simple_graph_alg.h>
#include <ogdf/basic/CombinatorialEmbedding.h>
#include <ogdf/basic/FaceArray.h>
#include <ogdf/basic/extended_graph_alg.h>
#include <ogdf/basic/Array2D.h>
#include <ogdf/basic/geometry.h>
#include <ogdf/basic/Math.h>
#include <ogdf/planarity/PlanarizationGridLayout.h>
#include <ogdf/planarlayout/SchnyderLayout.h>
using std::minstd_rand;
using std::uniform_int_distribution;
using std::uniform_real_distribution;
namespace ogdf {
void customGraph(Graph &G, int n, List<std::pair<int,int>> edges, Array<node> &nodes)
{
nodes.init(n);
G.clear();
for (int i = 0; i < n; i++) {
nodes[i] = G.newNode();
}
for (auto e : edges) {
G.newEdge(nodes[std::get<0>(e)], nodes[std::get<1>(e)]);
}
}
void circulantGraph(Graph &G, int n, Array<int> jumps)
{
G.clear();
Array<node> nodes(n);
for (int i=0; i<n; i++) {
nodes[i] = G.newNode();
}
Array2D<bool> buildEdge(0,n-1,0,n-1,false);
auto pos_modulo = [&n](int i) {return (i % n + n) % n;};
for (int s: jumps) {
for (int i=0; i<n; i++) {
buildEdge(i, pos_modulo(i+s)) = true;
buildEdge(i, pos_modulo(i-s)) = true;
}
}
for (int i=0; i<n; i++) {
for (int j=i; j<n; j++) {
if (buildEdge(i,j)) {
G.newEdge(nodes[i], nodes[j]);
}
}
}
}
void regularTree(Graph& G, int n, int children)
{
G.clear();
node* id2node = new node[n];
id2node[0] = G.newNode();
for(int i=1; i<n; i++) {
G.newEdge(id2node[(i-1)/children], id2node[i] = G.newNode());
}
delete[] id2node;
}
void completeGraph(Graph &G, int n)
{
G.clear();
Array<node> v(n);
int i,j;
for(i = n; i-- > 0;)
v[i] = G.newNode();
for(i = n; i-- > 0;)
for(j = i; j-- > 0;)
G.newEdge(v[i],v[j]);
}
void completeKPartiteGraph(Graph &G, const Array<int> &signature)
{
G.clear();
if (signature.size() <= 0) {
return;
}
Array<Array<node>> partitions(signature.size());
// generate nodes in partitions
for (int i = 0; i < partitions.size(); ++i) {
OGDF_ASSERT(signature[i] > 0);
partitions[i].init(signature[i]);
for (int j = 0; j < signature[i]; ++j) {
partitions[i][j] = G.newNode();
}
}
// generate edges
for (int i = 0; i < partitions.size(); ++i) {
for (node u : partitions[i]) {
for (int j = i+1; j < partitions.size(); ++j) {
for (node v : partitions[j]) {
G.newEdge(u, v);
}
}
}
}
}
void completeBipartiteGraph(Graph &G, int n, int m)
{
completeKPartiteGraph(G, {n, m});
}
void wheelGraph(Graph &G, int n)
{
G.clear();
if (n <= 2) return;
node center = G.newNode();
node n0 = nullptr;
node n1 = nullptr;
while (n--) {
node n2 = G.newNode();
G.newEdge(center, n2);
if (n1)
G.newEdge(n1, n2);
else
n0 = n2;
n1 = n2;
}
G.newEdge(n1, n0);
}
void suspension(Graph &G, int n)
{
if(n == 0) return;
OGDF_ASSERT( n>0 );
List<node> nds;
G.allNodes(nds);
while (n--) {
node n0 = G.newNode();
for(node v : nds)
G.newEdge(n0,v);
}
}
void cubeGraph(Graph &G, int n)
{
OGDF_ASSERT(n >= 0);
OGDF_ASSERT(n < 8*(int)sizeof(int)-1); // one sign bit, one less to be safe
G.clear();
int c = 1 << n;
Array<node> lu(c);
for(int i=0; i<c; ++i) {
lu[i] = G.newNode();
int q = 1;
while( q <= i ) {
if(q&i) G.newEdge(lu[i^q],lu[i]);
q <<= 1;
}
}
}
void gridGraph(Graph &G, int n, int m, bool loopN, bool loopM)
{
G.clear();
Array<node> front(0,n-1,nullptr);
Array<node> fringe(0,n-1,nullptr);
node first = nullptr;
node last = nullptr;
node cur;
for(int j = m; j-- > 0;) {
for(int i = n; i-- > 0;) {
cur = G.newNode();
if(!last) first=cur;
else G.newEdge(last,cur);
if(fringe[i]) G.newEdge(fringe[i],cur);
else front[i] = cur;
fringe[i] = cur;
last = cur;
}
if(loopN)
G.newEdge(last, first);
last = nullptr;
}
if(loopM) {
for(int i = n; i-- > 0;) {
G.newEdge(fringe[i],front[i]);
}
}
}
void petersenGraph(Graph &G, int n, int m)
{
G.clear();
Array<node> inner(0, n-1, nullptr);
node first = nullptr;
node last = nullptr;
for(int i = n; i-- > 0;) {
node outn = G.newNode();
node inn = G.newNode();
G.newEdge(outn,inn);
inner[i]=inn;
if(!last) first=outn;
else G.newEdge(last,outn);
last = outn;
}
G.newEdge(last, first);
for(int i = n; i-- > 0;) {
G.newEdge(inner[i],inner[(i+m)%n]);
}
}
void regularLatticeGraph(Graph &G, int n, int k)
{
OGDF_ASSERT(n >= 4); // For a circle with all even degrees, we need at least four nodes.
OGDF_ASSERT(k > 0);
OGDF_ASSERT(k <= n-2);
OGDF_ASSERT(k % 2 == 0);
Array<int> jumps = Array<int>(k/2);
for (int i = 0; i < k/2; i++) {
jumps[i] = i+1;
}
circulantGraph(G, n, jumps);
}
void emptyGraph(Graph &G, int nodes)
{
G.clear();
for (int i = 0; i < nodes; i++) {
G.newNode();
}
}
}
| 20.062718 | 89 | 0.609934 | MichaelTiernan |
6ed0caefcd0ab8aff75867a73e480389777cb7e1 | 1,095 | hpp | C++ | device-manager.hpp | KeyboxWallet/keyboxd | 67c9103aaf48d5e83c922311acf5a4deab8c0755 | [
"MIT"
] | 2 | 2018-11-26T10:40:46.000Z | 2019-05-30T05:30:01.000Z | device-manager.hpp | KeyboxWallet/keyboxd | 67c9103aaf48d5e83c922311acf5a4deab8c0755 | [
"MIT"
] | null | null | null | device-manager.hpp | KeyboxWallet/keyboxd | 67c9103aaf48d5e83c922311acf5a4deab8c0755 | [
"MIT"
] | 1 | 2018-10-16T10:17:23.000Z | 2018-10-16T10:17:23.000Z | #ifndef _KEYBOX_DEVICE_MANAGER_INCLUDE_
#define _KEYBOX_DEVICE_MANAGER_INCLUDE_
#include "base-device.hpp"
#define KEYBOX2_VENDOR_ID 0xb6ab
#define KEYBOX2_PRODUCT_ID 0xbaeb
#define KEYBOX2_BCD_DEVICE 0x0001
#include <boost/asio.hpp>
#include <set>
class DeviceEventListener {
public:
virtual void deviceAdded(BaseDevice *) = 0;
virtual void deviceRemoved(const std::string &dev_id) = 0;
};
class DeviceManager {
public:
static DeviceManager * getDeviceManager(boost::asio::io_context *ioc);
BaseDevice * getDeviceById(const std::string &id );
std::vector<BaseDevice*> deviceList();
void addDevice(BaseDevice *);
void rmDevice(BaseDevice *);
void registerEventListener(DeviceEventListener *listener);
void unRegisterEventListener(DeviceEventListener *listener);
private:
boost::asio::io_context * mContext;
explicit DeviceManager(boost::asio::io_context *ioc);
std::map<std::string, BaseDevice *> mDeviceMaps;
std::set<DeviceEventListener *> mListeners;
boost::asio::steady_timer *mTimer;
void enumerateUsbDevice();
};
#endif
| 27.375 | 74 | 0.750685 | KeyboxWallet |
6ed55ed03b8a725a0e8cfa7a7481e4645e53f254 | 109,294 | cpp | C++ | src/Exciton/PaintingSecrets/nPaintingSecretGui.cpp | Vladimir-Lin/QtExciton | ac5bc82f22ac3cdcdccb90526f7dd79060535b5a | [
"MIT"
] | null | null | null | src/Exciton/PaintingSecrets/nPaintingSecretGui.cpp | Vladimir-Lin/QtExciton | ac5bc82f22ac3cdcdccb90526f7dd79060535b5a | [
"MIT"
] | null | null | null | src/Exciton/PaintingSecrets/nPaintingSecretGui.cpp | Vladimir-Lin/QtExciton | ac5bc82f22ac3cdcdccb90526f7dd79060535b5a | [
"MIT"
] | null | null | null | #include <exciton.h>
///////////////////////////////////////////////////////////////////////////////
#define DEBUGPAINTING
#ifdef DEBUGPAINTING
#define XDEBUG(msg) if (plan->Verbose>=90) plan -> Debug ( msg)
#else
#define XDEBUG(msg)
#endif
///////////////////////////////////////////////////////////////////////////////
typedef struct {
int Id ;
char * Path ;
} LocaleDirectory ;
#pragma message("PaintingSecretGui LocaleDirectory requires some fix up")
LocaleDirectory LocaleDirectories[4096] ;
void * psLocaleDirectories = (void *)LocaleDirectories ;
static bool LidTo(int Id,QString & LC)
{
int i = 0 ;
while (LocaleDirectories[i].Id!=0) {
if (Id==LocaleDirectories[i].Id) {
LC = LocaleDirectories[i].Path ;
return true ;
} ;
i++ ;
} ;
return false ;
}
N::PaintingSecretGui:: PaintingSecretGui ( QWidget * parent , Plan * p )
: Splitter ( Qt::Vertical , parent , p )
, header ( NULL )
, stack ( NULL )
, menu ( NULL )
, encrypt ( NULL )
, decrypt ( NULL )
, depot ( NULL )
, settings ( NULL )
, srcPicture ( NULL )
, keyPicture ( NULL )
, picTool ( NULL )
, fileTool ( NULL )
, folderTool ( NULL )
, folderEdit ( NULL )
, textTool ( NULL )
, audioTool ( NULL )
, folderList ( NULL )
, vcf ( NULL )
, ftp ( NULL )
, fontconf ( NULL )
, screenconf ( NULL )
, mdi ( NULL )
, label ( NULL )
, progress ( NULL )
, pickPicture ( NULL )
, pickLanguage ( NULL )
, encryptReport ( NULL )
, decryptReport ( NULL )
, plainText ( NULL )
, line ( NULL )
, archive ( NULL )
, pickArchive ( NULL )
, help ( NULL )
, packaging ( 0 )
, SourcePicture ( "" )
, KeyPicture ( "" )
, DecryptPicture ( "" )
, DecryptKey ( "" )
, BackWidget ( NULL )
, BackMenu ( NULL )
, ReturnLabel ( "" )
, debug ( false )
{
Configure ( ) ;
}
N::PaintingSecretGui::~PaintingSecretGui (void)
{
}
QSize N::PaintingSecretGui::sizeHint(void) const
{
if ( plan -> Booleans [ "Desktop" ] ) {
return QSize ( 1280 , 900 ) ;
} else
if ( plan -> Booleans [ "Pad" ] ) {
return QSize ( 1024 , 720 ) ;
} else
if ( plan -> Booleans [ "Phone" ] ) {
return QSize ( 320 , 480 ) ;
} ;
return QSize ( 1024 , 720 ) ;
}
void N::PaintingSecretGui::resizeEvent(QResizeEvent * event)
{
QSplitter :: resizeEvent ( event ) ;
relocation ( ) ;
}
void N::PaintingSecretGui::showEvent(QShowEvent * event)
{
QSplitter :: showEvent ( event ) ;
relocation ( ) ;
}
void N::PaintingSecretGui::Configure (void)
{
setHandleWidth ( 1 ) ;
////////////////////////////////////////////////////////
plan -> settings . beginGroup ( "System" ) ;
if (plan->settings.contains("Debug")) {
debug = plan->settings.value("Debug").toBool() ;
} ;
plan -> settings . endGroup ( ) ;
////////////////////////////////////////////////////////
header = new StackedWidget ( this , plan ) ;
stack = new StackedWidget ( this , plan ) ;
menu = new StackedWidget ( this , plan ) ;
////////////////////////////////////////////////////////
header -> setMinimumHeight ( 28 ) ;
header -> setMaximumHeight ( 28 ) ;
menu -> setMinimumHeight ( 40 ) ;
menu -> setMaximumHeight ( 40 ) ;
////////////////////////////////////////////////////////
addWidget ( header ) ;
addWidget ( stack ) ;
addWidget ( menu ) ;
////////////////////////////////////////////////////////
encrypt = new PaintingEncryptionTool ( menu , plan ) ;
decrypt = new PaintingDecryptionTool ( menu , plan ) ;
depot = new PaintingDepotTool ( menu , plan ) ;
settings = new PaintingSettingsTool ( menu , plan ) ;
srcPicture = new PaintingPickTool ( menu , plan ) ;
keyPicture = new PaintingPickTool ( menu , plan ) ;
getEncrypt = new PaintingPickTool ( menu , plan ) ;
getKeyPic = new PaintingPickTool ( menu , plan ) ;
viewImages = new PaintingPickTool ( menu , plan ) ;
viewEncrypt = new PaintingPickTool ( menu , plan ) ;
viewKeys = new PaintingPickTool ( menu , plan ) ;
fileTool = new PaintingFilesTool ( menu , plan ) ;
folderTool = new PaintingFolderTool ( menu , plan ) ;
textTool = new PaintingTextTool ( menu , plan ) ;
textEdit = new PaintingTextTool ( menu , plan ) ;
audioTool = new PaintingAudioTool ( menu , plan ) ;
folderEdit = new PaintingFolderEdit ( menu , plan ) ;
////////////////////////////////////////////////////////
menu -> addWidget ( encrypt ) ;
menu -> addWidget ( decrypt ) ;
menu -> addWidget ( depot ) ;
menu -> addWidget ( settings ) ;
menu -> addWidget ( srcPicture ) ;
menu -> addWidget ( keyPicture ) ;
menu -> addWidget ( getEncrypt ) ;
menu -> addWidget ( getKeyPic ) ;
menu -> addWidget ( viewImages ) ;
menu -> addWidget ( viewEncrypt ) ;
menu -> addWidget ( viewKeys ) ;
menu -> addWidget ( fileTool ) ;
menu -> addWidget ( folderTool ) ;
menu -> addWidget ( textTool ) ;
menu -> addWidget ( textEdit ) ;
menu -> addWidget ( audioTool ) ;
menu -> addWidget ( folderEdit ) ;
////////////////////////////////////////////////////////
viewImages -> canPick = false ;
viewEncrypt -> canPick = false ;
viewKeys -> canPick = false ;
////////////////////////////////////////////////////////
ftp = new FtpControl ( stack , plan ) ;
stack -> addWidget ( ftp ) ;
ftp -> startup ( ) ;
ftp -> setBack ( false ) ;
////////////////////////////////////////////////////////
label = new QLabel ( header ) ;
header -> addWidget ( label ) ;
label -> setStyleSheet (
"QLabel{background:rgb(255,255,255);}" ) ;
////////////////////////////////////////////////////////
progress = new QProgressBar ( header ) ;
header -> addWidget ( progress ) ;
////////////////////////////////////////////////////////
folderList = new PaintingFolderList ( header ) ;
header -> addWidget ( folderList ) ;
////////////////////////////////////////////////////////
fontconf = new FontConfigurator ( stack , plan ) ;
fontconf->addItem(Fonts::Default ,tr("Default" )) ;
fontconf->addItem(Fonts::Menu ,tr("Menu" )) ;
fontconf->addItem(Fonts::Status ,tr("Status" )) ;
fontconf->addItem(Fonts::Message ,tr("Message" )) ;
fontconf->addItem(Fonts::ComboBox ,tr("Drop items")) ;
fontconf->addItem(Fonts::TreeView ,tr("Text items")) ;
fontconf->addItem(Fonts::ListView ,tr("Icon text" )) ;
fontconf->addItem(Fonts::TableView ,tr("Table" )) ;
fontconf->addItem(Fonts::Label ,tr("Label" )) ;
fontconf->addItem(Fonts::CheckBox ,tr("CheckBox" )) ;
fontconf->addItem(Fonts::Progress ,tr("Progress" )) ;
fontconf->addItem(Fonts::Button ,tr("Button" )) ;
fontconf->addItem(Fonts::Spin ,tr("Spin" )) ;
stack ->addWidget(fontconf) ;
fontconf->startup() ;
fontconf->ItemChanged(0) ;
////////////////////////////////////////////////////////
screenconf = new ScreenConfigurator ( stack , plan ) ;
stack -> addWidget ( screenconf ) ;
screenconf -> setMeasure ( false ) ;
////////////////////////////////////////////////////////
pickLanguage = new TreeWidget ( stack , plan ) ;
stack -> addWidget ( pickLanguage ) ;
pickLanguage -> setColumnCount ( 1 ) ;
pickLanguage -> setHeaderHidden ( true ) ;
pickLanguage -> setRootIsDecorated ( false ) ;
pickLanguage -> setAlternatingRowColors ( true ) ;
nConnect ( pickLanguage , SIGNAL(itemClicked (QTreeWidgetItem*,int)) ,
this , SLOT (languageClicked(QTreeWidgetItem*,int)) ) ;
////////////////////////////////////////////////////////
encryptReport = new TextEdit ( stack , plan ) ;
stack -> addWidget ( encryptReport ) ;
encryptReport-> setReadOnly ( true ) ;
////////////////////////////////////////////////////////
decryptReport = new TextEdit ( stack , plan ) ;
stack -> addWidget ( decryptReport ) ;
decryptReport-> setReadOnly ( true ) ;
////////////////////////////////////////////////////////
depotReport = new TextEdit ( stack , plan ) ;
stack -> addWidget ( depotReport ) ;
depotReport -> setReadOnly ( true ) ;
////////////////////////////////////////////////////////
plainText = new TextEdit ( stack , plan ) ;
stack -> addWidget ( plainText ) ;
////////////////////////////////////////////////////////
line = new LineEdit ( header , plan ) ;
header -> addWidget ( line ) ;
////////////////////////////////////////////////////////
lineRename = new LineEdit ( header , plan ) ;
header -> addWidget ( lineRename ) ;
////////////////////////////////////////////////////////
lineMove = new LineEdit ( header , plan ) ;
header -> addWidget ( lineMove ) ;
////////////////////////////////////////////////////////
lineDirectory = new LineEdit ( header , plan ) ;
header -> addWidget ( lineDirectory ) ;
////////////////////////////////////////////////////////
archive = new ArchiveList ( stack , plan ) ;
stack -> addWidget ( archive ) ;
////////////////////////////////////////////////////////
pickArchive = new ArchivePick ( stack , plan ) ;
stack -> addWidget ( pickArchive ) ;
////////////////////////////////////////////////////////
help = new WebBrowser ( stack , plan ) ;
stack -> addWidget ( help ) ;
////////////////////////////////////////////////////////
mdi = new MdiArea ( stack , plan ) ;
stack -> addWidget ( mdi ) ;
////////////////////////////////////////////////////////
nConnect ( encrypt , SIGNAL(Back ()) ,
this , SIGNAL(Back ()) ) ;
nConnect ( decrypt , SIGNAL(Back ()) ,
this , SIGNAL(Back ()) ) ;
nConnect ( depot , SIGNAL(Back ()) ,
this , SIGNAL(Back ()) ) ;
nConnect ( settings , SIGNAL(Back ()) ,
this , SIGNAL(Back ()) ) ;
nConnect ( srcPicture , SIGNAL(Back ()) ,
this , SLOT (Encryption()) ) ;
nConnect ( keyPicture , SIGNAL(Back ()) ,
this , SLOT (Encryption()) ) ;
nConnect ( getEncrypt , SIGNAL(Back ()) ,
this , SLOT (Decryption()) ) ;
nConnect ( getKeyPic , SIGNAL(Back ()) ,
this , SLOT (Decryption()) ) ;
nConnect ( viewImages , SIGNAL(Back ()) ,
this , SLOT (Depot ()) ) ;
nConnect ( viewEncrypt, SIGNAL(Back ()) ,
this , SLOT (Depot ()) ) ;
nConnect ( viewKeys , SIGNAL(Back ()) ,
this , SLOT (Depot ()) ) ;
nConnect ( fileTool , SIGNAL(Back ()) ,
this , SLOT (Encryption()) ) ;
nConnect ( folderTool , SIGNAL(Back ()) ,
this , SLOT (MakeFile ()) ) ;
nConnect ( textTool , SIGNAL(Back ()) ,
this , SLOT (AddFile ()) ) ;
nConnect ( textEdit , SIGNAL(Back ()) ,
this , SLOT (BackEdit ()) ) ;
nConnect ( audioTool , SIGNAL(Back ()) ,
this , SLOT (AddFile ()) ) ;
nConnect ( folderEdit , SIGNAL(Back ()) ,
this , SLOT (FolderMenu()) ) ;
////////////////////////////////////////////////////////
nConnect ( settings , SIGNAL(Ftp ()) ,
this , SLOT (Sharing ()) ) ;
nConnect ( settings , SIGNAL(Language ()) ,
this , SLOT (Language ()) ) ;
nConnect ( settings , SIGNAL(Fonts ()) ,
this , SLOT (Fonts ()) ) ;
nConnect ( settings , SIGNAL(Display ()) ,
this , SLOT (Display ()) ) ;
nConnect ( settings , SIGNAL(Help ()) ,
this , SLOT (Help ()) ) ;
////////////////////////////////////////////////////////
nConnect ( encrypt , SIGNAL(Files ()) ,
this , SLOT (MakeFile ()) ) ;
nConnect ( encrypt , SIGNAL(Picture ()) ,
this , SLOT (GetPicture ()) ) ;
nConnect ( encrypt , SIGNAL(Key ()) ,
this , SLOT (PickKey ()) ) ;
nConnect ( encrypt , SIGNAL(Encrypt ()) ,
this , SLOT (DoEncrypt ()) ) ;
////////////////////////////////////////////////////////
nConnect ( decrypt , SIGNAL(Picture ()) ,
this , SLOT (DataPicture ()) ) ;
nConnect ( decrypt , SIGNAL(Key ()) ,
this , SLOT (DataKey ()) ) ;
nConnect ( decrypt , SIGNAL(Decrypt ()) ,
this , SLOT (DoDecrypt ()) ) ;
////////////////////////////////////////////////////////
nConnect ( depot , SIGNAL(List ()) ,
this , SLOT (DepotList ()) ) ;
nConnect ( depot , SIGNAL(Pictures ()) ,
this , SLOT (DepotPictures ()) ) ;
nConnect ( depot , SIGNAL(Keys ()) ,
this , SLOT (DepotKeys ()) ) ;
nConnect ( depot , SIGNAL(Encrypted ()) ,
this , SLOT (DepotEncrypted()) ) ;
nConnect ( depot , SIGNAL(Ftp ()) ,
this , SLOT (DepotFtp ()) ) ;
////////////////////////////////////////////////////////
pickPicture = new PickPicture ( stack , plan ) ;
stack -> addWidget ( pickPicture ) ;
nConnect ( pickPicture,SIGNAL(FileSelected(QString)) ,
this ,SLOT (FileSelected(QString)) ) ;
nConnect ( pickPicture,SIGNAL(FileSelected(QString)) ,
srcPicture ,SLOT (FileSelected(QString)) ) ;
nConnect ( pickPicture,SIGNAL(Full (int,bool)) ,
srcPicture ,SLOT (Full (int,bool)) ) ;
nConnect ( pickPicture,SIGNAL(Empty ()) ,
srcPicture ,SLOT (Empty ()) ) ;
nConnect ( srcPicture ,SIGNAL(Previous ()) ,
pickPicture,SLOT (Previous ()) ) ;
nConnect ( srcPicture ,SIGNAL(Next ()) ,
pickPicture,SLOT (Next ()) ) ;
nConnect ( srcPicture ,SIGNAL(Pick ()) ,
this ,SLOT (ObtainPic ()) ) ;
nConnect ( srcPicture ,SIGNAL(View ()) ,
this ,SLOT (ViewPicture()) ) ;
nConnect ( srcPicture ,SIGNAL(Import ()) ,
this ,SLOT (ImportPicture()) ) ;
nConnect ( pickPicture,SIGNAL(FileSelected(QString)) ,
keyPicture ,SLOT (FileSelected(QString)) ) ;
nConnect ( pickPicture,SIGNAL(Full (int,bool)) ,
keyPicture ,SLOT (Full (int,bool)) ) ;
nConnect ( pickPicture,SIGNAL(Empty ()) ,
keyPicture ,SLOT (Empty ()) ) ;
nConnect ( keyPicture ,SIGNAL(Previous ()) ,
pickPicture,SLOT (Previous ()) ) ;
nConnect ( keyPicture ,SIGNAL(Next ()) ,
pickPicture,SLOT (Next ()) ) ;
nConnect ( keyPicture ,SIGNAL(Pick ()) ,
this ,SLOT (ObtainKey ()) ) ;
nConnect ( keyPicture ,SIGNAL(View ()) ,
this ,SLOT (ViewPicture()) ) ;
nConnect ( keyPicture ,SIGNAL(Import ()) ,
this ,SLOT (ImportKey ()) ) ;
nConnect ( pickPicture,SIGNAL(FileSelected(QString)) ,
viewImages ,SLOT (FileSelected(QString)) ) ;
nConnect ( pickPicture,SIGNAL(Full (int,bool)) ,
viewImages ,SLOT (Full (int,bool)) ) ;
nConnect ( pickPicture,SIGNAL(Empty ()) ,
viewImages ,SLOT (Empty ()) ) ;
nConnect ( viewImages ,SIGNAL(Previous ()) ,
pickPicture,SLOT (Previous ()) ) ;
nConnect ( viewImages ,SIGNAL(Next ()) ,
pickPicture,SLOT (Next ()) ) ;
nConnect ( viewImages ,SIGNAL(View ()) ,
this ,SLOT (ViewDepot ()) ) ;
nConnect ( viewImages ,SIGNAL(Import ()) ,
this ,SLOT (ImportPicture()) ) ;
////////////////////////////////////////////////////////
pickEncrypt = new PickPicture ( stack , plan ) ;
stack -> addWidget ( pickEncrypt ) ;
nConnect ( pickEncrypt,SIGNAL(FileSelected(QString)) ,
this ,SLOT (FileSelected(QString)) ) ;
nConnect ( pickEncrypt,SIGNAL(FileSelected(QString)) ,
getEncrypt ,SLOT (FileSelected(QString)) ) ;
nConnect ( pickEncrypt,SIGNAL(Full (int,bool)) ,
getEncrypt ,SLOT (Full (int,bool)) ) ;
nConnect ( pickEncrypt,SIGNAL(Empty ()) ,
getEncrypt ,SLOT (Empty ()) ) ;
nConnect ( getEncrypt ,SIGNAL(Previous ()) ,
pickEncrypt,SLOT (Previous ()) ) ;
nConnect ( getEncrypt ,SIGNAL(Next ()) ,
pickEncrypt,SLOT (Next ()) ) ;
nConnect ( getEncrypt ,SIGNAL(Pick ()) ,
this ,SLOT (ObtainEncrypted()) ) ;
nConnect ( getEncrypt ,SIGNAL(View ()) ,
this ,SLOT (ViewEncrypted()) ) ;
nConnect ( getEncrypt ,SIGNAL(Import ()) ,
this ,SLOT (ImportEncrypted()) ) ;
nConnect ( pickEncrypt,SIGNAL(FileSelected(QString)) ,
viewEncrypt,SLOT (FileSelected(QString)) ) ;
nConnect ( pickEncrypt,SIGNAL(Full (int,bool)) ,
viewEncrypt,SLOT (Full (int,bool)) ) ;
nConnect ( pickEncrypt,SIGNAL(Empty ()) ,
viewEncrypt,SLOT (Empty ()) ) ;
nConnect ( viewEncrypt,SIGNAL(Previous ()) ,
pickEncrypt,SLOT (Previous ()) ) ;
nConnect ( viewEncrypt,SIGNAL(Next ()) ,
pickEncrypt,SLOT (Next ()) ) ;
nConnect ( viewEncrypt,SIGNAL(View ()) ,
this ,SLOT (ViewDepot ()) ) ;
nConnect ( viewEncrypt,SIGNAL(Import ()) ,
this ,SLOT (ImportEncrypted()) ) ;
////////////////////////////////////////////////////////
pickKey = new PickPicture ( stack , plan ) ;
stack -> addWidget ( pickKey ) ;
nConnect ( pickKey ,SIGNAL(FileSelected(QString)) ,
this ,SLOT (FileSelected(QString)) ) ;
nConnect ( pickKey ,SIGNAL(FileSelected(QString)) ,
getKeyPic ,SLOT (FileSelected(QString)) ) ;
nConnect ( pickKey ,SIGNAL(Full (int,bool)) ,
getKeyPic ,SLOT (Full (int,bool)) ) ;
nConnect ( pickKey ,SIGNAL(Empty ()) ,
getKeyPic ,SLOT (Empty ()) ) ;
nConnect ( getKeyPic ,SIGNAL(Previous ()) ,
pickKey ,SLOT (Previous ()) ) ;
nConnect ( getKeyPic ,SIGNAL(Next ()) ,
pickKey ,SLOT (Next ()) ) ;
nConnect ( getKeyPic ,SIGNAL(Pick ()) ,
this ,SLOT (ObtainKeys()) ) ;
nConnect ( getKeyPic ,SIGNAL(View ()) ,
this ,SLOT (ViewKeys ()) ) ;
nConnect ( getKeyPic ,SIGNAL(Import ()) ,
this ,SLOT (ImportKeys()) ) ;
nConnect ( pickKey ,SIGNAL(FileSelected(QString)) ,
viewKeys ,SLOT (FileSelected(QString)) ) ;
nConnect ( pickKey ,SIGNAL(Full (int,bool)) ,
viewKeys ,SLOT (Full (int,bool)) ) ;
nConnect ( pickKey ,SIGNAL(Empty ()) ,
viewKeys ,SLOT (Empty ()) ) ;
nConnect ( viewKeys ,SIGNAL(Previous ()) ,
pickKey ,SLOT (Previous ()) ) ;
nConnect ( viewKeys ,SIGNAL(Next ()) ,
pickKey ,SLOT (Next ()) ) ;
nConnect ( viewKeys ,SIGNAL(View ()) ,
this ,SLOT (ViewDepot ()) ) ;
nConnect ( viewKeys ,SIGNAL(Import ()) ,
this ,SLOT (ImportKeys()) ) ;
////////////////////////////////////////////////////////
nConnect ( fileTool , SIGNAL(New ()) ,
this , SLOT (NewFile ()) ) ;
nConnect ( fileTool , SIGNAL(Add ()) ,
this , SLOT (AddFile ()) ) ;
nConnect ( fileTool , SIGNAL(Remove ()) ,
this , SLOT (RemoveFile ()) ) ;
nConnect ( fileTool , SIGNAL(Packaging ()) ,
this , SLOT (CreatePackage()) ) ;
////////////////////////////////////////////////////////
nConnect ( folderTool , SIGNAL(Join ()) ,
this , SLOT (FolderJoin ()) ) ;
nConnect ( folderTool , SIGNAL(Edit ()) ,
this , SLOT (FolderEdit ()) ) ;
nConnect ( folderTool , SIGNAL(Delete ()) ,
this , SLOT (FolderDelete ()) ) ;
nConnect ( folderTool , SIGNAL(Text ()) ,
this , SLOT (FolderText ()) ) ;
nConnect ( folderTool , SIGNAL(Recorder ()) ,
this , SLOT (FolderRecorder()) ) ;
////////////////////////////////////////////////////////
nConnect ( folderList , SIGNAL(CdUp ()) ,
pickArchive , SLOT (CdUp ()) ) ;
nConnect ( folderList , SIGNAL(Directory(QString)) ,
pickArchive , SLOT (Directory(QString)) ) ;
nConnect ( pickArchive , SIGNAL(Folders(bool,QStringList)) ,
folderList , SLOT (Folders(bool,QStringList)) ) ;
nConnect ( pickArchive , SIGNAL(Listing ()) ,
this , SLOT (FolderListing ()) ) ;
nConnect ( pickArchive , SIGNAL(Ready ()) ,
this , SLOT (FolderReady ()) ) ;
nConnect ( pickArchive , SIGNAL(selectionChanged()) ,
this , SLOT (FolderSelected ()) ) ;
nConnect ( archive , SIGNAL(selectionChanged()) ,
this , SLOT (FileSelected ()) ) ;
////////////////////////////////////////////////////////
nConnect ( textTool , SIGNAL(New ()) ,
this , SLOT (FolderText()) ) ;
nConnect ( textTool , SIGNAL(Save ()) ,
this , SLOT (SaveText ()) ) ;
////////////////////////////////////////////////////////
nConnect ( textEdit , SIGNAL(New ()) ,
this , SLOT (NewEdit ()) ) ;
nConnect ( textEdit , SIGNAL(Save ()) ,
this , SLOT (SaveEdit ()) ) ;
////////////////////////////////////////////////////////
nConnect ( lineRename , SIGNAL(returnPressed ()) ,
this , SLOT (RenameAction ()) ) ;
nConnect ( lineMove , SIGNAL(returnPressed ()) ,
this , SLOT (MoveAction ()) ) ;
nConnect ( lineDirectory , SIGNAL(returnPressed ()) ,
this , SLOT (DirectoryAction()) ) ;
nConnect ( lineRename , SIGNAL(editingFinished()) ,
this , SLOT (FolderBack ()) ) ;
nConnect ( lineMove , SIGNAL(editingFinished()) ,
this , SLOT (FolderBack ()) ) ;
nConnect ( lineDirectory , SIGNAL(editingFinished()) ,
this , SLOT (FolderBack ()) ) ;
////////////////////////////////////////////////////////
nConnect ( folderEdit , SIGNAL(Rename ()) ,
this , SLOT (FileRename ()) ) ;
nConnect ( folderEdit , SIGNAL(Move ()) ,
this , SLOT (FileMove ()) ) ;
nConnect ( folderEdit , SIGNAL(Directory ()) ,
this , SLOT (FileDirectory ()) ) ;
nConnect ( folderEdit , SIGNAL(Edit ()) ,
this , SLOT (EditText ()) ) ;
nConnect ( folderEdit , SIGNAL(Ftp ()) ,
this , SLOT (FileFtp ()) ) ;
////////////////////////////////////////////////////////
}
void N::PaintingSecretGui::BootupFtp(void)
{
if ( ! plan -> Booleans [ "Desktop" ] ) {
if (ftp->AutoStartup()) ftp->begin(true) ;
} ;
}
void N::PaintingSecretGui::FileSelected(QString path)
{
label -> setText ( path ) ;
}
void N::PaintingSecretGui::AndroidPathes(void)
{
#define AFP(NX) N::FtpSettings::addFolder(plan->Path("files/" NX),QString(NX),true) ; \
if (debug) qDebug ( plan->Path("files/" NX).toUtf8().constData() )
AFP ( "Documents" ) ;
AFP ( "Download" ) ;
AFP ( "Encryption" ) ;
AFP ( "Files" ) ;
AFP ( "Images" ) ;
AFP ( "Keys" ) ;
AFP ( "Upload" ) ;
if (debug) {
AFP ( "Temp" ) ;
AFP ( "Sounds" ) ;
AFP ( "Users" ) ;
} ;
#undef AFP
}
void N::PaintingSecretGui::ApplePathes(void)
{
#define AFP(NX) N::FtpSettings::addFolder(plan->Path("Documents/" NX),QString(NX),true) ; \
if (debug) qDebug ( plan->Path("Documents/" NX).toUtf8().constData() )
AFP ( "Documents" ) ;
AFP ( "Download" ) ;
AFP ( "Encryption" ) ;
AFP ( "Files" ) ;
AFP ( "Images" ) ;
AFP ( "Keys" ) ;
AFP ( "Upload" ) ;
if (debug) {
AFP ( "Temp" ) ;
AFP ( "Sounds" ) ;
AFP ( "Users" ) ;
} ;
#undef AFP
}
void N::PaintingSecretGui::InstallPathes(void)
{
if ( plan -> Booleans [ "Desktop" ] ) {
pickPicture -> setRoot ( plan->Path("Images" ) ) ;
pickEncrypt -> setRoot ( plan->Path("Download") ) ;
pickKey -> setRoot ( plan->Path("Upload" ) ) ;
archive -> setRoot ( plan->Path("Files" ) ) ;
pickArchive -> setRoot ( plan->Path("Files" ) ) ;
} else {
#ifdef Q_OS_ANDROID
pickPicture -> setRoot ( plan->Path("files/Images" ) ) ;
pickEncrypt -> setRoot ( plan->Path("files/Encryption") ) ;
pickKey -> setRoot ( plan->Path("files/Keys" ) ) ;
archive -> setRoot ( plan->Path("files/Documents" ) ) ;
pickArchive -> setRoot ( plan->Path("files/Documents" ) ) ;
#endif
#ifdef Q_OS_IOS
pickPicture -> setRoot ( plan->Path("Documents/Images" ) ) ;
pickEncrypt -> setRoot ( plan->Path("Documents/Encryption") ) ;
pickKey -> setRoot ( plan->Path("Documents/Keys" ) ) ;
archive -> setRoot ( plan->Path("Documents/Documents" ) ) ;
pickArchive -> setRoot ( plan->Path("Documents/Documents" ) ) ;
#endif
} ;
}
void N::PaintingSecretGui::relocation(void)
{
}
QString N::PaintingSecretGui::LanguagePath(QString filename)
{
QString LC ;
LidTo(plan->LanguageId,LC) ;
QString p = QString("Translations/%1/%2").arg(LC).arg(filename) ;
return Root.absoluteFilePath(p) ;
}
void N::PaintingSecretGui::Encryption(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( encryptReport ) ;
menu -> setCurrentWidget ( encrypt ) ;
label -> setText ( tr("Encrypt data into a picture") ) ;
//////////////////////////////////////////////////////////////////
QString p = LanguagePath("steganoencrypt.html") ;
QFileInfo F(p) ;
if (!F.exists()) return ;
QByteArray Body ;
File::toByteArray ( p , Body ) ;
encryptReport -> clear ( ) ;
encryptReport -> append ( QString::fromUtf8(Body) ) ;
encryptReport -> verticalScrollBar ( ) -> setValue ( 0 ) ;
}
void N::PaintingSecretGui::Decryption(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( decryptReport ) ;
menu -> setCurrentWidget ( decrypt ) ;
label -> setText ( tr("Decrypt data from picture") ) ;
////////////////////////////////////////////////////////////////
QString p = LanguagePath("steganodecrypt.html") ;
QFileInfo F(p) ;
if (!F.exists()) return ;
QByteArray Body ;
File::toByteArray ( p , Body ) ;
decryptReport -> clear ( ) ;
decryptReport -> append ( QString::fromUtf8(Body) ) ;
decryptReport -> verticalScrollBar ( ) -> setValue ( 0 ) ;
}
void N::PaintingSecretGui::Depot(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( depotReport ) ;
menu -> setCurrentWidget ( depot ) ;
label -> setText ( tr("Painting secrets depot") ) ;
/////////////////////////////////////////////////////////////
QString p = LanguagePath("steganodepot.html") ;
QFileInfo F(p) ;
if (!F.exists()) return ;
QByteArray Body ;
File::toByteArray ( p , Body ) ;
depotReport -> clear ( ) ;
depotReport -> append ( QString::fromUtf8(Body) ) ;
depotReport -> verticalScrollBar ( ) -> setValue ( 0 ) ;
}
void N::PaintingSecretGui::Settings(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( ftp ) ;
menu -> setCurrentWidget ( settings ) ;
label -> setText ( tr("Painting secrets settings") ) ;
}
void N::PaintingSecretGui::Sharing(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( ftp ) ;
menu -> setCurrentWidget ( settings ) ;
label -> setText ( tr("Ftp sharing server") ) ;
Alert ( Error ) ;
//////////////////////////////////////////////////////////////////////////////
QHostInfo info ;
QString qstr = info.localHostName() ;
QHostInfo info2 ( QHostInfo ::fromName ( qstr ) ) ;
QList<QHostAddress> list ;
bool found = false ;
list = info2.addresses() ;
if (list.count()<=0) list = QNetworkInterface::allAddresses() ;
//////////////////////////////////////////////////////////////////////////////
for (int i=0;!found && i<list.count();i++) {
if (!list[i].isLoopback()) {
if (list[i].protocol() == QAbstractSocket::IPv4Protocol) {
label -> setText ( tr("Local address : %1") .arg(list[i].toString()) ) ;
found = true ;
} ;
} ;
} ;
}
void N::PaintingSecretGui::Fonts(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( fontconf ) ;
menu -> setCurrentWidget ( settings ) ;
label -> setText ( tr("Setup fonts") ) ;
Alert ( Error ) ;
}
void N::PaintingSecretGui::Language(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( pickLanguage ) ;
menu -> setCurrentWidget ( settings ) ;
ListLanguage ( ) ;
Alert ( Error ) ;
}
void N::PaintingSecretGui::languageClicked(QTreeWidgetItem * item,int column)
{ Q_UNUSED ( column ) ;
for (int i=0;i<pickLanguage->topLevelItemCount();i++) {
QTreeWidgetItem * it = pickLanguage->topLevelItem(i) ;
if (it==item) {
QString s = it->text(0) ;
QString m ;
int l = item->data(0,Qt::UserRole).toInt() ;
it -> setIcon ( 0 , QIcon(":/images/yes.png" ) ) ;
it -> setData ( 0 , Qt::UserRole+1 , 1 ) ;
plan -> settings . beginGroup ( "System" ) ;
plan -> settings . setValue ( "Language" , l ) ;
plan -> settings . endGroup ( ) ;
m = tr("Language change to %1 will take effect after restart").arg(s) ;
label -> setText ( m ) ;
} else {
it -> setIcon ( 0 , QIcon(":/icons/empty.png") ) ;
it -> setData ( 0 , Qt::UserRole+1 , 0 ) ;
} ;
} ;
}
void N::PaintingSecretGui::ListLanguage(void)
{
int LID ;
menu -> setEnabled ( false ) ;
pickLanguage -> clear ( ) ;
ForLanguage ( LID , plan->languages.Supports ) ;
QString LC ;
if (LidTo(LID,LC) || LID==1819) {
QString p = QString("Translations/%1/%2").arg(LC).arg(QM) ;
p = Root.absoluteFilePath(p) ;
QFileInfo F(p) ;
if (F.exists() || LID==1819) {
QString n = (plan->languages)[LID] ;
NewTreeWidgetItem ( IT ) ;
IT -> setData ( 0 , Qt::UserRole , LID ) ;
IT -> setText ( 0 , n ) ;
if (LID==plan->LanguageId) {
IT -> setIcon ( 0 , QIcon(":/images/yes.png" )) ;
IT -> setData ( 0 , Qt::UserRole+1 , 1 ) ;
} else {
IT -> setIcon ( 0 , QIcon(":/icons/empty.png" )) ;
IT -> setData ( 0 , Qt::UserRole+1 , 0 ) ;
} ;
pickLanguage -> addTopLevelItem ( IT ) ;
} ;
} ;
if (debug) {
QString nn = (plan->languages)[LID] ;
qDebug ( nn.toUtf8().constData() ) ;
} ;
EndLanguage ( LID , plan->languages.Supports ) ;
QString l = (plan->languages)[plan->LanguageId] ;
QString m ;
m = tr("Setup language, current language is %1").arg(l) ;
label -> setText ( m ) ;
menu -> setEnabled ( true ) ;
}
void N::PaintingSecretGui::Display(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( screenconf ) ;
menu -> setCurrentWidget ( settings ) ;
label -> setText ( tr("Setup display size") ) ;
Alert ( Error ) ;
}
void N::PaintingSecretGui::Help(void)
{
emit Manual ( ) ;
}
void N::PaintingSecretGui::MakeFile(void)
{
if (packaging<=0) packaging = ObtainUuid ( ) ;
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( archive ) ;
menu -> setCurrentWidget ( fileTool ) ;
QString m ;
m = tr("Create data package, signature is `%1`.").arg(packaging) ;
label -> setText ( m ) ;
fileTool -> setDeletion ( archive->Selections () > 0 ) ;
fileTool -> setPackaging ( archive->topLevelItemCount() > 0 ) ;
Alert ( Error ) ;
}
SUID N::PaintingSecretGui::ObtainUuid(void)
{
SUID u = 0 ;
SqlConnection SC(plan->sql) ;
if (SC.open("PaintingSecretGui","ObtainUuid")) {
u = SC.Unique (PlanTable(MajorUuid),"uuid") ;
SC.close() ;
} ;
SC.remove() ;
return u ;
}
void N::PaintingSecretGui::NewFile(void)
{
if (packaging>0) {
QString t = QString("Temp/%1.tar.xz").arg(packaging) ;
t = Root.absoluteFilePath(t) ;
QFile::remove(t) ;
} ;
packaging = ObtainUuid ( ) ;
archive -> clear ( ) ;
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( archive ) ;
menu -> setCurrentWidget ( fileTool ) ;
QString m ;
m = tr("Create data package, signature is `%1`.").arg(packaging ) ;
label -> setText ( m ) ;
fileTool -> setDeletion ( archive->Selections () > 0 ) ;
fileTool -> setPackaging ( archive->topLevelItemCount() > 0 ) ;
Alert ( Error ) ;
}
void N::PaintingSecretGui::AddFile(void)
{
header -> setCurrentWidget ( folderList ) ;
stack -> setCurrentWidget ( pickArchive ) ;
menu -> setCurrentWidget ( folderTool ) ;
plan -> processEvents ( ) ;
pickArchive -> List ( ) ;
}
void N::PaintingSecretGui::RemoveFile(void)
{
archive -> Delete ( ) ;
fileTool -> setDeletion ( archive->Selections () > 0 ) ;
fileTool -> setPackaging ( archive->topLevelItemCount() > 0 ) ;
}
void N::PaintingSecretGui::CreatePackage(void)
{
XDEBUG ( "N::PaintingSecretGui::CreatePackage" ) ;
//////////////////////////////////////////
if (packaging<=0) return ;
//////////////////////////////////////////
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( archive ) ;
menu -> setCurrentWidget ( fileTool ) ;
//////////////////////////////////////////
QStringList L = archive -> PickFiles( ) ;
if (L.count()<=0) return ;
//////////////////////////////////////////
QString m ;
m = tr("Compress %1") . arg( packaging ) ;
label -> setText ( m ) ;
stack -> setEnabled ( false ) ;
menu -> setEnabled ( false ) ;
plan -> processEvents ( ) ;
//////////////////////////////////////////
XDEBUG ( "N::PaintingSecretGui::CreatePackage@Bale" ) ;
//////////////////////////////////////////
QString XZ ;
VirtualIO IO ;
XZ = QString("%1.tar.xz").arg(packaging) ;
XZ = QString("Temp/%1" ).arg(XZ ) ;
XZ = Root.absoluteFilePath (XZ ) ;
IO . setDirectory ( archive -> Path() ) ;
IO . setFile ( File::Xz ) ;
IO . setVIO ( VirtualDisk::Tar ) ;
IO . append ( L ) ;
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
qDebug ( "N::PaintingSecretGui::CreatePackage@IO.append" ) ;
#endif
IO . Bale ( XZ ) ;
//////////////////////////////////////////
XDEBUG ( "N::PaintingSecretGui::CreatePackage@Display" ) ;
//////////////////////////////////////////
QFileInfo F(XZ) ;
m = tr("Compressed data size is %1").arg(F.size()) ;
label -> setText ( m ) ;
//////////////////////////////////////////
plan -> processEvents ( ) ;
stack -> setEnabled ( true ) ;
menu -> setEnabled ( true ) ;
plan -> processEvents ( ) ;
//////////////////////////////////////////
Alert ( Error ) ;
}
void N::PaintingSecretGui::FileSelected(void)
{
fileTool -> setDeletion ( archive->Selections () > 0 ) ;
fileTool -> setPackaging ( archive->topLevelItemCount() > 0 ) ;
}
void N::PaintingSecretGui::FolderJoin(void)
{
QStringList L = pickArchive -> PickFiles ( ) ;
if (L.count()<=0) return ;
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( archive ) ;
menu -> setCurrentWidget ( fileTool ) ;
plan -> processEvents ( ) ;
archive -> Append ( L ) ;
plan -> processEvents ( ) ;
fileTool -> setDeletion ( archive->Selections () > 0 ) ;
fileTool -> setPackaging ( archive->topLevelItemCount() > 0 ) ;
}
void N::PaintingSecretGui::FolderEdit(void)
{
menu -> setCurrentWidget ( folderEdit ) ;
Alert ( Click ) ;
}
void N::PaintingSecretGui::FolderMenu(void)
{
menu -> setCurrentWidget ( folderTool ) ;
Alert ( Click ) ;
}
void N::PaintingSecretGui::DeletePath(QDir & root,QStringList files)
{
QString S ;
foreach (S,files) {
QFileInfo F ( S ) ;
if (F.isDir()) {
QDir D ( S ) ;
QFileInfoList L ;
QStringList M ;
QString p = S ;
p = root.relativeFilePath(p) ;
L = D.entryInfoList (
QDir::Dirs |
QDir::Files |
QDir::NoDotAndDotDot |
QDir::NoSymLinks ) ;
for (int i=0;i<L.count();i++) {
M << L[i].absoluteFilePath() ;
} ;
DeletePath ( root , M ) ;
label->setText(tr("Delete %1").arg(p)) ;
root . rmpath ( S ) ;
} else
if (F.isFile()) {
QString p = S ;
p = root.relativeFilePath(p) ;
label->setText(tr("Delete %1").arg(p)) ;
QFile::remove(S) ;
} ;
plan -> processEvents ( ) ;
} ;
}
void N::PaintingSecretGui::FolderDelete(void)
{
QStringList L = pickArchive -> PickFiles ( ) ;
if (L.count()<=0) return ;
folderTool -> setEnabled ( false ) ;
header -> setCurrentWidget ( label ) ;
plan -> processEvents ( ) ;
QDir r = pickArchive->Path ( ) ;
DeletePath ( r , L ) ;
header -> setCurrentWidget ( folderList ) ;
folderTool -> setEnabled ( true ) ;
plan -> processEvents ( ) ;
pickArchive -> List ( ) ;
}
void N::PaintingSecretGui::FolderText(void)
{
emit NewText ( pickArchive -> Path() , pickArchive -> CurrentPath() ) ;
#ifdef XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
plainText -> clear ( ) ;
header -> setCurrentWidget ( line ) ;
stack -> setCurrentWidget ( plainText ) ;
menu -> setCurrentWidget ( textTool ) ;
label -> setText ( tr("Plain text editor" ) ) ;
////////////////////////////////////////////////////////////
bool e = false ;
QDir r = pickArchive -> Path ( ) ;
QDir c = pickArchive -> CurrentPath ( ) ;
QString f = tr("Noname") ;
QString t ;
int i = 1 ;
do {
t = QString("%1-%2.txt").arg(f).arg(i) ;
i++ ;
t = c.absoluteFilePath(t) ;
QFileInfo F(t) ;
if (!F.exists()) {
t = r.relativeFilePath(t) ;
e = true ;
} ;
} while (!e) ;
line -> blockSignals ( true ) ;
line -> setText ( t ) ;
line -> blockSignals ( false ) ;
////////////////////////////////////////////////////////////
Alert ( Error ) ;
#endif
}
void N::PaintingSecretGui::SaveText(void)
{
QString note = line->text() ;
if (note.length()<=0) return ;
QDir r = pickArchive -> Path( ) ;
QString file = r.absoluteFilePath ( note ) ;
QString head = r.absoluteFilePath ( "" ) ;
if (!file.contains(head)) return ;
QString text = plainText -> toPlainText ( ) ;
QByteArray body = text . toUtf8 ( ) ;
QFileInfo fdir ( file ) ;
r . mkpath ( fdir . absolutePath ( ) ) ;
File :: toFile ( file , body ) ;
AddFile ( ) ;
}
void N::PaintingSecretGui::FolderRecorder(void)
{
QString path = pickArchive->CurrentPath().absoluteFilePath("") ;
emit Recording ( path ) ;
}
void N::PaintingSecretGui::FolderListing(void)
{
folderList -> setEnabled ( false ) ;
folderTool -> setEnabled ( false ) ;
}
void N::PaintingSecretGui::FolderReady(void)
{
folderList -> setEnabled ( true ) ;
folderTool -> setEnabled ( true ) ;
FolderSelected ( ) ;
}
void N::PaintingSecretGui::FolderSelected(void)
{
QTreeWidgetItem * item = pickArchive->currentItem ( ) ;
bool isText = false ;
if (NotNull(item)) {
int t = item->data(1,Qt::UserRole).toInt() ;
if (t==0) {
QFileInfo F(item->text(0)) ;
QString S = F.suffix() ;
S = S.toLower() ;
isText = ( S == "txt" ) ;
} ;
} ;
folderTool -> setSelected ( pickArchive->Selections() ) ;
folderEdit -> setSelected ( pickArchive->Selections() ) ;
folderEdit -> setEdit ( isText ) ;
}
void N::PaintingSecretGui::GetPicture(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( pickPicture ) ;
menu -> setCurrentWidget ( srcPicture ) ;
label -> setText ( tr("Pick picture for encryption") ) ;
Alert ( Error ) ;
srcPicture -> setEnabled ( false ) ;
plan -> processEvents ( ) ;
pickPicture -> Index = 0 ;
pickPicture -> Refresh ( ) ;
srcPicture -> setEnabled ( true ) ;
}
void N::PaintingSecretGui::PickKey(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( pickPicture ) ;
menu -> setCurrentWidget ( keyPicture ) ;
label -> setText ( tr("Pick a picture as key") ) ;
Alert ( Error ) ;
keyPicture -> setEnabled ( false ) ;
plan -> processEvents ( ) ;
pickPicture -> Index = 0 ;
pickPicture -> Refresh ( ) ;
keyPicture -> setEnabled ( true ) ;
}
void N::PaintingSecretGui::DoEncrypt(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( encryptReport ) ;
menu -> setCurrentWidget ( encrypt ) ;
menu -> setEnabled ( false ) ;
////////////////////////////////////////////////////////////////
QString m ;
QString rp ;
m = tr("Creating steganographic picture `%1`.").arg(packaging) ;
label -> setText ( m ) ;
////////////////////////////////////////////////////////////////
encryptReport -> clear ( ) ;
plan -> processEvents ( ) ;
Alert ( Click ) ;
////////////////////////////////////////////////////////////////
bool hasData = false ;
QByteArray XzData ;
QByteArray PackData ;
QByteArray KeyData ;
QString XZ ;
QImage SrcImage ;
QImage KeyImage ;
////////////////////////////////////////////////////////////////
if (packaging>0) {
XZ = QString("Temp/%1.tar.xz").arg(packaging) ;
XZ = Root.absoluteFilePath ( XZ ) ;
QFileInfo F ( XZ ) ;
if (F.exists() && F.size()>0) {
if (F.size()<(8*1024*1024)) {
File :: toByteArray ( XZ , XzData ) ;
if (XzData.size()==F.size()) {
hasData = true ;
m = tr ( "Compressed data size for %1 is %2" )
. arg ( packaging )
. arg ( F.size() ) ;
encryptReport -> append ( m ) ;
plan -> processEvents ( ) ;
} else {
m = tr ( "Failure to read compressed data" ) ;
encryptReport -> append ( m ) ;
menu -> setEnabled ( true ) ;
plan -> processEvents ( ) ;
Alert ( Error ) ;
return ;
} ;
} else {
m = tr ( "Compressed data size %1 exceeds limit %2" )
. arg ( F.size() )
. arg ( (8*1024*1024) ) ;
encryptReport -> append ( m ) ;
menu -> setEnabled ( true ) ;
plan -> processEvents ( ) ;
Alert ( Error ) ;
return ;
} ;
} ;
} ;
if (!hasData) {
m = tr("You did not specify the data you want to encrypt." ) ;
encryptReport -> append ( m ) ;
menu -> setEnabled ( true ) ;
plan -> processEvents ( ) ;
Alert ( Error ) ;
return ;
} ;
////////////////////////////////////////////////////////////////
if (SourcePicture.length()<=0) {
m = tr("You did not specify your source picture." ) ;
encryptReport -> append ( m ) ;
menu -> setEnabled ( true ) ;
plan -> processEvents ( ) ;
Alert ( Error ) ;
return ;
} ;
rp = SourcePicture ;
rp = Root.relativeFilePath(rp) ;
m = tr("Source image filename is `%1`").arg(rp) ;
encryptReport -> append ( m ) ;
plan -> processEvents ( ) ;
if (!SrcImage.load(SourcePicture) ||
SrcImage . width ( ) <= 0 ||
SrcImage . height ( ) <= 0 ) {
m = tr("Source picture can not be loaded." ) ;
encryptReport -> append ( m ) ;
menu -> setEnabled ( true ) ;
plan -> processEvents ( ) ;
Alert ( Error ) ;
return ;
} ;
m = tr("Source image size is %1 x %2").arg(SrcImage.width()).arg(SrcImage.height()) ;
encryptReport -> append ( m ) ;
plan -> processEvents ( ) ;
////////////////////////////////////////////////////////////////
if (KeyPicture.length()<=0) {
m = tr("You did not specify your key picture." ) ;
encryptReport -> append ( m ) ;
menu -> setEnabled ( true ) ;
plan -> processEvents ( ) ;
Alert ( Error ) ;
return ;
} ;
rp = KeyPicture ;
rp = Root.relativeFilePath(rp) ;
m = tr("Key image filename is `%1`").arg(rp) ;
encryptReport -> append ( m ) ;
plan -> processEvents ( ) ;
if (!KeyImage.load(KeyPicture) ||
KeyImage . width ( ) <= 0 ||
KeyImage . height ( ) <= 0 ) {
m = tr("Key picture can not be loaded." ) ;
encryptReport -> append ( m ) ;
menu -> setEnabled ( true ) ;
plan -> processEvents ( ) ;
Alert ( Error ) ;
return ;
} ;
m = tr("Key image size is %1 x %2").arg(KeyImage.width()).arg(KeyImage.height()) ;
encryptReport -> append ( m ) ;
plan -> processEvents ( ) ;
////////////////////////////////////////////////////////////////
bool encrypted = false ;
if (Images::EncryptPair(packaging,XzData,PackData,KeyData)) {
encrypted = true ;
if ( PackData . size ( ) <= 0 ) encrypted = false ;
if ( KeyData . size ( ) <= 0 ) encrypted = false ;
} ;
if (!encrypted) {
m = tr("Encryption failure") ;
encryptReport -> append ( m ) ;
menu -> setEnabled ( true ) ;
plan -> processEvents ( ) ;
Alert ( Error ) ;
return ;
} ;
////////////////////////////////////////////////////////////////
QDir K ;
QDir E ;
if ( plan -> Booleans [ "Desktop" ] ) {
K = QDir ( Root.absoluteFilePath("Upload" ) ) ;
E = QDir ( Root.absoluteFilePath("Download" ) ) ;
} else {
K = QDir ( Root.absoluteFilePath("Keys" ) ) ;
E = QDir ( Root.absoluteFilePath("Encryption") ) ;
} ;
////////////////////////////////////////////////////////////////
if (PackData.size()>0) {
QImage O ;
if (N::Images::Embedded(SrcImage,O,PackData)) {
QString FO = QString("PSH-%1.png").arg(packaging) ;
FO = E . absoluteFilePath ( FO ) ;
if ( O . save ( FO ) ) {
QString XP ;
XP = FO ;
XP = Root.relativeFilePath ( XP ) ;
m = tr("Steganographic picture saved at `%1`.").arg(XP) ;
encryptReport -> append ( m ) ;
plan -> processEvents ( ) ;
} else {
m = tr("Steganographic picture can not be saved.") ;
encryptReport -> append ( m ) ;
menu -> setEnabled ( true ) ;
Alert ( Error ) ;
plan -> processEvents ( ) ;
return ;
} ;
} else {
m = tr("Data is too big to fit into the picture.") ;
encryptReport -> append ( m ) ;
menu -> setEnabled ( true ) ;
plan -> processEvents ( ) ;
Alert ( Error ) ;
return ;
} ;
} ;
////////////////////////////////////////////////////////////////
if (KeyData .size()>0) {
QImage O ;
if (N::Images::Embedded(KeyImage,O,KeyData)) {
QString FO = QString("KEY-%1.png").arg(packaging) ;
FO = K . absoluteFilePath ( FO ) ;
if ( O . save ( FO ) ) {
QString XP ;
XP = FO ;
XP = Root.relativeFilePath ( XP ) ;
m = tr("Steganographic key saved at `%1`.").arg(XP) ;
encryptReport -> append ( m ) ;
plan -> processEvents ( ) ;
} else {
m = tr("Steganographic key can not be saved.") ;
encryptReport -> append ( m ) ;
menu -> setEnabled ( true ) ;
plan -> processEvents ( ) ;
Alert ( Error ) ;
return ;
} ;
} else {
m = tr("Key data is too big to fit into the picture.") ;
encryptReport -> append ( m ) ;
menu -> setEnabled ( true ) ;
plan -> processEvents ( ) ;
Alert ( Error ) ;
return ;
} ;
} ;
////////////////////////////////////////////////////////////////
if (XZ.length()>0) {
QFileInfo FXZ ( XZ ) ;
if (FXZ.exists()) QFile :: remove ( XZ ) ;
} ;
////////////////////////////////////////////////////////////////
if ( ! plan -> Booleans [ "Desktop" ] ) {
SqlConnection SC ( plan -> sql ) ;
if (SC.open("PaintingSecretGui","DoEncrypt")) {
SC . assureUuid ( PlanTable(MajorUuid) , packaging , 260 ) ;
SC . close ( ) ;
} ;
SC . remove ( ) ;
} ;
////////////////////////////////////////////////////////////////
SourcePicture = "" ;
KeyPicture = "" ;
////////////////////////////////////////////////////////////////
m = tr("Encryption successful, please go to `Depot` to see the results, or use FTP upload to your target machine.") ;
encryptReport -> append ( m ) ;
m = tr("Do not change the image file format, otherwise the data hidden in the picture will be lost.") ;
encryptReport -> append ( m ) ;
menu -> setEnabled ( true ) ;
plan -> processEvents ( ) ;
Alert ( Error ) ;
}
void N::PaintingSecretGui::DataPicture(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( pickEncrypt ) ;
menu -> setCurrentWidget ( getEncrypt ) ;
label -> setText ( tr("Pick picture for decryption") ) ;
Alert ( Error ) ;
getEncrypt -> setEnabled ( false ) ;
plan -> processEvents ( ) ;
pickEncrypt -> Index = 0 ;
pickEncrypt -> Refresh ( ) ;
getEncrypt -> setEnabled ( true ) ;
}
void N::PaintingSecretGui::DataKey(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( pickKey ) ;
menu -> setCurrentWidget ( getKeyPic ) ;
label -> setText ( tr("Pick key picture for decryption") ) ;
Alert ( Error ) ;
getKeyPic -> setEnabled ( false ) ;
plan -> processEvents ( ) ;
pickKey -> Index = 0 ;
pickKey -> Refresh ( ) ;
getKeyPic -> setEnabled ( true ) ;
}
void N::PaintingSecretGui::DoDecrypt(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( decryptReport ) ;
menu -> setCurrentWidget ( decrypt ) ;
menu -> setEnabled ( false ) ;
//////////////////////////////////////////////////////////////////////////
QString m ;
QString rp ;
decryptReport -> clear ( ) ;
plan -> processEvents ( ) ;
if (DecryptPicture.length()<=0) {
m = tr("You did not specify your encrypted picture." ) ;
decryptReport -> append ( m ) ;
menu -> setEnabled ( true ) ;
plan -> processEvents ( ) ;
Alert ( Error ) ;
return ;
} ;
//////////////////////////////////////////////////////////////////////////
QFileInfoList L = pickKey->Root.entryInfoList (
QDir::Files |
QDir::NoDotAndDotDot |
QDir::NoSymLinks ) ;
QStringList S ;
for (int i=0;i<L.count();i++) S << L[i].fileName() ;
//////////////////////////////////////////////////////////////////////////
if (DecryptKey.length()>0) {
int index = S . indexOf ( DecryptKey ) ;
if (index>=0) S . takeAt ( index ) ;
S . prepend ( DecryptKey ) ;
} ;
if (S.count()<=0) {
m = tr("No decryption picture found.") ;
decryptReport -> append ( m ) ;
menu -> setEnabled ( true ) ;
plan -> processEvents ( ) ;
Alert ( Error ) ;
return ;
} ;
//////////////////////////////////////////////////////////////////////////
QImage SRC ;
QImage KEY ;
QByteArray Body ;
SUID srid = 0 ;
bool correct = true ;
rp = pickEncrypt->Root.absoluteFilePath ( DecryptPicture ) ;
if (!SRC.load(rp)) correct = false ;
if (correct) {
if (!Images::Extract(SRC,Body)) correct = false ;
} ;
if (correct) {
int t = Images::DecryptPair(Body,srid) ;
if (t!=1) correct = false ;
} ;
if (!correct) {
m = tr("Decryption failure.") ;
decryptReport -> append ( m ) ;
menu -> setEnabled ( true ) ;
plan -> processEvents ( ) ;
Alert ( Error ) ;
return ;
} ;
//////////////////////////////////////////////////////////////////////////
correct = false ;
for (int i=0;!correct && i<S.count();i++) {
QString s = S[i] ;
rp = pickKey->Root.absoluteFilePath(s) ;
KEY = QImage() ;
if (KEY.load(rp)) {
QByteArray KB ;
decryptReport -> append ( s ) ;
plan -> processEvents ( ) ;
if (Images::Extract(KEY,KB)) {
SUID krid = 0 ;
int t = Images::DecryptPair(KB,krid) ;
if (t==0 && krid==srid) {
QByteArray XZB ;
if (Images::DecryptBody(srid,XZB,Body,KB)) {
if (XZB.size()>0) {
QString fs = QString("Temp/%1.tar.xz").arg(srid) ;
fs = Root.absoluteFilePath(fs) ;
File :: toFile ( fs , XZB ) ;
QString dd = QString("Files/%1").arg(srid) ;
dd = Root.absoluteFilePath ( dd ) ;
VirtualIO VIO ;
QDir vdd ( dd ) ;
VIO . setDirectory ( vdd ) ;
VIO . setFile ( File::Xz ) ;
VIO . setVIO ( VirtualDisk::Tar ) ;
VIO . setFileName ( fs ) ;
VIO . Unpack ( ) ;
m = tr("Decrypt %1 successful").arg(srid) ;
decryptReport -> append ( m ) ;
if (VIO.files.count()>0) {
m = "===================" ;
decryptReport -> append ( m ) ;
m = tr("Decrypted files") ;
decryptReport -> append ( m ) ;
m = "===================" ;
decryptReport -> append ( m ) ;
plan -> processEvents ( ) ;
for (int i=0;i<VIO.files.count();i++) {
m = QString("Files/%1/%2").arg(srid).arg(VIO.files[i].Filename) ;
decryptReport -> append ( m ) ;
plan -> processEvents ( ) ;
} ;
m = "===================" ;
decryptReport -> append ( m ) ;
plan -> processEvents ( ) ;
m = tr("Please use FTP download to your machine for usage.") ;
decryptReport -> append ( m ) ;
plan -> processEvents ( ) ;
} ;
QFile :: remove ( fs ) ;
correct = true ;
} ;
} ;
} ;
} ;
} ;
} ;
if (!correct) {
m = tr("Decryption failure.") ;
decryptReport -> append ( m ) ;
menu -> setEnabled ( true ) ;
plan -> processEvents ( ) ;
Alert ( Error ) ;
return ;
} ;
//////////////////////////////////////////////////////////////////////////
DecryptPicture = "" ;
DecryptKey = "" ;
//////////////////////////////////////////////////////////////////////////
menu -> setEnabled ( true ) ;
Alert ( Error ) ;
}
void N::PaintingSecretGui::DepotList(void)
{
emit FullDepot ( ) ;
}
void N::PaintingSecretGui::DepotPictures(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( pickPicture ) ;
menu -> setCurrentWidget ( viewImages ) ;
label -> setText ( tr("Pictures") ) ;
Alert ( Error ) ;
viewImages -> setEnabled ( false ) ;
plan -> processEvents ( ) ;
pickPicture -> Index = 0 ;
pickPicture -> Refresh ( ) ;
viewImages -> setEnabled ( true ) ;
///////////////////////////////////////////////
BackWidget = pickPicture ;
BackMenu = viewImages ;
ReturnLabel = tr("Pictures") ;
}
void N::PaintingSecretGui::DepotKeys(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( pickKey ) ;
menu -> setCurrentWidget ( viewKeys ) ;
label -> setText ( tr("Decryption key pictures") ) ;
Alert ( Error ) ;
viewKeys -> setEnabled ( false ) ;
plan -> processEvents ( ) ;
pickKey -> Index = 0 ;
pickKey -> Refresh ( ) ;
viewKeys -> setEnabled ( true ) ;
//////////////////////////////////////////////////////////////
BackWidget = pickKey ;
BackMenu = viewKeys ;
ReturnLabel = tr("Decryption key pictures") ;
}
void N::PaintingSecretGui::DepotEncrypted(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( pickEncrypt ) ;
menu -> setCurrentWidget ( viewEncrypt ) ;
label -> setText ( tr("Encrypted pictures") ) ;
Alert ( Error ) ;
viewEncrypt -> setEnabled ( false ) ;
plan -> processEvents ( ) ;
pickEncrypt -> Index = 0 ;
pickEncrypt -> Refresh ( ) ;
viewEncrypt -> setEnabled ( true ) ;
/////////////////////////////////////////////////////////
BackWidget = pickEncrypt ;
BackMenu = viewEncrypt ;
ReturnLabel = tr("Encrypted pictures") ;
}
void N::PaintingSecretGui::DepotFtp(void)
{
emit FullFtp ( ) ;
}
void N::PaintingSecretGui::ViewPicture(void)
{
QString path ;
if (!pickPicture->CurrentPath(path)) return ;
QString file = pickPicture->Root.absoluteFilePath ( path ) ;
////////////////////////////////////////////////////////////
QFileInfo IFG(file) ;
if (!IFG.exists()) return ;
picTool = new PaintingViewTool ( menu , plan ) ;
vcf = new VcfView ( stack , plan ) ;
menu -> addWidget ( picTool ) ;
stack -> addWidget ( vcf ) ;
menu -> setCurrentWidget ( picTool ) ;
stack -> setCurrentWidget ( vcf ) ;
header -> setCurrentWidget ( label ) ;
plan -> processEvents ( ) ;
vcf -> ViewPicture ( IFG , NULL ) ;
vcf -> resize ( stack->size() ) ;
Alert ( Done ) ;
////////////////////////////////////////////////////////////
vcf -> skipMouse = true ;
nConnect ( picTool , SIGNAL(Back ()) ,
this , SLOT (ReturnPick()) ) ;
nConnect ( picTool , SIGNAL(ZoomIn ()) ,
vcf , SLOT (ZoomIn ()) ) ;
nConnect ( picTool , SIGNAL(ZoomOut ()) ,
vcf , SLOT (ZoomOut ()) ) ;
}
void N::PaintingSecretGui::ReturnPick(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( pickPicture ) ;
menu -> setCurrentWidget ( srcPicture ) ;
label -> setText ( tr("Pick picture for encryption") ) ;
Alert ( Error ) ;
///////////////////////////////////////////////////////////////////
picTool -> deleteLater ( ) ;
vcf -> deleteLater ( ) ;
///////////////////////////////////////////////////////////////////
picTool = NULL ;
vcf = NULL ;
}
void N::PaintingSecretGui::ViewEncrypted(void)
{
QString path ;
if (!pickEncrypt->CurrentPath(path)) return ;
QString file = pickEncrypt->Root.absoluteFilePath ( path ) ;
////////////////////////////////////////////////////////////
QFileInfo IFG(file) ;
if (!IFG.exists()) return ;
picTool = new PaintingViewTool ( menu , plan ) ;
vcf = new VcfView ( stack , plan ) ;
menu -> addWidget ( picTool ) ;
stack -> addWidget ( vcf ) ;
menu -> setCurrentWidget ( picTool ) ;
stack -> setCurrentWidget ( vcf ) ;
header -> setCurrentWidget ( label ) ;
plan -> processEvents ( ) ;
vcf -> ViewPicture ( IFG , NULL ) ;
vcf -> resize ( stack->size() ) ;
Alert ( Done ) ;
////////////////////////////////////////////////////////////
vcf -> skipMouse = true ;
nConnect ( picTool , SIGNAL(Back ()) ,
this , SLOT (ReturnEncrypted()) ) ;
nConnect ( picTool , SIGNAL(ZoomIn ()) ,
vcf , SLOT (ZoomIn ()) ) ;
nConnect ( picTool , SIGNAL(ZoomOut ()) ,
vcf , SLOT (ZoomOut ()) ) ;
}
void N::PaintingSecretGui::ReturnEncrypted(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( pickEncrypt ) ;
menu -> setCurrentWidget ( getEncrypt ) ;
label -> setText ( tr("Pick picture for decryption") ) ;
Alert ( Error ) ;
///////////////////////////////////////////////////////////////////
picTool -> deleteLater ( ) ;
vcf -> deleteLater ( ) ;
///////////////////////////////////////////////////////////////////
picTool = NULL ;
vcf = NULL ;
}
void N::PaintingSecretGui::ViewKeys(void)
{
QString path ;
if (!pickKey->CurrentPath(path)) return ;
QString file = pickKey->Root.absoluteFilePath ( path ) ;
////////////////////////////////////////////////////////////
QFileInfo IFG(file) ;
if (!IFG.exists()) return ;
picTool = new PaintingViewTool ( menu , plan ) ;
vcf = new VcfView ( stack , plan ) ;
menu -> addWidget ( picTool ) ;
stack -> addWidget ( vcf ) ;
menu -> setCurrentWidget ( picTool ) ;
stack -> setCurrentWidget ( vcf ) ;
header -> setCurrentWidget ( label ) ;
plan -> processEvents ( ) ;
vcf -> ViewPicture ( IFG , NULL ) ;
vcf -> resize ( stack->size() ) ;
Alert ( Done ) ;
////////////////////////////////////////////////////////////
vcf -> skipMouse = true ;
nConnect ( picTool , SIGNAL(Back ()) ,
this , SLOT (ReturnKeys()) ) ;
nConnect ( picTool , SIGNAL(ZoomIn ()) ,
vcf , SLOT (ZoomIn ()) ) ;
nConnect ( picTool , SIGNAL(ZoomOut ()) ,
vcf , SLOT (ZoomOut ()) ) ;
}
void N::PaintingSecretGui::ReturnKeys(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( pickKey ) ;
menu -> setCurrentWidget ( getKeyPic ) ;
label -> setText ( tr("Pick key picture for decryption") ) ;
Alert ( Error ) ;
///////////////////////////////////////////////////////////////////
picTool -> deleteLater ( ) ;
vcf -> deleteLater ( ) ;
///////////////////////////////////////////////////////////////////
picTool = NULL ;
vcf = NULL ;
}
void N::PaintingSecretGui::ViewDepot(void)
{
QString path ;
PickPicture * pp = (PickPicture *)BackWidget ;
if (!pp->CurrentPath(path)) return ;
QString file = pp->Root.absoluteFilePath ( path ) ;
////////////////////////////////////////////////////////////
QFileInfo IFG(file) ;
if (!IFG.exists()) return ;
picTool = new PaintingViewTool ( menu , plan ) ;
vcf = new VcfView ( stack , plan ) ;
menu -> addWidget ( picTool ) ;
stack -> addWidget ( vcf ) ;
menu -> setCurrentWidget ( picTool ) ;
stack -> setCurrentWidget ( vcf ) ;
header -> setCurrentWidget ( label ) ;
plan -> processEvents ( ) ;
vcf -> ViewPicture ( IFG , NULL ) ;
vcf -> resize ( stack->size() ) ;
Alert ( Done ) ;
////////////////////////////////////////////////////////////
vcf -> skipMouse = true ;
nConnect ( picTool , SIGNAL(Back ()) ,
this , SLOT (ReturnDepot()) ) ;
nConnect ( picTool , SIGNAL(ZoomIn ()) ,
vcf , SLOT (ZoomIn ()) ) ;
nConnect ( picTool , SIGNAL(ZoomOut ()) ,
vcf , SLOT (ZoomOut ()) ) ;
}
void N::PaintingSecretGui::ReturnDepot(void)
{
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( BackWidget ) ;
menu -> setCurrentWidget ( BackMenu ) ;
label -> setText ( ReturnLabel ) ;
Alert ( Error ) ;
//////////////////////////////////////////////
picTool -> deleteLater ( ) ;
vcf -> deleteLater ( ) ;
//////////////////////////////////////////////
picTool = NULL ;
vcf = NULL ;
}
void N::PaintingSecretGui::ObtainPic(void)
{
QString path ;
if (!pickPicture->CurrentPath(path)) return ;
QString file = pickPicture->Root.absoluteFilePath ( path ) ;
//////////////////////////////////////////////////////////////////
QFileInfo IFG(file) ;
if (!IFG.exists()) return ;
//////////////////////////////////////////////////////////////////
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( encryptReport ) ;
menu -> setCurrentWidget ( encrypt ) ;
label -> setText ( tr("Encrypt data into a picture") ) ;
//////////////////////////////////////////////////////////////////
SourcePicture = file ;
}
void N::PaintingSecretGui::ObtainKey(void)
{
QString path ;
if (!pickPicture->CurrentPath(path)) return ;
QString file = pickPicture->Root.absoluteFilePath ( path ) ;
//////////////////////////////////////////////////////////////////
QFileInfo IFG(file) ;
if (!IFG.exists()) return ;
//////////////////////////////////////////////////////////////////
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( encryptReport ) ;
menu -> setCurrentWidget ( encrypt ) ;
label -> setText ( tr("Encrypt data into a picture") ) ;
//////////////////////////////////////////////////////////////////
KeyPicture = file ;
}
void N::PaintingSecretGui::ObtainEncrypted(void)
{
QString path ;
if (!pickEncrypt->CurrentPath(path)) return ;
QString file = pickEncrypt->Root.absoluteFilePath ( path ) ;
////////////////////////////////////////////////////////////////
QFileInfo IFG(file) ;
if (!IFG.exists()) return ;
////////////////////////////////////////////////////////////////
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( decryptReport ) ;
menu -> setCurrentWidget ( decrypt ) ;
label -> setText ( tr("Decrypt data from picture") ) ;
////////////////////////////////////////////////////////////////
DecryptPicture = file ;
}
void N::PaintingSecretGui::ObtainKeys(void)
{
QString path ;
if (!pickKey->CurrentPath(path)) return ;
QString file = pickKey->Root.absoluteFilePath ( path ) ;
////////////////////////////////////////////////////////////////
QFileInfo IFG(file) ;
if (!IFG.exists()) return ;
////////////////////////////////////////////////////////////////
header -> setCurrentWidget ( label ) ;
stack -> setCurrentWidget ( decryptReport ) ;
menu -> setCurrentWidget ( decrypt ) ;
label -> setText ( tr("Decrypt data from picture") ) ;
////////////////////////////////////////////////////////////////
DecryptKey = file ;
}
void N::PaintingSecretGui::FileRename(void)
{
header -> setCurrentWidget ( lineRename ) ;
QTreeWidgetItem * item = pickArchive->currentItem ( ) ;
if (NotNull(item)) {
QString path = item -> text ( 0 ) ;
QDir cp = pickArchive -> CurrentPath ( ) ;
QDir rp = pickArchive -> Path ( ) ;
path = cp . absoluteFilePath ( path ) ;
path = rp . relativeFilePath ( path ) ;
lineRename -> blockSignals ( true ) ;
lineRename -> setText ( path ) ;
lineRename -> blockSignals ( false ) ;
} else {
lineRename -> blockSignals ( true ) ;
lineRename -> setText ( "" ) ;
lineRename -> blockSignals ( false ) ;
} ;
lineRename -> setFocus ( Qt::TabFocusReason ) ;
}
void N::PaintingSecretGui::RenameAction(void)
{
QTreeWidgetItem * item = pickArchive->currentItem ( ) ;
if (NotNull(item)) {
QString name = lineRename->text() ;
QString path = item -> text ( 0 ) ;
QDir cp = pickArchive -> CurrentPath ( ) ;
QDir rp = pickArchive -> Path ( ) ;
path = cp . absoluteFilePath ( path ) ;
if (name.length()>0) {
name = rp . absoluteFilePath ( name ) ;
if (name.length()>0 && path.length()) {
QFile :: rename ( path , name ) ;
} ;
} ;
} ;
header -> setCurrentWidget ( folderList ) ;
plan -> processEvents ( ) ;
pickArchive -> List ( ) ;
Alert ( Error ) ;
}
void N::PaintingSecretGui::FileMove(void)
{
header -> setCurrentWidget ( lineMove ) ;
QTreeWidgetItem * item = pickArchive->currentItem ( ) ;
if (NotNull(item)) {
QString path = item -> text ( 0 ) ;
QDir cp = pickArchive -> CurrentPath ( ) ;
QDir rp = pickArchive -> Path ( ) ;
path = cp . absoluteFilePath ( path ) ;
path = rp . relativeFilePath ( path ) ;
lineMove -> blockSignals ( true ) ;
lineMove -> setText ( path ) ;
lineMove -> blockSignals ( false ) ;
} else {
lineMove -> blockSignals ( true ) ;
lineMove -> setText ( "" ) ;
lineMove -> blockSignals ( false ) ;
} ;
lineMove -> setFocus ( Qt::TabFocusReason ) ;
}
void N::PaintingSecretGui::MoveAction(void)
{
QTreeWidgetItem * item = pickArchive->currentItem ( ) ;
if (NotNull(item)) {
QString name = lineMove->text() ;
QString path = item -> text ( 0 ) ;
QDir cp = pickArchive -> CurrentPath ( ) ;
QDir rp = pickArchive -> Path ( ) ;
path = cp . absoluteFilePath ( path ) ;
if (name.length()>0) {
name = rp . absoluteFilePath ( name ) ;
if (name.length()>0 && path.length()) {
QFile :: rename ( path , name ) ;
} ;
} ;
} ;
header -> setCurrentWidget ( folderList ) ;
plan -> processEvents ( ) ;
pickArchive -> List ( ) ;
Alert ( Error ) ;
}
void N::PaintingSecretGui::FileDirectory(void)
{
header -> setCurrentWidget ( lineDirectory ) ;
lineDirectory -> blockSignals ( true ) ;
lineDirectory -> setText ( "" ) ;
lineDirectory -> blockSignals ( false ) ;
lineDirectory -> setFocus ( Qt::TabFocusReason ) ;
}
void N::PaintingSecretGui::DirectoryAction(void)
{
QString name = lineDirectory -> text ( ) ;
if (name.length()>0) {
QDir cp = pickArchive -> CurrentPath ( ) ;
QDir rp = pickArchive -> Path ( ) ;
QString path = cp . absoluteFilePath ( name ) ;
QString tp = rp . absoluteFilePath ( "" ) ;
if (path.contains(tp)) {
cp . mkdir ( name ) ;
} ;
} ;
header -> setCurrentWidget ( folderList ) ;
plan -> processEvents ( ) ;
pickArchive -> List ( ) ;
Alert ( Error ) ;
}
void N::PaintingSecretGui::FolderBack(void)
{
header -> setCurrentWidget ( folderList ) ;
}
void N::PaintingSecretGui::EditText(void)
{
QTreeWidgetItem * item = pickArchive->currentItem ( ) ;
if (IsNull(item)) return ;
QDir cp = pickArchive -> CurrentPath ( ) ;
QString path = item -> text ( 0 ) ;
path = cp . absoluteFilePath ( path ) ;
QFileInfo F ( path ) ;
QString S = F.suffix () ;
S = S.toLower() ;
if ( S != "txt" ) return ;
emit LoadText ( pickArchive->Path() , pickArchive -> CurrentPath() , path ) ;
#ifdef XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
////////////////////////////////////////////////////////////
plainText -> clear ( ) ;
header -> setCurrentWidget ( line ) ;
stack -> setCurrentWidget ( plainText ) ;
menu -> setCurrentWidget ( textEdit ) ;
label -> setText ( tr("Plain text editor" ) ) ;
////////////////////////////////////////////////////////////
QByteArray Body ;
File :: toByteArray ( path , Body ) ;
plainText -> blockSignals ( true ) ;
plainText -> append ( QString::fromUtf8(Body) ) ;
plainText -> verticalScrollBar ( ) -> setValue ( 0 ) ;
plainText -> blockSignals ( false ) ;
////////////////////////////////////////////////////////////
line -> blockSignals ( true ) ;
line -> setText ( item -> text ( 0 ) ) ;
line -> blockSignals ( false ) ;
////////////////////////////////////////////////////////////
Alert ( Error ) ;
#endif
}
void N::PaintingSecretGui::BackEdit(void)
{
header -> setCurrentWidget ( folderList ) ;
stack -> setCurrentWidget ( pickArchive ) ;
menu -> setCurrentWidget ( folderEdit ) ;
plan -> processEvents ( ) ;
pickArchive -> List ( ) ;
Alert ( Click ) ;
}
void N::PaintingSecretGui::NewEdit(void)
{
plainText -> clear ( ) ;
}
void N::PaintingSecretGui::SaveEdit(void)
{
QString note = line->text() ;
if (note.length()<=0) return ;
QDir r = pickArchive -> Path( ) ;
QString file = r.absoluteFilePath ( note ) ;
QString head = r.absoluteFilePath ( "" ) ;
if (!file.contains(head)) return ;
QString text = plainText -> toPlainText ( ) ;
QByteArray body = text . toUtf8 ( ) ;
QFileInfo fdir ( file ) ;
r . mkpath ( fdir . absolutePath ( ) ) ;
File :: toFile ( file , body ) ;
/////////////////////////////////////////////////
header -> setCurrentWidget ( folderList ) ;
stack -> setCurrentWidget ( pickArchive ) ;
menu -> setCurrentWidget ( folderEdit ) ;
plan -> processEvents ( ) ;
pickArchive -> List ( ) ;
Alert ( Click ) ;
}
void N::PaintingSecretGui::FileFtp(void)
{
QString path = pickArchive->CurrentPath().absoluteFilePath("") ;
emit Transfer ( path ) ;
}
void N::PaintingSecretGui::ImportPicture(void)
{
QString path = pickPicture->Root.absoluteFilePath("") ;
emit Obtain ( path ) ;
}
void N::PaintingSecretGui::ImportKey(void)
{
QString path = pickPicture->Root.absoluteFilePath("") ;
emit Obtain ( path ) ;
}
void N::PaintingSecretGui::ImportEncrypted(void)
{
QString path = pickEncrypt->Root.absoluteFilePath("") ;
emit Transfer ( path ) ;
}
void N::PaintingSecretGui::ImportKeys(void)
{
QString path = pickKey->Root.absoluteFilePath("") ;
emit Transfer ( path ) ;
}
| 53.919092 | 119 | 0.332223 | Vladimir-Lin |
6ed6e77359a63b9ad0bf7f144a6129153538d41a | 3,112 | cpp | C++ | Engine/Plugins/Online/OnlineSubsystemUtils/Source/OnlineSubsystemUtils/Private/ShowLoginUICallbackProxy.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Plugins/Online/OnlineSubsystemUtils/Source/OnlineSubsystemUtils/Private/ShowLoginUICallbackProxy.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Plugins/Online/OnlineSubsystemUtils/Source/OnlineSubsystemUtils/Private/ShowLoginUICallbackProxy.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "ShowLoginUICallbackProxy.h"
#include "EngineGlobals.h"
#include "Engine/Engine.h"
#include "GameFramework/PlayerState.h"
#include "GameFramework/PlayerController.h"
#include "Engine/LocalPlayer.h"
#include "OnlineSubsystem.h"
#include "OnlineSubsystemBPCallHelper.h"
#include "Interfaces/OnlineExternalUIInterface.h"
UShowLoginUICallbackProxy::UShowLoginUICallbackProxy(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
, WorldContextObject(nullptr)
{
}
UShowLoginUICallbackProxy* UShowLoginUICallbackProxy::ShowExternalLoginUI(UObject* WorldContextObject, APlayerController* InPlayerController)
{
UShowLoginUICallbackProxy* Proxy = NewObject<UShowLoginUICallbackProxy>();
Proxy->PlayerControllerWeakPtr = InPlayerController;
Proxy->WorldContextObject = WorldContextObject;
return Proxy;
}
void UShowLoginUICallbackProxy::Activate()
{
APlayerController* MyPlayerController = PlayerControllerWeakPtr.Get();
if (!MyPlayerController)
{
FFrame::KismetExecutionMessage(TEXT("A player controller must be provided in order to show the external login UI."), ELogVerbosity::Warning);
OnFailure.Broadcast(MyPlayerController);
return;
}
const FOnlineSubsystemBPCallHelper Helper(TEXT("ShowLoginUI"), WorldContextObject);
if (Helper.OnlineSub == nullptr)
{
OnFailure.Broadcast(MyPlayerController);
return;
}
IOnlineExternalUIPtr OnlineExternalUI = Helper.OnlineSub->GetExternalUIInterface();
if (!OnlineExternalUI.IsValid())
{
FFrame::KismetExecutionMessage(TEXT("External UI not supported by the current online subsystem"), ELogVerbosity::Warning);
OnFailure.Broadcast(MyPlayerController);
return;
}
const ULocalPlayer* LocalPlayer = Cast<ULocalPlayer>(MyPlayerController->Player);
if (LocalPlayer == nullptr)
{
FFrame::KismetExecutionMessage(TEXT("Can only show login UI for local players"), ELogVerbosity::Warning);
OnFailure.Broadcast(MyPlayerController);
return;
}
const bool bWaitForDelegate = OnlineExternalUI->ShowLoginUI(LocalPlayer->GetControllerId(), false, false,
FOnLoginUIClosedDelegate::CreateUObject(this, &UShowLoginUICallbackProxy::OnShowLoginUICompleted));
if (!bWaitForDelegate)
{
FFrame::KismetExecutionMessage(TEXT("The online subsystem couldn't show its login UI"), ELogVerbosity::Log);
OnFailure.Broadcast(MyPlayerController);
}
}
void UShowLoginUICallbackProxy::OnShowLoginUICompleted(TSharedPtr<const FUniqueNetId> UniqueId, int LocalPlayerNum)
{
// Update the cached unique ID for the local player and the player state.
APlayerController* MyPlayerController = PlayerControllerWeakPtr.Get();
if (MyPlayerController != nullptr)
{
ULocalPlayer* LocalPlayer = MyPlayerController->GetLocalPlayer();
if (LocalPlayer != nullptr)
{
LocalPlayer->SetCachedUniqueNetId(UniqueId);
}
if (MyPlayerController->PlayerState != nullptr)
{
MyPlayerController->PlayerState->SetUniqueId(UniqueId);
}
}
if (UniqueId.IsValid())
{
OnSuccess.Broadcast(MyPlayerController);
}
else
{
OnFailure.Broadcast(MyPlayerController);
}
}
| 31.755102 | 143 | 0.793059 | windystrife |
6ed8d02b14716e8d04470d3b09828cf51c00c8d2 | 1,266 | cpp | C++ | src/shogun/loss/HingeLoss.cpp | ShankarNara/shogun | 8ab196de16b8d8917e5c84770924c8d0f5a3d17c | [
"BSD-3-Clause"
] | 2,753 | 2015-01-02T11:34:13.000Z | 2022-03-25T07:04:27.000Z | src/shogun/loss/HingeLoss.cpp | ShankarNara/shogun | 8ab196de16b8d8917e5c84770924c8d0f5a3d17c | [
"BSD-3-Clause"
] | 2,404 | 2015-01-02T19:31:41.000Z | 2022-03-09T10:58:22.000Z | src/shogun/loss/HingeLoss.cpp | ShankarNara/shogun | 8ab196de16b8d8917e5c84770924c8d0f5a3d17c | [
"BSD-3-Clause"
] | 1,156 | 2015-01-03T01:57:21.000Z | 2022-03-26T01:06:28.000Z | /*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Authors: Fernando Iglesias, Shashwat Lal Das
*/
#include <shogun/loss/HingeLoss.h>
#include <shogun/mathematics/Math.h>
using namespace shogun;
float64_t HingeLoss::loss(float64_t prediction, float64_t label)
{
float64_t e = 1 - label * prediction;
return (e > 0) ? e : 0;
}
float64_t HingeLoss::loss(float64_t z)
{
return Math::max(0.0, z);
}
float64_t HingeLoss::first_derivative(float64_t prediction, float64_t label)
{
return (label * prediction >= label * label) ? 0 : -label;
}
float64_t HingeLoss::first_derivative(float64_t z)
{
return z > 0.0 ? 1.0 : 0.0;
}
float64_t HingeLoss::second_derivative(float64_t prediction, float64_t label)
{
return 0.;
}
float64_t HingeLoss::second_derivative(float64_t z)
{
return 0;
}
float64_t HingeLoss::get_update(float64_t prediction, float64_t label, float64_t eta_t, float64_t norm)
{
if (label * prediction >= label * label)
return 0;
float64_t err = (label*label - label*prediction)/(label * label);
float64_t normal = eta_t;
return label * (normal < err ? normal : err)/norm;
}
float64_t HingeLoss::get_square_grad(float64_t prediction, float64_t label)
{
return first_derivative(prediction, label);
}
| 22.210526 | 103 | 0.731438 | ShankarNara |
6edb231d511296e3cc3f04fab65844934e4425b2 | 3,697 | cc | C++ | src/page.cc | minkezhang/giga | bae6fe295e417b132ba5b6064fb25906188e3cbe | [
"MIT"
] | 1 | 2016-11-23T14:55:29.000Z | 2016-11-23T14:55:29.000Z | src/page.cc | cripplet/giga | bae6fe295e417b132ba5b6064fb25906188e3cbe | [
"MIT"
] | null | null | null | src/page.cc | cripplet/giga | bae6fe295e417b132ba5b6064fb25906188e3cbe | [
"MIT"
] | 1 | 2021-12-24T23:08:00.000Z | 2021-12-24T23:08:00.000Z | #include <random>
#include <sstream>
#include <string>
#include <vector>
#include "libs/cachepp/globals.h"
#include "libs/exceptionpp/exception.h"
#include "libs/md5/md5.h"
#include "src/page.h"
giga::Page::Page(cachepp::identifier id, std::string filename, size_t file_offset, size_t size, bool is_dirty) : cachepp::LineInterface<std::string>::LineInterface(id), filename(filename), file_offset(file_offset), size(size) {
this->is_dirty = is_dirty;
this->set_filename(this->filename);
this->data.clear();
this->set_checksum(this->hash());
this->r = rand();
}
giga::Page::~Page() {
// remove tmp file to lessen bloat
if(this->cached.compare(this->filename) != 0 && this->filename.compare("") != 0) {
remove(this->get_filename().c_str());
}
}
size_t giga::Page::get_size() { return(this->size); }
void giga::Page::set_size(size_t size) { this->size = size; }
size_t giga::Page::probe(size_t offset, size_t len, bool is_forward) {
if(offset > this->get_size()) {
throw(exceptionpp::InvalidOperation("giga::Page::probe", "offset is invalid"));
}
if(is_forward) {
return((this->get_size() - offset) > len ? len : (this->get_size() - offset));
} else {
return(offset > len ? len : offset);
}
}
void giga::Page::set_filename(std::string filename) { this->cached = filename; }
std::string giga::Page::get_filename() {
if(this->get_is_dirty()) {
std::stringstream path;
std::stringstream buf;
buf << this->cached << "_" << this->get_identifier();
path << "/tmp/giga/" << md5(buf.str()) << this->r;
return(path.str());
} else {
return(this->cached);
}
}
void giga::Page::set_file_offset(size_t file_offset) { this->file_offset = file_offset; }
void giga::Page::aux_load() {
// deallocate the data vector
this->data.clear();
std::vector<uint8_t>().swap(this->data);
if(this->get_size() == 0) {
return;
}
std::vector<uint8_t> buf(this->get_size(), 0);
// load data into the page
if(!this->get_is_dirty()) {
FILE *fp = fopen(this->get_filename().c_str(), "r");
if(fp == NULL) {
std::stringstream buf;
buf << "cannot open working file '" << this->get_filename() << "'";
throw(exceptionpp::RuntimeError("giga::Page::aux_load", buf.str()));
}
if(fseek(fp, this->file_offset, SEEK_SET) == -1) {
fclose(fp);
fp = NULL;
throw(exceptionpp::RuntimeError("giga::Page::aux_load", "invalid result returned from fseek"));
}
if(fread(buf.data(), sizeof(char), this->get_size(), fp) < this->get_size()) {
fclose(fp);
fp = NULL;
throw(exceptionpp::RuntimeError("giga::Page::aux_load", "invalid result returned from fread"));
}
fclose(fp);
fp = NULL;
buf.swap(this->data);
}
}
void giga::Page::aux_unload() {
this->set_size(this->data.size());
if(this->get_is_dirty()) {
FILE *fp = fopen(this->get_filename().c_str(), "w");
if(fp == NULL) {
std::stringstream buf;
buf << "cannot open working file '" << this->get_filename() << "'";
throw(exceptionpp::RuntimeError("giga::Page::aux_unload", buf.str()));
}
if(fputs(std::string(this->data.begin(), this->data.end()).c_str(), fp) < 0) {
fclose(fp);
fp = NULL;
throw(exceptionpp::RuntimeError("giga::Page::aux_unload", "invalid result returned from fputs"));
}
fclose(fp);
fp = NULL;
// we are now reading a "clean" file again next time
this->set_file_offset(0);
// remove tmp file to lessen bloat
if(this->cached.compare(this->filename)) {
remove(this->cached.c_str());
}
this->set_filename(this->get_filename());
this->set_is_dirty(false);
}
this->data.clear();
std::vector<uint8_t>().swap(this->data);
}
std::string giga::Page::hash() { return(md5(std::string(this->data.begin(), this->data.end()))); }
| 28.007576 | 227 | 0.650798 | minkezhang |
6edcd5c4f6463bf25aca47ed69148505c77bd844 | 292 | cpp | C++ | 11172-Relational_Operators/RO.cpp | dangercard/Uva_Challenges | 735bf80da5d1995fece4614d38174d1ea276e7c2 | [
"Apache-2.0"
] | null | null | null | 11172-Relational_Operators/RO.cpp | dangercard/Uva_Challenges | 735bf80da5d1995fece4614d38174d1ea276e7c2 | [
"Apache-2.0"
] | null | null | null | 11172-Relational_Operators/RO.cpp | dangercard/Uva_Challenges | 735bf80da5d1995fece4614d38174d1ea276e7c2 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std ;
int main()
{
int n,a,b ;
cin >> n ;
while(n--)
{
cin >> a >> b ;
if(a > b)
{
cout << ">" << endl ;
}
else if(b > a)
{
cout << "<" << endl ;
}
else
{
cout << "=" << endl ;
}
}
}
| 10.068966 | 27 | 0.342466 | dangercard |
6ee1d7a9db4930b9f902cd0fba265dd5e38d3983 | 1,445 | hpp | C++ | addons/UH60/config/turrets/pilotCamera.hpp | ZHANGTIANYAO1/H-60 | 4c6764f74190dbe7d81ddeae746cf78d8b7dff92 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 14 | 2021-02-11T23:23:21.000Z | 2021-09-08T05:36:47.000Z | addons/UH60/config/turrets/pilotCamera.hpp | ZHANGTIANYAO1/H-60 | 4c6764f74190dbe7d81ddeae746cf78d8b7dff92 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 130 | 2021-09-09T21:43:16.000Z | 2022-03-30T09:00:37.000Z | addons/UH60/config/turrets/pilotCamera.hpp | ZHANGTIANYAO1/H-60 | 4c6764f74190dbe7d81ddeae746cf78d8b7dff92 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 11 | 2021-02-18T19:55:51.000Z | 2021-09-01T17:08:47.000Z | class OpticsIn
{
class Wide
{
opticsDisplayName = "TRK COR";
initAngleX = 0;
minAngleX = -360;
maxAngleX = 360;
initAngleY = 0;
minAngleY = -15;
maxAngleY = 85;
initFov = 0.3;
minFov = 0.3;
maxFov = 0.3;
visionMode[] = {"Normal", "NVG", "Ti"};
thermalMode[] = {0, 1};
directionStabilized = 1;
horizontallyStabilized = 1;
gunnerOpticsModel = "\A3\Weapons_F\empty";
opticsPPEffects[] = {"OpticsCHAbera3","OpticsBlur3"};
gunnerOpticsEffect[] = {"TankCommanderOptics2"};
};
class WideT: Wide
{
initFov = 0.2;
minFov = 0.2;
maxFov = 0.2;
gunnerOpticsModel = "\A3\Weapons_F\empty";
};
class MediumT: WideT
{
initFov = 0.1;
minFov = 0.1;
maxFov = 0.1;
gunnerOpticsModel = "\A3\Weapons_F\empty";
};
class NarrowT: WideT
{
initFov = 0.022;
minFov = 0.022;
maxFov = 0.022;
gunnerOpticsModel = "\A3\Weapons_F\empty";
};
class NarrowT2: WideT
{
initFov = 0.0092;
minFov = 0.0092;
maxFov = 0.0092;
gunnerOpticsModel = "\A3\Weapons_F\empty";
};
};
stabilizedInAxes = 3;
minElev = -40;
maxElev = 90;
initElev = 0;
minTurn = -180;
maxTurn = 180;
initTurn = 0;
maxXRotSpeed=0.5;
maxYRotSpeed=0.5;
pilotOpticsShowCursor=1;
controllable=1;
| 22.936508 | 61 | 0.536332 | ZHANGTIANYAO1 |
6ee36251eab69097dfc764dd240c98d10b042426 | 145 | hpp | C++ | src/Game.hpp | eXpl0it3r/MartisOpibus | 120910e564f73a8a2ed4822d0a1daf2cb9a15a2f | [
"CC0-1.0"
] | null | null | null | src/Game.hpp | eXpl0it3r/MartisOpibus | 120910e564f73a8a2ed4822d0a1daf2cb9a15a2f | [
"CC0-1.0"
] | null | null | null | src/Game.hpp | eXpl0it3r/MartisOpibus | 120910e564f73a8a2ed4822d0a1daf2cb9a15a2f | [
"CC0-1.0"
] | null | null | null | #pragma once
#include <SFML/Graphics/RenderWindow.hpp>
class Game
{
public:
void Run();
private:
sf::RenderWindow m_window;
};
| 11.153846 | 42 | 0.655172 | eXpl0it3r |
6ee9a6ab36a701feaf86ccfe4d5628281b21c69c | 5,785 | hpp | C++ | vlc_linux/vlc-3.0.16/modules/demux/adaptive/plumbing/CommandsQueue.hpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | vlc_linux/vlc-3.0.16/modules/demux/adaptive/plumbing/CommandsQueue.hpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | vlc_linux/vlc-3.0.16/modules/demux/adaptive/plumbing/CommandsQueue.hpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | /*
* CommandsQueue.hpp
*****************************************************************************
* Copyright © 2015 VideoLAN and VLC Authors
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifndef COMMANDSQUEUE_HPP_
#define COMMANDSQUEUE_HPP_
#include <vlc_common.h>
#include <vlc_es.h>
#include <vlc_atomic.h>
#include <list>
namespace adaptive
{
class FakeESOut;
class FakeESOutID;
class AbstractCommand
{
friend class CommandsFactory;
public:
virtual ~AbstractCommand();
virtual void Execute( es_out_t * ) = 0;
virtual mtime_t getTime() const;
int getType() const;
protected:
AbstractCommand( int );
int type;
};
class AbstractFakeEsCommand : public AbstractCommand
{
protected:
AbstractFakeEsCommand( int, FakeESOutID * );
FakeESOutID *p_fakeid;
};
class EsOutSendCommand : public AbstractFakeEsCommand
{
friend class CommandsFactory;
public:
virtual ~EsOutSendCommand();
virtual void Execute( es_out_t *out );
virtual mtime_t getTime() const;
const void * esIdentifier() const;
protected:
EsOutSendCommand( FakeESOutID *, block_t * );
block_t *p_block;
};
class EsOutDelCommand : public AbstractFakeEsCommand
{
friend class CommandsFactory;
public:
virtual void Execute( es_out_t *out );
protected:
EsOutDelCommand( FakeESOutID * );
};
class EsOutAddCommand : public AbstractFakeEsCommand
{
friend class CommandsFactory;
public:
virtual ~EsOutAddCommand();
virtual void Execute( es_out_t *out );
protected:
EsOutAddCommand( FakeESOutID * );
};
class EsOutControlPCRCommand : public AbstractCommand
{
friend class CommandsFactory;
public:
virtual void Execute( es_out_t *out );
virtual mtime_t getTime() const;
protected:
EsOutControlPCRCommand( int, mtime_t );
int group;
mtime_t pcr;
};
class EsOutDestroyCommand : public AbstractCommand
{
friend class CommandsFactory;
public:
virtual void Execute( es_out_t *out );
protected:
EsOutDestroyCommand();
};
class EsOutControlResetPCRCommand : public AbstractCommand
{
friend class CommandsFactory;
public:
virtual void Execute( es_out_t *out );
protected:
EsOutControlResetPCRCommand();
};
class EsOutMetaCommand : public AbstractCommand
{
friend class CommandsFactory;
public:
virtual void Execute( es_out_t *out );
protected:
EsOutMetaCommand( int, vlc_meta_t * );
virtual ~EsOutMetaCommand();
int group;
vlc_meta_t *p_meta;
};
/* Factory so we can alter behaviour and filter on execution */
class CommandsFactory
{
public:
virtual ~CommandsFactory() {}
virtual EsOutSendCommand * createEsOutSendCommand( FakeESOutID *, block_t * ) const;
virtual EsOutDelCommand * createEsOutDelCommand( FakeESOutID * ) const;
virtual EsOutAddCommand * createEsOutAddCommand( FakeESOutID * ) const;
virtual EsOutControlPCRCommand * createEsOutControlPCRCommand( int, mtime_t ) const;
virtual EsOutControlResetPCRCommand * creatEsOutControlResetPCRCommand() const;
virtual EsOutDestroyCommand * createEsOutDestroyCommand() const;
virtual EsOutMetaCommand * createEsOutMetaCommand( int, const vlc_meta_t * ) const;
};
/* Queuing for doing all the stuff in order */
class CommandsQueue
{
public:
CommandsQueue( CommandsFactory * );
~CommandsQueue();
const CommandsFactory * factory() const;
void Schedule( AbstractCommand * );
mtime_t Process( es_out_t *out, mtime_t );
void Abort( bool b_reset );
void Commit();
bool isEmpty() const;
void setDrop( bool );
void setDraining();
void setEOF( bool );
bool isDraining() const;
bool isEOF() const;
mtime_t getDemuxedAmount(mtime_t) const;
mtime_t getBufferingLevel() const;
mtime_t getFirstDTS() const;
mtime_t getPCR() const;
private:
CommandsFactory *commandsFactory;
void LockedCommit();
void LockedSetDraining();
std::list<AbstractCommand *> incoming;
std::list<AbstractCommand *> commands;
mtime_t bufferinglevel;
mtime_t pcr;
bool b_draining;
bool b_drop;
bool b_eof;
};
}
#endif /* COMMANDSQUEUE_HPP_ */
| 30.935829 | 96 | 0.597407 | Brook1711 |
6eeb77bb351b602838edfcf2dbb32cf286f9c8ba | 1,285 | cpp | C++ | Treap (Cartesian Tree)/Cartesian Tree Build (stack).cpp | yokeshrana/Fast_Algorithms_in_Data_Structures | 2346fee16c6c3ffceac7cb79b1f449b4d8dc9df2 | [
"MIT"
] | 4 | 2021-01-15T16:30:48.000Z | 2021-08-12T03:17:00.000Z | Treap (Cartesian Tree)/Cartesian Tree Build (stack).cpp | andy489/Fast_Algorithms_in_Data_Structures | 0f28a75030df3367902f0aa859a34096ea2b2582 | [
"MIT"
] | null | null | null | Treap (Cartesian Tree)/Cartesian Tree Build (stack).cpp | andy489/Fast_Algorithms_in_Data_Structures | 0f28a75030df3367902f0aa859a34096ea2b2582 | [
"MIT"
] | 2 | 2021-02-24T14:50:08.000Z | 2021-02-28T17:39:41.000Z | // github.com/andy489
#include <vector>
#include <stack>
using namespace std;
vector<int> build(int *A, int n) {
vector<int> parent(n, -1);
stack<int> s;
for (int i = 0; i < n; ++i) {
int last = -1;
while (!s.empty() && A[s.top()] >= A[i]) {
last = s.top();
s.pop();
}
if (!s.empty())
parent[i] = s.top();
if (last >= 0)
parent[last] = i;
s.push(i);
}
return parent;
}
#include <queue>
void display(int u, vector<vector<int>> &adj) {
queue<int> Q;
Q.push(u);
int SZ;
while (!Q.empty()) {
SZ = Q.size();
while (SZ--) {
int cur = Q.front();
Q.pop();
printf("%d ", cur);
for (const int &child: adj[cur])
Q.push(child);
}
printf("\n");
}
}
int main() {
int A[] = {7, 3, 500, 12, 1001, 10, 17, 128};
int n = sizeof A / sizeof(int);
vector<int> CartesianTree = build(A, n);
vector<vector<int>> adj(n, vector<int>());
int root = -1;
for (int i = 0; i < n; ++i) {
if (CartesianTree[i] != -1)
adj[CartesianTree[i]].push_back(i);
else
root = i;
}
return display(root, adj), 0;
}
| 19.769231 | 50 | 0.438911 | yokeshrana |
6ef56e394fd47f690e8ca8dc51d23f417aa34b7f | 2,023 | cpp | C++ | src/KeyboardHook.cpp | Erwan28250/KeyChattering | b69e0b25064232b6bea9a87d6b9070a5dd04d40e | [
"MIT"
] | 1 | 2021-12-18T01:47:28.000Z | 2021-12-18T01:47:28.000Z | src/KeyboardHook.cpp | Erwan28250/KeyChattering | b69e0b25064232b6bea9a87d6b9070a5dd04d40e | [
"MIT"
] | null | null | null | src/KeyboardHook.cpp | Erwan28250/KeyChattering | b69e0b25064232b6bea9a87d6b9070a5dd04d40e | [
"MIT"
] | null | null | null | /*
* MIT Licence
*
* KeyChattering
*
* Copyright © 2021 Erwan Saclier de la Bâtie (Erwan28250)
*
* 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 "KeyboardHook.h"
#include "KeyPressData.h"
#include <iostream>
LRESULT CALLBACK keyHookProc(
int nCode,
WPARAM wParam,
LPARAM lParam)
{
if (nCode < 0)
return CallNextHookEx(nullptr, nCode, wParam, lParam);
switch (wParam)
{
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
{
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;
bool result = KeyPressData::instance()->isKeyPressChatter(p->vkCode);
if (result)
return 1;
} break;
case WM_KEYUP:
case WM_SYSKEYUP:
{
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;
bool result = KeyPressData::instance()->isKeyReleaseChatter(p->vkCode);
if (result)
return 1;
} break;
}
return CallNextHookEx(nullptr, nCode, wParam, lParam);
} | 38.169811 | 160 | 0.692042 | Erwan28250 |
6ef61a9fbe5f82477bca8259bd65ea8a29d33aa5 | 3,212 | hpp | C++ | include/ltac/RegisterManager.hpp | wichtounet/eddic | 66398a493a499eab5d1f465f93f9f099a2140d59 | [
"MIT"
] | 24 | 2015-10-08T23:08:50.000Z | 2021-09-18T21:15:01.000Z | include/ltac/RegisterManager.hpp | wichtounet/eddic | 66398a493a499eab5d1f465f93f9f099a2140d59 | [
"MIT"
] | 1 | 2016-02-29T20:20:45.000Z | 2016-03-03T07:16:53.000Z | include/ltac/RegisterManager.hpp | wichtounet/eddic | 66398a493a499eab5d1f465f93f9f099a2140d59 | [
"MIT"
] | 5 | 2015-08-09T09:53:52.000Z | 2021-09-18T21:15:05.000Z | //=======================================================================
// Copyright Baptiste Wicht 2011-2016.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef LTAC_REGISTER_MANAGER_H
#define LTAC_REGISTER_MANAGER_H
#include <memory>
#include <vector>
#include <unordered_set>
#include "Platform.hpp"
#include "FloatPool.hpp"
#include "mtac/EscapeAnalysis.hpp"
#include "mtac/forward.hpp"
#include "mtac/Argument.hpp"
//Forward is not enough for PseudoRegisters
#include "ltac/Argument.hpp"
#include "ltac/Operator.hpp"
#include "ltac/PseudoRegister.hpp"
#include "ltac/PseudoFloatRegister.hpp"
#include "ltac/Instruction.hpp"
#include "asm/PseudoRegisters.hpp"
namespace eddic {
namespace ltac {
class StatementCompiler;
class RegisterManager {
public:
std::unordered_set<std::shared_ptr<Variable>> written;
std::unordered_set<std::shared_ptr<Variable>> local;
mtac::escaped_variables_ptr pointer_escaped;
mtac::basic_block_p bb;
RegisterManager(FloatPool& float_pool);
/*!
* Deleted copy constructor
*/
RegisterManager(const RegisterManager& rhs) = delete;
/*!
* Deleted copy assignment operator.
*/
RegisterManager& operator=(const RegisterManager& rhs) = delete;
void reset();
ltac::PseudoRegister get_pseudo_reg(std::shared_ptr<Variable> var);
ltac::PseudoRegister get_pseudo_reg_no_move(std::shared_ptr<Variable> var);
ltac::PseudoFloatRegister get_pseudo_float_reg(std::shared_ptr<Variable> var);
ltac::PseudoFloatRegister get_pseudo_float_reg_no_move(std::shared_ptr<Variable> var);
void copy(mtac::Argument argument, ltac::PseudoFloatRegister reg);
void copy(mtac::Argument argument, ltac::PseudoRegister reg, tac::Size size = tac::Size::DEFAULT);
void move(mtac::Argument argument, ltac::PseudoRegister reg);
void move(mtac::Argument argument, ltac::PseudoFloatRegister reg);
ltac::PseudoRegister get_free_pseudo_reg();
ltac::PseudoFloatRegister get_free_pseudo_float_reg();
ltac::PseudoRegister get_bound_pseudo_reg(unsigned short hard);
ltac::PseudoFloatRegister get_bound_pseudo_float_reg(unsigned short hard);
bool is_written(std::shared_ptr<Variable> variable);
void set_written(std::shared_ptr<Variable> variable);
bool is_escaped(std::shared_ptr<Variable> variable);
void collect_parameters(eddic::Function& definition, const PlatformDescriptor* descriptor);
int last_pseudo_reg();
int last_float_pseudo_reg();
void remove_from_pseudo_reg(std::shared_ptr<Variable> variable);
void remove_from_pseudo_float_reg(std::shared_ptr<Variable> variable);
private:
FloatPool& float_pool;
//The pseudo registers
as::PseudoRegisters<ltac::PseudoRegister> pseudo_registers;
as::PseudoRegisters<ltac::PseudoFloatRegister> pseudo_float_registers;
};
} //end of ltac
} //end of eddic
#endif
| 31.184466 | 106 | 0.679639 | wichtounet |
6ef75b61101c57ae2bd1673bc48a238ded03d753 | 710 | cpp | C++ | p/3k/3741/main.cpp | josedelinux/luogu | f9ce86b8623224512aa3f9e1eecc45d3c89c74e4 | [
"MIT"
] | null | null | null | p/3k/3741/main.cpp | josedelinux/luogu | f9ce86b8623224512aa3f9e1eecc45d3c89c74e4 | [
"MIT"
] | null | null | null | p/3k/3741/main.cpp | josedelinux/luogu | f9ce86b8623224512aa3f9e1eecc45d3c89c74e4 | [
"MIT"
] | null | null | null | /*
4 possibilities:
vv(ok)
kk(ok)
vk(ok,target)
kv(unchangeable)
*/
#include <bits/stdc++.h>
#define DEBUGn
using namespace std;
int main() {
int cnt = 0;
int flag = 0; // "yes we can change" flag
int n;
string s;
cin >> n;
cin >> s;
for (int i = 0; i < n - 1; i++) {
int cur = s[i];
int next = s[i + 1];
if (cur == 'V' && next == 'K') {
cnt++;
// disable them
s[i] = tolower(cur);
s[i + 1] = tolower(next);
}
}
for (int i = 0; i < n - 1; i++) {
int cur = s[i];
int next = s[i + 1];
if (!islower(s[i]) && cur == next) flag = 1;
}
#ifdef DEBUG
cout << "flag: " << flag << endl;
#endif
cout << cnt + flag << endl;
return 0;
} | 15.434783 | 48 | 0.474648 | josedelinux |
6ef7a80f4b765a75be37b615c05d2b080fe32d77 | 7,821 | hh | C++ | include/stmicro/stm32l4x6/syscfg.hh | no111u3/lp_devices | 9fcd370a2b8a3f03a8a2181e403ffe562e48a611 | [
"Apache-2.0"
] | null | null | null | include/stmicro/stm32l4x6/syscfg.hh | no111u3/lp_devices | 9fcd370a2b8a3f03a8a2181e403ffe562e48a611 | [
"Apache-2.0"
] | null | null | null | include/stmicro/stm32l4x6/syscfg.hh | no111u3/lp_devices | 9fcd370a2b8a3f03a8a2181e403ffe562e48a611 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2018 Boris Vinogradov <no111u3@gmail.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.
*
* Hardware support for syscfg
* @file syscfg.hh
* @author Boris Vinogradov
*/
#include <associate_bit.hh>
#include <io_register.hh>
#include <types.hh>
#ifndef SYSCFG_HH
#define SYSCFG_HH
/* System configuration controller */
template <lp::addr_t base_address>
struct syscfg_t {
/* memory remap register */
using memrmp = lp::io_register<lp::u32_t, base_address + 0x0>;
/* Flash Bank mode selection */
using memrmp_fb_mode = lp::assoc_bit<memrmp, 8>;
/* QUADSPI memory mapping swap */
using memrmp_qfs = lp::assoc_bit<memrmp, 3>;
/* Memory mapping selection */
using memrmp_mem_mode = lp::assoc_bit<memrmp, 0, 3>;
/* configuration register 1 */
using cfgr1 = lp::io_register<lp::u32_t, base_address + 0x4>;
/* Floating Point Unit interrupts enable bits */
using cfgr1_fpu_ie = lp::assoc_bit<cfgr1, 26, 6>;
/* I2C3 Fast-mode Plus driving capability activation */
using cfgr1_i2c3_fmp = lp::assoc_bit<cfgr1, 22>;
/* I2C2 Fast-mode Plus driving capability activation */
using cfgr1_i2c2_fmp = lp::assoc_bit<cfgr1, 21>;
/* I2C1 Fast-mode Plus driving capability activation */
using cfgr1_i2c1_fmp = lp::assoc_bit<cfgr1, 20>;
/* Fast-mode Plus (Fm+) driving capability activation on PB9 */
using cfgr1_i2c_pb9_fmp = lp::assoc_bit<cfgr1, 19>;
/* Fast-mode Plus (Fm+) driving capability activation on PB8 */
using cfgr1_i2c_pb8_fmp = lp::assoc_bit<cfgr1, 18>;
/* Fast-mode Plus (Fm+) driving capability activation on PB7 */
using cfgr1_i2c_pb7_fmp = lp::assoc_bit<cfgr1, 17>;
/* Fast-mode Plus (Fm+) driving capability activation on PB6 */
using cfgr1_i2c_pb6_fmp = lp::assoc_bit<cfgr1, 16>;
/* I/O analog switch voltage booster enable */
using cfgr1_boosten = lp::assoc_bit<cfgr1, 8>;
/* Firewall disable */
using cfgr1_fwdis = lp::assoc_bit<cfgr1, 0>;
/* external interrupt configuration register 1 */
using exticr1 = lp::io_register<lp::u32_t, base_address + 0x8>;
/* EXTI 3 configuration bits */
using exticr1_exti3 = lp::assoc_bit<exticr1, 12, 3>;
/* EXTI 2 configuration bits */
using exticr1_exti2 = lp::assoc_bit<exticr1, 8, 3>;
/* EXTI 1 configuration bits */
using exticr1_exti1 = lp::assoc_bit<exticr1, 4, 3>;
/* EXTI 0 configuration bits */
using exticr1_exti0 = lp::assoc_bit<exticr1, 0, 3>;
/* external interrupt configuration register 2 */
using exticr2 = lp::io_register<lp::u32_t, base_address + 0xc>;
/* EXTI 7 configuration bits */
using exticr2_exti7 = lp::assoc_bit<exticr2, 12, 3>;
/* EXTI 6 configuration bits */
using exticr2_exti6 = lp::assoc_bit<exticr2, 8, 3>;
/* EXTI 5 configuration bits */
using exticr2_exti5 = lp::assoc_bit<exticr2, 4, 3>;
/* EXTI 4 configuration bits */
using exticr2_exti4 = lp::assoc_bit<exticr2, 0, 3>;
/* external interrupt configuration register 3 */
using exticr3 = lp::io_register<lp::u32_t, base_address + 0x10>;
/* EXTI 11 configuration bits */
using exticr3_exti11 = lp::assoc_bit<exticr3, 12, 3>;
/* EXTI 10 configuration bits */
using exticr3_exti10 = lp::assoc_bit<exticr3, 8, 3>;
/* EXTI 9 configuration bits */
using exticr3_exti9 = lp::assoc_bit<exticr3, 4, 3>;
/* EXTI 8 configuration bits */
using exticr3_exti8 = lp::assoc_bit<exticr3, 0, 3>;
/* external interrupt configuration register 4 */
using exticr4 = lp::io_register<lp::u32_t, base_address + 0x14>;
/* EXTI15 configuration bits */
using exticr4_exti15 = lp::assoc_bit<exticr4, 12, 3>;
/* EXTI14 configuration bits */
using exticr4_exti14 = lp::assoc_bit<exticr4, 8, 3>;
/* EXTI13 configuration bits */
using exticr4_exti13 = lp::assoc_bit<exticr4, 4, 3>;
/* EXTI12 configuration bits */
using exticr4_exti12 = lp::assoc_bit<exticr4, 0, 3>;
/* SCSR */
using scsr = lp::io_register<lp::u32_t, base_address + 0x18>;
/* SRAM2 busy by erase operation */
using scsr_sram2bsy = lp::assoc_bit<scsr, 1>;
/* SRAM2 Erase */
using scsr_sram2er = lp::assoc_bit<scsr, 0>;
/* CFGR2 */
using cfgr2 = lp::io_register<lp::u32_t, base_address + 0x1c>;
/* SRAM2 parity error flag */
using cfgr2_spf = lp::assoc_bit<cfgr2, 8>;
/* ECC Lock */
using cfgr2_eccl = lp::assoc_bit<cfgr2, 3>;
/* PVD lock enable bit */
using cfgr2_pvdl = lp::assoc_bit<cfgr2, 2>;
/* SRAM2 parity lock bit */
using cfgr2_spl = lp::assoc_bit<cfgr2, 1>;
/* Cortex-M4 LOCKUP (Hardfault) output enable bit */
using cfgr2_cll = lp::assoc_bit<cfgr2, 0>;
/* SWPR */
using swpr = lp::io_register<lp::u32_t, base_address + 0x20>;
/* SRAM2 page 31 write protection */
using swpr_p31wp = lp::assoc_bit<swpr, 31>;
/* P30WP */
using swpr_p30wp = lp::assoc_bit<swpr, 30>;
/* P29WP */
using swpr_p29wp = lp::assoc_bit<swpr, 29>;
/* P28WP */
using swpr_p28wp = lp::assoc_bit<swpr, 28>;
/* P27WP */
using swpr_p27wp = lp::assoc_bit<swpr, 27>;
/* P26WP */
using swpr_p26wp = lp::assoc_bit<swpr, 26>;
/* P25WP */
using swpr_p25wp = lp::assoc_bit<swpr, 25>;
/* P24WP */
using swpr_p24wp = lp::assoc_bit<swpr, 24>;
/* P23WP */
using swpr_p23wp = lp::assoc_bit<swpr, 23>;
/* P22WP */
using swpr_p22wp = lp::assoc_bit<swpr, 22>;
/* P21WP */
using swpr_p21wp = lp::assoc_bit<swpr, 21>;
/* P20WP */
using swpr_p20wp = lp::assoc_bit<swpr, 20>;
/* P19WP */
using swpr_p19wp = lp::assoc_bit<swpr, 19>;
/* P18WP */
using swpr_p18wp = lp::assoc_bit<swpr, 18>;
/* P17WP */
using swpr_p17wp = lp::assoc_bit<swpr, 17>;
/* P16WP */
using swpr_p16wp = lp::assoc_bit<swpr, 16>;
/* P15WP */
using swpr_p15wp = lp::assoc_bit<swpr, 15>;
/* P14WP */
using swpr_p14wp = lp::assoc_bit<swpr, 14>;
/* P13WP */
using swpr_p13wp = lp::assoc_bit<swpr, 13>;
/* P12WP */
using swpr_p12wp = lp::assoc_bit<swpr, 12>;
/* P11WP */
using swpr_p11wp = lp::assoc_bit<swpr, 11>;
/* P10WP */
using swpr_p10wp = lp::assoc_bit<swpr, 10>;
/* P9WP */
using swpr_p9wp = lp::assoc_bit<swpr, 9>;
/* P8WP */
using swpr_p8wp = lp::assoc_bit<swpr, 8>;
/* P7WP */
using swpr_p7wp = lp::assoc_bit<swpr, 7>;
/* P6WP */
using swpr_p6wp = lp::assoc_bit<swpr, 6>;
/* P5WP */
using swpr_p5wp = lp::assoc_bit<swpr, 5>;
/* P4WP */
using swpr_p4wp = lp::assoc_bit<swpr, 4>;
/* P3WP */
using swpr_p3wp = lp::assoc_bit<swpr, 3>;
/* P2WP */
using swpr_p2wp = lp::assoc_bit<swpr, 2>;
/* P1WP */
using swpr_p1wp = lp::assoc_bit<swpr, 1>;
/* P0WP */
using swpr_p0wp = lp::assoc_bit<swpr, 0>;
/* SKR */
using skr = lp::io_register<lp::u32_t, base_address + 0x24>;
/* SRAM2 write protection key for software erase */
using skr_key = lp::assoc_bit<skr, 0, 8>;
};
using syscfg = syscfg_t<0x40010000>;
#endif // SYSCFG_HH
| 36.71831 | 81 | 0.628692 | no111u3 |
6ef844ef4469ae396ff8ec3cd10309a9d373d31b | 428 | cpp | C++ | mainservo/servotestfunction.cpp | frank1789/hexpaodArduino | 9dfd5920eff38618a3439305b80fb7b37fb0b4a5 | [
"MIT"
] | null | null | null | mainservo/servotestfunction.cpp | frank1789/hexpaodArduino | 9dfd5920eff38618a3439305b80fb7b37fb0b4a5 | [
"MIT"
] | null | null | null | mainservo/servotestfunction.cpp | frank1789/hexpaodArduino | 9dfd5920eff38618a3439305b80fb7b37fb0b4a5 | [
"MIT"
] | null | null | null | #include "servotestfunction.h"
#include <Arduino.h>
void testservo(Leg& legs) {
for (int i = 0; i < 6; i++) {
legs["coxa"]->setServoAngle(75);
delay(500);
legs["coxa"]->setServoAngle(90);
delay(500);
legs["femur"]->setServoAngle(120);
delay(500);
legs["femur"]->setServoAngle(90);
delay(500);
legs["tibia"]->setServoAngle(120);
delay(500);
legs["tibia"]->setServoAngle(90);
}
}
| 21.4 | 38 | 0.595794 | frank1789 |
6efa0b7caa5c3485087e445ab01d9180aff7e1b5 | 21,293 | cc | C++ | src/video_encoder.cc | AugmentariumLab/foveated-360-video | bd5cb585712cc67b20da1264430c33c8bc68cf49 | [
"MIT"
] | 3 | 2021-03-30T15:46:36.000Z | 2021-11-26T03:20:15.000Z | src/video_encoder.cc | AugmentariumLab/foveated-360-video | bd5cb585712cc67b20da1264430c33c8bc68cf49 | [
"MIT"
] | null | null | null | src/video_encoder.cc | AugmentariumLab/foveated-360-video | bd5cb585712cc67b20da1264430c33c8bc68cf49 | [
"MIT"
] | 2 | 2021-03-30T15:46:40.000Z | 2021-12-19T09:53:38.000Z | #include "video_encoder.h"
VideoEncoder::VideoEncoder(AVCodecContext *s_video_codec_ctx) {
using namespace std;
int ret = 0;
std::array<char, 256> errstr;
hw_frame = av_frame_alloc();
hw_device_ctx = NULL;
out_format_ctx = NULL;
audio_codec = NULL;
audio_codec_ctx = NULL;
if ((ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_CUDA, NULL,
NULL, 0)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to create hw context" << endl;
av_make_error_string(errstr.data(), errstr.size(), ret);
cerr << "Ret: " << ret << "," << errstr.data() << endl;
return;
}
if (!(video_codec = avcodec_find_encoder_by_name("h264_nvenc"))) {
cerr << "[VideoEncoder::VideoEncoder] Failed to find h264_nvenc encoder"
<< endl;
return;
}
video_codec_ctx = avcodec_alloc_context3(video_codec);
video_codec_ctx->bit_rate = std::pow(10, 8);
// std::cerr << "Max bitrate " << video_codec_ctx->bit_rate << std::endl;
video_codec_ctx->width = s_video_codec_ctx->width;
video_codec_ctx->height = s_video_codec_ctx->height;
std::cerr << "Encoded resolution " << s_video_codec_ctx->width << ", "
<< s_video_codec_ctx->height << std::endl;
video_codec_ctx->codec_type = AVMEDIA_TYPE_VIDEO;
video_codec_ctx->time_base = s_video_codec_ctx->time_base;
input_timebase = s_video_codec_ctx->time_base;
video_codec_ctx->framerate = s_video_codec_ctx->framerate;
video_codec_ctx->pix_fmt = AV_PIX_FMT_CUDA;
video_codec_ctx->profile = FF_PROFILE_H264_MAIN;
video_codec_ctx->max_b_frames = 0;
video_codec_ctx->delay = 0;
ret = av_opt_set(video_codec_ctx->priv_data, "cq", "25", 0);
if (ret != 0) {
std::cerr << "Failed to set cq in priv data" << std::endl;
}
if ((ret = SetHWFrameCtx(video_codec_ctx, hw_device_ctx)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to set hwframe context."
<< endl;
return;
}
AVDictionary *opts = NULL;
av_dict_set(&opts, "preset", "fast", 0);
if (avcodec_open2(video_codec_ctx, video_codec, &opts) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to open H264 codec" << endl;
return;
}
if ((ret = av_hwframe_get_buffer(video_codec_ctx->hw_frames_ctx, hw_frame,
0)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Av_hwframe_get_buffer failed" << endl;
return;
}
NvencContext *nv = (NvencContext *)video_codec_ctx->priv_data;
// auto r = nv->output_surface_ready_queue;
// auto p = nv->output_surface_queue;
// std::cerr << "Ready "
// << (uint32_t)(r->wndx - r->rndx) / sizeof(NvencSurface *)
// << std::endl;
// std::cerr << "Pending "
// << (uint32_t)(p->wndx - p->rndx) / sizeof(NvencSurface *)
// << std::endl;
// std::cerr << "rc_lookahead " << nv->rc_lookahead << std::endl;
// std::cerr << "nb_surfaces " << nv->nb_surfaces << std::endl;
nv->async_depth = 1;
}
VideoEncoder::VideoEncoder(AVCodecContext *s_video_codec_ctx,
AVCodecContext *s_audio_codec_ctx,
std::string filename) {
using namespace std;
int ret = 0;
hw_frame = av_frame_alloc();
hw_device_ctx = NULL;
this->output_filename = filename;
if ((ret = avformat_alloc_output_context2(
&out_format_ctx, NULL, NULL, this->output_filename.c_str())) < 0) {
cerr << "[VideoEncoder::VideoEncoder] avformat_alloc_output_context2 failed"
<< endl;
return;
}
if ((ret = avio_open(&out_format_ctx->pb, this->output_filename.c_str(),
AVIO_FLAG_WRITE)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] AVIO Open failed" << endl;
return;
}
if ((ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_CUDA, NULL,
NULL, 0)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to create hw context" << endl;
return;
}
if (!(video_codec = avcodec_find_encoder_by_name("h264_nvenc"))) {
cerr << "[VideoEncoder::VideoEncoder] Failed to find h264_nvenc encoder"
<< endl;
return;
}
video_codec_ctx = avcodec_alloc_context3(video_codec);
video_codec_ctx->bit_rate = std::pow(10, 8);
video_codec_ctx->width = s_video_codec_ctx->width;
video_codec_ctx->height = s_video_codec_ctx->height;
// video_codec_ctx->codec_type = AVMEDIA_TYPE_VIDEO;
video_codec_ctx->time_base = s_video_codec_ctx->time_base;
input_timebase = s_video_codec_ctx->time_base;
video_codec_ctx->framerate = s_video_codec_ctx->framerate;
video_codec_ctx->pix_fmt = AV_PIX_FMT_CUDA;
video_codec_ctx->profile = FF_PROFILE_H264_MAIN;
video_codec_ctx->max_b_frames = 0;
video_codec_ctx->delay = 0;
ret = av_opt_set(video_codec_ctx->priv_data, "cq", "25", 0);
if ((ret = SetHWFrameCtx(video_codec_ctx, hw_device_ctx)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to set hwframe context."
<< endl;
return;
}
AVDictionary *opts = NULL;
av_dict_set(&opts, "preset", "fast", 0);
if (avcodec_open2(video_codec_ctx, video_codec, &opts) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to open H264 codec" << endl;
return;
}
if (!(out_video_stream = avformat_new_stream(out_format_ctx, video_codec))) {
cerr << "[VideoEncoder::VideoEncoder] Failed to allocate output stream"
<< endl;
}
out_video_stream->time_base = video_codec_ctx->time_base;
out_video_stream->r_frame_rate = video_codec_ctx->framerate;
if ((ret = avcodec_parameters_from_context(out_video_stream->codecpar,
video_codec_ctx)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to copy parameters to context"
<< endl;
return;
}
if (s_audio_codec_ctx) {
out_audio_stream = avformat_new_stream(out_format_ctx, NULL);
audio_codec = avcodec_find_encoder(s_audio_codec_ctx->codec_id);
if (!audio_codec) {
std::cerr << __func__ << " Audio encoder not found" << std::endl;
return;
}
audio_codec_ctx = avcodec_alloc_context3(audio_codec);
if (!audio_codec_ctx) {
std::cerr << __func__ << "Failed to allocate the encoder context\n"
<< std::endl;
return;
}
/* In this example, we transcode to same properties (picture size,
* sample rate etc.). These properties can be changed for output
* streams easily using filters */
audio_codec_ctx->sample_rate = s_audio_codec_ctx->sample_rate;
audio_codec_ctx->channel_layout = s_audio_codec_ctx->channel_layout;
audio_codec_ctx->channels =
av_get_channel_layout_nb_channels(s_audio_codec_ctx->channel_layout);
/* take first format from list of supported formats */
audio_codec_ctx->sample_fmt = audio_codec->sample_fmts[0];
audio_codec_ctx->time_base = {1, audio_codec_ctx->sample_rate};
if (out_format_ctx->oformat->flags & AVFMT_GLOBALHEADER)
audio_codec_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
/* Third parameter can be used to pass settings to encoder */
ret = avcodec_open2(audio_codec_ctx, audio_codec, NULL);
if (ret < 0) {
std::cerr << __func__ << "Cannot open video encoder for audio stream"
<< std::endl;
return;
}
ret = avcodec_parameters_from_context(out_audio_stream->codecpar,
audio_codec_ctx);
if (ret < 0) {
std::cerr << __func__
<< "Failed to copy encoder parameters to audio stream"
<< std::endl;
return;
}
out_audio_stream->time_base = audio_codec_ctx->time_base;
} else {
audio_codec_ctx = NULL;
out_audio_stream = NULL;
}
if ((ret = av_hwframe_get_buffer(video_codec_ctx->hw_frames_ctx, hw_frame,
0)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Av_hwframe_get_buffer failed" << endl;
return;
}
if ((ret = avformat_write_header(out_format_ctx, NULL)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to copy parameters to context"
<< endl;
return;
}
}
VideoEncoder::VideoEncoder(AVCodecContext *s_video_codec_ctx,
AVCodecContext *s_audio_codec_ctx,
std::string filename, int bitrate) {
using namespace std;
int ret = 0;
hw_frame = av_frame_alloc();
hw_device_ctx = NULL;
this->output_filename = filename;
if ((ret = avformat_alloc_output_context2(
&out_format_ctx, NULL, NULL, this->output_filename.c_str())) < 0) {
cerr << "[VideoEncoder::VideoEncoder] avformat_alloc_output_context2 failed"
<< endl;
return;
}
if ((ret = avio_open(&out_format_ctx->pb, this->output_filename.c_str(),
AVIO_FLAG_WRITE)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] AVIO Open failed" << endl;
return;
}
if ((ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_CUDA, NULL,
NULL, 0)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to create hw context" << endl;
return;
}
if (!(video_codec = avcodec_find_encoder_by_name("h264_nvenc"))) {
cerr << "[VideoEncoder::VideoEncoder] Failed to find h264_nvenc encoder"
<< endl;
return;
}
video_codec_ctx = avcodec_alloc_context3(video_codec);
video_codec_ctx->width = s_video_codec_ctx->width;
video_codec_ctx->height = s_video_codec_ctx->height;
// video_codec_ctx->codec_type = AVMEDIA_TYPE_VIDEO;
video_codec_ctx->time_base = s_video_codec_ctx->time_base;
input_timebase = s_video_codec_ctx->time_base;
video_codec_ctx->framerate = s_video_codec_ctx->framerate;
video_codec_ctx->pix_fmt = AV_PIX_FMT_CUDA;
video_codec_ctx->profile = FF_PROFILE_H264_MAIN;
video_codec_ctx->max_b_frames = 0;
video_codec_ctx->delay = 0;
if (bitrate > 0) {
video_codec_ctx->bit_rate = bitrate;
} else {
video_codec_ctx->bit_rate = std::pow(10, 8);
ret = av_opt_set(video_codec_ctx->priv_data, "cq", "25", 0);
}
if ((ret = SetHWFrameCtx(video_codec_ctx, hw_device_ctx)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to set hwframe context."
<< endl;
return;
}
AVDictionary *opts = NULL;
av_dict_set(&opts, "preset", "fast", 0);
if (avcodec_open2(video_codec_ctx, video_codec, &opts) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to open H264 codec" << endl;
return;
}
if (!(out_video_stream = avformat_new_stream(out_format_ctx, video_codec))) {
cerr << "[VideoEncoder::VideoEncoder] Failed to allocate output stream"
<< endl;
}
out_video_stream->time_base = video_codec_ctx->time_base;
out_video_stream->r_frame_rate = video_codec_ctx->framerate;
if ((ret = avcodec_parameters_from_context(out_video_stream->codecpar,
video_codec_ctx)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to copy parameters to context"
<< endl;
return;
}
if (s_audio_codec_ctx) {
out_audio_stream = avformat_new_stream(out_format_ctx, NULL);
audio_codec = avcodec_find_encoder(s_audio_codec_ctx->codec_id);
if (!audio_codec) {
std::cerr << __func__ << " Audio encoder not found" << std::endl;
return;
}
audio_codec_ctx = avcodec_alloc_context3(audio_codec);
if (!audio_codec_ctx) {
std::cerr << __func__ << "Failed to allocate the encoder context\n"
<< std::endl;
return;
}
/* In this example, we transcode to same properties (picture size,
* sample rate etc.). These properties can be changed for output
* streams easily using filters */
audio_codec_ctx->sample_rate = s_audio_codec_ctx->sample_rate;
audio_codec_ctx->channel_layout = s_audio_codec_ctx->channel_layout;
audio_codec_ctx->channels =
av_get_channel_layout_nb_channels(s_audio_codec_ctx->channel_layout);
/* take first format from list of supported formats */
audio_codec_ctx->sample_fmt = audio_codec->sample_fmts[0];
audio_codec_ctx->time_base = {1, audio_codec_ctx->sample_rate};
if (out_format_ctx->oformat->flags & AVFMT_GLOBALHEADER)
audio_codec_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
/* Third parameter can be used to pass settings to encoder */
ret = avcodec_open2(audio_codec_ctx, audio_codec, NULL);
if (ret < 0) {
std::cerr << __func__ << "Cannot open video encoder for audio stream"
<< std::endl;
return;
}
ret = avcodec_parameters_from_context(out_audio_stream->codecpar,
audio_codec_ctx);
if (ret < 0) {
std::cerr << __func__
<< "Failed to copy encoder parameters to audio stream"
<< std::endl;
return;
}
out_audio_stream->time_base = audio_codec_ctx->time_base;
} else {
audio_codec_ctx = NULL;
out_audio_stream = NULL;
}
if ((ret = av_hwframe_get_buffer(video_codec_ctx->hw_frames_ctx, hw_frame,
0)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Av_hwframe_get_buffer failed" << endl;
return;
}
if ((ret = avformat_write_header(out_format_ctx, NULL)) < 0) {
cerr << "[VideoEncoder::VideoEncoder] Failed to copy parameters to context"
<< endl;
return;
}
}
VideoEncoder::~VideoEncoder() {
if (hw_frame != NULL) {
av_frame_free(&hw_frame);
}
if (video_codec_ctx != NULL) {
avcodec_close(video_codec_ctx);
avcodec_free_context(&video_codec_ctx);
}
av_buffer_unref(&hw_device_ctx);
if (out_format_ctx != NULL) {
WriteTrailerAndCloseFile();
}
}
int VideoEncoder::EncodeFrame(AVPacket *out_packet, AVFrame *source_frame) {
int ret = 0;
std::array<char, 256> err_buf;
if (source_frame == NULL) {
// std::cerr << __func__ << " Source frame is null" << std::endl;
avcodec_send_frame(video_codec_ctx, NULL);
ret = avcodec_receive_packet(video_codec_ctx, out_packet);
if (ret == 0 && !pts_queue.empty()) {
PtsDts pts = pts_queue.front();
pts_queue.pop();
out_packet->pts = pts.pts;
out_packet->dts = pts.dts;
}
return ret;
}
AVFrame *yuv_frame = source_frame;
if (!hw_frame->hw_frames_ctx) {
std::cerr << "[VideoEncoder::EncodeFrame] Error no memory" << std::endl;
goto Error;
}
if (yuv_frame->format != AV_PIX_FMT_YUV420P) {
yuv_frame = av_frame_alloc();
yuv_frame->width = source_frame->width;
yuv_frame->height = source_frame->height;
yuv_frame->format = AV_PIX_FMT_YUV420P;
yuv_frame->pts = source_frame->pts;
yuv_frame->pkt_dts = source_frame->pkt_dts;
av_frame_get_buffer(yuv_frame, 0);
SwsContext *to_yuv =
sws_getContext(source_frame->width, source_frame->height,
(AVPixelFormat)source_frame->format, source_frame->width,
source_frame->height, AV_PIX_FMT_YUV420P, SWS_BILINEAR,
NULL, NULL, NULL);
sws_scale(to_yuv, source_frame->data, source_frame->linesize, 0,
source_frame->height, yuv_frame->data, yuv_frame->linesize);
sws_freeContext(to_yuv);
}
if ((ret = av_hwframe_transfer_data(hw_frame, yuv_frame, 0)) < 0) {
av_make_error_string(err_buf.data(), 256, ret);
std::cerr
<< "[VideoEncoder::EncodeFrame] Error transfering frame from software "
"to hardware; "
<< ret << "; " << err_buf.data() << std::endl;
if (source_frame != NULL) {
AVPixelFormat *format;
const char *pix_fmt_name =
av_get_pix_fmt_name((AVPixelFormat)source_frame->format);
std::cout << "[VideoEncoder::EncodeFrame] Received format "
<< pix_fmt_name << ", " << source_frame->format << std::endl;
} else {
std::cerr << "[VideoEncoder::EncodeFrame] Source frame was null"
<< std::endl;
}
goto Error;
}
av_init_packet(out_packet);
out_packet->data = NULL;
out_packet->size = 0;
pts_queue.emplace(yuv_frame->pts, yuv_frame->pkt_dts);
if ((ret = avcodec_send_frame(video_codec_ctx, hw_frame)) < 0) {
std::cerr << "[VideoEncoder::EncodeFrame] Error in send frame" << std::endl;
goto Error;
}
if (yuv_frame != source_frame) {
av_frame_free(&yuv_frame);
}
ret = avcodec_receive_packet(video_codec_ctx, out_packet);
if (ret == 0 && !pts_queue.empty()) {
PtsDts pts = pts_queue.front();
pts_queue.pop();
out_packet->pts = pts.pts;
out_packet->dts = pts.dts;
}
return ret;
Error:
return -1;
}
int VideoEncoder::EncodeFrameToFile(AVFrame *source_frame) {
using namespace std;
if (out_format_ctx == NULL) {
cerr << "[VideoEncoder::EncodeFrameToFile] No file opened" << endl;
return -1;
}
int ret = 0;
char err_buf[256];
AVPacket packet;
av_init_packet(&packet);
packet.data = NULL;
packet.size = 0;
ret = EncodeFrame(&packet, source_frame);
if (source_frame == NULL) {
while (ret == 0) {
packet.stream_index = 0;
av_packet_rescale_ts(&packet, input_timebase,
out_video_stream->time_base);
ret = av_interleaved_write_frame(out_format_ctx, &packet);
if (ret < 0) {
cerr
<< "[VideoEncoder::EncodeFrameToFile] Error writing to output file."
<< endl;
return -1;
}
av_packet_unref(&packet);
ret = GetPacket(&packet);
}
return 0;
}
if (ret == 0) {
packet.stream_index = 0;
av_packet_rescale_ts(&packet, input_timebase, out_video_stream->time_base);
ret = av_interleaved_write_frame(out_format_ctx, &packet);
if (ret < 0) {
cerr << "[VideoEncoder::EncodeFrameToFile] Error writing to output file."
<< endl;
return -1;
}
}
return 0;
}
int VideoEncoder::EncodeFrameToFile(AVFrame *source_frame,
AVPacketSideData side_data) {
using namespace std;
if (out_format_ctx == NULL) {
cerr << "[VideoEncoder::EncodeFrameToFile] No file opened" << endl;
return -1;
}
int ret = 0;
char err_buf[256];
AVPacket packet;
av_init_packet(&packet);
packet.data = NULL;
packet.size = 0;
ret = EncodeFrame(&packet, source_frame);
if (ret == 0) {
packet.stream_index = 0;
av_packet_rescale_ts(&packet, input_timebase, out_video_stream->time_base);
cout << "Adding side data to packet: " << side_data.size << endl;
ret = av_packet_add_side_data(&packet, side_data.type, side_data.data,
side_data.size);
if (ret != 0) {
av_make_error_string(err_buf, 256, ret);
cout << "Add side data error " << err_buf << endl;
}
cout << "Side_data_size: " << packet.side_data->size << endl;
ret = av_interleaved_write_frame(out_format_ctx, &packet);
if (ret < 0) {
cerr << "[VideoEncoder::EncodeFrameToFile] Error writing to output file."
<< endl;
return -1;
}
}
return 0;
}
int VideoEncoder::GetPacket(AVPacket *out_packet) {
using namespace std;
int ret = -1;
av_init_packet(out_packet);
out_packet->data = NULL;
out_packet->size = 0;
ret = avcodec_receive_packet(video_codec_ctx, out_packet);
// ret = video_codec_ctx->codec->receive_packet(video_codec_ctx, out_packet);
if (ret == 0 && !pts_queue.empty()) {
PtsDts pts = pts_queue.front();
pts_queue.pop();
out_packet->pts = pts.pts;
out_packet->dts = pts.dts;
}
return ret;
}
int VideoEncoder::SetHWFrameCtx(AVCodecContext *ctx,
AVBufferRef *hw_device_ctx) {
using namespace std;
AVBufferRef *hw_frames_ref;
AVHWFramesContext *frames_ctx = NULL;
int err = 0;
if (!(hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx))) {
fprintf(stderr,
"[VideoEncoder::SetHWFrameCtx] Failed to create hw "
"frame context.\n");
return -1;
}
frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
frames_ctx->format = AV_PIX_FMT_CUDA;
frames_ctx->sw_format = AV_PIX_FMT_YUV420P;
frames_ctx->width = ctx->width;
frames_ctx->height = ctx->height;
frames_ctx->initial_pool_size = 20;
if ((err = av_hwframe_ctx_init(hw_frames_ref)) < 0) {
cerr << "[VideoEncoder::SetHWFrameCtx] Failed to initialize hw frame "
"context."
<< endl;
av_buffer_unref(&hw_frames_ref);
return err;
}
ctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
if (!ctx->hw_frames_ctx) err = AVERROR(ENOMEM);
// av_buffer_unref(&hw_frames_ref);
return err;
}
void VideoEncoder::WriteTrailerAndCloseFile() {
using namespace std;
if (out_format_ctx == NULL) {
cerr << "[VideoEncoder::EncodeFrameToFile] No file opened" << endl;
}
av_write_trailer(out_format_ctx);
avformat_close_input(&out_format_ctx);
}
void VideoEncoder::PrintSupportedPixelFormats() {
using namespace std;
AVPixelFormat *formats;
cout << "Supported Formats: ";
av_hwframe_transfer_get_formats(
hw_frame->hw_frames_ctx, AV_HWFRAME_TRANSFER_DIRECTION_TO, &formats, 0);
for (int i = 0; i < 99 && formats[i] != AV_PIX_FMT_NONE; i++) {
const char *pix_fmt_name = av_get_pix_fmt_name(formats[i]);
cout << pix_fmt_name;
if (formats[i + 1] != AV_PIX_FMT_NONE) {
cout << ", ";
}
}
cout << endl;
free(formats);
}
| 35.967905 | 80 | 0.651388 | AugmentariumLab |
6efe0572727c8fb4559384c095099fe3b89acddd | 3,129 | cpp | C++ | ros/src/meta_planner/src/environment.cpp | ICRA-2018/meta_fastrack | 19c62cf5cd6684315a462eadc4c053ca22cb0cc8 | [
"BSD-3-Clause"
] | 16 | 2018-07-01T02:09:26.000Z | 2022-03-21T04:46:53.000Z | ros/src/meta_planner/src/environment.cpp | ICRA-2018/meta_fastrack | 19c62cf5cd6684315a462eadc4c053ca22cb0cc8 | [
"BSD-3-Clause"
] | 1 | 2019-10-10T08:45:38.000Z | 2021-05-07T15:44:46.000Z | ros/src/meta_planner/src/environment.cpp | ICRA-2018/meta_fastrack | 19c62cf5cd6684315a462eadc4c053ca22cb0cc8 | [
"BSD-3-Clause"
] | 9 | 2018-06-11T21:08:46.000Z | 2021-09-11T07:47:24.000Z | /*
* Copyright (c) 2017, The Regents of the University of California (Regents).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Please contact the author(s) of this library if you have any questions.
* Authors: David Fridovich-Keil ( dfk@eecs.berkeley.edu )
*/
///////////////////////////////////////////////////////////////////////////////
//
// Defines the Environment abstract class interface.
//
///////////////////////////////////////////////////////////////////////////////
#include <meta_planner/environment.h>
namespace meta {
// Initialize this class from a ROS node.
bool Environment::Initialize(const ros::NodeHandle& n) {
name_ = ros::names::append(n.getNamespace(), "environment");
if (!LoadParameters(n)) {
ROS_ERROR("%s: Failed to load parameters.", name_.c_str());
return false;
}
if (!RegisterCallbacks(n)) {
ROS_ERROR("%s: Failed to register callbacks.", name_.c_str());
return false;
}
initialized_ = true;
return true;
}
// Load all parameters.
bool Environment::LoadParameters(const ros::NodeHandle& n) {
ros::NodeHandle nl(n);
// Switching bound.
if (!nl.getParam("srv/switching_bound", switching_bound_name_)) return false;
return true;
}
// Register all callbacks and publishers.
bool Environment::RegisterCallbacks(const ros::NodeHandle& n) {
ros::NodeHandle nl(n);
// Server.
ros::service::waitForService(switching_bound_name_.c_str());
switching_bound_srv_ = nl.serviceClient<value_function_srvs::SwitchingTrackingBoundBox>(
switching_bound_name_.c_str(), true);
return true;
}
} //\namespace meta
| 35.556818 | 90 | 0.695749 | ICRA-2018 |
3e01e78f73b43fad156ad659d8806a25f17646b6 | 7,208 | hpp | C++ | client/ui/UIBase.hpp | LoneDev6/MikuMikuOnline_wss-mod | de05011d5b7f0d5492640743c79ae005a832109a | [
"BSD-3-Clause"
] | 6 | 2015-01-03T08:18:16.000Z | 2022-01-22T00:01:23.000Z | client/ui/UIBase.hpp | LoneDev6/MikuMikuOnline_wss-mod | de05011d5b7f0d5492640743c79ae005a832109a | [
"BSD-3-Clause"
] | 1 | 2021-10-03T19:07:56.000Z | 2021-10-03T19:07:56.000Z | client/ui/UIBase.hpp | LoneDev6/MikuMikuOnline_wss-mod | de05011d5b7f0d5492640743c79ae005a832109a | [
"BSD-3-Clause"
] | 1 | 2021-10-03T19:29:40.000Z | 2021-10-03T19:29:40.000Z | //
// UIBase.hpp
//
#pragma once
#include "UISuper.hpp"
#include <v8.h>
#include "../InputManager.hpp"
#include <functional>
using namespace v8;
class ScriptEnvironment;
typedef std::weak_ptr<ScriptEnvironment> ScriptEnvironmentWeakPtr;
class UIBase;
class Input;
typedef std::shared_ptr<UIBase> UIBasePtr;
typedef std::weak_ptr<UIBase> UIBaseWeakPtr;
typedef std::function<void(UIBase*)> CallbackFuncWithThisPointer;
class UIBase : public UISuper {
public:
UIBase();
virtual ~UIBase();
virtual void ProcessInput(InputManager* input);
virtual void Update();
virtual void Draw();
virtual void AsyncUpdate(); // 毎ループ実行する必要のない処理
/* function */
static Handle<Value> Function_addChild(const Arguments& args);
static Handle<Value> Function_removeChild(const Arguments& args);
static Handle<Value> Function_parent(const Arguments& args);
/* property */
static Handle<Value> Property_visible(Local<String> property, const AccessorInfo &info);
static void Property_set_visible(Local<String> property, Local<Value> value, const AccessorInfo& info);
static Handle<Value> Property_width(Local<String> property, const AccessorInfo &info);
static void Property_set_width(Local<String> property, Local<Value> value, const AccessorInfo& info);
static Handle<Value> Property_height(Local<String> property, const AccessorInfo &info);
static void Property_set_height(Local<String> property, Local<Value> value, const AccessorInfo& info);
static Handle<Value> Property_top(Local<String> property, const AccessorInfo &info);
static void Property_set_top(Local<String> property, Local<Value> value, const AccessorInfo& info);
static Handle<Value> Property_left(Local<String> property, const AccessorInfo &info);
static void Property_set_left(Local<String> property, Local<Value> value, const AccessorInfo& info);
static Handle<Value> Property_right(Local<String> property, const AccessorInfo &info);
static void Property_set_right(Local<String> property, Local<Value> value, const AccessorInfo& info);
static Handle<Value> Property_bottom(Local<String> property, const AccessorInfo &info);
static void Property_set_bottom(Local<String> property, Local<Value> value, const AccessorInfo& info);
static Handle<Value> Property_docking(Local<String> property, const AccessorInfo &info);
static void Property_set_docking(Local<String> property, Local<Value> value, const AccessorInfo& info);
/* event */
static Handle<Value> Property_on_click(Local<String> property, const AccessorInfo &info);
static void Property_set_on_click(Local<String> property, Local<Value> value, const AccessorInfo& info);
Handle<Object> parent() const;
void set_parent(const Handle<Object>& parent);
UIBasePtr parent_c() const;
void set_parent_c(const UIBasePtr &parent_c);
Input* input_adpator() const;
void set_input_adaptor(Input * adaptor);
size_t children_size() const;
template<class T>
static void SetObjectTemplate(const std::string& classname,
Handle<ObjectTemplate>* object);
template<class F>
static void SetFunction(Handle<ObjectTemplate>* object, const std::string& name, F func);
template<class G, class S>
static void SetProperty(Handle<ObjectTemplate>* object, const std::string& name, G getter, S setter);
template<class T>
static void SetConstant(Handle<ObjectTemplate>* object, const std::string& name, T value);
public:
static void DefineInstanceTemplate(Handle<ObjectTemplate>* object);
protected:
virtual void UpdatePosition();
void ProcessInputChildren(InputManager* input);
void UpdateChildren();
void DrawChildren();
void AsyncUpdateChildren();
virtual void UpdateBaseImage();
void GetParam(const Handle<Object>& object, const std::string& name, int* value);
void GetParam(const Handle<Object>& object, const std::string& name, bool* value);
void GetParam(const Handle<Object>& object, const std::string& name, std::string* value);
void Focus();
public:
/* Property */
template<class F>
void set_on_click_function_(F function);
template<class F>
void set_on_hover_function_(F function);
template<class F>
void set_on_out_function_(F function);
protected:
Persistent<Object> parent_;
std::vector<Persistent<Object>> children_;
Persistent<Function> on_click_;
CallbackFuncWithThisPointer on_click_function_;
CallbackFuncWithThisPointer on_hover_function_;
CallbackFuncWithThisPointer on_out_function_;
bool hover_flag_;
/*C++からクラスを伝達するためのメンバ*/
UIBasePtr parent_c_;
Input* input_adaptor_;
};
//inline void Destruct(Persistent<Value> handle, void* parameter) {
inline void Destruct(Isolate* isolate,Persistent<Value> handle, void* parameter) {
auto instance = static_cast<UIBasePtr*>(parameter);
delete instance;
handle.Dispose();
}
template<class T>
Handle<Value> Construct(const Arguments& args) {
UIBasePtr* instance = new UIBasePtr(new T());
Local<v8::Object> thisObject = args.This();
assert(thisObject->InternalFieldCount() > 0);
thisObject->SetInternalField(0, External::New(instance));
Persistent<v8::Object> holder = Persistent<v8::Object>::New(thisObject);
// holder.MakeWeak(instance, Destruct);
holder.MakeWeak(Isolate::GetCurrent(),instance, Destruct); // ※ V8のバージョンを上げるために変更
return thisObject;
}
template<class T>
void UIBase::SetObjectTemplate(const std::string& classname,
Handle<ObjectTemplate>* object)
{
auto func = FunctionTemplate::New(Construct<T>);
func->SetClassName(String::New(classname.c_str()));
auto instance_template = func->InstanceTemplate();
instance_template->SetInternalFieldCount(1);
T::DefineInstanceTemplate(&instance_template);
(*object)->Set(String::New(("_" + classname).c_str()), func,
PropertyAttribute(ReadOnly));
}
template<class F>
void UIBase::SetFunction(Handle<ObjectTemplate>* object, const std::string& name, F func)
{
Handle<ObjectTemplate>& instance_template = *object;
instance_template->Set(String::New(name.c_str()), FunctionTemplate::New(func));
}
template<class G, class S>
void UIBase::SetProperty(Handle<ObjectTemplate>* object, const std::string& name, G getter, S setter)
{
Handle<ObjectTemplate>& instance_template = *object;
instance_template->SetAccessor(String::New(name.c_str()), getter, setter);
}
template<class T>
void UIBase::SetConstant(Handle<ObjectTemplate>* object, const std::string& name, T value)
{
Handle<ObjectTemplate>& instance_template = *object;
instance_template->Set(String::New(name.c_str()), value);
}
template<class F>
void UIBase::set_on_click_function_(F function)
{
on_click_function_ = function;
}
template<class F>
void UIBase::set_on_hover_function_(F function)
{
on_hover_function_ = function;
}
template<class F>
void UIBase::set_on_out_function_(F function)
{
on_out_function_ = function;
} | 35.683168 | 112 | 0.720172 | LoneDev6 |
3e02918fea0f5319730bcb9858404f2221358db1 | 2,959 | cpp | C++ | tests/unit/watchtower/error_cache_test.cpp | EnrikoChavez/opencbdc-tx | 3f4ebe9fa8296542158ff505b47fd8f277e313dd | [
"MIT"
] | 652 | 2022-02-03T19:31:04.000Z | 2022-03-31T17:45:29.000Z | tests/unit/watchtower/error_cache_test.cpp | EnrikoChavez/opencbdc-tx | 3f4ebe9fa8296542158ff505b47fd8f277e313dd | [
"MIT"
] | 50 | 2022-02-03T23:16:36.000Z | 2022-03-31T19:50:19.000Z | tests/unit/watchtower/error_cache_test.cpp | EnrikoChavez/opencbdc-tx | 3f4ebe9fa8296542158ff505b47fd8f277e313dd | [
"MIT"
] | 116 | 2022-02-03T19:57:26.000Z | 2022-03-20T17:23:47.000Z | // Copyright (c) 2021 MIT Digital Currency Initiative,
// Federal Reserve Bank of Boston
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "uhs/atomizer/watchtower/error_cache.hpp"
#include "uhs/atomizer/watchtower/tx_error_messages.hpp"
#include <gtest/gtest.h>
class error_cache_test : public ::testing::Test {
protected:
void SetUp() override {
std::vector<cbdc::watchtower::tx_error> errs{
{cbdc::watchtower::tx_error{
{'t', 'x', 'a'},
cbdc::watchtower::tx_error_inputs_dne{
{{'u', 'h', 's', 'a'}, {'u', 'h', 's', 'b'}}}},
cbdc::watchtower::tx_error{
{'t', 'x', 'b'},
cbdc::watchtower::tx_error_stxo_range{}},
cbdc::watchtower::tx_error{{'t', 'x', 'c'},
cbdc::watchtower::tx_error_sync{}},
cbdc::watchtower::tx_error{
{'t', 'x', 'd'},
cbdc::watchtower::tx_error_inputs_spent{
{{'u', 'h', 's', 'c'}, {'u', 'h', 's', 'd'}}}}}};
m_ec.push_errors(std::move(errs));
}
cbdc::watchtower::error_cache m_ec{4};
};
TEST_F(error_cache_test, no_errors) {
ASSERT_FALSE(m_ec.check_tx_id({'Z'}).has_value());
ASSERT_FALSE(m_ec.check_uhs_id({'Z'}).has_value());
}
TEST_F(error_cache_test, add_k_plus_1) {
ASSERT_TRUE(m_ec.check_tx_id({'t', 'x', 'a'}).has_value());
ASSERT_TRUE(m_ec.check_uhs_id({'u', 'h', 's', 'a'}).has_value());
ASSERT_TRUE(m_ec.check_uhs_id({'u', 'h', 's', 'b'}).has_value());
ASSERT_TRUE(m_ec.check_tx_id({'t', 'x', 'b'}).has_value());
ASSERT_TRUE(m_ec.check_tx_id({'t', 'x', 'c'}).has_value());
ASSERT_TRUE(m_ec.check_tx_id({'t', 'x', 'd'}).has_value());
ASSERT_TRUE(m_ec.check_uhs_id({'u', 'h', 's', 'c'}).has_value());
ASSERT_TRUE(m_ec.check_uhs_id({'u', 'h', 's', 'd'}).has_value());
m_ec.push_errors({cbdc::watchtower::tx_error{
{'t', 'x', 'e'},
cbdc::watchtower::tx_error_inputs_spent{
{{'u', 'h', 's', 'e'}, {'u', 'h', 's', 'f'}}}}});
ASSERT_TRUE(m_ec.check_tx_id({'t', 'x', 'e'}).has_value());
ASSERT_TRUE(m_ec.check_uhs_id({'u', 'h', 's', 'e'}).has_value());
ASSERT_TRUE(m_ec.check_uhs_id({'u', 'h', 's', 'f'}).has_value());
ASSERT_TRUE(m_ec.check_tx_id({'t', 'x', 'b'}).has_value());
ASSERT_TRUE(m_ec.check_tx_id({'t', 'x', 'c'}).has_value());
ASSERT_TRUE(m_ec.check_tx_id({'t', 'x', 'd'}).has_value());
ASSERT_TRUE(m_ec.check_uhs_id({'u', 'h', 's', 'c'}).has_value());
ASSERT_TRUE(m_ec.check_uhs_id({'u', 'h', 's', 'd'}).has_value());
ASSERT_FALSE(m_ec.check_tx_id({'t', 'x', 'a'}).has_value());
ASSERT_FALSE(m_ec.check_uhs_id({'u', 'h', 's', 'a'}).has_value());
ASSERT_FALSE(m_ec.check_uhs_id({'u', 'h', 's', 'b'}).has_value());
}
| 44.164179 | 75 | 0.558297 | EnrikoChavez |
3e068924620de9486e0a8e14f90b29bf809b5b26 | 1,428 | hpp | C++ | Utility/VLTree/HydraGame/a_Body.hpp | p-adic/cpp | 9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c | [
"MIT"
] | 2 | 2020-09-13T07:31:22.000Z | 2022-03-26T08:37:32.000Z | Utility/VLTree/HydraGame/a_Body.hpp | p-adic/cpp | 9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c | [
"MIT"
] | null | null | null | Utility/VLTree/HydraGame/a_Body.hpp | p-adic/cpp | 9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c | [
"MIT"
] | null | null | null | // c:/Users/user/Documents/Programming/Utility/VLTree/HydraGame/a_Body.hpp
#pragma once
#include "../a_Body.hpp"
template <typename T>
void CutHydra( VLSubTree<T>& t , const uint& n )
{
if( t.IsLeaf() ){
ERR_CALL;
}
VLSubTree<T> t0 = t.RightMostSubTree();
if( t0.IsLeaf() ){
t.pop_back();
} else {
VLSubTree<T> t1 = t0.RightMostSubTree();
if( t1.IsLeaf() ){
t0.pop_back();
for( uint i = 0 ; i < n ; i++ ){
t.push_back( t0 );
}
} else {
CutHydra( t0 , n );
}
}
return;
}
template <typename T>
uint KillHydra( VLTree<T>& t , uint& n , const uint& incr )
{
string s = to_string( t );
s += "[n]";
cout << s << endl;
while( KillHydra_Body( t , n ) ){
cout << "[" << n << "]" << endl;
n += incr;
}
return n;
}
template <typename T>
void KillHydra( VLTree<T>& t )
{
string s = to_string( t );
s += "[n]";
cout << s << endl;
uint n = 0;
cout << "n = ";
cin >> n;
while( KillHydra_Body( t , n ) && n != 691){
cout << "[" << n << "][n]" << endl;
cout << "n = ";
cin >> n;
}
return;
}
template <typename T>
bool KillHydra_Body( VLTree<T>& t , const uint& n )
{
if( t.IsLeaf() ){
return false;
}
CutHydra( t , n );
cout << to_string( t );
return true;
}
| 12.981818 | 75 | 0.465686 | p-adic |
3e0a827c83017a380a5b79e4a44f54b9318fe5c0 | 2,258 | cpp | C++ | code/sudoku-solver/sudoku_solver.cpp | shenhuaze/leetcode-cpp | 2a70f33697fbc562207e1ed3bbe8d038512628be | [
"MIT"
] | 1 | 2019-06-17T04:37:39.000Z | 2019-06-17T04:37:39.000Z | code/sudoku-solver/sudoku_solver.cpp | shenhuaze/leetcode-cpp | 2a70f33697fbc562207e1ed3bbe8d038512628be | [
"MIT"
] | null | null | null | code/sudoku-solver/sudoku_solver.cpp | shenhuaze/leetcode-cpp | 2a70f33697fbc562207e1ed3bbe8d038512628be | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
/**
* @author Huaze Shen
* @date 2019-07-17
*/
bool IsValid(vector<vector<char>>& board, int i, int j) {
for (int col = 0; col < 9; col++) {
if (col != j && board[i][col] == board[i][j]) {
return false;
}
}
for (int row = 0; row < 9; row++) {
if (row != i && board[row][j] == board[i][j]) {
return false;
}
}
for (int row = i / 3 * 3; row < i / 3 * 3 + 3; row++) {
for (int col = j / 3 * 3; col < j / 3 * 3 + 3; col++) {
if (row != i && col != j && board[row][col] == board[i][j]) {
return false;
}
}
}
return true;
}
bool SolveSudokuDFS(vector<vector<char>>& board, int i, int j) {
if (i == 9) {
return true;
}
if (j >= 9) {
return SolveSudokuDFS(board, i + 1, 0);
}
if (board[i][j] == '.') {
for (int k = 1; k <= 9; k++) {
board[i][j] = (char)(k + '0');
if (IsValid(board, i, j)) {
if (SolveSudokuDFS(board, i, j + 1)) {
return true;
}
}
board[i][j] = '.';
}
} else {
return SolveSudokuDFS(board, i, j + 1);
}
return false;
}
void SolveSudoku(vector<vector<char>>& board) {
if (board.empty() || board.size() != 9 || board[0].size() != 9) {
return;
}
SolveSudokuDFS(board, 0, 0);
}
int main() {
vector<vector<char>> board = {
{'5', '3', '.', '.', '7', '.', '.', '.', '.'},
{'6', '.', '.', '1', '9', '5', '.', '.', '.'},
{'.', '9', '8', '.', '.', '.', '.', '6', '.'},
{'8', '.', '.', '.', '6', '.', '.', '.', '3'},
{'4', '.', '.', '8', '.', '3', '.', '.', '1'},
{'7', '.', '.', '.', '2', '.', '.', '.', '6'},
{'.', '6', '.', '.', '.', '.', '2', '8', '.'},
{'.', '.', '.', '4', '1', '9', '.', '.', '5'},
{'.', '.', '.', '.', '8', '.', '.', '7', '9'}
};
SolveSudoku(board);
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
cout << board[i][j] << " ";
}
cout << "\n";
}
return 0;
} | 27.204819 | 73 | 0.330381 | shenhuaze |
3e0b343eaf91117d585500c802c60951fbb7bb20 | 1,203 | hpp | C++ | include/Object.hpp | fu7mu4/entonetics | d0b2643f039a890b25d5036cc94bfe3b4d840480 | [
"MIT"
] | null | null | null | include/Object.hpp | fu7mu4/entonetics | d0b2643f039a890b25d5036cc94bfe3b4d840480 | [
"MIT"
] | null | null | null | include/Object.hpp | fu7mu4/entonetics | d0b2643f039a890b25d5036cc94bfe3b4d840480 | [
"MIT"
] | null | null | null | #ifndef ENTO_OBJECT_HPP_INCLUDED
#define ENTO_OBJECT_HPP_INCLUDED
#include <Box2D.h>
namespace ento
{
/// Base for all game objects
class Object
{
public:
/// list of all game object types
enum Type
{
e_Static_Terrain,
e_Entomon,
e_Shot
};
Object( Type type );
virtual ~Object( void )
{
}
/// @return whether the next object should see the contact
virtual bool addContact( const b2ContactResult& point, b2Shape* s )
{
return true;
}
/// @return whether the next object should see the collision
virtual bool addCollision( const b2ContactPoint& point, b2Shape* s )
{
return true;
}
virtual int collisionPriority( void )
{
return 0;
}
virtual void preStep( float dt )
{
}
virtual void postStep( float dt )
{
}
inline Type type( void );
private:
const Type m_type; ///< the game object type
};
/// @return the object type
inline Object::Type Object::
type( void )
{
return m_type;
}
}// namespace ento
#endif // ENTO_OBJECT_HPP_INCLUDED
| 17.955224 | 74 | 0.571904 | fu7mu4 |
3e0ea51a9742e9ee27272a85e2e2eaeedde464ed | 1,791 | hpp | C++ | galaxy/src/galaxy/input/Mouse.hpp | reworks/rework | 90508252c9a4c77e45a38e7ce63cfd99f533f42b | [
"Apache-2.0"
] | 6 | 2018-07-21T20:37:01.000Z | 2018-10-31T01:49:35.000Z | galaxy/src/galaxy/input/Mouse.hpp | reworks/rework | 90508252c9a4c77e45a38e7ce63cfd99f533f42b | [
"Apache-2.0"
] | null | null | null | galaxy/src/galaxy/input/Mouse.hpp | reworks/rework | 90508252c9a4c77e45a38e7ce63cfd99f533f42b | [
"Apache-2.0"
] | null | null | null | ///
/// Mouse.hpp
/// galaxy
///
/// Refer to LICENSE.txt for more details.
///
#ifndef GALAXY_INPUT_MOUSE_HPP_
#define GALAXY_INPUT_MOUSE_HPP_
#include <glm/vec2.hpp>
#include "galaxy/input/InputDevice.hpp"
namespace galaxy
{
namespace input
{
///
/// Physical mouse device and state management.
///
class Mouse final : public InputDevice
{
friend class core::Window;
public:
///
/// \brief Enum class representing mouse buttons.
///
/// Values used are based off of GLFW.
///
enum class Buttons : int
{
UNKNOWN = -1,
BTN_1 = 0,
BTN_2 = 1,
BTN_3 = 2,
BTN_4 = 3,
BTN_5 = 4,
BTN_6 = 5,
BTN_7 = 6,
BTN_8 = 7,
BTN_LAST = BTN_8,
BTN_LEFT = BTN_1,
BTN_RIGHT = BTN_2,
BTN_MIDDLE = BTN_3
};
///
/// Destructor.
///
virtual ~Mouse() noexcept = default;
///
/// \brief Enable sticky mouse.
///
/// The pollable state of a nouse button will remain pressed until the state of that button is polled.
///
void enable_sticky_mouse() noexcept;
///
/// Disable sticky mouse.
///
void disable_sticky_mouse() noexcept;
///
/// Get last recorded mouse position.
///
/// \return XY vector position of cursor.
///
[[nodiscard]] glm::dvec2 get_pos() noexcept;
private:
///
/// Constructor.
///
Mouse() noexcept;
///
/// Move constructor.
///
Mouse(Mouse&&) = delete;
///
/// Move assignment operator.
///
Mouse& operator=(Mouse&&) = delete;
///
/// Copy constructor.
///
Mouse(const Mouse&) = delete;
///
/// Copy assignment operator.
///
Mouse& operator=(const Mouse&) = delete;
};
} // namespace input
} // namespace galaxy
#endif | 17.558824 | 105 | 0.564489 | reworks |
3e0f99001035521eca0535e341d247d24db03c45 | 7,115 | hpp | C++ | third_party/misc/def/def/defrCallBacks.hpp | jesec/livehd | 1a82dbea1d86dbd1511de588609de320aa4ef6ed | [
"BSD-3-Clause"
] | 115 | 2019-09-28T13:39:41.000Z | 2022-03-24T11:08:53.000Z | third_party/misc/def/def/defrCallBacks.hpp | jesec/livehd | 1a82dbea1d86dbd1511de588609de320aa4ef6ed | [
"BSD-3-Clause"
] | 120 | 2018-05-16T23:11:09.000Z | 2019-09-25T18:52:49.000Z | third_party/misc/def/def/defrCallBacks.hpp | jesec/livehd | 1a82dbea1d86dbd1511de588609de320aa4ef6ed | [
"BSD-3-Clause"
] | 44 | 2019-09-28T07:53:21.000Z | 2022-02-13T23:21:12.000Z | // *****************************************************************************
// *****************************************************************************
// Copyright 2013, Cadence Design Systems
//
// This file is part of the Cadence LEF/DEF Open Source
// Distribution, Product Version 5.8.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// For updates, support, or to become part of the LEF/DEF Community,
// check www.openeda.org for details.
//
// $Author: dell $
// $Revision: #1 $
// $Date: 2017/06/06 $
// $State: $
// *****************************************************************************
// *****************************************************************************
#ifndef DEFRCALLBACKS_H
#define DEFRCALLBACKS_H 1
#include "defiKRDefs.hpp"
#include "defrReader.hpp"
BEGIN_LEFDEF_PARSER_NAMESPACE
class defrCallbacks {
public:
defrCallbacks();
void SetUnusedCallbacks(defrVoidCbkFnType f);
defrStringCbkFnType DesignCbk;
defrStringCbkFnType TechnologyCbk;
defrVoidCbkFnType DesignEndCbk;
defrPropCbkFnType PropCbk;
defrVoidCbkFnType PropDefEndCbk;
defrVoidCbkFnType PropDefStartCbk;
defrStringCbkFnType ArrayNameCbk;
defrStringCbkFnType FloorPlanNameCbk;
defrDoubleCbkFnType UnitsCbk;
defrStringCbkFnType DividerCbk;
defrStringCbkFnType BusBitCbk;
defrSiteCbkFnType SiteCbk;
defrSiteCbkFnType CanplaceCbk;
defrSiteCbkFnType CannotOccupyCbk;
defrIntegerCbkFnType ComponentStartCbk;
defrVoidCbkFnType ComponentEndCbk;
defrComponentCbkFnType ComponentCbk;
defrComponentMaskShiftLayerCbkFnType ComponentMaskShiftLayerCbk;
defrIntegerCbkFnType NetStartCbk;
defrVoidCbkFnType NetEndCbk;
defrNetCbkFnType NetCbk;
defrStringCbkFnType NetNameCbk;
defrStringCbkFnType NetSubnetNameCbk;
defrStringCbkFnType NetNonDefaultRuleCbk;
defrNetCbkFnType NetPartialPathCbk;
defrPathCbkFnType PathCbk;
defrDoubleCbkFnType VersionCbk;
defrStringCbkFnType VersionStrCbk;
defrStringCbkFnType PinExtCbk;
defrStringCbkFnType ComponentExtCbk;
defrStringCbkFnType ViaExtCbk;
defrStringCbkFnType NetConnectionExtCbk;
defrStringCbkFnType NetExtCbk;
defrStringCbkFnType GroupExtCbk;
defrStringCbkFnType ScanChainExtCbk;
defrStringCbkFnType IoTimingsExtCbk;
defrStringCbkFnType PartitionsExtCbk;
defrStringCbkFnType HistoryCbk;
defrBoxCbkFnType DieAreaCbk;
defrPinCapCbkFnType PinCapCbk;
defrPinCbkFnType PinCbk;
defrIntegerCbkFnType StartPinsCbk;
defrVoidCbkFnType PinEndCbk;
defrIntegerCbkFnType DefaultCapCbk;
defrRowCbkFnType RowCbk;
defrTrackCbkFnType TrackCbk;
defrGcellGridCbkFnType GcellGridCbk;
defrIntegerCbkFnType ViaStartCbk;
defrVoidCbkFnType ViaEndCbk;
defrViaCbkFnType ViaCbk;
defrIntegerCbkFnType RegionStartCbk;
defrVoidCbkFnType RegionEndCbk;
defrRegionCbkFnType RegionCbk;
defrIntegerCbkFnType SNetStartCbk;
defrVoidCbkFnType SNetEndCbk;
defrNetCbkFnType SNetCbk;
defrNetCbkFnType SNetPartialPathCbk;
defrNetCbkFnType SNetWireCbk;
defrIntegerCbkFnType GroupsStartCbk;
defrVoidCbkFnType GroupsEndCbk;
defrStringCbkFnType GroupNameCbk;
defrStringCbkFnType GroupMemberCbk;
defrGroupCbkFnType GroupCbk;
defrIntegerCbkFnType AssertionsStartCbk;
defrVoidCbkFnType AssertionsEndCbk;
defrAssertionCbkFnType AssertionCbk;
defrIntegerCbkFnType ConstraintsStartCbk;
defrVoidCbkFnType ConstraintsEndCbk;
defrAssertionCbkFnType ConstraintCbk;
defrIntegerCbkFnType ScanchainsStartCbk;
defrVoidCbkFnType ScanchainsEndCbk;
defrScanchainCbkFnType ScanchainCbk;
defrIntegerCbkFnType IOTimingsStartCbk;
defrVoidCbkFnType IOTimingsEndCbk;
defrIOTimingCbkFnType IOTimingCbk;
defrIntegerCbkFnType FPCStartCbk;
defrVoidCbkFnType FPCEndCbk;
defrFPCCbkFnType FPCCbk;
defrIntegerCbkFnType TimingDisablesStartCbk;
defrVoidCbkFnType TimingDisablesEndCbk;
defrTimingDisableCbkFnType TimingDisableCbk;
defrIntegerCbkFnType PartitionsStartCbk;
defrVoidCbkFnType PartitionsEndCbk;
defrPartitionCbkFnType PartitionCbk;
defrIntegerCbkFnType PinPropStartCbk;
defrVoidCbkFnType PinPropEndCbk;
defrPinPropCbkFnType PinPropCbk;
defrIntegerCbkFnType CaseSensitiveCbk;
defrIntegerCbkFnType BlockageStartCbk;
defrVoidCbkFnType BlockageEndCbk;
defrBlockageCbkFnType BlockageCbk;
defrIntegerCbkFnType SlotStartCbk;
defrVoidCbkFnType SlotEndCbk;
defrSlotCbkFnType SlotCbk;
defrIntegerCbkFnType FillStartCbk;
defrVoidCbkFnType FillEndCbk;
defrFillCbkFnType FillCbk;
defrIntegerCbkFnType NonDefaultStartCbk;
defrVoidCbkFnType NonDefaultEndCbk;
defrNonDefaultCbkFnType NonDefaultCbk;
defrIntegerCbkFnType StylesStartCbk;
defrVoidCbkFnType StylesEndCbk;
defrStylesCbkFnType StylesCbk;
defrStringCbkFnType ExtensionCbk;
};
END_LEFDEF_PARSER_NAMESPACE
USE_LEFDEF_PARSER_NAMESPACE
#endif
| 45.903226 | 80 | 0.581588 | jesec |
3e14095a07a869c7851dcaece44d3a89081e1964 | 7,634 | cpp | C++ | Umbrella-Engine/Graphics/SDLWindow.cpp | jfla-fan/JFla-Engine | dcbdcdff815fd1729bed35ec556b850cc94f6553 | [
"MIT"
] | null | null | null | Umbrella-Engine/Graphics/SDLWindow.cpp | jfla-fan/JFla-Engine | dcbdcdff815fd1729bed35ec556b850cc94f6553 | [
"MIT"
] | null | null | null | Umbrella-Engine/Graphics/SDLWindow.cpp | jfla-fan/JFla-Engine | dcbdcdff815fd1729bed35ec556b850cc94f6553 | [
"MIT"
] | null | null | null | #include <OpenImageIO/imageio.h>
#include "../Image/ImageLoader.h"
#include "../Image/ImageUtils.h"
#include "SDLWindow.h"
#include <array>
#include <vector>
namespace J::Graphics
{
JSDLWindow::JSDLWindow(const SWindowCreateOptions& InOptions)
: options(InOptions), bIsOpened(false), window(nullptr, [](WindowHandle* window) {})
{
OnCreate(InOptions);
}
JSDLWindow::~JSDLWindow()
{
OnDestroy();
}
// examples of simple shaders
const std::string& VertexShader = R"(
#version 450 core
in vec3 inPosition;
in vec3 inColor;
in vec2 inTexCoords;
out vec3 outColor;
out vec2 outTexCoords;
void main()
{
gl_Position = vec4(inPosition, 1.0);
outColor = inColor;
outTexCoords = inTexCoords;
}
)";
const std::string& FragmentShader = R"(
#version 450 core
in vec3 outColor;
in vec2 outTexCoords;
uniform sampler2D sampler1;
uniform sampler2D sampler2;
void main()
{
gl_FragColor = max(texture(sampler1, outTexCoords), texture(sampler2, outTexCoords));
//gl_FragColor = texture(sampler1, outTexCoords);
//gl_FragColor = texture(sampler2, outTexCoords);
}
)";
//static std::map<Utils::ERawImageFormat, EGLDataType> ImageFormatToGLDataTypeTable =
//{
// { }
//}
void JSDLWindow::OnCreate(const SWindowCreateOptions& InOptions)
{
window = Scope<WindowHandle, DestroyWindowCallback>
(
SDL_CreateWindow
(
options.title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
options.width, options.height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE
),
[](WindowHandle* handle) { SDL_DestroyWindow(handle); }
);
// #todo set time when the window was created.
context = GraphicsContext::Create(window.get());
bIsOpened = true;
glViewport(0, 0, options.width, options.height);
const Math::LinearColor& yellow = Math::LinearColor::Yellow;
// rectangle
RECT_VAO = MakeRef<OpenGLVertexArray>();
// rectangle coordinates and color
// position // color
Vertices[0] = { Vector3 {0.5f, 0.5f, 0.f}, Vector3 {1.0f, 0.0f, 0.0f} };
Vertices[1] = { Vector3 {-0.5f, 0.5f, 0.f}, Vector3 {0.0f, 1.0f, 0.0f} };
Vertices[2] = { Vector3 {-0.5f, -0.5f, 0.f}, Vector3 {0.0f, 0.0f, 1.0f} };
Vertices[3] = { Vector3 {0.5f, -0.5f, 0.f}, Vector3 { yellow.R(), yellow.G(), yellow.B() } };
const std::string ImagePath = "C:/Users/ДНС/Documents/Projects/VisualStudioProjects/GameEngine/Resources/Images/sleepy-cat.jpg";
const std::string DendyImagePath = "C:/Users/ДНС/Documents/Projects/VisualStudioProjects/GameEngine/Resources/Images/dendy.png";
const std::string SaveImagePath = "C:/Users/ДНС/Documents/Projects/VisualStudioProjects/GameEngine/Resources/Images/flipped-sleepy-cat.jpg";
Utils::ImagePtr image = Utils::ImageLoader::Load(ImagePath, true);
if (!image)
{
std::cout << std::format("Could not load {} image.\n", ImagePath);
std::exit(EXIT_FAILURE);
}
image->PrintImageMetaData(std::cout);
Utils::ImagePtr dendyImage = Utils::ImageLoader::Load(DendyImagePath, true);
if (!dendyImage)
{
std::cout << std::format("Could not load {} image.\n", DendyImagePath);
std::exit(EXIT_FAILURE);
}
dendyImage->PrintImageMetaData(std::cout);
//glGenTextures(1, &TextureID);
//glGenTextures(1, &texture2);
//glActiveTexture(GL_TEXTURE0);
//glBindTexture(GL_TEXTURE_2D, TextureID);
//glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, dendyImage->GetWidth(), dendyImage->GetHeight(), 0, GL_RGB, GL_UNSIGNED_BYTE, dendyImage->RawData());
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
////glTextureParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, color);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_NEAREST);
//glGenerateMipmap(GL_TEXTURE_2D);
////glBindTexture(GL_TEXTURE_2D, 0);
//glActiveTexture(GL_TEXTURE0 + 1);
//glBindTexture(GL_TEXTURE_2D, texture2);
//glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, image->GetWidth(), image->GetHeight(), 0, GL_RGB8, GL_UNSIGNED_BYTE, image->RawData());
//
//float color[] = { 1.0f, 0.0f, 0.0f, 1.0f };
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
////glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, color);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_NEAREST);
//glGenerateMipmap(GL_TEXTURE_2D);
RECT_TEXTURE1 = MakeRef<OpenGLTexture>();
RECT_TEXTURE2 = MakeRef<OpenGLTexture>();
if (!RECT_TEXTURE1->Load(*image))
{
std::cout << "Failed to load texture\n";
std::exit(1);
}
if (!RECT_TEXTURE2->Load(*dendyImage))
{
std::cout << "Failed to load texture\n";
std::exit(1);
}
image.reset();
dendyImage.reset();
RECT_VBO = OpenGLVertexBuffer::Create(
new float[]
{
// position // color // uv - texture coordinates
0.5f, 0.5f, 0.f, 1.0f, 0.0f, 0.0f, /* red */ 1.0f, 1.0f,
-0.5f, 0.5f, 0.f, 0.0f, 1.0f, 0.0f, /* green */ 0.0f, 1.0f,
-0.5f, -0.5f, 0.f, 0.0f, 0.0f, 1.0f, /* blue */ 0.0f, 0.0f,
0.5f, -0.5f, 0.f, yellow.R(), yellow.G(), yellow.B(), 1.0f, 0.0f,
},
8 * 4
);
// index buffer
RECT_IBO = OpenGLIndexBuffer::Create(
new uint32[]
{
0, 1, 2,
3, 0, 2
},
6,
GpuApi::EBufferAccessBits::ALL
);
RECT_VAO->AddVertexLayout(RECT_VBO,
std::array
{
SVertexAttribute::GetAttribute<Vector3>(),
SVertexAttribute::GetAttribute<Vector3>(),
SVertexAttribute::GetAttribute<Vector2>()
}
);
// disable color attribute
// this should result in a black square (square without color) [to enable add true to every attribute in constructor]
RECT_VAO->RemoveVertexLayout(
std::array
{
SVertexAttribute::GetAttribute<Vector3>(),
SVertexAttribute::GetAttribute<Vector3>(),
}
);
// Dealing with shaders
SHADER = MakeRef<OpenGLShader>();
SHADER->LoadFromString(VertexShader, FragmentShader);
/*glUniform1i(glGetUniformLocation(SHADER->GetHandle(), "samp"), 0);
glUniform1i(glGetUniformLocation(SHADER->GetHandle(), "cat"), 1);*/
GraphicsContext::BindShader(*SHADER);
RECT_TEXTURE1->Bind(0);
RECT_TEXTURE2->Bind(1);
SHADER->SetUniform("sampler1", 0);
SHADER->SetUniform("sampler2", 1);
//SHADER->SetUniform("sampler2", 1);
}
void JSDLWindow::OnUpdate()
{
SDL_Event e;
while (SDL_PollEvent(&e))
{
// dispatch every event using event dispatcher.
// all the callbacks should be invoked in application class
// using event dispatcher
if (e.type == SDL_QUIT)
{
std::cout << "quit";
this->Close();
std::exit(0);
}
}
}
void JSDLWindow::OnRender()
{
/*GraphicsContext::ClearColor(Math::LinearColor::Blue);
GraphicsContext::Clear();*/
const float color[] = { 0.2f, 0.5f, 0.7f, 1.0f };
glClearBufferfv(GL_COLOR, 0, color);
// draw something with OpenGL here
RECT_VAO->Bind();
//glDrawArrays(GL_POINTS, 0, 3);
GraphicsContext::DrawElements(EGLPrimitiveType::TRIANGLES, *RECT_IBO); // instead of graphics context here will be used renderer
GraphicsContext::SwapBuffers(window.get());
}
void JSDLWindow::OnDestroy()
{
this->Close();
}
void JSDLWindow::Close()
{
if (bIsOpened)
{
std::cout << "Releasing resource\n";
window.reset();
bIsOpened = false;
}
}
}
| 26.233677 | 144 | 0.680639 | jfla-fan |
3e190dba3891551e0742b37c384e58d2634746bc | 755 | cpp | C++ | HackerEarth/Data Structure/Arrays/1D/Takeoff.cpp | AdityaChirravuri/CompetitiveProgramming | 642550e8916b3f7939a1fdd52d10f5f8ae43f161 | [
"MIT"
] | 1 | 2021-07-13T01:49:25.000Z | 2021-07-13T01:49:25.000Z | HackerEarth/Data Structure/Arrays/1D/Takeoff.cpp | AdityaChirravuri/CompetitiveProgramming | 642550e8916b3f7939a1fdd52d10f5f8ae43f161 | [
"MIT"
] | null | null | null | HackerEarth/Data Structure/Arrays/1D/Takeoff.cpp | AdityaChirravuri/CompetitiveProgramming | 642550e8916b3f7939a1fdd52d10f5f8ae43f161 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define fastIO ios_base::sync_with_stdio(false); cin.tie(NULL);
#define ll long long int
int main()
{
fastIO
int t;
cin >> t;
for(int i=0; i<t; i++){
ll n, p, q, r;
cin >> n >> p >> q >> r;
vector<ll>arr(n+1, 0);
for(ll i=1; i<=n; i++){
if(i%p == 0){
arr[i]++;
}
if(i%q == 0){
arr[i]++;
}
if(i%r == 0){
arr[i]++;
}
}
ll count = 0;
for(ll i=1; i<=n; i++){
//cout << arr[i] << " ";
if(arr[i] == 1)count++;
}
cout << count << "\n";
}
return 0;
}
| 18.414634 | 63 | 0.335099 | AdityaChirravuri |
3e192b7bc7c7109250b95f60e59ff653a775bbc6 | 367 | cxx | C++ | Algorithms/Strings/beautiful-binary-string.cxx | will-crawford/HackerRank | 74965480ee6a51603eb320e5982b0943fdaf1302 | [
"MIT"
] | null | null | null | Algorithms/Strings/beautiful-binary-string.cxx | will-crawford/HackerRank | 74965480ee6a51603eb320e5982b0943fdaf1302 | [
"MIT"
] | null | null | null | Algorithms/Strings/beautiful-binary-string.cxx | will-crawford/HackerRank | 74965480ee6a51603eb320e5982b0943fdaf1302 | [
"MIT"
] | null | null | null | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n; cin >> n; string s, needle = "010"; cin >> s; int changes = 0;
for ( string::size_type p = 0, q = string::npos; ( p = s.find ( needle, p ) ) != q; p += 3, ++changes )
;
cout << changes << endl;
return 0;
}
| 22.9375 | 107 | 0.566757 | will-crawford |
3e1bdee67edb08fffcaa80562d57b36e7a17f7ca | 6,580 | inl | C++ | include/ffsm2/detail/structure/composite.inl | linuxxiaolei/FFSM2 | d432e2ea361d81c69638a931ad821e7a7e47e748 | [
"MIT"
] | 1 | 2021-01-28T14:54:32.000Z | 2021-01-28T14:54:32.000Z | include/ffsm2/detail/structure/composite.inl | linuxxiaolei/FFSM2 | d432e2ea361d81c69638a931ad821e7a7e47e748 | [
"MIT"
] | null | null | null | include/ffsm2/detail/structure/composite.inl | linuxxiaolei/FFSM2 | d432e2ea361d81c69638a931ad821e7a7e47e748 | [
"MIT"
] | null | null | null | namespace ffsm2 {
namespace detail {
////////////////////////////////////////////////////////////////////////////////
template <typename TA, typename TH, typename... TS>
bool
C_<TA, TH, TS...>::deepForwardEntryGuard(GuardControl& control) noexcept {
FFSM2_ASSERT(control._registry.active != INVALID_SHORT);
const Short requested = control._registry.requested;
FFSM2_ASSERT(requested != INVALID_SHORT);
return _subStates.wideEntryGuard(control, requested);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TA, typename TH, typename... TS>
bool
C_<TA, TH, TS...>::deepEntryGuard(GuardControl& control) noexcept {
const Short requested = control._registry.requested;
FFSM2_ASSERT(requested != INVALID_SHORT);
return _headState.deepEntryGuard(control) ||
_subStates.wideEntryGuard(control, requested);
}
//------------------------------------------------------------------------------
template <typename TA, typename TH, typename... TS>
void
C_<TA, TH, TS...>::deepConstruct(PlanControl& control) noexcept {
Short& active = control._registry.active;
Short& requested = control._registry.requested;
FFSM2_ASSERT(active == INVALID_SHORT);
FFSM2_ASSERT(requested != INVALID_SHORT);
active = requested;
requested = INVALID_SHORT;
_headState.deepConstruct(control);
_subStates.wideConstruct(control, active);
}
//------------------------------------------------------------------------------
template <typename TA, typename TH, typename... TS>
void
C_<TA, TH, TS...>::deepEnter(PlanControl& control) noexcept {
const Short active = control._registry.active;
FFSM2_ASSERT(active != INVALID_SHORT);
FFSM2_ASSERT(control._registry.requested == INVALID_SHORT);
_headState.deepEnter(control);
_subStates.wideEnter(control, active);
}
//------------------------------------------------------------------------------
template <typename TA, typename TH, typename... TS>
void
C_<TA, TH, TS...>::deepUpdate(FullControl& control) noexcept {
const Short active = control._registry.active;
FFSM2_ASSERT(active != INVALID_SHORT);
FFSM2_ASSERT(control._registry.requested == INVALID_SHORT);
if (_headState.deepUpdate(control)) {
ControlLock lock{control};
_subStates.wideUpdate(control, active);
} else {
FFSM2_IF_PLANS(const Status subStatus =)
_subStates.wideUpdate(control, active);
#ifdef FFSM2_ENABLE_PLANS
if (subStatus && control._planData.planExists)
control.updatePlan(_headState, subStatus);
#endif
}
}
//------------------------------------------------------------------------------
template <typename TA, typename TH, typename... TS>
template <typename TEvent>
void
C_<TA, TH, TS...>::deepReact(FullControl& control,
const TEvent& event) noexcept
{
const Short active = control._registry.active;
FFSM2_ASSERT(active != INVALID_SHORT);
FFSM2_ASSERT(control._registry.requested == INVALID_SHORT);
if (_headState.deepReact(control, event)) {
ControlLock lock{control};
_subStates.wideReact(control, event, active);
} else {
FFSM2_IF_PLANS(const Status subStatus =)
_subStates.wideReact(control, event, active);
#ifdef FFSM2_ENABLE_PLANS
if (subStatus && control._planData.planExists)
control.updatePlan(_headState, subStatus);
#endif
}
}
//------------------------------------------------------------------------------
template <typename TA, typename TH, typename... TS>
bool
C_<TA, TH, TS...>::deepForwardExitGuard(GuardControl& control) noexcept {
FFSM2_ASSERT(control._registry.requested != INVALID_SHORT);
const Short active = control._registry.active;
FFSM2_ASSERT(active != INVALID_SHORT);
return _subStates.wideExitGuard(control, active);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TA, typename TH, typename... TS>
bool
C_<TA, TH, TS...>::deepExitGuard(GuardControl& control) noexcept {
const Short active = control._registry.active;
FFSM2_ASSERT(active != INVALID_SHORT);
FFSM2_ASSERT(control._registry.requested != INVALID_SHORT);
return _headState.deepExitGuard(control) ||
_subStates.wideExitGuard(control, active);
}
//------------------------------------------------------------------------------
template <typename TA, typename TH, typename... TS>
void
C_<TA, TH, TS...>::deepExit(PlanControl& control) noexcept {
const Short active = control._registry.active;
FFSM2_ASSERT(active != INVALID_SHORT);
_subStates.wideExit(control, active);
_headState.deepExit(control);
}
//------------------------------------------------------------------------------
template <typename TA, typename TH, typename... TS>
void
C_<TA, TH, TS...>::deepDestruct(PlanControl& control) noexcept {
Short& active = control._registry.active;
FFSM2_ASSERT(active != INVALID_SHORT);
_subStates.wideDestruct(control, active);
_headState.deepDestruct(control);
active = INVALID_SHORT;
#ifdef FFSM2_ENABLE_PLANS
auto plan = control.plan();
plan.clear();
#endif
}
//------------------------------------------------------------------------------
// COMMON
template <typename TA, typename TH, typename... TS>
void
C_<TA, TH, TS...>::deepChangeToRequested(PlanControl& control) noexcept {
Short& active = control._registry.active;
Short& requested = control._registry.requested;
FFSM2_ASSERT(active != INVALID_SHORT);
FFSM2_ASSERT(requested != INVALID_SHORT);
if (requested != active) {
_subStates.wideExit (control, active);
_subStates.wideDestruct (control, active);
active = requested;
requested = INVALID_SHORT;
_subStates.wideConstruct(control, active);
_subStates.wideEnter (control, active);
} else {
requested = INVALID_SHORT;
// reconstruction done in S_::reenter()
_subStates.wideReenter (control, active);
}
}
//------------------------------------------------------------------------------
#ifdef FFSM2_ENABLE_SERIALIZATION
template <typename TA, typename TH, typename... TS>
void
C_<TA, TH, TS...>::deepSaveActive(const Registry& registry,
WriteStream& stream) const noexcept
{
stream.template write<WIDTH_BITS>(registry.active);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TA, typename TH, typename... TS>
void
C_<TA, TH, TS...>::deepLoadRequested(Registry& registry,
ReadStream& stream) const noexcept
{
registry.requested = stream.template read<WIDTH_BITS>();
FFSM2_ASSERT(registry.requested < WIDTH);
}
#endif
// COMMON
////////////////////////////////////////////////////////////////////////////////
}
}
| 28.362069 | 80 | 0.615957 | linuxxiaolei |
3e1c678ad3701d9aa1940eb91bb452f846afb038 | 482 | cc | C++ | bucket_1F/mysql80/patches/patch-storage_myisam_mi__dynrec.cc | jrmarino/ravensource | 91d599fd1f2af55270258d15e72c62774f36033e | [
"FTL"
] | 17 | 2017-04-22T21:53:52.000Z | 2021-01-21T16:57:55.000Z | bucket_1F/mysql80/patches/patch-storage_myisam_mi__dynrec.cc | jrmarino/ravensource | 91d599fd1f2af55270258d15e72c62774f36033e | [
"FTL"
] | 186 | 2017-09-12T20:46:52.000Z | 2021-11-27T18:15:14.000Z | bucket_1F/mysql80/patches/patch-storage_myisam_mi__dynrec.cc | jrmarino/ravensource | 91d599fd1f2af55270258d15e72c62774f36033e | [
"FTL"
] | 74 | 2017-09-06T14:48:01.000Z | 2021-08-28T02:48:27.000Z | --- storage/myisam/mi_dynrec.cc.orig 2021-07-01 07:53:49 UTC
+++ storage/myisam/mi_dynrec.cc
@@ -92,6 +92,9 @@ bool mi_dynmap_file(MI_INFO *info, my_of
mapping. When swap space is not reserved one might get SIGSEGV
upon a write if no physical memory is available.
*/
+#ifndef MAP_NORESERVE
+#define MAP_NORESERVE 0
+#endif
info->s->file_map = (uchar *)my_mmap(
nullptr, (size_t)size,
info->s->mode == O_RDONLY ? PROT_READ : PROT_READ | PROT_WRITE,
| 37.076923 | 70 | 0.684647 | jrmarino |
3e1d42cb90f570ba2f60d5ee941351edb677e1c7 | 1,093 | cpp | C++ | Source/Engine/Ultra/Renderer/Framebuffer.cpp | larioteo/ultra | 48910110caae485ef518a0e972ab7271f5e5b430 | [
"MIT"
] | null | null | null | Source/Engine/Ultra/Renderer/Framebuffer.cpp | larioteo/ultra | 48910110caae485ef518a0e972ab7271f5e5b430 | [
"MIT"
] | null | null | null | Source/Engine/Ultra/Renderer/Framebuffer.cpp | larioteo/ultra | 48910110caae485ef518a0e972ab7271f5e5b430 | [
"MIT"
] | null | null | null | #include "FrameBuffer.h"
#include "Ultra/Platform/OpenGL/GLFramebuffer.h"
#include "Ultra/Platform/Vulkan/VKFramebuffer.h"
#include "Renderer.h"
namespace Ultra {
Reference<Framebuffer> Framebuffer::Create(const FramebufferProperties &properties) {
switch (Context::API) {
case GraphicsAPI::Null: { return nullptr; }
case GraphicsAPI::OpenGL: { return CreateReference<GLFramebuffer>(properties); }
case GraphicsAPI::Vulkan: { return CreateReference<VKFramebuffer>(properties); }
default: { break; }
}
AppLogCritical("[Engine::Renderer::Framebuffer] ", "The current graphics API doesn't support Framebuffers!");
return nullptr;
}
FramebufferPool::FramebufferPool(uint32_t maxBuffers) {
static FramebufferPool *instance = this;
Instance = instance;
}
FramebufferPool::~FramebufferPool() {}
void FramebufferPool::Add(const Reference<Framebuffer> &framebuffer) {
Pool.push_back(framebuffer);
}
weak_ptr<Framebuffer> FramebufferPool::Allocate() {
// ToDo: Push back to Pool
return weak_ptr<Framebuffer>();
}
}
| 29.540541 | 113 | 0.717292 | larioteo |
4a3f10ec880bcfce0979584c6d23b68a9347c114 | 1,369 | cc | C++ | tests/api/mpi/comm/ctxalloc.cc | jpkenny/sst-macro | bcc1f43034281885104962586d8b104df84b58bd | [
"BSD-Source-Code"
] | 20 | 2017-01-26T09:28:23.000Z | 2022-01-17T11:31:55.000Z | tests/api/mpi/comm/ctxalloc.cc | jpkenny/sst-macro | bcc1f43034281885104962586d8b104df84b58bd | [
"BSD-Source-Code"
] | 542 | 2016-03-29T22:50:58.000Z | 2022-03-22T20:14:08.000Z | tests/api/mpi/comm/ctxalloc.cc | jpkenny/sst-macro | bcc1f43034281885104962586d8b104df84b58bd | [
"BSD-Source-Code"
] | 36 | 2016-03-10T21:33:54.000Z | 2021-12-01T07:44:12.000Z | /*
*
* (C) 2003 by Argonne National Laboratory.
* See COPYRIGHT in top-level directory.
*/
#include <sstmac/replacements/mpi/mpi.h>
#include <stdio.h>
#include "mpitest.h"
namespace ctxalloc {
/**
* This program tests the allocation (and deallocation) of contexts.
*
*/
int ctxalloc( int argc, char **argv )
{
int errs = 0;
int i, j, err;
MPI_Comm newcomm1, newcomm2[200];
MTest_Init( &argc, &argv );
/** Get a separate communicator to duplicate */
MPI_Comm_dup( MPI_COMM_WORLD, &newcomm1 );
MPI_Errhandler_set( newcomm1, MPI_ERRORS_RETURN );
/** Allocate many communicators in batches, then free them */
for (i=0; i<1000; i++) {
for (j=0; j<200; j++) {
err = MPI_Comm_dup( newcomm1, &newcomm2[j] );
if (err) {
errs++;
if (errs < 10) {
fprintf( stderr, "Failed to duplicate communicator for (%d,%d)\n", i, j );
MTestPrintError( err );
}
}
}
for (j=0; j<200; j++) {
err = MPI_Comm_free( &newcomm2[j] );
if (err) {
errs++;
if (errs < 10) {
fprintf( stderr, "Failed to free %d,%d\n", i, j );
MTestPrintError( err );
}
}
}
}
err = MPI_Comm_free( &newcomm1 );
if (err) {
errs++;
fprintf( stderr, "Failed to free newcomm1\n" );
MTestPrintError( err );
}
MTest_Finalize( errs );
MPI_Finalize();
return 0;
}
}
| 20.432836 | 80 | 0.583638 | jpkenny |
4a4147713a1fcb999b67f43f50d048973489619c | 5,766 | cpp | C++ | blades/xbmc/xbmc/linux/FDEventMonitor.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 4 | 2016-04-26T03:43:54.000Z | 2016-11-17T08:09:04.000Z | blades/xbmc/xbmc/linux/FDEventMonitor.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 17 | 2015-01-05T21:06:22.000Z | 2015-12-07T20:45:44.000Z | blades/xbmc/xbmc/linux/FDEventMonitor.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 3 | 2016-04-26T03:43:55.000Z | 2020-11-06T11:02:08.000Z | /*
* Copyright (C) 2014 Team Kodi
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Kodi; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "system.h"
#ifdef HAS_ALSA
#include <poll.h>
#include <sys/eventfd.h>
#include <errno.h>
#include "utils/log.h"
#include "FDEventMonitor.h"
CFDEventMonitor::CFDEventMonitor() :
CThread("FDEventMonitor"),
m_nextID(0),
m_wakeupfd(-1)
{
}
CFDEventMonitor::~CFDEventMonitor()
{
CSingleLock lock(m_mutex);
InterruptPoll();
if (m_wakeupfd >= 0)
{
/* sets m_bStop */
StopThread(false);
/* wake up the poll() call */
eventfd_write(m_wakeupfd, 1);
/* Wait for the thread to stop */
{
CSingleExit exit(m_mutex);
StopThread(true);
}
close(m_wakeupfd);
}
}
void CFDEventMonitor::AddFD(const MonitoredFD& monitoredFD, int& id)
{
CSingleLock lock(m_mutex);
InterruptPoll();
AddFDLocked(monitoredFD, id);
StartMonitoring();
}
void CFDEventMonitor::AddFDs(const std::vector<MonitoredFD>& monitoredFDs,
std::vector<int>& ids)
{
CSingleLock lock(m_mutex);
InterruptPoll();
for (unsigned int i = 0; i < monitoredFDs.size(); ++i)
{
int id;
AddFDLocked(monitoredFDs[i], id);
ids.push_back(id);
}
StartMonitoring();
}
void CFDEventMonitor::RemoveFD(int id)
{
CSingleLock lock(m_mutex);
InterruptPoll();
if (m_monitoredFDs.erase(id) != 1)
{
CLog::Log(LOGERROR, "CFDEventMonitor::RemoveFD - Tried to remove non-existing monitoredFD %d", id);
}
UpdatePollDescs();
}
void CFDEventMonitor::RemoveFDs(const std::vector<int>& ids)
{
CSingleLock lock(m_mutex);
InterruptPoll();
for (unsigned int i = 0; i < ids.size(); ++i)
{
if (m_monitoredFDs.erase(ids[i]) != 1)
{
CLog::Log(LOGERROR, "CFDEventMonitor::RemoveFDs - Tried to remove non-existing monitoredFD %d while removing %u FDs", ids[i], (unsigned)ids.size());
}
}
UpdatePollDescs();
}
void CFDEventMonitor::Process()
{
eventfd_t dummy;
while (!m_bStop)
{
CSingleLock lock(m_mutex);
CSingleLock pollLock(m_pollMutex);
/*
* Leave the main mutex here to allow another thread to
* lock it while we are in poll().
* By then calling InterruptPoll() the other thread can
* wake up poll and wait for the processing to pause at
* the above lock(m_mutex).
*/
lock.Leave();
int err = poll(&m_pollDescs[0], m_pollDescs.size(), -1);
if (err < 0 && errno != EINTR)
{
CLog::Log(LOGERROR, "CFDEventMonitor::Process - poll() failed, error %d, stopping monitoring", errno);
StopThread(false);
}
// Something woke us up - either there is data available or we are being
// paused/stopped via m_wakeupfd.
for (unsigned int i = 0; i < m_pollDescs.size(); ++i)
{
struct pollfd& pollDesc = m_pollDescs[i];
int id = m_monitoredFDbyPollDescs[i];
const MonitoredFD& monitoredFD = m_monitoredFDs[id];
if (pollDesc.revents)
{
if (monitoredFD.callback)
{
monitoredFD.callback(id, pollDesc.fd, pollDesc.revents,
monitoredFD.callbackData);
}
if (pollDesc.revents & (POLLERR | POLLHUP | POLLNVAL))
{
CLog::Log(LOGERROR, "CFDEventMonitor::Process - polled fd %d got revents 0x%x, removing it", pollDesc.fd, pollDesc.revents);
/* Probably would be nice to inform our caller that their FD was
* dropped, but oh well... */
m_monitoredFDs.erase(id);
UpdatePollDescs();
}
pollDesc.revents = 0;
}
}
/* flush wakeup fd */
eventfd_read(m_wakeupfd, &dummy);
}
}
void CFDEventMonitor::AddFDLocked(const MonitoredFD& monitoredFD, int& id)
{
id = m_nextID;
while (m_monitoredFDs.count(id))
{
++id;
}
m_nextID = id + 1;
m_monitoredFDs[id] = monitoredFD;
AddPollDesc(id, monitoredFD.fd, monitoredFD.events);
}
void CFDEventMonitor::AddPollDesc(int id, int fd, short events)
{
struct pollfd newPollFD;
newPollFD.fd = fd;
newPollFD.events = events;
newPollFD.revents = 0;
m_pollDescs.push_back(newPollFD);
m_monitoredFDbyPollDescs.push_back(id);
}
void CFDEventMonitor::UpdatePollDescs()
{
m_monitoredFDbyPollDescs.clear();
m_pollDescs.clear();
for (std::map<int, MonitoredFD>::iterator it = m_monitoredFDs.begin();
it != m_monitoredFDs.end(); ++it)
{
AddPollDesc(it->first, it->second.fd, it->second.events);
}
}
void CFDEventMonitor::StartMonitoring()
{
if (!IsRunning())
{
/* Start the monitoring thread */
m_wakeupfd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
if (m_wakeupfd < 0)
{
CLog::Log(LOGERROR, "CFDEventMonitor::StartMonitoring - Failed to create eventfd, error %d", errno);
return;
}
/* Add wakeup fd to the fd list */
int id;
AddFDLocked(MonitoredFD(m_wakeupfd, POLLIN, NULL, NULL), id);
Create(false);
}
}
void CFDEventMonitor::InterruptPoll()
{
if (m_wakeupfd >= 0)
{
eventfd_write(m_wakeupfd, 1);
/* wait for the poll() result handling (if any) to end */
CSingleLock pollLock(m_pollMutex);
}
}
#endif
| 23.156627 | 154 | 0.647242 | krattai |
4a421482460913dfde21e0ed245bf59855dc508c | 105 | cpp | C++ | chapter-10/10.23.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-10/10.23.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-10/10.23.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | // bind requires an argument as callable and the rest arguments responded to given callable's arguments.
| 52.5 | 104 | 0.809524 | zero4drift |
4a4599afa096b26e7200e173d36392f3092d1798 | 2,966 | cpp | C++ | src/systemc/tests/systemc/utils/sc_vector/test09/iter_test.cpp | hyu-iot/gem5 | aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5 | [
"BSD-3-Clause"
] | 765 | 2015-01-14T16:17:04.000Z | 2022-03-28T07:46:28.000Z | src/systemc/tests/systemc/utils/sc_vector/test09/iter_test.cpp | hyu-iot/gem5 | aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5 | [
"BSD-3-Clause"
] | 148 | 2018-07-20T00:58:36.000Z | 2021-11-16T01:52:33.000Z | src/systemc/tests/systemc/utils/sc_vector/test09/iter_test.cpp | hyu-iot/gem5 | aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5 | [
"BSD-3-Clause"
] | 807 | 2015-01-06T09:55:38.000Z | 2022-03-30T10:23:36.000Z | /*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
/*****************************************************************************
iter_test.cpp -- sc_vector iterator comparisons
Original Author: Philipp A. Hartmann, OFFIS, 2014-08-21
*****************************************************************************/
#include <systemc.h>
SC_MODULE(mod)
{
sc_in<bool> p;
SC_CTOR(mod){}
};
int sc_main(int,char*[])
{
typedef sc_vector<mod> module_vec;
typedef sc_vector_assembly<mod,sc_in<bool> > module_port_vec;
module_vec mv("sigs",5);
module_vec::const_iterator citr = mv.begin();
module_vec::iterator itr = mv.begin();
module_port_vec mpv = sc_assemble_vector(mv, &mod::p);
module_port_vec::const_iterator cpitr = mpv.cbegin();
module_port_vec::iterator pitr = mpv.begin();
sc_assert(itr == citr);
sc_assert(citr == itr);
sc_assert(!(itr != citr));
sc_assert(!(citr != itr));
sc_assert(itr == cpitr);
sc_assert(citr == pitr);
sc_assert(cpitr == itr);
sc_assert(pitr == citr);
sc_assert(!(itr != cpitr));
sc_assert(!(citr != pitr));
sc_assert(!(cpitr != pitr));
sc_assert(!(pitr != itr));
sc_assert(itr < mv.end());
sc_assert(!(itr > mv.cend()));
sc_assert(citr < mv.end());
sc_assert(!(citr > mv.cend()));
++citr;
sc_assert(itr != citr);
sc_assert(citr != itr);
sc_assert(!(itr == citr));
sc_assert(!(citr == itr));
sc_assert(!(itr < itr));
sc_assert(!(itr > itr));
sc_assert(itr < citr);
sc_assert(citr > itr);
sc_assert(1 == citr - mv.begin());
sc_assert(0 == pitr - mv.cbegin());
itr += citr - mpv.begin();
sc_assert(1 == itr - mpv.cbegin());
sc_assert(citr == itr);
sc_assert(itr <= citr);
sc_assert(citr <= itr);
sc_assert(cpitr <= itr);
sc_assert(!(itr <= cpitr));
itr++;
cpitr = pitr += itr - mv.begin();
sc_assert(itr == pitr);
sc_assert(itr >= citr);
sc_assert(!(citr >= pitr));
cout << "\nSuccess" << endl;
return 0;
}
| 30.265306 | 79 | 0.574511 | hyu-iot |
4a45ea7316f8208ddb76bfaca6df1524088df1fd | 9,579 | cxx | C++ | StRoot/StMuDSTMaker/COMMON/StMuEmcUtil.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StRoot/StMuDSTMaker/COMMON/StMuEmcUtil.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | StRoot/StMuDSTMaker/COMMON/StMuEmcUtil.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | #include "StMuEmcUtil.h"
#include "StEvent.h"
#include "StMessMgr.h"
#include "StEventTypes.h"
#include "StMuEmcCollection.h"
#include "SystemOfUnits.h"
#include "StEmcUtil/geometry/StEmcGeom.h"
#include "StMuEmcTowerData.h"
ClassImp(StMuEmcUtil)
#define __EMC_HITS_ID_DIM__ 18000
StMuEmcUtil::StMuEmcUtil()
: TObject()
{
for(Int_t i =0;i<4;i++) mGeo[i]=StEmcGeom::getEmcGeom(i+1);
}
StMuEmcUtil::~StMuEmcUtil()
{
}
StMuEmcCollection* StMuEmcUtil::getMuEmc(const StEmcCollection *emccol)
{
if(!emccol) return NULL;
StMuEmcCollection* muEmc=new StMuEmcCollection();
fillMuEmc(muEmc,emccol);
return muEmc;
}
StEmcCollection* StMuEmcUtil::getEmc(const StMuEmcCollection* muEmc)
{
if(!muEmc) return NULL;
StEmcCollection *emc=new StEmcCollection();
fillEmc(emc,muEmc);
return emc;
}
void StMuEmcUtil::fillMuEmc(StMuEmcCollection *muEmc, const StEmcCollection *emccol)
{
if(!emccol) return;
if(!muEmc) return;
// starting by hits;
//cout <<"Filling hits and clusters \n";
for(Int_t d=0; d<8; d++)
{
Int_t EmcDet=d+1;
StDetectorId id = static_cast<StDetectorId>(d+kBarrelEmcTowerId);
const StEmcDetector* detector=emccol->detector(id);
if(detector)
{
Int_t maxMod = 121;
if(d>3) maxMod = 14;
//cout <<"Filling hits for detetor "<<EmcDet<<endl;
for(Int_t j=1;j<maxMod;j++)
{
const StEmcModule* module = detector->module(j);
if(module)
{
const StSPtrVecEmcRawHit& rawHit=module->hits();
Int_t nhits=(Int_t)rawHit.size();
if(nhits>0)
for(Int_t k=0;k<nhits;k++)
{
Int_t m = rawHit[k]->module();
Int_t e = rawHit[k]->eta();
Int_t s = abs(rawHit[k]->sub());
Int_t adc = rawHit[k]->adc();
Float_t energy = rawHit[k]->energy();
Int_t cal = rawHit[k]->calibrationType();
Int_t rid;
bool save = true;
if(d<4 && cal>127) save = false;
if(save)
{
if (d<4) // for the barrel
{
mGeo[d]->getId(m,e,s,rid);
}
else
{
if(getEndcapId(EmcDet,m,e,s,rid)) continue;// on error
}
if(EmcDet == 1 || EmcDet == 5 ) // towers save only ADC
{
muEmc->setTowerADC(rid,adc,EmcDet);
}
if(EmcDet==2 || EmcDet == 6) //pre shower
{
muEmc->addPrsHit(EmcDet);
StMuEmcHit* muHit = muEmc->getPrsHit(muEmc->getNPrsHits(EmcDet)-1,EmcDet);
muHit->setId(rid);
muHit->setAdc(adc);
muHit->setEnergy(energy);
muHit->setCalType(cal);
}
if(EmcDet==3 || EmcDet==4 || EmcDet==7 || EmcDet==8)
{
muEmc->addSmdHit(EmcDet);
StMuEmcHit* muHit = muEmc->getSmdHit(muEmc->getNSmdHits(EmcDet)-1,EmcDet);
muHit->setId(rid);
muHit->setAdc(adc);
muHit->setEnergy(energy);
muHit->setCalType(cal);
}
}
}
}
}
Int_t n_crate=0;
switch (EmcDet) {
case 1:
n_crate=StMuEmcTowerData::nBTowCrates;
break;
case 2:
n_crate=StMuEmcTowerData::nBPrsCrates;
break;
case 3:
n_crate=StMuEmcTowerData::nBSmdCrates;
break;
case 5:
n_crate=StMuEmcTowerData::nETowCrates;
break;
case 6:
n_crate=StMuEmcTowerData::nEPrsCrates;
break;
case 7:
n_crate=StMuEmcTowerData::nESmdCrates;
break;
}
for (Int_t i_crate=1; i_crate<=n_crate; i_crate++) {
muEmc->setCrateStatus(detector->crateStatus(i_crate),i_crate,EmcDet);
}
}
}
return;
}
void StMuEmcUtil::fillEmc(StEmcCollection* emc, const StMuEmcCollection* muEmc)
{
if(!muEmc) return;
if(!emc) return;
//cout <<"FILLING EMC COLLECTION\n";
for(Int_t i=0;i<8;i++)
{
Int_t det=i+1;
StDetectorId id = static_cast<StDetectorId>(i+kBarrelEmcTowerId);
int nMod = 120;
if(i>=4) nMod = 13;
StEmcDetector* detector = new StEmcDetector(id, nMod);
emc->setDetector(detector);
// hits
Int_t nh=0;
if (det==1) nh = 4800;
if (det==5) nh = 720;
if (det==2 || det ==6) nh=muEmc->getNPrsHits(det);
if (det==3 || det==4 || det==7 || det==8) nh=muEmc->getNSmdHits(det);
//cout <<"Number of hits for detector "<<det<<" = "<<nh<<endl;
for(Int_t j=0;j<nh;j++)
{
Bool_t save = kTRUE;
Int_t m,e,s,rid;
Int_t a=0,cal=0;
Float_t energy=0;
if(det==1 || det==5) // towers have only ADC
{
a = muEmc->getTowerADC(j+1,det);
if(det==1) mGeo[det-1]->getBin(j+1,m,e,s);
else {
if( getEndcapBin(det,j+1,m,e,s)) continue ;// on error
}
energy = 0;
cal = 0;
if(a==0) save = kFALSE;
}
if(det==2 || det ==6) //prs
{
const StMuEmcHit* hit=muEmc->getPrsHit(j,det);
if(hit)
{
rid=hit->getId();
if(det==2) mGeo[det-1]->getBin(rid,m,e,s);
else {
if( getEndcapBin(det,rid,m,e,s)) continue ;// on error
}
a=hit->getAdc();
cal=hit->getCalType();
energy=hit->getEnergy();
} else save = kFALSE;
}
if(det==3 || det==4 || det==7 || det==8) //smd
{
const StMuEmcHit* hit=muEmc->getSmdHit(j,det);
if(hit)
{
rid=hit->getId();
if(det<5) mGeo[det-1]->getBin(rid,m,e,s);
else {
if( getEndcapBin(det,rid,m,e,s)) continue ;// on error
}
a=hit->getAdc();
cal=hit->getCalType();
energy=hit->getEnergy();
} else save = kFALSE;
}
if(save)
{
StEmcRawHit* rawHit=new StEmcRawHit(id,(UInt_t)m,(UInt_t)e,(UInt_t)s,(UInt_t)a,energy);
rawHit->setCalibrationType(cal);
//cout <<"det = "<<det<<" Hit number "<<j<<" m = "<<m<<" e = "<<e<<" s = "<<s<<" adc = "<<a<<" en = "<<energy<<"\n";
detector->addHit(rawHit);
}
}
Int_t n_crate=0;
switch (det) {
case 1:
n_crate=StMuEmcTowerData::nBTowCrates;
break;
case 2:
n_crate=StMuEmcTowerData::nBPrsCrates;
break;
case 3:
case 4:
n_crate=StMuEmcTowerData::nBSmdCrates;
break;
case 5:
n_crate=StMuEmcTowerData::nETowCrates;
break;
case 6:
n_crate=StMuEmcTowerData::nEPrsCrates;
break;
case 7:
case 8:
n_crate=StMuEmcTowerData::nESmdCrates;
break;
}
for (Int_t i_crate=1; i_crate<=n_crate; i_crate++) {
detector->setCrateStatus(i_crate,muEmc->getCrateStatus(i_crate,det));
}
}
return;
}
//=================================================
//=================================================
int StMuEmcUtil::getEndcapId(int d,int m, int e, int s,int &rid) const {
rid=1;
/* first tower or first strip is default,
I do not like it, but it is the only safe value,JB
*/
TString text;
if( m<=0 || m >12 || d<5 || d>8 ) {
text="m<=0 || m >12 || d<5 || d>8 ";
goto abort;
}
switch (d) {
case 5:
if( e<=0 || e>12 || s<=0 || s>5 ) {
text="e<=0 || e>12 || s<=0 || s>5 ,towers";
goto abort;
}
rid = 60*(m-1) + 12*(s-1) + e-1;
break;
case 6:
if( e<=0 || e>12 || s<=0 || s>15 ) {
text="e<=0 || e>12 || s<=0 || s>15 , pre/post";
goto abort;
}
rid = 180*(m-1) + 12*(s-1) + e-1;
break;
case 7:
case 8:
if( s!=1 || e<=0 || e>288 ) {
text=" s!=1 || e<=0 || e>288, SMD";
goto abort;
}
rid = 300*(m-1) + e-1;
break;
default:;
}
rid++; // to compensate for counting from 1
if( rid<=0 ) {
text=" rid<=0";
goto abort;
}
return 0; // all went OK
abort:
gMessMgr->Error() <<"StMuEmcUtil::getEndcapId(), FATAL internal error: "
<<text<<"\n d="<<d<<" m="<<m<<" e="<<" s="<<s<<" rid "<<rid
<<"\n ENDCAP data may be wrong, " << endm;
return 1;
}
int StMuEmcUtil::getEndcapBin(int d,int rid0,int &m, int &e, int &s) const
{
m=e=s=1;
/* first tower or first strip is default,
I do not like it, but it is the only safe value,JB
*/
TString text;
int rid=rid0-1;
int x;
if( rid0<=0 || d<5 || d>8 ) {
text="rid0<=0 || d<5 || d>8 ";
goto abort;
}
switch (d) {
case 5:
m=1+ rid/60;
x=rid%60;
s=1 +x/12;
e=1 + x%12;
if ( m>12 || s<1 || s>5 || e>12 ) {
text=" m>12 || s<1 || s>5 || e>12 , tower";
goto abort;
}
break;
case 6:
m=1+ rid/180;
x=rid%180;
s=1 +x/12;
e=1 + x%12;
if ( m>12 || s<1 || s>15 || e>12 ) {
text=" m>12 || s<1 || s>15 || e>12 , pre/post";
goto abort;
}
break;
case 7:
case 8:
m=1+ rid/300;
s=1;
e=1 + rid%300;
if ( m>12 || e>288 || e <1 ) {
text=" m>12 || s<=0 || s>5 || e>12 , smd";
goto abort;
}
break;
default: ;
}
return 0; // all went OK
abort:
gMessMgr->Error() <<"StMuEmcUtil::getEndcapBin(), FATAL internal error: "
<<text<<"\n d="<<d<<" m="<<m<<" e="<<" s="<<s<<" rid0 "<<rid0
<<"\n ENDCAP data may be wrong, "
<<" assert() should be here, JB"<<endm;
return 1;
}
| 25.680965 | 130 | 0.502766 | xiaohaijin |
4a4ad52a38af8707af30b515a584c5f18f47927e | 1,524 | cpp | C++ | Binary_search/Search_in_Row_wise_And_Column_wise_Sorted_Array.cpp | shitesh2607/dsa | 2293eb090c0a0334a9903b83aa881b5201ec26e4 | [
"MIT"
] | 1 | 2021-11-27T06:57:22.000Z | 2021-11-27T06:57:22.000Z | Binary_search/Search_in_Row_wise_And_Column_wise_Sorted_Array.cpp | shitesh2607/dsa | 2293eb090c0a0334a9903b83aa881b5201ec26e4 | [
"MIT"
] | null | null | null | Binary_search/Search_in_Row_wise_And_Column_wise_Sorted_Array.cpp | shitesh2607/dsa | 2293eb090c0a0334a9903b83aa881b5201ec26e4 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
// Actualy both problem are exactly same.
// leetcode: 240. Search a 2D Matrix =: https://leetcode.com/problems/search-a-2d-matrix/
class soluion{
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(!matrix.size()) return false;
int n = matrix.size();
int m = matrix[0].size();
int low = 0;
int high = (n*m) - 1;
while(low<=high){
int mid = (low +(high - low) / 2);
if(matrix[mid/m][mid % m] == target){
return true;
}
if(matrix[mid/m][mid%m] < target){
low = mid +1;
}else{
high = mid -1;
}
}
return false;
}
};
// leetcode: 240. Search a 2D Matrix II =: https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/1598490/240-search-a-2d-matrix-ii-c-solution-time-complexity-omn-binary-search
class solution{
public:
bool searchMatrix(vector<vector<int>> matrix, int target) {
int row = matrix.size();
int col = matrix[0].size();
int i = 0;
int j = col-1;
while((i>=0 && i<=row-1) && (j<=col-1 && j>=0)){
if(matrix[i][j]==target){
return true;
}else if(matrix[i][j]>target){
j--;
}else if(matrix[i][j]<target){
i++;
}
}
return false;
}
}; | 31.75 | 181 | 0.476378 | shitesh2607 |
4a4c6efe25064ed287e3a63e36a936a8b425b865 | 4,130 | cpp | C++ | test/barebone_sounds.cpp | Sgw32/UltiSID | 319edaa63f25c76b6c2675a2cb87d7992724b2d9 | [
"MIT"
] | 9 | 2021-04-30T09:06:13.000Z | 2022-03-31T04:52:07.000Z | test/barebone_sounds.cpp | Sgw32/UltiSID | 319edaa63f25c76b6c2675a2cb87d7992724b2d9 | [
"MIT"
] | null | null | null | test/barebone_sounds.cpp | Sgw32/UltiSID | 319edaa63f25c76b6c2675a2cb87d7992724b2d9 | [
"MIT"
] | 4 | 2021-04-30T16:37:09.000Z | 2022-03-01T23:11:26.000Z | #include "barebone_sounds.h"
extern uint8_t period;
extern uint8_t multiplier;
extern uint8_t DEFAULT_SONG;
extern const uint8_t magic_number;
void error_sound_SD() {
//reset_SID();
OSC_1_HiLo = 0xffff; // just having fun with globals here :-)
MASTER_VOLUME = 0x0f;
ADSR_Attack_1 = 0x09;
ADSR_Decay_1 = 0x07;
ADSR_Sustain_1 = 0x06;
ADSR_Release_1 = 0x0b;
PW_HiLo_voice_1 = 0x400;
//sawtooth_bit_voice_1=1;
triangle_bit_voice_1 = 1;
pulse_bit_voice_1 = 1;
Gate_bit_1 = 1;
delay(480);
OSC_1_HiLo = 0xf000;
Gate_bit_1 = 0;
delay(4000);
}
inline void error_sound_ROOT() {
//reset_SID();
OSC_1_HiLo = 0x1000;
MASTER_VOLUME = 0x0f;
ADSR_Attack_1 = 0x09;
ADSR_Decay_1 = 0x07;
ADSR_Sustain_1 = 0x06;
ADSR_Release_1 = 0x0b;
PW_HiLo_voice_1 = 0x400;
//sawtooth_bit_voice_1=1;
triangle_bit_voice_1 = 1;
pulse_bit_voice_1 = 1;
Gate_bit_1 = 1;
delay(480);
OSC_1_HiLo = 0x0800;
Gate_bit_1 = 0;
delay(1000);
}
inline void error_open_file() {
//reset_SID();
OSC_1_HiLo = 0xc000;
MASTER_VOLUME = 0x0f;
ADSR_Attack_1 = 0x00;
ADSR_Decay_1 = 0x00;
ADSR_Sustain_1 = 0x0f;
ADSR_Release_1 = 0x05;
PW_HiLo_voice_1 = 0x400;
//sawtooth_bit_voice_1=1;
// triangle_bit_voice_1 = 1;
//pulse_bit_voice_1 = 1;
noise_bit_voice_1;
Gate_bit_1 = 1;
delay(480);
OSC_1_HiLo = 0xc800;
Gate_bit_1 = 0;
delay(480);
}
inline void error_open_folder () {
//reset_SID();
OSC_1_HiLo = 0x2000;
MASTER_VOLUME = 0x0f;
ADSR_Attack_1 = 0x09;
ADSR_Decay_1 = 0x07;
ADSR_Sustain_1 = 0x06;
ADSR_Release_1 = 0x0b;
PW_HiLo_voice_1 = 0x400;
//sawtooth_bit_voice_1=1;
triangle_bit_voice_1 = 1;
pulse_bit_voice_1 = 1;
Gate_bit_1 = 1;
delay(480);
OSC_1_HiLo = 0x1000;
Gate_bit_1 = 0;
delay(1000);
}
inline void error_open_sid () {
//reset_SID();
OSC_1_HiLo = 0x4000;
MASTER_VOLUME = 0x0f;
ADSR_Attack_1 = 0x0b;
ADSR_Decay_1 = 0x08;
ADSR_Sustain_1 = 0x06;
ADSR_Release_1 = 0x0b;
PW_HiLo_voice_1 = 0x400;
//sawtooth_bit_voice_1=1;
triangle_bit_voice_1 = 1;
pulse_bit_voice_1 = 1;
Gate_bit_1 = 1;
delay(1500);
OSC_1_HiLo = 0x3f00;
Gate_bit_1 = 0;
Gate_bit_2 = 0;
Gate_bit_3 = 0;
for (int oscup = 0; oscup > 4000; oscup++) {
OSC_1_HiLo = oscup;
delay(1);
}
}
inline void error_PSID_V2_RAM_OVERFLOW () {
//reset_SID();
OSC_1_HiLo = 0x4000; // barebone sound
MASTER_VOLUME = 0x0f;
ADSR_Attack_1 = 0x0b;
ADSR_Decay_1 = 0x08;
ADSR_Sustain_1 = 0x06;
ADSR_Release_1 = 0x0b;
PW_HiLo_voice_1 = 0x400;
//sawtooth_bit_voice_1=1;
triangle_bit_voice_1 = 1;
pulse_bit_voice_1 = 1;
Gate_bit_1 = 1;
delay(1500);
OSC_1_HiLo = 0x3f00;
Gate_bit_1 = 0;
Gate_bit_2 = 0;
Gate_bit_3 = 0;
for (int oscdown = 4000; oscdown > 0; oscdown = oscdown - 2) {
OSC_1_HiLo = oscdown;
delay(1);
}
}
inline void reset_SID() {
OSC_1_HiLo = 0;
PW_HiLo_voice_1 = 0;
noise_bit_voice_1 = 0;
pulse_bit_voice_1 = 0;
sawtooth_bit_voice_1 = 0;
triangle_bit_voice_1 = 0;
test_bit_voice_1 = 0;
ring_bit_voice_1 = 0;
SYNC_bit_voice_1 = 0;
Gate_bit_1 = 0;
ADSR_Attack_1 = 0;
ADSR_Decay_1 = 0;
ADSR_Sustain_1 = 0;
ADSR_Release_1 = 0;
OSC_2_HiLo = 0;
PW_HiLo_voice_2 = 0;
noise_bit_voice_2 = 0;
pulse_bit_voice_2 = 0;
sawtooth_bit_voice_2 = 0;
triangle_bit_voice_2 = 0;
test_bit_voice_2 = 0;
ring_bit_voice_2 = 0;
SYNC_bit_voice_2 = 0;
Gate_bit_2 = 0;
ADSR_Attack_2 = 0;
ADSR_Decay_2 = 0;
ADSR_Sustain_2 = 0;
ADSR_Release_2 = 0;
OSC_3_HiLo = 0;
PW_HiLo_voice_3 = 0;
noise_bit_voice_3 = 0;
pulse_bit_voice_3 = 0;
sawtooth_bit_voice_3 = 0;
triangle_bit_voice_3 = 0;
test_bit_voice_3 = 0;
ring_bit_voice_3 = 0;
SYNC_bit_voice_3 = 0;
Gate_bit_3 = 0;
ADSR_Attack_3 = 0;
ADSR_Decay_3 = 0;
ADSR_Sustain_3 = 0;
ADSR_Release_3 = 0;
FILTER_HiLo = 0;
FILTER_Resonance = 0;
FILTER_Enable_1 = 0;
FILTER_Enable_2 = 0;
FILTER_Enable_3 = 0;
FILTER_Enable_EXT = 0;
FILTER_Enable_switch = 0;
OFF3 = 0;
FILTER_HP = 0;
FILTER_BP = 0;
FILTER_LP = 0;
MASTER_VOLUME = 0;
} | 19.57346 | 64 | 0.678692 | Sgw32 |
4a5155a016ba64c8b36cb336a94595bd16e03096 | 682 | cpp | C++ | nd-coursework/books/cpp/C++ConcurrencyInAction/Chapter02/Listing2_05/Listing2_05.cpp | crdrisko/nd-grad | f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44 | [
"MIT"
] | 1 | 2020-09-26T12:38:55.000Z | 2020-09-26T12:38:55.000Z | nd-coursework/books/cpp/C++ConcurrencyInAction/Chapter02/Listing2_05/Listing2_05.cpp | crdrisko/nd-research | f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44 | [
"MIT"
] | null | null | null | nd-coursework/books/cpp/C++ConcurrencyInAction/Chapter02/Listing2_05/Listing2_05.cpp | crdrisko/nd-research | f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44 | [
"MIT"
] | null | null | null | // Copyright (c) 2019 by Anthony Williams. All rights reserved.
// Licensed under the Boost Software License. See the LICENSE file in the project root for more information.
//
// Name: Listing2_05.cpp
// Author: crdrisko
// Date: 12/26/2020-07:57:22
// Description: Returning a std::thread from a function
#include <thread>
void some_function() {}
void some_other_function(int) {}
std::thread f()
{
void some_function();
return std::thread(some_function);
}
std::thread g()
{
void some_other_function(int);
std::thread t(some_other_function, 42);
return t;
}
int main()
{
std::thread t1 = f();
t1.join();
std::thread t2 = g();
t2.join();
}
| 19.485714 | 108 | 0.668622 | crdrisko |
4a53db9992c70d155a8361999b3aff87e1f88831 | 369 | cpp | C++ | AtCoder/tkppc3/b/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | AtCoder/tkppc3/b/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | 1 | 2021-10-19T08:47:23.000Z | 2022-03-07T05:23:56.000Z | AtCoder/tkppc3/b/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
using namespace std;
int main() {
cpp_int n; cin >> n;
if (n % 6 == 0) cout << "yES" << endl;
else cout << "nO" << endl;
if (n % 11 == 0) cout << "yES" << endl;
else cout << "nO" << endl;
}
| 24.6 | 43 | 0.601626 | H-Tatsuhiro |
4a54dee2701eec0c1dbb49eac4ee1bc5a1bd6ff9 | 1,452 | cpp | C++ | tests/buffer_complex_test.cpp | Tommoa/Snippets | ceaa29b1486615abdbab0e6a7ad152353d3a3ccc | [
"MIT"
] | 1 | 2017-06-07T06:52:16.000Z | 2017-06-07T06:52:16.000Z | tests/buffer_complex_test.cpp | Tommoa/Snippets | ceaa29b1486615abdbab0e6a7ad152353d3a3ccc | [
"MIT"
] | null | null | null | tests/buffer_complex_test.cpp | Tommoa/Snippets | ceaa29b1486615abdbab0e6a7ad152353d3a3ccc | [
"MIT"
] | null | null | null | #include "../buffer/buffer_complex.hpp"
#include <fstream>
#include <iostream>
using namespace Snippets;
int main() {
std::cout << std::endl << "Start of complex buffer test" << std::endl;
std::cout << std::endl;
std::cout << "size of buffer: " << sizeof(buffer_complex) << std::endl
<< std::endl;
Snippets::buffer_complex complex_buffer =
Snippets::buffer_complex(); // Will use malloc, has no special traits.
std::cout << "Assigned new complex buffer with malloc" << std::endl;
int* test_int_1 = (int*)complex_buffer.allocate(sizeof(int));
long* test_long_1 = (long*)complex_buffer.allocate(sizeof(long));
std::cout << "Allocated a new int and a new long on the buffer"
<< std::endl;
*test_int_1 = rand();
*test_long_1 = rand();
std::cout << "\ttest_int_1: " << *test_int_1 << std::endl;
std::cout << "\ttestlong_1: " << *test_long_1 << std::endl;
std::cout << std::endl;
std::ofstream out("buffer_complex_test");
complex_buffer.save(out);
out.close();
std::cout << "Saved buffer to file" << std::endl;
std::ifstream in("buffer_complex_test");
buffer_complex cb = buffer_complex();
cb.load(in);
in.close();
std::cout << "Read buffer to new buffer 'cb'" << std::endl;
std::cout << std::endl;
std::cout << "Attempting to read back the int and the long" << std::endl;
test_int_1 = (int*)cb.offset(0);
test_long_1 = (long*)cb.offset(4);
std::cout << *test_int_1 << std::endl << *test_long_1 << std::endl;
}
| 32.266667 | 74 | 0.661157 | Tommoa |
4a5522ef04b83812ad9dd47013eb11d1ff99f629 | 8,037 | cpp | C++ | Controller/CPU-related/AMD/Griffin/UsageGetterAndControllerBase.cpp | st-gb/CPUinfoAndControl | 5e93d4a195b4692d147bb05cfef534e38d7f8b64 | [
"MIT"
] | null | null | null | Controller/CPU-related/AMD/Griffin/UsageGetterAndControllerBase.cpp | st-gb/CPUinfoAndControl | 5e93d4a195b4692d147bb05cfef534e38d7f8b64 | [
"MIT"
] | null | null | null | Controller/CPU-related/AMD/Griffin/UsageGetterAndControllerBase.cpp | st-gb/CPUinfoAndControl | 5e93d4a195b4692d147bb05cfef534e38d7f8b64 | [
"MIT"
] | 1 | 2021-07-16T21:01:26.000Z | 2021-07-16T21:01:26.000Z | /* Do not remove this header/ copyright information.
*
* Copyright © Trilobyte Software Engineering GmbH, Berlin, Germany 2010-2011.
* You are allowed to modify and use the source code from
* Trilobyte Software Engineering GmbH, Berlin, Germany for free if you are not
* making profit with it or its adaption. Else you may contact Trilobyte SE.
*/
/*
* UsageGetterAndControllerBase.cpp
*
* Created on: 09.04.2010
* Author: Stefan
*/
#include <Controller/AMD/Griffin/UsageGetterAndControllerBase.hpp>
#include <Controller/AMD/Griffin/AMD_family17.h>
#include <Controller/I_CPUaccess.hpp>
#include <preprocessor_helper_macros.h> //BITMASK_FOR_LOWMOST_8BIT
namespace Griffin
{
UsageGetterAndControllerBase::UsageGetterAndControllerBase() {
// TODO Auto-generated constructor stub
}
UsageGetterAndControllerBase::~UsageGetterAndControllerBase() {
// TODO Auto-generated destructor stub
}
//this method is for this purpose:
//AMD BIOS and Kernel Dev Guide:
//"To accurately start counting with the write that enables the counter,
//disable the counter when changing the event and then enable the counter
//with a second MSR write."
void UsageGetterAndControllerBase::AccuratelyStartPerformanceCounting(
DWORD dwAffinityBitMask ,
BYTE byPerformanceCounterNumber ,
WORD wEventSelect ,
bool bInvertCounterMask
)
{
//Disables the performance counter for accurately start performance
//counting.
PrepareForNextPerformanceCounting(
dwAffinityBitMask , byPerformanceCounterNumber) ;
PerformanceEventSelectRegisterWrite(
dwAffinityBitMask ,
byPerformanceCounterNumber ,
//wEventSelect
//0x0C1 ,
wEventSelect ,
// 0x076 ,
//byCounterMask: 00h: The corresponding PERF_CTR[3:0] register is incremented by the number of events
//occurring in a clock cycle. Maximum number of events in one cycle is 3.
0,
bInvertCounterMask ,
//0,
//bEnablePerformanceCounter
1,
//bEnableAPICinterrupt
0,
//bEdgeDetect
0,
//bOSmode
//0
true
,
//bUserMode
true
,
//byEventQualification
0
) ;
}
BYTE UsageGetterAndControllerBase::GetNumberOfCPUCores()
{
BYTE byCoreNumber = 0 ;
DWORD dwEAX;
DWORD dwEBX;
DWORD dwECX;
DWORD dwEDX;
DEBUG_COUTN("UsageGetterAndControllerBase::GetNumberOfCPUCores()");
if( //CpuidEx(
mp_cpuaccess->CpuidEx(
//AMD: "CPUID Fn8000_0008 Address Size And Physical Core Count Information"
0x80000008,
&dwEAX,
&dwEBX,
&dwECX,
&dwEDX,
1
)
)
{
byCoreNumber = ( dwECX & BITMASK_FOR_LOWMOST_7BIT )
//"ECX 7:0 NC: number of physical cores - 1.
//The number of cores in the processor is NC+1 (e.g., if
//NC=0, then there is one core).
//See also section 2.9.2 [Number of Cores and Core Number]."
+ 1 ;
//DEBUG("Number of CPU cores: %u\n", (WORD) byCoreNumber );
DEBUG_COUTN("UsageGetterAndControllerBase::GetNumberOfCPUCores() "
"Number of CPU cores according to CPUID: " << (WORD) byCoreNumber );
}
else
{
DEBUG_COUTN("UsageGetterAndControllerBase::GetNumberOfCPUCores() "
"mp_cpuaccess->CpuidEx failed" );
}
return byCoreNumber ;
}
void UsageGetterAndControllerBase::PerformanceEventSelectRegisterWrite(
DWORD dwAffinityBitMask ,
//Griffin has 4 "Performance Event Select Register" from
// MSR 0xC001_0000_00 to MSRC001_00_03 for
// 4 "Performance Event Counter Registers" from
// MSR 0xC001_0004 to 0xC001_0007
// that store the 48 bit counter value
BYTE byPerformanceEventSelectRegisterNumber ,
WORD wEventSelect ,
BYTE byCounterMask ,
bool bInvertCounterMask ,
bool bEnablePerformanceCounter,
bool bEnableAPICinterrupt,
bool bEdgeDetect,
bool bOSmode,
bool bUserMode,
BYTE byEventQualification
)
{
if( bInvertCounterMask == true )
//When Inv = 1, the corresponding PERF_CTR[3:0] register is incremented by 1, if the
//number of events occurring in a clock cycle is less than CntMask value.
//Less than 1 = 0 -> so if Clocks not halted and 0 times "not halted": ->"halted"
byCounterMask = 1 ;
//see AMD Family 11h Processor BKDG, paragraph
//"MSRC001_00[03:00] Performance Event Select Register (PERF_CTL[3:0])"
//bits:
//31:24 CntMask: counter mask. Read-write. Controls the number of events
//counted per clock cycle.
//00h The corresponding PERF_CTR[3:0] register is incremented by the number of events
//occurring in a clock cycle. Maximum number of events in one cycle is 3.
//01h-03h When Inv = 0, the corresponding PERF_CTR[3:0] register is incremented by 1, if the
//number of events occurring in a clock cycle is greater than or equal to the CntMask value.
//When Inv = 1, the corresponding PERF_CTR[3:0] register is incremented by 1, if the
//number of events occurring in a clock cycle is less than CntMask value.
//04h-FFh Reserved.
//23 | Inv: invert counter mask. Read-write. See CntMask.
DWORD dwLow = 0 |
( byCounterMask << 24 ) |
( bInvertCounterMask << 23 ) |
( bEnablePerformanceCounter << 22 ) |
( bEnableAPICinterrupt << 20 ) |
( bEdgeDetect << 18 ) |
( bOSmode << 17 ) |
( bUserMode << 16 ) |
( byEventQualification << 8 ) |
( wEventSelect & BITMASK_FOR_LOWMOST_8BIT )
;
#ifdef _EMULATE_TURION_X2_ULTRA_ZM82
#else
mp_cpuaccess->WrmsrEx(
PERF_CTL_0 + byPerformanceEventSelectRegisterNumber ,
dwLow ,
wEventSelect >> 8 ,
//1=core 0
//1
dwAffinityBitMask
) ;
#endif //_EMULATE_TURION_X2_ULTRA_ZM82
}
void UsageGetterAndControllerBase::PrepareForNextPerformanceCounting(
DWORD dwAffinityBitMask
, BYTE byPerformanceEventSelectRegisterNumber
)
{
PerformanceEventSelectRegisterWrite(
dwAffinityBitMask ,
//byPerformanceCounterNumber ,
byPerformanceEventSelectRegisterNumber ,
//wEventSelect ,
0x0C1 ,
// 0x076 ,
// 0x076 ,
//byCounterMask: 00h: The corresponding PERF_CTR[3:0] register is incremented by the number of events
//occurring in a clock cycle. Maximum number of events in one cycle is 3.
//0,
//"When Inv = 0, the corresponding PERF_CTR[3:0] register is
//incremented by 1, if the number of events occurring in a clock
//cycle is greater than or equal to the CntMask"
1 ,
//bInvertCounterMask
0,
//bEnablePerformanceCounter
0,
//bEnableAPICinterrupt
0,
//bEdgeDetect
0,
//bOSmode[...]1=Events are only counted when CPL=0.
//(CPL=Current Privilege Level?) http://en.wikipedia.org/wiki/Current_privilege_level
1,
//bUserMode
1,
//byEventQualification
0
) ;
}
//inline
bool UsageGetterAndControllerBase::ReadPerformanceEventCounterRegister(
BYTE byPerformanceEventCounterNumber ,
ULONGLONG & r_ull ,
DWORD_PTR dwAffinityMask // Thread Affinity Mask
)
{
DWORD dwLow , dwHigh ;
bool bRet =
//TODO better use ReadPMC? : AMD Family 11h Processor BKDG :
//"The RDPMC instruction is not serializing, and it can be executed
//out-of-order with respect to other instructions around it.
//Even when bound by serializing instructions, the system environment at
//the time the instruction is executed can cause events to be counted
//before the counter value is loaded into EDX:EAX."
RdmsrEx(
PERFORMANCE_EVENT_COUNTER_0_REGISTER + byPerformanceEventCounterNumber ,
//PERFORMANCE_EVENT_COUNTER_1_REGISTER ,
dwLow,
dwHigh,
//1=core 0
dwAffinityMask
) ;
//RdpmcEx seemed to cause a blue screen (maybe because of wrong param values)
//mp_cpuaccess->RdpmcEx(
// PERFORMANCE_EVENT_COUNTER_0_REGISTER + byPerformanceEventCounterNumber ,
// //PERFORMANCE_EVENT_COUNTER_1_REGISTER ,
// & dwLow,
// & dwHigh,
// //1=core 0
// dwAffinityMask
// ) ;
r_ull = dwHigh ;
r_ull <<= 32 ;
r_ull |= dwLow ;
return bRet ;
}
} //end namespace
| 31.641732 | 105 | 0.696155 | st-gb |
4a5af316c672a9bc47d5d81ee695c6c946eab90f | 13,850 | hpp | C++ | src/thirdparty/stlsoft/STLSoft/include/winstl/diagnostics/threadtimes_stopwatch.hpp | nneesshh/servercore | 8aceb7c9d5b26976469645a708b4ab804864c03f | [
"MIT"
] | null | null | null | src/thirdparty/stlsoft/STLSoft/include/winstl/diagnostics/threadtimes_stopwatch.hpp | nneesshh/servercore | 8aceb7c9d5b26976469645a708b4ab804864c03f | [
"MIT"
] | null | null | null | src/thirdparty/stlsoft/STLSoft/include/winstl/diagnostics/threadtimes_stopwatch.hpp | nneesshh/servercore | 8aceb7c9d5b26976469645a708b4ab804864c03f | [
"MIT"
] | 2 | 2020-11-04T03:07:09.000Z | 2020-11-05T08:14:45.000Z | /* /////////////////////////////////////////////////////////////////////////
* File: winstl/diagnostics/threadtimes_stopwatch.hpp (formerly winstl::threadtimes_counter, winstl/performance/threadtimes_counter.hpp)
*
* Purpose: WinSTL thread-time stopwatch class.
*
* Created: 22nd March 2002
* Updated: 11th January 2017
*
* Home: http://stlsoft.org/
*
* Copyright (c) 2002-2017, Matthew Wilson and Synesis Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name(s) of Matthew Wilson and Synesis Software nor the
* names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ////////////////////////////////////////////////////////////////////// */
/** \file winstl/diagnostics/threadtimes_stopwatch.hpp
*
* \brief [C++ only] Definition of the
* \link winstl::threadtimes_stopwatch threadtimes_stopwatch\endlink class
* (\ref group__library__Diagnostic "Diagnostic" Library).
*/
#ifndef WINSTL_INCL_WINSTL_DIAGNOSTICS_HPP_THREADTIMES_STOPWATCH
#define WINSTL_INCL_WINSTL_DIAGNOSTICS_HPP_THREADTIMES_STOPWATCH
#ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION
# define WINSTL_VER_WINSTL_DIAGNOSTICS_HPP_THREADTIMES_STOPWATCH_MAJOR 5
# define WINSTL_VER_WINSTL_DIAGNOSTICS_HPP_THREADTIMES_STOPWATCH_MINOR 0
# define WINSTL_VER_WINSTL_DIAGNOSTICS_HPP_THREADTIMES_STOPWATCH_REVISION 1
# define WINSTL_VER_WINSTL_DIAGNOSTICS_HPP_THREADTIMES_STOPWATCH_EDIT 56
#endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */
/* /////////////////////////////////////////////////////////////////////////
* includes
*/
#ifndef WINSTL_INCL_WINSTL_H_WINSTL
# include <winstl/winstl.h>
#endif /* !WINSTL_INCL_WINSTL_H_WINSTL */
#ifdef STLSOFT_TRACE_INCLUDE
# pragma message(__FILE__)
#endif /* STLSOFT_TRACE_INCLUDE */
/* /////////////////////////////////////////////////////////////////////////
* namespace
*/
#ifndef WINSTL_NO_NAMESPACE
# if defined(STLSOFT_NO_NAMESPACE) || \
defined(STLSOFT_DOCUMENTATION_SKIP_SECTION)
/* There is no stlsoft namespace, so must define ::winstl */
namespace winstl
{
# else
/* Define stlsoft::winstl_project */
namespace stlsoft
{
namespace winstl_project
{
# endif /* STLSOFT_NO_NAMESPACE */
#endif /* !WINSTL_NO_NAMESPACE */
/* /////////////////////////////////////////////////////////////////////////
* classes
*/
// class winstl::threadtimes_stopwatch
/** A stopwatch that provides thread-specific performance timings
*
* \ingroup group__library__Diagnostic
*
* This class uses the operating system's performance monitoring facilities to provide timing
* information pertaining to the calling thread only, irrespective of the activities of other
* threads on the system. This class does not provide meaningful timing information on operating
* systems that do not provide thread-specific monitoring.
*/
class threadtimes_stopwatch
{
public:
/// This type
typedef threadtimes_stopwatch class_type;
private:
typedef ws_sint64_t epoch_type;
public:
/// The interval type
///
/// The type of the interval measurement, a 64-bit signed integer
typedef ws_sint64_t interval_type;
// Construction
public:
/// Constructor
///
/// Creates an instance of the class, and caches the thread token so that measurements will
/// be taken with respect to the thread in which the class was created.
threadtimes_stopwatch();
// Operations
public:
/// Starts measurement
///
/// Begins the measurement period
void start();
/// Ends measurement
///
/// Ends the measurement period
void stop();
// Attributes
public:
// Kernel
/// The elapsed count in the measurement period for kernel mode activity
///
/// This represents the extent, in machine-specific increments, of the measurement period for kernel mode activity
interval_type get_kernel_period_count() const;
/// The number of whole seconds in the measurement period for kernel mode activity
///
/// This represents the extent, in whole seconds, of the measurement period for kernel mode activity
interval_type get_kernel_seconds() const;
/// The number of whole milliseconds in the measurement period for kernel mode activity
///
/// This represents the extent, in whole milliseconds, of the measurement period for kernel mode activity
interval_type get_kernel_milliseconds() const;
/// The number of whole microseconds in the measurement period for kernel mode activity
///
/// This represents the extent, in whole microseconds, of the measurement period for kernel mode activity
interval_type get_kernel_microseconds() const;
/// The number of whole nanoseconds in the measurement period for kernel mode activity
///
/// This represents the extent, in whole nanoseconds, of the measurement period for kernel mode activity
interval_type get_kernel_nanoseconds() const;
// User
/// The elapsed count in the measurement period for user mode activity
///
/// This represents the extent, in machine-specific increments, of the measurement period for user mode activity
interval_type get_user_period_count() const;
/// The number of whole seconds in the measurement period for user mode activity
///
/// This represents the extent, in whole seconds, of the measurement period for user mode activity
interval_type get_user_seconds() const;
/// The number of whole milliseconds in the measurement period for user mode activity
///
/// This represents the extent, in whole milliseconds, of the measurement period for user mode activity
interval_type get_user_milliseconds() const;
/// The number of whole microseconds in the measurement period for user mode activity
///
/// This represents the extent, in whole microseconds, of the measurement period for user mode activity
interval_type get_user_microseconds() const;
/// The number of whole nanoseconds in the measurement period for user mode activity
///
/// This represents the extent, in whole nanoseconds, of the measurement period for user mode activity
interval_type get_user_nanoseconds() const;
// Total
/// The elapsed count in the measurement period
///
/// This represents the extent, in machine-specific increments, of the measurement period
interval_type get_period_count() const;
/// The number of whole seconds in the measurement period
///
/// This represents the extent, in whole seconds, of the measurement period
interval_type get_seconds() const;
/// The number of whole milliseconds in the measurement period
///
/// This represents the extent, in whole milliseconds, of the measurement period
interval_type get_milliseconds() const;
/// The number of whole microseconds in the measurement period
///
/// This represents the extent, in whole microseconds, of the measurement period
interval_type get_microseconds() const;
/// The number of whole nanoseconds in the measurement period
///
/// This represents the extent, in whole nanoseconds, of the measurement period
interval_type get_nanoseconds() const;
private: // Implementation
static epoch_type convert_(FILETIME const& ft);
// Members
private:
epoch_type m_kernelStart;
epoch_type m_kernelEnd;
epoch_type m_userStart;
epoch_type m_userEnd;
HANDLE m_thread;
};
////////////////////////////////////////////////////////////////////////////
// Implementation
#ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION
inline
/* static */
threadtimes_stopwatch::epoch_type
threadtimes_stopwatch::convert_(FILETIME const& ft)
{
epoch_type r = ft.dwHighDateTime;
r <<= 32;
r += ft.dwLowDateTime;
return r;
}
inline
threadtimes_stopwatch::threadtimes_stopwatch()
: m_thread(::GetCurrentThread())
{
// Note that the constructor does nothing, for performance reasons. Calling
// any of the Attribute methods before having gone through a start()-stop()
// cycle will yield undefined results.
}
// Operations
inline
void
threadtimes_stopwatch::start()
{
FILETIME creationTime;
FILETIME exitTime;
FILETIME kernelTime;
FILETIME userTime;
if(!::GetThreadTimes(m_thread, &creationTime, &exitTime, &kernelTime, &userTime))
{
m_kernelStart = 0;
m_userStart = 0;
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
; // TODO: throw
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
else
{
m_kernelStart = convert_(kernelTime);
m_userStart = convert_(userTime);
}
}
inline
void
threadtimes_stopwatch::stop()
{
FILETIME creationTime;
FILETIME exitTime;
FILETIME kernelTime;
FILETIME userTime;
if(!::GetThreadTimes(m_thread, &creationTime, &exitTime, &kernelTime, &userTime))
{
m_kernelEnd = 0;
m_userEnd = 0;
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
; // TODO: throw
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
else
{
m_kernelEnd = convert_(kernelTime);
m_userEnd = convert_(userTime);
}
}
// Attributes
// Kernel
inline
threadtimes_stopwatch::interval_type
threadtimes_stopwatch::get_kernel_period_count() const
{
return static_cast<interval_type>(m_kernelEnd - m_kernelStart);
}
inline
threadtimes_stopwatch::interval_type
threadtimes_stopwatch::get_kernel_seconds() const
{
return get_kernel_period_count() / interval_type(10000000);
}
inline
threadtimes_stopwatch::interval_type
threadtimes_stopwatch::get_kernel_milliseconds() const
{
return get_kernel_period_count() / interval_type(10000);
}
inline
threadtimes_stopwatch::interval_type
threadtimes_stopwatch::get_kernel_microseconds() const
{
return get_kernel_period_count() / interval_type(10);
}
inline
threadtimes_stopwatch::interval_type
threadtimes_stopwatch::get_kernel_nanoseconds() const
{
return get_kernel_period_count() * interval_type(100);
}
// User
inline
threadtimes_stopwatch::interval_type
threadtimes_stopwatch::get_user_period_count() const
{
return static_cast<interval_type>(m_userEnd - m_userStart);
}
inline
threadtimes_stopwatch::interval_type
threadtimes_stopwatch::get_user_seconds() const
{
return get_user_period_count() / interval_type(10000000);
}
inline
threadtimes_stopwatch::interval_type
threadtimes_stopwatch::get_user_milliseconds() const
{
return get_user_period_count() / interval_type(10000);
}
inline
threadtimes_stopwatch::interval_type
threadtimes_stopwatch::get_user_microseconds() const
{
return get_user_period_count() / interval_type(10);
}
inline
threadtimes_stopwatch::interval_type
threadtimes_stopwatch::get_user_nanoseconds() const
{
return get_user_period_count() * interval_type(100);
}
// Total
inline
threadtimes_stopwatch::interval_type
threadtimes_stopwatch::get_period_count() const
{
return get_kernel_period_count() + get_user_period_count();
}
inline
threadtimes_stopwatch::interval_type
threadtimes_stopwatch::get_seconds() const
{
return get_period_count() / interval_type(10000000);
}
inline
threadtimes_stopwatch::interval_type
threadtimes_stopwatch::get_milliseconds() const
{
return get_period_count() / interval_type(10000);
}
inline
threadtimes_stopwatch::interval_type
threadtimes_stopwatch::get_microseconds() const
{
return get_period_count() / interval_type(10);
}
inline
threadtimes_stopwatch::interval_type
threadtimes_stopwatch::get_nanoseconds() const
{
return get_period_count() * interval_type(100);
}
#endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */
/* ////////////////////////////////////////////////////////////////////// */
#ifndef WINSTL_NO_NAMESPACE
# if defined(STLSOFT_NO_NAMESPACE) || \
defined(STLSOFT_DOCUMENTATION_SKIP_SECTION)
} /* namespace winstl */
# else
} /* namespace winstl_project */
} /* namespace stlsoft */
# endif /* STLSOFT_NO_NAMESPACE */
#endif /* !WINSTL_NO_NAMESPACE */
/* /////////////////////////////////////////////////////////////////////////
* inclusion
*/
#ifdef STLSOFT_CF_PRAGMA_ONCE_SUPPORT
# pragma once
#endif /* STLSOFT_CF_PRAGMA_ONCE_SUPPORT */
/* ////////////////////////////////////////////////////////////////////// */
#endif /* !WINSTL_INCL_WINSTL_DIAGNOSTICS_HPP_THREADTIMES_STOPWATCH */
/* ///////////////////////////// end of file //////////////////////////// */
| 31.83908 | 143 | 0.703394 | nneesshh |
4a5cca250efd7d3ea01d9a6edd88e75b2fc21058 | 13,636 | cpp | C++ | master/core/third/cxxtools/src/convert.cpp | importlib/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 4 | 2017-12-04T08:22:48.000Z | 2019-10-26T21:44:59.000Z | master/core/third/cxxtools/src/convert.cpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | null | null | null | master/core/third/cxxtools/src/convert.cpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 4 | 2017-12-19T11:13:56.000Z | 2018-02-23T08:44:03.000Z | /*
* Copyright (C) 2011 Tommi Maekitalo
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <cxxtools/convert.h>
#include <iomanip>
#include <limits>
#include <cctype>
namespace cxxtools
{
template <typename IterT>
void _skipws(IterT& it, IterT end)
{
while (it != end && isspace(*it))
++it;
}
template<typename T>
class nullterm_array_iterator : public std::iterator<std::input_iterator_tag, T>
{
public:
nullterm_array_iterator()
: _ptr(0)
{ }
explicit nullterm_array_iterator(const T* ptr)
: _ptr(ptr)
{
if(*_ptr == '\0')
_ptr = 0;
}
nullterm_array_iterator<T>& operator=(const nullterm_array_iterator<T>& it)
{
_ptr = it._ptr;
return *this;
}
bool operator==(const nullterm_array_iterator<T>& it) const
{
return _ptr == it._ptr;
}
bool operator!=(const nullterm_array_iterator<T>& it) const
{
return _ptr != it._ptr;
}
const T& operator*() const
{
return *_ptr;
}
nullterm_array_iterator<T>& operator++()
{
if(*++_ptr == '\0')
_ptr = 0;
return *this;
}
nullterm_array_iterator<T> operator++(int)
{
if(*++_ptr == '\0')
_ptr = 0;
return *this;
}
private:
const T* _ptr;
};
template <typename T>
void convertInt(T& n, const String& str, const char* typeto)
{
bool ok = false;
String::const_iterator r = getInt( str.begin(), str.end(), ok, n, DecimalFormat<Char>() );
if (ok)
_skipws(r, str.end());
if( r != str.end() || ! ok )
ConversionError::doThrow(typeto, "String", str.narrow().c_str());
}
template <typename T>
void convertInt(T& n, const std::string& str, const char* typeto)
{
bool ok = false;
std::string::const_iterator r = getInt( str.begin(), str.end(), ok, n );
if (ok)
_skipws(r, str.end());
if( r != str.end() || ! ok )
ConversionError::doThrow(typeto, "string", str.c_str());
}
template <typename T>
void convertInt(T& n, const char* str, const char* typeto)
{
bool ok = false;
nullterm_array_iterator<char> it(str);
nullterm_array_iterator<char> end;
it = getInt( it, end, ok, n );
if (ok)
_skipws(it, end);
if( it != end || ! ok )
ConversionError::doThrow(typeto, "char*");
}
template <typename T>
void convertFloat(T& n, const String& str, const char* typeto)
{
bool ok = false;
String::const_iterator r = getFloat(str.begin(), str.end(), ok, n, FloatFormat<Char>() );
if (ok)
_skipws(r, str.end());
if(r != str.end() || ! ok)
ConversionError::doThrow(typeto, "String", str.narrow().c_str());
}
template <typename T>
void convertFloat(T& n, const std::string& str, const char* typeto)
{
bool ok = false;
std::string::const_iterator r = getFloat(str.begin(), str.end(), ok, n);
if (ok)
_skipws(r, str.end());
if(r != str.end() || ! ok)
ConversionError::doThrow(typeto, "string", str.c_str());
}
template <typename T>
void convertFloat(T& n, const char* str, const char* typeto)
{
bool ok = false;
nullterm_array_iterator<char> it(str);
nullterm_array_iterator<char> end;
it = getFloat( it, end, ok, n );
if (ok)
_skipws(it, end);
if( it != end || ! ok )
ConversionError::doThrow(typeto, "char*", str);
}
//
// Conversions to cxxtools::String
//
void convert(String& s, const std::string& value)
{
s = String::widen(value);
}
void convert(String& str, bool value)
{
static const wchar_t* trueValue = L"true";
static const wchar_t* falseValue = L"false";
str = value ? trueValue : falseValue;
}
void convert(String& str, char value)
{
str = String(1, Char(value));
}
void convert(String& str, wchar_t value)
{
str = String(1, Char(value));
}
void convert(String& str, Char value)
{
str = String(1, value);
}
void convert(String& str, unsigned char value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(String& str, signed char value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(String& str, short value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(String& str, unsigned short value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(String& str, int value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(String& str, unsigned int value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(String& str, long value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(String& str, unsigned long value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(String& str, float value)
{
str.clear();
putFloat(std::back_inserter(str), value);
}
void convert(String& str, double value)
{
str.clear();
putFloat(std::back_inserter(str), value);
}
void convert(String& str, long double value)
{
str.clear();
putFloat(std::back_inserter(str), value);
}
//
// Conversions from cxxtools::String
//
void convert(bool& n, const String& str)
{
if (str == L"true" || str == L"1")
n = true;
else if (str == L"false" || str == L"0")
n = false;
else
ConversionError::doThrow("bool", "String", str.narrow().c_str());
}
void convert(char& c, const String& str)
{
if ( str.empty() )
ConversionError::doThrow("char", "String");
c = str[0].narrow();
}
void convert(wchar_t& c, const String& str)
{
if ( str.empty() )
ConversionError::doThrow("wchar_t", "String");
c = str[0].toWchar();
}
void convert(Char& c, const String& str)
{
if ( str.empty() )
ConversionError::doThrow("char", "Char");
c = str[0];
}
void convert(unsigned char& n, const String& str)
{
convertInt(n, str, "unsigned char");
}
void convert(signed char& n, const String& str)
{
convertInt(n, str, "signed char");
}
void convert(short& n, const String& str)
{
convertInt(n, str, "short");
}
void convert(unsigned short& n, const String& str)
{
convertInt(n, str, "unsigned short");
}
void convert(int& n, const String& str)
{
convertInt(n, str, "int");
}
void convert(unsigned int& n, const String& str)
{
convertInt(n, str, "unsigned int");
}
void convert(long& n, const String& str)
{
convertInt(n, str, "long");
}
void convert(unsigned long& n, const String& str)
{
convertInt(n, str, "unsigned long");
}
#ifdef HAVE_LONG_LONG
void convert(long long& n, const String& str)
{
convertInt(n, str, "long long");
}
#endif
#ifdef HAVE_UNSIGNED_LONG_LONG
void convert(unsigned long long& n, const String& str)
{
convertInt(n, str, "unsigned long long");
}
#endif
void convert(float& n, const String& str)
{
convertFloat(n, str, "float");
}
void convert(double& n, const String& str)
{
convertFloat(n, str, "double");
}
void convert(long double& n, const String& str)
{
convertFloat(n, str, "long double");
}
//
// Conversions to std::string
//
void convert(std::string& s, const String& str)
{
s = str.narrow();
}
void convert(std::string& str, bool value)
{
static const char* trueValue = "true";
static const char* falseValue = "false";
str = value ? trueValue : falseValue;
}
void convert(std::string& str, char value)
{
str.clear();
str += value;
}
void convert(std::string& str, signed char value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(std::string& str, unsigned char value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(std::string& str, short value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(std::string& str, unsigned short value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(std::string& str, int value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(std::string& str, unsigned int value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(std::string& str, long value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(std::string& str, unsigned long value)
{
str.clear();
putInt(std::back_inserter(str), value);
}
void convert(std::string& str, float value)
{
str.clear();
putFloat(std::back_inserter(str), value);
}
void convert(std::string& str, double value)
{
str.clear();
putFloat(std::back_inserter(str), value);
}
void convert(std::string& str, long double value)
{
str.clear();
putFloat(std::back_inserter(str), value);
}
//
// Conversions from std::string
//
void convert(bool& n, const std::string& str)
{
if (str == "true" || str == "1")
n = true;
else if (str == "false" || str == "0")
n = false;
else
ConversionError::doThrow("bool", "string", str.c_str());
}
void convert(char& c, const std::string& str)
{
if ( str.empty() )
ConversionError::doThrow("char", "string");
int n = str[0];
c = n;
}
void convert(signed char& n, const std::string& str)
{
convertInt(n, str, "signed char");
}
void convert(unsigned char& n, const std::string& str)
{
convertInt(n, str, "unsigned char");
}
void convert(short& n, const std::string& str)
{
convertInt(n, str, "short");
}
void convert(unsigned short& n, const std::string& str)
{
convertInt(n, str, "unsigned short");
}
void convert(int& n, const std::string& str)
{
convertInt(n, str, "int");
}
void convert(unsigned int& n, const std::string& str)
{
convertInt(n, str, "unsigned int");
}
void convert(long& n, const std::string& str)
{
convertInt(n, str, "long");
}
void convert(unsigned long& n, const std::string& str)
{
convertInt(n, str, "unsigned long");
}
#ifdef HAVE_LONG_LONG
void convert(long long& n, const std::string& str)
{
convertInt(n, str, "long long");
}
#endif
#ifdef HAVE_UNSIGNED_LONG_LONG
void convert(unsigned long long& n, const std::string& str)
{
convertInt(n, str, "unsigned long long");
}
#endif
void convert(float& n, const std::string& str)
{
convertFloat(n, str, "float");
}
void convert(double& n, const std::string& str)
{
convertFloat(n, str, "double");
}
void convert(long double& n, const std::string& str)
{
convertFloat(n, str, "long double");
}
//
// Conversions from const char*
//
void convert(bool& n, const char* str)
{
if (std::strcmp(str, "true") == 0 || std::strcmp(str, "1") == 0)
n = true;
else if (std::strcmp(str, "false") || std::strcmp(str, "0"))
n = false;
else
ConversionError::doThrow("bool", "char*", str);
}
void convert(char& c, const char* str)
{
if ( *str == '\0' )
ConversionError::doThrow("char", "char*");
c = str[0];
}
void convert(signed char& n, const char* str)
{
convertInt(n, str, "signed char");
}
void convert(unsigned char& n, const char* str)
{
convertInt(n, str, "unsigned char");
}
void convert(short& n, const char* str)
{
convertInt(n, str, "short");
}
void convert(unsigned short& n, const char* str)
{
convertInt(n, str, "unsigned short");
}
void convert(int& n, const char* str)
{
convertInt(n, str, "int");
}
void convert(unsigned int& n, const char* str)
{
convertInt(n, str, "unsigned int");
}
void convert(long& n, const char* str)
{
convertInt(n, str, "long");
}
void convert(unsigned long& n, const char* str)
{
convertInt(n, str, "unsigned long");
}
#ifdef HAVE_LONG_LONG
void convert(long long& n, const char* str)
{
convertInt(n, str, "long long");
}
#endif
#ifdef HAVE_UNSIGNED_LONG_LONG
void convert(unsigned long long& n, const char* str)
{
convertInt(n, str, "unsigned long long");
}
#endif
void convert(float& n, const char* str)
{
convertFloat(n, str, "float");
}
void convert(double& n, const char* str)
{
convertFloat(n, str, "double");
}
void convert(long double& n, const char* str)
{
convertFloat(n, str, "long double");
}
}
| 18.730769 | 94 | 0.62115 | importlib |
4a5d29f3944111cf1b6b85339919d58fcb13a027 | 11,724 | cpp | C++ | ble-cpp/src/mc/MetropolisSampler.cpp | harsh-agarwal/blelocpp | eaba46c6239981c7b8e69bef2ab33bb08ecb15b4 | [
"MIT"
] | 8 | 2016-06-13T20:47:18.000Z | 2021-12-22T17:29:32.000Z | ble-cpp/src/mc/MetropolisSampler.cpp | harsh-agarwal/blelocpp | eaba46c6239981c7b8e69bef2ab33bb08ecb15b4 | [
"MIT"
] | 11 | 2016-03-14T07:00:04.000Z | 2019-05-07T18:20:15.000Z | ble-cpp/src/mc/MetropolisSampler.cpp | harsh-agarwal/blelocpp | eaba46c6239981c7b8e69bef2ab33bb08ecb15b4 | [
"MIT"
] | 11 | 2016-02-03T07:41:00.000Z | 2019-09-11T10:03:48.000Z | /*******************************************************************************
* Copyright (c) 2014-2016 IBM Corporation and others
*
* 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 "MetropolisSampler.hpp"
namespace loc{
// Implementation
template <class Tstate, class Tinput>
void MetropolisSampler<Tstate, Tinput>::input(const Tinput& input){
mInput = input;
initialize();
}
template <class Tstate, class Tinput>
void MetropolisSampler<Tstate, Tinput>::observationModel(std::shared_ptr<ObservationModel<Tstate, Tinput>> obsModel){
mObsModel = obsModel;
}
template <class Tstate, class Tinput>
void MetropolisSampler<Tstate, Tinput>::statusInitializer(std::shared_ptr<StatusInitializerImpl> statusInitializer){
mStatusInitializer = statusInitializer;
}
template <class Tstate, class Tinput>
State MetropolisSampler<Tstate, Tinput>::findInitialMaxLikelihoodState(){
Locations locations;
if (mParams.initType == INIT_WITH_SAMPLE_LOCATIONS) {
locations = mStatusInitializer->extractLocationsCloseToBeacons(mInput, mParams.radius2D);
} else if (mParams.initType == INIT_WITH_BEACON_LOCATIONS){
locations = mStatusInitializer->generateLocationsCloseToBeaconsWithPerturbation(mInput, mParams.radius2D);
}
if(locations.size()==0){
BOOST_THROW_EXCEPTION(LocException("No location close to beacons was found in sampler."));
}
locations = Location::filterLocationsOnFlatFloor(locations); // Remove locations with an unusual z value.
locations = mStatusInitializer->extractMovableLocations(locations);
if(locations.size()==0){
std::cerr << "All locations were removed at filtering step in sampler. Not filtered locations are used." << std::endl;
if (mParams.initType == INIT_WITH_SAMPLE_LOCATIONS) {
locations = mStatusInitializer->extractLocationsCloseToBeacons(mInput, mParams.radius2D);
} else if (mParams.initType == INIT_WITH_BEACON_LOCATIONS){
locations = mStatusInitializer->generateLocationsCloseToBeaconsWithPerturbation(mInput, mParams.radius2D);
}
}
auto states = mStatusInitializer->initializeStatesFromLocations(locations);
std::vector<double> logLLs = mObsModel->computeLogLikelihood(states, mInput);
auto iterMax = std::max_element(logLLs.begin(), logLLs.end());
size_t index = std::distance(logLLs.begin(), iterMax);
Tstate locMaxLL = states.at(index);
if(isVerbose){
std::cout << "findInitialMaxLikelihoodState: states.size=" << states.size() << "max state=" << locMaxLL << std::endl;
}
return locMaxLL;
}
template <class Tstate, class Tinput>
void MetropolisSampler<Tstate, Tinput>::initialize(){
clear();
currentState = findInitialMaxLikelihoodState();
std::vector<Tstate> ss = {currentState};
currentLogLL = mObsModel->computeLogLikelihood(ss, mInput).at(0);
}
template <class Tstate, class Tinput>
void MetropolisSampler<Tstate, Tinput>::prepare(){
startBurnIn();
}
template <class Tstate, class Tinput>
void MetropolisSampler<Tstate, Tinput>::startBurnIn(int burnIn){
for(int i=0; i<burnIn; i++){
sample();
}
isBurnInFinished = true;
}
template <class Tstate, class Tinput>
void MetropolisSampler<Tstate, Tinput>::startBurnIn(){
startBurnIn(mParams.burnIn);
}
template <class Tstate, class Tinput>
std::vector<Tstate> MetropolisSampler<Tstate, Tinput>::getAllStates() const{
return allStates;
}
template <class Tstate, class Tinput>
std::vector<double> MetropolisSampler<Tstate, Tinput>::getAllLogLLs() const{
return allLogLLs;
}
template <class Tstate, class Tinput>
bool MetropolisSampler<Tstate, Tinput>::sample(){
return sample(true, true);
}
// This function returns the result whether a proposed sample was accepted or not.
template <class Tstate, class Tinput>
bool MetropolisSampler<Tstate, Tinput>::sample(bool transitLoc, bool transitRssiBias){
Tstate stateNew = transitState(currentState, transitLoc, transitRssiBias);
std::vector<Tstate> ss = {stateNew};
double logLLNew = mObsModel->computeLogLikelihood(ss, mInput).at(0);
double r = std::exp(logLLNew-currentLogLL); // p(xnew)/p(x) = exp(log(p(xnew))-log(p(xpre)))
bool isAccepted = false;
if(randGen.nextDouble() < r){
currentState = stateNew;
currentLogLL = logLLNew;
isAccepted = true;
}
// Save current state
allStates.push_back(Tstate(currentState));
allLogLLs.push_back(currentLogLL);
return isAccepted;
}
template <class Tstate, class Tinput>
std::vector<Tstate> MetropolisSampler<Tstate, Tinput>::sampling(int n){
return sampling(n, mParams.withOrdering);
/*
std::vector<Tstate> sampledStates;
int count = 0;
int countAccepted = 0;
for(int i=1; ;i++){
bool isAccepted = sample();
count++;
if(isAccepted){
countAccepted++;
}
if(i%mParams.interval==0){
sampledStates.push_back(Tstate(currentState));
}
if(sampledStates.size()>=n){
break;
}
}
std::cout << "M-H acceptance rate = " << (double)countAccepted / (double) count << " (" << countAccepted << "/" << count << ")" << std::endl;
return sampledStates;
*/
}
template <class Tstate, class Tinput>
std::vector<Tstate> MetropolisSampler<Tstate, Tinput>::sampling(int n, bool withOrderging){
if(! isBurnInFinished){
this->startBurnIn();
}
std::vector<Tstate> sampledStates;
int count = 0;
int countAccepted = 0;
for(int i=1; ;i++){
if(n==0){
break;
}
bool isAccepted = sample();
count++;
if(isAccepted){
countAccepted++;
}
if(i%mParams.interval==0){
sampledStates.push_back(Tstate(currentState));
}
if(sampledStates.size()>=n){
break;
}
}
if(isVerbose){
std::cout << "M-H acceptance rate = " << (double)countAccepted / (double) count << " (" << countAccepted << "/" << count << ")" << std::endl;
}
if(! withOrderging){
return sampledStates;
}else{
sampledStates = std::vector<State>();
std::vector<int> indices(allStates.size());
// create indices = {1,2,3,...,n};
std::iota(indices.begin(), indices.end(), 0);
std::sort(indices.begin(), indices.end(),[&](int a, int b){
return allLogLLs.at(a) < allLogLLs.at(b);
});
double logLLMemo = std::numeric_limits<double>::lowest();
for(int i=0; ;i++){
//std::cout << "indices.size() = " << indices.size() << std::endl;
int index = indices.at(indices.size()-1-i);
double logLL = allLogLLs.at(index);
// if(logLLMemo!=logLL)
{
logLLMemo = logLL;
sampledStates.push_back(allStates.at(index));
//std::cout << "state=" << allStates.at(index) << ", logLL=" << logLLMemo << std::endl;
}
if(sampledStates.size()>=n){
break;
}
}
}
return sampledStates;
}
template <class Tstate, class Tinput>
std::vector<Tstate> MetropolisSampler<Tstate, Tinput>::sampling(int n, const Location &location){
Locations locs = {location};
auto states = mStatusInitializer->initializeStatesFromLocations(locs);
std::vector<Tstate> ss = {states};
currentState = ss.at(0);
currentLogLL = mObsModel->computeLogLikelihood(ss, mInput).at(0);
std::vector<Tstate> sampledStates;
int count = 0;
int countAccepted = 0;
for(int i=1; ;i++){
if(n==0){
break;
}
bool isAccepted = sample(false, true);
count++;
if(isAccepted){
countAccepted++;
}
if(i%mParams.interval==0){
sampledStates.push_back(Tstate(currentState));
}
if(sampledStates.size()>=n){
break;
}
}
std::cout << "M-H acceptance rate = " << (double)countAccepted / (double) count << " (" << countAccepted << "/" << count << ")" << std::endl;
return sampledStates;
}
template <class Tstate, class Tinput>
State MetropolisSampler<Tstate, Tinput>::transitState(Tstate state) {
return transitState(state, true, true);
}
template <class Tstate, class Tinput>
State MetropolisSampler<Tstate, Tinput>::transitState(Tstate state, bool transitLoc, bool transitRssiBias){
// update variables that affect mainly likelihood
Tstate stateNew(state);
if (transitLoc) {
auto locNew = mStatusInitializer->perturbLocation(stateNew);
stateNew.x(locNew.x());
stateNew.y(locNew.y());
}
if (transitRssiBias) {
stateNew = mStatusInitializer->perturbRssiBias(stateNew);
}
return stateNew;
}
template <class Tstate, class Tinput>
void MetropolisSampler<Tstate, Tinput>::clear(){
allStates.clear();
allLogLLs.clear();
}
template <class Tstate, class Tinput>
void MetropolisSampler<Tstate, Tinput>::print() const{
double averageLogLL = std::accumulate(allLogLLs.begin(), allLogLLs.end(), 0.0)/(allLogLLs.size());
std::cout << "allStates.size()=" << allStates.size()
<< ",allLogLLs.size()=" << allLogLLs.size()
<< ",averageLogLL=" << averageLogLL << std::endl;
}
// explicit instantiation
template class MetropolisSampler<State, Beacons>;
}
| 38.313725 | 153 | 0.58376 | harsh-agarwal |
4a5e7f3d0eb904ca51a0068b09804230a450577c | 9,643 | hpp | C++ | src/sutil/CRegisteredCallbacks.hpp | samirmenon/sUtil | 6b75697cddf18bc309ceea571f9f687045883183 | [
"Unlicense",
"MIT"
] | 3 | 2015-04-26T03:51:13.000Z | 2019-04-09T03:33:17.000Z | src/sutil/CRegisteredCallbacks.hpp | samirmenon/sUtil | 6b75697cddf18bc309ceea571f9f687045883183 | [
"Unlicense",
"MIT"
] | 2 | 2015-03-31T22:36:33.000Z | 2016-01-25T23:31:52.000Z | src/sutil/CRegisteredCallbacks.hpp | samirmenon/sUtil | 6b75697cddf18bc309ceea571f9f687045883183 | [
"Unlicense",
"MIT"
] | null | null | null | /* This file is part of sUtil, a random collection of utilities.
See the Readme.txt file in the root folder for licensing information.
*/
/* \file CRegisteredCallbacks.hpp
*
* Created on: Sep 13, 2011
*
* Copyright (C) 2011, Samir Menon <smenon@stanford.edu>
*/
#ifndef CREGISTEREDCALLBACKS_HPP_
#define CREGISTEREDCALLBACKS_HPP_
#include <sutil/CSingleton.hpp>
#include <sutil/CMappedList.hpp>
#include <vector>
#ifdef DEBUG
#include <iostream>
#endif
namespace sutil
{
// These are forward declarations. Read the class comments for details.
template <typename Idx> class CCallbackSuperBase;
template <typename Idx, typename ArgumentTuple, typename Data> class CCallbackBase;
template <typename Idx> class CRegisteredCallbacks;
/** Use this namespace to create and call callback
* functions
*
* Example usage:
*
* // 1. Defining a callback function class
*
* // NOTE: You can also use typename Data to
* // customize different objects of this class and then
* // register them.
* class CCallbackFunc : public
* sutil::CCallbackBase<std::string, std::vector<std::string> >
* {
* typedef sutil::CCallbackBase<std::string, std::vector<std::string> > base;
* public:
* virtual void call(std::vector<std::string>& args)
* {//Do something with the argument
* std::vector<std::string>::iterator it,ite;
* for(it = args.begin(), ite = args.end(); it!=ite; ++it)
* { std::cout<<"\nPassed arg : "<<*it; }
*
* //And/or copy the result into it
* std::string x;
* std::cin>>x;
* args.push_back(x);
* }
*
* virtual base* createObject()
* { return dynamic_cast<base*>(new CCallbackFunc()); }
* };
*
* //2. Register the function
* std::string name("BoboFunc");
* std::vector<std::string> args;
*
* flag = sutil::callbacks::add<CCallbackFunc,
* std::string, std::vector<std::string> >(name);
*
* //3. Call the function
* sutil::callbacks::call<std::string,std::vector<std::string> >(callback_name,args);
*/
namespace callbacks
{
/** This function returns an indexed callback (if the
* callback has already been registered with the singleton) */
template<typename Idx, typename ArgumentTuple, typename Data=bool >
bool call(const Idx& arg_callback_name, ArgumentTuple& args)
{
CCallbackSuperBase<Idx>** mapped_callback =
CRegisteredCallbacks<Idx>::getCallbacks()->at(arg_callback_name);
if(0 == mapped_callback) { return false; } //Function not found.
CCallbackBase<Idx, ArgumentTuple, Data>* callback =
dynamic_cast<CCallbackBase<Idx, ArgumentTuple, Data>*>(*mapped_callback);
if(NULL == callback)
{ return false; }
callback->call(args); //The actual function call
return true; //Everything worked out
}
/** Why do we allow specifying Data?
* Ans: Well a class might automatically and uniquely
* initialize the Data in the constructor */
template< typename CallbackClass, typename Idx,
typename ArgumentTuple, typename Data=bool >
bool add(const Idx& arg_callback_name)
{
CallbackClass f;
return f.sutil::CCallbackBase<Idx, ArgumentTuple, Data>::
registerCallback(arg_callback_name);
}
template< typename CallbackClass, typename Idx,
typename ArgumentTuple, typename Data>
bool add(const Idx& arg_callback_name, Data* arg_data)
{
CallbackClass f;
return f.sutil::CCallbackBase<Idx, ArgumentTuple, Data>::
registerCallback(arg_callback_name, arg_data);
}
/** Return a list of the registered callbacks (a vector of indices) */
template<typename Idx>
bool list(std::vector<Idx>& idxlist)
{ typedef CMappedPointerList<Idx,CCallbackSuperBase<Idx>,true> map;
map* m = CRegisteredCallbacks<Idx>::getCallbacks();
if(NULL == m) { return false; }
typename map::iterator it,ite;
idxlist.clear();
for(it = m->begin(), ite = m->end();it!=ite;++it)
{ idxlist.push_back(!it); }//Add the index to the vector
return true;
}
}
/** This class implements a callback factory singleton. In plain English,
* it is a one-of-a-kind class that can give you an function based on
* its name.
*
* NOTE: The singleton manages its memory and deletes all the pointers. */
template <typename Idx>
class CRegisteredCallbacks : private CSingleton<CMappedPointerList<Idx,CCallbackSuperBase<Idx>,true> >
{
//A typedef for easy use;
typedef CSingleton<CMappedPointerList<Idx,CCallbackSuperBase<Idx>,true> > singleton;
//So that the base class can call the register function
friend class CCallbackSuperBase<Idx>;
public:
/** Checks whether this callback has been registered with the factory */
static bool callbackRegistered(const Idx& arg_callback_name)
{
CCallbackSuperBase<Idx>** mapped_callback = singleton::getData()->at(arg_callback_name);
if(0 == mapped_callback) { return false; }
return true;
}
/** Deletes the singleton object and creates a new one
* in its stead */
static bool resetCallbacks()
{ return singleton::resetData(); }
/** Used to access the callback list */
static CMappedPointerList<Idx,CCallbackSuperBase<Idx>,true>* getCallbacks()
{ return singleton::getData(); }
private:
/** This function registers new dynamic callbacks with the factory.
* You can get objects of this callback by calling the
* createObjectForCallback function */
static bool registerCallback(const Idx& arg_callback_name,
CCallbackSuperBase<Idx>* arg_callback_object)
{
if(callbackRegistered(arg_callback_name))
{
#ifdef DEBUG
std::cerr<<"\nCRegisteredCallbacks::registerCallback() Warning :"
<<" The passed callback is already registered.";
#endif
return false;
}
// Creates an object that points to the passed callback object
CCallbackSuperBase<Idx>** t = singleton::getData()->
create(arg_callback_name,arg_callback_object);
if(0 == t)
{
#ifdef DEBUG
std::cerr<<"\nCRegisteredCallbacks::registerCallback() Error :"
<<" Failed to create callback in the callback mapped list.";
#endif
return false;
}
return true;
}
/** Private for the singleton */
CRegisteredCallbacks();
/** Private for the singleton */
CRegisteredCallbacks(const CRegisteredCallbacks&);
/** Private for the singleton */
CRegisteredCallbacks& operator= (const CRegisteredCallbacks&);
};
/** *********************************************************
* To support indexed querying for dynamic object allocation:
* Subclass CCallbackSuperBase and implement the createObject()
* function to return an object of the wanted callback.
* ********************************************************* */
template <typename Idx>
class CCallbackSuperBase
{
public:
/** Default Destructor : Does nothing */
virtual ~CCallbackSuperBase(){}
protected:
/** The constructor may only be called by a subclass */
CCallbackSuperBase(){}
/** To allow the callback registry to create objects for itself */
virtual bool registerCallbackSuper(
const Idx &arg_callback_name,
CCallbackSuperBase* arg_obj)
{
return CRegisteredCallbacks<Idx>::
registerCallback(arg_callback_name,arg_obj);
}
private:
/** Must name a callback while creating an object */
CCallbackSuperBase(const CCallbackSuperBase&);
/** Must name a callback while creating an object */
CCallbackSuperBase& operator= (const CCallbackSuperBase&);
};
/** *********************************************************
* This enables supporting dynamic typing for arbitrary
* index and object callbacks.
* ********************************************************* */
template <typename Idx, typename ArgumentTuple, typename Data=bool>
class CCallbackBase : public CCallbackSuperBase<Idx>
{
public:
/** A subclass must implement this function.
* You can choose to add a "return type" into
* the ArgumentTuple and get data from the function. */
virtual void call(ArgumentTuple& args) = 0;
/** A subclass must implement this function */
virtual CCallbackBase<Idx, ArgumentTuple, Data>* createObject()=0;
virtual bool registerCallback(
const Idx& arg_callback_name,
Data* arg_data = 0)
{
bool flag;
flag = CRegisteredCallbacks<Idx>::callbackRegistered(arg_callback_name);
if(flag)//Callback already registered. Do nothing and return false.
{ return false; }
else
{
//Duplicate this object and register the new one with the singleton
CCallbackBase<Idx,ArgumentTuple,Data>* obj = createObject();
//Set up data for this function object
if(0 != arg_data)
{ obj->data_ = arg_data; }
flag = CCallbackSuperBase<Idx>::registerCallbackSuper(
arg_callback_name,
dynamic_cast<CCallbackSuperBase<Idx>*>(obj) );
if(!flag)
{ delete obj; return false; }
}
return true;
}
/** Default Destructor : Does nothing */
virtual ~CCallbackBase(){}
protected:
/** Only a subclass may create an object of this type */
CCallbackBase() : data_(NULL){}
Data* data_;
private:
CCallbackBase(const CCallbackBase&);
CCallbackBase& operator= (const CCallbackBase&);
};
}
#endif /* CREGISTEREDCALLBACKS_HPP_ */
| 32.911263 | 104 | 0.649176 | samirmenon |
4a614ff0c95a5f176b6bc7725166d87fbf28ad41 | 22,088 | hpp | C++ | libs/log/src/windows/ipc_sync_wrappers.hpp | Manu343726/boost-cmake | 009c3843b49a56880d988ffdca6d909f881edb3d | [
"BSL-1.0"
] | 61 | 2017-07-03T18:36:45.000Z | 2021-09-14T14:57:19.000Z | libs/log/src/windows/ipc_sync_wrappers.hpp | Manu343726/boost-cmake | 009c3843b49a56880d988ffdca6d909f881edb3d | [
"BSL-1.0"
] | 49 | 2016-02-29T17:59:52.000Z | 2019-05-05T04:59:26.000Z | libs/log/src/windows/ipc_sync_wrappers.hpp | Manu343726/boost-cmake | 009c3843b49a56880d988ffdca6d909f881edb3d | [
"BSL-1.0"
] | 31 | 2017-07-04T14:15:34.000Z | 2021-09-12T04:50:41.000Z | /*
* Copyright Andrey Semashev 2016.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
/*!
* \file windows/ipc_sync_wrappers.hpp
* \author Andrey Semashev
* \date 23.01.2016
*
* \brief This header is the Boost.Log library implementation, see the library documentation
* at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html.
*/
#ifndef BOOST_LOG_WINDOWS_IPC_SYNC_WRAPPERS_HPP_INCLUDED_
#define BOOST_LOG_WINDOWS_IPC_SYNC_WRAPPERS_HPP_INCLUDED_
#include <boost/log/detail/config.hpp>
#include <boost/detail/winapi/access_rights.hpp>
#include <boost/detail/winapi/handles.hpp>
#include <boost/detail/winapi/event.hpp>
#include <boost/detail/winapi/semaphore.hpp>
#include <boost/detail/winapi/wait.hpp>
#include <boost/detail/winapi/dll.hpp>
#include <boost/detail/winapi/time.hpp>
#include <boost/detail/winapi/get_last_error.hpp>
#include <cstddef>
#include <limits>
#include <string>
#include <utility>
#include <boost/assert.hpp>
#include <boost/throw_exception.hpp>
#include <boost/checked_delete.hpp>
#include <boost/memory_order.hpp>
#include <boost/atomic/atomic.hpp>
#include <boost/intrusive/options.hpp>
#include <boost/intrusive/set.hpp>
#include <boost/intrusive/set_hook.hpp>
#include <boost/intrusive/list.hpp>
#include <boost/intrusive/list_hook.hpp>
#include <boost/log/exceptions.hpp>
#include <boost/log/utility/permissions.hpp>
#include "windows/auto_handle.hpp"
#include <boost/log/detail/header.hpp>
namespace boost {
BOOST_LOG_OPEN_NAMESPACE
namespace ipc {
namespace aux {
// TODO: Port to Boost.Atomic when it supports extended atomic ops
#if defined(BOOST_MSVC) && (_MSC_VER >= 1400) && !defined(UNDER_CE)
#if _MSC_VER == 1400
extern "C" unsigned char _interlockedbittestandset(long *a, long b);
extern "C" unsigned char _interlockedbittestandreset(long *a, long b);
#else
extern "C" unsigned char _interlockedbittestandset(volatile long *a, long b);
extern "C" unsigned char _interlockedbittestandreset(volatile long *a, long b);
#endif
#pragma intrinsic(_interlockedbittestandset)
#pragma intrinsic(_interlockedbittestandreset)
BOOST_FORCEINLINE bool bit_test_and_set(boost::atomic< uint32_t >& x, uint32_t bit) BOOST_NOEXCEPT
{
return _interlockedbittestandset(reinterpret_cast< long* >(&x.storage()), static_cast< long >(bit)) != 0;
}
BOOST_FORCEINLINE bool bit_test_and_reset(boost::atomic< uint32_t >& x, uint32_t bit) BOOST_NOEXCEPT
{
return _interlockedbittestandreset(reinterpret_cast< long* >(&x.storage()), static_cast< long >(bit)) != 0;
}
#elif (defined(BOOST_MSVC) || defined(BOOST_INTEL_WIN)) && defined(_M_IX86)
BOOST_FORCEINLINE bool bit_test_and_set(boost::atomic< uint32_t >& x, uint32_t bit) BOOST_NOEXCEPT
{
boost::atomic< uint32_t >::storage_type* p = &x.storage();
bool ret;
__asm
{
mov eax, bit
mov edx, p
lock bts [edx], eax
setc ret
};
return ret;
}
BOOST_FORCEINLINE bool bit_test_and_reset(boost::atomic< uint32_t >& x, uint32_t bit) BOOST_NOEXCEPT
{
boost::atomic< uint32_t >::storage_type* p = &x.storage();
bool ret;
__asm
{
mov eax, bit
mov edx, p
lock btr [edx], eax
setc ret
};
return ret;
}
#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
#if !defined(__CUDACC__)
#define BOOST_LOG_DETAIL_ASM_CLOBBER_CC_COMMA "cc",
#else
#define BOOST_LOG_DETAIL_ASM_CLOBBER_CC_COMMA
#endif
BOOST_FORCEINLINE bool bit_test_and_set(boost::atomic< uint32_t >& x, uint32_t bit) BOOST_NOEXCEPT
{
bool res;
__asm__ __volatile__
(
"lock; bts %[bit_number], %[storage]\n\t"
"setc %[result]\n\t"
: [storage] "+m" (x.storage()), [result] "=q" (res)
: [bit_number] "Kq" (bit)
: BOOST_LOG_DETAIL_ASM_CLOBBER_CC_COMMA "memory"
);
return res;
}
BOOST_FORCEINLINE bool bit_test_and_reset(boost::atomic< uint32_t >& x, uint32_t bit) BOOST_NOEXCEPT
{
bool res;
__asm__ __volatile__
(
"lock; btr %[bit_number], %[storage]\n\t"
"setc %[result]\n\t"
: [storage] "+m" (x.storage()), [result] "=q" (res)
: [bit_number] "Kq" (bit)
: BOOST_LOG_DETAIL_ASM_CLOBBER_CC_COMMA "memory"
);
return res;
}
#else
BOOST_FORCEINLINE bool bit_test_and_set(boost::atomic< uint32_t >& x, uint32_t bit) BOOST_NOEXCEPT
{
const uint32_t mask = uint32_t(1u) << bit;
uint32_t old_val = x.fetch_or(mask, boost::memory_order_acq_rel);
return (old_val & mask) != 0u;
}
BOOST_FORCEINLINE bool bit_test_and_reset(boost::atomic< uint32_t >& x, uint32_t bit) BOOST_NOEXCEPT
{
const uint32_t mask = uint32_t(1u) << bit;
uint32_t old_val = x.fetch_and(~mask, boost::memory_order_acq_rel);
return (old_val & mask) != 0u;
}
#endif
//! Interprocess event object
class interprocess_event
{
private:
auto_handle m_event;
public:
void create(const wchar_t* name, bool manual_reset, permissions const& perms = permissions());
void create_or_open(const wchar_t* name, bool manual_reset, permissions const& perms = permissions());
void open(const wchar_t* name);
boost::detail::winapi::HANDLE_ get_handle() const BOOST_NOEXCEPT { return m_event.get(); }
void set()
{
if (BOOST_UNLIKELY(!boost::detail::winapi::SetEvent(m_event.get())))
{
const boost::detail::winapi::DWORD_ err = boost::detail::winapi::GetLastError();
BOOST_LOG_THROW_DESCR_PARAMS(boost::log::system_error, "Failed to set an interprocess event object", (err));
}
}
void set_noexcept() BOOST_NOEXCEPT
{
BOOST_VERIFY(!!boost::detail::winapi::SetEvent(m_event.get()));
}
void reset()
{
if (BOOST_UNLIKELY(!boost::detail::winapi::ResetEvent(m_event.get())))
{
const boost::detail::winapi::DWORD_ err = boost::detail::winapi::GetLastError();
BOOST_LOG_THROW_DESCR_PARAMS(boost::log::system_error, "Failed to reset an interprocess event object", (err));
}
}
void wait()
{
const boost::detail::winapi::DWORD_ retval = boost::detail::winapi::WaitForSingleObject(m_event.get(), boost::detail::winapi::infinite);
if (BOOST_UNLIKELY(retval != boost::detail::winapi::wait_object_0))
{
const boost::detail::winapi::DWORD_ err = boost::detail::winapi::GetLastError();
BOOST_LOG_THROW_DESCR_PARAMS(boost::log::system_error, "Failed to block on an interprocess event object", (err));
}
}
bool wait(boost::detail::winapi::HANDLE_ abort_handle)
{
boost::detail::winapi::HANDLE_ handles[2u] = { m_event.get(), abort_handle };
const boost::detail::winapi::DWORD_ retval = boost::detail::winapi::WaitForMultipleObjects(2u, handles, false, boost::detail::winapi::infinite);
if (retval == (boost::detail::winapi::wait_object_0 + 1u))
{
// Wait was interrupted
return false;
}
else if (BOOST_UNLIKELY(retval != boost::detail::winapi::wait_object_0))
{
const boost::detail::winapi::DWORD_ err = boost::detail::winapi::GetLastError();
BOOST_LOG_THROW_DESCR_PARAMS(boost::log::system_error, "Failed to block on an interprocess event object", (err));
}
return true;
}
void swap(interprocess_event& that) BOOST_NOEXCEPT
{
m_event.swap(that.m_event);
}
};
//! Interprocess semaphore object
class interprocess_semaphore
{
private:
typedef boost::detail::winapi::DWORD_ NTSTATUS_;
struct semaphore_basic_information
{
boost::detail::winapi::ULONG_ current_count; // current semaphore count
boost::detail::winapi::ULONG_ maximum_count; // max semaphore count
};
typedef NTSTATUS_ (__stdcall *nt_query_semaphore_t)(boost::detail::winapi::HANDLE_ h, unsigned int info_class, semaphore_basic_information* pinfo, boost::detail::winapi::ULONG_ info_size, boost::detail::winapi::ULONG_* ret_len);
typedef bool (*is_semaphore_zero_count_t)(boost::detail::winapi::HANDLE_ h);
private:
auto_handle m_sem;
static boost::atomic< is_semaphore_zero_count_t > is_semaphore_zero_count;
static nt_query_semaphore_t nt_query_semaphore;
public:
void create_or_open(const wchar_t* name, permissions const& perms = permissions());
void open(const wchar_t* name);
boost::detail::winapi::HANDLE_ get_handle() const BOOST_NOEXCEPT { return m_sem.get(); }
void post(uint32_t count)
{
BOOST_ASSERT(count <= static_cast< uint32_t >((std::numeric_limits< boost::detail::winapi::LONG_ >::max)()));
if (BOOST_UNLIKELY(!boost::detail::winapi::ReleaseSemaphore(m_sem.get(), static_cast< boost::detail::winapi::LONG_ >(count), NULL)))
{
const boost::detail::winapi::DWORD_ err = boost::detail::winapi::GetLastError();
BOOST_LOG_THROW_DESCR_PARAMS(boost::log::system_error, "Failed to post on an interprocess semaphore object", (err));
}
}
bool is_zero_count() const
{
return is_semaphore_zero_count.load(boost::memory_order_acquire)(m_sem.get());
}
void wait()
{
const boost::detail::winapi::DWORD_ retval = boost::detail::winapi::WaitForSingleObject(m_sem.get(), boost::detail::winapi::infinite);
if (BOOST_UNLIKELY(retval != boost::detail::winapi::wait_object_0))
{
const boost::detail::winapi::DWORD_ err = boost::detail::winapi::GetLastError();
BOOST_LOG_THROW_DESCR_PARAMS(boost::log::system_error, "Failed to block on an interprocess semaphore object", (err));
}
}
bool wait(boost::detail::winapi::HANDLE_ abort_handle)
{
boost::detail::winapi::HANDLE_ handles[2u] = { m_sem.get(), abort_handle };
const boost::detail::winapi::DWORD_ retval = boost::detail::winapi::WaitForMultipleObjects(2u, handles, false, boost::detail::winapi::infinite);
if (retval == (boost::detail::winapi::wait_object_0 + 1u))
{
// Wait was interrupted
return false;
}
else if (BOOST_UNLIKELY(retval != boost::detail::winapi::wait_object_0))
{
const boost::detail::winapi::DWORD_ err = boost::detail::winapi::GetLastError();
BOOST_LOG_THROW_DESCR_PARAMS(boost::log::system_error, "Failed to block on an interprocess semaphore object", (err));
}
return true;
}
void swap(interprocess_semaphore& that) BOOST_NOEXCEPT
{
m_sem.swap(that.m_sem);
}
private:
static bool is_semaphore_zero_count_init(boost::detail::winapi::HANDLE_ h);
static bool is_semaphore_zero_count_nt_query_semaphore(boost::detail::winapi::HANDLE_ h);
static bool is_semaphore_zero_count_emulated(boost::detail::winapi::HANDLE_ h);
};
//! Interprocess mutex. Implementation adopted from Boost.Sync.
class interprocess_mutex
{
public:
//! Shared state that should be visible to all processes using the mutex
struct shared_state
{
boost::atomic< uint32_t > m_lock_state;
shared_state() BOOST_NOEXCEPT : m_lock_state(0u)
{
}
};
struct auto_unlock
{
explicit auto_unlock(interprocess_mutex& mutex) BOOST_NOEXCEPT : m_mutex(mutex) {}
~auto_unlock() { m_mutex.unlock(); }
BOOST_DELETED_FUNCTION(auto_unlock(auto_unlock const&))
BOOST_DELETED_FUNCTION(auto_unlock& operator=(auto_unlock const&))
private:
interprocess_mutex& m_mutex;
};
struct optional_unlock
{
optional_unlock() BOOST_NOEXCEPT : m_mutex(NULL) {}
explicit optional_unlock(interprocess_mutex& mutex) BOOST_NOEXCEPT : m_mutex(&mutex) {}
~optional_unlock() { if (m_mutex) m_mutex->unlock(); }
interprocess_mutex* disengage() BOOST_NOEXCEPT
{
interprocess_mutex* p = m_mutex;
m_mutex = NULL;
return p;
}
void engage(interprocess_mutex& mutex) BOOST_NOEXCEPT
{
BOOST_ASSERT(!m_mutex);
m_mutex = &mutex;
}
BOOST_DELETED_FUNCTION(optional_unlock(optional_unlock const&))
BOOST_DELETED_FUNCTION(optional_unlock& operator=(optional_unlock const&))
private:
interprocess_mutex* m_mutex;
};
private:
interprocess_event m_event;
shared_state* m_shared_state;
#if !defined(BOOST_MSVC) || _MSC_VER >= 1800
static BOOST_CONSTEXPR_OR_CONST uint32_t lock_flag_bit = 31u;
static BOOST_CONSTEXPR_OR_CONST uint32_t event_set_flag_bit = 30u;
static BOOST_CONSTEXPR_OR_CONST uint32_t lock_flag_value = 1u << lock_flag_bit;
static BOOST_CONSTEXPR_OR_CONST uint32_t event_set_flag_value = 1u << event_set_flag_bit;
static BOOST_CONSTEXPR_OR_CONST uint32_t waiter_count_mask = event_set_flag_value - 1u;
#else
// MSVC 8-11, inclusively, fail to link if these constants are declared as static constants instead of an enum
enum
{
lock_flag_bit = 31u,
event_set_flag_bit = 30u,
lock_flag_value = 1u << lock_flag_bit,
event_set_flag_value = 1u << event_set_flag_bit,
waiter_count_mask = event_set_flag_value - 1u
};
#endif
public:
interprocess_mutex() BOOST_NOEXCEPT : m_shared_state(NULL)
{
}
void create(const wchar_t* name, shared_state* shared, permissions const& perms = permissions())
{
m_event.create(name, false, perms);
m_shared_state = shared;
}
void open(const wchar_t* name, shared_state* shared)
{
m_event.open(name);
m_shared_state = shared;
}
bool try_lock()
{
return !bit_test_and_set(m_shared_state->m_lock_state, lock_flag_bit);
}
void lock()
{
if (BOOST_UNLIKELY(!try_lock()))
lock_slow();
}
bool lock(boost::detail::winapi::HANDLE_ abort_handle)
{
if (BOOST_LIKELY(try_lock()))
return true;
return lock_slow(abort_handle);
}
void unlock() BOOST_NOEXCEPT
{
const uint32_t old_count = m_shared_state->m_lock_state.fetch_add(lock_flag_value, boost::memory_order_release);
if ((old_count & event_set_flag_value) == 0u && (old_count > lock_flag_value))
{
if (!bit_test_and_set(m_shared_state->m_lock_state, event_set_flag_bit))
{
m_event.set_noexcept();
}
}
}
BOOST_DELETED_FUNCTION(interprocess_mutex(interprocess_mutex const&))
BOOST_DELETED_FUNCTION(interprocess_mutex& operator=(interprocess_mutex const&))
private:
void lock_slow();
bool lock_slow(boost::detail::winapi::HANDLE_ abort_handle);
void mark_waiting_and_try_lock(uint32_t& old_state);
void clear_waiting_and_try_lock(uint32_t& old_state);
};
//! A simple clock that corresponds to GetTickCount/GetTickCount64 timeline
struct tick_count_clock
{
#if BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WIN6
typedef boost::detail::winapi::ULONGLONG_ time_point;
#else
typedef boost::detail::winapi::DWORD_ time_point;
#endif
static time_point now() BOOST_NOEXCEPT
{
#if BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WIN6
return boost::detail::winapi::GetTickCount64();
#else
return boost::detail::winapi::GetTickCount();
#endif
}
};
//! Interprocess condition variable
class interprocess_condition_variable
{
private:
typedef boost::intrusive::list_base_hook<
boost::intrusive::tag< struct for_sem_order_by_usage >,
boost::intrusive::link_mode< boost::intrusive::safe_link >
> semaphore_info_list_hook_t;
typedef boost::intrusive::set_base_hook<
boost::intrusive::tag< struct for_sem_lookup_by_id >,
boost::intrusive::link_mode< boost::intrusive::safe_link >,
boost::intrusive::optimize_size< true >
> semaphore_info_set_hook_t;
//! Information about a semaphore object
struct semaphore_info :
public semaphore_info_list_hook_t,
public semaphore_info_set_hook_t
{
struct order_by_id
{
typedef bool result_type;
result_type operator() (semaphore_info const& left, semaphore_info const& right) const BOOST_NOEXCEPT
{
return left.m_id < right.m_id;
}
result_type operator() (semaphore_info const& left, uint32_t right) const BOOST_NOEXCEPT
{
return left.m_id < right;
}
result_type operator() (uint32_t left, semaphore_info const& right) const BOOST_NOEXCEPT
{
return left < right.m_id;
}
};
//! The semaphore
interprocess_semaphore m_semaphore;
//! Timestamp of the moment when the semaphore was checked for zero count and it was not zero. In milliseconds since epoch.
tick_count_clock::time_point m_last_check_for_zero;
//! The flag indicates that the semaphore has been checked for zero count and it was not zero
bool m_checked_for_zero;
//! The semaphore id
const uint32_t m_id;
explicit semaphore_info(uint32_t id) BOOST_NOEXCEPT : m_last_check_for_zero(0u), m_id(id)
{
}
//! Checks if the semaphore is in 'non-zero' state for too long
bool check_non_zero_timeout(tick_count_clock::time_point now) BOOST_NOEXCEPT
{
if (!m_checked_for_zero)
{
m_last_check_for_zero = now;
m_checked_for_zero = true;
return false;
}
return (now - m_last_check_for_zero) >= 2000u;
}
BOOST_DELETED_FUNCTION(semaphore_info(semaphore_info const&))
BOOST_DELETED_FUNCTION(semaphore_info& operator=(semaphore_info const&))
};
typedef boost::intrusive::list<
semaphore_info,
boost::intrusive::base_hook< semaphore_info_list_hook_t >,
boost::intrusive::constant_time_size< false >
> semaphore_info_list;
typedef boost::intrusive::set<
semaphore_info,
boost::intrusive::base_hook< semaphore_info_set_hook_t >,
boost::intrusive::compare< semaphore_info::order_by_id >,
boost::intrusive::constant_time_size< false >
> semaphore_info_set;
public:
struct shared_state
{
//! Number of waiters blocked on the semaphore if >0, 0 if no threads are blocked, <0 when the blocked threads were signalled
int32_t m_waiters;
//! The semaphore generation
uint32_t m_generation;
//! Id of the semaphore which is used to block threads on
uint32_t m_semaphore_id;
shared_state() BOOST_NOEXCEPT :
m_waiters(0),
m_generation(0u),
m_semaphore_id(0u)
{
}
};
private:
//! The list of semaphores used for blocking. The list is in the order at which the semaphores are considered to be picked for being used.
semaphore_info_list m_semaphore_info_list;
//! The list of semaphores used for blocking. Used for searching for a particular semaphore by id.
semaphore_info_set m_semaphore_info_set;
//! The semaphore that is currently being used for blocking
semaphore_info* m_current_semaphore;
//! A string storage for formatting a semaphore name
std::wstring m_semaphore_name;
//! Permissions used to create new semaphores
permissions m_perms;
//! Process-shared state
shared_state* m_shared_state;
//! The next id for creating a new semaphore
uint32_t m_next_semaphore_id;
public:
interprocess_condition_variable() BOOST_NOEXCEPT :
m_current_semaphore(NULL),
m_shared_state(NULL),
m_next_semaphore_id(0u)
{
}
~interprocess_condition_variable()
{
m_semaphore_info_set.clear();
m_semaphore_info_list.clear_and_dispose(boost::checked_deleter< semaphore_info >());
}
void init(const wchar_t* name, shared_state* shared, permissions const& perms = permissions())
{
m_perms = perms;
m_shared_state = shared;
m_semaphore_name = name;
// Reserve space for generate_semaphore_name()
m_semaphore_name.append(L".sem00000000");
m_current_semaphore = get_semaphore(m_shared_state->m_semaphore_id);
}
void notify_all()
{
const int32_t waiters = m_shared_state->m_waiters;
if (waiters > 0)
{
const uint32_t id = m_shared_state->m_semaphore_id;
if (m_current_semaphore->m_id != id)
m_current_semaphore = get_semaphore(id);
m_current_semaphore->m_semaphore.post(waiters);
m_shared_state->m_waiters = -waiters;
}
}
bool wait(interprocess_mutex::optional_unlock& lock, boost::detail::winapi::HANDLE_ abort_handle);
BOOST_DELETED_FUNCTION(interprocess_condition_variable(interprocess_condition_variable const&))
BOOST_DELETED_FUNCTION(interprocess_condition_variable& operator=(interprocess_condition_variable const&))
private:
//! Finds or opens a semaphore with the specified id
semaphore_info* get_semaphore(uint32_t id);
//! Finds or creates a semaphore with zero counter
semaphore_info* get_unused_semaphore();
//! Marks the semaphore info as unused and moves to the end of list
void mark_unused(semaphore_info& info) BOOST_NOEXCEPT;
//! Generates semaphore name according to id
void generate_semaphore_name(uint32_t id) BOOST_NOEXCEPT;
//! Returns \c true if \a left is less than \a right considering possible integer overflow
static bool is_overflow_less(uint32_t left, uint32_t right) BOOST_NOEXCEPT
{
return ((left - right) & 0x80000000u) != 0u;
}
};
} // namespace aux
} // namespace ipc
BOOST_LOG_CLOSE_NAMESPACE // namespace log
} // namespace boost
#include <boost/log/detail/footer.hpp>
#endif // BOOST_LOG_WINDOWS_IPC_SYNC_WRAPPERS_HPP_INCLUDED_
| 33.825421 | 232 | 0.680188 | Manu343726 |
4a64925586459e57961c312fddfbaef60a543db5 | 4,835 | cpp | C++ | cpp_files/caffe_jni.cpp | malreddysid/sudoku_android | 2018aea4fbf11ccc739aeed8a22c97b6e0319fdc | [
"MIT"
] | 2 | 2016-08-10T12:05:05.000Z | 2016-08-10T12:10:14.000Z | cpp_files/caffe_jni.cpp | malreddysid/sudoku_android | 2018aea4fbf11ccc739aeed8a22c97b6e0319fdc | [
"MIT"
] | null | null | null | cpp_files/caffe_jni.cpp | malreddysid/sudoku_android | 2018aea4fbf11ccc739aeed8a22c97b6e0319fdc | [
"MIT"
] | null | null | null | #include <string.h>
#include <jni.h>
#include <android/log.h>
#include <string>
#include <vector>
#ifdef USE_EIGEN
#include <omp.h>
#else
#include <cblas.h>
#endif
#include "caffe/caffe.hpp"
#include "caffe_mobile.hpp"
#ifdef __cplusplus
extern "C" {
#endif
using std::string;
using std::vector;
using caffe::CaffeMobile;
int getTimeSec() {
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
return (int)now.tv_sec;
}
string jstring2string(JNIEnv *env, jstring jstr) {
const char *cstr = env->GetStringUTFChars(jstr, 0);
string str(cstr);
env->ReleaseStringUTFChars(jstr, cstr);
return str;
}
JNIEXPORT void JNICALL
Java_com_sh1r0_caffe_1android_1lib_CaffeMobile_setNumThreads(JNIEnv *env,
jobject thiz,
jint numThreads) {
int num_threads = numThreads;
#ifdef USE_EIGEN
omp_set_num_threads(num_threads);
#else
openblas_set_num_threads(num_threads);
#endif
}
JNIEXPORT void JNICALL Java_com_sh1r0_caffe_1android_1lib_CaffeMobile_enableLog(
JNIEnv *env, jobject thiz, jboolean enabled) {}
JNIEXPORT jint JNICALL Java_com_sh1r0_caffe_1android_1lib_CaffeMobile_loadModel(
JNIEnv *env, jobject thiz, jstring modelPath, jstring weightsPath) {
CaffeMobile::Get(jstring2string(env, modelPath),
jstring2string(env, weightsPath));
return 0;
}
JNIEXPORT void JNICALL
Java_com_sh1r0_caffe_1android_1lib_CaffeMobile_setMeanWithMeanFile(
JNIEnv *env, jobject thiz, jstring meanFile) {
CaffeMobile *caffe_mobile = CaffeMobile::Get();
caffe_mobile->SetMean(jstring2string(env, meanFile));
}
JNIEXPORT void JNICALL
Java_com_sh1r0_caffe_1android_1lib_CaffeMobile_setMeanWithMeanValues(
JNIEnv *env, jobject thiz, jfloatArray meanValues) {
CaffeMobile *caffe_mobile = CaffeMobile::Get();
int num_channels = env->GetArrayLength(meanValues);
jfloat *ptr = env->GetFloatArrayElements(meanValues, 0);
vector<float> mean_values(ptr, ptr + num_channels);
caffe_mobile->SetMean(mean_values);
}
JNIEXPORT void JNICALL Java_com_sh1r0_caffe_1android_1lib_CaffeMobile_setScale(
JNIEnv *env, jobject thiz, jfloat scale) {
CaffeMobile *caffe_mobile = CaffeMobile::Get();
caffe_mobile->SetScale(scale);
}
JNIEXPORT jfloatArray JNICALL
Java_com_sh1r0_caffe_1android_1lib_CaffeMobile_getConfidenceScore(
JNIEnv *env, jobject thiz, jstring imgPath) {
CaffeMobile *caffe_mobile = CaffeMobile::Get();
vector<float> conf_score =
caffe_mobile->GetConfidenceScore(jstring2string(env, imgPath));
jfloatArray result;
result = env->NewFloatArray(conf_score.size());
if (result == NULL) {
return NULL; /* out of memory error thrown */
}
// move from the temp structure to the java structure
env->SetFloatArrayRegion(result, 0, conf_score.size(), &conf_score[0]);
return result;
}
JNIEXPORT jintArray JNICALL
Java_com_sh1r0_caffe_1android_1lib_CaffeMobile_predictImage(JNIEnv *env,
jobject thiz,
jstring imgPath,
jint k) {
CaffeMobile *caffe_mobile = CaffeMobile::Get();
vector<int> top_k =
caffe_mobile->PredictTopK(jstring2string(env, imgPath), k);
jintArray result;
result = env->NewIntArray(k);
if (result == NULL) {
return NULL; /* out of memory error thrown */
}
// move from the temp structure to the java structure
env->SetIntArrayRegion(result, 0, k, &top_k[0]);
return result;
}
JNIEXPORT jobjectArray JNICALL
Java_com_sh1r0_caffe_1android_1lib_CaffeMobile_extractFeatures(
JNIEnv *env, jobject thiz, jstring imgPath, jstring blobNames) {
CaffeMobile *caffe_mobile = CaffeMobile::Get();
vector<vector<float>> features = caffe_mobile->ExtractFeatures(
jstring2string(env, imgPath), jstring2string(env, blobNames));
jobjectArray array2D =
env->NewObjectArray(features.size(), env->FindClass("[F"), NULL);
for (size_t i = 0; i < features.size(); ++i) {
jfloatArray array1D = env->NewFloatArray(features[i].size());
if (array1D == NULL) {
return NULL; /* out of memory error thrown */
}
// move from the temp structure to the java structure
env->SetFloatArrayRegion(array1D, 0, features[i].size(), &features[i][0]);
env->SetObjectArrayElement(array2D, i, array1D);
}
return array2D;
}
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
JNIEnv *env = NULL;
jint result = -1;
if (vm->GetEnv((void **)&env, JNI_VERSION_1_6) != JNI_OK) {
LOG(FATAL) << "GetEnv failed!";
return result;
}
FLAGS_redirecttologcat = true;
FLAGS_android_logcat_tag = "caffe_jni";
return JNI_VERSION_1_6;
}
#ifdef __cplusplus
}
#endif
| 30.796178 | 80 | 0.696174 | malreddysid |
4a6e85f157a7c7f9ee4d3a3ae7de86cb7102000f | 1,221 | hpp | C++ | boost/network/protocol/http/message/wrappers/anchor.hpp | antoinelefloch/cpp-netlib | 5eb9b5550a10d06f064ee9883c7d942d3426f31b | [
"BSL-1.0"
] | 3 | 2015-02-10T22:08:08.000Z | 2021-11-13T20:59:25.000Z | include/boost/network/protocol/http/message/wrappers/anchor.hpp | waTeim/boost | eb3850fae8c037d632244cf15cf6905197d64d39 | [
"BSL-1.0"
] | 1 | 2018-08-10T04:47:12.000Z | 2018-08-10T13:54:57.000Z | include/boost/network/protocol/http/message/wrappers/anchor.hpp | waTeim/boost | eb3850fae8c037d632244cf15cf6905197d64d39 | [
"BSL-1.0"
] | 5 | 2017-12-28T12:42:25.000Z | 2021-07-01T07:41:53.000Z | #ifndef BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_WRAPPERS_ANCHOR_HPP_20100618
#define BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_WRAPPERS_ANCHOR_HPP_20100618
// Copyright 2010 (c) Dean Michael Berris.
// Copyright 2010 (c) Sinefunc, Inc.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
namespace boost { namespace network { namespace http {
template <class Tag>
struct basic_request;
namespace impl {
template <class Tag>
struct anchor_wrapper {
basic_request<Tag> const & message_;
anchor_wrapper(basic_request<Tag> const & message)
: message_(message) {}
typedef typename basic_request<Tag>::string_type string_type;
operator string_type() {
return message_.anchor();
}
};
}
template <class Tag> inline
impl::anchor_wrapper<Tag>
anchor(basic_request<Tag> const & request) {
return impl::anchor_wrapper<Tag>(request);
}
} // namespace http
} // namespace network
} // nmaespace boost
#endif // BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_WRAPPERS_ANCHOR_HPP_20100618
| 29.780488 | 74 | 0.689599 | antoinelefloch |
4a6f0ef95381bfd42ad02c0f8cc864fa7f262cc2 | 1,279 | cpp | C++ | Problems/ej/it-e/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | null | null | null | Problems/ej/it-e/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | 1 | 2019-05-09T19:17:00.000Z | 2019-05-09T19:17:00.000Z | Problems/ej/it-e/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | null | null | null | #include<iostream>
#include<algorithm>
using namespace std;
int net[1000][1000];
bool visited[1000] = {false};
int getFirstUnvistedNode(bool* nodes, int size) {
for (int i = 0; i < size; i++)
if (!nodes[i])
return i;
return size;
}
int dfs(int nodeIndex, int net[1000][1000], bool* visited, int nodesCount) {
int vistis = 0;
if (!visited[nodeIndex]) {
vistis++;
visited[nodeIndex] = true;
for (int i = 0; i < nodesCount; i++) {
if (net[nodeIndex][i]) {
vistis += dfs(i, net, visited, nodesCount);
}
}
}
return vistis;
}
int main()
{
//#ifndef ONLINE_JUDGE
// freopen("input.txt", "rt", stdin);
//#endif
int friends;
cin >> friends;
for (int i = 0; i < friends; i++)
for (int j = 0; j < friends; j++)
cin >> net[i][j];
int nodesVisited = 0;
int nodeIndex = getFirstUnvistedNode(visited, friends);
int paths = 1;
while (nodesVisited < friends && nodeIndex < friends) {
nodesVisited += dfs(nodeIndex, net, visited, friends);
if (nodesVisited < friends) {
paths++;
nodeIndex = getFirstUnvistedNode(visited, friends);
}
}
cout << paths;
return 0;
} | 22.839286 | 76 | 0.545739 | grand87 |
4a741ced2f0ee29ca58e7909fc4b0aeb05dbe762 | 1,666 | cpp | C++ | ros_ws/src/crazyswarm/externalDependencies/libmotioncapture/deps/vrpn/server_src/ghostEffects/InstantBuzzEffect.cpp | rasmus-rudling/crazyswarm | 1326fbc679061f64a8632a6553a9d6ae269bc1a4 | [
"MIT"
] | 1 | 2021-10-20T22:55:12.000Z | 2021-10-20T22:55:12.000Z | vrpn/server_src/ghostEffects/InstantBuzzEffect.cpp | deakinshaun/UniCAVE-Deakin | 8dc184d7dd598d4554627b8564cae99975ef3dc2 | [
"MIT"
] | null | null | null | vrpn/server_src/ghostEffects/InstantBuzzEffect.cpp | deakinshaun/UniCAVE-Deakin | 8dc184d7dd598d4554627b8564cae99975ef3dc2 | [
"MIT"
] | null | null | null | /*
# instantBuzzEffect : instantaneous buzz "custom" effect for Phantom server
# written by Sebastien MARAUX, ONDIM SA (France)
# maraux@ondim.fr
*/
#include "InstantBuzzEffect.h"
#ifdef VRPN_USE_PHANTOM_SERVER
#ifdef VRPN_USE_HDAPI
#include <HD/hd.h>
#else
#include <gstPHANToM.h>
#endif
#include <math.h>
#ifdef VRPN_USE_HDAPI
vrpn_HapticVector InstantBuzzEffect::calcEffectForce(void) {
#else
gstVector InstantBuzzEffect::calcEffectForce(void *phantom) {
#endif
// No force if inactive
if (!active) {
return vrpn_HapticVector(0,0,0);
}
// XXX Needs to be implemented on non-Windows platforms. Use
// the gettimeofday() function to calculate timing on those platforms.
// We might want to switch to vrpn_gettimeofday() on all platforms, since
// that is now implemented on Windows.
#ifdef _WIN32
LARGE_INTEGER counter;
if (currentPerformanceFrequency.HighPart == 0 && currentPerformanceFrequency.LowPart == 0) {
return vrpn_HapticVector(0,0,0);
}
if (QueryPerformanceCounter(&counter) != TRUE){
fprintf(stderr, "unable to get perfo counter\n");
return vrpn_HapticVector(0,0,0);
}
double elapsedSec = (counter.QuadPart - debut.QuadPart) / (double) currentPerformanceFrequency.QuadPart;
if (elapsedSec < getDuration()) {
double currentPart = (counter.QuadPart*getFrequency()/currentPerformanceFrequency.QuadPart);
currentPart = (currentPart-(long)currentPart)*2*PI;
double currentForce = sin(currentPart);
double force = currentForce*getAmplitude();
return vrpn_HapticVector( x*force, y*force, z*force );
}
#endif
return vrpn_HapticVector(0,0,0);
}
#endif // VRPN_USE_PHANTOM_SERVER
| 28.724138 | 109 | 0.738896 | rasmus-rudling |
4a79db6c722db364b380ae93722af5eff778d9bd | 7,921 | hpp | C++ | lib/soc/stm32l011xx/mcu.hpp | JayKickliter/CML | d21061a3abc013a8386798280b9595e9d4a2978c | [
"MIT"
] | null | null | null | lib/soc/stm32l011xx/mcu.hpp | JayKickliter/CML | d21061a3abc013a8386798280b9595e9d4a2978c | [
"MIT"
] | null | null | null | lib/soc/stm32l011xx/mcu.hpp | JayKickliter/CML | d21061a3abc013a8386798280b9595e9d4a2978c | [
"MIT"
] | null | null | null | #pragma once
/*
Name: mcu.hpp
Copyright(c) 2019 Mateusz Semegen
This code is licensed under MIT license (see LICENSE file for details)
*/
//std
#include <cstdint>
//externals
#include <stm32l0xx.h>
//cml
#include <cml/bit.hpp>
#include <cml/frequency.hpp>
namespace soc {
namespace stm32l011xx {
struct mcu
{
enum class Clock : uint32_t
{
msi = RCC_CR_MSION,
hsi = RCC_CR_HSION,
pll = RCC_CR_PLLON,
lsi
};
enum class Sysclk_source : uint32_t
{
msi = RCC_CFGR_SW_MSI,
hsi = RCC_CFGR_SW_HSI,
pll = RCC_CFGR_SW_PLL
};
enum class Msi_frequency : uint32_t
{
_65536_Hz = 0,
_131072_Hz = 1,
_262144_Hz = 2,
_524288_Hz = 3,
_1048_kHz = 4,
_2097_kHz = 5,
_4194_kHz = 6
};
enum class Hsi_frequency : uint32_t
{
_16_MHz
};
enum class Lsi_frequency : uint32_t
{
_37_kHz
};
enum class Flash_latency : uint32_t
{
_0 = 0,
_1 = FLASH_ACR_LATENCY,
unknown
};
enum class Voltage_scaling : uint32_t
{
_1 = PWR_CR_VOS_0,
_2 = PWR_CR_VOS_1,
_3 = PWR_CR_VOS_0 | PWR_CR_VOS_1,
unknown
};
enum class Reset_source : uint32_t
{
illegal_low_power = RCC_CSR_LPWRRSTF,
window_watchdog = RCC_CSR_WWDGRSTF,
independent_window_watchdog = RCC_CSR_IWDGRSTF,
software = RCC_CSR_SFTRSTF,
por_bdr = RCC_CSR_PORRSTF,
pin = RCC_CSR_PINRSTF,
option_byte_loader = RCC_CSR_OBLRSTF
};
struct Pll_config
{
enum class Source : uint32_t
{
hsi = RCC_CFGR_PLLSRC_HSI
};
enum class Multiplier
{
_3 = RCC_CFGR_PLLMUL3,
_4 = RCC_CFGR_PLLMUL4,
_6 = RCC_CFGR_PLLMUL6,
_8 = RCC_CFGR_PLLMUL8,
_12 = RCC_CFGR_PLLMUL12,
_16 = RCC_CFGR_PLLMUL16,
_24 = RCC_CFGR_PLLMUL24,
_32 = RCC_CFGR_PLLMUL32,
_48 = RCC_CFGR_PLLMUL48,
unknown
};
enum class Divider
{
_2 = RCC_CFGR_PLLDIV2,
_3 = RCC_CFGR_PLLDIV3,
_4 = RCC_CFGR_PLLDIV4,
unknown
};
Source source;
bool hsidiv_enabled = false;
Multiplier multiplier = Multiplier::unknown;
Divider divider = Divider::unknown;
};
struct Device_id
{
const uint8_t serial_number[12] = { 0 };
const uint32_t type = 0;
};
struct Sysclk_frequency_change_callback
{
using Function = void(*)(void* a_p_user_data);
Function function = nullptr;
void* p_user_data = nullptr;
};
struct Bus_prescalers
{
enum class AHB
{
_1,
_2,
_4,
_8,
_16,
_64,
_128,
_256,
unknown
};
enum class APB1
{
_1,
_2,
_4,
_8,
_16,
unknown
};
enum class APB2
{
_1,
_2,
_4,
_8,
_16,
unknown
};
AHB ahb = AHB::unknown;
APB1 apb1 = APB1::unknown;
APB2 apb2 = APB2::unknown;
};
public:
static void enable_msi_clock(Msi_frequency a_freq);
static void enable_hsi_clock(Hsi_frequency a_freq);
static void enable_lsi_clock(Lsi_frequency a_freq);
static void disable_msi_clock();
static void disable_hsi_clock();
static void disable_lsi_clock();
static void enable_pll(const Pll_config& a_pll_config);
static void disable_pll();
static void set_sysclk(Sysclk_source a_source, const Bus_prescalers& a_prescalers);
static void reset();
static void halt();
static void register_pre_sysclk_frequency_change_callback(const Sysclk_frequency_change_callback& a_callback);
static void register_post_sysclk_frequency_change_callback(const Sysclk_frequency_change_callback& a_callback);
static Bus_prescalers get_bus_prescalers();
static Pll_config get_pll_config();
static void enable_syscfg()
{
cml::set_flag(&(RCC->APB2ENR), RCC_APB2ENR_SYSCFGEN);
}
static void disable_syscfg()
{
cml::clear_flag(&(RCC->APB2ENR), RCC_APB2ENR_SYSCFGEN);
}
static bool is_syscfg_enabled()
{
return cml::is_flag(RCC->APB2ENR, RCC_APB2ENR_SYSCFGEN);
}
static Device_id get_device_id()
{
const uint8_t* p_id_location = reinterpret_cast<uint8_t*>(UID_BASE);
return { { p_id_location[0], p_id_location[1], p_id_location[2], p_id_location[3],
p_id_location[4], p_id_location[5], p_id_location[6], p_id_location[7],
p_id_location[8], p_id_location[9], p_id_location[10], p_id_location[11] },
DBGMCU->IDCODE
};
}
static Sysclk_source get_sysclk_source()
{
return static_cast<Sysclk_source>(cml::get_flag(RCC->CFGR, RCC_CFGR_SWS) >> RCC_CFGR_SWS_Pos);
}
static uint32_t get_sysclk_frequency_hz()
{
return SystemCoreClock;
}
static constexpr cml::frequency get_hsi_frequency_hz()
{
return cml::MHz(16u);
}
static constexpr cml::frequency get_lsi_frequency_hz()
{
return cml::kHz(37u);
}
static bool is_clock_enabled(Clock a_clock)
{
switch (a_clock)
{
case Clock::msi:
case Clock::hsi:
case Clock::pll:
{
return cml::is_flag(RCC->CR, static_cast<uint32_t>(a_clock));
}
break;
case Clock::lsi:
{
return cml::is_flag(RCC->CSR, RCC_CSR_LSION);
}
break;
}
return false;
}
static Voltage_scaling get_voltage_scaling()
{
return static_cast<Voltage_scaling>(cml::get_flag(PWR->CR, PWR_CR_VOS));
}
static Flash_latency get_flash_latency()
{
return static_cast<Flash_latency>(cml::get_flag(FLASH->ACR, FLASH_ACR_LATENCY));
}
static Reset_source get_reset_source()
{
uint32_t flag = cml::get_flag(RCC->CSR, 0xFB000000u);
if (flag == 0x0u)
{
flag = RCC_CSR_PINRSTF;
}
cml::set_flag(&(RCC->CSR), RCC_CSR_RMVF);
return static_cast<Reset_source>(flag);
}
private:
mcu() = delete;
mcu(const mcu&) = delete;
mcu(mcu&&) = delete;
~mcu() = default;
mcu& operator = (const mcu&) = delete;
mcu& operator = (mcu&&) = delete;
static Flash_latency select_flash_latency(uint32_t a_syclk_freq, Voltage_scaling a_voltage_scaling);
static Voltage_scaling select_voltage_scaling(Sysclk_source a_source, uint32_t a_sysclk_freq);
static void set_flash_latency(Flash_latency a_latency);
static void set_voltage_scaling(Voltage_scaling a_scaling);
static void set_sysclk_source(Sysclk_source a_sysclk_source);
static void set_bus_prescalers(const Bus_prescalers& a_prescalers);
static void increase_sysclk_frequency(Sysclk_source a_source,
cml::frequency a_frequency_hz,
const Bus_prescalers& a_prescalers);
static void decrease_sysclk_frequency(Sysclk_source a_source,
cml::frequency a_frequency_hz,
const Bus_prescalers& a_prescalers);
static uint32_t calculate_frequency_from_pll_configuration();
};
} // namespace stm32l011xx
} // namespace soc | 24.447531 | 115 | 0.573539 | JayKickliter |
4a79f5b0472a0acd03b9b8c3cae5ed72a228f525 | 1,741 | cpp | C++ | src/channel_utility.cpp | tangzhenquan/libatbus | a842439ffc6b9c05a94e79f52bf3b1a5c57da0a2 | [
"BSL-1.0",
"MIT"
] | 49 | 2015-03-10T06:41:17.000Z | 2021-03-16T05:10:34.000Z | src/channel_utility.cpp | tangzhenquan/libatbus | a842439ffc6b9c05a94e79f52bf3b1a5c57da0a2 | [
"BSL-1.0",
"MIT"
] | 1 | 2017-04-22T15:22:16.000Z | 2019-01-08T04:58:23.000Z | src/channel_utility.cpp | tangzhenquan/libatbus | a842439ffc6b9c05a94e79f52bf3b1a5c57da0a2 | [
"BSL-1.0",
"MIT"
] | 20 | 2015-11-03T08:48:41.000Z | 2021-03-16T05:10:37.000Z | /**
* @brief 所有channel文件的模式均为 c + channel<br />
* 使用c的模式是为了简单、结构清晰并且避免异常<br />
* 附带c++的部分是为了避免命名空间污染并且c++的跨平台适配更加简单
*/
#include <cstdio>
#include "common/string_oprs.h"
#include "detail/libatbus_channel_export.h"
namespace atbus {
namespace channel {
bool make_address(const char *in, channel_address_t &addr) {
addr.address = in;
// 获取协议
size_t scheme_end = addr.address.find_first_of("://");
if (addr.address.npos == scheme_end) {
return false;
}
addr.scheme = addr.address.substr(0, scheme_end);
size_t port_end = addr.address.find_last_of(":");
addr.port = 0;
if (addr.address.npos != port_end && port_end >= scheme_end + 3) {
UTIL_STRFUNC_SSCANF(addr.address.c_str() + port_end + 1, "%d", &addr.port);
}
// 截取域名
addr.host = addr.address.substr(scheme_end + 3, (port_end == addr.address.npos) ? port_end : port_end - scheme_end - 3);
return true;
}
void make_address(const char *scheme, const char *host, int port, channel_address_t &addr) {
addr.scheme = scheme;
addr.host = host;
addr.port = port;
addr.address.reserve(addr.scheme.size() + addr.host.size() + 4 + 8);
addr.address = addr.scheme + "://" + addr.host;
if (port > 0) {
char port_str[16] = {0};
UTIL_STRFUNC_SNPRINTF(port_str, sizeof(port_str), "%d", port);
addr.address += ":";
addr.address += &port_str[0];
}
}
}
}
| 32.849057 | 133 | 0.517519 | tangzhenquan |
4a7d2f0f81da0a1387ae06aa8e8f17b5710c0306 | 1,835 | cpp | C++ | contracts/wawaka/common/StateReference.cpp | marcelamelara/private-data-objects | be6841715865d4733b6555f416c56dde8839849e | [
"Apache-2.0"
] | null | null | null | contracts/wawaka/common/StateReference.cpp | marcelamelara/private-data-objects | be6841715865d4733b6555f416c56dde8839849e | [
"Apache-2.0"
] | null | null | null | contracts/wawaka/common/StateReference.cpp | marcelamelara/private-data-objects | be6841715865d4733b6555f416c56dde8839849e | [
"Apache-2.0"
] | null | null | null | /* Copyright 2019 Intel Corporation
*
* 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 "StateReference.h"
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// Class: ww::value::StateReference
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// -----------------------------------------------------------------
bool ww::value::StateReference::deserialize(const ww::value::Object& reference)
{
if (! reference.validate_schema(STATE_REFERENCE_SCHEMA))
return false;
contract_id_ = reference.get_string("contract_id");
state_hash_ = reference.get_string("state_hash");
return true;
}
// -----------------------------------------------------------------
bool ww::value::StateReference::serialize(ww::value::Value& serialized_reference) const
{
ww::value::Structure reference(STATE_REFERENCE_SCHEMA);
if (! reference.set_string("contract_id", contract_id_.c_str()))
return false;
if (! reference.set_string("state_hash", state_hash_.c_str()))
return false;
serialized_reference.set(reference);
return true;
}
// -----------------------------------------------------------------
bool ww::value::StateReference::add_to_response(Response& rsp) const
{
return rsp.add_dependency(contract_id_, state_hash_);
}
| 35.980392 | 87 | 0.666485 | marcelamelara |
4a7e596a5d27f1c9928fb8c3adaa3be1b853d2ab | 2,258 | cpp | C++ | src/util/generic.cpp | nabijaczleweli/pb-cpp | ccf28ba3dd7a3ec7898bc155f6b14755cc79a8f3 | [
"MIT"
] | 9 | 2018-01-11T10:41:25.000Z | 2020-01-14T06:49:56.000Z | src/util/generic.cpp | nabijaczleweli/pb-cpp | ccf28ba3dd7a3ec7898bc155f6b14755cc79a8f3 | [
"MIT"
] | 1 | 2018-06-29T22:03:53.000Z | 2018-06-30T00:04:19.000Z | src/util/generic.cpp | nabijaczleweli/pb-cpp | ccf28ba3dd7a3ec7898bc155f6b14755cc79a8f3 | [
"MIT"
] | null | null | null | // The MIT License (MIT)
// Copyright (c) 2017 nabijaczleweli
// 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 "../../include/pb-cpp/util.hpp"
#include <cmath>
std::ostream & pb::util::operator<<(std::ostream & out, human_readable hr) {
static const auto ln_kib = std::log(1024.);
static const char * suffixes[] = {"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"};
if(hr.size == 0)
out << "0 B";
else {
const auto exp = std::min(std::max(static_cast<std::size_t>(std::log(static_cast<double>(hr.size)) / ln_kib), static_cast<std::size_t>(0)),
sizeof(suffixes) / sizeof(*suffixes));
const auto val = static_cast<double>(hr.size) / std::pow(2., exp * 10);
if(exp > 0)
out << std::round(val * 10.) / 10. << ' ' << suffixes[static_cast<std::size_t>(exp)];
else
out << std::round(val) << ' ' << suffixes[0];
}
return out;
}
pb::util::human_readable pb::util::make_human_readable(std::size_t size) {
return {size};
}
pb::util::cursor_up_mover pb::util::move_cursor_up(std::size_t by) {
return {by};
}
pb::util::cursor_hide::cursor_hide(bool a) : actually(a) {
if(actually)
hide();
}
pb::util::cursor_hide::~cursor_hide() {
if(actually)
restore();
}
| 34.738462 | 141 | 0.687777 | nabijaczleweli |
4a7fe3eb7b966c5b6159f9bfc90663d9a73e9f2f | 214 | cpp | C++ | .history/src/log_20200716172848.cpp | zoedsy/LibManage | 590311fb035d11daa209301f9ce76f53ccae7643 | [
"MIT"
] | 1 | 2021-03-16T05:22:46.000Z | 2021-03-16T05:22:46.000Z | .history/src/log_20200716172848.cpp | zoedsy/LibManage | 590311fb035d11daa209301f9ce76f53ccae7643 | [
"MIT"
] | null | null | null | .history/src/log_20200716172848.cpp | zoedsy/LibManage | 590311fb035d11daa209301f9ce76f53ccae7643 | [
"MIT"
] | null | null | null | /*
* @Author: your name
* @Date: 2020-07-16 17:28:47
* @LastEditTime: 2020-07-16 17:28:48
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \LibManage\src\log.cpp
*/
| 23.777778 | 39 | 0.672897 | zoedsy |
4a821fb67de99b4fe87185440310b4838847a6b5 | 10,005 | hpp | C++ | benchmark/bm_conv.hpp | matazure/mtensor | 4289284b201cb09ed1dfc49f44d6738751affd63 | [
"MIT"
] | 82 | 2020-04-11T09:33:36.000Z | 2022-03-23T03:47:25.000Z | benchmark/bm_conv.hpp | Lexxos/mtensor | feb120923dad3fb4ae3b31dd09931622a63c3d06 | [
"MIT"
] | 28 | 2017-04-26T17:12:35.000Z | 2019-04-08T04:05:24.000Z | benchmark/bm_conv.hpp | Lexxos/mtensor | feb120923dad3fb4ae3b31dd09931622a63c3d06 | [
"MIT"
] | 22 | 2017-01-10T14:57:29.000Z | 2019-12-17T08:55:59.000Z | #pragma once
#include "bm_config.hpp"
namespace _tmp {
#ifndef MATAZURE_CUDA
using matazure::for_index;
using matazure::tensor;
#else
using matazure::cuda::for_index;
using matazure::cuda::tensor;
#endif
}
template <typename tensor_type>
inline void bm_tensor2f_general_roll_conv(benchmark::State& state) {
const static int_t rank = tensor_type::rank;
typedef typename tensor_type::value_type value_type;
pointi<rank> shape;
fill(shape, state.range(0));
pointi<rank> kernel_shape;
fill(kernel_shape, 3);
tensor_type kernel(kernel_shape);
auto kernel_radius = kernel_shape / 2;
tensor_type ts_dst(shape);
tensor_type ts_src_pad(shape + kernel.shape() - 1);
auto ts_src_view = view::slice(ts_src_pad, kernel_radius, shape);
while (state.KeepRunning()) {
_tmp::for_index(ts_dst.shape(), MLAMBDA(pointi<rank> idx) {
auto re = zero<value_type>::value();
for_index(zero<pointi<rank>>::value(), kernel_shape, [&](pointi<rank> neigbor_idx) {
re += kernel(neigbor_idx) * ts_src_view(idx + neigbor_idx - kernel_radius);
});
ts_dst(idx) = re;
});
benchmark::DoNotOptimize(ts_dst.data());
}
state.SetBytesProcessed(state.iterations() * static_cast<size_t>(ts_src_pad.size()) *
sizeof(ts_dst[0]));
state.SetItemsProcessed(state.iterations() * static_cast<size_t>(ts_dst.size()) *
kernel.size() * 2);
}
template <typename tensor_type>
inline void bm_tensor2f_general_unroll_conv(benchmark::State& state) {
const static int_t rank = tensor_type::rank;
typedef typename tensor_type::value_type value_type;
pointi<rank> shape;
fill(shape, state.range(0));
pointi<rank> kernel_shape;
fill(kernel_shape, 3);
tensor_type kernel(kernel_shape);
auto kernel_radius = kernel_shape / 2;
tensor_type ts_dst(shape);
tensor_type ts_src_pad(shape + kernel.shape() - 1);
auto ts_src_view = view::slice(ts_src_pad, kernel_radius, shape);
while (state.KeepRunning()) {
_tmp::for_index(ts_dst.shape(), MLAMBDA(pointi<rank> idx) {
// clang-format off
auto re = zero<value_type>::value();
re += kernel(pointi<2>{0, 0}) * ts_src_view(idx + pointi<2>{-1, -1});
re += kernel(pointi<2>{1, 0}) * ts_src_view(idx + pointi<2>{ 0, -1});
re += kernel(pointi<2>{2, 0}) * ts_src_view(idx + pointi<2>{ 1, -1});
re += kernel(pointi<2>{0, 1}) * ts_src_view(idx + pointi<2>{-1, 0});
re += kernel(pointi<2>{1, 1}) * ts_src_view(idx + pointi<2>{ 0, 0});
re += kernel(pointi<2>{2, 1}) * ts_src_view(idx + pointi<2>{ 1, 0});
re += kernel(pointi<2>{0, 2}) * ts_src_view(idx + pointi<2>{-1, 1});
re += kernel(pointi<2>{1, 2}) * ts_src_view(idx + pointi<2>{ 0, 1});
re += kernel(pointi<2>{2, 2}) * ts_src_view(idx + pointi<2>{ 1, 1});
ts_dst(idx) = re;
// clang-format on
});
benchmark::DoNotOptimize(ts_dst.data());
}
state.SetBytesProcessed(state.iterations() * static_cast<size_t>(ts_src_pad.size()) *
sizeof(ts_dst[0]));
state.SetItemsProcessed(state.iterations() * static_cast<size_t>(ts_dst.size()) *
kernel.size() * 2);
}
template <typename tensor_type>
inline void bm_tensor2f_padding_layout_general_unroll_conv(benchmark::State& state) {
const static int_t rank = tensor_type::rank;
typedef typename tensor_type::value_type value_type;
pointi<rank> shape;
fill(shape, state.range(0));
pointi<rank> kernel_shape;
fill(kernel_shape, 3);
tensor_type kernel(kernel_shape);
auto kernel_radius = kernel_shape / 2;
tensor_type ts_dst(shape);
_tmp::tensor<value_type, rank, padding_layout<rank>> ts_src(shape, kernel_radius,
kernel_radius);
while (state.KeepRunning()) {
_tmp::for_index(ts_dst.shape(), MLAMBDA(pointi<rank> idx) {
// clang-format off
auto re = zero<value_type>::value();
re += kernel(pointi<2>{0, 0}) * ts_src(idx + pointi<2>{-1, -1});
re += kernel(pointi<2>{1, 0}) * ts_src(idx + pointi<2>{ 0, -1});
re += kernel(pointi<2>{2, 0}) * ts_src(idx + pointi<2>{ 1, -1});
re += kernel(pointi<2>{0, 1}) * ts_src(idx + pointi<2>{-1, 0});
re += kernel(pointi<2>{1, 1}) * ts_src(idx + pointi<2>{ 0, 0});
re += kernel(pointi<2>{2, 1}) * ts_src(idx + pointi<2>{ 1, 0});
re += kernel(pointi<2>{0, 2}) * ts_src(idx + pointi<2>{-1, 1});
re += kernel(pointi<2>{1, 2}) * ts_src(idx + pointi<2>{ 0, 1});
re += kernel(pointi<2>{2, 2}) * ts_src(idx + pointi<2>{ 1, 1});
ts_dst(idx) = re;
// clang-format on
});
benchmark::DoNotOptimize(ts_dst.data());
}
state.SetBytesProcessed(state.iterations() * static_cast<size_t>(ts_src.size()) *
sizeof(ts_dst[0]));
state.SetItemsProcessed(state.iterations() * static_cast<size_t>(ts_dst.size()) *
kernel.size() * 2);
}
template <typename tensor_type>
inline void bm_tensor2_view_conv_local_tensor3x3(benchmark::State& state) {
const static int_t rank = tensor_type::rank;
typedef typename tensor_type::value_type value_type;
pointi<rank> shape;
fill(shape, state.range(0));
local_tensor<value_type, dim<3, 3>> kernel;
tensor_type ts_src_pad(shape + kernel.shape() - 1);
auto ts_src_view = view::slice(ts_src_pad, kernel.shape() / 2, shape);
tensor_type ts_dst(shape);
while (state.KeepRunning()) {
copy(view::conv(ts_src_view, kernel), ts_dst);
benchmark::DoNotOptimize(ts_dst.data());
}
state.SetBytesProcessed(state.iterations() * static_cast<size_t>(ts_src_pad.size()) *
sizeof(ts_src_view[0]));
state.SetItemsProcessed(state.iterations() * static_cast<size_t>(ts_dst.size()) *
kernel.size() * 2);
}
template <typename tensor_type>
inline void bm_tensor_view_conv_tensor3x3(benchmark::State& state) {
const static int_t rank = tensor_type::rank;
typedef typename tensor_type::value_type value_type;
pointi<rank> shape;
fill(shape, state.range(0));
pointi<rank> kernel_shape;
fill(kernel_shape, 3);
tensor_type kernel(kernel_shape);
tensor_type ts_src_pad(shape + kernel.shape() - 1);
auto ts_src_view = view::slice(ts_src_pad, kernel.shape() / 2, shape);
tensor_type ts_dst(shape);
while (state.KeepRunning()) {
copy(view::conv(ts_src_view, kernel), ts_dst);
benchmark::DoNotOptimize(ts_dst.data());
}
state.SetBytesProcessed(state.iterations() * static_cast<size_t>(ts_src_pad.size()) *
sizeof(ts_src_view[0]));
state.SetItemsProcessed(state.iterations() * static_cast<size_t>(ts_dst.size()) *
kernel.size() * 2);
}
template <typename tensor_type>
inline void bm_tensor2_view_conv_neighbors_weights3x3(benchmark::State& state) {
const static int_t rank = tensor_type::rank;
typedef typename tensor_type::value_type value_type;
pointi<rank> shape;
fill(shape, state.range(0));
tensor<tuple<pointi<rank>, value_type>, 1> neightbors_weights(9);
neightbors_weights[0] = make_tuple(pointi<rank>{-1, -1}, value_type{1});
neightbors_weights[0] = make_tuple(pointi<rank>{-1, -0}, value_type{1});
neightbors_weights[0] = make_tuple(pointi<rank>{-1, +1}, value_type{1});
neightbors_weights[0] = make_tuple(pointi<rank>{-0, -1}, value_type{1});
neightbors_weights[0] = make_tuple(pointi<rank>{-0, -0}, value_type{1});
neightbors_weights[0] = make_tuple(pointi<rank>{-0, +1}, value_type{1});
neightbors_weights[0] = make_tuple(pointi<rank>{+1, -1}, value_type{1});
neightbors_weights[0] = make_tuple(pointi<rank>{+1, -0}, value_type{1});
neightbors_weights[0] = make_tuple(pointi<rank>{+1, +1}, value_type{1});
pointi<2> padding = {1, 1};
tensor_type ts_src_pad(shape + 2 * padding);
auto ts_src_view = view::slice(ts_src_pad, padding, shape);
tensor_type ts_dst(shape);
while (state.KeepRunning()) {
copy(view::conv(ts_src_view, neightbors_weights), ts_dst);
benchmark::DoNotOptimize(ts_dst.data());
}
state.SetBytesProcessed(state.iterations() * static_cast<size_t>(ts_src_pad.size()) *
sizeof(ts_src_view[0]));
state.SetItemsProcessed(state.iterations() * static_cast<size_t>(ts_dst.size()) *
neightbors_weights.size() * 2);
}
template <typename tensor_type>
inline void bm_tensor2_view_conv_stride2_relu6_local_tensor3x3(benchmark::State& state) {
const static int_t rank = tensor_type::rank;
typedef typename tensor_type::value_type value_type;
pointi<rank> shape;
fill(shape, state.range(0));
local_tensor<value_type, dim<3, 3>> kernel;
tensor_type ts_src_pad(shape + kernel.shape() - 1);
auto ts_src_view = view::slice(ts_src_pad, kernel.shape() / 2, shape);
tensor_type ts_dst(shape / 2);
while (state.KeepRunning()) {
auto ts_conv_view = view::conv(ts_src_view, kernel);
auto ts_conv_stride_view = view::stride(ts_conv_view, pointi<2>{2, 2});
auto ts_conv_stride_relu6_view =
view::map(ts_conv_stride_view, [] MATAZURE_GENERAL(value_type v) { return v; });
copy(ts_conv_stride_view, ts_dst);
benchmark::DoNotOptimize(ts_dst.data());
}
state.SetBytesProcessed(state.iterations() * static_cast<size_t>(ts_src_pad.size()) *
sizeof(ts_src_view[0]));
state.SetItemsProcessed(state.iterations() * static_cast<size_t>(ts_dst.size()) *
kernel.size() * 2);
}
| 41.004098 | 96 | 0.625487 | matazure |
4a822b402279cba9624e983f628f28602c057281 | 776 | hpp | C++ | include/RED4ext/Types/generated/game/ui/AccessPointMiniGameStatus.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | 1 | 2021-02-01T23:07:50.000Z | 2021-02-01T23:07:50.000Z | include/RED4ext/Types/generated/game/ui/AccessPointMiniGameStatus.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | include/RED4ext/Types/generated/game/ui/AccessPointMiniGameStatus.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/Types/generated/game/ui/HackingMinigameState.hpp>
#include <RED4ext/Types/generated/red/Event.hpp>
namespace RED4ext
{
namespace game::ui {
struct AccessPointMiniGameStatus : red::Event
{
static constexpr const char* NAME = "gameuiAccessPointMiniGameStatus";
static constexpr const char* ALIAS = "AccessPointMiniGameStatus";
game::ui::HackingMinigameState minigameState; // 40
uint8_t unk44[0x48 - 0x44]; // 44
};
RED4EXT_ASSERT_SIZE(AccessPointMiniGameStatus, 0x48);
} // namespace game::ui
using AccessPointMiniGameStatus = game::ui::AccessPointMiniGameStatus;
} // namespace RED4ext
| 29.846154 | 74 | 0.770619 | Cyberpunk-Extended-Development-Team |
4a8246c58975a1961c4e550db4be876bfd9ea2b7 | 1,009 | cpp | C++ | tests/regression/ConnectedButIndepIters/test.cpp | SusanTan/noelle | 33c9e10a20bc59590c13bf29fb661fc406a9e687 | [
"MIT"
] | 43 | 2020-09-04T15:21:40.000Z | 2022-03-23T03:53:02.000Z | tests/regression/ConnectedButIndepIters/test.cpp | SusanTan/noelle | 33c9e10a20bc59590c13bf29fb661fc406a9e687 | [
"MIT"
] | 15 | 2020-09-17T18:06:15.000Z | 2022-01-24T17:14:36.000Z | tests/regression/ConnectedButIndepIters/test.cpp | SusanTan/noelle | 33c9e10a20bc59590c13bf29fb661fc406a9e687 | [
"MIT"
] | 23 | 2020-09-04T15:50:09.000Z | 2022-03-25T13:38:25.000Z | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
long long int computePowerSeries (long long int *a, long long int iters){
long long int s =0;
long long int t =0;
long long int u =0;
long long int v =0;
for (auto i=0; i < iters; ++i){
s += a[i];
for (long long int j=0; j < iters / 10; ++j){
t += a[j];
}
u -= t;
for (long long int j=0; j < iters / 10; ++j){
u += a[j];
}
v -= u;
for (long long int j=0; j < iters / 10; ++j){
v += a[j];
}
}
long long int x = s + t + u + v;
return x;
}
int main (int argc, char *argv[]){
/*
* Check the inputs.
*/
if (argc < 2){
fprintf(stderr, "USAGE: %s LOOP_ITERATIONS\n", argv[0]);
return -1;
}
auto iterations = atoll(argv[1]);
long long int *array = (long long int *) malloc(sizeof(long long int) * iterations);
for (auto i=0; i < iterations; i++){
array[i] = i;
}
auto s = computePowerSeries(array, iterations);
printf("%lld\n", s);
return 0;
}
| 19.784314 | 86 | 0.531219 | SusanTan |
4a832803d05002d65d711d2a82aeb4719fc462ec | 440 | cpp | C++ | tools/calc_2.cpp | void-zxh/CS410-MSA-project | e38c628783575f80a0826d7200413a1a87f4279c | [
"MIT"
] | null | null | null | tools/calc_2.cpp | void-zxh/CS410-MSA-project | e38c628783575f80a0826d7200413a1a87f4279c | [
"MIT"
] | null | null | null | tools/calc_2.cpp | void-zxh/CS410-MSA-project | e38c628783575f80a0826d7200413a1a87f4279c | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdio.h>
#include <algorithm>
#include <cstring>
using namespace std;
const int GAP=2;
const int MISMATCH=3;
char si[100005];
char si2[100005];
int main()
{
int i,len;
scanf("%s",si+1);
scanf("%s",si2+1);
len=strlen(si+1);
int ans=0;
for(i=1;i<=len;i++)
if(si[i]=='-'||si2[i]=='-')
ans+=GAP;
else if(si[i]!=si2[i])
ans+=MISMATCH;
printf("%d\n",ans);
return 0;
} | 16.296296 | 30 | 0.563636 | void-zxh |
4a854a2c6ca04ce3877a0c49cbac3f78590b1f30 | 15,369 | cc | C++ | chrome/browser/chromeos/attestation/platform_verification_flow.cc | kurli/chromium-crosswalk | f4c5d15d49d02b74eb834325e4dff50b16b53243 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/chromeos/attestation/platform_verification_flow.cc | kurli/chromium-crosswalk | f4c5d15d49d02b74eb834325e4dff50b16b53243 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/chromeos/attestation/platform_verification_flow.cc | kurli/chromium-crosswalk | f4c5d15d49d02b74eb834325e4dff50b16b53243 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "platform_verification_flow.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/chromeos/attestation/attestation_ca_client.h"
#include "chrome/browser/chromeos/attestation/attestation_signed_data.pb.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/chromeos/system/statistics_provider.h"
#include "chrome/browser/prefs/scoped_user_pref_update.h"
#include "chrome/common/pref_names.h"
#include "chromeos/attestation/attestation_flow.h"
#include "chromeos/cryptohome/async_method_caller.h"
#include "chromeos/dbus/cryptohome_client.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "components/user_prefs/pref_registry_syncable.h"
#include "components/user_prefs/user_prefs.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
namespace {
// A switch which allows consent to be given on the command line.
// TODO(dkrahn): Remove this when UI has been implemented (crbug.com/270908).
const char kAutoApproveSwitch[] =
"auto-approve-platform-verification-consent-prompts";
// A callback method to handle DBus errors.
void DBusCallback(const base::Callback<void(bool)>& on_success,
const base::Closure& on_failure,
chromeos::DBusMethodCallStatus call_status,
bool result) {
if (call_status == chromeos::DBUS_METHOD_CALL_SUCCESS) {
on_success.Run(result);
} else {
LOG(ERROR) << "PlatformVerificationFlow: DBus call failed!";
on_failure.Run();
}
}
// A helper to call a ChallengeCallback with an error result.
void ReportError(
const chromeos::attestation::PlatformVerificationFlow::ChallengeCallback&
callback,
chromeos::attestation::PlatformVerificationFlow::Result error) {
callback.Run(error, std::string(), std::string(), std::string());
}
} // namespace
namespace chromeos {
namespace attestation {
// A default implementation of the Delegate interface.
class DefaultDelegate : public PlatformVerificationFlow::Delegate {
public:
DefaultDelegate() {}
virtual ~DefaultDelegate() {}
virtual void ShowConsentPrompt(
PlatformVerificationFlow::ConsentType type,
content::WebContents* web_contents,
const PlatformVerificationFlow::Delegate::ConsentCallback& callback)
OVERRIDE {
if (CommandLine::ForCurrentProcess()->HasSwitch(kAutoApproveSwitch)) {
LOG(WARNING) << "PlatformVerificationFlow: Automatic approval enabled.";
callback.Run(PlatformVerificationFlow::CONSENT_RESPONSE_ALLOW);
} else {
NOTIMPLEMENTED();
}
}
private:
DISALLOW_COPY_AND_ASSIGN(DefaultDelegate);
};
PlatformVerificationFlow::PlatformVerificationFlow()
: attestation_flow_(NULL),
async_caller_(cryptohome::AsyncMethodCaller::GetInstance()),
cryptohome_client_(DBusThreadManager::Get()->GetCryptohomeClient()),
user_manager_(UserManager::Get()),
statistics_provider_(system::StatisticsProvider::GetInstance()),
delegate_(NULL),
testing_prefs_(NULL),
weak_factory_(this) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
scoped_ptr<ServerProxy> attestation_ca_client(new AttestationCAClient());
default_attestation_flow_.reset(new AttestationFlow(
async_caller_,
cryptohome_client_,
attestation_ca_client.Pass()));
attestation_flow_ = default_attestation_flow_.get();
default_delegate_.reset(new DefaultDelegate());
delegate_ = default_delegate_.get();
}
PlatformVerificationFlow::PlatformVerificationFlow(
AttestationFlow* attestation_flow,
cryptohome::AsyncMethodCaller* async_caller,
CryptohomeClient* cryptohome_client,
UserManager* user_manager,
system::StatisticsProvider* statistics_provider,
Delegate* delegate)
: attestation_flow_(attestation_flow),
async_caller_(async_caller),
cryptohome_client_(cryptohome_client),
user_manager_(user_manager),
statistics_provider_(statistics_provider),
delegate_(delegate),
testing_prefs_(NULL),
weak_factory_(this) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
}
PlatformVerificationFlow::~PlatformVerificationFlow() {
}
void PlatformVerificationFlow::ChallengePlatformKey(
content::WebContents* web_contents,
const std::string& service_id,
const std::string& challenge,
const ChallengeCallback& callback) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
if (!IsAttestationEnabled(web_contents)) {
LOG(INFO) << "PlatformVerificationFlow: Feature disabled.";
ReportError(callback, POLICY_REJECTED);
return;
}
BoolDBusMethodCallback dbus_callback = base::Bind(
&DBusCallback,
base::Bind(&PlatformVerificationFlow::CheckConsent,
weak_factory_.GetWeakPtr(),
web_contents,
service_id,
challenge,
callback),
base::Bind(&ReportError, callback, INTERNAL_ERROR));
cryptohome_client_->TpmAttestationIsEnrolled(dbus_callback);
}
void PlatformVerificationFlow::CheckPlatformState(
const base::Callback<void(bool result)>& callback) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
std::string stat_value;
if (!statistics_provider_->GetMachineStatistic(system::kDevSwitchBootMode,
&stat_value)) {
LOG(ERROR) << __func__ << ": Failed to get boot mode statistic.";
callback.Run(false);
return;
}
if (stat_value != "0") {
LOG(INFO) << __func__ << ": Statistic indicates developer mode.";
callback.Run(false);
return;
}
BoolDBusMethodCallback dbus_callback = base::Bind(
&DBusCallback,
callback,
base::Bind(callback, false));
cryptohome_client_->TpmAttestationIsPrepared(dbus_callback);
}
void PlatformVerificationFlow::CheckConsent(content::WebContents* web_contents,
const std::string& service_id,
const std::string& challenge,
const ChallengeCallback& callback,
bool attestation_enrolled) {
ConsentType consent_type = CONSENT_TYPE_NONE;
if (!attestation_enrolled || IsFirstUse(web_contents)) {
consent_type = CONSENT_TYPE_ATTESTATION;
} else if (IsAlwaysAskRequired(web_contents)) {
consent_type = CONSENT_TYPE_ALWAYS;
}
Delegate::ConsentCallback consent_callback = base::Bind(
&PlatformVerificationFlow::OnConsentResponse,
weak_factory_.GetWeakPtr(),
web_contents,
service_id,
challenge,
callback,
consent_type);
if (consent_type == CONSENT_TYPE_NONE) {
consent_callback.Run(CONSENT_RESPONSE_NONE);
} else {
delegate_->ShowConsentPrompt(consent_type,
web_contents,
consent_callback);
}
}
void PlatformVerificationFlow::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* prefs) {
prefs->RegisterBooleanPref(prefs::kRAConsentFirstTime,
false,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
prefs->RegisterDictionaryPref(
prefs::kRAConsentDomains,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
prefs->RegisterBooleanPref(prefs::kRAConsentAlways,
false,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
}
void PlatformVerificationFlow::OnConsentResponse(
content::WebContents* web_contents,
const std::string& service_id,
const std::string& challenge,
const ChallengeCallback& callback,
ConsentType consent_type,
ConsentResponse consent_response) {
if (consent_type != CONSENT_TYPE_NONE) {
if (consent_response == CONSENT_RESPONSE_NONE) {
// No user response - do not proceed and do not modify any settings.
LOG(WARNING) << "PlatformVerificationFlow: No response from user.";
ReportError(callback, USER_REJECTED);
return;
}
if (!UpdateSettings(web_contents, consent_type, consent_response)) {
ReportError(callback, INTERNAL_ERROR);
return;
}
if (consent_response == CONSENT_RESPONSE_DENY) {
LOG(INFO) << "PlatformVerificationFlow: User rejected request.";
ReportError(callback, USER_REJECTED);
return;
}
}
// At this point all user interaction is complete and we can proceed with the
// certificate request.
AttestationFlow::CertificateCallback certificate_callback = base::Bind(
&PlatformVerificationFlow::OnCertificateReady,
weak_factory_.GetWeakPtr(),
service_id,
challenge,
callback);
attestation_flow_->GetCertificate(
PROFILE_CONTENT_PROTECTION_CERTIFICATE,
user_manager_->GetActiveUser()->email(),
service_id,
false, // Don't force a new key.
certificate_callback);
}
void PlatformVerificationFlow::OnCertificateReady(
const std::string& service_id,
const std::string& challenge,
const ChallengeCallback& callback,
bool operation_success,
const std::string& certificate) {
if (!operation_success) {
LOG(WARNING) << "PlatformVerificationFlow: Failed to certify platform.";
ReportError(callback, PLATFORM_NOT_VERIFIED);
return;
}
cryptohome::AsyncMethodCaller::DataCallback cryptohome_callback = base::Bind(
&PlatformVerificationFlow::OnChallengeReady,
weak_factory_.GetWeakPtr(),
certificate,
challenge,
callback);
std::string key_name = kContentProtectionKeyPrefix;
key_name += service_id;
async_caller_->TpmAttestationSignSimpleChallenge(KEY_USER,
key_name,
challenge,
cryptohome_callback);
}
void PlatformVerificationFlow::OnChallengeReady(
const std::string& certificate,
const std::string& challenge,
const ChallengeCallback& callback,
bool operation_success,
const std::string& response_data) {
if (!operation_success) {
LOG(ERROR) << "PlatformVerificationFlow: Failed to sign challenge.";
ReportError(callback, INTERNAL_ERROR);
return;
}
SignedData signed_data_pb;
if (response_data.empty() || !signed_data_pb.ParseFromString(response_data)) {
LOG(ERROR) << "PlatformVerificationFlow: Failed to parse response data.";
ReportError(callback, INTERNAL_ERROR);
return;
}
callback.Run(SUCCESS,
signed_data_pb.data(),
signed_data_pb.signature(),
certificate);
LOG(INFO) << "PlatformVerificationFlow: Platform successfully verified.";
}
PrefService* PlatformVerificationFlow::GetPrefs(
content::WebContents* web_contents) {
if (testing_prefs_)
return testing_prefs_;
return user_prefs::UserPrefs::Get(web_contents->GetBrowserContext());
}
const GURL& PlatformVerificationFlow::GetURL(
content::WebContents* web_contents) {
if (!testing_url_.is_empty())
return testing_url_;
return web_contents->GetLastCommittedURL();
}
bool PlatformVerificationFlow::IsAttestationEnabled(
content::WebContents* web_contents) {
// Check the device policy for the feature.
bool enabled_for_device = false;
if (!CrosSettings::Get()->GetBoolean(kAttestationForContentProtectionEnabled,
&enabled_for_device)) {
LOG(ERROR) << "Failed to get device setting.";
return false;
}
if (!enabled_for_device)
return false;
// Check the user preference for the feature.
PrefService* pref_service = GetPrefs(web_contents);
if (!pref_service) {
LOG(ERROR) << "Failed to get user prefs.";
return false;
}
if (!pref_service->GetBoolean(prefs::kEnableDRM))
return false;
// Check the user preference for this domain.
bool enabled_for_domain = false;
bool found = GetDomainPref(web_contents, &enabled_for_domain);
return (!found || enabled_for_domain);
}
bool PlatformVerificationFlow::IsFirstUse(content::WebContents* web_contents) {
PrefService* pref_service = GetPrefs(web_contents);
if (!pref_service) {
LOG(ERROR) << "Failed to get user prefs.";
return true;
}
return !pref_service->GetBoolean(prefs::kRAConsentFirstTime);
}
bool PlatformVerificationFlow::IsAlwaysAskRequired(
content::WebContents* web_contents) {
PrefService* pref_service = GetPrefs(web_contents);
if (!pref_service) {
LOG(ERROR) << "Failed to get user prefs.";
return true;
}
if (!pref_service->GetBoolean(prefs::kRAConsentAlways))
return false;
// Show the consent UI if the user has not already explicitly allowed or
// denied for this domain.
return !GetDomainPref(web_contents, NULL);
}
bool PlatformVerificationFlow::UpdateSettings(
content::WebContents* web_contents,
ConsentType consent_type,
ConsentResponse consent_response) {
PrefService* pref_service = GetPrefs(web_contents);
if (!pref_service) {
LOG(ERROR) << "Failed to get user prefs.";
return false;
}
if (consent_type == CONSENT_TYPE_ATTESTATION) {
if (consent_response == CONSENT_RESPONSE_DENY) {
pref_service->SetBoolean(prefs::kEnableDRM, false);
} else if (consent_response == CONSENT_RESPONSE_ALLOW) {
pref_service->SetBoolean(prefs::kRAConsentFirstTime, true);
RecordDomainConsent(web_contents, true);
} else if (consent_response == CONSENT_RESPONSE_ALWAYS_ASK) {
pref_service->SetBoolean(prefs::kRAConsentFirstTime, true);
pref_service->SetBoolean(prefs::kRAConsentAlways, true);
RecordDomainConsent(web_contents, true);
}
} else if (consent_type == CONSENT_TYPE_ALWAYS) {
bool allowed = (consent_response == CONSENT_RESPONSE_ALLOW ||
consent_response == CONSENT_RESPONSE_ALWAYS_ASK);
RecordDomainConsent(web_contents, allowed);
}
return true;
}
bool PlatformVerificationFlow::GetDomainPref(
content::WebContents* web_contents,
bool* pref_value) {
PrefService* pref_service = GetPrefs(web_contents);
CHECK(pref_service);
base::DictionaryValue::Iterator iter(
*pref_service->GetDictionary(prefs::kRAConsentDomains));
const GURL& url = GetURL(web_contents);
while (!iter.IsAtEnd()) {
if (url.DomainIs(iter.key().c_str())) {
if (pref_value) {
if (!iter.value().GetAsBoolean(pref_value)) {
LOG(ERROR) << "Unexpected pref type.";
*pref_value = false;
}
}
return true;
}
iter.Advance();
}
return false;
}
void PlatformVerificationFlow::RecordDomainConsent(
content::WebContents* web_contents,
bool allow_domain) {
PrefService* pref_service = GetPrefs(web_contents);
CHECK(pref_service);
DictionaryPrefUpdate updater(pref_service, prefs::kRAConsentDomains);
const GURL& url = GetURL(web_contents);
updater->SetBoolean(url.host(), allow_domain);
}
} // namespace attestation
} // namespace chromeos
| 36.247642 | 80 | 0.704145 | kurli |
4a8743d525979612620674f14049f851d2af8ceb | 7,744 | cpp | C++ | source/core/mining-manager/suffix-match-manager/SuffixMatchMiningTask.cpp | izenecloud/sf1r-lite | 8de9aa83c38c9cd05a80b216579552e89609f136 | [
"Apache-2.0"
] | 77 | 2015-02-12T20:59:20.000Z | 2022-03-05T18:40:49.000Z | source/core/mining-manager/suffix-match-manager/SuffixMatchMiningTask.cpp | fytzzh/sf1r-lite | 8de9aa83c38c9cd05a80b216579552e89609f136 | [
"Apache-2.0"
] | 1 | 2017-04-28T08:55:47.000Z | 2017-07-10T10:10:53.000Z | source/core/mining-manager/suffix-match-manager/SuffixMatchMiningTask.cpp | fytzzh/sf1r-lite | 8de9aa83c38c9cd05a80b216579552e89609f136 | [
"Apache-2.0"
] | 33 | 2015-01-05T03:03:05.000Z | 2022-02-06T04:22:46.000Z | #include "SuffixMatchMiningTask.hpp"
#include <document-manager/DocumentManager.h>
#include <boost/filesystem.hpp>
#include <glog/logging.h>
#include <icma/icma.h>
#include <la-manager/KNlpWrapper.h>
#include <la-manager/LAPool.h>
#include <mining-manager/util/split_ustr.h>
#include <util/ustring/UString.h>
#include "FilterManager.h"
#include "FMIndexManager.h"
#include <fstream>
#include <boost/lexical_cast.hpp>
namespace sf1r
{
SuffixMatchMiningTask::SuffixMatchMiningTask(
boost::shared_ptr<DocumentManager>& document_manager,
boost::shared_ptr<FMIndexManager>& fmi_manager,
boost::shared_ptr<FilterManager>& filter_manager,
std::string data_root_path,
boost::shared_mutex& mutex)
: isRtypeIncremental_(false)
, document_manager_(document_manager)
, fmi_manager_(fmi_manager)
, filter_manager_(filter_manager)
, data_root_path_(data_root_path)
, is_incrememtalTask_(false)
, mutex_(mutex)
{
}
SuffixMatchMiningTask::~SuffixMatchMiningTask()
{
}
bool SuffixMatchMiningTask::preProcess(int64_t timestamp)
{
if (!is_incrememtalTask_)
{
new_filter_manager.reset(new FilterManager(document_manager_, filter_manager_->getGroupManager(), data_root_path_,
filter_manager_->getAttrManager(), filter_manager_->getNumericTableBuilder()));
new_filter_manager->copyPropertyInfo(filter_manager_);
new_filter_manager->generatePropertyId();
new_fmi_manager.reset(new FMIndexManager(data_root_path_,
document_manager_,
new_filter_manager,
fmi_manager_->getFuzzyNormalizer()));
std::vector<std::string> properties;
VirtualConfig virtulProperty;
for (int i = 0; i < FMIndexManager::FM_TYPE_COUNT; ++i)
{
fmi_manager_->getProperties(properties, (FMIndexManager::PropertyFMType)i);
fmi_manager_->getVirtualProperty(virtulProperty);
new_fmi_manager->addProperties(properties, (FMIndexManager::PropertyFMType)i);
new_fmi_manager->setVirtualProperty(virtulProperty);
std::vector<std::string>().swap(properties);
}
size_t last_docid = fmi_manager_ ? fmi_manager_->docCount() : 0;
need_rebuild = false;
std::vector<uint32_t> del_docid_list;
document_manager_->getDeletedDocIdList(del_docid_list);
if (last_docid == document_manager_->getMaxDocId())
{
// check if there is any new deleted doc.
std::vector<size_t> doclen_list(del_docid_list.size(), 0);
fmi_manager_->getDocLenList(del_docid_list, doclen_list);
for (size_t i = 0; i < doclen_list.size(); ++i)
{
if (doclen_list[i] > 0)
{
need_rebuild = true;
break;
}
}
if (!need_rebuild)
{
/*
@brief : in here document_manager_->isThereRtypePro() just means for the -R SCD,
because the Rtype doc in -U SCD is not in this flow.
*/
if (document_manager_->isThereRtypePro())
{
LOG (INFO) << "Update for R-type SCD" << endl;
const std::vector<std::pair<int32_t, std::string> >& prop_list = filter_manager_->getProp_list();
for (std::vector<std::pair<int32_t, std::string> >::const_iterator i = prop_list.begin(); i != prop_list.end(); ++i)
{
std::set<string>::iterator iter = document_manager_->RtypeDocidPros_.find((*i).second);
if (iter == document_manager_->RtypeDocidPros_.end())
{
if (!filter_manager_->isNumericProp((*i).second) && !filter_manager_->isDateProp((*i).second))
{
new_filter_manager->addUnchangedProperty((*i).second);
LOG (INFO) << "Add Unchanged property : " << (*i).second << endl;
}
}
}
}
else
{
LOG (INFO) << "All filter properties do not need rebuild ... " << endl;
return false;
}
}
}
else
{
LOG(INFO) << "old fmi docCount is : " << last_docid << ", document_manager count:" << document_manager_->getMaxDocId();
need_rebuild = true;
}
if (need_rebuild)
{
LOG(INFO) << "rebuilding in fm-index is needed.";
}
else
{
new_fmi_manager->useOldDocCount(fmi_manager_.get());
}
bool isInitAndLoad = true;
if (!need_rebuild) return true;
if (!new_fmi_manager->initAndLoadOldDocs(fmi_manager_.get()))
{
LOG(ERROR) << "fmindex init building failed, must stop. ";
new_fmi_manager->clearFMIData();
isInitAndLoad = false;
}
if (!isInitAndLoad) return false;
}
return true;
}
bool SuffixMatchMiningTask::postProcess()
{
if (!is_incrememtalTask_)
{
if (need_rebuild && !new_fmi_manager->buildCollectionAfter())
return false;
new_filter_manager->setRebuildFlag(filter_manager_.get());
size_t last_docid = fmi_manager_ ? fmi_manager_->docCount() : 0;
new_filter_manager->finishBuildStringFilters();
new_filter_manager->buildFilters(last_docid, document_manager_->getMaxDocId());
new_fmi_manager->setFilterList(new_filter_manager->getFilterList());
LOG(INFO) << "building filter data finished";
new_fmi_manager->buildLessDVProperties();
new_fmi_manager->buildExternalFilter(); //although here is empty ... but it will swap Unchanged Filter ...
{
WriteLock lock(mutex_);
if (!need_rebuild)
{
// no rebuilding, so just take the owner of old data.
LOG(INFO) << "no rebuild need, just swap data for common properties.";
new_fmi_manager->swapCommonProperties(fmi_manager_.get());
new_fmi_manager->swapUnchangedFilter(fmi_manager_.get());
new_filter_manager->swapUnchangedFilter(filter_manager_.get());
new_filter_manager->clearUnchangedProperties();
}
fmi_manager_.swap(new_fmi_manager);
filter_manager_.swap(new_filter_manager);
filter_manager_->clearRebuildFlag();
new_fmi_manager.reset();
new_filter_manager.reset();
}
LOG(INFO) << "saving fm-index data";
fmi_manager_->saveAll();
filter_manager_->saveFilterId();
filter_manager_->clearFilterList();
LOG(INFO) << "building fm-index finished";
}
return true;
}
bool SuffixMatchMiningTask::buildDocument(docid_t docID, const Document& doc)
{
if (!is_incrememtalTask_ && !isRtypeIncremental_)
{
bool failed = (doc.getId() == 0);
new_fmi_manager->appendDocsAfter(failed, doc);
if (!failed)
{
new_filter_manager->buildStringFiltersForDoc(docID, doc);
}
}
return true;
}
docid_t SuffixMatchMiningTask::getLastDocId()
{
return fmi_manager_ ? fmi_manager_->docCount() + 1 : 1;
}
void SuffixMatchMiningTask::setTaskStatus(bool is_incrememtalTask)
{
is_incrememtalTask_ = is_incrememtalTask;
}
}
| 36.018605 | 136 | 0.58626 | izenecloud |
4a88056dc75fcc250ddeaff290464f9d7946f921 | 2,606 | cpp | C++ | apps/unit_tests/test_fft_correctness_2.cpp | lzhang714/SIRIUS-develop | c07eefe995c417fb4247e8ddaf138784189523be | [
"BSD-2-Clause"
] | 1 | 2021-01-22T20:02:42.000Z | 2021-01-22T20:02:42.000Z | apps/unit_tests/test_fft_correctness_2.cpp | lzhang714/SIRIUS-develop | c07eefe995c417fb4247e8ddaf138784189523be | [
"BSD-2-Clause"
] | null | null | null | apps/unit_tests/test_fft_correctness_2.cpp | lzhang714/SIRIUS-develop | c07eefe995c417fb4247e8ddaf138784189523be | [
"BSD-2-Clause"
] | null | null | null | #include <sirius.h>
/* test FFT: tranfrom random function to real space, transfrom back and compare with the original function */
using namespace sirius;
int test_fft_complex(cmd_args& args, device_t fft_pu__)
{
double cutoff = args.value<double>("cutoff", 40);
matrix3d<double> M = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
auto fft_grid = get_min_fft_grid(cutoff, M);
auto spl_z = split_fft_z(fft_grid[2], Communicator::world());
Gvec gvec(M, cutoff, Communicator::world(), false);
Gvec_partition gvp(gvec, Communicator::world(), Communicator::self());
spfft::Grid spfft_grid(fft_grid[0], fft_grid[1], fft_grid[2], gvp.zcol_count_fft(), spl_z.local_size(),
SPFFT_PU_HOST, -1, Communicator::world().mpi_comm(), SPFFT_EXCH_DEFAULT);
const auto fft_type = gvec.reduced() ? SPFFT_TRANS_R2C : SPFFT_TRANS_C2C;
auto gv = gvp.get_gvec();
spfft::Transform spfft(spfft_grid.create_transform(SPFFT_PU_HOST, fft_type, fft_grid[0], fft_grid[1], fft_grid[2],
spl_z.local_size(), gvp.gvec_count_fft(), SPFFT_INDEX_TRIPLETS,
gv.at(memory_t::host)));
mdarray<double_complex, 1> f(gvp.gvec_count_fft());
for (int ig = 0; ig < gvp.gvec_count_fft(); ig++) {
f[ig] = utils::random<double_complex>();
}
mdarray<double_complex, 1> g(gvp.gvec_count_fft());
spfft.backward(reinterpret_cast<double const*>(&f[0]), spfft.processing_unit());
spfft.forward(spfft.processing_unit(), reinterpret_cast<double*>(&g[0]), SPFFT_FULL_SCALING);
double diff{0};
for (int ig = 0; ig < gvp.gvec_count_fft(); ig++) {
diff += std::pow(std::abs(f[ig] - g[ig]), 2);
}
Communicator::world().allreduce(&diff, 1);
diff = std::sqrt(diff / gvec.num_gvec());
if (diff > 1e-10) {
return 1;
} else {
return 0;
}
}
int run_test(cmd_args& args)
{
int result = test_fft_complex(args, device_t::CPU);
#ifdef __GPU
result += test_fft_complex(args, device_t::GPU);
#endif
return result;
}
int main(int argn, char **argv)
{
cmd_args args;
args.register_key("--cutoff=", "{double} cutoff radius in G-space");
args.parse_args(argn, argv);
if (args.exist("help")) {
printf("Usage: %s [options]\n", argv[0]);
args.print_help();
return 0;
}
sirius::initialize(true);
printf("running %-30s : ", argv[0]);
int result = run_test(args);
if (result) {
printf("\x1b[31m" "Failed" "\x1b[0m" "\n");
} else {
printf("\x1b[32m" "OK" "\x1b[0m" "\n");
}
sirius::finalize();
return result;
}
| 29.954023 | 118 | 0.625096 | lzhang714 |
4a88a44501e658620eeb7fe00f467dd82ca1e35f | 212 | cpp | C++ | sw-src/test/test_client.cpp | jijinfanhua/IPSA-ipbm | c82dc003bf9c68ba029814d7539f502fd29e1326 | [
"Apache-2.0"
] | null | null | null | sw-src/test/test_client.cpp | jijinfanhua/IPSA-ipbm | c82dc003bf9c68ba029814d7539f502fd29e1326 | [
"Apache-2.0"
] | null | null | null | sw-src/test/test_client.cpp | jijinfanhua/IPSA-ipbm | c82dc003bf9c68ba029814d7539f502fd29e1326 | [
"Apache-2.0"
] | null | null | null | //
// Created by xilinx_0 on 1/14/22.
//
#include <iostream>
#include "test_client.h"
int main() {
// std::cout << cup->a << std::endl;
cup->a = 4;
std::cout << cup->a << std::endl;
return 0;
}
| 14.133333 | 39 | 0.533019 | jijinfanhua |
4a8a504e35af0eb7bae4b015eb43ef14c85c0cdc | 2,435 | cpp | C++ | B2G/gecko/other-licenses/7zstub/src/Windows/FileName.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | B2G/gecko/other-licenses/7zstub/src/Windows/FileName.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | null | null | null | B2G/gecko/other-licenses/7zstub/src/Windows/FileName.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | // Windows/FileName.cpp
#include "StdAfx.h"
#include "Windows/FileName.h"
#include "Common/Wildcard.h"
namespace NWindows {
namespace NFile {
namespace NName {
static const wchar_t kDiskDelimiter = L':';
/*
static bool IsCharAPrefixDelimiter(wchar_t c)
{ return (c == kDirDelimiter || c == kDiskDelimiter); }
*/
void NormalizeDirPathPrefix(CSysString &dirPath)
{
if (dirPath.IsEmpty())
return;
if (dirPath.ReverseFind(kDirDelimiter) != dirPath.Length() - 1)
dirPath += kDirDelimiter;
}
#ifndef _UNICODE
void NormalizeDirPathPrefix(UString &dirPath)
{
if (dirPath.IsEmpty())
return;
if (dirPath.ReverseFind(wchar_t(kDirDelimiter)) != dirPath.Length() - 1)
dirPath += wchar_t(kDirDelimiter);
}
#endif
namespace NPathType
{
EEnum GetPathType(const UString &path)
{
if (path.Length() <= 2)
return kLocal;
if (path[0] == kDirDelimiter && path[1] == kDirDelimiter)
return kUNC;
return kLocal;
}
}
void CParsedPath::ParsePath(const UString &path)
{
int curPos = 0;
switch (NPathType::GetPathType(path))
{
case NPathType::kLocal:
{
int posDiskDelimiter = path.Find(kDiskDelimiter);
if(posDiskDelimiter >= 0)
{
curPos = posDiskDelimiter + 1;
if (path.Length() > curPos)
if(path[curPos] == kDirDelimiter)
curPos++;
}
break;
}
case NPathType::kUNC:
{
int curPos = path.Find(kDirDelimiter, 2);
if(curPos < 0)
curPos = path.Length();
else
curPos++;
}
}
Prefix = path.Left(curPos);
SplitPathToParts(path.Mid(curPos), PathParts);
}
UString CParsedPath::MergePath() const
{
UString result = Prefix;
for(int i = 0; i < PathParts.Size(); i++)
{
if (i != 0)
result += kDirDelimiter;
result += PathParts[i];
}
return result;
}
const wchar_t kExtensionDelimiter = L'.';
void SplitNameToPureNameAndExtension(const UString &fullName,
UString &pureName, UString &extensionDelimiter, UString &extension)
{
int index = fullName.ReverseFind(kExtensionDelimiter);
if (index < 0)
{
pureName = fullName;
extensionDelimiter.Empty();
extension.Empty();
}
else
{
pureName = fullName.Left(index);
extensionDelimiter = kExtensionDelimiter;
extension = fullName.Mid(index + 1);
}
}
}}}
| 21.741071 | 75 | 0.617248 | wilebeast |
4a8d78519d0a45746d6dc0bec068d0db8febe0db | 2,665 | cpp | C++ | course_project/ruledsurfacebycardinalspline.cpp | Dukend/Computer-graphics | b8a575f3e56e49399d2be1c62ebb96e85236971f | [
"MIT"
] | null | null | null | course_project/ruledsurfacebycardinalspline.cpp | Dukend/Computer-graphics | b8a575f3e56e49399d2be1c62ebb96e85236971f | [
"MIT"
] | null | null | null | course_project/ruledsurfacebycardinalspline.cpp | Dukend/Computer-graphics | b8a575f3e56e49399d2be1c62ebb96e85236971f | [
"MIT"
] | null | null | null | #include "ruledsurfacebycardinalspline.h"
RuledSurfaceByCardinalSpline::RuledSurfaceByCardinalSpline()
{
QObject::connect(&fLine, SIGNAL(splineChanged()), this, SLOT(acceptChanges()));
QObject::connect(&sLine, SIGNAL(splineChanged()), this, SLOT(acceptChanges()));
setFrameColor(Qt::black);
setMaterialColor(Qt::blue);
}
void RuledSurfaceByCardinalSpline::setPrecision(float p){
if(precision != p){
precision = p;
emit surfaceChanged();
}
}
float RuledSurfaceByCardinalSpline::getPrecision(){
return precision;
}
void RuledSurfaceByCardinalSpline::paint(){
if(fLine.isValid() && sLine.isValid()){
fLine.calculate();
sLine.calculate();
if(fLine.getSegments().size() > sLine.getSegments().size()){
paintLine(fLine, bufferFLinePoints, precision);
paintLine(sLine, bufferSLinePoints, precision * (float)fLine.getSegments().size()/(float)sLine.getSegments().size());
} else{
paintLine(fLine, bufferFLinePoints, precision * (float)sLine.getSegments().size()/(float)fLine.getSegments().size());
paintLine(sLine, bufferSLinePoints, precision);
}
while(bufferFLinePoints.size() < bufferSLinePoints.size())
bufferFLinePoints.push_back(fLine.getSegments().back().calculatePoint(1));
while(bufferFLinePoints.size() > bufferSLinePoints.size())
bufferSLinePoints.push_back(sLine.getSegments().back().calculatePoint(1));
for(int i = 0;i<bufferFLinePoints.size()-1;++i){
/*
addPolygon(bufferFLinePoints[i], bufferFLinePoints[i+1], bufferSLinePoints[i]);
addPolygon(bufferFLinePoints[i+1], bufferSLinePoints[i+1], bufferSLinePoints[i]);
*/
addPolygon(bufferFLinePoints[i], bufferSLinePoints[i],bufferFLinePoints[i+1]);
addPolygon(bufferFLinePoints[i+1],bufferSLinePoints[i], bufferSLinePoints[i+1]);
}
}
}
void RuledSurfaceByCardinalSpline::acceptChanges(){
emit surfaceChanged();
}
void RuledSurfaceByCardinalSpline::paintLine(CardinalSplineClass& line, QVector<QVector3D>& buffer, float pres){
buffer.clear();
auto& segments = line.getSegments();
float step = 1/pres;
QVector3D p;
for(int i = 0;i<segments.size(); ++i){
for(float s = 0; s < 1; s+= step){
p = segments[i].calculatePoint(s);
buffer.push_back(p);
}
}
p = segments.back().calculatePoint(1);
buffer.push_back(p);
}
void RuledSurfaceByCardinalSpline::recievePrecision(int p){
setPrecision(p);
}
| 38.071429 | 130 | 0.644653 | Dukend |
4a8f7d80227ed94b1e7fb6fff07021344469f7b3 | 432 | hpp | C++ | addons/external_intercom/ACEActions.hpp | severgun/task-force-arma-3-radio | 1379327a6ff71948dae692ca7a43876c9031e90e | [
"RSA-MD"
] | null | null | null | addons/external_intercom/ACEActions.hpp | severgun/task-force-arma-3-radio | 1379327a6ff71948dae692ca7a43876c9031e90e | [
"RSA-MD"
] | null | null | null | addons/external_intercom/ACEActions.hpp | severgun/task-force-arma-3-radio | 1379327a6ff71948dae692ca7a43876c9031e90e | [
"RSA-MD"
] | null | null | null | #define ADD_PLAYER_SELF_ACTIONS \
class ACE_SelfActions { \
class TFAR_Radio { \
condition = QUOTE((([] call TFAR_fnc_haveSWRadio) || {([] call TFAR_fnc_haveLRRadio) || !isNil {_player getVariable 'TFAR_ExternalIntercomVehicle'}})); \
insertChildren = QUOTE(([_player] call tfar_core_fnc_getOwnRadiosChildren) + (call TFAR_external_intercom_fnc_addWirelessIntercomMenu)); \
statement = " "; \
}; \
}
| 48 | 161 | 0.703704 | severgun |
4a903cd45a15239be1b0a55f4d1c6085d9eac6a8 | 1,791 | cpp | C++ | Engine/Dependencies/Celero/src/Timer.cpp | colinhect/hect | 2ef89be60ba9d450c5b56f5be6cef9803cc1855a | [
"MIT"
] | 2 | 2015-01-17T00:56:34.000Z | 2015-12-01T07:02:47.000Z | Engine/Dependencies/Celero/src/Timer.cpp | colinhect/hect | 2ef89be60ba9d450c5b56f5be6cef9803cc1855a | [
"MIT"
] | 63 | 2015-01-06T17:42:22.000Z | 2017-09-10T00:21:52.000Z | Engine/Dependencies/Celero/src/Timer.cpp | colinhect/hect | 2ef89be60ba9d450c5b56f5be6cef9803cc1855a | [
"MIT"
] | null | null | null | ///
/// \author John Farrier
///
/// \copyright Copyright 2015 John Farrier
///
/// 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 <celero/Timer.h>
#include <celero/Print.h>
#ifdef WIN32
#include <Windows.h>
LARGE_INTEGER QPCFrequency;
#else
#include <chrono>
#endif
#include <iostream>
uint64_t celero::timer::GetSystemTime()
{
#ifdef WIN32
LARGE_INTEGER timeStorage;
QueryPerformanceCounter(&timeStorage);
return static_cast<uint64_t>(timeStorage.QuadPart * 1000000)/static_cast<uint64_t>(QPCFrequency.QuadPart);
#else
auto timePoint = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::microseconds>(timePoint.time_since_epoch()).count();
#endif
}
double celero::timer::ConvertSystemTime(uint64_t x)
{
return x * 1.0e-6;
}
void celero::timer::CachePerformanceFrequency()
{
std::cout << "Timer resolution: ";
#ifdef WIN32
QueryPerformanceFrequency(&QPCFrequency);
auto precision = ((1.0/static_cast<double>(QPCFrequency.QuadPart)) * 1000000.0);
#else
auto precision = (static_cast<double>(std::chrono::high_resolution_clock::period::num) /
static_cast<double>(std::chrono::high_resolution_clock::period::den)) * 1000000.0;
#endif
std::cout << std::to_string(precision) << " us\n";
}
| 28.887097 | 108 | 0.731993 | colinhect |
4a918c4b2908814fd4957711da9745ba73fe4e0a | 6,196 | cc | C++ | Graphs/OpenGL/GL_FBO.cc | TrevorShelton/cplot | 8bf40e94519cc4fd69b2e0677d3a3dcf8695245a | [
"MIT"
] | 32 | 2017-11-27T03:04:44.000Z | 2022-01-21T17:03:40.000Z | Graphs/OpenGL/GL_FBO.cc | TrevorShelton/cplot | 8bf40e94519cc4fd69b2e0677d3a3dcf8695245a | [
"MIT"
] | 30 | 2017-11-10T09:47:16.000Z | 2018-11-21T22:36:47.000Z | Graphs/OpenGL/GL_FBO.cc | TrevorShelton/cplot | 8bf40e94519cc4fd69b2e0677d3a3dcf8695245a | [
"MIT"
] | 20 | 2018-01-05T17:15:11.000Z | 2021-07-30T14:11:01.000Z | #include "GL_FBO.h"
#include <cassert>
#ifdef TXDEBUG
#define DEBUG_TEXTURES(x) std::cerr << x << std::endl
#else
#define DEBUG_TEXTURES(x)
#endif
bool GL_FBO::init(GL_Context context, unsigned w_, unsigned h_, int bpp, bool depth_buffer)
{
assert(context);
GL_CHECK;
bool ok = (w_ > 0 && h_ > 0);
if (ok && !fbo)
{
glGenFramebuffers(1, &fbo);
if (!fbo) ok = false;
DEBUG_TEXTURES("Allocating FBO: " << fbo);
}
if (w > 0 && h > 0)
{
if (depth && (!ok || !depth_buffer || w != w_ || h != h_))
{
DEBUG_TEXTURES("Releasing FBO depth (" << w << " x " << h << ")");
context.delete_texture(depth);
depth = 0;
}
if (texture && (!ok || w != w_ || h != h_))
{
DEBUG_TEXTURES("Releasing FBO texture (" << w << " x " << h << ")");
context.delete_texture(texture);
texture = 0;
w = h = 0;
}
}
assert(texture || !depth); // if texture was released, depth buffer was too
if (ok && !texture)
{
glGenTextures(1, &texture);
if (!texture) ok = false;
DEBUG_TEXTURES("Allocating FBO texture id: " << texture);
}
if (ok && depth_buffer && !depth)
{
glGenTextures(1, &depth);
if (!depth) ok = false;
DEBUG_TEXTURES("Allocating FBO depth id: " << depth);
}
GL_CHECK;
if (ok && (w != w_ || h != h_))
{
assert(w == 0 && h == 0);
w = w_;
h = h_;
DEBUG_TEXTURES("Allocating FBO texture data (" << w << " x " << h << ")");
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glBindTexture(GL_TEXTURE_2D, texture);
switch (bpp)
{
case 8: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL); break;
case 16: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, w, h, 0, GL_BGRA, GL_HALF_FLOAT_ARB, NULL); break;
//case 16: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16, w, h, 0, GL_BGRA, GL_UNSIGNED_SHORT, NULL); break;
case 32: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, w, h, 0, GL_BGRA, GL_FLOAT, NULL); break;
default: assert(false); ok = false; break;
}
if (ok)
{
glBindTexture (GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE)
{
ok = false;
DEBUG_TEXTURES("Failed with code " << status);
}
}
if (ok && depth_buffer)
{
DEBUG_TEXTURES("Allocating FBO depth data (" << w << " x " << h << ")");
GL_CHECK;
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glBindTexture(GL_TEXTURE_2D, depth);
glTexImage2D (GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, w, h, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);
GL_CHECK;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
GL_CHECK;
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
GL_CHECK;
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE)
{
ok = false;
DEBUG_TEXTURES("Failed with code " << status);
}
}
}
GL_CHECK;
if (!ok)
{
if (fbo)
{
DEBUG_TEXTURES("Releasing FBO: " << fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, &fbo);
fbo = 0;
}
if (depth)
{
DEBUG_TEXTURES("Releasing FBO depth data (" << w << " x " << h << ")");
context.delete_texture(depth);
depth = 0;
}
if (texture)
{
DEBUG_TEXTURES("Releasing FBO texture data (" << w << " x " << h << ")");
context.delete_texture(texture);
texture = 0;
w = h = 0;
}
}
GL_CHECK;
return ok || (w_ == 0 || h_ == 0);
}
void GL_FBO::bind() const
{
assert(fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
}
void GL_FBO::draw(bool blend, float factor) const
{
assert(fbo && texture);
if (!fbo || !texture){ assert(false); return; }
glMatrixMode(GL_TEXTURE); glLoadIdentity();
glMatrixMode(GL_MODELVIEW); glLoadIdentity();
glMatrixMode(GL_PROJECTION); glLoadIdentity();
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
glDisable(GL_DEPTH_TEST);
if (blend)
{
glEnable(GL_BLEND);
if (factor < 1.0f-1e-8)
{
glBlendColor(0.0f, 0.0f, 0.0f, factor);
glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE);
}
else
{
glBlendFunc(GL_ONE, GL_ONE);
}
}
else if (factor < 1.0f-1e-8)
{
glEnable(GL_BLEND);
glBlendColor(0.0f, 0.0f, 0.0f, factor);
glBlendFunc(GL_CONSTANT_ALPHA, GL_ZERO);
glBlendFunc(GL_ZERO, GL_CONSTANT_ALPHA);
}
else
{
glDisable(GL_BLEND);
}
glDisable(GL_LIGHTING);
glActiveTexture(GL_TEXTURE0);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(1.0f, 1.0f, 0.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(0.0f, 1.0f, 0.0f);
glEnd();
glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
}
void GL_FBO::acc_load(const GL_FBO &other, float factor)
{
if (factor < 1.0f-1e-8)
{
bind();
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
acc_add(other, factor);
}
else
{
bind();
glBindTexture(GL_TEXTURE_2D, texture);
other.bind();
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, w, h);
glBindTexture(GL_TEXTURE_2D, 0);
}
}
void GL_FBO::acc_add(const GL_FBO &other, float factor)
{
bind();
other.draw(true, factor);
other.bind();
}
| 25.924686 | 109 | 0.668173 | TrevorShelton |
4a93a40e263c5ac6e1428f34e9552bb928963986 | 1,083 | cpp | C++ | BOJ_solve/16602.cpp | python-programmer1512/Code_of_gunwookim | e72e6724fb9ee6ccf2e1064583956fa954ba0282 | [
"MIT"
] | 4 | 2021-01-27T11:51:30.000Z | 2021-01-30T17:02:55.000Z | BOJ_solve/16602.cpp | python-programmer1512/Code_of_gunwookim | e72e6724fb9ee6ccf2e1064583956fa954ba0282 | [
"MIT"
] | null | null | null | BOJ_solve/16602.cpp | python-programmer1512/Code_of_gunwookim | e72e6724fb9ee6ccf2e1064583956fa954ba0282 | [
"MIT"
] | 5 | 2021-01-27T11:46:12.000Z | 2021-05-06T05:37:47.000Z | #include <bits/stdc++.h>
#define x first
#define y second
#define pb push_back
#define all(v) v.begin(),v.end()
#pragma gcc optimize("O3")
#pragma gcc optimize("Ofast")
#pragma gcc optimize("unroll-loops")
using namespace std;
const int INF = 1e9;
const int TMX = 1 << 18;
const long long llINF = 5e18;
const long long mod = 1e9+7;
const long long hmod1 = 1e9+409;
const long long hmod2 = 1e9+433;
const long long base = 257;
typedef long long ll;
typedef long double ld;
typedef pair <int,int> pi;
typedef pair <ll,ll> pl;
typedef vector <int> vec;
typedef vector <pi> vecpi;
typedef long long ll;
int n,ti,ans,t[400005],ind[400005];
vec v[400005];
int main() {
ios_base::sync_with_stdio(false), cin.tie(0);
cin >> n;
for(int i = 1;i <= n;i++) {
int x,y; cin >> t[i] >> x;
for(;x--;) cin >> y, v[i].pb(y), ind[y]++;
}
priority_queue <pi> q;
for(int i = 1;i <= n;i++) {
if(!ind[i]) q.push({-t[i],i});
}
while(!q.empty()) {
pi x = q.top(); q.pop();
ans = max(ans,n-ti-1-x.x), ti++;
for(int i : v[x.y]) {
if(!--ind[i]) q.push({-t[i],i});
}
}
cout << ans;
} | 23.543478 | 46 | 0.611265 | python-programmer1512 |
4a94280f6546dd03a58e1186bf9d6c5b4990ddc5 | 782 | cpp | C++ | PAT_LevelA/1036_Boys_vs_Girls.cpp | MarkIlV/PAT_Answers | 89eacf085069dc03b684d431f51715c491dbb984 | [
"MIT"
] | null | null | null | PAT_LevelA/1036_Boys_vs_Girls.cpp | MarkIlV/PAT_Answers | 89eacf085069dc03b684d431f51715c491dbb984 | [
"MIT"
] | null | null | null | PAT_LevelA/1036_Boys_vs_Girls.cpp | MarkIlV/PAT_Answers | 89eacf085069dc03b684d431f51715c491dbb984 | [
"MIT"
] | null | null | null | #include "cstdio"
struct Stu{
char name[11];
char sex;
char id[11];
int grade;
}male,female,tmp;
int main() {
int n;
male.grade = 101;
female.grade = -1;
if (scanf("%d",&n)==1);
for (int i = 0; i < n; ++i) {
if (scanf("%s %c %s %d",tmp.name,&tmp.sex,tmp.id,&tmp.grade)==1);
if (tmp.sex=='M' && (tmp.grade < male.grade)) male = tmp;
if (tmp.sex=='F' && (tmp.grade > female.grade)) female = tmp;
}
if (female.grade == -1) printf("Absent\n");
else printf("%s %s\n",female.name,female.id);
if (male.grade == 101) printf("Absent\n");
else printf("%s %s\n",male.name,male.id);
if(female.grade == -1 || male.grade == 101) printf("NA");
else printf("%d",female.grade-male.grade);
return 0;
} | 24.4375 | 73 | 0.531969 | MarkIlV |
4a946ecb9d43117814d1c8b8c18b6fc8b861d0aa | 875 | cpp | C++ | CPP/ex_2.7.9_multidem.cpp | w1ld/StepikExercies | 3efe07819a0456aa3846587b2a23bad9dd9710db | [
"MIT"
] | 4 | 2019-05-11T17:26:24.000Z | 2022-01-30T17:48:25.000Z | CPP/ex_2.7.9_multidem.cpp | w1ld/StepikExercises | 3efe07819a0456aa3846587b2a23bad9dd9710db | [
"MIT"
] | null | null | null | CPP/ex_2.7.9_multidem.cpp | w1ld/StepikExercises | 3efe07819a0456aa3846587b2a23bad9dd9710db | [
"MIT"
] | 4 | 2019-01-24T22:15:21.000Z | 2020-12-21T10:23:52.000Z | #include <iostream>
using namespace std;
int ** transpose(const int * const * m, unsigned rows, unsigned cols)
{
int ** mt = new int * [cols];
mt[0] = new int[cols * rows];
for(unsigned i = 1; i != cols; i++) {
mt[i] = mt[i - 1] + rows;
}
for(unsigned i = 0; i < rows; i++) {
for(unsigned j = 0; j < cols; j++) {
mt[j][i] = m[i][j];
}
}
return mt;
}
int main() {
const unsigned rows = 3;
const unsigned cols = 2;
int ** m = new int * [rows];
m[0] = new int[cols * rows];
for(unsigned i = 1; i != rows; i++) {
m[i] = m[i - 1] + cols;
}
m[0][0] = 1;
m[0][1] = 2;
m[1][0] = 3;
m[1][1] = 4;
m[2][0] = 5;
m[2][1] = 6;
int ** mt = transpose((int**)m, rows, cols);
for(unsigned i = 0; i < cols; i++) {
for(unsigned j = 0; j < rows; j++) {
cout << mt[i][j] << ' ';
}
cout << endl;
}
}
| 19.886364 | 70 | 0.459429 | w1ld |
4a95d7da4590c9bb35efdf4007fbdd5002baf531 | 1,689 | cpp | C++ | Source/modules/serviceworkers/Response.cpp | quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit | 20e637e67a0c272870ae4d78466a68bcb77af041 | [
"BSD-3-Clause"
] | null | null | null | Source/modules/serviceworkers/Response.cpp | quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit | 20e637e67a0c272870ae4d78466a68bcb77af041 | [
"BSD-3-Clause"
] | null | null | null | Source/modules/serviceworkers/Response.cpp | quanganh2627/bytm-x64-L-w05-2015_external_chromium_org_third_party_WebKit | 20e637e67a0c272870ae4d78466a68bcb77af041 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "Response.h"
#include "bindings/v8/Dictionary.h"
#include "core/fileapi/Blob.h"
#include "modules/serviceworkers/ResponseInit.h"
#include "platform/NotImplemented.h"
#include "public/platform/WebServiceWorkerResponse.h"
namespace WebCore {
PassRefPtr<Response> Response::create(Blob* body, const Dictionary& responseInit)
{
RefPtr<BlobDataHandle> blobDataHandle = body ? body->blobDataHandle() : nullptr;
// FIXME: Maybe append or override content-length and content-type headers using the blob. The spec will clarify what to do:
// https://github.com/slightlyoff/ServiceWorker/issues/192
return adoptRef(new Response(blobDataHandle.release(), ResponseInit(responseInit)));
}
PassRefPtr<HeaderMap> Response::headers() const
{
// FIXME: Implement. Spec will eventually whitelist allowable headers.
return m_headers;
}
void Response::populateWebServiceWorkerResponse(blink::WebServiceWorkerResponse& response)
{
response.setStatus(status());
response.setStatusText(statusText());
response.setHeaders(m_headers->headerMap());
response.setBlobDataHandle(m_blobDataHandle);
}
Response::Response(PassRefPtr<BlobDataHandle> blobDataHandle, const ResponseInit& responseInit)
: m_status(responseInit.status)
, m_statusText(responseInit.statusText)
, m_headers(responseInit.headers)
, m_blobDataHandle(blobDataHandle)
{
ScriptWrappable::init(this);
if (!m_headers)
m_headers = HeaderMap::create();
}
} // namespace WebCore
| 32.480769 | 128 | 0.759029 | quanganh2627 |
4a9e53065f732e1ee8912b7cb0a5ed331289cc55 | 129 | cpp | C++ | tensorflow-yolo-ios/dependencies/eigen/unsupported/test/BVH.cpp | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 27 | 2017-06-07T19:07:32.000Z | 2020-10-15T10:09:12.000Z | tensorflow-yolo-ios/dependencies/eigen/unsupported/test/BVH.cpp | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 3 | 2017-08-25T17:39:46.000Z | 2017-11-18T03:40:55.000Z | tensorflow-yolo-ios/dependencies/eigen/unsupported/test/BVH.cpp | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 10 | 2017-06-16T18:04:45.000Z | 2018-07-05T17:33:01.000Z | version https://git-lfs.github.com/spec/v1
oid sha256:ccc4d628c6edaf86b7ac04d255d639790b9c39147a94e8d7950eba698898b910
size 7182
| 32.25 | 75 | 0.883721 | initialz |
4aa05e4d234e239b2a9a32382fee6d7dd4e33fcf | 1,047 | cpp | C++ | Back Tracking/gen-ip.cpp | richidubey/AwesomeDataStructuresAndAlgorithms | 356a43272c5898a4aa7b87bab8a02aa08cb81cd4 | [
"MIT"
] | 3 | 2018-11-15T07:59:13.000Z | 2021-07-20T02:06:28.000Z | Back Tracking/gen-ip.cpp | richidubey/AwesomeDataStructuresAndAlgorithms | 356a43272c5898a4aa7b87bab8a02aa08cb81cd4 | [
"MIT"
] | null | null | null | Back Tracking/gen-ip.cpp | richidubey/AwesomeDataStructuresAndAlgorithms | 356a43272c5898a4aa7b87bab8a02aa08cb81cd4 | [
"MIT"
] | 3 | 2018-11-15T06:39:53.000Z | 2021-07-20T02:09:18.000Z | set <string> sans;
void genip(string s,int dots,int mark,string ans)
{
if(mark==s.size()&&dots==3)
{
int c=0,m=0;
if(ans[ans.size()-1]=='.')
return;
for(int j=ans.size()-1;j>=0;j--)
{
if(ans[j]=='.')
{
// cout<<c<<endl;
c=0;
m=0;
}
else
{
c+=pow(10,m)*(ans[j]-'0');
m++;
}
if(ans[j]=='0'&&j!=0&&ans[j-1]=='.'&&j!=ans.size()-1&&ans[j+1]!='.')
return;
if(c>255)
return;
}
sans.insert(ans);
//cout<<ans<<endl;
return;
}
for(int i=mark;i<s.size();i++)
{
ans.push_back(s[i]);
genip(s,dots,i+1,ans);
if(dots<3)
{
ans.push_back('.');
genip(s,dots+1,i+1,ans);
ans.pop_back();
}
}
}
vector<string> genIp(string s)
{
sans.clear();
string ans="";
vector<string>ret;
if(s.size()<4||s.size()>12)
return ret;
genip(s,0,0,ans);
//Your code here
for(set<string>::iterator it=sans.begin();it!=sans.end();it++)
ret.push_back(*it);
return ret;
}
| 12.925926 | 71 | 0.464183 | richidubey |
4aa38aeeb1a5eba5cc5cbd11fd1bb1c47b91be77 | 2,088 | cc | C++ | audit/util/issue_util.cc | google/plusfish | a56ac07ca132613ecda7f252a69312ada66bbbca | [
"Apache-2.0"
] | 14 | 2020-10-16T18:33:37.000Z | 2022-03-27T18:29:00.000Z | audit/util/issue_util.cc | qause/plusfish | a56ac07ca132613ecda7f252a69312ada66bbbca | [
"Apache-2.0"
] | 2 | 2021-03-18T11:19:59.000Z | 2021-04-26T12:27:33.000Z | audit/util/issue_util.cc | qause/plusfish | a56ac07ca132613ecda7f252a69312ada66bbbca | [
"Apache-2.0"
] | 5 | 2021-06-29T10:51:04.000Z | 2022-01-09T05:18:16.000Z | // Copyright 2020 Google LLC. 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 "audit/util/issue_util.h"
#include <glog/logging.h>
#include <memory>
#include <unordered_set>
#include "absl/container/node_hash_set.h"
#include "opensource/deps/base/basictypes.h"
namespace plusfish {
namespace util {
// The amount of bytes to include include in a response snippets is based on the
// following approach: <100 bytes><payload offset><100 bytes>. This mean the
// snippet will never be longer than 200 bytes.
static const int kSnippetOffset = 100;
void UpdateIssueVectorWithSnippet(
const IssueDetails::IssueType issue_type, const Severity severity,
int64 req_id, const std::string& response_body, int64 response_body_offset,
const std::string& extra_info,
absl::node_hash_set<std::unique_ptr<IssueDetails>>* issues) {
IssueDetails* issue = new IssueDetails();
issue->set_severity(severity);
issue->set_type(issue_type);
issue->set_extra_info(extra_info);
issue->set_request_id(req_id);
issue->set_response_body_offset(response_body_offset);
int64 snippet_size = kSnippetOffset;
// Add a response snippet.
if (response_body_offset < response_body.size()) {
int64 start_offset = 0;
if (kSnippetOffset < response_body_offset) {
start_offset = response_body_offset - kSnippetOffset;
snippet_size += kSnippetOffset;
}
issue->set_response_snippet(
response_body.substr(start_offset, snippet_size));
}
issues->emplace(issue);
}
} // namespace util
} // namespace plusfish
| 33.142857 | 80 | 0.746648 | google |
4aa8f23ecf8e261d28d9cef01e41991beb451f26 | 565 | cpp | C++ | source/bounded/detail/arithmetic/left_shift.cpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | 44 | 2020-10-03T21:37:52.000Z | 2022-03-26T10:08:46.000Z | source/bounded/detail/arithmetic/left_shift.cpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | 1 | 2021-01-01T23:22:39.000Z | 2021-01-01T23:22:39.000Z | source/bounded/detail/arithmetic/left_shift.cpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | null | null | null | // Copyright David Stone 2017.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <bounded/detail/arithmetic/left_shift.hpp>
#include <bounded/detail/class.hpp>
#include "../../homogeneous_equals.hpp"
namespace {
static_assert(homogeneous_equals(
bounded::integer<0, 2>(bounded::constant<1>) << bounded::integer<0, 60>(bounded::constant<3>),
bounded::integer<0, bounded::normalize<(2LL << 60LL)>>(bounded::constant<(1 << 3)>)
));
} // namespace
| 31.388889 | 95 | 0.723894 | davidstone |
4aa9ac69b8425c90eab363e74e1ef03e0533a6c8 | 255 | cpp | C++ | example/main.cpp | pqrs-org/cpp-osx-kext_return | a640bd791ea316baa2b6114fa7976460f7c80e21 | [
"BSL-1.0"
] | 1 | 2019-08-16T03:30:09.000Z | 2019-08-16T03:30:09.000Z | example/main.cpp | pqrs-org/cpp-osx-kext_return | a640bd791ea316baa2b6114fa7976460f7c80e21 | [
"BSL-1.0"
] | null | null | null | example/main.cpp | pqrs-org/cpp-osx-kext_return | a640bd791ea316baa2b6114fa7976460f7c80e21 | [
"BSL-1.0"
] | null | null | null | #include <pqrs/osx/os_kext_return.hpp>
int main(void) {
{
pqrs::osx::os_kext_return r(kOSKextReturnSystemPolicy);
std::cout << r << std::endl;
}
{
pqrs::osx::os_kext_return r(54321);
std::cout << r << std::endl;
}
return 0;
}
| 15.9375 | 59 | 0.6 | pqrs-org |
4aadc93014d7383b8ea4ec6ada706017bf6517ab | 1,120 | cc | C++ | third_party/blink/renderer/modules/webcodecs/codec_state_helper.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | third_party/blink/renderer/modules/webcodecs/codec_state_helper.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | third_party/blink/renderer/modules/webcodecs/codec_state_helper.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/webcodecs/codec_state_helper.h"
namespace blink {
// static
bool ThrowIfCodecStateClosed(V8CodecState state,
String operation,
ExceptionState& exception_state) {
if (state.AsEnum() != V8CodecState::Enum::kClosed)
return false;
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"Cannot call '" + operation + "' on a closed codec.");
return true;
}
// static
bool ThrowIfCodecStateUnconfigured(V8CodecState state,
String operation,
ExceptionState& exception_state) {
if (state.AsEnum() != V8CodecState::Enum::kUnconfigured)
return false;
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"Cannot call '" + operation + "' on an unconfigured codec.");
return true;
}
} // namespace blink
| 31.111111 | 76 | 0.658929 | zealoussnow |
4ab9ca28ba453ee2f6a5e6f4a41dc49c5233eb49 | 6,805 | cc | C++ | ChiModules/LinearBoltzmannSolver/lbs_compute_balance.cc | zachhardy/chi-tech | 18fb6cb691962a90820e2ef4fcb05473f4a6bdd6 | [
"MIT"
] | 7 | 2019-09-10T12:16:08.000Z | 2021-05-06T16:01:59.000Z | ChiModules/LinearBoltzmannSolver/lbs_compute_balance.cc | zachhardy/chi-tech | 18fb6cb691962a90820e2ef4fcb05473f4a6bdd6 | [
"MIT"
] | 72 | 2019-09-04T15:00:25.000Z | 2021-12-02T20:47:29.000Z | ChiModules/LinearBoltzmannSolver/lbs_compute_balance.cc | Naktakala/chi-tech | df5f517d5aff1d167db50ccbcf4229ac0cb668c4 | [
"MIT"
] | 41 | 2019-09-02T15:33:31.000Z | 2022-02-10T13:26:49.000Z | #include "lbs_linear_boltzmann_solver.h"
#include "ChiMath/SpatialDiscretization/FiniteElement/PiecewiseLinear/pwl.h"
#include "chi_log.h"
extern ChiLog& chi_log;
#include <iomanip>
//###################################################################
/**Zeroes all the outflow data-structures required to compute
* balance.*/
void LinearBoltzmann::Solver::ZeroOutflowBalanceVars(LBSGroupset& groupset)
{
for (auto& cell_transport_view : cell_transport_views)
for (auto& group : groupset.groups)
cell_transport_view.ZeroOutflow(group.id);
}
//###################################################################
/**Compute balance.*/
void LinearBoltzmann::Solver::ComputeBalance()
{
MPI_Barrier(MPI_COMM_WORLD);
chi_log.Log() << "\n********** Computing balance\n";
auto pwld =
std::dynamic_pointer_cast<SpatialDiscretization_PWLD>(discretization);
if (not pwld) throw std::logic_error("Trouble getting PWLD-SDM in " +
std::string(__FUNCTION__));
SpatialDiscretization_PWLD& grid_fe_view = *pwld;
//======================================== Get material source
// This is done using the SetSource routine
// because it allows a lot of flexibility.
auto mat_src = phi_old_local;
mat_src.assign(mat_src.size(),0.0);
for (auto& groupset : groupsets)
{
q_moments_local.assign(q_moments_local.size(), 0.0);
SetSource(groupset, q_moments_local,
APPLY_MATERIAL_SOURCE | APPLY_AGS_FISSION_SOURCE |
APPLY_WGS_FISSION_SOURCE);
ScopedCopySTLvectors(groupset, q_moments_local, mat_src);
}
//======================================== Initialize diffusion params
// for xs
// This populates sigma_a
for (auto& xs : material_xs)
if (not xs->diffusion_initialized)
xs->ComputeDiffusionParameters();
//======================================== Compute absorption, material-source
// and in-flow
size_t num_groups=groups.size();
double local_out_flow = 0.0;
double local_in_flow = 0.0;
double local_absorption = 0.0;
double local_production = 0.0;
for (const auto& cell : grid->local_cells)
{
const auto& transport_view = cell_transport_views[cell.local_id];
const auto& fe_intgrl_values = grid_fe_view.GetUnitIntegrals(cell);
const size_t num_nodes = transport_view.NumNodes();
const auto& IntV_shapeI = fe_intgrl_values.GetIntV_shapeI();
const auto& IntS_shapeI = fe_intgrl_values.GetIntS_shapeI();
//====================================== Inflow
// This is essentially an integration over
// all faces, all angles, and all groups.
// Only the cosines that are negative are
// added to the integral.
for (int f=0; f<cell.faces.size(); ++f)
{
const auto& face = cell.faces[f];
for (const auto& groupset : groupsets)
{
for (int n = 0; n < groupset.quadrature->omegas.size(); ++n)
{
const auto &omega = groupset.quadrature->omegas[n];
const double wt = groupset.quadrature->weights[n];
const double mu = omega.Dot(face.normal);
if (mu < 0.0 and (not face.has_neighbor)) //mu<0 and bndry
{
const auto &bndry = sweep_boundaries[face.neighbor_id];
for (int fi = 0; fi < face.vertex_ids.size(); ++fi)
{
const int i = fe_intgrl_values.FaceDofMapping(f, fi);
const auto &IntFi_shapeI = IntS_shapeI[f][i];
for (const auto &group : groupset.groups)
{
const int g = group.id;
const double psi = bndry->boundary_flux[g];
local_in_flow -= mu * wt * psi * IntFi_shapeI;
}//for g
}//for fi
}//if bndry
}//for n
}//for groupset
}//for f
//====================================== Outflow
//The group-wise outflow was determined
//during a solve so here we just
//consolidate it.
for (int g=0; g<num_groups; ++g)
local_out_flow += transport_view.GetOutflow(g);
//====================================== Absorption and Src
//Isotropic flux based absorption and source
auto& xs = *material_xs[transport_view.XSMapping()];
for (int i=0; i<num_nodes; ++i)
for (int g=0; g<num_groups; ++g)
{
size_t imap = transport_view.MapDOF(i,0,g);
double phi_0g = phi_old_local[imap];
double q_0g = mat_src[imap];
local_absorption += xs.sigma_a[g] * phi_0g * IntV_shapeI[i];
local_production += q_0g * IntV_shapeI[i];
}//for g
}//for cell
//======================================== Consolidate local balances
double local_balance = local_production + local_in_flow
- local_absorption - local_out_flow;
double local_gain = local_production + local_in_flow;
std::vector<double> local_balance_table = {local_absorption,
local_production,
local_in_flow,
local_out_flow,
local_balance,
local_gain};
size_t table_size = local_balance_table.size();
std::vector<double> globl_balance_table(table_size,0.0);
MPI_Allreduce(local_balance_table.data(), //sendbuf
globl_balance_table.data(), //recvbuf
table_size,MPI_DOUBLE, //count + datatype
MPI_SUM, //operation
MPI_COMM_WORLD); //communicator
double globl_absorption = globl_balance_table.at(0);
double globl_production = globl_balance_table.at(1);
double globl_in_flow = globl_balance_table.at(2);
double globl_out_flow = globl_balance_table.at(3);
double globl_balance = globl_balance_table.at(4);
double globl_gain = globl_balance_table.at(5);
chi_log.Log() << "Balance table:\n"
<< std::setprecision(5) << std::scientific
<< " Absorption rate = " << globl_absorption << "\n"
<< " Production rate = " << globl_production << "\n"
<< " In-flow rate = " << globl_in_flow << "\n"
<< " Out-flow rate = " << globl_out_flow << "\n"
<< " Integrated scalar flux = " << globl_gain << "\n"
<< " Net Gain/Loss = " << globl_balance << "\n"
<< " Net Gain/Loss normalized = " << globl_balance/globl_gain << "\n";
chi_log.Log() << "\n********** Done computing balance\n";
MPI_Barrier(MPI_COMM_WORLD);
} | 40.029412 | 80 | 0.554739 | zachhardy |
4ab9cd7af36551920e7b49b6d693287ea8eb133e | 5,328 | cpp | C++ | src/AnimationSystem.cpp | SimonWallner/kocmoc-demo | a4f769b5ed7592ce50a18ab93c603d4371fbd291 | [
"MIT",
"Unlicense"
] | 12 | 2015-01-21T07:02:23.000Z | 2021-11-15T19:47:53.000Z | src/AnimationSystem.cpp | SimonWallner/kocmoc-demo | a4f769b5ed7592ce50a18ab93c603d4371fbd291 | [
"MIT",
"Unlicense"
] | null | null | null | src/AnimationSystem.cpp | SimonWallner/kocmoc-demo | a4f769b5ed7592ce50a18ab93c603d4371fbd291 | [
"MIT",
"Unlicense"
] | 3 | 2017-03-04T08:50:46.000Z | 2020-10-23T14:27:04.000Z | #include "AnimationSystem.hpp"
#include "Property.hpp"
#include "utility.hpp"
#include <fstream>
#include <gtx/spline.hpp>
using namespace kocmoc;
AnimationSystem::AnimationSystem(void)
{
fullPath = (std::string)util::Property("scriptsRootFolder") + (std::string)util::Property("animationFileName");
}
AnimationSystem::~AnimationSystem(void)
{
}
AnimationSystem& AnimationSystem::getInstance()
{
static AnimationSystem instance;
return instance;
}
bool AnimationSystem::isspacesonly(const string& line)
{
for (unsigned int i = 0; i < line.length(); ++i)
{
if (!isspace(line[i]))
return false;
}
return true;
}
void AnimationSystem::getnextline(std::istream& is, std::string& line)
{
while (!is.eof())
{
getline(is, line);
if (!isspacesonly(line))
return;
}
}
bool AnimationSystem::parseAnimationFile()
{
std::ifstream file(fullPath.c_str());
if (!file)
{
cout << "failed to load file: " << fullPath << endl;
return false;
}
try
{
string line = "";
string key, value;
while(!file.eof())
{
getnextline(file, line);
const char* cString = line.c_str();
// skip comment lines
if (cString[0] == '#' || cString[0] == '!')
continue;
std::vector<std::string > tokens;
util::tokenize(line, tokens, "\t");
if (tokens.size() == 3)
{
std::string name = tokens[1];
float time, offset, scalar;
if (tokens[0].c_str()[0] == '+')
{
sscanf(tokens[0].c_str(), "%f", &offset);
time = scalarLastKeyTime[name] + offset;
}
else
sscanf(tokens[0].c_str(), "%f", &time);
sscanf(tokens[2].c_str(), "%f", &scalar);
scalarMap[name].push_back(ScalarPair(time, scalar));
scalarLastKeyTime[name] = time;
}
else if (tokens.size() == 5)
{
std::string name = tokens[1];
float time, offset, v0, v1, v2;
if (tokens[0].c_str()[0] == '+')
{
sscanf(tokens[0].c_str(), "%f", &offset);
time = vecLastKeyTime[name] + offset;
}
else
sscanf(tokens[0].c_str(), "%f", &time);
sscanf(tokens[2].c_str(), "%f", &v0);
sscanf(tokens[3].c_str(), "%f", &v1);
sscanf(tokens[4].c_str(), "%f", &v2);
vecMap[name].push_back(VecPair(time, vec3(v0, v1, v2)));
vecLastKeyTime[name] = time;
}
else
std::cout << "failed to parse line: '" << line << "'" << std::endl;
}
} catch (...) {
file.close();
return false;
}
//cout << "parsing successful!" << endl;
file.close();
return true;
}
float AnimationSystem::getScalar(double time, std::string name)
{
// get list
ScalarValues values = scalarMap[name];
if (values.size() == 0)
return 0.0f;
if (values.size() == 1)
return values[0].second;
// binary search
unsigned int lowerIndex = binarySearch(values, time, 0, values.size());
// interpolate
if (lowerIndex == values.size() - 1)
return values[lowerIndex].second;
else
{
float timeA = values[lowerIndex].first;
float valueA = values[lowerIndex].second;
float timeB = values[lowerIndex + 1].first;
float valueB = values[lowerIndex + 1].second;
if (time < timeA)
return valueA;
if (time > timeB)
return valueB;
// we are right in the middle
float t = (timeB - time) / (timeB - timeA);
return t * valueA + (1 - t) * valueB;
}
}
vec3 AnimationSystem::getVec3(double time, std::string name)
{
// get list
VecValues values = vecMap[name];
if (values.size() == 0) // default value for 0 values
return vec3(0.0f);
if (values.size() == 1) // constant interpolation for a single value
return values[0].second;
// binary search
unsigned int lowerIndex = binarySearch(values, time, 0, values.size());
// interpolate
// time is left or right of all samples
if ((lowerIndex == 0 && time < values[lowerIndex].first) || lowerIndex == values.size() - 1)
{
return values[lowerIndex].second; // constant interpolation
}
// only one sample is left or right of time
else // if (lowerIndex == 0 || lowerIndex == values.size() - 2) // linearily interpolate
{
float timeA = values[lowerIndex].first;
vec3 valueA = values[lowerIndex].second;
float timeB = values[lowerIndex + 1].first;
vec3 valueB = values[lowerIndex + 1].second;
float t = (timeB - time) / (timeB - timeA);
return valueA * t + valueB * (1 - t);
}
// NOTE: going back to only linear interpolation
//else // enougth samples on both sides
//{
// // A--B-(time)-C--D
// vec3 valueA = values[lowerIndex -1].second;
// vec3 valueB = values[lowerIndex].second;
// vec3 valueC = values[lowerIndex + 1].second;
// vec3 valueD = values[lowerIndex + 2].second;
// float timeB = values[lowerIndex].first;
// float timeC = values[lowerIndex + 1].first;
//
// float t = (time - timeB) / (timeC - timeB);
// vec3 result = glm::gtx::spline::catmullRom(valueA, valueB, valueC, valueD, t);
// return result;
//}
}
template <class T> unsigned int AnimationSystem::binarySearch(T values, float needle, unsigned int lower, unsigned int upper)
{
if (upper - lower <= 1)
return lower;
unsigned int middle = lower + (upper - lower)/2;
if (needle < values[middle].first) // branch left
return binarySearch(values, needle, lower, middle);
else // branch right
return binarySearch(values, needle, middle, upper);
}
void AnimationSystem::reload()
{
scalarMap.clear();
vecMap.clear();
parseAnimationFile();
} | 22.481013 | 125 | 0.636637 | SimonWallner |
38581fd6694c02298ca0eee94f1c424c769390fc | 398 | cpp | C++ | math/babylonian_method/c++/babylonian_root.cpp | CarbonDDR/al-go-rithms | 8e65affbe812931b7dde0e2933eb06c0f44b4130 | [
"CC0-1.0"
] | 1,253 | 2017-06-06T07:19:25.000Z | 2022-03-30T17:07:58.000Z | math/babylonian_method/c++/babylonian_root.cpp | rishabh99-rc/al-go-rithms | 4df20d7ef7598fda4bc89101f9a99aac94cdd794 | [
"CC0-1.0"
] | 554 | 2017-09-29T18:56:01.000Z | 2022-02-21T15:48:13.000Z | math/babylonian_method/c++/babylonian_root.cpp | rishabh99-rc/al-go-rithms | 4df20d7ef7598fda4bc89101f9a99aac94cdd794 | [
"CC0-1.0"
] | 2,226 | 2017-09-29T19:59:59.000Z | 2022-03-25T08:59:55.000Z | #include <bits/stdc++.h>
using namespace std;
float Babylonian(float n)
{ float s=n;//initial assumption is number itself
float error = 0.000001; //this decides the accuracy of answer
while( (s-n/s) > error )
{
s=(s+n/s)/2;
}
return s;
}
int main()
{
int n = 60;
cout<<"Square root of "<<n<<" is "<<Babylonian(n);
return 0;
}
/*
Output :
Square root of 60 is 7.74597
*/
| 16.583333 | 64 | 0.60804 | CarbonDDR |
38595c4df2496111b0c7d8796862dd51dbc6c958 | 7,109 | hh | C++ | src/kt84/graphics/phong_tessellation.hh | honoriocassiano/skbar | e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4 | [
"MIT"
] | null | null | null | src/kt84/graphics/phong_tessellation.hh | honoriocassiano/skbar | e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4 | [
"MIT"
] | 5 | 2020-09-01T12:16:28.000Z | 2020-09-01T12:21:41.000Z | src/kt84/graphics/phong_tessellation.hh | honoriocassiano/skbar | e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4 | [
"MIT"
] | null | null | null | #pragma once
#include <GL/glew.h>
#include <vector>
#include <tuple>
#include <Eigen/Core>
#include "../geometry/PointNormal.hh"
namespace kt84 {
namespace phong_tessellation {
enum struct Mode {
TRIANGLES = 0,
LINES,
TRIANGLE_FAN,
LINE_LOOP,
LINE_STRIP
};
inline int& subdiv() {
static int subdiv = 3;
return subdiv;
}
inline double& weight() {
static double weight = 0.7;
return weight;
}
namespace internal {
inline Mode& mode() {
static Mode mode = Mode::TRIANGLES;
return mode;
}
inline bool& enabled() {
static bool enabled = true;
return enabled;
}
inline std::vector<std::tuple<bool, int, double>>& config_stack() {
static std::vector<std::tuple<bool, int, double>> config_stack;
return config_stack;
}
inline std::vector<PointNormal>& pointnormals() {
static std::vector<PointNormal> pointnormals;
return pointnormals;
}
inline PointNormal project(const PointNormal& p, const PointNormal& q) {
PointNormal result;
result.head(3) = q.head(3) - (q - p).head(3).dot(p.tail(3)) * p.tail(3);
result.tail(3) = p.tail(3);
return result;
}
inline PointNormal interpolate(const Eigen::Vector3d& baryCoord, const PointNormal& pn0, const PointNormal& pn1, const PointNormal& pn2) {
PointNormal result = baryCoord[0] * pn0 + baryCoord[1] * pn1 + baryCoord[2] * pn2;
pn_normalize(result);
return result;
}
inline PointNormal interpolate(double u, const PointNormal& pn0, const PointNormal& pn1) {
PointNormal result = (1 - u) * pn0 + u * pn1;
pn_normalize(result);
return result;
}
inline void draw_triangle_sub(int i, int j, const PointNormal& pn0, const PointNormal& pn1, const PointNormal& pn2) {
Eigen::Vector3d baryCoord;
baryCoord[1] = i / static_cast<double>(subdiv());
baryCoord[2] = j / static_cast<double>(subdiv());
baryCoord[0] = 1.0 - baryCoord[1] - baryCoord[2];
PointNormal p = interpolate(baryCoord, pn0, pn1, pn2);
PointNormal q0 = project(pn0, p);
PointNormal q1 = project(pn1, p);
PointNormal q2 = project(pn2, p);
PointNormal q = interpolate(baryCoord, q0, q1, q2);
PointNormal r = (1.0 - weight()) * p + weight() * q;
pn_normalize(r);
glNormal3dv(&r[3]);
glVertex3dv(&r[0]);
}
inline void draw_line_sub(int i, const PointNormal& pn0, const PointNormal& pn1) {
double u = i / static_cast<double>(subdiv());
PointNormal p = interpolate(u, pn0, pn1);
PointNormal q0 = project(pn0, p);
PointNormal q1 = project(pn1, p);
PointNormal q = interpolate(u, q0, q1);
PointNormal r = (1.0 - weight()) * p + weight() * q;
pn_normalize(r);
glNormal3dv(&r[3]);
glVertex3dv(&r[0]);
}
}
inline void begin(Mode mode_) { internal::mode() = mode_; }
inline void vertex(const PointNormal& pn) { internal::pointnormals().push_back(pn); }
inline void vertex(const Eigen::Vector3d& point, const Eigen::Vector3d& normal) {
PointNormal pn;
pn << point, normal;
vertex(pn);
}
inline void enable () { internal::enabled() = true; }
inline void disable() { internal::enabled() = false; }
// config stack
inline void push_config() {
internal::config_stack().push_back(std::make_tuple(internal::enabled(), subdiv(), weight()));
}
inline void pop_config () {
std::tie(internal::enabled(), subdiv(), weight()) = internal::config_stack().back();
internal::config_stack().pop_back();
}
inline void draw_triangle(const PointNormal& pn0, const PointNormal& pn1, const PointNormal& pn2) {
glBegin(GL_TRIANGLES);
if (internal::enabled()) {
for (int i = 0; i < subdiv(); ++i) {
for (int j = 0; j < subdiv() - 1 - i; ++j) {
internal::draw_triangle_sub(i , j , pn0, pn1, pn2);
internal::draw_triangle_sub(i + 1, j , pn0, pn1, pn2);
internal::draw_triangle_sub(i , j + 1, pn0, pn1, pn2);
internal::draw_triangle_sub(i , j + 1, pn0, pn1, pn2);
internal::draw_triangle_sub(i + 1, j , pn0, pn1, pn2);
internal::draw_triangle_sub(i + 1, j + 1, pn0, pn1, pn2);
}
internal::draw_triangle_sub(i , subdiv() - i, pn0, pn1, pn2);
internal::draw_triangle_sub(i , subdiv() - 1 - i, pn0, pn1, pn2);
internal::draw_triangle_sub(i + 1, subdiv() - 1 - i, pn0, pn1, pn2);
}
} else {
glNormal3dv(&pn0[3]); glVertex3dv(&pn0[0]);
glNormal3dv(&pn1[3]); glVertex3dv(&pn1[0]);
glNormal3dv(&pn2[3]); glVertex3dv(&pn2[0]);
}
glEnd();
}
inline void draw_line(const PointNormal& pn0, const PointNormal& pn1) {
glBegin(GL_LINE_STRIP);
if (internal::enabled()) {
for (int i = 0; i < subdiv(); ++i) {
internal::draw_line_sub(i , pn0, pn1);
internal::draw_line_sub(i + 1, pn0, pn1);
}
} else {
glNormal3dv(&pn0[3]); glVertex3dv(&pn0[0]);
glNormal3dv(&pn1[3]); glVertex3dv(&pn1[0]);
}
glEnd();
}
inline void end() {
auto& mode = internal::mode();
auto& pointnormals = internal::pointnormals();
auto n = pointnormals.size();
if (mode == Mode::TRIANGLES) {
if (n < 3) return;
size_t m = n / 3;
for (size_t i = 0; i < m; ++i)
draw_triangle(pointnormals[3 * i], pointnormals[3 * i + 1], pointnormals[3 * i + 2]);
} else if (mode == Mode::LINES) {
if (n < 2) return;
size_t m = n / 2;
for (size_t i = 0; i < m; ++i)
draw_line(pointnormals[2 * i], pointnormals[2 * i + 1]);
} else if (mode == Mode::TRIANGLE_FAN) {
if (n < 3) return;
for (size_t i = 1; i < n - 1; ++i)
draw_triangle(pointnormals[0], pointnormals[i], pointnormals[i + 1]);
} else if (mode == Mode::LINE_LOOP) {
if (n < 2) return;
for (size_t i = 0; i < n; ++i)
draw_line(pointnormals[i], pointnormals[(i + 1) % n]);
} else if (mode == Mode::LINE_STRIP) {
if (n < 2) return;
for (size_t i = 0; i < n - 1; ++i)
draw_line(pointnormals[i], pointnormals[i + 1]);
}
pointnormals .clear();
}
};
}
| 37.81383 | 146 | 0.517654 | honoriocassiano |
385c5629f0871645f8db23744cfeb2928c20aa6b | 52,957 | cpp | C++ | lumino/LuminoCore/src/Math/Matrix.cpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 113 | 2020-03-05T01:27:59.000Z | 2022-03-28T13:20:51.000Z | lumino/LuminoCore/src/Math/Matrix.cpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 35 | 2016-04-18T06:14:08.000Z | 2020-02-09T15:51:58.000Z | lumino/LuminoCore/src/Math/Matrix.cpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 12 | 2020-12-21T12:03:59.000Z | 2021-12-15T02:07:49.000Z |
#include <math.h>
#include <assert.h>
#include <string.h>
#include <LuminoCore/Math/Math.hpp>
#include <LuminoCore/Math/Vector3.hpp>
#include <LuminoCore/Math/Vector4.hpp>
#include <LuminoCore/Math/Quaternion.hpp>
#include <LuminoCore/Math/AttitudeTransform.hpp>
#include <LuminoCore/Math/Plane.hpp>
#include <LuminoCore/Math/Matrix.hpp>
#include "Asm.h"
//#define USE_D3DX9MATH
#ifdef USE_D3DX9MATH
#include <d3dx9math.h>
#pragma comment(lib, "d3dx9.lib")
#endif
namespace ln {
//==============================================================================
// Matrix
const Matrix Matrix::Identity = Matrix();
Matrix::Matrix()
{
m[0][0] = m[1][1] = m[2][2] = m[3][3] = 1.0f;
m[0][1] = m[0][2] = m[0][3] = 0.0f;
m[1][0] = m[1][2] = m[1][3] = 0.0f;
m[2][0] = m[2][1] = m[2][3] = 0.0f;
m[3][0] = m[3][1] = m[3][2] = 0.0f;
}
Matrix::Matrix(
float m11,
float m12,
float m13,
float m14,
float m21,
float m22,
float m23,
float m24,
float m31,
float m32,
float m33,
float m34,
float m41,
float m42,
float m43,
float m44)
{
m[0][0] = m11;
m[0][1] = m12;
m[0][2] = m13;
m[0][3] = m14;
m[1][0] = m21;
m[1][1] = m22;
m[1][2] = m23;
m[1][3] = m24;
m[2][0] = m31;
m[2][1] = m32;
m[2][2] = m33;
m[2][3] = m34;
m[3][0] = m41;
m[3][1] = m42;
m[3][2] = m43;
m[3][3] = m44;
}
Matrix::Matrix(const Vector4& row1, const Vector4& row2, const Vector4& row3, const Vector4& row4)
{
*((Vector4*)this->m[0]) = row1;
*((Vector4*)this->m[1]) = row2;
*((Vector4*)this->m[2]) = row3;
*((Vector4*)this->m[3]) = row4;
}
//Matrix::Matrix(const Quaternion& q)
//{
// float xx = q.X * q.X;
// float yy = q.Y * q.Y;
// float zz = q.Z * q.Z;
// float xy = q.X * q.Y;
// float zw = q.Z * q.W;
// float zx = q.Z * q.X;
// float yw = q.Y * q.W;
// float yz = q.Y * q.Z;
// float xw = q.X * q.W;
// M11 = 1.0f - (2.0f * (yy + zz));
// M12 = 2.0f * (xy + zw);
// M13 = 2.0f * (zx - yw);
// M14 = 0.0f;
// M21 = 2.0f * (xy - zw);
// M22 = 1.0f - (2.0f * (zz + xx));
// M23 = 2.0f * (yz + xw);
// M24 = 0.0f;
// M31 = 2.0f * (zx + yw);
// M32 = 2.0f * (yz - xw);
// M33 = 1.0f - (2.0f * (yy + xx));
// M34 = 0.0f;
// M41 = 0.0f;
// M42 = 0.0f;
// M43 = 0.0f;
// M44 = 1.0f;
//}
Matrix::Matrix(const AttitudeTransform& transform)
{
m[0][0] = m[1][1] = m[2][2] = m[3][3] = 1.0f;
m[0][1] = m[0][2] = m[0][3] = 0.0f;
m[1][0] = m[1][2] = m[1][3] = 0.0f;
m[2][0] = m[2][1] = m[2][3] = 0.0f;
m[3][0] = m[3][1] = m[3][2] = 0.0f;
scale(transform.scale);
rotateQuaternion(transform.rotation);
translate(transform.translation);
}
void Matrix::set(
float m11,
float m12,
float m13,
float m14,
float m21,
float m22,
float m23,
float m24,
float m31,
float m32,
float m33,
float m34,
float m41,
float m42,
float m43,
float m44)
{
m[0][0] = m11;
m[0][1] = m12;
m[0][2] = m13;
m[0][3] = m14;
m[1][0] = m21;
m[1][1] = m22;
m[1][2] = m23;
m[1][3] = m24;
m[2][0] = m31;
m[2][1] = m32;
m[2][2] = m33;
m[2][3] = m34;
m[3][0] = m41;
m[3][1] = m42;
m[3][2] = m43;
m[3][3] = m44;
}
bool Matrix::isIdentity() const
{
return (memcmp(this, &Matrix::Identity, sizeof(Matrix)) == 0);
}
void Matrix::translate(float x, float y, float z)
{
m[3][0] += x;
m[3][1] += y;
m[3][2] += z;
}
void Matrix::translate(const Vector3& vec)
{
m[3][0] += vec.x;
m[3][1] += vec.y;
m[3][2] += vec.z;
}
void Matrix::rotateX(float r)
{
float c, s;
Asm::sincos(r, &s, &c);
/* 普通の行列計算
m[0][0], m[0][1], m[0][2], m[0][3] 1, 0, 0, 0
m[1][0], m[1][1], m[1][2], m[1][3] 0, c,-s, 0
m[2][0], m[2][1], m[2][2], m[2][3] * 0, s, c, 0
m[3][0], m[3][1], m[3][2], m[3][3] 0, 0, 0, 1
*/
/* 計算イメージ
m[0][0] = m[0][0] * 1 + m[0][1] * 0 + m[0][2] * 0 + m[0][3] * 0;
m[0][1] = m[0][0] * 0 + m[0][1] * c + m[0][2] * s + m[0][3] * 0;
m[0][2] = m[0][0] * 0 + m[0][1] *-s + m[0][2] * c + m[0][3] * 0;
m[0][3] = m[0][0] * 0 + m[0][1] * 0 + m[0][2] * 0 + m[0][3] * 1;
m[1][0] = m[1][0] * 1 + m[1][1] * 0 + m[1][2] * 0 + m[1][3] * 0;
m[1][1] = m[1][0] * 0 + m[1][1] * c + m[1][2] * s + m[1][3] * 0;
m[1][2] = m[1][0] * 0 + m[1][1] *-s + m[1][2] * c + m[1][3] * 0;
m[1][3] = m[1][0] * 0 + m[1][1] * 0 + m[1][2] * 0 + m[1][3] * 1;
m[2][0] = m[2][0] * 1 + m[2][1] * 0 + m[2][2] * 0 + m[2][3] * 0;
m[2][1] = m[2][0] * 0 + m[2][1] * c + m[2][2] * s + m[2][3] * 0;
m[2][2] = m[2][0] * 0 + m[2][1] *-s + m[2][2] * c + m[2][3] * 0;
m[2][3] = m[2][0] * 0 + m[2][1] * 0 + m[2][2] * 0 + m[2][3] * 1;
m[3][0] = m[3][0] * 1 + m[3][1] * 0 + m[3][2] * 0 + m[3][3] * 0;
m[3][1] = m[3][0] * 0 + m[3][1] * c + m[3][2] * s + m[3][3] * 0;
m[3][2] = m[3][0] * 0 + m[3][1] *-s + m[3][2] * c + m[3][3] * 0;
m[3][3] = m[3][0] * 0 + m[3][1] * 0 + m[3][2] * 0 + m[3][3] * 1;
*/
/* 正しく計算できるようにしたもの
lfloat mx0 = m[0][0];
lfloat mx1 = m[0][1];
lfloat mx2 = m[0][2];
m[0][0] = mx0 * 1 + mx1 * 0 + mx2 * 0 + m[0][3] * 0;
m[0][1] = mx0 * 0 + mx1 * c + mx2 * s + m[0][3] * 0;
m[0][2] = mx0 * 0 + mx1 *-s + mx2 * c + m[0][3] * 0;
m[0][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[0][3] * 1;
mx0 = m[1][0];
mx1 = m[1][1];
mx2 = m[1][2];
m[1][0] = mx0 * 1 + mx1 * 0 + mx2 * 0 + m[1][3] * 0;
m[1][1] = mx0 * 0 + mx1 * c + mx2 * s + m[1][3] * 0;
m[1][2] = mx0 * 0 + mx1 *-s + mx2 * c + m[1][3] * 0;
m[1][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[1][3] * 1;
mx0 = m[2][0];
mx1 = m[2][1];
mx2 = m[2][2];
m[2][0] = mx0 * 1 + mx1 * 0 + mx2 * 0 + m[2][3] * 0;
m[2][1] = mx0 * 0 + mx1 * c + mx2 * s + m[2][3] * 0;
m[2][2] = mx0 * 0 + mx1 *-s + mx2 * c + m[2][3] * 0;
m[2][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[2][3] * 1;
mx0 = m[3][0];
mx1 = m[3][1];
mx2 = m[3][2];
m[3][0] = mx0 * 1 + mx1 * 0 + mx2 * 0 + m[3][3] * 0;
m[3][1] = mx0 * 0 + mx1 * c + mx2 * s + m[3][3] * 0;
m[3][2] = mx0 * 0 + mx1 *-s + mx2 * c + m[3][3] * 0;
m[3][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[3][3] * 1;
*/
/* 単純に * 0 とかの無駄なところを切る
lfloat mx0 = m[0][0];
lfloat mx1 = m[0][1];
lfloat mx2 = m[0][2];
m[0][0] = mx0;
m[0][1] = mx1 * c + mx2 * s;
m[0][2] = mx1 *-s + mx2 * c;
m[0][3] = m[0][3];
mx0 = m[1][0];
mx1 = m[1][1];
mx2 = m[1][2];
m[1][0] = mx0;
m[1][1] = mx1 * c + mx2 * s;
m[1][2] = mx1 *-s + mx2 * c;
m[1][3] = m[1][3];
mx0 = m[2][0];
mx1 = m[2][1];
mx2 = m[2][2];
m[2][0] = mx0;
m[2][1] = mx1 * c + mx2 * s;
m[2][2] = mx1 *-s + mx2 * c;
m[2][3] = m[2][3];
mx0 = m[3][0];
mx1 = m[3][1];
mx2 = m[3][2];
m[3][0] = mx0;
m[3][1] = mx1 * c + mx2 * s;
m[3][2] = mx1 *-s + mx2 * c;
m[3][3] = m[3][3];
*/
// 自分自身を代入しているところを切る
float mx1 = m[0][1];
m[0][1] = mx1 * c + m[0][2] * -s;
m[0][2] = mx1 * s + m[0][2] * c;
mx1 = m[1][1];
m[1][1] = mx1 * c + m[1][2] * -s;
m[1][2] = mx1 * s + m[1][2] * c;
mx1 = m[2][1];
m[2][1] = mx1 * c + m[2][2] * -s;
m[2][2] = mx1 * s + m[2][2] * c;
mx1 = m[3][1];
m[3][1] = mx1 * c + m[3][2] * -s;
m[3][2] = mx1 * s + m[3][2] * c;
/* OpenGL
lnFloat mx1 = m[0][1];
m[0][1] = mx1 * c + m[0][2] * s;
m[0][2] = mx1 *-s + m[0][2] * c;
mx1 = m[1][1];
m[1][1] = mx1 * c + m[1][2] * s;
m[1][2] = mx1 *-s + m[1][2] * c;
mx1 = m[2][1];
m[2][1] = mx1 * c + m[2][2] * s;
m[2][2] = mx1 *-s + m[2][2] * c;
mx1 = m[3][1];
m[3][1] = mx1 * c + m[3][2] * s;
m[3][2] = mx1 *-s + m[3][2] * c;
*/
}
void Matrix::rotateY(float r)
{
float c, s;
Asm::sincos(r, &s, &c);
/* 普通の行列計算
m[0][0], m[0][1], m[0][2], m[0][3] c, 0, s, 0
m[1][0], m[1][1], m[1][2], m[1][3] 0, 1, 0, 0
m[2][0], m[2][1], m[2][2], m[2][3] * -s, 0, c, 0
m[3][0], m[3][1], m[3][2], m[3][3] 0, 0, 0, 1
*/
/* 計算イメージ
m[0][0] = m[0][0] * c + m[0][1] * 0 + m[0][2] *-s + m[0][3] * 0;
m[0][1] = m[0][0] * 0 + m[0][1] * 1 + m[0][2] * 0 + m[0][3] * 0;
m[0][2] = m[0][0] * s + m[0][1] * 0 + m[0][2] * c + m[0][3] * 0;
m[0][3] = m[0][0] * 0 + m[0][1] * 0 + m[0][2] * 0 + m[0][3] * 1;
m[1][0] = m[1][0] * c + m[1][1] * 0 + m[1][2] *-s + m[1][3] * 0;
m[1][1] = m[1][0] * 0 + m[1][1] * 1 + m[1][2] * 0 + m[1][3] * 0;
m[1][2] = m[1][0] * s + m[1][1] * 0 + m[1][2] * c + m[1][3] * 0;
m[1][3] = m[1][0] * 0 + m[1][1] * 0 + m[1][2] * 0 + m[1][3] * 1;
m[2][0] = m[2][0] * c + m[2][1] * 0 + m[2][2] *-s + m[2][3] * 0;
m[2][1] = m[2][0] * 0 + m[2][1] * 1 + m[2][2] * 0 + m[2][3] * 0;
m[2][2] = m[2][0] * s + m[2][1] * 0 + m[2][2] * c + m[2][3] * 0;
m[2][3] = m[2][0] * 0 + m[2][1] * 0 + m[2][2] * 0 + m[2][3] * 1;
m[3][0] = m[3][0] * c + m[3][1] * 0 + m[3][2] *-s + m[3][3] * 0;
m[3][1] = m[3][0] * 0 + m[3][1] * 1 + m[3][2] * 0 + m[3][3] * 0;
m[3][2] = m[3][0] * s + m[3][1] * 0 + m[3][2] * c + m[3][3] * 0;
m[3][3] = m[3][0] * 0 + m[3][1] * 0 + m[3][2] * 0 + m[3][3] * 1;
*/
/* 正しく計算できるようにしたもの
lfloat mx0 = m[0][0];
lfloat mx1 = m[0][1];
lfloat mx2 = m[0][2];
m[0][0] = mx0 * c + mx1 * 0 + mx2 *-s + m[0][3] * 0;
m[0][1] = mx0 * 0 + mx1 * 1 + mx2 * 0 + m[0][3] * 0;
m[0][2] = mx0 * s + mx1 * 0 + mx2 * c + m[0][3] * 0;
m[0][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[0][3] * 1;
mx0 = m[1][0];
mx1 = m[1][1];
mx2 = m[1][2];
m[1][0] = mx0 * c + mx1 * 0 + mx2 *-s + m[1][3] * 0;
m[1][1] = mx0 * 0 + mx1 * 1 + mx2 * 0 + m[1][3] * 0;
m[1][2] = mx0 * s + mx1 * 0 + mx2 * c + m[1][3] * 0;
m[1][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[1][3] * 1;
mx0 = m[2][0];
mx1 = m[2][1];
mx2 = m[2][2];
m[2][0] = mx0 * c + mx1 * 0 + mx2 *-s + m[2][3] * 0;
m[2][1] = mx0 * 0 + mx1 * 1 + mx2 * 0 + m[2][3] * 0;
m[2][2] = mx0 * s + mx1 * 0 + mx2 * c + m[2][3] * 0;
m[2][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[2][3] * 1;
mx0 = m[3][0];
mx1 = m[3][1];
mx2 = m[3][2];
m[3][0] = mx0 * c + mx1 * 0 + mx2 *-s + m[3][3] * 0;
m[3][1] = mx0 * 0 + mx1 * 1 + mx2 * 0 + m[3][3] * 0;
m[3][2] = mx0 * s + mx1 * 0 + mx2 * c + m[3][3] * 0;
m[3][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[3][3] * 1;
*/
/* 単純に * 0 とかの無駄なところを切る
lfloat mx0 = m[0][0];
lfloat mx1 = m[0][1];
lfloat mx2 = m[0][2];
m[0][0] = mx0 * c + mx2 *-s;
m[0][1] = mx1;
m[0][2] = mx0 * s + mx2 * c;
m[0][3] = m[0][3];
mx0 = m[1][0];
mx1 = m[1][1];
mx2 = m[1][2];
m[1][0] = mx0 * c + mx2 *-s;
m[1][1] = mx1;
m[1][2] = mx0 * s + mx2 * c;
m[1][3] = m[1][3];
mx0 = m[2][0];
mx1 = m[2][1];
mx2 = m[2][2];
m[2][0] = mx0 * c + mx2 *-s;
m[2][1] = mx1;
m[2][2] = mx0 * s + mx2 * c;
m[2][3] = mx3;
mx0 = m[3][0];
mx1 = m[3][1];
mx2 = m[3][2];
m[3][0] = mx0 * c + mx2 *-s;
m[3][1] = mx1;
m[3][2] = mx0 * s + mx2 * c;
m[3][3] = m[3][3];
*/
// 自分自身を代入しているところを切る
float mx0 = m[0][0];
m[0][0] = mx0 * c + m[0][2] * s;
m[0][2] = mx0 * -s + m[0][2] * c;
mx0 = m[1][0];
m[1][0] = mx0 * c + m[1][2] * s;
m[1][2] = mx0 * -s + m[1][2] * c;
mx0 = m[2][0];
m[2][0] = mx0 * c + m[2][2] * s;
m[2][2] = mx0 * -s + m[2][2] * c;
mx0 = m[3][0];
m[3][0] = mx0 * c + m[3][2] * s;
m[3][2] = mx0 * -s + m[3][2] * c;
/* OpenGL
lnFloat mx0 = m[0][0];
m[0][0] = mx0 * c + m[0][2] *-s;
m[0][2] = mx0 * s + m[0][2] * c;
mx0 = m[1][0];
m[1][0] = mx0 * c + m[1][2] *-s;
m[1][2] = mx0 * s + m[1][2] * c;
mx0 = m[2][0];
m[2][0] = mx0 * c + m[2][2] *-s;
m[2][2] = mx0 * s + m[2][2] * c;
mx0 = m[3][0];
m[3][0] = mx0 * c + m[3][2] *-s;
m[3][2] = mx0 * s + m[3][2] * c;
*/
}
void Matrix::rotateZ(float r)
{
float c, s;
Asm::sincos(r, &s, &c);
/* 基本の計算イメージ
m[0][0] = m[0][0] * c + m[0][1] * s + m[0][2] * 0 + m[0][3] * 0;
m[0][1] = m[0][0] *-s + m[0][1] * c + m[0][2] * 0 + m[0][3] * 0;
m[0][2] = m[0][0] * 0 + m[0][1] * 0 + m[0][2] * 1 + m[0][3] * 0;
m[0][3] = m[0][0] * 0 + m[0][1] * 0 + m[0][2] * 0 + m[0][3] * 1;
m[1][0] = m[1][0] * c + m[1][1] * s + m[1][2] * 0 + m[1][3] * 0;
m[1][1] = m[1][0] *-s + m[1][1] * c + m[1][2] * 0 + m[1][3] * 0;
m[1][2] = m[1][0] * 0 + m[1][1] * 0 + m[1][2] * 1 + m[1][3] * 0;
m[1][3] = m[1][0] * 0 + m[1][1] * 0 + m[1][2] * 0 + m[1][3] * 1;
m[2][0] = m[2][0] * c + m[2][1] * s + m[2][2] * 0 + m[2][3] * 0;
m[2][1] = m[2][0] *-s + m[2][1] * c + m[2][2] * 0 + m[2][3] * 0;
m[2][2] = m[2][0] * 0 + m[2][1] * 0 + m[2][2] * 1 + m[2][3] * 0;
m[2][3] = m[2][0] * 0 + m[2][1] * 0 + m[2][2] * 0 + m[2][3] * 1;
m[3][0] = m[3][0] * c + m[3][1] * s + m[3][2] * 0 + m[3][3] * 0;
m[3][1] = m[3][0] *-s + m[3][1] * c + m[3][2] * 0 + m[3][3] * 0;
m[3][2] = m[3][0] * 0 + m[3][1] * 0 + m[3][2] * 1 + m[3][3] * 0;
m[3][3] = m[3][0] * 0 + m[3][1] * 0 + m[3][2] * 0 + m[3][3] * 1;
*/
/* 正しく計算できるようにしたもの
lfloat mx0 = m[0][0];
lfloat mx1 = m[0][1];
lfloat mx2 = m[0][2];
m[0][0] = mx0 * c + mx1 * s + mx2 * 0 + m[0][3] * 0;
m[0][1] = mx0 *-s + mx1 * c + mx2 * 0 + m[0][3] * 0;
m[0][2] = mx0 * 0 + mx1 * 0 + mx2 * 1 + m[0][3] * 0;
m[0][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[0][3] * 1;
mx0 = m[1][0];
mx1 = m[1][1];
mx2 = m[1][2];
m[1][0] = mx0 * c + mx1 * s + mx2 * 0 + m[1][3] * 0;
m[1][1] = mx0 *-s + mx1 * c + mx2 * 0 + m[1][3] * 0;
m[1][2] = mx0 * 0 + mx1 * 0 + mx2 * 1 + m[1][3] * 0;
m[1][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[1][3] * 1;
mx0 = m[2][0];
mx1 = m[2][1];
mx2 = m[2][2];
m[2][0] = mx0 * c + mx1 * s + mx2 * 0 + m[2][3] * 0;
m[2][1] = mx0 *-s + mx1 * c + mx2 * 0 + m[2][3] * 0;
m[2][2] = mx0 * 0 + mx1 * 0 + mx2 * 1 + m[2][3] * 0;
m[2][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[2][3] * 1;
mx0 = m[3][0];
mx1 = m[3][1];
mx2 = m[3][2];
m[3][0] = mx0 * c + mx1 * s + mx2 * 0 + m[3][3] * 0;
m[3][1] = mx0 *-s + mx1 * c + mx2 * 0 + m[3][3] * 0;
m[3][2] = mx0 * 0 + mx1 * 0 + mx2 * 1 + m[3][3] * 0;
m[3][3] = mx0 * 0 + mx1 * 0 + mx2 * 0 + m[3][3] * 1;
*/
/* 単純に * 0 とかの無駄なところを切る
lfloat mx0 = m[0][0];
lfloat mx1 = m[0][1];
lfloat mx2 = m[0][2];
m[0][0] = mx0 * c + mx1 * s;
m[0][1] = mx0 *-s + mx1 * c;
m[0][2] = mx2;
m[0][3] = m[0][3];
mx0 = m[1][0];
mx1 = m[1][1];
mx2 = m[1][2];
m[1][0] = mx0 * c + mx1 * s;
m[1][1] = mx0 *-s + mx1 * c;
m[1][2] = mx2;
m[1][3] = m[1][3];
mx0 = m[2][0];
mx1 = m[2][1];
mx2 = m[2][2];
m[2][0] = mx0 * c + mx1 * s;
m[2][1] = mx0 *-s + mx1 * c;
m[2][2] = mx2;
m[2][3] = m[2][3];
mx0 = m[3][0];
mx1 = m[3][1];
mx2 = m[3][2];
m[3][0] = mx0 * c + mx1 * s;
m[3][1] = mx0 *-s + mx1 * c;
m[3][2] = mx2;
m[3][3] = m[3][3];
*/
// 自分自身を代入しているところを切る
float mx0 = m[0][0];
m[0][0] = mx0 * c + m[0][1] * -s;
m[0][1] = mx0 * s + m[0][1] * c;
mx0 = m[1][0];
m[1][0] = mx0 * c + m[1][1] * -s;
m[1][1] = mx0 * s + m[1][1] * c;
mx0 = m[2][0];
m[2][0] = mx0 * c + m[2][1] * -s;
m[2][1] = mx0 * s + m[2][1] * c;
mx0 = m[3][0];
m[3][0] = mx0 * c + m[3][1] * -s;
m[3][1] = mx0 * s + m[3][1] * c;
// OpenGL
/*
lnFloat mx0 = m[0][0];
m[0][0] = mx0 * c + m[0][1] * s;
m[0][1] = mx0 *-s + m[0][1] * c;
mx0 = m[1][0];
m[1][0] = mx0 * c + m[1][1] * s;
m[1][1] = mx0 *-s + m[1][1] * c;
mx0 = m[2][0];
m[2][0] = mx0 * c + m[2][1] * s;
m[2][1] = mx0 *-s + m[2][1] * c;
mx0 = m[3][0];
m[3][0] = mx0 * c + m[3][1] * s;
m[3][1] = mx0 *-s + m[3][1] * c;
*/
}
void Matrix::rotateEulerAngles(float x, float y, float z, RotationOrder order)
{
rotateEulerAngles(Vector3(x, y, z), order);
}
void Matrix::rotateEulerAngles(const Vector3& angles, RotationOrder order)
{
switch (order) {
case RotationOrder::XYZ:
rotateX(angles.x);
rotateY(angles.y);
rotateZ(angles.z);
break;
case RotationOrder::YZX:
rotateY(angles.y);
rotateZ(angles.z);
rotateX(angles.x);
break;
case RotationOrder::ZXY:
rotateZ(angles.z);
rotateX(angles.x);
rotateY(angles.y);
break; // RotationYawPitchRoll
default:
assert(0);
break;
}
}
void Matrix::rotateAxis(const Vector3& axis_, float r)
{
Vector3 axis = axis_;
if (axis.lengthSquared() != 1.0f) {
axis.mutatingNormalize();
}
float s, c;
Asm::sincos(r, &s, &c);
float mc = 1.0f - c;
/* 計算イメージ
_00 = ( axis_.x * axis_.x ) * mc + c;
_01 = ( axis_.x * axis_.y ) * mc + ( axis_.z * s );
_02 = ( axis_.x * axis_.z ) * mc - ( axis_.y * s );
_03 = 0;
_10 = ( axis_.x * axis_.y ) * mc - ( axis_.z * s );
_11 = ( axis_.y * axis_.y ) * mc + c;
_12 = ( axis_.y * axis_.z ) * mc + ( axis_.x * s );
_13 = 0;
_20 = ( axis_.x * axis_.z ) * mc + ( axis_.y * s );
_21 = ( axis_.y * axis_.z ) * mc - ( axis_.x * s );
_22 = ( axis_.z * axis_.z ) * mc + c;
_23 = 0;
_30 = _31 = _32 = 0;
_33 = 1;
m[0][0] = m[0][0] * _00 + m[0][1] * _10 + m[0][2] * _20 + m[0][3] * _30;
m[0][1] = m[0][0] * _01 + m[0][1] * _11 + m[0][2] * _21 + m[0][3] * _31;
m[0][2] = m[0][0] * _02 + m[0][1] * _12 + m[0][2] * _22 + m[0][3] * _32;
m[0][3] = m[0][0] * _03 + m[0][1] * _13 + m[0][2] * _23 + m[0][3] * _33;
m[1][0] = m[1][0] * _00 + m[1][1] * _10 + m[1][2] * _20 + m[1][3] * _30;
m[1][1] = m[1][0] * _01 + m[1][1] * _11 + m[1][2] * _21 + m[1][3] * _31;
m[1][2] = m[1][0] * _02 + m[1][1] * _12 + m[1][2] * _22 + m[1][3] * _32;
m[1][3] = m[1][0] * _03 + m[1][1] * _13 + m[1][2] * _23 + m[1][3] * _33;
m[2][0] = m[2][0] * _00 + m[2][1] * _10 + m[2][2] * _20 + m[2][3] * _30;
m[2][1] = m[2][0] * _01 + m[2][1] * _11 + m[2][2] * _21 + m[2][3] * _31;
m[2][2] = m[2][0] * _02 + m[2][1] * _12 + m[2][2] * _22 + m[2][3] * _32;
m[2][3] = m[2][0] * _03 + m[2][1] * _13 + m[2][2] * _23 + m[2][3] * _33;
m[3][0] = m[3][0] * _00 + m[3][1] * _10 + m[3][2] * _20 + m[3][3] * _30;
m[3][1] = m[3][0] * _01 + m[3][1] * _11 + m[3][2] * _21 + m[3][3] * _31;
m[3][2] = m[3][0] * _02 + m[3][1] * _12 + m[3][2] * _22 + m[3][3] * _32;
m[3][3] = m[3][0] * _03 + m[3][1] * _13 + m[3][2] * _23 + m[3][3] * _33;
*/
/* 正しく計算できるようにしたもの
lfloat mx0 = m[0][0];
lfloat mx1 = m[0][1];
lfloat mx2 = m[0][2];
m[0][0] = mx0 * _00 + mx1 * _10 + mx2 * _20 + m[0][3] * _30;
m[0][1] = mx0 * _01 + mx1 * _11 + mx2 * _21 + m[0][3] * _31;
m[0][2] = mx0 * _02 + mx1 * _12 + mx2 * _22 + m[0][3] * _32;
m[0][3] = mx0 * _03 + mx1 * _13 + mx2 * _23 + m[0][3] * _33;
mx0 = m[1][0];
mx1 = m[1][1];
mx2 = m[1][2];
m[1][0] = mx0 * _00 + mx1 * _10 + mx2 * _20 + m[1][3] * _30;
m[1][1] = mx0 * _01 + mx1 * _11 + mx2 * _21 + m[1][3] * _31;
m[1][2] = mx0 * _02 + mx1 * _12 + mx2 * _22 + m[1][3] * _32;
m[1][3] = mx0 * _03 + mx1 * _13 + mx2 * _23 + m[1][3] * _33;
mx0 = m[2][0];
mx1 = m[2][1];
mx2 = m[2][2];
m[2][0] = mx0 * _00 + mx1 * _10 + mx2 * _20 + m[2][3] * _30;
m[2][1] = mx0 * _01 + mx1 * _11 + mx2 * _21 + m[2][3] * _31;
m[2][2] = mx0 * _02 + mx1 * _12 + mx2 * _22 + m[2][3] * _32;
m[2][3] = mx0 * _03 + mx1 * _13 + mx2 * _23 + m[2][3] * _33;
mx0 = m[3][0];
mx1 = m[3][1];
mx2 = m[3][2];
m[3][0] = mx0 * _00 + mx1 * _10 + mx2 * _20 + m[3][3] * _30;
m[3][1] = mx0 * _01 + mx1 * _11 + mx2 * _21 + m[3][3] * _31;
m[3][2] = mx0 * _02 + mx1 * _12 + mx2 * _22 + m[3][3] * _32;
m[3][3] = mx0 * _03 + mx1 * _13 + mx2 * _23 + m[3][3] * _33;
*/
/* 0 を乗算してるところと、*1 で自分自身代入しているところを切る
lfloat mx0 = m[0][0];
lfloat mx1 = m[0][1];
lfloat mx2 = m[0][2];
m[0][0] = mx0 * _00 + mx1 * _10 + mx2 * _20;
m[0][1] = mx0 * _01 + mx1 * _11 + mx2 * _21;
m[0][2] = mx0 * _02 + mx1 * _12 + mx2 * _22;
mx0 = m[1][0];
mx1 = m[1][1];
mx2 = m[1][2];
m[1][0] = mx0 * _00 + mx1 * _10 + mx2 * _20;
m[1][1] = mx0 * _01 + mx1 * _11 + mx2 * _21;
m[1][2] = mx0 * _02 + mx1 * _12 + mx2 * _22;
mx0 = m[2][0];
mx1 = m[2][1];
mx2 = m[2][2];
m[2][0] = mx0 * _00 + mx1 * _10 + mx2 * _20;
m[2][1] = mx0 * _01 + mx1 * _11 + mx2 * _21;
m[2][2] = mx0 * _02 + mx1 * _12 + mx2 * _22;
mx0 = m[3][0];
mx1 = m[3][1];
mx2 = m[3][2];
m[3][0] = mx0 * _00 + mx1 * _10 + mx2 * _20;
m[3][1] = mx0 * _01 + mx1 * _11 + mx2 * _21;
m[3][2] = mx0 * _02 + mx1 * _12 + mx2 * _22;
*/
// ※古いコードのなので変数名が 0 スタートになっている点に注意
float _00 = (axis.x * axis.x) * mc + c;
float _01 = (axis.x * axis.y) * mc + (axis.z * s);
float _02 = (axis.x * axis.z) * mc - (axis.y * s);
float _10 = (axis.x * axis.y) * mc - (axis.z * s);
float _11 = (axis.y * axis.y) * mc + c;
float _12 = (axis.y * axis.z) * mc + (axis.x * s);
float _20 = (axis.x * axis.z) * mc + (axis.y * s);
float _21 = (axis.y * axis.z) * mc - (axis.x * s);
float _22 = (axis.z * axis.z) * mc + c;
float mx0 = m[0][0];
float mx1 = m[0][1];
m[0][0] = mx0 * _00 + mx1 * _10 + m[0][2] * _20;
m[0][1] = mx0 * _01 + mx1 * _11 + m[0][2] * _21;
m[0][2] = mx0 * _02 + mx1 * _12 + m[0][2] * _22;
mx0 = m[1][0];
mx1 = m[1][1];
m[1][0] = mx0 * _00 + mx1 * _10 + m[1][2] * _20;
m[1][1] = mx0 * _01 + mx1 * _11 + m[1][2] * _21;
m[1][2] = mx0 * _02 + mx1 * _12 + m[1][2] * _22;
mx0 = m[2][0];
mx1 = m[2][1];
m[2][0] = mx0 * _00 + mx1 * _10 + m[2][2] * _20;
m[2][1] = mx0 * _01 + mx1 * _11 + m[2][2] * _21;
m[2][2] = mx0 * _02 + mx1 * _12 + m[2][2] * _22;
mx0 = m[3][0];
mx1 = m[3][1];
m[3][0] = mx0 * _00 + mx1 * _10 + m[3][2] * _20;
m[3][1] = mx0 * _01 + mx1 * _11 + m[3][2] * _21;
m[3][2] = mx0 * _02 + mx1 * _12 + m[3][2] * _22;
}
void Matrix::rotateQuaternion(const Quaternion& q)
{
float xx = q.x * q.x;
float yy = q.y * q.y;
float zz = q.z * q.z;
float xy = q.x * q.y;
float zw = q.z * q.w;
float zx = q.z * q.x;
float yw = q.y * q.w;
float yz = q.y * q.z;
float xw = q.x * q.w;
// ※古いコードのなので変数名が 0 スタートになっている点に注意
float _00 = 1.0f - (2.0f * (yy + zz));
float _01 = 2.0f * (xy + zw);
float _02 = 2.0f * (zx - yw);
float _10 = 2.0f * (xy - zw);
float _11 = 1.0f - (2.0f * (zz + xx));
float _12 = 2.0f * (yz + xw);
float _20 = 2.0f * (zx + yw);
float _21 = 2.0f * (yz - xw);
float _22 = 1.0f - (2.0f * (yy + xx));
float mx0 = m[0][0];
float mx1 = m[0][1];
m[0][0] = mx0 * _00 + mx1 * _10 + m[0][2] * _20;
m[0][1] = mx0 * _01 + mx1 * _11 + m[0][2] * _21;
m[0][2] = mx0 * _02 + mx1 * _12 + m[0][2] * _22;
mx0 = m[1][0];
mx1 = m[1][1];
m[1][0] = mx0 * _00 + mx1 * _10 + m[1][2] * _20;
m[1][1] = mx0 * _01 + mx1 * _11 + m[1][2] * _21;
m[1][2] = mx0 * _02 + mx1 * _12 + m[1][2] * _22;
mx0 = m[2][0];
mx1 = m[2][1];
m[2][0] = mx0 * _00 + mx1 * _10 + m[2][2] * _20;
m[2][1] = mx0 * _01 + mx1 * _11 + m[2][2] * _21;
m[2][2] = mx0 * _02 + mx1 * _12 + m[2][2] * _22;
mx0 = m[3][0];
mx1 = m[3][1];
m[3][0] = mx0 * _00 + mx1 * _10 + m[3][2] * _20;
m[3][1] = mx0 * _01 + mx1 * _11 + m[3][2] * _21;
m[3][2] = mx0 * _02 + mx1 * _12 + m[3][2] * _22;
}
void Matrix::scale(float x, float y, float z)
{
m[0][0] *= x;
m[0][1] *= y;
m[0][2] *= z;
m[1][0] *= x;
m[1][1] *= y;
m[1][2] *= z;
m[2][0] *= x;
m[2][1] *= y;
m[2][2] *= z;
m[3][0] *= x;
m[3][1] *= y;
m[3][2] *= z;
}
void Matrix::scale(const Vector3& vec)
{
scale(vec.x, vec.y, vec.z);
}
void Matrix::scale(float xyz)
{
scale(xyz, xyz, xyz);
}
void Matrix::inverse()
{
(*this) = Matrix::makeInverse(*this);
}
void Matrix::transpose()
{
(*this) = Matrix::makeTranspose(*this);
}
void Matrix::decompose(Vector3* scale, Quaternion* rot, Vector3* trans) const
{
Matrix scaleMat;
Matrix rotMat;
Matrix transMat;
decomposeMatrices(&scaleMat, &rotMat, &transMat);
if (scale) {
scale->set(scaleMat.m[0][0], scaleMat.m[1][1], scaleMat.m[2][2]);
}
if (rot) {
*rot = Quaternion::makeFromRotationMatrix(rotMat);
}
if (trans) {
trans->set(transMat.m[3][0], transMat.m[3][1], transMat.m[3][2]);
}
}
void Matrix::decomposeMatrices(Matrix* scale, Matrix* rot, Matrix* trans) const
{
if (trans) {
*trans = Matrix::makeTranslation(position());
}
Vector3 sc(
sqrtf(m[0][0] * m[0][0] + m[0][1] * m[0][1] + m[0][2] * m[0][2]),
sqrtf(m[1][0] * m[1][0] + m[1][1] * m[1][1] + m[1][2] * m[1][2]),
sqrtf(m[2][0] * m[2][0] + m[2][1] * m[2][1] + m[2][2] * m[2][2]));
if (scale) {
*scale = Matrix::makeScaling(sc);
}
if (rot) {
*rot = Identity;
rot->m[0][0] = (sc.x != 0.0f) ? m[0][0] / sc.x : 0.0f;
rot->m[0][1] = (sc.x != 0.0f) ? m[0][1] / sc.x : 0.0f;
rot->m[0][2] = (sc.x != 0.0f) ? m[0][2] / sc.x : 0.0f;
rot->m[0][3] = 0.0f;
rot->m[1][0] = (sc.y != 0.0f) ? m[1][0] / sc.y : 0.0f;
rot->m[1][1] = (sc.y != 0.0f) ? m[1][1] / sc.y : 0.0f;
rot->m[1][2] = (sc.y != 0.0f) ? m[1][2] / sc.y : 0.0f;
rot->m[1][3] = 0.0f;
rot->m[2][0] = (sc.z != 0.0f) ? m[2][0] / sc.z : 0.0f;
rot->m[2][1] = (sc.z != 0.0f) ? m[2][1] / sc.z : 0.0f;
rot->m[2][2] = (sc.z != 0.0f) ? m[2][2] / sc.z : 0.0f;
rot->m[2][3] = 0.0f;
rot->m[3][0] = 0.0f;
rot->m[3][1] = 0.0f;
rot->m[3][2] = 0.0f;
rot->m[3][3] = 1.0f;
}
}
#if 0
void Matrix::decompose(Vector3* scale, Matrix* rot, Vector3* trans)
{
if (trans)
{
trans->Set(m[3][0], m[3][1], m[3][2]);
}
Vector3 sc(
sqrtf(m[0][0] * m[0][0] + m[0][1] * m[0][1] + m[0][2] * m[0][2]),
sqrtf(m[1][0] * m[1][0] + m[1][1] * m[1][1] + m[1][2] * m[1][2]),
sqrtf(m[2][0] * m[2][0] + m[2][1] * m[2][1] + m[2][2] * m[2][2]));
if (scale)
{
*scale = sc;
}
if (rot)
{
rot->m[0][0] = (sc.X != 0.0f) ? m[0][0] / sc.X : 0.0f;
rot->m[0][1] = (sc.X != 0.0f) ? m[0][1] / sc.X : 0.0f;
rot->m[0][2] = (sc.X != 0.0f) ? m[0][2] / sc.X : 0.0f;
rot->m[0][3] = 0.0f;
rot->m[1][0] = (sc.Y != 0.0f) ? m[1][0] / sc.Y : 0.0f;
rot->m[1][1] = (sc.Y != 0.0f) ? m[1][1] / sc.Y : 0.0f;
rot->m[1][2] = (sc.Y != 0.0f) ? m[1][2] / sc.Y : 0.0f;
rot->m[1][3] = 0.0f;
rot->m[2][0] = (sc.Z != 0.0f) ? m[2][0] / sc.Z : 0.0f;
rot->m[2][1] = (sc.Z != 0.0f) ? m[2][1] / sc.Z : 0.0f;
rot->m[2][2] = (sc.Z != 0.0f) ? m[2][2] / sc.Z : 0.0f;
rot->m[2][3] = 0.0f;
rot->m[3][0] = 0.0f;
rot->m[3][1] = 0.0f;
rot->m[3][2] = 0.0f;
rot->m[3][3] = 1.0f;
}
}
void Matrix::decompose(Vector3* scale, Quaternion* rot, Vector3* trans) const
{
if (rot)
{
Matrix rotMat;
decompose(scale, &rotMat, trans);
*rot =
}
else
{
decompose(scale, NULL, trans);
}
}
#endif
static bool EulerAnglesXYZ(const Matrix& mat, float* xRot, float* yRot, float* zRot)
{
static const float Threshold = 0.0001f;
if (mat.m[0][2] > 1.0f - Threshold || mat.m[0][2] < -1.0f + Threshold) // ジンバルロック判定
{
*xRot = 0.0f;
*yRot = (mat.m[0][2] < 0 ? Math::PIDiv2 : -Math::PIDiv2);
*zRot = -atan2f(-mat.m[1][0], mat.m[1][1]);
return false;
}
*yRot = -asinf(mat.m[0][2]);
*xRot = asinf(mat.m[1][2] / cosf(*yRot));
if (Math::isNaN(*xRot)) // ジンバルロック判定
{
*xRot = 0.0f;
*yRot = (mat.m[0][2] < 0 ? Math::PIDiv2 : -Math::PIDiv2);
*zRot = -atan2f(-mat.m[1][0], mat.m[1][1]);
return false;
}
if (mat.m[2][2] < 0.0f) {
*xRot = Math::PI - (*xRot);
}
*zRot = atan2f(mat.m[0][1], mat.m[0][0]);
return true;
}
static bool EulerAnglesYZX(const Matrix& mat, float* xRot, float* yRot, float* zRot)
{
static const float Threshold = 0.0001f;
if (mat.m[1][0] > 1.0f - Threshold || mat.m[1][0] < -1.0f + Threshold) // ジンバルロック判定
{
*xRot = -atan2f(-mat.m[2][1], mat.m[2][2]);
*yRot = 0.0f;
*zRot = (mat.m[1][0] < 0 ? Math::PIDiv2 : -Math::PIDiv2);
return false;
}
*zRot = -asinf(mat.m[1][0]);
*yRot = asinf(mat.m[2][0] / cosf(*zRot));
if (Math::isNaN(*yRot)) // ジンバルロック判定
{
*xRot = -atan2f(-mat.m[2][1], mat.m[2][2]);
*yRot = 0.0f;
*zRot = (mat.m[1][0] < 0 ? Math::PIDiv2 : -Math::PIDiv2);
return false;
}
if (mat.m[0][0] < 0.0f) {
*yRot = Math::PI - (*yRot);
}
*xRot = atan2f(mat.m[1][2], mat.m[1][1]);
return true;
}
static bool EulerAnglesZXY(const Matrix& mat, float* xRot, float* yRot, float* zRot)
{
static const float Threshold = 0.0001f;
//if (locked) { *locked = true; } // 最初にジンバルロック発生状態にしておく
if (mat.m[2][1] > 1.0f - Threshold || mat.m[2][1] < -1.0f + Threshold) // ジンバルロック判定
{
*xRot = (mat.m[2][1] < 0 ? Math::PIDiv2 : -Math::PIDiv2);
*yRot = (float)atan2f(-mat.m[0][2], mat.m[0][0]);
*zRot = 0.0f;
return false;
}
*xRot = -(float)asinf(mat.m[2][1]);
*zRot = (float)asinf(mat.m[0][1] / cosf(*xRot));
if (Math::isNaN(*zRot)) // ジンバルロック判定
{
*xRot = (mat.m[2][1] < 0 ? Math::PIDiv2 : -Math::PIDiv2);
*yRot = (float)atan2f(-mat.m[0][2], mat.m[0][0]);
*zRot = 0.0f;
return false;
}
if (mat.m[1][1] < 0.0f) {
*zRot = Math::PI - (*zRot);
}
*yRot = (float)atan2f(mat.m[2][0], mat.m[2][2]);
//if (locked) { *locked = false; } // ジンバルロックは発生しなかった
//return Vector3(xRot, yRot, zRot);
return true;
}
Vector3 Matrix::toEulerAngles(RotationOrder order, bool* locked_) const
{
bool locked;
float xRot, yRot, zRot;
switch (order) {
case RotationOrder::XYZ:
locked = !EulerAnglesXYZ(*this, &xRot, &yRot, &zRot);
break;
//case RotationOrder_XZY: break;
//case RotationOrder_YXZ: break;
case RotationOrder::YZX:
locked = !EulerAnglesYZX(*this, &xRot, &yRot, &zRot);
break;
case RotationOrder::ZXY:
locked = !EulerAnglesZXY(*this, &xRot, &yRot, &zRot); // RotationYawPitchRoll
break;
//case RotationOrder_ZYX: break;
default:
assert(0);
return Vector3();
}
if (locked_ != NULL) {
*locked_ = locked;
}
return Vector3(xRot, yRot, zRot);
}
Matrix Matrix::getRotationMatrix() const
{
return Matrix(
m[0][0], m[0][1], m[0][2], 0.0f, m[1][0], m[1][1], m[1][2], 0.0f, m[2][0], m[2][1], m[2][2], 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
}
bool Matrix::isNaNOrInf() const
{
return Math::isNaNOrInf(m[0][0]) || Math::isNaNOrInf(m[0][1]) || Math::isNaNOrInf(m[0][2]) || Math::isNaNOrInf(m[0][3]) ||
Math::isNaNOrInf(m[1][0]) || Math::isNaNOrInf(m[1][1]) || Math::isNaNOrInf(m[1][2]) || Math::isNaNOrInf(m[1][3]) ||
Math::isNaNOrInf(m[2][0]) || Math::isNaNOrInf(m[2][1]) || Math::isNaNOrInf(m[2][2]) || Math::isNaNOrInf(m[2][3]) ||
Math::isNaNOrInf(m[3][0]) || Math::isNaNOrInf(m[3][1]) || Math::isNaNOrInf(m[3][2]) || Math::isNaNOrInf(m[3][3]);
}
String Matrix::toString() const
{
const std::size_t BufferLength = 4096;
char text[BufferLength];
StringHelper::vsprintf2(
text, BufferLength, "Matrix((%f, %f, %f, %f), (%f, %f, %f, %f), (%f, %f, %f, %f), (%f, %f, %f, %f))",
m[0][0], m[0][1], m[0][2], m[0][3],
m[1][0], m[1][1], m[1][2], m[1][3],
m[2][0], m[2][1], m[2][2], m[2][3],
m[3][0], m[3][1], m[3][2], m[3][3]);
return String::fromCString(text);
}
const float& Matrix::operator()(int row, int column) const
{
LN_CHECK(0 <= row && row <= 3);
LN_CHECK(0 <= column && column <= 3);
return m[row][column];
}
float & Matrix::operator()(int row, int column)
{
LN_CHECK(0 <= row && row <= 3);
LN_CHECK(0 <= column && column <= 3);
return m[row][column];
}
// static
Matrix Matrix::multiply(const Matrix& mat1, const Matrix& mat2)
{
Matrix out;
out.m[0][0] = mat1.m[0][0] * mat2.m[0][0] + mat1.m[0][1] * mat2.m[1][0] + mat1.m[0][2] * mat2.m[2][0] + mat1.m[0][3] * mat2.m[3][0];
out.m[0][1] = mat1.m[0][0] * mat2.m[0][1] + mat1.m[0][1] * mat2.m[1][1] + mat1.m[0][2] * mat2.m[2][1] + mat1.m[0][3] * mat2.m[3][1];
out.m[0][2] = mat1.m[0][0] * mat2.m[0][2] + mat1.m[0][1] * mat2.m[1][2] + mat1.m[0][2] * mat2.m[2][2] + mat1.m[0][3] * mat2.m[3][2];
out.m[0][3] = mat1.m[0][0] * mat2.m[0][3] + mat1.m[0][1] * mat2.m[1][3] + mat1.m[0][2] * mat2.m[2][3] + mat1.m[0][3] * mat2.m[3][3];
out.m[1][0] = mat1.m[1][0] * mat2.m[0][0] + mat1.m[1][1] * mat2.m[1][0] + mat1.m[1][2] * mat2.m[2][0] + mat1.m[1][3] * mat2.m[3][0];
out.m[1][1] = mat1.m[1][0] * mat2.m[0][1] + mat1.m[1][1] * mat2.m[1][1] + mat1.m[1][2] * mat2.m[2][1] + mat1.m[1][3] * mat2.m[3][1];
out.m[1][2] = mat1.m[1][0] * mat2.m[0][2] + mat1.m[1][1] * mat2.m[1][2] + mat1.m[1][2] * mat2.m[2][2] + mat1.m[1][3] * mat2.m[3][2];
out.m[1][3] = mat1.m[1][0] * mat2.m[0][3] + mat1.m[1][1] * mat2.m[1][3] + mat1.m[1][2] * mat2.m[2][3] + mat1.m[1][3] * mat2.m[3][3];
out.m[2][0] = mat1.m[2][0] * mat2.m[0][0] + mat1.m[2][1] * mat2.m[1][0] + mat1.m[2][2] * mat2.m[2][0] + mat1.m[2][3] * mat2.m[3][0];
out.m[2][1] = mat1.m[2][0] * mat2.m[0][1] + mat1.m[2][1] * mat2.m[1][1] + mat1.m[2][2] * mat2.m[2][1] + mat1.m[2][3] * mat2.m[3][1];
out.m[2][2] = mat1.m[2][0] * mat2.m[0][2] + mat1.m[2][1] * mat2.m[1][2] + mat1.m[2][2] * mat2.m[2][2] + mat1.m[2][3] * mat2.m[3][2];
out.m[2][3] = mat1.m[2][0] * mat2.m[0][3] + mat1.m[2][1] * mat2.m[1][3] + mat1.m[2][2] * mat2.m[2][3] + mat1.m[2][3] * mat2.m[3][3];
out.m[3][0] = mat1.m[3][0] * mat2.m[0][0] + mat1.m[3][1] * mat2.m[1][0] + mat1.m[3][2] * mat2.m[2][0] + mat1.m[3][3] * mat2.m[3][0];
out.m[3][1] = mat1.m[3][0] * mat2.m[0][1] + mat1.m[3][1] * mat2.m[1][1] + mat1.m[3][2] * mat2.m[2][1] + mat1.m[3][3] * mat2.m[3][1];
out.m[3][2] = mat1.m[3][0] * mat2.m[0][2] + mat1.m[3][1] * mat2.m[1][2] + mat1.m[3][2] * mat2.m[2][2] + mat1.m[3][3] * mat2.m[3][2];
out.m[3][3] = mat1.m[3][0] * mat2.m[0][3] + mat1.m[3][1] * mat2.m[1][3] + mat1.m[3][2] * mat2.m[2][3] + mat1.m[3][3] * mat2.m[3][3];
return out;
}
// static
Matrix Matrix::makeTranslation(float x, float y, float z)
{
return Matrix(
1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, x, y, z, 1.0f);
}
// static
Matrix Matrix::makeTranslation(const Vector3& vec)
{
return Matrix(
1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, vec.x, vec.y, vec.z, 1.0f);
}
// static
Matrix Matrix::makeRotationX(float r)
{
float c, s;
Asm::sincos(r, &s, &c);
return Matrix(
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, c, s, 0.0f,
0.0f,-s, c, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
}
// static
Matrix Matrix::makeRotationY(float r)
{
float c, s;
Asm::sincos(r, &s, &c);
return Matrix(
c, 0.0f, -s, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, s, 0.0f, c, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
}
// static
Matrix Matrix::makeRotationZ(float r)
{
float c, s;
Asm::sincos(r, &s, &c);
return Matrix(
c, s, 0.0f, 0.0f,
-s, c, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
}
// static
Matrix Matrix::makeRotationAxis(const Vector3& axis_, float r)
{
Vector3 axis = axis_;
if (axis.lengthSquared() != 1.0f) {
axis.mutatingNormalize();
}
float s, c;
Asm::sincos(r, &s, &c);
float mc = 1.0f - c;
return Matrix(
(axis.x * axis.x) * mc + c, (axis.x * axis.y) * mc + (axis.z * s), (axis.x * axis.z) * mc - (axis.y * s), 0.0f, (axis.x * axis.y) * mc - (axis.z * s), (axis.y * axis.y) * mc + c, (axis.y * axis.z) * mc + (axis.x * s), 0.0f, (axis.x * axis.z) * mc + (axis.y * s), (axis.y * axis.z) * mc - (axis.x * s), (axis.z * axis.z) * mc + c, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
}
// static
Matrix Matrix::makeRotationQuaternion(const Quaternion& qua)
{
float xx = qua.x * qua.x;
float yy = qua.y * qua.y;
float zz = qua.z * qua.z;
float xy = qua.x * qua.y;
float zw = qua.z * qua.w;
float zx = qua.z * qua.x;
float yw = qua.y * qua.w;
float yz = qua.y * qua.z;
float xw = qua.x * qua.w;
return Matrix(
1.0f - (2.0f * (yy + zz)), 2.0f * (xy + zw), 2.0f * (zx - yw), 0.0f, 2.0f * (xy - zw), 1.0f - (2.0f * (zz + xx)), 2.0f * (yz + xw), 0.0f, 2.0f * (zx + yw), 2.0f * (yz - xw), 1.0f - (2.0f * (yy + xx)), 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
}
// static
Matrix Matrix::makeRotationEulerAngles(const Vector3& angles, RotationOrder order)
{
Matrix m;
switch (order) {
case RotationOrder::XYZ:
m.rotateX(angles.x);
m.rotateY(angles.y);
m.rotateZ(angles.z);
break;
//case RotationOrder_XZY:
// m.rotateX(angles.X); m.rotateZ(angles.Z); m.rotateY(angles.Y); break;
//case RotationOrder_YXZ:
// m.rotateY(angles.Y); m.rotateX(angles.X); m.rotateZ(angles.Z); break;
case RotationOrder::YZX:
m.rotateY(angles.y);
m.rotateZ(angles.z);
m.rotateX(angles.x);
break;
case RotationOrder::ZXY:
m.rotateZ(angles.z);
m.rotateX(angles.x);
m.rotateY(angles.y);
break; // RotationYawPitchRoll
//case RotationOrder_ZYX:
// m.rotateZ(angles.Z); m.rotateY(angles.Y); m.rotateX(angles.X); break;
default:
assert(0);
return m;
}
return m;
}
// static
Matrix Matrix::makeRotationEulerAngles(float x, float y, float z, RotationOrder order)
{
Matrix m;
switch (order) {
case RotationOrder::XYZ:
m.rotateX(x);
m.rotateY(y);
m.rotateZ(z);
break;
case RotationOrder::YZX:
m.rotateY(y);
m.rotateZ(z);
m.rotateX(y);
break;
case RotationOrder::ZXY:
m.rotateZ(z);
m.rotateX(x);
m.rotateY(y);
break; // RotationYawPitchRoll
default:
assert(0);
return m;
}
return m;
}
// static
Matrix Matrix::makeRotationYawPitchRoll(float yaw, float pitch, float roll)
{
Quaternion q = Quaternion::makeFromYawPitchRoll(yaw, pitch, roll);
return Matrix::makeRotationQuaternion(q);
}
// static
Matrix Matrix::makeScaling(float x, float y, float z)
{
return Matrix(
x, 0.0f, 0.0f, 0.0f, 0.0f, y, 0.0f, 0.0f, 0.0f, 0.0f, z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
}
// static
Matrix Matrix::makeScaling(const Vector3& vec)
{
return Matrix(
vec.x, 0.0f, 0.0f, 0.0f, 0.0f, vec.y, 0.0f, 0.0f, 0.0f, 0.0f, vec.z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
}
// static
Matrix Matrix::makeScaling(float xyz)
{
return Matrix(
xyz, 0.0f, 0.0f, 0.0f, 0.0f, xyz, 0.0f, 0.0f, 0.0f, 0.0f, xyz, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
}
// static
Matrix Matrix::makeInverse(const Matrix& mat)
{
#if 1 // 速度は D3DXMatrixInverse の 2~3倍 (100000 回で 3000us。コンストラクタとかが足引っ張ってそうな気がする…)
float coef00 = mat.m[2][2] * mat.m[3][3] - mat.m[3][2] * mat.m[2][3];
float coef02 = mat.m[1][2] * mat.m[3][3] - mat.m[3][2] * mat.m[1][3];
float coef03 = mat.m[1][2] * mat.m[2][3] - mat.m[2][2] * mat.m[1][3];
float coef04 = mat.m[2][1] * mat.m[3][3] - mat.m[3][1] * mat.m[2][3];
float coef06 = mat.m[1][1] * mat.m[3][3] - mat.m[3][1] * mat.m[1][3];
float coef07 = mat.m[1][1] * mat.m[2][3] - mat.m[2][1] * mat.m[1][3];
float coef08 = mat.m[2][1] * mat.m[3][2] - mat.m[3][1] * mat.m[2][2];
float coef10 = mat.m[1][1] * mat.m[3][2] - mat.m[3][1] * mat.m[1][2];
float coef11 = mat.m[1][1] * mat.m[2][2] - mat.m[2][1] * mat.m[1][2];
float coef12 = mat.m[2][0] * mat.m[3][3] - mat.m[3][0] * mat.m[2][3];
float coef14 = mat.m[1][0] * mat.m[3][3] - mat.m[3][0] * mat.m[1][3];
float coef15 = mat.m[1][0] * mat.m[2][3] - mat.m[2][0] * mat.m[1][3];
float coef16 = mat.m[2][0] * mat.m[3][2] - mat.m[3][0] * mat.m[2][2];
float coef18 = mat.m[1][0] * mat.m[3][2] - mat.m[3][0] * mat.m[1][2];
float coef19 = mat.m[1][0] * mat.m[2][2] - mat.m[2][0] * mat.m[1][2];
float coef20 = mat.m[2][0] * mat.m[3][1] - mat.m[3][0] * mat.m[2][1];
float coef22 = mat.m[1][0] * mat.m[3][1] - mat.m[3][0] * mat.m[1][1];
float coef23 = mat.m[1][0] * mat.m[2][1] - mat.m[2][0] * mat.m[1][1];
Vector4 fac0(coef00, coef00, coef02, coef03);
Vector4 fac1(coef04, coef04, coef06, coef07);
Vector4 fac2(coef08, coef08, coef10, coef11);
Vector4 fac3(coef12, coef12, coef14, coef15);
Vector4 fac4(coef16, coef16, coef18, coef19);
Vector4 fac5(coef20, coef20, coef22, coef23);
Vector4 vec0(mat.m[1][0], mat.m[0][0], mat.m[0][0], mat.m[0][0]);
Vector4 vec1(mat.m[1][1], mat.m[0][1], mat.m[0][1], mat.m[0][1]);
Vector4 vec2(mat.m[1][2], mat.m[0][2], mat.m[0][2], mat.m[0][2]);
Vector4 vec3(mat.m[1][3], mat.m[0][3], mat.m[0][3], mat.m[0][3]);
Vector4 inv0(vec1 * fac0 - vec2 * fac1 + vec3 * fac2);
Vector4 inv1(vec0 * fac0 - vec2 * fac3 + vec3 * fac4);
Vector4 inv2(vec0 * fac1 - vec1 * fac3 + vec3 * fac5);
Vector4 inv3(vec0 * fac2 - vec1 * fac4 + vec2 * fac5);
Vector4 signA(+1, -1, +1, -1);
Vector4 signB(-1, +1, -1, +1);
Matrix inverse(inv0 * signA, inv1 * signB, inv2 * signA, inv3 * signB);
Vector4 dot0(mat.m[0][0] * inverse.m[0][0], mat.m[0][1] * inverse.m[1][0], mat.m[0][2] * inverse.m[2][0], mat.m[0][3] * inverse.m[3][0]);
float dot1 = (dot0.x + dot0.y) + (dot0.z + dot0.w);
if (dot1 == 0.0) {
// 計算できない。D3D に合わせて、単位行列で返す
return Identity;
}
float oneOverDeterminant = 1.0f / dot1;
return inverse * oneOverDeterminant;
#endif
#if 0 // 速度は D3DXMatrixInverse の 10倍
int i, j;
float buf;
Matrix tm(mat_);
identity(out_);
// 掃き出し法
for (i = 0; i < 4; ++i)
{
//if (tm.m[ i ][ i ] != 0)
buf = 1.0f / tm.m[i][i]; // 0除算の可能性がある
//else
// buf = 0.0;
for (j = 0; j < 4; ++j)
{
tm.m[i][j] *= buf;
out_->m[i][j] *= buf;
}
for (j = 0; j < 4; ++j)
{
if (i != j)
{
buf = tm.m[j][i];
for (int k = 0; k < 4; ++k)
{
tm.m[j][k] -= tm.m[i][k] * buf;
out_->m[j][k] -= out_->m[i][k] * buf;
}
}
}
}
#endif
#ifdef USE_D3DX9MATH
Matrix out;
D3DXMatrixInverse((D3DXMATRIX*)&out, NULL, (D3DXMATRIX*)&mat);
return out;
#endif
#if 0
// http://www.cg.info.hiroshima-cu.ac.jp/~miyazaki/knowledge/tech23.html
float m0011 = mat_.m[0][0] * mat_.m[1][1];
float m0012 = mat_.m[0][0] * mat_.m[1][2];
float m0021 = mat_.m[0][0] * mat_.m[2][1];
float m0022 = mat_.m[0][0] * mat_.m[2][2];
float m0110 = mat_.m[0][1] * mat_.m[1][0];
float m0112 = mat_.m[0][1] * mat_.m[1][2];
float m0120 = mat_.m[0][1] * mat_.m[2][0];
float m0122 = mat_.m[0][1] * mat_.m[2][2];
float m0210 = mat_.m[0][2] * mat_.m[1][0];
float m0211 = mat_.m[0][2] * mat_.m[1][1];
float m0220 = mat_.m[0][2] * mat_.m[2][0];
float m0221 = mat_.m[0][2] * mat_.m[2][1];
float m1021 = mat_.m[1][0] * mat_.m[2][1];
float m1022 = mat_.m[1][0] * mat_.m[2][2];
float m1120 = mat_.m[1][1] * mat_.m[2][0];
float m1122 = mat_.m[1][1] * mat_.m[2][2];
float m1220 = mat_.m[1][2] * mat_.m[2][0];
float m1221 = mat_.m[1][2] * mat_.m[2][1];
float m1122_m1221 = m1122 - m1221;
float m1220_m1022 = m1220 - m1022;
float m1021_m1120 = m1021 - m1120;
float delta = mat_.m[0][0] * (m1122_m1221)+mat_.m[0][1] * (m1220_m1022)+mat_.m[0][2] * (m1021_m1120);
float rcpDelta = 1.f / delta;
Matrix mat;
mat.m[0][0] = (m1122_m1221)* rcpDelta;
mat.m[1][0] = (m1220_m1022)* rcpDelta;
mat.m[2][0] = (m1021_m1120)* rcpDelta;
mat.m[0][1] = (m0221 - m0122) * rcpDelta;
mat.m[1][1] = (m0022 - m0220) * rcpDelta;
mat.m[2][1] = (m0120 - m0021) * rcpDelta;
mat.m[0][2] = (m0112 - m0211) * rcpDelta;
mat.m[1][2] = (m0210 - m0012) * rcpDelta;
mat.m[2][2] = (m0011 - m0110) * rcpDelta;
float t03 = mat_.m[0][3];
float t13 = mat_.m[1][3];
mat.m[0][3] = -(mat.m[0][0] * t03 + mat.m[0][1] * t13 + mat.m[0][2] * mat_.m[2][3]);
mat.m[1][3] = -(mat.m[1][0] * t03 + mat.m[1][1] * t13 + mat.m[1][2] * mat_.m[2][3]);
mat.m[2][3] = -(mat.m[2][0] * t03 + mat.m[2][1] * t13 + mat.m[2][2] * mat_.m[2][3]);
return mat;
#endif
}
// static
Matrix Matrix::makeTranspose(const Matrix& mat)
{
return Matrix(
mat.m[0][0], mat.m[1][0], mat.m[2][0], mat.m[3][0], mat.m[0][1], mat.m[1][1], mat.m[2][1], mat.m[3][1], mat.m[0][2], mat.m[1][2], mat.m[2][2], mat.m[3][2], mat.m[0][3], mat.m[1][3], mat.m[2][3], mat.m[3][3]);
}
// static
Matrix Matrix::makeReflection(const Plane& plane_)
{
Plane plane = Plane::normalize(plane_);
float x = plane.normal.x;
float y = plane.normal.y;
float z = plane.normal.z;
float x2 = -2.0f * x;
float y2 = -2.0f * y;
float z2 = -2.0f * z;
return Matrix(
(x2 * x) + 1.0f, y2 * x, z2 * x, 0.0f, x2 * y, (y2 * y) + 1.0f, z2 * y, 0.0f, x2 * z, y2 * z, (z2 * z) + 1.0f, 0.0f, x2 * plane.distance, y2 * plane.distance, z2 * plane.distance, 1.0f);
}
// static
Matrix Matrix::makeLookAtLH(const Vector3& position, const Vector3& lookAt, const Vector3& up)
{
Vector3 xaxis, yaxis, zaxis;
// 注視点からカメラ位置までのベクトルをZ軸とする
zaxis = lookAt;
zaxis -= position;
zaxis.mutatingNormalize();
// Z軸と上方向のベクトルの外積をとるとX軸が分かる
xaxis = Vector3::cross(up, zaxis);
xaxis.mutatingNormalize();
// 2つの軸がわかったので、その2つの外積は残りの軸(Y軸)になる
yaxis = Vector3::cross(zaxis, xaxis);
return Matrix(
xaxis.x, yaxis.x, zaxis.x, 0.0f,
xaxis.y, yaxis.y, zaxis.y, 0.0f,
xaxis.z, yaxis.z, zaxis.z, 0.0f,
-(xaxis.x * position.x + xaxis.y * position.y + xaxis.z * position.z),
-(yaxis.x * position.x + yaxis.y * position.y + yaxis.z * position.z),
-(zaxis.x * position.x + zaxis.y * position.y + zaxis.z * position.z),
1.0f);
}
// static
Matrix Matrix::makeLookAtRH(const Vector3& position, const Vector3& lookAt, const Vector3& up)
{
Vector3 xaxis, yaxis, zaxis;
// 注視点からカメラ位置までのベクトルをZ軸とする
zaxis = position;
zaxis -= lookAt;
zaxis.mutatingNormalize();
// Z軸と上方向のベクトルの外積をとるとX軸が分かる
xaxis = Vector3::cross(up, zaxis);
xaxis.mutatingNormalize();
// 2つの軸がわかったので、その2つの外積は残りの軸(Y軸)になる
yaxis = Vector3::cross(zaxis, xaxis);
return Matrix(
xaxis.x, yaxis.x, zaxis.x, 0.0f,
xaxis.y, yaxis.y, zaxis.y, 0.0f,
xaxis.z, yaxis.z, zaxis.z, 0.0f,
-(xaxis.x * position.x + xaxis.y * position.y + xaxis.z * position.z),
-(yaxis.x * position.x + yaxis.y * position.y + yaxis.z * position.z),
-(zaxis.x * position.x + zaxis.y * position.y + zaxis.z * position.z),
1.0f);
}
// static
Matrix Matrix::makePerspectiveFovLH(float fovY, float aspect, float nearZ, float farZ)
{
float h = 1.f / tanf(fovY * 0.5f); // cot(fovY/2)
return Matrix(
h / aspect, 0.0f, 0.0f, 0.0f,
0.0f, h, 0.0f, 0.0f,
0.0f, 0.0f, farZ / (farZ - nearZ), 1.0f,
0.0f, 0.0f, (-nearZ * farZ) / (farZ - nearZ), 0.0f);
}
// static
Matrix Matrix::makePerspectiveFovRH(float fovY, float aspect, float nearZ, float farZ)
{
float h = 1.f / tanf(fovY * 0.5f); // cot(fovY/2)
return Matrix(
h / aspect, 0.0f, 0.0f, 0.0f,
0.0f, h, 0.0f, 0.0f,
0.0f, 0.0f, farZ / (nearZ - farZ), -1.0f,
0.0f, 0.0f, (nearZ * farZ) / (nearZ - farZ), 0.0f);
}
// static
Matrix Matrix::makeOrthoLH(float width, float height, float nearZ, float farZ)
{
return Matrix(
2.0f / width, 0.0f, 0.0f, 0.0f,
0.0f, 2.0f / height, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f / (farZ - nearZ),
0.0f, 0.0f, 0.0f, -nearZ / (nearZ - farZ), 1.0f);
}
// static
Matrix Matrix::makeOrthoRH(float width, float height, float nearZ, float farZ)
{
return Matrix(
2.0f / width, 0.0f, 0.0f, 0.0f,
0.0f, 2.0f / height, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f / (nearZ - farZ), 0.0f,
0.0f, 0.0f, nearZ / (nearZ - farZ), 1.0f);
}
// static
Matrix Matrix::makePerspective2DLH(float width, float height, float nearZ, float farZ)
{
return Matrix(
2.0f / width, 0.0f, 0.0f, 0.0f,
0.0f, -2.0f / height, 0.0f, 0.0f,
0.0f, 0.0f, -1.0f / (farZ - nearZ), 0.0f,
-1.0f, 1.0f, -nearZ / (nearZ - farZ) + 1.0f, 1.0f);
}
// static
Matrix Matrix::makePerspective2DRH(float width, float height, float nearZ, float farZ)
{
return Matrix(
-2.0f / width,0.0f, 0.0f, 0.0f,
0.0f, -2.0f / height, 0.0f, 0.0f,
0.0f, 0.0f, -1.0f / (nearZ - farZ), 0.0f,
-1.0f, 1.0f, nearZ / (nearZ - farZ)/* + 1.0f*/, 1.0f);
}
// static
Matrix Matrix::makeAffineTransformation(const Vector3& scaling, const Vector3& rotationCenter, const Quaternion& rotation, const Vector3& translation)
{
Matrix m = Matrix::makeScaling(scaling);
m.translate(-rotationCenter);
m.rotateQuaternion(rotation);
m.translate(rotationCenter);
m.translate(translation);
return m;
}
Matrix Matrix::extractRotation(const Matrix& mat)
{
Matrix result;
auto& d = result.m;
const auto& s = mat.m;
float scaleX = 1.0f / Vector3(s[0][0], s[1][0], s[2][0]).length();
float scaleY = 1.0f / Vector3(s[0][1], s[1][1], s[2][1]).length();
float scaleZ = 1.0f / Vector3(s[0][2], s[1][2], s[2][2]).length();
d[0][0] = s[0][0] * scaleX;
d[1][0] = s[1][0] * scaleX;
d[2][0] = s[2][0] * scaleX;
d[0][1] = s[0][1] * scaleY;
d[1][1] = s[1][1] * scaleY;
d[2][1] = s[2][1] * scaleY;
d[0][2] = s[0][2] * scaleZ;
d[1][2] = s[1][2] * scaleZ;
d[2][2] = s[2][2] * scaleZ;
return result;
}
// Note: inverse(lookAtLH) と同じ結果 (誤差はあるけど)
Matrix Matrix::makeAffineLookAtLH(const Vector3& eye, const Vector3& target, const Vector3& up)
{
if (target == eye) return Matrix::Identity;
// left-hand coord
Vector3 f = Vector3::normalize(target - eye);
Vector3 s = Vector3::cross(up, f);
if (Vector3::nearEqual(s, Vector3::Zero))
{
if (Math::nearEqual(std::abs(up.z), 1.0f)) {
f.x += 0.0001f;
}
else {
f.z += 0.0001f;
}
f.mutatingNormalize();
s = Vector3::cross(up, f);
}
s.mutatingNormalize();
Vector3 u = Vector3::cross(f, s);
return Matrix(
s.x, s.y, s.z, 0.0f,
u.x, u.y, u.z, 0.0f,
f.x, f.y, f.z, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
}
Matrix& Matrix::operator*=(const Matrix& matrix)
{
float mx0 = m[0][0];
float mx1 = m[0][1];
float mx2 = m[0][2];
m[0][0] = mx0 * matrix.m[0][0] + mx1 * matrix.m[1][0] + mx2 * matrix.m[2][0] + m[0][3] * matrix.m[3][0];
m[0][1] = mx0 * matrix.m[0][1] + mx1 * matrix.m[1][1] + mx2 * matrix.m[2][1] + m[0][3] * matrix.m[3][1];
m[0][2] = mx0 * matrix.m[0][2] + mx1 * matrix.m[1][2] + mx2 * matrix.m[2][2] + m[0][3] * matrix.m[3][2];
m[0][3] = mx0 * matrix.m[0][3] + mx1 * matrix.m[1][3] + mx2 * matrix.m[2][3] + m[0][3] * matrix.m[3][3];
mx0 = m[1][0];
mx1 = m[1][1];
mx2 = m[1][2];
m[1][0] = mx0 * matrix.m[0][0] + mx1 * matrix.m[1][0] + mx2 * matrix.m[2][0] + m[1][3] * matrix.m[3][0];
m[1][1] = mx0 * matrix.m[0][1] + mx1 * matrix.m[1][1] + mx2 * matrix.m[2][1] + m[1][3] * matrix.m[3][1];
m[1][2] = mx0 * matrix.m[0][2] + mx1 * matrix.m[1][2] + mx2 * matrix.m[2][2] + m[1][3] * matrix.m[3][2];
m[1][3] = mx0 * matrix.m[0][3] + mx1 * matrix.m[1][3] + mx2 * matrix.m[2][3] + m[1][3] * matrix.m[3][3];
mx0 = m[2][0];
mx1 = m[2][1];
mx2 = m[2][2];
m[2][0] = mx0 * matrix.m[0][0] + mx1 * matrix.m[1][0] + mx2 * matrix.m[2][0] + m[2][3] * matrix.m[3][0];
m[2][1] = mx0 * matrix.m[0][1] + mx1 * matrix.m[1][1] + mx2 * matrix.m[2][1] + m[2][3] * matrix.m[3][1];
m[2][2] = mx0 * matrix.m[0][2] + mx1 * matrix.m[1][2] + mx2 * matrix.m[2][2] + m[2][3] * matrix.m[3][2];
m[2][3] = mx0 * matrix.m[0][3] + mx1 * matrix.m[1][3] + mx2 * matrix.m[2][3] + m[2][3] * matrix.m[3][3];
mx0 = m[3][0];
mx1 = m[3][1];
mx2 = m[3][2];
m[3][0] = mx0 * matrix.m[0][0] + mx1 * matrix.m[1][0] + mx2 * matrix.m[2][0] + m[3][3] * matrix.m[3][0];
m[3][1] = mx0 * matrix.m[0][1] + mx1 * matrix.m[1][1] + mx2 * matrix.m[2][1] + m[3][3] * matrix.m[3][1];
m[3][2] = mx0 * matrix.m[0][2] + mx1 * matrix.m[1][2] + mx2 * matrix.m[2][2] + m[3][3] * matrix.m[3][2];
m[3][3] = mx0 * matrix.m[0][3] + mx1 * matrix.m[1][3] + mx2 * matrix.m[2][3] + m[3][3] * matrix.m[3][3];
return (*this);
}
Matrix operator*(const Matrix& mat1, const Matrix& mat2)
{
return Matrix::multiply(mat1, mat2);
}
Matrix operator*(const Matrix& mat1, float v)
{
return Matrix(
mat1.m[0][0] * v, mat1.m[0][1] * v, mat1.m[0][2] * v, mat1.m[0][3] * v, mat1.m[1][0] * v, mat1.m[1][1] * v, mat1.m[1][2] * v, mat1.m[1][3] * v, mat1.m[2][0] * v, mat1.m[2][1] * v, mat1.m[2][2] * v, mat1.m[2][3] * v, mat1.m[3][0] * v, mat1.m[3][1] * v, mat1.m[3][2] * v, mat1.m[3][3] * v);
}
static bool equals(const Matrix& value1, const Matrix& value2)
{
return (
value1.m11 == value2.m11 && value1.m12 == value2.m12 && value1.m13 == value2.m13 && value1.m14 == value2.m14 &&
value1.m21 == value2.m21 && value1.m22 == value2.m22 && value1.m23 == value2.m23 && value1.m24 == value2.m24 &&
value1.m31 == value2.m31 && value1.m32 == value2.m32 && value1.m33 == value2.m33 && value1.m34 == value2.m34 &&
value1.m41 == value2.m41 && value1.m42 == value2.m42 && value1.m43 == value2.m43 && value1.m44 == value2.m44);
}
bool Matrix::operator==(const Matrix& mat) const
{
return equals(*this, mat);
}
bool Matrix::operator!=(const Matrix& mat) const
{
return !equals(*this, mat);
}
} // namespace ln
| 30.575635 | 368 | 0.465548 | GameDevery |
3862f1bf18c94812188ef2a7aabf38130014edd7 | 9,408 | cc | C++ | test/test_psend_precv.cc | mpi-advance/Exhanced-MPL-tiny- | 9585fdc337a69c207a7c771d850b5ad7542666fa | [
"BSD-3-Clause"
] | 2 | 2021-10-13T03:55:48.000Z | 2022-01-28T15:33:54.000Z | test/test_psend_precv.cc | mpi-advance/mpl-subset | 9585fdc337a69c207a7c771d850b5ad7542666fa | [
"BSD-3-Clause"
] | null | null | null | test/test_psend_precv.cc | mpi-advance/mpl-subset | 9585fdc337a69c207a7c771d850b5ad7542666fa | [
"BSD-3-Clause"
] | null | null | null | #define BOOST_TEST_MODULE psend_precv
#include <boost/test/included/unit_test.hpp>
#include <limits>
#include <cstddef>
#include <complex>
#include <mpl/mpl.hpp>
template<typename T>
bool psend_precv_test(const T &data) {
const mpl::communicator &comm_world = mpl::environment::comm_world();
if (comm_world.size() < 2)
return false;
if (comm_world.rank() == 0) {
auto r{comm_world.send_init(data, 1)};
r.start();
r.wait();
}
if (comm_world.rank() == 1) {
T data_r;
auto r{comm_world.recv_init(data_r, 0)};
r.start();
while (not r.test().first) {
}
return data_r == data;
}
return true;
}
template<typename T>
bool pbsend_precv_test(const T &data) {
const mpl::communicator &comm_world = mpl::environment::comm_world();
if (comm_world.size() < 2)
return false;
if (comm_world.rank() == 0) {
const int size{comm_world.bsend_size<T>()};
mpl::bsend_buffer<> buff(size);
auto r{comm_world.bsend_init(data, 1)};
r.start();
r.wait();
}
if (comm_world.rank() == 1) {
T data_r;
auto r{comm_world.recv_init(data_r, 0)};
r.start();
while (not r.test().first) {
}
return data_r == data;
}
return true;
}
template<typename T>
bool pssend_precv_test(const T &data) {
const mpl::communicator &comm_world = mpl::environment::comm_world();
if (comm_world.size() < 2)
return false;
if (comm_world.rank() == 0) {
auto r{comm_world.ssend_init(data, 1)};
r.start();
r.wait();
}
if (comm_world.rank() == 1) {
T data_r;
auto r{comm_world.recv_init(data_r, 0)};
r.start();
while (not r.test().first) {
}
return data_r == data;
}
return true;
}
template<typename T>
bool prsend_precv_test(const T &data) {
const mpl::communicator &comm_world = mpl::environment::comm_world();
if (comm_world.size() < 2)
return false;
if (comm_world.rank() == 0) {
comm_world.barrier();
auto r{comm_world.rsend_init(data, 1)};
r.start();
r.wait();
} else if (comm_world.rank() == 1) {
T data_r;
auto r{comm_world.recv_init(data_r, 0)};
r.start();
comm_world.barrier();
while (not r.test().first) {
}
return data_r == data;
} else
comm_world.barrier();
return true;
}
BOOST_AUTO_TEST_CASE(psend_precv) {
// integer types
BOOST_TEST(psend_precv_test(std::byte(77)));
BOOST_TEST(psend_precv_test(std::numeric_limits<char>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<signed char>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<unsigned char>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<signed short>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<unsigned short>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<signed int>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<unsigned int>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<signed long>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<unsigned long>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<signed long long>::max() - 1));
BOOST_TEST(psend_precv_test(std::numeric_limits<unsigned long long>::max() - 1));
// character types
BOOST_TEST(psend_precv_test(static_cast<wchar_t>('A')));
BOOST_TEST(psend_precv_test(static_cast<char16_t>('A')));
BOOST_TEST(psend_precv_test(static_cast<char32_t>('A')));
// floating point number types
BOOST_TEST(psend_precv_test(static_cast<float>(3.14)));
BOOST_TEST(psend_precv_test(static_cast<double>(3.14)));
BOOST_TEST(psend_precv_test(static_cast<long double>(3.14)));
BOOST_TEST(psend_precv_test(std::complex<float>(3.14, 2.72)));
BOOST_TEST(psend_precv_test(std::complex<double>(3.14, 2.72)));
BOOST_TEST(psend_precv_test(std::complex<long double>(3.14, 2.72)));
// logical type
BOOST_TEST(psend_precv_test(true));
// enums
enum class my_enum : int { val = std::numeric_limits<int>::max() - 1 };
BOOST_TEST(psend_precv_test(my_enum::val));
}
BOOST_AUTO_TEST_CASE(pbsend_precv) {
// integer types
BOOST_TEST(pbsend_precv_test(std::byte(77)));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<char>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<signed char>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<unsigned char>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<signed short>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<unsigned short>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<signed int>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<unsigned int>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<signed long>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<unsigned long>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<signed long long>::max() - 1));
BOOST_TEST(pbsend_precv_test(std::numeric_limits<unsigned long long>::max() - 1));
// character types
BOOST_TEST(pbsend_precv_test(static_cast<wchar_t>('A')));
BOOST_TEST(pbsend_precv_test(static_cast<char16_t>('A')));
BOOST_TEST(pbsend_precv_test(static_cast<char32_t>('A')));
// floating point number types
BOOST_TEST(pbsend_precv_test(static_cast<float>(3.14)));
BOOST_TEST(pbsend_precv_test(static_cast<double>(3.14)));
BOOST_TEST(pbsend_precv_test(static_cast<long double>(3.14)));
BOOST_TEST(pbsend_precv_test(std::complex<float>(3.14, 2.72)));
BOOST_TEST(pbsend_precv_test(std::complex<double>(3.14, 2.72)));
BOOST_TEST(pbsend_precv_test(std::complex<long double>(3.14, 2.72)));
// logical type
BOOST_TEST(pbsend_precv_test(true));
// enums
enum class my_enum : int { val = std::numeric_limits<int>::max() - 1 };
BOOST_TEST(pbsend_precv_test(my_enum::val));
}
BOOST_AUTO_TEST_CASE(pssend_precv) {
// integer types
BOOST_TEST(pssend_precv_test(std::byte(77)));
BOOST_TEST(pssend_precv_test(std::numeric_limits<char>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<signed char>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<unsigned char>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<signed short>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<unsigned short>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<signed int>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<unsigned int>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<signed long>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<unsigned long>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<signed long long>::max() - 1));
BOOST_TEST(pssend_precv_test(std::numeric_limits<unsigned long long>::max() - 1));
// character types
BOOST_TEST(pssend_precv_test(static_cast<wchar_t>('A')));
BOOST_TEST(pssend_precv_test(static_cast<char16_t>('A')));
BOOST_TEST(pssend_precv_test(static_cast<char32_t>('A')));
// floating point number types
BOOST_TEST(pssend_precv_test(static_cast<float>(3.14)));
BOOST_TEST(pssend_precv_test(static_cast<double>(3.14)));
BOOST_TEST(pssend_precv_test(static_cast<long double>(3.14)));
BOOST_TEST(pssend_precv_test(std::complex<float>(3.14, 2.72)));
BOOST_TEST(pssend_precv_test(std::complex<double>(3.14, 2.72)));
BOOST_TEST(pssend_precv_test(std::complex<long double>(3.14, 2.72)));
// logical type
BOOST_TEST(pssend_precv_test(true));
// enums
enum class my_enum : int { val = std::numeric_limits<int>::max() - 1 };
BOOST_TEST(pssend_precv_test(my_enum::val));
}
BOOST_AUTO_TEST_CASE(prsend_precv) {
// integer types
BOOST_TEST(prsend_precv_test(std::byte(77)));
BOOST_TEST(prsend_precv_test(std::numeric_limits<char>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<signed char>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<unsigned char>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<signed short>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<unsigned short>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<signed int>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<unsigned int>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<signed long>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<unsigned long>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<signed long long>::max() - 1));
BOOST_TEST(prsend_precv_test(std::numeric_limits<unsigned long long>::max() - 1));
// character types
BOOST_TEST(prsend_precv_test(static_cast<wchar_t>('A')));
BOOST_TEST(prsend_precv_test(static_cast<char16_t>('A')));
BOOST_TEST(prsend_precv_test(static_cast<char32_t>('A')));
// floating point number types
BOOST_TEST(prsend_precv_test(static_cast<float>(3.14)));
BOOST_TEST(prsend_precv_test(static_cast<double>(3.14)));
BOOST_TEST(prsend_precv_test(static_cast<long double>(3.14)));
BOOST_TEST(prsend_precv_test(std::complex<float>(3.14, 2.72)));
BOOST_TEST(prsend_precv_test(std::complex<double>(3.14, 2.72)));
BOOST_TEST(prsend_precv_test(std::complex<long double>(3.14, 2.72)));
// logical type
BOOST_TEST(prsend_precv_test(true));
// enums
enum class my_enum : int { val = std::numeric_limits<int>::max() - 1 };
BOOST_TEST(prsend_precv_test(my_enum::val));
}
| 41.813333 | 84 | 0.713861 | mpi-advance |