hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3980ddb11912c717756203aedbd529e1a02bc41c | 15,018 | cpp | C++ | test/v13/multipart/queue_stats_test.cpp | amedama41/bulb | 2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb | [
"BSL-1.0"
] | null | null | null | test/v13/multipart/queue_stats_test.cpp | amedama41/bulb | 2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb | [
"BSL-1.0"
] | 8 | 2016-07-21T11:29:13.000Z | 2016-12-03T05:16:42.000Z | test/v13/multipart/queue_stats_test.cpp | amedama41/bulb | 2e9fd8a8c35cfc2be2ecf5f747f83cf36ffbbdbb | [
"BSL-1.0"
] | null | null | null | #define BOOST_TEST_DYN_LINK
#include <canard/net/ofp/v13/message/multipart/queue_stats.hpp>
#include <boost/test/unit_test.hpp>
#include <cstdint>
#include <vector>
#include <canard/net/ofp/v13/io/openflow.hpp>
#include "../../test_utility.hpp"
namespace of = canard::net::ofp;
namespace v13 = of::v13;
namespace multipart = v13::messages::multipart;
namespace protocol = v13::protocol;
namespace {
using body_type = multipart::queue_stats_reply::body_type;
struct queue_stats_parameter {
std::uint32_t queue_id = 0x12345678;
std::uint32_t port_no = protocol::OFPP_MAX;
std::uint64_t tx_packets = 0x0102030405060708;
std::uint64_t tx_bytes = 0xf1f2f3f4f5f6f7f8;
std::uint64_t tx_errors = 0xff00ff00ff00ff00;
v13::elapsed_time elapsed_time{0x1234, 0x5678};
};
struct queue_stats_fixture : queue_stats_parameter {
multipart::queue_stats sut{
queue_id, port_no, tx_packets, tx_bytes, tx_errors, elapsed_time
};
std::vector<std::uint8_t> bin
= "\xff\xff\xff\x00\x12\x34\x56\x78""\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8"
"\x01\x02\x03\x04\x05\x06\x07\x08""\xff\x00\xff\x00\xff\x00\xff\x00"
"\x00\x00\x12\x34\x00\x00\x56\x78"
""_bin
;
};
struct queue_stats_request_parameter {
std::uint32_t queue_id = 0x12345678;
std::uint32_t port_no = protocol::OFPP_MAX;
std::uint32_t xid = 0x12345678;
};
struct queue_stats_request_fixture : queue_stats_request_parameter {
multipart::queue_stats_request sut{queue_id, port_no, xid};
std::vector<std::uint8_t> bin
= "\x04\x12\x00\x18\x12\x34\x56\x78""\x00\x05\x00\x00\x00\x00\x00\x00"
"\xff\xff\xff\x00\x12\x34\x56\x78"
""_bin
;
};
struct body_fixture {
multipart::queue_stats queue_stats0{
0x1, 0x1
, 0x0102030405060708, 0xf1f2f3f4f5f6f7f8, 0xff00ff00ff00ff00
, v13::elapsed_time{0x10001234, 0x10005678}
};
multipart::queue_stats queue_stats1{
0xfffffffe, 0x1
, 0x1112131415161718, 0xe1e2e3e4e5e6e7e8, 0xee00ee00ee00ee00
, v13::elapsed_time{0x20001234, 0x20005678}
};
multipart::queue_stats queue_stats2{
0x2, protocol::OFPP_MAX
, 0x8182838485868788, 0xa1a2a3a4a5a6a7a8, 0xbf00bf00bf00bf00
, v13::elapsed_time{0x30001234, 0x30005678}
};
};
struct queue_stats_reply_parameter : body_fixture {
body_type body{queue_stats0, queue_stats1, queue_stats2};
std::uint16_t flags = protocol::OFPMPF_REPLY_MORE;
std::uint32_t xid = 0x12345678;
};
struct queue_stats_reply_fixture : queue_stats_reply_parameter {
multipart::queue_stats_reply sut{body, flags, xid};
std::vector<std::uint8_t> bin
= "\x04\x13\x00\x88\x12\x34\x56\x78""\x00\x05\x00\x01\x00\x00\x00\x00"
"\x00\x00\x00\x01\x00\x00\x00\x01""\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8"
"\x01\x02\x03\x04\x05\x06\x07\x08""\xff\x00\xff\x00\xff\x00\xff\x00"
"\x10\x00\x12\x34\x10\x00\x56\x78"
"\x00\x00\x00\x01\xff\xff\xff\xfe""\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8"
"\x11\x12\x13\x14\x15\x16\x17\x18""\xee\x00\xee\x00\xee\x00\xee\x00"
"\x20\x00\x12\x34\x20\x00\x56\x78"
"\xff\xff\xff\x00\x00\x00\x00\x02""\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8"
"\x81\x82\x83\x84\x85\x86\x87\x88""\xbf\x00\xbf\x00\xbf\x00\xbf\x00"
"\x30\x00\x12\x34\x30\x00\x56\x78"
""_bin
;
};
}
BOOST_AUTO_TEST_SUITE(message_test)
BOOST_AUTO_TEST_SUITE(multipart_test)
BOOST_AUTO_TEST_SUITE(queue_stats)
BOOST_AUTO_TEST_SUITE(constructor)
BOOST_AUTO_TEST_CASE(constructible)
{
auto const queue_id = std::uint32_t{3};
auto const port_no = std::uint32_t{1};
auto const tx_packets = std::uint64_t{1234};
auto const tx_bytes = std::uint64_t{5678};
auto const tx_errors = std::uint64_t{987654};
auto const elapsed_time = v13::elapsed_time{32, 45};
multipart::queue_stats const sut{
queue_id, port_no, tx_packets, tx_bytes, tx_errors, elapsed_time
};
BOOST_TEST(sut.length() == sizeof(protocol::ofp_queue_stats));
BOOST_TEST(sut.queue_id() == queue_id);
BOOST_TEST(sut.port_no() == port_no);
BOOST_TEST(sut.tx_packets() == tx_packets);
BOOST_TEST(sut.tx_bytes() == tx_bytes);
BOOST_TEST(sut.tx_errors() == tx_errors);
BOOST_TEST(sut.duration_sec() == elapsed_time.duration_sec());
BOOST_TEST(sut.duration_nsec() == elapsed_time.duration_nsec());
}
BOOST_FIXTURE_TEST_CASE(copy_constructible, queue_stats_fixture)
{
auto const copy = sut;
BOOST_TEST((copy == sut));
}
BOOST_AUTO_TEST_SUITE_END() // constructor
BOOST_FIXTURE_TEST_SUITE(equality, queue_stats_parameter)
BOOST_AUTO_TEST_CASE(true_if_same_object)
{
auto const sut = multipart::queue_stats{
queue_id, port_no, tx_packets, tx_bytes, tx_errors, elapsed_time
};
BOOST_TEST((sut == sut));
}
BOOST_AUTO_TEST_CASE(true_if_values_are_equal)
{
BOOST_TEST(
(multipart::queue_stats{
queue_id, port_no, tx_packets, tx_bytes, tx_errors, elapsed_time
}
== multipart::queue_stats{
queue_id, port_no, tx_packets, tx_bytes, tx_errors, elapsed_time
}));
}
BOOST_AUTO_TEST_CASE(false_if_queue_id_is_not_equal)
{
BOOST_TEST(
(multipart::queue_stats{
1, port_no, tx_packets, tx_bytes, tx_errors, elapsed_time
}
!= multipart::queue_stats{
2, port_no, tx_packets, tx_bytes, tx_errors, elapsed_time
}));
}
BOOST_AUTO_TEST_CASE(false_if_port_no_is_not_equal)
{
BOOST_TEST(
(multipart::queue_stats{
queue_id, 1, tx_packets, tx_bytes, tx_errors, elapsed_time
}
!= multipart::queue_stats{
queue_id, 2, tx_packets, tx_bytes, tx_errors, elapsed_time
}));
}
BOOST_AUTO_TEST_CASE(false_if_tx_packets_is_not_equal)
{
BOOST_TEST(
(multipart::queue_stats{
queue_id, port_no, 1, tx_bytes, tx_errors, elapsed_time
}
!= multipart::queue_stats{
queue_id, port_no, 2, tx_bytes, tx_errors, elapsed_time
}));
}
BOOST_AUTO_TEST_CASE(false_if_tx_bytes_is_not_equal)
{
BOOST_TEST(
(multipart::queue_stats{
queue_id, port_no, tx_packets, 1, tx_errors, elapsed_time
}
!= multipart::queue_stats{
queue_id, port_no, tx_packets, 2, tx_errors, elapsed_time
}));
}
BOOST_AUTO_TEST_CASE(false_if_tx_errors_is_not_equal)
{
BOOST_TEST(
(multipart::queue_stats{
queue_id, port_no, tx_packets, tx_bytes, 1, elapsed_time
}
!= multipart::queue_stats{
queue_id, port_no, tx_packets, tx_bytes, 2, elapsed_time
}));
}
BOOST_AUTO_TEST_CASE(false_if_duration_sec_is_not_equal)
{
BOOST_TEST(
(multipart::queue_stats{
queue_id, port_no, tx_packets, tx_bytes, tx_errors
, v13::elapsed_time{1, 0}
}
!= multipart::queue_stats{
queue_id, port_no, tx_packets, tx_bytes, tx_errors
, v13::elapsed_time{2, 0}
}));
}
BOOST_AUTO_TEST_CASE(false_if_duration_nsec_is_not_equal)
{
BOOST_TEST(
(multipart::queue_stats{
queue_id, port_no, tx_packets, tx_bytes, tx_errors
, v13::elapsed_time{0, 1}
}
!= multipart::queue_stats{
queue_id, port_no, tx_packets, tx_bytes, tx_errors
, v13::elapsed_time{0, 2}
}));
}
BOOST_AUTO_TEST_SUITE_END() // equality
BOOST_AUTO_TEST_SUITE(encode)
BOOST_FIXTURE_TEST_CASE(generate_binary, queue_stats_fixture)
{
auto buffer = std::vector<std::uint8_t>{};
sut.encode(buffer);
BOOST_TEST(buffer.size() == sut.byte_length());
BOOST_TEST(buffer == bin, boost::test_tools::per_element{});
}
BOOST_AUTO_TEST_SUITE_END() // encode
BOOST_AUTO_TEST_SUITE(decode)
BOOST_FIXTURE_TEST_CASE(construct_from_binary, queue_stats_fixture)
{
auto it = bin.begin();
auto const queue_stats = multipart::queue_stats::decode(it, bin.end());
BOOST_TEST((it == bin.end()));
BOOST_TEST((queue_stats == sut));
}
BOOST_AUTO_TEST_SUITE_END() // decode
BOOST_AUTO_TEST_SUITE_END() // queue_stats
BOOST_AUTO_TEST_SUITE(queue_stats_request)
BOOST_AUTO_TEST_SUITE(constructor)
BOOST_AUTO_TEST_CASE(constructible)
{
auto const queue_id = std::uint32_t{93283};
auto const port_no = std::uint32_t{7833};
multipart::queue_stats_request const sut{queue_id, port_no};
BOOST_TEST(sut.version() == protocol::OFP_VERSION);
BOOST_TEST(sut.type() == protocol::OFPT_MULTIPART_REQUEST);
BOOST_TEST(sut.length() == sizeof(protocol::ofp_multipart_request)
+ sizeof(protocol::ofp_queue_stats_request));
BOOST_TEST(sut.multipart_type() == protocol::OFPMP_QUEUE);
BOOST_TEST(sut.flags() == 0);
BOOST_TEST(sut.queue_id() == queue_id);
BOOST_TEST(sut.port_no() == port_no);
}
BOOST_FIXTURE_TEST_CASE(copy_constructible, queue_stats_request_fixture)
{
auto const copy = sut;
BOOST_TEST((copy == sut));
}
BOOST_AUTO_TEST_SUITE_END() // constructor
BOOST_FIXTURE_TEST_SUITE(equality, queue_stats_request_parameter)
BOOST_AUTO_TEST_CASE(true_if_same_object)
{
auto const sut = multipart::queue_stats_request{queue_id, port_no, xid};
BOOST_TEST((sut == sut));
}
BOOST_AUTO_TEST_CASE(true_if_values_are_equal)
{
BOOST_TEST(
(multipart::queue_stats_request{queue_id, port_no, xid}
== multipart::queue_stats_request{queue_id, port_no, xid}));
}
BOOST_AUTO_TEST_CASE(false_if_queue_id_is_not_equal)
{
BOOST_TEST(
(multipart::queue_stats_request{1, port_no, xid}
!= multipart::queue_stats_request{2, port_no, xid}));
}
BOOST_AUTO_TEST_CASE(false_if_port_no_is_not_equal)
{
BOOST_TEST(
(multipart::queue_stats_request{queue_id, 1, xid}
!= multipart::queue_stats_request{queue_id, 2, xid}));
}
BOOST_AUTO_TEST_CASE(false_if_xid_is_not_equal)
{
BOOST_TEST(
(multipart::queue_stats_request{queue_id, port_no, 1}
!= multipart::queue_stats_request{queue_id, port_no, 2}));
}
BOOST_AUTO_TEST_SUITE_END() // equality
BOOST_AUTO_TEST_SUITE(encode)
BOOST_FIXTURE_TEST_CASE(generate_binary, queue_stats_request_fixture)
{
auto buffer = std::vector<std::uint8_t>{};
sut.encode(buffer);
BOOST_TEST(buffer.size() == sut.byte_length());
BOOST_TEST(buffer == bin, boost::test_tools::per_element{});
}
BOOST_AUTO_TEST_SUITE_END() // encode
BOOST_AUTO_TEST_SUITE(decode)
BOOST_FIXTURE_TEST_CASE(construct_from_binary, queue_stats_request_fixture)
{
auto it = bin.begin();
auto const queue_stats_request
= multipart::queue_stats_request::decode(it, bin.end());
BOOST_TEST((it == bin.end()));
BOOST_TEST((queue_stats_request == sut));
}
BOOST_AUTO_TEST_SUITE_END() // decode
BOOST_AUTO_TEST_SUITE_END() // queue_stats_request
BOOST_AUTO_TEST_SUITE(queue_stats_reply)
BOOST_AUTO_TEST_SUITE(constructor)
BOOST_FIXTURE_TEST_CASE(constructible, body_fixture)
{
auto const body = ::body_type{queue_stats0, queue_stats1};
multipart::queue_stats_reply const sut{body};
BOOST_TEST(sut.version() == protocol::OFP_VERSION);
BOOST_TEST(sut.type() == protocol::OFPT_MULTIPART_REPLY);
BOOST_TEST(sut.length() == sizeof(protocol::ofp_multipart_request)
+ body.length());
BOOST_TEST(sut.multipart_type() == protocol::OFPMP_QUEUE);
BOOST_TEST(sut.flags() == 0);
BOOST_TEST((sut.body() == body));
}
BOOST_FIXTURE_TEST_CASE(copy_constructible, queue_stats_reply_fixture)
{
auto const copy = sut;
BOOST_TEST((copy == sut));
}
BOOST_FIXTURE_TEST_CASE(move_constructible, queue_stats_reply_fixture)
{
auto moved = sut;
auto const copy = std::move(moved);
BOOST_TEST((copy == sut));
BOOST_TEST(moved.length() == sizeof(protocol::ofp_multipart_reply));
BOOST_TEST(moved.body().empty());
}
BOOST_AUTO_TEST_SUITE_END() // constructor
BOOST_FIXTURE_TEST_SUITE(assignment, queue_stats_reply_fixture)
BOOST_AUTO_TEST_CASE(copy_assignable)
{
auto copy = multipart::queue_stats_reply{{}};
copy = sut;
BOOST_TEST((copy == sut));
}
BOOST_AUTO_TEST_CASE(move_assignable)
{
auto copy = multipart::queue_stats_reply{{}};
auto moved = sut;
copy = std::move(moved);
BOOST_TEST((copy == sut));
BOOST_TEST(moved.length() == sizeof(protocol::ofp_multipart_reply));
BOOST_TEST(moved.body().empty());
}
BOOST_AUTO_TEST_SUITE_END() // assignment
BOOST_FIXTURE_TEST_SUITE(equality, queue_stats_reply_parameter)
BOOST_AUTO_TEST_CASE(true_if_same_object)
{
auto const sut = multipart::queue_stats_reply{body, flags, xid};
BOOST_TEST((sut == sut));
}
BOOST_AUTO_TEST_CASE(true_if_values_are_equal)
{
BOOST_TEST(
(multipart::queue_stats_reply{body, flags, xid}
== multipart::queue_stats_reply{body, flags, xid}));
}
BOOST_AUTO_TEST_CASE(false_if_body_is_not_equal)
{
BOOST_TEST(
(multipart::queue_stats_reply{body_type{queue_stats1}, flags, xid}
!= multipart::queue_stats_reply{body_type{queue_stats2}, flags, xid}));
}
BOOST_AUTO_TEST_CASE(false_if_flags_is_not_equal)
{
BOOST_TEST(
(multipart::queue_stats_reply{body, 0, xid}
!= multipart::queue_stats_reply{body, 1, xid}));
}
BOOST_AUTO_TEST_CASE(false_if_xid_is_not_equal)
{
BOOST_TEST(
(multipart::queue_stats_reply{body, flags, 1}
!= multipart::queue_stats_reply{body, flags, 2}));
}
BOOST_AUTO_TEST_SUITE_END() // equality
BOOST_AUTO_TEST_SUITE(encode)
BOOST_FIXTURE_TEST_CASE(generate_binary, queue_stats_reply_fixture)
{
auto buffer = std::vector<std::uint8_t>{};
sut.encode(buffer);
BOOST_TEST(buffer.size() == sut.byte_length());
BOOST_TEST(buffer == bin, boost::test_tools::per_element{});
}
BOOST_AUTO_TEST_SUITE_END() // encode
BOOST_AUTO_TEST_SUITE(decode)
BOOST_FIXTURE_TEST_CASE(construct_from_binary, queue_stats_reply_fixture)
{
auto it = bin.begin();
auto const queue_stats_reply
= multipart::queue_stats_reply::decode(it, bin.end());
BOOST_TEST((it == bin.end()));
BOOST_TEST((queue_stats_reply == sut));
}
BOOST_AUTO_TEST_SUITE_END() // decode
BOOST_AUTO_TEST_SUITE_END() // queue_stats_reply
BOOST_AUTO_TEST_SUITE_END() // multipart_test
BOOST_AUTO_TEST_SUITE_END() // message_test
| 32.862144 | 79 | 0.666933 | [
"vector"
] |
398677fdd6c18e1905f9aadf7c4eaa86cb5098a3 | 38,544 | cpp | C++ | src/binaryServer/HaSession.cpp | peramic/OPC-UA.Server | ebfafb0f9a1943fc1f2d44f20a0497a59e5bfd97 | [
"Apache-2.0"
] | null | null | null | src/binaryServer/HaSession.cpp | peramic/OPC-UA.Server | ebfafb0f9a1943fc1f2d44f20a0497a59e5bfd97 | [
"Apache-2.0"
] | null | null | null | src/binaryServer/HaSession.cpp | peramic/OPC-UA.Server | ebfafb0f9a1943fc1f2d44f20a0497a59e5bfd97 | [
"Apache-2.0"
] | null | null | null | #include "HaSession.h"
#include "Event.h"
#include "EventField.h"
#include "HaSessionException.h"
#include "HaSubscription.h"
#include "HaSubscriptionException.h"
#include "../provider/binary/common/TimeoutException.h"
#include <common/Exception.h>
#include <common/Mutex.h>
#include <common/MutexLock.h>
#include <common/ScopeGuard.h>
#include <common/VectorScopeGuard.h>
#include <common/logging/Logger.h>
#include <common/logging/LoggerFactory.h>
#include <statuscode.h> // UaStatus
#include <uaargument.h> // UaArguments
#include <uaarraytemplates.h> // UaStringArray
#include <uabytestring.h> // UaByteString
#include <uaclientsdk.h> // UaSessionCallback
#include <uadatetime.h> // UaDateTime
#include <uadiagnosticinfos.h> // UaDiagnosticInfos
#include <uaqualifiedname.h> // UaQualifiedName
#include <uanodeid.h> // UaNodeId
#include <uaplatformdefs.h> // UA_GetHostname
#include <uasession.h> // UaSession
#include <uastring.h> // UaString
#include <uastructuredefinition.h> // UaStructureDefinition
#include <uavariant.h> // UaVariant
#include <ctime> // std::time_t
#include <sstream> // std::ostringstream
#include <time.h> // nanosleep
using namespace CommonNamespace;
class HaSessionPrivate: public UaClientSdk::UaSessionCallback {
friend class HaSession;
private:
class HaSessionSubscriptionCallback: public HaSubscription::HaSubscriptionCallback {
public:
HaSessionSubscriptionCallback(HaSession::HaSessionCallback& callback) {
this->callback = &callback;
}
virtual void dataChanged(std::vector<NodeAttributes*>& nodeAttributes)
/*throws Exception */{
try {
// fire event
callback->dataChanged(nodeAttributes); // any exception
} catch (Exception& e) {
HaSessionException ex = ExceptionDef(HaSessionException,
std::string("Cannot send data change notification"));
ex.setCause(&e);
throw ex;
}
}
virtual void newEvents(
std::vector<const BinaryServerNamespace::Event*>& events)
/* throws Exception */{
try {
// fire event
callback->newEvents(events); // any exception
} catch (Exception& e) {
HaSessionException ex = ExceptionDef(HaSessionException,
std::string("Cannot send events"));
ex.setCause(&e);
throw ex;
}
}
private:
HaSession::HaSessionCallback* callback;
};
// Sdk 1.5.2: uaclient/uaclientcpp/uasession.cpp:
// The SDK is managing the connection to the server by
// - Monitoring the status of the session with read calls to the server status variable. The frequency of the read calls can be
// controlled with the setting SessionConnectInfo::nWatchdogTime
// - Reconnect on TCP/IP or SecureChannel level if the connection was lost
// - Recreation of the session if the session timed out or the server was restarted
// - The callback function UaSessionCallback::connectionStatusChanged provides information about the current status of the session
static const OpcUa_Double SESSION_TIMEOUT = 3600000; // in ms
Logger* log;
HaSession* parent;
HaSession::Configuration* conf;
HaSession::HaSessionCallback* callback;
UaString applicationName;
UaString serverUrl;
UaString applicationUri;
UaString productUri;
UaClientSdk::UaSession* session;
HaSubscription* subscription;
HaSessionSubscriptionCallback* subscriptionCallback;
Mutex* mutex;
void read(const std::vector<const UaNodeId*>& nodeIds,
std::vector<OpcUa_UInt32>& attributeIds,
std::vector<NodeAttributes*>& returnNodeAttributes) /* throws HaSessionException */;
void getEventFields(const UaNodeId& eventTypeId,
std::vector<BinaryServerNamespace::EventField*>& returnEventFields)
/*throws HaSessionException*/;
// interface UaSessionCallback
virtual void connectionStatusChanged(OpcUa_UInt32 clientConnectionId,
UaClientSdk::UaClient::ServerStatus serverStatus);
};
HaSession::HaSessionCallback::HaSessionCallback() {
}
HaSession::HaSessionCallback::~HaSessionCallback() {
}
HaSession::HaSession(HaSession::Configuration& conf,
HaSession::HaSessionCallback& callback)
/* throws MutexException */{
d = new HaSessionPrivate();
d->log = LoggerFactory::getLogger("HaSession");
d->parent = this;
d->conf = &conf;
d->callback = &callback;
d->applicationName = UaString("binaryServer");
UaString companyName("harting");
UaString productName("binaryServer");
if (d->conf->port != 0) {
d->serverUrl = UaString("opc.tcp://%1:%2").arg(
UaString(d->conf->host.c_str())).arg(d->conf->port);
} else {
d->serverUrl = UaString("opc.tcp://%1").arg(
UaString(d->conf->host.c_str()));
}
UaString nodeName("unknown_host");
char szHostName[256];
if (0 == UA_GetHostname(szHostName, 256)) {
nodeName = szHostName;
}
d->applicationUri =
UaString("urn:%1:%2:%3").arg(nodeName).arg(companyName).arg(
productName);
d->productUri = UaString("urn:%1:%2").arg(companyName).arg(productName);
d->subscriptionCallback =
new HaSessionPrivate::HaSessionSubscriptionCallback(callback);
d->mutex = new Mutex(); // MutexException
}
HaSession::~HaSession() /* throws HaSessionException */{
close();
delete d->mutex;
delete d->subscriptionCallback;
delete d;
}
void HaSession::open() /* throws HaSessionException */{
MutexLock lock(*d->mutex);
if (d->session != NULL) {
return;
}
// create a new UaSession
d->session = new UaClientSdk::UaSession();
d->subscription = new HaSubscription(*d->session,
d->conf->sendReceiveTimeout, d->conf->publishingInterval,
*d->subscriptionCallback);
UaClientSdk::SessionConnectInfo sessionConnectInfo;
sessionConnectInfo.clientConnectionId = 0;
sessionConnectInfo.sLocaleId = "en";
sessionConnectInfo.sApplicationName = d->applicationName;
sessionConnectInfo.sApplicationUri = d->applicationUri;
sessionConnectInfo.sProductUri = d->productUri;
sessionConnectInfo.sSessionName = sessionConnectInfo.sApplicationUri;
sessionConnectInfo.nSessionTimeout = d->SESSION_TIMEOUT;
sessionConnectInfo.nWatchdogTime = d->conf->watchdogInterval * 1000;
sessionConnectInfo.nWatchdogTimeout = d->conf->sendReceiveTimeout * 1000;
sessionConnectInfo.bAutomaticReconnect = true;
sessionConnectInfo.bRetryInitialConnect = false;
UaClientSdk::SessionSecurityInfo sessionSecurityInfo;
if (d->conf->username != NULL) {
sessionSecurityInfo.setUserPasswordUserIdentity(
UaString(d->conf->username->c_str()),
UaString(d->conf->password->c_str()));
}
timespec reconnectDelay;
reconnectDelay.tv_sec = 0;
reconnectDelay.tv_nsec = 0;
std::time_t time = std::time(NULL);
std::time_t endTime = time + d->conf->connectTimeout;
std::time_t remainingTimeout = endTime - time;
UaStatus result(OpcUa_Bad);
try {
while (!result.isGood()) {
if (remainingTimeout <= 0) {
std::ostringstream msg;
msg << "Time out after " << d->conf->connectTimeout << " sec.";
throw ExceptionDef(TimeoutException, msg.str());
}
sessionConnectInfo.nConnectTimeout = remainingTimeout * 1000;
result = d->session->connect(d->serverUrl, sessionConnectInfo,
sessionSecurityInfo, d /* UaSessionCallback */);
if (result.isGood()) {
// connection has been successfully created => reset reconnect delay
reconnectDelay.tv_sec = 0;
} else {
if (d->log->isWarnEnabled()) {
d->log->warn("Cannot open a connection to %s: %s",
d->serverUrl.toUtf8(), result.toString().toUtf8());
}
// wait some time
if (reconnectDelay.tv_sec < d->conf->maxReconnectDelay) {
reconnectDelay.tv_sec++;
}
remainingTimeout = endTime - std::time(NULL);
if (reconnectDelay.tv_sec > remainingTimeout) {
reconnectDelay.tv_sec = remainingTimeout;
}
d->log->debug("Waiting %ld seconds...", reconnectDelay.tv_sec);
nanosleep(&reconnectDelay, NULL /* remaining */);
remainingTimeout -= reconnectDelay.tv_sec;
}
}
d->log->debug(
"Opened connection to %s (sessionId=%s,revisedSessionTimeout=%d (s),revisedWatchdogInterval=%d (s), sendReceiveTimeout=%d (s), publishInterval=%d (ms), connectTimeout=%d (s))",
d->serverUrl.toUtf8(),
d->session->sessionId().toXmlString().toUtf8(),
(int)(d->session->revisedSessionTimeout() / 1000.0),
d->session->watchdogTime() / 1000,
d->conf->sendReceiveTimeout,
d->conf->publishingInterval,
d->conf->connectTimeout);
} catch (Exception& e) {
delete d->session;
d->session = NULL;
// convert exception to IODataProviderException
std::ostringstream msg;
msg << "Cannot open a connection to " << d->serverUrl.toUtf8()
<< " within " << d->conf->connectTimeout << " seconds";
HaSessionException ex = ExceptionDef(HaSessionException, msg.str());
ex.setCause(&e);
throw ex;
}
}
std::string HaSession::getSessionId() {
return d->session->sessionId().toXmlString().toUtf8();
}
void HaSession::close() /* throws HaSessionException, HaSubscriptionException */{
MutexLock lock(*d->mutex);
if (d->session == NULL) {
return;
}
// delete subscription
delete d->subscription; // HaSubscriptionException
d->subscription = NULL;
// disconnect
UaClientSdk::ServiceSettings serviceSettings;
serviceSettings.callTimeout = d->conf->sendReceiveTimeout * 1000;
UaStatus result = d->session->disconnect(serviceSettings,
OpcUa_True /* deleteSubscriptions*/);
if (result.isGood()) {
if (d->log->isDebugEnabled()) {
d->log->debug("Closed connection %s to %s",
d->session->sessionId().toXmlString().toUtf8(),
d->serverUrl.toUtf8());
}
delete d->session;
d->session = NULL;
} else {
std::ostringstream msg;
msg << "Cannot close the connection to " << d->serverUrl.toUtf8()
<< ": " << result.toString().toUtf8();
throw ExceptionDef(HaSessionException, msg.str());
}
}
UaStringArray HaSession::getNamespaceTable() const {
MutexLock lock(*d->mutex);
if (d->session == NULL) {
throw ExceptionDef(HaSessionException,
std::string(
"Cannot get namespace table due to closed session"));
}
return d->session->getNamespaceTable();
}
UaStructureDefinition HaSession::getStructureDefinition(
const UaNodeId& dataTypeId) {
MutexLock lock(*d->mutex);
if (d->session == NULL) {
throw ExceptionDef(HaSessionException,
std::string(
"Cannot get structure definition due to closed session"));
}
return d->session->structureDefinition(dataTypeId);
}
std::vector<UaNodeId>* HaSession::getSuperTypes(const UaNodeId& typeId)
/*throws HaSessionException*/{
MutexLock lock(*d->mutex);
if (d->session == NULL) {
throw ExceptionDef(HaSessionException,
std::string("Cannot get super types due to closed session"));
}
std::vector<UaNodeId>* ret = new std::vector<UaNodeId>();
UaClientSdk::ServiceSettings serviceSettings;
serviceSettings.callTimeout = d->conf->sendReceiveTimeout * 1000;
UaClientSdk::BrowseContext browseContext;
browseContext.maxReferencesToReturn = 0;
browseContext.browseDirection = OpcUa_BrowseDirection_Inverse;
browseContext.referenceTypeId = OpcUaId_HasSubtype;
browseContext.includeSubtype = OpcUa_True;
browseContext.nodeClassMask = 0;
UaNodeId nodeId = typeId;
while (!nodeId.isNull() && nodeId.namespaceIndex() != 0) {
UaByteString continuationPoint;
UaReferenceDescriptions referenceDescriptions;
UaStatus result = d->session->browse(serviceSettings, nodeId,
browseContext, continuationPoint, referenceDescriptions);
if (!result.isGood()) {
std::ostringstream msg;
msg << "Cannot get super types for "
<< typeId.toXmlString().toUtf8() << ": "
<< result.toString().toUtf8();
throw ExceptionDef(HaSessionException, msg.str());
}
if (referenceDescriptions.length() > 0) {
for (OpcUa_UInt32 i = 0; i < referenceDescriptions.length(); i++) {
nodeId = UaNodeId(referenceDescriptions[i].NodeId.NodeId);
ret->push_back(nodeId);
}
} else {
nodeId = UaNodeId();
}
}
return ret;
}
void HaSession::getMethodArguments(const UaNodeId& methodId,
UaArguments& returnInputArguments,
UaArguments& returnOutputArguments) /* throws HaSessionException */{
MutexLock lock(*d->mutex);
if (d->session == NULL) {
throw ExceptionDef(HaSessionException,
std::string(
"Cannot get method arguments due to closed session"));
}
UaClientSdk::ServiceSettings serviceSettings;
serviceSettings.callTimeout = d->conf->sendReceiveTimeout * 1000;
if (d->log->isDebugEnabled()) {
d->log->debug("Getting method arguments for %s",
methodId.toXmlString().toUtf8());
}
UaStatus result = d->session->getMethodArguments(serviceSettings, methodId,
returnInputArguments, returnOutputArguments);
if (d->log->isDebugEnabled()) {
for (int i = 0; i < returnInputArguments.length(); i++) {
UaArgument arg(returnInputArguments[i]);
d->log->debug("Get method input argument %-20s dataTypeId=%s",
arg.getName().toUtf8(),
arg.getDataType().toXmlString().toUtf8());
}
for (int i = 0; i < returnOutputArguments.length(); i++) {
UaArgument arg(returnOutputArguments[i]);
d->log->debug("Get method output argument %-20s dataTypeId=%s",
arg.getName().toUtf8(),
arg.getDataType().toXmlString().toUtf8());
}
}
if (!result.isGood()) {
std::ostringstream msg;
msg << "Cannot get method arguments for "
<< methodId.toXmlString().toUtf8() << ": "
<< result.toString().toUtf8();
throw ExceptionDef(HaSessionException, msg.str());
}
}
void HaSession::read(const std::vector<const UaNodeId*>& nodeIds,
std::vector<NodeAttributes*>& returnNodeAttributes) /* throws HaSessionException */{
if (nodeIds.size() == 0) {
return;
}
MutexLock lock(*d->mutex);
if (d->session == NULL) {
throw ExceptionDef(HaSessionException,
std::string("Cannot read due to closed session"));
}
// get node classes
std::vector<OpcUa_UInt32> attributeIds;
attributeIds.push_back(OpcUa_Attributes_NodeClass);
//test code for registerNodes (the following read call must be deactivated)
// UaClientSdk::ServiceSettings registerServiceSettings;
// UaNodeIdArray nodesToRegister;
// nodesToRegister.create(nodeIds.size());
// for (OpcUa_Int16 i = 0; i < nodeIds.size(); i++) {
// nodeIds.at(i)->copyTo(&nodesToRegister[i]);
// d->log->debug("Register node %s", nodeIds.at(i)->toXmlString().toUtf8());
// }
// UaNodeIdArray registeredNodes;
// UaStatus registerResult = d->session->registerNodes(registerServiceSettings, nodesToRegister, registeredNodes);
// if (!registerResult.isGood()) {
// throw ExceptionDef(HaSessionException, std::string("Cannot register nodes"));
// }
// std::vector<const UaNodeId*>* registeredNodeIds = new std::vector<const UaNodeId*>();
// VectorScopeGuard<const UaNodeId> registeredNodeIdsSG(registeredNodeIds);
// for (OpcUa_Int16 i = 0; i < registeredNodes.length(); i++) {
// registeredNodeIds->push_back(new UaNodeId(registeredNodes[i]));
// d->log->debug("Registered node %s", registeredNodeIds->at(i)->toXmlString().toUtf8());
// }
// d->read(*registeredNodeIds, attributeIds, returnNodeAttributes); // HaSessionException
d->read(nodeIds, attributeIds, returnNodeAttributes); // HaSessionException
// nodeIdXml -> node attributes
std::map<std::string, NodeAttributes*> retNodeAttrMap;
// get readable nodes (without event types)
std::vector<const UaNodeId*> readableNodeIds;
// for each node
for (int i = 0; i < returnNodeAttributes.size(); i++) {
NodeAttributes& nodeAttr = *returnNodeAttributes[i];
if (nodeAttr.getException() == NULL) {
// if event type
if (*nodeAttr.getNodeClass() == OpcUa_NodeClass_ObjectType) {
// return any value
UaVariant* var = new UaVariant();
var->setByte(1);
nodeAttr.setValue(var);
nodeAttr.setDataType(new UaNodeId(OpcUaType_Byte));
} else {
readableNodeIds.push_back(&nodeAttr.getNodeId());
}
retNodeAttrMap[nodeAttr.getNodeId().toXmlString().toUtf8()] =
&nodeAttr;
}
}
try {
// read values and their data type
if (readableNodeIds.size() > 0) {
attributeIds.clear();
attributeIds.push_back(OpcUa_Attributes_Value);
attributeIds.push_back(OpcUa_Attributes_DataType);
std::vector<NodeAttributes*>* values = new std::vector<
NodeAttributes*>();
d->read(readableNodeIds, attributeIds, *values); // HaSessionException
VectorScopeGuard<NodeAttributes> valuesSG(values);
for (int i = 0; i < values->size(); i++) {
NodeAttributes& nodeAttr = *(*values)[i];
NodeAttributes& retNodeAttr =
*retNodeAttrMap[nodeAttr.getNodeId().toXmlString().toUtf8()];
if (nodeAttr.getValue() != NULL) {
retNodeAttr.setValue(new UaVariant(*nodeAttr.getValue()));
}
if (nodeAttr.getDataType() != NULL) {
retNodeAttr.setDataType(
new UaNodeId(*nodeAttr.getDataType()));
}
if (nodeAttr.getException() != NULL) {
retNodeAttr.setException(nodeAttr.getException()->copy());
}
}
}
} catch (Exception& e) {
// remove added node attributes
for (int i = 0; i < returnNodeAttributes.size(); i++) {
delete returnNodeAttributes[i];
}
returnNodeAttributes.clear();
throw;
}
}
void HaSession::write(const std::map<const UaNodeId*, const UaVariant*>& nodes)
/* throws HaSessionException */{
if (nodes.size() == 0) {
return;
}
MutexLock lock(*d->mutex);
if (d->session == NULL) {
throw ExceptionDef(HaSessionException,
std::string("Cannot write data to closed session"));
}
//test code for registerNodes (the following block creating UaWriteValues must be deactivated)
// UaClientSdk::ServiceSettings registerServiceSettings;
// UaNodeIdArray nodesToRegister;
// nodesToRegister.create(nodes.size());
// int i = 0;
// for (std::map<const UaNodeId*, const UaVariant*>::const_iterator it = nodes.begin();
// it != nodes.end(); it++) {
// const UaNodeId& nodeId = *it->first;
// nodeId.copyTo(&nodesToRegister[i]);
// d->log->debug("Register node %s", nodeId.toXmlString().toUtf8());
// i++;
// }
// UaNodeIdArray registeredNodes;
// UaStatus registerResult = d->session->registerNodes(registerServiceSettings, nodesToRegister, registeredNodes);
// if (!registerResult.isGood()) {
// throw ExceptionDef(HaSessionException, std::string("Cannot register nodes"));
// }
// UaWriteValues attrToWrite;
// attrToWrite.create(nodes.size());
// int index = 0;
// for (std::map<const UaNodeId*, const UaVariant*>::const_iterator it = nodes.begin();
// it != nodes.end(); it++) {
// const UaNodeId& nodeId = registeredNodes[index];
// const UaVariant& value = *it->second;
// attrToWrite[index].AttributeId = OpcUa_Attributes_Value;
// nodeId.copyTo(&attrToWrite[index].NodeId);
// value.copyTo(&attrToWrite[index].Value.Value);
// index++;
// }
UaWriteValues attrToWrite;
attrToWrite.create(nodes.size());
int index = 0;
for (std::map<const UaNodeId*, const UaVariant*>::const_iterator it =
nodes.begin(); it != nodes.end(); it++) {
const UaNodeId& nodeId = *it->first;
const UaVariant& value = *it->second;
attrToWrite[index].AttributeId = OpcUa_Attributes_Value;
nodeId.copyTo(&attrToWrite[index].NodeId);
value.copyTo(&attrToWrite[index].Value.Value);
index++;
}
// write values
UaClientSdk::ServiceSettings serviceSettings;
serviceSettings.callTimeout = d->conf->sendReceiveTimeout * 1000;
UaStatusCodeArray results;
UaDiagnosticInfos diagnosticInfos;
d->log->debug("Writing %d node attributes", attrToWrite.length());
UaStatus result = d->session->write(serviceSettings, attrToWrite, results,
diagnosticInfos);
if (!result.isGood()) {
std::ostringstream msg;
msg << "Cannot read values: " << result.toString().toUtf8();
throw ExceptionDef(HaSessionException, msg.str());
}
d->log->debug("Wrote %d node attributes\n", results.length());
// for each result
for (OpcUa_UInt32 i = 0; i < results.length(); i++) {
UaNodeId nodeId(attrToWrite[i].NodeId);
UaStatus status(results[i]);
if (!status.isGood()) {
std::ostringstream msg;
msg << "Cannot write value for " << nodeId.toXmlString().toUtf8()
<< ": " << status.toString().toUtf8();
throw ExceptionDef(HaSessionException, msg.str());
}
if (d->log->isDebugEnabled()) {
d->log->debug("Wrote %s value=%s", nodeId.toXmlString().toUtf8(),
UaVariant(attrToWrite[i].Value.Value).toFullString().toUtf8());
}
}
}
UaStatus HaSession::browse(ServiceSettings &serviceSettings,
const UaNodeId &startingNode, BrowseContext &browseContext,
UaByteString &continuationPoint,
UaReferenceDescriptions &referenceDescriptions) {
UaStatus state = d->session->browse(serviceSettings, startingNode,
browseContext, continuationPoint, referenceDescriptions);
return state;
}
UaStatus HaSession::browseNext(ServiceSettings &settings, OpcUa_Boolean release,
UaByteString &continuationPoint,
UaReferenceDescriptions &referenceDescriptions) {
return d->session->browseNext(settings, release, continuationPoint,
referenceDescriptions);
}
std::vector<UaVariant*>* HaSession::call(const UaNodeId& methodId,
const UaNodeId& objectId,
const std::vector<UaVariant*>& inputArguments) /*throws HaSessionException*/{
MutexLock lock(*d->mutex);
if (d->session == NULL) {
throw ExceptionDef(HaSessionException,
std::string("Cannot call method due to closed session"));
}
UaClientSdk::ServiceSettings serviceSettings;
serviceSettings.callTimeout = d->conf->sendReceiveTimeout * 1000;
if (d->log->isDebugEnabled()) {
d->log->debug(
"Calling method %s on object %s with %d input arguments...",
methodId.toXmlString().toUtf8(),
objectId.toXmlString().toUtf8(), inputArguments.size());
}
UaClientSdk::CallIn callRequest;
callRequest.methodId = methodId;
callRequest.objectId = objectId;
callRequest.inputArguments.create(inputArguments.size());
for (int i = 0; i < inputArguments.size(); i++) {
inputArguments[i]->copyTo(&callRequest.inputArguments[i]);
if (d->log->isDebugEnabled()) {
d->log->debug("Sending method input argument value=%s",
inputArguments[i]->toFullString().toUtf8());
}
}
UaClientSdk::CallOut callResult;
UaStatus result = d->session->call(serviceSettings, callRequest,
callResult);
// if calling failed
if (!result.isGood()) {
std::ostringstream msg;
msg << "Cannot call method " << methodId.toXmlString().toUtf8()
<< " on object " << objectId.toXmlString().toUtf8() << ": "
<< result.toString().toUtf8();
HaSessionException ex = ExceptionDef(HaSessionException, msg.str());
unsigned long errorCode = result.code();
ex.setErrorCode(&errorCode);
throw ex;
}
if (!callResult.callResult.isGood()) {
std::ostringstream msg;
msg << "Cannot call method " << methodId.toXmlString().toUtf8()
<< " on object " << objectId.toXmlString().toUtf8() << ": "
<< callResult.callResult.toString().toUtf8();
HaSessionException ex = ExceptionDef(HaSessionException, msg.str());
unsigned long errorCode = callResult.callResult.code();
ex.setErrorCode(&errorCode);
throw ex;
}
if (d->log->isDebugEnabled()) {
d->log->debug("Called method returned with %d output arguments",
callResult.outputArguments.length());
}
std::vector<UaVariant*>* ret = new std::vector<UaVariant*>();
if (callResult.outputArguments.length() > 0) {
for (OpcUa_UInt32 i = 0; i < callResult.outputArguments.length(); i++) {
ret->push_back(new UaVariant(callResult.outputArguments[i]));
if (d->log->isDebugEnabled()) {
d->log->debug("Get method output argument value=%s",
ret->back()->toFullString().toUtf8());
}
}
}
return ret;
}
void HaSession::subscribe(const std::vector<const UaNodeId*>& nodeIds,
std::vector<NodeAttributes*>& returnNodeAttributes,
std::map<UaNodeId, std::vector<BinaryServerNamespace::EventField*>*>& returnEventFields)
/* throws HaSubscriptionException */{
MutexLock lock(*d->mutex);
if (d->session == NULL) {
throw ExceptionDef(HaSessionException,
std::string("Cannot subscribe due to closed session"));
}
//test code for registerNodes(the following read call must be deactivated)
// UaClientSdk::ServiceSettings registerServiceSettings;
// UaNodeIdArray nodesToRegister;
// nodesToRegister.create(nodeIds.size());
// for (OpcUa_Int16 i = 0; i < nodeIds.size(); i++) {
// nodeIds.at(i)->copyTo(&nodesToRegister[i]);
// d->log->debug("Register node %s", nodeIds.at(i)->toXmlString().toUtf8());
// }
// UaNodeIdArray registeredNodes;
// UaStatus registerResult = d->session->registerNodes(registerServiceSettings, nodesToRegister, registeredNodes);
// if (!registerResult.isGood()) {
// throw ExceptionDef(HaSessionException, std::string("Cannot register nodes"));
// }
// std::vector<const UaNodeId*>* registeredNodeIds = new std::vector<const UaNodeId*>();
// VectorScopeGuard<const UaNodeId> registeredNodeIdsSG(registeredNodeIds);
// for (OpcUa_Int16 i = 0; i < registeredNodes.length(); i++) {
// registeredNodeIds->push_back(new UaNodeId(registeredNodes[i]));
// d->log->debug("Registered node %s", registeredNodeIds->at(i)->toXmlString().toUtf8());
// }
// read(*registeredNodeIds, returnNodeAttributes); // HaSessionException
// read node attributes
read(nodeIds, returnNodeAttributes); // HaSessionException
// read event fields
HaSessionException* exception = NULL;
std::vector<NodeAttributes*> validNodeAttributes;
// for each node
for (int i = 0; i < returnNodeAttributes.size(); i++) {
NodeAttributes* attr = returnNodeAttributes[i];
try {
// if reading of attributes failed
if (attr->getException() != NULL) {
throw *attr->getException();
}
// if node is an event type
if (*attr->getNodeClass() == OpcUa_NodeClass_ObjectType) {
// get event fields
std::vector<BinaryServerNamespace::EventField*>* evFields =
new std::vector<BinaryServerNamespace::EventField*>();
VectorScopeGuard<BinaryServerNamespace::EventField> evFieldsSG(
evFields);
if (d->log->isDebugEnabled()) {
d->log->debug("Getting event fields for %s...",
attr->getNodeId().toXmlString().toUtf8());
}
d->getEventFields(attr->getNodeId(), *evFields); // HaSessionException
if (d->log->isDebugEnabled()) {
for (int i = 0; i < evFields->size(); i++) {
BinaryServerNamespace::EventField* evField =
(*evFields)[i];
d->log->debug(
"Get event field %-20s nodeId=%s,dataType=%s",
evField->getQualifiedName()->toString().toUtf8(),
evField->getNodeId().toXmlString().toUtf8(),
evField->getDataTypeId()->toXmlString().toUtf8());
}
}
// for each event field
for (int i = 0; i < evFields->size(); i++) {
BinaryServerNamespace::EventField& evField = *(*evFields)[i];
// if an exception has occurred
if (evField.getException() != NULL) {
throw *evField.getException();
}
}
returnEventFields[attr->getNodeId()] = evFieldsSG.detach();
}
validNodeAttributes.push_back(attr);
} catch (Exception& e) {
if (exception == NULL) {
std::ostringstream msg;
msg << "Cannot add node "
<< attr->getNodeId().toXmlString().toUtf8()
<< " to subscription";
exception = new ExceptionDef(HaSessionException, msg.str());
exception->setCause(&e);
}
}
}
if (validNodeAttributes.size() > 0) {
try {
// add nodes to subscription
d->subscription->add(validNodeAttributes, returnEventFields); // HaSubscriptionException
} catch (Exception& e) {
if (exception == NULL) {
exception = new ExceptionDef(HaSessionException,
std::string("Cannot add nodes to subscription"));
exception->setCause(&e);
}
}
}
if (exception != NULL) {
// delete node attributes
for (int i = 0; i < returnNodeAttributes.size(); i++) {
delete returnNodeAttributes[i];
}
returnNodeAttributes.clear();
// delete eventField structure
for (std::map<UaNodeId, std::vector<BinaryServerNamespace::EventField*>*>::const_iterator it =
returnEventFields.begin(); it != returnEventFields.end();
it++) {
VectorScopeGuard<BinaryServerNamespace::EventField> eventFieldsSG(
it->second);
}
returnEventFields.clear();
ScopeGuard<HaSessionException> exceptionSG(exception);
throw *exception;
}
}
void HaSession::unsubscribe(
const std::vector<const UaNodeId*>& nodeIds) /* throws HaSubscriptionException */{
MutexLock lock(*d->mutex);
if (d->subscription != NULL) {
d->subscription->remove(nodeIds);
}
}
void HaSession::unsubscribe() /* throws HaSubscriptionException */{
MutexLock lock(*d->mutex);
if (d->subscription != NULL) {
d->subscription->removeAll();
}
}
void HaSessionPrivate::read(const std::vector<const UaNodeId*>& nodeIds,
std::vector<OpcUa_UInt32>& attributeIds,
std::vector<NodeAttributes*>& returnNodeAttributes)
/* throws HaSessionException */{
if (nodeIds.size() == 0) {
return;
}
UaReadValueIds attrToRead;
attrToRead.create(nodeIds.size() * attributeIds.size());
// nodeToRead index -> ret index
std::map<OpcUa_UInt32, OpcUa_UInt32> indexMap;
OpcUa_UInt32 attrToReadIndex = 0;
// for each node
for (OpcUa_UInt32 retIndex = 0; retIndex < nodeIds.size(); retIndex++) {
const UaNodeId& nodeId = *nodeIds[retIndex];
// for each attribute
for (int i = 0; i < attributeIds.size(); i++) {
attrToRead[attrToReadIndex].AttributeId = attributeIds[i];
nodeId.copyTo(&attrToRead[attrToReadIndex].NodeId);
indexMap[attrToReadIndex++] = retIndex;
}
// add empty object for attribute values to return array
returnNodeAttributes.push_back(
new NodeAttributes(*new UaNodeId(nodeId),
true /*attachValues*/));
}
// if nothing has to be read
if (attrToReadIndex == 0) {
return;
}
// read data
attrToRead.resize(attrToReadIndex);
UaClientSdk::ServiceSettings serviceSettings;
serviceSettings.callTimeout = conf->sendReceiveTimeout * 1000;
UaDataValues values;
UaDiagnosticInfos diagnosticInfos;
log->debug("Reading %d node attributes...", attrToReadIndex);
UaStatus result = session->read(serviceSettings, 0 /*maxAge*/,
OpcUa_TimestampsToReturn_Both, attrToRead, values, diagnosticInfos);
// if reading failed
if (!result.isGood()) {
// remove added node attributes
for (int i = 0; i < returnNodeAttributes.size(); i++) {
delete returnNodeAttributes[i];
}
returnNodeAttributes.clear();
// throw an exception
std::ostringstream msg;
msg << "Cannot read values: " << result.toString().toUtf8();
throw ExceptionDef(HaSessionException, msg.str());
}
log->debug("Read %d node attributes", values.length());
// for each result
for (OpcUa_UInt32 nodesToReadIndex = 0;
nodesToReadIndex < attrToRead.length(); nodesToReadIndex++) {
UaNodeId nodeId(attrToRead[nodesToReadIndex].NodeId);
UaStatus status(values[nodesToReadIndex].StatusCode);
OpcUa_UInt32 retIndex = indexMap[nodesToReadIndex];
if (status.isGood()) {
if (log->isDebugEnabled()) {
log->debug("Read %s attributeId=%d,value=%s",
nodeId.toXmlString().toUtf8(),
attrToRead[nodesToReadIndex].AttributeId,
UaVariant(values[nodesToReadIndex].Value).toFullString().toUtf8());
}
switch (attrToRead[nodesToReadIndex].AttributeId) {
case OpcUa_Attributes_NodeClass: {
UaVariant value(values[nodesToReadIndex].Value);
OpcUa_NodeClass* nodeClass = new OpcUa_NodeClass;
value.toInt32(*(OpcUa_Int32*) nodeClass);
returnNodeAttributes[retIndex]->setNodeClass(nodeClass);
break;
}
case OpcUa_Attributes_Value:
returnNodeAttributes[retIndex]->setValue(
new UaVariant(values[nodesToReadIndex].Value));
break;
case OpcUa_Attributes_DataType: {
UaVariant value(values[nodesToReadIndex].Value);
UaNodeId* dataTypeId = new UaNodeId();
value.toNodeId(*dataTypeId);
returnNodeAttributes[retIndex]->setDataType(dataTypeId);
break;
}
}
} else {
if (log->isDebugEnabled()) {
log->debug("Read %s attributeId=%d,status=%s",
nodeId.toXmlString().toUtf8(),
attrToRead[nodesToReadIndex].AttributeId,
status.toString().toUtf8());
}
std::ostringstream msg;
msg << "Cannot read value for " << nodeId.toXmlString().toUtf8()
<< " and attributeId "
<< attrToRead[nodesToReadIndex].AttributeId << ": "
<< status.toString().toUtf8();
returnNodeAttributes[retIndex]->setException(
new ExceptionDef(HaSessionException, msg.str()));
}
}
}
UaVariant HaSession::getVariable(const UaNodeId &variableNodeId){
UaClientSdk::ServiceSettings serviceSettings;
serviceSettings.callTimeout = d->conf->sendReceiveTimeout * 1000;
UaClientSdk::BrowseContext browseContext;
browseContext.browseDirection = OpcUa_BrowseDirection_Both;
browseContext.referenceTypeId = OpcUaId_HierarchicalReferences;
browseContext.maxReferencesToReturn = 1;
browseContext.nodeClassMask = OpcUa_NodeClass_Variable;
UaByteString continuationPoint;
UaReferenceDescriptions referenceDescriptions;
UaStatus result = d->session->browse(serviceSettings, variableNodeId,
browseContext, continuationPoint, referenceDescriptions);
if (referenceDescriptions.length() == 1){
return UaVariant(referenceDescriptions[0].NodeId.NodeId);
}
return UaVariant(false);
}
void HaSessionPrivate::getEventFields(const UaNodeId & eventTypeId,
std::vector<BinaryServerNamespace::EventField*>& returnEventFields)
/*throws HaSessionException*/{
UaClientSdk::ServiceSettings serviceSettings;
serviceSettings.callTimeout = conf->sendReceiveTimeout * 1000;
UaClientSdk::BrowseContext browseContext;
browseContext.browseDirection = OpcUa_BrowseDirection_Both;
browseContext.referenceTypeId = OpcUaId_HierarchicalReferences;
browseContext.includeSubtype = OpcUa_True;
browseContext.maxReferencesToReturn = 0;
browseContext.nodeClassMask = OpcUa_NodeClass_Variable
| OpcUa_NodeClass_ObjectType;
UaByteString continuationPoint;
UaReferenceDescriptions referenceDescriptions;
UaStatus result = session->browse(serviceSettings, eventTypeId,
browseContext, continuationPoint, referenceDescriptions);
if (!result.isGood()) {
std::ostringstream msg;
msg << "Cannot get event fields for "
<< eventTypeId.toXmlString().toUtf8() << ": "
<< result.toString().toUtf8();
throw ExceptionDef(HaSessionException, msg.str());
}
// add variables
for (OpcUa_UInt32 i = 0; i < referenceDescriptions.length(); i++) {
// if variable
if (OpcUaId_HasSubtype
!= UaNodeId(referenceDescriptions[i].ReferenceTypeId).identifierNumeric()) {
// check for duplicate browse name (eg. overridden variable)
bool found = false;
for (int j = 0; j < returnEventFields.size() && !found; j++) {
found = (*returnEventFields[j]->getQualifiedName())
== UaQualifiedName(referenceDescriptions[i].BrowseName);
}
if (found) {
// skip variable
continue;
}
// read dataTypeId of event field
UaNodeId nodeId(referenceDescriptions[i].NodeId.NodeId);
std::vector<const UaNodeId*> nodeIds;
nodeIds.push_back(&nodeId);
std::vector<NodeAttributes*>* nodeAttributes = new std::vector<
NodeAttributes*>();
VectorScopeGuard<NodeAttributes> nodeAttributesSG(nodeAttributes);
BinaryServerNamespace::EventField* field =
new BinaryServerNamespace::EventField(*new UaNodeId(nodeId),
true /*attachValues*/);
try {
parent->read(nodeIds, *nodeAttributes); // HaSessionException
// if the data type could be read
if (nodeAttributes != NULL && nodeAttributes->size() > 0) {
// if exception is returned
if ((*nodeAttributes)[0]->getException() != NULL) {
std::ostringstream msg;
msg << "Cannot get data type of event field "
<< nodeId.toXmlString().toUtf8()
<< " of event type "
<< eventTypeId.toXmlString().toUtf8();
HaSessionException* exception =
new ExceptionDef(HaSessionException, msg.str());
exception->setCause(
(*nodeAttributes)[0]->getException());
field->setException(exception);
} else {
field->setQualifiedName(
new UaQualifiedName(
referenceDescriptions[i].BrowseName));
field->setDataTypeId(
new UaNodeId(
*(*nodeAttributes)[0]->getDataType()));
}
} else {
std::ostringstream msg;
msg << "Cannot read node attributes of event field "
<< nodeId.toXmlString().toUtf8()
<< " of event type "
<< eventTypeId.toXmlString().toUtf8();
field->setException(
new ExceptionDef(HaSessionException, msg.str()));
}
} catch (Exception& e) {
std::ostringstream msg;
msg << "Cannot get data type of event field "
<< nodeId.toXmlString().toUtf8() << " of event type "
<< eventTypeId.toXmlString().toUtf8();
HaSessionException* exception =
new ExceptionDef(HaSessionException, msg.str());
exception->setCause(&e);
field->setException(exception);
}
returnEventFields.push_back(field);
}
}
// add variables of super types
for (OpcUa_UInt32 i = 0; i < referenceDescriptions.length(); i++) {
UaNodeId nodeId(referenceDescriptions[i].NodeId.NodeId);
try {
// if super type or sub type
if (OpcUaId_HasSubtype
== UaNodeId(referenceDescriptions[i].ReferenceTypeId).identifierNumeric()) {
// if super type
if (!referenceDescriptions[i].IsForward) {
// get event fields of super type
getEventFields(nodeId, returnEventFields); // HaSessionException
}
// childs are ignored
}
} catch (Exception& e) {
// process as many event fields as possible
std::string st;
e.getStackTrace(st);
log->error("Exception while getting event fields: %s", st.c_str());
}
}
}
void HaSessionPrivate::connectionStatusChanged(OpcUa_UInt32 clientConnectionId,
UaClientSdk::UaClient::ServerStatus serverStatus) {
callback->connectionStateChanged(serverStatus);
switch (serverStatus) {
case UaClientSdk::UaClient::Disconnected:
log->debug("Connection status changed to Disconnected");
break;
case UaClientSdk::UaClient::Connected:
log->debug("Connection status changed to Connected");
break;
case UaClientSdk::UaClient::ConnectionWarningWatchdogTimeout:
log->debug(
"Connection status changed to ConnectionWarningWatchdogTimeout");
break;
case UaClientSdk::UaClient::ConnectionErrorApiReconnect:
log->debug("Connection status changed to ConnectionErrorApiReconnect");
break;
case UaClientSdk::UaClient::ServerShutdown:
log->debug("Connection status changed to ServerShutdown");
break;
case UaClientSdk::UaClient::NewSessionCreated:
log->debug("Connection status changed to NewSessionCreated");
break;
}
}
| 36.259643 | 180 | 0.704156 | [
"object",
"vector"
] |
39984ba92b3852854297cd8190666295c74313ab | 1,716 | cpp | C++ | Samples/MapReduceActors/MapReduceActorRunner.cpp | renestein/Rstein.AsyncCpp | 8f020ad271250479f600d7e2e862f701472c3a48 | [
"MIT"
] | 41 | 2020-05-04T05:58:24.000Z | 2022-03-25T07:21:45.000Z | Samples/MapReduceActors/MapReduceActorRunner.cpp | renestein/Rstein.AsyncCpp | 8f020ad271250479f600d7e2e862f701472c3a48 | [
"MIT"
] | 15 | 2021-02-03T16:05:19.000Z | 2021-08-17T17:09:28.000Z | Samples/MapReduceActors/MapReduceActorRunner.cpp | renestein/Rstein.AsyncCpp | 8f020ad271250479f600d7e2e862f701472c3a48 | [
"MIT"
] | 4 | 2020-05-04T15:41:37.000Z | 2021-08-24T00:59:18.000Z | #include "MapReduceActorRunner.h"
#include "LineParserActor.h"
#include "MapWordsActor.h"
#include "ReduceWordProcessorActor.h"
#include "WriteTopWordsActor.h"
#include "../../RStein.AsyncCpp/Actors/SimpleActor.h"
#include "../Utils/TimeUtils.h"
#include <vector>
#include <memory>
#include <iostream>
using namespace RStein::AsyncCpp::Actors;
using namespace std;
namespace Samples::MapReduceActors
{
void MapReduceActorRunner::Run()
{
const size_t LINE_BATCH_SIZE = 1000;
MeasureTime([] {
cout << "Creating actors..." << endl;
auto numberOfWordsMapActors = thread::hardware_concurrency();
WriteTopWordsActor topWordsActor{};
ReduceWordProcessorActor reduceWordProcessorActor{&topWordsActor, numberOfWordsMapActors};
vector<unique_ptr<MapWordsActor>> mapWordsActors{};
for (unsigned i = 0; i < numberOfWordsMapActors; i++)
{
mapWordsActors.push_back(make_unique<MapWordsActor>(&reduceWordProcessorActor));
}
vector<MapWordsActor*> rawMapWordsActors;
transform(mapWordsActors.begin(), mapWordsActors.end(), back_inserter(rawMapWordsActors), [](const std::unique_ptr<MapWordsActor>& wordParserActor)
{
return wordParserActor.get();
});
LineParserActor lineParserActor{rawMapWordsActors, LINE_BATCH_SIZE};
cout << "Done." << endl;
cout << "Processing book Shakespeare.txt..." << endl;
//TODO: Change path to the file.
lineParserActor.ProcessBook("c:\\Repositories_Git\\RStein.AsyncCpp\\Samples\\MapReduceActors\\Shakespeare.txt").Wait();
lineParserActor.Complete();
topWordsActor.Completion().Wait();
cout << "Done." << endl;
});
cin.get();
}
}
| 31.2 | 153 | 0.699301 | [
"vector",
"transform"
] |
399d8baf6885455639eb51c45791e16c385fa4b0 | 2,483 | hpp | C++ | System.Core/include/Switch/System/Collections/Generic/Comparer.hpp | kkptm/CppLikeCSharp | b2d8d9da9973c733205aa945c9ba734de0c734bc | [
"MIT"
] | 4 | 2021-10-14T01:43:00.000Z | 2022-03-13T02:16:08.000Z | System.Core/include/Switch/System/Collections/Generic/Comparer.hpp | kkptm/CppLikeCSharp | b2d8d9da9973c733205aa945c9ba734de0c734bc | [
"MIT"
] | null | null | null | System.Core/include/Switch/System/Collections/Generic/Comparer.hpp | kkptm/CppLikeCSharp | b2d8d9da9973c733205aa945c9ba734de0c734bc | [
"MIT"
] | 2 | 2022-03-13T02:16:06.000Z | 2022-03-14T14:32:57.000Z | /// @file
/// @brief Contains Switch::System::Collections::Generic::Comparer <T> class.
#pragma once
#include "../../Object.hpp"
#include "IComparer.hpp"
/// @brief The Switch namespace contains all fundamental classes to access Hardware, Os, System, and more.
namespace Switch {
/// @brief The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.
namespace System {
/// @brief The System::Collections namespace contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hash tables and dictionaries.
namespace Collections {
/// @brief The System::Collections::Generic namespace contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.
namespace Generic {
/// @brief Exposes a method that compares two objects.
template<typename T>
class Comparer : public Object, public IComparer<T> {
public:
/// @cond
Comparer() {}
/// @endcond
/// @brief Returns a default sort order comparer for the type specified by the generic argument
static const Comparer<T> Default;
/// @brief Compares two entities and returns a value indicating whether one is less than, equal to, or greater than the other.
/// @param x The first entity to compare.
/// @param y The second entity to compare.
/// @return Int32 A 32-bit signed integer that indicates the relative order of the entities being compared. The return value has these meanings:
/// - Less than zero x is less than y.
/// - Zero x equals y.
/// - Greater than zero x is greater than y.
virtual int32 Compare(const T& x, const T& y) const {return x < y ? -1 : (x == y ? 0 : 1);}
};
/// @cond
template<typename T>
const Comparer<T> Comparer<T>::Default;
template<typename T>
class EmptyComparer : public Object, public IComparer<T> {
public:
EmptyComparer() {}
virtual int32 Compare(const T& x, const T& y) const {return 0;}
};
/// @endcond
}
}
}
}
using namespace Switch;
| 45.981481 | 272 | 0.65445 | [
"object"
] |
39a1dfa33e947c8494af37217eb80a356dc29a5a | 9,337 | cpp | C++ | src/core/lib/core_data_model/reflection/reflected_object_item_new.cpp | wgsyd/wgtf | d8cacb43e2c5d40080d33c18a8c2f5bd27d21bed | [
"BSD-3-Clause"
] | 28 | 2016-06-03T05:28:25.000Z | 2019-02-14T12:04:31.000Z | src/core/lib/core_data_model/reflection/reflected_object_item_new.cpp | karajensen/wgtf | 740397bcfdbc02bc574231579d57d7c9cd5cc26d | [
"BSD-3-Clause"
] | null | null | null | src/core/lib/core_data_model/reflection/reflected_object_item_new.cpp | karajensen/wgtf | 740397bcfdbc02bc574231579d57d7c9cd5cc26d | [
"BSD-3-Clause"
] | 14 | 2016-06-03T05:52:27.000Z | 2019-03-21T09:56:03.000Z | #include "reflected_object_item_new.hpp"
#include "reflected_group_item_new.hpp"
#include "reflected_property_item_new.hpp"
#include "core_common/assert.hpp"
#include "core_data_model/i_item_role.hpp"
#include "core_data_model/common_data_roles.hpp"
#include "core_reflection/metadata/meta_impl.hpp"
#include "core_reflection/metadata/meta_base.hpp"
#include "core_reflection/object_handle.hpp"
#include "core_reflection/property_accessor.hpp"
#include "core_reflection/interfaces/i_base_property.hpp"
#include "core_string_utils/string_utils.hpp"
#include <codecvt>
#include <set>
namespace wgt
{
namespace
{
bool compareWStrings(const wchar_t* a, const wchar_t* b)
{
return wcscmp(a, b) < 0;
}
} // namespace
class ReflectedObjectItemNew::Implementation : public Depends<IDefinitionManager>
{
public:
Implementation(const ObjectHandle& object);
typedef std::set<const wchar_t*, bool (*)(const wchar_t*, const wchar_t*)> Groups;
const Groups& getGroups(const ReflectedObjectItemNew& self);
ObjectHandle object_;
std::string displayName_;
std::vector<std::unique_ptr<ReflectedTreeItemNew>> children_;
Groups groups_;
};
ReflectedObjectItemNew::Implementation::Implementation(const ObjectHandle& object)
: object_(object), groups_(compareWStrings)
{
}
const ReflectedObjectItemNew::Implementation::Groups& ReflectedObjectItemNew::Implementation::getGroups(
const ReflectedObjectItemNew& self)
{
auto definition = self.getDefinition();
if (!groups_.empty() || (definition == nullptr))
{
return groups_;
}
auto pDefinitionManager = self.impl_->get<IDefinitionManager>();
if (pDefinitionManager == nullptr)
{
return groups_;
}
auto& parent = const_cast<ReflectedObjectItemNew&>(self);
self.enumerateVisibleProperties(
[this, &self, &parent, pDefinitionManager](const IBasePropertyPtr& property, const std::string& inPlacePath) {
auto groupObj = findFirstMetaData<MetaGroupObj>(*property, *pDefinitionManager);
if (groupObj != nullptr && groups_.insert(groupObj->getGroupName(parent.getObject())).second)
{
children_.emplace_back(
new ReflectedGroupItemNew(
property->getMetaData(), groupObj, &parent, children_.size(), inPlacePath));
}
return true;
});
return groups_;
}
ReflectedObjectItemNew::ReflectedObjectItemNew(const ObjectHandle& object, const ReflectedTreeModelNew& model)
: ReflectedTreeItemNew(model), impl_(new Implementation(object))
{
}
ReflectedObjectItemNew::ReflectedObjectItemNew(const ObjectHandle& object, ReflectedTreeItemNew* parent, size_t index)
: ReflectedTreeItemNew(parent, index, parent ? parent->getPath() + "." : ""), impl_(new Implementation(object))
{
}
ReflectedObjectItemNew::~ReflectedObjectItemNew()
{
}
Variant ReflectedObjectItemNew::getData(int column, ItemRole::Id roleId) const /* override */
{
if (roleId == ItemRole::displayId)
{
switch (column)
{
case 0:
if (impl_->displayName_.empty())
{
auto definition = this->getDefinition();
if (definition == nullptr)
{
return "";
}
auto pDefinitionManager = impl_->get<IDefinitionManager>();
if (pDefinitionManager == nullptr)
{
return "";
}
auto displayName = findFirstMetaData<MetaDisplayNameObj>(*definition, *pDefinitionManager);
if (displayName == nullptr)
{
impl_->displayName_ = definition->getName();
}
else
{
impl_->displayName_ = StringUtils::to_string(displayName->getDisplayName(impl_->object_));
}
}
return impl_->displayName_.c_str();
default:
auto definition = getDefinition();
if (definition == nullptr)
{
return "";
}
return definition->getName();
}
}
else if (roleId == ItemRole::itemIdId)
{
return getId();
}
if (roleId == ValueRole::roleId_)
{
return impl_->object_;
}
if (roleId == ValueTypeRole::roleId_)
{
return TypeId::getType<ObjectHandle>().getName();
}
else if (roleId == ObjectRole::roleId_)
{
return this->getObject();
}
else if (roleId == RootObjectRole::roleId_)
{
return this->getRootObject();
}
return Variant();
}
bool ReflectedObjectItemNew::setData(int column, ItemRole::Id roleId, const Variant& data) /* override */
{
if (roleId != ValueRole::roleId_)
{
return false;
}
ObjectHandle other;
if (!data.tryCast(other))
{
return false;
}
auto pDefinitionManager = impl_->get<IDefinitionManager>();
if (pDefinitionManager == nullptr)
{
return false;
}
auto obj = this->getRootObject();
auto definition = pDefinitionManager->getDefinition(obj);
auto otherDef = pDefinitionManager->getDefinition(other);
if (definition != otherDef)
{
return false;
}
for (auto prop : definition->allProperties())
{
auto accessor = definition->bindProperty(prop->getName(), obj);
auto otherAccessor = definition->bindProperty(prop->getName(), other);
if (accessor.canSetValue())
{
TF_ASSERT(otherAccessor.canGetValue());
accessor.setValue(otherAccessor.getValue());
}
}
const auto pParent = this->getParent();
if (pParent)
{
return pParent->setData(column, roleId, obj);
}
return true;
}
const ObjectHandle& ReflectedObjectItemNew::getRootObject() const /* override */
{
return parent_ ? parent_->getRootObject() : impl_->object_;
}
const ObjectHandle& ReflectedObjectItemNew::getObject() const /* override */
{
return impl_->object_;
}
const IClassDefinition* ReflectedObjectItemNew::getDefinition() const
{
auto pDefinitionManager = impl_->get<IDefinitionManager>();
if (pDefinitionManager == nullptr)
{
return nullptr;
}
return pDefinitionManager->getDefinition(impl_->object_);
}
ReflectedTreeItemNew* ReflectedObjectItemNew::getChild(size_t index) const
{
if (impl_->children_.size() > index)
{
return impl_->children_[index].get();
}
size_t currentIndex = 0;
this->enumerateChildren([¤tIndex, index](ReflectedTreeItemNew& item) { return (currentIndex++ == index); });
if (currentIndex > 0)
{
return impl_->children_[--currentIndex].get();
}
return nullptr;
}
int ReflectedObjectItemNew::rowCount() const
{
int count = 0;
this->enumerateChildren([&count](ReflectedTreeItemNew&) {
++count;
return true;
});
return count;
}
bool ReflectedObjectItemNew::isInPlace() const
{
return parent_ != nullptr;
}
bool ReflectedObjectItemNew::preSetValue(const PropertyAccessor& accessor, const Variant& value)
{
for (auto it = impl_->children_.begin(); it != impl_->children_.end(); ++it)
{
if ((*it) == nullptr)
{
continue;
}
if ((*it)->preSetValue(accessor, value))
{
return true;
}
}
return false;
}
bool ReflectedObjectItemNew::postSetValue(const PropertyAccessor& accessor, const Variant& value)
{
for (auto it = impl_->children_.begin(); it != impl_->children_.end(); ++it)
{
if ((*it) == nullptr)
{
continue;
}
if ((*it)->postSetValue(accessor, value))
{
return true;
}
}
return false;
}
bool ReflectedObjectItemNew::preInsert(const PropertyAccessor& accessor, size_t index, size_t count)
{
for (auto it = impl_->children_.begin(); it != impl_->children_.end(); ++it)
{
if ((*it) == nullptr)
{
continue;
}
if ((*it)->preInsert(accessor, index, count))
{
return true;
}
}
return false;
}
bool ReflectedObjectItemNew::postInserted(const PropertyAccessor& accessor, size_t index, size_t count)
{
for (auto it = impl_->children_.begin(); it != impl_->children_.end(); ++it)
{
if ((*it) == nullptr)
{
continue;
}
if ((*it)->postInserted(accessor, index, count))
{
return true;
}
}
return false;
}
bool ReflectedObjectItemNew::preErase(const PropertyAccessor& accessor, size_t index, size_t count)
{
for (auto it = impl_->children_.begin(); it != impl_->children_.end(); ++it)
{
if ((*it) == nullptr)
{
continue;
}
if ((*it)->preErase(accessor, index, count))
{
return true;
}
}
return false;
}
bool ReflectedObjectItemNew::postErased(const PropertyAccessor& accessor, size_t index, size_t count)
{
for (auto it = impl_->children_.begin(); it != impl_->children_.end(); ++it)
{
if ((*it) == nullptr)
{
continue;
}
if ((*it)->postErased(accessor, index, count))
{
return true;
}
}
return false;
}
void ReflectedObjectItemNew::enumerateChildren(const ReflectedItemCallback& callback) const
{
// Get the groups and iterate them first
const auto& groups = impl_->getGroups(*this);
// This will iterate all the groups and any cached children
for (auto& child : impl_->children_)
{
if (!callback(*child.get()))
{
return;
}
}
auto pDefinitionManager = impl_->get<IDefinitionManager>();
if (pDefinitionManager == nullptr)
{
return;
}
// ReflectedGroupItem children handle grouped items
int skipChildCount = static_cast<int>(impl_->children_.size() - groups.size());
auto parent = const_cast<ReflectedObjectItemNew*>(this);
this->enumerateVisibleProperties([&](const IBasePropertyPtr& property, const std::string& inPlacePath) {
bool isGrouped = findFirstMetaData<MetaGroupObj>(*property, *pDefinitionManager) != nullptr;
if (!isGrouped)
{
// Skip already iterated children
if (--skipChildCount < 0)
{
impl_->children_.emplace_back(
new ReflectedPropertyItemNew(property, parent, impl_->children_.size(), inPlacePath));
return callback(*impl_->children_.back().get());
}
}
return true;
});
}
} // end namespace wgt
| 23.226368 | 118 | 0.707508 | [
"object",
"vector",
"model"
] |
39a2be40f45831e4d6c65e974b9fe0f128ed01d9 | 4,559 | cpp | C++ | cetty-shiro/src/cetty/shiro/authz/Authorizer.cpp | frankee/cetty2 | 62ac0cd1438275097e47a9ba471e72efd2746ded | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 26 | 2015-11-08T10:58:21.000Z | 2021-02-25T08:27:26.000Z | cetty-shiro/src/cetty/shiro/authz/Authorizer.cpp | frankee/cetty2 | 62ac0cd1438275097e47a9ba471e72efd2746ded | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2019-02-18T08:46:17.000Z | 2019-02-18T08:46:17.000Z | cetty-shiro/src/cetty/shiro/authz/Authorizer.cpp | frankee/cetty2 | 62ac0cd1438275097e47a9ba471e72efd2746ded | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 8 | 2016-02-27T02:37:10.000Z | 2021-09-29T05:25:00.000Z | /*
* Authorizer.cpp
*
* Created on: 2012-9-4
* Author: chenhl
*/
#include <cetty/shiro/authz/Authorizer.h>
#include <cetty/logging/LoggerHelper.h>
#include <cetty/config/ConfigCenter.h>
#include <cetty/shiro/authz/PermissionResolver.h>
#include <cetty/shiro/authz/AuthorizationInfoPtr.h>
#include <cetty/shiro/authz/AuthorizationInfo.h>
namespace cetty {
namespace shiro {
namespace authz {
using namespace cetty::config;
using namespace cetty::shiro::realm;
const std::string Authorizer::ALL_PERMISSION = "all_permission";
const std::string Authorizer::WILDCARD_PERMISSION = "wildcard_permission";
Authorizer::Authorizer(){
ConfigCenter::instance().configure(&config);
if(config.permissionType == WILDCARD_PERMISSION){
permissionResolver = &wildcardPermissionResolver;
} else {
permissionResolver = &allPermissionResolver;
}
}
void Authorizer::isPermitted(const std::string& principal,
const std::string& permission,
const AuthorizeCallback& callback) const {
assert(realmConfigured());
PrincipalCollection principals(principal, realm->getName());
PermissionPtr p = permissionResolver(permission);
isPermitted(principals, p, callback);
}
void Authorizer::isPermitted(const PrincipalCollection& principals,
const std::string& permission,
const AuthorizeCallback& callback) const {
assert(realmConfigured());
PermissionPtr p = permissionResolver(permission);
isPermitted(principals, p, callback);
}
void Authorizer::isPermitted(const PrincipalCollection& principal,
const PermissionPtr& permission,
const AuthorizeCallback& callback) const {
realm->getAuthorizationInfo(principal,
boost::bind(
&Authorizer::doPermite,
this,
_1, // AuthorizationInfoPtr
principal,
permission,
callback));
}
void Authorizer::doPermite(AuthorizationInfoPtr info,
PrincipalCollection principal,
PermissionPtr permission,
AuthorizeCallback callback) const {
if (!callback) {
LOG_ERROR << "doPermite input callback can NOT be NULL";
return;
}
if(!info){
LOG_TRACE<< "Can't find account info for principal ["
<< principal.getPrimaryPrincipal() << "]";
callback(false, principal.getPrimaryPrincipal(), permission->stringPermission());
}
if(config.permissionType == ALL_PERMISSION)
callback(true, principal.getPrimaryPrincipal(), permission->stringPermission());
std::vector<PermissionPtr> permissions = info->getPermissions();
std::vector<PermissionPtr>::iterator it;
for (it = permissions.begin(); it != permissions.end(); ++it) {
if ((*it)->implies(permission)) {
LOG_TRACE << "[" << principal.getPrimaryPrincipal() << "]"
<<"is permited for permission [" << permission->stringPermission() << "].";
callback(true, principal.getPrimaryPrincipal(), permission->stringPermission());
return;
}
}
std::vector<std::string> strPermissions = info->getStringPermissions();
std::vector<std::string>::iterator begin = strPermissions.begin();
for (; begin != strPermissions.end(); ++begin) {
PermissionPtr pm = permissionResolver(*begin);
if (pm->implies(permission)) {
LOG_TRACE << "[" << principal.getPrimaryPrincipal() << "]"
<<"is permited for permission [" << permission->stringPermission() << "].";
callback(true, principal.getPrimaryPrincipal(), permission->stringPermission());
return;
}
}
LOG_TRACE << "[" << principal.getPrimaryPrincipal() << "]"
<<"is not permited for permission [" << permission->stringPermission() << "].";
callback(false, principal.getPrimaryPrincipal(), permission->stringPermission());
}
bool Authorizer::realmConfigured() const {
if (!realm) {
LOG_TRACE << "Configuration error: No realms have been configured! One or more realms must be "
<< "present to execute an authorization operation.";
return false;
}
return true;
}
}
}
}
| 35.069231 | 105 | 0.606712 | [
"vector"
] |
39a2e6252ecae098d251177f7b0e7849ab932d5a | 6,059 | hpp | C++ | 7drl-violation/collisions.hpp | maxphilippov/7drl-violation | cc43314ece4176e9b5b453b6169b27c0d41b4c58 | [
"MIT"
] | null | null | null | 7drl-violation/collisions.hpp | maxphilippov/7drl-violation | cc43314ece4176e9b5b453b6169b27c0d41b4c58 | [
"MIT"
] | null | null | null | 7drl-violation/collisions.hpp | maxphilippov/7drl-violation | cc43314ece4176e9b5b453b6169b27c0d41b4c58 | [
"MIT"
] | null | null | null | //
// collisions.hpp
// 7drl-violation
//
// Copyright © 2016 Max Philippov
//
#ifndef collisions_h
#define collisions_h
#include <algorithm>
#include <iterator>
#include <vector>
#include <unordered_map>
#include <map>
#include "basic_types.hpp"
#include "map.hpp"
#include "interaction_types.hpp"
#include "position.hpp"
#include "city.hpp"
std::unordered_set<MapTile> unpassable_tiles = {
MapTile::Wall
};
std::unordered_set<MapTile> obscuring_tiles = {
MapTile::Wall, MapTile::Crowd
};
struct PosVel
{
Position pos;
Velocity vel;
};
class CollisionManager
{
typedef std::map<physical_object_id_type, PosVel> ObjectContainer;
ObjectContainer objects;
physical_object_id_type next_id = 0;
public:
void restart()
{
objects.clear();
}
void update(Bounds const& simulation_bounds,
CityManager const& city,
std::vector<ActorCollisionInfo>& collisions)
{
auto const& level_bounds = city.bounds();
// Update all entities positions (actually should update just nearest to the player)
auto new_objects = objects;
// Dispose objects outside of bounds
{
auto begin = std::begin(new_objects);
auto end_iter = std::end(new_objects);
for(auto iter = begin; iter != end_iter; ) {
if (!simulation_bounds.contains(iter->second.pos)) {
new_objects.erase(iter++);
} else {
auto const& p = iter->second.pos;
auto const& v = iter->second.vel;
auto new_pos = Position{
std::max(0, std::min(p.x + v.x, level_bounds.width - 1)),
std::max(0, std::min(p.y + v.y, level_bounds.height - 1))
};
auto tile = city.get(new_pos);
auto collision = (unpassable_tiles.count(tile) == 0);
iter->second.pos = collision ? new_pos : p;
iter->second.vel = Velocity{ 0, 0 };
++iter;
}
}
}
{
auto begin = std::begin(new_objects);
auto end_iter = std::end(new_objects);
for(auto const& kv: new_objects) {
auto const& new_pos = kv.second.pos;
auto collision_entity = std::find_if(begin, end_iter,
[&new_pos](auto const& kv) {
auto const &p = kv.second.pos;
return p.x == new_pos.x &&
p.y == new_pos.y;
});
if(collision_entity != end_iter && collision_entity->first != kv.first) {
collisions.push_back({
collision_entity->first,
kv.first
});
collision_entity->second.pos = objects.find(collision_entity->first)->second.pos;
}
}
}
objects = new_objects;
}
auto check_free_cells(CityManager const& city, std::vector<Position> const& poss) const
{
auto free_pos = std::vector<Position>(poss.size());
auto it = std::copy_if(std::begin(poss),
std::end(poss),
std::begin(free_pos),
[&city](auto const& p) {
auto tile = city.get(p);
return (unpassable_tiles.count(tile) == 0);
} );
free_pos.resize(std::distance(std::begin(free_pos), it));
return free_pos;
}
// Return false if there's no such object registered for collisions
// which means we disposed it already
auto change_velocity(physical_object_id_type id, Velocity vel)
{
auto it = objects.find(id);
auto found = it != std::end(objects);
if (found) {
it->second.vel = vel;
}
return found;
}
auto get_position(physical_object_id_type id) const
{
auto it = objects.find(id);
auto r = std::pair<bool, Position>{ false, Position {} };
if (it != std::end(objects)) {
r.first = true;
r.second = it->second.pos;
}
return r;
}
auto check_vision(CityManager const& city,
physical_object_id_type id,
Position const& pos,
int sqr_max_range) const
{
auto const& pair = get_position(id);
if (pair.first) {
auto distance = squared_distance(pair.second, pos);
if (distance > sqr_max_range) {
return false;
}
auto line = draw_line(pair.second, pos);
for(auto const& p: line) {
auto tile = city.get(p);
if(obscuring_tiles.count(tile) !=0 ) return false;
}
return true;
}
return false;
}
auto add_moving_entity(Position pos, Velocity vel = Velocity{0, 0})
{
auto id = next_id;
objects.insert({ next_id, { pos, vel } });
++next_id;
return id;
}
auto get_in_range(Position const& player, MapSize const& half_screen) const
{
auto bounds = Bounds{
player.x - half_screen.width,
player.y - half_screen.height,
player.x + half_screen.width,
player.y + half_screen.height
};
auto r = std::vector<Position>();
r.reserve(objects.size());
for(auto const& kv: objects) {
auto const& p = kv.second.pos;
if (bounds.contains(p)) {
r.push_back(p);
}
}
return r;
}
};
#endif /* collisions_h */
| 29.129808 | 101 | 0.495956 | [
"object",
"vector"
] |
39b7545ae7e6ee414005800b355b891db3c4a437 | 26,694 | cc | C++ | sling/myelin/rnn.cc | anysql/sling | d521b27f1537608ddf3d8b4281edd585ffd90545 | [
"Apache-2.0"
] | 97 | 2020-03-11T07:44:05.000Z | 2022-03-27T14:24:15.000Z | sling/myelin/rnn.cc | anysql/sling | d521b27f1537608ddf3d8b4281edd585ffd90545 | [
"Apache-2.0"
] | 11 | 2020-10-23T09:26:26.000Z | 2021-08-25T09:31:28.000Z | sling/myelin/rnn.cc | anysql/sling | d521b27f1537608ddf3d8b4281edd585ffd90545 | [
"Apache-2.0"
] | 8 | 2018-06-11T07:59:18.000Z | 2021-06-09T09:19:05.000Z | // Copyright 2018 Google Inc.
//
// 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 "sling/myelin/rnn.h"
#include "sling/myelin/builder.h"
#include "sling/myelin/gradient.h"
namespace sling {
namespace myelin {
RNN::Variables RNN::Build(Flow *flow,
Flow::Variable *input,
Flow::Variable *dinput) {
// Build RNN cell.
bool learn = dinput != nullptr;
Variables vars;
FlowBuilder tf(flow, name);
auto dt = input->type;
int input_dim = input->dim(1);
int rnn_dim = spec.dim;
// Build inputs.
auto *x = tf.Placeholder("input", dt, input->shape, true);
auto *h_in = tf.Placeholder("h_in", dt, {1, rnn_dim}, true);
Flow::Variable *c_in = nullptr;
if (spec.type != GRU) {
c_in = tf.Placeholder("c_in", dt, {1, rnn_dim}, true);
}
// Build recurrent unit.
Flow::Variable *h_out = nullptr; // hidden output
Flow::Variable *c_out = nullptr; // control output
Flow::Variable *residual = nullptr; // residial gate for highway connection
switch (spec.type) {
case LSTM: {
// Standard LSTM.
auto *x2i = tf.Parameter("x2i", dt, {input_dim, rnn_dim});
auto *h2i = tf.Parameter("h2i", dt, {rnn_dim, rnn_dim});
auto *bi = tf.Parameter("bi", dt, {1, rnn_dim});
tf.RandomOrtho(x2i);
tf.RandomOrtho(h2i);
auto *x2f = tf.Parameter("x2f", dt, {input_dim, rnn_dim});
auto *h2f = tf.Parameter("h2f", dt, {rnn_dim, rnn_dim});
auto *bf = tf.Parameter("bf", dt, {1, rnn_dim});
tf.RandomOrtho(x2f);
tf.RandomOrtho(h2f);
auto *x2g = tf.Parameter("x2g", dt, {input_dim, rnn_dim});
auto *h2g = tf.Parameter("h2g", dt, {rnn_dim, rnn_dim});
auto *bg = tf.Parameter("bg", dt, {1, rnn_dim});
tf.RandomOrtho(x2g);
tf.RandomOrtho(h2g);
auto *x2o = tf.Parameter("x2o", dt, {input_dim, rnn_dim});
auto *h2o = tf.Parameter("h2o", dt, {rnn_dim, rnn_dim});
auto *bo = tf.Parameter("bo", dt, {1, rnn_dim});
tf.RandomOrtho(x2o);
tf.RandomOrtho(h2o);
// i = sigmoid(x * x2i + h_in * h2i + bi)
auto *ia = tf.Add(tf.MatMul(x, x2i), tf.Add(tf.MatMul(h_in, h2i), bi));
auto *i = tf.Name(tf.Sigmoid(ia), "i");
// f = sigmoid(x * x2f + h_in * h2f + bf)
auto *fa = tf.Add(tf.MatMul(x, x2f), tf.Add(tf.MatMul(h_in, h2f), bf));
auto *f = tf.Name(tf.Sigmoid(fa), "f");
// g = tanh(x * x2g + h_in * h2g + bg)
auto *ga = tf.Add(tf.MatMul(x, x2g), tf.Add(tf.MatMul(h_in, h2g), bg));
auto *g = tf.Name(tf.Tanh(ga), "g");
// o = sigmoid(x * x2o + h_in * h2o + bo)
auto *oa = tf.Add(tf.MatMul(x, x2o), tf.Add(tf.MatMul(h_in, h2o), bo));
auto *o = tf.Name(tf.Sigmoid(oa), "o");
// residual = sigmoid(x * x2r + h_in * h2r + br)
if (spec.highways) {
auto *x2r = tf.Parameter("x2r", dt, {input_dim, rnn_dim});
auto *h2r = tf.Parameter("h2r", dt, {rnn_dim, rnn_dim});
auto *br = tf.Parameter("br", dt, {1, rnn_dim});
tf.RandomOrtho(x2r);
tf.RandomOrtho(h2r);
auto *ra = tf.Add(tf.Add(tf.MatMul(x, x2r),tf.MatMul(h_in, h2r)), br);
residual = tf.Name(tf.Sigmoid(ra), "r");
}
// c_out = f * c_in + i * g
c_out = tf.Add(tf.Mul(f, c_in), tf.Mul(i, g));
// h_out = o * tanh(c_out)
h_out = tf.Mul(o, tf.Tanh(c_out));
break;
}
case DRAGNN_LSTM: {
// DRAGNN LSTM with peephole and coupled gates.
auto *x2i = tf.Parameter("x2i", dt, {input_dim, rnn_dim});
auto *h2i = tf.Parameter("h2i", dt, {rnn_dim, rnn_dim});
auto *c2i = tf.Parameter("c2i", dt, {rnn_dim, rnn_dim});
auto *bi = tf.Parameter("bi", dt, {1, rnn_dim});
tf.RandomOrtho(x2i);
tf.RandomOrtho(h2i);
tf.RandomOrtho(c2i);
auto *x2o = tf.Parameter("x2o", dt, {input_dim, rnn_dim});
auto *h2o = tf.Parameter("h2o", dt, {rnn_dim, rnn_dim});
auto *c2o = tf.Parameter("c2o", dt, {rnn_dim, rnn_dim});
auto *bo = tf.Parameter("bo", dt, {1, rnn_dim});
tf.RandomOrtho(x2o);
tf.RandomOrtho(h2o);
tf.RandomOrtho(c2o);
auto *x2c = tf.Parameter("x2c", dt, {input_dim, rnn_dim});
auto *h2c = tf.Parameter("h2c", dt, {rnn_dim, rnn_dim});
auto *bc = tf.Parameter("bc", dt, {1, rnn_dim});
tf.RandomOrtho(x2c);
tf.RandomOrtho(h2c);
// i = sigmoid(x * x2i + h_in * h2i + c_in * c2i + bi)
auto *ia = tf.Add(tf.MatMul(x, x2i),
tf.Add(tf.MatMul(h_in, h2i),
tf.Add(tf.MatMul(c_in, c2i), bi)));
auto *i = tf.Name(tf.Sigmoid(ia), "i");
// f = 1 - i
auto *f = tf.Name(tf.Sub(tf.One(), i), "f");
// w = tanh(x * x2c + h_in * h2c + bc)
auto *wa = tf.Add(tf.MatMul(x, x2c),
tf.Add(tf.MatMul(h_in, h2c), bc));
auto *w = tf.Name(tf.Tanh(wa), "w");
// c_out = i * w + f * c_in
c_out = tf.Add(tf.Mul(i, w), tf.Mul(f, c_in));
// o = sigmoid(x * x2o + c_out * c2o + h_in * h2o + bo)
auto *oa = tf.Add(tf.MatMul(x, x2o),
tf.Add(tf.MatMul(c_out, c2o),
tf.Add(tf.MatMul(h_in, h2o), bo)));
auto *o = tf.Name(tf.Sigmoid(oa), "o");
// r = sigmoid(x * x2r + h_in * h2r + br)
if (spec.highways) {
auto *x2r = tf.Parameter("x2r", dt, {input_dim, rnn_dim});
auto *h2r = tf.Parameter("h2r", dt, {rnn_dim, rnn_dim});
auto *br = tf.Parameter("br", dt, {1, rnn_dim});
tf.RandomOrtho(x2r);
tf.RandomOrtho(h2r);
auto *ra = tf.Add(tf.Add(tf.MatMul(x, x2r),tf.MatMul(h_in, h2r)), br);
residual = tf.Name(tf.Sigmoid(ra), "r");
}
// h_out = o * tanh(c_out)
h_out = tf.Mul(o, tf.Tanh(c_out));
break;
}
case DOZAT_LSTM: {
// Standard LSTM with one matrix multiplication.
int gates = spec.highways ? 5 : 4;
auto *w = tf.Parameter("W", dt, {input_dim + rnn_dim, gates * rnn_dim});
auto *b = tf.Parameter("b", dt, {1, gates * rnn_dim});
tf.RandomOrtho(w);
// Preactivations.
auto *xh = tf.Concat({x, h_in}, 1);
auto p = tf.Split(tf.Add(tf.MatMul(xh, w), b), gates, 1);
// Gates.
auto *f = tf.Name(tf.Sigmoid(p[0]), "f");
auto *i = tf.Name(tf.Sigmoid(p[1]), "i");
auto *o = tf.Name(tf.Sigmoid(p[2]), "o");
auto *g = tf.Name(tf.Tanh(p[3]), "g");
if (spec.highways) {
residual = tf.Name(tf.Sigmoid(p[4]), "r");
}
// Outputs.
c_out = tf.Add(tf.Mul(f, c_in), tf.Mul(i, g));
h_out = tf.Mul(o, tf.Tanh(c_out));
break;
}
case PYTORCH_LSTM: {
// Standard LSTM with two matrix multiplications.
int gates = spec.highways ? 5 : 4;
auto *w_ih = tf.Parameter("w_ih", dt, {input_dim, gates * rnn_dim});
auto *w_hh = tf.Parameter("w_hh", dt, {rnn_dim, gates * rnn_dim});
auto *b_ih = tf.Parameter("b_ih", dt, {1, gates * rnn_dim});
auto *b_hh = tf.Parameter("b_hh", dt, {1, gates * rnn_dim});
tf.RandomOrtho(w_ih);
tf.RandomOrtho(w_hh);
// Preactivations.
auto *ih = tf.Add(tf.MatMul(x, w_ih), b_ih);
auto *hh = tf.Add(tf.MatMul(h_in, w_hh), b_hh);
auto p = tf.Split(tf.Add(ih, hh), gates, 1);
// Gates.
auto *f = tf.Name(tf.Sigmoid(p[0]), "f");
auto *i = tf.Name(tf.Sigmoid(p[1]), "i");
auto *o = tf.Name(tf.Sigmoid(p[2]), "o");
auto *g = tf.Name(tf.Tanh(p[3]), "g");
if (spec.highways) {
residual = tf.Name(tf.Sigmoid(p[4]), "r");
}
// Outputs.
c_out = tf.Add(tf.Mul(f, c_in), tf.Mul(i, g));
h_out = tf.Mul(o, tf.Tanh(c_out));
break;
}
case GRU: {
// Gated Recurrent Unit.
auto *x2z = tf.Parameter("x2z", dt, {input_dim, rnn_dim});
auto *h2z = tf.Parameter("h2z", dt, {rnn_dim, rnn_dim});
tf.RandomOrtho(x2z);
tf.RandomOrtho(h2z);
auto *x2r = tf.Parameter("x2r", dt, {input_dim, rnn_dim});
auto *h2r = tf.Parameter("h2r", dt, {rnn_dim, rnn_dim});
tf.RandomOrtho(x2r);
tf.RandomOrtho(h2r);
auto *x2h = tf.Parameter("x2h", dt, {input_dim, rnn_dim});
auto *h2h = tf.Parameter("h2h", dt, {rnn_dim, rnn_dim});
tf.RandomOrtho(x2h);
tf.RandomOrtho(h2h);
// z = sigmoid(x * x2z + h_in * h2z)
auto *za = tf.Add(tf.MatMul(x, x2z), tf.MatMul(h_in, h2z));
auto *z = tf.Name(tf.Sigmoid(za), "z");
// r = sigmoid(x * x2r + h_in * h2r)
auto *ra = tf.Add(tf.MatMul(x, x2r), tf.MatMul(h_in, h2r));
auto *r = tf.Name(tf.Sigmoid(ra), "r");
// h = tanh(x * x2h + (r * h_in) * h2h)
auto *ha = tf.Add(tf.MatMul(x, x2h), tf.MatMul(tf.Mul(r, h_in), h2h));
auto *h = tf.Name(tf.Tanh(ha), "h");
// residual = sigmoid(x * x2b + h_in * h2b)
if (spec.highways) {
auto *x2b = tf.Parameter("x2b", dt, {input_dim, rnn_dim});
auto *h2b = tf.Parameter("h2b", dt, {rnn_dim, rnn_dim});
tf.RandomOrtho(x2b);
tf.RandomOrtho(h2b);
auto *ra = tf.Add(tf.MatMul(x, x2b),tf.MatMul(h_in, h2b));
residual = tf.Name(tf.Sigmoid(ra), "r");
}
// h_out = (1 - z) * h_in + z * h
h_out = tf.Add(tf.Mul(tf.Sub(tf.One(), z), h_in), tf.Mul(z, h));
break;
}
default:
LOG(FATAL) << "RNN type not supported: " << spec.type;
}
// Highway connection.
if (residual != nullptr) {
// Highway connection.
auto *bypass = x;
if (input_dim != rnn_dim) {
// Linear transform from input to output dimension.
auto *wx = tf.RandomOrtho(tf.Parameter("Wr", dt, {input_dim, rnn_dim}));
bypass = tf.MatMul(x, wx);
}
h_out = tf.Add(tf.Mul(residual, h_out),
tf.Mul(tf.Sub(tf.One(), residual), bypass));
}
// Apply dropout to output.
if (learn && spec.dropout != 0.0) {
auto *mask = tf.Placeholder("mask", DT_FLOAT, {1, rnn_dim}, true);
mask->set(Flow::Variable::NOGRADIENT);
h_out = tf.Mul(h_out, mask);
// The no-dropout mask is used for testing during training when no dropout
// should be applied.
std::vector<float> ones(rnn_dim, 1.0);
auto *nodropout = tf.Name(tf.Const(ones), "nodropout");
nodropout->set_out();
flow->Connect({nodropout, mask});
}
// Name RNN outputs.
if (h_out != nullptr) tf.Name(h_out, "h_out");
if (c_out != nullptr) tf.Name(c_out, "c_out");
// Make zero element.
auto *zero = tf.Name(tf.Const(nullptr, dt, {1, rnn_dim}), "zero");
zero->set_out();
// Connect RNN units.
vars.input = x;
vars.output = h_out;
flow->Connect({x, input});
h_out->set_out()->set_ref();
flow->Connect({h_in, h_out, zero});
if (c_in != nullptr) {
c_out->set_out()->set_ref();
flow->Connect({c_in, c_out, zero});
// The control channel has a single-source gradient.
c_in->set_unique();
}
// Build gradients for learning.
if (learn) {
auto *gf = Gradient(flow, tf.func());
vars.dinput = flow->GradientVar(vars.input);
vars.doutput = flow->GradientVar(vars.output);
flow->Connect({vars.dinput, dinput});
// Make sink variable for final channel gradients.
auto *sink = tf.Var("sink", dt, {1, rnn_dim})->set_out();
gf->unused.push_back(sink);
auto *dh_in = flow->GradientVar(h_in);
auto *dh_out = flow->GradientVar(h_out);
flow->Connect({dh_in, dh_out, sink});
if (c_out != nullptr) {
auto *dc_in = flow->GradientVar(c_in);
auto *dc_out = flow->GradientVar(c_out);
flow->Connect({dc_in, dc_out, sink});
}
}
return vars;
}
void RNN::Initialize(const Network &net) {
// Initialize RNN cell. Control channel is optional.
cell = net.GetCell(name);
input = net.GetParameter(name + "/input");
h_in = net.GetParameter(name + "/h_in");
h_out = net.GetParameter(name + "/h_out");
c_in = net.LookupParameter(name + "/c_in");
c_out = net.LookupParameter(name + "/c_out");
zero = net.GetParameter(name + "/zero");
// Initialize gradient cell for RNN.
gcell = cell->Gradient();
if (gcell != nullptr) {
primal = cell->Primal();
dinput = input->Gradient();
dh_in = h_in->Gradient();
dh_out = h_out->Gradient();
dc_in = c_in == nullptr ? nullptr : c_in->Gradient();
dc_out = c_out == nullptr ? nullptr : c_out->Gradient();
sink = net.GetParameter(name + "/sink");
}
// Initialize dropout mask.
if (spec.dropout != 0.0) {
mask = net.GetParameter(name + "/mask");
nodropout = net.GetParameter(name + "/nodropout");
}
}
RNNMerger::Variables RNNMerger::Build(Flow *flow,
Flow::Variable *left,
Flow::Variable *right,
Flow::Variable *dleft,
Flow::Variable *dright) {
Variables vars;
// Build merger cell.
FlowBuilder f(flow, name);
vars.left = f.Placeholder("left", left->type, left->shape);
vars.left->set_dynamic()->set_unique();
vars.right = f.Placeholder("right", right->type, right->shape);
vars.right->set_dynamic()->set_unique();
vars.merged = f.Name(f.Concat({vars.left, vars.right}, 1), "merged");
vars.merged->set_dynamic();
flow->Connect({vars.left, left});
flow->Connect({vars.right, right});
// Build gradients for learning.
if (dleft != nullptr && dright != nullptr) {
Gradient(flow, f.func());
vars.dmerged = flow->GradientVar(vars.merged);
vars.dleft = flow->GradientVar(vars.left);
vars.dright = flow->GradientVar(vars.right);
flow->Connect({vars.dleft, dleft});
flow->Connect({vars.dright, dright});
} else {
vars.dmerged = vars.dleft = vars.dright = nullptr;
}
return vars;
}
void RNNMerger::Initialize(const Network &net) {
cell = net.GetCell(name);
left = net.GetParameter(name + "/left");
right = net.GetParameter(name + "/right");
merged = net.GetParameter(name + "/merged");
gcell = cell->Gradient();
if (gcell != nullptr) {
dmerged = merged->Gradient();
dleft = left->Gradient();
dright = right->Gradient();
}
}
RNNLayer::RNNLayer(const string &name, const RNN::Spec &spec, bool bidir)
: name_(name),
bidir_(bidir),
dropout_(spec.dropout),
lr_(bidir ? name + "/lr" : name, spec),
rl_(name + "/rl", spec),
merger_(name) {}
RNN::Variables RNNLayer::Build(Flow *flow,
Flow::Variable *input,
Flow::Variable *dinput) {
if (bidir_) {
// Build left-to-right and right-to-left RNNs.
auto l = lr_.Build(flow, input, dinput);
auto r = rl_.Build(flow, input, dinput);
// Build channel merger.
auto m = merger_.Build(flow, l.output, r.output, l.doutput, r.doutput);
// Return outputs.
RNN::Variables vars;
vars.input = l.input;
vars.output = m.merged;
vars.dinput = l.dinput;
vars.doutput = m.dmerged;
return vars;
} else {
return lr_.Build(flow, input, dinput);
}
}
void RNNLayer::Initialize(const Network &net) {
lr_.Initialize(net);
if (bidir_) {
rl_.Initialize(net);
merger_.Initialize(net);
}
}
RNNPredictor::RNNPredictor(const RNNLayer *rnn)
: rnn_(rnn),
lr_(rnn->lr_.cell),
lr_hidden_(rnn->lr_.h_out),
lr_control_(rnn->lr_.c_out),
rl_(rnn->rl_.cell),
rl_hidden_(rnn->rl_.h_out),
rl_control_(rnn->rl_.c_out),
merger_(rnn->merger_.cell),
merged_(rnn->merger_.merged) {}
Channel *RNNPredictor::Compute(Channel *input) {
// Get sequence length.
int length = input->size();
bool ctrl = rnn_->lr_.has_control();
// Set pass-through dropout mask.
if (rnn_->lr_.has_mask()) {
lr_.SetReference(rnn_->lr_.mask, rnn_->lr_.nodropout->data());
}
// Compute left-to-right RNN.
lr_hidden_.resize(length);
if (ctrl) lr_control_.resize(length);
if (length > 0) {
lr_.Set(rnn_->lr_.input, input, 0);
lr_.SetReference(rnn_->lr_.h_in, rnn_->lr_.zero->data());
lr_.Set(rnn_->lr_.h_out, &lr_hidden_, 0);
if (ctrl) {
lr_.SetReference(rnn_->lr_.c_in, rnn_->lr_.zero->data());
lr_.Set(rnn_->lr_.c_out, &lr_control_, 0);
}
lr_.Compute();
}
for (int i = 1; i < length; ++i) {
lr_.Set(rnn_->lr_.input, input, i);
lr_.Set(rnn_->lr_.h_in, &lr_hidden_, i - 1);
lr_.Set(rnn_->lr_.h_out, &lr_hidden_, i);
if (ctrl) {
lr_.Set(rnn_->lr_.c_in, &lr_control_, i - 1);
lr_.Set(rnn_->lr_.c_out, &lr_control_, i);
}
lr_.Compute();
}
// Return left-to-right hidden channel for unidirectional RNN.
if (!rnn_->bidir_) return &lr_hidden_;
// Set pass-through dropout mask.
if (rnn_->rl_.has_mask()) {
rl_.SetReference(rnn_->rl_.mask, rnn_->rl_.nodropout->data());
}
// Compute right-to-left RNN.
rl_hidden_.resize(length);
if (ctrl) rl_control_.resize(length);
if (length > 0) {
rl_.Set(rnn_->rl_.input, input, length - 1);
rl_.SetReference(rnn_->rl_.h_in, rnn_->rl_.zero->data());
rl_.Set(rnn_->rl_.h_out, &rl_hidden_, length - 1);
if (ctrl) {
rl_.SetReference(rnn_->rl_.c_in, rnn_->rl_.zero->data());
rl_.Set(rnn_->rl_.c_out, &rl_control_, length - 1);
}
rl_.Compute();
}
for (int i = length - 2; i >= 0; --i) {
rl_.Set(rnn_->rl_.input, input, i);
rl_.Set(rnn_->rl_.h_in, &rl_hidden_, i + 1);
rl_.Set(rnn_->rl_.h_out, &rl_hidden_, i);
if (ctrl) {
rl_.Set(rnn_->rl_.c_in, &rl_control_, i + 1);
rl_.Set(rnn_->rl_.c_out, &rl_control_, i);
}
rl_.Compute();
}
// Merge outputs.
merged_.resize(length);
merger_.SetChannel(rnn_->merger_.left, &lr_hidden_);
merger_.SetChannel(rnn_->merger_.right, &rl_hidden_);
merger_.SetChannel(rnn_->merger_.merged, &merged_);
merger_.Compute();
return &merged_;
}
RNNLearner::RNNLearner(const RNNLayer *rnn)
: rnn_(rnn),
lr_fwd_(rnn->lr_.cell),
lr_hidden_(rnn->lr_.h_out),
lr_control_(rnn->lr_.c_out),
lr_bkw_(rnn->lr_.gcell),
lr_dhidden_(rnn->lr_.dh_in),
lr_dcontrol_(rnn->lr_.dc_in),
rl_fwd_(rnn->rl_.cell),
rl_hidden_(rnn->rl_.h_out),
rl_control_(rnn->rl_.c_out),
rl_bkw_(rnn->rl_.gcell),
rl_dhidden_(rnn->rl_.dh_in),
rl_dcontrol_(rnn->rl_.dc_in),
dinput_(rnn_->lr_.dinput),
merger_(rnn->merger_.cell),
splitter_(rnn->merger_.gcell),
merged_(rnn->merger_.merged),
dleft_(rnn->merger_.dleft),
dright_(rnn->merger_.dright),
mask_(rnn_->lr_.mask) {
if (rnn->dropout_ != 0.0) {
mask_.resize(1);
}
}
Channel *RNNLearner::Compute(Channel *input) {
// Get sequence length.
int length = input->size();
bool ctrl = rnn_->lr_.has_control();
// Set up dropout mask.
bool dropout = rnn_->dropout_ != 0.0;
if (dropout) {
float *mask = reinterpret_cast<float *>(mask_.at(0));
float rate = rnn_->dropout_;
float scaler = 1.0 / (1.0 - rate);
int size = rnn_->lr_.spec.dim;
for (int i = 0; i < size; ++i) {
mask[i] = Random() < rate ? 0.0 : scaler;
}
}
// Compute left-to-right RNN.
lr_fwd_.Resize(length);
lr_hidden_.resize(length);
if (ctrl) lr_control_.resize(length);
if (length > 0) {
Instance &data = lr_fwd_[0];
data.Set(rnn_->lr_.input, input, 0);
data.SetReference(rnn_->lr_.h_in, rnn_->lr_.zero->data());
data.Set(rnn_->lr_.h_out, &lr_hidden_, 0);
if (ctrl) {
data.SetReference(rnn_->lr_.c_in, rnn_->lr_.zero->data());
data.Set(rnn_->lr_.c_out, &lr_control_, 0);
}
if (dropout) {
data.Set(rnn_->lr_.mask, &mask_, 0);
}
data.Compute();
}
for (int i = 1; i < length; ++i) {
Instance &data = lr_fwd_[i];
data.Set(rnn_->lr_.input, input, i);
data.Set(rnn_->lr_.h_in, &lr_hidden_, i - 1);
data.Set(rnn_->lr_.h_out, &lr_hidden_, i);
if (ctrl) {
data.Set(rnn_->lr_.c_in, &lr_control_, i - 1);
data.Set(rnn_->lr_.c_out, &lr_control_, i);
}
if (dropout) {
data.Set(rnn_->lr_.mask, &mask_, 0);
}
data.Compute();
}
// Return left-to-right hidden channel for unidirectional RNN.
if (!rnn_->bidir_) return &lr_hidden_;
// Compute right-to-left RNN.
rl_fwd_.Resize(length);
rl_hidden_.resize(length);
if (ctrl) rl_control_.resize(length);
if (length > 0) {
Instance &data = rl_fwd_[length - 1];
data.Set(rnn_->rl_.input, input, length - 1);
data.SetReference(rnn_->rl_.h_in, rnn_->rl_.zero->data());
data.Set(rnn_->rl_.h_out, &rl_hidden_, length - 1);
if (ctrl) {
data.SetReference(rnn_->rl_.c_in, rnn_->rl_.zero->data());
data.Set(rnn_->rl_.c_out, &rl_control_, length - 1);
}
if (dropout) {
data.Set(rnn_->rl_.mask, &mask_, 0);
}
data.Compute();
}
for (int i = length - 2; i >= 0; --i) {
Instance &data = rl_fwd_[i];
data.Set(rnn_->rl_.input, input, i);
data.Set(rnn_->rl_.h_in, &rl_hidden_, i + 1);
data.Set(rnn_->rl_.h_out, &rl_hidden_, i);
if (ctrl) {
data.Set(rnn_->rl_.c_in, &rl_control_, i + 1);
data.Set(rnn_->rl_.c_out, &rl_control_, i);
}
if (dropout) {
data.Set(rnn_->rl_.mask, &mask_, 0);
}
data.Compute();
}
// Merge outputs.
merged_.resize(length);
merger_.SetChannel(rnn_->merger_.left, &lr_hidden_);
merger_.SetChannel(rnn_->merger_.right, &rl_hidden_);
merger_.SetChannel(rnn_->merger_.merged, &merged_);
merger_.Compute();
return &merged_;
}
Channel *RNNLearner::Backpropagate(Channel *doutput) {
// Clear input gradient.
int length = doutput->size();
dinput_.reset(length);
bool ctrl = rnn_->lr_.has_control();
// Split gradient for bidirectional RNN.
Channel *dleft;
Channel *dright;
if (rnn_->bidir_) {
// Split gradients.
dleft_.resize(length);
dright_.resize(length);
splitter_.SetChannel(rnn_->merger_.dmerged, doutput);
splitter_.SetChannel(rnn_->merger_.dleft, &dleft_);
splitter_.SetChannel(rnn_->merger_.dright, &dright_);
splitter_.Compute();
dleft = &dleft_;
dright = &dright_;
} else {
dleft = doutput;
dright = nullptr;
}
// Propagate gradients for left-to-right RNN.
if (dleft != nullptr) {
if (ctrl) lr_dcontrol_.reset(length);
for (int i = length - 1; i > 0; --i) {
lr_bkw_.Set(rnn_->lr_.primal, &lr_fwd_[i]);
lr_bkw_.Set(rnn_->lr_.dh_out, dleft, i);
lr_bkw_.Set(rnn_->lr_.dh_in, dleft, i - 1);
lr_bkw_.Set(rnn_->lr_.dinput, &dinput_, i);
if (ctrl) {
lr_bkw_.Set(rnn_->lr_.dc_out, &lr_dcontrol_, i);
lr_bkw_.Set(rnn_->lr_.dc_in, &lr_dcontrol_, i - 1);
}
lr_bkw_.Compute();
}
if (length > 0) {
void *sink = lr_bkw_.GetAddress(rnn_->lr_.sink);
lr_bkw_.Set(rnn_->lr_.primal, &lr_fwd_[0]);
lr_bkw_.Set(rnn_->lr_.dh_out, dleft, 0);
lr_bkw_.SetReference(rnn_->lr_.dh_in, sink);
lr_bkw_.Set(rnn_->lr_.dinput, &dinput_, 0);
if (ctrl) {
lr_bkw_.Set(rnn_->lr_.dc_out, &lr_dcontrol_, 0);
lr_bkw_.SetReference(rnn_->lr_.dc_in, sink);
}
lr_bkw_.Compute();
}
}
// Propagate gradients for right-to-left RNN.
if (dright != nullptr) {
if (ctrl) rl_dcontrol_.reset(length);
for (int i = 0; i < length - 1; ++i) {
rl_bkw_.Set(rnn_->rl_.primal, &rl_fwd_[i]);
rl_bkw_.Set(rnn_->rl_.dh_out, dright, i);
rl_bkw_.Set(rnn_->rl_.dh_in, dright, i + 1);
rl_bkw_.Set(rnn_->rl_.dinput, &dinput_, i);
if (ctrl) {
rl_bkw_.Set(rnn_->rl_.dc_out, &rl_dcontrol_, i);
rl_bkw_.Set(rnn_->rl_.dc_in, &rl_dcontrol_, i + 1);
}
rl_bkw_.Compute();
}
if (length > 0) {
void *sink = rl_bkw_.GetAddress(rnn_->rl_.sink);
rl_bkw_.Set(rnn_->rl_.primal, &rl_fwd_[length - 1]);
rl_bkw_.Set(rnn_->rl_.dh_out, dright, length - 1);
rl_bkw_.SetReference(rnn_->rl_.dh_in, sink);
rl_bkw_.Set(rnn_->rl_.dinput, &dinput_, length - 1);
if (ctrl) {
rl_bkw_.Set(rnn_->rl_.dc_out, &rl_dcontrol_, length - 1);
rl_bkw_.SetReference(rnn_->rl_.dc_in, sink);
}
rl_bkw_.Compute();
}
}
// Return input gradient.
return &dinput_;
}
void RNNLearner::CollectGradients(Instances *gradients) {
gradients->Add(&lr_bkw_);
if (rnn_->bidir_) gradients->Add(&rl_bkw_);
}
void RNNStack::AddLayer(const RNN::Spec &spec, bool bidir) {
string name = name_ + "/rnn" + std::to_string(layers_.size());
layers_.emplace_back(name, spec, bidir);
}
void RNNStack::AddLayers(int layers, const RNN::Spec &spec, bool bidir) {
for (int l = 0; l < layers; ++l) {
AddLayer(spec, bidir);
}
}
RNN::Variables RNNStack::Build(Flow *flow,
Flow::Variable *input,
Flow::Variable *dinput) {
RNN::Variables vars;
vars.input = vars.output = input;
vars.dinput = vars.doutput = dinput;
for (RNNLayer &l : layers_) {
RNN::Variables v = l.Build(flow, vars.output, vars.doutput);
vars.output = v.output;
vars.doutput = v.doutput;
}
return vars;
}
void RNNStack::Initialize(const Network &net) {
for (RNNLayer &l : layers_) {
l.Initialize(net);
}
}
RNNStackPredictor::RNNStackPredictor(const RNNStack &stack) {
layers_.reserve(stack.layers().size());
for (const RNNLayer &l : stack.layers()) {
layers_.emplace_back(&l);
}
}
Channel *RNNStackPredictor::Compute(Channel *input) {
Channel *channel = input;
for (RNNPredictor &l : layers_) {
channel = l.Compute(channel);
}
return channel;
}
RNNStackLearner::RNNStackLearner(const RNNStack &stack) {
layers_.reserve(stack.layers().size());
for (const RNNLayer &l : stack.layers()) {
layers_.emplace_back(&l);
}
}
Channel *RNNStackLearner::Compute(Channel *input) {
Channel *channel = input;
for (RNNLearner &l : layers_) {
channel = l.Compute(channel);
}
return channel;
}
Channel *RNNStackLearner::Backpropagate(Channel *doutput) {
Channel *channel = doutput;
for (int i = layers_.size() - 1; i >= 0; --i) {
channel = layers_[i].Backpropagate(channel);
}
return channel;
}
void RNNStackLearner::CollectGradients(Instances *gradients) {
for (RNNLearner &l : layers_) {
l.CollectGradients(gradients);
}
}
} // namespace myelin
} // namespace sling
| 31.257611 | 78 | 0.589945 | [
"shape",
"vector",
"transform"
] |
39b86867fbe2f5417889df1c664df1f2cf37d481 | 5,362 | cpp | C++ | src/modules/adc_readout/SampleProcessing.cpp | geishm-ansto/event-formation-unit | bab9f211913ee9e633eae627ec2c2ed96ae380b4 | [
"BSD-2-Clause"
] | 8 | 2017-12-02T09:20:26.000Z | 2022-03-28T08:17:40.000Z | src/modules/adc_readout/SampleProcessing.cpp | geishm-ansto/event-formation-unit | bab9f211913ee9e633eae627ec2c2ed96ae380b4 | [
"BSD-2-Clause"
] | 296 | 2017-10-24T09:06:10.000Z | 2022-03-31T07:31:06.000Z | src/modules/adc_readout/SampleProcessing.cpp | geishm-ansto/event-formation-unit | bab9f211913ee9e633eae627ec2c2ed96ae380b4 | [
"BSD-2-Clause"
] | 8 | 2018-04-08T15:35:50.000Z | 2021-04-12T05:06:15.000Z | /** Copyright (C) 2018 European Spallation Source ERIC */
/** @file
*
* \brief Sample processing of the ADC data.
*/
#include "SampleProcessing.h"
#include "AdcReadoutConstants.h"
#include "senv_data_generated.h"
#include <algorithm>
#include <cmath>
std::uint64_t CalcSampleTimeStamp(const TimeStamp &Start, const TimeStamp &End,
const TimeStampLocation Location) {
std::uint64_t StartNS = Start.getTimeStampNS();
std::uint64_t EndNS = End.getTimeStampNS();
if (TimeStampLocation::Start == Location) {
return StartNS;
}
if (TimeStampLocation::End == Location) {
return EndNS;
}
return StartNS + (EndNS - StartNS) / 2;
}
ProcessedSamples ChannelProcessing::processModule(const SamplingRun &Samples) {
int FinalOversamplingFactor = MeanOfNrOfSamples * Samples.OversamplingFactor;
if (FinalOversamplingFactor == 0) {
FinalOversamplingFactor = 1;
}
size_t SampleIndex{0};
size_t TotalNumberOfSamples =
(Samples.Data.size() + NrOfSamplesSummed) / MeanOfNrOfSamples;
ProcessedSamples ReturnSamples(TotalNumberOfSamples);
ReturnSamples.TimeDelta = FinalOversamplingFactor *
Samples.ReferenceTimestamp.getClockCycleLength();
std::uint64_t TimeStampOffset{0};
if (TSLocation == TimeStampLocation::Middle) {
TimeStampOffset =
std::llround(0.5 * (ReturnSamples.TimeDelta / FinalOversamplingFactor) *
(FinalOversamplingFactor - 1));
} else if (TSLocation == TimeStampLocation::End) {
TimeStampOffset =
std::llround((ReturnSamples.TimeDelta / FinalOversamplingFactor) *
(FinalOversamplingFactor - 1));
}
for (size_t i = 0; i < Samples.Data.size(); i++) {
if (0 == NrOfSamplesSummed) {
TimeStampOfFirstSample = Samples.StartTime.getOffsetTimeStamp(
i * Samples.OversamplingFactor - (Samples.OversamplingFactor - 1));
}
SumOfSamples += Samples.Data[i];
NrOfSamplesSummed++;
if (NrOfSamplesSummed == MeanOfNrOfSamples) {
ReturnSamples.Samples[SampleIndex] =
SumOfSamples / FinalOversamplingFactor;
ReturnSamples.TimeStamps[SampleIndex] =
TimeStampOfFirstSample.getTimeStampNS() + TimeStampOffset;
ChannelProcessing::reset();
++SampleIndex;
}
}
if (not ReturnSamples.TimeStamps.empty()) {
ReturnSamples.TimeStamp = ReturnSamples.TimeStamps[0];
}
ReturnSamples.Identifier = Samples.Identifier;
return ReturnSamples;
}
void ChannelProcessing::setMeanOfSamples(int NrOfSamples) {
MeanOfNrOfSamples = NrOfSamples;
reset();
}
void ChannelProcessing::setTimeStampLocation(TimeStampLocation Location) {
TSLocation = Location;
}
void ChannelProcessing::reset() {
SumOfSamples = 0;
NrOfSamplesSummed = 0;
}
SampleProcessing::SampleProcessing(std::shared_ptr<ProducerBase> Prod,
std::string Name, OffsetTime UsedOffset)
: AdcDataProcessor(std::move(Prod)), AdcName(std::move(Name)),
TimeOffset(UsedOffset) {}
void SampleProcessing::setMeanOfSamples(int NrOfSamples) {
MeanOfNrOfSamples = NrOfSamples;
ProcessingInstance.setMeanOfSamples(MeanOfNrOfSamples);
}
void SampleProcessing::setSerializeTimestamps(bool SerializeTimeStamps) {
SampleTimestamps = SerializeTimeStamps;
}
void SampleProcessing::setTimeStampLocation(TimeStampLocation Location) {
TSLocation = Location;
ProcessingInstance.setTimeStampLocation(TSLocation);
}
void SampleProcessing::processData(const SamplingRun &Data) {
auto ResultingSamples = ProcessingInstance.processModule(Data);
if (not ResultingSamples.Samples.empty()) {
serializeAndTransmitData(ResultingSamples);
}
}
void SampleProcessing::serializeAndTransmitData(ProcessedSamples const &Data) {
flatbuffers::FlatBufferBuilder builder;
auto FBSampleData = builder.CreateVector(Data.Samples);
auto SampleDataUnion = CreateUInt16Array(builder, FBSampleData);
flatbuffers::Offset<flatbuffers::Vector<std::uint64_t>> FBTimeStamps;
if (SampleTimestamps) {
auto SampleTimes = Data.TimeStamps;
std::transform(
SampleTimes.begin(), SampleTimes.end(), SampleTimes.begin(),
[this](auto const &TS) { return TimeOffset.calcTimestampNS(TS); });
FBTimeStamps = builder.CreateVector(SampleTimes);
}
auto FBName = builder.CreateString(
AdcName + "_Adc" + std::to_string(Data.Identifier.SourceID) + "_Ch" +
std::to_string(Data.Identifier.ChannelNr) + "_waveform");
SampleEnvironmentDataBuilder MessageBuilder(builder);
MessageBuilder.add_Name(FBName);
MessageBuilder.add_Values(SampleDataUnion.Union());
MessageBuilder.add_Values_type(ValueUnion::UInt16Array);
if (SampleTimestamps) {
MessageBuilder.add_Timestamps(FBTimeStamps);
}
MessageBuilder.add_Channel(Data.Identifier.ChannelNr);
auto NewOffsetTimestamp = TimeOffset.calcTimestampNS(Data.TimeStamp);
MessageBuilder.add_PacketTimestamp(NewOffsetTimestamp);
MessageBuilder.add_TimeDelta(Data.TimeDelta);
MessageBuilder.add_MessageCounter(MessageCounter++);
MessageBuilder.add_TimestampLocation(
Location(TimeLocSerialisationMap.at(TSLocation)));
builder.Finish(MessageBuilder.Finish(), SampleEnvironmentDataIdentifier());
ProducerPtr->produce({builder.GetBufferPointer(), builder.GetSize()},
NewOffsetTimestamp / 1000000);
}
| 35.509934 | 80 | 0.731257 | [
"vector",
"transform"
] |
39b992f8f633061e56aaab2373c47b5d5153c823 | 6,429 | cpp | C++ | Sources/Elastos/LibCore/src/org/apache/http/impl/conn/IdleConnectionHandler.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/LibCore/src/org/apache/http/impl/conn/IdleConnectionHandler.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/LibCore/src/org/apache/http/impl/conn/IdleConnectionHandler.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "Elastos.CoreLibrary.Utility.Concurrent.h"
#include "org/apache/http/impl/conn/IdleConnectionHandler.h"
#include "elastos/core/CSystem.h"
#include "elastos/core/Math.h"
#include "elastos/utility/CHashMap.h"
#include "elastos/utility/logging/Logger.h"
using Elastos::Core::ISystem;
using Elastos::Core::CSystem;
using Elastos::Core::Math;
using Elastos::Utility::IHashMap;
using Elastos::Utility::CHashMap;
using Elastos::Utility::ISet;
using Elastos::Utility::IIterator;
using Elastos::Utility::Logging::Logger;
namespace Org {
namespace Apache {
namespace Http {
namespace Impl {
namespace Conn {
//==============================================================================
// IdleConnectionHandler::TimeValues
//==============================================================================
IdleConnectionHandler::TimeValues::TimeValues(
/* [in] */ Int64 now,
/* [in] */ Int64 validDuration,
/* [in] */ ITimeUnit* validUnit)
: mTimeAdded(0)
, mTimeExpires(0)
{
mTimeAdded = now;
if (validDuration > 0) {
Int64 millis;
validUnit->ToMillis(validDuration, &millis);
mTimeExpires = now + millis;
}
else {
mTimeExpires = Elastos::Core::Math::INT64_MAX_VALUE;
}
}
//==============================================================================
// IdleConnectionHandler
//==============================================================================
IdleConnectionHandler::IdleConnectionHandler()
{
AutoPtr<IHashMap> hm;
CHashMap::New((IHashMap**)&hm);
mConnectionToTimes = IMap::Probe(hm);
}
void IdleConnectionHandler::Add(
/* [in] */ IHttpConnection* connection,
/* [in] */ Int64 validDuration,
/* [in] */ ITimeUnit* unit)
{
AutoPtr<ISystem> system;
CSystem::AcquireSingleton((ISystem**)&system);
Int64 timeAdded;
system->GetCurrentTimeMillis(&timeAdded);
// if (log.isDebugEnabled()) {
// log.debug("Adding connection at: " + timeAdded);
// }
AutoPtr<TimeValues> timeValues = new TimeValues(timeAdded, validDuration, unit);
mConnectionToTimes->Put(connection, timeValues->Probe(EIID_IInterface));
}
Boolean IdleConnectionHandler::Remove(
/* [in] */ IHttpConnection* connection)
{
AutoPtr<IInterface> value;
mConnectionToTimes->Remove(connection, (IInterface**)&value);
if(value == NULL) {
Logger::D("IdleConnectionHandler", "Removing a connection that never existed!");
return TRUE;
}
else {
AutoPtr<TimeValues> times = (TimeValues*)(Object*)(IObject*)value.Get();
AutoPtr<ISystem> system;
CSystem::AcquireSingleton((ISystem**)&system);
Int64 current;
system->GetCurrentTimeMillis(¤t);
return current <= times->mTimeExpires;
}
}
void IdleConnectionHandler::RemoveAll()
{
mConnectionToTimes->Clear();
}
void IdleConnectionHandler::CloseIdleConnections(
/* [in] */ Int64 idleTime)
{
// the latest time for which connections will be closed
AutoPtr<ISystem> system;
CSystem::AcquireSingleton((ISystem**)&system);
Int64 current;
system->GetCurrentTimeMillis(¤t);
Int64 idleTimeout = current - idleTime;
// if (log.isDebugEnabled()) {
// log.debug("Checking for connections, idleTimeout: " + idleTimeout);
// }
AutoPtr<ISet> keySet;
mConnectionToTimes->GetKeySet((ISet**)&keySet);
AutoPtr<IIterator> it;
keySet->GetIterator((IIterator**)&it);
Boolean hasNext;
while (it->HasNext(&hasNext), hasNext) {
AutoPtr<IInterface> key;
it->GetNext((IInterface**)&key);
AutoPtr<IHttpConnection> conn = IHttpConnection::Probe(key);
AutoPtr<IInterface> value;
mConnectionToTimes->Get(conn, (IInterface**)&value);
AutoPtr<TimeValues> times = (TimeValues*)(Object*)(IObject*)value.Get();
Int64 connectionTime = times->mTimeAdded;
if (connectionTime <= idleTimeout) {
// if (log.isDebugEnabled()) {
// log.debug("Closing connection, connection time: " + connectionTime);
// }
it->Remove();
// try {
conn->Close();
// } catch (IOException ex) {
// log.debug("I/O error closing connection", ex);
// }
}
}
}
void IdleConnectionHandler::CloseExpiredConnections()
{
AutoPtr<ISystem> system;
CSystem::AcquireSingleton((ISystem**)&system);
Int64 now;
system->GetCurrentTimeMillis(&now);
// if (log.isDebugEnabled()) {
// log.debug("Checking for expired connections, now: " + now);
// }
AutoPtr<ISet> keySet;
mConnectionToTimes->GetKeySet((ISet**)&keySet);
AutoPtr<IIterator> it;
keySet->GetIterator((IIterator**)&it);
Boolean hasNext;
while (it->HasNext(&hasNext), hasNext) {
AutoPtr<IInterface> key;
it->GetNext((IInterface**)&key);
AutoPtr<IHttpConnection> conn = IHttpConnection::Probe(key);
AutoPtr<IInterface> value;
mConnectionToTimes->Get(conn, (IInterface**)&value);
AutoPtr<TimeValues> times = (TimeValues*)(Object*)(IObject*)value.Get();
if(times->mTimeExpires <= now) {
// if (log.isDebugEnabled()) {
// log.debug("Closing connection, expired @: " + times.timeExpires);
// }
it->Remove();
// try {
conn->Close();
// } catch (IOException ex) {
// log.debug("I/O error closing connection", ex);
// }
}
}
}
} // namespace Conn
} // namespace Impl
} // namespace Http
} // namespace Apache
} // namespace Org | 33.310881 | 88 | 0.595271 | [
"object"
] |
39c38f5eeee806fa2f68e1531e017abf2394ba7e | 9,979 | cpp | C++ | src/Tools/Popup.cpp | pgate1/QROQS | c4b09d00a2bcc751c7e8de11ca6a8601c390a95f | [
"MIT"
] | null | null | null | src/Tools/Popup.cpp | pgate1/QROQS | c4b09d00a2bcc751c7e8de11ca6a8601c390a95f | [
"MIT"
] | null | null | null | src/Tools/Popup.cpp | pgate1/QROQS | c4b09d00a2bcc751c7e8de11ca6a8601c390a95f | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
//
// Popup.cpp : implementation file
//
///////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <objbase.h>
#include <initguid.h>
#include "Popup.h"
#include "Draw.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
///////////////////////////////////////////////////////////////////////////////
CPopup::CPopup () : m_pControl (NULL), m_pCaller (NULL), m_pEvents (NULL),
m_hPrevParentCtrl (NULL), m_bDestroy (false)
{
}
///////////////////////////////////////////////////////////////////////////////
bool CPopup::Display (CWnd* pControl, CWnd* pCaller, CRect& rcCaller, IPopupCtrlEvent* pEvents, DWORD dwStyles)
{
if ( pControl == NULL )
{
delete this;
return false;
}
m_pControl = pControl;
m_pCaller = pCaller;
m_rcCaller = rcCaller;
m_pEvents = pEvents;
if ( m_pEvents != NULL && !m_pEvents->OnInit() )
{
delete this;
return false;
}
// Calculate the most appropriate position for the left-top corner of control
// By default, at left and bottom of the caller
CPoint pt (rcCaller.left, rcCaller.bottom);
CWindowRect rcCtrl (m_pControl);
if ( rcCtrl.Width() == 0 || rcCtrl.Height() == 0 )
{
return false;
}
int nOffset = 0;
if ( dwStyles & WS_DLGFRAME )
{
rcCtrl.InflateRect (4, 4);
nOffset = 1;
}
if ( dwStyles & WS_BORDER )
{
rcCtrl.right += 2;
rcCtrl.bottom += 2;
}
// Alignment at right if necessary
if ( pt.x + rcCtrl.Width() > ::GetSystemMetrics (SM_CXSCREEN) )
{
pt.x = rcCaller.right-rcCtrl.Width();
}
// Alignment at top if necessary
if ( pt.y + rcCtrl.Height() > ::GetSystemMetrics (SM_CYSCREEN) )
{
pt.y = rcCaller.top-rcCtrl.Height();
}
// Adjustments to keep control into screen
if ( pt.x + rcCtrl.Width() > ::GetSystemMetrics (SM_CXSCREEN) )
{
pt.x = ::GetSystemMetrics (SM_CXSCREEN)-rcCtrl.Width();
}
if ( pt.y + rcCtrl.Height() > ::GetSystemMetrics (SM_CYSCREEN) )
{
pt.y = ::GetSystemMetrics (SM_CYSCREEN)-rcCtrl.Height();
}
if ( pt.x < 0 ) pt.x = 0;
if ( pt.y < 0 ) pt.y = 0;
if ( !CMiniFrameWnd::Create (NULL, _T(""), WS_POPUP|dwStyles|(m_pCaller != NULL ? MFS_SYNCACTIVE : 0),
CRect (pt.x, pt.y, pt.x+rcCtrl.Width(), pt.y+rcCtrl.Height()),
m_pControl->GetParent()) )
{
return false;
}
m_hPrevParentCtrl = m_pControl->SetParent (this)->GetSafeHwnd();
m_pControl->SetWindowPos (NULL, nOffset, nOffset, 0, 0, SWP_NOZORDER|SWP_NOSIZE);
// Don't use SWP_SHOWWINDOW because OnShowWindow isn't call
m_pControl->ShowWindow (SW_SHOW);
EnableToolTips (TRUE);
ShowWindow (SW_SHOW);
if ( m_pEvents != NULL )
{
m_pEvents->OnShow();
}
return true;
}
// user defined message (different of any Win32/MFC message?)
#define WM_DELAYDESTROY (WM_USER+0x0100)
///////////////////////////////////////////////////////////////////////////////
void CPopup::EndPopup (bool bAbort, bool bSetFocus)
{
if ( m_pEvents != NULL )
{
m_pEvents->OnHide (bAbort);
}
ASSERT (m_pControl->m_hWnd != NULL);
m_pControl->ShowWindow (SW_HIDE);
ASSERT (m_hPrevParentCtrl != NULL);
::SetParent (m_pControl->m_hWnd, m_hPrevParentCtrl);
// Do a local copy of the pointer because DestroyWindow delete object
// and m_pCaller will not be valid after
CWnd* pCaller = m_pCaller;
if ( !m_bDestroy )
{
m_bDestroy = true;
PostMessage (WM_DELAYDESTROY);
}
if ( bSetFocus && pCaller != NULL )
{
pCaller->SetFocus();
}
}
///////////////////////////////////////////////////////////////////////////////
BOOL CPopup::PreTranslateMessage (MSG* pMsg)
{
bool bEnd = false, bAbort = false, bResult = false;
int nCode = doNothing;
switch ( pMsg->message )
{
case WM_KEYDOWN:
// Default action for <Escape> key
if ( pMsg->wParam == VK_ESCAPE )
{
bEnd = bAbort = bResult = true;
break;
}
if ( m_pEvents != NULL )
{
IPopupCtrlEvent* pEvents = m_pEvents;
// Search for the interface for the correct object (referenced by pMsg->hwnd)
if ( pMsg->hwnd != m_pControl->m_hWnd )
{
pEvents = m_pEvents->GetInterfaceOf (pMsg->hwnd);
}
if ( pEvents != NULL )
{
nCode = pEvents->OnKeyDown (pMsg->wParam, LOWORD(pMsg->lParam), HIWORD(pMsg->lParam));
}
}
break;
case WM_LBUTTONDOWN:
if ( m_pEvents != NULL )
{
IPopupCtrlEvent* pEvents = m_pEvents;
// Search for the interface for the correct object
if ( pMsg->hwnd != m_pControl->m_hWnd )
{
pEvents = m_pEvents->GetInterfaceOf (pMsg->hwnd);
}
if ( pEvents != NULL )
{
nCode = pEvents->OnLButtonDown (pMsg->wParam, CPoint ((short)LOWORD(pMsg->lParam), (short)HIWORD(pMsg->lParam)));
}
}
break;
case WM_LBUTTONUP:
if ( m_pEvents != NULL )
{
IPopupCtrlEvent* pEvents = m_pEvents;
// Search for the interface for the correct object
if ( pMsg->hwnd != m_pControl->m_hWnd )
{
pEvents = m_pEvents->GetInterfaceOf (pMsg->hwnd);
}
if ( pEvents != NULL )
{
nCode = pEvents->OnLButtonUp (pMsg->wParam, CPoint ((short)LOWORD(pMsg->lParam), (short)HIWORD(pMsg->lParam)));
}
}
break;
}
switch ( nCode )
{
case noSend:
bResult = true;
break;
case end:
bEnd = bResult = true;
break;
case abort:
bEnd = bAbort = bResult = true;
break;
}
if ( !bResult )
{
bResult = CMiniFrameWnd::PreTranslateMessage (pMsg) != 0;
}
if ( bEnd )
{
EndPopup (bAbort);
}
return bResult;
}
///////////////////////////////////////////////////////////////////////////////
void CPopup::PostNcDestroy ()
{
delete this;
}
///////////////////////////////////////////////////////////////////////////////
BEGIN_MESSAGE_MAP (CPopup, CMiniFrameWnd)
//{{AFX_MSG_MAP(CPopup)
ON_WM_ERASEBKGND()
ON_WM_ACTIVATE()
ON_WM_CANCELMODE()
ON_MESSAGE(WM_DELAYDESTROY, OnDelayDestroy)
ON_WM_NCPAINT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP ()
IMPLEMENT_DYNCREATE (CPopup, CMiniFrameWnd);
///////////////////////////////////////////////////////////////////////////////
BOOL CPopup::OnEraseBkgnd (CDC* pDC)
{
pDC->FillSolidRect (CClientRect (this), ::GetSysColor (COLOR_3DFACE));
return true;
}
///////////////////////////////////////////////////////////////////////////////
void CPopup::OnNcPaint ()
{
Default();
if ( (GetStyle()&WS_TABBORDER) == WS_TABBORDER )
{
CWindowDC cDC (this);
CWindowRect rc (this);
CPenDC pen (cDC, HLS_TRANSFORM (::GetSysColor (COLOR_3DFACE), 20, 0));
if ( m_rcCaller.bottom == rc.top )
{
cDC.MoveTo (1, 0);
cDC.LineTo (m_rcCaller.Width()-1, 0);
pen.Color (::GetSysColor (COLOR_3DSHADOW));
cDC.LineTo (rc.Width()-1, 0);
cDC.LineTo (rc.Width()-1, rc.Height()-1);
cDC.LineTo (0, rc.Height()-1);
cDC.LineTo (0, -1);
}
else
{
cDC.MoveTo (1, rc.Height()-1);
cDC.LineTo (m_rcCaller.Width()-1, rc.Height()-1);
pen.Color (::GetSysColor (COLOR_3DSHADOW));
cDC.LineTo (rc.Width()-1, rc.Height()-1);
cDC.LineTo (rc.Width()-1, 0);
cDC.LineTo (0, 0);
cDC.LineTo (0, rc.Height());
}
}
}
///////////////////////////////////////////////////////////////////////////////
void CPopup::OnActivate (UINT nState, CWnd* pWndOther, BOOL bMinimized)
{
CMiniFrameWnd::OnActivate (nState, pWndOther, bMinimized);
if ( nState == WA_INACTIVE && !m_bDestroy )
{
EndPopup (true, false);
}
}
///////////////////////////////////////////////////////////////////////////////
void CPopup::OnCancelMode ()
{
if ( !m_bDestroy )
{
EndPopup (true, false);
}
}
///////////////////////////////////////////////////////////////////////////////
LRESULT CPopup::OnDelayDestroy (WPARAM, LPARAM)
{
DestroyWindow();
return 0;
}
///////////////////////////////////////////////////////////////////////////////
int CPopup::OnToolHitTest (CPoint, TOOLINFO* pTI) const
{
UNUSED(pTI);
#ifdef _DEBUG
if ( m_pControl != NULL )
{
if ( pTI != NULL && pTI->cbSize >= 40/*sizeof(TOOLINFO)*/ )
{
// setup the TOOLINFO structure
pTI->hwnd = m_hWnd;
pTI->uId = (UINT)m_pControl->m_hWnd;
pTI->uFlags |= TTF_IDISHWND;
pTI->lpszText = _tcsdup (_T("Press <Esc> to hide me !"));
}
return m_pControl->GetDlgCtrlID();
}
#endif
return -1;
}
| 29.523669 | 134 | 0.46207 | [
"object"
] |
39c6b1602ea021cd45892dfc61e7e35c2704b061 | 6,524 | cpp | C++ | test/unit/src/Path2dTest.cpp | nselikoff/Cinder | 54590aabdc3d74b0b078d43590dfad89e50e9c94 | [
"BSD-2-Clause"
] | 12 | 2015-03-15T08:03:55.000Z | 2022-01-06T02:30:18.000Z | test/unit/src/Path2dTest.cpp | nselikoff/Cinder | 54590aabdc3d74b0b078d43590dfad89e50e9c94 | [
"BSD-2-Clause"
] | 8 | 2020-01-05T23:38:51.000Z | 2020-02-23T22:18:18.000Z | test/unit/src/Path2dTest.cpp | nselikoff/Cinder | 54590aabdc3d74b0b078d43590dfad89e50e9c94 | [
"BSD-2-Clause"
] | 3 | 2015-09-14T09:37:35.000Z | 2017-05-23T06:10:16.000Z | #include "cinder/app/App.h"
#include "cinder/Path2d.h"
#include "cinder/Rand.h"
#include "catch.hpp"
using namespace ci;
using namespace ci::app;
using namespace std;
bool subPathHelper( const Path2d &p, float start, float end )
{
float targetLength = ( end - start ) * p.calcLength();
Path2d sub = p.getSubPath( p.calcNormalizedTime( start, false ), p.calcNormalizedTime( end, false ) );
float subLength = sub.calcLength();
return abs( targetLength - subLength ) <= (0.01f * targetLength);
}
TEST_CASE("Path2d")
{
// getSubPath()
SECTION("getSubPath: Single Segment")
{
Path2d line;
line.moveTo( 50, 50 ); line.lineTo( 150, 150 );
REQUIRE( subPathHelper( line, 0.3f, 0.7f ) );
REQUIRE( subPathHelper( line, 0.0f, 1.0f ) );
Path2d quad;
quad.moveTo( 50, 50 ); quad.quadTo( 75, 123, 150, 147 );
REQUIRE( subPathHelper( quad, 0.3f, 0.7f ) );
REQUIRE( subPathHelper( quad, 0.0f, 1.0f ) );
Path2d cubic;
cubic.moveTo( 50, 50 ); cubic.curveTo( 75, 123, 150, 147, 200, 233 );
REQUIRE( subPathHelper( cubic, 0.3f, 0.7f ) );
REQUIRE( subPathHelper( cubic, 0.0f, 1.0f ) );
}
SECTION("getSubPath: Multi Segment")
{
Path2d p1;
p1.moveTo( 50, 50 ); p1.lineTo( 123, 345 );
REQUIRE( subPathHelper( p1, 0.3f, 0.7f ) );
REQUIRE( subPathHelper( p1, 0.2f, 1.0f ) );
REQUIRE( subPathHelper( p1, 0.0f, 0.7f ) );
Path2d p2;
p2.moveTo( 50, 50 ); p2.lineTo( 123, 345 ); p2.quadTo( 77, 88, 111, 121 );
REQUIRE( subPathHelper( p2, 0.3f, 0.7f ) );
REQUIRE( subPathHelper( p2, 0.2f, 1.0f ) );
REQUIRE( subPathHelper( p2, 0.0f, 0.7f ) );
Path2d p2b;
p2b.moveTo( 50, 50 ); p2b.lineTo( 123, 345 ); p2b.lineTo( 77, 88 ); p2b.close();
REQUIRE( subPathHelper( p2, 0.3f, 0.7f ) );
REQUIRE( subPathHelper( p2, 0.2f, 1.0f ) );
REQUIRE( subPathHelper( p2, 0.0f, 0.7f ) );
Path2d p3;
p3.moveTo( 50, 50 ); p3.lineTo( 123, 345 ); p3.curveTo( 77, 88, 111, 121, 99, 144 );
REQUIRE( subPathHelper( p3, 0.3f, 0.7f ) );
REQUIRE( subPathHelper( p3, 0.2f, 1.0f ) );
REQUIRE( subPathHelper( p3, 0.0f, 0.7f ) );
Rand r1;
for( int p = 0; p < 50; ++p ) {
Path2d p4;
p4.moveTo( 123, 345 );
int count = r1.nextInt( 20 );
for( int i = 0; i < count; ++i ) {
switch( r1.nextInt() % 3 ) {
case 0:
p4.lineTo( r1.nextFloat( 500 ), r1.nextFloat( 500 ) );
break;
case 1:
p4.quadTo( r1.nextFloat( 500 ), r1.nextFloat( 500 ), r1.nextFloat( 500 ), r1.nextFloat( 500 ) );
break;
case 2:
p4.curveTo( r1.nextFloat( 500 ), r1.nextFloat( 500 ), r1.nextFloat( 500 ), r1.nextFloat( 500 ),
r1.nextFloat( 500 ), r1.nextFloat( 500 ) );
break;
}
}
if( r1.nextBool() )
p4.close();
console() << p4 << std::endl;
REQUIRE( subPathHelper( p4, 0.3f, 0.7f ) );
REQUIRE( subPathHelper( p4, 0.2f, 1.0f ) );
REQUIRE( subPathHelper( p4, 0.0f, 0.7f ) );
}
}
// Distance
SECTION("Distance: Vertical line")
{
vector<vec2> input({
vec2( 0, 100 ),
vec2( 0, 200 )
});
Path2d p;
p.moveTo( input[0] );
p.lineTo( input[1] );
REQUIRE( p.calcDistance( vec2( 50, 150 ) ) == Approx( 50 ) ); // center, right 50
REQUIRE( glm::distance( p.calcClosestPoint( vec2( 50, 150 ) ), vec2( 0, 150 ) ) == Approx( 0 ) ); // center, right 50
REQUIRE( p.calcDistance( vec2( 0, 150 ) ) == Approx( 0 ) ); // along line
REQUIRE( glm::distance( p.calcClosestPoint( vec2( 0, 150 ) ), vec2( 0, 150 ) ) == Approx( 0 ) ); // along line
REQUIRE( p.calcDistance( vec2( 0, 250 ) ) == Approx( 50 ) ); // directly below line 50
REQUIRE( glm::distance( p.calcClosestPoint( vec2( 0, 250 ) ), vec2( 0, 200 ) ) == Approx( 0 ) ); // directly below line 50
REQUIRE( p.calcDistance( vec2( 0, 100 ) ) == Approx( 0 ) ); // co-sited with top
REQUIRE( glm::distance( p.calcClosestPoint( vec2( 0, 100 ) ), vec2( 0, 100 ) ) == Approx( 0 ) ); // co-sited with top*/
}
SECTION("Distance: Triangle")
{
vector<vec2> input({
vec2( 0, 100 ),
vec2( 0, 200 ),
vec2( 50, 150 )
});
Path2d p;
p.moveTo( input[0] );
p.lineTo( input[1] );
p.lineTo( input[2] );
REQUIRE( p.calcDistance( vec2( 50, 150 ) ) == Approx( 0 ) ); // co-sited with middle point
REQUIRE( p.calcDistance( vec2( 50, 150 ), 0 ) == Approx( 50 ) ); // co-sited with righmost point, but test only the first segment
REQUIRE( p.calcDistance( vec2( -1, 150 ) ) == Approx( 1 ) ); // exterior, directly left 1
REQUIRE( p.calcSignedDistance( vec2( -1, 150 ) ) == Approx( 1 ) ); // interior, one unit right of the left vertical line
REQUIRE( p.calcDistance( vec2( 1, 150 ) ) == Approx( 1 ) ); // interior, one unit right of the left vertical line
REQUIRE( p.calcSignedDistance( vec2( 1, 150 ) ) == Approx( -1 ) ); // interior, one unit right of the left vertical line
}
SECTION("Distance: Quadratic")
{
Path2d p; // shape matches Path2d guide from the docs
p.moveTo( vec2( 300.0f, 270.0f ) );
p.quadTo( vec2( 300.0f, 70.0f ), vec2( 500.0f, 70.0f ) );
REQUIRE( p.calcDistance( vec2( 300.0f, 270.0f ) ) == Approx( 0 ) ); // co-sited with first point
REQUIRE( glm::distance( p.calcClosestPoint( vec2( 300.0f, 270.0f ) ), vec2( 300.0f, 270.0f ) ) == Approx( 0 ) ); // co-sited with first point
REQUIRE( p.calcDistance( vec2( 300.0f, 70.0f ) ) == Approx( 70.71 ) ); // middle control point; closest is ( 350, 120 ); sqrt(50*50 + 50*50)
REQUIRE( glm::distance( p.calcClosestPoint( vec2( 300.0f, 70.0f ) ), vec2( 350.0f, 120.0f ) ) == Approx( 0 ) ); // middle control point
}
SECTION("Distance: Cubic")
{
Path2d p; // shape matches Path2d guide from the docs
p.moveTo( vec2( 300.0f, 270.0f ) );
p.curveTo( vec2( 400.0f, 270.0f ), vec2( 400.0f, 70.0f ), vec2( 500.0f, 70.0f ) );
REQUIRE( p.calcDistance( vec2( 300.0f, 270.0f ) ) == Approx( 0 ) ); // co-sited with first point
REQUIRE( glm::distance( p.calcClosestPoint( vec2( 300.0f, 270.0f ) ), vec2( 300.0f, 270.0f ) ) == Approx( 0 ) ); // co-sited with first point
REQUIRE( p.calcDistance( vec2( 400.0f, 270.0f ) ) == Approx( 51.2251847f ) ); // second control point; closest is ( 360.310f, 237.616f );
REQUIRE( glm::distance( p.calcClosestPoint( vec2( 400.0f, 270.0f ) ), vec2( 360.310f, 237.616f ) ) == Approx( 0 ).epsilon( 0.001 ) ); // second control point
}
SECTION("calcNormalizedTime")
{
// test pathological case of 0-length
Path2d p;
p.moveTo( 50, 50 );
p.lineTo( 50, 50 );
float t = p.calcNormalizedTime( 0.5f );
REQUIRE( glm::distance( p.getPosition( t ), vec2( 50, 50 ) ) == Approx( 0 ).epsilon( 0.001 ) );
}
}
| 37.930233 | 159 | 0.607143 | [
"shape",
"vector"
] |
39c92691fea70a272ecc268e8c477dca7c8fb065 | 1,994 | cc | C++ | airec/src/model/ListDashboardParametersResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | null | null | null | airec/src/model/ListDashboardParametersResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | null | null | null | airec/src/model/ListDashboardParametersResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 1 | 2020-11-27T09:13:12.000Z | 2020-11-27T09:13:12.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/airec/model/ListDashboardParametersResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Airec;
using namespace AlibabaCloud::Airec::Model;
ListDashboardParametersResult::ListDashboardParametersResult() :
ServiceResult()
{}
ListDashboardParametersResult::ListDashboardParametersResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ListDashboardParametersResult::~ListDashboardParametersResult()
{}
void ListDashboardParametersResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto resultNode = value["Result"];
auto allTraceId = resultNode["TraceId"]["TraceId"];
for (auto value : allTraceId)
result_.traceId.push_back(value.asString());
auto allSceneId = resultNode["SceneId"]["SceneId"];
for (auto value : allSceneId)
result_.sceneId.push_back(value.asString());
if(!value["Code"].isNull())
code_ = value["Code"].asString();
if(!value["Message"].isNull())
message_ = value["Message"].asString();
}
std::string ListDashboardParametersResult::getMessage()const
{
return message_;
}
std::string ListDashboardParametersResult::getCode()const
{
return code_;
}
ListDashboardParametersResult::Result ListDashboardParametersResult::getResult()const
{
return result_;
}
| 28.084507 | 90 | 0.755266 | [
"model"
] |
39d09de82ab05966421bde1dabde8a77234fee23 | 1,590 | cpp | C++ | src/Tracker/ShortPathCalculator.cpp | xzou999/Multitarget-tracker | 94b22341d009c9585d08fcb64c25859283f86e7d | [
"Apache-2.0"
] | 1,801 | 2015-01-19T16:28:03.000Z | 2022-03-31T12:28:56.000Z | src/Tracker/ShortPathCalculator.cpp | xzou999/Multitarget-tracker | 94b22341d009c9585d08fcb64c25859283f86e7d | [
"Apache-2.0"
] | 168 | 2016-03-02T06:23:20.000Z | 2022-03-25T12:29:37.000Z | src/Tracker/ShortPathCalculator.cpp | xzou999/Multitarget-tracker | 94b22341d009c9585d08fcb64c25859283f86e7d | [
"Apache-2.0"
] | 608 | 2015-01-19T16:27:51.000Z | 2022-03-30T02:07:56.000Z | #include "ShortPathCalculator.h"
#include <GTL/GTL.h>
#include "mygraph.h"
#include "mwbmatching.h"
#include "tokenise.h"
///
/// \brief SPBipart::Solve
/// \param costMatrix
/// \param N
/// \param M
/// \param assignment
/// \param maxCost
///
void SPBipart::Solve(const distMatrix_t& costMatrix, size_t N, size_t M, assignments_t& assignment, track_t maxCost)
{
MyGraph G;
G.make_directed();
std::vector<GTL::node> nodes(N + M);
for (size_t i = 0; i < nodes.size(); ++i)
{
nodes[i] = G.new_node();
}
GTL::edge_map<int> weights(G, 100);
for (size_t i = 0; i < N; i++)
{
bool hasZeroEdge = false;
for (size_t j = 0; j < M; j++)
{
track_t currCost = costMatrix[i + j * N];
GTL::edge e = G.new_edge(nodes[i], nodes[N + j]);
if (currCost < m_settings.m_distThres)
{
int weight = static_cast<int>(maxCost - currCost + 1);
G.set_edge_weight(e, weight);
weights[e] = weight;
}
else
{
if (!hasZeroEdge)
{
G.set_edge_weight(e, 0);
weights[e] = 0;
}
hasZeroEdge = true;
}
}
}
GTL::edges_t L = MAX_WEIGHT_BIPARTITE_MATCHING(G, weights);
for (GTL::edges_t::iterator it = L.begin(); it != L.end(); ++it)
{
GTL::node a = it->source();
GTL::node b = it->target();
assignment[b.id()] = static_cast<assignments_t::value_type>(a.id() - N);
}
}
| 24.461538 | 116 | 0.506289 | [
"vector"
] |
39df1d5b7f0553729f751f9db161e9d3db178c24 | 160 | cpp | C++ | obi-problems/problem008/main.cpp | Davi-Argemiro/Algorithms-and-Data-Structures | 4cbf083fbe00da793c1147c4b9e3493d96ac50a1 | [
"MIT"
] | 1 | 2022-03-01T15:47:08.000Z | 2022-03-01T15:47:08.000Z | obi-problems/problem008/main.cpp | Davi-Argemiro/Algorithms-and-Data-Structures | 4cbf083fbe00da793c1147c4b9e3493d96ac50a1 | [
"MIT"
] | 1 | 2022-03-21T20:01:08.000Z | 2022-03-21T20:01:08.000Z | obi-problems/problem008/main.cpp | Davi-Argemiro/Algorithms-and-Data-Structures | 4cbf083fbe00da793c1147c4b9e3493d96ac50a1 | [
"MIT"
] | 1 | 2022-03-21T17:53:34.000Z | 2022-03-21T17:53:34.000Z | #include <iostream>
#include <vector>
using namespace std;
int main() {
int n, tot;
cin >> n;
tot = (n+2)*(n+1)/2;
cout << tot << endl;
return 0;
} | 8.888889 | 21 | 0.55625 | [
"vector"
] |
39e96b419fcc1047a1344a66938981252c1e627b | 4,063 | cxx | C++ | src/main/algorithms/NonZeroCondition.cxx | cc4s/cc4s | bff205f8fc98f29d4b9ff8f8b6faffbda50a8555 | [
"Apache-2.0"
] | null | null | null | src/main/algorithms/NonZeroCondition.cxx | cc4s/cc4s | bff205f8fc98f29d4b9ff8f8b6faffbda50a8555 | [
"Apache-2.0"
] | null | null | null | src/main/algorithms/NonZeroCondition.cxx | cc4s/cc4s | bff205f8fc98f29d4b9ff8f8b6faffbda50a8555 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2021 cc4s.org
*
* 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 <algorithms/NonZeroCondition.hpp>
#include <tcc/Tcc.hpp>
#include <Cc4s.hpp>
#include <Parser.hpp>
#include <Scanner.hpp>
#include <Real.hpp>
#include <Complex.hpp>
#include <MathFunctions.hpp>
#include <vector>
using namespace cc4s;
ALGORITHM_REGISTRAR_DEFINITION(NonZeroCondition)
/**
* \brief Extracts a Delta tensor from the given tensor
* representing a given non-zero condition. The
* Delta has indices according to the properties used
* by the given non-zero condition. Its entries are one
* for those combinations where the non-zero condition of
* the given tensor is met and zero otherwise.
* E.g the non-zero condition "spin" of a
* spin-conserving one-body Hamiltonian with two state indices is a
* 2x2 diagonal matrix, indicating that the spin component of the
* Hamiltonian's indices must match.
*/
Ptr<MapNode> NonZeroCondition::run(const Ptr<MapNode> &arguments) {
// multiplex calls to template methods
Ptr<MapNode> result;
if (Cc4s::dryRun) {
using TE = DefaultDryTensorEngine;
(
result = run<Real<>,TE>(arguments)
) || (
result = run<Complex<>,TE>(arguments)
);
} else {
using TE = DefaultTensorEngine;
(
result = run<Real<>,TE>(arguments)
) || (
result = run<Complex<>,TE>(arguments)
);
}
ASSERT_LOCATION(
result, "expecting operator to be a tensor", arguments->sourceLocation
);
return result;
}
template <typename F, typename TE>
Ptr<MapNode> NonZeroCondition::run(
const Ptr<MapNode> &arguments
) {
typedef TensorExpression<F,TE> T;
auto tensorExpression(arguments->getPtr<T>("operator"));
if (!tensorExpression) return nullptr;
auto tensor(tensorExpression->inspect());
auto conditionName(arguments->getValue<std::string>("conditionName"));
for (auto condition: tensor->nonZeroConditions->all) {
if (condition->name == conditionName) {
// find dimensions of Delta tensor
std::vector<Natural<>> conditionLens;
std::vector<std::string> conditionDimensions;
for (auto dimProperty: condition->dimensionPropertyReferences) {
conditionLens.push_back(dimProperty.property->indicesOfProperty.size());
conditionDimensions.push_back(dimProperty.property->name);
}
// create Delta tensor for non-zero condition
auto Delta(
Tcc<TE>::template tensor<F>(
conditionLens, tensor->getName() + "." + conditionName
)
);
// enter one at the coordinates found in the non-zero tuples list
Natural<> indicesCount(
Cc4s::world->getRank() == 0 ? condition->tuples.size() : 0
);
std::vector<Natural<>> indices(indicesCount);
std::vector<F> values(indicesCount);
for (Natural<> t(0); t < indicesCount; ++t) {
Natural<> index(0);
for (Natural<> d(conditionLens.size()-1); d > 0; --d) {
index += condition->tuples[t][d];
index *= conditionLens[d-1];
}
index += condition->tuples[t][0];
indices[t] = index;
values[t] = F(1);
}
Delta->write(indicesCount, indices.data(), values.data());
Delta->getUnit() = 1.0;
// generate result
auto result(New<MapNode>(SOURCE_LOCATION));
result->setPtr("nonZeroCondition", Delta);
return result;
}
}
THROW_LOCATION(
"Tensor "
+ tensor->getName()
+ " does not have a non-zero condition named "
+ conditionName,
arguments->sourceLocation
);
}
| 31.742188 | 80 | 0.668472 | [
"vector"
] |
39f4cfd364a3c8f46ec434f4d0a6c5ebe256d699 | 2,998 | cpp | C++ | HAL/Camera/Drivers/HDMI/HDMIDriver.cpp | vhanded/HAL | 56819df45a1d3edf118282b644449c9d1e395286 | [
"Apache-2.0"
] | 34 | 2015-07-19T06:34:09.000Z | 2022-03-15T13:34:38.000Z | HAL/Camera/Drivers/HDMI/HDMIDriver.cpp | vhanded/HAL | 56819df45a1d3edf118282b644449c9d1e395286 | [
"Apache-2.0"
] | 43 | 2015-02-08T17:06:28.000Z | 2020-06-09T15:22:16.000Z | HAL/Camera/Drivers/HDMI/HDMIDriver.cpp | vhanded/HAL | 56819df45a1d3edf118282b644449c9d1e395286 | [
"Apache-2.0"
] | 36 | 2015-04-18T15:41:49.000Z | 2021-05-28T15:55:28.000Z |
#include "HDMIDriver.h"
#include "opencv/cv.h" // for Mat structure
///////////////////////////////////////////////////////////////////////////////
HDMIDriver::HDMIDriver()
{
}
///////////////////////////////////////////////////////////////////////////////
HDMIDriver::~HDMIDriver()
{
}
///////////////////////////////////////////////////////////////////////////////
bool HDMIDriver::Capture( std::vector<rpg::ImageWrapper>& vImages )
{
// if there are any matrices, delete them
vImages.clear();
unsigned char *buffer, *controlBuffer;
int length, controlLength;
// while there are no frames, block the calls
while(m_pDelegate->GetFrame(buffer, length,controlBuffer,controlLength) == false ){ }
// allocate images if necessary
if( vImages.size() != m_nNumImages ){
vImages.resize( m_nNumImages );
}
//unsigned int timestamp;
//memcpy( ×tamp, controlBuffer, 4 );
//printf("Timestamp: %d\n",timestamp);
//m_pPropertyMap->SetProperty("Timestamp0", timestamp);
//memcpy( ×tamp, controlBuffer+8, 8 );
//m_pPropertyMap->SetProperty("Timestamp1", timestamp);
// now copy the images from the delegate
for ( size_t ii = 0; ii < m_nNumImages; ii++) {
vImages[ii].Image = cv::Mat(m_nImageHeight,m_nImageWidth, CV_8UC1, buffer);
//advance the pointer forward
buffer += m_nImageHeight*m_nImageWidth;
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
bool HDMIDriver::Init()
{
assert(m_pPropertyMap);
m_pPropertyMap->PrintPropertyMap();
m_nNumImages = m_pPropertyMap->GetProperty<int>( "NumImages", 1 );
m_nImageWidth = m_pPropertyMap->GetProperty<int>( "ImageWidth", 640 );
m_nImageHeight = m_pPropertyMap->GetProperty<int>( "ImageHeight", 480 );
int bufferCount = m_pPropertyMap->GetProperty<int>("BufferCount",5);
m_pIterator = CreateDeckLinkIteratorInstance();
HRESULT result;
// Connect to the first DeckLink instance
result = m_pIterator->Next( &m_pDeckLink );
if (result != S_OK)
{
fprintf(stderr, "No DeckLink PCI cards found.\n");
return false;
}
if (m_pDeckLink->QueryInterface(IID_IDeckLinkInput, (void**)&m_pDeckLinkInput) != S_OK) {
return false;
}
BMDVideoInputFlags inputFlags = 0;
BMDDisplayMode selectedDisplayMode = bmdModeHD720p60;
BMDPixelFormat pixelFormat = bmdFormat8BitYUV;
// set up the callback delegate
m_pDelegate = new CaptureDelegate(bufferCount,m_nNumImages,m_nImageWidth,m_nImageHeight);
m_pDeckLinkInput->SetCallback( m_pDelegate );
result = m_pDeckLinkInput->EnableVideoInput(selectedDisplayMode, pixelFormat, inputFlags);
if(result != S_OK)
{
fprintf(stderr, "Failed to enable video input. Is another application using the card?\n");
return false;
}
// start stream
result = m_pDeckLinkInput->StartStreams();
if(result != S_OK) {
return false;
}
return true;
}
| 28.552381 | 94 | 0.613742 | [
"vector"
] |
39f60fc9af566f9963125ff6de0cb4f66aa55b2f | 713 | hpp | C++ | src/scene_object.hpp | Ybalrid/gl_framework | 4cf57b63306e0d95040ee7d7b5c710be0efb59de | [
"MIT",
"Zlib",
"BSD-3-Clause"
] | 3 | 2019-09-16T01:42:10.000Z | 2021-11-28T02:58:42.000Z | src/scene_object.hpp | Ybalrid/gl_framework | 4cf57b63306e0d95040ee7d7b5c710be0efb59de | [
"MIT",
"Zlib",
"BSD-3-Clause"
] | null | null | null | src/scene_object.hpp | Ybalrid/gl_framework | 4cf57b63306e0d95040ee7d7b5c710be0efb59de | [
"MIT",
"Zlib",
"BSD-3-Clause"
] | 2 | 2020-01-28T23:33:00.000Z | 2021-11-08T06:14:41.000Z | #pragma once
#include "renderable.hpp"
#include "camera.hpp"
#include "transform.hpp"
#include "mesh.hpp"
///Object that is part of the scene
class scene_object
{
///The mesh
mesh mesh_ {};
public:
///The scene object
scene_object(mesh m) : mesh_ { m } {}
///Get the oriented bounding box of the scene
std::vector<bounding_box> get_obb(const glm::mat4 model)
{
std::vector<bounding_box> output(mesh_.get_submeshes().size());
for(size_t i = 0; i < output.size(); ++i)
output[i] = (renderable_manager::get_from_handle(mesh_.get_submeshes()[i]).get_world_obb(model));
return output;
}
///Get the mesh of the scene object
mesh const& get_mesh() const { return mesh_; }
};
| 23.766667 | 103 | 0.674614 | [
"mesh",
"object",
"vector",
"model",
"transform"
] |
2600883db371385c0e8f4ac4baf6398fbf5c59e7 | 1,641 | cpp | C++ | action/action_plugins/src/follow_route_action.cpp | cvasfi/scenario_runner.iv.universe | b8a6388faf502478fdc217ad7a30d8cab2dcae39 | [
"Apache-2.0"
] | 2 | 2020-09-25T08:53:18.000Z | 2020-10-23T09:42:49.000Z | action/action_plugins/src/follow_route_action.cpp | cvasfi/scenario_runner.iv.universe | b8a6388faf502478fdc217ad7a30d8cab2dcae39 | [
"Apache-2.0"
] | 36 | 2020-10-23T07:40:37.000Z | 2021-02-19T09:24:46.000Z | action/action_plugins/src/follow_route_action.cpp | cvasfi/scenario_runner.iv.universe | b8a6388faf502478fdc217ad7a30d8cab2dcae39 | [
"Apache-2.0"
] | 15 | 2020-09-30T16:37:57.000Z | 2021-12-03T07:06:17.000Z | #include "action_plugins/follow_route_action.h"
#include "scenario_utility/scenario_utility.h"
#include <ros/ros.h>
namespace action_plugins
{
FollowRouteAction::FollowRouteAction()
: EntityActionBase {"FollowRoute"}
{}
void FollowRouteAction::configure(
const YAML::Node& node,
const std::vector<std::string> actors,
const std::shared_ptr<ScenarioAPI>& api_ptr)
try
{
node_ = node;
actors_ = actors;
api_ptr_ = api_ptr;
if (actors_.empty())
{
SCENARIO_WARNING_ABOUT_NO_ACTORS_SPECIFIED();
}
call_with_essential(node_, "Params", [&](const auto& node) mutable
{
call_with_essential(node, "GoalPose", [&](const auto& node) mutable
{
const auto pose_stamped { read_essential<geometry_msgs::PoseStamped>(node, "Pose") };
if (pose_stamped.header.frame_id != "/map")
{
goal_ = api_ptr_->getRelativePose(pose_stamped.header.frame_id, pose_stamped.pose);
}
else
{
goal_ = pose_stamped.pose;
}
shift_ = read_optional<std::string>(node, "Shift", "Center");
});
});
}
catch (...)
{
SCENARIO_RETHROW_ERROR_FROM_ACTION_CONFIGURATION();
}
void FollowRouteAction::run(
const std::shared_ptr<scenario_intersection::IntersectionManager>&)
{
for (const auto& each : actors_)
{
if (not api_ptr_->sendGoalPoint(each, goal_, true, shift_))
{
SCENARIO_ERROR_THROW(CATEGORY(),
type_ << "Action failed to send goal-pose to " << each << ".");
}
}
}
} // namespace action_plugins
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS(action_plugins::FollowRouteAction, scenario_actions::EntityActionBase)
| 24.132353 | 93 | 0.691042 | [
"vector"
] |
2609f1e24c275f4f6f106b85571388a3c871863f | 11,008 | cpp | C++ | ComponentMesh.cpp | rogerta97/TryHard_Engine | 6dc6725264a2a1d86530aa3d8f00f260f8509883 | [
"MIT"
] | null | null | null | ComponentMesh.cpp | rogerta97/TryHard_Engine | 6dc6725264a2a1d86530aa3d8f00f260f8509883 | [
"MIT"
] | null | null | null | ComponentMesh.cpp | rogerta97/TryHard_Engine | 6dc6725264a2a1d86530aa3d8f00f260f8509883 | [
"MIT"
] | null | null | null | #include "ComponentMesh.h"
#include "ComponentMaterial.h"
#include "ComponentRectTransform.h"
#include "ComponentCanvas.h"
#include "ComponentTransform.h"
#include "Application.h"
#include "GameObject.h"
#include "MeshImporter.h"
#include "imgui.h"
#include "OpenGL.h"
#include "mmgr\mmgr.h"
ComponentMesh::ComponentMesh(GameObject* parent)
{
SetGameObject(parent);
component_type = CMP_MESH;
material = nullptr;
mesh = nullptr;
wireframe = false;
draw_mesh = true;
draw_normals = false;
container_fbx = "";
active = true;
}
ComponentMesh::~ComponentMesh()
{
}
bool ComponentMesh::Update()
{
if (draw_mesh == false || mesh == nullptr)
return false;
ComponentTransform* trans = nullptr;
if (gameobject->GetIsUI())
{
ComponentRectTransform* rect_trans = (ComponentRectTransform*)gameobject->GetComponent(CMP_RECTTRANSFORM);
trans = rect_trans->GetTransform();
}
else
trans = (ComponentTransform*)gameobject->GetComponent(CMP_TRANSFORM);
if (trans->HasTransformed()) {
UpdateBoundingBox();
trans->SetHasTransformed(false);
}
return true;
}
bool ComponentMesh::CleanUp()
{
if (mesh != nullptr)
{
mesh->reference_counting--;
mesh->CleanMeshData();
mesh = nullptr;
}
return false;
}
void ComponentMesh::SetMesh(Mesh * new_mesh)
{
mesh = new_mesh;
}
void ComponentMesh::DrawNormals()
{
if (mesh->num_normals == 0)
return;
glBegin(GL_LINES);
glColor3f(1.0f, 0.0f, 0.0f);
ComponentTransform* trans = (ComponentTransform*)gameobject->GetComponent(CMP_TRANSFORM);
for (int i = 0; i < mesh->num_normals; i++)
{
LineSegment curr_line;
curr_line.a = mesh->vertices[i];
curr_line.b = mesh->vertices[i] + (mesh->normal_cords[i]*0.5f);
curr_line.Transform(trans->GetGlobalViewMatrix());
glVertex3f(curr_line.a.x, curr_line.a.y, curr_line.a.z);
glVertex3f(curr_line.b.x, curr_line.b.y, curr_line.b.z);
}
glEnd();
}
void ComponentMesh::DrawMesh()
{
if (frustum_col_type == OUTSIDE_FRUSTUM || mesh == nullptr)
return;
ComponentMaterial* material = (ComponentMaterial*)gameobject->GetComponent(CMP_MATERIAL);
ComponentTransform* trans = nullptr;
if (gameobject->GetIsUI() == false)
trans = (ComponentTransform*)gameobject->GetComponent(CMP_TRANSFORM);
else
{
ComponentRectTransform* rtransform = (ComponentRectTransform*)gameobject->GetComponent(CMP_RECTTRANSFORM);
trans = rtransform->GetTransform();
}
glEnableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, mesh->vertices_id);
glVertexPointer(3, GL_FLOAT, 0, NULL);
float4x4 view_mat = float4x4::identity;
if (trans)
{
GLfloat matrix[16];
glGetFloatv(GL_MODELVIEW_MATRIX, matrix);
view_mat.Set((float*)matrix);
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf((GLfloat*)((trans->GetGlobalViewMatrix()).Transposed() * view_mat).v);
}
bool valid_mat = false;
if (material && material->GetMaterial())
{
valid_mat = true;
if (material->GetMaterial()->GetDiffuseTexture() != nullptr)
{
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, mesh->uvs_id);
material->GetMaterial()->GetDiffuseTexture()->Bind();
glTexCoordPointer(3, GL_FLOAT, 0, NULL);
if (mesh->num_normals != 0)
{
glEnableClientState(GL_NORMAL_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, mesh->normals_id);
glNormalPointer(GL_FLOAT, 0, NULL);
}
}
else
{
glDisable(GL_TEXTURE_2D);
Color color = material->GetMaterial()->color;
glColor3f(color.r, color.g, color.b);
}
}
else if(!valid_mat)
{
glDisable(GL_TEXTURE_2D);
glColor3f(0.5f, 0.5f, 1.0f);
}
if (wireframe)
{
App->renderer3D->UseDebugRenderSettings();
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->indices_id);
glDrawElements(GL_TRIANGLES, mesh->num_indices, GL_UNSIGNED_INT, NULL);
if (valid_mat)
material->GetMaterial()->GetDiffuseTexture()->UnBind();
if (trans)
{
trans->DrawAxis();
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf((GLfloat*)view_mat.v);
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
void ComponentMesh::Draw(bool is_editor)
{
if (wireframe == false)
{
App->renderer3D->UseCurrentRenderSettings();
DrawMesh();
}
//if the mesh is selected we draw it again in wireframe mode
if (gameobject->selected && App->renderer3D->render_settings.wireframe_selected == true && is_editor == true)
{
App->renderer3D->UseDebugRenderSettings();
glLineWidth(3.0f);
DrawMesh();
App->renderer3D->UseCurrentRenderSettings();
}
if (draw_normals)
DrawNormals();
if (draw_bounding_box)
DrawBoundingBox();
}
void ComponentMesh::SetDefaultSettings()
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
void ComponentMesh::PrintRenderSettings()
{
ImGui::Spacing();
ImGui::Text("Vertices:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "%d", mesh->num_vertices);
ImGui::Text("Index:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "%d", mesh->num_indices);
ImGui::Text("TexCoords:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "%d", mesh->num_uvs*2);
ImGui::Text("Normals: "); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "%d", mesh->num_normals);
ImGui::Spacing();
ImGui::Separator();
ImGui::Spacing();
ImGui::Checkbox("Wireframe", &wireframe); ImGui::SameLine(); ImGui::Checkbox("Draw Normals", &draw_normals);
}
void ComponentMesh::AssignMaterial(ComponentMaterial * new_mat)
{
material = new_mat;
}
Mesh * ComponentMesh::GetMesh() const
{
return mesh;
}
bool ComponentMesh::CreateEnclosedMeshAABB()
{
bounding_box.SetNegativeInfinity();
bounding_box = bounding_box.MinimalEnclosingAABB(GetMesh()->vertices, GetMesh()->num_vertices);
if(gameobject)
gameobject->bounding_box = &bounding_box;
return true;
}
void ComponentMesh::DrawBoundingBox()
{
//Draw The AABB
if (gameobject->selected && draw_bounding_box)
{
LineSegment curr_line;
glBegin(GL_LINES);
App->renderer3D->UseDebugRenderSettings();
glColor3f(1.0f, 0.0f, 0.0f);
for (int i = 0; i < 12; i++)
{
curr_line = bounding_box.Edge(i);
glVertex3f(curr_line.a.x, curr_line.a.y, curr_line.a.z);
glVertex3f(curr_line.b.x, curr_line.b.y, curr_line.b.z);
}
glEnd();
}
}
void ComponentMesh::UpdateBoundingBox(ComponentTransform* force_trans)
{
ComponentTransform* trans = nullptr;
if (force_trans)
trans = force_trans;
else
trans = (ComponentTransform*)gameobject->GetComponent(CMP_TRANSFORM);
if (trans && mesh)
{
bounding_box.SetNegativeInfinity();
bounding_box = bounding_box.MinimalEnclosingAABB(mesh->vertices, mesh->num_vertices);
bounding_box.TransformAsAABB(trans->GetGlobalViewMatrix());
}
}
void ComponentMesh::SetBBColor(float r, float g, float b)
{
glColor3f(r,g,b);
}
void ComponentMesh::SetWireframe(bool newValue)
{
wireframe = newValue;
}
bool ComponentMesh::GetClosestIntersectionPoint(LineSegment line, float3 &closest_point, float & distance)
{
ComponentTransform* trans = (ComponentTransform*)gameobject->GetComponent(CMP_TRANSFORM);
Triangle tri;
float current_distance;
float closest_distance = 10000; //Hmm maybe there is a better way to do this
float3 hit_point;
bool ret = false;
if (!mesh)
return false;
if (!mesh->vertices)
return false;
int num_tris = mesh->num_indices / 3;
float4x4 gm = trans->GetGlobalViewMatrix();
line.Transform(gm.Inverted());
for (int i = 0; i < mesh->num_indices; i+=3)
{
float3 vertex_a = mesh->vertices[mesh->indices[i]];
float3 vertex_b = mesh->vertices[mesh->indices[i + 1]];
float3 vertex_c = mesh->vertices[mesh->indices[i + 2]];
tri.a = vertex_a;
tri.b = vertex_b;
tri.c = vertex_c;
bool hit = line.Intersects(tri, ¤t_distance, &hit_point);
if (hit)
{
//CONSOLE_LOG("hitpoint: x:%f, y:%f, z:%f", hit_point.x, hit_point.y, hit_point.z);
if (current_distance < closest_distance)
{
closest_point = hit_point;
closest_distance = current_distance;
ret = true;
}
}
}
closest_point += gm.TranslatePart();
distance = closest_distance;
//if (ret)
// CONSOLE_LOG("x:%f, y:%f, z:%f distance:%f", closest_point.x, closest_point.y, closest_point.z, closest_distance);
return ret;
}
ComponentMaterial * ComponentMesh::GetMaterial() const
{
return material;
}
void ComponentMesh::SetMaterial(ComponentMaterial * mat)
{
material = mat;
}
void ComponentMesh::DeleteMaterial()
{
if(material != nullptr)
material->CleanUp();
material = nullptr;
}
void ComponentMesh::CheckAABBPoints(float3 & min_point, float3 & max_point)
{
if (bounding_box.minPoint.Distance({0,0,0}) >= min_point.Distance({ 0,0,0 }))
min_point = bounding_box.minPoint;
if (bounding_box.maxPoint.Distance({ 0,0,0 }) >= max_point.Distance({ 0,0,0 }))
max_point = bounding_box.maxPoint;
}
void ComponentMesh::Load(JSON_Object * root_obj, UID prefab_uid)
{
string container_fbx = json_object_dotget_string(root_obj, "FBXName");
string meta_path = json_object_dotget_string(root_obj, "MetaName");
string mesh_name = App->file_system->GetLastPathItem(meta_path, true);
///Save somehow from what FBX the mesh is comming, if the Mesh don't exist in the library,
///load the FBX (not adding it to the scene) and unload it in order to create the library mesh.
///Then you can go on
//Check if it's in library
if (!App->file_system->IsFileInDirectory(App->file_system->GetModelsPath() + "\\MetaMeshes", mesh_name.c_str()))
{
//Load the containing FBX && Unload It
GameObject* new_go = App->resources->mesh_importer->CreateFBXMesh(string(App->file_system->GetModelsPath() + string("\\") + container_fbx + ".fbx").c_str(), prefab_uid, true);
if (new_go)
{
new_go->DeleteRecursive();
App->scene->DeleteGameObjectsNow();
}
else
{
CONSOLE_ERROR("Object '%s' could not be found in Assets folder. The '%s'.fbx resource has been deleted or renamed", gameobject->name.c_str(), container_fbx.c_str());
return;
}
}
//Load Library Resource
SetMesh(App->resources->mesh_importer->LoadFromBinary(meta_path.c_str()));
mesh->type = MESH_FBX;
if(mesh->reference_counting == 0)
mesh->LoadToMemory();
draw_bounding_box = false;
mesh->reference_counting++;
}
void ComponentMesh::Save(JSON_Object * root_obj, const char* root)
{
std::string node_name = root;
std::string item_name = "";
item_name = node_name + ".ComponentMesh.MeshName";
json_object_dotset_string(root_obj, item_name.c_str(), this->GetMesh()->name.c_str());
item_name = node_name + ".ComponentMesh.MetaName";
json_object_dotset_string(root_obj, item_name.c_str(), mesh->meta_path.c_str());
item_name = node_name + ".ComponentMesh.FBXName";
json_object_dotset_string(root_obj, item_name.c_str(), container_fbx.c_str());
item_name = node_name + ".ComponentMesh.Type";
json_object_dotset_string(root_obj, item_name.c_str(), ".fbx");
}
| 23.724138 | 177 | 0.712664 | [
"mesh",
"object",
"transform"
] |
2615652cd9f99e57f8ca046c76881015858962a5 | 5,917 | cpp | C++ | test/brain/model_test.cpp | llvim/peloton | e738acb956306d6914a5a94e6773f410a3eae4a1 | [
"Apache-2.0"
] | 3 | 2018-01-08T01:06:17.000Z | 2019-06-17T23:14:36.000Z | test/brain/model_test.cpp | llvim/peloton | e738acb956306d6914a5a94e6773f410a3eae4a1 | [
"Apache-2.0"
] | 1 | 2016-05-10T14:38:18.000Z | 2016-05-10T18:49:08.000Z | test/brain/model_test.cpp | llvim/peloton | e738acb956306d6914a5a94e6773f410a3eae4a1 | [
"Apache-2.0"
] | 2 | 2017-03-23T18:59:38.000Z | 2017-03-25T19:15:08.000Z | //===----------------------------------------------------------------------===//
//
// Peloton
//
// linear_models_test.cpp
//
// Identification: test/brain/linear_model_test.cpp
//
// Copyright (c) 2015-2018, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <algorithm>
#include "brain/testing_forecast_util.h"
#include "brain/util/model_util.h"
#include "brain/workload/kernel_model.h"
#include "brain/workload/linear_model.h"
#include "brain/workload/lstm.h"
#include "brain/workload/workload_defaults.h"
#include "common/harness.h"
#include "util/file_util.h"
namespace peloton {
namespace test {
class ModelTests : public PelotonTest {};
TEST_F(ModelTests, NormalizerTest) {
auto n = brain::Normalizer();
matrix_eig X =
brain::EigenUtil::ToEigenMat({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
n.Fit(X);
matrix_eig Xrecon = n.ReverseTransform(n.Transform(X));
EXPECT_TRUE(Xrecon.isApprox(X));
}
// Enable after resolving
TEST_F(ModelTests, DISABLED_TimeSeriesLSTMTest) {
auto model = std::unique_ptr<brain::TimeSeriesLSTM>(new brain::TimeSeriesLSTM(
brain::LSTMWorkloadDefaults::NFEATS,
brain::LSTMWorkloadDefaults::NENCODED, brain::LSTMWorkloadDefaults::NHID,
brain::LSTMWorkloadDefaults::NLAYERS, brain::LSTMWorkloadDefaults::LR,
brain::LSTMWorkloadDefaults::DROPOUT_RATE,
brain::LSTMWorkloadDefaults::CLIP_NORM,
brain::LSTMWorkloadDefaults::BATCH_SIZE,
brain::LSTMWorkloadDefaults::BPTT, brain::CommonWorkloadDefaults::HORIZON,
brain::CommonWorkloadDefaults::INTERVAL,
brain::LSTMWorkloadDefaults::EPOCHS));
EXPECT_TRUE(model->IsTFModel());
size_t LOG_INTERVAL = 20;
size_t NUM_SAMPLES = 1000;
size_t NUM_FEATS = 3;
float VAL_SPLIT = 0.5;
bool NORMALIZE = false;
float VAL_THESH = 0.05;
TestingForecastUtil::WorkloadTest(*model, WorkloadType::SimpleSinusoidal,
LOG_INTERVAL, NUM_SAMPLES, NUM_FEATS,
VAL_SPLIT, NORMALIZE, VAL_THESH,
brain::CommonWorkloadDefaults::ESTOP_PATIENCE,
brain::CommonWorkloadDefaults::ESTOP_DELTA);
}
TEST_F(ModelTests, LinearRegTest) {
auto model = std::unique_ptr<brain::TimeSeriesLinearReg>(
new brain::TimeSeriesLinearReg(brain::LinearRegWorkloadDefaults::BPTT,
brain::CommonWorkloadDefaults::HORIZON,
brain::CommonWorkloadDefaults::INTERVAL));
EXPECT_FALSE(model->IsTFModel());
size_t LOG_INTERVAL = 1;
size_t NUM_SAMPLES = 1000;
size_t NUM_FEATS = 3;
float VAL_SPLIT = 0.5;
bool NORMALIZE = true;
float VAL_THESH = 0.1;
TestingForecastUtil::WorkloadTest(*model, WorkloadType::NoisyLinear,
LOG_INTERVAL, NUM_SAMPLES, NUM_FEATS,
VAL_SPLIT, NORMALIZE, VAL_THESH,
brain::CommonWorkloadDefaults::ESTOP_PATIENCE,
brain::CommonWorkloadDefaults::ESTOP_DELTA);
}
TEST_F(ModelTests, KernelRegTest) {
auto model = std::unique_ptr<brain::TimeSeriesKernelReg>(
new brain::TimeSeriesKernelReg(brain::KernelRegWorkloadDefaults::BPTT,
brain::CommonWorkloadDefaults::HORIZON,
brain::CommonWorkloadDefaults::INTERVAL));
EXPECT_FALSE(model->IsTFModel());
size_t LOG_INTERVAL = 1;
size_t NUM_SAMPLES = 1000;
size_t NUM_FEATS = 3;
float VAL_SPLIT = 0.5;
bool NORMALIZE = true;
float VAL_THESH = 0.1;
TestingForecastUtil::WorkloadTest(*model, WorkloadType::NoisyLinear,
LOG_INTERVAL, NUM_SAMPLES, NUM_FEATS,
VAL_SPLIT, NORMALIZE, VAL_THESH,
brain::CommonWorkloadDefaults::ESTOP_PATIENCE,
brain::CommonWorkloadDefaults::ESTOP_DELTA);
}
TEST_F(ModelTests, DISABLED_TimeSeriesEnsembleTest) {
auto lr_model = std::make_shared<brain::TimeSeriesLinearReg>(
brain::LinearRegWorkloadDefaults::BPTT,
brain::CommonWorkloadDefaults::HORIZON,
brain::CommonWorkloadDefaults::INTERVAL);
auto kr_model = std::make_shared<brain::TimeSeriesKernelReg>(
brain::KernelRegWorkloadDefaults::BPTT,
brain::CommonWorkloadDefaults::HORIZON,
brain::CommonWorkloadDefaults::INTERVAL);
auto lstm_model = std::make_shared<brain::TimeSeriesLSTM>(
brain::LSTMWorkloadDefaults::NFEATS,
brain::LSTMWorkloadDefaults::NENCODED, brain::LSTMWorkloadDefaults::NHID,
brain::LSTMWorkloadDefaults::NLAYERS, brain::LSTMWorkloadDefaults::LR,
brain::LSTMWorkloadDefaults::DROPOUT_RATE,
brain::LSTMWorkloadDefaults::CLIP_NORM,
brain::LSTMWorkloadDefaults::BATCH_SIZE,
brain::LSTMWorkloadDefaults::BPTT, brain::CommonWorkloadDefaults::HORIZON,
brain::CommonWorkloadDefaults::INTERVAL,
brain::LSTMWorkloadDefaults::EPOCHS);
size_t LOG_INTERVAL = 20;
size_t NUM_SAMPLES = 1000;
size_t NUM_FEATS = 3;
float VAL_SPLIT = 0.5;
bool NORMALIZE = false;
float VAL_THESH = 0.06;
auto model =
std::unique_ptr<brain::TimeSeriesEnsemble>(new brain::TimeSeriesEnsemble(
{lr_model, kr_model, lstm_model}, {0.33f, 0.33f, 0.33},
brain::LSTMWorkloadDefaults::BATCH_SIZE));
TestingForecastUtil::WorkloadTest(*model, WorkloadType::SimpleSinusoidal,
LOG_INTERVAL, NUM_SAMPLES, NUM_FEATS,
VAL_SPLIT, NORMALIZE, VAL_THESH,
brain::CommonWorkloadDefaults::ESTOP_PATIENCE,
brain::CommonWorkloadDefaults::ESTOP_DELTA);
}
} // namespace test
} // namespace peloton | 42.568345 | 82 | 0.64002 | [
"model",
"transform"
] |
2620e5bdc1de7061eeb2a719f10b08f406300921 | 1,055 | cpp | C++ | src/coherence/dev/compiler/ErrorList.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-01T21:38:30.000Z | 2021-11-03T01:35:11.000Z | src/coherence/dev/compiler/ErrorList.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 1 | 2020-07-24T17:29:22.000Z | 2020-07-24T18:29:04.000Z | src/coherence/dev/compiler/ErrorList.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-10T18:40:58.000Z | 2022-02-18T01:23:40.000Z | /*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#include "private/coherence/dev/compiler/ErrorList.hpp"
#include "coherence/util/Iterator.hpp"
COH_OPEN_NAMESPACE3(coherence,dev,compiler)
using coherence::util::Iterator;
// ----- constructors -------------------------------------------------------
ErrorList::ErrorList()
{
}
// ----- Object interface ---------------------------------------------------
TypedHandle<const String> ErrorList::toString() const
{
if (isEmpty())
{
return String::create("ErrorList is empty.");
}
else
{
String::View vs = COH_TO_STRING("ErrorList contains " << size() << " items:");
size32_t c = 0;
for (Iterator::Handle i = iterator(); i->hasNext(); ++c)
{
vs = COH_TO_STRING(vs << "\n[" << c << "]=" << i->next());
}
return vs;
}
}
COH_CLOSE_NAMESPACE3
| 22.934783 | 86 | 0.520379 | [
"object"
] |
262210cdb0a596bdab8ace160e11e767de6a3182 | 4,862 | cpp | C++ | arangod/Utils/DocumentHelper.cpp | morsdatum/ArangoDB | 9cfc6d5cd50b8f451ebdedd77e2c5257fa72a573 | [
"Apache-2.0"
] | null | null | null | arangod/Utils/DocumentHelper.cpp | morsdatum/ArangoDB | 9cfc6d5cd50b8f451ebdedd77e2c5257fa72a573 | [
"Apache-2.0"
] | null | null | null | arangod/Utils/DocumentHelper.cpp | morsdatum/ArangoDB | 9cfc6d5cd50b8f451ebdedd77e2c5257fa72a573 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
/// @brief document utility functions
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "DocumentHelper.h"
#include "Basics/json.h"
#include "Basics/StringUtils.h"
#include "VocBase/vocbase.h"
using namespace triagens::arango;
using namespace triagens::basics;
// -----------------------------------------------------------------------------
// --SECTION-- class DocumentHelper
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- public static methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief assemble a document id from a string and a string
////////////////////////////////////////////////////////////////////////////////
std::string DocumentHelper::assembleDocumentId (std::string const& collectionName,
std::string const& key) {
return collectionName + TRI_DOCUMENT_HANDLE_SEPARATOR_STR + key;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief assemble a document id from a string and a char* key
////////////////////////////////////////////////////////////////////////////////
std::string DocumentHelper::assembleDocumentId (std::string const& collectionName,
const TRI_voc_key_t key) {
if (key == 0) {
return collectionName + TRI_DOCUMENT_HANDLE_SEPARATOR_STR + "_unknown";
}
return collectionName + TRI_DOCUMENT_HANDLE_SEPARATOR_STR + key;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief extract the collection id and document key from an id
////////////////////////////////////////////////////////////////////////////////
bool DocumentHelper::parseDocumentId (CollectionNameResolver const& resolver,
char const* input,
TRI_voc_cid_t& cid,
char** key) {
if (input == nullptr) {
return false;
}
char const* pos = strchr(input, TRI_DOCUMENT_HANDLE_SEPARATOR_CHR);
if (pos == nullptr) {
return false;
}
cid = resolver.getCollectionIdCluster(std::string(input, pos - input));
*key = (char*) (pos + 1);
if (cid == 0 || **key == '\0') {
// unknown collection or empty key
return false;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief extract the "_key" attribute from a JSON object
////////////////////////////////////////////////////////////////////////////////
int DocumentHelper::getKey (TRI_json_t const* json,
TRI_voc_key_t* key) {
*key = 0;
// check type of json
if (! TRI_IsArrayJson(json)) {
return TRI_ERROR_NO_ERROR;
}
// check if _key is there
TRI_json_t const* k = TRI_LookupArrayJson(json, TRI_VOC_ATTRIBUTE_KEY);
if (k == nullptr) {
return TRI_ERROR_NO_ERROR;
}
if (! TRI_IsStringJson(k)) {
// _key is there but not a string
return TRI_ERROR_ARANGO_DOCUMENT_KEY_BAD;
}
// _key is there and a string
*key = k->_value._string.data;
return TRI_ERROR_NO_ERROR;
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
| 35.231884 | 91 | 0.458865 | [
"object"
] |
262f5eaa5023407f7f8c268ba8fc5e9efad9312e | 684 | cpp | C++ | test/unit/math/mix/fun/exp_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | test/unit/math/mix/fun/exp_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | test/unit/math/mix/fun/exp_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | #include <test/unit/math/test_ad.hpp>
TEST(mathMixMatFun, exp) {
auto f = [](const auto& x) {
using stan::math::exp;
return exp(x);
};
stan::test::expect_common_unary_vectorized<stan::test::PromoteToComplex::Yes>(
f);
stan::test::expect_unary_vectorized<stan::test::PromoteToComplex::Yes>(
f, -15.2, -10, -0.5, 0.5, 1, 1.0, 1.3, 5, 10);
stan::test::expect_complex_common(f);
std::vector<double> com_args = stan::test::internal::common_nonzero_args();
std::vector<double> args{-2.6, -0.5, 0.5, 1.5};
stan::test::expect_ad_vector_matvar(f, stan::math::to_vector(com_args));
stan::test::expect_ad_vector_matvar(f, stan::math::to_vector(args));
}
| 34.2 | 80 | 0.668129 | [
"vector"
] |
1c7958ad5ad00e49d5b1df3425217908be6eb979 | 2,796 | cpp | C++ | main/src/vtr_path_tracker/src/robust_mpc/experience/experience_management_base.cpp | utiasASRL/vtr3 | b4edca56a19484666d3cdb25a032c424bdc6f19d | [
"Apache-2.0"
] | 32 | 2021-09-15T03:42:42.000Z | 2022-03-26T10:40:01.000Z | main/src/vtr_path_tracker/src/robust_mpc/experience/experience_management_base.cpp | shimp-t/vtr3 | bdcad784ffe26fabfa737d0e195bcb3bacb930c3 | [
"Apache-2.0"
] | 7 | 2021-09-18T19:18:15.000Z | 2022-02-02T11:15:40.000Z | main/src/vtr_path_tracker/src/robust_mpc/experience/experience_management_base.cpp | shimp-t/vtr3 | bdcad784ffe26fabfa737d0e195bcb3bacb930c3 | [
"Apache-2.0"
] | 7 | 2021-09-18T01:31:28.000Z | 2022-03-14T05:09:37.000Z | // Copyright 2021, Autonomous Space Robotics Lab (ASRL)
//
// 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.
/**
* \file experience_management_base.cpp
* \brief
* \details
*
* \author Autonomous Space Robotics Lab (ASRL)
*/
#include <vtr_path_tracker/robust_mpc/experience/experience_management_base.hpp>
namespace vtr {
namespace path_tracker {
void ExperienceManagement::initialize_running_experiences(
vtr::path_tracker::MpcNominalModel &MpcNominalModel, uint64_t &at_vertex_id,
uint64_t &to_vertex_id, double &turn_radius) {
MpcNominalModel.initialize_experience(experience_km2_, ros_clock);
MpcNominalModel.initialize_experience(experience_km1_, ros_clock);
MpcNominalModel.initialize_experience(experience_k_, ros_clock);
experience_km2_.at_vertex_id = at_vertex_id;
experience_km2_.to_vertex_id = to_vertex_id;
experience_km2_.path_curvature = turn_radius;
experience_km1_.at_vertex_id = at_vertex_id;
experience_km1_.to_vertex_id = to_vertex_id;
experience_km1_.path_curvature = turn_radius;
experience_k_.at_vertex_id = at_vertex_id;
experience_k_.to_vertex_id = to_vertex_id;
experience_k_.path_curvature = turn_radius;
}
void ExperienceManagement::initializeExperience(
MpcNominalModel::experience_t &experience) {
// State
experience.x_k.x_k = Eigen::VectorXf::Zero(STATE_SIZE);
// Velocity estimate
experience.x_k.velocity_km1 = Eigen::VectorXf::Zero(VELOCITY_SIZE);
// Commands
experience.x_k.command_k = Eigen::VectorXf::Zero(VELOCITY_SIZE);
experience.x_k.command_km1 = Eigen::VectorXf::Zero(VELOCITY_SIZE);
// Tracking error and distance
experience.x_k.dist_along_path_k = 0;
experience.x_k.tracking_error_k = Eigen::VectorXf::Zero(STATE_SIZE);
experience.x_k.tracking_error_km1 = Eigen::VectorXf::Zero(STATE_SIZE);
experience.x_k.tracking_error_k_interp = Eigen::VectorXf::Zero(STATE_SIZE);
// Vertex info
pose_graph::VertexId vid;
experience.at_vertex_id = vid;
experience.to_vertex_id = vid;
experience.T_0_v = tf2::Transform();
experience.transform_time = ros_clock.now();
// Variables for GP
experience.gp_data.x_meas = Eigen::VectorXf::Zero(DIST_DEP_SIZE);
experience.gp_data.g_x_meas = Eigen::VectorXf::Zero(STATE_SIZE);
}
} // namespace path_tracker
} // namespace vtr
| 36.311688 | 80 | 0.775751 | [
"transform"
] |
1c7acb604f251677874c55c1797cd9aff2091306 | 821 | cpp | C++ | examples/example01.cpp | JordanCpp/LDL | 39048ea4af28970e274a71e08fa57725b28d34c7 | [
"BSL-1.0"
] | null | null | null | examples/example01.cpp | JordanCpp/LDL | 39048ea4af28970e274a71e08fa57725b28d34c7 | [
"BSL-1.0"
] | null | null | null | examples/example01.cpp | JordanCpp/LDL | 39048ea4af28970e274a71e08fa57725b28d34c7 | [
"BSL-1.0"
] | null | null | null | #include <LDL/Graphics/Window.h>
#include <LDL/Graphics/Render.h>
#include <LDL/Graphics/FpsCounter.h>
#include <LDL/Graphics/FpsLimiter.h>
int main(int argc, char** argv)
{
LDL::Graphics::Window window(LDL::Graphics::Point(0, 0), LDL::Graphics::Point(800, 600), "Example01");
LDL::Graphics::FpsLimiter<60> fpsLimiter;
if (window.Ok())
{
LDL::Graphics::Render render(&window);
LDL::Events::Event event;
LDL::Graphics::FpsCounter fpsCounter;
while (window.GetEvent(event))
{
render.Color(LDL::Graphics::Color(0, 162, 232));
render.Clear();
if (event.Type == LDL::Events::IsQuit)
{
window.StopEvent();
}
render.Present();
if (fpsCounter.Calc())
{
window.Title(std::to_string(fpsCounter.Fps()));
fpsCounter.Clear();
}
fpsLimiter.Sleep();
}
}
return 0;
} | 19.093023 | 103 | 0.652862 | [
"render"
] |
1c7e132e71067be3f84d0e2f4415c11708d19fde | 7,945 | cpp | C++ | src/vedo/anne/Anne.cpp | IAries/VEDO | 8268005d381268cafcf7024ff38fef91c6318ef4 | [
"BSD-3-Clause"
] | null | null | null | src/vedo/anne/Anne.cpp | IAries/VEDO | 8268005d381268cafcf7024ff38fef91c6318ef4 | [
"BSD-3-Clause"
] | null | null | null | src/vedo/anne/Anne.cpp | IAries/VEDO | 8268005d381268cafcf7024ff38fef91c6318ef4 | [
"BSD-3-Clause"
] | null | null | null | #include <aries/utility/Constants.h>
#include <aries/utility/BinaryIO.h>
#include <vedo/framework/Assembler.h>
#include <vedo/framework/Consultant.h>
#include <vedo/framework/DataType.h>
#include <vedo/framework/DOModel.h>
#include <vedo/framework/DOWorld.h>
#include <vedo/framework/GeometricShape.h>
#include <vedo/framework/IactRecordTab.h>
#include <vedo/framework/SimMediator.h>
#include <vedo/common/LeapConsultant.h>
#include <vedo/common/NBSConsultant.h>
#include <vedo/common/NearConsultant.h>
#include <vedo/common/SafeConsultant.h>
#include <vedo/ModuleList.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iostream>
#include <string>
void usage (vedo::_uint_t g)
{
std::cout
<< "Anne " << aries::information::_Version << std::endl
<< aries::information::_Information << std::endl << std::endl
<< "Usage: anne <Mode> <IDO file> <Type> <Record> <UpIact>" << std::endl
<< "Mode : analysis/redistribute" << std::endl
<< "Type : (I) safe/near" << std::endl
<< " (II) nbs/leap" << std::endl
<< "Record : integer" << std::endl
<< "UpIact (for Type II): integer" << std::endl;
exit(0);
}
int main(int argc, char* argv[])
{
if (argc < 5)
{
usage(1);
}
std::vector<std::string> arg;
for (int i=0; i<argc; i++)
{
arg.push_back(argv[i]);
}
time_t starttime; // Starting time
time_t endtime; // Endind time
time(&starttime);
vedo::_float_t timeSystem = 0.0; // Time of system preparing, starting and ending
vedo::_float_t timeImpactSolving = 0.0; // Time of impact solving
vedo::_float_t timeSyncDOContainer = 0.0; // Time of "SyncDOContainer"
vedo::_float_t timeFieldForceAdding = 0.0; // Time of field force adding
vedo::_float_t timeResponseUpdating = 0.0; // Time of response updating
vedo::_float_t timeContactDetection = 0.0; // Time of contact detection
vedo::_float_t timeNextStep = 0.0; // Time of "NextStep"
std::string mode = arg[1];
std::string type = arg[3];
std::string s = arg[4];
vedo::_uint_t RecordStep = aries::String2T<vedo::_uint_t>(arg[4]);
vedo::_uint_t UpIact = 1;
if (arg.size() >= 6)
{
UpIact = aries::String2T<vedo::_uint_t>(arg[5]);
}
vedo::DOWorld* pDOWorld;
vedo::Consultant* pConsultant;
vedo::IactRecordTab* pIactRecordTab = new vedo::IactRecordTab();
vedo::Assembler* pAssembler = vedo::CreateNewAssembler();
std::string idofilename;
if (aries::CheckSubName(arg[2], ".ido"))
{
pDOWorld = new vedo::DOWorld;
idofilename = arg[2];
pDOWorld->ReadIDO(idofilename, pIactRecordTab);
}
else
{
usage(2);
}
if (type == "safe")
{
pConsultant = new vedo::SafeConsultant(pDOWorld, pIactRecordTab, idofilename, RecordStep);
}
else if (type == "near")
{
pConsultant = new vedo::NearConsultant(pDOWorld, pIactRecordTab, idofilename, RecordStep);
}
else if (type == "nbs")
{
if (argc < 6)
{
usage(3);
}
pConsultant = new vedo::NBSConsultant(pDOWorld, pIactRecordTab, idofilename, RecordStep, UpIact);
}
else if (type == "leap")
{
if (argc < 6)
{
usage(3);
}
pConsultant = new vedo::LeapConsultant(pDOWorld, pIactRecordTab, idofilename, RecordStep, UpIact);
}
else
{
usage(5);
}
//njr::RunTime("Simulation Start !!");
vedo::SimMediator sm(pConsultant, pAssembler);
time(&endtime);
timeSystem += (endtime - starttime);
if (mode == "analysis")
{
while (sm.Run());
}
else if (mode == "redistribute")
{
while (sm.ReDistribute());
}
/*
else if (!strcmp(mode, "show"))
{
sm.ShowInteraction();
std::string vtufile(idofilename);
vtufile = vtufile.substr(0, vtufile.size() - 4) += ".vtu";
sm.WriteInteractionForce(vtufile.c_str());
}
*/
else
{
usage(1);
}
time(&starttime);
//njr::RunTime("Simulation End !!");
timeSystem += (sm.timeSystem);
timeImpactSolving = (sm.timeImpactSolving);
timeSyncDOContainer = (sm.timeSyncDOContainer);
timeFieldForceAdding = (sm.timeFieldForceAdding);
timeResponseUpdating = (sm.timeResponseUpdating);
timeContactDetection = (sm.timeContactDetection);
timeNextStep = (sm.timeNextStep);
time(&endtime);
timeSystem += (endtime - starttime);
vedo::_float_t timeComputing
= timeSystem + timeImpactSolving + timeFieldForceAdding + timeResponseUpdating + timeContactDetection + timeNextStep;
vedo::_float_t timeCommunication = timeSyncDOContainer;
vedo::_float_t timeTotal = timeComputing + timeCommunication;
std::ofstream FileLog("time.txt", std::ios::out);
FileLog
<< "=============================================================" << std::endl
<< " Simulated Time: "
<< pConsultant->GetDOWorld()->GetSystemParameter()->GetTimeCurrent()
<< " seconds" << std::endl
<< "-------------------------------------------------------------" << std::endl
<< " Item Time(s) Rate(%) " << std::endl
<< "-------------------------------------------------------------" << std::endl
<< " System " << '\t'
<< timeSystem << "\t\t"
<< timeSystem /timeTotal*100.0 << std::endl
<< " Impact Solving " << '\t'
<< timeImpactSolving << "\t\t"
<< timeImpactSolving /timeTotal*100.0 << std::endl
<< " Field Force Adding " << '\t'
<< timeFieldForceAdding << "\t\t"
<< timeFieldForceAdding /timeTotal*100.0 << std::endl
<< " Response Updating " << '\t'
<< timeResponseUpdating << "\t\t"
<< timeResponseUpdating /timeTotal*100.0 << std::endl
<< " Contact Detection " << '\t'
<< timeContactDetection << "\t\t"
<< timeContactDetection /timeTotal*100.0 << std::endl
<< " NextStep " << '\t'
<< timeNextStep << "\t\t"
<< timeNextStep /timeTotal*100.0 << std::endl
<< " DOContainer Synchronization " << '\t'
<< timeSyncDOContainer << "\t\t"
<< timeSyncDOContainer /timeTotal*100.0 << std::endl
<< "-------------------------------------------------------------" << std::endl
<< " Computing " << '\t'
<< timeComputing << "\t\t"
<< timeComputing /timeTotal*100.0 << std::endl
<< " Communication " << '\t'
<< timeCommunication << "\t\t"
<< timeCommunication /timeTotal*100.0 << std::endl
<< "-------------------------------------------------------------" << std::endl
<< " Total " << '\t'
<< timeTotal << "\t\t"
<< 100 << std::endl
<< "=============================================================" << std::endl;
FileLog.close();
delete pIactRecordTab;
delete pDOWorld;
delete pConsultant;
exit(0);
return true;
}
| 35.950226 | 119 | 0.496035 | [
"vector"
] |
1c87fd24ba19c4184192655f93069042bc039500 | 1,879 | cpp | C++ | test/training_data/plag_original_codes/dp_i_7194931_636_plag.cpp | xryuseix/SA-Plag | 167f7a2b2fa81ff00fd5263772a74c2c5c61941d | [
"MIT"
] | 13 | 2021-01-20T19:53:16.000Z | 2021-11-14T16:30:32.000Z | test/training_data/plag_original_codes/dp_i_7194931_636_plag.cpp | xryuseix/SA-Plag | 167f7a2b2fa81ff00fd5263772a74c2c5c61941d | [
"MIT"
] | null | null | null | test/training_data/plag_original_codes/dp_i_7194931_636_plag.cpp | xryuseix/SA-Plag | 167f7a2b2fa81ff00fd5263772a74c2c5c61941d | [
"MIT"
] | null | null | null | /*
引用元:https://atcoder.jp/contests/dp/tasks/dp_i
I - CoinsEditorial
// ソースコードの引用元 : https://atcoder.jp/contests/dp/submissions/7194931
// 提出ID : 7194931
// 問題ID : dp_i
// コンテストID : dp
// ユーザID : xryuseix
// コード長 : 2127
// 実行時間 : 48
*/
#include <algorithm>
#include <bitset>
#include <cctype>
#include <cfloat>
#include <climits>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
typedef long double ld;
typedef long long int ll;
typedef unsigned long long int ull;
typedef vector<int> vi;
typedef vector<char> vc;
typedef vector<double> vd;
typedef vector<string> vs;
typedef vector<ll> vll;
typedef vector<pair<int, int>> vpii;
typedef vector<vector<int>> vvi;
typedef vector<vector<char>> vvc;
typedef vector<vector<string>> vvs;
typedef vector<vector<ll>> vvll;
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define mp(p, q) make_pair(p, q)
const int P = 1000000007;
const int INF = INT_MAX;
const ll LLINF = 1LL << 60;
int main(void) {
int n;
double ans = 0;
cin >> n;
vd p(n);
rep(i, n) cin >> p[i];
vector<vector<double>> dp(n + 100, vector<double>(n + 100, 0));
dp[0][0] = 1.0;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
dp[i + 1][j] += dp[i][j] * (1 - p[i]);
dp[i + 1][j + 1] += dp[i][j] * p[i];
}
}
for (int i = (n + 1) / 2; i <= n; i++) ans += dp[n][i];
printf("%.12f\n", ans);
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n; j++) {
continue;
}
}
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n; j++) {
continue;
}
}
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n; j++) {
continue;
}
}
}
| 22.105882 | 67 | 0.541245 | [
"vector"
] |
1c8aa8a7f063ca72c351885682477b0761b9d2eb | 5,169 | cpp | C++ | ros/src/evaluation/evaluation/src/pcl2pcl2.cpp | uos/hatsdf_slam | f30f69c0f6b9286cd4fa51ca17f0e2d423ca4682 | [
"BSD-3-Clause"
] | 5 | 2021-05-21T07:52:50.000Z | 2022-02-09T04:26:31.000Z | ros/src/evaluation/evaluation/src/pcl2pcl2.cpp | uos/hatsdf_slam | f30f69c0f6b9286cd4fa51ca17f0e2d423ca4682 | [
"BSD-3-Clause"
] | null | null | null | ros/src/evaluation/evaluation/src/pcl2pcl2.cpp | uos/hatsdf_slam | f30f69c0f6b9286cd4fa51ca17f0e2d423ca4682 | [
"BSD-3-Clause"
] | 1 | 2022-02-09T04:26:33.000Z | 2022-02-09T04:26:33.000Z | #include <string>
#include <ros/ros.h>
#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/point_cloud2_iterator.h>
#include <sensor_msgs/point_cloud_conversion.h>
#include <geometry_msgs/Point32.h>
constexpr auto TOTAL_RINGS = 16u;
struct PCL2PCL2
{
/**
* @brief Construct a new PCL2PCL2 object
*
* @param n Nodehandle
* @param topic topic to publish to
*/
PCL2PCL2(ros::Publisher& pub) : pcl2pub{pub} {}
/// default destructor
~PCL2PCL2() = default;
double opening_angle(const geometry_msgs::Point32& point)
{
double norm = std::sqrt(point.x * point.x + point.y * point.y + point.z * point.z);
return std::acos(point.z / norm);
}
/**
* @brief Convert PointCloud to PointCloud2
*
* @param pcl incoming PointCloud
*/
void pclCallback(const sensor_msgs::PointCloud::ConstPtr& pc_ptr)
{
sensor_msgs::PointCloud2 pc2;
pc2.header = pc_ptr->header;
pc2.height = 1;
pc2.width = pc_ptr->points.size();
pc2.fields.resize(5);
pc2.fields[0].name = "x";
pc2.fields[1].name = "y";
pc2.fields[2].name = "z";
pc2.fields[3].name = "intensity";
pc2.fields[4].name = "ring";
auto offset = 0u;
for (auto index = 0u; index < 3; ++index, offset += sizeof(float))
{
pc2.fields[index].offset = offset;
pc2.fields[index].datatype = sensor_msgs::PointField::FLOAT32;
pc2.fields[index].count = 1;
}
pc2.fields[3].offset = 16;
pc2.fields[3].datatype = sensor_msgs::PointField::FLOAT32;
pc2.fields[4].count = 1;
pc2.fields[4].offset = 20;
pc2.fields[4].datatype = sensor_msgs::PointField::UINT16;
pc2.fields[4].count = 1;
pc2.is_bigendian = false;
pc2.point_step = 22;
pc2.row_step = pc2.width * pc2.point_step;
pc2.data.resize(pc2.row_step * pc2.height);
pc2.is_dense = true;
sensor_msgs::PointCloud2Iterator<float> iter_x(pc2, "x");
sensor_msgs::PointCloud2Iterator<float> iter_intensity(pc2, "intensity");
sensor_msgs::PointCloud2Iterator<int> iter_ring(pc2, "ring");
const auto& pc_points = pc_ptr->points;
std::vector<std::vector<std::vector<float>>> points(TOTAL_RINGS);
std::map<double, int> ring_order;
std::array<bool, TOTAL_RINGS> ring_valid;
ring_valid.fill(false);
for (auto index = 0u; index < pc_points.size(); ++index)
{
std::vector<float> point(3);
point[0] = pc_points[index].x;
point[1] = pc_points[index].y;
point[2] = pc_points[index].z;
auto ring = index % TOTAL_RINGS;
if (!ring_valid[ring] && (point[0] != 0.0 || point[1] != 0.0 || point[2] != 0.0))
{
double angle = opening_angle(pc_points[index]);
ring_order.insert(std::make_pair(angle, ring));
ring_valid[ring] = true;
}
points[ring].push_back(point);
}
std::vector<std::vector<std::vector<float>>> ring_order_points(TOTAL_RINGS);
auto index = 0u;
if (ring_order.size() == 0)
{
std::cerr << "Could not find valid points in the cloud!" << std::endl;
return;
}
for (const auto& entry : ring_order)
{
auto ring = entry.second;
if ( ring_valid[ring])
{
ring_order_points[index] = std::move(points[ring]);
}
++index;
}
for(; index < TOTAL_RINGS; ++index)
{
ring_order_points[index] = std::vector<std::vector<float>>(ring_order_points[0].size(), std::vector<float>(3, 0.0));
}
for (auto ring = 0u; ring < ring_order_points.size(); ++ring)
{
for (const auto& point : ring_order_points[ring])
{
iter_x[0] = point[0];
iter_x[1] = point[1];
iter_x[2] = 1.0 / (ring + 1.0);
iter_intensity[0] = 1.0 / (ring + 1.0);
iter_ring[0] = ring;
++iter_x;
++iter_intensity;
++iter_ring;
}
}
pc2.header.stamp = ros::Time::now();
// publish the generated pcl
pcl2pub.publish(pc2);
}
// publishes PointCloud2
ros::Publisher& pcl2pub;
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "pcl2pcl2");
ros::NodeHandle n("~");
std::string intopic;
n.param("intopic", intopic, std::string("pcl"));
std::string outtopic;
n.param("outtopic", outtopic, std::string("pcl2"));
ROS_INFO_STREAM("Publishing pcl from '" << intopic << "' as pcl2 on '" << outtopic << "'.");
ros::Publisher pub = n.advertise<sensor_msgs::PointCloud2>(outtopic, 1000);
PCL2PCL2 pcl2pcl2(pub);
ros::Subscriber sub = n.subscribe(intopic, 1000, &PCL2PCL2::pclCallback, &pcl2pcl2);
ros::spin();
return 0;
} | 28.092391 | 128 | 0.550977 | [
"object",
"vector"
] |
1c8dc659447763c0ddc6828f9e00cc1e80c65b3b | 20,411 | cc | C++ | media/audio/audio_output_device_unittest.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | media/audio/audio_output_device_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | media/audio/audio_output_device_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright (c) 2012 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 "media/audio/audio_output_device.h"
#include <stdint.h>
#include <utility>
#include <vector>
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/memory/shared_memory.h"
#include "base/single_thread_task_runner.h"
#include "base/sync_socket.h"
#include "base/task_runner.h"
#include "base/test/scoped_task_environment.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "media/audio/audio_sync_reader.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::CancelableSyncSocket;
using base::SharedMemory;
using base::SyncSocket;
using testing::_;
using testing::DoAll;
using testing::Invoke;
using testing::Return;
using testing::WithArg;
using testing::StrictMock;
using testing::NiceMock;
using testing::NotNull;
using testing::Mock;
namespace media {
namespace {
constexpr char kDefaultDeviceId[] = "";
constexpr char kNonDefaultDeviceId[] = "valid-nondefault-device-id";
constexpr char kUnauthorizedDeviceId[] = "unauthorized-device-id";
constexpr float kAudioData = 0.618;
constexpr base::TimeDelta kAuthTimeout =
base::TimeDelta::FromMilliseconds(10000);
constexpr base::TimeDelta kDelay = base::TimeDelta::FromMicroseconds(123);
constexpr int kFramesSkipped = 456;
constexpr int kFrames = 789;
constexpr int kBitstreamFrames = 101;
constexpr size_t kBitstreamDataSize = 512;
class MockRenderCallback : public AudioRendererSink::RenderCallback {
public:
MockRenderCallback() = default;
~MockRenderCallback() override = default;
MOCK_METHOD4(Render,
int(base::TimeDelta delay,
base::TimeTicks timestamp,
int prior_frames_skipped,
AudioBus* dest));
MOCK_METHOD0(OnRenderError, void());
};
class MockAudioOutputIPC : public AudioOutputIPC {
public:
MockAudioOutputIPC() = default;
~MockAudioOutputIPC() override = default;
MOCK_METHOD3(RequestDeviceAuthorization,
void(AudioOutputIPCDelegate* delegate,
int session_id,
const std::string& device_id));
MOCK_METHOD2(CreateStream,
void(AudioOutputIPCDelegate* delegate,
const AudioParameters& params));
MOCK_METHOD0(PlayStream, void());
MOCK_METHOD0(PauseStream, void());
MOCK_METHOD0(CloseStream, void());
MOCK_METHOD1(SetVolume, void(double volume));
};
// Converts a new-style shared memory region to a old-style shared memory
// handle using a mojo::ScopedSharedBufferHandle that supports both types.
// TODO(https://crbug.com/844508): get rid of this when AudioOutputDevice shared
// memory refactor is done.
base::SharedMemoryHandle ToSharedMemoryHandle(
base::UnsafeSharedMemoryRegion region) {
mojo::ScopedSharedBufferHandle buffer_handle =
mojo::WrapUnsafeSharedMemoryRegion(std::move(region));
base::SharedMemoryHandle memory_handle;
mojo::UnwrappedSharedMemoryHandleProtection protection;
size_t memory_length = 0;
auto result = mojo::UnwrapSharedMemoryHandle(
std::move(buffer_handle), &memory_handle, &memory_length, &protection);
DCHECK_EQ(result, MOJO_RESULT_OK);
DCHECK_EQ(protection,
mojo::UnwrappedSharedMemoryHandleProtection::kReadWrite);
return memory_handle;
}
} // namespace.
class AudioOutputDeviceTest : public testing::Test {
public:
AudioOutputDeviceTest();
~AudioOutputDeviceTest() override;
void ReceiveAuthorization(OutputDeviceStatus device_status);
void StartAudioDevice();
void CallOnStreamCreated();
void StopAudioDevice();
void CreateDevice(const std::string& device_id);
void SetDevice(const std::string& device_id);
void CheckDeviceStatus(OutputDeviceStatus device_status);
protected:
base::test::ScopedTaskEnvironment task_env_{
base::test::ScopedTaskEnvironment::MainThreadType::MOCK_TIME};
AudioParameters default_audio_parameters_;
StrictMock<MockRenderCallback> callback_;
MockAudioOutputIPC* audio_output_ipc_; // owned by audio_device_
scoped_refptr<AudioOutputDevice> audio_device_;
OutputDeviceStatus device_status_;
private:
int CalculateMemorySize();
SharedMemory shared_memory_;
CancelableSyncSocket browser_socket_;
CancelableSyncSocket renderer_socket_;
DISALLOW_COPY_AND_ASSIGN(AudioOutputDeviceTest);
};
AudioOutputDeviceTest::AudioOutputDeviceTest()
: device_status_(OUTPUT_DEVICE_STATUS_ERROR_INTERNAL) {
default_audio_parameters_.Reset(AudioParameters::AUDIO_PCM_LINEAR,
CHANNEL_LAYOUT_STEREO, 48000, 1024);
SetDevice(kDefaultDeviceId);
}
AudioOutputDeviceTest::~AudioOutputDeviceTest() {
audio_device_ = nullptr;
}
void AudioOutputDeviceTest::CreateDevice(const std::string& device_id) {
// Make sure the previous device is properly cleaned up.
if (audio_device_)
StopAudioDevice();
audio_output_ipc_ = new NiceMock<MockAudioOutputIPC>();
audio_device_ = new AudioOutputDevice(base::WrapUnique(audio_output_ipc_),
task_env_.GetMainThreadTaskRunner(), 0,
device_id, kAuthTimeout);
}
void AudioOutputDeviceTest::SetDevice(const std::string& device_id) {
CreateDevice(device_id);
EXPECT_CALL(*audio_output_ipc_,
RequestDeviceAuthorization(audio_device_.get(), 0, device_id));
audio_device_->RequestDeviceAuthorization();
task_env_.FastForwardBy(base::TimeDelta());
// Simulate response from browser
OutputDeviceStatus device_status =
(device_id == kUnauthorizedDeviceId)
? OUTPUT_DEVICE_STATUS_ERROR_NOT_AUTHORIZED
: OUTPUT_DEVICE_STATUS_OK;
ReceiveAuthorization(device_status);
audio_device_->Initialize(default_audio_parameters_,
&callback_);
}
void AudioOutputDeviceTest::CheckDeviceStatus(OutputDeviceStatus status) {
DCHECK(!task_env_.GetMainThreadTaskRunner()->BelongsToCurrentThread());
EXPECT_EQ(status, audio_device_->GetOutputDeviceInfo().device_status());
}
void AudioOutputDeviceTest::ReceiveAuthorization(OutputDeviceStatus status) {
device_status_ = status;
if (device_status_ != OUTPUT_DEVICE_STATUS_OK)
EXPECT_CALL(*audio_output_ipc_, CloseStream());
audio_device_->OnDeviceAuthorized(device_status_, default_audio_parameters_,
kDefaultDeviceId);
task_env_.FastForwardBy(base::TimeDelta());
}
void AudioOutputDeviceTest::StartAudioDevice() {
if (device_status_ == OUTPUT_DEVICE_STATUS_OK)
EXPECT_CALL(*audio_output_ipc_, CreateStream(audio_device_.get(), _));
else
EXPECT_CALL(callback_, OnRenderError());
audio_device_->Start();
task_env_.FastForwardBy(base::TimeDelta());
}
void AudioOutputDeviceTest::CallOnStreamCreated() {
const uint32_t kMemorySize =
ComputeAudioOutputBufferSize(default_audio_parameters_);
ASSERT_TRUE(shared_memory_.CreateAndMapAnonymous(kMemorySize));
memset(shared_memory_.memory(), 0xff, kMemorySize);
ASSERT_TRUE(CancelableSyncSocket::CreatePair(&browser_socket_,
&renderer_socket_));
// Create duplicates of the handles we pass to AudioOutputDevice since
// ownership will be transferred and AudioOutputDevice is responsible for
// freeing.
SyncSocket::TransitDescriptor audio_device_socket_descriptor;
ASSERT_TRUE(renderer_socket_.PrepareTransitDescriptor(
base::GetCurrentProcessHandle(), &audio_device_socket_descriptor));
base::SharedMemoryHandle duplicated_memory_handle =
shared_memory_.handle().Duplicate();
ASSERT_TRUE(duplicated_memory_handle.IsValid());
// TODO(erikchen): This appears to leak the SharedMemoryHandle.
// https://crbug.com/640840.
audio_device_->OnStreamCreated(
duplicated_memory_handle,
SyncSocket::UnwrapHandle(audio_device_socket_descriptor),
/*playing_automatically*/ false);
task_env_.FastForwardBy(base::TimeDelta());
}
void AudioOutputDeviceTest::StopAudioDevice() {
if (device_status_ == OUTPUT_DEVICE_STATUS_OK)
EXPECT_CALL(*audio_output_ipc_, CloseStream());
audio_device_->Stop();
task_env_.FastForwardBy(base::TimeDelta());
}
TEST_F(AudioOutputDeviceTest, Initialize) {
// Tests that the object can be constructed, initialized and destructed
// without having ever been started.
StopAudioDevice();
}
// Calls Start() followed by an immediate Stop() and check for the basic message
// filter messages being sent in that case.
TEST_F(AudioOutputDeviceTest, StartStop) {
StartAudioDevice();
StopAudioDevice();
}
// AudioOutputDevice supports multiple start/stop sequences.
TEST_F(AudioOutputDeviceTest, StartStopStartStop) {
StartAudioDevice();
StopAudioDevice();
StartAudioDevice();
StopAudioDevice();
}
// Simulate receiving OnStreamCreated() prior to processing ShutDownOnIOThread()
// on the IO loop.
TEST_F(AudioOutputDeviceTest, StopBeforeRender) {
StartAudioDevice();
// Call Stop() but don't run the IO loop yet.
audio_device_->Stop();
// Expect us to shutdown IPC but not to render anything despite the stream
// getting created.
EXPECT_CALL(*audio_output_ipc_, CloseStream());
CallOnStreamCreated();
}
// Multiple start/stop with nondefault device
TEST_F(AudioOutputDeviceTest, NonDefaultStartStopStartStop) {
SetDevice(kNonDefaultDeviceId);
StartAudioDevice();
StopAudioDevice();
EXPECT_CALL(*audio_output_ipc_,
RequestDeviceAuthorization(audio_device_.get(), 0, _));
StartAudioDevice();
// Simulate reply from browser
ReceiveAuthorization(OUTPUT_DEVICE_STATUS_OK);
StopAudioDevice();
}
TEST_F(AudioOutputDeviceTest, UnauthorizedDevice) {
SetDevice(kUnauthorizedDeviceId);
StartAudioDevice();
StopAudioDevice();
}
TEST_F(AudioOutputDeviceTest,
StartUnauthorizedDeviceAndStopBeforeErrorFires_NoError) {
SetDevice(kUnauthorizedDeviceId);
audio_device_->Start();
// Don't run the runloop. We stop before |audio_device| gets the
// authorization error, so it's not allowed to dereference |callback_|.
EXPECT_CALL(callback_, OnRenderError()).Times(0);
StopAudioDevice();
}
TEST_F(AudioOutputDeviceTest, AuthorizationFailsBeforeInitialize_NoError) {
// Clear audio device set by fixture.
StopAudioDevice();
audio_output_ipc_ = new NiceMock<MockAudioOutputIPC>();
audio_device_ = new AudioOutputDevice(base::WrapUnique(audio_output_ipc_),
task_env_.GetMainThreadTaskRunner(), 0,
kDefaultDeviceId, kAuthTimeout);
EXPECT_CALL(
*audio_output_ipc_,
RequestDeviceAuthorization(audio_device_.get(), 0, kDefaultDeviceId));
audio_device_->RequestDeviceAuthorization();
audio_device_->Initialize(default_audio_parameters_, &callback_);
task_env_.FastForwardBy(base::TimeDelta());
audio_device_->Stop();
// We've stopped, so accessing |callback_| isn't ok.
EXPECT_CALL(callback_, OnRenderError()).Times(0);
audio_device_->OnDeviceAuthorized(OUTPUT_DEVICE_STATUS_ERROR_NOT_AUTHORIZED,
default_audio_parameters_,
kDefaultDeviceId);
task_env_.FastForwardBy(base::TimeDelta());
}
TEST_F(AudioOutputDeviceTest, AuthorizationTimedOut) {
CreateDevice(kNonDefaultDeviceId);
EXPECT_CALL(
*audio_output_ipc_,
RequestDeviceAuthorization(audio_device_.get(), 0, kNonDefaultDeviceId));
EXPECT_CALL(*audio_output_ipc_, CloseStream());
// Request authorization; no reply from the browser.
audio_device_->RequestDeviceAuthorization();
// Advance time until we hit the timeout.
task_env_.FastForwardUntilNoTasksRemain();
audio_device_->Stop();
task_env_.FastForwardBy(base::TimeDelta());
}
namespace {
// This struct collects useful stuff without doing anything magical. It is used
// below, where the test fixture is too inflexible.
struct TestEnvironment {
explicit TestEnvironment(const AudioParameters& params) {
const uint32_t memory_size = ComputeAudioOutputBufferSize(params);
auto shared_memory_region =
base::UnsafeSharedMemoryRegion::Create(memory_size);
auto shared_memory_mapping = shared_memory_region.Map();
CHECK(shared_memory_region.IsValid());
CHECK(shared_memory_mapping.IsValid());
auto browser_socket = std::make_unique<base::CancelableSyncSocket>();
CHECK(CancelableSyncSocket::CreatePair(browser_socket.get(),
&renderer_socket));
reader = std::make_unique<AudioSyncReader>(
/*log callback*/ base::DoNothing(), params,
std::move(shared_memory_region), std::move(shared_memory_mapping),
std::move(browser_socket));
time_stamp = base::TimeTicks::Now();
#if defined(OS_FUCHSIA)
// Raise the timeout limits to reduce bot flakiness.
// Fuchsia's task scheduler suffers from bad jitter on systems running many
// tests simultaneously on nested virtualized deployments (e.g. test bots),
// leading some read operations to randomly timeout.
reader->set_max_wait_timeout_for_test(
base::TimeDelta::FromMilliseconds(50));
#endif
}
base::CancelableSyncSocket renderer_socket;
StrictMock<MockRenderCallback> callback;
std::unique_ptr<AudioSyncReader> reader;
base::TimeTicks time_stamp;
};
} // namespace
TEST_F(AudioOutputDeviceTest, VerifyDataFlow) {
// The test fixture isn't used in this test, but we still have to clean up
// after it.
StopAudioDevice();
auto params = AudioParameters::UnavailableDeviceParams();
params.set_frames_per_buffer(kFrames);
ASSERT_EQ(2, params.channels());
TestEnvironment env(params);
auto* ipc = new MockAudioOutputIPC(); // owned by |audio_device|.
auto audio_device = base::MakeRefCounted<AudioOutputDevice>(
base::WrapUnique(ipc), task_env_.GetMainThreadTaskRunner(), 0,
kDefaultDeviceId, kAuthTimeout);
// Start a stream.
audio_device->RequestDeviceAuthorization();
audio_device->Initialize(params, &env.callback);
audio_device->Start();
EXPECT_CALL(*ipc, RequestDeviceAuthorization(audio_device.get(), 0,
kDefaultDeviceId));
EXPECT_CALL(*ipc, CreateStream(audio_device.get(), _));
EXPECT_CALL(*ipc, PlayStream());
task_env_.RunUntilIdle();
Mock::VerifyAndClear(ipc);
audio_device->OnDeviceAuthorized(OUTPUT_DEVICE_STATUS_OK, params,
kDefaultDeviceId);
audio_device->OnStreamCreated(
ToSharedMemoryHandle(env.reader->TakeSharedMemoryRegion()),
env.renderer_socket.Release(), /*playing_automatically*/ false);
task_env_.RunUntilIdle();
// At this point, the callback thread should be running. Send some data over
// and verify that it's propagated to |env.callback|. Do it a few times.
auto test_bus = AudioBus::Create(params);
for (int i = 0; i < 10; ++i) {
test_bus->Zero();
EXPECT_CALL(env.callback,
Render(kDelay, env.time_stamp, kFramesSkipped, NotNull()))
.WillOnce(WithArg<3>(Invoke([](AudioBus* renderer_bus) -> int {
// Place some test data in the bus so that we can check that it was
// copied to the browser side.
std::fill_n(renderer_bus->channel(0), renderer_bus->frames(),
kAudioData);
std::fill_n(renderer_bus->channel(1), renderer_bus->frames(),
kAudioData);
return renderer_bus->frames();
})));
env.reader->RequestMoreData(kDelay, env.time_stamp, kFramesSkipped);
env.reader->Read(test_bus.get());
Mock::VerifyAndClear(&env.callback);
for (int i = 0; i < kFrames; ++i) {
EXPECT_EQ(kAudioData, test_bus->channel(0)[i]);
EXPECT_EQ(kAudioData, test_bus->channel(1)[i]);
}
}
audio_device->Stop();
EXPECT_CALL(*ipc, CloseStream());
task_env_.RunUntilIdle();
}
TEST_F(AudioOutputDeviceTest, CreateNondefaultDevice) {
// The test fixture isn't used in this test, but we still have to clean up
// after it.
StopAudioDevice();
auto params = AudioParameters::UnavailableDeviceParams();
params.set_frames_per_buffer(kFrames);
ASSERT_EQ(2, params.channels());
TestEnvironment env(params);
auto* ipc = new MockAudioOutputIPC(); // owned by |audio_device|.
auto audio_device = base::MakeRefCounted<AudioOutputDevice>(
base::WrapUnique(ipc), task_env_.GetMainThreadTaskRunner(), 0,
kNonDefaultDeviceId, kAuthTimeout);
audio_device->RequestDeviceAuthorization();
audio_device->Initialize(params, &env.callback);
audio_device->Start();
EXPECT_CALL(*ipc, RequestDeviceAuthorization(audio_device.get(), 0,
kNonDefaultDeviceId));
EXPECT_CALL(*ipc, CreateStream(audio_device.get(), _));
EXPECT_CALL(*ipc, PlayStream());
task_env_.RunUntilIdle();
Mock::VerifyAndClear(ipc);
audio_device->OnDeviceAuthorized(OUTPUT_DEVICE_STATUS_OK, params,
kNonDefaultDeviceId);
audio_device->OnStreamCreated(
ToSharedMemoryHandle(env.reader->TakeSharedMemoryRegion()),
env.renderer_socket.Release(), /*playing_automatically*/ false);
audio_device->Stop();
EXPECT_CALL(*ipc, CloseStream());
task_env_.RunUntilIdle();
}
TEST_F(AudioOutputDeviceTest, CreateBitStreamStream) {
// The test fixture isn't used in this test, but we still have to clean up
// after it.
StopAudioDevice();
const int kAudioParameterFrames = 4321;
AudioParameters params(AudioParameters::AUDIO_BITSTREAM_EAC3,
CHANNEL_LAYOUT_STEREO, 48000, kAudioParameterFrames);
TestEnvironment env(params);
auto* ipc = new MockAudioOutputIPC(); // owned by |audio_device|.
auto audio_device = base::MakeRefCounted<AudioOutputDevice>(
base::WrapUnique(ipc), task_env_.GetMainThreadTaskRunner(), 0,
kNonDefaultDeviceId, kAuthTimeout);
// Start a stream.
audio_device->RequestDeviceAuthorization();
audio_device->Initialize(params, &env.callback);
audio_device->Start();
EXPECT_CALL(*ipc, RequestDeviceAuthorization(audio_device.get(), 0,
kNonDefaultDeviceId));
EXPECT_CALL(*ipc, CreateStream(audio_device.get(), _));
EXPECT_CALL(*ipc, PlayStream());
task_env_.RunUntilIdle();
Mock::VerifyAndClear(ipc);
audio_device->OnDeviceAuthorized(OUTPUT_DEVICE_STATUS_OK, params,
kNonDefaultDeviceId);
audio_device->OnStreamCreated(
ToSharedMemoryHandle(env.reader->TakeSharedMemoryRegion()),
env.renderer_socket.Release(), /*playing_automatically*/ false);
task_env_.RunUntilIdle();
// At this point, the callback thread should be running. Send some data over
// and verify that it's propagated to |env.callback|. Do it a few times.
auto test_bus = AudioBus::Create(params);
for (int i = 0; i < 10; ++i) {
test_bus->Zero();
EXPECT_CALL(env.callback,
Render(kDelay, env.time_stamp, kFramesSkipped, NotNull()))
.WillOnce(WithArg<3>(Invoke([](AudioBus* renderer_bus) -> int {
EXPECT_TRUE(renderer_bus->is_bitstream_format());
// Place some test data in the bus so that we can check that it was
// copied to the browser side.
std::fill_n(renderer_bus->channel(0),
kBitstreamDataSize / sizeof(float), kAudioData);
renderer_bus->SetBitstreamFrames(kBitstreamFrames);
renderer_bus->SetBitstreamDataSize(kBitstreamDataSize);
return renderer_bus->frames();
})));
env.reader->RequestMoreData(kDelay, env.time_stamp, kFramesSkipped);
env.reader->Read(test_bus.get());
Mock::VerifyAndClear(&env.callback);
EXPECT_TRUE(test_bus->is_bitstream_format());
EXPECT_EQ(kBitstreamFrames, test_bus->GetBitstreamFrames());
EXPECT_EQ(kBitstreamDataSize, test_bus->GetBitstreamDataSize());
for (size_t i = 0; i < kBitstreamDataSize / sizeof(float); ++i) {
EXPECT_EQ(kAudioData, test_bus->channel(0)[i]);
}
}
audio_device->Stop();
EXPECT_CALL(*ipc, CloseStream());
task_env_.RunUntilIdle();
}
} // namespace media.
| 36.976449 | 80 | 0.723825 | [
"render",
"object",
"vector"
] |
1c9a868c59726059ea03c0261205f8574b39f68b | 806 | cpp | C++ | Interview Problems/TCS(maximum tip calculator-vector pair-greedy).cpp | kaiserkumars/Cplusplus | 26ecfab62606fb5cda99f41f18f009b0e8eb38a7 | [
"MIT"
] | null | null | null | Interview Problems/TCS(maximum tip calculator-vector pair-greedy).cpp | kaiserkumars/Cplusplus | 26ecfab62606fb5cda99f41f18f009b0e8eb38a7 | [
"MIT"
] | null | null | null | Interview Problems/TCS(maximum tip calculator-vector pair-greedy).cpp | kaiserkumars/Cplusplus | 26ecfab62606fb5cda99f41f18f009b0e8eb38a7 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
//https://practice.geeksforgeeks.org/problems/maximum-tip-calculator/0
bool comp(pair<int,int> x, pair<int,int> y)
{
return (fabs(x.first-x.second)>fabs(y.first-y.second));
}
int main() {
int t;
cin>>t;
int n,x,y;
while(t--)
{
cin>>n>>x>>y;
vector<pair<int,int> >a(n);
for(int i=0;i<n;++i) cin>>a[i].first;
for(int i=0;i<n;++i) cin>>a[i].second;
sort(a.begin(),a.end(),comp);
int ans=0;
for(int i=0;i < n;++i)
{
if(x > 0 && ((a[i].first>=a[i].second)||y==0))
{
ans+=a[i].first;
x--;
}
else if(y>0 &&((a[i].first<a[i].second)||x==0))
{
ans+=a[i].second;
y--;
}
}
cout<<ans<<endl;
}
return 0;
}
| 19.658537 | 70 | 0.468983 | [
"vector"
] |
1cb5a377af7848b572c06bb82a136c956ca8abbd | 3,103 | hpp | C++ | include/SUAPI-CppWrapper/model/Group.hpp | kant/Sketchup-API-C-Wrapper | 807f450fc80d4111ac3a4f057013f300bca07bff | [
"MIT"
] | 20 | 2017-04-05T07:29:44.000Z | 2022-01-10T18:41:42.000Z | include/SUAPI-CppWrapper/model/Group.hpp | kant/Sketchup-API-C-Wrapper | 807f450fc80d4111ac3a4f057013f300bca07bff | [
"MIT"
] | 42 | 2017-05-21T07:47:14.000Z | 2019-10-31T16:19:00.000Z | include/SUAPI-CppWrapper/model/Group.hpp | kant/Sketchup-API-C-Wrapper | 807f450fc80d4111ac3a4f057013f300bca07bff | [
"MIT"
] | 9 | 2017-04-20T13:03:13.000Z | 2022-02-08T23:53:36.000Z | //
// Group.hpp
//
// Sketchup C++ Wrapper for C API
// MIT License
//
// Copyright (c) 2017 Tom Kaneko
//
// 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.
//
#ifndef Group_hpp
#define Group_hpp
#include <stdio.h>
#include <SketchUpAPI/model/group.h>
#include "SUAPI-CppWrapper/model/ComponentInstance.hpp"
namespace CW {
// Forward Declarations
class Entities;
class Transformation;
class ComponentDefinition;
class String;
class Group :public ComponentInstance {
private:
/**
* Create new SUGroupRef object
*/
static SUGroupRef create_group();
static SUGroupRef copy_reference(const Group& other);
public:
/**
* Construct a new, empty Group object.
*/
Group();
/**
* Construct a Group from an existing SUGroupRef object. Groups must always be attached to a parent (there is no release function for Groups)
*/
Group(SUGroupRef group, bool attached = true);
/**
* Construct a Group from instance object. If the instance is not a group, you will get errors, as the constructor does not check for this.
*/
Group(const ComponentInstance& instance);
/** Copy constructor */
Group(const Group& other);
/** Destructor */
~Group();
/** Copy assignment operator */
Group& operator=(const Group& other);
/**
* Returns the raw SUGroupRef object.
*/
SUGroupRef ref() const;
/*
* The class object can be converted to a SUGroupRef.
*/
operator SUGroupRef() const;
operator SUGroupRef*();
/**
* Return the ComponentDefinition of the Group.
*/
ComponentDefinition definition() const;
/**
* Return the Entities object of the Group.
*/
Entities entities() const;
/**
* Return the name of the Group.
*/
String name() const;
/**
* Set the name of this Group.
*/
void name(const String& string);
/**
* Return the Transformation object of the group.
*/
Transformation transformation() const;
/**
* Set the Transformation of the group.
*/
void transformation(const Transformation& transform);
};
} /* namespace CW */
#endif /* Group_hpp */
| 24.824 | 143 | 0.705124 | [
"object",
"model",
"transform"
] |
1cc31668f75c94b4a87f8b3ddf5ec03e63093922 | 4,435 | cpp | C++ | src/Module/Monitor/BFER/Monitor_BFER.cpp | codechecker123/aff3ct | 030af3e990027fa803fb2c68f974c9ec0ee79b5d | [
"MIT"
] | null | null | null | src/Module/Monitor/BFER/Monitor_BFER.cpp | codechecker123/aff3ct | 030af3e990027fa803fb2c68f974c9ec0ee79b5d | [
"MIT"
] | null | null | null | src/Module/Monitor/BFER/Monitor_BFER.cpp | codechecker123/aff3ct | 030af3e990027fa803fb2c68f974c9ec0ee79b5d | [
"MIT"
] | null | null | null | #include <string>
#include <vector>
#include <stdexcept>
#include "Monitor_BFER.hpp"
using namespace aff3ct::module;
template <typename B>
Monitor_BFER<B>
::Monitor_BFER(const int size, const unsigned max_fe, const int n_frames)
: Monitor(size, n_frames),
max_fe(max_fe),
n_bit_errors(0),
n_frame_errors(0),
n_analyzed_frames(0)
{
const std::string name = "Monitor_BFER";
this->set_name(name);
auto &p = this->create_task("check_errors", mnt::tsk::check_errors);
auto &ps_U = this->template create_socket_in<B>(p, "U", this->size * this->n_frames);
auto &ps_V = this->template create_socket_in<B>(p, "V", this->size * this->n_frames);
this->create_codelet(p, [this, &ps_U, &ps_V]() -> int
{
return this->check_errors(static_cast<B*>(ps_U.get_dataptr()),
static_cast<B*>(ps_V.get_dataptr()));
});
}
template <typename B>
int Monitor_BFER<B>
::check_errors(const B *U, const B *V, const int frame_id)
{
const auto f_start = (frame_id < 0) ? 0 : frame_id % this->n_frames;
const auto f_stop = (frame_id < 0) ? this->n_frames : f_start +1;
int n_be = 0;
for (auto f = f_start; f < f_stop; f++)
n_be += this->_check_errors(U + f * this->size,
V + f * this->size,
f);
return n_be;
}
template <typename B>
int Monitor_BFER<B>
::_check_errors(const B *U, const B *V, const int frame_id)
{
auto bit_errors_count = 0;
for (auto b = 0; b < this->size; b++)
bit_errors_count += !U[b] != !V[b];
if (bit_errors_count)
{
n_bit_errors += bit_errors_count;
n_frame_errors++;
for (auto c : this->callbacks_fe)
c(bit_errors_count, frame_id);
if (this->fe_limit_achieved() && frame_id == this->n_frames -1)
for (auto c : this->callbacks_fe_limit_achieved)
c();
}
n_analyzed_frames++;
if (frame_id == this->n_frames -1)
for (auto c : this->callbacks_check)
c();
return bit_errors_count;
}
template <typename B>
bool Monitor_BFER<B>
::fe_limit_achieved()
{
return (get_n_fe() >= get_fe_limit()) || Monitor::interrupt;
}
template <typename B>
unsigned Monitor_BFER<B>
::get_fe_limit() const
{
return max_fe;
}
template <typename B>
unsigned long long Monitor_BFER<B>
::get_n_analyzed_fra() const
{
return n_analyzed_frames;
}
template <typename B>
unsigned long long Monitor_BFER<B>
::get_n_fe() const
{
return n_frame_errors;
}
template <typename B>
unsigned long long Monitor_BFER<B>
::get_n_be() const
{
return n_bit_errors;
}
template <typename B>
float Monitor_BFER<B>
::get_fer() const
{
auto t_fer = 0.f;
if (this->get_n_be() != 0)
t_fer = (float)this->get_n_fe() / (float)this->get_n_analyzed_fra();
else
t_fer = (1.f) / ((float)this->get_n_analyzed_fra());
return t_fer;
}
template <typename B>
float Monitor_BFER<B>
::get_ber() const
{
auto t_ber = 0.f;
if (this->get_n_be() != 0)
t_ber = (float)this->get_n_be() / (float)this->get_n_analyzed_fra() / (float)this->get_size();
else
t_ber = (1.f) / ((float)this->get_n_analyzed_fra()) / this->get_size();
return t_ber;
}
template <typename B>
void Monitor_BFER<B>
::add_handler_fe(std::function<void(unsigned, int)> callback)
{
this->callbacks_fe.push_back(callback);
}
template <typename B>
void Monitor_BFER<B>
::add_handler_check(std::function<void(void)> callback)
{
this->callbacks_check.push_back(callback);
}
template <typename B>
void Monitor_BFER<B>
::add_handler_fe_limit_achieved(std::function<void(void)> callback)
{
this->callbacks_fe_limit_achieved.push_back(callback);
}
template <typename B>
void Monitor_BFER<B>
::reset()
{
Monitor::reset();
this->n_bit_errors = 0;
this->n_frame_errors = 0;
this->n_analyzed_frames = 0;
}
template <typename B>
void Monitor_BFER<B>
::clear_callbacks()
{
this->callbacks_fe .clear();
this->callbacks_check .clear();
this->callbacks_fe_limit_achieved.clear();
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::module::Monitor_BFER<B_8>;
template class aff3ct::module::Monitor_BFER<B_16>;
template class aff3ct::module::Monitor_BFER<B_32>;
template class aff3ct::module::Monitor_BFER<B_64>;
#else
template class aff3ct::module::Monitor_BFER<B>;
#endif
// ==================================================================================== explicit template instantiation
| 23.342105 | 119 | 0.66133 | [
"vector"
] |
1cc4a70a5c1cf0c3e8219f21d99670a4e70f77a7 | 5,755 | cpp | C++ | app/InformedRRTStar.cpp | SrinidhiSreenath/ENPM808X-Midterm-InformedRRTStar | 01e092b4795e3267cb6b0e37321cd103afdbc90b | [
"MIT"
] | 4 | 2018-10-10T00:42:05.000Z | 2020-07-09T07:46:38.000Z | app/InformedRRTStar.cpp | SrinidhiSreenath/ENPM808X-Midterm-InformedRRTStar | 01e092b4795e3267cb6b0e37321cd103afdbc90b | [
"MIT"
] | 8 | 2018-10-24T04:28:31.000Z | 2018-11-06T21:07:27.000Z | app/InformedRRTStar.cpp | SrinidhiSreenath/ENPM808X-Midterm-InformedRRTStar | 01e092b4795e3267cb6b0e37321cd103afdbc90b | [
"MIT"
] | 1 | 2019-10-13T01:12:37.000Z | 2019-10-13T01:12:37.000Z | /****************************************************************************
* MIT License
* Copyright (c) 2018 Srinidhi Sreenath
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
******************************************************************************/
/**
* @file InformedRRTStar.cpp
* @author Srinidhi Sreenath (SrinidhiSreenath)
* @date 10/16/2018
* @version 1.0
*
* @brief RRT STar Class definition for the planner
*
* @section DESCRIPTION
*
* Source file for class Informed RRT Star. The class is used to implement the
* faster convergence of the optimized version of the Rapidly-exploring Random
* Tree algorithm (i-RRT*) to find a path from a start point to a given
* goal point in a pre-defined environment. Once a path is found from RRT
* algorithm, the i-RRT* samples nodes only in the heuristic region around the
* path to minimize the cost to come i.e cost to arrive at a given node from
* start node with a path in the tree.
*
*/
// Class header file
#include "InformedRRTStar.hpp"
// CPP Headers
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <limits>
InformedRRTStar::InformedRRTStar() {
std::cout << "Initializing Informed RRTStar planner!" << std::endl;
}
InformedRRTStar::~InformedRRTStar() {
std::cout << "Finished Informed RRTStar plan!" << std::endl;
}
std::vector<double> InformedRRTStar::generateHeuristicNode() {
std::vector<double> heuristicNode;
// heuristic region is the region around start and goal node defined by an
// ellipse engulfing the path. Here I have approximated a bit by taking the
// square engulfing the ellipse.
int heuristic = std::sqrt((cmax_ * cmax_ - 0.75 * cmin_ * cmin_));
heuristicNode.push_back(startNode_[0] + rand() % heuristic);
heuristicNode.push_back(startNode_[1] + rand() % heuristic);
return heuristicNode;
}
void InformedRRTStar::runPlanner() {
auto randomNode = generateRandomNode();
bool reachedGoal = false;
std::pair<double, double> goalNodePt =
std::make_pair(goalNode_[0], goalNode_[1]);
size_t iterations = 0;
bool check = true;
while (iterations < maxIterations_) {
if (!reachedGoal) {
iterations++;
auto closestTreeNode = findClosestTreeNode(randomNode);
auto newNode = generateNewNode(randomNode, closestTreeNode);
auto treeNodePts = closestTreeNode->getState();
std::pair<double, double> treeNode =
std::make_pair(treeNodePts[0], treeNodePts[1]);
std::pair<double, double> newNodePt =
std::make_pair(newNode[0], newNode[1]);
if (map_.isValidNode(treeNode, newNodePt)) {
appendRRTree(newNode, closestTreeNode);
}
randomNode = generateRandomNode();
std::vector<double> leafNode = RRTStarTree.back().getState();
std::pair<double, double> leafNodePt =
std::make_pair(leafNode[0], leafNode[1]);
reachedGoal =
isGoalReached(leafNode) && map_.isValidNode(leafNodePt, goalNodePt);
} else {
if (check) {
std::shared_ptr<RRTNode> goalParentPtr =
std::make_shared<RRTNode>(RRTStarTree.back());
appendRRTree(goalNode_, goalParentPtr);
check = false;
std::cout << "Goal Found!" << std::endl;
cmin_ = getEuclideanDistance(startNode_, goalNode_);
}
iterations++;
auto closestTreeNode = findClosestTreeNode(randomNode);
auto newNode = generateNewNode(randomNode, closestTreeNode);
auto treeNodePts = closestTreeNode->getState();
std::pair<double, double> treeNode =
std::make_pair(treeNodePts[0], treeNodePts[1]);
std::pair<double, double> newNodePt =
std::make_pair(newNode[0], newNode[1]);
auto rewiredParent = rewireRRTree(newNode, closestTreeNode);
if (map_.isValidNode(treeNode, newNodePt)) {
appendRRTree(newNode, rewiredParent);
}
auto waypoints = getPlannerPath();
cmax_ = 0.0;
for (size_t iter = 0; iter < waypoints.size() - 1; iter++) {
cmax_ +=
std::hypot((waypoints[iter + 1].first - waypoints[iter].first),
(waypoints[iter + 1].second - waypoints[iter].second));
}
// Instead of sampling a random node in the environment, the sampling
// takes place in the heuristic region. This accelerates the convergence
// of the algorithm.
randomNode = generateHeuristicNode();
}
}
if (!reachedGoal && iterations >= maxIterations_) {
resetPlanner();
std::cout << "RRTStar Planner could not find a path" << std::endl;
}
}
void InformedRRTStar::resetPlanner() {
RRTStarTree.clear();
startNode_.clear();
goalNode_.clear();
map_.resetMap();
}
| 37.129032 | 80 | 0.66881 | [
"vector"
] |
1ccab4582ce12356229d86b94a7d23773ad03f09 | 21,498 | cpp | C++ | src/4-hierarchyz/renderer.cpp | AirGuanZ/EfficientShading | 6f9c0a3aebcee0a2ad42fa3d6bc53d4b8f743cde | [
"MIT"
] | 4 | 2021-02-08T10:50:01.000Z | 2022-03-07T08:04:13.000Z | src/4-hierarchyz/renderer.cpp | AirGuanZ/EfficientShading | 6f9c0a3aebcee0a2ad42fa3d6bc53d4b8f743cde | [
"MIT"
] | null | null | null | src/4-hierarchyz/renderer.cpp | AirGuanZ/EfficientShading | 6f9c0a3aebcee0a2ad42fa3d6bc53d4b8f743cde | [
"MIT"
] | null | null | null | #include <agz-utils/file.h>
#include "./renderer.h"
Renderer::Renderer(D3D12Context &d3d)
: d3d_(d3d)
{
}
rg::Vertex *Renderer::addToRenderGraph(
rg::Graph &graph,
rg::Resource *renderTarget,
rg::Resource *hierarchyZ,
int cullThread,
int cullQueue,
int renderThread,
int renderQueue)
{
initCullPipeline(graph, hierarchyZ);
initRenderPipeline(graph, renderTarget);
rg::Pass *copyPerMeshConstsPass,
*clearCommandBufferCounterPass,
*cullPass,
*renderPass;
{
copyPerMeshConstsPass = graph.addPass(
"copy per-mesh constants", cullThread, cullQueue);
copyPerMeshConstsPass->addResourceState(
perMeshConsts_, D3D12_RESOURCE_STATE_COPY_DEST);
copyPerMeshConstsPass->setCallback(
this, &Renderer::doCopyPerMeshConstsPass);
}
{
clearCommandBufferCounterPass = graph.addPass(
"clear command buffer counter", cullThread, cullQueue);
clearCommandBufferCounterPass->addResourceState(
commandBuffer_, D3D12_RESOURCE_STATE_COPY_DEST);
clearCommandBufferCounterPass->addResourceState(
culledCommandBuffer_, D3D12_RESOURCE_STATE_COPY_DEST);
clearCommandBufferCounterPass->setCallback(
this, &Renderer::doClearCommandBufferCounterPass);
}
{
cullPass = graph.addPass("cull", cullThread, cullQueue);
cullTable_ = cullPass->addDescriptorTable(false, true);
cullTable_->addSRV(
perMeshConsts_,
rg::ShaderResourceType::NonPixelOnly,
D3D12_SHADER_RESOURCE_VIEW_DESC{
.Format = DXGI_FORMAT_UNKNOWN,
.ViewDimension = D3D12_SRV_DIMENSION_BUFFER,
.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
.Buffer = D3D12_BUFFER_SRV{
.FirstElement = 0,
.NumElements = MAX_MESH_COUNT,
.StructureByteStride = sizeof(PerMeshConst),
.Flags = D3D12_BUFFER_SRV_FLAG_NONE
}
});
cullTable_->addSRV(
hierarchyZ_,
rg::ShaderResourceType::NonPixelOnly,
D3D12_SHADER_RESOURCE_VIEW_DESC{
.Format = DXGI_FORMAT_R32_FLOAT,
.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D,
.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
.Texture2D = D3D12_TEX2D_SRV{
.MostDetailedMip = 0,
.MipLevels = UINT(-1),
.PlaneSlice = 0,
.ResourceMinLODClamp = 0
}
});
cullTable_->addUAV(
commandBuffer_,
commandBuffer_,
D3D12_UNORDERED_ACCESS_VIEW_DESC{
.Format = DXGI_FORMAT_UNKNOWN,
.ViewDimension = D3D12_UAV_DIMENSION_BUFFER,
.Buffer = D3D12_BUFFER_UAV{
.FirstElement = 0,
.NumElements = MAX_MESH_COUNT,
.StructureByteStride = sizeof(IndirectCommand),
.CounterOffsetInBytes = commandBufferCounterOffset_,
.Flags = D3D12_BUFFER_UAV_FLAG_NONE
}
});
cullTable_->addUAV(
culledCommandBuffer_,
culledCommandBuffer_,
D3D12_UNORDERED_ACCESS_VIEW_DESC{
.Format = DXGI_FORMAT_UNKNOWN,
.ViewDimension = D3D12_UAV_DIMENSION_BUFFER,
.Buffer = D3D12_BUFFER_UAV{
.FirstElement = 0,
.NumElements = MAX_MESH_COUNT,
.StructureByteStride = sizeof(IndirectCommand),
.CounterOffsetInBytes = commandBufferCounterOffset_,
.Flags = D3D12_BUFFER_UAV_FLAG_NONE
}
});
cullPass->setCallback(this, &Renderer::doCullPass);
}
{
renderPass = graph.addPass("forward", renderThread, renderQueue);
renderPass->addResourceState(
commandBuffer_, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
renderPass->addResourceState(
culledCommandBuffer_, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
renderPass->addRTV(
renderTarget_,
D3D12_RENDER_TARGET_VIEW_DESC{
.Format = DXGI_FORMAT_UNKNOWN,
.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D,
.Texture2D = { 0, 0 }
});
renderPass->addDSV(
renderDepthBuffer_,
rg::DepthStencilType::ReadAndWrite,
D3D12_DEPTH_STENCIL_VIEW_DESC{
.Format = DXGI_FORMAT_D32_FLOAT,
.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D,
.Flags = D3D12_DSV_FLAG_NONE,
.Texture2D = { 0 }
});
renderPass->setCallback(this, &Renderer::doRenderPass);
}
graph.addDependency(copyPerMeshConstsPass, cullPass);
graph.addDependency(clearCommandBufferCounterPass, cullPass);
graph.addDependency(cullPass, renderPass);
return graph.addAggregate("cull and render", cullPass, renderPass);
}
void Renderer::addMesh(const Mesh *mesh)
{
if(meshes_.size() >= MAX_MESH_COUNT)
throw std::runtime_error("too many meshes!");
meshes_.push_back(mesh);
}
void Renderer::setCamera(const Mat4 &view, const Mat4 &proj)
{
view_ = view;
proj_ = proj;
}
void Renderer::setCulledMeshRenderingEnabled(bool enabled)
{
renderCulledMeshes_ = enabled;
}
void Renderer::initCullPipeline(rg::Graph &graph, rg::Resource *hierarchyZ)
{
if(!cullRootSignature_)
{
CD3DX12_DESCRIPTOR_RANGE csTableRanges[2] = {};
csTableRanges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 2, 0);
csTableRanges[1].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 2, 0);
CD3DX12_ROOT_PARAMETER params[2] = {};
params[0].InitAsConstantBufferView(0);
params[1].InitAsDescriptorTable(2, csTableRanges);
RootSignatureBuilder builder;
builder.addParameters(params);
builder.addStaticSampler(
s0, D3D12_SHADER_VISIBILITY_ALL, D3D12_FILTER_MIN_MAG_MIP_POINT);
cullRootSignature_ = builder.build(d3d_.getDevice());
}
if(!cullPipeline_)
{
FXC compiler;
compiler.setWarnings(true);
const char *shaderFilename = "./asset/hierarchyz/cull.hlsl";
const std::string shaderSource = agz::file::read_txt_file(shaderFilename);
auto cs = compiler.compile(
shaderSource, "cs_5_0",
FXC::Options{
.includes = D3D_COMPILE_STANDARD_FILE_INCLUDE,
.sourceName = shaderFilename,
.entry = "CSMain"
});
D3D12_COMPUTE_PIPELINE_STATE_DESC desc;
desc.pRootSignature = cullRootSignature_.Get();
desc.CS.pShaderBytecode = cs->GetBufferPointer();
desc.CS.BytecodeLength = cs->GetBufferSize();
desc.NodeMask = 0;
desc.CachedPSO = {};
desc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
AGZ_D3D12_CHECK_HR(
d3d_.getDevice()->CreateComputePipelineState(
&desc, IID_PPV_ARGS(cullPipeline_.GetAddressOf())));
}
if(!cullParams_.isAvailable())
{
cullParams_.initializeUpload(
d3d_.getResourceManager(), d3d_.getFramebufferCount());
}
const size_t perMeshConstsSize = sizeof(PerMeshConst) * MAX_MESH_COUNT;
if(perMeshConstsUpload_.empty())
{
perMeshConstsUpload_.resize(d3d_.getFramebufferCount());
for(auto &b : perMeshConstsUpload_)
{
b.initializeUpload(
d3d_.getResourceManager(), perMeshConstsSize);
}
}
perMeshConsts_ = graph.addInternalResource("per mesh constants");
perMeshConsts_->setInitialState(D3D12_RESOURCE_STATE_COPY_DEST);
perMeshConsts_->setDescription(
CD3DX12_RESOURCE_DESC::Buffer(perMeshConstsSize));
if(!commandBufferZeroCounter_.isAvailable())
{
commandBufferZeroCounter_.initializeUpload(
d3d_.getResourceManager(), 4);
const uint32_t counterValue = 0;
commandBufferZeroCounter_.updateData(0, 4, &counterValue);
}
const size_t commandsSize = sizeof(IndirectCommand) * MAX_MESH_COUNT;
commandBufferCounterOffset_ = agz::upalign_to<size_t>(
commandsSize, D3D12_UAV_COUNTER_PLACEMENT_ALIGNMENT);
const size_t commandBufferSize = commandBufferCounterOffset_ + 4;
commandBuffer_ = graph.addInternalResource("command buffer");
commandBuffer_->setInitialState(D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
commandBuffer_->setDescription(
CD3DX12_RESOURCE_DESC::Buffer(
commandBufferSize, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS));
commandBuffer_->setPerFrame();
culledCommandBuffer_ = graph.addInternalResource("culled command buffer");
culledCommandBuffer_->setInitialState(D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
culledCommandBuffer_->setDescription(commandBuffer_->getDescription());
culledCommandBuffer_->setPerFrame();
hierarchyZ_ = hierarchyZ;
}
void Renderer::initRenderPipeline(rg::Graph &graph, rg::Resource *renderTarget)
{
FXC compiler;
compiler.setWarnings(true);
if(!renderRootSignature_)
{
CD3DX12_ROOT_PARAMETER params[3] = {};
params[0].InitAsConstantBufferView(0, 0, D3D12_SHADER_VISIBILITY_VERTEX);
params[1].InitAsConstantBufferView(1, 0, D3D12_SHADER_VISIBILITY_VERTEX);
params[2].InitAsConstantBufferView(2, 0, D3D12_SHADER_VISIBILITY_PIXEL);
RootSignatureBuilder builder;
builder.addParameters(params);
builder.addFlags(D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
renderRootSignature_ = builder.build(d3d_.getDevice());
}
if(!culledRootSignature_)
{
CD3DX12_ROOT_PARAMETER params[2] = {};
params[0].InitAsConstantBufferView(0, 0, D3D12_SHADER_VISIBILITY_VERTEX);
params[1].InitAsConstantBufferView(1, 0, D3D12_SHADER_VISIBILITY_VERTEX);
RootSignatureBuilder builder;
builder.addParameters(params);
builder.addFlags(D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
culledRootSignature_ = builder.build(d3d_.getDevice());
}
if(!renderPipeline_)
{
const char *shaderFilename = "./asset/hierarchyz/forward.hlsl";
const std::string shaderSource = agz::file::read_txt_file(shaderFilename);
auto vs = compiler.compile(
shaderSource, "vs_5_0",
FXC::Options{
.includes = D3D_COMPILE_STANDARD_FILE_INCLUDE,
.sourceName = shaderFilename,
.entry = "VSMain"
});
auto ps = compiler.compile(
shaderSource, "ps_5_0",
FXC::Options{
.includes = D3D_COMPILE_STANDARD_FILE_INCLUDE,
.sourceName = shaderFilename,
.entry = "PSMain"
});
PipelineBuilder builder;
builder.addInputElement({
"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT,
0, offsetof(Mesh::Vertex, position),
D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0
});
builder.addInputElement({
"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT,
0, offsetof(Mesh::Vertex, normal),
D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0
});
builder.setRootSignature(renderRootSignature_.Get());
builder.setVertexShader(vs);
builder.setPixelShader(ps);
builder.setPrimitiveTopology(D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE);
builder.setRenderTargetCount(1);
builder.setRenderTargetFormat(0, renderTarget->getDescription().Format);
builder.setDepthStencilFormat(DXGI_FORMAT_D32_FLOAT);
builder.setMultisample(1, 0);
builder.setCullMode(D3D12_CULL_MODE_BACK);
builder.setDepthTest(true, true);
renderPipeline_ = builder.build(d3d_.getDevice());
}
if(!culledPipeline_)
{
const char *shaderFilename = "./asset/hierarchyz/forward_culled.hlsl";
const std::string shaderSource = agz::file::read_txt_file(shaderFilename);
auto vs = compiler.compile(
shaderSource, "vs_5_0",
FXC::Options{
.includes = D3D_COMPILE_STANDARD_FILE_INCLUDE,
.sourceName = shaderFilename,
.entry = "VSMain"
});
auto ps = compiler.compile(
shaderSource, "ps_5_0",
FXC::Options{
.includes = D3D_COMPILE_STANDARD_FILE_INCLUDE,
.sourceName = shaderFilename,
.entry = "PSMain"
});
PipelineBuilder builder;
builder.addInputElement({
"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT,
0, offsetof(Mesh::Vertex, position),
D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0
});
builder.setRootSignature(culledRootSignature_.Get());
builder.setVertexShader(vs);
builder.setPixelShader(ps);
builder.setPrimitiveTopology(D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE);
builder.setRenderTargetCount(1);
builder.setRenderTargetFormat(0, renderTarget->getDescription().Format);
builder.setMultisample(1, 0);
builder.setCullMode(D3D12_CULL_MODE_BACK);
builder.setDepthTest(false, false);
culledPipeline_ = builder.build(d3d_.getDevice());
}
if(!renderCommandSignature_)
{
D3D12_INDIRECT_ARGUMENT_DESC args[3] = {};
args[0].Type = D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW;
args[0].ConstantBufferView.RootParameterIndex = 0;
args[1].Type = D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW;
args[1].VertexBuffer.Slot = 0;
args[2].Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW;
D3D12_COMMAND_SIGNATURE_DESC desc;
desc.ByteStride = sizeof(IndirectCommand);
desc.NumArgumentDescs = static_cast<UINT>(agz::array_size(args));
desc.pArgumentDescs = args;
desc.NodeMask = 0;
AGZ_D3D12_CHECK_HR(
d3d_.getDevice()->CreateCommandSignature(
&desc, renderRootSignature_.Get(),
IID_PPV_ARGS(renderCommandSignature_.GetAddressOf())));
}
if(!culledCommandSignature_)
{
D3D12_INDIRECT_ARGUMENT_DESC args[3] = {};
args[0].Type = D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW;
args[0].ConstantBufferView.RootParameterIndex = 0;
args[1].Type = D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW;
args[1].VertexBuffer.Slot = 0;
args[2].Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW;
D3D12_COMMAND_SIGNATURE_DESC desc;
desc.ByteStride = sizeof(IndirectCommand);
desc.NumArgumentDescs = static_cast<UINT>(agz::array_size(args));
desc.pArgumentDescs = args;
desc.NodeMask = 0;
AGZ_D3D12_CHECK_HR(
d3d_.getDevice()->CreateCommandSignature(
&desc, culledRootSignature_.Get(),
IID_PPV_ARGS(culledCommandSignature_.GetAddressOf())));
}
if(!vsCamera_.isAvailable())
{
vsCamera_.initializeUpload(
d3d_.getResourceManager(), d3d_.getFramebufferCount());
}
if(!psParams_.isAvailable())
{
psParams_.initializeUpload(
d3d_.getResourceManager(), d3d_.getFramebufferCount());
}
viewport_ = renderTarget->getDefaultViewport();
scissor_ = renderTarget->getDefaultScissor();
renderTarget_ = renderTarget;
const UINT w = static_cast<UINT>(renderTarget->getDescription().Width);
const UINT h = static_cast<UINT>(renderTarget->getDescription().Height);
auto renderDepthBuffer = graph.addInternalResource("forward depth buffer");
renderDepthBuffer->setInitialState(D3D12_RESOURCE_STATE_DEPTH_WRITE);
renderDepthBuffer->setClearValue(
D3D12_CLEAR_VALUE{
.Format = DXGI_FORMAT_D32_FLOAT,
.DepthStencil = { 1, 0 }
});
renderDepthBuffer->setDescription(
CD3DX12_RESOURCE_DESC::Tex2D(
DXGI_FORMAT_D32_FLOAT, w, h, 1, 1, 1, 0,
D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL));
renderDepthBuffer_ = renderDepthBuffer;
}
void Renderer::doCopyPerMeshConstsPass(rg::PassContext &ctx)
{
if(meshes_.empty())
return;
std::vector<PerMeshConst> perMeshConstsData(meshes_.size());
for(size_t i = 0; i < meshes_.size(); ++i)
{
auto mesh = meshes_[i];
auto &meshConst = perMeshConstsData[i];
meshConst.World = mesh->vsTransformData.World;
meshConst.vertexCount = mesh->vertexBuffer.getVertexCount();
meshConst.lower = mesh->lower;
meshConst.upper = mesh->upper;
meshConst.vertexBuffer =
mesh->vertexBuffer.getView().BufferLocation;
meshConst.constantBuffer =
mesh->vsTransform.getGPUVirtualAddress(ctx.getFrameIndex());
}
auto &uploadBuffer = perMeshConstsUpload_[ctx.getFrameIndex()];
uploadBuffer.updateData(
0,
sizeof(PerMeshConst) * perMeshConstsData.size(),
perMeshConstsData.data());
ctx->CopyBufferRegion(
ctx.getRawResource(perMeshConsts_), 0,
uploadBuffer.getResource(), 0,
uploadBuffer.getByteSize());
}
void Renderer::doClearCommandBufferCounterPass(rg::PassContext &ctx)
{
ctx->CopyBufferRegion(
ctx.getRawResource(commandBuffer_),
commandBufferCounterOffset_,
commandBufferZeroCounter_.getResource(),
0, 4);
ctx->CopyBufferRegion(
ctx.getRawResource(culledCommandBuffer_),
commandBufferCounterOffset_,
commandBufferZeroCounter_.getResource(),
0, 4);
}
void Renderer::doCullPass(rg::PassContext &ctx)
{
if(meshes_.empty())
return;
ctx->SetComputeRootSignature(cullRootSignature_.Get());
ctx->SetPipelineState(cullPipeline_.Get());
cullParams_.updateData(
ctx.getFrameIndex(),
{
view_,
proj_,
{
static_cast<float>(renderTarget_->getDescription().Width),
static_cast<float>(renderTarget_->getDescription().Height)
},
static_cast<int>(meshes_.size())
});
ctx->SetComputeRootConstantBufferView(
0, cullParams_.getGPUVirtualAddress(ctx.getFrameIndex()));
auto cullTable = ctx.getDescriptorRange(cullTable_);
ctx->SetComputeRootDescriptorTable(1, cullTable[0]);
const int threadGroupCount =
agz::upalign_to<int>(
static_cast<int>(meshes_.size()), CULL_THREAD_GROUP_SIZE) /
CULL_THREAD_GROUP_SIZE;
ctx->Dispatch(threadGroupCount, 1, 1);
}
void Renderer::doRenderPass(rg::PassContext &ctx)
{
auto rawRTV = ctx.getDescriptor(renderTarget_).getCPUHandle();
auto rawDSV = ctx.getDescriptor(renderDepthBuffer_).getCPUHandle();
ctx->ClearDepthStencilView(
rawDSV, D3D12_CLEAR_FLAG_DEPTH, 1, 0, 1, &scissor_);
ctx->OMSetRenderTargets(1, &rawRTV, false, &rawDSV);
ctx->RSSetViewports(1, &viewport_);
ctx->RSSetScissorRects(1, &scissor_);
ctx->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
// normal meshes
ctx->SetGraphicsRootSignature(renderRootSignature_.Get());
ctx->SetPipelineState(renderPipeline_.Get());
vsCamera_.updateData(ctx.getFrameIndex(), { view_ * proj_ });
ctx->SetGraphicsRootConstantBufferView(
1, vsCamera_.getGPUVirtualAddress(ctx.getFrameIndex()));
psParams_.updateData(ctx.getFrameIndex(), { Float3(0.3f, -1, 0.5f).normalize() });
ctx->SetGraphicsRootConstantBufferView(
2, psParams_.getGPUVirtualAddress(ctx.getFrameIndex()));
auto rawCommandBuffer = ctx.getRawResource(commandBuffer_);
ctx->ExecuteIndirect(
renderCommandSignature_.Get(), MAX_MESH_COUNT,
rawCommandBuffer, 0,
rawCommandBuffer, commandBufferCounterOffset_);
// culled meshes
if(renderCulledMeshes_)
{
ctx->SetGraphicsRootSignature(culledRootSignature_.Get());
ctx->SetPipelineState(culledPipeline_.Get());
ctx->SetGraphicsRootConstantBufferView(
1, vsCamera_.getGPUVirtualAddress(ctx.getFrameIndex()));
auto rawCulledCommandBuffer = ctx.getRawResource(culledCommandBuffer_);
ctx->ExecuteIndirect(
culledCommandSignature_.Get(), MAX_MESH_COUNT,
rawCulledCommandBuffer, 0,
rawCulledCommandBuffer, commandBufferCounterOffset_);
}
}
| 35.358553 | 106 | 0.628617 | [
"mesh",
"render",
"vector"
] |
1ccda97281e626b30620b7214100fcd606f48205 | 2,014 | cpp | C++ | wwi-2019/jablonie--beta.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | 2 | 2019-05-04T09:37:09.000Z | 2019-05-22T18:07:28.000Z | wwi-2019/jablonie--beta.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | null | null | null | wwi-2019/jablonie--beta.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef int32_t I;
const I inf = 2e9;
// Drzewo przedziałowe (+, max), z operacją index(x).
struct segment_tree {
I n, w;
vector<I> v, d;
segment_tree(I n) : n(n) {
for (w = 1; w < n;) w *= 2;
v.resize(2 * w);
d.resize(2 * w);
}
void push(I i) {
for (I k = 0; k < 2; ++k) v[2 * i + k] += d[i], d[2 * i + k] += d[i];
d[i] = 0;
}
I query(I qb, I qe, I rb, I re, I i, I x) {
if (qb > re || qe < rb) return 0;
if (qb <= rb && re <= qe) {
v[i] += x, d[i] += x;
return v[i];
}
push(i);
I mid = (rb + re) / 2;
I r = query(qb, qe, rb, mid, 2 * i, x) +
query(qb, qe, mid + 1, re, 2 * i + 1, x);
v[i] = max(v[2 * i], v[2 * i + 1]);
return r;
}
I add(I qb, I qe, I x) { return query(qb, qe, 0, w - 1, 1, x); }
I get(I qb, I qe) { return query(qb, qe, 0, w - 1, 1, 0); }
I get(I q) { return query(q, q, 0, w - 1, 1, 0); }
I index(I x) {
I i = 1;
while (i < w) {
push(i);
if (x <= v[2 * i]) {
i = 2 * i;
} else {
i = 2 * i + 1;
}
}
return i - w;
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
I n, m;
cin >> n >> m;
vector<I> v(n);
for (I &i : v) cin >> i;
sort(v.begin(), v.end());
segment_tree tree(n + 1);
for (I i = 0; i < n; ++i) {
tree.add(i, i, v[i]);
}
tree.add(n, n, inf);
while (m--) {
string o;
cin >> o;
if (o[0] == 'p') {
I x;
cin >> x;
--x;
I a = tree.get(x);
if (x + 1 < n && a == tree.get(x + 1)) {
I y = tree.index(a), z = tree.index(a + 1) - 1, l = x - y + 1;
if (y > 0) tree.add(0, y - 1, +1);
tree.add(z - l + 1, z, +1);
} else {
tree.add(0, x, +1);
}
} else {
I a, b;
cin >> a >> b;
cout << tree.index(b + 1) - tree.index(a) << "\n";
}
}
#ifdef UNITEST
cout.flush();
system("pause");
#endif
return 0;
}
| 20.55102 | 73 | 0.412115 | [
"vector"
] |
1cd0c835fbb08c4a55a1fb9fe59b557993f84303 | 862 | cc | C++ | FZU/1901_Period II/1901.cc | pdszhh/ACM | 956b3d03a5d3f070ef24c940b7459f5cccb11d6c | [
"MIT"
] | 1 | 2019-05-05T03:51:20.000Z | 2019-05-05T03:51:20.000Z | FZU/1901_Period II/1901.cc | pdszhh/ACM | 956b3d03a5d3f070ef24c940b7459f5cccb11d6c | [
"MIT"
] | null | null | null | FZU/1901_Period II/1901.cc | pdszhh/ACM | 956b3d03a5d3f070ef24c940b7459f5cccb11d6c | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <cstring>
#include <iterator>
#include <algorithm>
using namespace std;
const int MAXN = 1000010;
int len;
char s[MAXN];
int Next[MAXN];
void get_next() {
int k = Next[0] = -1, j = 0;
while (j != len) {
if (k == -1 or s[j] == s[k])
Next[++j] = ++k;
else
k = Next[k];
}
}
int main() {
int T;
cin >> T;
for (int cases = 1; cases <= T; ++cases) {
cin >> s;
len = strlen(s);
get_next();
vector<int> v;
int ans = 0;
for (int i = Next[len]; i; i = Next[i]) {
++ans;
v.push_back(len - i);
}
cout << "Case #" << cases << ": " << ans + 1 << endl;
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
cout << len << endl;
}
return 0;
}
| 19.155556 | 67 | 0.446636 | [
"vector"
] |
1cd593bc4cd841b9aa0ed9384afd8c728cdbfac2 | 1,206 | cc | C++ | src/parser.cc | ryangraham/cfg | 3b8d951f5c251f3269501d5ab22388ca9a219f9f | [
"MIT"
] | null | null | null | src/parser.cc | ryangraham/cfg | 3b8d951f5c251f3269501d5ab22388ca9a219f9f | [
"MIT"
] | null | null | null | src/parser.cc | ryangraham/cfg | 3b8d951f5c251f3269501d5ab22388ca9a219f9f | [
"MIT"
] | null | null | null | #include "cfg/parser.h"
#include <map>
#include <range/v3/all.hpp>
#include <string>
#include <vector>
#include "cfg/ctree.h"
#include "cfg/token.h"
using namespace ranges;
namespace cfg {
parser::parser(ctree& ctree) : ctree_(&ctree) {}
void parser::parse(std::vector<token> tokens) {
std::vector<token_type> const section = {
token_type::LEFTBRACKET, token_type::IDENTIFIER, token_type::RIGHTBRACKET,
token_type::END};
std::vector<token_type> const kv = {token_type::IDENTIFIER, token_type::EQUAL,
token_type::VALUE, token_type::END};
auto token_types = tokens |
views::transform([](auto& token) { return token.type; }) |
to<std::vector<token_type>>;
if (equal(section, token_types)) {
do_section(tokens);
return;
}
if (equal(kv, token_types)) {
do_kv(tokens);
return;
}
}
void parser::do_section(std::vector<token> tokens) {
current_section = tokens[1].value;
(*ctree_)[current_section];
}
void parser::do_kv(std::vector<token> tokens) {
std::string k{tokens[0].value};
std::string v{tokens[2].value};
(*ctree_)[current_section][k] = v;
}
} // namespace cfg
| 23.647059 | 80 | 0.635987 | [
"vector",
"transform"
] |
1cd862564de96336f922cc313fee74633df0bc94 | 8,349 | hpp | C++ | agario/core/renderables.hpp | jondeaton/AgarLE | f3e956109a245f1297b152cb71d25f9446880f6e | [
"MIT"
] | 6 | 2020-01-16T14:31:18.000Z | 2022-03-08T15:22:32.000Z | agario/core/renderables.hpp | jondeaton/AgarLE | f3e956109a245f1297b152cb71d25f9446880f6e | [
"MIT"
] | null | null | null | agario/core/renderables.hpp | jondeaton/AgarLE | f3e956109a245f1297b152cb71d25f9446880f6e | [
"MIT"
] | 2 | 2020-04-26T02:01:33.000Z | 2021-12-14T11:51:34.000Z | #pragma once
#define GL_SILENCE_DEPRECATION
#include "agario/rendering/platform.hpp"
#include "agario/core/color.hpp"
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <agario/core/Ball.hpp>
#include <agario/rendering/shader.hpp>
#define COLOR_LEN 3
namespace agario {
class RenderingException : public std::runtime_error {
using runtime_error::runtime_error;
};
template<unsigned NSides>
class Circle {
public:
GLfloat verts[3 * (NSides + 2)];
GLfloat color[COLOR_LEN];
GLuint vao; // vertex attribute object
GLuint vbo; // vertex buffer object (gpu memory)
void set_color(agario::color c) {
GLfloat *color_array;
switch (c) {
case agario::color::red:
color_array = red_color;
break;
case agario::color::blue:
color_array = blue_color;
break;
case agario::color::green:
color_array = green_color;
break;
case agario::color::orange:
color_array = orange_color;
break;
case agario::color::purple:
color_array = purple_color;
break;
case agario::color::yellow:
color_array = yellow_color;
break;
default:
throw RenderingException("Not a color");
}
std::copy(color_array, color_array + COLOR_LEN, color);
}
};
template<unsigned NSides>
class RenderableBall : virtual public Ball {
public:
using Ball::Ball;
agario::color color;
template<typename Loc>
explicit RenderableBall(Loc &&loc) : Ball(loc), color(agario::random_color()),
_initialized(false) {}
RenderableBall(agario::distance x, agario::distance y) :
RenderableBall(Location(x, y)) {}
// move constructor
RenderableBall(RenderableBall &&rb) noexcept : RenderableBall(rb.location()) {
if (rb._initialized) {
_initialized = true;
circle = rb.circle;
}
color = rb.color;
rb._initialized = false;
}
// move assignment
RenderableBall &operator=(RenderableBall &&rb) noexcept {
x = rb.x;
y = rb.y;
if (rb._initialized) {
_initialized = true;
circle = rb.circle;
}
color = rb.color;
rb._initialized = false;
return *this;
}
// copy constructor and assignment operator
RenderableBall(const RenderableBall &rbm) = delete;
RenderableBall &operator=(const RenderableBall &rmb) = delete;
void set_color(agario::color c) {
color = c;
circle.set_color(c);
}
void draw(Shader &shader) {
if (!_initialized) _initialize();
shader.setVec4("color", circle.color[0], circle.color[1], circle.color[2], 1.0);
// world location
auto location = glm::vec3(x, y, 0);
glm::mat4 position_transform(1);
position_transform = glm::translate(position_transform, location);
// scaling
glm::mat4 scale_transform(1);
scale_transform = glm::scale(scale_transform, glm::vec3(radius(), radius(), 0));
shader.setMat4("model_transform", position_transform * scale_transform);
// draw them!
glBindVertexArray(circle.vao);
glDrawArrays(GL_TRIANGLE_FAN, 0, NVertices);
glBindVertexArray(0);
}
~RenderableBall() override {
// If you get a "function not found" compilation error
// right here its probably because you didn't link OpenGL
if (_initialized) {
glDeleteVertexArrays(1, &circle.vao);
glDeleteBuffers(1, &circle.vbo);
}
}
protected:
static constexpr unsigned NVertices = NSides + 2;
Circle<NSides> circle;
bool _initialized;
void _initialize() {
_create_vertices();
circle.set_color(color);
glGenVertexArrays(1, &circle.vao);
glGenBuffers(1, &circle.vbo);
glBindVertexArray(circle.vao);
glBindBuffer(GL_ARRAY_BUFFER, circle.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(circle.verts), circle.verts, GL_STREAM_DRAW);
// Position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
glEnableVertexAttribArray(0);
_initialized = true;
}
virtual void _create_vertices() {
circle.verts[0] = 0;
circle.verts[1] = 0;
circle.verts[2] = 0;
for (unsigned i = 1; i < NVertices; i++) {
circle.verts[i * 3] = cos(i * 2 * M_PI / NSides);
circle.verts[i * 3 + 1] = sin(i * 2 * M_PI / NSides);
circle.verts[i * 3 + 2] = 0;
}
}
};
template<unsigned NSides>
class RenderableMovingBall : public RenderableBall<NSides>, public MovingBall {
public:
// inherit move constructor from RenderableBall
using RenderableBall<NSides>::RenderableBall;
template<typename Loc, typename Vel>
RenderableMovingBall(Loc &&loc, Vel &&vel) : Ball(loc),
RenderableBall<NSides>(loc),
MovingBall(loc, vel) {}
template<typename Loc>
explicit RenderableMovingBall(Loc &&loc) : RenderableMovingBall(loc, Velocity()) {}
// move constructor
RenderableMovingBall(RenderableMovingBall &&rmb) noexcept :
RenderableMovingBall(rmb.location(), rmb.velocity) {
if (rmb._initialized) {
this->_initialized = true;
this->circle = rmb.circle;
}
this->color = rmb.color;
rmb._initialized = false;
}
// move assignment
RenderableMovingBall &operator=(RenderableMovingBall &&rmb) noexcept {
x = rmb.x;
y = rmb.y;
velocity = rmb.velocity;
if (rmb._initialized) {
this->_initialized = true;
this->circle = rmb.circle;
}
this->color = rmb.color;
rmb._initialized = false;
return *this;
}
};
template<unsigned NLines>
class Grid {
public:
Grid(distance arena_width, distance arena_height, float z = 0.0) :
arena_width(arena_width), arena_height(arena_height), z(z), _initialized(false) {}
void draw(Shader &shader) {
if (!_initialized) _initialize(); // lazy initialization
shader.setVec4("color", color[0], color[1], color[2], 1.0);
glm::mat4 model_matrix(1);
model_matrix = glm::scale(model_matrix, glm::vec3(arena_width, arena_height, 0));
shader.setMat4("model_transform", model_matrix);
// do the actual drawing
glBindVertexArray(vao);
glDrawArrays(GL_LINES, 0, NumVertices);
glBindVertexArray(0);
}
~Grid() {
if (_initialized) {
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &vbo);
}
}
private:
static constexpr unsigned NumVertices = 2 * 3 * 2 * NLines;
distance arena_width;
distance arena_height;
GLfloat z;
GLfloat color[COLOR_LEN];
GLuint vao;
GLuint vbo;
GLfloat vertices[NumVertices];
bool _initialized;
void _initialize() {
_create_vertices();
color[0] = 0.1;
color[1] = 0.1;
color[2] = 0.1;
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// Position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
glEnableVertexAttribArray(0);
_initialized = true;
}
void _create_vertices() {
_create_horiz_verts(&vertices[3 * 2 * NLines]);
_create_vertical_verts(&vertices[0]);
}
void _create_vertical_verts(GLfloat verts[]) {
GLfloat spacing = 1.0 / (NLines - 1);
for (unsigned i = 0; i < NLines; i++) {
GLfloat x = i * spacing;
verts[6 * i] = x;
verts[6 * i + 1] = 0;
verts[6 * i + 2] = z;
verts[6 * i + 3] = x;
verts[6 * i + 4] = 1;
verts[6 * i + 5] = z;
}
}
void _create_horiz_verts(GLfloat verts[]) {
GLfloat spacing = 1.0 / (NLines - 1);
for (unsigned i = 0; i < NLines; i++) {
GLfloat y = i * spacing;
verts[6 * i] = 0;
verts[6 * i + 1] = y;
verts[6 * i + 2] = z;
verts[6 * i + 3] = 1;
verts[6 * i + 4] = y;
verts[6 * i + 5] = z;
}
}
};
}
| 26.674121 | 88 | 0.599832 | [
"object"
] |
1cd95a64d11f8e69f144247ae5191630993d32fa | 5,929 | cpp | C++ | src/Tile.cpp | jianwei-sun/minesweeper | 5e3ee79ac1a62ac4acdbd4a9972a5beee9d4941d | [
"MIT"
] | null | null | null | src/Tile.cpp | jianwei-sun/minesweeper | 5e3ee79ac1a62ac4acdbd4a9972a5beee9d4941d | [
"MIT"
] | null | null | null | src/Tile.cpp | jianwei-sun/minesweeper | 5e3ee79ac1a62ac4acdbd4a9972a5beee9d4941d | [
"MIT"
] | null | null | null | //----------------------------------------------------------------------------------------------------
// File: Tile.cpp
// Date: 08/22/2021
// Desc: Source file for the Tile class
//----------------------------------------------------------------------------------------------------
#include "Tile.hpp"
//----------------------------------------------------------------------------------------------------
// Function: Tile (constructor)
// Desc: constructs the Tile object
//----------------------------------------------------------------------------------------------------
Tile::Tile(Coordinates coordinates, QWidget* parent)
: QPushButton(parent),
coordinates_(coordinates),
bomb_(false),
neighborBombs_(0),
revealed_(false),
gameStarted_(false),
visualState_(TileVisualState::unclicked)
{
// Fix the size
this->setFixedSize(Tile::pixelSize_, Tile::pixelSize_);
}
void Tile::reset(bool bomb, int neighborBombs){
this->bomb_ = bomb;
this->neighborBombs_ = neighborBombs;
this->revealed_ = false;
this->gameStarted_ = false;
this->visualState_ = TileVisualState::unclicked;
this->setIcon(QIcon());
this->setStyleSheet("");
this->setText("");
}
void Tile::reveal(void){
if(this->bomb_){
switch(this->visualState_){
case TileVisualState::flag:{
this->setIcon(QIcon(":/images/mine_flag.png"));
break;
}
case TileVisualState::unsure:{
this->setIcon(QIcon(":/images/mine_question-mark.png"));
break;
}
default:{
this->setIcon(QIcon(":/images/mine.png"));
}
}
this->setIconSize(QSize(Tile::pixelIconSize_, Tile::pixelIconSize_));
}
this->revealed_ = true;
}
//----------------------------------------------------------------------------------------------------
// Function: mousePressEvent
// Desc: reimplement the mousePress event to respond to primary and secondary clicks
//----------------------------------------------------------------------------------------------------
void Tile::mousePressEvent(QMouseEvent* mouseEvent){
if(!this->gameStarted_){
this->gameStarted_ = true;
emit this->gameStarted();
}
if(mouseEvent->button() == Qt::LeftButton){
this->primaryClicked();
} else if(mouseEvent->button() == Qt::RightButton){
this->secondaryClicked();
}
}
void Tile::emptyReveal(void){
// The goal is to reveal the largest island of tiles without neighbors, including a boundary of tiles with at least 1 neighbor
// This logic can be realized by simulating a primary click if the tile does not have a bomb, because it ensures that the tile would either
// continue to propagate to nearby tiles without neighbors, or display the number of neighbors with bombs (which would end the propagation at the desired boundary)
if(!this->bomb_){
this->primaryClicked();
}
}
void Tile::primaryClicked(void){
// Clicking only makes sense if the tile has not yet been revealed
if(!(this->revealed_ || this->visualState_ == TileVisualState::flag || this->visualState_ == TileVisualState::unsure)){
// Disable the tile from being revealed again
this->revealed_ = true;
// End the game if the user clicks on a bomb tile
if(this->bomb_){
this->setIcon(QIcon(":/images/mine.png"));
this->setStyleSheet("background-color:red;");
emit this->gameOver(this->coordinates_);
// Otherwise reveal a number and/or propagate neighbors
} else{
// Show the button as having been pressed
this->setStyleSheet(QString("border: 0px;"));
// Indicate that the tile is pressed
emit this->tileDelta();
// Display the number
if(this->neighborBombs_ > 0){
this->setText(QString::number(this->neighborBombs_));
QString fontStyle = QString("font:bold;color:") + Tile::fontColors_[this->neighborBombs_ - 1] + QString(";");
this->setStyleSheet(this->styleSheet().append(fontStyle));
// Propagate to neighbors
} else{
emit this->revealEmpty();
}
}
}
}
void Tile::secondaryClicked(void){
if(!this->revealed_){
// Alternate between the unrevealed states
switch(this->visualState_){
case TileVisualState::unclicked:{
this->setIcon(QIcon(":/images/flag.png"));
this->setIconSize(QSize(Tile::pixelIconSize_, Tile::pixelIconSize_));
this->visualState_ = TileVisualState::flag;
emit this->flagDelta(1);
break;
}
case TileVisualState::flag:{
this->setIcon(QIcon(":/images/question-mark.png"));
this->setIconSize(QSize(Tile::pixelIconSize_, Tile::pixelIconSize_));
this->visualState_ = TileVisualState::unsure;
emit this->flagDelta(-1);
break;
}
case TileVisualState::unsure:{
this->setIcon(QIcon());
this->visualState_ = TileVisualState::unclicked;
break;
}
default:{
}
}
}
}
//----------------------------------------------------------------------------------------------------
// Static constants
//----------------------------------------------------------------------------------------------------
const int Tile::pixelSize_ = 22;
const int Tile::pixelIconSize_ = 18;
const std::array<QString, 8> Tile::fontColors_ = {
QString("blue"),
QString("green"),
QString("red"),
QString("purple"),
QString("maroon"),
QString("teal"),
QString("black"),
QString("gray")
}; | 37.05625 | 167 | 0.512059 | [
"object"
] |
1cf5a311161f5967752ce667612c584970af70ac | 1,109 | cpp | C++ | problemes/probleme1xx/probleme135.cpp | ZongoForSpeed/ProjectEuler | 2e2d45f984d48a1da8275886c976f909a0de94ce | [
"MIT"
] | 6 | 2015-10-13T17:07:21.000Z | 2018-05-08T11:50:22.000Z | problemes/probleme1xx/probleme135.cpp | ZongoForSpeed/ProjectEuler | 2e2d45f984d48a1da8275886c976f909a0de94ce | [
"MIT"
] | null | null | null | problemes/probleme1xx/probleme135.cpp | ZongoForSpeed/ProjectEuler | 2e2d45f984d48a1da8275886c976f909a0de94ce | [
"MIT"
] | null | null | null | #include "problemes.h"
#include "arithmetique.h"
#include <fstream>
typedef unsigned long long nombre;
typedef std::vector<nombre> vecteur;
ENREGISTRER_PROBLEME(135, "Same differences") {
// Given the positive integers, x, y, and z, are consecutive terms of an arithmetic progression, the least value of
// the positive integer, n, for which the equation, x² − y² − z² = n, has exactly two solutions is n = 27:
//
// 34² − 27² − 20² = 12² − 9² − 6² = 27
//
// It turns out that n = 1155 is the least value which has exactly ten solutions.
//
// How many values of n less than one million have exactly ten distinct solutions?
nombre limite = 1000000;
vecteur compteur(limite, 0);
for (nombre x = 1; x < limite; ++x) {
for (nombre m = (x + 2) / 3; m < limite; ++m) {
if (nombre n = (m + x) * (3 * m - x);n < limite)
compteur[n]++;
else
break;
}
}
auto resultat = std::count(compteur.begin(), compteur.end(), 10);
return std::to_string(resultat);
}
| 33.606061 | 119 | 0.580703 | [
"vector"
] |
1cf5b41d326f381718328c03841122602e6902ae | 1,003 | cpp | C++ | HackerRank/Dictionaries and Hashmaps/Count-Triplets.cpp | GokulVSD/ScratchPad | 53dee2293a2039186b00c7a465c7ef28e2b8e291 | [
"Unlicense"
] | null | null | null | HackerRank/Dictionaries and Hashmaps/Count-Triplets.cpp | GokulVSD/ScratchPad | 53dee2293a2039186b00c7a465c7ef28e2b8e291 | [
"Unlicense"
] | null | null | null | HackerRank/Dictionaries and Hashmaps/Count-Triplets.cpp | GokulVSD/ScratchPad | 53dee2293a2039186b00c7a465c7ef28e2b8e291 | [
"Unlicense"
] | null | null | null | // https://www.hackerrank.com/challenges/count-triplets-1/
// calculates nCr, may be very useful in the future.
// long comb(long n, int r)
// {
// long res = 1;
// if ( r > n - r )
// r = n - r;
// for (int i = 0; i < r; ++i){
// res *= (n - i);
// res /= (i + 1);
// }
// return res;
// }
long countTriplets(vector<long> arr, long r) {
/* can't use array as a map since elements can be
larger than 10^7.
*/
unordered_map<long, long> potential;
unordered_map<long, long> count;
potential.reserve(100000);
count.reserve(100000);
long triplets = 0;
for(int i = 0; i < arr.size(); ++i){
long cur = arr[i];
long prev = arr[i] / r;
if(arr[i] % r == 0){
triplets += count[prev];
count[cur] += potential[prev];
}
++potential[cur];
}
return triplets;
} | 18.574074 | 59 | 0.451645 | [
"vector"
] |
1cf8bdccdc38ff5ffeb6aff0ecffa803b91dcc4c | 13,681 | cpp | C++ | include/libtcod/console/rexpaint.cpp | EK47/WorldGeneration | 3ed26e3ee7b63e37bd1154e18ba7048538affef8 | [
"MIT"
] | 1 | 2019-09-18T16:09:10.000Z | 2019-09-18T16:09:10.000Z | include/libtcod/console/rexpaint.cpp | EK47/WorldGeneration | 3ed26e3ee7b63e37bd1154e18ba7048538affef8 | [
"MIT"
] | null | null | null | include/libtcod/console/rexpaint.cpp | EK47/WorldGeneration | 3ed26e3ee7b63e37bd1154e18ba7048538affef8 | [
"MIT"
] | null | null | null | /* BSD 3-Clause License
*
* Copyright © 2008-2019, Jice and the libtcod contributors.
* 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.
*/
#include "rexpaint.h"
#ifdef TCOD_CONSOLE_SUPPORT
#include <limits>
#include <zlib.h>
#include "../console.h"
#include "../libtcod_int.h" /* Needed only for TCOD_fatal */
#include "../console_types.h"
#include "../color.h"
/* Convert a little-endian number to native memory order. */
static uint32_t decode_little_endian(uint32_t data)
{
uint32_t result = 0;
const uint8_t* p = reinterpret_cast<uint8_t*>(&data);
for(int i = 0; i < static_cast<int>(sizeof(result)); ++i) {
result += p[i] << (std::numeric_limits<uint8_t>::digits * i);
}
return result;
}
/* Byte swaps a number into little-endian order to be saved to disk. */
static uint32_t encode_little_endian(uint32_t number) {
uint32_t result = 0;
uint8_t* p = reinterpret_cast<uint8_t*>(&result);
for(int i = 0; i < static_cast<int>(sizeof(result)); ++i) {
p[i] = number & std::numeric_limits<uint8_t>::max();
number >>= std::numeric_limits<uint8_t>::digits;
}
return result;
}
/* RexPaint structs */
struct RexPaintHeader {
int32_t version;
int32_t layer_count;
};
struct RexPaintLayerChunk {
int32_t width;
int32_t height;
};
struct RexPaintTile {
int32_t ch;
TCOD_color_t fg;
TCOD_color_t bg;
};
/* Read data from a gz file, returns 0 on success, or -1 on any error. */
static int load_gz_confirm(gzFile gz_file, void *data, size_t length) {
int length_ = static_cast<int>(length);
if (gzread(gz_file, data, length_) != length_) { return -1; }
return 0;
}
/* Loads a little-endian 32 bit signed int into memory. */
static int load_int32(gzFile gz_file, int32_t *out) {
if (load_gz_confirm(gz_file, out, sizeof(out[0]))) { return -1; }
*out = static_cast<int32_t>(
decode_little_endian(static_cast<uint32_t>(out[0]))
);
return 0;
}
static int load_header(gzFile gz_file, struct RexPaintHeader *xp_header) {
return (load_int32(gz_file, &xp_header->version) ||
load_int32(gz_file, &xp_header->layer_count));
}
static int load_layer(gzFile gz_file, struct RexPaintLayerChunk *xp_layer) {
return (load_int32(gz_file, &xp_layer->width) ||
load_int32(gz_file, &xp_layer->height));
}
/* Read a single REXPaint tile, return 0 on success, or -1 on error. */
static int load_tile(gzFile gz_file, struct RexPaintTile *tile) {
return (load_int32(gz_file, &tile->ch) ||
load_gz_confirm(gz_file, &tile->fg, sizeof(tile->fg)) ||
load_gz_confirm(gz_file, &tile->bg, sizeof(tile->bg)));
}
/* Read a layer of REXPaint tiles onto a console.
If transparent is true, then follow REXPaint's rules for transparency. */
static int load_tiles(
gzFile gz_file, TCOD_Console* console, int transparent) {
int x, y;
const int width = TCOD_console_get_width(console);
const int height = TCOD_console_get_height(console);
/* REXPaint tiles are in column-major order. */
for (x = 0; x < width; ++x) {
for (y = 0; y < height; ++y) {
struct RexPaintTile tile;
if (load_tile(gz_file, &tile)) {
return -1;
}
/* REXPaint uses a magic pink background to mark transparency. */
if (transparent &&
tile.bg.r == 0xff &&
tile.bg.g == 0x00 &&
tile.bg.b == 0xff) { continue; }
TCOD_console_set_char(console, x, y, tile.ch);
TCOD_console_set_char_foreground(console, x, y, tile.fg);
TCOD_console_set_char_background(console, x, y, tile.bg, TCOD_BKGND_SET);
}
}
return 0;
}
/* Return the next REXPaint layer as a console. After reading the header you
could just keep calling this function until it returns NULL. */
static TCOD_console_t load_console(gzFile gz_file) {
struct RexPaintLayerChunk xp_layer;
TCOD_console_t console;
if (load_layer(gz_file, &xp_layer)) { return NULL; }
console = TCOD_console_new(xp_layer.width, xp_layer.height);
if (!console) { return NULL; }
if (load_tiles(gz_file, console, 0)) {
TCOD_console_delete(console);
return NULL;
}
return console;
}
/* Load all the contents of a REXPaint file into a list of consoles. */
static TCOD_list_t load_consoleList(gzFile gz_file) {
struct RexPaintHeader xp_header;
TCOD_list_t console_list;
int i;
if (load_header(gz_file, &xp_header)) { return NULL; }
console_list = TCOD_list_allocate(xp_header.layer_count);
if (!console_list) { return NULL; }
for (i = 0; i < xp_header.layer_count; ++i) {
TCOD_console_t console = load_console(gz_file);
if (!console) {
/* There was an issue then delete everything so far and return NULL */
while (!TCOD_list_is_empty(console_list)) {
TCOD_console_delete(
static_cast<TCOD_Console*>(TCOD_list_pop(console_list)));
}
TCOD_list_delete(console_list);
return NULL;
}
TCOD_list_push(console_list, console);
}
return console_list;
}
/* Convert a list of consoles into a single console, deleting the list.
Follows REXPaint's rules for transparency. */
static TCOD_console_t combine_console_list(TCOD_list_t console_list) {
TCOD_console_t main_console;
if (!console_list) { return NULL; }
/* Reverse the list so that elements will be dequeued. */
TCOD_list_reverse(console_list);
main_console = static_cast<TCOD_Console*>(TCOD_list_pop(console_list));
while (!TCOD_list_is_empty(console_list)) {
TCOD_console_t console =
static_cast<TCOD_Console*>(TCOD_list_pop(console_list));
/* Set key color to {255, 0, 255} before blit. */
TCOD_console_set_key_color(console, TCOD_fuchsia);
/* This blit may fail if the consoles do not match shapes. */
TCOD_console_blit(console, 0, 0, 0, 0, main_console, 0, 0, 1.0f, 1.0f);
TCOD_console_delete(console);
}
TCOD_list_delete(console_list);
return main_console;
}
/**
* \brief Return a list of consoles from a REXPaint file.
*
* \param [in] filename A path to the REXPaint file.
* \return Returns a TCOD_list_t of TCOD_console_t objects. Or NULL on an
* error. You will need to delete this list and each console individually.
*
* This function can load a REXPaint file with variable layer shapes,
* which would cause issues for a function like TCOD_console_list_from_xp.
*/
TCOD_list_t TCOD_console_list_from_xp(const char *filename) {
int z_errno = Z_ERRNO;
TCOD_list_t console_list;
gzFile gz_file = gzopen(filename, "rb");
if (!gz_file) {
TCOD_fatal("Could not open file: '%s'", filename);
return NULL;
}
console_list = load_consoleList(gz_file);
if (!console_list){
TCOD_fatal("Error parsing '%s'\n%s", filename, gzerror(gz_file, &z_errno));
/* Could fall-through here and return NULL. */
}
gzclose(gz_file);
return console_list;
}
/**
* \brief Return a new console loaded from a REXPaint ``.xp`` file.
*
* \param [in] filename A path to the REXPaint file.
* \return A new TCOD_console_t object. New consoles will need
* to be deleted with a call to :any:`TCOD_console_delete`.
* Returns NULL on an error.
*
*/
TCOD_console_t TCOD_console_from_xp(const char *filename) {
return combine_console_list(TCOD_console_list_from_xp(filename));
}
/**
* \brief Update a console from a REXPaint ``.xp`` file.
*
* \param [out] con A console instance to update from the REXPaint file.
* \param [in] filename A path to the REXPaint file.
*
* In C++, you can pass the filepath directly to the :any:`TCODConsole`
* constructor to load a REXPaint file.
*/
bool TCOD_console_load_xp(TCOD_console_t con, const char *filename) {
TCOD_console_t xp_console = TCOD_console_from_xp(filename);
if (!xp_console) { return false; }
if (TCOD_console_get_width(con) != TCOD_console_get_width(xp_console) ||
TCOD_console_get_height(con) != TCOD_console_get_height(xp_console)) {
TCOD_console_delete(xp_console);
return false;
}
TCOD_console_blit(xp_console, 0, 0, 0, 0, con, 0, 0, 1.0f, 1.0f);
TCOD_console_delete(xp_console);
return true;
}
/* Saves a 32-bit signed int encoded as little-endian to gz_file. */
static int write_int32(gzFile gz_file, int32_t number) {
uint32_t encoded = encode_little_endian(static_cast<uint32_t>(number));
if (!gzwrite(gz_file, &encoded, sizeof(encoded))) {
return -1;
}
return 0;
}
static int write_header(gzFile gz_file, struct RexPaintHeader *xp_header) {
return (write_int32(gz_file, xp_header->version) ||
write_int32(gz_file, xp_header->layer_count));
}
static int write_layer(gzFile gz_file, struct RexPaintLayerChunk *xp_layer) {
return (write_int32(gz_file, xp_layer->width) ||
write_int32(gz_file, xp_layer->height));
}
static int write_tile(gzFile gz_file, struct RexPaintTile *tile) {
if (write_int32(gz_file, tile->ch) ||
!gzwrite(gz_file, &tile->fg, sizeof(tile->fg)) ||
!gzwrite(gz_file, &tile->bg, sizeof(tile->bg))) {
return -1;
}
return 0;
}
static int write_console(gzFile gz_file, const TCOD_Console* console) {
int x, y;
struct RexPaintLayerChunk xp_layer;
xp_layer.width = TCOD_console_get_width(console);
xp_layer.height = TCOD_console_get_height(console);
if (write_layer(gz_file, &xp_layer)) {
return -1; /* error writing layer */
}
/* Write console data out in column-major order. */
for (x = 0; x < xp_layer.width; ++x) {
for (y = 0; y < xp_layer.height; ++y) {
struct RexPaintTile tile;
tile.ch = TCOD_console_get_char(console, x, y);
tile.fg = TCOD_console_get_char_foreground(console, x, y);
tile.bg = TCOD_console_get_char_background(console, x, y);
if (write_tile(gz_file, &tile)) {
return -1; /* error writing tile data */
}
}
}
return 0;
}
/**
* \brief Save a console as a REXPaint ``.xp`` file.
*
* \param [in] con The console instance to save.
* \param [in] filename The filepath to save to.
* \param [in] compress_level A zlib compression level, from 0 to 9.
* 1=fast, 6=balanced, 9=slowest, 0=uncompressed.
* \return ``true`` when the file is saved succesfully, or ``false`` when an
* issue is detected.
*
* The REXPaint format can support a 1:1 copy of a libtcod console.
*/
bool TCOD_console_save_xp(
const TCOD_Console* con, const char *filename, int compress_level) {
struct RexPaintHeader xp_header;
gzFile gz_file = gzopen(filename, "wb");
if (!gz_file) { return false; /* could not open file */ }
gzsetparams(gz_file, compress_level, Z_DEFAULT_STRATEGY);
xp_header.version = -1; /* REXPaint uses this version. */
xp_header.layer_count = 1;
if (write_header(gz_file, &xp_header) || write_console(gz_file, con)) {
gzclose(gz_file);
return false; /* error writing data */
}
if (gzclose(gz_file)) { return false; /* error writing to file */ }
return true;
}
/**
* \brief Save a list of consoles to a REXPaint file.
*
* \param [in] console_list A TCOD_list_t of TCOD_console_t objects.
* \param [in] filename Path to save to.
* \param [in] compress_level zlib compression level.
* \return true on success, false on a failure such as not being able to write
* to the path provided.
*
* This function can save any number of layers with multiple
* different sizes.
*
* The REXPaint tool only supports files with up to 9 layers where
* all layers are the same size.
*/
bool TCOD_console_list_save_xp(
TCOD_list_t console_list, const char *filename, int compress_level) {
int i;
struct RexPaintHeader xp_header;
gzFile gz_file = gzopen(filename, "wb");
if (!gz_file) { return false; /* could not open file */ }
gzsetparams(gz_file, compress_level, Z_DEFAULT_STRATEGY);
xp_header.version = -1;
xp_header.layer_count = TCOD_list_size(console_list);
if (write_header(gz_file, &xp_header)) {
gzclose(gz_file);
return false; /* error writing metadata */
}
for (i = 0; i < xp_header.layer_count; ++i){
if (write_console(
gz_file, static_cast<TCOD_Console*>(TCOD_list_get(console_list, i)))) {
gzclose(gz_file);
return false; /* error writing out console data */
}
}
if (gzclose(gz_file)) { return false; /* error writing to file */ }
return true;
}
#endif /* TCOD_CONSOLE_SUPPORT */
| 37.792818 | 79 | 0.704115 | [
"object"
] |
7f2e68e9ee0c773583cb08e6054f06bf07ba1588 | 10,098 | cpp | C++ | src/game/game.cpp | ProjectElon/Crafty | 626b5c2d355bfe369bc3047043f5d5948a6ac691 | [
"MIT"
] | 6 | 2022-02-04T17:50:17.000Z | 2022-02-10T12:16:26.000Z | src/game/game.cpp | ProjectElon/Crafty | 626b5c2d355bfe369bc3047043f5d5948a6ac691 | [
"MIT"
] | null | null | null | src/game/game.cpp | ProjectElon/Crafty | 626b5c2d355bfe369bc3047043f5d5948a6ac691 | [
"MIT"
] | null | null | null | #include "game.h"
#include "game/world.h"
#include "game/job_system.h"
#include "core/platform.h"
#include "core/input.h"
#include "core/event.h"
#include "renderer/opengl_renderer.h"
#include "renderer/opengl_2d_renderer.h"
#include "renderer/opengl_debug_renderer.h"
#include "renderer/font.h"
#include "renderer/camera.h"
#include "game/physics.h"
#include "game/ecs.h"
#include "ui/ui.h"
#include "ui/dropdown_console.h"
#include "game/profiler.h"
namespace minecraft {
static bool on_quit(const Event *event, void *sender)
{
Game::internal_data.is_running = false;
return true;
}
static bool on_key_press(const Event *event, void *sender)
{
u16 key;
Event_System::parse_key_code(event, &key);
if (key == MC_KEY_F1)
{
Dropdown_Console::toggle();
}
if (key == MC_KEY_F2)
{
Input::toggle_cursor();
Game::toggle_should_update_camera();
}
if (Dropdown_Console::is_closed())
{
if (key == MC_KEY_ESCAPE)
{
Game::internal_data.is_running = false;
}
if (key == MC_KEY_U)
{
Game::toggle_show_debug_status_hud();
}
}
else
{
if (key == MC_KEY_ESCAPE)
{
Dropdown_Console::close();
}
}
return false;
}
static bool on_mouse_press(const Event *event, void *sender)
{
(void)event;
(void)sender;
u8 button;
Event_System::parse_button_code(event, &button);
return false;
}
static bool on_mouse_wheel(const Event *event, void *sender)
{
(void)event;
(void)sender;
f32 xoffset;
f32 yoffset;
Event_System::parse_model_wheel(event, &xoffset, &yoffset);
return false;
}
static bool on_mouse_move(const Event *event, void *sender)
{
(void)event;
(void)sender;
f32 mouse_x;
f32 mouse_y;
Event_System::parse_mouse_move(event, &mouse_x, &mouse_y);
return false;
}
static bool on_char(const Event *event, void *sender)
{
(void)event;
(void)sender;
char code_point;
Event_System::parse_char(event, &code_point);
return false;
}
static bool on_resize(const Event *event, void *sender)
{
u32 width;
u32 height;
Event_System::parse_resize_event(event, &width, &height);
Camera& camera = Game::get_camera();
camera.aspect_ratio = (f32)width / (f32)height;
return false;
}
bool Game::start()
{
// @todo(harlequin): load the game config from a file
Game_Config& config = internal_data.config;
config.window_title = "Minecraft";
config.window_x = -1;
config.window_y = -1;
config.window_width = 1280;
config.window_height = 720;
config.window_mode = WindowMode_Windowed;
u32 opengl_major_version = 4;
u32 opengl_minor_version = 4;
Platform* platform = new Platform; // @todo(harlequin): memory system
if (!platform->initialize(opengl_major_version, opengl_minor_version))
{
fprintf(stderr, "[ERROR]: failed to initialize platform\n");
return false;
}
if (!Input::initialize(platform))
{
fprintf(stderr, "[ERROR]: failed to initialize input system\n");
return false;
}
Input::set_raw_mouse_motion(true);
Input::set_cursor_mode(false);
bool is_tracing_events = false;
if (!Event_System::initialize(platform, is_tracing_events))
{
fprintf(stderr, "[ERROR]: failed to initialize event system\n");
return false;
}
if (!Opengl_Renderer::initialize(platform))
{
fprintf(stderr, "[ERROR]: failed to initialize render system\n");
return false;
}
if (!Opengl_2D_Renderer::initialize())
{
fprintf(stderr, "[ERROR]: failed to initialize 2d renderer system\n");
return false;
}
if (!Opengl_Debug_Renderer::initialize())
{
fprintf(stderr, "[ERROR]: failed to initialize debug render system\n");
return false;
}
if (!Job_System::initialize())
{
fprintf(stderr, "[ERROR]: failed to initialize job system\n");
return false;
}
i32 physics_update_rate = 120;
if (!Physics::initialize(physics_update_rate))
{
fprintf(stderr, "[ERROR] failed to initialize physics system\n");
return false;
}
const u32 max_entity_count = 1024;
if (!ECS::initialize(max_entity_count))
{
fprintf(stderr, "[ERROR] failed to initialize ecs\n");
return false;
}
if (!Profiler::initialize(60))
{
fprintf(stderr, "[ERROR] failed to initialize profiler\n");
return false;
}
// setting the max number of open files using fopen
i32 new_max = _setmaxstdio(8192);
assert(new_max == 8192);
Event_System::register_event(EventType_Quit, on_quit);
Event_System::register_event(EventType_KeyPress, on_key_press);
Event_System::register_event(EventType_Char, on_char);
Event_System::register_event(EventType_Resize, Opengl_Renderer::on_resize);
Event_System::register_event(EventType_MouseButtonPress, on_mouse_press);
Event_System::register_event(EventType_MouseMove, on_mouse_move);
Event_System::register_event(EventType_MouseWheel, on_mouse_wheel);
Bitmap_Font *fira_code = new Bitmap_Font; // @todo(harlequin): memory system
fira_code->load_from_file("../assets/fonts/FiraCode-Regular.ttf", 22);
Bitmap_Font *noto_mono = new Bitmap_Font; // @todo(harlequin): memory system
noto_mono->load_from_file("../assets/fonts/NotoMono-Regular.ttf", 22);
Bitmap_Font *consolas = new Bitmap_Font; // @todo(harlequin): memory system
consolas->load_from_file("../assets/fonts/Consolas.ttf", 20);
Bitmap_Font *liberation_mono = new Bitmap_Font; // @todo(harlequin): memory system
liberation_mono->load_from_file("../assets/fonts/liberation-mono.ttf", 20);
UI_State default_ui_state;
default_ui_state.cursor = { 0.0f, 0.0f };
default_ui_state.text_color = { 1.0f, 1.0f, 1.0f, 1.0f };
default_ui_state.fill_color = { 1.0f, 0.0f, 0.0f, 1.0f };
default_ui_state.offset = { 0.0f, 0.0f };
default_ui_state.font = noto_mono;
if (!UI::initialize(&default_ui_state))
{
fprintf(stderr, "[ERROR]: failed to initialize ui system\n");
return false;
}
f32 normalize_color_factor = 1.0f / 255.0f;
glm::vec4 text_color = { 0xee, 0xe6, 0xce, 0xff };
glm::vec4 background_color = { 31, 35, 52, 0xff * 0.8f };
glm::vec4 input_text_color = { 0xff, 0xff, 0xff, 0xff };
glm::vec4 input_text_background_color = { 0x15, 0x72, 0xA1, 0xff }; // 1572A1
glm::vec4 input_text_cursor_color = { 0x85, 0xC8, 0x8A, 0xff * 0.7f }; // 85C88A
glm::vec4 scroll_bar_background_color = { 0xff, 0x9f, 0x45, 0xff * 0.5f }; // FF9F45
glm::vec4 scrool_bar_color = { 0xf7, 0x6e, 0x11, 0xff }; // F76E11
glm::vec4 command_color = { 0xf4, 0x73, 0x40, 0xff }; // F47340
glm::vec4 argument_color = { 0xFF, 0x59, 0x59, 0xff }; // FF5959
glm::vec4 type_color = { 0x84, 0x79, 0xe1, 0xff }; // 8479E1
if (!Dropdown_Console::initialize(consolas,
text_color * normalize_color_factor,
background_color * normalize_color_factor,
input_text_color * normalize_color_factor,
input_text_background_color * normalize_color_factor,
input_text_cursor_color * normalize_color_factor,
scroll_bar_background_color * normalize_color_factor,
scrool_bar_color * normalize_color_factor,
command_color * normalize_color_factor,
argument_color * normalize_color_factor,
type_color * normalize_color_factor))
{
fprintf(stderr, "[ERROR]: failed to initialize dropdown console\n");
return false;
}
Camera *camera = new Camera; // @todo(harlequin): memory system
f32 fov = 90.0f;
glm::vec3 camera_position = { 0.0f, 0.0f, 0.0f };
camera->initialize(camera_position, fov);
Event_System::register_event(EventType_Resize, on_resize);
// @todo(harlequin): game menu to add worlds
std::string world_name = "harlequin";
std::string world_path = "../assets/worlds/" + world_name;
World::initialize(world_path);
internal_data.platform = platform;
internal_data.camera = camera;
internal_data.should_update_camera = true;
internal_data.show_debug_stats_hud = false;
internal_data.is_running = true;
return true;
}
void Game::shutdown()
{
internal_data.is_running = false;
ECS::shutdown();
Physics::shutdown();
Job_System::wait_for_jobs_to_finish();
Job_System::shutdown();
Dropdown_Console::shutdown();
UI::shutdown();
Opengl_2D_Renderer::shutdown();
Opengl_Debug_Renderer::shutdown();
Opengl_Renderer::shutdown();
Event_System::shutdown();
Input::shutdown();
internal_data.platform->shutdown();
}
Game_Data Game::internal_data;
} | 32.159236 | 95 | 0.582393 | [
"render"
] |
7f3a6380e518a59356aa138c719ae2b080adb986 | 3,678 | cpp | C++ | Server-Client/Client/Client.cpp | Dina-Nashaat/Server-Client | 7bb2cce4dc2d37bbcdf49efc4ed817eb18fa1631 | [
"MIT"
] | null | null | null | Server-Client/Client/Client.cpp | Dina-Nashaat/Server-Client | 7bb2cce4dc2d37bbcdf49efc4ed817eb18fa1631 | [
"MIT"
] | null | null | null | Server-Client/Client/Client.cpp | Dina-Nashaat/Server-Client | 7bb2cce4dc2d37bbcdf49efc4ed817eb18fa1631 | [
"MIT"
] | null | null | null | // Client.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include <WinSock2.h>
#include <iostream>
#include <vector>
#pragma comment(lib,"ws2_32.lib")
#include "helper.h"
#include "RequestsProvider.h"
#define IPAddress "172.16.2.154"
int main()
{
//Winsock Startup
WSAData wsaData;
WORD DllVersion = MAKEWORD(2, 1);
if (WSAStartup(DllVersion, &wsaData) != 0) //If WSAStartup returns anything other than 0, then that means an error has occured in the WinSock Startup.
{
MessageBoxA(NULL, "Winsock startup failed", "Error", MB_OK | MB_ICONERROR);
exit(1);
}
SOCKADDR_IN addr; //Address to be binded to our Connection socket
int sizeofaddr = sizeof(addr); //Need sizeofaddr for the connect function
addr.sin_addr.s_addr = inet_addr(IPAddress); //Address
addr.sin_port = htons(1111); //Port = 1111
addr.sin_family = AF_INET; //IPv4 Socket
SOCKET Connection = socket(AF_INET, SOCK_STREAM, NULL); //Set Connection socket
vector<string> requests = getRequests();
array<string, 3> serverParams;
array<string, 3> clientParams;
string requestCommand; //GET or POST
string filename;
string hostname; //Server Name
for (int currentRequest = 0; currentRequest < requests.size(); currentRequest++) {
if (connect(Connection, (SOCKADDR*)&addr, sizeofaddr) != 0) //If we are unable to connect...
{
MessageBoxA(NULL, "Failed to Connect", "Error", MB_OK | MB_ICONERROR);
currentRequest--;
continue; //Failed to Connect
}
std::cout << "Magdy Connected!" << std::endl;
//Receive Permission Message from the server
char permission[256];
recv(Connection, permission, sizeof(permission), NULL);
std::cout << "Permission Response: " << permission << std::endl;
//Current Request to be sent to the server
char request[1024];
strncpy_s(request, requests[currentRequest].c_str(), sizeof(request));
request[sizeof(request) - 1] = 0;
std::cout << "Sending the Request: " << request << std::endl;
//Parse the request to be sent
clientParams = parseRequest(request);
requestCommand = clientParams[0];
filename = clientParams[1];
hostname = clientParams[2];
//Send the Request
Sleep(7000);
send(Connection, request, sizeof(request), NULL);
//Receives response from the server (in case of GET)
recv(Connection, request, sizeof(request), NULL);
std::cout << "Receiving Response: " << request;
if (requestCommand == "GET") {
//Check if 200 response or 404 response
serverParams = parseRequest(request);
if (!strcmp(serverParams[1].c_str(), "200")) {
//Receives length of file to be read
char buffer[1024];
recv(Connection, buffer, sizeof(buffer), NULL);
cout << "Content-Length: " << buffer << endl;
int contentLength = atoi(buffer);
//Recevies the file requested
char *bufferRecevier = new (nothrow) char[contentLength];
recv(Connection, bufferRecevier, contentLength, NULL);
//Write the file to the disk
writeFile(filename, bufferRecevier, contentLength);
cout << "File has been downloaded successfully." << endl;
}
}
else if (requestCommand == "POST") {
//Read the file from the disk
char *bufferSender;
int length;
readFile(filename, bufferSender, &length);
//Get & Send the file length
string strLength = to_string(length);
char bufferLength[1024];
strcpy_s(bufferLength, sizeof(bufferLength), strLength.c_str());
send(Connection, bufferLength, sizeof(bufferLength), NULL);
//Send the file
send(Connection, bufferSender, length, NULL);
}
cout << endl;
closesocket(Connection);
}
system("pause");
} | 31.169492 | 151 | 0.7031 | [
"vector"
] |
7f41db86bebeb0e0c15e71f4f715295a138c79c3 | 1,549 | cpp | C++ | tester/libtbag/math/EquationTest.cpp | osom8979/tbag | c31e2d884907d946df0836a70d8d5d69c4bf3c27 | [
"MIT"
] | 21 | 2016-04-05T06:08:41.000Z | 2022-03-28T10:20:22.000Z | tester/libtbag/math/EquationTest.cpp | osom8979/tbag | c31e2d884907d946df0836a70d8d5d69c4bf3c27 | [
"MIT"
] | null | null | null | tester/libtbag/math/EquationTest.cpp | osom8979/tbag | c31e2d884907d946df0836a70d8d5d69c4bf3c27 | [
"MIT"
] | 2 | 2019-07-16T00:37:21.000Z | 2021-11-10T06:14:09.000Z | /**
* @file EquationTest.cpp
* @brief Equation tester.
* @author zer0
* @date 2016-08-26
*/
#include <gtest/gtest.h>
#include <libtbag/math/Equation.hpp>
using namespace libtbag;
using namespace libtbag::math;
// ---------------
namespace __impl {
// ---------------
inline bool testIsCross(double p11x, double p11y, double p12x, double p12y, double p21x, double p21y, double p22x, double p22y)
{
using namespace libtbag::geometry;
Pointd const P11(p11x, p11y);
Pointd const P12(p12x, p12y);
Pointd const P21(p21x, p21y);
Pointd const P22(p22x, p22y);
Pointd cross;
return isCross<double, Pointd>(P11, P12, P21, P22, cross);
}
// ------------------
} // namespace __impl
// ------------------
TEST(EquationTest, GetLinearEquationWithTwoPoint)
{
auto e = getLinearEquationWithTwoPoint(1, 1, 2, 2);
ASSERT_EQ(1, e.a);
ASSERT_EQ(0, e.b);
}
TEST(EquationTest, IsParallelWithTwoLinearEquation)
{
LinearEquation<double> e1{2.4, 1};
LinearEquation<double> e2{2.4, 2};
ASSERT_TRUE(isParallelWithTwoLinearEquation(e1, e2));
}
TEST(EquationTest, GetIntersectionWithTwoLinearEquation)
{
LinearEquation<double> e1{ 2, 0};
LinearEquation<double> e2{-2, 2};
auto p = getIntersectionWithTwoLinearEquation(e1, e2);
ASSERT_NEAR(0.5, p.x, 0.1);
ASSERT_NEAR(1.0, p.y, 0.1);
}
TEST(EquationTest, IsCross)
{
ASSERT_TRUE(__impl::testIsCross(108, 53, 185, 144, 113.5, 61.5, 115.5, 61.5));
ASSERT_TRUE(__impl::testIsCross(201, 140, 113, 42, 135.5, 67.5, 137 , 67.5));
}
| 24.983871 | 127 | 0.652679 | [
"geometry"
] |
7f42015100a411c39324fe5cfa719dade951148d | 1,216 | cpp | C++ | cpp/src/main/filters/AvailabilityFilter.cpp | fbobee/Alpenglow | 5f956511017c1bee72390aaecd964c04d8ad4b45 | [
"Apache-2.0"
] | null | null | null | cpp/src/main/filters/AvailabilityFilter.cpp | fbobee/Alpenglow | 5f956511017c1bee72390aaecd964c04d8ad4b45 | [
"Apache-2.0"
] | null | null | null | cpp/src/main/filters/AvailabilityFilter.cpp | fbobee/Alpenglow | 5f956511017c1bee72390aaecd964c04d8ad4b45 | [
"Apache-2.0"
] | null | null | null | #include "AvailabilityFilter.h"
void AvailabilityFilter::run(RecDat* rec_dat){
double time = rec_dat->time;
while(availability_ends_.size() != 0 && get<0>(availability_ends_.top()) <= time){
auto item = availability_ends_.top();
availability_ends_.pop();
pair<int, double> npair = make_pair(get<1>(item), -1);
available_items_set_.erase(npair);
}
while(availabilites_.size() != 0 && get<0>(availabilites_.top()) <= time){
auto item = availabilites_.top();
availabilites_.pop();
pair<int, double> npair = make_pair(get<1>(item), -1);
available_items_set_.insert(npair);
availability_ends_.push(make_pair(get<0>(item)+get<2>(item), get<1>(item)));
}
available_items_ = vector<pair<int, double>>(available_items_set_.begin(), available_items_set_.end());
}
vector<pair<int,double>>* AvailabilityFilter::get_global_items(){
return &available_items_;
}
bool AvailabilityFilter::active(RecDat* r){
auto available = available_items_set_.find(make_pair(r->item, -1));
return available != available_items_set_.end();
}
void AvailabilityFilter::add_availability(double time, int id, int duration){
availabilites_.push(tuple<double, int, int>(time, id, duration));
}
| 36.848485 | 105 | 0.712993 | [
"vector"
] |
7f48281b71c05db78b299a3ec337571718d1a86a | 2,932 | cpp | C++ | examples/demoFlow.cpp | YcheParallelStudio/easyLambda | e496a3e3070b806e8c48124d3454543c4cebc9b7 | [
"BSL-1.0"
] | null | null | null | examples/demoFlow.cpp | YcheParallelStudio/easyLambda | e496a3e3070b806e8c48124d3454543c4cebc9b7 | [
"BSL-1.0"
] | null | null | null | examples/demoFlow.cpp | YcheParallelStudio/easyLambda | e496a3e3070b806e8c48124d3454543c4cebc9b7 | [
"BSL-1.0"
] | null | null | null | /*!
* @file
* demo for data-flow.
*
* Shows iterative data-flow pipeline, a diamond like pipeline with splitter
* followed by a joiner and other expressions such as addFlow, flow<>()...
* 
*
* Results are dumped on stdout.
* */
#include <iostream>
#include <stdexcept>
#include <tuple>
#include <vector>
#include <boost/mpi.hpp>
#include <ezl.hpp>
#include <ezl/algorithms/io.hpp>
#include <ezl/algorithms/filters.hpp>
// returns a map-flow that can be placed in a pipeline later
auto sqr() {
return ezl::flow<char, int>()
.map<2>([](int i) { return i * i; }).colsTransform()
.build();
}
void demoFlow() {
using std::vector;
using std::tuple;
using std::make_tuple;
vector<tuple<char, vector<int>>> buf;
buf.emplace_back(make_tuple('a', vector<int>{2}));
buf.emplace_back(make_tuple('b', vector<int>{3, 4, 5}));
auto pivot = sqr();
ezl::flow(pivot).run(); // doesn't do anything as there isn't a rise yet
// a circular pipeline, also showing a pipeline run inside a map.
auto ld = ezl::rise(ezl::fromMem(buf).split())
.map<2>([](const vector<int>& v) {
return ezl::rise(ezl::fromMem(v)).runResult();
}).colsTransform()
.addFlow(pivot) // adds the flow and continues adding to it
.filter<2>(ezl::gt(100)).dump()
.oneUp() // moves to adding to pivot again
.filter<2>(ezl::lt(100))
.addFlow(pivot)
.run();
// when recieving result as ref and returning a ref don't forget to put
// auto& as explicit return type of your lambda (I just saw the compile
// error for that)
auto joiner = ezl::flow<int, double>().reduce<1>(
[](int key, double val, tuple<vector<double>> &ret) -> auto& {
std::get<0>(ret).emplace_back(val);
return ret;
}, tuple<vector<double>>{}).ordered() // w/o ordered output rets reversed
.build();
// a pipeline with a splitter followed by a joiner
auto source = ezl::fromMem({4, 2, 1, 3, 5}).split();
auto flow1 = ezl::rise(source)
.branchFlow( // adds flow as a branch
ezl::flow<int>()
.map([](int x) { return double(x)/2.; })
.branchFlow(joiner)
.build()
)
.map([](int x) { return double(x*2); })
.addFlow(joiner)
.filter([](int, vector<double> halfnDouble) {
return true;
}).dump("", "number, (half, double)")
.run();
// running again
source = source.buffer({6 ,9 ,8 ,7});
ezl::flow(flow1).run();
}
int main(int argc, char *argv[]) {
boost::mpi::environment env(argc, argv, false);
try {
demoFlow();
} catch (const std::exception& ex) {
std::cerr<<"error: "<<ex.what()<<'\n';
env.abort(1);
} catch (...) {
std::cerr<<"unknown exception\n";
env.abort(2);
}
return 0;
}
| 29.616162 | 79 | 0.574352 | [
"vector"
] |
7f4f873aa6e78f6dacd45dcb50109005bc919d86 | 1,993 | cpp | C++ | test/testNet/testHttp/testHttpAcceptPatch/testAcceptPatchParse.cpp | wangsun1983/Obotcha | 2464e53599305703f5150df72bf73579a39d8ef4 | [
"MIT"
] | 27 | 2019-04-27T00:51:22.000Z | 2022-03-30T04:05:44.000Z | test/testNet/testHttp/testHttpAcceptPatch/testAcceptPatchParse.cpp | wangsun1983/Obotcha | 2464e53599305703f5150df72bf73579a39d8ef4 | [
"MIT"
] | 9 | 2020-05-03T12:17:50.000Z | 2021-10-15T02:18:47.000Z | test/testNet/testHttp/testHttpAcceptPatch/testAcceptPatchParse.cpp | wangsun1983/Obotcha | 2464e53599305703f5150df72bf73579a39d8ef4 | [
"MIT"
] | 1 | 2019-04-16T01:45:36.000Z | 2019-04-16T01:45:36.000Z | #include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include "Thread.hpp"
#include "Object.hpp"
#include "HttpMime.hpp"
#include "HttpAcceptPatch.hpp"
using namespace obotcha;
void testPatchParse() {
while(1) {
HttpAcceptPatch encoding1 = createHttpAcceptPatch();
encoding1->import("application/example, text/example");
auto encodings = encoding1->getAcceptPatches();
if(encodings->size() != 2) {
printf("---[HttpAcceptPatch test Parse case1] [FAILED]--- \n");
break;
}
if(!encodings->get(0)->type->equals("application/example")
|| !encodings->get(1)->type->equals("text/example")) {
printf("---[HttpAcceptPatch test Parse case2] [FAILED]--- \n");
break;
}
break;
}
while(1) {
HttpAcceptPatch encoding1 = createHttpAcceptPatch();
encoding1->import("text/example;charset=utf-8");
auto encodings = encoding1->getAcceptPatches();
if(encodings->size() != 1) {
printf("---[HttpAcceptPatch test Parse case3] [FAILED]--- \n");
break;
}
if(!encodings->get(0)->type->equals("text/example")) {
printf("---[HttpAcceptPatch test Parse case4] [FAILED]--- \n");
break;
}
if(!encodings->get(0)->charset->equals("utf-8")) {
printf("---[HttpAcceptPatch test Parse case4] [FAILED]--- \n");
break;
}
break;
}
while(1) {
HttpAcceptPatch encoding1 = createHttpAcceptPatch();
encoding1->import("application/merge-patch+json");
auto encodings = encoding1->getAcceptPatches();
if(encodings->size() != 1) {
printf("---[HttpAcceptPatch test Parse case5] [FAILED]--- \n");
break;
}
if(!encodings->get(0)->type->equals("application/merge-patch+json")) {
printf("---[HttpAcceptPatch test Parse case6] [FAILED]--- \n");
break;
}
break;
}
printf("---[HttpAcceptPatch test Parse case100] [OK]--- \n");
}
| 27.680556 | 75 | 0.587556 | [
"object"
] |
7f567d6acafd4985cfe1a517631696bc476f5da1 | 11,638 | cpp | C++ | Engine/Engine/bumpmodelclass.cpp | firatozbay/RasterTek_DirectX11_Series2 | 8596bde1cc2709eebc02d6b5845fd5ffa13ae209 | [
"MIT"
] | 1 | 2021-02-11T12:00:50.000Z | 2021-02-11T12:00:50.000Z | Engine/Engine/bumpmodelclass.cpp | firatozbay/RasterTek-DirectX11-Tutorials-Series2 | 8596bde1cc2709eebc02d6b5845fd5ffa13ae209 | [
"MIT"
] | null | null | null | Engine/Engine/bumpmodelclass.cpp | firatozbay/RasterTek-DirectX11-Tutorials-Series2 | 8596bde1cc2709eebc02d6b5845fd5ffa13ae209 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// Filename: bumpmodelclass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "bumpmodelclass.h"
BumpModelClass::BumpModelClass()
{
m_vertexBuffer = 0;
m_indexBuffer = 0;
m_model = 0;
m_ColorTexture = 0;
m_NormalMapTexture = 0;
}
BumpModelClass::BumpModelClass(const BumpModelClass& other)
{
}
BumpModelClass::~BumpModelClass()
{
}
bool BumpModelClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, char* modelFilename, WCHAR* textureFilename1, WCHAR* textureFilename2)
{
bool result;
// Load in the model data,
result = LoadModel(modelFilename);
if (!result)
{
return false;
}
// Calculate the tangent and binormal vectors for the model.
CalculateModelVectors();
// Initialize the vertex and index buffers.
result = InitializeBuffers(device);
if (!result)
{
return false;
}
// Load the textures for this model.
result = LoadTextures(device, deviceContext, textureFilename1, textureFilename2);
if (!result)
{
return false;
}
return true;
}
void BumpModelClass::Shutdown()
{
// Release the model textures.
ReleaseTextures();
// Shutdown the vertex and index buffers.
ShutdownBuffers();
// Release the model data.
ReleaseModel();
return;
}
void BumpModelClass::Render(ID3D11DeviceContext* deviceContext)
{
// Put the vertex and index buffers on the graphics pipeline to prepare them for drawing.
RenderBuffers(deviceContext);
return;
}
int BumpModelClass::GetIndexCount()
{
return m_indexCount;
}
ID3D11ShaderResourceView* BumpModelClass::GetColorTexture()
{
return m_ColorTexture->GetTexture();
}
ID3D11ShaderResourceView* BumpModelClass::GetNormalMapTexture()
{
return m_NormalMapTexture->GetTexture();
}
bool BumpModelClass::InitializeBuffers(ID3D11Device* device)
{
VertexType* vertices;
unsigned long* indices;
D3D11_BUFFER_DESC vertexBufferDesc, indexBufferDesc;
D3D11_SUBRESOURCE_DATA vertexData, indexData;
HRESULT result;
int i;
// Create the vertex array.
vertices = new VertexType[m_vertexCount];
if (!vertices)
{
return false;
}
// Create the index array.
indices = new unsigned long[m_indexCount];
if (!indices)
{
return false;
}
// Load the vertex array and index array with data.
for (i = 0; i<m_vertexCount; i++)
{
vertices[i].position = XMFLOAT3(m_model[i].x, m_model[i].y, m_model[i].z);
vertices[i].texture = XMFLOAT2(m_model[i].tu, m_model[i].tv);
vertices[i].normal = XMFLOAT3(m_model[i].nx, m_model[i].ny, m_model[i].nz);
vertices[i].tangent = XMFLOAT3(m_model[i].tx, m_model[i].ty, m_model[i].tz);
vertices[i].binormal = XMFLOAT3(m_model[i].bx, m_model[i].by, m_model[i].bz);
indices[i] = i;
}
// Set up the description of the static vertex buffer.
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
vertexBufferDesc.ByteWidth = sizeof(VertexType) * m_vertexCount;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
// Give the subresource structure a pointer to the vertex data.
vertexData.pSysMem = vertices;
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;
// Now create the vertex buffer.
result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &m_vertexBuffer);
if (FAILED(result))
{
return false;
}
// Set up the description of the static index buffer.
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(unsigned long) * m_indexCount;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
indexBufferDesc.StructureByteStride = 0;
// Give the subresource structure a pointer to the index data.
indexData.pSysMem = indices;
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;
// Create the index buffer.
result = device->CreateBuffer(&indexBufferDesc, &indexData, &m_indexBuffer);
if (FAILED(result))
{
return false;
}
// Release the arrays now that the vertex and index buffers have been created and loaded.
delete[] vertices;
vertices = 0;
delete[] indices;
indices = 0;
return true;
}
void BumpModelClass::ShutdownBuffers()
{
// Release the index buffer.
if (m_indexBuffer)
{
m_indexBuffer->Release();
m_indexBuffer = 0;
}
// Release the vertex buffer.
if (m_vertexBuffer)
{
m_vertexBuffer->Release();
m_vertexBuffer = 0;
}
return;
}
void BumpModelClass::RenderBuffers(ID3D11DeviceContext* deviceContext)
{
unsigned int stride;
unsigned int offset;
// Set vertex buffer stride and offset.
stride = sizeof(VertexType);
offset = 0;
// Set the vertex buffer to active in the input assembler so it can be rendered.
deviceContext->IASetVertexBuffers(0, 1, &m_vertexBuffer, &stride, &offset);
// Set the index buffer to active in the input assembler so it can be rendered.
deviceContext->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0);
// Set the type of primitive that should be rendered from this vertex buffer, in this case triangles.
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
return;
}
bool BumpModelClass::LoadTextures(ID3D11Device* device, ID3D11DeviceContext* deviceContext, WCHAR* filename1, WCHAR* filename2)
{
bool result;
// Create the color texture object.
m_ColorTexture = new TextureClass;
if (!m_ColorTexture)
{
return false;
}
// Initialize the color texture object.
result = m_ColorTexture->Initialize(device, deviceContext, filename1);
if (!result)
{
return false;
}
// Create the normal map texture object.
m_NormalMapTexture = new TextureClass;
if (!m_NormalMapTexture)
{
return false;
}
// Initialize the normal map texture object.
result = m_NormalMapTexture->Initialize(device, deviceContext, filename2);
if (!result)
{
return false;
}
return true;
}
void BumpModelClass::ReleaseTextures()
{
// Release the texture objects.
if (m_ColorTexture)
{
m_ColorTexture->Shutdown();
delete m_ColorTexture;
m_ColorTexture = 0;
}
if (m_NormalMapTexture)
{
m_NormalMapTexture->Shutdown();
delete m_NormalMapTexture;
m_NormalMapTexture = 0;
}
return;
}
bool BumpModelClass::LoadModel(char* filename)
{
ifstream fin;
char input;
int i;
// Open the model file. If it could not open the file then exit.
fin.open(filename);
if (fin.fail())
{
return false;
}
// Read up to the value of vertex count.
fin.get(input);
while (input != ':')
{
fin.get(input);
}
// Read in the vertex count.
fin >> m_vertexCount;
// Set the number of indices to be the same as the vertex count.
m_indexCount = m_vertexCount;
// Create the model using the vertex count that was read in.
m_model = new ModelType[m_vertexCount];
if (!m_model)
{
return false;
}
// Read up to the beginning of the data.
fin.get(input);
while (input != ':')
{
fin.get(input);
}
fin.get(input);
fin.get(input);
// Read in the vertex data.
for (i = 0; i<m_vertexCount; i++)
{
fin >> m_model[i].x >> m_model[i].y >> m_model[i].z;
fin >> m_model[i].tu >> m_model[i].tv;
fin >> m_model[i].nx >> m_model[i].ny >> m_model[i].nz;
}
// Close the model file.
fin.close();
return true;
}
void BumpModelClass::ReleaseModel()
{
if (m_model)
{
delete[] m_model;
m_model = 0;
}
return;
}
void BumpModelClass::CalculateModelVectors()
{
int faceCount, i, index;
TempVertexType vertex1, vertex2, vertex3;
VectorType tangent, binormal;
// Calculate the number of faces in the model.
faceCount = m_vertexCount / 3;
// Initialize the index to the model data.
index = 0;
// Go through all the faces and calculate the the tangent, binormal, and normal vectors.
for (i = 0; i<faceCount; i++)
{
// Get the three vertices for this face from the model.
vertex1.x = m_model[index].x;
vertex1.y = m_model[index].y;
vertex1.z = m_model[index].z;
vertex1.tu = m_model[index].tu;
vertex1.tv = m_model[index].tv;
vertex1.nx = m_model[index].nx;
vertex1.ny = m_model[index].ny;
vertex1.nz = m_model[index].nz;
index++;
vertex2.x = m_model[index].x;
vertex2.y = m_model[index].y;
vertex2.z = m_model[index].z;
vertex2.tu = m_model[index].tu;
vertex2.tv = m_model[index].tv;
vertex2.nx = m_model[index].nx;
vertex2.ny = m_model[index].ny;
vertex2.nz = m_model[index].nz;
index++;
vertex3.x = m_model[index].x;
vertex3.y = m_model[index].y;
vertex3.z = m_model[index].z;
vertex3.tu = m_model[index].tu;
vertex3.tv = m_model[index].tv;
vertex3.nx = m_model[index].nx;
vertex3.ny = m_model[index].ny;
vertex3.nz = m_model[index].nz;
index++;
// Calculate the tangent and binormal of that face.
CalculateTangentBinormal(vertex1, vertex2, vertex3, tangent, binormal);
// Store the normal, tangent, and binormal for this face back in the model structure.
m_model[index - 1].tx = tangent.x;
m_model[index - 1].ty = tangent.y;
m_model[index - 1].tz = tangent.z;
m_model[index - 1].bx = binormal.x;
m_model[index - 1].by = binormal.y;
m_model[index - 1].bz = binormal.z;
m_model[index - 2].tx = tangent.x;
m_model[index - 2].ty = tangent.y;
m_model[index - 2].tz = tangent.z;
m_model[index - 2].bx = binormal.x;
m_model[index - 2].by = binormal.y;
m_model[index - 2].bz = binormal.z;
m_model[index - 3].tx = tangent.x;
m_model[index - 3].ty = tangent.y;
m_model[index - 3].tz = tangent.z;
m_model[index - 3].bx = binormal.x;
m_model[index - 3].by = binormal.y;
m_model[index - 3].bz = binormal.z;
}
return;
}
void BumpModelClass::CalculateTangentBinormal(TempVertexType vertex1, TempVertexType vertex2, TempVertexType vertex3,
VectorType& tangent, VectorType& binormal)
{
float vector1[3], vector2[3];
float tuVector[2], tvVector[2];
float den;
float length;
// Calculate the two vectors for this face.
vector1[0] = vertex2.x - vertex1.x;
vector1[1] = vertex2.y - vertex1.y;
vector1[2] = vertex2.z - vertex1.z;
vector2[0] = vertex3.x - vertex1.x;
vector2[1] = vertex3.y - vertex1.y;
vector2[2] = vertex3.z - vertex1.z;
// Calculate the tu and tv texture space vectors.
tuVector[0] = vertex2.tu - vertex1.tu;
tvVector[0] = vertex2.tv - vertex1.tv;
tuVector[1] = vertex3.tu - vertex1.tu;
tvVector[1] = vertex3.tv - vertex1.tv;
// Calculate the denominator of the tangent/binormal equation.
den = 1.0f / (tuVector[0] * tvVector[1] - tuVector[1] * tvVector[0]);
// Calculate the cross products and multiply by the coefficient to get the tangent and binormal.
tangent.x = (tvVector[1] * vector1[0] - tvVector[0] * vector2[0]) * den;
tangent.y = (tvVector[1] * vector1[1] - tvVector[0] * vector2[1]) * den;
tangent.z = (tvVector[1] * vector1[2] - tvVector[0] * vector2[2]) * den;
binormal.x = (tuVector[0] * vector2[0] - tuVector[1] * vector1[0]) * den;
binormal.y = (tuVector[0] * vector2[1] - tuVector[1] * vector1[1]) * den;
binormal.z = (tuVector[0] * vector2[2] - tuVector[1] * vector1[2]) * den;
// Calculate the length of this normal.
length = sqrt((tangent.x * tangent.x) + (tangent.y * tangent.y) + (tangent.z * tangent.z));
// Normalize the normal and then store it
tangent.x = tangent.x / length;
tangent.y = tangent.y / length;
tangent.z = tangent.z / length;
// Calculate the length of this normal.
length = sqrt((binormal.x * binormal.x) + (binormal.y * binormal.y) + (binormal.z * binormal.z));
// Normalize the normal and then store it
binormal.x = binormal.x / length;
binormal.y = binormal.y / length;
binormal.z = binormal.z / length;
return;
} | 23.702648 | 160 | 0.697027 | [
"render",
"object",
"model"
] |
7f5ed5d6f0132333869c3336d4106ac4c631a01b | 4,790 | hxx | C++ | main/svx/inc/svx/svdhlpln.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/svx/inc/svx/svdhlpln.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/svx/inc/svx/svdhlpln.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _SVDHLPLN_HXX
#define _SVDHLPLN_HXX
#include <sal/types.h>
#include <tools/color.hxx>
#include <tools/gen.hxx>
#ifndef _POINTR_HXX //autogen
#include <vcl/pointr.hxx>
#endif
#include <tools/contnr.hxx>
#include "svx/svxdllapi.h"
class OutputDevice;
////////////////////////////////////////////////////////////////////////////////////////////////////
enum SdrHelpLineKind {SDRHELPLINE_POINT,SDRHELPLINE_VERTICAL,SDRHELPLINE_HORIZONTAL};
#define SDRHELPLINE_MIN SDRHELPLINE_POINT
#define SDRHELPLINE_MAX SDRHELPLINE_HORIZONTAL
#define SDRHELPLINE_POINT_PIXELSIZE 15 /* Tatsaechliche Groesse= PIXELSIZE*2+1 */
class SdrHelpLine {
Point aPos; // je nach Wert von eKind ist X oder Y evtl. belanglos
SdrHelpLineKind eKind;
// #i27493#
// Helper method to draw a hor or ver two-colored dashed line
void ImpDrawDashedTwoColorLine(OutputDevice& rOut, sal_Int32 nStart, sal_Int32 nEnd, sal_Int32 nFixPos,
sal_Int32 nStepWidth, Color aColA, Color aColB, sal_Bool bHorizontal) const;
public:
SdrHelpLine(SdrHelpLineKind eNewKind=SDRHELPLINE_POINT): eKind(eNewKind) {}
SdrHelpLine(SdrHelpLineKind eNewKind, const Point& rNewPos): aPos(rNewPos), eKind(eNewKind) {}
bool operator==(const SdrHelpLine& rCmp) const { return aPos==rCmp.aPos && eKind==rCmp.eKind; }
bool operator!=(const SdrHelpLine& rCmp) const { return !operator==(rCmp); }
void SetKind(SdrHelpLineKind eNewKind) { eKind=eNewKind; }
SdrHelpLineKind GetKind() const { return eKind; }
void SetPos(const Point& rPnt) { aPos=rPnt; }
const Point& GetPos() const { return aPos; }
Pointer GetPointer() const;
FASTBOOL IsHit(const Point& rPnt, sal_uInt16 nTolLog, const OutputDevice& rOut) const;
// OutputDevice wird benoetigt, da Fangpunkte eine feste Pixelgroesse haben
Rectangle GetBoundRect(const OutputDevice& rOut) const;
/* returns true if this and the given help line would be rendered at the same pixel position
of the given OutputDevice. This can be used to avoid drawing multiple help lines with xor
on same position which could render them invisible */
bool IsVisibleEqual( const SdrHelpLine& rHelpLine, const OutputDevice& rOut ) const;
};
#define SDRHELPLINE_NOTFOUND 0xFFFF
class SVX_DLLPUBLIC SdrHelpLineList {
Container aList;
protected:
SdrHelpLine* GetObject(sal_uInt16 i) const { return (SdrHelpLine*)(aList.GetObject(i)); }
public:
SdrHelpLineList(): aList(1024,4,4) {}
SdrHelpLineList(const SdrHelpLineList& rSrcList): aList(1024,4,4) { *this=rSrcList; }
~SdrHelpLineList() { Clear(); }
void Clear();
void operator=(const SdrHelpLineList& rSrcList);
bool operator==(const SdrHelpLineList& rCmp) const;
bool operator!=(const SdrHelpLineList& rCmp) const { return !operator==(rCmp); }
sal_uInt16 GetCount() const { return sal_uInt16(aList.Count()); }
void Insert(const SdrHelpLine& rHL, sal_uInt16 nPos=0xFFFF) { aList.Insert(new SdrHelpLine(rHL),nPos); }
void Delete(sal_uInt16 nPos) { delete (SdrHelpLine*)aList.Remove(nPos); } // #i24900#
void Move(sal_uInt16 nPos, sal_uInt16 nNewPos) { aList.Insert(aList.Remove(nPos),nNewPos); }
SdrHelpLine& operator[](sal_uInt16 nPos) { return *GetObject(nPos); }
const SdrHelpLine& operator[](sal_uInt16 nPos) const { return *GetObject(nPos); }
sal_uInt16 HitTest(const Point& rPnt, sal_uInt16 nTolLog, const OutputDevice& rOut) const;
};
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //_SVDHLPLN_HXX
| 46.057692 | 132 | 0.645094 | [
"render"
] |
7f6f06d7d7ffb3b10564a8821fd0bee3fbbd5354 | 2,570 | cpp | C++ | src/c99/3d.cpp | kochol/ari2 | ca185191531acc1954cd4acfec2137e32fdb5c2d | [
"MIT"
] | 81 | 2018-12-11T20:48:41.000Z | 2022-03-18T22:24:11.000Z | src/c99/3d.cpp | kochol/ari2 | ca185191531acc1954cd4acfec2137e32fdb5c2d | [
"MIT"
] | 7 | 2020-04-19T11:50:39.000Z | 2021-11-12T16:08:53.000Z | src/c99/3d.cpp | kochol/ari2 | ca185191531acc1954cd4acfec2137e32fdb5c2d | [
"MIT"
] | 4 | 2019-04-24T11:51:29.000Z | 2021-03-10T05:26:33.000Z | #include "3d.h"
#include "3d/Camera.hpp"
#include "3d/BoxShape.hpp"
#include "3d/RenderSystem.hpp"
#include "3d/SceneSystem.hpp"
// System functions
void* CreateRenderSystem()
{
return ari::core::Memory::New<ari::en::RenderSystem>();
}
void* CreateSceneSystem()
{
return ari::core::Memory::New<ari::en::SceneSystem>();
}
// Node3D
bool IsValidNode3D(uint32_t& _handle)
{
return ari::core::HandleManager<ari::en::Node3D>::IsHandleValid(_handle);
}
Node3dMembers GetNode3dMembers(void* _node)
{
auto node = reinterpret_cast<ari::en::Node3D*>(_node);
return { reinterpret_cast<Vector3*>(&node->Position),
reinterpret_cast<Quat*>(&node->Rotation),
reinterpret_cast<Vector3*>(&node->Scale) };
}
// Camera
Node3dHandle CreateCameraComponent()
{
const auto c = ari::en::World::CreateComponent<ari::en::Camera, ari::en::Node3D>();
return { c.Handle, c.Index, c.Component, c.Owner };
}
void AddCameraToWorld(void* _world, EntityHandle* _entity, const Node3dHandle& _camera)
{
union { Node3dHandle c{}; ari::en::ComponentHandle<ari::en::Camera> cpp; } cam = { _camera };
const union { EntityHandle c{}; ari::en::EntityHandle cpp; } en = { *_entity };
reinterpret_cast<ari::en::World*>(_world)->AddDerivedComponent<ari::en::Camera, ari::en::Node3D>(en.cpp, cam.cpp);
}
CameraMembers GetCameraMembers(void* _node)
{
auto node = reinterpret_cast<ari::en::Camera*>(_node);
return {
reinterpret_cast<Vector3*>(&node->Target),
reinterpret_cast<Vector3*>(&node->Up),
reinterpret_cast<Vector3*>(&node->Right),
&node->AspectRatio,
&node->Fov,
&node->xMag,
&node->yMag,
&node->zNear,
&node->zFar,
};
}
// BoxShape
Node3dHandle CreateBoxShapeComponent()
{
const auto c = ari::en::World::CreateComponent<ari::en::BoxShape, ari::en::Node3D>();
return { c.Handle, c.Index, c.Component, c.Owner };
}
void AddBoxShapeToWorld(void* _world, EntityHandle* _entity, const Node3dHandle& _box)
{
union { Node3dHandle c{}; ari::en::ComponentHandle<ari::en::BoxShape> cpp; } box = { _box };
const union { EntityHandle c{}; ari::en::EntityHandle cpp; } en = { *_entity };
reinterpret_cast<ari::en::World*>(_world)->AddDerivedComponent<ari::en::BoxShape, ari::en::Node3D>(en.cpp, box.cpp);
}
BoxShapeMembers GetBoxShapeMembers(void* _node)
{
auto node = reinterpret_cast<ari::en::BoxShape*>(_node);
return {
reinterpret_cast<TextureHandle*>(&node->Texture),
reinterpret_cast<SubMeshHandle*>(&node->SubMesh)
};
} | 30.963855 | 120 | 0.66965 | [
"3d"
] |
7f7b010feba5188bcccbb70083f7c04f4e4007dc | 4,202 | cpp | C++ | libs/gui/src/init.cpp | alex-tdrn/renderdeck | 0f5d020b154d4a426f73e31d6e62901ee790550b | [
"MIT"
] | null | null | null | libs/gui/src/init.cpp | alex-tdrn/renderdeck | 0f5d020b154d4a426f73e31d6e62901ee790550b | [
"MIT"
] | null | null | null | libs/gui/src/init.cpp | alex-tdrn/renderdeck | 0f5d020b154d4a426f73e31d6e62901ee790550b | [
"MIT"
] | null | null | null | #include "clk/gui/init.hpp"
#include "clk/base/graph.hpp"
#include "clk/gui/panel.hpp"
#include "clk/gui/widgets/graph_editor.hpp"
#include "clk/gui/widgets/graph_viewer.hpp"
#include "clk/gui/widgets/profiler_editor.hpp"
#include "clk/gui/widgets/widget.hpp"
#include "clk/gui/widgets/widget_factory.hpp"
#include "clk/gui/widgets/widget_tree.hpp"
#include "clk/util/profiler.hpp"
#include "clk/util/type_list.hpp"
#include <chrono>
#include <glm/glm.hpp>
#include <imgui.h>
#include <range/v3/algorithm/find.hpp>
#include <range/v3/algorithm/remove_if.hpp>
#include <range/v3/functional/identity.hpp>
#include <string_view>
#include <type_traits>
#include <utility>
#include <vector>
namespace clk
{
class color_rgb;
class color_rgba;
template <typename T>
class bounded;
} // namespace clk
namespace clk::gui
{
template <typename data_type>
class editor_of;
template <typename data_type>
class viewer_of;
auto create_default_factory() -> std::shared_ptr<widget_factory>
{
auto factory = std::make_shared<widget_factory>();
using default_types = meta::type_list<bool, int, float, glm::vec2, glm::vec3, glm::vec4, clk::bounded<int>,
clk::bounded<float>, clk::bounded<glm::vec2>, clk::bounded<glm::vec3>, clk::bounded<glm::vec4>, clk::color_rgb,
clk::color_rgba, std::chrono::nanoseconds>;
default_types::for_each([&](auto* dummy) {
using current_type = std::remove_cv_t<std::remove_pointer_t<decltype(dummy)>>;
factory->register_viewer<current_type, viewer_of<current_type>>();
factory->register_editor<current_type, editor_of<current_type>>();
});
factory->register_viewer<clk::graph, graph_viewer>();
factory->register_editor<clk::profiler, profiler_editor>();
factory->register_editor<clk::graph, graph_editor>();
return factory;
}
void draw()
{
ImGuiViewport* viewport = ImGui::GetMainViewport();
ImGui::SetNextWindowPos(viewport->Pos);
ImGui::SetNextWindowSize(viewport->Size);
ImGui::SetNextWindowViewport(viewport->ID);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
ImGuiWindowFlags window_flags = ImGuiWindowFlags_MenuBar;
window_flags |= ImGuiWindowFlags_NoDocking;
window_flags |= ImGuiWindowFlags_NoTitleBar;
window_flags |= ImGuiWindowFlags_NoCollapse;
window_flags |= ImGuiWindowFlags_NoResize;
window_flags |= ImGuiWindowFlags_NoMove;
window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus;
window_flags |= ImGuiWindowFlags_NoNavFocus;
ImGui::Begin("Main Window", nullptr, window_flags);
ImGui::PopStyleVar(3);
ImGuiID dockspace_id = ImGui::GetID("Main Window Dockspace");
ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), ImGuiDockNodeFlags_None);
if(ImGui::BeginMenuBar())
{
if(ImGui::BeginMenu("View"))
{
for(auto* panel : clk::gui::panel::_all_panels)
if(ImGui::MenuItem(panel->title().data(), "", panel->visible()))
panel->toggle_visibility();
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
ImGui::End();
for(auto* panel : panel::_all_panels)
panel->draw();
for(auto [panel_id, action] : panel::_queued_actions)
{
auto it = ranges::find(panel::_all_panels, panel_id, &panel::_id);
if(it == panel::_all_panels.end())
continue;
auto* panel = *it;
switch(action)
{
case panel::action_type::duplicate:
{
auto copy = *panel;
panel::orphan(std::move(copy));
break;
}
case panel::action_type::remove:
{
panel::_orphaned_panels.erase(ranges::remove_if(panel::_orphaned_panels,
[panel](auto const& other) {
return other._id == panel->_id;
}),
panel::_orphaned_panels.end());
break;
}
case panel::action_type::extract_widget_settings:
{
if(panel->widget() != nullptr)
{
if(auto const* settings = panel->widget()->get_settings(); settings != nullptr)
{
auto clone = settings->clone();
static_cast<widget_tree*>(clone.get())->set_draw_mode(widget_tree::draw_mode::tree_nodes);
panel->add_child_panel(clk::gui::panel(std::move(clone)));
}
}
break;
}
}
}
panel::_queued_actions.clear();
}
} // namespace clk::gui | 29.384615 | 113 | 0.716326 | [
"vector"
] |
7f7c6f42c2b803c7bb424010e8da216511ab8c37 | 857 | cpp | C++ | src/CJExecThrow.cpp | colinw7/CJavaScript | 9ab75280421927d74ffbc1c1b82a2cd6a02942b7 | [
"MIT"
] | 2 | 2016-07-20T13:35:32.000Z | 2021-12-23T02:21:19.000Z | src/CJExecThrow.cpp | colinw7/CJavaScript | 9ab75280421927d74ffbc1c1b82a2cd6a02942b7 | [
"MIT"
] | null | null | null | src/CJExecThrow.cpp | colinw7/CJavaScript | 9ab75280421927d74ffbc1c1b82a2cd6a02942b7 | [
"MIT"
] | 2 | 2019-04-01T13:12:10.000Z | 2019-04-01T13:47:44.000Z | #include <CJExecThrow.h>
#include <CJExecExpression.h>
#include <CJavaScript.h>
#include <CJError.h>
CJExecThrow::
CJExecThrow() :
CJToken(CJToken::Type::Throw)
{
}
CJValueP
CJExecThrow::
exec(CJavaScript *js)
{
// evaluate expression
CJValueP value;
if (expr_)
value = expr_->exec(js);
// create error object (if not one already)
CJErrorBaseP perror;
if (value && value->isError()) {
perror = CJValue::cast<CJErrorBase>(value);
}
else {
CJError *error = new CJError(js);
error->setValue(value);
perror = CJErrorBaseP(error);
}
// throw error
js->throwError(this, perror);
return CJValueP();
}
std::string
CJExecThrow::
toString() const
{
std::ostringstream ss; ss << *this;
return ss.str();
}
void
CJExecThrow::
print(std::ostream &os) const
{
if (expr_) {
os << "throw " << *expr_;
}
}
| 14.525424 | 47 | 0.645274 | [
"object"
] |
7f85e2bc369c003eb2f66f9758c4c1757e36200b | 971 | cpp | C++ | something-learned/Algorithms and Data-Structures/Competitive-programming-library/CP/codechef/June Challenge 17/SUMQ.cpp | gopala-kr/CR-101 | dd27b767cdc0c667655ab8e32e020ed4248bd112 | [
"MIT"
] | 5 | 2018-05-09T04:02:04.000Z | 2021-02-21T19:27:56.000Z | something-learned/Algorithms and Data-Structures/Competitive-programming-library/CP/codechef/June Challenge 17/SUMQ.cpp | gopala-kr/CR-101 | dd27b767cdc0c667655ab8e32e020ed4248bd112 | [
"MIT"
] | null | null | null | something-learned/Algorithms and Data-Structures/Competitive-programming-library/CP/codechef/June Challenge 17/SUMQ.cpp | gopala-kr/CR-101 | dd27b767cdc0c667655ab8e32e020ed4248bd112 | [
"MIT"
] | 5 | 2018-02-23T22:08:28.000Z | 2020-08-19T08:31:47.000Z | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
while(t--) {
long p,q,r;
cin>>p>>q>>r;
vector<long long> a(p),b(q),c(r);
for(long i=0;i<p;i++)
scanf("%lld", &a[i]);
for(long i=0;i<q;i++)
scanf("%lld", &b[i]);
for(long i=0;i<r;i++)
scanf("%lld", &c[i]);
sort(a.begin(),a.end());
sort(b.begin(),b.end());
sort(c.begin(),c.end());
long long mod = 1000000007;
long i,k;
i=k=0;
long long sumi, sumk;
sumi=sumk=0;
long long ans = 0;
for(long j=0;j<b.size();j++) {
while(i < p && a[i] <= b[j]) {
sumi += a[i];
i++;
}
while(k < r && c[k] <= b[j]) {
sumk += c[k];
k++;
}
sumi %= mod;
sumk %= mod;
long long prod = i;
prod *= k;
prod %= mod;
ans += (((prod*b[j])%mod)*b[j])%mod;
ans += (((sumi*k)%mod)*b[j])%mod;
ans %=mod;
ans += (((sumk*i)%mod)*b[j])%mod;
ans %=mod;
ans += (sumk*sumi)%mod;
ans %=mod;
}
printf("%lld\n",ans);
}
return 0;
} | 19.42 | 39 | 0.467559 | [
"vector"
] |
7f8832175e4f3b5deff7b51c40fd8f7371f01d35 | 5,748 | cpp | C++ | src/Hadoucan_IO_mgr.cpp | suburbanembedded/hadoucan_util | 35295189d35bffbb661d7102c48c2cfeb80513c3 | [
"BSD-3-Clause"
] | null | null | null | src/Hadoucan_IO_mgr.cpp | suburbanembedded/hadoucan_util | 35295189d35bffbb661d7102c48c2cfeb80513c3 | [
"BSD-3-Clause"
] | 3 | 2020-07-02T03:35:36.000Z | 2020-07-06T18:49:31.000Z | src/Hadoucan_IO_mgr.cpp | suburbanembedded/hadoucan_util | 35295189d35bffbb661d7102c48c2cfeb80513c3 | [
"BSD-3-Clause"
] | null | null | null | /**
* @brief Hadoucan_IO_mgr
* @author Nicholas Schloss <nicholas.schloss@suburbanmarine.io>
* @copyright Copyright (c) 2020 Suburban Marine, Inc. All rights reserved.
* @license Licensed under the 3-Clause BSD license. See LICENSE for details
*/
#include "hadoucan_util/Hadoucan_IO_mgr.hpp"
#include "hadoucan_util/lawicel_linux_conversions.hpp"
#include "hadoucan_util/lin_can_helper.hpp"
#include "hadoucan_util/error_handling.hpp"
#include <fcntl.h>
#include <iostream>
#include <functional>
#include <vector>
#include <deque>
#include <fstream>
#include <boost/date_time.hpp>
/*----------------------------- HADOUCAN serial port management class ------------------------*/
Hadoucan_IO_mgr::Hadoucan_IO_mgr(bool set_timestamp)
{
serial_fh = -1;
timeout = std::chrono::milliseconds(10);
max_str_length = 140;
timestamp = set_timestamp;
if(timestamp)
{
max_str_length = 144;
}
}
Hadoucan_IO_mgr::~Hadoucan_IO_mgr()
{
end_read_thread_func();
close_filehandle();
}
bool Hadoucan_IO_mgr::set_termios_attr()
{
cfmakeraw(&t);
t.c_lflag &= ~ICANON;
t.c_cc[VMIN] = 0;
t.c_cc[VTIME] = 1;
if(tcsetattr(serial_fh, TCSAFLUSH, &t) != 0)
{
printf("Failed to set termios attributes\n");
return false;
}
return true;
}
bool Hadoucan_IO_mgr::set_filehandle(int filehandle){
if(filehandle < 0)
{
printf("Error, invalid filehandle\n");
return false;
}
serial_fh = filehandle;
if(!set_termios_attr())
{
return false;
}
read_thread = boost::thread(std::bind(&Hadoucan_IO_mgr::read_thread_func, this));
return true;
}
bool Hadoucan_IO_mgr::open_filehandle(std::string file_path){
serial_fh = open(file_path.data(), O_RDWR | O_NOCTTY);
if(serial_fh < 0)
{
printf("Error opening device %s\n", file_path.data());
std::cout << get_errno_msg() << "\n";
return false;
}
if(!set_termios_attr())
{
return false;
}
return true;
}
bool Hadoucan_IO_mgr::close_filehandle(){
int ret = close(serial_fh);
if(ret < 0)
{
printf("Error closing serial port\n");
return false;
}
return true;
}
bool Hadoucan_IO_mgr::send_packet(const std::string& msg)
{
bool success = true;
size_t bytes_written = 0;
do{
ssize_t ret = write(serial_fh, msg.data(), msg.size());
if(ret == -1)
{
if(errno != EINTR)
{
success = false;
break;
}
continue;
}
bytes_written += ret;
}while(bytes_written < msg.size());
tcflush(serial_fh, TCOFLUSH);
return success;
}
bool Hadoucan_IO_mgr::send_packet(canfd_frame frame, size_t mtu)
{
std::string packet;
if(!linux_to_lawicel(&frame, mtu, &packet))
{
printf("string to CAN frame conversion failed\n");
return false;
}
bool success = true;
size_t bytes_written = 0;
do{
ssize_t ret = write(serial_fh, packet.data(), packet.size());
if(ret == -1)
{
if(errno != EINTR)
{
success = false;
break;
}
continue;
}
bytes_written += ret;
}while(bytes_written < packet.size());
tcflush(serial_fh, TCOFLUSH);
return success;
}
bool Hadoucan_IO_mgr::read_queue_not_empty() const
{
return !in_packet_queue.empty();
}
bool Hadoucan_IO_mgr::get_packet(std::chrono::milliseconds max_wait, Linux_can *obj_frame)
{
std::unique_lock<std::mutex> lock(in_packet_queue_mutex);
if(!in_packet_queue_condvar.wait_for(lock, max_wait, std::bind(&Hadoucan_IO_mgr::read_queue_not_empty, this)))
{
return false;
}
obj_frame->fd_frame = in_packet_queue.front()->fd_frame;
obj_frame->mtu = in_packet_queue.front()->mtu;
obj_frame->time_Read = in_packet_queue.front()->time_Read;
in_packet_queue.pop_front();
return true;
}
void Hadoucan_IO_mgr::begin_read_thread_func()
{
read_thread = boost::thread(std::bind(&Hadoucan_IO_mgr::read_thread_func, this));
}
void Hadoucan_IO_mgr::read_thread_func()
{
std::vector<char> buffer;
buffer.resize(2048);
while(true)
{
boost::this_thread::interruption_point();
const int nbytes = read(serial_fh, buffer.data(), buffer.size());
const std::string time_of_read = to_simple_string(boost::posix_time::microsec_clock::local_time());
if(nbytes == -1)
{
if(errno != EINTR)
{
printf("Failed to read from serial buffer\n");
return;
}
continue;
}
in_byte_queue.insert(in_byte_queue.end(), buffer.data(), buffer.data()+nbytes);
std::string packet;
packet.reserve(256);
while(!in_byte_queue.empty())
{
switch(std::toupper(in_byte_queue.front()))
{
case 'T':
case 'D':
case 'B':
case 'R':
{
break;
}
default :
{
in_byte_queue.pop_front();
continue;
}
}
std::deque<char>::iterator iter = std::find(in_byte_queue.begin(), in_byte_queue.end(), '\r');
if(std::distance(in_byte_queue.begin(), iter) > max_str_length)
{
in_byte_queue.pop_front();
break;
}
if(iter == in_byte_queue.end())
{
break;
}
std::shared_ptr<Linux_can> obj_frame = std::make_shared<Linux_can>();
if(timestamp)
{
packet.assign(in_byte_queue.begin(), iter - 4);
for(size_t i = 4; i > 0; i--)
{
obj_frame->time_Read.assign(iter-4, iter);
}
}
if(!timestamp)
{
packet.assign(in_byte_queue.begin(), iter);
obj_frame->time_Read = time_of_read;
}
if(lawicel_to_linux(packet, &(obj_frame->fd_frame), &(obj_frame->mtu)))
{
{
std::lock_guard<std::mutex> lock(in_packet_queue_mutex);
in_packet_queue.push_back(obj_frame);
}
in_packet_queue_condvar.notify_one();
}
else
{
printf("FAILED LAWICEL\n");
}
in_byte_queue.erase(in_byte_queue.begin(), iter);
} // while in_byte_queue not empty
} // while no interrupt
}
void Hadoucan_IO_mgr::end_read_thread_func()
{
read_thread.interrupt();
read_thread.join();
}
bool Hadoucan_IO_mgr::timestamp_on()
{
return timestamp;
} | 20.239437 | 111 | 0.676409 | [
"vector"
] |
7f991a8bfd0c372b52a554f3e7964a53a84d8fc4 | 2,686 | cpp | C++ | code/steps/main_gprof.cpp | cuihantao/steps | 60327bf42299cb7117ed5907a931583d7cdf590d | [
"MIT"
] | 1 | 2021-01-21T13:10:40.000Z | 2021-01-21T13:10:40.000Z | code/steps/main_gprof.cpp | cuihantao/steps | 60327bf42299cb7117ed5907a931583d7cdf590d | [
"MIT"
] | null | null | null | code/steps/main_gprof.cpp | cuihantao/steps | 60327bf42299cb7117ed5907a931583d7cdf590d | [
"MIT"
] | 1 | 2020-10-01T03:48:38.000Z | 2020-10-01T03:48:38.000Z | #include "header/basic/utility.h"
#include "header/data_imexporter/psse_imexporter.h"
#include "header/prepare_for_tests/prepare_models_for_test.h"
#include "header/meter/meter_setter.h"
#include "header/steps_namespace.h"
#include "header/toolkit/powerflow_solver/powerflow_solver.h"
#include "header/toolkit/dynamic_simulator/dynamic_simulator.h"
#include <cstdlib>
#include <cstring>
#include <istream>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <ctime>
int main()
{
clock_t start = clock();
DYNAMICS_SIMULATOR& simulator = default_toolkit.get_dynamic_simulator();
POWER_SYSTEM_DATABASE& psdb = default_toolkit.get_power_system_database();
string file = "test_log/";
file += __FUNCTION__;
file += ".txt";
default_toolkit.open_log_file(file);
PSSE_IMEXPORTER importer(default_toolkit);
psdb.set_allowed_max_bus_number(1000);
importer.load_powerflow_data("../../../bench/bench_shandong_change.raw");
importer.load_dynamic_data("../../../bench/bench_shandong_change_with_gov.dyr");
vector<HVDC*> hvdcs = psdb.get_all_hvdcs();
unsigned int n = hvdcs.size();
for(unsigned int i=0; i!=n; ++i)
hvdcs[i]->turn_rectifier_constant_power_mode_into_constant_current_mode();
POWERFLOW_SOLVER& powerflow_solver = default_toolkit.get_powerflow_solver();
powerflow_solver.set_max_iteration(30);
powerflow_solver.set_allowed_max_active_power_imbalance_in_MW(0.00001);
powerflow_solver.set_allowed_max_reactive_power_imbalance_in_MVar(0.00001);
powerflow_solver.set_flat_start_logic(false);
powerflow_solver.set_transformer_tap_adjustment_logic(true);
powerflow_solver.solve_with_fast_decoupled_solution();
//simulator.prepare_meters();
simulator.set_output_file("test_log/bench_shandong_100_bus_model_dynamic_test_result_GENROU_CDC4T");
simulator.set_allowed_max_power_imbalance_in_MVA(0.001);
//simulator.set_max_DAE_iteration(20);
//simulator.set_max_network_iteration(200);
default_toolkit.set_dynamic_simulation_time_step_in_s(0.01);
simulator.start();
simulator.run_to(1.0);
DEVICE_ID did;
did.set_device_type("LINE");
TERMINAL terminal;
terminal.append_bus(60);
terminal.append_bus(62);
did.set_device_terminal(terminal);
did.set_device_identifier("1");
simulator.set_line_fault(did, 60, 0.0, complex<double>(0.0, -1e6));
simulator.run_to(1.1);
simulator.clear_line_fault(did, 60, 0.0);
simulator.trip_line(did);
simulator.run_to(5.0);
default_toolkit.close_log_file();
clock_t stop = clock();
cout<<"time elapse: "<<double(stop-start)*1e-6<<" s"<<endl;
return 0;
}
| 32.361446 | 104 | 0.750931 | [
"vector"
] |
7fa33adba61e24c3a6ea19501942ddeec8e8d328 | 23,973 | cpp | C++ | vnpy/api/tora/vntora/generated_files/generated_functions_6.cpp | howyu88/vnpy2 | c8ae445823dc1f71abda1a79fae7d4be3dd92dd4 | [
"MIT"
] | 323 | 2015-11-21T14:45:29.000Z | 2022-03-16T08:54:37.000Z | vnpy/api/tora/vntora/generated_files/generated_functions_6.cpp | howyu88/vnpy2 | c8ae445823dc1f71abda1a79fae7d4be3dd92dd4 | [
"MIT"
] | 9 | 2017-03-21T08:26:21.000Z | 2021-08-23T06:41:17.000Z | vnpy/api/tora/vntora/generated_files/generated_functions_6.cpp | howyu88/vnpy2 | c8ae445823dc1f71abda1a79fae7d4be3dd92dd4 | [
"MIT"
] | 148 | 2016-09-26T03:25:39.000Z | 2022-02-06T14:43:48.000Z | #include "config.h"
#include <iostream>
#include <string>
#include <pybind11/pybind11.h>
#include <autocxxpy/autocxxpy.hpp>
#include "module.hpp"
#include "wrappers.hpp"
#include "generated_functions.h"
#include "TORATstpMdApi.h"
#include "TORATstpTraderApi.h"
#include "TORATstpUserApiDataType.h"
#include "TORATstpUserApiStruct.h"
void generate_class_CTORATstpMdSpi(pybind11::object & parent)
{
pybind11::class_<CTORATstpMdSpi, PyCTORATstpMdSpi> c(parent, "CTORATstpMdSpi");
if constexpr (std::is_default_constructible_v<PyCTORATstpMdSpi>)
c.def(pybind11::init<>());
c.def("OnFrontConnected",
&CTORATstpMdSpi::OnFrontConnected,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnFrontDisconnected",
&CTORATstpMdSpi::OnFrontDisconnected,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspError",
&CTORATstpMdSpi::OnRspError,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspUserLogin",
&CTORATstpMdSpi::OnRspUserLogin,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspUserLogout",
&CTORATstpMdSpi::OnRspUserLogout,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspSubMarketData",
&CTORATstpMdSpi::OnRspSubMarketData,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspUnSubMarketData",
&CTORATstpMdSpi::OnRspUnSubMarketData,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspSubSpecialMarketData",
&CTORATstpMdSpi::OnRspSubSpecialMarketData,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspUnSubSpecialMarketData",
&CTORATstpMdSpi::OnRspUnSubSpecialMarketData,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspSubFundsFlowMarketData",
&CTORATstpMdSpi::OnRspSubFundsFlowMarketData,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspUnSubFundsFlowMarketData",
&CTORATstpMdSpi::OnRspUnSubFundsFlowMarketData,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRtnDepthMarketData",
&CTORATstpMdSpi::OnRtnDepthMarketData,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRtnSpecialMarketData",
&CTORATstpMdSpi::OnRtnSpecialMarketData,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRtnEffectPriceMarketData",
&CTORATstpMdSpi::OnRtnEffectPriceMarketData,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRtnEffectVolumeMarketData",
&CTORATstpMdSpi::OnRtnEffectVolumeMarketData,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRtnFundsFlowMarketData",
&CTORATstpMdSpi::OnRtnFundsFlowMarketData,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpMdSpi, c);
module_vntora::objects.emplace("CTORATstpMdSpi", c);
}
void generate_class_CTORATstpMdApi(pybind11::object & parent)
{
pybind11::class_<
CTORATstpMdApi,
std::unique_ptr<CTORATstpMdApi, pybind11::nodelete>,
PyCTORATstpMdApi
> c(parent, "CTORATstpMdApi");
if constexpr (std::is_default_constructible_v<PyCTORATstpMdApi>)
c.def(pybind11::init<>());
c.def_static("CreateTstpMdApi",
&CTORATstpMdApi::CreateTstpMdApi,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def_static("GetApiVersion",
&CTORATstpMdApi::GetApiVersion,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("Release",
&CTORATstpMdApi::Release,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("Init",
&CTORATstpMdApi::Init,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("Join",
&CTORATstpMdApi::Join,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("RegisterFront",
&CTORATstpMdApi::RegisterFront,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("RegisterNameServer",
&CTORATstpMdApi::RegisterNameServer,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("RegisterDeriveServer",
&CTORATstpMdApi::RegisterDeriveServer,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("RegisterSpi",
&CTORATstpMdApi::RegisterSpi,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("SubscribeMarketData",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&CTORATstpMdApi::SubscribeMarketData
>,
brigand::list<
autocxxpy::indexed_transform_holder<autocxxpy::string_array_transform, 0 + 1/*self*/>
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("UnSubscribeMarketData",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&CTORATstpMdApi::UnSubscribeMarketData
>,
brigand::list<
autocxxpy::indexed_transform_holder<autocxxpy::string_array_transform, 0 + 1/*self*/>
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("SubscribeSpecialMarketData",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&CTORATstpMdApi::SubscribeSpecialMarketData
>,
brigand::list<
autocxxpy::indexed_transform_holder<autocxxpy::string_array_transform, 0 + 1/*self*/>
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("UnSubscribeSpecialMarketData",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&CTORATstpMdApi::UnSubscribeSpecialMarketData
>,
brigand::list<
autocxxpy::indexed_transform_holder<autocxxpy::string_array_transform, 0 + 1/*self*/>
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("SubscribeFundsFlowMarketData",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&CTORATstpMdApi::SubscribeFundsFlowMarketData
>,
brigand::list<
autocxxpy::indexed_transform_holder<autocxxpy::string_array_transform, 0 + 1/*self*/>
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("UnSubscribeFundsFlowMarketData",
autocxxpy::apply_function_transform<
autocxxpy::function_constant<
&CTORATstpMdApi::UnSubscribeFundsFlowMarketData
>,
brigand::list<
autocxxpy::indexed_transform_holder<autocxxpy::string_array_transform, 0 + 1/*self*/>
>
>::value,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("ReqUserLogin",
&CTORATstpMdApi::ReqUserLogin,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("ReqUserLogout",
&CTORATstpMdApi::ReqUserLogout,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpMdApi, c);
module_vntora::objects.emplace("CTORATstpMdApi", c);
}
void generate_class_CTORATstpTraderSpi(pybind11::object & parent)
{
pybind11::class_<CTORATstpTraderSpi, PyCTORATstpTraderSpi> c(parent, "CTORATstpTraderSpi");
if constexpr (std::is_default_constructible_v<PyCTORATstpTraderSpi>)
c.def(pybind11::init<>());
c.def("OnFrontConnected",
&CTORATstpTraderSpi::OnFrontConnected,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnFrontDisconnected",
&CTORATstpTraderSpi::OnFrontDisconnected,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspError",
&CTORATstpTraderSpi::OnRspError,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspUserLogin",
&CTORATstpTraderSpi::OnRspUserLogin,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspUserLogout",
&CTORATstpTraderSpi::OnRspUserLogout,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspUserPasswordUpdate",
&CTORATstpTraderSpi::OnRspUserPasswordUpdate,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspInputDeviceSerial",
&CTORATstpTraderSpi::OnRspInputDeviceSerial,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspOrderInsert",
&CTORATstpTraderSpi::OnRspOrderInsert,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRtnOrder",
&CTORATstpTraderSpi::OnRtnOrder,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnErrRtnOrderInsert",
&CTORATstpTraderSpi::OnErrRtnOrderInsert,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspOrderAction",
&CTORATstpTraderSpi::OnRspOrderAction,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnErrRtnOrderAction",
&CTORATstpTraderSpi::OnErrRtnOrderAction,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRtnTrade",
&CTORATstpTraderSpi::OnRtnTrade,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRtnMarketStatus",
&CTORATstpTraderSpi::OnRtnMarketStatus,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspCondOrderInsert",
&CTORATstpTraderSpi::OnRspCondOrderInsert,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRtnCondOrder",
&CTORATstpTraderSpi::OnRtnCondOrder,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnErrRtnCondOrderInsert",
&CTORATstpTraderSpi::OnErrRtnCondOrderInsert,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspCondOrderAction",
&CTORATstpTraderSpi::OnRspCondOrderAction,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnErrRtnCondOrderAction",
&CTORATstpTraderSpi::OnErrRtnCondOrderAction,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspInquiryJZFund",
&CTORATstpTraderSpi::OnRspInquiryJZFund,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspTransferFund",
&CTORATstpTraderSpi::OnRspTransferFund,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRtnTransferFund",
&CTORATstpTraderSpi::OnRtnTransferFund,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnErrRtnTransferFund",
&CTORATstpTraderSpi::OnErrRtnTransferFund,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRtnTransferPosition",
&CTORATstpTraderSpi::OnRtnTransferPosition,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnErrRtnTransferPosition",
&CTORATstpTraderSpi::OnErrRtnTransferPosition,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspTransferCollateral",
&CTORATstpTraderSpi::OnRspTransferCollateral,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspInquiryBankAccountFund",
&CTORATstpTraderSpi::OnRspInquiryBankAccountFund,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspInquiryTradeConcentration",
&CTORATstpTraderSpi::OnRspInquiryTradeConcentration,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRtnTradingNotice",
&CTORATstpTraderSpi::OnRtnTradingNotice,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspInquiryMaxOrderVolume",
&CTORATstpTraderSpi::OnRspInquiryMaxOrderVolume,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRtnPeripheryTransferPosition",
&CTORATstpTraderSpi::OnRtnPeripheryTransferPosition,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspInquiryHistoryOrder",
&CTORATstpTraderSpi::OnRspInquiryHistoryOrder,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspInquiryHistoryTrade",
&CTORATstpTraderSpi::OnRspInquiryHistoryTrade,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryExchange",
&CTORATstpTraderSpi::OnRspQryExchange,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryMarketData",
&CTORATstpTraderSpi::OnRspQryMarketData,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQrySecurity",
&CTORATstpTraderSpi::OnRspQrySecurity,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryETFFile",
&CTORATstpTraderSpi::OnRspQryETFFile,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryETFBasket",
&CTORATstpTraderSpi::OnRspQryETFBasket,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryIPOInfo",
&CTORATstpTraderSpi::OnRspQryIPOInfo,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryBUProxy",
&CTORATstpTraderSpi::OnRspQryBUProxy,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryUser",
&CTORATstpTraderSpi::OnRspQryUser,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryInvestor",
&CTORATstpTraderSpi::OnRspQryInvestor,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryShareholderAccount",
&CTORATstpTraderSpi::OnRspQryShareholderAccount,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryOrder",
&CTORATstpTraderSpi::OnRspQryOrder,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryOrderAction",
&CTORATstpTraderSpi::OnRspQryOrderAction,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryTrade",
&CTORATstpTraderSpi::OnRspQryTrade,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryTradingAccount",
&CTORATstpTraderSpi::OnRspQryTradingAccount,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryPosition",
&CTORATstpTraderSpi::OnRspQryPosition,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryTradingFee",
&CTORATstpTraderSpi::OnRspQryTradingFee,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryInvestorTradingFee",
&CTORATstpTraderSpi::OnRspQryInvestorTradingFee,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryIPOQuota",
&CTORATstpTraderSpi::OnRspQryIPOQuota,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryMarket",
&CTORATstpTraderSpi::OnRspQryMarket,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryOrderFundDetail",
&CTORATstpTraderSpi::OnRspQryOrderFundDetail,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryFundTransferDetail",
&CTORATstpTraderSpi::OnRspQryFundTransferDetail,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryPositionTransferDetail",
&CTORATstpTraderSpi::OnRspQryPositionTransferDetail,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryPledgePosition",
&CTORATstpTraderSpi::OnRspQryPledgePosition,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryPledgeInfo",
&CTORATstpTraderSpi::OnRspQryPledgeInfo,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryConversionBondInfo",
&CTORATstpTraderSpi::OnRspQryConversionBondInfo,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryBondPutbackInfo",
&CTORATstpTraderSpi::OnRspQryBondPutbackInfo,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryStandardBondPosition",
&CTORATstpTraderSpi::OnRspQryStandardBondPosition,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQrySpecialMarketData",
&CTORATstpTraderSpi::OnRspQrySpecialMarketData,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryPrematurityRepoOrder",
&CTORATstpTraderSpi::OnRspQryPrematurityRepoOrder,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryShareholderParam",
&CTORATstpTraderSpi::OnRspQryShareholderParam,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryPeripheryPositionTransferDetail",
&CTORATstpTraderSpi::OnRspQryPeripheryPositionTransferDetail,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryInvestorCondOrderLimitParam",
&CTORATstpTraderSpi::OnRspQryInvestorCondOrderLimitParam,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryCondOrder",
&CTORATstpTraderSpi::OnRspQryCondOrder,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryCondOrderAction",
&CTORATstpTraderSpi::OnRspQryCondOrderAction,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryTradingNotice",
&CTORATstpTraderSpi::OnRspQryTradingNotice,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryIPONumberResult",
&CTORATstpTraderSpi::OnRspQryIPONumberResult,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
c.def("OnRspQryIPOMatchNumberResult",
&CTORATstpTraderSpi::OnRspQryIPOMatchNumberResult,
pybind11::return_value_policy::reference,
pybind11::call_guard<pybind11::gil_scoped_release>()
);
AUTOCXXPY_POST_REGISTER_CLASS(tag_vntora, CTORATstpTraderSpi, c);
module_vntora::objects.emplace("CTORATstpTraderSpi", c);
}
| 39.756219 | 101 | 0.69011 | [
"object"
] |
7fa4e9d4007c54432408d253d5bcf6bf85d450bb | 1,424 | cpp | C++ | main.cpp | putara/pi-stat | b1f2005288145a641a5378742215bbd1ae4d7f4b | [
"WTFPL"
] | null | null | null | main.cpp | putara/pi-stat | b1f2005288145a641a5378742215bbd1ae4d7f4b | [
"WTFPL"
] | null | null | null | main.cpp | putara/pi-stat | b1f2005288145a641a5378742215bbd1ae4d7f4b | [
"WTFPL"
] | null | null | null | #include "ssd1306.hpp"
#include "helpers.hpp"
#include "render.hpp"
#include "config.hpp"
#include <signal.h>
volatile sig_atomic_t done = 0;
struct sigaction action;
void sig_handler(int signo) noexcept {
done = 1;
// printf("signal: %d\n", signo);
}
int main() noexcept {
printf("pid: %d\n", getpid());
memset(&action, 0, sizeof(struct sigaction));
action.sa_handler = sig_handler;
if (sigaction(SIGINT, &action, nullptr) == -1) {
perror("Error: cannot handle SIGINT");
}
if (sigaction(SIGTERM, &action, nullptr) == -1) {
perror("Error: cannot handle SIGTERM");
}
config config;
if (config.load() == false) {
return EXIT_FAILURE;
}
ssd1306* dev;
auto ret = ssd1306::init(config.i2c_dev, config.i2c_addr, &dev);
if (ret == S_OK) {
printf("ready\n");
renderer canvas;
while (!done) {
canvas.start();
if (lcd::HEIGHT == 64) {
canvas.print_title(config.title);
canvas.print_time();
canvas.print_ip(config.ifnames);
canvas.print_cpu();
canvas.print_mem();
canvas.print_disk(config.mountpoint);
} else if (lcd::HEIGHT == 32) {
canvas.print_ip(config.ifnames);
canvas.print_cpu();
canvas.print_mem();
}
auto lcd = canvas.end();
dev->refresh(lcd);
os::wait_until_next_tick();
}
printf("\nexiting\n");
dev->exit();
}
return EXIT_SUCCESS;
}
| 23.344262 | 66 | 0.608848 | [
"render"
] |
7fab282554045afb5775200253f962ad784c3288 | 5,418 | cc | C++ | BParkingNano/plugins/TrgBitTableProducer.cc | alesauva/BParkingNANO | 2ed4e5d245c443d5d8ed59626c2293693f8fb19c | [
"Apache-2.0"
] | 2 | 2021-11-21T14:59:57.000Z | 2021-12-14T21:04:02.000Z | BParkingNano/plugins/TrgBitTableProducer.cc | alesauva/BParkingNANO | 2ed4e5d245c443d5d8ed59626c2293693f8fb19c | [
"Apache-2.0"
] | 70 | 2019-07-25T17:55:32.000Z | 2021-02-08T21:39:10.000Z | BParkingNano/plugins/TrgBitTableProducer.cc | alesauva/BParkingNANO | 2ed4e5d245c443d5d8ed59626c2293693f8fb19c | [
"Apache-2.0"
] | 39 | 2019-07-25T13:53:18.000Z | 2021-11-07T16:35:44.000Z | //// table to produce hlt and l1 bits that we are going to use in the analysis, to avoid saving every bit in the menu
// system include files
#include <memory>
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
#include "FWCore/Utilities/interface/InputTag.h"
#include "DataFormats/Common/interface/View.h"
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/stream/EDProducer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Utilities/interface/StreamID.h"
#include "DataFormats/NanoAOD/interface/FlatTable.h"
#include "FWCore/Common/interface/TriggerNames.h"
#include "DataFormats/HLTReco/interface/TriggerEvent.h"
#include "DataFormats/HLTReco/interface/TriggerObject.h"
#include "HLTrigger/HLTcore/interface/defaultModuleLabel.h"
#include "DataFormats/HLTReco/interface/TriggerFilterObjectWithRefs.h"
#include "DataFormats/PatCandidates/interface/TriggerObjectStandAlone.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "TString.h"
#include <string>
#include "CondFormats/DataRecord/interface/L1TUtmTriggerMenuRcd.h"
#include "CondFormats/L1TObjects/interface/L1TUtmTriggerMenu.h"
#include "DataFormats/L1TGlobal/interface/GlobalAlgBlk.h"
class TrgBitTableProducer : public edm::stream::EDProducer<> {
public:
explicit TrgBitTableProducer(const edm::ParameterSet &cfg):
hltresultsToken_(consumes<edm::TriggerResults>(cfg.getParameter<edm::InputTag> ("hltresults"))),
l1resultsToken_(consumes<GlobalAlgBlkBxCollection>(cfg.getParameter<edm::InputTag> ("l1results"))),
hltpaths_( cfg.getParameter< std::vector<std::string> >( "paths" ) ),
l1seeds_( cfg.getParameter< std::vector<std::string> >( "seeds" ) )
{
produces<nanoaod::FlatTable>();
}
~TrgBitTableProducer() override {}
void produce(edm::Event&, edm::EventSetup const&) override;
static void fillDescriptions(edm::ConfigurationDescriptions &descriptions) {}
private:
const edm::EDGetTokenT< edm::TriggerResults > hltresultsToken_;
const edm::EDGetTokenT<GlobalAlgBlkBxCollection> l1resultsToken_;
// l1 seeds not implemented yet but can be added with litle effort
const std::vector< std::string > hltpaths_;
const std::vector< std::string > l1seeds_;
TString * algoBitToName = new TString[512];
bool loaded = false;
};
void
TrgBitTableProducer::produce( edm::Event &evt, edm::EventSetup const &stp)
{
//input
edm::Handle<GlobalAlgBlkBxCollection> l1Results;
evt.getByToken(l1resultsToken_,l1Results);
edm::Handle< edm::TriggerResults > hltResults;
evt.getByToken( hltresultsToken_, hltResults);
// returns uint8 instead of bool, because addCollumnValue<bool> is unsuported. (cmsRun error). the next "economical" class is uint8
std::vector<uint8_t> hltbits;
std::vector<uint8_t> l1bits;
unsigned int Npaths = hltpaths_.size();
hltbits.reserve( Npaths );
unsigned int Nseeds = l1seeds_.size();
l1bits.reserve( Nseeds );
edm::TriggerNames trigName = evt.triggerNames( *hltResults );
// get L1 seeds
if ( !l1Results.isValid() ) {
for (unsigned int iseed=0; iseed<l1seeds_.size(); iseed++)
l1bits.push_back( 0 );
} else{
if (!loaded){
edm::ESHandle<L1TUtmTriggerMenu> menu;
stp.get<L1TUtmTriggerMenuRcd>().get(menu);
for (auto const & keyval: menu->getAlgorithmMap()) {
std::string const & trigName = keyval.second.getName();
algoBitToName[ int( keyval.second.getIndex() ) ] = TString( trigName );
}
loaded=true;
}
GlobalAlgBlk const &result=l1Results->at(0, 0);
for ( auto& l1seed: l1seeds_ ){
bool sfire=false;
for (unsigned int itrg=0; itrg<result.maxPhysicsTriggers; ++itrg){
if (result.getAlgoDecisionFinal(itrg)!=1) continue;
std::string l1trigName = static_cast<const char *>(algoBitToName[itrg]);
if (l1trigName!=l1seed) continue;
sfire=true;
break;
}
if (sfire) l1bits.push_back( 1 );
else l1bits.push_back( 0 );
}
}
// get HLT triggers
if ( hltResults.failedToGet() ){
for ( unsigned int ibit = 0; ibit < Npaths; ++ibit)
hltbits.push_back( 0 );
} else {
int Ntrg = hltResults->size();
for ( auto& hltpath: hltpaths_ ){
bool fire = false;
for( int itrg = 0; itrg < Ntrg; ++itrg ){
if ( !hltResults->accept( itrg ) ) continue;
TString TrigPath = trigName.triggerName( itrg );
if ( TrigPath.Contains( hltpath ) ){
fire=true;
break;
}
}
if( fire ) hltbits.push_back( 1 );
else hltbits.push_back( 0 );
}
}
auto tab = std::make_unique<nanoaod::FlatTable>(1,"", true);
for (unsigned int ipath = 0; ipath <Npaths; ++ipath ){
tab->addColumnValue<uint8_t> (hltpaths_[ipath], hltbits[ipath], "hlt path", nanoaod::FlatTable::UInt8Column);
}
for (unsigned int iseed = 0; iseed <Nseeds; ++iseed ){
tab->addColumnValue<uint8_t> (l1seeds_[iseed], l1bits[iseed], "l1 seed", nanoaod::FlatTable::UInt8Column);
}
evt.put(std::move(tab));
}
//define this as a plug-in
DEFINE_FWK_MODULE(TrgBitTableProducer);
| 31.684211 | 133 | 0.699889 | [
"vector"
] |
7faec02760aabfd6fe5920f93d91024a9eb8081a | 12,504 | cpp | C++ | src/kernel/os.cpp | anna328p/IncludeOS | b9858b8e6842d6c0cc227a34a015e7e8de9438ab | [
"Apache-2.0"
] | null | null | null | src/kernel/os.cpp | anna328p/IncludeOS | b9858b8e6842d6c0cc227a34a015e7e8de9438ab | [
"Apache-2.0"
] | null | null | null | src/kernel/os.cpp | anna328p/IncludeOS | b9858b8e6842d6c0cc227a34a015e7e8de9438ab | [
"Apache-2.0"
] | null | null | null | // This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.
//#define DEBUG
#define MYINFO(X,...) INFO("Kernel", X, ##__VA_ARGS__)
#include <cstdio>
#include <os>
#include <boot/multiboot.h>
#include <kernel/elf.hpp>
#include <hw/acpi.hpp>
#include <hw/apic.hpp>
#include <hw/apic_timer.hpp>
#include <hw/cmos.hpp>
#include <kernel/irq_manager.hpp>
#include <kernel/pci_manager.hpp>
#include <kernel/timers.hpp>
#include <kernel/rtc.hpp>
#include <statman>
#include <vector>
extern "C" uint16_t _cpu_sampling_freq_divider_;
extern uintptr_t heap_begin;
extern uintptr_t heap_end;
extern uintptr_t _start;
extern uintptr_t _end;
extern uintptr_t _ELF_START_;
extern uintptr_t _TEXT_START_;
extern uintptr_t _LOAD_START_;
extern uintptr_t _ELF_END_;
extern uintptr_t _MAX_MEM_MIB_;
bool OS::power_ {true};
MHz OS::cpu_mhz_ {1000};
RTC::timestamp_t OS::booted_at_ {0};
uintptr_t OS::low_memory_size_ {0};
uintptr_t OS::high_memory_size_ {0};
uintptr_t OS::heap_max_ {0xfffffff};
const uintptr_t OS::elf_binary_size_ {(uintptr_t)&_ELF_END_ - (uintptr_t)&_ELF_START_};
// stdout redirection
static std::vector<OS::print_func> os_print_handlers;
extern void default_stdout_handlers();
// custom init
std::vector<OS::Custom_init_struct> OS::custom_init_;
// OS version
#ifndef OS_VERSION
#define OS_VERSION "v?.?.?"
#endif
std::string OS::version_field = OS_VERSION;
// Multiboot command line for the service
static std::string os_cmdline = "";
// sleep statistics
static uint64_t* os_cycles_hlt = nullptr;
static uint64_t* os_cycles_total = nullptr;
extern "C" uintptr_t get_cpu_esp();
void OS::start(uint32_t boot_magic, uint32_t boot_addr) {
atexit(default_exit);
default_stdout_handlers();
// Print a fancy header
FILLINE('=');
CAPTION("#include<os> // Literally\n");
FILLINE('=');
auto esp = get_cpu_esp();
MYINFO ("Stack: 0x%x", esp);
Expects (esp < 0xA0000 and esp > 0x0 and "Stack location OK");
MYINFO("Boot args: 0x%x (multiboot magic), 0x%x (bootinfo addr)",
boot_magic, boot_addr);
MYINFO("Max mem (from linker): %i MiB", reinterpret_cast<size_t>(&_MAX_MEM_MIB_));
if (boot_magic == MULTIBOOT_BOOTLOADER_MAGIC) {
OS::multiboot(boot_magic, boot_addr);
} else {
// Fetch CMOS memory info (unfortunately this is maximally 10^16 kb)
auto mem = cmos::meminfo();
low_memory_size_ = mem.base.total * 1024;
INFO2("* Low memory: %i Kib", mem.base.total);
high_memory_size_ = mem.extended.total * 1024;
// Use memsize provided by Make / linker unless CMOS knows this is wrong
decltype(high_memory_size_) hardcoded_mem = reinterpret_cast<size_t>(&_MAX_MEM_MIB_ - 0x100000) << 20;
if (mem.extended.total == 0xffff or hardcoded_mem < mem.extended.total) {
high_memory_size_ = hardcoded_mem;
INFO2("* High memory (from linker): %i Kib", high_memory_size_ / 1024);
} else {
INFO2("* High memory (from cmos): %i Kib", mem.extended.total);
}
}
MYINFO("Assigning fixed memory ranges (Memory map)");
auto& memmap = memory_map();
// @ Todo: The first ~600k of memory is free for use. What can we put there?
memmap.assign_range({0x0009FC00, 0x0009FFFF,
"EBDA", "Extended BIOS data area"});
memmap.assign_range({0x000A0000, 0x000FFFFF,
"VGA/ROM", "Memory mapped video memory"});
memmap.assign_range({(uintptr_t)&_LOAD_START_, (uintptr_t)&_end,
"ELF", "Your service binary including OS"});
// @note for security we don't want to expose this
memmap.assign_range({(uintptr_t)&_end + 1, heap_begin - 1,
"Pre-heap", "Heap randomization area (not for use))"});
memmap.assign_range({0x8000, 0x9fff, "Statman", "Statistics"});
memmap.assign_range({0xA000, 0x9fbff, "Kernel / service main stack"});
// Create ranges for heap and the remaining address space
// @note : since the maximum size of a span is unsigned (ptrdiff_t) we may need more than one
uintptr_t addr_max = std::numeric_limits<std::size_t>::max();
uintptr_t span_max = std::numeric_limits<std::ptrdiff_t>::max();
// Give the rest of physical memory to heap
heap_max_ = ((0x100000 + high_memory_size_) & 0xffff0000) - 1;
// ...Unless it's more than the maximum for a range
// @note : this is a stupid way to limit the heap - we'll change it, but not until
// we have a good solution.
heap_max_ = std::min(span_max, heap_max_);
memmap.assign_range({heap_begin, heap_max_,
"Heap", "Dynamic memory", heap_usage });
uintptr_t unavail_start = 0x100000 + high_memory_size_;
size_t interval = std::min(span_max, addr_max - unavail_start) - 1;
uintptr_t unavail_end = unavail_start + interval;
while (unavail_end < addr_max){
INFO2("* Unavailable memory: 0x%x - 0x%x", unavail_start, unavail_end);
memmap.assign_range({unavail_start, unavail_end,
"N/A", "Reserved / outside physical range" });
unavail_start = unavail_end + 1;
interval = std::min(span_max, addr_max - unavail_start);
// Increment might wrapped around
if (unavail_start > unavail_end + interval or unavail_start + interval == addr_max){
INFO2("* Last chunk of memory: 0x%x - 0x%x", unavail_start, addr_max);
memmap.assign_range({unavail_start, addr_max,
"N/A", "Reserved / outside physical range" });
break;
}
unavail_end += interval;
}
MYINFO("Printing memory map");
for (const auto &i : memory_map())
INFO2("* %s",i.second.to_string().c_str());
// Set up interrupt and exception handlers
IRQ_manager::init();
// read ACPI tables
hw::ACPI::init();
// setup APIC, APIC timer, SMP etc.
hw::APIC::init();
// enable interrupts
INFO("BSP", "Enabling interrupts");
IRQ_manager::enable_interrupts();
// Initialize the Interval Timer
hw::PIT::init();
// Initialize PCI devices
PCI_manager::init();
// Print registered devices
hw::Devices::print_devices();
// Estimate CPU frequency
MYINFO("Estimating CPU-frequency");
INFO2("|");
INFO2("+--(10 samples, %f sec. interval)",
(hw::PIT::frequency() / _cpu_sampling_freq_divider_).count());
INFO2("|");
// TODO: Debug why actual measurments sometimes causes problems. Issue #246.
cpu_mhz_ = hw::PIT::CPU_frequency();
INFO2("+--> %f MHz", cpu_mhz_.count());
// cpu_mhz must be known before we can start timer system
/// initialize timers hooked up to APIC timer
Timers::init(
// timer start function
hw::APIC_Timer::oneshot,
// timer stop function
hw::APIC_Timer::stop);
// initialize BSP APIC timer
hw::APIC_Timer::init(
[] {
// set final interrupt handler
hw::APIC_Timer::set_handler(Timers::timers_handler);
// signal that kernel is done with everything
Service::ready();
// signal ready
// NOTE: this executes the first timers, so we
// don't want to run this before calling Service ready
Timers::ready();
});
// Realtime/monotonic clock
RTC::init();
booted_at_ = RTC::now();
// sleep statistics
os_cycles_hlt = &Statman::get().create(
Stat::UINT64, std::string("cpu0.cycles_hlt")).get_uint64();
os_cycles_total = &Statman::get().create(
Stat::UINT64, std::string("cpu0.cycles_total")).get_uint64();
// Trying custom initialization functions
MYINFO("Calling custom initialization functions");
for (auto init : custom_init_) {
INFO2("* Calling %s", init.name_);
try{
init.func_();
} catch(std::exception& e){
MYINFO("Exception thrown when calling custom init: %s", e.what());
} catch(...){
MYINFO("Unknown exception when calling custom initialization function");
}
}
// Everything is ready
MYINFO("Starting %s", Service::name().c_str());
FILLINE('=');
// initialize random seed based on cycles since start
srand(cycles_since_boot() & 0xFFFFFFFF);
// begin service start
Service::start(Service::command_line());
event_loop();
}
void OS::register_custom_init(Custom_init delg, const char* name){
MYINFO("Registering custom init function %s", name);
custom_init_.emplace_back(delg, name);
}
uintptr_t OS::heap_max() {
// Before the memory map is populated
if (UNLIKELY(memory_map().empty()))
return heap_max_;
// After memory map is populated
return memory_map().at(heap_begin).addr_end();
}
uintptr_t OS::heap_usage() noexcept {
return (uintptr_t) (heap_end - heap_begin);
}
uint64_t OS::get_cycles_halt() noexcept {
return *os_cycles_hlt;
}
__attribute__((noinline))
void OS::halt() {
*os_cycles_total = cycles_since_boot();
asm volatile("hlt");
// add a global symbol here so we can quickly discard
// event loop from stack sampling
asm volatile(
".global _irq_cb_return_location;\n"
"_irq_cb_return_location:" );
// Count sleep cycles
*os_cycles_hlt += cycles_since_boot() - *os_cycles_total;
}
uint64_t OS::get_cycles_total() noexcept {
return *os_cycles_total;
}
void OS::event_loop() {
FILLINE('=');
printf(" IncludeOS %s\n", version().c_str());
printf(" +--> Running [ %s ]\n", Service::name().c_str());
FILLINE('~');
while (power_) {
IRQ_manager::get().process_interrupts();
debug2("OS going to sleep.\n");
OS::halt();
}
// Cleanup
Service::stop();
// ACPI shutdown sequence
hw::ACPI::shutdown();
}
void OS::shutdown()
{
power_ = false;
}
void OS::add_stdout(OS::print_func func)
{
os_print_handlers.push_back(func);
}
size_t OS::print(const char* str, const size_t len) {
// Output callbacks
for (auto& func : os_print_handlers)
func(str, len);
return len;
}
void OS::multiboot(uint32_t boot_magic, uint32_t boot_addr){
MYINFO("Booted with multiboot");
INFO2("* magic value: 0x%x Multiboot info at 0x%x", boot_magic, boot_addr);
multiboot_info_t* bootinfo = (multiboot_info_t*) boot_addr;
if (! bootinfo->flags & MULTIBOOT_INFO_MEMORY) {
INFO2("* No memory info provided in multiboot info");
return;
}
uint32_t mem_low_start = 0;
uint32_t mem_low_end = (bootinfo->mem_lower * 1024) - 1;
uint32_t mem_low_kb = bootinfo->mem_lower;
uint32_t mem_high_start = 0x100000;
uint32_t mem_high_end = mem_high_start + (bootinfo->mem_upper * 1024) - 1;
uint32_t mem_high_kb = bootinfo->mem_upper;
OS::low_memory_size_ = mem_low_kb * 1024;
OS::high_memory_size_ = mem_high_kb * 1024;
INFO2("* Valid memory (%i Kib):", mem_low_kb + mem_high_kb);
INFO2("\t 0x%08x - 0x%08x (%i Kib)",
mem_low_start, mem_low_end, mem_low_kb);
INFO2("\t 0x%08x - 0x%08x (%i Kib)",
mem_high_start, mem_high_end, mem_high_kb);
INFO2("");
if (bootinfo->flags & MULTIBOOT_INFO_CMDLINE) {
os_cmdline = (char*) bootinfo->cmdline;
INFO2("* Booted with parameters: %s", os_cmdline.c_str());
}
if (bootinfo->flags & MULTIBOOT_INFO_MEM_MAP) {
INFO2("* Multiboot provided memory map (%i entries)",bootinfo->mmap_length / sizeof(multiboot_memory_map_t));
gsl::span<multiboot_memory_map_t> mmap { reinterpret_cast<multiboot_memory_map_t*>(bootinfo->mmap_addr),
(int)(bootinfo->mmap_length / sizeof(multiboot_memory_map_t))};
for (auto map : mmap) {
const char* str_type = map.type & MULTIBOOT_MEMORY_AVAILABLE ? "FREE" : "RESERVED";
INFO2("\t 0x%08llx - 0x%08llx %s (%llu Kb.)",
map.addr, map.addr + map.len - 1, str_type, map.len / 1024 );
/*if (map.addr + map.len > mem_high_end)
break;*/
}
printf("\n");
}
}
/// SERVICE RELATED ///
// the name of the current service (built from another module)
extern "C" {
__attribute__((weak))
const char* service_name__ = "(missing service name)";
}
std::string Service::name() {
return service_name__;
}
const std::string& Service::command_line()
{
return os_cmdline;
}
// functions that we can override if we want to
__attribute__((weak))
void Service::ready() {}
__attribute__((weak))
void Service::stop() {}
| 30.950495 | 114 | 0.689379 | [
"vector"
] |
7fb01724c0553f40646f26ed1f6442670e13bb18 | 1,693 | cpp | C++ | src/main/c++/patterns/command/main.cpp | jeanpierrethach/Design-Patterns | 1d0ed384b8d01421d41358feaa0383bb1896aa79 | [
"MIT"
] | null | null | null | src/main/c++/patterns/command/main.cpp | jeanpierrethach/Design-Patterns | 1d0ed384b8d01421d41358feaa0383bb1896aa79 | [
"MIT"
] | null | null | null | src/main/c++/patterns/command/main.cpp | jeanpierrethach/Design-Patterns | 1d0ed384b8d01421d41358feaa0383bb1896aa79 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <memory>
class Command
{
public:
virtual void execute() = 0;
};
class Receiver
{
public:
void turnOn()
{
std::cout<<"The light is on."<<std::endl;
}
void turnOff()
{
std::cout << "The light is off." << std::endl;
}
};
class ConcreteCommand1 : public Command
{
private:
Receiver* m_receiver;
public:
ConcreteCommand1(Receiver* receiver)
: m_receiver(receiver)
{
}
void execute() override
{
m_receiver->turnOn();
}
};
class ConcreteCommand2 : public Command
{
private:
Receiver* m_receiver;
public:
ConcreteCommand2(Receiver* receiver)
: m_receiver(receiver)
{
}
void execute() override
{
m_receiver->turnOff();
}
};
class Invoker
{
private:
std::vector<Command* > m_history_commands;
public:
void storeAndExecute(Command* command)
{
if (command)
{
m_history_commands.push_back(command);
command->execute();
}
}
};
int main()
{
std::unique_ptr<Receiver> receiver = std::make_unique<Receiver>();
std::unique_ptr<Command> switchOn(new ConcreteCommand1(receiver.get()));
std::unique_ptr<Command> switchOff(new ConcreteCommand2(receiver.get()));
std::unique_ptr<Invoker> switcher = std::make_unique<Invoker>();
switcher->storeAndExecute(switchOn.get());
switcher->storeAndExecute(switchOff.get());
return 0;
} | 18.604396 | 77 | 0.544005 | [
"vector"
] |
7fb1fe0bd01b65c816eed1a17e245015aa6ffe0a | 1,354 | cpp | C++ | main.cpp | EldarKurbanov/circleContourServer | b000ac50260763bc39716f3422ac54144a25f4b9 | [
"MIT"
] | null | null | null | main.cpp | EldarKurbanov/circleContourServer | b000ac50260763bc39716f3422ac54144a25f4b9 | [
"MIT"
] | null | null | null | main.cpp | EldarKurbanov/circleContourServer | b000ac50260763bc39716f3422ac54144a25f4b9 | [
"MIT"
] | null | null | null | #include <iostream>
#include <opencv2/opencv.hpp>
int main() {
cv::Mat rgbImg = cv::imread("/Users/eldarkurbanov/CLionProjects/circleContourServer/img12.jpeg", cv::IMREAD_COLOR);
cv::Mat hsvImg;
cv::cvtColor(rgbImg, hsvImg, cv::COLOR_BGR2HSV);
std::vector<cv::Mat> chans;
cv::split(hsvImg, chans);
cv::threshold(255 - chans[2], chans[2], 200, 255, cv::THRESH_BINARY);
std::vector<cv::Vec4i> linesP;
cv::HoughLinesP(chans[2], linesP, 1, CV_PI/180, 50, chans[2].rows / 4, 10);
for (auto l : linesP)
{
cv::line(chans[2], cv::Point(l[0], l[1]), cv::Point(l[2], l[3]), cv::Scalar::all(0), 3, cv::LINE_AA);
}
cv::dilate(chans[2], chans[2], cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)), cv::Point(-1, -1), 4);
cv::erode(chans[2], chans[2], cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)), cv::Point(-1, -1), 3);
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours(chans[2], contours, hierarchy, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE);
for (size_t i = 0; i < contours.size(); i++)
{
if (contours[i].size() > 4)
{
cv::ellipse(rgbImg, cv::fitEllipse(contours[i]), cv::Scalar(255, 0, 255), 2);
}
}
cv::imshow("rgbImg", rgbImg);
cv::waitKey(0);
return 0;
}
| 34.717949 | 119 | 0.599705 | [
"vector"
] |
7fb2a26fa186a3d5ce30d2203e05db0fd36134ec | 7,988 | cpp | C++ | galaga/GalagaMachine.cpp | lukka/CppOpenGLWebAssemblyCMake | 1e2f161812f808d4467cec7cfd8c2e7181af0a75 | [
"MIT"
] | 59 | 2018-06-10T03:29:03.000Z | 2022-01-19T18:01:05.000Z | galaga/GalagaMachine.cpp | lukka/CppOpenGLWebAssemblyCMake | 1e2f161812f808d4467cec7cfd8c2e7181af0a75 | [
"MIT"
] | 3 | 2019-05-04T10:58:19.000Z | 2020-05-15T03:08:20.000Z | galaga/GalagaMachine.cpp | lukka/CppOpenGLWebAssemblyCMake | 1e2f161812f808d4467cec7cfd8c2e7181af0a75 | [
"MIT"
] | 7 | 2018-07-02T22:31:07.000Z | 2021-05-10T12:07:26.000Z | #include "GalagaMachine.h"
#include <algorithm>
#include <cassert>
#include <cmath>
#include "Audio.h"
#include "Cpu2.h"
#include "Cpu3.h"
#include "Frame.h"
#include "GalagaInputPorts.h"
#include "GalagaRoms.h"
#include "MainCpu.h"
#include "Namco06.h"
#include "emulator/DeviceInput.h"
#include "emulator/Timer.h"
namespace Galaga
{
// static
const double GalagaMachine::ClockFrequency = 3.072 * 1e6; // 3.072 MHz
const uint32_t GalagaMachine::AudioSampleRate = 48000; // 48 KHz
GalagaMachine::GalagaMachine()
: scheduler(Quantum),
screenDevice(nullptr),
romManager(GalagaRoms{}),
ioHandler(this),
vblankCallbacks(),
customMod(0),
machinePorts()
{
ram = new uint8_t[65536];
memset(ram, 0, 65536);
twoPlayersGame = true;
difficulty = Difficulty::Easy;
demoSound = true;
freeze = false;
rackTest = false;
cabinetType = CabinetType::Upright;
coinage = Coinage::FreePlay;
initialLives = InitialLives::Five;
bonusLives =
BonusLives::OnetoFour_20K_70K_Every70K__Five_30K_120K_Every120K;
machinePorts["IN0L"] = in0lPort = new IN0LPort(*this);
machinePorts["IN0H"] = in0hPort = new IN0HPort(*this);
machinePorts["IN1L"] = in1lPort = new IN1LPort(*this);
machinePorts["IN1H"] = in1hPort = new IN1HPort(*this);
machinePorts["DSWA"] = dswaPort = new DSWAPort(*this);
machinePorts["DSWB"] = dswbPort = new DSWBPort(*this);
screenDevice = new ScreenDevice(this, ram);
mainCpu = new MainCpu(*this, ram, 64 * 1024, ioHandler);
cpu2 = new Cpu2(*this, ram, 64 * 1024, ioHandler);
cpu3 = new Cpu3(*this, ram, 64 * 1024, ioHandler);
cpu3InterruptCallbackTimer =
new Emulator::CTimer("OnCpu3InterruptCallback", scheduler,
[this](int64_t param, int64_t currentTime) {
OnCpu3InterruptCallback(param);
});
namco06xx = new Namco06(*this);
discreteAudio = new DiscreteAudio(*this, AudioSampleRate);
namcoSound = new NamcoSound(*this);
audio = new Audio(*this);
Reset();
}
GalagaMachine::~GalagaMachine()
{
machinePorts.clear();
delete dswbPort;
delete dswaPort;
delete in1hPort;
delete in1lPort;
delete in0hPort;
delete in0lPort;
delete namcoSound;
delete discreteAudio;
delete audio;
delete namco06xx;
delete cpu3InterruptCallbackTimer;
delete cpu3;
delete cpu2;
delete mainCpu;
delete screenDevice;
delete[] ram;
}
void GalagaMachine::Draw(Frame& frame)
{
frame.Clear();
screenDevice->DrawStars(frame);
screenDevice->DrawTiles(frame);
screenDevice->DrawSprites(frame);
}
void GalagaMachine::GetAudioSamples(AudioFrame& audioFrame)
{
// Generate a sinusoidal sound for testing purposes.
#if 0
double angle = 0;
std::vector<int> samples(960);
for(size_t i = 0; i < samples.size(); i++)
{
samples[i] = sin((i * 3.14f* 2*2000)/samples.size())* 2000;
}
audioFrame.Set(samples);
#else
audioFrame.Set(audio->GetAudio());
#endif
}
Emulator::IInputPort* GalagaMachine::GetPortByTag(const std::string& tag)
{
MachinePorts::iterator it = machinePorts.find(tag);
if (machinePorts.end() == it)
{
assert(false);
return nullptr;
}
return it->second;
}
void GalagaMachine::OnCpu3InterruptCallback(int64_t param)
{
int scanline = (int)param;
cpu3->NmiLinePulse();
scanline = scanline + 128;
if (scanline >= 272)
{
scanline = 64;
}
cpu3InterruptCallbackTimer->Start(screenDevice->TimeUntilScanline(scanline),
false, scanline);
}
void GalagaMachine::OnVblankStartCallback()
{
std::for_each(std::begin(vblankCallbacks), std::end(vblankCallbacks),
[](Action a) { a(); });
if (mainCpu->get_IsInterruptEnabled())
{
mainCpu->OnVblankStart();
}
if (cpu2->get_IsInterruptEnabled())
{
cpu2->OnVblankStart();
}
}
void GalagaMachine::Out0PortWrite(uint8_t data)
{
// set_led_status(1, data & 1);
// set_led_status(0, data & 2);
// coin_counter_w(1, ~data & 4);
// coin_counter_w(0, ~data & 8);
}
void GalagaMachine::Out1PortWrite(uint8_t data)
{
// coin_lockout_global_w(data & 1);
}
uint8_t GalagaMachine::ReadDsw(int offset)
{
uint8_t dswa = machinePorts["DSWA"]->Read();
uint8_t dswb = machinePorts["DSWB"]->Read();
uint8_t bit0 = (dswb >> offset) & 1;
uint8_t bit1 = (dswa >> offset) & 1;
return (bit0 | (bit1 << 1));
}
const ByteArray& GalagaMachine::ReadRom(const std::string& rom)
{
return romManager.ReadRom(rom);
}
void GalagaMachine::RegisterVblankCallback(Action callback)
{
vblankCallbacks.push_back(callback);
}
void GalagaMachine::Reset()
{
ResetLatch();
cpu3InterruptCallbackTimer->Start(screenDevice->TimeUntilScanline(64),
false, 64);
}
void GalagaMachine::ResetLatch()
{
for (int i = 0; i < 8; i++)
{
WriteLatch(i, 0);
}
}
void GalagaMachine::WriteLatch(int offset, uint8_t value)
{
int bit = (value & 1);
switch (offset)
{
case 0x00: // IRQ1
mainCpu->set_IsInterruptEnabled(bit != 0);
if (0 == bit)
{
mainCpu->get_Processor().get_IrqInputLine().SetState(
Emulator::LineState::Clear);
}
break;
case 0x01: // IRQ2
cpu2->set_IsInterruptEnabled(bit != 0);
if (0 == bit)
{
cpu2->get_Processor().get_IrqInputLine().SetState(
Emulator::LineState::Clear);
}
break;
case 0x02: // NMION
cpu3->set_IsInterruptEnabled(bit == 0);
break;
case 0x03: // RESET
cpu2->get_Processor().get_ResetInputLine().SetState(
bit != 0 ? Emulator::LineState::Clear
: Emulator::LineState::Assert);
cpu3->get_Processor().get_ResetInputLine().SetState(
bit != 0 ? Emulator::LineState::Clear
: Emulator::LineState::Assert);
break;
case 0x04: // n.c.
break;
case 0x05: // MOD 0
customMod = (customMod & ~0x01) | (bit << 0);
break;
case 0x06: // MOD 1
customMod = (customMod & ~0x02) | (bit << 1);
break;
case 0x07: // MOD 2
customMod = (customMod & ~0x04) | (bit << 2);
break;
}
}
void GalagaMachine::Run(double us, Frame& videoFrame, AudioFrame& audioFrame)
{
us = us < 75000 ? us : 75000; // no more than 75ms
long currentTime = scheduler.get_CurrentTime();
while (scheduler.get_CurrentTime() < (currentTime + us))
{
scheduler.Timeslice();
}
// video
Draw(videoFrame);
// audio
GetAudioSamples(audioFrame);
}
void GalagaMachine::set_InsertCoin(bool value) { in0hPort->InsertCoin = value; }
void GalagaMachine::set_Start1Player(bool value)
{
in0lPort->Start1Player = value;
}
void GalagaMachine::set_Start2Player(bool value)
{
in0lPort->Start2Player = value;
}
void GalagaMachine::set_MoveLeft(bool value) { in1lPort->MoveLeft = value; }
void GalagaMachine::set_MoveRight(bool value) { in1lPort->MoveRight = value; }
void GalagaMachine::set_Button1(bool value) { in0lPort->Button1 = value; }
void GalagaMachine::SetProgramCounterListener(
ProgramCounterListener& pcListener)
{
this->mainCpu->SetProgramCounterListener(pcListener);
}
} // namespace Galaga
| 26.986486 | 81 | 0.588883 | [
"vector"
] |
7fb2a389d3219af29a9594ffb723adfa682eb4fb | 2,608 | cpp | C++ | testing/unit_tests/governing_equations/cahn_hilliard_2d_fd_test.cpp | mlohry/maDGiCart-CH | 36723e992449fce670d17279b606f54d4b5b5545 | [
"MIT"
] | 3 | 2022-01-25T19:31:17.000Z | 2022-01-25T21:10:39.000Z | testing/unit_tests/governing_equations/cahn_hilliard_2d_fd_test.cpp | mlohry/maDGiCart-CH | 36723e992449fce670d17279b606f54d4b5b5545 | [
"MIT"
] | 20 | 2021-12-17T14:58:00.000Z | 2022-02-05T21:25:35.000Z | testing/unit_tests/governing_equations/cahn_hilliard_2d_fd_test.cpp | mlohry/maDGiCart-CH | 36723e992449fce670d17279b606f54d4b5b5545 | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include "typedefs.hpp"
#include "data_structures/exec_includes.hpp"
#include "governing_equations/cahn_hilliard/cahn_hilliard_2d_fd.hpp"
#include "spatial_discretization/discretization_2d_cart.hpp"
#include "testing/utils/order_of_accuracy.hpp"
#include "testing/utils/domain_generator.hpp"
TEST(CahnHilliard, RHSEvaluation)
{
OrderOfAccuracy accuracy_chrhs;
const std::vector<int> mesh_sizes = {16, 32, 64, 128, 256};
const int expected_order = 2;
for (auto N : mesh_sizes) {
Discretization2DCart geom(generateTriplyPeriodicDomain(N));
CahnHilliardParameters ch_params;
CahnHilliard2DFD ch_rhs(geom, ch_params);
auto state = ch_rhs.createSolutionState();
auto dstate_dt = ch_rhs.createSolutionState();
auto idx = read_access_host(geom.interiorIndices());
auto f = write_access_host(dynamic_cast<CahnHilliardState&>(*state).c());
auto x = read_access_host(geom.x());
auto y = read_access_host(geom.y());
maDGForAllHost(ii, 0, idx.size(), {
int i;
int j;
f.getIJ(idx[ii], i, j);
f(i, j) = sin(x(i, j)) * cos(y(i, j));
});
ch_rhs.evalRHSImpl(*state, 0, *dstate_dt);
ReduceSumRealHostSeq squared_norm(0);
const real_wp m = ch_params.m();
const real_wp eps2 = ch_params.eps2();
const real_wp sigma = ch_params.sigma();
auto rhs = read_access_host(dynamic_cast<CahnHilliardState&>(*dstate_dt).c());
maDGForAllHost(ii, 0, idx.size(), {
int i;
int j;
f.getIJ(idx[ii], i, j);
const real_wp sinx = sin(x(i, j));
const real_wp siny = sin(y(i, j));
const real_wp cosx = cos(x(i, j));
const real_wp cosy = cos(y(i, j));
// laplacian (c^3 -c)
const real_wp expected_laplacian =
2 * sinx * cosy *
(3 * sinx * sinx * siny * siny + 3 * cosx * cosx * cosy * cosy - 3 * sinx * sinx * cosy * cosy + 1);
// biharmonic(c)
const real_wp expected_biharmonic = 4 * sinx * cosy;
const real_wp expected_linear = sinx * cosy - m;
const real_wp expected = -eps2*expected_biharmonic + expected_laplacian - sigma * expected_linear;
squared_norm += pow(expected - rhs(i, j), 2.0);
});
const real_wp l2error = std::sqrt(squared_norm.get() / geom.nInteriorPoints());
accuracy_chrhs.addSolutionError(expected_order, N, l2error);
}
std::cout << "cartesian finite difference Cahn-Hilliard error:\n" << accuracy_chrhs << "\n";
EXPECT_NEAR(accuracy_chrhs.getConvergenceRate().at(expected_order).back(), expected_order, 0.01);
}
| 32.6 | 110 | 0.654525 | [
"vector"
] |
7fb6b3c9a94366678b40babc3247944d28bc7f86 | 1,057 | cpp | C++ | H-HashMap/Multimap.cpp | SoumyoNathTripathy/LearnCPP | 876119bdb2ab3a0fa601785c4bf1691aa8782b2d | [
"MIT"
] | 272 | 2021-02-15T08:20:59.000Z | 2022-03-31T19:28:01.000Z | H-HashMap/Multimap.cpp | SoumyoNathTripathy/LearnCPP | 876119bdb2ab3a0fa601785c4bf1691aa8782b2d | [
"MIT"
] | 778 | 2021-02-15T07:47:05.000Z | 2022-03-31T20:55:29.000Z | H-HashMap/Multimap.cpp | SoumyoNathTripathy/LearnCPP | 876119bdb2ab3a0fa601785c4bf1691aa8782b2d | [
"MIT"
] | 472 | 2021-03-05T07:38:27.000Z | 2022-03-31T21:02:14.000Z |
#include<map>
#include<iostream>
using namespace std;
int main(){
int n;
char c;
string s;
multimap<char,string> m;
/*Multimap can be used to store multiple values
for the same key */
cin>>n;
for(int i=0;i<n;i++){
cin>>c>>s;
m.insert(make_pair(c,s));
}
for (auto p:m)
cout<<p.first<<" -> "<<p.second<<endl;
//To erase an object from multimap
auto it =m.begin();
//cout<<it<<" will be removed";
m.erase(it);
auto it2=m.lower_bound('D'); //dog
auto it3=m.upper_bound('D'); //Eyes
for(auto it4=it2;it4!=it3;it4++)
cout<<it4->second<<" , ";
cout<<endl;
cout<<"Cat Removed "<<endl;
auto f=m.find('C');
if(f->second=="Cat")
m.erase(f);
for (auto p:m)
cout<<p.first<<" -> "<<p.second<<endl;
return 0;
}
/* -----INPUT-----
5
A Apple
B Banana
C Cat
D Dog
E Eyes
//------OUTPUT-----
A -> Apple
B -> Banana
C -> Cat
D -> Dog
E -> Eyes
Dog ,
Cat Removed
B -> Banana
D -> Dog
E -> Eyes
*/
| 14.887324 | 48 | 0.508042 | [
"object"
] |
7fbc70a87c9609c6aaf654ed8d85ab775d2a37a8 | 29,361 | cpp | C++ | src/parsing/parser.cpp | RobertLeahy/UnicodePP | 7dadaf0bf64a53ab0ebc38d914159cce61ce539a | [
"BSD-2-Clause"
] | 2 | 2016-01-20T16:48:52.000Z | 2020-02-09T10:15:51.000Z | src/parsing/parser.cpp | RobertLeahy/UnicodePP | 7dadaf0bf64a53ab0ebc38d914159cce61ce539a | [
"BSD-2-Clause"
] | null | null | null | src/parsing/parser.cpp | RobertLeahy/UnicodePP | 7dadaf0bf64a53ab0ebc38d914159cce61ce539a | [
"BSD-2-Clause"
] | 2 | 2018-10-25T04:09:31.000Z | 2019-04-29T05:21:39.000Z | #include "enum.hpp"
#include "parser.hpp"
#include "path.hpp"
#include "tointeger.hpp"
#include <algorithm>
#include <cstdlib>
using namespace Unicode;
static const std::pair<GeneralCategory,const char *> general_category []={
{GeneralCategory::Lu,"Lu"},
{GeneralCategory::Ll,"Ll"},
{GeneralCategory::Lt,"Lt"},
{GeneralCategory::Mn,"Mn"},
{GeneralCategory::Mc,"Mc"},
{GeneralCategory::Me,"Me"},
{GeneralCategory::Nd,"Nd"},
{GeneralCategory::Nl,"Nl"},
{GeneralCategory::No,"No"},
{GeneralCategory::Zs,"Zs"},
{GeneralCategory::Zl,"Zl"},
{GeneralCategory::Zp,"Zp"},
{GeneralCategory::Cc,"Cc"},
{GeneralCategory::Cf,"Cf"},
{GeneralCategory::Cs,"Cs"},
{GeneralCategory::Co,"Co"},
{GeneralCategory::Cn,"Cn"},
{GeneralCategory::Lm,"Lm"},
{GeneralCategory::Lo,"Lo"},
{GeneralCategory::Pc,"Pc"},
{GeneralCategory::Pd,"Pd"},
{GeneralCategory::Ps,"Ps"},
{GeneralCategory::Pe,"Pe"},
{GeneralCategory::Pi,"Pi"},
{GeneralCategory::Pf,"Pf"},
{GeneralCategory::Po,"Po"},
{GeneralCategory::Sm,"Sm"},
{GeneralCategory::Sc,"Sc"},
{GeneralCategory::Sk,"Sk"},
{GeneralCategory::So,"So"}
};
static const std::pair<BidirectionalClass,const char *> bidi_class []={
{BidirectionalClass::L,"L"},
{BidirectionalClass::R,"R"},
{BidirectionalClass::AL,"AL"},
{BidirectionalClass::EN,"EN"},
{BidirectionalClass::ES,"ES"},
{BidirectionalClass::ET,"ET"},
{BidirectionalClass::AN,"AN"},
{BidirectionalClass::CS,"CS"},
{BidirectionalClass::NSM,"NSM"},
{BidirectionalClass::BN,"BN"},
{BidirectionalClass::B,"B"},
{BidirectionalClass::S,"S"},
{BidirectionalClass::WS,"WS"},
{BidirectionalClass::ON,"ON"},
{BidirectionalClass::LRE,"LRE"},
{BidirectionalClass::LRO,"LRO"},
{BidirectionalClass::RLE,"RLE"},
{BidirectionalClass::RLO,"RLO"},
{BidirectionalClass::PDF,"PDF"},
{BidirectionalClass::LRI,"LRI"},
{BidirectionalClass::RLI,"RLI"},
{BidirectionalClass::FSI,"FSI"},
{BidirectionalClass::PDI,"PDI"}
};
static const std::pair<GraphemeClusterBreak,const char *> grapheme_cluster_break []={
{GraphemeClusterBreak::CR,"CR"},
{GraphemeClusterBreak::LF,"LF"},
{GraphemeClusterBreak::Control,"Control"},
{GraphemeClusterBreak::Extend,"Extend"},
{GraphemeClusterBreak::RegionalIndicator,"Regional_Indicator"},
{GraphemeClusterBreak::Prepend,"Prepend"},
{GraphemeClusterBreak::SpacingMark,"SpacingMark"},
{GraphemeClusterBreak::L,"L"},
{GraphemeClusterBreak::V,"V"},
{GraphemeClusterBreak::T,"T"},
{GraphemeClusterBreak::LV,"LV"},
{GraphemeClusterBreak::LVT,"LVT"},
{GraphemeClusterBreak::XX,"XX"}
};
static const std::pair<LineBreak,const char *> line_break []={
{LineBreak::BK,"BK"},
{LineBreak::CR,"CR"},
{LineBreak::LF,"LF"},
{LineBreak::CM,"CM"},
{LineBreak::NL,"NL"},
{LineBreak::SG,"SG"},
{LineBreak::WJ,"WJ"},
{LineBreak::ZW,"ZW"},
{LineBreak::GL,"GL"},
{LineBreak::SP,"SP"},
{LineBreak::B2,"B2"},
{LineBreak::BA,"BA"},
{LineBreak::BB,"BB"},
{LineBreak::HY,"HY"},
{LineBreak::CB,"CB"},
{LineBreak::CL,"CL"},
{LineBreak::CP,"CP"},
{LineBreak::EX,"EX"},
{LineBreak::IN,"IN"},
{LineBreak::NS,"NS"},
{LineBreak::OP,"OP"},
{LineBreak::QU,"QU"},
{LineBreak::IS,"IS"},
{LineBreak::NU,"NU"},
{LineBreak::PO,"PO"},
{LineBreak::PR,"PR"},
{LineBreak::SY,"SY"},
{LineBreak::AI,"AI"},
{LineBreak::AL,"AL"},
{LineBreak::CJ,"CJ"},
{LineBreak::H2,"H2"},
{LineBreak::H3,"H3"},
{LineBreak::HL,"HL"},
{LineBreak::ID,"ID"},
{LineBreak::JL,"JL"},
{LineBreak::JV,"JV"},
{LineBreak::JT,"JT"},
{LineBreak::RI,"RI"},
{LineBreak::SA,"SA"},
{LineBreak::XX,"XX"}
};
static const std::pair<WordBreak,const char *> word_break []={
{WordBreak::CR,"CR"},
{WordBreak::LF,"LF"},
{WordBreak::Newline,"Newline"},
{WordBreak::Extend,"Extend"},
{WordBreak::RegionalIndicator,"Regional_Indicator"},
{WordBreak::Format,"Format"},
{WordBreak::Katakana,"Katakana"},
{WordBreak::HebrewLetter,"Hebrew_Letter"},
{WordBreak::ALetter,"ALetter"},
{WordBreak::SingleQuote,"Single_Quote"},
{WordBreak::DoubleQuote,"Double_Quote"},
{WordBreak::MidNumLet,"MidNumLet"},
{WordBreak::MidLetter,"MidLetter"},
{WordBreak::MidNum,"MidNum"},
{WordBreak::Numeric,"Numeric"},
{WordBreak::ExtendNumLet,"ExtendNumLet"},
{WordBreak::XX,"XX"}
};
static const std::pair<SentenceBreak,const char *> sentence_break []={
{SentenceBreak::CR,"CR"},
{SentenceBreak::LF,"LF"},
{SentenceBreak::Extend,"Extend"},
{SentenceBreak::Sep,"Sep"},
{SentenceBreak::Format,"Format"},
{SentenceBreak::Sp,"Sp"},
{SentenceBreak::Lower,"Lower"},
{SentenceBreak::Upper,"Upper"},
{SentenceBreak::OLetter,"OLetter"},
{SentenceBreak::Numeric,"Numeric"},
{SentenceBreak::ATerm,"ATerm"},
{SentenceBreak::SContinue,"SContinue"},
{SentenceBreak::STerm,"STerm"},
{SentenceBreak::Close,"Close"},
{SentenceBreak::XX,"XX"}
};
static const std::pair<QuickCheck,const char *> quick_check []={
{QuickCheck::Yes,"Yes"},
{QuickCheck::No,"No"},
{QuickCheck::Maybe,"Maybe"}
};
static const std::pair<const char *,const char *> conditions []={
{"Final_Sigma","FinalSigma"},
{"After_Soft_Dotted","AfterSoftDotted"},
{"More_Above","MoreAbove"},
{"Before_Dot","BeforeDot"},
{"After_I","AfterI"}
};
static const std::pair<NumericType,const char *> numeric_type []={
{NumericType::Decimal,"Decimal"},
{NumericType::Digit,"Digit"},
{NumericType::Numeric,"Numeric"}
};
template <typename T, std::size_t i>
static std::string from_enum (const std::pair<T,const char *> (&arr) [i], T e) {
std::string raw=FromEnum(arr,e);
std::string retr;
for (auto c : raw) if (c!='_') retr.push_back(c);
return retr;
}
static bool in_range (CodePoint::Type cp, CodePoint::Type low, CodePoint::Type high) noexcept {
return (cp>=low) && (cp<=high);
}
bool Parser::Info::in_range (CodePoint::Type low, CodePoint::Type high) const noexcept {
return ::in_range(CodePoint,low,high);
}
Parser::Info::Info (Unicode::CodePoint::Type cp) noexcept
: CodePoint(cp),
WhiteSpace(false),
Alphabetic(false),
NoncharacterCodePoint(false),
DefaultIgnorableCodePoint(false),
Deprecated(false),
LogicalOrderException(false),
VariationSelector(false),
Uppercase(false),
Lowercase(false),
SoftDotted(false),
Cased(false),
CaseIgnorable(false),
HexDigit(false),
ASCIIHexDigit(false),
CanonicalCombiningClass(0),
CompositionExclusion(false),
FullCompositionExclusion(false),
NFCQuickCheck(QuickCheck::Yes),
NFDQuickCheck(QuickCheck::Yes),
LineBreak(Unicode::LineBreak::XX),
GraphemeClusterBreak(Unicode::GraphemeClusterBreak::XX),
SentenceBreak(Unicode::SentenceBreak::XX),
WordBreak(Unicode::WordBreak::XX),
BidirectionalControl(false),
Mirrored(false),
Ideographic(false),
UnifiedIdeograph(false),
Radical(false),
Math(false),
QuotationMark(false),
Dash(false),
STerm(false),
TerminalPunctuation(false),
Diacritic(false),
Extender(false),
GraphemeBase(false),
GraphemeLink(false)
{
// Certain code points do not have a default
// line break property of XX
if (
in_range(0x3400,0x4DBF) ||
in_range(0x4E00,0x9FFF) ||
in_range(0xF900,0xFAFF) ||
in_range(0x20000,0x2FFFD) ||
in_range(0x30000,0x3FFFD)
) LineBreak=Unicode::LineBreak::ID;
else if (in_range(0x20A0,0x20CF)) LineBreak=Unicode::LineBreak::PR;
}
void Parser::Info::Derive () noexcept {
typedef Unicode::GeneralCategory GC;
// Lowercase
if (GeneralCategory==GC::Ll) Lowercase=true;
// Uppercase
if (GeneralCategory==GC::Lu) Uppercase=true;
// Cased
if (Lowercase || Uppercase || (GeneralCategory==GC::Lt)) Cased=true;
// Case ignorable
switch (GeneralCategory) {
case GC::Mn:
case GC::Me:
case GC::Cf:
case GC::Lm:
case GC::Sk:
CaseIgnorable=true;
default:
break;
}
switch (WordBreak) {
case Unicode::WordBreak::MidLetter:
case Unicode::WordBreak::MidNumLet:
CaseIgnorable=true;
default:
break;
}
// Alphabetic
switch (GeneralCategory) {
case GC::Lu:
case GC::Ll:
case GC::Lt:
case GC::Lm:
case GC::Lo:
case GC::Nl:
Alphabetic=true;
default:
break;
}
// Default Ignorable Code Point
// Handle the negative case first
if (
WhiteSpace ||
(
(CodePoint>=0xFFF9) &&
(CodePoint<=0xFFFB)
) ||
(
(CodePoint>=0x0600) &&
(CodePoint<=0x0604)
) ||
(CodePoint==0x06DD) ||
(CodePoint==0x070F) ||
(CodePoint==0x110BD)
) DefaultIgnorableCodePoint=false;
// Now the positive case
else if (
(GeneralCategory==GC::Cf) ||
VariationSelector
) DefaultIgnorableCodePoint=true;
// Grapheme Base
switch (GeneralCategory) {
case GC::Cc:
case GC::Cf:
case GC::Cs:
case GC::Co:
case GC::Cn:
case GC::Zl:
case GC::Zp:
GraphemeBase=false;
break;
default:
if (GraphemeClusterBreak==Unicode::GraphemeClusterBreak::Extend) {
GraphemeBase=false;
break;
}
GraphemeBase=true;
break;
}
// Grapheme Link
// Canonical_Combining_Class=Virama
if (CanonicalCombiningClass==9) GraphemeLink=true;
// Math
if (GeneralCategory==GC::Sm) Math=true;
}
std::vector<Parser::Info>::iterator Parser::lower_bound (CodePoint::Type cp) noexcept {
return std::lower_bound(
info.begin(),
info.end(),
cp,
[] (const Info & a, CodePoint::Type cp) noexcept { return a.CodePoint<cp; }
);
}
std::vector<Parser::Info>::iterator Parser::find (CodePoint::Type cp) noexcept {
auto iter=lower_bound(cp);
auto end=info.end();
return ((iter==end) || (iter->CodePoint!=cp)) ? end : iter;
}
Parser::Info & Parser::get (CodePoint::Type cp) {
auto iter=lower_bound(cp);
if (
(iter!=info.end()) &&
(iter->CodePoint==cp)
) return *iter;
auto loc=iter-info.begin();
info.emplace(iter,cp);
return info[loc];
}
CodePoint::Type Parser::get_cp (const Item & item) {
auto cp=item.CodePoint();
if (!cp) throw std::runtime_error("Expected code point");
return *cp;
}
Parser::Info & Parser::get (const Item & item) {
return get(get_cp(item));
}
[[noreturn]]
static void bad_case_mapping () {
throw std::runtime_error("Bad case mapping in UnicodeData.txt");
}
static std::optional<CodePoint::Type> get_simple_case_mapping (const Item & i) {
auto mapping=i.CodePoints();
if (!mapping) bad_case_mapping();
switch (mapping->size()) {
case 0:
return std::optional<CodePoint::Type>{};
case 1:
return (*mapping)[0];
default:
bad_case_mapping();
}
}
Parser::cps_key Parser::get_decomposition_mapping (const Item & item) {
auto & str=item.Get();
if (
(str.size()==0) ||
(str[0]=='<')
) return cps.Add();
auto dcm=item.CodePoints();
if (!dcm) throw std::runtime_error("Bad decomposition mapping in UnicodeData.txt");
return cps.Add(std::move(*dcm));
}
[[noreturn]]
static void invalid_numeric () {
throw std::runtime_error("Invalid numeric entry in UnicodeData.txt");
}
static double get_digit (const std::string & str) {
auto num=ToInteger<std::size_t>(str);
if (
!num ||
(*num>9)
) invalid_numeric();
return static_cast<double>(*num);
}
static std::optional<double> get_double (const std::string & str) {
if (str.size()==0) return std::optional<double>{};
auto begin=&str[0];
auto end=&str[0]+str.size();
char * str_end;
auto retr=std::strtod(begin,&str_end);
if (str_end!=end) return std::optional<double>{};
return retr;
}
static double get_numeric (const std::string & str) {
auto dbl=get_double(str);
if (dbl) return *dbl;
std::string num;
std::string denom;
bool found=false;
for (auto c : str) {
if (c=='/') {
if (found) invalid_numeric();
found=true;
continue;
}
if (found) denom.push_back(c);
else num.push_back(c);
}
if (!found) invalid_numeric();
auto num_d=get_double(num);
if (!num_d) invalid_numeric();
auto denom_d=get_double(denom);
if (
!denom_d ||
(*denom_d==0)
) invalid_numeric();
return *num_d/ *denom_d;
}
static std::optional<Numeric> get_numeric (const Line & line) {
auto & six=line[6].Get();
auto & seven=line[7].Get();
auto & eight=line[8].Get();
NumericType type;
double value;
if (six.size()==0) {
if ((seven.size()==0) && (eight.size()==0)) return std::optional<Numeric>{};
// Either Digit or Numeric
if (eight.size()==0) invalid_numeric();
if (seven.size()==0) {
// Numeric
type=NumericType::Numeric;
value=get_numeric(eight);
} else {
// Digit
type=NumericType::Digit;
value=get_digit(seven);
}
} else if ((seven.size()==0) || (eight.size()==0)) {
invalid_numeric();
} else {
// Decimal
type=NumericType::Decimal;
value=get_digit(six);
}
return Numeric{type,value};
}
void Parser::get_data (const Line & line) {
// Verify this line, there must be 15 fields:
//
// 1. Code point
// 2. Name
// 3. General category
// 4. Canonical combining class
// 5. Bidirectional category
// 6. Decomposition mapping
// 7. Decimal digit value
// 8. Digit value
// 9. Numeric value
// 10. Mirrored (Y/N)
// 11. Unicode 1.0 Name
// 12. 10646 comment field
// 13. Uppercase mapping (simple)
// 14. Lowercase mapping (simple)
// 15. Titlecase mapping (simple)
if (line.size()<15) throw std::runtime_error("Bad line in UnicodeData.txt");
// Get the code point info structure
// for this code point
auto & info=get(line[0]);
// Populate
info.Name=line[1].Get();
info.GeneralCategory=ToEnum(general_category,line[2].Get());
auto ccc=ToInteger<decltype(info.CanonicalCombiningClass)>(line[3].Get());
if (!ccc) throw std::runtime_error("Bad canonical combining class in UnicodeData.txt");
info.CanonicalCombiningClass=*ccc;
info.BidirectionalClass=ToEnum(bidi_class,line[4].Get());
info.DecompositionMapping=get_decomposition_mapping(line[5]);
info.Numeric=get_numeric(line);
auto & mirrored=line[9].Get();
if (mirrored=="Y") info.Mirrored=true;
else if (mirrored=="N") info.Mirrored=false;
else throw std::runtime_error("Bad mirrored in UnicodeData.txt");
info.SimpleUppercaseMapping=get_simple_case_mapping(line[12]);
info.SimpleLowercaseMapping=get_simple_case_mapping(line[13]);
info.SimpleTitlecaseMapping=get_simple_case_mapping(line[14]);
// Derived properties
info.Derive();
}
void Parser::get_data () {
for (auto & line : data) get_data(line);
}
const std::pair<bool (Parser::Info::*),const char *> Parser::prop_map []={
{&Info::WhiteSpace,"White_Space"},
{&Info::Dash,"Dash"},
{&Info::Hyphen,"Hyphen"},
{&Info::QuotationMark,"Quotation_Mark"},
{&Info::TerminalPunctuation,"Terminal_Punctuation"},
{&Info::Math,"Other_Math"},
{&Info::HexDigit,"Hex_Digit"},
{&Info::ASCIIHexDigit,"ASCII_Hex_Digit"},
{&Info::Alphabetic,"Other_Alphabetic"},
{&Info::Diacritic,"Diacritic"},
{&Info::Extender,"Extender"},
{&Info::Lowercase,"Other_Lowercase"},
{&Info::Uppercase,"Other_Uppercase"},
{&Info::NoncharacterCodePoint,"Noncharacter_Code_Point"},
{&Info::DefaultIgnorableCodePoint,"Other_Default_Ignorable_Code_Point"},
{&Info::Deprecated,"Deprecated"},
{&Info::SoftDotted,"Soft_Dotted"},
{&Info::LogicalOrderException,"Logical_Order_Exception"},
{&Info::VariationSelector,"Variation_Selector"},
{&Info::STerm,"STerm"},
{&Info::BidirectionalControl,"Bidi_Control"},
{&Info::Ideographic,"Ideographic"},
{&Info::UnifiedIdeograph,"Unified_Ideograph"},
{&Info::Radical,"Radical"}
};
void Parser::get_prop_list () {
foreach(prop_list,2,[&] (Info & info, const Line & line) noexcept {
auto & str=line[1].Get();
for (auto & pair : prop_map) if (str==pair.second) {
info.*(pair.first)=true;
info.Derive();
return;
};
});
}
static std::size_t get_string (
const std::string & str,
std::vector<std::string> & vec,
std::unordered_map<std::string,std::size_t> & map
) {
auto iter=map.find(str);
if (iter!=map.end()) return iter->second;
auto key=vec.size();
vec.push_back(str);
map.emplace(str,key);
return key;
}
void Parser::get_blocks (const Range & range, std::size_t i) noexcept {
foreach(range,[&] (Info & info) noexcept { info.Block=i; });
}
void Parser::get_blocks (const Line & line) {
if (line.size()<2) throw std::runtime_error("Bad line in Blocks.txt");
auto i=get_string(line[1].Get(),blocks,blocks_map);
auto range=line[0].Range();
if (range) {
get_blocks(*range,i);
return;
}
auto cp=get_cp(line[0]);
get_blocks(Range{cp,cp},i);
}
void Parser::get_blocks () {
for (auto & line : b) get_blocks(line);
}
void Parser::get_scripts (const Range & range, std::size_t i) noexcept {
foreach(range,[&] (Info & info) noexcept { info.Script=i; });
}
void Parser::get_scripts (const Line & line) {
if (line.size()<2) throw std::runtime_error("Bad line in Scripts.txt");
auto i=get_string(line[1].Get(),scripts,scripts_map);
auto range=line[0].Range();
if (range) {
get_scripts(*range,i);
return;
}
auto cp=get_cp(line[0]);
get_scripts(Range{cp,cp},i);
}
void Parser::get_scripts () {
for (auto & line : s) get_scripts(line);
}
void Parser::get_name_aliases (const Line & line) {
if (line.size()<3) throw std::runtime_error("Bad line in NameAliases.txt");
auto iter=find(get_cp(line[0]));
if (iter==info.end()) return;
auto & alias=line[1].Get();
auto & str=line[2].Get();
if (str=="abbreviation") iter->Abbreviation=alias;
else if (str=="correction") iter->Name=alias;
else iter->Alias=alias;
}
void Parser::get_name_aliases () {
for (auto & line : name_aliases) get_name_aliases(line);
}
void Parser::get_composition_exclusions () {
foreach(composition_exclusions,1,[&] (Info & info, const Line &) noexcept {
info.CompositionExclusion=true;
info.Derive();
});
}
void Parser::get_line_break () {
foreach(line_break,2,[&] (Info & info, const Line & line) {
info.LineBreak=ToEnum(::line_break,line[1].Get());
info.Derive();
});
}
void Parser::get_grapheme_cluster_break () {
foreach(grapheme_break,2,[&] (Info & info, const Line & line) {
info.GraphemeClusterBreak=ToEnum(grapheme_cluster_break,line[1].Get());
info.Derive();
});
}
void Parser::get_sentence_break () {
foreach(sentence_break,2,[&] (Info & info, const Line & line) {
info.SentenceBreak=ToEnum(::sentence_break,line[1].Get());
info.Derive();
});
}
void Parser::get_word_break () {
foreach(sentence_break,2,[&] (Info & info, const Line & line) {
info.WordBreak=ToEnum(::word_break,line[1].Get());
info.Derive();
});
}
void Parser::get_derived_normalization_props (Info & info, bool nfd, const std::string & val) {
QuickCheck qc;
if (val=="Y") qc=QuickCheck::Yes;
else if (val=="M") qc=QuickCheck::Maybe;
else if (val=="N") qc=QuickCheck::No;
else throw std::runtime_error("Invalid quick check value in DerivedNormalizationProps.txt");
if (nfd) info.NFDQuickCheck=qc;
else info.NFCQuickCheck=qc;
info.Derive();
}
void Parser::get_derived_normalization_props () {
// DerivedNormalizationProps.txt has lines with only
// 2 entries, all the ones we want have at least 3,
// so we'll have to do a separate check
foreach(derived_normalization_props,2,[&] (Info & info, const Line & line) {
auto & str=line[1].Get();
bool nfd;
if (str=="NFD_QC") nfd=true;
else if (str=="NFC_QC") nfd=false;
else return;
if (line.size()<3) throw std::runtime_error("Bad line in DerivedNormalizationProps.txt");
get_derived_normalization_props(info,nfd,line[2].Get());
});
}
void Parser::get_full_composition_exclusion (Info & info) {
// If this code point is excluded from composition
// already, clearly the FullCompositionExclusion
// property is true
//
// Alternately, if this code point is a non-starter,
// it's excluded from composition
if (
info.CompositionExclusion ||
(info.CanonicalCombiningClass!=0)
) {
info.FullCompositionExclusion=true;
return;
}
auto & vec=cps[info.DecompositionMapping];
// If there's no decomposition, ignore
if (vec.size()==0) return;
// If this code point decomposes to a single character,
// it shouldn't be composed to
if (vec.size()==1) {
info.FullCompositionExclusion=true;
return;
}
// If this code point decomposes to a sequence
// which begins with a non-starter, it is excluded
auto iter=find(vec[0]);
if (!(
(iter==this->info.end()) ||
(iter->CanonicalCombiningClass==0)
)) {
info.FullCompositionExclusion=true;
return;
}
}
void Parser::get_full_composition_exclusion () {
for (auto & i : info) get_full_composition_exclusion(i);
}
static bool compare (const std::vector<CodePoint::Type> & a, const std::vector<CodePoint::Type> & b) noexcept {
auto a_b=a.begin();
auto a_e=a.end();
auto b_b=b.begin();
auto b_e=b.end();
for (
;
!(
(a_b==a_e) ||
(b_b==b_e)
);
++a_b,++b_b
) {
auto & a=*a_b;
auto & b=*b_b;
if (a<b) return true;
if (a==b) continue;
return false;
}
return (a_b==a_e) && (b_b!=b_e);
}
void Parser::sort_compositions () {
std::sort(
comps.begin(),
comps.end(),
[&] (const Composition & a, const Composition & b) noexcept {
return compare(
cps[a.Composition],
cps[b.Composition]
);
}
);
}
void Parser::get_compositions (const Info & info) {
comps.push_back(
Composition{
info.CodePoint,
info.DecompositionMapping
}
);
}
void Parser::get_compositions () {
for (auto & i : info) {
// Exclude code points that are excluded
// from composition, or which do not have
// a decomposition
if (
i.FullCompositionExclusion ||
(cps[i.DecompositionMapping].size()==0)
) continue;
get_compositions(i);
}
// Sort the compositions
sort_compositions();
}
void Parser::output (const std::string & str) {
if (str.size()==0) out << "nullptr";
else out.WriteString(str);
}
void Parser::output (bool bln) {
out << (bln ? "true" : "false");
}
void Parser::output (const ConditionInfo & c) {
out << "{";
output(c.Negated);
out << ",";
out.WriteString(c.Name);
out << "}";
}
void Parser::output (const ::Array & arr, const std::string & str) {
out << "{";
if (arr.Size!=0) out << "&" << str << "[" << arr.Offset << "]," << arr.Size;
out << "}";
}
void Parser::output (const Numeric & n) {
out << "Numeric{NumericType::" << from_enum(numeric_type,n.Type) << "," << n.Value << "}";
}
void Parser::next (bool newline) {
out << ",";
if (newline) out << Newline;
}
void Parser::output_cps () {
out.BeginArray("CodePoint::Type","cps");
bool first=true;
for (auto cp : cps) {
if (first) first=false;
else out << ",";
output(cp);
}
out.EndArray();
}
void Parser::output_blocks () {
out.BeginArray("char *","blocks");
out.BeginIndent();
bool first=true;
for (auto & block : blocks) {
if (first) first=false;
else out << "," << Newline;
output(block);
}
out.EndIndent();
out.EndArray();
}
void Parser::output_scripts () {
out.BeginArray("char *","scripts");
out.BeginIndent();
bool first=true;
for (auto & script : scripts) {
if (first) first=false;
else out << "," << Newline;
output(script);
}
out.EndIndent();
out.EndArray();
}
void Parser::output_conds () {
out.BeginArray("Condition","conds");
bool first=true;
for (auto & c : conds) {
if (first) first=false;
else out << ",";
output(c);
}
out.EndArray();
}
void Parser::output_arrays () {
output_cps();
out.WhiteSpace();
output_blocks();
out.WhiteSpace();
output_scripts();
out.WhiteSpace();
output_conds();
out.WhiteSpace();
casing.Output();
}
void Parser::output_code_point_info_inner (const Info & info) {
// Get casing information for this
// code point
auto casing_info=casing.Get(info.CodePoint);
output(info.CodePoint);
next();
output(info.Name);
next();
output(info.Alias);
next();
output(info.Abbreviation);
next();
if (info.Block) out << "blocks[" << *info.Block << "]";
else out << "nullptr";
next();
out << "GeneralCategory::" << from_enum(general_category,info.GeneralCategory);
next();
if (info.Script) out << "scripts[" << *info.Script << "]";
else out << "nullptr";
next();
output(info.WhiteSpace);
next();
output(info.Alphabetic);
next();
output(info.NoncharacterCodePoint);
next();
output(info.DefaultIgnorableCodePoint);
next();
output(info.Deprecated);
next();
output(info.LogicalOrderException);
next();
output(info.VariationSelector);
next();
output(info.Uppercase);
next();
output(info.Lowercase);
next();
auto str="mappings";
output(casing_info.LowercaseMappings,str);
next();
output(casing_info.TitlecaseMappings,str);
next();
output(casing_info.UppercaseMappings,str);
next();
output(casing_info.CaseFoldings,str);
next();
output(info.SimpleLowercaseMapping);
next();
output(info.SimpleTitlecaseMapping);
next();
output(info.SimpleUppercaseMapping);
next();
output(casing_info.SimpleCaseFolding);
next();
output(info.SoftDotted);
next();
output(info.Cased);
next();
output(info.CaseIgnorable);
next();
output(info.Numeric);
next();
output(info.HexDigit);
next();
output(info.ASCIIHexDigit);
next();
out << info.CanonicalCombiningClass;
next();
output(
cps.Get(info.DecompositionMapping),
"cps"
);
next();
output(info.CompositionExclusion);
next();
output(info.FullCompositionExclusion);
next();
out << "QuickCheck::" << from_enum(quick_check,info.NFCQuickCheck);
next();
out << "QuickCheck::" << from_enum(quick_check,info.NFDQuickCheck);
next();
out << "LineBreak::" << from_enum(::line_break,info.LineBreak);
next();
out << "GraphemeClusterBreak::" << from_enum(::grapheme_cluster_break,info.GraphemeClusterBreak);
next();
out << "SentenceBreak::" << from_enum(::sentence_break,info.SentenceBreak);
next();
out << "WordBreak::" << from_enum(::word_break,info.WordBreak);
next();
out << "BidirectionalClass::" << from_enum(bidi_class,info.BidirectionalClass);
next();
output(info.BidirectionalControl);
next();
output(info.Mirrored);
next();
output(info.Ideographic);
next();
output(info.UnifiedIdeograph);
next();
output(info.Radical);
next();
output(info.Math);
next();
output(info.QuotationMark);
next();
output(info.Dash);
next();
output(info.Hyphen);
next();
output(info.STerm);
next();
output(info.TerminalPunctuation);
next();
output(info.Diacritic);
next();
output(info.Extender);
next();
output(info.GraphemeBase);
next();
output(info.GraphemeLink);
}
void Parser::output_code_point_info (const Info & info) {
out << "{";
out.BeginIndent();
output_code_point_info_inner(info);
out.EndIndent();
out << "}";
}
void Parser::output_code_point_info () {
out.BeginArray("CodePointInfo","info");
out.BeginIndent();
bool first=true;
for (auto & i : info) {
if (first) first=false;
else out << "," << Newline;
output_code_point_info(i);
}
out.EndIndent();
out.EndArray();
}
void Parser::output_composition (const Composition & comp) {
out << "{";
output(cps.Get(comp.Composition),"cps");
out << ",";
output(comp.CodePoint);
out << "}";
}
void Parser::output_compositions () {
out.BeginArray("Composition","compositions");
out.BeginIndent();
bool first=true;
for (auto & comp : comps) {
if (first) first=false;
else out << "," << Newline;
output_composition(comp);
}
out.EndIndent();
out.EndArray();
}
Parser::Parser (const std::string & base, const std::string & output)
: data(Join(base,"UnicodeData.txt").c_str()),
prop_list(Join(base,"PropList.txt").c_str()),
b(Join(base,"Blocks.txt").c_str()),
s(Join(base,"Scripts.txt").c_str()),
name_aliases(Join(base,"NameAliases.txt").c_str()),
composition_exclusions(Join(base,"CompositionExclusions.txt").c_str()),
line_break(Join(base,"LineBreak.txt").c_str()),
grapheme_break(Join(base,"auxiliary","GraphemeBreakProperty.txt").c_str()),
sentence_break(Join(base,"auxiliary","SentenceBreakProperty.txt").c_str()),
word_break(Join(base,"auxiliary","WordBreakProperty.txt").c_str()),
derived_normalization_props(Join(base,"DerivedNormalizationProps.txt").c_str()),
out(output),
casing(
base,
cps,
conds,
out
)
{ }
void Parser::Get () {
// Fire nested objects
casing.Get();
// Get UnicodeData.txt
get_data();
// Get PropList.txt
get_prop_list();
// Get Blocks.txt
get_blocks();
// Get Scripts.txt
get_scripts();
// Get NameAliases.txt
get_name_aliases();
// Get CompositionExclusions.txt
get_composition_exclusions();
// Get LineBreak.txt
get_line_break();
// Get GraphemeBreakProperty.txt
get_grapheme_cluster_break();
// Get SentenceBreakProperty.txt
get_sentence_break();
// Get WordBreakProperty.txt
get_word_break();
// Get DerivedNormalizationProps.txt
get_derived_normalization_props();
// Derive full composition exclusion
get_full_composition_exclusion();
// Get compositions
get_compositions();
}
void Parser::Output () {
// Print out required headers
out.Header("unicode/codepoint.hpp");
out.Header("utility");
// Begin the Unicode namespace
out.WhiteSpace();
out.BeginNamespace("Unicode");
// Output arrays
output_arrays();
out.WhiteSpace();
// Output CodePointInfo structures
output_code_point_info();
// Output compositions
output_compositions();
// Done
out.EndNamespace();
out.End();
}
| 18.713193 | 111 | 0.663193 | [
"vector"
] |
7fc69a4010b723d3168dc711a34c84ab25b01449 | 25,017 | cpp | C++ | qtdeclarative/src/qml/jsruntime/qv4sequenceobject.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | qtdeclarative/src/qml/jsruntime/qv4sequenceobject.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | qtdeclarative/src/qml/jsruntime/qv4sequenceobject.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtQml/qqml.h>
#include "qv4sequenceobject_p.h"
#include <private/qv4functionobject_p.h>
#include <private/qv4arrayobject_p.h>
#include <private/qqmlengine_p.h>
#include <private/qv4scopedvalue_p.h>
#include "qv4runtime_p.h"
#include "qv4objectiterator_p.h"
#include <private/qqmlvaluetypewrapper_p.h>
#include <private/qqmlmodelindexvaluetype_p.h>
#include <QtCore/qabstractitemmodel.h>
#include <algorithm>
QT_BEGIN_NAMESPACE
using namespace QV4;
// helper function to generate valid warnings if errors occur during sequence operations.
static void generateWarning(QV4::ExecutionEngine *v4, const QString& description)
{
QQmlEngine *engine = v4->qmlEngine();
if (!engine)
return;
QQmlError retn;
retn.setDescription(description);
QV4::StackFrame frame = v4->currentStackFrame();
retn.setLine(frame.line);
retn.setUrl(QUrl(frame.source));
QQmlEnginePrivate::warning(engine, retn);
}
// F(elementType, elementTypeName, sequenceType, defaultValue)
#define FOREACH_QML_SEQUENCE_TYPE(F) \
F(int, Int, QList<int>, 0) \
F(qreal, Real, QList<qreal>, 0.0) \
F(bool, Bool, QList<bool>, false) \
F(QString, String, QList<QString>, QString()) \
F(QString, QString, QStringList, QString()) \
F(QUrl, Url, QList<QUrl>, QUrl()) \
F(QModelIndex, QModelIndex, QModelIndexList, QModelIndex()) \
F(QItemSelectionRange, QItemSelectionRange, QItemSelection, QItemSelectionRange())
static QV4::ReturnedValue convertElementToValue(QV4::ExecutionEngine *engine, const QString &element)
{
return engine->newString(element)->asReturnedValue();
}
static QV4::ReturnedValue convertElementToValue(QV4::ExecutionEngine *, int element)
{
return QV4::Encode(element);
}
static QV4::ReturnedValue convertElementToValue(QV4::ExecutionEngine *engine, const QUrl &element)
{
return engine->newString(element.toString())->asReturnedValue();
}
static QV4::ReturnedValue convertElementToValue(QV4::ExecutionEngine *engine, const QModelIndex &element)
{
const QMetaObject *vtmo = QQmlValueTypeFactory::metaObjectForMetaType(QMetaType::QModelIndex);
return QV4::QQmlValueTypeWrapper::create(engine, QVariant(element), vtmo, QMetaType::QModelIndex);
}
static QV4::ReturnedValue convertElementToValue(QV4::ExecutionEngine *engine, const QItemSelectionRange &element)
{
int metaTypeId = qMetaTypeId<QItemSelectionRange>();
const QMetaObject *vtmo = QQmlValueTypeFactory::metaObjectForMetaType(metaTypeId);
return QV4::QQmlValueTypeWrapper::create(engine, QVariant::fromValue(element), vtmo, metaTypeId);
}
static QV4::ReturnedValue convertElementToValue(QV4::ExecutionEngine *, qreal element)
{
return QV4::Encode(element);
}
static QV4::ReturnedValue convertElementToValue(QV4::ExecutionEngine *, bool element)
{
return QV4::Encode(element);
}
static QString convertElementToString(const QString &element)
{
return element;
}
static QString convertElementToString(int element)
{
return QString::number(element);
}
static QString convertElementToString(const QUrl &element)
{
return element.toString();
}
static QString convertElementToString(const QModelIndex &element)
{
return reinterpret_cast<const QQmlModelIndexValueType *>(&element)->toString();
}
static QString convertElementToString(const QItemSelectionRange &element)
{
return reinterpret_cast<const QQmlItemSelectionRangeValueType *>(&element)->toString();
}
static QString convertElementToString(qreal element)
{
QString qstr;
RuntimeHelpers::numberToString(&qstr, element, 10);
return qstr;
}
static QString convertElementToString(bool element)
{
if (element)
return QStringLiteral("true");
else
return QStringLiteral("false");
}
template <typename ElementType> ElementType convertValueToElement(const Value &value);
template <> QString convertValueToElement(const Value &value)
{
return value.toQString();
}
template <> int convertValueToElement(const Value &value)
{
return value.toInt32();
}
template <> QUrl convertValueToElement(const Value &value)
{
return QUrl(value.toQString());
}
template <> QModelIndex convertValueToElement(const Value &value)
{
const QQmlValueTypeWrapper *v = value.as<QQmlValueTypeWrapper>();
if (v)
return v->toVariant().toModelIndex();
return QModelIndex();
}
template <> QItemSelectionRange convertValueToElement(const Value &value)
{
const QQmlValueTypeWrapper *v = value.as<QQmlValueTypeWrapper>();
if (v)
return v->toVariant().value<QItemSelectionRange>();
return QItemSelectionRange();
}
template <> qreal convertValueToElement(const Value &value)
{
return value.toNumber();
}
template <> bool convertValueToElement(const Value &value)
{
return value.toBoolean();
}
namespace QV4 {
template <typename Container> struct QQmlSequence;
namespace Heap {
template <typename Container>
struct QQmlSequence : Object {
QQmlSequence(const Container &container);
QQmlSequence(QObject *object, int propertyIndex);
mutable Container container;
QPointer<QObject> object;
int propertyIndex;
bool isReference;
};
}
template <typename Container>
struct QQmlSequence : public QV4::Object
{
V4_OBJECT2(QQmlSequence<Container>, QV4::Object)
Q_MANAGED_TYPE(QmlSequence)
V4_PROTOTYPE(sequencePrototype)
V4_NEEDS_DESTROY
public:
void init()
{
defineAccessorProperty(QStringLiteral("length"), method_get_length, method_set_length);
}
QV4::ReturnedValue containerGetIndexed(uint index, bool *hasProperty) const
{
/* Qt containers have int (rather than uint) allowable indexes. */
if (index > INT_MAX) {
generateWarning(engine(), QLatin1String("Index out of range during indexed get"));
if (hasProperty)
*hasProperty = false;
return Encode::undefined();
}
if (d()->isReference) {
if (!d()->object) {
if (hasProperty)
*hasProperty = false;
return Encode::undefined();
}
loadReference();
}
qint32 signedIdx = static_cast<qint32>(index);
if (signedIdx < d()->container.count()) {
if (hasProperty)
*hasProperty = true;
return convertElementToValue(engine(), d()->container.at(signedIdx));
}
if (hasProperty)
*hasProperty = false;
return Encode::undefined();
}
void containerPutIndexed(uint index, const QV4::Value &value)
{
if (internalClass()->engine->hasException)
return;
/* Qt containers have int (rather than uint) allowable indexes. */
if (index > INT_MAX) {
generateWarning(engine(), QLatin1String("Index out of range during indexed set"));
return;
}
if (d()->isReference) {
if (!d()->object)
return;
loadReference();
}
qint32 signedIdx = static_cast<qint32>(index);
int count = d()->container.count();
typename Container::value_type element = convertValueToElement<typename Container::value_type>(value);
if (signedIdx == count) {
d()->container.append(element);
} else if (signedIdx < count) {
d()->container[signedIdx] = element;
} else {
/* according to ECMA262r3 we need to insert */
/* the value at the given index, increasing length to index+1. */
d()->container.reserve(signedIdx + 1);
while (signedIdx > count++) {
d()->container.append(typename Container::value_type());
}
d()->container.append(element);
}
if (d()->isReference)
storeReference();
}
QV4::PropertyAttributes containerQueryIndexed(uint index) const
{
/* Qt containers have int (rather than uint) allowable indexes. */
if (index > INT_MAX) {
generateWarning(engine(), QLatin1String("Index out of range during indexed query"));
return QV4::Attr_Invalid;
}
if (d()->isReference) {
if (!d()->object)
return QV4::Attr_Invalid;
loadReference();
}
qint32 signedIdx = static_cast<qint32>(index);
return (signedIdx < d()->container.count()) ? QV4::Attr_Data : QV4::Attr_Invalid;
}
void containerAdvanceIterator(ObjectIterator *it, Value *name, uint *index, Property *p, PropertyAttributes *attrs)
{
name->setM(0);
*index = UINT_MAX;
if (d()->isReference) {
if (!d()->object) {
QV4::Object::advanceIterator(this, it, name, index, p, attrs);
return;
}
loadReference();
}
if (it->arrayIndex < static_cast<uint>(d()->container.count())) {
*index = it->arrayIndex;
++it->arrayIndex;
*attrs = QV4::Attr_Data;
p->value = convertElementToValue(engine(), d()->container.at(*index));
return;
}
QV4::Object::advanceIterator(this, it, name, index, p, attrs);
}
bool containerDeleteIndexedProperty(uint index)
{
/* Qt containers have int (rather than uint) allowable indexes. */
if (index > INT_MAX)
return false;
if (d()->isReference) {
if (!d()->object)
return false;
loadReference();
}
qint32 signedIdx = static_cast<qint32>(index);
if (signedIdx >= d()->container.count())
return false;
/* according to ECMA262r3 it should be Undefined, */
/* but we cannot, so we insert a default-value instead. */
d()->container.replace(signedIdx, typename Container::value_type());
if (d()->isReference)
storeReference();
return true;
}
bool containerIsEqualTo(Managed *other)
{
if (!other)
return false;
QQmlSequence<Container> *otherSequence = other->as<QQmlSequence<Container> >();
if (!otherSequence)
return false;
if (d()->isReference && otherSequence->d()->isReference) {
return d()->object == otherSequence->d()->object && d()->propertyIndex == otherSequence->d()->propertyIndex;
} else if (!d()->isReference && !otherSequence->d()->isReference) {
return this == otherSequence;
}
return false;
}
struct DefaultCompareFunctor
{
bool operator()(typename Container::value_type lhs, typename Container::value_type rhs)
{
return convertElementToString(lhs) < convertElementToString(rhs);
}
};
struct CompareFunctor
{
CompareFunctor(QV4::ExecutionContext *ctx, const QV4::Value &compareFn)
: m_ctx(ctx), m_compareFn(&compareFn)
{}
bool operator()(typename Container::value_type lhs, typename Container::value_type rhs)
{
QV4::Scope scope(m_ctx);
ScopedObject compare(scope, m_compareFn);
ScopedCallData callData(scope, 2);
callData->args[0] = convertElementToValue(this->m_ctx->d()->engine, lhs);
callData->args[1] = convertElementToValue(this->m_ctx->d()->engine, rhs);
callData->thisObject = this->m_ctx->d()->engine->globalObject;
QV4::ScopedValue result(scope, compare->call(callData));
return result->toNumber() < 0;
}
private:
QV4::ExecutionContext *m_ctx;
const QV4::Value *m_compareFn;
};
void sort(QV4::CallContext *ctx)
{
if (d()->isReference) {
if (!d()->object)
return;
loadReference();
}
QV4::Scope scope(ctx);
if (ctx->argc() == 1 && ctx->args()[0].as<FunctionObject>()) {
CompareFunctor cf(ctx, ctx->args()[0]);
std::sort(d()->container.begin(), d()->container.end(), cf);
} else {
DefaultCompareFunctor cf;
std::sort(d()->container.begin(), d()->container.end(), cf);
}
if (d()->isReference)
storeReference();
}
static QV4::ReturnedValue method_get_length(QV4::CallContext *ctx)
{
QV4::Scope scope(ctx);
QV4::Scoped<QQmlSequence<Container> > This(scope, ctx->thisObject().as<QQmlSequence<Container> >());
if (!This)
return ctx->engine()->throwTypeError();
if (This->d()->isReference) {
if (!This->d()->object)
return QV4::Encode(0);
This->loadReference();
}
return QV4::Encode(This->d()->container.count());
}
static QV4::ReturnedValue method_set_length(QV4::CallContext* ctx)
{
QV4::Scope scope(ctx);
QV4::Scoped<QQmlSequence<Container> > This(scope, ctx->thisObject().as<QQmlSequence<Container> >());
if (!This)
return ctx->engine()->throwTypeError();
quint32 newLength = ctx->args()[0].toUInt32();
/* Qt containers have int (rather than uint) allowable indexes. */
if (newLength > INT_MAX) {
generateWarning(scope.engine, QLatin1String("Index out of range during length set"));
return QV4::Encode::undefined();
}
/* Read the sequence from the QObject property if we're a reference */
if (This->d()->isReference) {
if (!This->d()->object)
return QV4::Encode::undefined();
This->loadReference();
}
/* Determine whether we need to modify the sequence */
qint32 newCount = static_cast<qint32>(newLength);
qint32 count = This->d()->container.count();
if (newCount == count) {
return QV4::Encode::undefined();
} else if (newCount > count) {
/* according to ECMA262r3 we need to insert */
/* undefined values increasing length to newLength. */
/* We cannot, so we insert default-values instead. */
This->d()->container.reserve(newCount);
while (newCount > count++) {
This->d()->container.append(typename Container::value_type());
}
} else {
/* according to ECMA262r3 we need to remove */
/* elements until the sequence is the required length. */
while (newCount < count) {
count--;
This->d()->container.removeAt(count);
}
}
/* write back if required. */
if (This->d()->isReference) {
/* write back. already checked that object is non-null, so skip that check here. */
This->storeReference();
}
return QV4::Encode::undefined();
}
QVariant toVariant() const
{ return QVariant::fromValue<Container>(d()->container); }
static QVariant toVariant(QV4::ArrayObject *array)
{
QV4::Scope scope(array->engine());
Container result;
quint32 length = array->getLength();
QV4::ScopedValue v(scope);
for (quint32 i = 0; i < length; ++i)
result << convertValueToElement<typename Container::value_type>((v = array->getIndexed(i)));
return QVariant::fromValue(result);
}
void loadReference() const
{
Q_ASSERT(d()->object);
Q_ASSERT(d()->isReference);
void *a[] = { &d()->container, 0 };
QMetaObject::metacall(d()->object, QMetaObject::ReadProperty, d()->propertyIndex, a);
}
void storeReference()
{
Q_ASSERT(d()->object);
Q_ASSERT(d()->isReference);
int status = -1;
QQmlPropertyPrivate::WriteFlags flags = QQmlPropertyPrivate::DontRemoveBinding;
void *a[] = { &d()->container, 0, &status, &flags };
QMetaObject::metacall(d()->object, QMetaObject::WriteProperty, d()->propertyIndex, a);
}
static QV4::ReturnedValue getIndexed(const QV4::Managed *that, uint index, bool *hasProperty)
{ return static_cast<const QQmlSequence<Container> *>(that)->containerGetIndexed(index, hasProperty); }
static void putIndexed(Managed *that, uint index, const QV4::Value &value)
{ static_cast<QQmlSequence<Container> *>(that)->containerPutIndexed(index, value); }
static QV4::PropertyAttributes queryIndexed(const QV4::Managed *that, uint index)
{ return static_cast<const QQmlSequence<Container> *>(that)->containerQueryIndexed(index); }
static bool deleteIndexedProperty(QV4::Managed *that, uint index)
{ return static_cast<QQmlSequence<Container> *>(that)->containerDeleteIndexedProperty(index); }
static bool isEqualTo(Managed *that, Managed *other)
{ return static_cast<QQmlSequence<Container> *>(that)->containerIsEqualTo(other); }
static void advanceIterator(Managed *that, ObjectIterator *it, Value *name, uint *index, Property *p, PropertyAttributes *attrs)
{ return static_cast<QQmlSequence<Container> *>(that)->containerAdvanceIterator(it, name, index, p, attrs); }
};
template <typename Container>
Heap::QQmlSequence<Container>::QQmlSequence(const Container &container)
: container(container)
, propertyIndex(-1)
, isReference(false)
{
QV4::Scope scope(internalClass->engine);
QV4::Scoped<QV4::QQmlSequence<Container> > o(scope, this);
o->setArrayType(Heap::ArrayData::Custom);
o->init();
}
template <typename Container>
Heap::QQmlSequence<Container>::QQmlSequence(QObject *object, int propertyIndex)
: object(object)
, propertyIndex(propertyIndex)
, isReference(true)
{
QV4::Scope scope(internalClass->engine);
QV4::Scoped<QV4::QQmlSequence<Container> > o(scope, this);
o->setArrayType(Heap::ArrayData::Custom);
o->loadReference();
o->init();
}
}
namespace QV4 {
typedef QQmlSequence<QStringList> QQmlQStringList;
DEFINE_OBJECT_TEMPLATE_VTABLE(QQmlQStringList);
typedef QQmlSequence<QList<QString> > QQmlStringList;
DEFINE_OBJECT_TEMPLATE_VTABLE(QQmlStringList);
typedef QQmlSequence<QList<int> > QQmlIntList;
DEFINE_OBJECT_TEMPLATE_VTABLE(QQmlIntList);
typedef QQmlSequence<QList<QUrl> > QQmlUrlList;
DEFINE_OBJECT_TEMPLATE_VTABLE(QQmlUrlList);
typedef QQmlSequence<QModelIndexList> QQmlQModelIndexList;
DEFINE_OBJECT_TEMPLATE_VTABLE(QQmlQModelIndexList);
typedef QQmlSequence<QItemSelection> QQmlQItemSelectionRangeList;
DEFINE_OBJECT_TEMPLATE_VTABLE(QQmlQItemSelectionRangeList);
typedef QQmlSequence<QList<bool> > QQmlBoolList;
DEFINE_OBJECT_TEMPLATE_VTABLE(QQmlBoolList);
typedef QQmlSequence<QList<qreal> > QQmlRealList;
DEFINE_OBJECT_TEMPLATE_VTABLE(QQmlRealList);
}
#define REGISTER_QML_SEQUENCE_METATYPE(unused, unused2, SequenceType, unused3) qRegisterMetaType<SequenceType>(#SequenceType);
void SequencePrototype::init()
{
FOREACH_QML_SEQUENCE_TYPE(REGISTER_QML_SEQUENCE_METATYPE)
defineDefaultProperty(QStringLiteral("sort"), method_sort, 1);
defineDefaultProperty(engine()->id_valueOf(), method_valueOf, 0);
}
#undef REGISTER_QML_SEQUENCE_METATYPE
QV4::ReturnedValue SequencePrototype::method_sort(QV4::CallContext *ctx)
{
QV4::Scope scope(ctx);
QV4::ScopedObject o(scope, ctx->thisObject());
if (!o || !o->isListType())
return ctx->engine()->throwTypeError();
if (ctx->argc() >= 2)
return o.asReturnedValue();
#define CALL_SORT(SequenceElementType, SequenceElementTypeName, SequenceType, DefaultValue) \
if (QQml##SequenceElementTypeName##List *s = o->as<QQml##SequenceElementTypeName##List>()) { \
s->sort(ctx); \
} else
FOREACH_QML_SEQUENCE_TYPE(CALL_SORT)
#undef CALL_SORT
{}
return o.asReturnedValue();
}
#define IS_SEQUENCE(unused1, unused2, SequenceType, unused3) \
if (sequenceTypeId == qMetaTypeId<SequenceType>()) { \
return true; \
} else
bool SequencePrototype::isSequenceType(int sequenceTypeId)
{
FOREACH_QML_SEQUENCE_TYPE(IS_SEQUENCE) { /* else */ return false; }
}
#undef IS_SEQUENCE
#define NEW_REFERENCE_SEQUENCE(ElementType, ElementTypeName, SequenceType, unused) \
if (sequenceType == qMetaTypeId<SequenceType>()) { \
QV4::ScopedObject obj(scope, engine->memoryManager->allocObject<QQml##ElementTypeName##List>(object, propertyIndex)); \
return obj.asReturnedValue(); \
} else
ReturnedValue SequencePrototype::newSequence(QV4::ExecutionEngine *engine, int sequenceType, QObject *object, int propertyIndex, bool *succeeded)
{
QV4::Scope scope(engine);
// This function is called when the property is a QObject Q_PROPERTY of
// the given sequence type. Internally we store a typed-sequence
// (as well as object ptr + property index for updated-read and write-back)
// and so access/mutate avoids variant conversion.
*succeeded = true;
FOREACH_QML_SEQUENCE_TYPE(NEW_REFERENCE_SEQUENCE) { /* else */ *succeeded = false; return QV4::Encode::undefined(); }
}
#undef NEW_REFERENCE_SEQUENCE
#define NEW_COPY_SEQUENCE(ElementType, ElementTypeName, SequenceType, unused) \
if (sequenceType == qMetaTypeId<SequenceType>()) { \
QV4::ScopedObject obj(scope, engine->memoryManager->allocObject<QQml##ElementTypeName##List>(v.value<SequenceType >())); \
return obj.asReturnedValue(); \
} else
ReturnedValue SequencePrototype::fromVariant(QV4::ExecutionEngine *engine, const QVariant& v, bool *succeeded)
{
QV4::Scope scope(engine);
// This function is called when assigning a sequence value to a normal JS var
// in a JS block. Internally, we store a sequence of the specified type.
// Access and mutation is extremely fast since it will not need to modify any
// QObject property.
int sequenceType = v.userType();
*succeeded = true;
FOREACH_QML_SEQUENCE_TYPE(NEW_COPY_SEQUENCE) { /* else */ *succeeded = false; return QV4::Encode::undefined(); }
}
#undef NEW_COPY_SEQUENCE
#define SEQUENCE_TO_VARIANT(ElementType, ElementTypeName, SequenceType, unused) \
if (QQml##ElementTypeName##List *list = object->as<QQml##ElementTypeName##List>()) \
return list->toVariant(); \
else
QVariant SequencePrototype::toVariant(Object *object)
{
Q_ASSERT(object->isListType());
FOREACH_QML_SEQUENCE_TYPE(SEQUENCE_TO_VARIANT) { /* else */ return QVariant(); }
}
#undef SEQUENCE_TO_VARIANT
#define SEQUENCE_TO_VARIANT(ElementType, ElementTypeName, SequenceType, unused) \
if (typeHint == qMetaTypeId<SequenceType>()) { \
return QQml##ElementTypeName##List::toVariant(a); \
} else
QVariant SequencePrototype::toVariant(const QV4::Value &array, int typeHint, bool *succeeded)
{
*succeeded = true;
if (!array.as<ArrayObject>()) {
*succeeded = false;
return QVariant();
}
QV4::Scope scope(array.as<Object>()->engine());
QV4::ScopedArrayObject a(scope, array);
FOREACH_QML_SEQUENCE_TYPE(SEQUENCE_TO_VARIANT) { /* else */ *succeeded = false; return QVariant(); }
}
#undef SEQUENCE_TO_VARIANT
#define MAP_META_TYPE(ElementType, ElementTypeName, SequenceType, unused) \
if (object->as<QQml##ElementTypeName##List>()) { \
return qMetaTypeId<SequenceType>(); \
} else
int SequencePrototype::metaTypeForSequence(const QV4::Object *object)
{
FOREACH_QML_SEQUENCE_TYPE(MAP_META_TYPE)
/*else*/ {
return -1;
}
}
#undef MAP_META_TYPE
QT_END_NAMESPACE
| 34.649584 | 145 | 0.657873 | [
"object"
] |
7fc9cc6a8c6ffe64ac543a2f5b632d84115a24d1 | 5,326 | cpp | C++ | kratos/tests/cpp_tests/containers/test_nodal_data.cpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 778 | 2017-01-27T16:29:17.000Z | 2022-03-30T03:01:51.000Z | kratos/tests/cpp_tests/containers/test_nodal_data.cpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 6,634 | 2017-01-15T22:56:13.000Z | 2022-03-31T15:03:36.000Z | kratos/tests/cpp_tests/containers/test_nodal_data.cpp | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | 224 | 2017-02-07T14:12:49.000Z | 2022-03-06T23:09:34.000Z | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license:
//kratos/license.txt
//
// Main authors: Pooyan Dadvand
//
//
// System includes
#include <unordered_set>
// External includes
// Project includes
#include "testing/testing.h"
#include "containers/nodal_data.h"
#include "includes/stream_serializer.h"
#include "containers/model.h"
namespace Kratos {
namespace Testing {
KRATOS_TEST_CASE_IN_SUITE(NodalSolutionStepData, KratosCoreFastSuite)
{
Model current_model;
const int repeat = 10;
ModelPart& model_part = current_model.CreateModelPart("test");
model_part.AddNodalSolutionStepVariable(DISTANCE);
model_part.AddNodalSolutionStepVariable(VELOCITY);
const std::size_t size = 10;
for (std::size_t i = 0; i < size; i++)
model_part.CreateNewNode(i, i, 0, 0);
for (int i = 0; i < repeat; i++) {
for (auto i_node = model_part.NodesBegin(); i_node != model_part.NodesEnd(); i_node++) {
i_node->FastGetSolutionStepValue(DISTANCE) = static_cast<double>(i);
i_node->FastGetSolutionStepValue(VELOCITY_X) = static_cast<double>(i);
}
double distance_sum = 0;
double velocity_x_sum = 0;
for (auto i_node = model_part.NodesBegin(); i_node != model_part.NodesEnd(); i_node++) {
distance_sum += i_node->FastGetSolutionStepValue(DISTANCE);
velocity_x_sum += i_node->FastGetSolutionStepValue(VELOCITY_X) * 2;
}
KRATOS_CHECK_DOUBLE_EQUAL(distance_sum, i * size);
KRATOS_CHECK_DOUBLE_EQUAL(velocity_x_sum, i * size * 2);
}
}
KRATOS_TEST_CASE_IN_SUITE(FluidNodalSolutionStepData, KratosCoreFastSuite)
{
Model current_model;
const int repeat = 10;
ModelPart& model_part = current_model.CreateModelPart("test");
model_part.AddNodalSolutionStepVariable(PRESSURE);
model_part.AddNodalSolutionStepVariable(VELOCITY);
model_part.AddNodalSolutionStepVariable(FRACT_VEL);
model_part.AddNodalSolutionStepVariable(MESH_VELOCITY);
model_part.AddNodalSolutionStepVariable(NODAL_AREA);
model_part.AddNodalSolutionStepVariable(BODY_FORCE);
model_part.AddNodalSolutionStepVariable(DENSITY);
model_part.AddNodalSolutionStepVariable(VISCOSITY);
model_part.AddNodalSolutionStepVariable(FLAG_VARIABLE);
model_part.AddNodalSolutionStepVariable(DISPLACEMENT);
model_part.AddNodalSolutionStepVariable(REACTION);
model_part.AddNodalSolutionStepVariable(NORMAL);
std::size_t size = 10;
for (std::size_t i = 0; i < size; i++)
model_part.CreateNewNode(i, i, 0, 0);
for (int i = 0; i < repeat; i++) {
for (auto i_node = model_part.NodesBegin(); i_node != model_part.NodesEnd(); i_node++) {
i_node->FastGetSolutionStepValue(PRESSURE) = static_cast<double>(i);
i_node->FastGetSolutionStepValue(VELOCITY_X) = static_cast<double>(2*i);
}
double pressure_sum = 0;
double velocity_x_sum = 0;
double velocity_y_sum = 0;
for (auto i_node = model_part.NodesBegin(); i_node != model_part.NodesEnd(); i_node++) {
pressure_sum += i_node->FastGetSolutionStepValue(PRESSURE);
velocity_x_sum += i_node->FastGetSolutionStepValue(VELOCITY_X);
velocity_y_sum += i_node->FastGetSolutionStepValue(VELOCITY_Y);
}
KRATOS_CHECK_DOUBLE_EQUAL(pressure_sum, i * size);
KRATOS_CHECK_DOUBLE_EQUAL(velocity_x_sum, 2*i * size);
KRATOS_CHECK_DOUBLE_EQUAL(velocity_y_sum, 0.00);
}
}
KRATOS_TEST_CASE_IN_SUITE(NodalSolutionStepDataSerialization, KratosCoreFastSuite)
{
Model current_model;
ModelPart& model_part = current_model.CreateModelPart("test");
model_part.AddNodalSolutionStepVariable(DISTANCE);
model_part.AddNodalSolutionStepVariable(VELOCITY);
StreamSerializer serializer;
const std::string tag_string("Node");
Node<3>::Pointer p_node_to_be_saved = model_part.CreateNewNode(1, 1, 0, 0);
p_node_to_be_saved->FastGetSolutionStepValue(DISTANCE) = 1.12;
p_node_to_be_saved->FastGetSolutionStepValue(VELOCITY_X) = 2.32;
Node<3>::Pointer p_node_to_be_loaded(nullptr);
serializer.save(tag_string, p_node_to_be_saved);
serializer.load(tag_string, p_node_to_be_loaded);
KRATOS_CHECK_EQUAL(p_node_to_be_loaded->Id() , 1);
KRATOS_CHECK_DOUBLE_EQUAL(p_node_to_be_loaded->FastGetSolutionStepValue(DISTANCE), 1.12);
KRATOS_CHECK_DOUBLE_EQUAL(p_node_to_be_loaded->FastGetSolutionStepValue(VELOCITY_X), 2.32);
}
KRATOS_TEST_CASE_IN_SUITE(NodalDataSerialization, KratosCoreFastSuite) {
Model current_model;
ModelPart& model_part = current_model.CreateModelPart("test");
model_part.AddNodalSolutionStepVariable(DISTANCE);
model_part.AddNodalSolutionStepVariable(VELOCITY);
NodalData nodal_data_to_be_saved(23, &model_part.GetNodalSolutionStepVariablesList());
NodalData nodal_data_to_be_loaded(42, &model_part.GetNodalSolutionStepVariablesList());
StreamSerializer serializer;
serializer.save("NodalData", nodal_data_to_be_saved);
serializer.load("NodalData", nodal_data_to_be_loaded);
KRATOS_CHECK_EQUAL(nodal_data_to_be_saved.Id(), nodal_data_to_be_loaded.Id());
}
}
} // namespace Kratos.
| 36.479452 | 99 | 0.725498 | [
"model"
] |
7fcbdad4468667b666c8b60bc11456e4a14a2c81 | 1,599 | cpp | C++ | C++/twoSum.cpp | ayushyado/HACKTOBERFEST2021-2 | b63d568fd7f33023ca0b0dbd91325444c70c4d10 | [
"MIT"
] | 125 | 2021-10-01T19:05:26.000Z | 2021-10-03T13:32:42.000Z | C++/twoSum.cpp | ayushyado/HACKTOBERFEST2021-2 | b63d568fd7f33023ca0b0dbd91325444c70c4d10 | [
"MIT"
] | 201 | 2021-10-30T20:40:01.000Z | 2022-03-22T17:26:28.000Z | C++/twoSum.cpp | ayushyado/HACKTOBERFEST2021-2 | b63d568fd7f33023ca0b0dbd91325444c70c4d10 | [
"MIT"
] | 294 | 2021-10-01T18:46:05.000Z | 2021-10-03T14:25:07.000Z | /*
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
*/
#include <iostream>
#include <vector>
#include <map>
using namespace std;
vector<int> twoSum(vector<int>& nums, int target)
{
map<int, int> umap;
int difference;
for(int i = 0; i < nums.size(); i++ ){
difference = target - nums.at(i);
if(umap.find(difference) != umap.end()) {
vector<int> v{umap[difference], i};
return v;
} else {
umap[nums.at(i)] = i;
}
}
return vector<int> {};
}
// Driver code
int main() {
int n,target;
cout << "Enter the size of vector/array: ";
cin >> n;
vector<int> nums(n);
cout << "Enter vector/array elements: ";
for(int i = 0;i<n;i++)
{
cin >> nums[i];
}
cout << "Enter the target sum: ";
cin >> target;
for(int i=0;i<twoSum(nums,target).size();i++)
{
cout << twoSum(nums,target)[i] << " ";
}
cout << endl;
}
/*
Test Case - 1:
Enter the size of vector/array: 4
Enter vector/array elements: 2 7 11 15
Enter the target sum: 9
Answer: 0 1
Test Case - 2:
Enter the size of vector/array: 3
Enter vector/array elements: 3 2 4
Enter the target sum: 6
Answer: 1 2
Link to the problem: https://leetcode.com/problems/two-sum/
*/ | 22.521127 | 121 | 0.561601 | [
"vector"
] |
7fcc37a65648b84d252a1622ff459cfaa10d6723 | 3,042 | cpp | C++ | Lib/OgreBullet/Collisions/src/Shapes/OgreBulletCollisionsTriangleShape.cpp | liuloppan/KinectOgreGame | 5a9c9ef5dd20d2195bd0167284206329ee13d9ab | [
"MIT"
] | 2 | 2017-06-21T12:20:33.000Z | 2018-12-13T15:48:05.000Z | Lib/OgreBullet/Collisions/src/Shapes/OgreBulletCollisionsTriangleShape.cpp | liuloppan/KinectOgreGame | 5a9c9ef5dd20d2195bd0167284206329ee13d9ab | [
"MIT"
] | 1 | 2019-03-07T13:11:40.000Z | 2019-03-07T13:11:40.000Z | Lib/OgreBullet/Collisions/src/Shapes/OgreBulletCollisionsTriangleShape.cpp | liuloppan/KinectOgreGame | 5a9c9ef5dd20d2195bd0167284206329ee13d9ab | [
"MIT"
] | 2 | 2017-05-29T06:24:11.000Z | 2019-03-07T06:42:09.000Z | /***************************************************************************
This source file is part of OGREBULLET
(Object-oriented Graphics Rendering Engine Bullet Wrapper)
For the latest info, see http://www.ogre3d.org/phpBB2addons/viewforum.php?f=10
Copyright (c) 2007 tuan.kuranes@gmail.com (Use it Freely, even Statically, but have to contribute any changes)
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 "OgreBulletCollisions.h"
#include "Shapes/OgreBulletCollisionsTriangleShape.h"
#include "BulletCollision/CollisionShapes/btTriangleShape.h"
#include "Utils/OgreBulletConverter.h"
#include "Debug/OgreBulletCollisionsDebugLines.h"
using namespace Ogre;
using namespace OgreBulletCollisions;
namespace OgreBulletCollisions
{
// -------------------------------------------------------------------------
TriangleCollisionShape::TriangleCollisionShape(
const Ogre::Vector3 &p1,
const Ogre::Vector3 &p2,
const Ogre::Vector3 &p3):
CollisionShape()
{
mShape = new btTriangleShape(OgreBtConverter::to(p1),
OgreBtConverter::to(p2),
OgreBtConverter::to(p3));
}
// -------------------------------------------------------------------------
TriangleCollisionShape::TriangleCollisionShape(
Ogre::Real p1X, Ogre::Real p1Y, Ogre::Real p1Z,
Ogre::Real p2X, Ogre::Real p2Y, Ogre::Real p2Z,
Ogre::Real p3X, Ogre::Real p3Y, Ogre::Real p3Z):
CollisionShape()
{
mShape = new btTriangleShape(btVector3(p1X, p1Z, p1Z),
btVector3(p2X, p2Y, p2Z),
btVector3(p3X, p3Y, p3Z));
}
// -------------------------------------------------------------------------
TriangleCollisionShape::~TriangleCollisionShape()
{
}
}
| 42.25 | 111 | 0.595989 | [
"object"
] |
7fd50801187eb9589342f25d2f42a834add326cd | 2,645 | cpp | C++ | Code/UnitTests/ToolsFoundationTest/Object/TestObjectManager.cpp | fereeh/ezEngine | 14e46cb2a1492812888602796db7ddd66e2b7110 | [
"MIT"
] | 1 | 2021-06-23T14:44:02.000Z | 2021-06-23T14:44:02.000Z | Code/UnitTests/ToolsFoundationTest/Object/TestObjectManager.cpp | fereeh/ezEngine | 14e46cb2a1492812888602796db7ddd66e2b7110 | [
"MIT"
] | null | null | null | Code/UnitTests/ToolsFoundationTest/Object/TestObjectManager.cpp | fereeh/ezEngine | 14e46cb2a1492812888602796db7ddd66e2b7110 | [
"MIT"
] | null | null | null | #include <ToolsFoundationTestPCH.h>
#include <ToolsFoundationTest/Object/TestObjectManager.h>
EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezTestDocument, 1, ezRTTINoAllocator)
EZ_END_DYNAMIC_REFLECTED_TYPE;
ezTestDocumentObjectManager::ezTestDocumentObjectManager() {}
ezTestDocumentObjectManager::~ezTestDocumentObjectManager() {}
ezTestDocument::ezTestDocument(const char* szDocumentPath, bool bUseIPCObjectMirror /*= false*/)
: ezDocument(szDocumentPath, EZ_DEFAULT_NEW(ezTestDocumentObjectManager))
, m_bUseIPCObjectMirror(bUseIPCObjectMirror)
{
}
ezTestDocument::~ezTestDocument()
{
if (m_bUseIPCObjectMirror)
{
m_ObjectMirror.Clear();
m_ObjectMirror.DeInit();
}
}
void ezTestDocument::InitializeAfterLoading(bool bFirstTimeCreation)
{
SUPER::InitializeAfterLoading(bFirstTimeCreation);
if (m_bUseIPCObjectMirror)
{
m_ObjectMirror.InitSender(GetObjectManager());
m_ObjectMirror.InitReceiver(&m_Context);
m_ObjectMirror.SendDocument();
}
}
void ezTestDocument::ApplyNativePropertyChangesToObjectManager(ezDocumentObject* pObject)
{
// Create native object graph
ezAbstractObjectGraph graph;
ezAbstractObjectNode* pRootNode = nullptr;
{
ezRttiConverterWriter rttiConverter(&graph, &m_Context, true, true);
pRootNode = rttiConverter.AddObjectToGraph(pObject->GetType(), m_ObjectMirror.GetNativeObjectPointer(pObject), "Object");
}
// Create object manager graph
ezAbstractObjectGraph origGraph;
ezAbstractObjectNode* pOrigRootNode = nullptr;
{
ezDocumentObjectConverterWriter writer(&origGraph, GetObjectManager());
pOrigRootNode = writer.AddObjectToGraph(pObject);
}
// Remap native guids so they match the object manager (stuff like embedded classes will not have a guid on the native side).
graph.ReMapNodeGuidsToMatchGraph(pRootNode, origGraph, pOrigRootNode);
ezDeque<ezAbstractGraphDiffOperation> diffResult;
graph.CreateDiffWithBaseGraph(origGraph, diffResult);
// As we messed up the native side the object mirror is no longer synced and needs to be destroyed.
m_ObjectMirror.Clear();
m_ObjectMirror.DeInit();
// Apply diff while object mirror is down.
GetObjectAccessor()->StartTransaction("Apply Native Property Changes to Object");
ezDocumentObjectConverterReader::ApplyDiffToObject(GetObjectAccessor(), pObject, diffResult);
GetObjectAccessor()->FinishTransaction();
// Restart mirror from scratch.
m_ObjectMirror.InitSender(GetObjectManager());
m_ObjectMirror.InitReceiver(&m_Context);
m_ObjectMirror.SendDocument();
}
ezDocumentInfo* ezTestDocument::CreateDocumentInfo()
{
return EZ_DEFAULT_NEW(ezDocumentInfo);
}
| 31.86747 | 127 | 0.79206 | [
"object"
] |
7fd758d53a0e40f272cd7a300b74d5e5239644fb | 51,235 | cp | C++ | MacOS/Sources/Application/Letter/CFileTable.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | MacOS/Sources/Application/Letter/CFileTable.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | MacOS/Sources/Application/Letter/CFileTable.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007 Cyrus Daboo. 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.
*/
// CFileTable.cp
#include "CFileTable.h"
#include "CAdminLock.h"
#include "CAliasAttachment.h"
#include "CAttachmentList.h"
#include "CBalloonDialog.h"
#include "CBetterScrollerX.h"
#include "CCommands.h"
#include "CContextMenu.h"
#include "CDataAttachment.h"
#include "CDragIt.h"
#include "CErrorHandler.h"
#include "CFileAttachment.h"
#include "CLetterPartProp.h"
#include "CLetterWindow.h"
#include "CMailControl.h"
#include "CMessage.h"
#include "CMessageAttachment.h"
#include "CMessageList.h"
#include "CMessagePartProp.h"
#include "CMessageWindow.h"
#include "CMulberryCommon.h"
#include "CNodeVectorTree.h"
#include "CPreferences.h"
#include "CResources.h"
#include "CSimpleTitleTable.h"
#include "CStringResources.h"
#include "CTableMultiRowSelector.h"
#include "CTableRowGeometry.h"
#include "CXStringResources.h"
#include <LDisclosureTriangle.h>
#include <LDropFlag.h>
#include <LTableArrayStorage.h>
#include <UStandardDialogs.h>
#include <stdio.h>
CFileTable::CFileTable(LStream *inStream)
: CHierarchyTableDrag(inStream)
{
mTableGeometry = new CTableRowGeometry(this, mFrameSize.width, 18);
mTableSelector = new CTableMultiRowSelector(this);
mTableStorage = new LTableArrayStorage(this, sizeof(CAttachment*));
mBody = NULL;
mAddAction = NULL;
mRowShow = 0;
mWindow = NULL;
mTitles = NULL;
mDirty = false;
mAttachmentsOnly = false;
mLocked = false;
}
CFileTable::~CFileTable()
{
}
// Get details of sub-panes
void CFileTable::FinishCreateSelf(void)
{
// Do inherited
LTableView::FinishCreateSelf();
// Find window in super view chain
mWindow = (CLetterWindow*) mSuperView;
while(mWindow->GetPaneID() != paneid_LetterWindow)
mWindow = (CLetterWindow*) mWindow->GetSuperView();
// Create columns and adjust flag rect
InsertCols(6, 1, NULL, 0, false);
SetOneColumnSelect(3);
AdaptToNewSurroundings();
SetRect(&mFlagRect, 2, 5, 18, 17);
// Set Drag & Drop pane to scroller
mPane = GetSuperView();
// Set Drag & Drop info
SetTable(this, false);
AddDropFlavor(cDragMsgType);
AddDropFlavor(cDragAtchType);
AddDropFlavor(cDragMsgAtchType);
// Only if not locked out
if (!CAdminLock::sAdminLock.mNoAttachments)
AddDropFlavor(flavorTypeHFS);
AddDragFlavor(cDragAtchType);
SetDDReadOnly(false);
SetDropCell(true);
SetDropCursor(true);
SetAllowDrag(true);
SetAllowMove(true);
SetSelfDrag(true);
// Set appropriate Drag & Drop inset
Rect ddInset = {1, 1, 1, 1};
if (((CBetterScrollerX*) mPane)->HasVerticalScrollBar())
ddInset.right += 15;
if (((CBetterScrollerX*) mPane)->HasHorizontalScrollBar())
ddInset.bottom += 15;
SetHiliteInset(ddInset);
}
void CFileTable::SetBody(CAttachment* aBody)
{
mBody = aBody;
// Reset table based on new body
ResetTable();
}
void CFileTable::SetRowShow(CAttachment* attach)
{
TableIndexT rows;
TableIndexT cols;
GetWideOpenTableSize(rows, cols);
// Look at each cell
for(int woRow = 1; woRow <= rows; woRow++)
{
STableCell woCell(woRow, 1);
CAttachment* row_attach = NULL;
UInt32 dataSize = sizeof(CAttachment*);
GetCellData(woCell, &row_attach, dataSize);
if (attach == row_attach)
{
mRowShow = woRow;
Refresh();
return;
}
}
}
CAttachment* CFileTable::GetPartShow(void)
{
STableCell woCell(mRowShow, 1);
CAttachment* attach = NULL;
UInt32 dataSize = sizeof(CAttachment*);
GetCellData(woCell, &attach, dataSize);
return attach;
}
unsigned long CFileTable::CountParts() const
{
if (GetAttachmentsOnly())
return mRows;
else if (mBody != NULL)
return mBody->CountParts();
else
return 0;
}
bool CFileTable::HasAttachments() const
{
if (GetAttachmentsOnly())
return mRows > 0;
else if (mBody != NULL)
return mBody->CountParts() > 1;
else
return false;
}
// Handle key presses
Boolean CFileTable::HandleKeyPress(const EventRecord &inKeyEvent)
{
switch (inKeyEvent.message & charCodeMask)
{
// Open the message
case char_Return:
case char_Enter:
{
// Try to show it, or do view
STableCell aCell;
GetFirstSelection(aCell);
if (IsSelectionValid() && (!IsSingleSelection() || mAttachmentsOnly || !ShowPart(aCell.row)))
DoViewParts();
break;
}
// Toggle delete
case char_Backspace:
case char_Clear:
// Special case escape key
if ((inKeyEvent.message & keyCodeMask) == vkey_Escape)
return CHierarchyTableDrag::HandleKeyPress(inKeyEvent);
else if (!mLocked)
{
DeleteSelection();
LCommander::SetUpdateCommandStatus(true);
}
break;
default:
return CHierarchyTableDrag::HandleKeyPress(inKeyEvent);
}
return true;
}
// Pass back status of a (menu) command
void CFileTable::FindCommandStatus(
CommandT inCommand,
Boolean &outEnabled,
Boolean &outUsesMark,
UInt16 &outMark,
Str255 outName)
{
outUsesMark = false;
switch (inCommand)
{
case cmd_Cut: // Cut, Copy, and Clear enabled
case cmd_Copy: // if something is selected
case cmd_Paste:
//outEnabled = IsSelectionValid();
outEnabled = false;
break;
case cmd_Clear:
outEnabled = !mLocked && IsSelectionValid();
break;
// Item selected?
case cmd_Properties:
outEnabled = IsSelectionValid();
break;
// Available when not locked
case cmd_NewTextPart:
case cmd_NewPlainTextPart:
case cmd_MultipartChoice:
case cmd_MultipartMixed:
case cmd_MultipartParallel:
case cmd_MultipartDigest:
case cmd_MultipartAlternative:
outEnabled = !mLocked;
break;
case cmd_NewEnrichedTextPart:
case cmd_NewHTMLTextPart:
// Only if allowed by admin and not locked
outEnabled = CAdminLock::sAdminLock.mAllowStyledComposition && !mLocked;
break;
default:
CHierarchyTableDrag::FindCommandStatus(inCommand, outEnabled, outUsesMark,
outMark, outName);
break;
}
}
// Respond to commands
Boolean CFileTable::ObeyCommand(CommandT inCommand,void *ioParam)
{
bool cmdHandled = true;
switch (inCommand)
{
case cmd_Cut:
case cmd_Copy:
case cmd_Paste:
break;
case cmd_Clear:
if (!mLocked)
DeleteSelection();
break;
case cmd_Properties:
DoEditProperties();
break;
case cmd_AttachFile:
// Only if not locked out
if (!CAdminLock::sAdminLock.mNoAttachments)
DoAttachFile();
break;
//Justin
case cmd_NewPlainTextPart:
DoNewTextPart(eContentSubPlain);
break;
case cmd_NewEnrichedTextPart:
DoNewTextPart(eContentSubEnriched);
break;
case cmd_NewHTMLTextPart:
DoNewTextPart(eContentSubHTML);
break;
case cmd_MultipartMixed:
DoMultipartMixed();
break;
case cmd_MultipartParallel:
DoMultipartParallel();
break;
case cmd_MultipartDigest:
DoMultipartDigest();
break;
case cmd_MultipartAlternative:
DoMultipartAlternative();
break;
case msg_TabSelect:
if (!IsEnabled() || !IsVisible()) {
cmdHandled = false;
}
break;
default:
cmdHandled = CHierarchyTableDrag::ObeyCommand(inCommand, ioParam);
break;
}
return cmdHandled;
}
void CFileTable::DrawCell(const STableCell &inCell, const Rect &inLocalRect)
{
TableIndexT woRow = mCollapsableTree->GetWideOpenIndex(inCell.row);
CAttachment* attach = GetAttachment(inCell.row);
// Save text state in stack object
StTextState textState;
StColorState saveColors;
StColorPenState::Normalize();
cdstring theTxt;
// Set to required text
UTextTraits::SetPortTextTraits(&mTextTraits);
// Erase to ensure drag hightlight is overwritten
::EraseRect(&inLocalRect);
// Clip to cell frame & table frame
Rect clipper = mRevealedRect;
PortToLocalPoint(topLeft(clipper));
PortToLocalPoint(botRight(clipper));
::SectRect(&clipper, &inLocalRect, &clipper);
StClipRgnState clip(clipper);
unsigned long col_type = 0;
switch(inCell.col)
{
case 1:
col_type = mAttachmentsOnly ? eColType_NameIcon : eColType_Diamond;
break;
case 2:
col_type = mAttachmentsOnly ? eColType_Size : eColType_RW;
break;
case 3:
col_type = mAttachmentsOnly ? eColType_MIME : eColType_MIMEIcon;
break;
case 4:
col_type = eColType_Name;
break;
case 5:
col_type = eColType_Size;
break;
case 6:
col_type = eColType_Encoding;
break;
}
switch(col_type)
{
case eColType_Diamond:
Rect iconRect;
iconRect.left = inLocalRect.left;
iconRect.right = iconRect.left + 16;
iconRect.bottom = inLocalRect.bottom - mIconDescent;
iconRect.top = iconRect.bottom - 16;
// Erase if multipart
if (attach->IsMultipart())
::EraseRect(&iconRect);
// Check for diamond type
else if (woRow == mRowShow)
::Ploticns(&iconRect, kAlignNone, kTransformNone, ICNx_DiamondTicked);
else if (attach->CanEdit())
::Ploticns(&iconRect, kAlignNone, kTransformNone, attach->IsSeen() ? ICNx_DiamondSeen : ICNx_Diamond);
else
::Ploticns(&iconRect, kAlignNone, kTransformNone, ICNx_DisabledDiamond);
break;
case eColType_RW:
iconRect.left = inLocalRect.left;
iconRect.right = iconRect.left + 16;
iconRect.bottom = inLocalRect.bottom - mIconDescent;
iconRect.top = iconRect.bottom - 16;
::Ploticns(&iconRect, kAlignNone, kTransformNone, attach->CanChange() && !mLocked ? ICNx_ReadWrite : ICNx_ReadOnly);
break;
case eColType_MIME:
{
::MoveTo(inLocalRect.left, inLocalRect.bottom - mTextDescent);
cdstring content(CMIMESupport::GenerateContentHeader(attach, false, lendl, false));
::DrawClippedStringUTF8(content, inLocalRect.right - inLocalRect.left, eDrawString_Left);
}
break;
case eColType_MIMEIcon:
{
DrawDropFlag(inCell, woRow);
// Draw selection
bool selected_state = DrawCellSelection(inCell);
UInt32 nestingLevel = mCollapsableTree->GetNestingLevel(woRow);
// Draw icon followed by encoding
iconRect.left = inLocalRect.left + mFirstIndent + nestingLevel * mLevelIndent;
iconRect.right = iconRect.left + 16;
iconRect.bottom = inLocalRect.bottom - mIconDescent;
iconRect.top = iconRect.bottom - 16;
PlotAttachIcon(attach, iconRect, selected_state);
// Get encoding mode
cdstring content(CMIMESupport::GenerateContentHeader(attach, false, lendl, false));
::MoveTo(iconRect.right - 2, inLocalRect.bottom - mTextDescent);
short width = inLocalRect.right - iconRect.right - 2;
::DrawClippedStringUTF8(content, width, eDrawString_Left);
}
break;
case eColType_Name:
if (!attach->IsMultipart())
{
::MoveTo(inLocalRect.left, inLocalRect.bottom - mTextDescent);
cdstring at_name = attach->GetMappedName(true, false);
if (!at_name.empty())
{
::DrawClippedStringUTF8(at_name, inLocalRect.right - inLocalRect.left, eDrawString_Left);
}
}
break;
case eColType_NameIcon:
{
DrawDropFlag(inCell, woRow);
// Draw selection
bool selected_state = DrawCellSelection(inCell);
UInt32 nestingLevel = mCollapsableTree->GetNestingLevel(woRow);
// Draw icon followed by encoding
iconRect.left = inLocalRect.left + mFirstIndent + nestingLevel * mLevelIndent;
iconRect.right = iconRect.left + 16;
iconRect.bottom = inLocalRect.bottom - mIconDescent;
iconRect.top = iconRect.bottom - 16;
PlotAttachIcon(attach, iconRect, selected_state);
// Get encoding mode
::MoveTo(iconRect.right - 2, inLocalRect.bottom - mTextDescent);
short width = inLocalRect.right - iconRect.right - 2;
cdstring at_name = attach->GetMappedName(true, false);
if (!at_name.empty())
{
::DrawClippedStringUTF8(at_name, width, eDrawString_Left);
}
}
break;
case eColType_Size:
// Draw size
if (!attach->IsMultipart())
{
long size = attach->GetSize();
theTxt = ::GetNumericFormat(size);
::MoveTo(inLocalRect.left, inLocalRect.bottom - mTextDescent);
::DrawClippedStringUTF8(theTxt, inLocalRect.right - inLocalRect.left, eDrawString_Right);
}
break;
case eColType_Encoding:
if (!attach->IsMultipart() && !attach->IsMessage())
{
// Get encoding mode
theTxt = rsrc::GetIndexedString("UI::Letter::EncodeMode", attach->GetTransferMode());
::MoveTo(inLocalRect.left, inLocalRect.bottom - mTextDescent);
::DrawClippedStringUTF8(theTxt, inLocalRect.right - inLocalRect.left, eDrawString_Left);
}
break;
default:
break;
}
}
// Plot appropriate icon for attachment
void CFileTable::PlotAttachIcon(CAttachment* attach, Rect& iconRect, bool inHilite)
{
if (attach->IsApplefile())
::Ploticns(&iconRect, kAlignNone, inHilite? kTransformSelected : kTransformNone, ICNx_Applefile);
else if (attach->IsMultipart())
::Ploticns(&iconRect, kAlignNone, inHilite? kTransformSelected : kTransformNone, ICNx_Multipart);
else if (attach->IsMessage())
::Ploticns(&iconRect, kAlignNone, inHilite? kTransformSelected : kTransformNone, ICNx_MessagePart);
else if (attach->IsCalendar())
::Ploticns(&iconRect, kAlignNone, inHilite? kTransformSelected : kTransformNone, ICNx_Calendar_Flag);
else if (attach->GetIconRef()->GetIconRef())
::PlotIconRef(&iconRect, kAlignNone, inHilite? kTransformSelected : kTransformNone, kIconServicesNormalUsageFlag, attach->GetIconRef()->GetIconRef());
else
::Ploticns(&iconRect, kAlignNone, inHilite? kTransformSelected : kTransformNone, ICNx_Unknownfile);
}
// Draw or undraw active hiliting for a Cell
void CFileTable::HiliteCellActively(const STableCell &inCell, Boolean inHilite)
{
if (!GetBody())
return;
CHierarchyTableDrag::HiliteCellActively(inCell, inHilite);
}
// Draw or undraw inactive hiliting for a Cell
void CFileTable::HiliteCellInactively(const STableCell &inCell, Boolean inHilite)
{
if (!GetBody())
return;
CHierarchyTableDrag::HiliteCellInactively(inCell, inHilite);
}
void CFileTable::CalcCellFlagRect(const STableCell &inCell, Rect &outRect)
{
if (inCell.col == (mAttachmentsOnly ? 1 : 3))
{
LHierarchyTable::CalcCellFlagRect(inCell, outRect);
outRect.right = outRect.left + 16;
outRect.bottom = outRect.top + 12;
::OffsetRect(&outRect, 0, -2);
}
else
::SetRect(&outRect, 0, 0, 0, 0);
}
// Show focus box
void CFileTable::BeTarget(void)
{
if (mBody)
Activate();
}
// Hide focus box
void CFileTable::DontBeTarget(void)
{
if (mBody)
Deactivate();
}
// Make it target first
void CFileTable::ClickSelf(const SMouseDownEvent &inMouseDown)
{
SwitchTarget(this);
CHierarchyTableDrag::ClickSelf(inMouseDown);
}
// Click in the cell
void CFileTable::ClickCell(
const STableCell &inCell,
const SMouseDownEvent &inMouseDown)
{
// Must check whether the current event is still the one we expect to handle.
// Its possible that a dialog appeared as a result of the initial click, and now
// the mouse is no longer down. However WaitMouseMoved will always wait for a mouse up
// before carrying on.
EventRecord currEvent;
LEventDispatcher::GetCurrentEvent(currEvent);
bool event_match = (inMouseDown.macEvent.what == currEvent.what) &&
(inMouseDown.macEvent.message == currEvent.message) &&
(inMouseDown.macEvent.when == currEvent.when) &&
(inMouseDown.macEvent.where.h == currEvent.where.h) &&
(inMouseDown.macEvent.where.v == currEvent.where.v) &&
(inMouseDown.macEvent.modifiers == currEvent.modifiers);
// Check whether D&D available and over a selected cell or not shift or cmd keys
if (event_match && (mAttachmentsOnly || (inCell.col != 1)) &&
DragAndDropIsPresent() &&
(CellIsSelected(inCell) ||
(!(inMouseDown.macEvent.modifiers & shiftKey) &&
!(inMouseDown.macEvent.modifiers & cmdKey))))
{
// Track item long enough to distinguish between a click to
// select, and the beginning of a drag
bool isDrag = !CContextMenuProcessAttachment::ProcessingContextMenu() &&
::WaitMouseMoved(inMouseDown.macEvent.where);
// Now do drag
if (isDrag)
{
// Force update of current part
mWindow->SyncPart();
// If we leave the window, the drag manager will be changing thePort,
// so we'll make sure thePort remains properly set.
OutOfFocus(NULL);
FocusDraw();
OSErr err = CreateDragEvent(inMouseDown);
OutOfFocus(NULL);
return;
}
}
// Do click in different text show
if (!inMouseDown.delaySelect && !mAttachmentsOnly && (inCell.col == 1))
ShowPart(inCell.row);
// If multiclick then view
if ((GetClickCount() > 1) && !inMouseDown.delaySelect)
{
// Try to show otherwise do view
if (mAttachmentsOnly || !ShowPart(inCell.row))
DoViewParts();
}
}
void CFileTable::SetAttachmentsOnly(bool attachments)
{
if (attachments != mAttachmentsOnly)
{
mAttachmentsOnly = attachments;
// Change columns before resetting to ensure
// data stored in cells is consistent
TableIndexT new_cols = mAttachmentsOnly ? 3 : 6;
TableIndexT old_cols = mCols;
if (old_cols > new_cols)
RemoveCols(old_cols - new_cols, 1, false);
else if (old_cols < new_cols)
InsertCols(new_cols - old_cols, 1, NULL, 0, false);
AdaptToNewSurroundings();
SetOneColumnSelect(mAttachmentsOnly ? 1 : 3);
// Change titles
if (mTitles)
{
mTitles->SyncTable(this, true);
mTitles->LoadTitles(mAttachmentsOnly ? "UI::Titles::LetterAttachments" : "UI::Titles::LetterParts", mAttachmentsOnly ? 3 : 6, true);
}
if (GetBody())
{
CAttachment* attach = GetPartShow();
ResetTable();
SetRowShow(attach);
}
}
}
// Reset the table from the mbox
void CFileTable::ResetTable(void)
{
TableIndexT old_show = mRowShow;
// Delete all existing rows (use inherited function to prevent attachment delete)
while (mRows)
CHierarchyTableDrag::RemoveRows(1, mRows, false);
if (mBody)
{
TableIndexT next_row = 1;
// Add main part
InsertPart(next_row, mBody, false);
// Expand top rows only (when not in attachments mode)
if (IsCollapsable(1) && !mAttachmentsOnly)
ExpandRow(1);
}
// Restore previous row show
mRowShow = old_show;
Refresh();
}
TableIndexT CFileTable::InsertPart(TableIndexT& parentRow, CAttachment* part, bool child, int pos)
{
TableIndexT child_insert = parentRow;
bool is_attachment = (dynamic_cast<CDataAttachment*>(part) == NULL) || !part->IsMultipart() && !part->CanEdit();
// Insert this part
if (!mAttachmentsOnly || is_attachment)
{
if (child)
{
// Determine position of part and how to insert
if (pos == 0)
{
InsertChildRows(1, parentRow, &part, sizeof(CAttachment*), part->IsMultipart() || part->IsMessage(), false);
child_insert = parentRow + 1;
}
else if (pos < 0)
{
AddLastChildRow(parentRow, &part, sizeof(CAttachment*), part->IsMultipart() || part->IsMessage(), false);
child_insert = parentRow + mCollapsableTree->CountAllDescendents(parentRow);
}
else
{
TableIndexT woRow = ((CNodeVectorTree*) mCollapsableTree)->SiblingIndex(parentRow, pos);
child_insert = InsertSiblingRows(1, woRow, &part, sizeof(CAttachment*), part->IsMultipart() || part->IsMessage(), false);
}
}
else
// Update to new parent
child_insert = InsertSiblingRows(1, parentRow, &part, sizeof(CAttachment*), part->IsMultipart() || part->IsMessage(), false);
}
// Add children (if there)
if ((part->IsMultipart() || part->IsMessage()) && part->GetParts())
{
// Add each sibling
for(CAttachmentList::iterator iter = part->GetParts()->begin(); iter != part->GetParts()->end(); iter++)
InsertPart(child_insert, *iter, mRows > 0);
}
// Adjust visible part position
if (child_insert <= mRowShow)
mRowShow += CountAllDescendents(child_insert) + 1;
return child_insert;
}
// Handle update of visible part
void CFileTable::DeleteSelection(void)
{
// Check for delete of visible row
TableIndexT oldrow = mRowShow;
// Force update of current part
mWindow->SyncPart();
// Do inherited action
DoToSelection((DoToSelectionPP) &CFileTable::DeleteRow, false);
// Force change of multipart structure
if (mBody && ConvertMultipart(false))
ResetTable();
// Update row show
UpdateRowShow();
}
// DeleteRow
bool CFileTable::DeleteRow(TableIndexT row)
{
TableIndexT woRow = GetWideOpenIndex(row);
RemoveRows(1, woRow, true);
return true;
}
// Remove rows and adjust parts
void CFileTable::RemoveRows(UInt32 inHowMany, TableIndexT inFromRow, Boolean inRefresh)
{
// Always called with inHowMany == 1
// Look for visible row in hierarchy to be deleted
if ((mRowShow >= inFromRow) && (mRowShow <= inFromRow + mCollapsableTree->CountAllDescendents(inFromRow)))
{
mRowShow = 0;
mWindow->mCurrentPart = NULL;
}
// Look for change in position of row show
if (mRowShow > inFromRow + mCollapsableTree->CountAllDescendents(inFromRow))
mRowShow -= 1 + mCollapsableTree->CountAllDescendents(inFromRow);
// Get attachment for this row
STableCell woCell(inFromRow, 1);
CAttachment* attach;
UInt32 dataSize = sizeof(CAttachment*);
GetCellData(woCell, &attach, dataSize);
// Remove it from its parent (will be deleted)
if (attach->GetParent())
attach->GetParent()->RemovePart(attach);
else
{
// Must be root part so delete
delete mBody;
mBody = NULL;
mWindow->SetBody(NULL);
}
// Do inherited action
LHierarchyTable::RemoveRows(inHowMany, inFromRow, inRefresh);
SetDirty(true);
}
TableIndexT CFileTable::AddPart(CAttachment* attach, CAttachment* parent, int parent_row, int pos, bool refresh)
{
bool force_reset = false;
TableIndexT new_woRow = 0;
if (mBody)
{
// Check for existing multipart
force_reset = ConvertMultipart(true);
// If changed bump up positions
if (force_reset)
{
// Reset to new parent
parent = mBody;
parent_row = 1;
pos = -1;
new_woRow = -1;
}
// Get default parent
if (!parent || !parent->CanChange())
{
parent = mBody;
parent_row = 1;
pos = -1;
// Check whether only one selected
if (!mAttachmentsOnly && IsSingleSelection())
{
// Check for multipart
STableCell aCell(0, 0);
GetFirstSelection(aCell);
UInt32 woRow = GetWideOpenIndex(aCell.row);
CAttachment* attach = GetAttachment(aCell.row);
// Set parent to single multipart selected item
if (attach->IsMultipart())
{
parent = attach;
parent_row = woRow;
}
}
}
// Add to parts
parent->AddPart(attach, pos);
}
else
{
mBody = attach;
mWindow->SetBody(mBody);
parent_row = 0;
pos = 0;
new_woRow = 1;
force_reset = true;
}
// Reset table if required
if (force_reset)
{
ResetTable();
// Must adjust new row to the last one that could possibly be
TableIndexT dummy;
GetWideOpenTableSize(new_woRow, dummy);
}
else
{
// Manually insert part as child or sibling (if flat attachment only list)
TableIndexT temp = parent_row;
if (mAttachmentsOnly)
{
TableIndexT sibling = ((CNodeVectorTree*) mCollapsableTree)->GetSiblingIndex(temp);
while(sibling != 0)
{
temp = sibling;
sibling = ((CNodeVectorTree*) mCollapsableTree)->GetSiblingIndex(temp);
}
}
new_woRow = InsertPart(temp, attach, !mAttachmentsOnly, pos);
}
// Force redraw if required
if (refresh)
Refresh();
SetDirty(true);
return new_woRow;
}
// Convert between single/multipart
// bool add : indicates whether a part is about to be added, or has been removed
// returns bool : true if root part changed (i.e. reset of whole table required
bool CFileTable::ConvertMultipart(bool add)
{
// Must have a valid body to do this
if (!mBody)
return false;
// Check for single (or unchangeable) part when adding a new part
if (add && (!mBody->IsMultipart() || !mBody->CanChange()))
{
// Create new multipart entity
CDataAttachment* root = new CDataAttachment();
root->GetContent().SetContent(eContentMultipart, eContentSubMixed);
// Add original part to new root
CAttachment* child = mBody;
root->AddPart(child);
// Make body start at new root
mBody = root;
// Force window to update
mWindow->SetBody(mBody, true);
// Bump up row show if not zero and reset window's current part back to original
if (mRowShow)
{
mRowShow++;
mWindow->mCurrentPart = child;
}
// Force table reset
return true;
}
// Check for multipart with a single or no child part
else if (!add && mBody->IsMultipart() && (!mBody->GetParts() || (mBody->GetParts()->size() < 2)))
{
// Get old root
CAttachment* old_root = mBody;
// Get new root from old
CAttachment* new_root = mBody->GetPart(2);
// Remove new from old without delete and delete old
if (new_root)
old_root->RemovePart(new_root, false);
delete old_root;
// Make body start at new root
mBody = new_root;
// Force window to update
mWindow->SetBody(mBody, true);
// Bump down row show if not zero (window's current part remians the same)
if (mRowShow)
{
mRowShow--;
}
// Iterate again
ConvertMultipart(false);
// Force table reset
return true;
}
return false;
}
// Find first editable part
void CFileTable::UpdateRowShow(void)
{
// Reset row show with first viewable if changed
if (!mAttachmentsOnly && !mRowShow)
{
for(int selrow = 1; selrow <= mCollapsableTree->CountNodes(); selrow++)
{
STableCell woCell(selrow, 1);
CAttachment* attach;
UInt32 dataSize = sizeof(CAttachment*);
GetCellData(woCell, &attach, dataSize);
if (attach->CanEdit())
{
mRowShow = selrow;
break;
}
}
// Force window text reset
mWindow->SetCurrentPart(GetAttachment(mRowShow, true));
// Refresh new one
TableIndexT row = GetExposedIndex(mRowShow);
if (row)
RefreshRow(row);
}
mWindow->UpdatePartsCaption();
}
bool CFileTable::ShowPart(TableIndexT row)
{
// Do click in different text show
TableIndexT woRow = mCollapsableTree->GetWideOpenIndex(row);
CAttachment* attach = GetAttachment(row);
if ((woRow != mRowShow) && attach->CanEdit())
{
// Refresh old one
TableIndexT old_row = GetExposedIndex(mRowShow);
// Change value before refresh to ensure no tick-mark
mRowShow = woRow;
RefreshRow(old_row);
// Show chosen part
mWindow->SetCurrentPart(GetAttachment(mRowShow, true));
// Refresh new one
RefreshRow(row);
return true;
}
else
return false;
}
// Test for selected message deleted
bool CFileTable::TestSelectionChangeable(TableIndexT row)
{
// Is it changeable?
CAttachment* attach = GetAttachment(row);
return attach->CanChange();
}
// Test for selected message deleted
bool CFileTable::TestSelectionUnchangeable(TableIndexT row)
{
// Is it unchangeable?
CAttachment* attach = GetAttachment(row);
return !attach->CanChange();
}
// Adjust column widths
void CFileTable::AdaptToNewSurroundings(void)
{
// Do inherited call
LHierarchyTable::AdaptToNewSurroundings();
// Set image to frame size
ResizeImageTo(mFrameSize.width, mImageSize.height, true);
if (mAttachmentsOnly)
{
// Name column has variable width
SetColWidth(mFrameSize.width - 260, 1, 1);
// Remaining columns have fixed width
SetColWidth(48, 2, 2);
SetColWidth(212, 3, 3);
}
else
{
// Name column has variable width
SetColWidth(mFrameSize.width - 370, 4, 4);
// Remaining columns have fixed width
SetColWidth(16, 1, 1);
SetColWidth(16, 2, 2);
SetColWidth(212, 3, 3);
SetColWidth(48, 5, 5);
SetColWidth(80, 6, 6);
}
if (mTitles)
mTitles->SyncTable(this);
}
// Do properties dialog
void CFileTable::DoEditProperties(void)
{
bool changed = false;
// Can only do to selection
if (!IsSelectionValid())
return;
// Test for selection all changeable or all not changeable
bool all_change = TestSelectionAnd((TestSelectionPP) &CFileTable::TestSelectionChangeable);
bool all_unchange = TestSelectionAnd((TestSelectionPP) &CFileTable::TestSelectionUnchangeable);
// All changeable => allow edit
if (all_change && !mLocked)
{
// Get content for first item
STableCell selCell(0, 0);
GetNextSelectedCell(selCell);
UInt32 woRow = GetWideOpenIndex(selCell.row);
CAttachment* attach = GetAttachment(selCell.row);
// Make a copy of the content
CMIMEContent content = attach->GetContent();
// Modify content if others selected
while(GetNextSelectedCell(selCell))
{
if (selCell.col == 1)
{
CAttachment* other_attach = GetAttachment(selCell.row);
content.NullDiff(other_attach->GetContent());
}
}
// Create the dialog
CBalloonDialog theHandler(paneid_LetterPart, this);
((CLetterPartProp*) theHandler.GetDialog())->SetFields(content);
theHandler.StartDialog();
// Let DialogHandler process events
while (true)
{
MessageT hitMessage = theHandler.DoDialog();
if (hitMessage == msg_OK)
{
((CLetterPartProp*) theHandler.GetDialog())->GetFields(content);
// Copy back into all selected items
selCell = STableCell(0, 0);
while(GetNextSelectedCell(selCell))
{
if (selCell.col == 1)
{
woRow = GetWideOpenIndex(selCell.row);
CAttachment* attach = GetAttachment(selCell.row);
if (attach->GetContent().GetContentSubtype() != content.GetContentSubtype())
{
changed = true;
}
if (((attach->GetContent().GetContentSubtype() == eContentSubEnriched) ||
(attach->GetContent().GetContentSubtype() == eContentSubHTML)) &&
(content.GetContentSubtype() == eContentSubPlain))
{
if (CErrorHandler::PutCautionAlertRsrc(true, "Alerts::Letter::WarnLoseFormatting") == CErrorHandler::Cancel)
{
break;
}
}
content.NullAdd(attach->GetContent());
// Need to force attachment name to be re-mapped
attach->SetName(cdstring::null_str);
if (changed && (woRow == mRowShow) && !mAttachmentsOnly)
mWindow->SetCurrentPart(GetAttachment(mRowShow, true));
}
}
RefreshSelection();
SetDirty(true);
break;
}
else if (hitMessage == msg_Cancel)
break;
}
}
// All unchangeable => no edit
else if (all_unchange || mLocked)
{
// Special if multiple
bool multi = !IsSingleSelection();
bool more = multi;
STableCell selCell(0, 0);
do
{
// Exit loop if no more
if (!GetNextSelectedCell(selCell))
break;
if (selCell.col == 1)
{
CAttachment* attach = GetAttachment(selCell.row);
// Create the dialog
CBalloonDialog theHandler(paneid_MessagePart, this);
((CMessagePartProp*) theHandler.GetDialog())->SetFields(*attach, multi);
theHandler.StartDialog();
// Let DialogHandler process events
while (true)
{
MessageT hitMessage = theHandler.DoDialog();
if (hitMessage == msg_OK)
break;
else if (hitMessage == msg_Cancel)
{
more = false;
break;
}
}
}
} while (more);
}
else
// Warn user of mixed selection
CErrorHandler::PutStopAlertRsrc("Alerts::Letter::MixedFileTableSelection");
}
// View selected parts
void CFileTable::DoViewParts()
{
if (!TestSelectionAnd((TestSelectionPP) &CFileTable::CheckViewPart))
CErrorHandler::PutStopAlertRsrc("Alerts::Message::CannotDownload");
else
{
DoToSelection((DoToSelectionPP) &CFileTable::ViewPart);
RefreshSelection();
}
}
// Check for valid view of specified part
bool CFileTable::CheckViewPart(TableIndexT row)
{
// Check against admin locks
CAttachment* attach = GetAttachment(row);
if (!attach)
return false;
// Look for local file attachment - we always allow the user to view these
// irrespective of admin locks since they can view it via the file system anyway
CFileAttachment* fattach = dynamic_cast<CFileAttachment*>(attach);
return (fattach != NULL) || CAdminLock::sAdminLock.CanDownload(attach->GetContent());
}
// View the part
bool CFileTable::ViewPart(TableIndexT row)
{
CAttachment* attach = GetAttachment(row);
if (!attach)
return false;
CFileAttachment* fattach = dynamic_cast<CFileAttachment*>(attach);
// Check part size first (only if its not on disk already)
if ((fattach == NULL) && !CMailControl::CheckSizeWarning(attach))
return false;
// View chosen part if cached
if (!attach->IsNotCached())
{
// Behaviour:
// file attachments are viewed directly off disk
// message attachments are viewed via their owning message
if (fattach)
fattach->ViewFile();
else
{
}
}
return true;
}
// Make sure list is visible in draft window
void CFileTable::ExposePartsList()
{
// Check whether twisted or not
if (!mWindow->IsPartsTwist())
// twist without changing focus
mWindow->DoPartsTwist(true, false);
}
// Do file attachment
void CFileTable::DoAttachFile(void)
{
bool done = false;
std::auto_ptr<CAttachmentList> attachList(new CAttachmentList);
attachList->set_delete_data(false);
// Determine if NavServices available
{
LFileTypeList fileTypes((NavTypeList**) NULL);
PP_StandardDialogs::LFileChooser chooser;
chooser.GetDialogOptions()->optionFlags = kNavDefaultNavDlogOptions; // Can select multiple files
done = chooser.AskOpenFile(fileTypes);
if (done)
{
for(int i = 1; i <= chooser.GetNumberOfFiles(); i++)
{
PPx::FSObject fspec;
chooser.GetFileSpec(i, fspec);
// Create new file attachment and add to list
CFileAttachment* attached = new CFileAttachment(fspec);
attachList->push_back(attached);
}
}
}
// Was it successful
if (done)
{
bool added = false;
// Want to select only the new ones
UnselectAllCells();
// Add parts to table
TableIndexT first_added = 0;
for(CAttachmentList::iterator iter = attachList->begin(); iter != attachList->end(); iter++)
{
// Must be unique to add
if (!mBody || mBody->UniqueFile(*static_cast<CFileAttachment*>(*iter)->GetFSSpec()))
{
// Create file attachment and add
TableIndexT woRow = AddPart(*iter, NULL, 0, 0, false);
TableIndexT exp_row = GetExposedIndex(woRow);
// Select each one added
SelectRow(exp_row);
// Cache the first one added for scroll into view
if (first_added == 0)
first_added = exp_row;
added = true;
}
else
delete *iter;
}
// Scroll so first one is in the view
if (added)
ScrollToRow(first_added, false, false, eScroll_Top);
// Refresh table if change
if (added)
Refresh();
// Clear all items from list as they are either in use or deleted
attachList->clear();
// Force parts visible
if (added)
ExposePartsList();
}
}
// Do new text attachment
void CFileTable::DoNewTextPart(EContentSubType subType)
{
// Must always be in full parts mode if we have more than one inline text part
SetAttachmentsOnly(false);
TableIndexT old_show = mRowShow;
CAttachment* tattach = new CDataAttachment((char*) NULL);
tattach->GetContent().SetContent(eContentText, subType);
TableIndexT woRow = AddPart(tattach, NULL, 0, 0, true);
// Refresh old one
TableIndexT old_row = GetExposedIndex(old_show);
RefreshRow(old_row);
// Change value
mRowShow = woRow;
// Show new part
mWindow->SetCurrentPart(GetAttachment(mRowShow, true));
mWindow->UpdatePartsCaption();
// Refresh new one
TableIndexT row = GetExposedIndex(mRowShow);
RefreshRow(row);
// Select only the new one
UnselectAllCells();
SelectRow(row);
ScrollToRow(row, false, false, eScroll_Top);
// Force parts visible
ExposePartsList();
}
// Do new multipart attachment
void CFileTable::DoMultipartMixed(void)
{
DoMultipart(eContentSubMixed);
}
// Do new multipart attachment
void CFileTable::DoMultipartParallel(void)
{
DoMultipart(eContentSubParallel);
}
// Do new multipart attachment
void CFileTable::DoMultipartDigest(void)
{
DoMultipart(eContentSubDigest);
}
// Do new multipart attachment
void CFileTable::DoMultipartAlternative(void)
{
DoMultipart(eContentSubAlternative);
}
// Do new multipart attachment
void CFileTable::DoMultipart(EContentSubType subType)
{
// Must always be in full parts mode if we add multiparts
SetAttachmentsOnly(false);
CDataAttachment* mattach = new CDataAttachment;
mattach->GetContent().SetContent(eContentMultipart, subType);
TableIndexT woRow = AddPart(mattach, NULL, 0, 0, true);
TableIndexT expRow = GetExposedIndex(woRow);
mWindow->UpdatePartsCaption();
// Select only the new one
UnselectAllCells();
SelectRow(expRow);
ScrollToRow(expRow, false, false, eScroll_Top);
// Force parts visible
ExposePartsList();
}
// Add whole message as part
void CFileTable::ForwardMessages(CMessageList* msgs, EForwardOptions forward)
{
for(CMessageList::const_iterator iter = msgs->begin(); iter != msgs->end(); iter++)
{
// Check that message has more than one alternative text part
if (!(*iter)->HasUniqueTextPart() || (forward & eForwardAttachment))
{
// Check for forward using message/rfc822 part
CAttachment* new_attach = NULL;
if (forward & eForwardRFC822)
new_attach = new CMessageAttachment(*iter, *iter);
else
{
// Make aliases of original body
if ((*iter)->GetBody()->IsMessage())
new_attach = new CMessageAttachment(*iter, (*iter)->GetBody()->GetMessage());
else
new_attach = new CAliasAttachment(*iter, (*iter)->GetBody());
}
AddPart(new_attach, NULL, 0, 0, true);
}
}
// Expose parts if items were added
if (mRows > 1)
ExposePartsList();
}
// Add whole message as total
void CFileTable::BounceMessages(CMessageList* msgs)
{
// Dump existing
delete mBody;
SetBody(NULL);
mWindow->SetBody(NULL);
// Must always be in full parts mode when bouncing
SetAttachmentsOnly(false);
CAttachment* new_attach = NULL;
for(CMessageList::const_iterator iter = msgs->begin(); iter != msgs->end(); iter++)
{
// Make aliases of original body
if ((*iter)->GetBody()->IsMessage())
new_attach = new CMessageAttachment(*iter, (*iter)->GetBody()->GetMessage());
else
new_attach = new CAliasAttachment(*iter, (*iter)->GetBody());
AddPart(new_attach, NULL, 0, 0, true);
}
// Expose parts if items were added
if (mRows > 1)
ExposePartsList();
}
// Add whole message as total
void CFileTable::RejectMessages(CMessageList* msgs, bool return_msg)
{
// Dump existing
delete mBody;
SetBody(NULL);
mWindow->SetBody(NULL);
// Must always be in full parts mode when rejecting
SetAttachmentsOnly(false);
// Can only do this to one message
if (msgs->size() != 1)
return;
// Create the DSN message
CAttachment* dsn = msgs->front()->CreateRejectDSNBody(return_msg);
// Give this to the table
if (dsn)
AddPart(dsn, NULL, 0, 0, true);
UpdateRowShow();
// Lock it to prevent changes to reject
mLocked = true;
// Prevent drag and drop when locked
SetDDReadOnly(true);
}
// Add whole message as total with editable bits
void CFileTable::SendAgainMessages(CMessageList* msgs)
{
// Dump existing
delete mBody;
SetBody(NULL);
mWindow->SetBody(NULL);
for(CMessageList::const_iterator iter = msgs->begin(); iter != msgs->end(); iter++)
{
CAttachment* new_attach = NULL;
// Clone entire body to editable parts
// This will take care of signed/encrypted/alternative types
new_attach = CAttachment::CloneAttachment(*iter, (*iter)->GetBody());
// Add to list and update visible part
AddPart(new_attach, NULL, 0, 0, true);
}
UpdateRowShow();
// Expose parts if items were added
if (mRows > 1)
ExposePartsList();
// We need to reset the display of the current part
mWindow->SetCurrentPart(mWindow->GetCurrentPart());
}
// Add whole message as part
void CFileTable::DigestMessages(CMessageList* msgs)
{
// Must always be in full parts mode when rejecting
SetAttachmentsOnly(false);
// Add multipart digest
CDataAttachment* mattach = new CDataAttachment();
mattach->GetContent().SetContent(eContentMultipart, eContentSubDigest);
TableIndexT parent_row = AddPart(mattach, NULL, 0, 0, true);
// Add all messages into digest
for(CMessageList::const_iterator iter = msgs->begin(); iter != msgs->end(); iter++)
{
CMessageAttachment* new_attach = new CMessageAttachment(*iter, *iter);
AddPart(new_attach, mattach, parent_row, -1, true);
}
// Expose parts if items were added
if (mRows > 1)
ExposePartsList();
}
// Add file from path
void CFileTable::AddFile(const cdstring& file)
{
// Create new file attachment and add to list
CFileAttachment* attached = new CFileAttachment(file);
// Must be unique to add
if (attached->ValidFile() &&
(!mBody || mBody->UniqueFile(*attached->GetFSSpec())))
{
// Create file attachment and add
AddPart(attached, NULL, 0, 0, true);
// Force parts visible
ExposePartsList();
}
else
delete attached;
}
// Add attachment
void CFileTable::AddAttachment(CDataAttachment* attach)
{
// Add attachment
AddPart(attach, NULL, 0, 0, true);
// Force parts visible
ExposePartsList();
}
// Server reset
void CFileTable::ServerReset(const CMboxProtocol* proto)
{
// Find any parts dependent on this message and remove them
if (mBody && CAttachment::ServerReset(mBody, proto))
{
ResetTable();
}
}
// Mailbox reset
void CFileTable::MailboxReset(const CMbox* mbox)
{
// Find any parts dependent on this message and remove them
if (mBody && CAttachment::MailboxReset(mBody, mbox))
{
ResetTable();
}
}
// Message removed
void CFileTable::MessageRemoved(const CMessage* msg)
{
// Find any parts dependent on this message and remove them
if (mBody && CAttachment::MessageRemoved(mBody, msg))
{
ResetTable();
}
}
// Get attachment from row
CAttachment* CFileTable::GetAttachment(TableIndexT row, bool is_worow)
{
if (row == 0)
return NULL;
TableIndexT woRow = is_worow ? row : GetWideOpenIndex(row);
STableCell woCell(woRow, 1);
CAttachment* attach;
UInt32 dataSize = sizeof(CAttachment*);
GetCellData(woCell, &attach, dataSize);
return attach;
}
// Add drag cells
void CFileTable::AddCellToDrag(CDragIt* theDragTask, const STableCell& theCell, Rect& dragRect)
{
// Add this message to drag
CAttachment* attach = GetAttachment(theCell.row);
theDragTask->AddFlavorItem(dragRect, (ItemReference) attach, cDragAtchType,
&attach, sizeof(CAttachment*), flavorSenderOnly, true);
}
// Current part changed
void CFileTable::ChangedCurrent(void)
{
// Refresh new one
if (!mAttachmentsOnly)
{
TableIndexT row = GetExposedIndex(mRowShow);
RefreshRow(row);
mWindow->SetCurrentPart(GetAttachment(mRowShow, true));
}
else
mWindow->SetCurrentPart(mWindow->GetCurrentPart());
}
// Test drop into cell
bool CFileTable::IsDropCell(DragReference inDragRef, STableCell aCell)
{
// Look for drop on self
if (sTableSource == this)
{
// Make sure row is not selected
if (CellIsSelected(aCell))
return false;
// Make sure parent row is not selected
int woRow = GetWideOpenIndex(aCell.row);
while((woRow = GetParentIndex(woRow)) > 0)
{
STableCell parent_cell(GetExposedIndex(woRow), 1);
if (CellIsSelected(parent_cell))
return false;
}
}
// Only drop into changable multipart part
int woRow = GetWideOpenIndex(aCell.row);
CAttachment* attach = GetAttachment(aCell.row);
return IsCollapsable(woRow) && attach->CanChange();
}
// Test drop at cell
bool CFileTable::IsDropAtCell(DragReference inDragRef, STableCell& aCell)
{
// Do not drop above top row
if (aCell.row == 1)
return false;
TableIndexT parent_row = 0;
CAttachment* parent = NULL;
TableIndexT pos = 0;
GetDropAtParent(aCell.row, parent_row, parent, pos);
if (!parent && (aCell.row <= mRows))
return false;
// Look for drop on self
if ((sTableSource == this) && parent_row)
{
// Make sure parent row is not selected
int woRow = parent_row;
do
{
STableCell parent_cell(GetExposedIndex(woRow), 1);
if (CellIsSelected(parent_cell))
return false;
} while((woRow = GetParentIndex(woRow)) > 0);
}
// Must be OK if we get here
return true;
}
// Drop data into whole table
// Occurs when table is empty before drop
void CFileTable::DropData(FlavorType theFlavor,
char* drag_data,
Size data_size)
{
// Do fake DropAtRow for top row
STableCell aCell(1, 1);
bool added = false;
TableIndexT parent_row = 0;
CAttachment* parent = NULL;
TableIndexT pos = -1;
if (theFlavor == cDragMsgType)
{
CMessage* theMsg = *((CMessage**) drag_data);
CMessageAttachment* new_attach = new CMessageAttachment(theMsg, theMsg);
AddPart(new_attach, parent, parent_row, pos, false);
added = true;
}
else if (theFlavor == cDragAtchType)
{
CAttachment* theAtch = *((CAttachment**) drag_data);
CAttachment* new_attach = CAttachment::CopyAttachment(*theAtch);
AddPart(new_attach, parent, parent_row, pos, false);
added = true;
}
else if (theFlavor == cDragMsgAtchType)
{
CMessage* owner = *((CMessage**) drag_data);
drag_data += sizeof(CMessage*);
CAttachment* theAtch = *((CAttachment**) drag_data);
if (theAtch->IsMessage())
{
CMessageAttachment* new_attach = new CMessageAttachment(owner, theAtch->GetMessage()); // Make alias, not copy
AddPart(new_attach, parent, parent_row, pos, false);
}
else
{
CAliasAttachment* new_attach = new CAliasAttachment(owner, theAtch); // Make alias, not copy
AddPart(new_attach, parent, parent_row, pos, false);
}
added = true;
}
// Only if not locked out
else if ((theFlavor == flavorTypeHFS) && !CAdminLock::sAdminLock.mNoAttachments)
{
HFSFlavor hfs = *((HFSFlavor*) drag_data);
CFileAttachment* theAtch = new CFileAttachment(hfs.fileSpec);
AddPart(theAtch, parent, parent_row, pos, false);
added = true;
}
// Refresh table if change
if (added)
{
UpdateRowShow();
Refresh();
}
}
// Drop data into cell
void CFileTable::DropDataIntoCell(FlavorType theFlavor,
char* drag_data,
Size data_size,
const STableCell& theCell)
{
bool added = false;
// Only allow drag to group
int woRow = GetWideOpenIndex(theCell.row);
if (!IsCollapsable(woRow))
return;
// Get attachment to drop into
CAttachment* parent = GetAttachment(theCell.row);
if (theFlavor == cDragMsgType)
{
CMessage* theMsg = *((CMessage**) drag_data);
CMessageAttachment* new_attach = new CMessageAttachment(theMsg, theMsg);
AddPart(new_attach, parent, woRow, -1, false);
added = true;
}
else if (theFlavor == cDragAtchType)
{
CAttachment* theAtch = *((CAttachment**) drag_data);
CAttachment* new_attach = CAttachment::CopyAttachment(*theAtch);
AddPart(new_attach, parent, woRow, -1, false);
added = true;
}
else if (theFlavor == cDragMsgAtchType)
{
CMessage* owner = *((CMessage**) drag_data);
drag_data += sizeof(CMessage*);
CAttachment* theAtch = *((CAttachment**) drag_data);
if (theAtch->IsMessage())
{
CMessageAttachment* new_attach = new CMessageAttachment(owner, theAtch->GetMessage()); // Make alias, not copy
AddPart(new_attach, parent, woRow, -1, false);
}
else
{
CAliasAttachment* new_attach = new CAliasAttachment(owner, theAtch); // Make alias, not copy
AddPart(new_attach, parent, woRow, -1, false);
}
added = true;
}
// Only if not locked out
else if ((theFlavor == flavorTypeHFS) && !CAdminLock::sAdminLock.mNoAttachments)
{
HFSFlavor hfs = *((HFSFlavor*) drag_data);
CFileAttachment* theAtch = new CFileAttachment(hfs.fileSpec);
AddPart(theAtch, parent, woRow, -1, false);
added = true;
}
// Refresh table if change
if (added)
{
UpdateRowShow();
Refresh();
}
}
// Drop data at cell
void CFileTable::DropDataAtCell(FlavorType theFlavor,
char* drag_data,
Size data_size,
const STableCell& beforeCell)
{
bool added = false;
// Get location of drop cell or first cell if beyond the start
int woRow = GetWideOpenIndex(beforeCell.row - 1);
if (!woRow)
woRow = GetWideOpenIndex(1);
TableIndexT old_total = mRows;
TableIndexT parent_row = 0;
CAttachment* parent = NULL;
TableIndexT pos = 0;
TableIndexT row = beforeCell.row;
GetDropAtParent(row, parent_row, parent, pos);
if (theFlavor == cDragMsgType)
{
CMessage* theMsg = *((CMessage**) drag_data);
CMessageAttachment* new_attach = new CMessageAttachment(theMsg, theMsg);
AddPart(new_attach, parent, parent_row, pos, false);
added = true;
}
else if (theFlavor == cDragAtchType)
{
CAttachment* theAtch = *((CAttachment**) drag_data);
CAttachment* new_attach = CAttachment::CopyAttachment(*theAtch);
AddPart(new_attach, parent, parent_row, pos, false);
added = true;
}
else if (theFlavor == cDragMsgAtchType)
{
CMessage* owner = *((CMessage**) drag_data);
drag_data += sizeof(CMessage*);
CAttachment* theAtch = *((CAttachment**) drag_data);
if (theAtch->IsMessage())
{
CMessageAttachment* new_attach = new CMessageAttachment(owner, theAtch->GetMessage()); // Make alias, not copy
AddPart(new_attach, parent, parent_row, pos, false);
}
else
{
CAliasAttachment* new_attach = new CAliasAttachment(owner, theAtch); // Make alias, not copy
AddPart(new_attach, parent, parent_row, pos, false);
}
added = true;
}
// Only if not locked out
else if ((theFlavor == flavorTypeHFS) && !CAdminLock::sAdminLock.mNoAttachments)
{
HFSFlavor hfs = *((HFSFlavor*) drag_data);
CFileAttachment* theAtch = new CFileAttachment(hfs.fileSpec);
AddPart(theAtch, parent, parent_row, pos, false);
added = true;
}
// Refresh table if change
if (added)
{
UpdateRowShow();
Refresh();
// Must update drop at position to take into account new item
int add = (mRows - old_total > 1) ? 2 : 1;
mLastDropCursor.row = std::min(mLastDropCursor.row + add, mRows);
}
}
// Get parent of cell for drop at
// returns bool : indicates whether original drop parent is used or not
void CFileTable::GetDropAtParent(TableIndexT& at_row, TableIndexT& parent_row, CAttachment*& parent, TableIndexT& pos)
{
// Get location of drop cell or first cell if beyond the start
int woRow = GetWideOpenIndex(at_row - 1); // This is row before cursor
if (!woRow)
woRow = GetWideOpenIndex(1);
parent_row = 0;
parent = NULL;
pos = 0;
if (IsCollapsable(woRow) && IsExpanded(woRow))
{
parent_row = woRow;
STableCell woCell(woRow, 1);
UInt32 dataSize = sizeof(CAttachment*);
GetCellData(woCell, &parent, dataSize);
pos = 0;
}
else
{
// Get attachment to drop into
// Note if there is only a single part it will be magically converted into a multipart
parent_row = GetParentIndex(woRow);
if (parent_row)
{
STableCell woCell(parent_row, 1);
UInt32 dataSize = sizeof(CAttachment*);
GetCellData(woCell, &parent, dataSize);
pos = ((CNodeVectorTree*) mCollapsableTree)->SiblingPosition(woRow);
}
else
{
parent_row = 0;
parent = NULL;
pos = -1;
}
}
// Now check that parent is changeable
if (parent && !parent->CanChange())
{
// Find parent's parent that is changeable
CAttachment* next = parent->GetParent();
int next_row = GetParentIndex(parent_row);
while(next && !next->CanChange())
{
parent = next;
parent_row = next_row;
next = parent->GetParent();
next_row = GetParentIndex(parent_row);
}
// Found a parent that will accept new attachment
if (next)
{
// New insert position is at child parent
at_row = parent_row;
// Find position for insert
pos = ((CNodeVectorTree*) mCollapsableTree)->SiblingPosition(parent_row);
parent = next;
parent_row = next_row;
}
else
{
parent_row = 0;
parent = NULL;
pos = -1;
// Force to last row
at_row = mRows + 1;
}
}
}
| 24.907632 | 152 | 0.706939 | [
"object"
] |
7fd9d4fbc9fc8e710b809883a79c26a52c0aecb3 | 3,484 | cpp | C++ | DlgPrefReference.cpp | RDamman/SpeakerWorkshop | 87a38d04197a07a9a7878b3f60d5e0706782163c | [
"OML"
] | 12 | 2019-06-07T10:06:41.000Z | 2021-03-22T22:13:59.000Z | DlgPrefReference.cpp | RDamman/SpeakerWorkshop | 87a38d04197a07a9a7878b3f60d5e0706782163c | [
"OML"
] | 1 | 2019-05-09T07:38:12.000Z | 2019-07-10T04:20:55.000Z | DlgPrefReference.cpp | RDamman/SpeakerWorkshop | 87a38d04197a07a9a7878b3f60d5e0706782163c | [
"OML"
] | 3 | 2020-09-08T08:27:33.000Z | 2021-05-13T09:25:43.000Z | // DlgPrefReference.cpp : implementation file
//
#include "stdafx.h"
#include "audtest.h"
#include "DlgPrefReference.h"
#include "Folder.h"
#include "DataSet.h"
#include "DlgSelec.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDlgPrefReference property page
IMPLEMENT_DYNCREATE(CDlgPrefReference, CPropertyPage)
CDlgPrefReference::CDlgPrefReference() : CPropertyPage(CDlgPrefReference::IDD)
{
EnableAutomation();
//{{AFX_DATA_INIT(CDlgPrefReference)
m_csLeftResponse = _T("");
m_csRightResponse = _T("");
m_csMicResponse = _T("");
m_fMicSensitivity = 0.0f;
//}}AFX_DATA_INIT
}
CDlgPrefReference::~CDlgPrefReference()
{
}
void CDlgPrefReference::OnFinalRelease()
{
// When the last reference for an automation object is released
// OnFinalRelease is called. The base class will automatically
// deletes the object. Add additional cleanup required for your
// object before calling the base class.
CPropertyPage::OnFinalRelease();
}
void CDlgPrefReference::DoDataExchange(CDataExchange* pDX)
{
CPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDlgPrefReference)
DDX_Text(pDX, IDC_LEFTRESP, m_csLeftResponse);
DDX_Text(pDX, IDC_RIGHTRESP, m_csRightResponse);
DDX_Text(pDX, IDC_MICRESP, m_csMicResponse);
DDX_Text(pDX, IDC_MICSENSE, m_fMicSensitivity);
DDV_MinMaxFloat(pDX, m_fMicSensitivity, 1.e-002f, 200.f);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CDlgPrefReference, CPropertyPage)
//{{AFX_MSG_MAP(CDlgPrefReference)
ON_BN_CLICKED(IDC_LEFTBROWSE, OnLeftbrowse)
ON_BN_CLICKED(IDC_RIGHTBROWSE, OnRightbrowse)
ON_BN_CLICKED(IDC_MICBROWSE, OnMicbrowse)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BEGIN_DISPATCH_MAP(CDlgPrefReference, CPropertyPage)
//{{AFX_DISPATCH_MAP(CDlgPrefReference)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_DISPATCH_MAP
END_DISPATCH_MAP()
// Note: we add support for IID_IDlgPrefReference to support typesafe binding
// from VBA. This IID must match the GUID that is attached to the
// dispinterface in the .ODL file.
// {A308C900-6D10-11CF-AA04-444553540000}
static const IID IID_IDlgPrefReference =
{ 0xa308c900, 0x6d10, 0x11cf, { 0xaa, 0x4, 0x44, 0x45, 0x53, 0x54, 0x0, 0x0 } };
BEGIN_INTERFACE_MAP(CDlgPrefReference, CPropertyPage)
INTERFACE_PART(CDlgPrefReference, IID_IDlgPrefReference, Dispatch)
END_INTERFACE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDlgPrefReference message handlers
static int do_HitButton( CFolder *cRoot, CString& csName, DWORD& dwID, UNITMSR uom)
{
CDlgSelectObject cdlg;
INT_PTR nrslt;
cdlg.SetParms( cRoot, dwID, ntDataSet, uom);
nrslt = cdlg.DoModal();
if ( IDOK == nrslt)
{
dwID = cdlg.m_dwSelected;
csName = "";
if ( cdlg.m_dwSelected)
{
CNamed *cnam = cRoot->GetItem( cdlg.m_dwSelected);
if ( cnam)
csName = cnam->GetFullName();
}
return IDOK;
}
return nrslt;
}
void CDlgPrefReference::OnLeftbrowse()
{
if ( IDOK == do_HitButton( m_cRoot, m_csLeftResponse, m_dwLeftResponse, uomFreq) )
UpdateData( FALSE);
}
void CDlgPrefReference::OnRightbrowse()
{
if ( IDOK == do_HitButton( m_cRoot, m_csRightResponse, m_dwRightResponse, uomFreq) )
UpdateData( FALSE);
}
void CDlgPrefReference::OnMicbrowse()
{
if ( IDOK == do_HitButton( m_cRoot, m_csMicResponse, m_dwMicResponse, uomFreq) )
UpdateData( FALSE);
}
| 24.70922 | 85 | 0.720723 | [
"object"
] |
8f0b432bbb4b4853ab5f344ebd6f23080eef63c0 | 1,168 | cpp | C++ | src/chapter_03_strings_and_regular_expressions/problem_023_binary_to_string_conversion.cpp | rturrado/TheModernCppChallenge | 648284fb417b6aaa43c21ea2b12a5a21c8cb9269 | [
"MIT"
] | null | null | null | src/chapter_03_strings_and_regular_expressions/problem_023_binary_to_string_conversion.cpp | rturrado/TheModernCppChallenge | 648284fb417b6aaa43c21ea2b12a5a21c8cb9269 | [
"MIT"
] | null | null | null | src/chapter_03_strings_and_regular_expressions/problem_023_binary_to_string_conversion.cpp | rturrado/TheModernCppChallenge | 648284fb417b6aaa43c21ea2b12a5a21c8cb9269 | [
"MIT"
] | null | null | null | #include "chapter_03_strings_and_regular_expressions/problem_023_binary_to_string_conversion.h"
#include <array>
#include <fmt/ostream.h>
#include <fmt/ranges.h>
#include <iostream> // cout
#include <numeric> // iota
#include <ostream>
#include <vector>
// Binary to string conversion
//
// Write a function that, given a range of 8-bit integers (such as an array or vector),
// returns a string that contains a hexadecimal representation of the input data.
// The function should be able to produce both uppercase and lowercase content.
//
// Here are some input and output examples:
// Input: { 0xBA, 0xAD, 0xF0, 0x0D }, output: "BAADF00D" or "baadf00d"
// Input: { 1, 2, 3, 4, 5, 6 }, output: "010203040506"
void problem_23_main(std::ostream& os) {
std::vector<uint8_t> v{ 0xBA, 0xAD, 0xf0, 0x0d };
fmt::print(os, "Converting vector [{:#02x}] to string \"{}\"\n", fmt::join(v, ", "), to_string(v));
std::array<uint8_t, 6> a{};
std::iota(std::begin(a), std::end(a), 1);
fmt::print(os, "Converting array [{:#02x}] to string \"{}\"\n\n", fmt::join(a, ", "), to_string(a));
}
void problem_23_main() {
problem_23_main(std::cout);
}
| 34.352941 | 104 | 0.670377 | [
"vector"
] |
8f1a01ecde13481407f68be3a91eca34703e6e47 | 7,480 | hh | C++ | include/blazevg.hh | FlightBlaze/blazevg | be71ab522012ad0351e46df157ee8574a173b92b | [
"Unlicense"
] | null | null | null | include/blazevg.hh | FlightBlaze/blazevg | be71ab522012ad0351e46df157ee8574a173b92b | [
"Unlicense"
] | null | null | null | include/blazevg.hh | FlightBlaze/blazevg | be71ab522012ad0351e46df157ee8574a173b92b | [
"Unlicense"
] | null | null | null | #pragma once
#include <glm/glm.hpp>
#include <vector>
#include <string>
#include <cmath>
#include <map>
namespace bvg {
enum class LineJoin {
Bevel,
Round,
Miter
};
enum class LineCap {
Butt,
Round,
Square
};
struct Color {
Color();
Color(float r, float g, float b, float a = 1.0f);
float r, g, b, a;
static Color lerp(Color a, Color b, float t);
};
namespace colors {
static const Color Black = Color(0.0f, 0.0f, 0.0f);
static const Color White = Color(1.0f, 1.0f, 1.0f);
} // namespace colors
struct Style {
Style();
enum class Type {
SolidColor,
LinearGradient,
RadialGradient,
ConicGradient
};
struct Linear {
Color startColor;
float startX = 0.0f;
float startY = 0.0f;
Color endColor;
float endX = 0.0f;
float endY = 0.0f;
};
struct Radial {
Color startColor;
Color endColor;
float x;
float y;
float radius;
};
struct Conic {
Color startColor;
Color endColor;
float x;
float y;
float angle;
};
Type type;
union {
Color color;
Linear linear;
Radial radial;
Conic conic;
};
};
Style SolidColor(Color color);
Style LinearGradient(float sx, float sy, float ex, float ey, Color start, Color end);
Style RadialGradient(float x, float y, float radius, Color start, Color end);
Style ConicGradient(float x, float y, float angle, Color start, Color end);
struct LineDash {
LineDash();
LineDash(float length, float gapLength, float offset = 0.0f);
float length, gapLength, offset;
std::vector<float> dash;
};
enum class BlendingMode : int {
Normal = 0,
Add = 1,
Subtract = 2,
Multiply = 3,
Divide = 4,
Screen = 5,
Overlay = 6,
Darker = 7,
Lighter = 8
};
namespace factory {
struct TwoPolylines {
std::vector<glm::vec2> first, second;
};
struct TriangeIndices {
int a, b, c;
};
struct ShapeMesh {
std::vector<glm::vec2> vertices;
std::vector<TriangeIndices> indices;
void add(ShapeMesh& b);
};
ShapeMesh strokePolyline(std::vector<glm::vec2>& points, const float diameter);
ShapeMesh bevelJoin(std::vector<glm::vec2>& a, std::vector<glm::vec2>& b, const float diameter);
ShapeMesh roundJoin(std::vector<glm::vec2>& a, std::vector<glm::vec2>& b, const float diameter);
ShapeMesh miterJoin(std::vector<glm::vec2>& a, std::vector<glm::vec2>& b, const float diameter,
float miterLimitAngle = M_PI_2 + M_PI_4);
TwoPolylines dividePolyline(std::vector<glm::vec2>& points, float t);
glm::vec2 getPointAtT(std::vector<glm::vec2>& points, float t);
std::vector<std::vector<glm::vec2>> dashedPolyline(std::vector<glm::vec2>& points,
float dashLength, float gapLength,
float offset = 0.0f);
ShapeMesh roundedCap(glm::vec2 position, glm::vec2 direction, const float diameter);
ShapeMesh squareCap(glm::vec2 position, glm::vec2 direction, const float diameter);
std::vector<float> measurePolyline(std::vector<glm::vec2>& points);
float lengthOfPolyline(std::vector<glm::vec2>& points);
float tAtLength(float length, std::vector<float>& lengths);
std::vector<TriangeIndices> createIndicesConvex(int numVertices);
} // namespace factory
namespace math {
glm::mat4 toMatrix3D(glm::mat3 mat2d);
bool isPointInTriange(glm::vec2 a, glm::vec2 b, glm::vec2 c, glm::vec2 point);
} // namespace math
class Font {
public:
struct Atlas {
int width, height;
};
struct Bounds {
float top, left, right, bottom;
};
struct Character {
int unicode, advance;
Bounds planeBounds, atlasBounds;
};
Atlas atlas;
int size, lineHeight, baseline;
int distanceRange;
protected:
virtual void loadCharacter(Character& character);
void parseJson(std::string& json);
};
class Context {
public:
Context(float width, float height);
Context();
float width = 0;
float height = 0;
float contentScale = 1.0f;
glm::mat4 viewProj = glm::mat4(1.0f);
glm::mat3 matrix = glm::mat3(1.0f);
BlendingMode blendingMode = BlendingMode::Normal;
LineJoin lineJoin = LineJoin::Miter;
LineCap lineCap = LineCap::Butt;
LineDash lineDash = LineDash();
float lineWidth = 2.0f;
Style fillStyle = SolidColor(colors::Black);
Style strokeStyle = SolidColor(colors::Black);
int blurRadius = 0;
std::map<std::string, Font*> fonts;
Font* font = nullptr;
float fontSize = 32.0f;
void loadFont(std::string jsonPath, std::string imagePath, std::string fontName);
virtual void loadFontFromMemory(std::string& json,
std::string fontName,
void* imageData,
int width,
int height,
int numChannels);
void orthographic(float width, float height);
void translate(float x, float y);
void scale(float x, float y);
void shearX(float x);
void shearY(float y);
void rotate(float a);
void clearTransform();
virtual void beginDrawing();
virtual void endDrawing();
void beginPath();
void closePath();
virtual void beginClip();
virtual void endClip();
virtual void clearClip();
virtual void convexFill();
virtual void fill();
virtual void stroke();
virtual void print(std::wstring str, float x, float y);
virtual void printOnPath(std::wstring str, float x = 0, float y = 0);
virtual float measureTextWidth(std::wstring str);
virtual float measureTextHeight();
void moveTo(float x, float y);
void lineTo(float x, float y);
void cubicTo(float cp1x, float cp1y, float cp2x, float cp2y, float x, float y);
void quadraticTo(float cpx, float cpy, float x, float y);
void arc(float x, float y, float radius, float startAngle, float endAngle);
void rect(float x, float y, float width, float height, float radius);
void rect(float x, float y, float width, float height);
void rect(float x, float y, float width, float height,
float topLeftRadius, float topRightRadius,
float bottomRightRadius, float bottomLeftRadius);
bool isPointInsideStroke(float x, float y);
bool isPointInsideConvexFill(float x, float y);
bool isPointInsideFill(float x, float y);
virtual ~Context();
protected:
std::vector<std::vector<glm::vec2>> mPolylines;
bool mIsPolylineClosed = false;
glm::vec2 mCurrentPos;
int mShapeDrawCounter = 0;
bool mDrawingBegan = false;
std::vector<glm::vec2> toOnePolyline(std::vector<std::vector<glm::vec2>> polylines);
factory::ShapeMesh internalFill();
factory::ShapeMesh internalConvexFill();
factory::ShapeMesh internalStroke();
void assertDrawingIsBegan();
std::vector<factory::TriangeIndices> debugTriangulate(std::vector<glm::vec2>& vertices,
bool draw);
};
namespace earcut {
std::vector<factory::TriangeIndices> triangulate(std::vector<glm::vec2>& vertices);
} // namespace earcut
} // namespace bvg
| 26.245614 | 96 | 0.617647 | [
"vector"
] |
8f1bc7d86701e7b7115ad0fe3548e437b2c098c4 | 16,058 | cpp | C++ | apiidec/PnlIdecAd1Control.cpp | mpsitech/idec_public | a74cf1c7095e08ee61b237fddc1642f83dbb852d | [
"BSD-2-Clause"
] | null | null | null | apiidec/PnlIdecAd1Control.cpp | mpsitech/idec_public | a74cf1c7095e08ee61b237fddc1642f83dbb852d | [
"BSD-2-Clause"
] | null | null | null | apiidec/PnlIdecAd1Control.cpp | mpsitech/idec_public | a74cf1c7095e08ee61b237fddc1642f83dbb852d | [
"BSD-2-Clause"
] | null | null | null | /**
* \file PnlIdecAd1Control.cpp
* API code for job PnlIdecAd1Control (implementation)
* \author Alexander Wirthmueller
* \date created: 30 Dec 2017
* \date modified: 30 Dec 2017
*/
#ifdef _WIN32
#include "stdafx.h"
#endif
#include "PnlIdecAd1Control.h"
/******************************************************************************
class PnlIdecAd1Control::VecVDo
******************************************************************************/
uint PnlIdecAd1Control::VecVDo::getIx(
const string& sref
) {
string s = StrMod::lc(sref);
if (s == "butmasterclick") return BUTMASTERCLICK;
else if (s == "butrunclick") return BUTRUNCLICK;
else if (s == "butstoclick") return BUTSTOCLICK;
return(0);
};
string PnlIdecAd1Control::VecVDo::getSref(
const uint ix
) {
if (ix == BUTMASTERCLICK) return("ButMasterClick");
else if (ix == BUTRUNCLICK) return("ButRunClick");
else if (ix == BUTSTOCLICK) return("ButStoClick");
return("");
};
/******************************************************************************
class PnlIdecAd1Control::VecVSge
******************************************************************************/
uint PnlIdecAd1Control::VecVSge::getIx(
const string& sref
) {
string s = StrMod::lc(sref);
if (s == "idle") return IDLE;
else if (s == "alrgum") return ALRGUM;
return(0);
};
string PnlIdecAd1Control::VecVSge::getSref(
const uint ix
) {
if (ix == IDLE) return("idle");
else if (ix == ALRGUM) return("alrgum");
return("");
};
/******************************************************************************
class PnlIdecAd1Control::ContIac
******************************************************************************/
PnlIdecAd1Control::ContIac::ContIac(
const double SldTll
, const double SldTul
, const int UpdMct
) : Block() {
this->SldTll = SldTll;
this->SldTul = SldTul;
this->UpdMct = UpdMct;
mask = {SLDTLL, SLDTUL, UPDMCT};
};
bool PnlIdecAd1Control::ContIac::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContIacIdecAd1Control");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "ContitemIacIdecAd1Control";
if (basefound) {
if (extractDoubleAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "SldTll", SldTll)) add(SLDTLL);
if (extractDoubleAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "SldTul", SldTul)) add(SLDTUL);
if (extractIntAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "UpdMct", UpdMct)) add(UPDMCT);
};
return basefound;
};
void PnlIdecAd1Control::ContIac::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "ContIacIdecAd1Control";
string itemtag;
if (shorttags) itemtag = "Ci";
else itemtag = "ContitemIacIdecAd1Control";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeDoubleAttr(wr, itemtag, "sref", "SldTll", SldTll);
writeDoubleAttr(wr, itemtag, "sref", "SldTul", SldTul);
writeIntAttr(wr, itemtag, "sref", "UpdMct", UpdMct);
xmlTextWriterEndElement(wr);
};
set<uint> PnlIdecAd1Control::ContIac::comm(
const ContIac* comp
) {
set<uint> items;
if (compareDouble(SldTll, comp->SldTll) < 1.0e-4) insert(items, SLDTLL);
if (compareDouble(SldTul, comp->SldTul) < 1.0e-4) insert(items, SLDTUL);
if (UpdMct == comp->UpdMct) insert(items, UPDMCT);
return(items);
};
set<uint> PnlIdecAd1Control::ContIac::diff(
const ContIac* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {SLDTLL, SLDTUL, UPDMCT};
for (auto it=commitems.begin();it!=commitems.end();it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlIdecAd1Control::ContInf
******************************************************************************/
PnlIdecAd1Control::ContInf::ContInf(
const uint numFSge
, const bool ButMasterOn
, const string& TxtPrg
) : Block() {
this->numFSge = numFSge;
this->ButMasterOn = ButMasterOn;
this->TxtPrg = TxtPrg;
mask = {NUMFSGE, BUTMASTERON, TXTPRG};
};
bool PnlIdecAd1Control::ContInf::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContInfIdecAd1Control");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "ContitemInfIdecAd1Control";
if (basefound) {
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFSge", numFSge)) add(NUMFSGE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "ButMasterOn", ButMasterOn)) add(BUTMASTERON);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxtPrg", TxtPrg)) add(TXTPRG);
};
return basefound;
};
set<uint> PnlIdecAd1Control::ContInf::comm(
const ContInf* comp
) {
set<uint> items;
if (numFSge == comp->numFSge) insert(items, NUMFSGE);
if (ButMasterOn == comp->ButMasterOn) insert(items, BUTMASTERON);
if (TxtPrg.compare(comp->TxtPrg) == 0) insert(items, TXTPRG);
return(items);
};
set<uint> PnlIdecAd1Control::ContInf::diff(
const ContInf* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {NUMFSGE, BUTMASTERON, TXTPRG};
for (auto it=commitems.begin();it!=commitems.end();it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlIdecAd1Control::StatApp
******************************************************************************/
PnlIdecAd1Control::StatApp::StatApp(
const uint ixIdecVExpstate
) : Block() {
this->ixIdecVExpstate = ixIdecVExpstate;
mask = {IXIDECVEXPSTATE};
};
bool PnlIdecAd1Control::StatApp::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
string srefIxIdecVExpstate;
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatAppIdecAd1Control");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "StatitemAppIdecAd1Control";
if (basefound) {
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "srefIxIdecVExpstate", srefIxIdecVExpstate)) {
ixIdecVExpstate = VecIdecVExpstate::getIx(srefIxIdecVExpstate);
add(IXIDECVEXPSTATE);
};
};
return basefound;
};
set<uint> PnlIdecAd1Control::StatApp::comm(
const StatApp* comp
) {
set<uint> items;
if (ixIdecVExpstate == comp->ixIdecVExpstate) insert(items, IXIDECVEXPSTATE);
return(items);
};
set<uint> PnlIdecAd1Control::StatApp::diff(
const StatApp* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {IXIDECVEXPSTATE};
for (auto it=commitems.begin();it!=commitems.end();it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlIdecAd1Control::StatShr
******************************************************************************/
PnlIdecAd1Control::StatShr::StatShr(
const double SldTllMin
, const double SldTllMax
, const double SldTulMin
, const double SldTulMax
, const int UpdMctMin
, const int UpdMctMax
, const bool ButRunActive
, const bool ButStoActive
) : Block() {
this->SldTllMin = SldTllMin;
this->SldTllMax = SldTllMax;
this->SldTulMin = SldTulMin;
this->SldTulMax = SldTulMax;
this->UpdMctMin = UpdMctMin;
this->UpdMctMax = UpdMctMax;
this->ButRunActive = ButRunActive;
this->ButStoActive = ButStoActive;
mask = {SLDTLLMIN, SLDTLLMAX, SLDTULMIN, SLDTULMAX, UPDMCTMIN, UPDMCTMAX, BUTRUNACTIVE, BUTSTOACTIVE};
};
bool PnlIdecAd1Control::StatShr::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatShrIdecAd1Control");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "StatitemShrIdecAd1Control";
if (basefound) {
if (extractDoubleAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "SldTllMin", SldTllMin)) add(SLDTLLMIN);
if (extractDoubleAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "SldTllMax", SldTllMax)) add(SLDTLLMAX);
if (extractDoubleAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "SldTulMin", SldTulMin)) add(SLDTULMIN);
if (extractDoubleAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "SldTulMax", SldTulMax)) add(SLDTULMAX);
if (extractIntAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "UpdMctMin", UpdMctMin)) add(UPDMCTMIN);
if (extractIntAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "UpdMctMax", UpdMctMax)) add(UPDMCTMAX);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButRunActive", ButRunActive)) add(BUTRUNACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButStoActive", ButStoActive)) add(BUTSTOACTIVE);
};
return basefound;
};
set<uint> PnlIdecAd1Control::StatShr::comm(
const StatShr* comp
) {
set<uint> items;
if (compareDouble(SldTllMin, comp->SldTllMin) < 1.0e-4) insert(items, SLDTLLMIN);
if (compareDouble(SldTllMax, comp->SldTllMax) < 1.0e-4) insert(items, SLDTLLMAX);
if (compareDouble(SldTulMin, comp->SldTulMin) < 1.0e-4) insert(items, SLDTULMIN);
if (compareDouble(SldTulMax, comp->SldTulMax) < 1.0e-4) insert(items, SLDTULMAX);
if (UpdMctMin == comp->UpdMctMin) insert(items, UPDMCTMIN);
if (UpdMctMax == comp->UpdMctMax) insert(items, UPDMCTMAX);
if (ButRunActive == comp->ButRunActive) insert(items, BUTRUNACTIVE);
if (ButStoActive == comp->ButStoActive) insert(items, BUTSTOACTIVE);
return(items);
};
set<uint> PnlIdecAd1Control::StatShr::diff(
const StatShr* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {SLDTLLMIN, SLDTLLMAX, SLDTULMIN, SLDTULMAX, UPDMCTMIN, UPDMCTMAX, BUTRUNACTIVE, BUTSTOACTIVE};
for (auto it=commitems.begin();it!=commitems.end();it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlIdecAd1Control::Tag
******************************************************************************/
PnlIdecAd1Control::Tag::Tag(
const string& Cpt
, const string& HdgRoi
, const string& CptTll
, const string& CptTul
, const string& CptMct
, const string& CptPrg
, const string& ButRun
, const string& ButSto
) : Block() {
this->Cpt = Cpt;
this->HdgRoi = HdgRoi;
this->CptTll = CptTll;
this->CptTul = CptTul;
this->CptMct = CptMct;
this->CptPrg = CptPrg;
this->ButRun = ButRun;
this->ButSto = ButSto;
mask = {CPT, HDGROI, CPTTLL, CPTTUL, CPTMCT, CPTPRG, BUTRUN, BUTSTO};
};
bool PnlIdecAd1Control::Tag::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "TagIdecAd1Control");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "TagitemIdecAd1Control";
if (basefound) {
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "Cpt", Cpt)) add(CPT);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "HdgRoi", HdgRoi)) add(HDGROI);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptTll", CptTll)) add(CPTTLL);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptTul", CptTul)) add(CPTTUL);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptMct", CptMct)) add(CPTMCT);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptPrg", CptPrg)) add(CPTPRG);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "ButRun", ButRun)) add(BUTRUN);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "ButSto", ButSto)) add(BUTSTO);
};
return basefound;
};
/******************************************************************************
class PnlIdecAd1Control::DpchAppData
******************************************************************************/
PnlIdecAd1Control::DpchAppData::DpchAppData(
const string& scrJref
, ContIac* contiac
, const set<uint>& mask
) : DpchAppIdec(VecIdecVDpch::DPCHAPPIDECAD1CONTROLDATA, scrJref) {
if (find(mask, ALL)) this->mask = {SCRJREF, CONTIAC};
else this->mask = mask;
if (find(this->mask, CONTIAC) && contiac) this->contiac = *contiac;
};
string PnlIdecAd1Control::DpchAppData::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(SCRJREF)) ss.push_back("scrJref");
if (has(CONTIAC)) ss.push_back("contiac");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlIdecAd1Control::DpchAppData::writeXML(
xmlTextWriter* wr
) {
xmlTextWriterStartElement(wr, BAD_CAST "DpchAppIdecAd1ControlData");
xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/idec");
if (has(SCRJREF)) writeString(wr, "scrJref", scrJref);
if (has(CONTIAC)) contiac.writeXML(wr);
xmlTextWriterEndElement(wr);
};
/******************************************************************************
class PnlIdecAd1Control::DpchAppDo
******************************************************************************/
PnlIdecAd1Control::DpchAppDo::DpchAppDo(
const string& scrJref
, const uint ixVDo
, const set<uint>& mask
) : DpchAppIdec(VecIdecVDpch::DPCHAPPIDECAD1CONTROLDO, scrJref) {
if (find(mask, ALL)) this->mask = {SCRJREF, IXVDO};
else this->mask = mask;
this->ixVDo = ixVDo;
};
string PnlIdecAd1Control::DpchAppDo::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(SCRJREF)) ss.push_back("scrJref");
if (has(IXVDO)) ss.push_back("ixVDo");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlIdecAd1Control::DpchAppDo::writeXML(
xmlTextWriter* wr
) {
xmlTextWriterStartElement(wr, BAD_CAST "DpchAppIdecAd1ControlDo");
xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/idec");
if (has(SCRJREF)) writeString(wr, "scrJref", scrJref);
if (has(IXVDO)) writeString(wr, "srefIxVDo", VecVDo::getSref(ixVDo));
xmlTextWriterEndElement(wr);
};
/******************************************************************************
class PnlIdecAd1Control::DpchEngData
******************************************************************************/
PnlIdecAd1Control::DpchEngData::DpchEngData() : DpchEngIdec(VecIdecVDpch::DPCHENGIDECAD1CONTROLDATA) {
feedFSge.tag = "FeedFSge";
};
string PnlIdecAd1Control::DpchEngData::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(SCRJREF)) ss.push_back("scrJref");
if (has(CONTIAC)) ss.push_back("contiac");
if (has(CONTINF)) ss.push_back("continf");
if (has(FEEDFSGE)) ss.push_back("feedFSge");
if (has(STATAPP)) ss.push_back("statapp");
if (has(STATSHR)) ss.push_back("statshr");
if (has(TAG)) ss.push_back("tag");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlIdecAd1Control::DpchEngData::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchEngIdecAd1ControlData");
else
basefound = checkXPath(docctx, basexpath);
if (basefound) {
if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) add(SCRJREF);
if (contiac.readXML(docctx, basexpath, true)) add(CONTIAC);
if (continf.readXML(docctx, basexpath, true)) add(CONTINF);
if (feedFSge.readXML(docctx, basexpath, true)) add(FEEDFSGE);
if (statapp.readXML(docctx, basexpath, true)) add(STATAPP);
if (statshr.readXML(docctx, basexpath, true)) add(STATSHR);
if (tag.readXML(docctx, basexpath, true)) add(TAG);
} else {
contiac = ContIac();
continf = ContInf();
feedFSge.clear();
statapp = StatApp();
statshr = StatShr();
tag = Tag();
};
};
| 28.933333 | 117 | 0.638685 | [
"vector"
] |
8f24e57dad521ffa2437ef9de9bd52f1ebdb113b | 20,706 | cpp | C++ | PPN_ChemoR/aux/scripts/trimal/source/statisticsConservation.cpp | zamanianlab/Phylogenetics | cba8b13c6fca7563a94d8e254d345464c740afc9 | [
"MIT"
] | 2 | 2020-04-23T00:58:42.000Z | 2020-08-17T22:16:50.000Z | bash/auxillary/trimal/source/statisticsConservation.cpp | zamanianlab/BrugiaChemo-ms | 47bea22f598784d713eafcc08e7848a4a76c659e | [
"MIT"
] | null | null | null | bash/auxillary/trimal/source/statisticsConservation.cpp | zamanianlab/BrugiaChemo-ms | 47bea22f598784d713eafcc08e7848a4a76c659e | [
"MIT"
] | null | null | null | /* ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** *****
***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** *****
trimAl v1.4: a tool for automated alignment trimming in large-scale
phylogenetics analyses.
2009-2011 Capella-Gutierrez S. and Gabaldon, T.
[scapella, tgabaldon]@crg.es
This file is part of trimAl.
trimAl 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, the last available version.
trimAl 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 trimAl. If not, see <http://www.gnu.org/licenses/>.
***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** *****
***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** ***** */
#include "statisticsConservation.h"
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
| statisticsConservation::statisticsConservation(char **, int, int) |
| |
| Class constructor. This method uses the inputs parameters to put the information in the new object that |
| has been created. |
| |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
statisticsConservation::statisticsConservation(string *alignmentMatrix, int species, int aminos, int dataType_) {
/* Initializate values to its corresponds values */
columns = aminos;
sequences = species;
dataType = dataType_;
halfWindow = -1;
/* Allocate memory to the structures and initializates it */
Q = new float[columns];
utils::initlVect(Q, columns, 0);
MDK = new float[columns];
utils::initlVect(MDK, columns, 0);
MDK_Window = new float[columns];
utils::initlVect(MDK_Window, columns, 0);
matrixIdentity = new float*[sequences];
for(int i = 0; i < sequences; i++){
matrixIdentity[i] = new float[sequences];
utils::initlVect(matrixIdentity[i], sequences, 0);
}
/* Initializate the similarity matrix to NULL. */
simMatrix = NULL;
/* Calculation methods call */
calculateMatrixIdentity(alignmentMatrix);
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
| statisticsConservation::statisticsConservation(void) |
| |
| Class constructor. |
| |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
statisticsConservation::statisticsConservation(void) {
/* Initializate all values to 0 */
columns = 0;
sequences = 0;
halfWindow = 0;
/* and the pointers to NULL */
Q = NULL;
MDK = NULL;
MDK_Window = NULL;
matrixIdentity = NULL;
simMatrix = NULL;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
| statisticsConservation::~statisticsConservation(void) |
| |
| Class destroyer. |
| |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
statisticsConservation::~statisticsConservation(void) {
int i;
/* Deallocate memory, if it have been allocated previously. */
if(Q != NULL) {
delete[] Q;
delete[] MDK;
delete[] MDK_Window;
for(i = 0; i < sequences; i++)
delete[] matrixIdentity[i];
delete[] matrixIdentity;
}
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
| void statisticsConservation::calculateMatrixIdentity(char **, int, int) |
| |
| This method computes the matrix identity between all the sequences in the alignment. |
| |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void statisticsConservation::calculateMatrixIdentity(string *alignmentMatrix) {
char indet;
int i, j, k, sum, length;
if(dataType == AAType)
indet = 'X';
else
indet = 'N';
/* For each sequences' pair */
for(i = 0; i < sequences; i++) {
for(j = i + 1; j < sequences; j++) {
/* For each position in the alignment of that pair than we are processing */
for(k = 0, sum = 0, length = 0; k < columns; k++) {
/* If we find a element that is not a gap or an X aminoacid in the first sequence of the pair */
if((alignmentMatrix[i][k] != '-') && (alignmentMatrix[i][k] != indet)) {
/* If we also find a valid element in the second sequence */
if((alignmentMatrix[j][k] != '-') && (alignmentMatrix[j][k] != indet))
/* If the two valid elements are the same increase the sum */
if(alignmentMatrix[j][k] == alignmentMatrix[i][k])
sum++;
/* Increase the length of the sequence free of gaps and X elements */
length++;
}
/* If the first processed element is invalid and in the second we find a valid element increase the length of
the sequence free of gaps and X elements */
else if((alignmentMatrix[j][k] != '-') && (alignmentMatrix[j][k] != indet))
length++;
}
/* Calculate the value of matrixidn for columns j and i */
matrixIdentity[j][i] = (100.0 - ((float) sum/ length) * 100.0);
matrixIdentity[i][j] = matrixIdentity[j][i];
}
}
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
| bool statisticsConservation::calculateVectors(char **, int *) |
| |
| This method computes the distance between pairs for each column in the alignment. |
| |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
bool statisticsConservation::calculateVectors(string *alignmentMatrix, int *gaps) {
char indet;
int i, j, k;
float num, den;
if(dataType == AAType)
indet = 'X';
else
indet = 'N';
/* A conservation matrix must be defined. If not, return false */
if(simMatrix == NULL)
return false;
/* For each column calculate the Q value and the MD value using an equation */
for(i = 0; i < columns; i++) {
/* For each AAs/Nucleotides' pair in the column we compute its distance */
for(j = 0, num = 0, den = 0; j < sequences; j++) {
/* We don't compute the distant if the first element is a indeterminate (X) or a gap (-) element. */
if((alignmentMatrix[j][i] != '-') && (alignmentMatrix[j][i] != indet))
for(k = j + 1; k < sequences; k++)
/* We don't compute the distant between the pair if the second element is a indeterminate or a gap element */
if((alignmentMatrix[k][i] != '-') && (alignmentMatrix[k][i] != indet)) {
/* We use the identity value for the two pairs and its distance based on similarity matrix's value. */
num += matrixIdentity[j][k] * simMatrix -> getDistance(alignmentMatrix[j][i], alignmentMatrix[k][i]);;
den += matrixIdentity[j][k];
}
}
/* If we are procesing a column with only one AA/nucleotide, the denominator is 0 and we don't execute the division
and we set the Q[i] value to 0. */
Q[i] = (den == 0) ? 0 : num / den;
MDK[i] = (float) exp(-Q[i]);
/* If the column has 80% or more gaps then we set its conservation value to 0 */
if(gaps != NULL)
if(((float) gaps[i] / sequences) >= 0.8) MDK[i] = 0;
/* If the MDK value is more than 1, we normalized this value to 1. */
if(MDK[i] > 1) MDK[i] = 1;
}
return true;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
| bool statisticsConservation::applyWindow(int) |
| |
| This method computes for each column's alignment its conservationwindows' value. For this purpose, the method |
| uses the values that previously has been calculated and the window's size value. |
| |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
bool statisticsConservation::applyWindow(int _halfWindow) {
int i, j, window;
/* If one of this conditions is true, we return FALSE: */
/* .- If already exists a previously calculated vector for this window size */
/* .- If mediumWinSize value is greater than 1/4 of alignment length */
if((halfWindow == _halfWindow) || (_halfWindow > columns/4))
return false;
halfWindow = _halfWindow;
window = 2 * halfWindow + 1;
/* Do the average window calculations */
for(i = 0; i < columns; i++) {
for(j = i - halfWindow; j <= i + halfWindow; j++) {
if(j < 0) MDK_Window[i] += MDK[-j];
else if(j >= columns) MDK_Window[i] += MDK[((2 * columns - j) - 2)];
else MDK_Window[i] += MDK[j];
}
/* Calculate the similiraty value for the i column */
MDK_Window[i] = MDK_Window[i] / (float) window;
}
return true;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
| bool statisticsConservation::isDefinedWindow(void) |
| |
| This method returns true if a similarity matrix has been defined and false in others cases. |
| |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
bool statisticsConservation::isDefinedWindow(void) {
return (halfWindow != -1);
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
| bool statisticsConservation::getMdkwVector(void) |
| |
| This method returns a pointer to conservation values' vector. |
| |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
float *statisticsConservation::getMdkwVector(void) {
return MDK_Window;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
| bool statisticsConservation::setSimilarityMatrix(similarityMatrix *) |
| |
| This method associated a pointer to similarity matrix gives as input parameter. If a conservation matrix is |
| being used the methods return false and doesn't do anything. |
| |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
bool statisticsConservation::setSimilarityMatrix(similarityMatrix *sm) {
/* Checks if a similarity matrix is being used. */
if(sm == NULL)
return false;
/* if a similarity matrix isn't being used, we associate a pointer gives as input parameter to object simMatrix's
pointer and return true. */
simMatrix = sm;
return true;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
| bool statisticsConservation::isSimMatrixDef(void) |
| |
| This method returns true if a similarity matrix is being used and false in others cases. |
| |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
bool statisticsConservation::isSimMatrixDef(void) {
return (simMatrix != NULL);
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
| float statisticsConservation::calcCutPoint(float baseLine, float conservationPct) |
| |
| This method computes and selects the cut point value based on alignment's conservation. For this purpose, this |
| select the minimum conservation value bewteen the conservationPct -a conservation value- and the conservation |
| value allows us conserve the columns' number associated to baseline. |
| |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
float statisticsConservation::calcCutPoint(float baseLine, float conservationPct) {
float cutBL, cutCons, *vectAux;
int i;
/* Allocate memory */
vectAux = new float[columns];
/* Sort a copy of the MDK_Window vector, and take the value of the column that marks the % baseline */
utils::copyVect(MDK_Window, vectAux, columns);
utils::quicksort(vectAux, 0, columns-1);
for(i = columns - 1; i >= 0; i--)
if(vectAux[i] < conservationPct) break;
cutCons = vectAux[i];
cutBL = vectAux[(int) ((float)(columns - 1) * (100.0 - baseLine)/100.0)];
/* Deallocate memory */
delete[] vectAux;
/* Return the minimum of the baseLine cut and conservationPct value */
return (cutBL < cutCons ? cutBL : cutCons);
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
| void statisticsConservation::printConservationColumns(void) |
| |
| This method prints the conservation's value for each column in the alignment. |
| |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void statisticsConservation::printConservationColumns(void) {
int i;
/* We set the output precision and print the header. */
cout << "| Residue\t Similarity |" << endl;
cout << "| Number \t Value |" << endl;
cout << "+----------------------------+" << endl;
cout.precision(10);
/* If MDK_Window vector is defined, we use it to print the conservation's values. */
if(MDK_Window != NULL)
for(i = 0; i < columns; i++)
cout << " " << setw(5) << i << "\t\t" << setw(7) << MDK_Window[i] << endl;
/* In others cases, we uses the MDK vector to print the conservation's vlaues. */
else
for(i = 0; i < columns; i++)
cout << " " << setw(5) << i << "\t\t" << setw(7) << MDK[i] << endl;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
| void statisticsConservation::printConservationAcl(void) |
| |
| This method prints the accumulative statistics related to conservation in the alignment. |
| |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void statisticsConservation::printConservationAcl(void) {
float refer, *vectAux;
int i, num, acm;
/* Allocate memory */
vectAux = new float[columns];
/* Select the conservation's value source and copy that vector in a auxiliar vector */
if(MDK_Window != NULL) utils::copyVect(MDK_Window, vectAux, columns);
else utils::copyVect(MDK, vectAux, columns);
/* Sort the auxiliar vector. */
utils::quicksort(vectAux, 0, columns-1);
/* We set the output precision and print the header. */
cout << "| Number of\t \t|\t Cumulative \t% Cumulative\t| Similarity |" << endl;
cout << "| Residues \t% Length\t|\tNumberResid.\t Length \t| Value |" << endl;
cout << "+-------------------------------+---------------------------------------+----------------+" << endl;
cout.precision(10);
/* Initializate some values */
refer = vectAux[columns-1];
acm = 0; num = 1;
/* Count the columns with the same conservation's value and compute this information to shows the accunulative
statistics in the alignment. */
for(i = columns-2; i >= 0; i--) {
acm++;
if(refer != vectAux[i]) {
cout << " " << num << "\t\t" << setw(10) << ((float) num/columns * 100.0)
<< "\t\t" << acm << "\t\t" << setw(10) << ((float) acm/columns * 100.0) << "\t"
<< setw(15) << refer << endl;
refer = vectAux[i];
num = 1;
}
else num++;
}
acm++;
cout << " " << num << "\t\t" << setw(10) << ((float) num/columns * 100.0)
<< "\t\t" << acm << "\t\t" << setw(10) << ((float) acm/columns * 100.0) << "\t"
<< setw(15) << refer << endl;
/* Deallocate the reserved memory. */
delete [] vectAux;
}
| 48.72 | 120 | 0.39404 | [
"object",
"vector"
] |
8f2d7132a01fd2920a21bed99cd7ca0fb73c0874 | 5,852 | cpp | C++ | src/vine_controller.cpp | vineyard2020/vine_controller | aab36529093ee51b2ca6c040c068761486b95e8b | [
"Apache-2.0"
] | 2 | 2021-04-06T12:00:43.000Z | 2021-04-06T12:14:44.000Z | src/vine_controller.cpp | CARV-ICS-FORTH/vine_controller | aab36529093ee51b2ca6c040c068761486b95e8b | [
"Apache-2.0"
] | null | null | null | src/vine_controller.cpp | CARV-ICS-FORTH/vine_controller | aab36529093ee51b2ca6c040c068761486b95e8b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018 Foundation for Research and Technology - Hellas
*
* 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 [1] [1]
*
* 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.
*
* Links:
* ------
* [1] http://www.apache.org/licenses/LICENSE-2.0 [1]
*/
#include <iostream>
#include <fstream>
#include <csignal>
#include <signal.h>
#include <iomanip>
#include <stdio.h>
#include <cstring>
#include <stdlib.h>
#include <sstream>
#include "vine_pipe.h"
#include <vector>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
#include "VineLibMgr.h"
#include "accelThread.h"
#include "Scheduler.h"
#include "definesEnable.h"
#include "Formater.h"
#include <chrono>
#include <ctime>
#include <sched.h>
using namespace ::std;
vine_pipe_s *vpipe; /* get a pointer to the vine pipe */
void *shm = 0; /* get a pointer to the share memory segment */
volatile bool shouldExit = false;
/* Define the function to be called when ctrl-c (SIGINT) signal is sent to
* process*/
void signal_callback_handler(int signum) {
#if (DEBUG_ENABLED)
cout << "Caught signal " << signum << endl;
#endif
shouldExit = true;
}
/*Deregister accelerators at termination*/
void deRegisterAccel(vine_pipe_s *vpipe_s,
vector<AccelConfig*> &accelSystemList) {
cout << "Deregister accelerators" << endl;
vector<AccelConfig*>::iterator it;
for (it = accelSystemList.begin(); it != accelSystemList.end(); ++it) {
vine_accel_release((vine_accel**)&((*it)->vine_accel));
}
}
/*Creates one thread per physical accelerator*/
bool spawnThreads(vine_pipe_s *vpipe_s,vector<AccelConfig*> &accelSystemList) {
/*iterate to the list with the accels from config file*/
vector<AccelConfig*>::iterator itr;
string msg;
accelThread *thread;
for (itr = accelSystemList.begin(); itr != accelSystemList.end(); ++itr) {
// Initialize accelerator
(*itr)->vine_accel = vine_accel_init(vpipe_s , (char *)((*itr)->name.c_str()), (*itr)->type);
if ((*itr)->vine_accel == 0)
{
msg = "Failed to perform initialization";
goto FAIL;
}
// Create thread
thread = threadFactory.constructType((*itr)->type_str,vpipe_s,*(*itr));
if(!thread)
{
msg = "Could not create thread";
goto FAIL;
}
(*itr)->accelthread = thread;
// Spawn thread
thread->spawn();
}
return true;
FAIL:
cerr << "While spawning line " << (*itr)->line << ": \'" << *itr << "\'\n" << msg << " for " << (*itr)->type_str << endl;
return false;
}
/*Deregister threads */
void deleteThreads(vector<AccelConfig*> &accelSystemList) {
/*iterate to the list with the accels from config file*/
vector<AccelConfig*>::iterator itr;
for (itr = accelSystemList.begin(); itr != accelSystemList.end(); ++itr) {
/*creates one thread per line from config file*/
(*itr)->accelthread->terminate();
}
for (itr = accelSystemList.begin(); itr != accelSystemList.end(); ++itr) {
(*itr)->accelthread->joinThreads();
delete (*itr)->accelthread;
}
}
vine_pipe_s *vpipe_s;
/*Main function*/
int main(int argc, char *argv[]) {
/* get the directories that .so exist*/
if (argc < 2)
{
cerr << "Usage:\n\t" << argv[0] << " config_file" << endl;
return 0;
}
/*Create a config instance*/
try
{
/*Config gets as arguments a file with the appropriate info*/
Config config(argv[1]);
/*Vector with the paths that libraries are located*/
vector<string> paths = config.getPaths();
if(paths.size() == 0)
{
cerr << "No library paths declared in config file" << endl;
return 0;
}
cerr << "Library paths: " << Formater<string>("\n\t","\n\t","\n",paths) << endl;
/*get the share mem segment*/
vpipe_s = vine_talk_init();
/* Load folder with .so*/
VineLibMgr *vineLibMgr = new VineLibMgr();
for (vector<string>::iterator itr = paths.begin() ; itr != paths.end(); itr++)
{
if(!vineLibMgr->loadFolder(*itr))
return -1;
}
vineLibMgr->startRunTimeLoader();
cerr << "Supported threads: "
<< Formater<string>("\n\t","\n\t","\n",threadFactory.getTypes()) << endl;
cerr << "Supported Schedulers: "
<< Formater<string>("\n\t","\n\t","\n",schedulerFactory.getTypes()) << endl;
cerr << config << endl;
/*create a vine task pointer*/
vector<AccelConfig*> vectorOfAccels;
vectorOfAccels = config.getAccelerators();
signal(SIGINT, signal_callback_handler);
/*create threads*/
if(!spawnThreads(vpipe_s,vectorOfAccels))
{
cerr << "Failed to spawn threads, exiting" << endl;
return 0;
}
while (!shouldExit)
{
usleep(1000);
if (shouldExit)
{
cout << "Ctr+c is pressed EXIT!" << endl;
break;
}
}
deleteThreads(vectorOfAccels);
deRegisterAccel(vpipe_s, vectorOfAccels);
/*Delete libraries*/
vineLibMgr->unloadLibraries(vpipe_s);
delete vineLibMgr;
}catch(exception * e)
{
cerr << "Error:\n\t" << e->what() << endl;
}
vine_talk_exit();
return 0;
}
| 28.970297 | 125 | 0.602529 | [
"vector"
] |
8f45a0547d490cd99b9fd768765392e5ccbdd44a | 17,068 | cc | C++ | mindspore/ccsrc/common/graph_kernel/model/op_node.cc | httpsgithu/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | 1 | 2022-02-23T09:13:43.000Z | 2022-02-23T09:13:43.000Z | mindspore/ccsrc/common/graph_kernel/model/op_node.cc | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/common/graph_kernel/model/op_node.cc | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2021-2022 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common/graph_kernel/model/op_node.h"
#include <math.h>
#include <algorithm>
#include <set>
#include <sstream>
#include <functional>
#include <numeric>
#include <utility>
#include "abstract/ops/primitive_infer_map.h"
#include "utils/hash_map.h"
#include "common/graph_kernel/model/node.h"
namespace mindspore::graphkernel::inner {
std::vector<int64_t> GetListInt(const ValuePtr &attr_value) {
bool is_int64 = true;
auto get_int_value = [&is_int64](const ValuePtr &value) -> int64_t {
if (value->isa<Int64Imm>()) {
return GetValue<int64_t>(value);
}
is_int64 = false;
return static_cast<int64_t>(GetValue<int>(value));
};
std::vector<int64_t> list_int;
const auto &vals = attr_value->cast<ValueSequencePtr>()->value();
(void)std::transform(vals.begin(), vals.end(), std::back_inserter(list_int), get_int_value);
if (!is_int64) {
MS_LOG(WARNING) << "Vector type should be 'int64_t' but got 'int'";
}
return list_int;
}
AbstractBasePtr InferWithAbstract(const PrimitivePtr &prim, const AbstractBasePtrList &abs_list) {
auto &frontend_infer_func = abstract::GetPrimitiveToEvalImplMap();
auto iter = frontend_infer_func.find(prim);
if (iter != frontend_infer_func.end()) {
MS_EXCEPTION_IF_NULL(iter->second.infer_shape_impl_);
return iter->second.infer_shape_impl_(nullptr, prim, abs_list);
}
auto &backend_infer_func = abstract::GetPrimitiveToBackendEvalImplMap();
auto iter2 = backend_infer_func.find(prim);
if (iter2 != backend_infer_func.end()) {
MS_EXCEPTION_IF_NULL(iter2->second.infer_shape_impl_);
return iter2->second.infer_shape_impl_(nullptr, prim, abs_list);
} else {
MS_LOG(EXCEPTION) << "The infer function of [" << prim->name() << "] is not defined.";
}
return nullptr;
}
NodeBase ExtractAbstract(const AbstractBasePtr &abs) {
NodeBase node;
if (abs->isa<abstract::AbstractTensor>()) {
auto shape_ptr = abs->BuildShape()->cast<abstract::ShapePtr>();
if (shape_ptr != nullptr) {
node.shape = shape_ptr->shape();
}
node.type = abs->cast<abstract::AbstractTensorPtr>()->element()->BuildType()->type_id();
} else { // abstract::AbstractScalar
// leave the node.shape empty
node.type = abs->BuildType()->type_id();
}
return node;
}
NodeBaseList PrimOp::InferShapeType(const NodePtrList &inputs, const DAttrs &attrs) {
auto op_primc_fns = ops::OpPrimCRegister::GetInstance().GetPrimCMap();
auto iter = op_primc_fns.find(op_);
if (iter == op_primc_fns.end()) {
MS_LOG(EXCEPTION) << "The PrimitiveC of [" << op_ << "] is not defined.";
}
auto primc = iter->second();
primc->SetAttrs(attrs);
AbstractBasePtrList inputs_abstract;
(void)std::transform(inputs.begin(), inputs.end(), std::back_inserter(inputs_abstract),
[](const NodePtr &node) -> AbstractBasePtr {
return std::make_shared<abstract::AbstractTensor>(TypeIdToType(node->type), node->shape);
});
RectifyAbstract(primc, &inputs_abstract);
AbstractBasePtr infer_result = InferWithAbstract(primc, inputs_abstract);
MS_EXCEPTION_IF_NULL(infer_result);
NodeBaseList result;
if (infer_result->isa<abstract::AbstractTuple>()) {
for (auto abs : infer_result->cast<abstract::AbstractTuplePtr>()->elements()) {
(void)result.emplace_back(ExtractAbstract(abs));
}
} else {
(void)result.emplace_back(ExtractAbstract(infer_result));
}
return result;
}
NodeBaseList PrimOp::Infer(const NodePtrList &inputs, const DAttrs &attrs) {
Check(inputs, attrs);
NodeBaseList result;
auto format = InferFormat(inputs, attrs);
auto shapes = InferShape(inputs, attrs);
auto types = InferType(inputs, attrs);
// use PrimitiveC's inference function when InferShape or InferType returns empty result.
if (shapes.empty() || types.empty()) {
result = InferShapeType(inputs, attrs);
if (!shapes.empty()) {
if (shapes.size() != result.size()) {
MS_LOG(EXCEPTION) << "The expected shapes num is " << result.size() << " but got " << shapes.size();
}
for (size_t i = 0; i < shapes.size(); i++) {
result[i].shape = shapes[i];
}
}
if (!types.empty()) {
if (types.size() != result.size()) {
MS_LOG(EXCEPTION) << "The expected types num is " << result.size() << " but got " << types.size();
}
for (size_t i = 0; i < types.size(); i++) {
result[i].type = types[i];
}
}
for (auto &r : result) {
r.format = format;
}
} else {
if (shapes.size() != types.size()) {
MS_LOG(EXCEPTION) << "The num of shapes and types should be equal. (" << shapes.size() << " vs " << types.size()
<< ")";
}
for (size_t i = 0; i < shapes.size(); i++) {
(void)result.emplace_back(NodeBase{shapes[i], types[i], format});
}
}
return result;
}
std::string PrimOp::ToString() const {
std::ostringstream oss;
oss << Node::ToString();
oss << " = " << this->op_ << "(";
for (size_t i = 0; i < inputs_.size(); i++) {
if (inputs_[i]->NodeType() == NType::Primitive) {
oss << inputs_[i]->Node::ToString();
} else {
oss << inputs_[i]->ToString();
}
if (i != inputs_.size() - 1) oss << ", ";
}
oss << ")";
std::ostringstream attr_oss;
bool has_attr = false;
std::set<std::string> black_list = {"IsFeatureMapInputList", "IsFeatureMapOutput", "output_names", "input_names"};
for (auto attr : attrs_) {
if (attr.second != nullptr && black_list.count(attr.first) == 0) {
if (has_attr) {
attr_oss << ", ";
} else {
has_attr = true;
}
attr_oss << attr.first << ": " << attr.second->ToString();
}
}
if (has_attr) {
oss << " // attr {" << attr_oss.str() << "}";
}
return oss.str();
}
template <typename TM, typename TD>
tensor::TensorPtr CalcByOperator(const NodePtrList &inputs, const std::string &op, TypeId tid) {
std::vector<TM> inputs_tm;
(void)std::transform(inputs.begin(), inputs.end(), std::back_inserter(inputs_tm), [](const NodePtr &i) {
return *static_cast<TM *>(std::static_pointer_cast<inner::ConstTensorNode>(i)->data()->data_c());
});
mindspore::HashMap<std::string, std::function<TM(const std::vector<TM> &)>> func_map = {
{"Add", [](const std::vector<TM> &n) { return n[0] + n[1]; }},
{"Sub", [](const std::vector<TM> &n) { return n[0] - n[1]; }},
{"Mul", [](const std::vector<TM> &n) { return n[0] * n[1]; }},
{"RealDiv", [](const std::vector<TM> &n) { return n[0] / n[1]; }},
{"Neg", [](const std::vector<TM> &n) { return TM(0) - n[0]; }},
{"Reciprocal", [](const std::vector<TM> &n) { return TM(1) / n[0]; }},
{"Log", [](const std::vector<TM> &n) { return log(n[0]); }},
{"Exp", [](const std::vector<TM> &n) { return exp(n[0]); }},
{"Abs", [](const std::vector<TM> &n) { return n[0] <= TM(0) ? (TM(0) - n[0]) : n[0]; }},
{"Sqrt", [](const std::vector<TM> &n) { return sqrt(n[0]); }},
{"Rsqrt", [](const std::vector<TM> &n) { return TM(1) / sqrt(n[0]); }},
};
if (func_map.find(op) == func_map.end()) {
return nullptr;
}
return std::make_shared<tensor::Tensor>(static_cast<TD>(func_map[op](inputs_tm)), TypeIdToType(tid));
}
NodePtr PrimOp::InferValue(const NodePtrList &inputs, const DAttrs &, const std::string &op) {
for (auto i : inputs) {
if (i->NodeType() != NType::Value) return nullptr;
}
TypeId output_type = this->type;
tensor::TensorPtr res = nullptr;
switch (static_cast<int>(output_type)) {
case TypeId::kNumberTypeUInt8: {
res = CalcByOperator<uint8_t, int64_t>(inputs, op, output_type);
break;
}
case TypeId::kNumberTypeInt8: {
res = CalcByOperator<int8_t, int64_t>(inputs, op, output_type);
break;
}
case TypeId::kNumberTypeInt16: {
res = CalcByOperator<int16_t, int64_t>(inputs, op, output_type);
break;
}
case TypeId::kNumberTypeInt32: {
res = CalcByOperator<int32_t, int64_t>(inputs, op, output_type);
break;
}
case TypeId::kNumberTypeInt64: {
res = CalcByOperator<int64_t, int64_t>(inputs, op, output_type);
break;
}
case TypeId::kNumberTypeUInt16: {
res = CalcByOperator<uint16_t, int64_t>(inputs, op, output_type);
break;
}
case TypeId::kNumberTypeUInt32: {
res = CalcByOperator<uint32_t, int64_t>(inputs, op, output_type);
break;
}
case TypeId::kNumberTypeUInt64: {
res = CalcByOperator<uint64_t, int64_t>(inputs, op, output_type);
break;
}
case TypeId::kNumberTypeFloat16: {
res = CalcByOperator<float16, double>(inputs, op, output_type);
break;
}
case TypeId::kNumberTypeFloat32: {
res = CalcByOperator<float, double>(inputs, op, output_type);
break;
}
case TypeId::kNumberTypeFloat64: {
res = CalcByOperator<double, double>(inputs, op, output_type);
break;
}
default:
return nullptr;
}
return res == nullptr ? nullptr : std::make_shared<ConstTensorNode>(res);
}
// default format shape to fractal_Nz format shape
DShape ToNz(const DShape &default_shape) {
constexpr size_t nz_size = 2;
constexpr auto align16 = 16;
auto len = default_shape.size();
DShape leading_shape;
DShape tail_shape;
if (default_shape.size() == 1 && default_shape[0] == 1) {
// # As shape (1,) can broadcast to any shape, it can be regarded as a special FractalNZ shape
return default_shape;
}
if (default_shape.size() > nz_size) {
(void)leading_shape.insert(leading_shape.end(), default_shape.begin(), default_shape.end() - SizeToLong(nz_size));
}
if (default_shape.size() == 1 || (default_shape.size() >= nz_size && default_shape[len - nz_size] == 1)) {
// (32) or (N, 1, 32) -> (N, 2, 1, 1, 16)
if (default_shape.back() % align16 != 0) {
MS_LOG(EXCEPTION) << "default_shape[-1] should be multiplies of 16, but got " << default_shape.back();
}
tail_shape = {default_shape.back() / align16, 1, 1, align16};
} else if (default_shape.size() >= nz_size || default_shape[1] == 1) {
// (N, 32, 1) -> (N, 1, 2, 16, 1)
if (default_shape[len - nz_size] % align16 != 0) {
MS_LOG(EXCEPTION) << "default_shape[-2] should be multiplies of 16, but got " << default_shape[len - nz_size];
}
tail_shape = {1, default_shape[0] / align16, align16, 1};
} else {
// (N, 32, 48) -> (N, 3, 2, 16, 16)
if (default_shape.back() % align16 != 0 || default_shape[len - nz_size] % align16 != 0) {
MS_LOG(EXCEPTION) << "default_shape[-1] and default_shape[-2]should be multiplies of 16, but got "
<< default_shape.back() << " " << default_shape[len - nz_size];
}
tail_shape = {default_shape[1] / align16, default_shape[0] / align16, align16, align16};
}
(void)leading_shape.insert(leading_shape.end(), tail_shape.begin(), tail_shape.end());
return leading_shape;
}
DShape BroadcastShape(const NodePtrList &inputs, bool to_nz = false) {
std::vector<std::vector<int64_t>> shapes;
for (auto &input : inputs) {
if (to_nz && input->format != kOpFormat_FRAC_NZ) {
(void)shapes.emplace_back(ToNz(input->shape));
} else {
(void)shapes.emplace_back(input->shape);
}
}
auto max_dim_input =
std::max_element(shapes.begin(), shapes.end(),
[](const std::vector<int64_t> &a, const std::vector<int64_t> &b) { return a.size() < b.size(); });
auto max_dim = max_dim_input->size();
std::vector<std::vector<int64_t>> align_shapes;
for (auto &s : shapes) {
std::vector<int64_t> cur(max_dim - s.size(), 1);
(void)cur.insert(cur.end(), s.begin(), s.end());
(void)align_shapes.emplace_back(cur);
}
std::vector<int64_t> output_shape(max_dim, 1);
for (size_t i = 0; i < max_dim; i++) {
for (auto &align_shape : align_shapes) {
if (align_shape[i] > 1) {
if (output_shape[i] == 1) {
output_shape[i] = align_shape[i];
}
if (output_shape[i] != align_shape[i]) {
MS_LOG(EXCEPTION) << "Shape broadcast failed: " << output_shape[i] << " vs " << align_shape[i];
}
}
}
}
return output_shape;
}
std::vector<DShape> ElemwiseOp::InferShape(const NodePtrList &inputs, const DAttrs &attrs) {
if (std::all_of(inputs.begin(), inputs.end(), [](const NodePtr &input) {
return input->format == kOpFormat_DEFAULT || input->format == kOpFormat_NHWC || input->format == kOpFormat_NCHW;
})) {
return PrimOp::InferShape(inputs, attrs);
}
if (std::all_of(inputs.begin(), inputs.end(), [](const NodePtr &input) {
return input->format == kOpFormat_DEFAULT || input->format == kOpFormat_NHWC ||
input->format == kOpFormat_NCHW || input->format == kOpFormat_FRAC_NZ;
})) {
return {BroadcastShape(inputs, true)};
}
std::string inputs_format;
for (const auto &input : inputs) {
static_cast<void>(inputs_format.append(" ").append(input->format));
}
MS_LOG(EXCEPTION) << "Unsupported inputs format: " << inputs_format;
}
DFormat ElemwiseOp::InferFormat(const NodePtrList &inputs, const DAttrs &) {
auto it = std::find_if(inputs.begin(), inputs.end(), [](const NodePtr &i) { return i->format != kOpFormat_DEFAULT; });
return it == inputs.end() ? kOpFormat_DEFAULT : (*it)->format;
}
DFormat TransposeOp::InferFormat(const NodePtrList &inputs, const DAttrs &attrs) {
// only support NCHW/NHWC now
if (inputs[0]->shape.size() != 4) return kOpFormat_DEFAULT;
CHECK_ATTR(attrs, "perm");
auto perm = GetListInt(attrs.find("perm")->second);
const auto &ori_format = inputs[0]->format;
if (ori_format == kOpFormat_DEFAULT || ori_format == kOpFormat_NCHW) {
std::vector<int64_t> nchw2nhwc = {0, 2, 3, 1};
if (perm == nchw2nhwc) return kOpFormat_NHWC;
} else if (ori_format == kOpFormat_NHWC) {
std::vector<int64_t> nhwc2nchw = {0, 3, 1, 2};
if (perm == nhwc2nchw) return kOpFormat_DEFAULT;
}
return kOpFormat_DEFAULT;
}
std::vector<DShape> PadAkgOp::InferShape(const NodePtrList &inputs, const DAttrs &attrs) {
std::vector<int64_t> shape0 = inputs[0]->shape;
size_t n = shape0.size();
CHECK_ATTR(attrs, "head");
CHECK_ATTR(attrs, "tail");
std::vector<int64_t> pad_before = GetListInt(attrs.find("head")->second);
std::vector<int64_t> pad_after = GetListInt(attrs.find("tail")->second);
if (pad_before.size() != n || pad_after.size() != n) {
MS_LOG(EXCEPTION) << "Input dimension and pad mismatch: " << n << " vs " << pad_before.size() << " vs "
<< pad_after.size();
}
std::vector<int64_t> output;
for (size_t i = 0; i < n; i++) {
(void)output.emplace_back(shape0[i] + pad_before[i] + pad_after[i]);
}
return {output};
}
std::vector<DShape> UnPadAkgOp::InferShape(const NodePtrList &inputs, const DAttrs &attrs) {
std::vector<int64_t> shape0 = inputs[0]->shape;
size_t n = shape0.size();
CHECK_ATTR(attrs, "tail");
std::vector<int64_t> unpad_after = GetListInt(attrs.find("tail")->second);
if (unpad_after.size() != n) {
MS_LOG(EXCEPTION) << "Input dimension and pad mismatch: " << n << " vs " << unpad_after.size();
}
std::vector<int64_t> output;
for (size_t i = 0; i < n; i++) {
(void)output.emplace_back(shape0[i] - unpad_after[i]);
}
return {output};
}
void ComplexOp::Check(const NodePtrList &inputs, const DAttrs &) {
if (inputs[0]->type != TypeId::kNumberTypeFloat32) {
MS_LOG(EXCEPTION) << "Complex's input[0] should be float32, but got " << TypeIdToString(inputs[0]->type, true);
}
if (inputs[0]->type != inputs[1]->type) {
MS_LOG(EXCEPTION) << "Complex's input[0] and inputs[1]'s type mismatch: " << TypeIdToString(inputs[0]->type, true)
<< " vs " << TypeIdToString(inputs[1]->type, true);
}
}
std::vector<DShape> StandardNormalOp::InferShape(const NodePtrList &, const DAttrs &attrs) {
CHECK_ATTR(attrs, "shape");
return {GetListInt(attrs.find("shape")->second)};
}
} // namespace mindspore::graphkernel::inner
| 40.16 | 121 | 0.621104 | [
"shape",
"vector",
"model",
"transform"
] |
8f488974c767967ed8aa9f43427e5189744f2cfd | 2,894 | cpp | C++ | source/index.cpp | YXTR/minisql | ac65652961a6681c595c6336e8a6d81340424edf | [
"MIT"
] | null | null | null | source/index.cpp | YXTR/minisql | ac65652961a6681c595c6336e8a6d81340424edf | [
"MIT"
] | 1 | 2018-06-19T14:35:33.000Z | 2018-06-19T14:35:33.000Z | source/index.cpp | YXTR/minisql | ac65652961a6681c595c6336e8a6d81340424edf | [
"MIT"
] | 3 | 2018-05-30T11:32:52.000Z | 2019-10-29T02:26:22.000Z | #include "index.h"
#include "buffer.h"
#include "OperationInput.h"
#include "BPTree.h"
#include <string>
#include <vector>
#include <map>
IndexManager::IndexManager(const Table& table)
{
//catalogManager catalog;
//if(catalog.isTableExist(Table.table_name))
//{
//vector<std::string> indexs = catalog.nameOfIndex(table_name);
//vector<std::string> types = catalog.nameOfType(table_name);
const string* indexs = table.all_index_name;
const ColumnType* types = table.column_type;
const int* sizes = table.string_length;
for (int i = 0; i < table.column_num; i++)
{
if (!indexs[i].empty())
{
int size = sizes[i];
if (size == 0)
{
size = 4;
}
createIndex(indexs[i], types[i], size);
}
}
//}
}
IndexManager::~IndexManager()
{
for (auto& i_Int : indexIntMap)
{
if(i_Int.second)
{
i_Int.second -> writeBack();
delete i_Int.second;
}
}
for (auto& i_Float : indexFloatMap)
{
if(i_Float.second)
{
i_Float.second->writeBack();
delete i_Float.second;
}
}
for (auto& i_String : indexStringMap)
{
if(i_String.second)
{
i_String.second->writeBack();
delete i_String.second;
}
}
}
void IndexManager::createIndex(const std::string& file_path, COLUMNTYPE type, int string_len)
{
const int degree = getBestDegree(type, string_len);
//const int degree = 32;
if(type == INT)
{
BPTree<int> *BPT = new BPTree<int>(file_path, degree);
indexIntMap.insert(intMap::value_type(file_path, BPT));
}
else if(type == FLOAT)
{
BPTree<float> *BPT = new BPTree<float>(file_path, degree);
indexFloatMap.insert(floatMap::value_type(file_path, BPT));
}
else
{
BPTree<std::string> *BPT = new BPTree<std::string>(file_path, degree);
indexStringMap.insert(stringMap::value_type(file_path, BPT));
}
return;
}
void IndexManager::dropIndex(const std::string& file_path, COLUMNTYPE type)
{
if(type == INT)
{
auto i_Int = indexIntMap.find(file_path);
if(i_Int == indexIntMap.end())
{
return;
}
else
{
delete i_Int -> second;
indexIntMap.erase(i_Int);
}
}
else if(type == FLOAT)
{
auto i_Float = indexFloatMap.find(file_path);
if(i_Float == indexFloatMap.end())
{
return;
}
else
{
delete i_Float -> second;
indexFloatMap.erase(i_Float);
}
}
else
{
auto i_String = indexStringMap.find(file_path);
if(i_String == indexStringMap.end())
{
return;
}
else
{
delete i_String -> second;
indexStringMap.erase(i_String);
}
}
return;
}
int IndexManager::getBestDegree(COLUMNTYPE type, int string_len)
{
int degree = (BLOCK_LEN) / (string_len + sizeof(int) + sizeof(int));
if(degree % 2 == 0) degree--;
return degree;
}
| 21.437037 | 94 | 0.610228 | [
"vector"
] |
8f4ed3ee14fc316282c7691038b2c3c73c24ea13 | 3,394 | cpp | C++ | src/lava_lib/reader_bgeo/test/test_packed_disk.cpp | cinepost/Falcor | f70bd1d97c064d6f91a017d4409aa2037fd6903a | [
"BSD-3-Clause"
] | 7 | 2018-09-25T23:45:52.000Z | 2021-07-07T04:08:01.000Z | src/lava_lib/reader_bgeo/test/test_packed_disk.cpp | cinepost/Falcor | f70bd1d97c064d6f91a017d4409aa2037fd6903a | [
"BSD-3-Clause"
] | 2 | 2021-03-02T10:16:06.000Z | 2021-08-13T10:10:21.000Z | src/lava_lib/reader_bgeo/test/test_packed_disk.cpp | cinepost/Lava | f70bd1d97c064d6f91a017d4409aa2037fd6903a | [
"BSD-3-Clause"
] | 3 | 2020-06-07T05:47:48.000Z | 2020-10-03T12:34:54.000Z | /*
* Copyright 2018 Laika, LLC. Authored by Peter Stuart
*
* Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
* http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
* http://opensource.org/licenses/MIT>, at your option. This file may not be
* copied, modified, or distributed except according to those terms.
*/
#include <hboost/test/unit_test.hpp>
#include "bgeo/parser/StorageTraits.h"
#include "bgeo/Bgeo.h"
#include "bgeo/PackedDisk.h"
namespace ika
{
namespace bgeo
{
namespace test_packed_disk
{
class PackedDiskFixture
{
public:
PackedDiskFixture()
: bgeo("geo/packed_disk.bgeo")
{
}
protected:
Bgeo bgeo;
};
namespace
{
float expected_P[] = {
0, 0, 0
};
double expected_xform[] = {
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
};
} // namespace anonymous
HBOOST_FIXTURE_TEST_SUITE(test_packed_disk, PackedDiskFixture)
HBOOST_AUTO_TEST_CASE(test_packed_disk_counts)
{
HBOOST_CHECK_EQUAL(1, bgeo.getPointCount());
HBOOST_CHECK_EQUAL(1, bgeo.getTotalVertexCount());
HBOOST_CHECK_EQUAL(1, bgeo.getPrimitiveCount());
HBOOST_CHECK_EQUAL(1, bgeo.getPointAttributeCount());
HBOOST_CHECK_EQUAL(1, bgeo.getPrimitiveAttributeCount());
}
HBOOST_AUTO_TEST_CASE(test_packed_disk_P)
{
std::vector<float> P;
bgeo.getP(P);
HBOOST_CHECK_EQUAL_COLLECTIONS(&expected_P[0], &expected_P[3], P.begin(), P.end());
}
HBOOST_AUTO_TEST_CASE(test_packed_disk_path)
{
auto attribute = bgeo.getPrimitiveAttributeByName("path");
HBOOST_CHECK(attribute);
std::vector<std::string> strings;
attribute->getStrings(strings);
HBOOST_CHECK_EQUAL(1, strings.size());
HBOOST_CHECK_EQUAL("sphere.bgeo", strings[0]);
HBOOST_CHECK_EQUAL(bgeo::parser::storage::Int32,
attribute->getFundamentalType());
std::vector<int32> indices;
attribute->getData(indices);
HBOOST_CHECK_EQUAL(1, indices.size());
HBOOST_CHECK_EQUAL(0, indices[0]);
}
HBOOST_AUTO_TEST_CASE(test_packed_disk_one_packed_primitive)
{
auto primitive = bgeo.getPrimitive(0);
HBOOST_CHECK(primitive);
HBOOST_CHECK(primitive->isType<PackedDisk>());
}
HBOOST_AUTO_TEST_CASE(test_packed_disk_packed_parameters)
{
auto primitive = bgeo.getPrimitive(0);
assert(primitive);
auto disk = primitive->cast<PackedDisk>();
assert(disk);
// translate
double translate[3] = { -1 };
disk->getTranslate(translate);
HBOOST_CHECK_CLOSE(expected_P[0], translate[0], 0.0001);
HBOOST_CHECK_CLOSE(expected_P[1], translate[1], 0.0001);
HBOOST_CHECK_CLOSE(expected_P[2], translate[2], 0.0001);
// pivot
double pivot[3] = { -1 };
disk->getPivot(pivot);
double expected_pivot[3] = {
0, 0, 0
};
HBOOST_CHECK_EQUAL_COLLECTIONS(&expected_pivot[0], &expected_pivot[3],
&pivot[0], &pivot[3]);
// extra transform
double xform[16] = { -1 };
disk->getExtraTransform(xform);
HBOOST_CHECK_EQUAL_COLLECTIONS(&expected_xform[0], &expected_xform[16],
&xform[0], &xform[16]);
// no bounding box
HBOOST_CHECK(!disk->hasBoundingBox());
// filename
HBOOST_CHECK_EQUAL("sphere.bgeo", disk->getFilename());
}
HBOOST_AUTO_TEST_SUITE_END()
} // namespace test_packed_disk
} // namespace bgeo
} // namespace ika
| 24.955882 | 87 | 0.680318 | [
"vector",
"transform"
] |
8f5d8516b2de4a63b1adc990f8789286a943c540 | 11,522 | cpp | C++ | core/tests/test_yaml_serialization.cpp | GameDevTecnico/cubos | 51f89c9f3afc8afe502d167dadecab7dfe5b1c7b | [
"MIT"
] | 2 | 2021-09-28T14:13:27.000Z | 2022-03-26T11:36:48.000Z | core/tests/test_yaml_serialization.cpp | GameDevTecnico/cubos | 51f89c9f3afc8afe502d167dadecab7dfe5b1c7b | [
"MIT"
] | 72 | 2021-09-29T08:55:26.000Z | 2022-03-29T21:21:00.000Z | core/tests/test_yaml_serialization.cpp | GameDevTecnico/cubos | 51f89c9f3afc8afe502d167dadecab7dfe5b1c7b | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <cubos/core/memory/buffer_stream.hpp>
#include <cubos/core/data/yaml_serializer.hpp>
#include <cubos/core/data/serialization_map.hpp>
using namespace cubos::core::memory;
using namespace cubos::core::data;
struct Human
{
std::string name;
int age;
double weight;
bool dead;
std::vector<Human*> children;
};
namespace cubos::core::data
{
static void serialize(Serializer& s, const Human& human, const char* name)
{
s.beginObject(name);
s.write(human.name, "name");
s.write(human.age, "age");
s.write(human.weight, "weight");
s.write(human.dead, "dead");
s.beginArray(human.children.size(), "children");
for (auto& child : human.children)
s.write(*child, "child");
s.endArray();
s.endObject();
}
static void serialize(Serializer& s, const Human& human, SerializationMap<Human*, size_t>* map, const char* name)
{
s.beginObject(name);
s.write(human.name, "name");
s.write(human.age, "age");
s.write(human.weight, "weight");
s.write(human.dead, "dead");
s.beginArray(human.children.size(), "children");
for (auto& child : human.children)
s.write(static_cast<uint64_t>(map->getId(child)), "child");
s.endArray();
s.endObject();
}
} // namespace cubos::core::data
TEST(Cubos_Memory_YAML_Serialization, Serialize_Primitives)
{
char buf[2048];
auto stream = BufferStream(buf, sizeof(buf));
{
auto serializer = YAMLSerializer(stream);
serializer.write(static_cast<uint8_t>(1), "named_uint8");
serializer.write(12, "named_integer");
serializer.write(0.5f, "named_float");
serializer.write(6.5, "named_double");
serializer.write(true, "named_bool");
serializer.write("string", "named_string");
serializer.write("\n\t\r\b", "named_string_with_special_chars");
serializer.write("anonymous string", nullptr);
}
stream.put('\0');
const char* expected = "---\n"
"named_uint8: 1\n"
"named_integer: 12\n"
"named_float: 0.5\n"
"named_double: 6.5\n"
"named_bool: true\n"
"named_string: string\n"
"named_string_with_special_chars: \"\\n\\t\\r\\b\"\n"
"anonymous: anonymous string\n"
"...\n";
EXPECT_STREQ(expected, buf);
}
TEST(Cubos_Memory_YAML_Serialization, Serialize_Array)
{
char buf[2048];
auto stream = BufferStream(buf, sizeof(buf));
{
auto serializer = (Serializer*)new YAMLSerializer(stream);
std::vector<int64_t> vec = {1, 5, 8, 3};
std::vector<std::vector<std::vector<int>>> vec3d = {{{1, 2}, {3, 4, 5}}, {{6, 7}, {8}}};
const char* strs[] = {"one", "two", "three"};
serializer->write(vec, "vector");
serializer->beginArray(3, "strings");
for (size_t i = 0; i < 3; ++i)
serializer->write(strs[i], nullptr);
serializer->endArray();
serializer->write(vec3d, "vector3d");
delete serializer;
}
stream.put('\0');
const char* expected = "---\n"
"vector:\n"
" - 1\n"
" - 5\n"
" - 8\n"
" - 3\n"
"strings:\n"
" - one\n"
" - two\n"
" - three\n"
"vector3d:\n"
" -\n"
" -\n"
" - 1\n"
" - 2\n"
" -\n"
" - 3\n"
" - 4\n"
" - 5\n"
" -\n"
" -\n"
" - 6\n"
" - 7\n"
" -\n"
" - 8\n"
"...\n";
EXPECT_STREQ(expected, buf);
}
TEST(Cubos_Memory_YAML_Serialization, Serialize_Dictionary)
{
char buf[2048];
auto stream = BufferStream(buf, sizeof(buf));
{
auto serializer = (Serializer*)new YAMLSerializer(stream);
const char* strs[] = {"one", "two", "three"};
serializer->beginDictionary(3, "strings");
for (size_t i = 0; i < 3; ++i)
{
serializer->write(static_cast<uint64_t>(i), nullptr);
serializer->write(strs[i], nullptr);
}
serializer->endDictionary();
delete serializer;
}
stream.put('\0');
const char* expected = "---\n"
"strings:\n"
" 0: one\n"
" 1: two\n"
" 2: three\n"
"...\n";
EXPECT_STREQ(expected, buf);
}
TEST(Cubos_Memory_YAML_Serialization, Serialize_GLM)
{
char buf[2048];
auto stream = BufferStream(buf, sizeof(buf));
{
auto serializer = (Serializer*)new YAMLSerializer(stream);
serializer->write(glm::vec2(1, 2), "fvec2");
serializer->write(glm::vec3(1, 2, 3), "fvec3");
serializer->write(glm::vec4(1, 2, 3, 4), "fvec4");
serializer->write(glm::ivec2(1, 2), "ivec2");
serializer->write(glm::ivec3(1, 2, 3), "ivec3");
serializer->write(glm::ivec4(1, 2, 3, 4), "ivec4");
serializer->write(glm::uvec2(1, 2), "uvec2");
serializer->write(glm::uvec3(1, 2, 3), "uvec3");
serializer->write(glm::uvec4(1, 2, 3, 4), "uvec4");
serializer->write(glm::quat(1, 2, 3, 4), "quat");
delete serializer;
}
stream.put('\0');
const char* expected = "---\n"
"fvec2:\n"
" x: 1\n"
" y: 2\n"
"fvec3:\n"
" x: 1\n"
" y: 2\n"
" z: 3\n"
"fvec4:\n"
" x: 1\n"
" y: 2\n"
" z: 3\n"
" w: 4\n"
"ivec2:\n"
" x: 1\n"
" y: 2\n"
"ivec3:\n"
" x: 1\n"
" y: 2\n"
" z: 3\n"
"ivec4:\n"
" x: 1\n"
" y: 2\n"
" z: 3\n"
" w: 4\n"
"uvec2:\n"
" x: 1\n"
" y: 2\n"
"uvec3:\n"
" x: 1\n"
" y: 2\n"
" z: 3\n"
"uvec4:\n"
" x: 1\n"
" y: 2\n"
" z: 3\n"
" w: 4\n"
"quat:\n"
" w: 1\n"
" x: 2\n"
" y: 3\n"
" z: 4\n"
"...\n";
EXPECT_STREQ(expected, buf);
}
TEST(Cubos_Memory_YAML_Serialization, Serialize_Custom_Serializable)
{
using namespace cubos::core::memory;
char buf[4096];
auto stream = BufferStream(buf, sizeof(buf));
{
std::vector<Human> humans = {{"José", 90, 79, true, {}},
{"Joana", 70, 60, false, {}},
{"Josefina", 50, 100, false, {}},
{"João", 30, 80, true, {}},
{"Joaquim", 23, 70, false, {}}};
humans[0].children.push_back(&humans[1]);
humans[1].children.push_back(&humans[2]);
humans[2].children.push_back(&humans[3]);
humans[2].children.push_back(&humans[4]);
auto map = SerializationMap<Human*, size_t>();
for (size_t i = 0; i < humans.size(); ++i)
map.add(&humans[i], i);
auto serializer = (Serializer*)new YAMLSerializer(stream);
serializer->write(humans[0], "trivially_serializable");
serializer->beginDictionary(humans.size(), "context_serializable");
for (size_t i = 0; i < humans.size(); ++i)
{
serializer->write(static_cast<uint64_t>(i), nullptr);
serializer->write(humans[i], &map, nullptr);
}
serializer->endDictionary();
delete serializer;
}
stream.put('\0');
EXPECT_STREQ("---\n"
"trivially_serializable:\n"
" name: José\n"
" age: 90\n"
" weight: 79\n"
" dead: true\n"
" children:\n"
" - name: Joana\n"
" age: 70\n"
" weight: 60\n"
" dead: false\n"
" children:\n"
" - name: Josefina\n"
" age: 50\n"
" weight: 100\n"
" dead: false\n"
" children:\n"
" - name: João\n"
" age: 30\n"
" weight: 80\n"
" dead: true\n"
" children:\n"
" []\n"
" - name: Joaquim\n"
" age: 23\n"
" weight: 70\n"
" dead: false\n"
" children:\n"
" []\n"
"context_serializable:\n"
" 0:\n"
" name: José\n"
" age: 90\n"
" weight: 79\n"
" dead: true\n"
" children:\n"
" - 1\n"
" 1:\n"
" name: Joana\n"
" age: 70\n"
" weight: 60\n"
" dead: false\n"
" children:\n"
" - 2\n"
" 2:\n"
" name: Josefina\n"
" age: 50\n"
" weight: 100\n"
" dead: false\n"
" children:\n"
" - 3\n"
" - 4\n"
" 3:\n"
" name: João\n"
" age: 30\n"
" weight: 80\n"
" dead: true\n"
" children:\n"
" []\n"
" 4:\n"
" name: Joaquim\n"
" age: 23\n"
" weight: 70\n"
" dead: false\n"
" children:\n"
" []\n"
"...\n",
buf);
}
| 35.021277 | 117 | 0.373199 | [
"vector"
] |
8f6109277ae3e11a81dbfc7059a88fb8d17a27fa | 11,537 | cpp | C++ | Source/SystemQOR/MSWindows/WinQAPI/src/User32/WinQMessages.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 9 | 2016-05-27T01:00:39.000Z | 2021-04-01T08:54:46.000Z | Source/SystemQOR/MSWindows/WinQAPI/src/User32/WinQMessages.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 1 | 2016-03-03T22:54:08.000Z | 2016-03-03T22:54:08.000Z | Source/SystemQOR/MSWindows/WinQAPI/src/User32/WinQMessages.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 4 | 2016-05-27T01:00:43.000Z | 2018-08-19T08:47:49.000Z | //WinQMessages.cpp
// Copyright Querysoft Limited 2013
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//Message and Message Queue functions
#include "WinQAPI/User32.h"
#include "../Source/SystemQOR/MSWindows/WinQAPI/include/ReturnCheck.h"
//--------------------------------------------------------------------------------
namespace nsWinQAPI
{
//--------------------------------------------------------------------------------
long CUser32::BroadcastSystemMessage( DWORD dwFlags, LPDWORD lpdwRecipients, UINT uiMessage, WPARAM wParam, LPARAM lParam )
{
_WINQ_FCONTEXT( "CUser32::BroadcastSystemMessage" );
CCheckReturn< long, CTCheckNotLess< long, 1 > >::TType lResult;
_WINQ_USESAPI( BroadcastSystemMessage );
lResult = Call< long, DWORD, LPDWORD, UINT, WPARAM, LPARAM >( pFunc, dwFlags, lpdwRecipients, uiMessage, wParam, lParam );
return lResult;
}
//--------------------------------------------------------------------------------
long CUser32::BroadcastSystemMessageExA( DWORD dwFlags, LPDWORD lpdwRecipients, UINT uiMessage, WPARAM wParam, LPARAM lParam, ::PBSMINFO pBSMInfo )
{
_WINQ_FCONTEXT( "CUser32::BroadcastSystemMessageExA" );
CCheckReturn< long, CTCheckNotLess< long, 1 > >::TType lResult;
_WINQ_USESAPI( BroadcastSystemMessageExA );
lResult = Call< long, DWORD, LPDWORD, UINT, WPARAM, LPARAM, PBSMINFO >( pFunc, dwFlags, lpdwRecipients, uiMessage, wParam, lParam, pBSMInfo );
return lResult;
}
//--------------------------------------------------------------------------------
long CUser32::BroadcastSystemMessageExW( DWORD dwFlags, LPDWORD lpdwRecipients, UINT uiMessage, WPARAM wParam, LPARAM lParam, ::PBSMINFO pBSMInfo )
{
_WINQ_FCONTEXT( "CUser32::BroadcastSystemMessageExW" );
CCheckReturn< long, CTCheckNotLess< long, 1 > >::TType lResult;
_WINQ_USESAPI( BroadcastSystemMessageExW );
lResult = Call< long, DWORD, LPDWORD, UINT, WPARAM, LPARAM, PBSMINFO >( pFunc, dwFlags, lpdwRecipients, uiMessage, wParam, lParam, pBSMInfo );
return lResult;
}
//--------------------------------------------------------------------------------
LRESULT CUser32::DispatchMessage( const MSG* lpmsg )
{
_WINQ_FCONTEXT( "CUser32::DispatchMessage" );
_WINQ_USESAPI( DispatchMessage );
return Call< LRESULT, const MSG* >( pFunc, lpmsg );
}
//--------------------------------------------------------------------------------
BOOL CUser32::GetInputState(void)
{
_WINQ_FCONTEXT( "CUser32::GetInputState" );
_WINQ_USESAPI( GetInputState );
return Call< BOOL >( pFunc );
}
//--------------------------------------------------------------------------------
BOOL CUser32::GetMessage( LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax )
{
_WINQ_FCONTEXT( "CUser32::GetMessage" );
CCheckReturn< BOOL, CTCheckFailureValue< BOOL, -1 > >::TType bResult;
_WINQ_USESAPI( GetMessage );
bResult = Call< BOOL, LPMSG, HWND, UINT, UINT >( pFunc, lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax );
return bResult;
}
//--------------------------------------------------------------------------------
LPARAM CUser32::GetMessageExtraInfo(void)
{
_WINQ_FCONTEXT( "CUser32::GetMessageExtraInfo" );
_WINQ_USESAPI( GetMessageExtraInfo );
return Call< LPARAM >( pFunc );
}
//--------------------------------------------------------------------------------
DWORD CUser32::GetMessagePos(void)
{
_WINQ_FCONTEXT( "CUser32::GetMessagePos" );
_WINQ_USESAPI( GetMessagePos );
return Call< DWORD >( pFunc );
}
//--------------------------------------------------------------------------------
LONG CUser32::GetMessageTime(void)
{
_WINQ_FCONTEXT( "CUser32::GetMessageTime" );
_WINQ_USESAPI( GetMessageTime );
return Call< LONG >( pFunc );
}
//--------------------------------------------------------------------------------
DWORD CUser32::GetQueueStatus( UINT flags )
{
_WINQ_FCONTEXT( "CUser32::GetQueueStatus" );
_WINQ_USESAPI( GetQueueStatus );
return Call< DWORD, UINT >( pFunc, flags );
}
//--------------------------------------------------------------------------------
BOOL CUser32::InSendMessage(void)
{
_WINQ_FCONTEXT( "CUser32::InSendMessage" );
_WINQ_USESAPI( InSendMessage );
return Call< BOOL >( pFunc );
}
//--------------------------------------------------------------------------------
DWORD CUser32::InSendMessageEx( LPVOID lpReserved )
{
_WINQ_FCONTEXT( "CUser32::InSendMessageEx" );
_WINQ_USESAPI( InSendMessageEx );
return Call< DWORD, LPVOID >( pFunc, lpReserved );
}
//--------------------------------------------------------------------------------
BOOL CUser32::PeekMessage( LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg )
{
_WINQ_FCONTEXT( "CUser32::PeekMessage" );
_WINQ_USESAPI( PeekMessage );
return Call< BOOL, LPMSG, HWND, UINT, UINT, UINT >( pFunc, lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg );
}
//--------------------------------------------------------------------------------
BOOL CUser32::PostMessage( HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam )
{
_WINQ_FCONTEXT( "CUser32::PostMessage" );
CCheckReturn< BOOL, CBoolCheck< > >::TType bResult;
_WINQ_USESAPI( PostMessage );
bResult = Call< BOOL, HWND, UINT, WPARAM, LPARAM >( pFunc, hWnd, Msg, wParam, lParam );
return bResult;
}
//--------------------------------------------------------------------------------
void CUser32::PostQuitMessage( int nExitCode )
{
_WINQ_FCONTEXT( "CUser32::PostQuitMessage" );
_WINQ_USESAPI( PostQuitMessage );
voidCall< int >( pFunc, nExitCode );
}
//--------------------------------------------------------------------------------
BOOL CUser32::PostThreadMessage( DWORD idThread, UINT Msg, WPARAM wParam, LPARAM lParam )
{
_WINQ_FCONTEXT( "CUser32::PostThreadMessage" );
CCheckReturn< BOOL, CBoolCheck< > >::TType bResult;
_WINQ_USESAPI( PostThreadMessage );
bResult = Call< BOOL, DWORD, UINT, WPARAM, LPARAM >( pFunc, idThread, Msg, wParam, lParam );
return bResult;
}
//--------------------------------------------------------------------------------
UINT CUser32::RegisterWindowMessage( LPCTSTR lpString )
{
_WINQ_FCONTEXT( "CUser32::RegisterWindowMessage" );
CCheckReturn< UINT, CCheckNonZero< UINT > >::TType uiResult;
_WINQ_USESAPI( RegisterWindowMessage );
uiResult = Call< UINT, LPCTSTR >( pFunc, lpString );
return uiResult;
}
//--------------------------------------------------------------------------------
BOOL CUser32::ReplyMessage( LRESULT lResult )
{
_WINQ_FCONTEXT( "CUser32::ReplyMessage" );
_WINQ_USESAPI( ReplyMessage );
return Call< BOOL, LRESULT >( pFunc, lResult );
}
//--------------------------------------------------------------------------------
BOOL CUser32::SendMessageCallbackA( HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam, ::SENDASYNCPROC lpCallBack, ULONG_PTR dwData )
{
_WINQ_FCONTEXT( "CUser32::SendMessageCallbackA" );
CCheckReturn< BOOL, CBoolCheck< > >::TType bResult;
_WINQ_USESAPI( SendMessageCallbackA );
bResult = Call< BOOL, HWND, UINT, WPARAM, LPARAM, ::SENDASYNCPROC, ULONG_PTR >( pFunc, hWnd, Msg, wParam, lParam, lpCallBack, dwData );
return bResult;
}
//--------------------------------------------------------------------------------
BOOL CUser32::SendMessageCallbackW( HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam, ::SENDASYNCPROC lpCallBack, ULONG_PTR dwData )
{
_WINQ_FCONTEXT( "CUser32::SendMessageCallbackW" );
CCheckReturn< BOOL, CBoolCheck< > >::TType bResult;
_WINQ_USESAPI( SendMessageCallbackW );
bResult = Call< BOOL, HWND, UINT, WPARAM, LPARAM, ::SENDASYNCPROC, ULONG_PTR >( pFunc, hWnd, Msg, wParam, lParam, lpCallBack, dwData );
return bResult;
}
//--------------------------------------------------------------------------------
LRESULT CUser32::SendMessageTimeout( HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam, UINT fuFlags, UINT uTimeout, PDWORD_PTR lpdwResult )
{
_WINQ_FCONTEXT( "CUser32::SendMessageTimeout" );
LRESULT Result = 0;
_WINQ_USESAPI( SendMessageTimeout );
Result = Call< LRESULT, HWND, UINT, WPARAM, LPARAM, UINT, UINT, PDWORD_PTR >( pFunc, hWnd, Msg, wParam, lParam, fuFlags, uTimeout, lpdwResult );
if( Result == 0 )
{
DWORD dwError = CKernel32::GetLastError();
if( dwError == ERROR_TIMEOUT )
{
__WINQAPI_WARNING(( RESULT_INDICATES_FAILURE_OR_PENDING, _T( "SendMessageTimeout" ), 0 ));
}
else
{
__WINQAPI_CONT_ERROR(( GENERAL_API_ERROR, _T( "SendMessageTimeout" ), 0 ));
}
}
return Result;
}
//--------------------------------------------------------------------------------
LRESULT CUser32::SendMessage( HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam )
{
_WINQ_FCONTEXT( "CUser32::SendMessage" );
_WINQ_USESAPI( SendMessage );
return Call< LRESULT, HWND, UINT, WPARAM, LPARAM >( pFunc, hWnd, Msg, wParam, lParam );
}
//--------------------------------------------------------------------------------
BOOL CUser32::SendNotifyMessage( HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam )
{
_WINQ_FCONTEXT( "CUser32::SendNotifyMessage" );
CCheckReturn< BOOL, CBoolCheck< > >::TType bResult;
_WINQ_USESAPI( SendNotifyMessage );
bResult = Call< BOOL, HWND, UINT, WPARAM, LPARAM >( pFunc, hWnd, Msg, wParam, lParam );
return bResult;
}
//--------------------------------------------------------------------------------
LPARAM CUser32::SetMessageExtraInfo( LPARAM lParam )
{
_WINQ_FCONTEXT( "CUser32::SetMessageExtraInfo" );
_WINQ_USESAPI( SetMessageExtraInfo );
return Call< LPARAM, LPARAM >( pFunc, lParam );
}
//--------------------------------------------------------------------------------
BOOL CUser32::TranslateMessage( const MSG* lpMsg )
{
_WINQ_FCONTEXT( "CUser32::TranslateMessage" );
BOOL bResult = 0;
_WINQ_USESAPI( TranslateMessage );
bResult = Call< BOOL, const MSG* >( pFunc, lpMsg );
return bResult;
}
//--------------------------------------------------------------------------------
BOOL CUser32::WaitMessage(void)
{
_WINQ_FCONTEXT( "CUser32::WaitMessage" );
CCheckReturn< BOOL, CBoolCheck< > >::TType bResult;
_WINQ_USESAPI( WaitMessage );
bResult = Call< BOOL >( pFunc );
return bResult;
}
}//nsWinQAPI
| 40.766784 | 148 | 0.587588 | [
"object"
] |
8f61264b2715893db08351f2bd16a5dded1326ba | 1,359 | hpp | C++ | arbiter/util/json.hpp | mccarthyryanc/arbiter | b0c0ea03394604ac3e6854c80dc38ded6d988057 | [
"MIT"
] | 17 | 2015-12-18T19:16:08.000Z | 2022-03-01T05:22:33.000Z | arbiter/util/json.hpp | mccarthyryanc/arbiter | b0c0ea03394604ac3e6854c80dc38ded6d988057 | [
"MIT"
] | 18 | 2016-09-04T14:17:47.000Z | 2021-07-09T15:06:44.000Z | arbiter/util/json.hpp | mccarthyryanc/arbiter | b0c0ea03394604ac3e6854c80dc38ded6d988057 | [
"MIT"
] | 15 | 2015-12-21T17:10:43.000Z | 2021-12-14T22:31:37.000Z | #pragma once
#ifndef ARBITER_IS_AMALGAMATION
#include <arbiter/third/json/json.hpp>
#endif
#ifdef ARBITER_CUSTOM_NAMESPACE
namespace ARBITER_CUSTOM_NAMESPACE
{
#endif
namespace arbiter
{
using json = nlohmann::json;
// Work around:
// https://github.com/nlohmann/json/issues/709
// https://github.com/google/googletest/pull/1186
inline void PrintTo(const json& j, std::ostream* os) { *os << j.dump(); }
// Merge B into A, without overwriting any keys from A.
inline json merge(const json& a, const json& b)
{
json out(a);
if (out.is_null()) out = json::object();
if (!b.is_null())
{
if (b.is_object())
{
for (const auto& p : b.items())
{
// If A doesn't have this key, then set it to B's value.
// If A has the key but it's an object, then recursively
// merge.
// Otherwise A already has a value here that we won't
// overwrite.
const std::string& key(p.key());
const json& val(p.value());
if (!out.count(key)) out[key] = val;
else if (out[key].is_object()) merge(out[key], val);
}
}
else
{
out = b;
}
}
return out;
}
} // namespace arbiter
#ifdef ARBITER_CUSTOM_NAMESPACE
}
#endif
| 22.278689 | 73 | 0.554084 | [
"object"
] |
8f6a8684ea667c1fa7cd9cd42fb5a1233b586c73 | 28,159 | cpp | C++ | WebKit/Source/WebCore/rendering/RenderFlexibleBox.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | 1 | 2019-06-18T06:52:54.000Z | 2019-06-18T06:52:54.000Z | WebKit/Source/WebCore/rendering/RenderFlexibleBox.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | null | null | null | WebKit/Source/WebCore/rendering/RenderFlexibleBox.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. 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
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "RenderFlexibleBox.h"
#include "LayoutRepainter.h"
#include "RenderView.h"
namespace WebCore {
// Normally, -1 and 0 are not valid in a HashSet, but these are relatively likely flex-order values. Instead,
// we make the two smallest int values invalid flex-order values (in the css parser code we clamp them to
// int min + 2).
struct FlexOrderHashTraits : WTF::GenericHashTraits<int> {
static const bool emptyValueIsZero = false;
static int emptyValue() { return std::numeric_limits<int>::min(); }
static void constructDeletedValue(int& slot) { slot = std::numeric_limits<int>::min() + 1; }
static bool isDeletedValue(int value) { return value == std::numeric_limits<int>::min() + 1; }
};
typedef HashSet<int, DefaultHash<int>::Hash, FlexOrderHashTraits> FlexOrderHashSet;
class RenderFlexibleBox::TreeOrderIterator {
public:
explicit TreeOrderIterator(RenderFlexibleBox* flexibleBox)
: m_flexibleBox(flexibleBox)
, m_currentChild(0)
{
}
RenderBox* first()
{
reset();
return next();
}
RenderBox* next()
{
m_currentChild = m_currentChild ? m_currentChild->nextSiblingBox() : m_flexibleBox->firstChildBox();
if (m_currentChild)
m_flexOrderValues.add(m_currentChild->style()->flexOrder());
return m_currentChild;
}
void reset()
{
m_currentChild = 0;
}
const FlexOrderHashSet& flexOrderValues()
{
return m_flexOrderValues;
}
private:
RenderFlexibleBox* m_flexibleBox;
RenderBox* m_currentChild;
FlexOrderHashSet m_flexOrderValues;
};
class RenderFlexibleBox::FlexOrderIterator {
public:
FlexOrderIterator(RenderFlexibleBox* flexibleBox, const FlexOrderHashSet& flexOrderValues)
: m_flexibleBox(flexibleBox)
, m_currentChild(0)
, m_orderValuesIterator(0)
{
copyToVector(flexOrderValues, m_orderValues);
std::sort(m_orderValues.begin(), m_orderValues.end());
}
RenderBox* first()
{
reset();
return next();
}
RenderBox* next()
{
do {
if (!m_currentChild) {
if (m_orderValuesIterator == m_orderValues.end())
return 0;
if (m_orderValuesIterator) {
++m_orderValuesIterator;
if (m_orderValuesIterator == m_orderValues.end())
return 0;
} else
m_orderValuesIterator = m_orderValues.begin();
m_currentChild = m_flexibleBox->firstChildBox();
} else
m_currentChild = m_currentChild->nextSiblingBox();
} while (!m_currentChild || m_currentChild->style()->flexOrder() != *m_orderValuesIterator);
return m_currentChild;
}
void reset()
{
m_currentChild = 0;
m_orderValuesIterator = 0;
}
private:
RenderFlexibleBox* m_flexibleBox;
RenderBox* m_currentChild;
Vector<int> m_orderValues;
Vector<int>::const_iterator m_orderValuesIterator;
};
RenderFlexibleBox::RenderFlexibleBox(Node* node)
: RenderBlock(node)
{
setChildrenInline(false); // All of our children must be block-level.
}
RenderFlexibleBox::~RenderFlexibleBox()
{
}
const char* RenderFlexibleBox::renderName() const
{
return "RenderFlexibleBox";
}
void RenderFlexibleBox::layoutBlock(bool relayoutChildren, int, BlockLayoutPass)
{
ASSERT(needsLayout());
if (!relayoutChildren && simplifiedLayout())
return;
LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
LayoutStateMaintainer statePusher(view(), this, IntSize(x(), y()), hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
IntSize previousSize = size();
setLogicalHeight(0);
// We need to call both of these because we grab both crossAxisExtent and mainAxisExtent in layoutFlexItems.
computeLogicalWidth();
computeLogicalHeight();
m_overflow.clear();
layoutFlexItems(relayoutChildren);
LayoutUnit oldClientAfterEdge = clientLogicalBottom();
computeLogicalHeight();
if (size() != previousSize)
relayoutChildren = true;
layoutPositionedObjects(relayoutChildren || isRoot());
// FIXME: css3/flexbox/repaint-rtl-column.html seems to repaint more overflow than it needs to.
computeOverflow(oldClientAfterEdge);
statePusher.pop();
updateLayerTransform();
repainter.repaintAfterLayout();
setNeedsLayout(false);
}
bool RenderFlexibleBox::hasOrthogonalFlow(RenderBox* child) const
{
// FIXME: If the child is a flexbox, then we need to check isHorizontalFlow.
return isHorizontalFlow() != child->isHorizontalWritingMode();
}
bool RenderFlexibleBox::isColumnFlow() const
{
return style()->isColumnFlexDirection();
}
bool RenderFlexibleBox::isHorizontalFlow() const
{
if (isHorizontalWritingMode())
return !isColumnFlow();
return isColumnFlow();
}
bool RenderFlexibleBox::isLeftToRightFlow() const
{
if (isColumnFlow())
return style()->writingMode() == TopToBottomWritingMode || style()->writingMode() == LeftToRightWritingMode;
return style()->isLeftToRightDirection() ^ (style()->flexDirection() == FlowRowReverse);
}
Length RenderFlexibleBox::mainAxisLengthForChild(RenderBox* child) const
{
return isHorizontalFlow() ? child->style()->width() : child->style()->height();
}
Length RenderFlexibleBox::crossAxisLength() const
{
return isHorizontalFlow() ? style()->height() : style()->width();
}
void RenderFlexibleBox::setCrossAxisExtent(LayoutUnit extent)
{
if (isHorizontalFlow())
setHeight(extent);
else
setWidth(extent);
}
LayoutUnit RenderFlexibleBox::crossAxisExtentForChild(RenderBox* child)
{
return isHorizontalFlow() ? child->height() : child->width();
}
LayoutUnit RenderFlexibleBox::mainAxisExtentForChild(RenderBox* child)
{
return isHorizontalFlow() ? child->width() : child->height();
}
LayoutUnit RenderFlexibleBox::crossAxisExtent() const
{
return isHorizontalFlow() ? height() : width();
}
LayoutUnit RenderFlexibleBox::mainAxisExtent() const
{
return isHorizontalFlow() ? width() : height();
}
LayoutUnit RenderFlexibleBox::crossAxisContentExtent() const
{
return isHorizontalFlow() ? contentHeight() : contentWidth();
}
LayoutUnit RenderFlexibleBox::mainAxisContentExtent() const
{
return isHorizontalFlow() ? contentWidth() : contentHeight();
}
WritingMode RenderFlexibleBox::transformedWritingMode() const
{
WritingMode mode = style()->writingMode();
if (!isColumnFlow())
return mode;
switch (mode) {
case TopToBottomWritingMode:
case BottomToTopWritingMode:
return style()->isLeftToRightDirection() ? LeftToRightWritingMode : RightToLeftWritingMode;
case LeftToRightWritingMode:
case RightToLeftWritingMode:
return style()->isLeftToRightDirection() ? TopToBottomWritingMode : BottomToTopWritingMode;
}
ASSERT_NOT_REACHED();
return TopToBottomWritingMode;
}
LayoutUnit RenderFlexibleBox::flowAwareBorderStart() const
{
if (isHorizontalFlow())
return isLeftToRightFlow() ? borderLeft() : borderRight();
return isLeftToRightFlow() ? borderTop() : borderBottom();
}
LayoutUnit RenderFlexibleBox::flowAwareBorderEnd() const
{
if (isHorizontalFlow())
return isLeftToRightFlow() ? borderRight() : borderLeft();
return isLeftToRightFlow() ? borderBottom() : borderTop();
}
LayoutUnit RenderFlexibleBox::flowAwareBorderBefore() const
{
switch (transformedWritingMode()) {
case TopToBottomWritingMode:
return borderTop();
case BottomToTopWritingMode:
return borderBottom();
case LeftToRightWritingMode:
return borderLeft();
case RightToLeftWritingMode:
return borderRight();
}
ASSERT_NOT_REACHED();
return borderTop();
}
LayoutUnit RenderFlexibleBox::crossAxisBorderAndPaddingExtent() const
{
return isHorizontalFlow() ? borderAndPaddingHeight() : borderAndPaddingWidth();
}
LayoutUnit RenderFlexibleBox::flowAwarePaddingStart() const
{
if (isHorizontalFlow())
return isLeftToRightFlow() ? paddingLeft() : paddingRight();
return isLeftToRightFlow() ? paddingTop() : paddingBottom();
}
LayoutUnit RenderFlexibleBox::flowAwarePaddingEnd() const
{
if (isHorizontalFlow())
return isLeftToRightFlow() ? paddingRight() : paddingLeft();
return isLeftToRightFlow() ? paddingBottom() : paddingTop();
}
LayoutUnit RenderFlexibleBox::flowAwarePaddingBefore() const
{
switch (transformedWritingMode()) {
case TopToBottomWritingMode:
return paddingTop();
case BottomToTopWritingMode:
return paddingBottom();
case LeftToRightWritingMode:
return paddingLeft();
case RightToLeftWritingMode:
return paddingRight();
}
ASSERT_NOT_REACHED();
return paddingTop();
}
LayoutUnit RenderFlexibleBox::flowAwareMarginStartForChild(RenderBox* child) const
{
if (isHorizontalFlow())
return isLeftToRightFlow() ? child->marginLeft() : child->marginRight();
return isLeftToRightFlow() ? child->marginTop() : child->marginBottom();
}
LayoutUnit RenderFlexibleBox::flowAwareMarginEndForChild(RenderBox* child) const
{
if (isHorizontalFlow())
return isLeftToRightFlow() ? child->marginRight() : child->marginLeft();
return isLeftToRightFlow() ? child->marginBottom() : child->marginTop();
}
LayoutUnit RenderFlexibleBox::flowAwareMarginBeforeForChild(RenderBox* child) const
{
switch (transformedWritingMode()) {
case TopToBottomWritingMode:
return child->marginTop();
case BottomToTopWritingMode:
return child->marginBottom();
case LeftToRightWritingMode:
return child->marginLeft();
case RightToLeftWritingMode:
return child->marginRight();
}
ASSERT_NOT_REACHED();
return marginTop();
}
LayoutUnit RenderFlexibleBox::flowAwareMarginAfterForChild(RenderBox* child) const
{
switch (transformedWritingMode()) {
case TopToBottomWritingMode:
return child->marginBottom();
case BottomToTopWritingMode:
return child->marginTop();
case LeftToRightWritingMode:
return child->marginRight();
case RightToLeftWritingMode:
return child->marginLeft();
}
ASSERT_NOT_REACHED();
return marginBottom();
}
LayoutUnit RenderFlexibleBox::crossAxisMarginExtentForChild(RenderBox* child) const
{
return isHorizontalFlow() ? child->marginTop() + child->marginBottom() : child->marginLeft() + child->marginRight();
}
LayoutPoint RenderFlexibleBox::flowAwareLocationForChild(RenderBox* child) const
{
return isHorizontalFlow() ? child->location() : child->location().transposedPoint();
}
void RenderFlexibleBox::setFlowAwareLocationForChild(RenderBox* child, const LayoutPoint& location)
{
if (isHorizontalFlow())
child->setLocation(location);
else
child->setLocation(location.transposedPoint());
}
LayoutUnit RenderFlexibleBox::mainAxisBorderAndPaddingExtentForChild(RenderBox* child) const
{
return isHorizontalFlow() ? child->borderAndPaddingWidth() : child->borderAndPaddingHeight();
}
LayoutUnit RenderFlexibleBox::mainAxisScrollbarExtentForChild(RenderBox* child) const
{
return isHorizontalFlow() ? child->verticalScrollbarWidth() : child->horizontalScrollbarHeight();
}
LayoutUnit RenderFlexibleBox::preferredMainAxisContentExtentForFlexItem(RenderBox* child) const
{
Length mainAxisLength = mainAxisLengthForChild(child);
if (mainAxisLength.isAuto()) {
LayoutUnit mainAxisExtent = hasOrthogonalFlow(child) ? child->logicalHeight() : child->maxPreferredLogicalWidth();
return mainAxisExtent - mainAxisBorderAndPaddingExtentForChild(child) - mainAxisScrollbarExtentForChild(child);
}
return mainAxisLength.calcMinValue(mainAxisContentExtent());
}
void RenderFlexibleBox::layoutFlexItems(bool relayoutChildren)
{
LayoutUnit preferredMainAxisExtent;
float totalPositiveFlexibility;
float totalNegativeFlexibility;
TreeOrderIterator treeIterator(this);
computePreferredMainAxisExtent(relayoutChildren, treeIterator, preferredMainAxisExtent, totalPositiveFlexibility, totalNegativeFlexibility);
LayoutUnit availableFreeSpace = mainAxisContentExtent() - preferredMainAxisExtent;
FlexOrderIterator flexIterator(this, treeIterator.flexOrderValues());
InflexibleFlexItemSize inflexibleItems;
WTF::Vector<LayoutUnit> childSizes;
while (!runFreeSpaceAllocationAlgorithm(flexIterator, availableFreeSpace, totalPositiveFlexibility, totalNegativeFlexibility, inflexibleItems, childSizes)) {
ASSERT(totalPositiveFlexibility >= 0 && totalNegativeFlexibility >= 0);
ASSERT(inflexibleItems.size() > 0);
}
layoutAndPlaceChildren(flexIterator, childSizes, availableFreeSpace, totalPositiveFlexibility);
}
float RenderFlexibleBox::positiveFlexForChild(RenderBox* child) const
{
return isHorizontalFlow() ? child->style()->flexboxWidthPositiveFlex() : child->style()->flexboxHeightPositiveFlex();
}
float RenderFlexibleBox::negativeFlexForChild(RenderBox* child) const
{
return isHorizontalFlow() ? child->style()->flexboxWidthNegativeFlex() : child->style()->flexboxHeightNegativeFlex();
}
LayoutUnit RenderFlexibleBox::availableAlignmentSpaceForChild(RenderBox* child)
{
LayoutUnit crossContentExtent = crossAxisContentExtent();
LayoutUnit childCrossExtent = crossAxisMarginExtentForChild(child) + crossAxisExtentForChild(child);
return crossContentExtent - childCrossExtent;
}
LayoutUnit RenderFlexibleBox::marginBoxAscent(RenderBox* child)
{
LayoutUnit ascent = child->firstLineBoxBaseline();
if (ascent == -1)
ascent = crossAxisExtentForChild(child) + flowAwareMarginAfterForChild(child);
return ascent + flowAwareMarginBeforeForChild(child);
}
void RenderFlexibleBox::computePreferredMainAxisExtent(bool relayoutChildren, TreeOrderIterator& iterator, LayoutUnit& preferredMainAxisExtent, float& totalPositiveFlexibility, float& totalNegativeFlexibility)
{
preferredMainAxisExtent = 0;
totalPositiveFlexibility = totalNegativeFlexibility = 0;
LayoutUnit flexboxAvailableContentExtent = mainAxisContentExtent();
for (RenderBox* child = iterator.first(); child; child = iterator.next()) {
if (mainAxisLengthForChild(child).isAuto()) {
child->clearOverrideSize();
if (!relayoutChildren)
child->setChildNeedsLayout(true);
child->layoutIfNeeded();
}
// We set the margins because we want to make sure 'auto' has a margin
// of 0 and because if we're not auto sizing, we don't do a layout that
// computes the start/end margins.
if (isHorizontalFlow()) {
child->setMarginLeft(child->style()->marginLeft().calcMinValue(flexboxAvailableContentExtent));
child->setMarginRight(child->style()->marginRight().calcMinValue(flexboxAvailableContentExtent));
preferredMainAxisExtent += child->marginLeft() + child->marginRight();
} else {
child->setMarginTop(child->style()->marginTop().calcMinValue(flexboxAvailableContentExtent));
child->setMarginBottom(child->style()->marginBottom().calcMinValue(flexboxAvailableContentExtent));
preferredMainAxisExtent += child->marginTop() + child->marginBottom();
}
preferredMainAxisExtent += mainAxisBorderAndPaddingExtentForChild(child);
preferredMainAxisExtent += preferredMainAxisContentExtentForFlexItem(child);
totalPositiveFlexibility += positiveFlexForChild(child);
totalNegativeFlexibility += negativeFlexForChild(child);
}
}
// Returns true if we successfully ran the algorithm and sized the flex items.
bool RenderFlexibleBox::runFreeSpaceAllocationAlgorithm(FlexOrderIterator& iterator, LayoutUnit& availableFreeSpace, float& totalPositiveFlexibility, float& totalNegativeFlexibility, InflexibleFlexItemSize& inflexibleItems, WTF::Vector<LayoutUnit>& childSizes)
{
childSizes.clear();
LayoutUnit flexboxAvailableContentExtent = mainAxisContentExtent();
for (RenderBox* child = iterator.first(); child; child = iterator.next()) {
LayoutUnit childPreferredSize;
if (inflexibleItems.contains(child))
childPreferredSize = inflexibleItems.get(child);
else {
childPreferredSize = preferredMainAxisContentExtentForFlexItem(child);
if (availableFreeSpace > 0 && totalPositiveFlexibility > 0) {
childPreferredSize += lroundf(availableFreeSpace * positiveFlexForChild(child) / totalPositiveFlexibility);
Length childLogicalMaxWidth = isHorizontalFlow() ? child->style()->maxWidth() : child->style()->maxHeight();
if (!childLogicalMaxWidth.isUndefined() && childLogicalMaxWidth.isSpecified() && childPreferredSize > childLogicalMaxWidth.calcValue(flexboxAvailableContentExtent)) {
childPreferredSize = childLogicalMaxWidth.calcValue(flexboxAvailableContentExtent);
availableFreeSpace -= childPreferredSize - preferredMainAxisContentExtentForFlexItem(child);
totalPositiveFlexibility -= positiveFlexForChild(child);
inflexibleItems.set(child, childPreferredSize);
return false;
}
} else if (availableFreeSpace < 0 && totalNegativeFlexibility > 0) {
childPreferredSize += lroundf(availableFreeSpace * negativeFlexForChild(child) / totalNegativeFlexibility);
Length childLogicalMinWidth = isHorizontalFlow() ? child->style()->minWidth() : child->style()->minHeight();
if (!childLogicalMinWidth.isUndefined() && childLogicalMinWidth.isSpecified() && childPreferredSize < childLogicalMinWidth.calcValue(flexboxAvailableContentExtent)) {
childPreferredSize = childLogicalMinWidth.calcValue(flexboxAvailableContentExtent);
availableFreeSpace += preferredMainAxisContentExtentForFlexItem(child) - childPreferredSize;
totalNegativeFlexibility -= negativeFlexForChild(child);
inflexibleItems.set(child, childPreferredSize);
return false;
}
}
}
childSizes.append(childPreferredSize);
}
return true;
}
static bool hasPackingSpace(LayoutUnit availableFreeSpace, float totalPositiveFlexibility)
{
return availableFreeSpace > 0 && !totalPositiveFlexibility;
}
static LayoutUnit initialPackingOffset(LayoutUnit availableFreeSpace, float totalPositiveFlexibility, EFlexPack flexPack)
{
if (hasPackingSpace(availableFreeSpace, totalPositiveFlexibility)) {
if (flexPack == PackEnd)
return availableFreeSpace;
if (flexPack == PackCenter)
return availableFreeSpace / 2;
}
return 0;
}
static LayoutUnit packingSpaceBetweenChildren(LayoutUnit availableFreeSpace, float totalPositiveFlexibility, EFlexPack flexPack, size_t numberOfChildren)
{
if (hasPackingSpace(availableFreeSpace, totalPositiveFlexibility) && flexPack == PackJustify && numberOfChildren > 1)
return availableFreeSpace / (numberOfChildren - 1);
return 0;
}
void RenderFlexibleBox::setLogicalOverrideSize(RenderBox* child, LayoutUnit childPreferredSize)
{
// FIXME: Rename setOverrideWidth/setOverrideHeight to setOverrideLogicalWidth/setOverrideLogicalHeight.
if (hasOrthogonalFlow(child))
child->setOverrideHeight(childPreferredSize);
else
child->setOverrideWidth(childPreferredSize);
}
void RenderFlexibleBox::layoutAndPlaceChildren(FlexOrderIterator& iterator, const WTF::Vector<LayoutUnit>& childSizes, LayoutUnit availableFreeSpace, float totalPositiveFlexibility)
{
LayoutUnit mainAxisOffset = flowAwareBorderStart() + flowAwarePaddingStart();
mainAxisOffset += initialPackingOffset(availableFreeSpace, totalPositiveFlexibility, style()->flexPack());
LayoutUnit crossAxisOffset = flowAwareBorderBefore() + flowAwarePaddingBefore();
LayoutUnit totalMainExtent = mainAxisExtent();
LayoutUnit maxAscent = 0, maxDescent = 0; // Used when flex-align: baseline.
bool shouldFlipMainAxis = !isColumnFlow() && !isLeftToRightFlow();
size_t i = 0;
for (RenderBox* child = iterator.first(); child; child = iterator.next(), ++i) {
LayoutUnit childPreferredSize = childSizes[i] + mainAxisBorderAndPaddingExtentForChild(child);
setLogicalOverrideSize(child, childPreferredSize);
child->setChildNeedsLayout(true);
child->layoutIfNeeded();
if (child->style()->flexAlign() == AlignBaseline) {
LayoutUnit ascent = marginBoxAscent(child);
LayoutUnit descent = (crossAxisMarginExtentForChild(child) + crossAxisExtentForChild(child)) - ascent;
maxAscent = std::max(maxAscent, ascent);
maxDescent = std::max(maxDescent, descent);
// FIXME: add flowAwareScrollbarLogicalHeight.
if (crossAxisLength().isAuto())
setCrossAxisExtent(std::max(crossAxisExtent(), crossAxisBorderAndPaddingExtent() + crossAxisMarginExtentForChild(child) + maxAscent + maxDescent + scrollbarLogicalHeight()));
} else if (crossAxisLength().isAuto())
setCrossAxisExtent(std::max(crossAxisExtent(), crossAxisBorderAndPaddingExtent() + crossAxisMarginExtentForChild(child) + crossAxisExtentForChild(child) + scrollbarLogicalHeight()));
mainAxisOffset += flowAwareMarginStartForChild(child);
LayoutUnit childMainExtent = mainAxisExtentForChild(child);
IntPoint childLocation(shouldFlipMainAxis ? totalMainExtent - mainAxisOffset - childMainExtent : mainAxisOffset,
crossAxisOffset + flowAwareMarginBeforeForChild(child));
// FIXME: Supporting layout deltas.
setFlowAwareLocationForChild(child, childLocation);
mainAxisOffset += childMainExtent + flowAwareMarginEndForChild(child);
mainAxisOffset += packingSpaceBetweenChildren(availableFreeSpace, totalPositiveFlexibility, style()->flexPack(), childSizes.size());
if (isColumnFlow())
setLogicalHeight(mainAxisOffset);
}
if (style()->flexDirection() == FlowColumnReverse) {
// We have to do an extra pass for column-reverse to reposition the flex items since the start depends
// on the height of the flexbox, which we only know after we've positioned all the flex items.
computeLogicalHeight();
layoutColumnReverse(iterator, childSizes, availableFreeSpace, totalPositiveFlexibility);
}
alignChildren(iterator, maxAscent);
}
void RenderFlexibleBox::layoutColumnReverse(FlexOrderIterator& iterator, const WTF::Vector<LayoutUnit>& childSizes, LayoutUnit availableFreeSpace, float totalPositiveFlexibility)
{
// This is similar to the logic in layoutAndPlaceChildren, except we place the children
// starting from the end of the flexbox. We also don't need to layout anything since we're
// just moving the children to a new position.
LayoutUnit mainAxisOffset = logicalHeight() - flowAwareBorderEnd() - flowAwarePaddingEnd();
mainAxisOffset -= initialPackingOffset(availableFreeSpace, totalPositiveFlexibility, style()->flexPack());
LayoutUnit crossAxisOffset = flowAwareBorderBefore() + flowAwarePaddingBefore();
size_t i = 0;
for (RenderBox* child = iterator.first(); child; child = iterator.next(), ++i) {
mainAxisOffset -= mainAxisExtentForChild(child) + flowAwareMarginEndForChild(child);
LayoutRect oldRect = child->frameRect();
setFlowAwareLocationForChild(child, IntPoint(mainAxisOffset, crossAxisOffset + flowAwareMarginBeforeForChild(child)));
if (!selfNeedsLayout() && child->checkForRepaintDuringLayout())
child->repaintDuringLayoutIfMoved(oldRect);
mainAxisOffset -= flowAwareMarginStartForChild(child);
mainAxisOffset -= packingSpaceBetweenChildren(availableFreeSpace, totalPositiveFlexibility, style()->flexPack(), childSizes.size());
}
}
void RenderFlexibleBox::adjustAlignmentForChild(RenderBox* child, LayoutUnit delta)
{
LayoutRect oldRect = child->frameRect();
setFlowAwareLocationForChild(child, flowAwareLocationForChild(child) + LayoutSize(0, delta));
// If the child moved, we have to repaint it as well as any floating/positioned
// descendants. An exception is if we need a layout. In this case, we know we're going to
// repaint ourselves (and the child) anyway.
if (!selfNeedsLayout() && child->checkForRepaintDuringLayout())
child->repaintDuringLayoutIfMoved(oldRect);
}
void RenderFlexibleBox::alignChildren(FlexOrderIterator& iterator, LayoutUnit maxAscent)
{
LayoutUnit crossExtent = crossAxisExtent();
for (RenderBox* child = iterator.first(); child; child = iterator.next()) {
// direction:rtl + flex-direction:column means the cross-axis direction is flipped.
if (!style()->isLeftToRightDirection() && isColumnFlow()) {
LayoutPoint location = flowAwareLocationForChild(child);
location.setY(crossExtent - crossAxisExtentForChild(child) - location.y());
setFlowAwareLocationForChild(child, location);
}
// FIXME: Make sure this does the right thing with column flows.
switch (child->style()->flexAlign()) {
case AlignStretch: {
if (!isColumnFlow() && child->style()->logicalHeight().isAuto()) {
LayoutUnit stretchedLogicalHeight = child->logicalHeight() + RenderFlexibleBox::availableAlignmentSpaceForChild(child);
child->setLogicalHeight(stretchedLogicalHeight);
child->computeLogicalHeight();
// FIXME: We need to relayout if the height changed.
}
break;
}
case AlignStart:
break;
case AlignEnd:
adjustAlignmentForChild(child, RenderFlexibleBox::availableAlignmentSpaceForChild(child));
break;
case AlignCenter:
adjustAlignmentForChild(child, RenderFlexibleBox::availableAlignmentSpaceForChild(child) / 2);
break;
case AlignBaseline: {
LayoutUnit ascent = marginBoxAscent(child);
adjustAlignmentForChild(child, maxAscent - ascent);
break;
}
}
}
}
}
| 38.786501 | 260 | 0.716503 | [
"vector"
] |
8f7826c94830368d5c14f8946d72ad121eddd6e7 | 1,910 | cpp | C++ | viewify/src/main/View/Image.cpp | ii887522/viewify | 2bd8ef48a63abeaeca73f7f532992ffb6122c76e | [
"MIT"
] | 1 | 2021-07-13T00:56:09.000Z | 2021-07-13T00:56:09.000Z | viewify/src/main/View/Image.cpp | ii887522/viewify | 2bd8ef48a63abeaeca73f7f532992ffb6122c76e | [
"MIT"
] | null | null | null | viewify/src/main/View/Image.cpp | ii887522/viewify | 2bd8ef48a63abeaeca73f7f532992ffb6122c76e | [
"MIT"
] | null | null | null | // Copyright ii887522
#ifndef CONSOLE_TEST
#include "Image.h"
#include <SDL.h>
#include <SDL_image.h>
#include <stdexcept>
#include "../Any/View.h"
#include "../Model/ImageModel.h"
#include "../Any/Enums.h"
#include "../Struct/Size.h"
#include "../Atlas/TextureAtlas.h"
using std::runtime_error;
namespace ii887522::viewify {
Image* Image::Builder::build() {
if (!hasSetAnimationController) throw runtime_error{ "Image animationController is required!" };
if (!hasSetAtlas) throw runtime_error{ "Image atlas is required!" };
if (!hasSetName) throw runtime_error{ "Image name is required!" };
return new Image{ *this };
}
Image::Image(const Builder& builder) : View{
builder.atlas->getRenderer(),
builder.position - (builder.align == Align::LEFT ?
Size{ 0, 0 } : Size{ builder.atlas->getSpriteUnrotatedSize(builder.name).w >> 1u /* which means builder.atlas->getSpriteUnrotatedSize(builder.name).w / 2 */, 0 }) },
atlas{ builder.atlas }, model{ ImageModel::Builder{ builder.animationController, builder.a }.setDuration(builder.duration).build() }, name{ builder.name }, align{ builder.align },
rotation{ builder.rotation } { }
void Image::set(const unsigned int p_name) {
const auto centerPosition{ getPosition().get() + Size{ atlas->getSpriteUnrotatedSize(name).w >> 1u /* which means atlas->getSpriteUnrotatedSize(name).w / 2 */, 0 } };
name = p_name;
if (align == Align::CENTER) getPosition().set(centerPosition - Size{ atlas->getSpriteUnrotatedSize(p_name).w >> 1u /* which means atlas->getSpriteUnrotatedSize(p_name).w / 2 */, 0 });
}
void Image::show() {
model.show();
}
void Image::hide() {
model.hide();
}
void Image::step(const unsigned int dt) {
model.step(dt);
}
void Image::render() {
TextureAtlas::Renderer{ name }.setPosition(getPosition().get()).setA(model.getA()).setRotation(rotation).render(atlas);
}
} // namespace ii887522::viewify
#endif
| 32.931034 | 186 | 0.7 | [
"render",
"model"
] |
8f83658444d38f68752395399137f6fcf4123b94 | 1,265 | cpp | C++ | Sockets/Sockets TCP/Client/main_client.cpp | Witiza/Xarxes_i_Jocs_Online | 54f18b43f5153406534e8c8e93b37665f4f08d2c | [
"MIT"
] | null | null | null | Sockets/Sockets TCP/Client/main_client.cpp | Witiza/Xarxes_i_Jocs_Online | 54f18b43f5153406534e8c8e93b37665f4f08d2c | [
"MIT"
] | null | null | null | Sockets/Sockets TCP/Client/main_client.cpp | Witiza/Xarxes_i_Jocs_Online | 54f18b43f5153406534e8c8e93b37665f4f08d2c | [
"MIT"
] | null | null | null | #define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include "Windows.h"
#include "WinSock2.h"
#include "Ws2tcpip.h"
#include <iostream>
#include <cstdlib>
#pragma comment(lib, "ws2_32.lib")
#define SERVER_ADDRESS "127.0.0.1"
#define SERVER_PORT 8888
#define PAUSE_AND_EXIT() system("pause"); exit(-1)
void printWSErrorAndExit(const char *msg)
{
wchar_t *s = NULL;
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, WSAGetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&s, 0, NULL);
fprintf(stderr, "%s: %S\n", msg, s);
LocalFree(s);
PAUSE_AND_EXIT();
}
void client(const char *serverAddrStr, int port)
{
// TODO-1: Winsock init
// TODO-2: Create socket (IPv4, stream, TCP)
// TODO-3: Create an address object with the server address
// TODO-4: Connect to server
for (int i = 0; i < 5; ++i)
{
// TODO-5:
// - Send a 'ping' packet to the server
// - Receive 'pong' packet from the server
// - Control errors in both cases
// - Control graceful disconnection from the server (recv receiving 0 bytes)
}
// TODO-6: Close socket
// TODO-7: Winsock shutdown
}
int main(int argc, char **argv)
{
client(SERVER_ADDRESS, SERVER_PORT);
PAUSE_AND_EXIT();
}
| 21.083333 | 108 | 0.704348 | [
"object"
] |
8f84f71e79e0fff119841d1aadf580b755397355 | 4,115 | cpp | C++ | src/radiusmessage.cpp | OpenIKEv2/libopenikev2_impl | 3c620ca479b20814fe42325cffcfd1d18dbf041c | [
"Apache-2.0"
] | 3 | 2017-03-03T17:05:37.000Z | 2020-06-16T04:50:40.000Z | src/radiusmessage.cpp | OpenIKEv2/libopenikev2_impl | 3c620ca479b20814fe42325cffcfd1d18dbf041c | [
"Apache-2.0"
] | 11 | 2017-02-27T09:31:17.000Z | 2020-03-20T16:31:05.000Z | src/radiusmessage.cpp | OpenIKEv2/libopenikev2_impl | 3c620ca479b20814fe42325cffcfd1d18dbf041c | [
"Apache-2.0"
] | null | null | null | /***************************************************************************
* Copyright (C) 2005 by *
* Alejandro Perez Mendez alex@um.es *
* Pedro J. Fernandez Ruiz pedroj@um.es *
* *
* This software may be modified and distributed under the terms *
* of the Apache license. See the LICENSE file for details. *
***************************************************************************/
#include "radiusmessage.h"
#include <libopenikev2/utils.h>
#include <libopenikev2/exception.h>
#include <assert.h>
namespace openikev2 {
RadiusMessage::RadiusMessage() {
}
RadiusMessage::RadiusMessage( RADIUS_MESSAGE_CODE code, uint8_t identifier, auto_ptr<ByteArray> authenticator ) {
assert( authenticator->size() == 16 );
this->code = code;
this->identifier = identifier;
this->authenticator = authenticator;
}
RadiusMessage::~RadiusMessage() {
}
auto_ptr< RadiusMessage > RadiusMessage::parse( ByteBuffer & byte_buffer ) {
auto_ptr<RadiusMessage> result( new RadiusMessage() );
// Pointer to the beginning of the transform
uint8_t * message_begin = byte_buffer.getReadPosition();
result->code = ( RADIUS_MESSAGE_CODE ) byte_buffer.readInt8();
result->identifier = byte_buffer.readInt8();
uint16_t length = byte_buffer.readInt16();
// Size must be at least size of fixed header
if ( length < 20 || length > 4096 )
throw ParsingException( "Invalid RADIUS message size: " + intToString( length ) );
result->authenticator = byte_buffer.readByteArray( 16 );
while ( byte_buffer.getReadPosition() < message_begin + length ) {
// parse the transform attribute
auto_ptr<RadiusAttribute> attribute = RadiusAttribute::parse( byte_buffer );
// adds the attribute to the collection
result->addAttribute( attribute );
}
return result;
}
void RadiusMessage::addAttribute( auto_ptr< RadiusAttribute > attribute ) {
this->attributes->push_back( attribute.release() );
}
void RadiusMessage::getBinaryRepresentation( ByteBuffer & byte_buffer ) const {
byte_buffer.writeInt8( this->code );
byte_buffer.writeInt8( this->identifier );
// writes a dummy lengh
uint8_t* length_field_position = byte_buffer.getWritePosition();
byte_buffer.writeInt16( 0 );
byte_buffer.writeByteArray( *this->authenticator );
for ( vector<RadiusAttribute*>::const_iterator it = this->attributes->begin(); it != this->attributes->end(); it++ ) {
( *it ) ->getBinaryRepresentation( byte_buffer );
}
// pointer to the current position
uint8_t* current_position = byte_buffer.getWritePosition();
// writes the real length value
byte_buffer.setWritePosition( length_field_position );
byte_buffer.writeInt16( current_position - length_field_position + 2 );
byte_buffer.setWritePosition( current_position );
}
RadiusAttribute * RadiusMessage::getAttribute( RadiusAttribute::RADIUS_ATTRIBUTE_TYPE type ) {
for ( vector<RadiusAttribute*>::const_iterator it = this->attributes->begin(); it != this->attributes->end(); it++ ) {
RadiusAttribute* current = ( *it );
if (current->getType() == type)
return current;
}
return NULL;
}
vector<RadiusAttribute*> RadiusMessage::getAttributes( RadiusAttribute::RADIUS_ATTRIBUTE_TYPE type ) {
vector<RadiusAttribute*> result;
for ( vector<RadiusAttribute*>::const_iterator it = this->attributes->begin(); it != this->attributes->end(); it++ ) {
RadiusAttribute* current = ( *it );
if (current->getType() == type)
result.push_back(current);
}
return result;
}
}
| 36.096491 | 126 | 0.587363 | [
"vector",
"transform"
] |
8f85d67b37fd9483c80bae14c3895cdcab41e3d7 | 18,733 | cpp | C++ | studyGlewApp/app/src/main/cpp/render/lineWrap.cpp | LightSun/study_harfbuzz | d35584123f0d559bf08be3a028fd9ef8e846163b | [
"Apache-2.0"
] | null | null | null | studyGlewApp/app/src/main/cpp/render/lineWrap.cpp | LightSun/study_harfbuzz | d35584123f0d559bf08be3a028fd9ef8e846163b | [
"Apache-2.0"
] | null | null | null | studyGlewApp/app/src/main/cpp/render/lineWrap.cpp | LightSun/study_harfbuzz | d35584123f0d559bf08be3a028fd9ef8e846163b | [
"Apache-2.0"
] | null | null | null | //
// Port of the implementation by:
// Bram Stein - http://www.bramstein.com/projects/typeset/
// Copyright 2009-2010, Bram Stein
//
// Preserve Knuth and Plass line breaking algorithm in C++
//
// Licensed under the new BSD License.
//
//
// Copyright 2015, Hannes Janetzek
//
#include "lineWrap.h"
#include <glm/vec2.hpp>
#include <algorithm>
#include <stdint.h>
#include <cmath>
#include <limits>
#include <string>
#include "logger.h"
using std::pow;
using std::abs;
//#define DEBUG_WRAP
#ifndef DEBUG_WRAP
#ifdef LOGD
#undef LOGD
#define LOGD(...)
#endif
#endif
#define Infinity std::numeric_limits<double>::infinity()
namespace alfons {
typedef WordWrap::Breakpoint Breakpoint;
typedef WordWrap::Row Row;
// Compute adjustment ratio for the line between start and end
double WordWrap::computeCost(const Breakpoint& start, const Box& node) {
int width = sumWidth - start.totalWidth;
LOGD("\tcompute cost:length:%d %d/%d", width, sumWidth, start.totalWidth);
// Get the length of the current line; if the line_lengths list is too short,
// the last value is always used for subsequent lines.
int lineLength = (start.line < (int)(lineLengths.size() - 1))
? lineLengths[start.line]
: lineLengths[lineLengths.size() - 1];
if (node.isPenalty) {
width += node.width;
LOGD("\tm add penaltiy %d", node.width);
}
// Compute how much the contents of the line would have to be stretched or
// shrunk to fit into the available space.
if (width < lineLength) {
// Calculate the stretch ratio
int stretch = sumStretch - start.totalStretch;
LOGD("\tLine too short: %d, stretch = %d %d/%d", lineLength - width,
stretch, sumStretch, start.totalStretch);
if (stretch > 0)
return (lineLength - width) / double(stretch);
else
return LINE_INFINITY;
} else if (width > lineLength) {
// Calculate the shrink ratio
int shrink = sumShrink - start.totalShrink;
LOGD("\tLine too long: %d, shrink = %d %d/%d", lineLength - width,
shrink, sumShrink, start.totalShrink);
if (shrink > 0)
return (lineLength - width) / double(shrink);
else
return LINE_INFINITY;
}
// Exactly the right width!
return 0;
}
struct Candidate {
// BreakpointRef active;
Breakpoint* active;
double demerits;
double ratio;
};
Breakpoint* WordWrap::newBreakpoint(uint32_t index, double demerits,
double ratio, int line, int fitnessClass,
int totalWidth, int totalStretch,
int totalShrink, Breakpoint* previous) {
if (!pool)
return new Breakpoint(index, demerits, ratio, line, fitnessClass,
totalWidth, totalStretch, totalShrink, previous);
Breakpoint* p = pool;
pool = pool->prev;
p->refs = 1;
p->index = index;
p->demerits = demerits;
p->ratio = ratio;
p->line = line;
p->fitnessClass = fitnessClass;
p->totalWidth = totalWidth;
p->totalStretch = totalStretch;
p->totalShrink = totalShrink;
p->prev = previous;
return p;
}
void WordWrap::drop(Breakpoint* t) {
while (t && --t->refs <= 0) {
Breakpoint* p = t->prev;
// release to pool
t->prev = pool;
pool = t;
t = p;
}
}
void WordWrap::mainloop(const uint32_t index, const Box& node) {
auto iter = activeNodes.begin();
if (iter == activeNodes.end()) {
LOGI("EMPTY");
return;
}
auto active = *iter;
Candidate candidate[4];
// The inner loop iterates through all the active nodes with (line <
// currentLine) and then breaks out to insert the new active node candidates
// before looking at the next active nodes for the next lines. The result of
// this is that the active node list is always sorted by line number.
LOGD("run %d - active nodes:%d", index, (int)activeNodes.size());
while (active) {
LOGD(">>> outer");
candidate[0].demerits = Infinity;
candidate[1].demerits = Infinity;
candidate[2].demerits = Infinity;
candidate[3].demerits = Infinity;
candidate[0].active = nullptr;
candidate[1].active = nullptr;
candidate[2].active = nullptr;
candidate[3].active = nullptr;
// Iterate through the linked list of active nodes to find new potential
// active nodes and deactivate current active nodes.
while (active) {
// auto nextActive = it++;
// active = *iter;
LOGD("\t>>> inner <<<");
if (!active)
break;
int currentLine = active->line + 1;
float ratio = computeCost(*active, node);
LOGD("\tline:%d ratio:%f", active->line, ratio);
// Deactive nodes when the distance between the current active node and
// the current node becomes too large (i.e. it exceeds the stretch limit
// and the stretch ratio becomes negative) or when the current node is a
// forced break (i.e. the end of the paragraph when we want to remove all
// active nodes, but possibly have a final candidate active node -- if the
// paragraph can be set using the given tolerance value.)
if (ratio < -1 || (node.isPenalty && node.p.penalty == -LINE_INFINITY)) {
// NB: reached an index at which the active breakpoint cannot be
// the start of the line anymore
iter = activeNodes.erase(iter);
// Drop at end of loop, if no new references were added
active->refs--;
} else {
iter++;
}
if ((ratio >= -1 && ratio <= tolerance)) {
// Compute demerits and fitness class
double demerits = pow(lineDemerit + 100.0 * pow(abs(ratio), 3.0), 2.0);
// double demerits;
if (node.isPenalty && node.p.penalty > 0) {
// Positive penalty
demerits += pow(node.p.penalty, 2.0);
} else if (node.isPenalty && node.p.penalty != -LINE_INFINITY) {
// Negative penalty but not a forced break
demerits -= pow(node.p.penalty, 2.0);
}
if (node.isPenalty && nodes[active->index].isPenalty)
demerits += (flaggedDemerit * node.p.flagged *
nodes[active->index].p.flagged);
// Figure out the fitness class of this line (tight, loose, very tight
// or very loose).
int fitnessClass = 0;
if (ratio < -0.5)
fitnessClass = 0;
else if (ratio <= 0.5)
fitnessClass = 1;
else if (ratio <= 1)
fitnessClass = 2;
else
fitnessClass = 3;
// Add a fitness penalty to the demerits if the fitness classes of two
// adjacent lines differ too much. If two consecutive lines are in very
// different fitness classes, add to the demerit score for this break.
if (abs(fitnessClass - active->fitnessClass) > 1) {
demerits += fitnessDemerit;
}
// Add the total demerits of the active node to get the total demerits
// of this candidate node.
demerits += active->demerits;
LOGD("\tdemerits %d, %f - %f", fitnessClass, demerits,
candidate[fitnessClass].demerits);
// Record a feasible break from A to B
// Only store the best candidate for each fitness class
if (demerits < candidate[fitnessClass].demerits) {
auto& b = candidate[fitnessClass];
if (b.active)
drop(b.active);
active->refs++;
b.active = active;
b.ratio = ratio;
b.demerits = demerits;
}
}
if (active->refs == 0)
drop(active);
active = nullptr;
if (iter != activeNodes.end()) {
// Continue whith next Breakpoint
active = *iter;
// Stop iterating through active nodes to insert new candidate active
// nodes in the active list before moving on to the active nodes for the
// next line.
// TODO: The Knuth and Plass paper suggests a conditional for
// currentLine < j0. This means paragraphs with identical line lengths
// will not be sorted by line number. Find out if that is a desirable
// outcome. For now I left this out, as it only adds minimal overhead
// to the algorithm and keeping the active node list sorted has a higher
// priority.
if (active->line >= currentLine) {
LOGD("exit inner: %d >= %d", active->line, currentLine);
break;
}
}
}
LOGD("<<< outer");
// Add width, stretch and shrink values from the current break point up to
// the next box or forced penalty.
int width = sumWidth;
int stretch = sumStretch;
int shrink = sumShrink;
for (uint32_t i = index; i < nodes.size(); i++) {
auto& n = nodes[i];
if (n.isGlue) {
width += n.width;
stretch += n.g.stretch;
shrink += n.g.shrink;
} else if (n.isBox || (n.p.penalty == -LINE_INFINITY && i > index)) {
break;
}
}
for (int fitnessClass = 0; fitnessClass < 4; fitnessClass++) {
auto& c = candidate[fitnessClass];
if (c.demerits == Infinity)
continue;
auto newNode =
newBreakpoint(index, c.demerits, c.ratio, c.active->line + 1,
fitnessClass, width, stretch, shrink, c.active);
#ifdef DEBUG_WRAP
LOGD("Insert breakpoint:");
newNode->print();
#endif
if (active) {
// LOGD("insert before");
// TEST: should insert before
iter = activeNodes.insert(iter, newNode);
iter++;
} else {
// LOGD("push back");
activeNodes.push_back(newNode);
}
}
}
}
std::vector<Row> WordWrap::breakLines() {
activeNodes.clear();
sumWidth = 0;
sumStretch = 0;
sumShrink = 0;
// Add an active node for the start of the paragraph.
activeNodes.push_back(newBreakpoint(0, // index
0, // demerits
0, // ratio
0, // line
0, // class
0, // width
0, // stretch,
0, // shrink,
nullptr));
uint32_t index = 0;
for (const auto& node : nodes) {
#ifdef DEBUG_WRAP
LOGD("");
node.print();
#endif
if (node.isBox) {
// LOGD("add box %d", index);
sumWidth += node.width;
} else if (node.isGlue) {
// LOGD("add glue %d", index);
if (index > 0 && nodes[index - 1].isBox)
mainloop(index, node);
sumWidth += node.width;
sumStretch += node.g.stretch;
sumShrink += node.g.shrink;
} else if (node.isPenalty && node.p.penalty != LINE_INFINITY) {
// LOGD("add penalty %d", index);
mainloop(index, node);
}
#ifdef DEBUG_WRAP
LOGD(">>>");
for (auto& node : activeNodes)
node->print();
LOGD("<<<");
#endif
index++;
if (activeNodes.empty())
break;
}
LOGD("Result nodes: %d", (int)activeNodes.size());
// Find the best active node (the one with the least total demerits.)
Breakpoint* best = nullptr;
Breakpoint* t = nullptr;
std::vector<Row> breaks;
#if 1
for (auto& brk : activeNodes) {
// node->print();
LOGD(">> %d - %d", (int)brk->demerits, (int)(brk->demerits * brk->line));
t = brk->prev; //.get();
while (t) {
LOGD(">> %d - %d", (int)t->demerits, (int)(t->demerits * t->line));
t = t->prev; //.get();
}
if (brk->index < index - 1) {
LOGI("missing chain %d", brk->index);
continue;
}
if (!best) {
best = brk; //.get();
continue;
}
if (brk->demerits < best->demerits) {
best = brk; //.get();
continue;
}
// if (brk->demerits * brk->line < best->demerits * brk->line) {
// best = brk.get();
// continue;
// }
// if (brk->line < best->line) {
// best = brk;
// continue;
// }
// if (brk->line == best->line && brk->demerits < best->demerits){
// best = brk;
// continue;
// }
};
LOGD("Result ptr: %p", best);
#ifdef DEBUG_WRAP
if (best) {
LOGD("Picked:");
best->print();
}
#endif
while (best && best->prev) {
breaks.emplace_back(best->index, best->ratio,
best->totalWidth - best->prev->totalWidth);
best = best->prev;
}
// Free remaining nodes
for (auto& brk : activeNodes)
drop(brk);
LOGD("Result breaks: %d", (int)breaks.size());
#else
for (auto& brk : activeNodes) {
// node->print();
breaks.push_back(brk->index);
LOGD(">> %d - %d", (int)brk->demerits, (int)(brk->demerits * brk->line));
t = brk->prev;
while (t) {
LOGD(">> %d - %d", t->demerits, (int)(t->demerits * t->line));
t = t->prev;
}
t = brk->prev;
while (t) {
breaks.push_back(t->index);
t = t->prev;
}
}
#endif
std::reverse(breaks.begin(), breaks.end());
return breaks;
}
bool WordWrap::wrapLine(LineLayout& layout, float width, float maxWidth,
Alignment align, glm::vec2& resultSize,
std::vector<glm::vec2> _offsets) {
nodes.clear();
int wordStart = 0;
float wordWidth = 0;
bool block = align == Alignment::block;
bool centered = align == Alignment::middle;
float space = 0;
float stretch = 0;
float shrink = 0;
int numWords = 0;
for (int i = 0, n = layout.shapes().size(); i < n; i++) {
auto& c = layout.shapes()[i];
if (c.canBreak) {
if (space == 0 && c.isSpace) {
space = layout.advance(c);
stretch = space * 2;
shrink = space / 2;
}
float s = space;
int pos = i;
if (!c.isSpace) {
wordWidth += layout.advance(c);
s = 0;
pos += 1;
}
wordWidth += 0.5;
if (wordWidth > width) {
width = wordWidth;
if (width > maxWidth) {
LOGD("MAX %f", width);
return false;
}
}
addBox(wordWidth, pos);
numWords++;
if (block) {
addGlue(s, stretch, shrink);
} else {
addGlue(0, width, 0);
addPenalty(0, 0, false);
addGlue(s, -width, 0);
}
wordStart = i;
wordWidth = 0;
} else {
wordWidth += layout.advance(c);
}
}
if (wordWidth > 0) {
addBox(wordWidth, wordStart);
numWords++;
if (block) {
addGlue(space, stretch, shrink);
} else {
addGlue(0, width, 0);
addPenalty(0, 0, false);
addGlue(space, -width, 0);
}
}
addClosingPenalty();
lineLengths[0] = width;
tolerance = 10;
flaggedDemerit = 100;
lineDemerit = 10;
fitnessDemerit = block || centered ? 1000 : 0;
auto rows = breakLines();
if (rows.empty()) {
LOGD("EMPTY %d", width);
return false;
}
int nodeStart = 0;
glm::vec2 offset(0);
wordStart = 0;
_offsets.clear();
offset.y -= (rows.size() - 1) * layout.height();
maxWidth = 0;
for (auto& row : rows) {
if (row.width > maxWidth)
maxWidth = row.width;
}
int glyphCount = 0;
for (auto& g : layout.shapes())
if (!g.isSpace)
glyphCount++;
_offsets.reserve(glyphCount);
for (auto& row : rows) {
float lineWordSpacing = space;
if (block)
lineWordSpacing += row.ratio * (row.ratio < 0 ? shrink : stretch);
int offsetStart = _offsets.size();
// if (centered)
// offset.x = (maxWidth - row.width) / 2;
for (int i = nodeStart; i < row.breakpoint; i++) {
auto& box = nodes[i];
if (box.isGlue) {
if (box.width > 0)
offset.x += lineWordSpacing;
} else if (box.isBox && box.width > 0) {
for (uint32_t j = wordStart; j < box.b.id; j++) {
auto& c = layout.shapes()[j];
if (!c.isSpace) {
_offsets.emplace_back(offset + c.position);
offset.x += layout.advance(c);
}
}
wordStart = box.b.id;
}
}
if (centered) {
//log("row width %f %f", row.width, offset.x);
int offsetEnd = _offsets.size();
float justify = (maxWidth - offset.x) / 2;
for (int j = offsetStart; j < offsetEnd; j++)
_offsets[j].x += justify;
}
nodeStart = row.breakpoint + 1;
offset.x = 0;
offset.y += layout.height();
}
resultSize.x = maxWidth;
resultSize.y = rows.size() * layout.height();
return true;
}
}
| 30.165862 | 88 | 0.496076 | [
"vector"
] |
8f9267a40c41737465e486739cabb513a42eeaa7 | 1,787 | cpp | C++ | android-31/android/view/FocusFinder.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/view/FocusFinder.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/android/view/FocusFinder.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../JIntArray.hpp"
#include "../graphics/Rect.hpp"
#include "./View.hpp"
#include "./ViewGroup.hpp"
#include "./FocusFinder.hpp"
namespace android::view
{
// Fields
// QJniObject forward
FocusFinder::FocusFinder(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
android::view::FocusFinder FocusFinder::getInstance()
{
return callStaticObjectMethod(
"android.view.FocusFinder",
"getInstance",
"()Landroid/view/FocusFinder;"
);
}
android::view::View FocusFinder::findNearestTouchable(android::view::ViewGroup arg0, jint arg1, jint arg2, jint arg3, JIntArray arg4) const
{
return callObjectMethod(
"findNearestTouchable",
"(Landroid/view/ViewGroup;III[I)Landroid/view/View;",
arg0.object(),
arg1,
arg2,
arg3,
arg4.object<jintArray>()
);
}
android::view::View FocusFinder::findNextFocus(android::view::ViewGroup arg0, android::view::View arg1, jint arg2) const
{
return callObjectMethod(
"findNextFocus",
"(Landroid/view/ViewGroup;Landroid/view/View;I)Landroid/view/View;",
arg0.object(),
arg1.object(),
arg2
);
}
android::view::View FocusFinder::findNextFocusFromRect(android::view::ViewGroup arg0, android::graphics::Rect arg1, jint arg2) const
{
return callObjectMethod(
"findNextFocusFromRect",
"(Landroid/view/ViewGroup;Landroid/graphics/Rect;I)Landroid/view/View;",
arg0.object(),
arg1.object(),
arg2
);
}
android::view::View FocusFinder::findNextKeyboardNavigationCluster(android::view::View arg0, android::view::View arg1, jint arg2) const
{
return callObjectMethod(
"findNextKeyboardNavigationCluster",
"(Landroid/view/View;Landroid/view/View;I)Landroid/view/View;",
arg0.object(),
arg1.object(),
arg2
);
}
} // namespace android::view
| 25.898551 | 140 | 0.707331 | [
"object"
] |
8f93a94db37c2b90ad26e1ce352c72d9bea754db | 382 | cpp | C++ | ch03/ex3_42.cpp | regconfi/Cpp-Primer | 6e59f24f4c7f3be4f679b7d29084d9d859a463d9 | [
"CC0-1.0"
] | 46 | 2015-07-07T11:13:12.000Z | 2022-03-27T10:20:54.000Z | ch03/ex3_42.cpp | lafener/Cpp-Primer | 8cf1568f2d27622bce2d41493158f58527e5072f | [
"CC0-1.0"
] | 11 | 2015-03-10T12:52:06.000Z | 2015-04-20T12:24:00.000Z | ch03/ex3_42.cpp | lafener/Cpp-Primer | 8cf1568f2d27622bce2d41493158f58527e5072f | [
"CC0-1.0"
] | 65 | 2015-07-01T14:15:48.000Z | 2021-04-10T08:44:19.000Z | #include <iostream>
#include <vector>
using std::vector; using std::cout; using std::endl; using std::begin; using std::end;
int main()
{
vector<int> ivec{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int int_arr[10];
for (int* i = begin(int_arr); i != end(int_arr); ++i)
*i = ivec[i-begin(int_arr)];
for (auto i : int_arr) cout << i << " ";
cout << endl;
return 0;
}
| 20.105263 | 86 | 0.565445 | [
"vector"
] |
8fa1ccb98e3ce1c3969c6bc39740db046f76c7d2 | 2,426 | cc | C++ | examples/save_and_restore/main.cc | Liuweiming/tensorflow_c | 2bb512ba20bafc21e1d6a9940b93cde8f4080ab5 | [
"MIT"
] | 1 | 2021-03-02T06:29:23.000Z | 2021-03-02T06:29:23.000Z | examples/save_and_restore/main.cc | Liuweiming/tensorflow_c | 2bb512ba20bafc21e1d6a9940b93cde8f4080ab5 | [
"MIT"
] | null | null | null | examples/save_and_restore/main.cc | Liuweiming/tensorflow_c | 2bb512ba20bafc21e1d6a9940b93cde8f4080ab5 | [
"MIT"
] | null | null | null | //
// Created by sergio on 16/05/19.
//
#include <iomanip>
#include <numeric>
#include "model.h"
#include "tensor.h"
using namespace tf_cpp;
void load_and_run(const std::string &path, bool restore, bool training,
bool save) {
Model model(path);
// std::cout << "operations: -----------" << std::endl;
// for (auto &op : model.get_operations()) {
// std::cout << op << std::endl;
// }
// std::cout << "-------------------" << std::endl;
TF_Operation *init = TF_GraphOperationByName(model.get_graph(), "init");
TF_Operation *train = TF_GraphOperationByName(model.get_graph(), "train");
Tensor input(model.get_graph(), "input", {3, 1, 1}, TF_FLOAT);
Tensor label(model.get_graph(), "target", {3, 1, 1}, TF_FLOAT);
Tensor predict(model.get_graph(), "output", {3, 1, 1}, TF_FLOAT);
Tensor loss(model.get_graph(), "loss", {}, TF_FLOAT);
model.run_operation(init);
if (restore) {
model.restore("save.ckpt");
}
int bs = 3;
std::vector<float> train_inputs(bs);
std::vector<float> train_labels(bs);
for (int i = 0; i != bs; ++i) {
train_inputs[i] = i;
train_labels[i] = 0.5 * train_inputs[i] - 1;
}
for (int i = 0; i != 3; ++i) {
input.at<float>(i, 0, 0) = train_inputs[i];
label.at<float>(i, 0, 0) = train_labels[i];
}
std::cout << "before training" << std::endl;
model.run({&input}, {&predict});
for (int i = 0; i != 3; ++i) {
std::cout << predict.at<float>(i, 0, 0) << " ";
}
std::cout << std::endl;
if (training) {
for (int iter = 0; iter != 100; ++iter) {
std::cout << "iteration " << iter << std::endl;
model.run({&input, &label}, {&predict, &loss}, {train});
float train_loss = loss.at<float>();
std::cout << "loss: " << train_loss << std::endl;
for (float f : train_labels) {
std::cout << f << " ";
}
std::cout << std::endl;
for (int i = 0; i != 3; ++i) {
std::cout << predict.at<float>(i, 0, 0) << " ";
}
std::cout << std::endl;
}
}
if (save) {
model.save_graph("save.pb");
model.save("save.ckpt");
}
}
int main() {
load_and_run("graph.pb", false, true, true);
// save graph, restore variables.
load_and_run("graph.pb", true, false, false);
// load graph, restore variables.
load_and_run("save.pb", true, false, false);
}
| 28.541176 | 77 | 0.538747 | [
"vector",
"model"
] |
8fa38e9cdd41a22642d44abc498e8f7a332011dd | 3,061 | cpp | C++ | components/render/manager/sources/render_dynamic_texture_entity_storage.cpp | untgames/funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 7 | 2016-03-30T17:00:39.000Z | 2017-03-27T16:04:04.000Z | components/render/manager/sources/render_dynamic_texture_entity_storage.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2017-11-21T11:25:49.000Z | 2018-09-20T17:59:27.000Z | components/render/manager/sources/render_dynamic_texture_entity_storage.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2016-11-29T15:18:40.000Z | 2017-03-27T16:04:08.000Z | #include "shared.h"
using namespace render::manager;
/*
Описание реализации хранилища динамических текстур объекта
*/
typedef stl::hash_map<stl::hash_key<const char*>, DynamicTexturePtr> DynamicTextureMap;
struct DynamicTextureEntityStorage::Impl
{
DynamicTextureMap dynamic_textures; //карта динамических текстур
Log log; //протокол рендеринга
};
/*
Конструктор / деструктор
*/
DynamicTextureEntityStorage::DynamicTextureEntityStorage ()
: impl (new Impl)
{
}
DynamicTextureEntityStorage::~DynamicTextureEntityStorage ()
{
}
/*
Обновление текстур
*/
void DynamicTextureEntityStorage::Update (const FramePtr& frame)
{
try
{
if (!frame)
throw xtl::make_null_argument_exception ("", "frame");
for (DynamicTextureMap::iterator iter=impl->dynamic_textures.begin (), end=impl->dynamic_textures.end (); iter!=end; ++iter)
{
DynamicTexturePtr texture = iter->second;
try
{
texture->Update (frame);
}
catch (std::exception& e)
{
impl->log.Printf ("Error at update dynamic texture '%s': %s", texture->Name (), e.what ());
}
catch (...)
{
impl->log.Printf ("Unknown error at update dynamic texture '%s'", texture->Name ());
}
}
}
catch (xtl::exception& e)
{
e.touch ("render::manager::DynamicTextureEntityStorage::Update");
throw;
}
}
/*
Добавление / поиск динамических текстур
*/
void DynamicTextureEntityStorage::AddTexture (const char* name, const DynamicTexturePtr& dynamic_texture)
{
static const char* METHOD_NAME = "render::manager::DynamicTextureEntityStorage::AddTexture";
if (!name)
throw xtl::make_null_argument_exception (METHOD_NAME, "name");
if (!dynamic_texture)
throw xtl::make_null_argument_exception (METHOD_NAME, "dynamic_texture");
DynamicTextureMap::iterator iter = impl->dynamic_textures.find (name);
if (iter != impl->dynamic_textures.end ())
throw xtl::make_argument_exception (METHOD_NAME, "name", name, "Dynamic texture has already registered for this entity");
impl->dynamic_textures.insert_pair (name, dynamic_texture);
}
DynamicTexturePtr DynamicTextureEntityStorage::FindTexture (const char* name)
{
if (!name)
return DynamicTexturePtr ();
DynamicTextureMap::iterator iter = impl->dynamic_textures.find (name);
if (iter == impl->dynamic_textures.end ())
return DynamicTexturePtr ();
return iter->second;
}
/*
Сброс неиспользуемых ресурсов
*/
void DynamicTextureEntityStorage::FlushUnusedTextures ()
{
for (DynamicTextureMap::iterator iter=impl->dynamic_textures.begin (), end=impl->dynamic_textures.end (); iter!=end;)
if (iter->second->use_count () == 1)
{
DynamicTextureMap::iterator next = iter;
++next;
impl->dynamic_textures.erase (iter);
iter = next;
}
else ++iter;
}
| 25.508333 | 129 | 0.644887 | [
"render"
] |
8fa59801c2d80ac9ad8d4411617982141f7d7930 | 4,706 | cpp | C++ | src/eventdispatcher_epoll_p.cpp | qkdreyer/qt_eventdispatcher_epoll | eb0352878acd60176478bcfb6b5a8abdca6239de | [
"MIT"
] | 37 | 2015-06-21T07:16:39.000Z | 2021-06-10T18:23:17.000Z | src/epoll/eventdispatcher_epoll_p.cpp | zx1239856/libserver | 8a72b8467c703b023e0703f74697e2d47d22757c | [
"MIT"
] | 3 | 2015-10-15T13:22:22.000Z | 2016-11-29T18:51:29.000Z | src/epoll/eventdispatcher_epoll_p.cpp | zx1239856/libserver | 8a72b8467c703b023e0703f74697e2d47d22757c | [
"MIT"
] | 17 | 2015-12-18T05:12:52.000Z | 2020-06-22T10:25:23.000Z | #include <QtCore/QCoreApplication>
#include <unistd.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <stdlib.h>
#include <errno.h>
#include "eventdispatcher_epoll.h"
#include "eventdispatcher_epoll_p.h"
#include "qt4compat.h"
EventDispatcherEPollPrivate::EventDispatcherEPollPrivate(EventDispatcherEPoll* const q)
: q_ptr(q),
m_epoll_fd(-1), m_event_fd(-1),
m_interrupt(false),
#if QT_VERSION >= 0x040400
m_wakeups(),
#endif
m_handles(), m_notifiers(), m_timers(), m_zero_timers()
{
this->m_epoll_fd = epoll_create1(EPOLL_CLOEXEC);
if (Q_UNLIKELY(-1 == this->m_epoll_fd)) {
qErrnoWarning("epoll_create1() failed");
abort();
}
this->m_event_fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
if (Q_UNLIKELY(-1 == this->m_event_fd)) {
qErrnoWarning("eventfd() failed");
abort();
}
struct epoll_event e;
e.events = EPOLLIN;
e.data.fd = this->m_event_fd;
if (Q_UNLIKELY(-1 == epoll_ctl(this->m_epoll_fd, EPOLL_CTL_ADD, this->m_event_fd, &e))) {
qErrnoWarning("%s: epoll_ctl() failed", Q_FUNC_INFO);
}
}
EventDispatcherEPollPrivate::~EventDispatcherEPollPrivate(void)
{
close(this->m_event_fd);
close(this->m_epoll_fd);
HandleHash::Iterator it = this->m_handles.begin();
while (it != this->m_handles.end()) {
delete it.value();
++it;
}
}
bool EventDispatcherEPollPrivate::processEvents(QEventLoop::ProcessEventsFlags flags)
{
Q_Q(EventDispatcherEPoll);
const bool exclude_notifiers = (flags & QEventLoop::ExcludeSocketNotifiers);
const bool exclude_timers = (flags & QEventLoop::X11ExcludeTimers);
exclude_notifiers && this->disableSocketNotifiers(true);
exclude_timers && this->disableTimers(true);
this->m_interrupt = false;
Q_EMIT q->awake();
bool result = q->hasPendingEvents();
#if QT_VERSION < 0x040500
QCoreApplication::sendPostedEvents(0, (flags & QEventLoop::DeferredDeletion) ? -1 : 0);
#else
QCoreApplication::sendPostedEvents();
#endif
bool can_wait =
!this->m_interrupt
&& (flags & QEventLoop::WaitForMoreEvents)
&& !result
;
int n_events = 0;
if (!this->m_interrupt) {
int timeout = 0;
if (!exclude_timers && this->m_zero_timers.size() > 0) {
QList<int> ids = this->m_zero_timers.keys();
for (int i=0; i<ids.size(); ++i) {
int tid = ids.at(i);
ZeroTimerHash::Iterator it = this->m_zero_timers.find(tid);
if (it != this->m_zero_timers.end()) {
ZeroTimer& data = it.value();
if (data.active) {
data.active = false;
QTimerEvent event(tid);
QCoreApplication::sendEvent(data.object, &event);
result = true;
it = this->m_zero_timers.find(tid);
if (it != this->m_zero_timers.end()) {
ZeroTimer& data = it.value();
if (!data.active) {
data.active = true;
}
}
}
}
}
}
if (can_wait && !result) {
Q_EMIT q->aboutToBlock();
timeout = -1;
}
struct epoll_event events[1024];
do {
n_events = epoll_wait(this->m_epoll_fd, events, 1024, timeout);
} while (Q_UNLIKELY(-1 == n_events && errno == EINTR));
for (int i=0; i<n_events; ++i) {
struct epoll_event& e = events[i];
int fd = e.data.fd;
if (fd == this->m_event_fd) {
if (Q_LIKELY(e.events & EPOLLIN)) {
this->wake_up_handler();
}
}
else {
HandleHash::ConstIterator it = this->m_handles.find(fd);
if (Q_LIKELY(it != this->m_handles.constEnd())) {
HandleData* data = it.value();
switch (data->type) {
case htSocketNotifier:
EventDispatcherEPollPrivate::socket_notifier_callback(data->sni, e.events);
break;
case htTimer:
this->timer_callback(data->ti);
break;
default:
Q_UNREACHABLE();
}
}
}
}
}
exclude_notifiers && this->disableSocketNotifiers(false);
exclude_timers && this->disableTimers(false);
return result || n_events > 0;
}
void EventDispatcherEPollPrivate::wake_up_handler(void)
{
eventfd_t value;
int res;
do {
res = eventfd_read(this->m_event_fd, &value);
} while (Q_UNLIKELY(-1 == res && EINTR == errno));
if (Q_UNLIKELY(-1 == res)) {
qErrnoWarning("%s: eventfd_read() failed", Q_FUNC_INFO);
}
#if QT_VERSION >= 0x040400
if (Q_UNLIKELY(!this->m_wakeups.testAndSetRelease(1, 0))) {
qCritical("%s: internal error, testAndSetRelease(1, 0) failed!", Q_FUNC_INFO);
}
#endif
}
void EventDispatcherEPollPrivate::wakeup(void)
{
#if QT_VERSION >= 0x040400
if (this->m_wakeups.testAndSetAcquire(0, 1))
#endif
{
const eventfd_t value = 1;
int res;
do {
res = eventfd_write(this->m_event_fd, value);
} while (Q_UNLIKELY(-1 == res && EINTR == errno));
if (Q_UNLIKELY(-1 == res)) {
qErrnoWarning("%s: eventfd_write() failed", Q_FUNC_INFO);
}
}
}
| 24.38342 | 90 | 0.659584 | [
"object"
] |
8fac0e15e26e1c51d468d2659fac6bb0f87c6370 | 10,178 | cpp | C++ | src/GameApp.cpp | PSP-Archive/POLYGUNSCROLLINGUARS | 042e70116a10a313a0b3de07630fd1d2b9c363c4 | [
"BSD-3-Clause"
] | null | null | null | src/GameApp.cpp | PSP-Archive/POLYGUNSCROLLINGUARS | 042e70116a10a313a0b3de07630fd1d2b9c363c4 | [
"BSD-3-Clause"
] | null | null | null | src/GameApp.cpp | PSP-Archive/POLYGUNSCROLLINGUARS | 042e70116a10a313a0b3de07630fd1d2b9c363c4 | [
"BSD-3-Clause"
] | null | null | null | //-------------------------------------------------------------------------------------
//
// JGE++ is a hardware accelerated 2D game SDK for PSP/Windows.
//
// Licensed under the BSD license, see LICENSE in JGE root for details.
//
// Copyright (c) 2007 James Hui (a.k.a. Dr.Watson) <jhkhui@gmail.com>
//
//-------------------------------------------------------------------------------------
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <JAssert.h>
#include <JGE.h>
#include <JRenderer.h>
#include <JLBFont.h>
#include <JSprite.h>
#include <JFileSystem.h>
#include "GameApp.h"
//antes de leer los comentarios de este file se recomeienda leer detalladamente los comentarios den las librerias incluidas en este SRC que son las siuientes...
//como dato las librerias son aquellos archivos cuya extencion es h.
//favor de prestar especial atencion a la libreria stars.h ya que es la mas documentada y donde se explican la mayoria de los fragmentos de codigo.
#include "particles.h"//incluimos la libreria que contiene definiciones de clases particulas.
#include "nave.h"//incluimos la libreria que contiene definiciones de clases naves.
#include "star.h"//incluimos la libreria que contiene definiciones de clases estrellas.
#define PSPW 480//definimos resolucin del psp
#define PSPH 272
//instanciamos las clases para tener accesos asus propiedades y metodos.
naveHero heroPlayer1;
//naveHero heroPlayer2; //si asi lo quisieramos podriamos tener 2 o mas heroes en pantalla... imagina un ad-hock o simplemente uno controla 1 nave son el pad y otro con los botones.. o mejor ahun: naves auxiliaras con AI..
//todo es cuestion de imaginacion y creatividad.. y coco.
enemySyst enemigos;
particlesys particles;
starSyst stars;
//-------------------------------------------------------------------------------------
// Constructor. Variables can be initialized here.
//
//-------------------------------------------------------------------------------------
GameApp::GameApp()
{
GAMEPUSED_BY_SYSYTEM=false;
}
//-------------------------------------------------------------------------------------
// Destructor.
//
//-------------------------------------------------------------------------------------
GameApp::~GameApp()
{
}
//-------------------------------------------------------------------------------------
// This is the init callback function. You should load and create your in-game
// resources here.
//
//-------------------------------------------------------------------------------------
void GameApp::Create()
{
//inicialisamos la semmilla random.
srand( (unsigned)JGE::GetInstance()->GetDelta());//generamos la semilla del random.
//inicialisamos nuestros controladores de clases.
heroPlayer1.init();
enemigos.init();
particles.init();
stars.init();
}
//-------------------------------------------------------------------------------------
// This is the clean up callback function. You should delete all your in-game
// resources, for example texture and quads, here.
//
//-------------------------------------------------------------------------------------
void GameApp::Destroy()
{
}
//-------------------------------------------------------------------------------------
// This is the update callback function and is called at each update frame
// before rendering. You should update the game logic here.
//
//-------------------------------------------------------------------------------------
void GameApp::Update()
{
if(GAMEPUSED_BY_SYSYTEM){return;}
JGE* engine = JGE::GetInstance();
// do a screen shot when the TRIANGLE button is pressed
if (engine->GetButtonClick(PSP_CTRL_TRIANGLE))
{
char s[80];
// save screen shot to root of Memory Stick
sprintf(s, "ms0:/screenshot.png");
JRenderer::GetInstance()->ScreenShot(s);
}
// exit when the CROSS button is pressed
if (engine->GetButtonClick(PSP_CTRL_RTRIGGER))
{
engine->End();
return;
}
//if (engine->GetButtonClick(PSP_CTRL_CROSS))
//{
// heroPlayer1.bullets.addbullet(heroPlayer1.x,heroPlayer1.y-20,0,-6);//establecemos las cordenadas para una bala y su velocidad.
//}
float dt = engine->GetDelta(); // Get time elapsed since last update.
//
// Your updating code here...
//
#ifdef WIN32
dt=1; // caundo compilamos a win no hace falta controlar el tiempo..
heroPlayer1.shotingTimeElapsed++;
#else
dt*=50; // esta valor determina el lag que meteremos en el psp para relentizar los codigos de update.
heroPlayer1.shotingTimeElapsed+=dt;//se actualiza la pausa en los disparos.
#endif
//controles de la nave..
if (engine->GetButtonState(PSP_CTRL_LEFT))
{
heroPlayer1.dx-=0.5*dt;
}
if (engine->GetButtonState(PSP_CTRL_RIGHT))
{
heroPlayer1.dx+=0.5*dt;
}
if (engine->GetButtonState(PSP_CTRL_CROSS)) //monitoreo del disparador
{
if(heroPlayer1.shotingTimeElapsed>heroPlayer1.shotingPauseTime){
heroPlayer1.bullets.addbullet(heroPlayer1.x,heroPlayer1.y-10,0,-6);//establecemos las cordenadas para una bala y su velocidad.
heroPlayer1.shotingTimeElapsed = 0;
}
}
//buscar colisiones heroe con enemigos tipo 1.
for(int i =0;i<maxEneTp1;i++){
if(collide(heroPlayer1.x,heroPlayer1.y,heroPlayer1.img->mHotSpotX/2,enemigos.enemigosTP1[i].x,enemigos.enemigosTP1[i].y,enemigos.imgEnemigosTP1->mHotSpotX/2)){
particles.createExplo(heroPlayer1.x,heroPlayer1.y,ARGB(255,rand()%255,rand()%255,rand()%255),100,30);
particles.createExplo(enemigos.enemigosTP1[i].x,enemigos.enemigosTP1[i].y,ARGB(255,rand()%255,rand()%255,rand()%255),20);
enemigos.enemigosTP1[i].regen();
heroPlayer1.reset();
}
//buscar colisiones balas del heroe con enemigos tipo 1.
for(int ii=0;ii<heroPlayer1.bullets.bulletlist.size();ii++){
if(collide(heroPlayer1.bullets.bulletlist[ii]->x,heroPlayer1.bullets.bulletlist[ii]->y,heroPlayer1.bullets.img->mHotSpotX/2,enemigos.enemigosTP1[i].x,enemigos.enemigosTP1[i].y,enemigos.imgEnemigosTP1->mHotSpotX/2)){
particles.createExplo(heroPlayer1.bullets.bulletlist[ii]->x,heroPlayer1.bullets.bulletlist[ii]->y,ARGB(255,255,150,0),20);
particles.createExplo(enemigos.enemigosTP1[i].x,enemigos.enemigosTP1[i].y,ARGB(255,rand()%255,rand()%255,rand()%255),20);
heroPlayer1.bullets.bulletlist.erase(heroPlayer1.bullets.bulletlist.begin()+ii);
enemigos.enemigosTP1[i].regen();
}
}
}
//buscar colisiones heroe con enemigos tipo 1.
for(int i =0;i<maxEneTp2;i++){
if(collide(heroPlayer1.x,heroPlayer1.y,heroPlayer1.img->mHotSpotX/2,enemigos.enemigosTP2[i].x,enemigos.enemigosTP2[i].y,enemigos.imgEnemigosTP2->mHotSpotX/2)){
particles.createExplo(heroPlayer1.x,heroPlayer1.y,ARGB(255,rand()%255,rand()%255,rand()%255),100,30);
particles.createExplo(enemigos.enemigosTP2[i].x,enemigos.enemigosTP2[i].y,ARGB(255,rand()%255,rand()%255,rand()%255),20);
enemigos.enemigosTP2[i].regen();
heroPlayer1.reset();
}
//buscar colisiones balas del heroe con enemigos tipo 2.
for(int ii=0;ii<heroPlayer1.bullets.bulletlist.size();ii++){
if(collide(heroPlayer1.bullets.bulletlist[ii]->x,heroPlayer1.bullets.bulletlist[ii]->y,heroPlayer1.bullets.img->mHotSpotX/2,enemigos.enemigosTP2[i].x,enemigos.enemigosTP2[i].y,enemigos.imgEnemigosTP2->mHotSpotX/2)){
particles.createExplo(heroPlayer1.bullets.bulletlist[ii]->x,heroPlayer1.bullets.bulletlist[ii]->y,ARGB(255,255,150,0),20);
particles.createExplo(enemigos.enemigosTP2[i].x,enemigos.enemigosTP2[i].y,ARGB(255,rand()%255,rand()%255,rand()%255),20);
heroPlayer1.bullets.bulletlist.erase(heroPlayer1.bullets.bulletlist.begin()+ii);
enemigos.enemigosTP2[i].regen();
}
}
}
//todas nuestras funciones de update deberantener como parametro dt. para tener control del tiempo.
heroPlayer1.update(dt);
heroPlayer1.bullets.update(dt);
enemigos.update(dt,heroPlayer1.x,heroPlayer1.y);
particles.update(dt);
//particulas para la cola del heroe.
if(particles.mTimer==0)particles.newparticle(heroPlayer1.x,heroPlayer1.y+10,4,3.1416+(((rand()%200)-100)*0.002),ARGB(255,0,100,255));
stars.update(dt);
}
//-------------------------------------------------------------------------------------
// All rendering operations should be done in Render() only.
//
//-------------------------------------------------------------------------------------
void GameApp::Render()
{
if(GAMEPUSED_BY_SYSYTEM){return;}
// get JRenderer instance
JRenderer* renderer = JRenderer::GetInstance();
// clear screen to black
//renderer->ClearScreen(ARGB(0,0,0,0));
//
// Your rendering code here...
//
//poner en modo blend normal
renderer->SetTexBlend(BLEND_SRC_ALPHA, BLEND_ONE_MINUS_SRC_ALPHA);
renderer->FillRect(0,0,PSPW,PSPH,ARGB(200,0,0,0));
stars.render();//renderisamos lasestrellas primero pues son las que deben estar en el plano mas bajo.
//poner en modo lightblend para que brillen..
renderer->SetTexBlend(BLEND_SRC_ALPHA, BLEND_ONE);
heroPlayer1.render();//dibujar la nave del heroe
heroPlayer1.bullets.render();//dibujar las bajas del heroe
enemigos.render();
particles.render();
}
//-------------------------------------------------------------------------------------
// This function is called when the system wants to pause the game. You can set a flag
// here to stop the update loop and audio playback.
//
//-------------------------------------------------------------------------------------
void GameApp::Pause()
{
GAMEPUSED_BY_SYSYTEM=true;
}
//-------------------------------------------------------------------------------------
// This function is called when the game returns from the pause state.
//
//-------------------------------------------------------------------------------------
void GameApp::Resume()
{
GAMEPUSED_BY_SYSYTEM=false;
}
int GameApp::collide(int Hotx1,int Hoty1,int radius1,int Hotx2,int Hoty2, int radius2)//funcion para detectar colicion cuadrada..
//se recomienda utilizar colicion cuadrada ya que una colision radial consume mas tiempo...
{
int Area1 = radius1*2;
int Area2 = radius2*2;
Hotx1 -=radius1;
Hoty1 -=radius1;
Hotx2 -=radius2;
Hoty2 -=radius2;
if(((Hotx1+Area1)>Hotx2)&&((Hoty1+Area1)>Hoty2)&&((Hotx2+Area2)>Hotx1)&&((Hoty2+Area2)>Hoty1))
return 1;
return 0;
} | 37.145985 | 222 | 0.6236 | [
"render"
] |
8fb1aad443507aff7f61e10bdd8ab930a180150b | 6,686 | hpp | C++ | Programming Guide/Headers/Siv3D/MultiPolygon.hpp | Reputeless/Siv3D-Reference | d58e92885241d11612007fb9187ce0289a7ee9cb | [
"MIT"
] | 38 | 2016-01-14T13:51:13.000Z | 2021-12-29T01:49:30.000Z | Programming Guide/Headers/Siv3D/MultiPolygon.hpp | Reputeless/Siv3D-Reference | d58e92885241d11612007fb9187ce0289a7ee9cb | [
"MIT"
] | null | null | null | Programming Guide/Headers/Siv3D/MultiPolygon.hpp | Reputeless/Siv3D-Reference | d58e92885241d11612007fb9187ce0289a7ee9cb | [
"MIT"
] | 16 | 2016-01-15T11:07:51.000Z | 2021-12-29T01:49:37.000Z | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (C) 2008-2016 Ryo Suzuki
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include "Polygon.hpp"
namespace s3d
{
/// <summary>
/// 多角形の集合
/// </summary>
class MultiPolygon
{
private:
struct MultiPolygonDetail;
std::shared_ptr<MultiPolygonDetail> m_detail;
MultiPolygon(MultiPolygonDetail&& detail);
public:
using iterator = Array<Polygon>::iterator;
using const_iterator = Array<Polygon>::const_iterator;
using reverse_iterator = Array<Polygon>::reverse_iterator;
using const_reverse_iterator = Array<Polygon>::const_reverse_iterator;
MultiPolygon();
explicit MultiPolygon(const String& pts)
{
std::wistringstream(pts.str()) >> *this;
}
explicit MultiPolygon(const Array<Polygon>& polygons);
explicit MultiPolygon(Array<Polygon>&& polygons);
explicit operator bool() const { return !isEmpty; }
Property_Get(bool, isEmpty) const;
MultiPolygon clone() const;
MultiPolygon operator + (const Vec2& v) const { return movedBy(v); }
MultiPolygon operator - (const Vec2& v) const { return movedBy(-v); }
MultiPolygon movedBy(double x, double y) const { return movedBy({ x, y }); }
MultiPolygon movedBy(const Vec2& v) const;
MultiPolygon& moveBy(double x, double y) { return moveBy({ x, y }); }
MultiPolygon& moveBy(const Vec2& v);
MultiPolygon rotated(double angle) const { return rotatedAt({ 0, 0 }, angle); }
MultiPolygon rotatedAt(const Vec2& pos, double angle) const;
double area() const;
double perimeter() const;
// 未実装
//Vec2 centroid() const;
Property_Get(size_t, num_polygons) const;
const Array<Polygon>& polygons() const;
const Polygon& polygon(size_t index) const;
Property_Get(RectF, boundingRect) const;
// 未実装
//Polygon computeConvexHull() const;
MultiPolygon simplified(double maxDistance = 2.0) const;
const_iterator begin() const;
const_iterator end() const;
reverse_iterator rbegin();
reverse_iterator rend();
const_reverse_iterator rbegin() const;
const_reverse_iterator rend() const;
const_iterator cbegin() const;
const_iterator cend() const;
const_reverse_iterator crbegin() const;
const_reverse_iterator crend() const;
template <class Shape>
bool intersects(const Shape& shape) const
{
return Geometry2D::Intersect(*this, shape);
}
template <class Shape>
bool contains(const Shape& shape) const
{
return Geometry2D::Within(shape, *this);
}
/// <summary>
/// 図形が左クリックされたかを示します。
/// </summary>
Property_Get(bool, leftClicked) const;
/// <summary>
/// 図形がマウスの左ボタンで押されているかを示します。
/// </summary>
Property_Get(bool, leftPressed) const;
/// <summary>
/// 図形の上でマウスの左ボタンが離されたかを示します。
/// </summary>
Property_Get(bool, leftReleased) const;
/// <summary>
/// 図形が右クリックされたかを示します。
/// </summary>
Property_Get(bool, rightClicked) const;
/// <summary>
/// 図形がマウスの右ボタンで押されているかを示します。
/// </summary>
Property_Get(bool, rightPressed) const;
/// <summary>
/// 図形の上でマウスの右ボタンが離されたかを示します。
/// </summary>
Property_Get(bool, rightReleased) const;
/// <summary>
/// 図形の上にマウスカーソルがあるかを示します。
/// </summary>
Property_Get(bool, mouseOver) const;
void write(Image& image, const Color& color = Palette::Black) const;
void write(Image& image, int x, int y, const Color& color = Palette::Black) const;
void write(Image& image, const Point& pos, const Color& color = Palette::Black) const;
void overwrite(Image& image, const Color& color = Palette::Black) const;
void overwrite(Image& image, int x, int y, const Color& color = Palette::Black) const;
void overwrite(Image& image, const Point& pos, const Color& color = Palette::Black) const;
void writeFrame(Image& image, const Color& color = Palette::Black) const;
void writeFrame(Image& image, int thickness, const Color& color = Palette::Black) const;
void writeFrame(Image& image, int x, int y, int thickness = 1, const Color& color = Palette::Black) const;
void writeFrame(Image& image, const Point& pos, int thickness = 1, const Color& color = Palette::Black) const;
void overwriteFrame(Image& image, const Color& color = Palette::Black) const;
void overwriteFrame(Image& image, int thickness, const Color& color = Palette::Black) const;
void overwriteFrame(Image& image, int x, int y, int thickness = 1, const Color& color = Palette::Black) const;
void overwriteFrame(Image& image, const Point& pos, int thickness = 1, const Color& color = Palette::Black) const;
void draw(const Color& color = Palette::White) const;
void draw(double x, double y, const Color& color = Palette::White) const;
void draw(const Vec2& pos, const Color& color = Palette::White) const;
void drawFrame(double thickness = 1.0, const Color& color = Palette::White) const;
void drawFrame(double x, double y, double thickness = 1.0, const Color& color = Palette::White) const;
void drawFrame(const Vec2& pos, double thickness = 1.0, const Color& color = Palette::White) const;
void drawWireframe(double thickness = 1.0, const Color& color = Palette::White) const;
void drawWireframe(double x, double y, double thickness = 1.0, const Color& color = Palette::White) const;
void drawWireframe(const Vec2& pos, double thickness = 1.0, const Color& color = Palette::White) const;
const MultiPolygonDetail* _detail() const;
};
template <class CharType>
inline std::basic_ostream<CharType>& operator << (std::basic_ostream<CharType>& os, const MultiPolygon& multiPolygon)
{
os << CharType('(');
bool b = false;
for (const auto& polygon : multiPolygon)
{
if (std::exchange(b, true))
{
os << CharType(',');
}
os << polygon;
}
return os << CharType(')');
}
template <class CharType>
inline std::basic_istream<CharType>& operator >> (std::basic_istream<CharType>& is, MultiPolygon& multiPolygon)
{
CharType unused;
is >> unused;
Array<Polygon> polygons;
do
{
Polygon polygon;
is >> polygon;
is >> unused;
polygons.push_back(polygon);
}
while (is && unused != (')'));
multiPolygon = MultiPolygon(polygons);
return is;
}
namespace Geometry2D
{
/// <summary>
/// 多角形の集合を太らせます。
/// </summary>
/// <param name="polygon">
/// 太らせる多角形の集合
/// </param>
/// <param name="distance">
/// 太らせる幅 [>0.0]
/// </param>
/// <param name="round">
/// 角を丸くするかのフラグ
/// </param>
/// <returns>
/// 太らせた多角形の集合の MultiPolygon
/// </returns>
MultiPolygon Buffer(const MultiPolygon& polygon, double distance, bool round = true);
}
}
| 24.671587 | 118 | 0.676787 | [
"shape"
] |
8fb2072a4c8192f0b584dd691251fc30fb079a87 | 12,132 | cpp | C++ | src/optimize.cpp | vardigroup/FourierSATPlus | 9a1b2461460cea32a900c8c36ac6ac8050479122 | [
"MIT"
] | null | null | null | src/optimize.cpp | vardigroup/FourierSATPlus | 9a1b2461460cea32a900c8c36ac6ac8050479122 | [
"MIT"
] | 1 | 2021-06-18T17:37:09.000Z | 2021-06-18T17:37:09.000Z | src/optimize.cpp | vardigroup/FourierSATPlus | 9a1b2461460cea32a900c8c36ac6ac8050479122 | [
"MIT"
] | null | null | null | #include <dlib/optimization.h>
#include <iostream>
#include "../include/optimize.h"
#include <random>
#include <algorithm>
#include <stdlib.h>
#define CHANGE_WEIGHTS
#include "omp.h"
using namespace std;
using namespace dlib;
static double sum(std::vector<double> *v){
double s = 0;
for (int i = 0; i < v->size(); i++){
s += (*v)[i];
}
return s;
}
Optimizer::Optimizer(){
}
Optimizer::Optimizer(int n, BDD *bdd, std::string name, Parameter *param){
srand(time(NULL));
this->bdd = bdd;
this->num_of_vars = n;
this->solved_flag = 0;
this->x = new std::vector<double>;
this->unsat_clauses = new std::vector<int>;
for(int i=0; i< n; i++){
double xi = (double) std::rand();
this->x->push_back( 1 - 2 * (xi/(double)RAND_MAX));
}
this->optimizer_name = name;
this->param = param;
this->number_of_trials_this_start = 0;
}
double Optimizer::fval_for_optimizer(const column_vector& m)
{
std::vector<double> x;
for (int i=0; i < this->bdd->num_of_vars; i++){
x.push_back((double)m(i));
}
return this->bdd->fval(&x);
}
const column_vector Optimizer::grad_for_optimizer (const column_vector& m)
{
std::vector<double> *grad;
std::vector<double> x;
for (int i=0; i < this->bdd->num_of_vars; i++){
x.push_back((double)m(i));
}
column_vector res(this->bdd->num_of_vars);
grad = this->bdd->grad(&x);
for (int i=0; i < this->bdd->num_of_vars; i++){
res(i) = (*grad)[i];
}
return res;
}
double fval_for_optimizer_nlopt(const std::vector<double> &x, std::vector<double> &grad, void *data){
Optimizer *opt = (Optimizer *) data;
std::vector<double> *grad_p = opt->bdd->grad(&x);
for ( int i = 0; i<grad.size(); i++) grad[i] = (*grad_p)[i];
return opt->bdd->fval(&x);
}
double fval_for_optimizer_nlopt_gdfree(const std::vector<double> &x, std::vector<double> &grad, void *data){
Optimizer *opt = (Optimizer *) data;
return opt->bdd->fval(&x);
}
void Optimizer::update_weights(){
for ( int i = 0; i < this->unsat_clauses->size(); i++){
(*this->bdd->clause_weights) [ (*this->unsat_clauses)[i] ] *= this->param->multiplier;
}
this->bdd->sum_of_clause_weights = sum(this->bdd->clause_weights);
}
static std::vector<double> *rounding( column_vector *m, int n){
std::vector<double> *res = new std::vector<double>;
for ( int i = 0; i < n; i++){
if ( (*m)(i) > 0 )
res->push_back(1);
else res->push_back(-1);
}
return res;
}
static std::vector<double> *rounding( std::vector<double> *x, int n){
std::vector<double> *res = new std::vector<double>;
for ( int i = 0; i < n; i++){
if ( (*x)[i] > 0 )
res->push_back(1);
else res->push_back(-1);
}
return res;
}
static void random_restart(std::vector<double> *x){
int n = x->size();
for(int i=0; i< n; i++){
double xi = (double) std::rand();
(*x)[i] = 1 - 2 * (xi/(double)RAND_MAX);
}
}
static int count(std::vector<double> *x){
int count = 0;
for( int i =0; i< x->size(); i++){
if ((*x)[i] < 0) count++;
}
return count;
}
static int count(column_vector &m, int n){
int count = 0;
for( int i =0; i< n; i++){
if (m(i) < 0) count++;
}
return count;
}
static void print_vector(std::vector<double> *x){
int n = x->size();
for(int i=0; i< n; i++){
std::cout<<(*x)[i]<<",";
}
std::cout<<std::endl;
}
static void print_solution(std::vector<double> *x){
int n = x->size();
std::cout<<"v ";
for(int i=0; i< n; i++){
if ((*x)[i] < 0){
std::cout<<i+1<<" ";
}
else
std::cout<<-(i+1)<<" ";
}
std::cout<<std::endl;
}
static void print_solution(column_vector &m, int n){
std::cout<<"v ";
for(int i=0; i< n; i++){
if (m(i) < 0){
std::cout<<i+1<<" ";
}
else
std::cout<<-(i+1)<<" ";
}
std::cout<<std::endl;
}
double Optimizer::minimize()
{
random_restart(this->x);
int n = this->num_of_vars;
static int min_unsat_for_maxsat = 1e9;
double tol = 1e-40;
while(1){
if ( number_of_trials_this_start >= this->param->max_trial_per_start ){
// if (this->param->verbose) std::cout<<"c Random restart"<<std::endl;
random_restart(this->x);
this->bdd->restart_weights();
this->number_of_trials_this_start = 0;
}
this->number_of_trials_this_start ++;
double stop_val = this->bdd->sum_of_clause_weights;
column_vector starting_point(n);
std::vector<double> *x = new std::vector<double>(n);
for(int i = 0; i < n; i++){
(*x)[i] = (*this->x)[i];
starting_point(i) = (double) (*x)[i];
}
std::vector<double> *roundedx;
std::string package;
if (this->optimizer_name=="CG"){
if (this->param->verbose)
std::cout<<"c Solver: CG"<<std::endl;
package = "DLIB";
find_min_box_constrained(cg_search_strategy(),
objective_delta_stop_strategy(tol),
[this](const column_vector& a){ return this->fval_for_optimizer(a);},
[this](const column_vector& a){ return this->grad_for_optimizer(a);},
starting_point, -1.0, 1.0);
roundedx = rounding(&starting_point,n);
std::cout<<"c CG finds local maximum with value "<<-this->bdd->fval(roundedx)
<<". Goal: "<<this->bdd->sum_of_clause_weights<< std::endl;
}
else if (this->optimizer_name=="BFGS"){
if (this->param->verbose)
std::cout<<"c Solver: BFGS"<<std::endl;
package = "DLIB";
find_min_box_constrained(bfgs_search_strategy(),
objective_delta_stop_strategy(tol),
[this](const column_vector& a){ return this->fval_for_optimizer(a);},
[this](const column_vector& a){ return this->grad_for_optimizer(a);},
starting_point, -1.0, 1.0);
roundedx = rounding(&starting_point,n);
std::cout<<"c BFGS finds local maximum with value "<<-this->bdd->fval(roundedx)
<<". Goal: "<<this->bdd->sum_of_clause_weights<< std::endl;
}
else if ( this->optimizer_name=="SLSQP"){
if (this->param->verbose)
std::cout<<"c Solver: SLSQP"<<std::endl;
package = "NLOPT";
nlopt::opt opt(nlopt::LD_SLSQP, n);
std::vector<double> lb(n);
std::vector<double> ub(n);
for ( int i =0; i<n;i++){
lb[i] = -1;
ub[i] = 1;
}
opt.set_lower_bounds(lb);
opt.set_upper_bounds(ub);
opt.set_min_objective(fval_for_optimizer_nlopt, this);
opt.set_xtol_rel(tol);
opt.set_ftol_abs(tol);
double minf;
try{
nlopt::result result = opt.optimize(*x, minf);
std::cout << "c SLSQP founds local maximum with value"<< std::setprecision(10) << -minf
<<". Goal: "<<this->bdd->sum_of_clause_weights<< std::endl;
}
catch(std::exception &e) {
if (this->param->verbose)
std::cout << "c nlopt failed: " << e.what() << std::endl;
}
roundedx = rounding(x,n);
}
else if ( this->optimizer_name=="MMA"){
if (this->param->verbose)
std::cout<<"c Solver: MMA"<<std::endl;
package = "NLOPT";
// nlopt::opt opt(nlopt::LD_MMA, n);
nlopt::opt opt(nlopt::LD_CCSAQ, n);
std::vector<double> lb(n);
std::vector<double> ub(n);
for ( int i =0; i<n;i++){
lb[i] = -1;
ub[i] = 1;
}
opt.set_lower_bounds(lb);
opt.set_upper_bounds(ub);
opt.set_min_objective(fval_for_optimizer_nlopt, this);
opt.set_xtol_rel(tol);
opt.set_ftol_abs(tol);
double minf;
try{
nlopt::result result = opt.optimize(*x, minf);
std::cout << "c MMA finds local minimum with value "
<< std::setprecision(10) << -minf
<<". Goal: "<<this->bdd->sum_of_clause_weights<< std::endl;
}
catch(std::exception &e) {
if (this->param->verbose)
std::cout << "c nlopt failed: " << e.what() << std::endl;
}
roundedx = rounding(x,n);
}
else{ std::cout<<"c undefined optimizer: "<<this->optimizer_name<<std::endl; exit(0);}
int num_unsat_clause, unsat_weight;
this->bdd->verify_solution(roundedx,this->unsat_clauses, &num_unsat_clause, &unsat_weight);
//double fval = fval_for_optimizer(starting_point);
#ifdef CHANGE_WEIGHTS
this->update_weights();
#endif
if (this->param->ismaxsat && (!this->param->iswcnf)){
#pragma omp critical
{
if (num_unsat_clause < min_unsat_for_maxsat){
min_unsat_for_maxsat = num_unsat_clause;
}
std::cout<<"o "<<min_unsat_for_maxsat<<std::endl;
}
}
else if (this->param->ismaxsat && (this->param->iswcnf)){
#pragma omp critical
{
if ( (unsat_weight < this->param->wcnf_weight) && (num_unsat_clause < min_unsat_for_maxsat)){
min_unsat_for_maxsat = num_unsat_clause;
}
std::cout<<"o "<<min_unsat_for_maxsat<<std::endl;
}
}
else{
#pragma omp critical
{
if (num_unsat_clause < min_unsat_for_maxsat){
std::cout<<"o "<<num_unsat_clause<<std::endl;
min_unsat_for_maxsat = num_unsat_clause;
}
}
}
#pragma omp critical
{
if (num_unsat_clause<=this->param->n_violance_tolerance){
cout<<"c solved by "<<this->optimizer_name<<". trials: "<<this->number_of_trials_this_start<<std::endl;
cout<<"s SATISFIABLE "<<std::endl;
if ( package == "DLIB" ){
print_solution(starting_point,n);
}
else if ( package == "NLOPT"){
print_solution(x);
}
this->solved_flag = 1;
exit(0);
}
}
}
return 0;
}
Optimizer_Portfolio::Optimizer_Portfolio(){
}
Optimizer_Portfolio::Optimizer_Portfolio(int num_of_vars, BDD *original_bdd, Parameter *param){
this->num_of_vars = num_of_vars;
this->bdd = original_bdd;
this->param = param;
}
void Optimizer_Portfolio::solve(){
BDD bdd_group[this->param->ncores];
Optimizer optimizer_group[this->param->ncores];
std::vector<std::string> solvers{"CG","SLSQP","MMA","BFGS"};
if (this->param->solver != "PORTFOLIO"){
solvers.clear();
solvers.push_back(this->param->solver);
cout<<"solver: "<<this->param->solver<<endl;
}
for ( int i = 0; i < this->param->ncores; i++){
bdd_group[i] = BDD(this->bdd);
optimizer_group[i] = Optimizer(this->num_of_vars, &bdd_group[i], solvers[i % solvers.size()], this->param);
}
int num_trials = 0;
bool solved_flag = 0;
if (this->param->verbose)
cout<<"c ncores "<<this->param->ncores<<endl;
int nthreads = param->ncores;
#pragma omp parallel for num_threads(this->param->ncores)
for ( int i = 0; i < nthreads; i++){
int tid = omp_get_thread_num();
optimizer_group[i].minimize();
solved_flag |= optimizer_group[i].solved_flag;
}
cout<<"c number of trials: "<<num_trials<<endl;
}
| 33.888268 | 115 | 0.527366 | [
"vector"
] |
8fb472d628ef8590ceb3a201505189cbb5f39735 | 13,508 | hpp | C++ | include/Core/Castor3D/Scene/Scene.hpp | DragonJoker/Castor3D | ee0b02eeda70cd235a224be306539850e32195f6 | [
"MIT"
] | 245 | 2015-10-29T14:31:45.000Z | 2022-03-31T13:04:45.000Z | include/Core/Castor3D/Scene/Scene.hpp | DragonJoker/Castor3D | ee0b02eeda70cd235a224be306539850e32195f6 | [
"MIT"
] | 64 | 2016-03-11T19:45:05.000Z | 2022-03-31T23:58:33.000Z | include/Core/Castor3D/Scene/Scene.hpp | DragonJoker/Castor3D | ee0b02eeda70cd235a224be306539850e32195f6 | [
"MIT"
] | 11 | 2018-05-24T09:07:43.000Z | 2022-03-21T21:05:20.000Z | /*
See LICENSE file in root folder
*/
#ifndef ___C3D_SCENE_H___
#define ___C3D_SCENE_H___
#include "Castor3D/Overlay/OverlayModule.hpp"
#include "Castor3D/Render/GlobalIllumination/GlobalIlluminationModule.hpp"
#include "Castor3D/Render/EnvironmentMap/EnvironmentMapModule.hpp"
#include "Castor3D/Render/Node/RenderNodeModule.hpp"
#include "Castor3D/Render/ShadowMap/ShadowMapModule.hpp"
#include "Castor3D/Render/GlobalIllumination/VoxelConeTracing/VoxelSceneData.hpp"
#include "Castor3D/Scene/SceneModule.hpp"
#include "Castor3D/Scene/Animation/AnimationModule.hpp"
#include "Castor3D/Scene/Background/BackgroundModule.hpp"
#include "Castor3D/Scene/Light/LightModule.hpp"
#include "Castor3D/Scene/ParticleSystem/ParticleModule.hpp"
#include "Castor3D/Cache/AnimatedObjectGroupCache.hpp"
#include "Castor3D/Cache/BillboardCache.hpp"
#include "Castor3D/Cache/CacheView.hpp"
#include "Castor3D/Cache/GeometryCache.hpp"
#include "Castor3D/Cache/LightCache.hpp"
#include "Castor3D/Cache/MaterialCache.hpp"
#include "Castor3D/Cache/ObjectCache.hpp"
#include "Castor3D/Cache/OverlayCache.hpp"
#include "Castor3D/Cache/TargetCache.hpp"
#include "Castor3D/Scene/Fog.hpp"
#include "Castor3D/Scene/Shadow.hpp"
#include <CastorUtils/Data/TextWriter.hpp>
#include <CastorUtils/Design/Named.hpp>
#include <CastorUtils/Design/Signal.hpp>
#include <CastorUtils/Graphics/FontCache.hpp>
#include <CastorUtils/Graphics/ImageCache.hpp>
#include <CastorUtils/Graphics/RgbColour.hpp>
#include <CastorUtils/Log/Logger.hpp>
#include <CastorUtils/Multithreading/ThreadPool.hpp>
#include <RenderGraph/FrameGraphPrerequisites.hpp>
#pragma warning( push )
#pragma warning( disable:4365 )
#include <atomic>
#pragma warning( pop )
namespace castor3d
{
class Scene
: public std::enable_shared_from_this< Scene >
, public castor::OwnedBy< Engine >
, public castor::Named
{
public:
/**
*\~english
*\brief Constructor
*\param[in] name The scene name
*\param[in] engine The core engine
*\~french
*\brief Constructeur
*\param[in] name Le nom de la scène
*\param[in] engine Le moteur
*/
C3D_API Scene( castor::String const & name, Engine & engine );
/**
*\~english
*\brief Destructor
*\~french
*\brief Destructeur
*/
C3D_API ~Scene();
/**
*\~english
*\brief Initialises the scene
*\~french
*\brief Initialise la scène
*/
C3D_API void initialise();
/**
*\~english
*\brief Clears the maps, leaves the root nodes
*\~french
*\brief Vide les maps, laisse les noeuds pères
*/
C3D_API void cleanup();
/**
*\~english
*\brief Updates the scene before render.
*\~french
*\brief Met à jour la scène avant le rendu.
*/
C3D_API void update( CpuUpdater & updater );
/**
*\~english
*\brief Updates the scene device dependant stuff.
*\~french
*\brief Met à jour les objets de scène dépendant du device.
*/
C3D_API void update( GpuUpdater & updater );
/**
*\~english
*\brief Sets the background for the scene.
*\param[in] value The new value.
*\~french
*\brief Définit le fond de la scène.
*\param[in] value La nouvelle valeur.
*/
C3D_API void setBackground( SceneBackgroundSPtr value );
/**
*\~english
*\brief Imports a scene from an foreign file
*\param[in] fileName file to read from
*\param[in] importer The importer, which is in charge of loading the scene
*\return \p true if successful, false if not
*\~french
*\brief Importe une scène à partir d'un fichier
*\param[in] fileName L'adresse du fichier
*\param[in] importer L'importeur chargé de la récupération des données
*\return \p false si un problème quelconque a été rencontré
*/
C3D_API bool importExternal( castor::Path const & fileName
, SceneImporter & importer );
/**
*\~english
*\brief Merges the content of the given scene to this scene
*\param[in] scene The scene to merge into this one
*\~french
*\brief Intègre à cette scène le contenu de celle donnée
*\param[in] scene La scène à intégrer
*/
C3D_API void merge( SceneSPtr scene );
/**
*\~english
*\brief Retrieves the vertices count
*\return The value
*\~french
*\brief Récupère le nombre de sommets
*\return La valeur
*/
C3D_API uint32_t getVertexCount()const;
/**
*\~english
*\brief Retrieves the faces count
*\return The value
*\~french
*\brief Récupère le nombre de faces
*\return La valeur
*/
C3D_API uint32_t getFaceCount()const;
/**
*\~english
*\return The scene flags.
*\~french
*\return Les indicateurs de la scène.
*/
C3D_API SceneFlags getFlags()const;
/**
*\~english
*\return Tells if the scene has a shadow projecting light.
*\~french
*\return Dit si la scène a au moins une source lumineuse projetant des ombres.
*/
C3D_API bool hasShadows()const;
/**
*\~english
*\return Tells if the scene has a shadow projecting light of given type.
*\~french
*\return Dit si la scène a au moins une source lumineuse du type donné projetant des ombres.
*/
C3D_API bool hasShadows( LightType lightType )const;
/**
*\~english
*\return Creates a reflection map for given node.
*\param[in] node The scene node from which the reflection map is generated.
*\~french
*\return Crée une reflection map pour le noeud donné.
*\param[in] node Le noeud de scène depuis lequel la reflection map est générée.
*/
C3D_API void addEnvironmentMap( SceneNode & node );
/**
*\~english
*\return Creates a reflection map for given node.
*\param[in] node The scene node from which the reflection map is generated.
*\~french
*\return Crée une reflection map pour le noeud donné.
*\param[in] node Le noeud de scène depuis lequel la reflection map est générée.
*/
C3D_API void removeEnvironmentMap( SceneNode & node );
/**
*\~english
*\return Tells if there is a reflection map for given node.
*\param[in] node The scene node.
*\~french
*\return Dit s'il y a une reflection map pour le noeud donné.
*\param[in] node Le noeud de scène.
*/
C3D_API bool hasEnvironmentMap( SceneNode & node )const;
/**
*\~english
*\remarks Call hasEnvironmentMap before calling this function (since this one returns a reference to an existing EnvironmentMap).
*\return Retrieves the reflection map for given node.
*\param[in] node The scene node.
*\~french
*\remarks Appelez hasEnvironmentMap avant d'appeler cette fonction (celle-ci retournant une référence sur une EnvironmentMap existante)
*\return Récupère la reflection map pour le noeud donné.
*\param[in] node Le noeud de scène.
*/
C3D_API EnvironmentMap & getEnvironmentMap()const;
/**
*\~english
*\remarks Call hasEnvironmentMap before calling this function (since this one returns a reference to an existing EnvironmentMap).
*\return Retrieves the reflection map for given node.
*\param[in] node The scene node.
*\~french
*\remarks Appelez hasEnvironmentMap avant d'appeler cette fonction (celle-ci retournant une référence sur une EnvironmentMap existante)
*\return Récupère la reflection map pour le noeud donné.
*\param[in] node Le noeud de scène.
*/
C3D_API uint32_t getEnvironmentMapIndex( SceneNode const & node )const;
C3D_API AnimatedObjectSPtr addAnimatedTexture( TextureUnit & texture
, Pass & pass );
C3D_API void registerLight( Light & light );
C3D_API void unregisterLight( Light & light );
/**
*\~english
*\name
* Getters.
*\~french
*\name
* Accesseurs.
*/
/**@{*/
C3D_API PassTypeID getPassesType()const;
C3D_API castor::String getPassesName()const;
C3D_API bool needsGlobalIllumination()const;
C3D_API bool needsGlobalIllumination( LightType ltType
, GlobalIlluminationType giType )const;
C3D_API crg::SemaphoreWaitArray getRenderTargetsSemaphores()const;
C3D_API uint32_t getLpvGridSize()const;
castor::BoundingBox const & getBoundingBox()const
{
return m_boundingBox;
}
SceneBackgroundSPtr getBackground()const
{
return m_background;
}
castor::RgbColour const & getBackgroundColour()const
{
return m_backgroundColour;
}
SceneNodeSPtr getRootNode()const
{
return m_rootNode;
}
SceneNodeSPtr getCameraRootNode()const
{
return m_rootCameraNode;
}
SceneNodeSPtr getObjectRootNode()const
{
return m_rootObjectNode;
}
bool hasChanged()const
{
return m_changed;
}
castor::RgbColour const & getAmbientLight()const
{
return m_ambientLight;
}
Fog const & getFog()const
{
return m_fog;
}
Fog & getFog()
{
return m_fog;
}
FrameListener const & getListener()const
{
CU_Require( !m_listener.expired() );
return *m_listener.lock();
}
FrameListener & getListener()
{
CU_Require( !m_listener.expired() );
return *m_listener.lock();
}
bool isInitialised()const
{
return m_initialised;
}
bool needsSubsurfaceScattering()const
{
return m_needsSubsurfaceScattering;
}
bool hasOpaqueObjects()const
{
return m_hasOpaqueObjects;
}
bool hasTransparentObjects()const
{
return m_hasTransparentObjects;
}
uint32_t getDirectionalShadowCascades()const
{
return m_directionalShadowCascades;
}
float getLpvIndirectAttenuation()const
{
return m_lpvIndirectAttenuation;
}
VoxelSceneData const & getVoxelConeTracingConfig()const
{
return m_voxelConfig;
}
VoxelSceneData & getVoxelConeTracingConfig()
{
return m_voxelConfig;
}
SceneRenderNodes & getRenderNodes()const
{
return *m_renderNodes;
}
LightFactory & getLightsFactory()const
{
return *m_lightFactory;
}
/**@}*/
/**
*\~english
*name
* Mutators.
*\~french
*name
* Mutateurs.
*/
/**@{*/
C3D_API void setDirectionalShadowCascades( uint32_t value );
C3D_API void setLpvIndirectAttenuation( float value );
C3D_API void setPassesType( PassTypeID value );
void setBackgroundColour( castor::RgbColour const & value )
{
m_backgroundColour = value;
}
void setChanged()
{
m_changed = true;
onChanged( *this );
}
void setAmbientLight( castor::RgbColour const & value )
{
m_ambientLight = value;
}
/**@}*/
private:
void doUpdateBoundingBox();
void doUpdateAnimations( CpuUpdater & updater );
void doUpdateMaterials();
bool doUpdateLightDependent( LightType lightType
, bool shadowProducer
, GlobalIlluminationType globalIllumination );
bool doUpdateLightsDependent();
void onMaterialChanged( Material const & material );
public:
//!\~english The signal raised when the scene has changed.
//!\~french Le signal levé lorsque la scène a changé.
mutable OnSceneChanged onChanged;
//!\~english The signal raised when the scene is updating.
//!\~french Le signal levé lorsque la scène se met à jour.
mutable OnSceneUpdate onUpdate;
//!\~english The signal raised when the scene background has changed.
//!\~french Le signal levé lorsque le fond a changé.
mutable OnBackgroundChanged onSetBackground;
private:
bool m_initialised{ false };
SceneNodeSPtr m_rootNode;
SceneNodeSPtr m_rootCameraNode;
SceneNodeSPtr m_rootObjectNode;
DECLARE_OBJECT_CACHE_MEMBER( sceneNode, SceneNode );
DECLARE_OBJECT_CACHE_MEMBER( camera, Camera );
DECLARE_OBJECT_CACHE_MEMBER( light, Light );
DECLARE_OBJECT_CACHE_MEMBER( geometry, Geometry );
DECLARE_OBJECT_CACHE_MEMBER( billboard, BillboardList );
DECLARE_OBJECT_CACHE_MEMBER( particleSystem, ParticleSystem );
DECLARE_CACHE_MEMBER( mesh, Mesh );
DECLARE_CACHE_MEMBER( animatedObjectGroup, AnimatedObjectGroup );
DECLARE_CACHE_VIEW_MEMBER( overlay, Overlay, EventType::ePreRender );
DECLARE_CACHE_VIEW_MEMBER( material, Material, EventType::ePreRender );
DECLARE_CACHE_VIEW_MEMBER( sampler, Sampler, EventType::ePreRender );
DECLARE_CU_CACHE_VIEW_MEMBER( font, Font, EventType::ePreRender );
bool m_changed{ false };
castor::RgbColour m_ambientLight;
castor::RgbColour m_backgroundColour;
SceneBackgroundSPtr m_background;
LightFactorySPtr m_lightFactory;
Fog m_fog;
FrameListenerWPtr m_listener;
std::unique_ptr< EnvironmentMap > m_reflectionMap;
castor::ThreadPool m_animationUpdater;
bool m_needsSubsurfaceScattering{ false };
bool m_hasOpaqueObjects{ false };
bool m_hasTransparentObjects{ false };
std::map< Material *, OnMaterialChangedConnection > m_materialsListeners;
bool m_dirtyMaterials{ true };
uint32_t m_directionalShadowCascades{ ShadowMapDirectionalTileCountX * ShadowMapDirectionalTileCountY };
castor::BoundingBox m_boundingBox;
std::atomic_bool m_needsGlobalIllumination;
std::array< std::atomic_bool, size_t( LightType::eCount ) > m_hasShadows;
std::array< std::set< GlobalIlluminationType >, size_t( LightType::eCount ) > m_giTypes;
std::atomic_bool m_hasAnyShadows;
std::map< castor::String, OnLightChangedConnection > m_lightConnections;
float m_lpvIndirectAttenuation{ 1.7f };
VoxelSceneData m_voxelConfig;
SceneRenderNodesUPtr m_renderNodes;
public:
//!\~english The cameras root node name.
//!\~french Le nom du noeud de scène racine des caméras.
static castor::String CameraRootNode;
//!\~english The objects root node name.
//!\~french Le nom du noeud de scène racine des objets.
static castor::String ObjectRootNode;
//!\~english The root node name.
//!\~french Le nom du noeud de scène racine.
static castor::String RootNode;
};
}
#endif
| 29.301518 | 139 | 0.722905 | [
"mesh",
"geometry",
"render"
] |
2632e253be12795a3b74ecbd0f41a0c68b597a2d | 2,769 | hpp | C++ | src/crosshatching/brush_language.hpp | jwezorek/crosshatching | 0811e239998cc68d5d6e900510974d6196638577 | [
"MIT"
] | null | null | null | src/crosshatching/brush_language.hpp | jwezorek/crosshatching | 0811e239998cc68d5d6e900510974d6196638577 | [
"MIT"
] | null | null | null | src/crosshatching/brush_language.hpp | jwezorek/crosshatching | 0811e239998cc68d5d6e900510974d6196638577 | [
"MIT"
] | null | null | null | #pragma once
#include "brush.hpp"
#include <vector>
#include <memory>
#include <string>
#include <optional>
#include <variant>
#include <iterator>
namespace ch {
enum class symbol {
true_,
false_,
pipe,
linear_brush,
norm_rnd,
lerp,
ramp,
rotate,
disintegrate,
jiggle,
merge
};
class brush_expr_base;
using brush_expr_ptr = std::shared_ptr<brush_expr_base>;
class brush_expr_base {
public:
virtual brush_pipeline_item eval() const = 0;
virtual std::optional<symbol> sym_type() const = 0;
virtual std::string to_short_string() const = 0;
virtual std::string to_string() const = 0;
virtual std::optional<double> to_number() const = 0;
virtual const std::vector<brush_expr_ptr>* children() const {
return nullptr;
}
virtual bool is_expression() const {
return false;
}
};
class brush_expr : public brush_expr_base {
public:
brush_expr( ch::symbol op);
template<typename Iter>
brush_expr(ch::symbol op, Iter begin, Iter end) : brush_expr(op) {
std::copy(begin, end, std::back_inserter(children_));
}
brush_pipeline_item eval() const override;
std::optional<symbol> sym_type() const override;
std::string to_short_string() const override;
std::string to_string() const override;
std::optional<double> to_number() const override;
const std::vector<brush_expr_ptr>* children() const override;
bool is_expression() const override;
private:
ch::symbol op_;
std::vector<brush_expr_ptr> children_;
};
class symbol_expr : public brush_expr_base {
public:
symbol_expr(symbol sym);
brush_pipeline_item eval() const override;
virtual std::optional<symbol> sym_type() const override;
std::string to_short_string() const override;
std::string to_string() const override;
std::optional<double> to_number() const override;
private:
symbol sym_;
};
class num_expr : public brush_expr_base {
public:
num_expr(double val);
brush_pipeline_item eval() const override;
virtual std::optional<symbol> sym_type() const override;
std::string to_short_string() const override;
std::string to_string() const override;
std::optional<double> to_number() const override;
private:
double val_;
};
std::variant<ch::brush_fn, std::string> brush_language_to_func(const std::string& input);
std::variant<ch::brush_expr_ptr, std::string> brush_language_to_expr(const std::string& input);
}; | 28.84375 | 99 | 0.627302 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.