text
stringlengths
500
20k
source
stringclasses
27 values
lang
stringclasses
3 values
char_count
int64
500
20k
word_count
int64
4
19.8k
#include "wifi.h" static const char* TAG = "WIFI"; bool wifiAPMode; std::string wifiSsid, wifiPw; static EventGroupHandle_t wifi_event_group; const int WIFI_CONNECTED_BIT = BIT0; #if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(4, 3, 0) #define WIFI_IF_STA ESP_IF_WIFI_STA #define WIFI_IF_AP ESP_IF_WIFI_AP #endif static void event_handler_ap(void* arg, esp_event_base_t base, int32_t event_id, void* data) { if (event_id == WIFI_EVENT_AP_STACONNECTED) { wifi_event_ap_staconnected_t* event = (wifi_event_ap_staconnected_t*)data; ESP_LOGI(TAG, "station " MACSTR " join, AID=%d", MAC2STR(event->mac), event->aid); } else if (event_id == WIFI_EVENT_AP_STADISCONNECTED) { wifi_event_ap_stadisconnected_t* event = (wifi_event_ap_stadisconnected_t*)data; ESP_LOGI(TAG, "station " MACSTR " leave, AID=%d", MAC2STR(event->mac), event->aid); } } static void wifi_init_softap() { esp_netif_create_default_wifi_ap(); wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); ESP_ERROR_CHECK(esp_wifi_init(&cfg)); ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler_ap, NULL, NULL)); wifi_config_t wificfg = {}; wificfg.ap.authmode = wifiPw.empty() ? WIFI_AUTH_OPEN : WIFI_AUTH_WPA2_PSK; wificfg.ap.max_connection = 32; wificfg.ap.beacon_interval = 300; strncpy((char*)wificfg.ap.ssid, wifiSsid.c_str(), sizeof(wificfg.ap.ssid) - 1); strncpy((char*)wificfg.ap.password, wifiPw.c_str(), sizeof(wificfg.ap.password) - 1); ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP)); ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &wificfg)); ESP_ERROR_CHECK(esp_wifi_start()); ESP_LOGI(TAG, "wifi_init_softap SSID: %s password: %s", wifiSsid.c_str(), wifiPw.c_str()); } static void event_handler_sta(void* arg, esp_event_base_t base, int32_t event_id, void* data) { if (event_id == WIFI_EVENT_STA_START) { ESP_LOGI(TAG, "starting"); esp_wifi_connect(); } else if (event_id == WIFI_EVENT_STA_DISCONNECTED) { ESP_LOGI(TAG, "disconnected"); xEventGroupClearBits(wifi_event_group, WIFI_CONNECTED_BIT); esp_wifi_connect(); } } static void event_handler_sta_ip(void* arg, esp_event_base_t base, int32_t event_id, void* data) { if (event_id == IP_EVENT_STA_GOT_IP) { ip_event_got_ip_t* event = (ip_event_got_ip_t*)data; ESP_LOGI(TAG, "got ip: " IPSTR, IP2STR(&event->ip_info.ip)); xEventGroupSetBits(wifi_event_group, WIFI_CONNECTED_BIT); } } static void wifi_init_sta() { esp_netif_create_default_wifi_sta(); wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); ESP_ERROR_CHECK(esp_wifi_init(&cfg)); ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler_sta, NULL, NULL)); ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler_sta_ip, NULL, NULL)); wifi_config_t wificfg = {}; wificfg.sta.sort_method = WIFI_CONNECT_AP_BY_SIGNAL; strncpy((char*)wificfg.sta.ssid, wifiSsid.c_str(), sizeof(wificfg.sta.ssid) - 1); strncpy((char*)wificfg.sta.password, wifiPw.c_str(), sizeof(wificfg.sta.password) - 1); ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA)); ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wificfg)); ESP_ERROR_CHECK(esp_wifi_start()); ESP_LOGI(TAG, "wifi_init_sta connecting to SSID: %s", wifiSsid.c_str()); } bool wifi_wait_for_connection(TickType_t delay) { return !!(xEventGroupWaitBits(wifi_event_group, WIFI_CONNECTED_BIT, false, true, delay) & WIFI_CONNECTED_BIT); } void wifi_init() { esp_log_level_set("wifi", ESP_LOG_WARN); // reduce built-in wifi logging wifi_event_group = xEventGroupCreate(); if (wifiSsid.empty()) return; ESP_ERROR_CHECK(esp_netif_init()); ESP_ERROR_CHECK(esp_event_loop_create_default()); if (wifiAPMode) { wifi_init_softap(); } else { wifi_init_sta(); } }
c++
code
3,997
792
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "compressiontype.h" namespace config { vespalib::string compressionTypeToString(const CompressionType & compressionType) { switch (compressionType) { case CompressionType::UNCOMPRESSED: return "UNCOMPRESSED"; default: return "LZ4"; } } CompressionType stringToCompressionType(const vespalib::string & type) { if (type.compare("UNCOMPRESSED") == 0) { return CompressionType::UNCOMPRESSED; } else { return CompressionType::LZ4; } } }
c++
code
639
113
// Copyright 2017 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/connectivity/bluetooth/core/bt-host/gap/peer_cache.h" #include <lib/inspect/testing/cpp/inspect.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "lib/gtest/test_loop_fixture.h" #include "src/connectivity/bluetooth/core/bt-host/common/device_class.h" #include "src/connectivity/bluetooth/core/bt-host/common/random.h" #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" #include "src/connectivity/bluetooth/core/bt-host/common/uint128.h" #include "src/connectivity/bluetooth/core/bt-host/gap/peer.h" #include "src/connectivity/bluetooth/core/bt-host/hci/low_energy_scanner.h" #include "src/connectivity/bluetooth/core/bt-host/sm/types.h" #include "src/connectivity/bluetooth/core/bt-host/sm/util.h" namespace bt { namespace gap { namespace { using namespace inspect::testing; // All fields are initialized to zero as they are unused in these tests. const hci::LEConnectionParameters kTestParams; // Arbitrary ID value used by the bonding tests below. The actual value of this // constant does not effect the test logic. constexpr PeerId kId(100); constexpr int8_t kTestRSSI = 10; const DeviceAddress kAddrBrEdr(DeviceAddress::Type::kBREDR, {0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA}); const DeviceAddress kAddrLePublic(DeviceAddress::Type::kLEPublic, {6, 5, 4, 3, 2, 1}); // LE Public Device Address that has the same value as a BR/EDR BD_ADDR, e.g. on // a dual-mode device. const DeviceAddress kAddrLeAlias(DeviceAddress::Type::kLEPublic, {0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA}); // TODO(armansito): Make these adhere to privacy specification. const DeviceAddress kAddrLeRandom(DeviceAddress::Type::kLERandom, {1, 2, 3, 4, 5, 6}); const DeviceAddress kAddrLeRandom2(DeviceAddress::Type::kLERandom, {0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF}); const DeviceAddress kAddrLeAnon(DeviceAddress::Type::kLEAnonymous, {1, 2, 3, 4, 5, 6}); // Arbitrary name value used by the bonding tests below. The actual value of // this constant does not effect the test logic. const std::string kName = "TestName"; const auto kAdvData = CreateStaticByteBuffer(0x05, // Length 0x09, // AD type: Complete Local Name 'T', 'e', 's', 't'); const auto kEirData = kAdvData; const bt::sm::LTK kLTK; const bt::sm::Key kKey{}; const bt::sm::LTK kBrEdrKey; // Phone (Networking) const DeviceClass kTestDeviceClass({0x06, 0x02, 0x02}); class GAP_PeerCacheTest : public ::gtest::TestLoopFixture { public: void SetUp() override { TestLoopFixture::SetUp(); cache_ = std::make_unique<PeerCache>(); } void TearDown() override { RunLoopUntilIdle(); cache_.reset(); TestLoopFixture::TearDown(); } protected: // Creates a new Peer, and caches a pointer to that peer. __WARN_UNUSED_RESULT bool NewPeer(const DeviceAddress& addr, bool connectable) { auto* peer = cache()->NewPeer(addr, connectable); if (!peer) { return false; } peer_ = peer; return true; } PeerCache* cache() { return cache_.get(); } // Returns the cached pointer to the peer created in the most recent call to // NewPeer(). The caller must ensure that the peer has not expired out of // the cache. (Tests of cache expiration should generally subclass the // GAP_PeerCacheExpirationTest fixture.) Peer* peer() { return peer_; } private: std::unique_ptr<PeerCache> cache_; Peer* peer_; }; TEST_F(GAP_PeerCacheTest, InspectHierarchyContainsAddedPeersAndDoesNotContainRemovedPeers) { inspect::Inspector inspector; cache()->AttachInspect(inspector.GetRoot()); Peer* peer0 = cache()->NewPeer(kAddrLePublic, true); auto peer0_matcher = AllOf(NodeMatches(AllOf(NameMatches("peer_0x0")))); cache()->NewPeer(kAddrBrEdr, true); auto peer1_matcher = AllOf(NodeMatches(AllOf(NameMatches("peer_0x1")))); // Hierarchy should contain peer0 and peer1. auto hierarchy = inspect::ReadFromVmo(inspector.DuplicateVmo()).take_value(); auto peer_cache_matcher0 = AllOf(NodeMatches(AllOf(PropertyList(testing::IsEmpty()))), ChildrenMatch(UnorderedElementsAre(peer0_matcher, peer1_matcher))); EXPECT_THAT(hierarchy, AllOf(ChildrenMatch(UnorderedElementsAre(peer_cache_matcher0)))); // peer0 should be removed from hierarchy after it is removed from the cache because its Node is // destroyed along with the Peer object. EXPECT_TRUE(cache()->RemoveDisconnectedPeer(peer0->identifier())); hierarchy = inspect::ReadFromVmo(inspector.DuplicateVmo()).take_value(); auto peer_cache_matcher1 = AllOf(NodeMatches(AllOf(PropertyList(testing::IsEmpty()))), ChildrenMatch(UnorderedElementsAre(peer1_matcher))); EXPECT_THAT(hierarchy, AllOf(ChildrenMatch(UnorderedElementsAre(peer_cache_matcher1)))); } TEST_F(GAP_PeerCacheTest, LookUp) { auto kAdvData0 = CreateStaticByteBuffer(0x05, 0x09, 'T', 'e', 's', 't'); auto kAdvData1 = CreateStaticByteBuffer(0x0C, 0x09, 'T', 'e', 's', 't', ' ', 'D', 'e', 'v', 'i', 'c', 'e'); // These should return false regardless of the input while the cache is empty. EXPECT_FALSE(cache()->FindByAddress(kAddrLePublic)); EXPECT_FALSE(cache()->FindById(kId)); auto peer = cache()->NewPeer(kAddrLePublic, true); ASSERT_TRUE(peer); ASSERT_TRUE(peer->le()); EXPECT_EQ(TechnologyType::kLowEnergy, peer->technology()); EXPECT_TRUE(peer->connectable()); EXPECT_TRUE(peer->temporary()); EXPECT_EQ(kAddrLePublic, peer->address()); EXPECT_EQ(0u, peer->le()->advertising_data().size()); EXPECT_EQ(hci::kRSSIInvalid, peer->rssi()); // A look up should return the same instance. EXPECT_EQ(peer, cache()->FindById(peer->identifier())); EXPECT_EQ(peer, cache()->FindByAddress(peer->address())); // Adding a peer with the same address should return nullptr. EXPECT_FALSE(cache()->NewPeer(kAddrLePublic, true)); peer->MutLe().SetAdvertisingData(kTestRSSI, kAdvData1); EXPECT_TRUE(ContainersEqual(kAdvData1, peer->le()->advertising_data())); EXPECT_EQ(kTestRSSI, peer->rssi()); peer->MutLe().SetAdvertisingData(kTestRSSI, kAdvData0); EXPECT_TRUE(ContainersEqual(kAdvData0, peer->le()->advertising_data())); EXPECT_EQ(kTestRSSI, peer->rssi()); } TEST_F(GAP_PeerCacheTest, LookUpBrEdrPeerByLePublicAlias) { ASSERT_FALSE(cache()->FindByAddress(kAddrLeAlias)); ASSERT_TRUE(NewPeer(kAddrBrEdr, true)); auto* p = cache()->FindByAddress(kAddrBrEdr); ASSERT_TRUE(p); EXPECT_EQ(peer(), p); p = cache()->FindByAddress(kAddrLeAlias); ASSERT_TRUE(p); EXPECT_EQ(peer(), p); EXPECT_EQ(DeviceAddress::Type::kBREDR, p->address().type()); } TEST_F(GAP_PeerCacheTest, LookUpLePeerByBrEdrAlias) { EXPECT_FALSE(cache()->FindByAddress(kAddrBrEdr)); ASSERT_TRUE(NewPeer(kAddrLeAlias, true)); auto* p = cache()->FindByAddress(kAddrLeAlias); ASSERT_TRUE(p); EXPECT_EQ(peer(), p); p = cache()->FindByAddress(kAddrBrEdr); ASSERT_TRUE(p); EXPECT_EQ(peer(), p); EXPECT_EQ(DeviceAddress::Type::kLEPublic, p->address().type()); } TEST_F(GAP_PeerCacheTest, NewPeerDoesNotCrashWhenNoCallbackIsRegistered) { cache()->NewPeer(kAddrLePublic, true); } TEST_F(GAP_PeerCacheTest, ForEachEmpty) { bool found = false; cache()->ForEach([&](const auto&) { found = true; }); EXPECT_FALSE(found); } TEST_F(GAP_PeerCacheTest, ForEach) { int count = 0; ASSERT_TRUE(NewPeer(kAddrLePublic, true)); cache()->ForEach([&](const auto& p) { count++; EXPECT_EQ(peer()->identifier(), p.identifier()); EXPECT_EQ(peer()->address(), p.address()); }); EXPECT_EQ(1, count); } TEST_F(GAP_PeerCacheTest, NewPeerInvokesCallbackWhenPeerIsFirstRegistered) { bool was_called = false; cache()->set_peer_updated_callback([&was_called](const auto&) { was_called = true; }); cache()->NewPeer(kAddrLePublic, true); EXPECT_TRUE(was_called); } TEST_F(GAP_PeerCacheTest, NewPeerDoesNotInvokeCallbackWhenPeerIsReRegistered) { int call_count = 0; cache()->set_peer_updated_callback([&call_count](const auto&) { ++call_count; }); cache()->NewPeer(kAddrLePublic, true); cache()->NewPeer(kAddrLePublic, true); EXPECT_EQ(1, call_count); } TEST_F(GAP_PeerCacheTest, NewPeerIdentityKnown) { EXPECT_TRUE(cache()->NewPeer(kAddrBrEdr, true)->identity_known()); EXPECT_TRUE(cache()->NewPeer(kAddrLePublic, true)->identity_known()); EXPECT_FALSE(cache()->NewPeer(kAddrLeRandom, true)->identity_known()); EXPECT_FALSE(cache()->NewPeer(kAddrLeAnon, false)->identity_known()); } TEST_F(GAP_PeerCacheTest, NewPeerInitialTechnologyIsClassic) { ASSERT_TRUE(NewPeer(kAddrBrEdr, true)); // A peer initialized with a BR/EDR address should start out as a // classic-only. ASSERT_TRUE(peer()); EXPECT_TRUE(peer()->bredr()); EXPECT_FALSE(peer()->le()); EXPECT_TRUE(peer()->identity_known()); EXPECT_EQ(TechnologyType::kClassic, peer()->technology()); } TEST_F(GAP_PeerCacheTest, NewPeerInitialTechnologyLowEnergy) { // LE address types should initialize the peer as LE-only. auto* le_publ_peer = cache()->NewPeer(kAddrLePublic, true /*connectable*/); auto* le_rand_peer = cache()->NewPeer(kAddrLeRandom, true /*connectable*/); auto* le_anon_peer = cache()->NewPeer(kAddrLeAnon, false /*connectable*/); ASSERT_TRUE(le_publ_peer); ASSERT_TRUE(le_rand_peer); ASSERT_TRUE(le_anon_peer); EXPECT_TRUE(le_publ_peer->le()); EXPECT_TRUE(le_rand_peer->le()); EXPECT_TRUE(le_anon_peer->le()); EXPECT_FALSE(le_publ_peer->bredr()); EXPECT_FALSE(le_rand_peer->bredr()); EXPECT_FALSE(le_anon_peer->bredr()); EXPECT_EQ(TechnologyType::kLowEnergy, le_publ_peer->technology()); EXPECT_EQ(TechnologyType::kLowEnergy, le_rand_peer->technology()); EXPECT_EQ(TechnologyType::kLowEnergy, le_anon_peer->technology()); EXPECT_TRUE(le_publ_peer->identity_known()); EXPECT_FALSE(le_rand_peer->identity_known()); EXPECT_FALSE(le_anon_peer->identity_known()); } TEST_F(GAP_PeerCacheTest, DisallowNewLowEnergyPeerIfBrEdrPeerExists) { ASSERT_TRUE(NewPeer(kAddrBrEdr, true)); // Try to add new LE peer with a public identity address containing the same // value as the existing BR/EDR peer's BD_ADDR. auto* le_alias_peer = cache()->NewPeer(kAddrLeAlias, true); EXPECT_FALSE(le_alias_peer); } TEST_F(GAP_PeerCacheTest, DisallowNewBrEdrPeerIfLowEnergyPeerExists) { ASSERT_TRUE(NewPeer(kAddrLeAlias, true)); // Try to add new BR/EDR peer with BD_ADDR containing the same value as the // existing LE peer's public identity address. auto* bredr_alias_peer = cache()->NewPeer(kAddrBrEdr, true); ASSERT_FALSE(bredr_alias_peer); } TEST_F(GAP_PeerCacheTest, BrEdrPeerBecomesDualModeWithAdvertisingData) { ASSERT_TRUE(NewPeer(kAddrBrEdr, true)); ASSERT_TRUE(peer()->bredr()); ASSERT_FALSE(peer()->le()); peer()->MutLe().SetAdvertisingData(kTestRSSI, kAdvData); EXPECT_TRUE(peer()->le()); EXPECT_EQ(TechnologyType::kDualMode, peer()->technology()); // Searching by LE address should turn up this peer, which should retain its // original address type. auto* const le_peer = cache()->FindByAddress(kAddrLeAlias); ASSERT_EQ(peer(), le_peer); EXPECT_EQ(DeviceAddress::Type::kBREDR, peer()->address().type()); } TEST_F(GAP_PeerCacheTest, BrEdrPeerBecomesDualModeWhenConnectedOverLowEnergy) { ASSERT_TRUE(NewPeer(kAddrBrEdr, true)); ASSERT_TRUE(peer()->bredr()); ASSERT_FALSE(peer()->le()); peer()->MutLe().SetConnectionState(Peer::ConnectionState::kConnected); EXPECT_TRUE(peer()->le()); EXPECT_EQ(TechnologyType::kDualMode, peer()->technology()); auto* const le_peer = cache()->FindByAddress(kAddrLeAlias); ASSERT_EQ(peer(), le_peer); EXPECT_EQ(DeviceAddress::Type::kBREDR, peer()->address().type()); } TEST_F(GAP_PeerCacheTest, BrEdrPeerBecomesDualModeWithLowEnergyConnParams) { ASSERT_TRUE(NewPeer(kAddrBrEdr, true)); ASSERT_TRUE(peer()->bredr()); ASSERT_FALSE(peer()->le()); peer()->MutLe().SetConnectionParameters({}); EXPECT_TRUE(peer()->le()); EXPECT_EQ(TechnologyType::kDualMode, peer()->technology()); auto* const le_peer = cache()->FindByAddress(kAddrLeAlias); ASSERT_EQ(peer(), le_peer); EXPECT_EQ(DeviceAddress::Type::kBREDR, peer()->address().type()); } TEST_F(GAP_PeerCacheTest, BrEdrPeerBecomesDualModeWithLowEnergyPreferredConnParams) { ASSERT_TRUE(NewPeer(kAddrBrEdr, true)); ASSERT_TRUE(peer()->bredr()); ASSERT_FALSE(peer()->le()); peer()->MutLe().SetPreferredConnectionParameters({}); EXPECT_TRUE(peer()->le()); EXPECT_EQ(TechnologyType::kDualMode, peer()->technology()); auto* const le_peer = cache()->FindByAddress(kAddrLeAlias); ASSERT_EQ(peer(), le_peer); EXPECT_EQ(DeviceAddress::Type::kBREDR, peer()->address().type()); } TEST_F(GAP_PeerCacheTest, LowEnergyPeerBecomesDualModeWithInquiryData) { ASSERT_TRUE(NewPeer(kAddrLeAlias, true)); ASSERT_TRUE(peer()->le()); ASSERT_FALSE(peer()->bredr()); hci::InquiryResult ir; ir.bd_addr = kAddrLeAlias.value(); peer()->MutBrEdr().SetInquiryData(ir); EXPECT_TRUE(peer()->bredr()); EXPECT_EQ(TechnologyType::kDualMode, peer()->technology()); // Searching by only BR/EDR technology should turn up this peer, which // should still retain its original address type. auto* const bredr_peer = cache()->FindByAddress(kAddrBrEdr); ASSERT_EQ(peer(), bredr_peer); EXPECT_EQ(DeviceAddress::Type::kLEPublic, peer()->address().type()); EXPECT_EQ(kAddrBrEdr, peer()->bredr()->address()); } TEST_F(GAP_PeerCacheTest, LowEnergyPeerBecomesDualModeWhenConnectedOverClassic) { ASSERT_TRUE(NewPeer(kAddrLeAlias, true)); ASSERT_TRUE(peer()->le()); ASSERT_FALSE(peer()->bredr()); peer()->MutBrEdr().SetConnectionState(Peer::ConnectionState::kConnected); EXPECT_TRUE(peer()->bredr()); EXPECT_EQ(TechnologyType::kDualMode, peer()->technology()); auto* const bredr_peer = cache()->FindByAddress(kAddrBrEdr); ASSERT_EQ(peer(), bredr_peer); EXPECT_EQ(DeviceAddress::Type::kLEPublic, peer()->address().type()); EXPECT_EQ(kAddrBrEdr, peer()->bredr()->address()); } TEST_F(GAP_PeerCacheTest, InitialAutoConnectBehavior) { ASSERT_TRUE(NewPeer(kAddrLeAlias, true)); // Peers are not autoconnected before they are bonded. EXPECT_FALSE(peer()->le()->should_auto_connect()); sm::PairingData data; data.peer_ltk = sm::LTK(); data.local_ltk = sm::LTK(); data.irk = sm::Key(sm::SecurityProperties(), Random<UInt128>()); EXPECT_TRUE(cache()->StoreLowEnergyBond(peer()->identifier(), data)); // Bonded peers should autoconnect EXPECT_TRUE(peer()->le()->should_auto_connect()); // Connecting peer leaves `should_auto_connect` unaffected. peer()->MutLe().SetConnectionState(Peer::ConnectionState::kConnected); EXPECT_TRUE(peer()->le()->should_auto_connect()); } TEST_F(GAP_PeerCacheTest, AutoConnectDisabledAfterIntentionalDisconnect) { ASSERT_TRUE(NewPeer(kAddrLeAlias, true)); cache()->SetAutoConnectBehaviorForIntentionalDisconnect(peer()->identifier()); EXPECT_FALSE(peer()->le()->should_auto_connect()); } TEST_F(GAP_PeerCacheTest, AutoConnectReenabledAfterSuccessfulConnect) { ASSERT_TRUE(NewPeer(kAddrLeAlias, true)); // Only bonded peers are eligible for autoconnect. sm::PairingData data; data.peer_ltk = sm::LTK(); data.local_ltk = sm::LTK(); data.irk = sm::Key(sm::SecurityProperties(), Random<UInt128>()); EXPECT_TRUE(cache()->StoreLowEnergyBond(peer()->identifier(), data)); cache()->SetAutoConnectBehaviorForIntentionalDisconnect(peer()->identifier()); EXPECT_FALSE(peer()->le()->should_auto_connect()); cache()->SetAutoConnectBehaviorForSuccessfulConnection(peer()->identifier()); EXPECT_TRUE(peer()->le()->should_auto_connect()); } class GAP_PeerCacheTest_BondingTest : public GAP_PeerCacheTest { public: void SetUp() override { GAP_PeerCacheTest::SetUp(); ASSERT_TRUE(NewPeer(kAddrLePublic, true)); bonded_callback_called_ = false; cache()->set_peer_bonded_callback([this](const auto&) { bonded_callback_called_ = true; }); updated_callback_count_ = 0; cache()->set_peer_updated_callback([this](auto&) { updated_callback_count_++; }); removed_callback_count_ = 0; cache()->set_peer_removed_callback([this](PeerId) { removed_callback_count_++; }); } void TearDown() override { cache()->set_peer_removed_callback(nullptr); removed_callback_count_ = 0; cache()->set_peer_updated_callback(nullptr); updated_callback_count_ = 0; cache()->set_peer_bonded_callback(nullptr); bonded_callback_called_ = false; GAP_PeerCacheTest::TearDown(); } protected: bool bonded_callback_called() const { return bonded_callback_called_; } // Returns 0 at the beginning of each test case. int updated_callback_count() const { return updated_callback_count_; } int removed_callback_count() const { return removed_callback_count_; } private: bool bonded_callback_called_; int updated_callback_count_; int removed_callback_count_; }; TEST_F(GAP_PeerCacheTest_BondingTest, AddBondedPeerFailsWithExistingId) { sm::PairingData data; data.peer_ltk = kLTK; data.local_ltk = kLTK; EXPECT_FALSE( cache()->AddBondedPeer(BondingData{peer()->identifier(), kAddrLeRandom, {}, data, {}})); EXPECT_FALSE(bonded_callback_called()); } TEST_F(GAP_PeerCacheTest_BondingTest, AddBondedPeerFailsWithExistingAddress) { sm::PairingData data; data.peer_ltk = kLTK; data.local_ltk = kLTK; EXPECT_FALSE(cache()->AddBondedPeer(BondingData{kId, peer()->address(), {}, data, {}})); EXPECT_FALSE(bonded_callback_called()); } TEST_F(GAP_PeerCacheTest_BondingTest, AddBondedLowEnergyPeerFailsWithExistingBrEdrAliasAddress) { EXPECT_TRUE(NewPeer(kAddrBrEdr, true)); sm::PairingData data; data.peer_ltk = kLTK; data.local_ltk = kLTK; EXPECT_FALSE(cache()->AddBondedPeer(BondingData{kId, kAddrLeAlias, {}, data, {}})); EXPECT_FALSE(bonded_callback_called()); } TEST_F(GAP_PeerCacheTest_BondingTest, AddBondedBrEdrPeerFailsWithExistingLowEnergyAliasAddress) { EXPECT_TRUE(NewPeer(kAddrLeAlias, true)); EXPECT_FALSE(cache()->AddBondedPeer(BondingData{kId, kAddrBrEdr, {}, {}, kBrEdrKey})); EXPECT_FALSE(bonded_callback_called()); } TEST_F(GAP_PeerCacheTest_BondingTest, AddBondedPeerFailsWithoutMandatoryKeys) { sm::PairingData data; EXPECT_FALSE(cache()->AddBondedPeer(BondingData{kId, kAddrLeAlias, {}, data, kBrEdrKey})); data.peer_ltk = kLTK; data.local_ltk = kLTK; EXPECT_FALSE(cache()->AddBondedPeer(BondingData{kId, kAddrBrEdr, {}, data, {}})); EXPECT_FALSE(bonded_callback_called()); } TEST_F(GAP_PeerCacheTest_BondingTest, AddLowEnergyBondedPeerSuccess) { sm::PairingData data; data.peer_ltk = kLTK; data.local_ltk = kLTK; EXPECT_TRUE(cache()->AddBondedPeer(BondingData{kId, kAddrLeRandom, kName, data, {}})); auto* peer = cache()->FindById(kId); ASSERT_TRUE(peer); EXPECT_EQ(peer, cache()->FindByAddress(kAddrLeRandom)); EXPECT_EQ(kId, peer->identifier()); EXPECT_EQ(kAddrLeRandom, peer->address()); EXPECT_EQ(kName, peer->name()); EXPECT_TRUE(peer->identity_known()); ASSERT_TRUE(peer->le()); EXPECT_TRUE(peer->le()->bonded()); ASSERT_TRUE(peer->le()->bond_data()); EXPECT_EQ(data, *peer->le()->bond_data()); EXPECT_FALSE(peer->bredr()); EXPECT_EQ(TechnologyType::kLowEnergy, peer->technology()); // The "new bond" callback should not be called when restoring a previously // bonded peer. EXPECT_FALSE(bonded_callback_called()); } TEST_F(GAP_PeerCacheTest_BondingTest, AddBrEdrBondedPeerSuccess) { PeerId kId(5); sm::PairingData data; EXPECT_TRUE(cache()->AddBondedPeer(BondingData{kId, kAddrBrEdr, {}, data, kBrEdrKey})); auto* peer = cache()->FindById(kId); ASSERT_TRUE(peer); EXPECT_EQ(peer, cache()->FindByAddress(kAddrBrEdr)); EXPECT_EQ(kId, peer->identifier()); EXPECT_EQ(kAddrBrEdr, peer->address()); ASSERT_FALSE(peer->name());
c++
code
20,000
4,659
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * 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 <graphene/chain/genesis_state.hpp> // these are required to serialize a genesis_state #include <graphene/chain/protocol/fee_schedule.hpp> namespace graphene { namespace chain { chain_id_type genesis_state_type::compute_chain_id() const { return initial_chain_id; } } } // graphene::chain FC_REFLECT_DERIVED_NO_TYPENAME(graphene::chain::genesis_state_type::initial_account_type, BOOST_PP_SEQ_NIL, (name)(owner_key)(active_key)(is_lifetime_member)) FC_REFLECT_DERIVED_NO_TYPENAME(graphene::chain::genesis_state_type::initial_asset_type, BOOST_PP_SEQ_NIL, (symbol)(issuer_name)(description)(precision)(max_supply)(accumulated_fees)(is_bitasset)(collateral_records)) FC_REFLECT_DERIVED_NO_TYPENAME(graphene::chain::genesis_state_type::initial_asset_type::initial_collateral_position, BOOST_PP_SEQ_NIL, (owner)(collateral)(debt)) FC_REFLECT_DERIVED_NO_TYPENAME(graphene::chain::genesis_state_type::initial_balance_type, BOOST_PP_SEQ_NIL, (owner)(asset_symbol)(amount)) FC_REFLECT_DERIVED_NO_TYPENAME(graphene::chain::genesis_state_type::initial_vesting_balance_type, BOOST_PP_SEQ_NIL, (owner)(asset_symbol)(amount)(begin_timestamp)(vesting_cliff_seconds)(vesting_duration_seconds)(begin_balance)) FC_REFLECT_DERIVED_NO_TYPENAME(graphene::chain::genesis_state_type::initial_witness_type, BOOST_PP_SEQ_NIL, (owner_name)(block_signing_key)) FC_REFLECT_DERIVED_NO_TYPENAME(graphene::chain::genesis_state_type::initial_committee_member_type, BOOST_PP_SEQ_NIL, (owner_name)) FC_REFLECT_DERIVED_NO_TYPENAME(graphene::chain::genesis_state_type::initial_worker_type, BOOST_PP_SEQ_NIL, (owner_name)(daily_pay)) FC_REFLECT_DERIVED_NO_TYPENAME(graphene::chain::genesis_state_type::initial_bts_account_type::initial_authority, BOOST_PP_SEQ_NIL, (weight_threshold) (account_auths) (key_auths) (address_auths)) FC_REFLECT_DERIVED_NO_TYPENAME(graphene::chain::genesis_state_type::initial_bts_account_type::initial_cdd_vesting_policy, BOOST_PP_SEQ_NIL, (vesting_seconds) (coin_seconds_earned) (start_claim) (coin_seconds_earned_last_update)) FC_REFLECT_DERIVED_NO_TYPENAME(graphene::chain::genesis_state_type::initial_bts_account_type::initial_linear_vesting_policy, BOOST_PP_SEQ_NIL, (begin_timestamp) (vesting_cliff_seconds) (vesting_duration_seconds) (begin_balance)) FC_REFLECT_DERIVED_NO_TYPENAME(graphene::chain::genesis_state_type::initial_bts_account_type::initial_vesting_balance, BOOST_PP_SEQ_NIL, (asset_symbol) (amount) (policy_type) (policy)) FC_REFLECT_DERIVED_NO_TYPENAME(graphene::chain::genesis_state_type::initial_bts_account_type, BOOST_PP_SEQ_NIL, (name) (owner_authority) (active_authority) (core_balance) (vesting_balances)) FC_REFLECT_DERIVED_NO_TYPENAME(graphene::chain::genesis_state_type, BOOST_PP_SEQ_NIL, (initial_timestamp)(max_core_supply)(initial_parameters)(initial_bts_accounts)(initial_accounts)(initial_assets)(initial_balances) (initial_vesting_balances)(initial_active_witnesses)(initial_witness_candidates) (initial_committee_candidates)(initial_worker_candidates) (initial_chain_id) (immutable_parameters)) GRAPHENE_EXTERNAL_SERIALIZATION( /*not extern*/, graphene::chain::genesis_state_type::initial_account_type) GRAPHENE_EXTERNAL_SERIALIZATION( /*not extern*/, graphene::chain::genesis_state_type::initial_asset_type) GRAPHENE_EXTERNAL_SERIALIZATION( /*not extern*/, graphene::chain::genesis_state_type::initial_asset_type::initial_collateral_position) GRAPHENE_EXTERNAL_SERIALIZATION( /*not extern*/, graphene::chain::genesis_state_type::initial_balance_type) GRAPHENE_EXTERNAL_SERIALIZATION( /*not extern*/, graphene::chain::genesis_state_type::initial_vesting_balance_type) GRAPHENE_EXTERNAL_SERIALIZATION( /*not extern*/, graphene::chain::genesis_state_type::initial_witness_type) GRAPHENE_EXTERNAL_SERIALIZATION( /*not extern*/, graphene::chain::genesis_state_type::initial_committee_member_type) GRAPHENE_EXTERNAL_SERIALIZATION( /*not extern*/, graphene::chain::genesis_state_type::initial_worker_type) GRAPHENE_EXTERNAL_SERIALIZATION( /*not extern*/, graphene::chain::genesis_state_type::initial_bts_account_type::initial_authority) GRAPHENE_EXTERNAL_SERIALIZATION( /*not extern*/, graphene::chain::genesis_state_type::initial_bts_account_type::initial_cdd_vesting_policy) GRAPHENE_EXTERNAL_SERIALIZATION( /*not extern*/, graphene::chain::genesis_state_type::initial_bts_account_type::initial_linear_vesting_policy) GRAPHENE_EXTERNAL_SERIALIZATION( /*not extern*/, graphene::chain::genesis_state_type::initial_bts_account_type::initial_vesting_balance) GRAPHENE_EXTERNAL_SERIALIZATION( /*not extern*/, graphene::chain::genesis_state_type::initial_bts_account_type) GRAPHENE_EXTERNAL_SERIALIZATION( /*not extern*/, graphene::chain::genesis_state_type)
c++
code
6,198
997
// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "util/coding.h" #include "util/testharness.h" namespace unikv { class Coding { }; TEST(Coding, Fixed32) { std::string s; for (uint32_t v = 0; v < 100000; v++) { PutFixed32(&s, v); } const char* p = s.data(); for (uint32_t v = 0; v < 100000; v++) { uint32_t actual = DecodeFixed32(p); ASSERT_EQ(v, actual); p += sizeof(uint32_t); } } TEST(Coding, Fixed64) { std::string s; for (int power = 0; power <= 63; power++) { uint64_t v = static_cast<uint64_t>(1) << power; PutFixed64(&s, v - 1); PutFixed64(&s, v + 0); PutFixed64(&s, v + 1); } const char* p = s.data(); for (int power = 0; power <= 63; power++) { uint64_t v = static_cast<uint64_t>(1) << power; uint64_t actual; actual = DecodeFixed64(p); ASSERT_EQ(v-1, actual); p += sizeof(uint64_t); actual = DecodeFixed64(p); ASSERT_EQ(v+0, actual); p += sizeof(uint64_t); actual = DecodeFixed64(p); ASSERT_EQ(v+1, actual); p += sizeof(uint64_t); } } // Test that encoding routines generate little-endian encodings TEST(Coding, EncodingOutput) { std::string dst; PutFixed32(&dst, 0x04030201); ASSERT_EQ(4, dst.size()); ASSERT_EQ(0x01, static_cast<int>(dst[0])); ASSERT_EQ(0x02, static_cast<int>(dst[1])); ASSERT_EQ(0x03, static_cast<int>(dst[2])); ASSERT_EQ(0x04, static_cast<int>(dst[3])); dst.clear(); PutFixed64(&dst, 0x0807060504030201ull); ASSERT_EQ(8, dst.size()); ASSERT_EQ(0x01, static_cast<int>(dst[0])); ASSERT_EQ(0x02, static_cast<int>(dst[1])); ASSERT_EQ(0x03, static_cast<int>(dst[2])); ASSERT_EQ(0x04, static_cast<int>(dst[3])); ASSERT_EQ(0x05, static_cast<int>(dst[4])); ASSERT_EQ(0x06, static_cast<int>(dst[5])); ASSERT_EQ(0x07, static_cast<int>(dst[6])); ASSERT_EQ(0x08, static_cast<int>(dst[7])); } TEST(Coding, Varint32) { std::string s; for (uint32_t i = 0; i < (32 * 32); i++) { uint32_t v = (i / 32) << (i % 32); PutVarint32(&s, v); } const char* p = s.data(); const char* limit = p + s.size(); for (uint32_t i = 0; i < (32 * 32); i++) { uint32_t expected = (i / 32) << (i % 32); uint32_t actual; const char* start = p; p = GetVarint32Ptr(p, limit, &actual); ASSERT_TRUE(p != NULL); ASSERT_EQ(expected, actual); ASSERT_EQ(VarintLength(actual), p - start); } ASSERT_EQ(p, s.data() + s.size()); } TEST(Coding, Varint64) { // Construct the list of values to check std::vector<uint64_t> values; // Some special values values.push_back(0); values.push_back(100); values.push_back(~static_cast<uint64_t>(0)); values.push_back(~static_cast<uint64_t>(0) - 1); for (uint32_t k = 0; k < 64; k++) { // Test values near powers of two const uint64_t power = 1ull << k; values.push_back(power); values.push_back(power-1); values.push_back(power+1); } std::string s; for (size_t i = 0; i < values.size(); i++) { PutVarint64(&s, values[i]); } const char* p = s.data(); const char* limit = p + s.size(); for (size_t i = 0; i < values.size(); i++) { ASSERT_TRUE(p < limit); uint64_t actual; const char* start = p; p = GetVarint64Ptr(p, limit, &actual); ASSERT_TRUE(p != NULL); ASSERT_EQ(values[i], actual); ASSERT_EQ(VarintLength(actual), p - start); } ASSERT_EQ(p, limit); } TEST(Coding, Varint32Overflow) { uint32_t result; std::string input("\x81\x82\x83\x84\x85\x11"); ASSERT_TRUE(GetVarint32Ptr(input.data(), input.data() + input.size(), &result) == NULL); } TEST(Coding, Varint32Truncation) { uint32_t large_value = (1u << 31) + 100; std::string s; PutVarint32(&s, large_value); uint32_t result; for (size_t len = 0; len < s.size() - 1; len++) { ASSERT_TRUE(GetVarint32Ptr(s.data(), s.data() + len, &result) == NULL); } ASSERT_TRUE(GetVarint32Ptr(s.data(), s.data() + s.size(), &result) != NULL); ASSERT_EQ(large_value, result); } TEST(Coding, Varint64Overflow) { uint64_t result; std::string input("\x81\x82\x83\x84\x85\x81\x82\x83\x84\x85\x11"); ASSERT_TRUE(GetVarint64Ptr(input.data(), input.data() + input.size(), &result) == NULL); } TEST(Coding, Varint64Truncation) { uint64_t large_value = (1ull << 63) + 100ull; std::string s; PutVarint64(&s, large_value); uint64_t result; for (size_t len = 0; len < s.size() - 1; len++) { ASSERT_TRUE(GetVarint64Ptr(s.data(), s.data() + len, &result) == NULL); } ASSERT_TRUE(GetVarint64Ptr(s.data(), s.data() + s.size(), &result) != NULL); ASSERT_EQ(large_value, result); } TEST(Coding, Strings) { std::string s; PutLengthPrefixedSlice(&s, Slice("")); PutLengthPrefixedSlice(&s, Slice("foo")); PutLengthPrefixedSlice(&s, Slice("bar")); PutLengthPrefixedSlice(&s, Slice(std::string(200, 'x'))); Slice input(s); Slice v; ASSERT_TRUE(GetLengthPrefixedSlice(&input, &v)); ASSERT_EQ("", v.ToString()); ASSERT_TRUE(GetLengthPrefixedSlice(&input, &v)); ASSERT_EQ("foo", v.ToString()); ASSERT_TRUE(GetLengthPrefixedSlice(&input, &v)); ASSERT_EQ("bar", v.ToString()); ASSERT_TRUE(GetLengthPrefixedSlice(&input, &v)); ASSERT_EQ(std::string(200, 'x'), v.ToString()); ASSERT_EQ("", input.ToString()); } } // namespace unikv int main(int argc, char** argv) { return unikv::test::RunAllTests(); }
c++
code
5,520
1,663
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "consensus/validation.h" #include "key.h" #include "validation.h" #include "miner.h" #include "pubkey.h" #include "txmempool.h" #include "random.h" #include "script/standard.h" #include "test/test_flamecoin.h" #include "utiltime.h" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(tx_validationcache_tests) static bool ToMemPool(CMutableTransaction& tx) { LOCK(cs_main); CValidationState state; return AcceptToMemoryPool(mempool, state, MakeTransactionRef(tx), false, NULL, true, 0); } BOOST_FIXTURE_TEST_CASE(tx_mempool_block_doublespend, TestChain100Setup) { // Make sure skipping validation of transctions that were // validated going into the memory pool does not allow // double-spends in blocks to pass validation when they should not. CScript scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG; // Create a double-spend of mature coinbase txn: std::vector<CMutableTransaction> spends; spends.resize(2); for (int i = 0; i < 2; i++) { spends[i].nVersion = 1; spends[i].vin.resize(1); spends[i].vin[0].prevout.hash = coinbaseTxns[0].GetHash(); spends[i].vin[0].prevout.n = 0; spends[i].vout.resize(1); spends[i].vout[0].nValue = 11*CENT; spends[i].vout[0].scriptPubKey = scriptPubKey; // Sign: std::vector<unsigned char> vchSig; uint256 hash = SignatureHash(scriptPubKey, spends[i], 0, SIGHASH_ALL); BOOST_CHECK(coinbaseKey.Sign(hash, vchSig)); vchSig.push_back((unsigned char)SIGHASH_ALL); spends[i].vin[0].scriptSig << vchSig; } CBlock block; // Test 1: block with both of those transactions should be rejected. block = CreateAndProcessBlock(spends, scriptPubKey); BOOST_CHECK(chainActive.Tip()->GetBlockHash() != block.GetHash()); // Test 2: ... and should be rejected if spend1 is in the memory pool BOOST_CHECK(ToMemPool(spends[0])); block = CreateAndProcessBlock(spends, scriptPubKey); BOOST_CHECK(chainActive.Tip()->GetBlockHash() != block.GetHash()); mempool.clear(); // Test 3: ... and should be rejected if spend2 is in the memory pool BOOST_CHECK(ToMemPool(spends[1])); block = CreateAndProcessBlock(spends, scriptPubKey); BOOST_CHECK(chainActive.Tip()->GetBlockHash() != block.GetHash()); mempool.clear(); // Final sanity test: first spend in mempool, second in block, that's OK: std::vector<CMutableTransaction> oneSpend; oneSpend.push_back(spends[0]); BOOST_CHECK(ToMemPool(spends[1])); block = CreateAndProcessBlock(oneSpend, scriptPubKey); BOOST_CHECK(chainActive.Tip()->GetBlockHash() == block.GetHash()); // spends[1] should have been removed from the mempool when the // block with spends[0] is accepted: BOOST_CHECK_EQUAL(mempool.size(), 0); } BOOST_AUTO_TEST_SUITE_END()
c++
code
3,101
687
// Copyright 2017 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "core/fxge/dib/cfx_dibbase.h" #include <algorithm> #include <memory> #include <utility> #include <vector> #include "core/fxcodec/fx_codec.h" #include "core/fxge/cfx_cliprgn.h" #include "core/fxge/dib/cfx_bitmapstorer.h" #include "core/fxge/dib/cfx_dibitmap.h" #include "core/fxge/dib/cfx_imagestretcher.h" #include "core/fxge/dib/cfx_imagetransformer.h" #include "third_party/base/logging.h" #include "third_party/base/ptr_util.h" namespace { void ColorDecode(uint32_t pal_v, uint8_t* r, uint8_t* g, uint8_t* b) { *r = static_cast<uint8_t>((pal_v & 0xf00) >> 4); *g = static_cast<uint8_t>(pal_v & 0x0f0); *b = static_cast<uint8_t>((pal_v & 0x00f) << 4); } void Obtain_Pal(std::pair<uint32_t, uint32_t>* luts, uint32_t* dest_pal, uint32_t lut) { uint32_t lut_1 = lut - 1; for (int row = 0; row < 256; ++row) { int lut_offset = lut_1 - row; if (lut_offset < 0) lut_offset += 256; uint32_t color = luts[lut_offset].second; uint8_t r; uint8_t g; uint8_t b; ColorDecode(color, &r, &g, &b); dest_pal[row] = (static_cast<uint32_t>(r) << 16) | (static_cast<uint32_t>(g) << 8) | b | 0xff000000; luts[lut_offset].first = row; } } class CFX_Palette { public: explicit CFX_Palette(const RetainPtr<CFX_DIBBase>& pBitmap); ~CFX_Palette(); const uint32_t* GetPalette() { return m_Palette.data(); } const std::pair<uint32_t, uint32_t>* GetLuts() const { return m_Luts.data(); } int32_t GetLutCount() const { return m_lut; } void SetAmountLut(int row, uint32_t value) { m_Luts[row].first = value; } private: std::vector<uint32_t> m_Palette; // (Amount, Color) pairs std::vector<std::pair<uint32_t, uint32_t>> m_Luts; int m_lut; }; CFX_Palette::CFX_Palette(const RetainPtr<CFX_DIBBase>& pBitmap) : m_Palette(256), m_Luts(4096), m_lut(0) { int bpp = pBitmap->GetBPP() / 8; int width = pBitmap->GetWidth(); int height = pBitmap->GetHeight(); for (int row = 0; row < height; ++row) { const uint8_t* scan_line = pBitmap->GetScanline(row); for (int col = 0; col < width; ++col) { const uint8_t* src_port = scan_line + col * bpp; uint32_t b = src_port[0] & 0xf0; uint32_t g = src_port[1] & 0xf0; uint32_t r = src_port[2] & 0xf0; uint32_t index = (r << 4) + g + (b >> 4); ++m_Luts[index].first; } } // Move non-zeros to the front and count them for (int row = 0; row < 4096; ++row) { if (m_Luts[row].first != 0) { m_Luts[m_lut].first = m_Luts[row].first; m_Luts[m_lut].second = row; ++m_lut; } } std::sort(m_Luts.begin(), m_Luts.begin() + m_lut, [](const std::pair<uint32_t, uint32_t>& arg1, const std::pair<uint32_t, uint32_t>& arg2) { return arg1.first < arg2.first; }); Obtain_Pal(m_Luts.data(), m_Palette.data(), m_lut); } CFX_Palette::~CFX_Palette() {} void ConvertBuffer_1bppMask2Gray(uint8_t* dest_buf, int dest_pitch, int width, int height, const RetainPtr<CFX_DIBBase>& pSrcBitmap, int src_left, int src_top) { static constexpr uint8_t kSetGray = 0xff; static constexpr uint8_t kResetGray = 0x00; for (int row = 0; row < height; ++row) { uint8_t* dest_scan = dest_buf + row * dest_pitch; memset(dest_scan, kResetGray, width); const uint8_t* src_scan = pSrcBitmap->GetScanline(src_top + row); for (int col = src_left; col < src_left + width; ++col) { if (src_scan[col / 8] & (1 << (7 - col % 8))) *dest_scan = kSetGray; ++dest_scan; } } } void ConvertBuffer_8bppMask2Gray(uint8_t* dest_buf, int dest_pitch, int width, int height, const RetainPtr<CFX_DIBBase>& pSrcBitmap, int src_left, int src_top) { for (int row = 0; row < height; ++row) { uint8_t* dest_scan = dest_buf + row * dest_pitch; const uint8_t* src_scan = pSrcBitmap->GetScanline(src_top + row) + src_left; memcpy(dest_scan, src_scan, width); } } void ConvertBuffer_1bppPlt2Gray(uint8_t* dest_buf, int dest_pitch, int width, int height, const RetainPtr<CFX_DIBBase>& pSrcBitmap, int src_left, int src_top) { uint32_t* src_plt = pSrcBitmap->GetPalette(); uint8_t gray[2]; uint8_t reset_r; uint8_t reset_g; uint8_t reset_b; uint8_t set_r; uint8_t set_g; uint8_t set_b; if (pSrcBitmap->IsCmykImage()) { std::tie(reset_r, reset_g, reset_b) = AdobeCMYK_to_sRGB1( FXSYS_GetCValue(src_plt[0]), FXSYS_GetMValue(src_plt[0]), FXSYS_GetYValue(src_plt[0]), FXSYS_GetKValue(src_plt[0])); std::tie(set_r, set_g, set_b) = AdobeCMYK_to_sRGB1( FXSYS_GetCValue(src_plt[1]), FXSYS_GetMValue(src_plt[1]), FXSYS_GetYValue(src_plt[1]), FXSYS_GetKValue(src_plt[1])); } else { reset_r = FXARGB_R(src_plt[0]); reset_g = FXARGB_G(src_plt[0]); reset_b = FXARGB_B(src_plt[0]); set_r = FXARGB_R(src_plt[1]); set_g = FXARGB_G(src_plt[1]); set_b = FXARGB_B(src_plt[1]); } gray[0] = FXRGB2GRAY(reset_r, reset_g, reset_b); gray[1] = FXRGB2GRAY(set_r, set_g, set_b); for (int row = 0; row < height; ++row) { uint8_t* dest_scan = dest_buf + row * dest_pitch; memset(dest_scan, gray[0], width); const uint8_t* src_scan = pSrcBitmap->GetScanline(src_top + row); for (int col = src_left; col < src_left + width; ++col) { if (src_scan[col / 8] & (1 << (7 - col % 8))) *dest_scan = gray[1]; ++dest_scan; } } } void ConvertBuffer_8bppPlt2Gray(uint8_t* dest_buf, int dest_pitch, int width, int height, const RetainPtr<CFX_DIBBase>& pSrcBitmap, int src_left, int src_top) { uint32_t* src_plt = pSrcBitmap->GetPalette(); uint8_t gray[256]; if (pSrcBitmap->IsCmykImage()) { uint8_t r; uint8_t g; uint8_t b; for (size_t i = 0; i < FX_ArraySize(gray); ++i) { std::tie(r, g, b) = AdobeCMYK_to_sRGB1( FXSYS_GetCValue(src_plt[i]), FXSYS_GetMValue(src_plt[i]), FXSYS_GetYValue(src_plt[i]), FXSYS_GetKValue(src_plt[i])); gray[i] = FXRGB2GRAY(r, g, b); } } else { for (size_t i = 0; i < FX_ArraySize(gray); ++i) { gray[i] = FXRGB2GRAY(FXARGB_R(src_plt[i]), FXARGB_G(src_plt[i]), FXARGB_B(src_plt[i])); } } for (int row = 0; row < height; ++row) { uint8_t* dest_scan = dest_buf + row * dest_pitch; const uint8_t* src_scan = pSrcBitmap->GetScanline(src_top + row) + src_left; for (int col = 0; col < width; ++col) *dest_scan++ = gray[*src_scan++]; } } void ConvertBuffer_RgbOrCmyk2Gray(uint8_t* dest_buf, int dest_pitch, int width, int height, const RetainPtr<CFX_DIBBase>& pSrcBitmap, int src_left, int src_top) { int Bpp = pSrcBitmap->GetBPP() / 8; if (pSrcBitmap->IsCmykImage()) { for (int row = 0; row < height; ++row) { uint8_t* dest_scan = dest_buf + row * dest_pitch; const uint8_t* src_scan = pSrcBitmap->GetScanline(src_top + row) + src_left * 4; for (int col = 0; col < width; ++col) { uint8_t r; uint8_t g; uint8_t b; std::tie(r, g, b) = AdobeCMYK_to_sRGB1( FXSYS_GetCValue(static_cast<uint32_t>(src_scan[0])), FXSYS_GetMValue(static_cast<uint32_t>(src_scan[1])), FXSYS_GetYValue(static_cast<uint32_t>(src_scan[2])), FXSYS_GetKValue(static_cast<uint32_t>(src_scan[3]))); *dest_scan++ = FXRGB2GRAY(r, g, b); src_scan += 4; } } } else { for (int row = 0; row < height; ++row) { uint8_t* dest_scan = dest_buf + row * dest_pitch; const uint8_t* src_scan = pSrcBitmap->GetScanline(src_top + row) + src_left * Bpp; for (int col = 0; col < width; ++col) { *dest_scan++ = FXRGB2GRAY(src_scan[2], src_scan[1], src_scan[0]); src_scan += Bpp; } } } } void ConvertBuffer_IndexCopy(uint8_t* dest_buf, int dest_pitch, int width, int height, const RetainPtr<CFX_DIBBase>& pSrcBitmap, int src_left, int src_top) { if (pSrcBitmap->GetBPP() == 1) { for (int row = 0; row < height; ++row) { uint8_t* dest_scan = dest_buf + row * dest_pitch; // Set all destination pixels to be white initially. memset(dest_scan, 255, width); const uint8_t* src_scan = pSrcBitmap->GetScanline(src_top + row); for (int col = src_left; col < src_left + width; ++col) { // If the source bit is set, then set the destination pixel to be black. if (src_scan[col / 8] & (1 << (7 - col % 8))) *dest_scan = 0; ++dest_scan; } } } else { for (int row = 0; row < height; ++row) { uint8_t* dest_scan = dest_buf + row * dest_pitch; const uint8_t* src_scan = pSrcBitmap->GetScanline(src_top + row) + src_left; memcpy(dest_scan, src_scan, width); } } } void ConvertBuffer_Plt2PltRgb8(uint8_t* dest_buf, int dest_pitch, int width, int height, const RetainPtr<CFX_DIBBase>& pSrcBitmap, int src_left, int src_top, uint32_t* dst_plt) { ConvertBuffer_IndexCopy(dest_buf, dest_pitch, width, height, pSrcBitmap, src_left, src_top); uint32_t* src_plt = pSrcBitmap->GetPalette(); int plt_size = pSrcBitmap->GetPaletteSize(); if (pSrcBitmap->IsCmykImage()) { for (int i = 0; i < plt_size; ++i) { uint8_t r; uint8_t g; uint8_t b; std::tie(r, g, b) = AdobeCMYK_to_sRGB1( FXSYS_GetCValue(src_plt[i]), FXSYS_GetMValue(src_plt[i]), FXSYS_GetYValue(src_plt[i]), FXSYS_GetKValue(src_plt[i])); dst_plt[i] = ArgbEncode(0xff, r, g, b); } } else { memcpy(dst_plt, src_plt, plt_size * 4); } } void ConvertBuffer_Rgb2PltRgb8(uint8_t* dest_buf, int dest_pitch, int width, int height, const RetainPtr<CFX_DIBBase>& pSrcBitmap, int src_left, int src_top, uint32_t* dst_plt) { int bpp = pSrcBitmap->GetBPP() / 8; CFX_Palette palette(pSrcBitmap); const std::pair<uint32_t, uint32_t>* Luts = palette.GetLuts(); int lut = palette.GetLutCount(); const uint32_t* pal = palette.GetPalette(); if (lut > 256) { int err; int min_err; int lut_256 = lut - 256; for (int row = 0; row < lut_256; ++row) { min_err = 1000000; uint8_t r; uint8_t g; uint8_t b; ColorDecode(Luts[row].second, &r, &g, &b); uint32_t clrindex = 0; for (int col = 0; col < 256; ++col) { uint32_t p_color = pal[col]; int d_r = r - static_cast<uint8_t>(p_color >> 16); int d_g = g - static_cast<uint8_t>(p_color >> 8); int d_b = b - static_cast<uint8_t>(p_color); err = d_r * d_r + d_g * d_g + d_b * d_b; if (err < min_err) { min_err = err; clrindex = col; } } palette.SetAmountLut(row, clrindex); } } int32_t lut_1 = lut - 1; for (int row = 0; row < height; ++row) { const uint8_t* src_scan = pSrcBitmap->GetScanline(src_top + row) + src_left; uint8_t* dest_scan = dest_buf + row * dest_pitch; for (int col = 0; col < width; ++col) { const uint8_t* src_port = src_scan + col * bpp; int r = src_port[2] & 0xf0; int g = src_port[1] & 0xf0; int b = src_port[0] & 0xf0; uint32_t clrindex = (r << 4) + g + (b >> 4); for (int i = lut_1; i >= 0; --i) if (clrindex == Luts[i].second) { *(dest_scan + col) = static_cast<uint8_t>(Luts[i].first); break; } } } memcpy(dst_plt, pal, sizeof(uint32_t) * 256); } void ConvertBuffer_1bppMask2Rgb(FXDIB_Format dest_format, uint8_t* dest_buf, int dest_pitch, int width, int height, const RetainPtr<CFX_DIBBase>& pSrcBitmap, int src_left, int src_top) { int comps = GetCompsFromFormat(dest_format); static constexpr uint8_t kSetGray = 0xff; static constexpr uint8_t kResetGray = 0x00; for (int row = 0; row < height; ++row) { uint8_t* dest_scan = dest_buf + row * dest_pitch; const uint8_t* src_scan = pSrcBitmap->GetScanline(src_top + row); for (int col = src_left; col < src_left + width; ++col) { if (src_scan[col / 8] & (1 << (7 - col % 8))) { dest_scan[0] = kSetGray; dest_scan[1] = kSetGray; dest_scan[2] = kSetGray; } else { dest_scan[0] = kResetGray; dest_scan[1] = kResetGray; dest_scan[2] = kResetGray; } dest_scan += comps; } } } void ConvertBuffer_8bppMask2Rgb(FXDIB_Format dest_format, uint8_t* dest_buf, int dest_pitch, int width, int height, const RetainPtr<CFX_DIBBase>& pSrcBitmap, int src_left, int src_top) { int comps = GetCompsFromFormat(dest_format); for (int row = 0; row < height; ++row) { uint8_t* dest_scan = dest_buf + row * dest_pitch; const uint8_t* src_scan = pSrcBitmap->GetScanline(src_top + row) + src_left; uint8_t src_pixel; for (int col = 0; col < width; ++col) { src_pixel = *src_scan++; *dest_scan++ = src_pixel; *dest_scan++ = src_pixel; *dest_scan = src_pixel; dest_scan += comps - 2; } } } void ConvertBuffer_1bppPlt2Rgb(FXDIB_Format dest_format, uint8_t* dest_buf, int dest_pitch, int width, int height, const RetainPtr<CFX_DIBBase>& pSrcBitmap, int src_left, int src_top) { int comps = GetCompsFromFormat(dest_format); uint32_t* src_plt = pSrcBitmap->GetPalette(); uint32_t plt[2]; uint8_t* bgr_ptr = reinterpret_cast<uint8_t*>(plt); if (pSrcBitmap->IsCmykImage()) { plt[0] = FXCMYK_TODIB(src_plt[0]); plt[1] = FXCMYK_TODIB(src_plt[1]); } else { bgr_ptr[0] = FXARGB_B(src_plt[0]); bgr_ptr[1] = FXARGB_G(src_plt[0]); bgr_ptr[2] = FXARGB_R(src_plt[0]); bgr_ptr[3] = FXARGB_B(src_plt[1]); bgr_ptr[4] = FXARGB_G(src_plt[1]); bgr_ptr[5] = FXARGB_R(src_plt[1]); } if (pSrcBitmap->IsCmykImage()) { std::tie(bgr_ptr[2], bgr_ptr[1], bgr_ptr[0]) = AdobeCMYK_to_sRGB1( FXSYS_GetCValue(src_plt[0]), FXSYS_GetMValue(src_plt[0]), FXSYS_GetYValue(src_plt[0]), FXSYS_GetKValue(src_plt[0])); std::tie(bgr_ptr[5], bgr_ptr[4], bgr_ptr[3]) = AdobeCMYK_to_sRGB1( FXSYS_GetCValue(src_plt[1]), FXSYS_GetMValue(src_plt[1]), FXSYS_GetYValue(src_plt[1]), FXSYS_GetKValue(src_plt[1])); } for (int row = 0; row < height; ++row) { uint8_t* dest_scan = dest_buf + row * dest_pitch; const uint8_t* src_scan = pSrcBitmap->GetScanline(src_top + row); for (int col = src_left; col < src_left + width; ++col) { if (src_scan[col / 8] & (1 << (7 - col % 8))) { *dest_scan++ = bgr_ptr[3]; *dest_scan++ = bgr_ptr[4]; *dest_scan = bgr_ptr[5]; } else { *dest_scan++ = bgr_ptr[0]; *dest_scan++ = bgr_ptr[1]; *dest_scan = bgr_ptr[2]; } dest_scan += comps - 2; } } } void ConvertBuffer_8bppPlt2Rgb(FXDIB_Format dest_format, uint8_t* dest_buf, int dest_pitch, int width, int height, const RetainPtr<CFX_DIBBase>& pSrcBitmap, int src_left, int src_top) { int comps = GetCompsFromFormat(dest_format); uint32_t* src_plt = pSrcBitmap->GetPalette(); uint32_t plt[256]; uint8_t* bgr_ptr = reinterpret_cast<uint8_t*>(plt); if (!pSrcBitmap->IsCmykImage()) { for (int i = 0; i < 256; ++i) { *bgr_ptr++ = FXARGB_B(src_plt[i]); *bgr_ptr++ = FXARGB_G(src_plt[i]); *bgr_ptr++ = FXARGB_R(src_plt[i]); } bgr_ptr = reinterpret_cast<uint8_t*>(plt); } if (pSrcBitmap->IsCmykImage()) { for (int i = 0; i < 256; ++i) { std::tie(bgr_ptr[2], bgr_ptr[1], bgr_ptr[0]) = AdobeCMYK_to_sRGB1( FXSYS_GetCValue(src_plt[i]), FXSYS_GetMValue(src_plt[i]), FXSYS_GetYValue(src_plt[i]), FXSYS_GetKValue(src_plt[i])); bgr_ptr += 3; } bgr_ptr = reinterpret_cast<uint8_t*>(plt); } for (int row = 0; row < height; ++row) { uint8_t* dest_scan = dest_buf + row * dest_pitch; const uint8_t* src_scan = pSrcBitmap->GetScanline(src_top + row) + src_left; for (int col = 0; col < width; ++col) { uint8_t* src_pixel = bgr_ptr + 3 * (*src_scan++); *dest_scan++ = *src_pixel++; *dest_scan++ = *src_pixel++; *dest_scan = *src_pixel++; dest_scan += comps - 2; } } } void ConvertBuffer_24bppRgb2Rgb24(uint8_t* dest_buf, int dest_pitch, int width, int height, const RetainPtr<CFX_DIBBase>& pSrcBitmap, int src_left, int src_top) { for (int row = 0; row < height; ++row) { uint8_t* dest_scan = dest_buf + row * dest_pitch; const uint8_t* src_scan = pSrcBitmap->GetScanline(src_top + row) + src_left * 3; memcpy(dest_scan, src_scan, width * 3); } } void ConvertBuffer_32bppRgb2Rgb24(uint8_t* dest_buf, int dest_pitch, int width, int height, const RetainPtr<CFX_DIBBase>& pSrcBitmap, int src_left, int src_top) { for (int row = 0; row < height; ++row) { uint8_t* dest_scan = dest_buf + row * dest_pitch; const uint8_t* src_scan = pSrcBitmap->GetScanline(src_top + row) + src_left * 4; for (int col = 0; col < width; ++col) { *dest_scan++ = *src_scan++; *dest_s
c++
code
20,000
4,217
/* Copyright 2015 The TensorFlow Authors. 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. ==============================================================================*/ // See docs in ../ops/io_ops.cc. #include <string> #include <vector> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/platform/env.h" namespace tensorflow { class MatchingFilesOp : public OpKernel { public: using OpKernel::OpKernel; void Compute(OpKernelContext* context) override { const Tensor* patterns_t; // NOTE(ringwalt): Changing the input name "pattern" to "patterns" would // break existing graphs. OP_REQUIRES_OK(context, context->input("pattern", &patterns_t)); OP_REQUIRES( context, TensorShapeUtils::IsScalar(patterns_t->shape()) || TensorShapeUtils::IsVector(patterns_t->shape()), errors::InvalidArgument( "Input patterns tensor must be scalar or vector, but had shape: ", patterns_t->shape().DebugString())); const auto patterns = patterns_t->flat<string>(); int num_patterns = patterns.size(); int num_files = 0; std::vector<std::vector<string>> all_fnames(num_patterns); for (int i = 0; i < num_patterns; i++) { OP_REQUIRES_OK(context, context->env()->GetMatchingPaths(patterns(i), &all_fnames[i])); num_files += all_fnames[i].size(); } Tensor* output_t = nullptr; OP_REQUIRES_OK( context, context->allocate_output("filenames", TensorShape({num_files}), &output_t)); auto output = output_t->vec<string>(); int index = 0; for (int i = 0; i < num_patterns; ++i) { for (int j = 0; j < all_fnames[i].size(); j++) { output(index++) = all_fnames[i][j]; } } std::sort(&output(0), &output(0) + num_files); } }; REGISTER_KERNEL_BUILDER(Name("MatchingFiles").Device(DEVICE_CPU), MatchingFilesOp); } // namespace tensorflow
c++
code
2,637
534
// Copyright (c) 2011-2013 The PPCoin developers // Copyright (c) 2013-2014 The NovaCoin Developers // Copyright (c) 2014-2018 The BlackCoin Developers //Copyright (c) 2015-2020 The PIVX developers //Copyright (c) 2020 The BitalGO developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "kernel.h" #include "db.h" #include "legacy/stakemodifier.h" #include "script/interpreter.h" #include "util.h" #include "stakeinput.h" #include "utilmoneystr.h" #include <boost/assign/list_of.hpp> /** * CStakeKernel Constructor * * @param[in] pindexPrev index of the parent of the kernel block * @param[in] stakeInput input for the coinstake of the kernel block * @param[in] nBits target difficulty bits of the kernel block * @param[in] nTimeTx time of the kernel block */ CStakeKernel::CStakeKernel(const CBlockIndex* const pindexPrev, CStakeInput* stakeInput, unsigned int nBits, int nTimeTx): stakeUniqueness(stakeInput->GetUniqueness()), nTime(nTimeTx), nBits(nBits), stakeValue(stakeInput->GetValue()) { // Set kernel stake modifier if (pindexPrev->nHeight + 1 < Params().GetConsensus().height_start_StakeModifierV2) { uint64_t nStakeModifier = 0; if (!GetOldStakeModifier(stakeInput, nStakeModifier)) LogPrintf("%s : ERROR: Failed to get kernel stake modifier\n", __func__); // Modifier v1 stakeModifier << nStakeModifier; } else { // Modifier v2 stakeModifier << pindexPrev->GetStakeModifierV2(); } CBlockIndex* pindexFrom = stakeInput->GetIndexFrom(); nTimeBlockFrom = pindexFrom->nTime; } // Return stake kernel hash uint256 CStakeKernel::GetHash() const { CDataStream ss(stakeModifier); ss << nTimeBlockFrom << stakeUniqueness << nTime; return Hash(ss.begin(), ss.end()); } // Check that the kernel hash meets the target required bool CStakeKernel::CheckKernelHash(bool fSkipLog) const { // Get weighted target uint256 bnTarget; bnTarget.SetCompact(nBits); bnTarget *= (uint256(stakeValue) / 100); // Check PoS kernel hash const uint256& hashProofOfStake = GetHash(); const bool res = hashProofOfStake < bnTarget; if (!fSkipLog || res) { LogPrint(BCLog::STAKING, "%s : Proof Of Stake:" "\nssUniqueID=%s" "\nnTimeTx=%d" "\nhashProofOfStake=%s" "\nnBits=%d" "\nweight=%d" "\nbnTarget=%s (res: %d)\n\n", __func__, HexStr(stakeUniqueness), nTime, hashProofOfStake.GetHex(), nBits, stakeValue, bnTarget.GetHex(), res); } return res; } /* * PoS Validation */ // helper function for CheckProofOfStake and GetStakeKernelHash bool LoadStakeInput(const CBlock& block, const CBlockIndex* pindexPrev, std::unique_ptr<CStakeInput>& stake) { // If previous index is not provided, look for it in the blockmap if (!pindexPrev) { BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock); if (mi != mapBlockIndex.end() && (*mi).second) pindexPrev = (*mi).second; else return error("%s : couldn't find previous block", __func__); } else { // check that is the actual parent block if (block.hashPrevBlock != pindexPrev->GetBlockHash()) return error("%s : previous block mismatch"); } // Check that this is a PoS block if (!block.IsProofOfStake()) return error("called on non PoS block"); // Construct the stakeinput object const CTxIn& txin = block.vtx[1].vin[0]; stake = std::unique_ptr<CStakeInput>(new CAlgStake()); return stake->InitFromTxIn(txin); } /* * Stake Check if stakeInput can stake a block on top of pindexPrev * * @param[in] pindexPrev index of the parent block of the block being staked * @param[in] stakeInput input for the coinstake * @param[in] nBits target difficulty bits * @param[in] nTimeTx new blocktime * @return bool true if stake kernel hash meets target protocol */ bool Stake(const CBlockIndex* pindexPrev, CStakeInput* stakeInput, unsigned int nBits, int64_t& nTimeTx) { // Double check stake input contextual checks const int nHeightTx = pindexPrev->nHeight + 1; if (!stakeInput || !stakeInput->ContextCheck(nHeightTx, nTimeTx)) return false; // Get the new time slot (and verify it's not the same as previous block) const bool fRegTest = Params().IsRegTestNet(); nTimeTx = (fRegTest ? GetAdjustedTime() : GetCurrentTimeSlot()); if (nTimeTx <= pindexPrev->nTime && !fRegTest) return false; // Verify Proof Of Stake CStakeKernel stakeKernel(pindexPrev, stakeInput, nBits, nTimeTx); return stakeKernel.CheckKernelHash(true); } /* * CheckProofOfStake Check if block has valid proof of stake * * @param[in] block block being verified * @param[out] strError string error (if any, else empty) * @param[in] pindexPrev index of the parent block * (if nullptr, it will be searched in mapBlockIndex) * @return bool true if the block has a valid proof of stake */ bool CheckProofOfStake(const CBlock& block, std::string& strError, const CBlockIndex* pindexPrev) { const int nHeight = pindexPrev->nHeight + 1; // Initialize stake input std::unique_ptr<CStakeInput> stakeInput; if (!LoadStakeInput(block, pindexPrev, stakeInput)) { strError = "stake input initialization failed"; return false; } // Stake input contextual checks if (!stakeInput->ContextCheck(nHeight, block.nTime)) { strError = "stake input failing contextual checks"; return false; } // Verify Proof Of Stake CStakeKernel stakeKernel(pindexPrev, stakeInput.get(), block.nBits, block.nTime); if (!stakeKernel.CheckKernelHash()) { strError = "kernel hash check fails"; return false; } // Verify tx input signature CTxOut stakePrevout; if (!stakeInput->GetTxOutFrom(stakePrevout)) { strError = "unable to get stake prevout for coinstake"; return false; } const CTransaction& tx = block.vtx[1]; const CTxIn& txin = tx.vin[0]; ScriptError serror; if (!VerifyScript(txin.scriptSig, stakePrevout.scriptPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&tx, 0), &serror)) { strError = strprintf("signature fails: %s", serror ? ScriptErrorString(serror) : ""); return false; } // All good return true; } /* * GetStakeKernelHash Return stake kernel of a block * * @param[out] hashRet hash of the kernel (set by this function) * @param[in] block block with the kernel to return * @param[in] pindexPrev index of the parent block * (if nullptr, it will be searched in mapBlockIndex) * @return bool false if kernel cannot be initialized, true otherwise */ bool GetStakeKernelHash(uint256& hashRet, const CBlock& block, const CBlockIndex* pindexPrev) { // Initialize stake input std::unique_ptr<CStakeInput> stakeInput; if (!LoadStakeInput(block, pindexPrev, stakeInput)) return error("%s : stake input initialization failed", __func__); CStakeKernel stakeKernel(pindexPrev, stakeInput.get(), block.nBits, block.nTime); hashRet = stakeKernel.GetHash(); return true; }
c++
code
7,666
1,532
#include <fstream> #include <unordered_map> #include <vector> #include "common/hash_util.h" #include "storage/arrow_serializer.h" #include "storage/block_access_controller.h" #include "storage/block_compactor.h" #include "storage/garbage_collector.h" #include "storage/storage_defs.h" #include "storage/tuple_access_strategy.h" #include "test_util/storage_test_util.h" #include "test_util/test_harness.h" #include "transaction/deferred_action_manager.h" #define EXPORT_TABLE_NAME "test_table.arrow" #define CSV_TABLE_NAME "test_table.csv" #define PYSCRIPT_NAME "transform_table.py" #define PYSCRIPT \ "import pyarrow as pa\n" \ "pa_table = pa.ipc.open_stream('" EXPORT_TABLE_NAME \ "').read_next_batch()\n" \ "pa_table = pa_table.to_pandas()\n" \ "pa_table.to_csv('" CSV_TABLE_NAME "', index=False, header=False)\n" namespace terrier { struct ExportTableTest : public ::terrier::TerrierTest { // This function decodes a utf-8 string from a csv file char by char // Example: // \xc8\x99\r&x"" // will be decoded to: // 192 153 13 38 120 34 // (\xc8) (\x99) (\r) (&) (x) ("") bool ParseNextChar(std::ifstream &csv_file, char stop_char, char *tmp_char) { csv_file.get(*tmp_char); bool end = false; switch (*tmp_char) { case '\\': // The next char starts with \. We know there are two possible cases: // 1. for a char with value > 127, it's begin with \x // 2. for special chars, it uses \ as escape character csv_file.get(*tmp_char); if (*tmp_char == 'x') { // \x, simply parse the hexadecimal number char hex_char = '\0'; csv_file.get(hex_char); *tmp_char = static_cast<char>((hex_char >= 'a' ? (hex_char - 'a' + 10) : (hex_char - '0')) * 16); csv_file.get(hex_char); *tmp_char = static_cast<char>(*tmp_char + (hex_char >= 'a' ? (hex_char - 'a' + 10) : hex_char - '0')); } else { // \ is an escape character switch (*tmp_char) { case '\\': *tmp_char = '\\'; break; case 'r': *tmp_char = '\r'; break; case 't': *tmp_char = '\t'; break; case 'n': *tmp_char = '\n'; break; } } break; case '"': // in the csv file, quote char is used to identify an item when the item itself contains comma. // So, when we encounter a single " followed by a comma or \n, we know current item has been // completely parsed. Since "" will be parsed as ", so if " is followed by another ", then // we get an " (tmp_char is ") but we know there are still more remaining chars to parse (end = false). csv_file.get(*tmp_char); if (*tmp_char == ',' || *tmp_char == '\n') { end = true; } break; case ',': // We just need to distinguish if the , is a real comma or is a delimiter. stop_char indicates if current // item is identified by comma (instead of quote). if (stop_char == ',') { end = true; } break; default: // Normal cases, we get a general ascii char. break; } return end; } bool CheckContent(std::ifstream &csv_file, transaction::TransactionManager *txn_manager, const storage::BlockLayout &layout, const std::unordered_map<storage::TupleSlot, storage::ProjectedRow *> &tuples, const storage::DataTable &table, storage::RawBlock *block) { auto initializer = storage::ProjectedRowInitializer::Create(layout, StorageTestUtil::ProjectionListAllColumns(layout)); byte *buffer = common::AllocationUtil::AllocateAligned(initializer.ProjectedRowSize()); auto *read_row = initializer.InitializeRow(buffer); // This transaction is guaranteed to start after the compacting one commits transaction::TransactionContext *txn = txn_manager->BeginTransaction(); int num_tuples = tuples.size(); // For all the rows. for (int i = 0; i < static_cast<int>(layout.NumSlots()); i++) { storage::TupleSlot slot(block, i); if (i < num_tuples) { table.Select(common::ManagedPointer(txn), slot, read_row); // For all the columns of a row for (int j = 0; j < read_row->NumColumns(); j++) { auto col_id = read_row->ColumnIds()[j]; // We try to parse the current column (item) std::string integer; std::vector<byte> bytes; char tmp_char; csv_file.get(tmp_char); switch (tmp_char) { case '"': // Current column is a utf-8 string delimited by " csv_file.seekg(1, std::ios_base::cur); while (!ParseNextChar(csv_file, '"', &tmp_char)) { bytes.emplace_back(static_cast<byte>(tmp_char)); } break; case 'b': // Current column is a normal utf-8 string while (!ParseNextChar(csv_file, ',', &tmp_char)) { bytes.emplace_back(static_cast<byte>(tmp_char)); } break; case ',': // there is nothing between two commas. It indicates a null value break; case '\n': // Similarly, nothing between the previous comma and current \n. It indicates a null value break; default: // Integer value integer = tmp_char; std::string remaining_digits; if (j == read_row->NumColumns() - 1) { std::getline(csv_file, remaining_digits, '\n'); } else { std::getline(csv_file, remaining_digits, ','); } integer += remaining_digits; break; } auto data = read_row->AccessWithNullCheck(j); if (data == nullptr) { // Expect null value if (!bytes.empty() || integer.length() != 0) { return false; } } else { if (layout.IsVarlen(col_id)) { auto *varlen = reinterpret_cast<storage::VarlenEntry *>(data); auto content = varlen->Content(); auto content_len = varlen->Size(); if (content_len != bytes.size() - 2) { return false; } // the first and last element of bytes are always useless. for (int k = 0; k < static_cast<int>(content_len); ++k) { if (bytes[k + 1] != content[k]) { return false; } } } else { int64_t true_integer = 0; // Extract the true integer (generated in C++) based on their bit-length switch (layout.AttrSize(col_id)) { case 1: true_integer = *reinterpret_cast<int8_t *>(data); break; case 2: true_integer = *reinterpret_cast<int16_t *>(data); break; case 4: true_integer = *reinterpret_cast<int32_t *>(data); break; case 8: true_integer = *reinterpret_cast<int64_t *>(data); break; default: throw NOT_IMPLEMENTED_EXCEPTION("Unsupported Attribute Size."); } if (std::fabs(1 - (std::stof(integer) + 1e-6) / (true_integer + 1e-6)) > 1e-6) { return false; } } } } } } txn_manager->Commit(txn, transaction::TransactionUtil::EmptyCallback, nullptr); delete[] buffer; return true; } storage::BlockStore block_store_{5000, 5000}; std::default_random_engine generator_; storage::RecordBufferSegmentPool buffer_pool_{100000, 100000}; double percent_empty_ = 0.5; }; // NOLINTNEXTLINE TEST_F(ExportTableTest, ExportDictionaryCompressedTableTest) { unlink(EXPORT_TABLE_NAME); unlink(CSV_TABLE_NAME); unlink(PYSCRIPT_NAME); std::ofstream outfile(PYSCRIPT_NAME, std::ios_base::out); outfile << PYSCRIPT; outfile.close(); generator_.seed( std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()) .count()); storage::BlockLayout layout = StorageTestUtil::RandomLayoutWithVarlens(100, &generator_); storage::TupleAccessStrategy accessor(layout); // Technically, the block above is not "in" the table, but since we don't sequential scan that does not matter storage::DataTable table(common::ManagedPointer<storage::BlockStore>(&block_store_), layout, storage::layout_version_t(0)); storage::RawBlock *block = table.begin()->GetBlock(); accessor.InitializeRawBlock(&table, block, storage::layout_version_t(0)); // Enable GC to cleanup transactions started by the block compactor transaction::TimestampManager timestamp_manager; transaction::DeferredActionManager deferred_action_manager{common::ManagedPointer(&timestamp_manager)}; transaction::TransactionManager txn_manager{common::ManagedPointer(&timestamp_manager), common::ManagedPointer(&deferred_action_manager), common::ManagedPointer(&buffer_pool_), true, DISABLED}; storage::GarbageCollector gc{common::ManagedPointer(&timestamp_manager), common::ManagedPointer(&deferred_action_manager), common::ManagedPointer(&txn_manager), DISABLED}; auto tuples = StorageTestUtil::PopulateBlockRandomly(&table, block, percent_empty_, &generator_); // Manually populate the block header's arrow metadata for test initialization auto &arrow_metadata = accessor.GetArrowBlockMetadata(block); std::vector<type::TypeId> column_types; column_types.resize(layout.NumColumns()); for (storage::col_id_t col_id : layout.AllColumns()) { if (layout.IsVarlen(col_id)) { arrow_metadata.GetColumnInfo(layout, col_id).Type() = storage::ArrowColumnType::DICTIONARY_COMPRESSED; column_types[!col_id] = type::TypeId::VARCHAR; } else { arrow_metadata.GetColumnInfo(layout, col_id).Type() = storage::ArrowColumnType::FIXED_LENGTH; column_types[!col_id] = type::TypeId::INTEGER; } } storage::BlockCompactor compactor; compactor.PutInQueue(block); compactor.ProcessCompactionQueue(&deferred_action_manager, &txn_manager); // compaction pass // Need to prune the version chain in order to make sure that the second pass succeeds gc.PerformGarbageCollection(); compactor.PutInQueue(block); compactor.ProcessCompactionQueue(&deferred_action_manager, &txn_manager); // gathering pass storage::ArrowSerializer arrow_serializer(table); arrow_serializer.ExportTable(EXPORT_TABLE_NAME, &column_types); EXPECT_EQ(system((std::string("python3 ") + PYSCRIPT_NAME).c_str()), 0); std::ifstream csv_file(CSV_TABLE_NAME, std::ios_base::in); EXPECT_TRUE(CheckContent(csv_file, &txn_manager, layout, tuples, table, block)); csv_file.close(); unlink(EXPORT_TABLE_NAME); for (auto &entry : tuples) delete[] reinterpret_cast<byte *>(entry.second); // reclaim memory used for bookkeeping gc.PerformGarbageCollection(); gc.PerformGarbageCollection(); // Second call to deallocate } // NOLINTNEXTLINE TEST_F(ExportTableTest, ExportVarlenTableTest) { unlink(EXPORT_TABLE_NAME); unlink(CSV_TABLE_NAME); unlink(PYSCRIPT_NAME); std::ofstream outfile(PYSCRIPT_NAME, std::ios_base::out); outfile << PYSCRIPT; outfile.close(); generator_.seed( std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()) .count()); storage::BlockLayout layout = StorageTestUtil::RandomLayoutWithVarlens(100, &generator_); storage::TupleAccessStrategy accessor(layout); // Technically, the block above is not "in" the table, but since we don't sequential scan that does not matter storage::DataTable table(common::ManagedPointer<storage::BlockStore>(&block_store_), layout, storage::layout_version_t(0)); storage::RawBlock *block = table.begin()->GetBlock(); accessor.InitializeRawBlock(&table, block, storage::layout_version_t(0)); // Enable GC to cleanup transactions started by the block compactor transaction::TimestampManager timestamp_manager; transaction::DeferredActionManager deferred_action_manager{common::ManagedPointer(&timestamp_manager)}; transaction::TransactionManager txn_manager{common::ManagedPointer(&timestamp_manager), common::ManagedPointer(&deferred_action_manager), common::ManagedPointer(&buffer_pool_), true, DISABLED}; storage::GarbageCollector gc{common::ManagedPointer(&timestamp_manager), common::ManagedPointer(&deferred_action_manager), common::ManagedPointer(&txn_manager), DISABLED}; auto tuples = StorageTestUtil::PopulateBlockRandomly(&table, block, percent_empty_, &generator_); // Manually populate the block header's arrow metadata for test initialization auto &arrow_metadata = accessor.GetArrowBlockMetadata(block); std::vector<type::TypeId> column_types; column_types.resize(layout.NumColumns()); for (storage::col_id_t col_id : layout.AllColumns()) { if (layout.IsVarlen(col_id)) { arrow_metadata.GetColumnInfo(layout, col_id).Type() = storage::ArrowColumnType::GATHERED_VARLEN; column_types[!col_id] = type::TypeId::VARCHAR; } else { arrow_metadata.GetColumnInfo(layout, col_id).Type() = storage::ArrowColumnType::FIXED_LENGTH; column_types[!col_id] = type::TypeId::INTEGER; } } storage::BlockCompactor compactor; compactor.PutInQueue(block); compactor.ProcessCompactionQueue(&deferred_action_manager, &txn_manager); // compaction pass // Need to prune the version chain in order to make sure that the second pass succeeds gc.PerformGarbageCollection(); compactor.PutInQueue(block); compactor.ProcessCompactionQueue(&deferred_action_manager, &txn_manager); // gathering pass storage::ArrowSerializer arrow_serializer(table); arrow_serializer.ExportTable(EXPORT_TABLE_NAME, &column_types); EXPECT_EQ(system((std::string("python3 ") + PYSCRIPT_NAME).c_str()), 0); std::ifstream csv_file(CSV_TABLE_NAME, std::ios_base::in); EXPECT_TRUE(CheckContent(csv_file, &txn_manager, layout, tuples, table, block)); csv_file.close(); unlink(EXPORT_TABLE_NAME); for (auto &entry : tuples) delete[] reinterpret_cast<byte *>(entry.second); // reclaim memory used for bookkeeping gc.PerformGarbageCollection(); gc.PerformGarbageCollection(); // Second call to deallocate. } } // namespace terrier
c++
code
15,180
2,999
/* Copyright 2005-2009 Intel Corporation. All Rights Reserved. The source code contained or described herein and all documents related to the source code ("Material") are owned by Intel Corporation or its suppliers or licensors. Title to the Material remains with Intel Corporation or its suppliers and licensors. The Material is protected by worldwide copyright laws and treaty provisions. No part of the Material may be used, copied, reproduced, modified, published, uploaded, posted, transmitted, distributed, or disclosed in any way without Intel's prior express written permission. No license under any patent, copyright, trade secret or other intellectual property right is granted to or conferred upon you by disclosure or delivery of the Materials, either expressly, by implication, inducement, estoppel or otherwise. Any license under such intellectual property rights must be express and approved by Intel in writing. */ /* The original source for this example is Copyright (c) 1994-2008 John E. Stone 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. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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. */ /* * intersect.c - This file contains code for CSG and intersection routines. * * $Id: intersect.cpp,v 1.2 2007-02-22 17:54:15 dpoulsen Exp $ */ #include "machine.h" #include "types.h" #include "intersect.h" #include "light.h" #include "util.h" #include "global.h" unsigned int new_objectid(void) { return numobjects++; /* global used to generate unique object ID's */ } unsigned int max_objectid(void) { return numobjects; } void add_object(object * obj) { object * objtemp; if (obj == NULL) return; obj->id = new_objectid(); objtemp = rootobj; rootobj = obj; obj->nextobj = objtemp; } void free_objects(object * start) { object * cur; object * cur2; cur=start; while (cur->nextobj != NULL) { cur2=(object *)cur->nextobj; cur->methods->free(cur); cur=cur2; } free(cur); } void reset_object(void) { if (rootobj != NULL) free_objects(rootobj); rootobj = NULL; numobjects = 0; /* set number of objects back to 0 */ } void intersect_objects(ray * intray) { object * cur; object temp; temp.nextobj = rootobj; /* setup the initial object pointers.. */ cur = &temp; /* ready, set */ while ((cur=(object *)cur->nextobj) != NULL) cur->methods->intersect(cur, intray); } void reset_intersection(intersectstruct * intstruct) { intstruct->num = 0; intstruct->list[0].t = FHUGE; intstruct->list[0].obj = NULL; intstruct->list[1].t = FHUGE; intstruct->list[1].obj = NULL; } void add_intersection(flt t, object * obj, ray * ry) { intersectstruct * intstruct = ry->intstruct; if (t > EPSILON) { /* if we hit something before maxdist update maxdist */ if (t < ry->maxdist) { ry->maxdist = t; /* if we hit *anything* before maxdist, and we're firing a */ /* shadow ray, then we are finished ray tracing the shadow */ if (ry->flags & RT_RAY_SHADOW) ry->flags |= RT_RAY_FINISHED; } intstruct->num++; intstruct->list[intstruct->num].obj = obj; intstruct->list[intstruct->num].t = t; } } int closest_intersection(flt * t, object ** obj, intersectstruct * intstruct) { int i; *t=FHUGE; for (i=1; i<=intstruct->num; i++) { if (intstruct->list[i].t < *t) { *t=intstruct->list[i].t; *obj=intstruct->list[i].obj; } } return intstruct->num; } int shadow_intersection(intersectstruct * intstruct, flt maxdist) { int i; if (intstruct->num > 0) { for (i=1; i<=intstruct->num; i++) { if ((intstruct->list[i].t < maxdist) && (intstruct->list[i].obj->tex->shadowcast == 1)) { return 1; } } } return 0; }
c++
code
5,390
1,151
// 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 "chrome/browser/chromeos/input_method/input_method_configuration.h" #include "base/bind.h" #include "base/chromeos/chromeos_version.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "chrome/browser/chromeos/input_method/browser_state_monitor.h" #include "chrome/browser/chromeos/input_method/input_method_delegate_impl.h" #include "chrome/browser/chromeos/input_method/input_method_manager_impl.h" #include "chrome/browser/chromeos/input_method/input_method_persistence.h" #include "chromeos/ime/ibus_bridge.h" namespace chromeos { namespace input_method { namespace { InputMethodManager* g_input_method_manager = NULL; InputMethodPersistence* g_input_method_persistence = NULL; BrowserStateMonitor* g_browser_state_monitor = NULL; } // namespace void OnSessionStateChange(InputMethodManagerImpl* input_method_manager_impl, InputMethodPersistence* input_method_persistence, InputMethodManager::State new_state) { input_method_persistence->OnSessionStateChange(new_state); input_method_manager_impl->SetState(new_state); } void Initialize( const scoped_refptr<base::SequencedTaskRunner>& ui_task_runner, const scoped_refptr<base::SequencedTaskRunner>& file_task_runner) { DCHECK(!g_input_method_manager); IBusDaemonController::Initialize(ui_task_runner, file_task_runner); if (!base::chromeos::IsRunningOnChromeOS()) { // IBusBridge is for ChromeOS on desktop Linux not for ChromeOS Devices or // production at this moment. // TODO(nona): Remove this condition when ibus-daemon is gone. // (crbug.com/170671) IBusBridge::Initialize(); } InputMethodManagerImpl* impl = new InputMethodManagerImpl( scoped_ptr<InputMethodDelegate>(new InputMethodDelegateImpl)); impl->Init(ui_task_runner, file_task_runner); g_input_method_manager = impl; g_input_method_persistence = new InputMethodPersistence(g_input_method_manager); g_browser_state_monitor = new BrowserStateMonitor( base::Bind(&OnSessionStateChange, impl, g_input_method_persistence)); DVLOG(1) << "InputMethodManager initialized"; } void InitializeForTesting(InputMethodManager* mock_manager) { DCHECK(!g_input_method_manager); g_input_method_manager = mock_manager; DVLOG(1) << "InputMethodManager for testing initialized"; } void Shutdown() { delete g_browser_state_monitor; g_browser_state_monitor = NULL; delete g_input_method_persistence; g_input_method_persistence = NULL; delete g_input_method_manager; g_input_method_manager = NULL; if (IBusBridge::Get()) { // TODO(nona): Remove this condition when ibus-daemon is gone. IBusBridge::Shutdown(); } IBusDaemonController::Shutdown(); DVLOG(1) << "InputMethodManager shutdown"; } InputMethodManager* GetInputMethodManager() { DCHECK(g_input_method_manager); return g_input_method_manager; } } // namespace input_method } // namespace chromeos
c++
code
3,142
453
#ifndef BOOST_ARCHIVE_BASIC_BINARY_OARCHIVE_HPP #define BOOST_ARCHIVE_BASIC_BINARY_OARCHIVE_HPP // MS compatible compilers support #pragma once #if defined(_MSC_VER) # pragma once #endif /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // basic_binary_oarchive.hpp // (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for updates, documentation, and revision history. // archives stored as native binary - this should be the fastest way // to archive the state of a group of obects. It makes no attempt to // convert to any canonical form. // IN GENERAL, ARCHIVES CREATED WITH THIS CLASS WILL NOT BE READABLE // ON PLATFORM APART FROM THE ONE THEY ARE CREATE ON #include <boost/assert.hpp> #include <boost/config.hpp> #include <boost/detail/workaround.hpp> #include <boost/integer.hpp> #include <boost/integer_traits.hpp> #include <boost/archive/detail/common_oarchive.hpp> #include <boost/serialization/string.hpp> #include <boost/serialization/collection_size_type.hpp> #include <boost/serialization/item_version_type.hpp> #include <boost/archive/detail/abi_prefix.hpp> // must be the last header #ifdef BOOST_MSVC # pragma warning(push) # pragma warning(disable : 4511 4512) #endif namespace lslboost { namespace archive { namespace detail { template<class Archive> class interface_oarchive; } // namespace detail ////////////////////////////////////////////////////////////////////// // class basic_binary_oarchive - write serialized objects to a binary output stream // note: this archive has no pretensions to portability. Archive format // may vary across machine architectures and compilers. About the only // guarentee is that an archive created with this code will be readable // by a program built with the same tools for the same machne. This class // does have the virtue of buiding the smalles archive in the minimum amount // of time. So under some circumstances it may be he right choice. template<class Archive> class BOOST_SYMBOL_VISIBLE basic_binary_oarchive : public detail::common_oarchive<Archive> { #ifdef BOOST_NO_MEMBER_TEMPLATE_FRIENDS public: #else protected: #if BOOST_WORKAROUND(BOOST_MSVC, < 1500) // for some inexplicable reason insertion of "class" generates compile erro // on msvc 7.1 friend detail::interface_oarchive<Archive>; #else friend class detail::interface_oarchive<Archive>; #endif #endif // any datatype not specifed below will be handled by base class typedef detail::common_oarchive<Archive> detail_common_oarchive; template<class T> void save_override(const T & t){ this->detail_common_oarchive::save_override(t); } // include these to trap a change in binary format which // isn't specifically handled BOOST_STATIC_ASSERT(sizeof(tracking_type) == sizeof(bool)); // upto 32K classes BOOST_STATIC_ASSERT(sizeof(class_id_type) == sizeof(int_least16_t)); BOOST_STATIC_ASSERT(sizeof(class_id_reference_type) == sizeof(int_least16_t)); // upto 2G objects BOOST_STATIC_ASSERT(sizeof(object_id_type) == sizeof(uint_least32_t)); BOOST_STATIC_ASSERT(sizeof(object_reference_type) == sizeof(uint_least32_t)); // binary files don't include the optional information void save_override(const class_id_optional_type & /* t */){} // enable this if we decide to support generation of previous versions #if 0 void save_override(const lslboost::archive::version_type & t){ library_version_type lvt = this->get_library_version(); if(lslboost::archive::library_version_type(7) < lvt){ this->detail_common_oarchive::save_override(t); } else if(lslboost::archive::library_version_type(6) < lvt){ const lslboost::uint_least16_t x = t; * this->This() << x; } else{ const unsigned int x = t; * this->This() << x; } } void save_override(const lslboost::serialization::item_version_type & t){ library_version_type lvt = this->get_library_version(); if(lslboost::archive::library_version_type(7) < lvt){ this->detail_common_oarchive::save_override(t); } else if(lslboost::archive::library_version_type(6) < lvt){ const lslboost::uint_least16_t x = t; * this->This() << x; } else{ const unsigned int x = t; * this->This() << x; } } void save_override(class_id_type & t){ library_version_type lvt = this->get_library_version(); if(lslboost::archive::library_version_type(7) < lvt){ this->detail_common_oarchive::save_override(t); } else if(lslboost::archive::library_version_type(6) < lvt){ const lslboost::int_least16_t x = t; * this->This() << x; } else{ const int x = t; * this->This() << x; } } void save_override(class_id_reference_type & t){ save_override(static_cast<class_id_type &>(t)); } #endif // explicitly convert to char * to avoid compile ambiguities void save_override(const class_name_type & t){ const std::string s(t); * this->This() << s; } #if 0 void save_override(const serialization::collection_size_type & t){ if (get_library_version() < lslboost::archive::library_version_type(6)){ unsigned int x=0; * this->This() >> x; t = serialization::collection_size_type(x); } else{ * this->This() >> t; } } #endif BOOST_ARCHIVE_OR_WARCHIVE_DECL void init(); basic_binary_oarchive(unsigned int flags) : detail::common_oarchive<Archive>(flags) {} }; } // namespace archive } // namespace lslboost #ifdef BOOST_MSVC #pragma warning(pop) #endif #include <boost/archive/detail/abi_suffix.hpp> // pops abi_suffix.hpp pragmas #endif // BOOST_ARCHIVE_BASIC_BINARY_OARCHIVE_HPP
c++
code
6,286
1,087
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Sun Microsystems, Inc. * Portions created by the Initial Developer are Copyright (C) 1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "JNIEnvTests.h" #include "ArrayOperations.h" JNI_OJIAPITest(JNIEnv_GetObjectArrayElement_1) { GET_JNI_FOR_TEST jclass clazz = env->FindClass("Ljava/lang/String;"); jmethodID methodID = env->GetMethodID(clazz, "<init>", "(Ljava/lang/String;)V"); jchar str_chars[]={'T', 'e', 's', 't'}; jstring str = env->NewString(str_chars, 4); jobject obj = env->NewObject(clazz, methodID, str); jobjectArray arr = env->NewObjectArray(4, clazz, obj); jstring str_n = (jstring)env->GetObjectArrayElement(arr, (jsize) 0); const char* chars = (char *) env->GetStringUTFChars(str_n, NULL); if(strcmp(chars, "Test") == 0){ return TestResult::PASS("GetObjectArrayElement(all correct index >= 0 ) returns correct value - empty array"); }else{ return TestResult::FAIL("GetObjectArrayElement(all correct index >= 0 ) returns incorrect value"); } }
c++
code
2,632
618
#ifndef ALIBABACLOUD_CREDENTIAL_H_ #define ALIBABACLOUD_CREDENTIAL_H_ #include <darabonba/core.hpp> #include <boost/any.hpp> #include <boost/asio/ssl.hpp> #include <boost/asio/ssl/stream.hpp> #include <cpprest/http_client.h> #include <exception> #include <iostream> #include <json/json.h> #include <map> using namespace std; namespace Alibabacloud_Credential { class RefreshCredentialException : public exception { public: explicit RefreshCredentialException(const string &msg) { _msg = msg; } const char *what() const noexcept override { string error_info; if (_msg.empty()) { error_info = "Refresh Credential Error "; } else { error_info = "Refresh Credential Error : " + _msg; } const char *c = error_info.c_str(); return c; } void setHttpResponse(const web::http::http_response &res) { _res = res; } web::http::http_response getHttpResponse() { return _res; } private: string _msg; web::http::http_response _res; }; class Config : public Darabonba::Model { public: Config() {} explicit Config(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (accessKeyId) { res["accessKeyId"] = boost::any(*accessKeyId); } if (accessKeySecret) { res["accessKeySecret"] = boost::any(*accessKeySecret); } if (securityToken) { res["securityToken"] = boost::any(*securityToken); } if (bearerToken) { res["bearerToken"] = boost::any(*bearerToken); } if (durationSeconds) { res["durationSeconds"] = boost::any(*durationSeconds); } if (roleArn) { res["roleArn"] = boost::any(*roleArn); } if (policy) { res["policy"] = boost::any(*policy); } if (roleSessionExpiration) { res["roleSessionExpiration"] = boost::any(*roleSessionExpiration); } if (roleSessionName) { res["roleSessionName"] = boost::any(*roleSessionName); } if (publicKeyId) { res["publicKeyId"] = boost::any(*publicKeyId); } if (privateKeyFile) { res["privateKeyFile"] = boost::any(*privateKeyFile); } if (roleName) { res["roleName"] = boost::any(*roleName); } if (type) { res["type"] = boost::any(*type); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("accessKeyId") != m.end() && !m["accessKeyId"].empty()) { accessKeyId = make_shared<string>(boost::any_cast<string>(m["accessKeyId"])); } if (m.find("accessKeySecret") != m.end() && !m["accessKeySecret"].empty()) { accessKeySecret = make_shared<string>(boost::any_cast<string>(m["accessKeySecret"])); } if (m.find("securityToken") != m.end() && !m["securityToken"].empty()) { securityToken = make_shared<string>(boost::any_cast<string>(m["securityToken"])); } if (m.find("bearerToken") != m.end() && !m["bearerToken"].empty()) { bearerToken = make_shared<string>(boost::any_cast<string>(m["bearerToken"])); } if (m.find("durationSeconds") != m.end() && !m["durationSeconds"].empty()) { durationSeconds = make_shared<int>(boost::any_cast<int>(m["durationSeconds"])); } if (m.find("roleArn") != m.end() && !m["roleArn"].empty()) { roleArn = make_shared<string>(boost::any_cast<string>(m["roleArn"])); } if (m.find("policy") != m.end() && !m["policy"].empty()) { policy = make_shared<string>(boost::any_cast<string>(m["policy"])); } if (m.find("roleSessionExpiration") != m.end() && !m["roleSessionExpiration"].empty()) { roleSessionExpiration = make_shared<int>(boost::any_cast<int>(m["roleSessionExpiration"])); } if (m.find("roleSessionName") != m.end() && !m["roleSessionName"].empty()) { roleSessionName = make_shared<string>(boost::any_cast<string>(m["roleSessionName"])); } if (m.find("publicKeyId") != m.end() && !m["publicKeyId"].empty()) { publicKeyId = make_shared<string>(boost::any_cast<string>(m["publicKeyId"])); } if (m.find("privateKeyFile") != m.end() && !m["privateKeyFile"].empty()) { privateKeyFile = make_shared<string>(boost::any_cast<string>(m["privateKeyFile"])); } if (m.find("roleName") != m.end() && !m["roleName"].empty()) { roleName = make_shared<string>(boost::any_cast<string>(m["roleName"])); } if (m.find("type") != m.end() && !m["type"].empty()) { type = make_shared<string>(boost::any_cast<string>(m["type"])); } } shared_ptr<string> accessKeyId{}; shared_ptr<string> accessKeySecret{}; shared_ptr<string> securityToken{}; shared_ptr<string> bearerToken{}; shared_ptr<int> durationSeconds{}; shared_ptr<string> roleArn{}; shared_ptr<string> policy{}; shared_ptr<int> roleSessionExpiration{}; shared_ptr<string> roleSessionName{}; shared_ptr<string> publicKeyId{}; shared_ptr<string> privateKeyFile{}; shared_ptr<string> roleName{}; shared_ptr<string> type{}; ~Config() = default; }; class Credential { public: explicit Credential(const Config &config); Credential(); ~Credential(); long getExpiration() const { return _expiration; } virtual string getAccessKeyId() { return _config.accessKeyId ? *_config.accessKeyId : ""; } virtual string getAccessKeySecret() { return _config.accessKeySecret ? *_config.accessKeySecret: ""; } virtual string getSecurityToken() { return _config.securityToken ? *_config.securityToken : ""; } virtual string getBearerToken() { return _config.bearerToken ? *_config.bearerToken : ""; } string getType() const { return _config.type ? *_config.type : ""; } Config getConfig() { return _config; } string requestSTS(string accessKeySecret, web::http::method mtd, map<string, string> query); virtual web::http::http_response request(string url); protected: Config _config; string _credentialType; long _expiration = 0; bool has_expired() const; }; class AccessKeyCredential : public Credential { public: explicit AccessKeyCredential(const Config &config); string getAccessKeyId() override; string getAccessKeySecret() override; }; class BearerTokenCredential : public Credential { public: explicit BearerTokenCredential(const Config &config); string getBearerToken() override; }; class StsCredential : public Credential { public: explicit StsCredential(const Config &config); string getAccessKeyId() override; string getAccessKeySecret() override; string getSecurityToken() override; }; class EcsRamRoleCredential : public Credential { public: explicit EcsRamRoleCredential(const Config &config); string getAccessKeyId() override; string getAccessKeySecret() override; string getSecurityToken() override; private: void refresh(); void refreshRam(); void refreshCredential(); const string URL_IN_ECS_META_DATA = "/latest/meta-data/ram/security-credentials/"; const string ECS_META_DATA_FETCH_ERROR_MSG = "Failed to get RAM session credentials from ECS metadata service."; const string META_DATA_SERVICE_HOST = "100.100.100.200"; }; class RamRoleArnCredential : public Credential { public: explicit RamRoleArnCredential(const Config &config); string getAccessKeyId() override; string getAccessKeySecret() override; string getSecurityToken() override; string getRoleArn(); string getPolicy(); private: void refresh(); void refreshCredential(); string _regionId = "cn-hangzhou"; }; class RsaKeyPairCredential : public Credential { public: explicit RsaKeyPairCredential(const Config &config); string getPublicKeyId(); string getPrivateKeySecret(); string getAccessKeyId() override; string getAccessKeySecret() override; string getSecurityToken() override; private: void refresh(); void refreshCredential(); }; class Client { public: Client(); ~Client(); explicit Client(shared_ptr<Config> config); string getAccessKeyId(); string getAccessKeySecret(); string getSecurityToken(); string getBearerToken(); string getType(); string getRoleArn(); string getRoleSessionName(); string getPolicy(); string getRoleName(); string getPublicKeyId(); string getPrivateKey(); Credential getCredential(); private: Credential *_credential{}; }; } // namespace Alibabacloud_Credential #endif
c++
code
8,412
2,042
#include <Halide.h> #include <stdio.h> using namespace Halide; int main(int argc, char **argv) { Var x; const int size = 100; // Try a nest of highly connection funcs all marked inline. std::vector<Func> funcs; funcs.push_back(lambda(x, x)); funcs.push_back(lambda(x, x)); for (size_t i = 2; i < size; i++) { funcs.push_back(lambda(x, funcs[i-1](x) + funcs[i-2](x))); } Func g; g(x) = funcs[funcs.size()-1](x); g.realize(10); // Test a nest of highly connected exprs. Compilation will barf if // this gets expanded into a tree. Func f; std::vector<Expr> e(size); e[0] = x; e[1] = x; for (size_t i = 2; i < e.size(); i++) { e[i] = e[i-1] + e[i-2]; } f(x) = e[e.size()-1]; f.realize(10); printf("Success!\n"); return 0; }
c++
code
835
276
// nnet2bin/nnet-align-compiled.cc // Copyright 2009-2012 Microsoft Corporation // Johns Hopkins University (author: Daniel Povey) // 2015 Vijayaditya Peddinti // 2015-16 Vimal Manohar // See ../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "base/kaldi-common.h" #include "util/common-utils.h" #include "gmm/am-diag-gmm.h" #include "hmm/transition-model.h" #include "hmm/hmm-utils.h" #include "fstext/fstext-lib.h" #include "decoder/decoder-wrappers.h" #include "decoder/training-graph-compiler.h" #include "nnet3/nnet-am-decodable-simple.h" #include "lat/kaldi-lattice.h" int main(int argc, char *argv[]) { try { using namespace kaldi; using namespace kaldi::nnet3; typedef kaldi::int32 int32; using fst::SymbolTable; using fst::VectorFst; using fst::StdArc; const char *usage = "Align features given nnet3 neural net model\n" "Usage: nnet3-align-compiled [options] <nnet-in> <graphs-rspecifier> " "<features-rspecifier> <alignments-wspecifier>\n" "e.g.: \n" " nnet3-align-compiled 1.mdl ark:graphs.fsts scp:train.scp ark:1.ali\n" "or:\n" " compile-train-graphs tree 1.mdl lex.fst ark:train.tra b, ark:- | \\\n" " nnet3-align-compiled 1.mdl ark:- scp:train.scp t, ark:1.ali\n"; ParseOptions po(usage); AlignConfig align_config; NnetSimpleComputationOptions decodable_opts; std::string use_gpu = "yes"; BaseFloat transition_scale = 1.0; BaseFloat self_loop_scale = 1.0; std::string ivector_rspecifier, online_ivector_rspecifier, utt2spk_rspecifier; int32 online_ivector_period = 0; align_config.Register(&po); decodable_opts.Register(&po); po.Register("use-gpu", &use_gpu, "yes|no|optional|wait, only has effect if compiled with CUDA"); po.Register("transition-scale", &transition_scale, "Transition-probability scale [relative to acoustics]"); po.Register("self-loop-scale", &self_loop_scale, "Scale of self-loop versus non-self-loop " "log probs [relative to acoustics]"); po.Register("ivectors", &ivector_rspecifier, "Rspecifier for " "iVectors as vectors (i.e. not estimated online); per utterance " "by default, or per speaker if you provide the --utt2spk option."); po.Register("online-ivectors", &online_ivector_rspecifier, "Rspecifier for " "iVectors estimated online, as matrices. If you supply this," " you must set the --online-ivector-period option."); po.Register("online-ivector-period", &online_ivector_period, "Number of frames " "between iVectors in matrices supplied to the --online-ivectors " "option"); po.Read(argc, argv); if (po.NumArgs() < 4 || po.NumArgs() > 5) { po.PrintUsage(); exit(1); } #if HAVE_CUDA==1 CuDevice::Instantiate().SelectGpuId(use_gpu); #endif std::string model_in_filename = po.GetArg(1), fst_rspecifier = po.GetArg(2), feature_rspecifier = po.GetArg(3), alignment_wspecifier = po.GetArg(4), scores_wspecifier = po.GetOptArg(5); int num_done = 0, num_err = 0, num_retry = 0; double tot_like = 0.0; kaldi::int64 frame_count = 0; { TransitionModel trans_model; AmNnetSimple am_nnet; { bool binary; Input ki(model_in_filename, &binary); trans_model.Read(ki.Stream(), binary); am_nnet.Read(ki.Stream(), binary); } RandomAccessBaseFloatMatrixReader online_ivector_reader( online_ivector_rspecifier); RandomAccessBaseFloatVectorReaderMapped ivector_reader( ivector_rspecifier, utt2spk_rspecifier); SequentialTableReader<fst::VectorFstHolder> fst_reader(fst_rspecifier); RandomAccessBaseFloatMatrixReader feature_reader(feature_rspecifier); Int32VectorWriter alignment_writer(alignment_wspecifier); BaseFloatWriter scores_writer(scores_wspecifier); for (; !fst_reader.Done(); fst_reader.Next()) { std::string utt = fst_reader.Key(); if (!feature_reader.HasKey(utt)) { KALDI_WARN << "No features for utterance " << utt; num_err++; continue; } const Matrix<BaseFloat> &features = feature_reader.Value(utt); VectorFst<StdArc> decode_fst(fst_reader.Value()); fst_reader.FreeCurrent(); // this stops copy-on-write of the fst // by deleting the fst inside the reader, since we're about to mutate // the fst by adding transition probs. if (features.NumRows() == 0) { KALDI_WARN << "Zero-length utterance: " << utt; num_err++; continue; } const Matrix<BaseFloat> *online_ivectors = NULL; const Vector<BaseFloat> *ivector = NULL; if (!ivector_rspecifier.empty()) { if (!ivector_reader.HasKey(utt)) { KALDI_WARN << "No iVector available for utterance " << utt; num_err++; continue; } else { ivector = &ivector_reader.Value(utt); } } if (!online_ivector_rspecifier.empty()) { if (!online_ivector_reader.HasKey(utt)) { KALDI_WARN << "No online iVector available for utterance " << utt; num_err++; continue; } else { online_ivectors = &online_ivector_reader.Value(utt); } } { // Add transition-probs to the FST. std::vector<int32> disambig_syms; // empty. AddTransitionProbs(trans_model, disambig_syms, transition_scale, self_loop_scale, &decode_fst); } DecodableAmNnetSimple nnet_decodable( decodable_opts, trans_model, am_nnet, features, ivector, online_ivectors, online_ivector_period); AlignUtteranceWrapper(align_config, utt, decodable_opts.acoustic_scale, &decode_fst, &nnet_decodable, &alignment_writer, &scores_writer, &num_done, &num_err, &num_retry, &tot_like, &frame_count); } KALDI_LOG << "Overall log-likelihood per frame is " << (tot_like/frame_count) << " over " << frame_count<< " frames."; KALDI_LOG << "Retried " << num_retry << " out of " << (num_done + num_err) << " utterances."; KALDI_LOG << "Done " << num_done << ", errors on " << num_err; } #if HAVE_CUDA==1 CuDevice::Instantiate().PrintProfile(); #endif return (num_done != 0 ? 0 : 1); } catch(const std::exception &e) { std::cerr << e.what(); return -1; } }
c++
code
7,559
1,346
#include<iostream> #include<string> #include<vector> #include<algorithm> #include<cmath> #include<numeric> #include<set> #include<assert.h> #include<queue> #include<stack> #include<unordered_set> using namespace std; #define sim template < class c #define ris return * this #define dor > debug & operator << #define eni(x) sim > typename \ enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) { sim > struct rge { c b, e; }; sim > rge<c> range(c i, c j) { return rge<c>{i, j}; } sim > auto dud(c* x) -> decltype(cerr << *x, 0); sim > char dud(...); struct debug { #ifdef LOCAL ~debug() { cerr << endl; } eni(!=) cerr << boolalpha << i; ris; } eni(==) ris << range(begin(i), end(i)); } sim, class b dor(pair < b, c > d) { ris << "(" << d.first << ", " << d.second << ")"; } sim dor(rge<c> d) { *this << "["; for (auto it = d.b; it != d.e; ++it) *this << ", " + 2 * (it == d.b) << *it; ris << "]"; } #else sim dor(const c&) { ris; } #endif }; #define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] " #define REP(i,a,b) for(int i=a; i<b;++i) #define endl "\n" #define F first #define S second #define MP make_pair #define PB push_back #define all(a) a.begin(),a.end() #define sz(a) int((a).size()) #define tr(c,i) for(typeof(c).begin() i = c.begin(); i != c.end(); i++) #define present(c,x) (c.find(x) != c.end()) #define cpresent(c,x) (find(all(c,x) != c.end()) typedef pair< int,int > ii; typedef vector<int> vi; typedef long long ll; typedef vector< vector<int> > vvi; int INF = 1e9; void calculate() { } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; vi d(T); REP(i,0,T) cin >> d[i]; REP(i,0,T) { REP(j,i,T) { REP(k,j,T){ if (d[i] + d[j] + d[k] == 2020){ cout << d[i] * d[j] * d[k]; return 0; } } } } }
c++
code
1,928
709
/* * Copyright 2017, OYMotion Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY 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. * */ // CmdTab3_Dlg.cpp // #include "stdafx.h" #include "SDK_BLE_GUI.h" #include "CmdTab3_Dlg.h" #include "afxdialogex.h" // CmdTab3_Dlg dialog IMPLEMENT_DYNAMIC(CmdTab3_Dlg, CDialogEx) CmdTab3_Dlg::CmdTab3_Dlg(CWnd* pParent /*=NULL*/) : CDialogEx(CmdTab3_Dlg::IDD, pParent) { } CmdTab3_Dlg::~CmdTab3_Dlg() { } void CmdTab3_Dlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_TAB3_IP_BE, m_ipBondEn); DDX_Control(pDX, IDC_TAB3_IP_AE, m_ipAuthEn); DDX_Control(pDX, IDC_TAB3_IP_SPR, m_ipSendPair); DDX_Control(pDX, IDC_TAB3_PI_PK, m_piPassKey); DDX_Control(pDX, IDC_TAB3_PI_SPK, m_piSendPK); DDX_Control(pDX, IDC_TAB3_USLTK_AB, m_ltkAuthBond); DDX_Control(pDX, IDC_TAB3_USLTK_LD, m_ltkDiv); DDX_Control(pDX, IDC_TAB3_USLTK_LR, m_ltkRand); DDX_Control(pDX, IDC_TAB3_USLTK_LTK, m_ltkEdit); DDX_Control(pDX, IDC_TAB3_USLTK_EL, m_ltkEncLink); } BEGIN_MESSAGE_MAP(CmdTab3_Dlg, CDialogEx) ON_BN_CLICKED(IDC_TAB3_IP_SPR, &CmdTab3_Dlg::OnBnClickedTab3SendPairReq) ON_BN_CLICKED(IDC_TAB3_PI_SPK, &CmdTab3_Dlg::OnBnClickedTab3SendPassKey) ON_BN_CLICKED(IDC_TAB3_USLTK_EL, &CmdTab3_Dlg::OnBnClickedTab3EncLink) END_MESSAGE_MAP() // CmdTab3_Dlg message handle BOOL CmdTab3_Dlg::OnInitDialog() { CDialogEx::OnInitDialog(); return TRUE; } void CmdTab3_Dlg::OnBnClickedTab3SendPairReq() { sGapAuth auth; UINT16 conHandle; WCHAR buf[128]; if (theApp.m_cmdHandle) { memset(&auth, 0x00, sizeof(auth)); //get connection handle theApp.m_cmdView->m_conHdl.GetWindowText(buf, 10); conHandle = (UINT16)wcstol(buf, NULL, 16); //Bond enabled if (m_ipBondEn.GetCheck() == BST_CHECKED) { auth.sec_authReq.req.bonding = NPI_TRUE; } //MITM enabled if (m_ipAuthEn.GetCheck() == BST_CHECKED) { auth.sec_authReq.req.mitm = NPI_TRUE; } auth.sec_ioCaps = KEYBOARD_DISPLAY; auth.sec_oobFlag = NPI_FALSE; auth.sec_maxEncKeySize = 0x10; auth.sec_keyDist.oper = 0x77; auth.pair_en = NPI_DISABLE; auth.pair_ioCaps = NO_INPUT_NO_OUTPUT; auth.pair_oobFlag = NPI_FALSE; auth.pair_authReq.req.bonding = NPI_TRUE; auth.pair_maxEncKeySize = 0x10; auth.pair_keyDist.oper = 0x77; theApp.m_cmdHandle->GAP_Authenticate(conHandle, &auth); } } void CmdTab3_Dlg::OnBnClickedTab3SendPassKey() { } void CmdTab3_Dlg::OnBnClickedTab3EncLink() { UINT16 conHdl; eEnDisMode authFlag = NPI_DISABLE; UINT8 ltk[16] = { 0 }; UINT8 random[8] = { 0 }; WCHAR wBuf[128]; UINT16 div; if (theApp.m_cmdHandle) { //get connection handle theApp.m_cmdView->m_conHdl.GetWindowText(wBuf, 10); conHdl = (UINT16)wcstol(wBuf, NULL, 16); //get Auth Bond Flag if (m_ltkAuthBond.GetCheck() == BST_CHECKED) { authFlag = NPI_ENABLE; } //get ltk m_ltkEdit.GetWindowText(wBuf, 128); if (wstr2hex(wBuf, ltk, 16, _T("FF:"))) { //get div m_ltkDiv.GetWindowText(wBuf, 10); div = (UINT16)wcstol(wBuf, NULL, 16); //get random(8 bytes) if (wstr2hex(wBuf, random, 8, _T("FF:"))) { theApp.m_cmdHandle->GAP_Bond(conHdl, authFlag, ltk, div, random, 16); } else { AfxMessageBox(_T("Convert LTK Random Error!")); } } else { AfxMessageBox(_T("Convert LTK Error!")); } } }
c++
code
4,557
956
/**************************************************************************** ** ** Copyright (C) 2005-2005 Trolltech AS. All rights reserved. ** ** This file is part of the example classes of the Qt Toolkit. ** ** This file may be used under the terms of the GNU General Public ** License version 2.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of ** this file. Please review the following information to ensure GNU ** General Public Licensing requirements will be met: ** http://www.trolltech.com/products/qt/opensource.html ** ** If you are unsure which license is appropriate for your use, please ** review the following information: ** http://www.trolltech.com/products/qt/licensing.html or contact the ** sales department at [email protected]. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ****************************************************************************/ #include <QtGui> #include "MarGridWindow.h" MarGridWindow::MarGridWindow() { QWidget *w = new QWidget; setCentralWidget(w); createActions(); createMenus(); QPushButton *extract = new QPushButton(tr("Extract")); QPushButton *train = new QPushButton(tr("Train")); QPushButton *predict = new QPushButton(tr("Predict")); // playLabel = new QLabel("Hello"); trainLabel = new QLabel("Train File: \t ./margrid_train.mf"); predictLabel = new QLabel("Predict File: \t ./margrid_test.mf"); gridHeightLabel = new QLabel("Grid Height: "); gridWidthLabel = new QLabel("Grid Width: "); gridWidth = new QLineEdit(this); gridWidth->setMinimumWidth(30); gridWidth->setMaximumWidth(30); gridWidth->setInputMask("99"); gridWidth->setText("12"); gridHeight = new QLineEdit(this); gridHeight->setInputMask("99"); gridHeight->setMinimumWidth(30); gridHeight->setMaximumWidth(30); gridHeight->setText("12"); QWidget *margrid = new MarGrid(); connect(this, SIGNAL(trainFile(QString)), margrid, SLOT(setupTrain(QString))); connect(this, SIGNAL(predictFile(QString)), margrid, SLOT(setupPredict(QString))); connect(this, SIGNAL(playbackMode(bool)), margrid, SLOT(setPlaybackMode(bool))); connect(this, SIGNAL(blackwhiteMode(bool)), margrid, SLOT(setBlackWhiteMode(bool))); connect(this, SIGNAL(openPredictGridFile(QString)), margrid, SLOT(openPredictionGrid(QString))); connect(this, SIGNAL(savePredictGridFile(QString)), margrid, SLOT(savePredictionGrid(QString))); QWidget *gridWidthWidget = new QWidget(); QHBoxLayout *gridWidthLayout = new QHBoxLayout; gridWidthLayout->addWidget(gridWidthLabel); gridWidthLayout->addWidget(gridWidth); gridWidthWidget->setLayout(gridWidthLayout); QWidget *gridHeightWidget = new QWidget(); QHBoxLayout *gridHeightLayout = new QHBoxLayout; gridHeightLayout->addWidget(gridHeightLabel); gridHeightLayout->addWidget(gridHeight); gridHeightWidget->setLayout(gridHeightLayout); QGridLayout *gridLayout = new QGridLayout; gridLayout->addWidget(trainLabel, 0, 0); gridLayout->addWidget(gridHeightWidget, 0, 1, 1, 2); gridLayout->addWidget(predictLabel, 1, 0); gridLayout->addWidget(gridWidthWidget, 1, 1, 1,2 ); gridLayout->addWidget(extract, 2, 0); gridLayout->addWidget(train, 2, 1); gridLayout->addWidget(predict, 2, 2); // gridLayout->addWidget(gridHeightWidget,3,0, 1, 3); // gridLayout->addWidget(gridWidthWidget,4,0); // gridLayout->addWidget(playLabel, 5, 0, 1, 3); gridLayout->addWidget(margrid, 6, 0, 1, 3); connect(extract, SIGNAL(clicked()), margrid, SLOT(extract())); connect(train, SIGNAL(clicked()), margrid, SLOT(train())); connect(predict, SIGNAL(clicked()), margrid, SLOT(predict())); connect(gridWidth, SIGNAL(textChanged(QString)), margrid, SLOT(setXGridSize(QString))); connect(gridHeight, SIGNAL(textChanged(QString)), margrid, SLOT(setYGridSize(QString))); connect(margrid, SIGNAL(playingFile(QString)), this, SLOT(playingFile(QString))); // connect(margrid, SIGNAL(newGridSize(int, int)), this, SLOT(resizeGrid(int, int))); w->setLayout(gridLayout); } void MarGridWindow::playingFile(QString s) { // playLabel->setText(s); } void MarGridWindow::createMenus() { fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(openPredictAct); fileMenu->addAction(openTrainAct); fileMenu->addAction(playbackAct); fileMenu->addAction(blackwhiteAct); fileMenu->addSeparator(); fileMenu->addAction(openPredictGridAct); fileMenu->addAction(savePerdictGridAct); menuBar()->addSeparator(); helpMenu = menuBar()->addMenu(tr("&Help")); helpMenu->addAction(aboutAct); } void MarGridWindow::openTrainFile() { QString fileName = QFileDialog::getOpenFileName(this); cout << "fileName = " << fileName.toStdString() << endl; trainLabel->setText("TrainFile: \t" + fileName); emit trainFile(fileName); } void MarGridWindow::openPredictFile() { QString fileName = QFileDialog::getOpenFileName(this); predictLabel->setText("PredictFile: \t" + fileName); emit predictFile(fileName); } void MarGridWindow::openPredictionGrid() { QString fileName = QFileDialog::getOpenFileName(this); cout << "Emit" << endl; emit openPredictGridFile(fileName); } void MarGridWindow::savePredictionGrid() { QString fileName = QFileDialog::getSaveFileName(this); cout << "Save" << endl; emit savePredictGridFile(fileName); } void MarGridWindow::resizeGrid(int height, int width) { gridHeight->setText("" + height); gridWidth->setText("" + width); } void MarGridWindow::createActions() { openTrainAct = new QAction(tr("&Open Collection File for Training"), this); openTrainAct->setStatusTip(tr("Open Collection File for Training")); connect(openTrainAct, SIGNAL(triggered()), this, SLOT(openTrainFile())); openPredictAct = new QAction(tr("&Open Collection File for Predicting"), this); openPredictAct->setStatusTip(tr("Open Collection File for Prediciting")); connect(openPredictAct, SIGNAL(triggered()), this, SLOT(openPredictFile())); // connect(openAct, SIGNAL(triggered()), this, SLOT(open())); aboutAct = new QAction(tr("&About"), this); aboutAct->setStatusTip(tr("Show the application's About box")); connect(aboutAct, SIGNAL(triggered(bool)), this, SLOT(about())); openPredictGridAct = new QAction(tr("&Open Saved Prediction Grid"), this); openPredictGridAct->setStatusTip(tr("Open Saved Prediction Grid")); connect(openPredictGridAct, SIGNAL(triggered(bool)), this, SLOT(openPredictionGrid())); savePerdictGridAct = new QAction(tr("&Save Prediction Grid"),this); savePerdictGridAct->setStatusTip(tr("Save Prediction Grid")); connect(savePerdictGridAct, SIGNAL(triggered(bool)), this, SLOT(savePredictionGrid())); playbackAct = new QAction(tr("&Continuous Playback mode"), this); playbackAct->setStatusTip(tr("Continuous Playback mode")); playbackAct->setCheckable(true); connect(playbackAct, SIGNAL(toggled(bool)), this, SIGNAL(playbackMode(bool))); blackwhiteAct = new QAction(tr("&Display as Black and White only"), this); blackwhiteAct->setStatusTip(tr("Display as Black and White only")); blackwhiteAct->setCheckable(true); connect(blackwhiteAct, SIGNAL(toggled(bool)), this, SIGNAL(blackwhiteMode(bool))); } void MarGridWindow::about() { QMessageBox::about(this, tr("Marsyas MarGrid"), tr("Marsyas MarGrid: Demonstrates continuous-feedback \n content-based music browsing using Self Organizing Maps")); }
c++
code
7,535
1,948
/* Copyright 2020 The TensorFlow Authors. 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 <stdlib.h> #include <string.h> #include "google/cloud/storage/client.h" #include "tensorflow/c/experimental/filesystem/filesystem_interface.h" #include "tensorflow/c/tf_status.h" // Implementation of a filesystem for GCS environments. // This filesystem will support `gs://` URI schemes. namespace gcs = google::cloud::storage; // We can cast `google::cloud::StatusCode` to `TF_Code` because they have the // same integer values. See // https://github.com/googleapis/google-cloud-cpp/blob/6c09cbfa0160bc046e5509b4dd2ab4b872648b4a/google/cloud/status.h#L32-L52 static inline void TF_SetStatusFromGCSStatus( const google::cloud::Status& gcs_status, TF_Status* status) { TF_SetStatus(status, static_cast<TF_Code>(gcs_status.code()), gcs_status.message().c_str()); } static void* plugin_memory_allocate(size_t size) { return calloc(1, size); } static void plugin_memory_free(void* ptr) { free(ptr); } // SECTION 1. Implementation for `TF_RandomAccessFile` // ---------------------------------------------------------------------------- namespace tf_random_access_file { // TODO(vnvo2409): Implement later } // namespace tf_random_access_file // SECTION 2. Implementation for `TF_WritableFile` // ---------------------------------------------------------------------------- namespace tf_writable_file { // TODO(vnvo2409): Implement later } // namespace tf_writable_file // SECTION 3. Implementation for `TF_ReadOnlyMemoryRegion` // ---------------------------------------------------------------------------- namespace tf_read_only_memory_region { // TODO(vnvo2409): Implement later } // namespace tf_read_only_memory_region // SECTION 4. Implementation for `TF_Filesystem`, the actual filesystem // ---------------------------------------------------------------------------- namespace tf_gcs_filesystem { // TODO(vnvo2409): Add lazy-loading and customizing parameters. static void Init(TF_Filesystem* filesystem, TF_Status* status) { google::cloud::StatusOr<gcs::Client> client = gcs::Client::CreateDefaultClient(); if (!client) { TF_SetStatusFromGCSStatus(client.status(), status); return; } filesystem->plugin_filesystem = plugin_memory_allocate(sizeof(gcs::Client)); auto gcs_client = static_cast<gcs::Client*>(filesystem->plugin_filesystem); (*gcs_client) = client.value(); TF_SetStatus(status, TF_OK, ""); } // TODO(vnvo2409): Implement later } // namespace tf_gcs_filesystem static void ProvideFilesystemSupportFor(TF_FilesystemPluginOps* ops, const char* uri) { TF_SetFilesystemVersionMetadata(ops); ops->scheme = strdup(uri); ops->filesystem_ops = static_cast<TF_FilesystemOps*>( plugin_memory_allocate(TF_FILESYSTEM_OPS_SIZE)); ops->filesystem_ops->init = tf_gcs_filesystem::Init; } void TF_InitPlugin(TF_FilesystemPluginInfo* info) { info->plugin_memory_allocate = plugin_memory_allocate; info->plugin_memory_free = plugin_memory_free; info->num_schemes = 1; info->ops = static_cast<TF_FilesystemPluginOps*>( plugin_memory_allocate(info->num_schemes * sizeof(info->ops[0]))); ProvideFilesystemSupportFor(&info->ops[0], "gs"); }
c++
code
3,855
799
/* --------------------------------------------------------------------------- Open Asset Import Library (assimp) --------------------------------------------------------------------------- Copyright (c) 2006-2016, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ /** @file UnrealLoader.cpp * @brief Implementation of the UNREAL (*.3D) importer class * * Sources: * http://local.wasp.uwa.edu.au/~pbourke/dataformats/unreal/ */ #ifndef ASSIMP_BUILD_NO_3D_IMPORTER #include "UnrealLoader.h" #include "StreamReader.h" #include "ParsingUtils.h" #include "fast_atof.h" #include "ConvertToLHProcess.h" #include <assimp/Importer.hpp> #include <assimp/DefaultLogger.hpp> #include <assimp/IOSystem.hpp> #include <assimp/scene.h> #include <memory> using namespace Assimp; static const aiImporterDesc desc = { "Unreal Mesh Importer", "", "", "", aiImporterFlags_SupportTextFlavour, 0, 0, 0, 0, "3d uc" }; // ------------------------------------------------------------------------------------------------ // Constructor to be privately used by Importer UnrealImporter::UnrealImporter() : configFrameID (0) , configHandleFlags (true) {} // ------------------------------------------------------------------------------------------------ // Destructor, private as well UnrealImporter::~UnrealImporter() {} // ------------------------------------------------------------------------------------------------ // Returns whether the class can handle the format of the given file. bool UnrealImporter::CanRead( const std::string& pFile, IOSystem* /*pIOHandler*/, bool /*checkSig*/) const { return SimpleExtensionCheck(pFile,"3d","uc"); } // ------------------------------------------------------------------------------------------------ // Build a string of all file extensions supported const aiImporterDesc* UnrealImporter::GetInfo () const { return &desc; } // ------------------------------------------------------------------------------------------------ // Setup configuration properties for the loader void UnrealImporter::SetupProperties(const Importer* pImp) { // The // AI_CONFIG_IMPORT_UNREAL_KEYFRAME option overrides the // AI_CONFIG_IMPORT_GLOBAL_KEYFRAME option. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_UNREAL_KEYFRAME,-1); if(static_cast<unsigned int>(-1) == configFrameID) { configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_GLOBAL_KEYFRAME,0); } // AI_CONFIG_IMPORT_UNREAL_HANDLE_FLAGS, default is true configHandleFlags = (0 != pImp->GetPropertyInteger(AI_CONFIG_IMPORT_UNREAL_HANDLE_FLAGS,1)); } // ------------------------------------------------------------------------------------------------ // Imports the given file into the given scene structure. void UnrealImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) { // For any of the 3 files being passed get the three correct paths // First of all, determine file extension std::string::size_type pos = pFile.find_last_of('.'); std::string extension = GetExtension(pFile); std::string d_path,a_path,uc_path; if (extension == "3d") { // jjjj_d.3d // jjjj_a.3d pos = pFile.find_last_of('_'); if (std::string::npos == pos) { throw DeadlyImportError("UNREAL: Unexpected naming scheme"); } extension = pFile.substr(0,pos); } else { extension = pFile.substr(0,pos); } // build proper paths d_path = extension+"_d.3d"; a_path = extension+"_a.3d"; uc_path = extension+".uc"; DefaultLogger::get()->debug("UNREAL: data file is " + d_path); DefaultLogger::get()->debug("UNREAL: aniv file is " + a_path); DefaultLogger::get()->debug("UNREAL: uc file is " + uc_path); // and open the files ... we can't live without them IOStream* p = pIOHandler->Open(d_path); if (!p) throw DeadlyImportError("UNREAL: Unable to open _d file"); StreamReaderLE d_reader(pIOHandler->Open(d_path)); const uint16_t numTris = d_reader.GetI2(); const uint16_t numVert = d_reader.GetI2(); d_reader.IncPtr(44); if (!numTris || numVert < 3) throw DeadlyImportError("UNREAL: Invalid number of vertices/triangles"); // maximum texture index unsigned int maxTexIdx = 0; // collect triangles std::vector<Unreal::Triangle> triangles(numTris); for (auto & tri : triangles) { for (unsigned int i = 0; i < 3;++i) { tri.mVertex[i] = d_reader.GetI2(); if (tri.mVertex[i] >= numTris) { DefaultLogger::get()->warn("UNREAL: vertex index out of range"); tri.mVertex[i] = 0; } } tri.mType = d_reader.GetI1(); // handle mesh flagss? if (configHandleFlags) tri.mType = Unreal::MF_NORMAL_OS; else { // ignore MOD and MASKED for the moment, treat them as two-sided if (tri.mType == Unreal::MF_NORMAL_MOD_TS || tri.mType == Unreal::MF_NORMAL_MASKED_TS) tri.mType = Unreal::MF_NORMAL_TS; } d_reader.IncPtr(1); for (unsigned int i = 0; i < 3;++i) for (unsigned int i2 = 0; i2 < 2;++i2) tri.mTex[i][i2] = d_reader.GetI1(); tri.mTextureNum = d_reader.GetI1(); maxTexIdx = std::max(maxTexIdx,(unsigned int)tri.mTextureNum); d_reader.IncPtr(1); } p = pIOHandler->Open(a_path); if (!p) throw DeadlyImportError("UNREAL: Unable to open _a file"); StreamReaderLE a_reader(pIOHandler->Open(a_path)); // read number of frames const uint32_t numFrames = a_reader.GetI2(); if (configFrameID >= numFrames) throw DeadlyImportError("UNREAL: The requested frame does not exist"); uint32_t st = a_reader.GetI2(); if (st != numVert*4) throw DeadlyImportError("UNREAL: Unexpected aniv file length"); // skip to our frame a_reader.IncPtr(configFrameID *numVert*4); // collect vertices std::vector<aiVector3D> vertices(numVert); for (auto &vertex : vertices) { int32_t val = a_reader.GetI4(); Unreal::DecompressVertex(vertex ,val); } // list of textures. std::vector< std::pair<unsigned int, std::string> > textures; // allocate the output scene aiNode* nd = pScene->mRootNode = new aiNode(); nd->mName.Set("<UnrealRoot>"); // we can live without the uc file if necessary std::unique_ptr<IOStream> pb (pIOHandler->Open(uc_path)); if (pb.get()) { std::vector<char> _data; TextFileToBuffer(pb.get(),_data); const char* data = &_data[0]; std::vector< std::pair< std::string,std::string > > tempTextures; // do a quick search in the UC file for some known, usually texture-related, tags for (;*data;++data) { if (TokenMatchI(data,"#exec",5)) { SkipSpacesAndLineEnd(&data); // #exec TEXTURE IMPORT [...] NAME=jjjjj [...] FILE=jjjj.pcx [...] if (TokenMatchI(data,"TEXTURE",7)) { SkipSpacesAndLineEnd(&data); if (TokenMatchI(data,"IMPORT",6)) { tempTextures.push_back(std::pair< std::string,std::string >()); std::pair< std::string,std::string >& me = tempTextures.back(); for (;!IsLineEnd(*data);++data) { if (!::ASSIMP_strincmp(data,"NAME=",5)) { const char *d = data+=5; for (;!IsSpaceOrNewLine(*data);++data); me.first = std::string(d,(size_t)(data-d)); } else if (!::ASSIMP_strincmp(data,"FILE=",5)) { const char *d = data+=5; for (;!IsSpaceOrNewLine(*data);++data); me.second = std::string(d,(size_t)(data-d)); } } if (!me.first.length() || !me.second.length()) tempTextures.pop_back(); } } // #exec MESHMAP SETTEXTURE MESHMAP=box NUM=1 TEXTURE=Jtex1 // #exec MESHMAP SCALE MESHMAP=box X=0.1 Y=0.1 Z=0.2 else if (TokenMatchI(data,"MESHMAP",7)) { SkipSpacesAndLineEnd(&data); if (TokenMatchI(data,"SETTEXTURE",10)) { textures.push_back(std::pair<unsigned int, std::string>()); std::pair<unsigned int, std::string>& me = textures.back(); for (;!IsLineEnd(*data);++data) { if (!::ASSIMP_strincmp(data,"NUM=",4)) { data += 4; me.first = strtoul10(data,&data); } else if (!::ASSIMP_strincmp(data,"TEXTURE=",8)) { data += 8; const char *d = data; for (;!IsSpaceOrNewLine(*data);++data); me.second = std::string(d,(size_t)(data-d)); // try to find matching path names, doesn't care if we don't find them for (std::vector< std::pair< std::string,std::string > >::const_iterator it = tempTextures.begin(); it != tempTextures.end(); ++it) { if ((*it).first == me.second) { me.second = (*it).second; break; } } } } } else if (TokenMatchI(data,"SCALE",5)) { for (;!IsLineEnd(*data);++data) { if (data[0] == 'X' && data[1] == '=') { data = fast_atoreal_move<float>(data+2,(float&)nd->mTransformation.a1); } else if (data[0] == 'Y' && data[1] == '=') { data = fast_atoreal_move<float>(data+2,(float&)nd->mTransformation.b2); } else if (data[0] == 'Z' && data[1] == '=') { data = fast_atoreal_move<float>(data+2,(float&)nd->mTransformation.c3); } } } } } } } else { DefaultLogger::get()->error("Unable to open .uc file"); } std::vector<Unreal::TempMat> materials; materials.reserve(textures.size()*2+5); // find out how many output meshes and materials we'll have and build material indices for (Unreal::Triangle &tri : triangles) { Unreal::TempMat mat(tri); std::vector<Unreal::TempMat>::iterator nt = std::find(materials.begin(),materials.end(),mat); if (nt == materials.end()) { // add material tri.matIndex = static_cast<unsigned int>(materials.size()); mat.numFaces = 1; materials.push_back(mat); ++pScene->mNumMeshes; } else { tri.matIndex = static_cast<unsigned int>(nt-materials.begin()); ++nt->numFaces; } } if (!pScene->mNumMeshes) { throw DeadlyImportError("UNREAL: Unable to find valid mesh data"); } // allocate meshes and bind them to the node graph pScene->mMeshes = new aiMesh*[pScene->mNumMeshes]; pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials = pScene->mNumMeshes]; nd->mNumMeshes = pScene->mNumMeshes; nd->mMeshes = new unsigned int[nd->mNumMeshes]; for (unsigned int i = 0; i < pScene->mNumMeshes;++i) { aiMesh* m = pScene->mMeshes[i] = new aiMesh(); m->mPrimitiveTypes = aiPrimitiveType_TRIANGLE; const unsigned int num = materials[i].numFaces; m->mFaces = new aiFace [num]; m->mVertices = new aiVector3D [num*3]; m->mTextureCoords[0] = new aiVector3D [num*3]; nd->mMeshes[i] = i; // create materials, too aiMaterial* mat = new aiMaterial(); pScene->mMaterials[i] = mat; // all white by default - texture rulez aiColor3D color(1.f,1.f,1.f); aiString s; ::ai_snprintf( s.data, MAXLEN, "mat%u_tx%u_",i,materials[i].tex ); // set the two-sided flag if (materials[i].type == Unreal::MF_NORMAL_TS) { const int twosided = 1; mat->AddProperty(&twosided,1,AI_MATKEY_TWOSIDED); ::strcat(s.data,"ts_"); } else ::strcat(s.data,"os_"); // make TRANS faces 90% opaque that RemRedundantMaterials won't catch us if (materials[i].type == Unreal::MF_NORMAL_TRANS_TS) { const float opac = 0.9f; mat->AddProperty(&opac,1,AI_MATKEY_OPACITY); ::strcat(s.data,"tran_"); } else ::strcat(s.data,"opaq_"); // a special name for the weapon attachment point if (materials[i].type == Unreal::MF_WEAPON_PLACEHOLDER) { s.length = ::ai_snprintf( s.data, MAXLEN, "$WeaponTag$" ); color = aiColor3D(0.f,0.f,0.f); } // set color and name mat->AddProperty(&color,1,AI_MATKEY_COLOR_DIFFUSE); s.length = ::strlen(s.data); mat->AddProperty(&s,AI_MATKEY_NAME); // set texture, if any const unsigned int tex = materials[i].tex; for (std::vector< std::pair< unsigned int, std::string > >::const_iterator it = textures.begin();it != textures.end();++it) { if ((*it).first == tex) { s.Set((*it).second); mat->AddProperty(&s,AI_MATKEY_TEXTURE_DIFFUSE(0)); break; } } } // fill them. for (const Unreal::Triangle &tri : triangles) { Unreal::TempMat mat(tri); std::vector<Unreal::TempMat>::iterator nt = std::find(materials.begin(),materials.end(),mat); aiMesh* mesh = pScene->mMeshes[nt-materials.begin()]; aiFace& f = mesh->mFaces[mesh->mNumFaces++]; f.mIndices = new unsigned int[f.mNumIndices = 3]; for (unsigned int i = 0; i < 3;++i,mesh->mNumVertices++) { f.mIndices[i] = mesh->mNumVertices; mesh->mVertices[mesh->mNumVertices] = vertices[ tri.mVertex[i] ]; mesh->mTextureCoords[0][mesh->mNumVertices] = aiVector3D( tri.mTex[i][0] / 255.f, 1.f - tri.mTex[i][1] / 255.f, 0.f); } } // convert to RH MakeLeftHandedProcess hero; hero.Execute(pScene); FlipWindingOrderProcess flipper; flipper.Execute(pScene); } #endif // !! ASSIMP_BUILD_NO_3D_IMPORTER
c++
code
16,715
3,886
/* This file is part of the JitCat library. Copyright (C) Machiel van Hooren 2018 Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT). */ #include "jitcat/SLRParseResult.h" #include "jitcat/ASTNode.h" using namespace jitcat::Parser; SLRParseResult::SLRParseResult(): astRootNode(nullptr), success(false) { } SLRParseResult::~SLRParseResult() { } SLRParseResult::SLRParseResult(SLRParseResult&& other): astRootNode(std::move(other.astRootNode)), success(other.success) { } SLRParseResult& SLRParseResult::operator=(SLRParseResult&& other) { success = other.success; astRootNode = std::move(other.astRootNode); return *this; } SLRParseResult& jitcat::Parser::SLRParseResult::operator=(std::unique_ptr<SLRParseResult>&& other) { SLRParseResult* otherPtr = other.release(); success = otherPtr->success; astRootNode = std::move(otherPtr->astRootNode); delete otherPtr; return *this; } void SLRParseResult::clear() { success = false; astRootNode.reset(nullptr); }
c++
code
1,033
233
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync_file_system/drive_backend/sync_engine.h" #include "base/bind.h" #include "base/threading/sequenced_worker_pool.h" #include "base/values.h" #include "chrome/browser/drive/drive_api_service.h" #include "chrome/browser/drive/drive_notification_manager.h" #include "chrome/browser/drive/drive_notification_manager_factory.h" #include "chrome/browser/drive/drive_service_interface.h" #include "chrome/browser/drive/drive_uploader.h" #include "chrome/browser/drive/drive_uploader.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/profile_oauth2_token_service.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/sync_file_system/drive_backend/conflict_resolver.h" #include "chrome/browser/sync_file_system/drive_backend/drive_backend_constants.h" #include "chrome/browser/sync_file_system/drive_backend/list_changes_task.h" #include "chrome/browser/sync_file_system/drive_backend/local_to_remote_syncer.h" #include "chrome/browser/sync_file_system/drive_backend/metadata_database.h" #include "chrome/browser/sync_file_system/drive_backend/register_app_task.h" #include "chrome/browser/sync_file_system/drive_backend/remote_to_local_syncer.h" #include "chrome/browser/sync_file_system/drive_backend/sync_engine_initializer.h" #include "chrome/browser/sync_file_system/drive_backend/uninstall_app_task.h" #include "chrome/browser/sync_file_system/file_status_observer.h" #include "chrome/browser/sync_file_system/logger.h" #include "chrome/browser/sync_file_system/sync_task.h" #include "chrome/browser/sync_file_system/syncable_file_system_util.h" #include "content/public/browser/browser_thread.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/extension_system_provider.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/common/extension.h" #include "google_apis/drive/drive_api_url_generator.h" #include "google_apis/drive/gdata_wapi_url_generator.h" #include "webkit/common/blob/scoped_file.h" #include "webkit/common/fileapi/file_system_util.h" namespace sync_file_system { namespace drive_backend { namespace { void EmptyStatusCallback(SyncStatusCode status) {} } // namespace scoped_ptr<SyncEngine> SyncEngine::CreateForBrowserContext( content::BrowserContext* context) { GURL base_drive_url( google_apis::DriveApiUrlGenerator::kBaseUrlForProduction); GURL base_download_url( google_apis::DriveApiUrlGenerator::kBaseDownloadUrlForProduction); GURL wapi_base_url( google_apis::GDataWapiUrlGenerator::kBaseUrlForProduction); scoped_refptr<base::SequencedWorkerPool> worker_pool( content::BrowserThread::GetBlockingPool()); scoped_refptr<base::SequencedTaskRunner> drive_task_runner( worker_pool->GetSequencedTaskRunnerWithShutdownBehavior( worker_pool->GetSequenceToken(), base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)); Profile* profile = Profile::FromBrowserContext(context); ProfileOAuth2TokenService* token_service = ProfileOAuth2TokenServiceFactory::GetForProfile(profile); SigninManagerBase* signin_manager = SigninManagerFactory::GetForProfile(profile); scoped_ptr<drive::DriveServiceInterface> drive_service( new drive::DriveAPIService( token_service, context->GetRequestContext(), drive_task_runner.get(), base_drive_url, base_download_url, wapi_base_url, std::string() /* custom_user_agent */)); drive_service->Initialize(signin_manager->GetAuthenticatedAccountId()); scoped_ptr<drive::DriveUploaderInterface> drive_uploader( new drive::DriveUploader(drive_service.get(), drive_task_runner.get())); drive::DriveNotificationManager* notification_manager = drive::DriveNotificationManagerFactory::GetForBrowserContext(context); ExtensionService* extension_service = extensions::ExtensionSystem::Get( context)->extension_service(); scoped_refptr<base::SequencedTaskRunner> task_runner( worker_pool->GetSequencedTaskRunnerWithShutdownBehavior( worker_pool->GetSequenceToken(), base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)); scoped_ptr<drive_backend::SyncEngine> sync_engine( new SyncEngine( GetSyncFileSystemDir(context->GetPath()), task_runner.get(), drive_service.Pass(), drive_uploader.Pass(), notification_manager, extension_service, token_service, NULL)); sync_engine->Initialize(); return sync_engine.Pass(); } void SyncEngine::AppendDependsOnFactories( std::set<BrowserContextKeyedServiceFactory*>* factories) { DCHECK(factories); factories->insert(drive::DriveNotificationManagerFactory::GetInstance()); factories->insert(ProfileOAuth2TokenServiceFactory::GetInstance()); factories->insert( extensions::ExtensionsBrowserClient::Get()->GetExtensionSystemFactory()); } SyncEngine::~SyncEngine() { net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this); drive_service_->RemoveObserver(this); if (notification_manager_) notification_manager_->RemoveObserver(this); } void SyncEngine::Initialize() { DCHECK(!task_manager_); task_manager_.reset(new SyncTaskManager(weak_ptr_factory_.GetWeakPtr())); task_manager_->Initialize(SYNC_STATUS_OK); PostInitializeTask(); if (notification_manager_) notification_manager_->AddObserver(this); drive_service_->AddObserver(this); net::NetworkChangeNotifier::AddNetworkChangeObserver(this); net::NetworkChangeNotifier::ConnectionType type = net::NetworkChangeNotifier::GetConnectionType(); network_available_ = type != net::NetworkChangeNotifier::CONNECTION_NONE; } void SyncEngine::AddServiceObserver(SyncServiceObserver* observer) { service_observers_.AddObserver(observer); } void SyncEngine::AddFileStatusObserver(FileStatusObserver* observer) { file_status_observers_.AddObserver(observer); } void SyncEngine::RegisterOrigin( const GURL& origin, const SyncStatusCallback& callback) { if (!metadata_database_ && drive_service_->HasRefreshToken()) PostInitializeTask(); task_manager_->ScheduleSyncTaskAtPriority( scoped_ptr<SyncTask>(new RegisterAppTask(this, origin.host())), SyncTaskManager::PRIORITY_HIGH, callback); } void SyncEngine::EnableOrigin( const GURL& origin, const SyncStatusCallback& callback) { task_manager_->ScheduleTaskAtPriority( base::Bind(&SyncEngine::DoEnableApp, weak_ptr_factory_.GetWeakPtr(), origin.host()), SyncTaskManager::PRIORITY_HIGH, callback); } void SyncEngine::DisableOrigin( const GURL& origin, const SyncStatusCallback& callback) { task_manager_->ScheduleTaskAtPriority( base::Bind(&SyncEngine::DoDisableApp, weak_ptr_factory_.GetWeakPtr(), origin.host()), SyncTaskManager::PRIORITY_HIGH, callback); } void SyncEngine::UninstallOrigin( const GURL& origin, UninstallFlag flag, const SyncStatusCallback& callback) { task_manager_->ScheduleSyncTaskAtPriority( scoped_ptr<SyncTask>(new UninstallAppTask(this, origin.host(), flag)), SyncTaskManager::PRIORITY_HIGH, callback); } void SyncEngine::ProcessRemoteChange( const SyncFileCallback& callback) { RemoteToLocalSyncer* syncer = new RemoteToLocalSyncer(this); task_manager_->ScheduleSyncTask( scoped_ptr<SyncTask>(syncer), base::Bind(&SyncEngine::DidProcessRemoteChange, weak_ptr_factory_.GetWeakPtr(), syncer, callback)); } void SyncEngine::SetRemoteChangeProcessor( RemoteChangeProcessor* processor) { remote_change_processor_ = processor; } LocalChangeProcessor* SyncEngine::GetLocalChangeProcessor() { return this; } bool SyncEngine::IsConflicting(const fileapi::FileSystemURL& url) { // TODO(tzik): Implement this before we support manual conflict resolution. return false; } RemoteServiceState SyncEngine::GetCurrentState() const { return service_state_; } void SyncEngine::GetOriginStatusMap(OriginStatusMap* status_map) { DCHECK(status_map); if (!extension_service_ || !metadata_database_) return; std::vector<std::string> app_ids; metadata_database_->GetRegisteredAppIDs(&app_ids); for (std::vector<std::string>::const_iterator itr = app_ids.begin(); itr != app_ids.end(); ++itr) { const std::string& app_id = *itr; GURL origin = extensions::Extension::GetBaseURLFromExtensionId(app_id); (*status_map)[origin] = metadata_database_->IsAppEnabled(app_id) ? "Enabled" : "Disabled"; } } scoped_ptr<base::ListValue> SyncEngine::DumpFiles(const GURL& origin) { if (!metadata_database_) return scoped_ptr<base::ListValue>(); return metadata_database_->DumpFiles(origin.host()); } scoped_ptr<base::ListValue> SyncEngine::DumpDatabase() { if (!metadata_database_) return scoped_ptr<base::ListValue>(); return metadata_database_->DumpDatabase(); } void SyncEngine::SetSyncEnabled(bool enabled) { if (sync_enabled_ == enabled) return; RemoteServiceState old_state = GetCurrentState(); sync_enabled_ = enabled; if (old_state == GetCurrentState()) return; const char* status_message = enabled ? "Sync is enabled" : "Sync is disabled"; FOR_EACH_OBSERVER( Observer, service_observers_, OnRemoteServiceStateUpdated(GetCurrentState(), status_message)); } SyncStatusCode SyncEngine::SetConflictResolutionPolicy( ConflictResolutionPolicy policy) { conflict_resolution_policy_ = policy; return SYNC_STATUS_OK; } ConflictResolutionPolicy SyncEngine::GetConflictResolutionPolicy() const { return conflict_resolution_policy_; } void SyncEngine::GetRemoteVersions( const fileapi::FileSystemURL& url, const RemoteVersionsCallback& callback) { // TODO(tzik): Implement this before we support manual conflict resolution. callback.Run(SYNC_STATUS_FAILED, std::vector<Version>()); } void SyncEngine::DownloadRemoteVersion( const fileapi::FileSystemURL& url, const std::string& version_id, const DownloadVersionCallback& callback) { // TODO(tzik): Implement this before we support manual conflict resolution. callback.Run(SYNC_STATUS_FAILED, webkit_blob::ScopedFile()); } void SyncEngine::PromoteDemotedChanges() { if (metadata_database_) metadata_database_->PromoteLowerPriorityTrackersToNormal(); } void SyncEngine::ApplyLocalChange( const FileChange& local_change, const base::FilePath& local_path, const SyncFileMetadata& local_metadata, const fileapi::FileSystemURL& url, const SyncStatusCallback& callback) { LocalToRemoteSyncer* syncer = new LocalToRemoteSyncer( this, local_metadata, local_change, local_path, url); task_manager_->ScheduleSyncTask( scoped_ptr<SyncTask>(syncer), base::Bind(&SyncEngine::DidApplyLocalChange, weak_ptr_factory_.GetWeakPtr(), syncer, callback)); } void SyncEngine::MaybeScheduleNextTask() { if (GetCurrentState() == REMOTE_SERVICE_DISABLED) return; // TODO(tzik): Notify observer of OnRemoteChangeQueueUpdated. // TODO(tzik): Add an interface to get the number of dirty trackers to // MetadataDatabase. MaybeStartFetchChanges(); } void SyncEngine::NotifyLastOperationStatus( SyncStatusCode sync_status, bool used_network) { UpdateServiceStateFromSyncStatusCode(sync_status, used_network); if (metadata_database_) { FOR_EACH_OBSERVER( Observer, service_observers_, OnRemoteChangeQueueUpdated( metadata_database_->GetDirtyTrackerCount())); } } void SyncEngine::OnNotificationReceived() { if (service_state_ == REMOTE_SERVICE_TEMPORARY_UNAVAILABLE) UpdateServiceState(REMOTE_SERVICE_OK, "Got push notification for Drive."); should_check_remote_change_ = true; MaybeScheduleNextTask(); } void SyncEngine::OnPushNotificationEnabled(bool enabled) {} void SyncEngine::OnReadyToSendRequests() { if (service_state_ == REMOTE_SERVICE_OK) return; UpdateServiceState(REMOTE_SERVICE_OK, "Authenticated"); if (!metadata_database_ && auth_token_service_) { SigninManagerBase* signin_manager = SigninManagerFactory::GetForProfile(auth_token_service_->profile()); drive_service_->Initialize(signin_manager->GetAuthenticatedAccountId()); PostInitializeTask(); return; } should_check_remote_change_ = true; MaybeScheduleNextTask(); } void SyncEngine::OnRefreshTokenInvalid() { UpdateServiceState( REMOTE_SERVICE_AUTHENTICATION_REQUIRED, "Found invalid refresh token."); } void SyncEngine::OnNetworkChanged( net::NetworkChangeNotifier::ConnectionType type) { bool new_network_availability = type != net::NetworkChangeNotifier::CONNECTION_NONE; if (network_available_ && !new_network_availability) { UpdateServiceState(REMOTE_SERVICE_TEMPORARY_UNAVAILABLE, "Disconnected"); } else if (!network_available_ && new_network_availability) { UpdateServiceState(REMOTE_SERVICE_OK, "Connected"); should_check_remote_change_ = true; MaybeStartFetchChanges(); } network_available_ = new_network_availability; } drive::DriveServiceInterface* SyncEngine::GetDriveService() { return drive_service_.get(); } drive::DriveUploaderInterface* SyncEngine::GetDriveUploader() { return drive_uploader_.get(); } MetadataDatabase* SyncEngine::GetMetadataDatabase() { return metadata_database_.get(); } RemoteChangeProcessor* SyncEngine::GetRemoteChangeProcessor() { return remote_change_processor_; } base::SequencedTaskRunner* SyncEngine::GetBlockingTaskRunner() { return task_runner_.get(); } SyncEngine::SyncEngine( const base::FilePath& base_dir, base::SequencedTaskRunner* task_runner, scoped_ptr<drive::DriveServiceInterface> drive_service, scoped_ptr<drive::DriveUploaderInterface> drive_uploader, drive::DriveNotificationManager* notification_manager, ExtensionServiceInterface* extension_service, ProfileOAuth2TokenService* auth_token_service, leveldb::Env* env_override) : base_dir_(base_dir), task_runner_(task_runner), env_override_(env_override), drive_service_(drive_service.Pass()), drive_uploader_(drive_uploader.Pass()), notification_manager_(notification_manager), extension_service_(extension_service), auth_token_service_(auth_token_service), remote_change_processor_(NULL), service_state_(REMOTE_SERVICE_TEMPORARY_UNAVAILABLE), should_check_conflict_(true), should_check_remote_change_(true), listing_remote_changes_(false), sync_enabled_(false), conflict_resolution_policy_(CONFLICT_RESOLUTION_POLICY_LAST_WRITE_WIN), network_available_(false), weak_ptr_factory_(this) { } void SyncEngine::DoDisableApp(const std::string& app_id, const SyncStatusCallback& callback) { if (metadata_database_) metadata_database_->DisableApp(app_id, callback); else callback.Run(SYNC_STATUS_OK); } void SyncEngine::DoEnableApp(const std::string& app_id, const SyncStatusCallback& callback) { if (metadata_database_) metadata_database_->EnableApp(app_id, callback); else callback.Run(SYNC_STATUS_OK); } void SyncEngine::PostInitializeTask() { DCHECK(!metadata_database_); // This initializer task may not run if metadata_database_ is already // initialized when it runs. SyncEngineInitializer* initializer = new SyncEngineInitializer(this, task_runner_.get(), drive_service_.get(), base_dir_.Append(kDatabaseName), env_override_); task_manager_->ScheduleSyncTaskAtPriority( scoped_ptr<SyncTask>(initializer), SyncTaskManager::PRIORITY_HIGH, base::Bind(&SyncEngine::DidInitialize, weak_ptr_factory_.GetWeakPtr(), initializer)); } void SyncEngine::DidInitialize(SyncEngineInitializer* initializer, SyncStatusCode status) { if (status != SYNC_STATUS_OK) { if (drive_service_->HasRefreshToken()) { UpdateServiceState(REMOTE_SERVICE_TEMPORARY_UNAVAILABLE, "Could not initialize remote service"); } else { UpdateServiceState(REMOTE_SERVICE_AUTHENTICATION_REQUIRED, "Authentication required."); } return; } scoped_ptr<MetadataDatabase> metadata_database = initializer->PassMetadataDatabase(); if (metadata_database) metadata_database_ = metadata_database.Pass(); DCHECK(metadata_database_); UpdateRegisteredApps(); } void SyncEngine::DidProcessRemoteChange(RemoteToLocalSyncer* syncer, const SyncFileCallback& callback, SyncStatusCode status) { if (syncer->is_sync_root_deletion()) { MetadataDatabase::ClearDatabase(metadata_database_.Pass()); PostInitializeTask(); callback.Run(status, syncer->url()); return; } if (status == SYNC_STATUS_OK) { if (syncer->sync_action() != SYNC_ACTION_NONE && syncer->url().is_valid()) { FOR_EACH_OBSERVER(FileStatusObserver, file_status_observers_, OnFileStatusChanged(syncer->url(), SYNC_FILE_STATUS_SYNCED, syncer->sync_action(), SYNC_DIRECTION_REMOTE_TO_LOCAL)); } if (syncer->sync_action() == SYNC_ACTION_DELETED && syncer->url().is_valid() && fileapi::VirtualPath::IsRootPath(syncer->url().path())) { RegisterOrigin(syncer->url().origin(), base::Bind(&EmptyStatusCallback)); } should_check_conflict_ = true; } callback.Run(status, syncer->url()); } void SyncEngine::DidApplyLocalChange(LocalToRemoteSyncer* syncer, const SyncStatusCallback& callback, SyncStatusCode status) { if ((status == SYNC_STATUS_OK || status == SYNC_STATUS_RETRY) && syncer->url().is_valid() && syncer->sync_action() != SYNC_ACTION_NONE) { fileapi::FileSystemURL updated_url = syncer->url(); if (!syncer->target_path().empty()) { updated_url = CreateSyncableFileSystemURL(syncer->url().origin(), syncer->target_path()); } FOR_EACH_OBSERVER(FileStatusObserver, file_status_observers_, OnFileStatusChanged(updated_url, SYNC_FILE_STATUS_SYNCED, syncer->sync_action(), SYNC_DIRECTION_LOCAL_TO_REMOTE)); } if (status == SYNC_STATUS_UNKNOWN_ORIGIN && syncer->url().is_valid()) { RegisterOrigin(syncer->url().origin(), base::Bind(&EmptyStatusCallback)); } if (syncer->needs_remote_change_listing() && !listing_remote_changes_) { task_manager_->ScheduleSyncTaskAtPriority( scoped_ptr<SyncTask>(new ListChangesTask(this)), SyncTaskManager::PRIORITY_HIGH, base::Bind(&SyncEngine::DidFetchChanges, weak_ptr_factory_.GetWeakPtr())); should_check_remote_change_ = false; listing_remote_changes_ = true; time_to_check_changes_ = base::TimeTicks::Now() + base::TimeDelta::FromSeconds(kListChan
c++
code
20,000
3,125
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2015, Oracle and/or its affiliates. // Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_ENVELOPE_TRANSFORM_UNITS_HPP #define BOOST_GEOMETRY_ALGORITHMS_DETAIL_ENVELOPE_TRANSFORM_UNITS_HPP #include <cstddef> #include <boost/geometry/core/tag.hpp> #include <boost/geometry/core/tags.hpp> #include <boost/geometry/strategies/strategy_transform.hpp> #include <boost/geometry/views/detail/indexed_point_view.hpp> #include <boost/geometry/views/detail/two_dimensional_view.hpp> #include <boost/geometry/algorithms/not_implemented.hpp> #include <boost/geometry/algorithms/transform.hpp> namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace envelope { template < typename GeometryIn, typename GeometryOut, typename TagIn = typename tag<GeometryIn>::type, typename TagOut = typename tag<GeometryOut>::type > struct transform_units_impl : not_implemented<TagIn, TagOut> {}; template <typename PointIn, typename PointOut> struct transform_units_impl<PointIn, PointOut, point_tag, point_tag> { static inline void apply(PointIn const& point_in, PointOut& point_out) { detail::two_dimensional_view<PointIn const> view_in(point_in); detail::two_dimensional_view<PointOut> view_out(point_out); geometry::transform(view_in, view_out); } }; template <typename BoxIn, typename BoxOut> struct transform_units_impl<BoxIn, BoxOut, box_tag, box_tag> { template <std::size_t Index> static inline void apply(BoxIn const& box_in, BoxOut& box_out) { typedef detail::indexed_point_view<BoxIn const, Index> view_in_type; typedef detail::indexed_point_view<BoxOut, Index> view_out_type; view_in_type view_in(box_in); view_out_type view_out(box_out); transform_units_impl < view_in_type, view_out_type >::apply(view_in, view_out); } static inline void apply(BoxIn const& box_in, BoxOut& box_out) { apply<min_corner>(box_in, box_out); apply<max_corner>(box_in, box_out); } }; // Short utility to transform the units of the first two coordinates of // geometry_in to the units of geometry_out template <typename GeometryIn, typename GeometryOut> inline void transform_units(GeometryIn const& geometry_in, GeometryOut& geometry_out) { transform_units_impl < GeometryIn, GeometryOut >::apply(geometry_in, geometry_out); } }} // namespace detail::envelope #endif // DOXYGEN_NO_DETAIL }} // namespace boost:geometry #endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_ENVELOPE_TRANSFORM_UNITS_HPP
c++
code
2,946
451
// Copyright 2021 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 "ui/accessibility/ax_computed_node_data.h" #include "base/check_op.h" #include "base/i18n/break_iterator.h" #include "base/logging.h" #include "base/numerics/safe_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node.h" #include "ui/accessibility/ax_node_position.h" #include "ui/accessibility/ax_position.h" #include "ui/accessibility/ax_range.h" #include "ui/accessibility/ax_tree_manager.h" #include "ui/accessibility/ax_tree_manager_map.h" namespace ui { AXComputedNodeData::AXComputedNodeData(const AXNode& node) : owner_(&node) {} AXComputedNodeData::~AXComputedNodeData() = default; int AXComputedNodeData::GetOrComputeUnignoredIndexInParent() const { DCHECK(!owner_->IsIgnored()); if (unignored_index_in_parent_) return *unignored_index_in_parent_; if (const AXNode* unignored_parent = owner_->GetUnignoredParent()) { unignored_parent->GetComputedNodeData().ComputeUnignoredValues(); } else { // This should be the root node and, by convention, we assign it an // index-in-parent of 0. unignored_index_in_parent_ = 0; } return *unignored_index_in_parent_; } int AXComputedNodeData::GetOrComputeUnignoredChildCount() const { DCHECK(!owner_->IsIgnored()); if (!unignored_child_count_) ComputeUnignoredValues(); return *unignored_child_count_; } const std::vector<AXNodeID>& AXComputedNodeData::GetOrComputeUnignoredChildIDs() const { DCHECK(!owner_->IsIgnored()); if (!unignored_child_ids_) ComputeUnignoredValues(); return *unignored_child_ids_; } bool AXComputedNodeData::HasOrCanComputeAttribute( const ax::mojom::StringAttribute attribute) const { if (owner_->data().HasStringAttribute(attribute)) return true; switch (attribute) { case ax::mojom::StringAttribute::kValue: // The value attribute could be computed on the browser for content // editables and ARIA text/search boxes. return owner_->data().IsNonAtomicTextField(); default: return false; } } bool AXComputedNodeData::HasOrCanComputeAttribute( const ax::mojom::IntListAttribute attribute) const { if (owner_->data().HasIntListAttribute(attribute)) return true; switch (attribute) { case ax::mojom::IntListAttribute::kLineStarts: case ax::mojom::IntListAttribute::kLineEnds: case ax::mojom::IntListAttribute::kSentenceStarts: case ax::mojom::IntListAttribute::kSentenceEnds: case ax::mojom::IntListAttribute::kWordStarts: case ax::mojom::IntListAttribute::kWordEnds: return true; default: return false; } } const std::string& AXComputedNodeData::GetOrComputeAttributeUTF8( const ax::mojom::StringAttribute attribute) const { if (owner_->data().HasStringAttribute(attribute)) return owner_->data().GetStringAttribute(attribute); switch (attribute) { case ax::mojom::StringAttribute::kValue: if (owner_->data().IsNonAtomicTextField()) { DCHECK(HasOrCanComputeAttribute(attribute)) << "Code in `HasOrCanComputeAttribute` should be in sync with " "'GetOrComputeAttributeUTF8`"; return GetOrComputeInnerTextUTF8(); } return base::EmptyString(); default: // This is a special case: for performance reasons do not use // `base::EmptyString()` in other places throughout the codebase. return base::EmptyString(); } } std::u16string AXComputedNodeData::GetOrComputeAttributeUTF16( const ax::mojom::StringAttribute attribute) const { return base::UTF8ToUTF16(GetOrComputeAttributeUTF8(attribute)); } const std::vector<int32_t>& AXComputedNodeData::GetOrComputeAttribute( const ax::mojom::IntListAttribute attribute) const { if (owner_->data().HasIntListAttribute(attribute)) return owner_->data().GetIntListAttribute(attribute); const std::vector<int32_t>* result = nullptr; switch (attribute) { case ax::mojom::IntListAttribute::kLineStarts: ComputeLineOffsetsIfNeeded(); result = &(*line_starts_); break; case ax::mojom::IntListAttribute::kLineEnds: ComputeLineOffsetsIfNeeded(); result = &(*line_ends_); break; case ax::mojom::IntListAttribute::kSentenceStarts: ComputeSentenceOffsetsIfNeeded(); result = &(*sentence_starts_); break; case ax::mojom::IntListAttribute::kSentenceEnds: ComputeSentenceOffsetsIfNeeded(); result = &(*sentence_ends_); break; case ax::mojom::IntListAttribute::kWordStarts: ComputeWordOffsetsIfNeeded(); result = &(*word_starts_); break; case ax::mojom::IntListAttribute::kWordEnds: ComputeWordOffsetsIfNeeded(); result = &(*word_ends_); break; default: return owner_->data().GetIntListAttribute( ax::mojom::IntListAttribute::kNone); } DCHECK(HasOrCanComputeAttribute(attribute)) << "Code in `HasOrCanComputeAttribute` should be in sync with " "'GetOrComputeAttribute`"; DCHECK(result); return *result; } const std::string& AXComputedNodeData::GetOrComputeInnerTextUTF8() const { if (!inner_text_utf8_) { VLOG_IF(1, inner_text_utf16_) << "Only a single encoding of inner text should be cached."; auto range = AXRange<AXPosition<AXNodePosition, AXNode>>::RangeOfContents(*owner_); inner_text_utf8_ = base::UTF16ToUTF8( range.GetText(AXTextConcatenationBehavior::kAsInnerText)); } return *inner_text_utf8_; } const std::u16string& AXComputedNodeData::GetOrComputeInnerTextUTF16() const { if (!inner_text_utf16_) { VLOG_IF(1, inner_text_utf8_) << "Only a single encoding of inner text should be cached."; auto range = AXRange<AXPosition<AXNodePosition, AXNode>>::RangeOfContents(*owner_); inner_text_utf16_ = range.GetText(AXTextConcatenationBehavior::kAsInnerText); } return *inner_text_utf16_; } const std::string& AXComputedNodeData::GetOrComputeTextContentUTF8() const { if (!text_content_utf8_) { VLOG_IF(1, text_content_utf16_) << "Only a single encoding of text content should be cached."; text_content_utf8_ = ComputeTextContentUTF8(); } return *text_content_utf8_; } const std::u16string& AXComputedNodeData::GetOrComputeTextContentUTF16() const { if (!text_content_utf16_) { VLOG_IF(1, text_content_utf8_) << "Only a single encoding of text content should be cached."; text_content_utf16_ = ComputeTextContentUTF16(); } return *text_content_utf16_; } int AXComputedNodeData::GetOrComputeTextContentLengthUTF8() const { return static_cast<int>(GetOrComputeTextContentUTF8().length()); } int AXComputedNodeData::GetOrComputeTextContentLengthUTF16() const { return static_cast<int>(GetOrComputeTextContentUTF16().length()); } void AXComputedNodeData::ComputeUnignoredValues( int starting_index_in_parent) const { // Reset any previously computed values. unignored_index_in_parent_ = absl::nullopt; unignored_child_count_ = absl::nullopt; unignored_child_ids_ = absl::nullopt; int unignored_child_count = 0; std::vector<AXNodeID> unignored_child_ids; for (auto iter = owner_->AllChildrenBegin(); iter != owner_->AllChildrenEnd(); ++iter) { const AXComputedNodeData& computed_data = iter->GetComputedNodeData(); int new_index_in_parent = starting_index_in_parent + unignored_child_count; if (iter->IsIgnored()) { // Skip the ignored node and recursively look at its children. computed_data.ComputeUnignoredValues(new_index_in_parent); DCHECK(computed_data.unignored_child_count_); unignored_child_count += *computed_data.unignored_child_count_; DCHECK(computed_data.unignored_child_ids_); unignored_child_ids.insert(unignored_child_ids.end(), computed_data.unignored_child_ids_->begin(), computed_data.unignored_child_ids_->end()); } else { ++unignored_child_count; unignored_child_ids.push_back(iter->id()); computed_data.unignored_index_in_parent_ = new_index_in_parent; } } // Ignored nodes store unignored child information in order to propagate it to // their parents, but do not expose it directly. unignored_child_count_ = unignored_child_count; unignored_child_ids_ = unignored_child_ids; } void AXComputedNodeData::ComputeLineOffsetsIfNeeded() const { if (line_starts_ || line_ends_) { DCHECK_EQ(line_starts_->size(), line_ends_->size()); return; // Already cached. } line_starts_ = std::vector<int32_t>(); line_ends_ = std::vector<int32_t>(); const std::u16string& text_content = GetOrComputeTextContentUTF16(); if (text_content.empty()) return; // TODO(nektar): Using the `base::i18n::BreakIterator` class is not enough. We // also need to pass information from Blink as to which inline text boxes // start a new line and deprecate next/previous_on_line. base::i18n::BreakIterator iter(text_content, base::i18n::BreakIterator::BREAK_NEWLINE); if (!iter.Init()) return; while (iter.Advance()) { line_starts_->push_back(base::checked_cast<int32_t>(iter.prev())); line_ends_->push_back(base::checked_cast<int32_t>(iter.pos())); } } void AXComputedNodeData::ComputeSentenceOffsetsIfNeeded() const { if (sentence_starts_ || sentence_ends_) { DCHECK_EQ(sentence_starts_->size(), sentence_ends_->size()); return; // Already cached. } sentence_starts_ = std::vector<int32_t>(); sentence_ends_ = std::vector<int32_t>(); const std::u16string& text_content = GetOrComputeTextContentUTF16(); if (text_content.empty()) return; // Unlike in ICU, a sentence boundary is not valid in Blink if it falls within // some whitespace that is used to separate sentences. We therefore need to // filter the boundaries returned by ICU and return a subset of them. For // example we should exclude a sentence boundary that is between two space // characters, "Hello. | there.". // TODO(nektar): The above is not accomplished simply by using the // `base::i18n::BreakIterator` class. base::i18n::BreakIterator iter(text_content, base::i18n::BreakIterator::BREAK_SENTENCE); if (!iter.Init()) return; while (iter.Advance()) { sentence_starts_->push_back(base::checked_cast<int32_t>(iter.prev())); sentence_ends_->push_back(base::checked_cast<int32_t>(iter.pos())); } } void AXComputedNodeData::ComputeWordOffsetsIfNeeded() const { if (word_starts_ || word_ends_) { DCHECK_EQ(word_starts_->size(), word_ends_->size()); return; // Already cached. } word_starts_ = std::vector<int32_t>(); word_ends_ = std::vector<int32_t>(); const std::u16string& text_content = GetOrComputeTextContentUTF16(); if (text_content.empty()) return; // Unlike in ICU, a word boundary is valid in Blink only if it is before, or // immediately preceded by, an alphanumeric character, a series of punctuation // marks, an underscore or a line break. We therefore need to filter the // boundaries returned by ICU and return a subset of them. For example we // should exclude a word boundary that is between two space characters, "Hello // | there". // TODO(nektar): Fix the fact that the `base::i18n::BreakIterator` class does // not take into account underscores as word separators. base::i18n::BreakIterator iter(text_content, base::i18n::BreakIterator::BREAK_WORD); if (!iter.Init()) return; while (iter.Advance()) { if (iter.IsWord()) { word_starts_->push_back(base::checked_cast<int>(iter.prev())); word_ends_->push_back(base::checked_cast<int>(iter.pos())); } } } std::string AXComputedNodeData::ComputeTextContentUTF8() const { // If a text field has no descendants, then we compute its text content from // its value or its placeholder. Otherwise we prefer to look at its descendant // text nodes because Blink doesn't always add all trailing white space to the // value attribute. const bool is_atomic_text_field_without_descendants = (owner_->data().IsTextField() && !owner_->GetUnignoredChildCount()); if (is_atomic_text_field_without_descendants) { std::string value = owner_->data().GetStringAttribute(ax::mojom::StringAttribute::kValue); // If the value is empty, then there might be some placeholder text in the // text field, or any other name that is derived from visible contents, even // if the text field has no children, so we treat this as any other leaf // node. if (!value.empty()) return value; } // Ordinarily, atomic text fields are leaves, and for all leaves we directly // retrieve their text content using the information provided by the tree // source, such as Blink. However, for atomic text fields we need to exclude // them from the set of leaf nodes when they expose any descendants. This is // because we want to compute their text content from their descendant text // nodes as we don't always trust the "value" attribute provided by Blink. const bool is_atomic_text_field_with_descendants = (owner_->data().IsTextField() && owner_->GetUnignoredChildCount()); if (owner_->IsLeaf() && !is_atomic_text_field_with_descendants) { switch (owner_->data().GetNameFrom()) { case ax::mojom::NameFrom::kNone: case ax::mojom::NameFrom::kUninitialized: // The accessible name is not displayed on screen, e.g. aria-label, or is // not displayed directly inside the node, e.g. an associated label // element. case ax::mojom::NameFrom::kAttribute: // The node's accessible name is explicitly empty. case ax::mojom::NameFrom::kAttributeExplicitlyEmpty: // The accessible name does not represent the entirety of the node's text // content, e.g. a table's caption or a figure's figcaption. case ax::mojom::NameFrom::kCaption: case ax::mojom::NameFrom::kRelatedElement: // The accessible name is not displayed directly inside the node but is // visible via e.g. a tooltip. case ax::mojom::NameFrom::kTitle: return std::string(); case ax::mojom::NameFrom::kContents: // The placeholder text is initially displayed inside the text field and // takes the place of its value. case ax::mojom::NameFrom::kPlaceholder: // The value attribute takes the place of the node's text content, e.g. // the value of a submit button is displayed inside the button itself. case ax::mojom::NameFrom::kValue: return owner_->data().GetStringAttribute( ax::mojom::StringAttribute::kName); } } std::string text_content; for (auto it = owner_->UnignoredChildrenCrossingTreeBoundaryBegin(); it != owner_->UnignoredChildrenCrossingTreeBoundaryEnd(); ++it) { text_content += it->GetInnerText(); } return text_content; } std::u16string AXComputedNodeData::ComputeTextContentUTF16() const { return base::UTF8ToUTF16(ComputeTextContentUTF8()); } } // namespace ui
c++
code
15,359
3,032
/* -- MAGMA (version 2.2.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date November 2016 @generated from sparse/control/magma_zfree.cpp, normal z -> s, Sun Nov 20 20:20:42 2016 @author Hartwig Anzt */ #include "magmasparse_internal.h" /** Purpose ------- Free the memory of a magma_s_matrix. Arguments --------- @param[in,out] A magma_s_matrix* matrix to free @param[in] queue magma_queue_t Queue to execute in. @ingroup magmasparse_saux ********************************************************************/ extern "C" magma_int_t magma_smfree( magma_s_matrix *A, magma_queue_t queue ) { if ( A->memory_location == Magma_CPU ) { if (A->storage_type == Magma_ELL || A->storage_type == Magma_ELLPACKT) { magma_free_cpu( A->val ); magma_free_cpu( A->col ); A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; } if (A->storage_type == Magma_ELLD ) { magma_free_cpu( A->val ); magma_free_cpu( A->col ); A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; } if ( A->storage_type == Magma_ELLRT ) { magma_free_cpu( A->val ); magma_free_cpu( A->row ); magma_free_cpu( A->col ); A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; } if ( A->storage_type == Magma_SELLP ) { magma_free_cpu( A->val ); magma_free_cpu( A->row ); magma_free_cpu( A->col ); A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; } if ( A->storage_type == Magma_CSR5 ) { magma_free_cpu( A->val ); magma_free_cpu( A->row ); magma_free_cpu( A->col ); magma_free_cpu( A->tile_ptr ); magma_free_cpu( A->tile_desc ); magma_free_cpu( A->tile_desc_offset_ptr ); magma_free_cpu( A->tile_desc_offset ); magma_free_cpu( A->calibrator ); A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; A->csr5_sigma = 0; A->csr5_bit_y_offset = 0; A->csr5_bit_scansum_offset = 0; A->csr5_num_packets = 0; A->csr5_p = 0; A->csr5_num_offsets = 0; A->csr5_tail_tile_start = 0; } if ( A->storage_type == Magma_CSRLIST ) { magma_free_cpu( A->val ); magma_free_cpu( A->row ); magma_free_cpu( A->col ); magma_free_cpu( A->list ); A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; } if ( A->storage_type == Magma_CSR || A->storage_type == Magma_CSC || A->storage_type == Magma_CSRD || A->storage_type == Magma_CSRL || A->storage_type == Magma_CSRU ) { magma_free_cpu( A->val ); magma_free_cpu( A->col ); magma_free_cpu( A->row ); A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; } if ( A->storage_type == Magma_CSRCOO ) { magma_free_cpu( A->val ); magma_free_cpu( A->col ); magma_free_cpu( A->row ); magma_free_cpu( A->rowidx ); A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; } if ( A->storage_type == Magma_BCSR ) { magma_free_cpu( A->val ); magma_free_cpu( A->col ); magma_free_cpu( A->row ); magma_free_cpu( A->blockinfo ); A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; A->blockinfo = 0; } if ( A->storage_type == Magma_DENSE ) { magma_free_cpu( A->val ); A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; } A->val = NULL; A->col = NULL; A->row = NULL; A->rowidx = NULL; A->blockinfo = NULL; A->diag = NULL; A->dval = NULL; A->dcol = NULL; A->drow = NULL; A->drowidx = NULL; A->ddiag = NULL; A->dlist = NULL; A->list = NULL; A->tile_ptr = NULL; A->dtile_ptr = NULL; A->tile_desc = NULL; A->dtile_desc = NULL; A->tile_desc_offset_ptr = NULL; A->dtile_desc_offset_ptr = NULL; A->tile_desc_offset = NULL; A->dtile_desc_offset = NULL; A->calibrator = NULL; A->dcalibrator = NULL; } if ( A->memory_location == Magma_DEV ) { if (A->storage_type == Magma_ELL || A->storage_type == Magma_ELLPACKT) { if ( magma_free( A->dval ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->dcol ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; } if ( A->storage_type == Magma_ELLD ) { if ( magma_free( A->dval ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->dcol ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; } if ( A->storage_type == Magma_ELLRT ) { if ( magma_free( A->dval ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->drow ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->dcol ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; } if ( A->storage_type == Magma_SELLP ) { if ( magma_free( A->dval ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->drow ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->dcol ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; } if ( A->storage_type == Magma_CSR5 ) { if ( magma_free( A->dval ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->drow ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->dcol ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->dtile_ptr ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->dtile_desc ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->dtile_desc_offset_ptr ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->dtile_desc_offset ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->dcalibrator ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; A->csr5_sigma = 0; A->csr5_bit_y_offset = 0; A->csr5_bit_scansum_offset = 0; A->csr5_num_packets = 0; A->csr5_p = 0; A->csr5_num_offsets = 0; A->csr5_tail_tile_start = 0; } if ( A->storage_type == Magma_CSRLIST ) { if ( magma_free( A->dval ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->drow ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->dcol ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->dlist ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; } if ( A->storage_type == Magma_CSR || A->storage_type == Magma_CSC || A->storage_type == Magma_CSRD || A->storage_type == Magma_CSRL || A->storage_type == Magma_CSRU ) { if ( magma_free( A->dval ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->drow ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->dcol ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; } if ( A->storage_type == Magma_CSRCOO ) { if ( magma_free( A->dval ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->drow ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->dcol ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->drowidx ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; } if ( A->storage_type == Magma_BCSR ) { if ( magma_free( A->dval ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->drow ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } if ( magma_free( A->dcol ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } magma_free_cpu( A->blockinfo ); A->blockinfo = NULL; A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; } if ( A->storage_type == Magma_DENSE ) { if ( magma_free( A->dval ) != MAGMA_SUCCESS ) { printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } A->num_rows = 0; A->num_cols = 0; A->nnz = 0; A->true_nnz = 0; } A->val = NULL; A->col = NULL; A->row = NULL; A->rowidx = NULL; A->blockinfo = NULL; A->diag = NULL; A->dval = NULL; A->dcol = NULL; A->drow = NULL; A->drowidx = NULL; A->ddiag = NULL; A->dlist = NULL; A->list = NULL; A->tile_ptr = NULL; A->dtile_ptr = NULL; A->tile_desc = NULL; A->dtile_desc = NULL; A->tile_desc_offset_ptr = NULL; A->dtile_desc_offset_ptr = NULL; A->tile_desc_offset = NULL; A->dtile_desc_offset = NULL; A->calibrator = NULL; A->dcalibrator = NULL; } else { // printf("Memory Free Error.\n"); return MAGMA_ERR_INVALID_PTR; } return MAGMA_SUCCESS; }
c++
code
13,515
2,796
// Copyright 2014 the V8 project 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 "src/execution.h" #include "src/api-inl.h" #include "src/bootstrapper.h" #include "src/compiler-dispatcher/optimizing-compile-dispatcher.h" #include "src/debug/debug.h" #include "src/isolate-inl.h" #include "src/messages.h" #include "src/runtime-profiler.h" #include "src/vm-state-inl.h" namespace v8 { namespace internal { StackGuard::StackGuard() : isolate_(nullptr) {} void StackGuard::set_interrupt_limits(const ExecutionAccess& lock) { DCHECK_NOT_NULL(isolate_); thread_local_.set_jslimit(kInterruptLimit); thread_local_.set_climit(kInterruptLimit); isolate_->heap()->SetStackLimits(); } void StackGuard::reset_limits(const ExecutionAccess& lock) { DCHECK_NOT_NULL(isolate_); thread_local_.set_jslimit(thread_local_.real_jslimit_); thread_local_.set_climit(thread_local_.real_climit_); isolate_->heap()->SetStackLimits(); } static void PrintDeserializedCodeInfo(Handle<JSFunction> function) { if (function->code() == function->shared()->GetCode() && function->shared()->deserialized()) { PrintF("[Running deserialized script"); Object* script = function->shared()->script(); if (script->IsScript()) { Object* name = Script::cast(script)->name(); if (name->IsString()) { PrintF(": %s", String::cast(name)->ToCString().get()); } } PrintF("]\n"); } } namespace { V8_WARN_UNUSED_RESULT MaybeHandle<Object> Invoke( Isolate* isolate, bool is_construct, Handle<Object> target, Handle<Object> receiver, int argc, Handle<Object> args[], Handle<Object> new_target, Execution::MessageHandling message_handling, Execution::Target execution_target) { DCHECK(!receiver->IsJSGlobalObject()); #ifdef USE_SIMULATOR // Simulators use separate stacks for C++ and JS. JS stack overflow checks // are performed whenever a JS function is called. However, it can be the case // that the C++ stack grows faster than the JS stack, resulting in an overflow // there. Add a check here to make that less likely. StackLimitCheck check(isolate); if (check.HasOverflowed()) { isolate->StackOverflow(); if (message_handling == Execution::MessageHandling::kReport) { isolate->ReportPendingMessages(); } return MaybeHandle<Object>(); } #endif // api callbacks can be called directly, unless we want to take the detour // through JS to set up a frame for break-at-entry. if (target->IsJSFunction()) { Handle<JSFunction> function = Handle<JSFunction>::cast(target); if ((!is_construct || function->IsConstructor()) && function->shared()->IsApiFunction() && !function->shared()->BreakAtEntry()) { SaveContext save(isolate); isolate->set_context(function->context()); DCHECK(function->context()->global_object()->IsJSGlobalObject()); if (is_construct) receiver = isolate->factory()->the_hole_value(); auto value = Builtins::InvokeApiFunction( isolate, is_construct, function, receiver, argc, args, Handle<HeapObject>::cast(new_target)); bool has_exception = value.is_null(); DCHECK(has_exception == isolate->has_pending_exception()); if (has_exception) { if (message_handling == Execution::MessageHandling::kReport) { isolate->ReportPendingMessages(); } return MaybeHandle<Object>(); } else { isolate->clear_pending_message(); } return value; } } // Entering JavaScript. VMState<JS> state(isolate); CHECK(AllowJavascriptExecution::IsAllowed(isolate)); if (!ThrowOnJavascriptExecution::IsAllowed(isolate)) { isolate->ThrowIllegalOperation(); if (message_handling == Execution::MessageHandling::kReport) { isolate->ReportPendingMessages(); } return MaybeHandle<Object>(); } // Placeholder for return value. Object* value = nullptr; using JSEntryFunction = GeneratedCode<Object*(Object * new_target, Object * target, Object * receiver, int argc, Object*** args)>; Handle<Code> code; switch (execution_target) { case Execution::Target::kCallable: code = is_construct ? isolate->factory()->js_construct_entry_code() : isolate->factory()->js_entry_code(); break; case Execution::Target::kRunMicrotasks: code = isolate->factory()->js_run_microtasks_entry_code(); break; default: UNREACHABLE(); } { // Save and restore context around invocation and block the // allocation of handles without explicit handle scopes. SaveContext save(isolate); SealHandleScope shs(isolate); JSEntryFunction stub_entry = JSEntryFunction::FromAddress(isolate, code->entry()); if (FLAG_clear_exceptions_on_js_entry) isolate->clear_pending_exception(); // Call the function through the right JS entry stub. Object* orig_func = *new_target; Object* func = *target; Object* recv = *receiver; Object*** argv = reinterpret_cast<Object***>(args); if (FLAG_profile_deserialization && target->IsJSFunction()) { PrintDeserializedCodeInfo(Handle<JSFunction>::cast(target)); } RuntimeCallTimerScope timer(isolate, RuntimeCallCounterId::kJS_Execution); value = stub_entry.Call(orig_func, func, recv, argc, argv); } #ifdef VERIFY_HEAP if (FLAG_verify_heap) { value->ObjectVerify(isolate); } #endif // Update the pending exception flag and return the value. bool has_exception = value->IsException(isolate); DCHECK(has_exception == isolate->has_pending_exception()); if (has_exception) { if (message_handling == Execution::MessageHandling::kReport) { isolate->ReportPendingMessages(); } return MaybeHandle<Object>(); } else { isolate->clear_pending_message(); } return Handle<Object>(value, isolate); } MaybeHandle<Object> CallInternal(Isolate* isolate, Handle<Object> callable, Handle<Object> receiver, int argc, Handle<Object> argv[], Execution::MessageHandling message_handling, Execution::Target target) { // Convert calls on global objects to be calls on the global // receiver instead to avoid having a 'this' pointer which refers // directly to a global object. if (receiver->IsJSGlobalObject()) { receiver = handle(Handle<JSGlobalObject>::cast(receiver)->global_proxy(), isolate); } return Invoke(isolate, false, callable, receiver, argc, argv, isolate->factory()->undefined_value(), message_handling, target); } } // namespace // static MaybeHandle<Object> Execution::Call(Isolate* isolate, Handle<Object> callable, Handle<Object> receiver, int argc, Handle<Object> argv[]) { return CallInternal(isolate, callable, receiver, argc, argv, MessageHandling::kReport, Execution::Target::kCallable); } // static MaybeHandle<Object> Execution::New(Isolate* isolate, Handle<Object> constructor, int argc, Handle<Object> argv[]) { return New(isolate, constructor, constructor, argc, argv); } // static MaybeHandle<Object> Execution::New(Isolate* isolate, Handle<Object> constructor, Handle<Object> new_target, int argc, Handle<Object> argv[]) { return Invoke(isolate, true, constructor, isolate->factory()->undefined_value(), argc, argv, new_target, MessageHandling::kReport, Execution::Target::kCallable); } MaybeHandle<Object> Execution::TryCall( Isolate* isolate, Handle<Object> callable, Handle<Object> receiver, int argc, Handle<Object> args[], MessageHandling message_handling, MaybeHandle<Object>* exception_out, Target target) { bool is_termination = false; MaybeHandle<Object> maybe_result; if (exception_out != nullptr) *exception_out = MaybeHandle<Object>(); DCHECK_IMPLIES(message_handling == MessageHandling::kKeepPending, exception_out == nullptr); // Enter a try-block while executing the JavaScript code. To avoid // duplicate error printing it must be non-verbose. Also, to avoid // creating message objects during stack overflow we shouldn't // capture messages. { v8::TryCatch catcher(reinterpret_cast<v8::Isolate*>(isolate)); catcher.SetVerbose(false); catcher.SetCaptureMessage(false); maybe_result = CallInternal(isolate, callable, receiver, argc, args, message_handling, target); if (maybe_result.is_null()) { DCHECK(isolate->has_pending_exception()); if (isolate->pending_exception() == ReadOnlyRoots(isolate).termination_exception()) { is_termination = true; } else { if (exception_out != nullptr) { DCHECK(catcher.HasCaught()); DCHECK(isolate->external_caught_exception()); *exception_out = v8::Utils::OpenHandle(*catcher.Exception()); } } if (message_handling == MessageHandling::kReport) { isolate->OptionalRescheduleException(true); } } } // Re-request terminate execution interrupt to trigger later. if (is_termination) isolate->stack_guard()->RequestTerminateExecution(); return maybe_result; } MaybeHandle<Object> Execution::RunMicrotasks( Isolate* isolate, MessageHandling message_handling, MaybeHandle<Object>* exception_out) { auto undefined = isolate->factory()->undefined_value(); return TryCall(isolate, undefined, undefined, 0, {}, message_handling, exception_out, Target::kRunMicrotasks); } void StackGuard::SetStackLimit(uintptr_t limit) { ExecutionAccess access(isolate_); // If the current limits are special (e.g. due to a pending interrupt) then // leave them alone. uintptr_t jslimit = SimulatorStack::JsLimitFromCLimit(isolate_, limit); if (thread_local_.jslimit() == thread_local_.real_jslimit_) { thread_local_.set_jslimit(jslimit); } if (thread_local_.climit() == thread_local_.real_climit_) { thread_local_.set_climit(limit); } thread_local_.real_climit_ = limit; thread_local_.real_jslimit_ = jslimit; } void StackGuard::AdjustStackLimitForSimulator() { ExecutionAccess access(isolate_); uintptr_t climit = thread_local_.real_climit_; // If the current limits are special (e.g. due to a pending interrupt) then // leave them alone. uintptr_t jslimit = SimulatorStack::JsLimitFromCLimit(isolate_, climit); if (thread_local_.jslimit() == thread_local_.real_jslimit_) { thread_local_.set_jslimit(jslimit); isolate_->heap()->SetStackLimits(); } } void StackGuard::EnableInterrupts() { ExecutionAccess access(isolate_); if (has_pending_interrupts(access)) { set_interrupt_limits(access); } } void StackGuard::DisableInterrupts() { ExecutionAccess access(isolate_); reset_limits(access); } void StackGuard::PushInterruptsScope(InterruptsScope* scope) { ExecutionAccess access(isolate_); DCHECK_NE(scope->mode_, InterruptsScope::kNoop); if (scope->mode_ == InterruptsScope::kPostponeInterrupts) { // Intercept already requested interrupts. int intercepted = thread_local_.interrupt_flags_ & scope->intercept_mask_; scope->intercepted_flags_ = intercepted; thread_local_.interrupt_flags_ &= ~intercepted; } else { DCHECK_EQ(scope->mode_, InterruptsScope::kRunInterrupts); // Restore postponed interrupts. int restored_flags = 0; for (InterruptsScope* current = thread_local_.interrupt_scopes_; current != nullptr; current = current->prev_) { restored_flags |= (current->intercepted_flags_ & scope->intercept_mask_); current->intercepted_flags_ &= ~scope->intercept_mask_; } thread_local_.interrupt_flags_ |= restored_flags; } if (!has_pending_interrupts(access)) reset_limits(access); // Add scope to the chain. scope->prev_ = thread_local_.interrupt_scopes_; thread_local_.interrupt_scopes_ = scope; } void StackGuard::PopInterruptsScope() { ExecutionAccess access(isolate_); InterruptsScope* top = thread_local_.interrupt_scopes_; DCHECK_NE(top->mode_, InterruptsScope::kNoop); if (top->mode_ == InterruptsScope::kPostponeInterrupts) { // Make intercepted interrupts active. DCHECK_EQ(thread_local_.interrupt_flags_ & top->intercept_mask_, 0); thread_local_.interrupt_flags_ |= top->intercepted_flags_; } else { DCHECK_EQ(top->mode_, InterruptsScope::kRunInterrupts); // Postpone existing interupts if needed. if (top->prev_) { for (int interrupt = 1; interrupt < ALL_INTERRUPTS; interrupt = interrupt << 1) { InterruptFlag flag = static_cast<InterruptFlag>(interrupt); if ((thread_local_.interrupt_flags_ & flag) && top->prev_->Intercept(flag)) { thread_local_.interrupt_flags_ &= ~flag; } } } } if (has_pending_interrupts(access)) set_interrupt_limits(access); // Remove scope from chain. thread_local_.interrupt_scopes_ = top->prev_; } bool StackGuard::CheckInterrupt(InterruptFlag flag) { ExecutionAccess access(isolate_); return thread_local_.interrupt_flags_ & flag; } void StackGuard::RequestInterrupt(InterruptFlag flag) { ExecutionAccess access(isolate_); // Check the chain of InterruptsScope for interception. if (thread_local_.interrupt_scopes_ && thread_local_.interrupt_scopes_->Intercept(flag)) { return; } // Not intercepted. Set as active interrupt flag. thread_local_.interrupt_flags_ |= flag; set_interrupt_limits(access); // If this isolate is waiting in a futex, notify it to wake up. isolate_->futex_wait_list_node()->NotifyWake(); } void StackGuard::ClearInterrupt(InterruptFlag flag) { ExecutionAccess access(isolate_); // Clear the interrupt flag from the chain of InterruptsScope. for (InterruptsScope* current = thread_local_.interrupt_scopes_; current != nullptr; current = current->prev_) { current->intercepted_flags_ &= ~flag; } // Clear the interrupt flag from the active interrupt flags. thread_local_.interrupt_flags_ &= ~flag; if (!has_pending_interrupts(access)) reset_limits(access); } bool StackGuard::CheckAndClearInterrupt(InterruptFlag flag) { ExecutionAccess access(isolate_); bool result = (thread_local_.interrupt_flags_ & flag); thread_local_.interrupt_flags_ &= ~flag; if (!has_pending_interrupts(access)) reset_limits(access); return result; } char* StackGuard::ArchiveStackGuard(char* to) { ExecutionAccess access(isolate_); MemCopy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal)); ThreadLocal blank; // Set the stack limits using the old thread_local_. // TODO(isolates): This was the old semantics of constructing a ThreadLocal // (as the ctor called SetStackLimits, which looked at the // current thread_local_ from StackGuard)-- but is this // really what was intended? isolate_->heap()->SetStackLimits(); thread_local_ = blank; return to + sizeof(ThreadLocal); } char* StackGuard::RestoreStackGuard(char* from) { ExecutionAccess access(isolate_); MemCopy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal)); isolate_->heap()->SetStackLimits(); return from + sizeof(ThreadLocal); } void StackGuard::FreeThreadResources() { Isolate::PerIsolateThreadData* per_thread = isolate_->FindOrAllocatePerThreadDataForThisThread(); per_thread->set_stack_limit(thread_local_.real_climit_); } void StackGuard::ThreadLocal::Clear() { real_jslimit_ = kIllegalLimit; set_jslimit(kIllegalLimit); real_climit_ = kIllegalLimit; set_climit(kIllegalLimit); interrupt_scopes_ = nullptr; interrupt_flags_ = 0; } bool StackGuard::ThreadLocal::Initialize(Isolate* isolate) { bool should_set_stack_limits = false; if (real_climit_ == kIllegalLimit) { const uintptr_t kLimitSize = FLAG_stack_size * KB; DCHECK_GT(GetCurrentStackPosition(), kLimitSize); uintptr_t limit = GetCurrentStackPosition() - kLimitSize; real_jslimit_ = SimulatorStack::JsLimitFromCLimit(isolate, limit); set_jslimit(SimulatorStack::JsLimitFromCLimit(isolate, limit)); real_climit_ = limit; set_climit(limit); should_set_stack_limits = true; } interrupt_scopes_ = nullptr; interrupt_flags_ = 0; return should_set_stack_limits; } void StackGuard::ClearThread(const ExecutionAccess& lock) { thread_local_.Clear(); isolate_->heap()->SetStackLimits(); } void StackGuard::InitThread(const ExecutionAccess& lock) { if (thread_local_.Initialize(isolate_)) isolate_->heap()->SetStackLimits(); Isolate::PerIsolateThreadData* per_thread = isolate_->FindOrAllocatePerThreadDataForThisThread(); uintptr_t stored_limit = per_thread->stack_limit(); // You should hold the ExecutionAccess lock when you call this. if (stored_limit != 0) { SetStackLimit(stored_limit); } } // --- C a l l s t o n a t i v e s --- Object* StackGuard::HandleInterrupts() { if (FLAG_verify_predictable) { // Advance synthetic time by making a time request. isolate_->heap()->MonotonicallyIncreasingTimeInMs(); } bool any_interrupt_handled = false; if (FLAG_trace_interrupts) { PrintF("[Handling interrupts: "); } if (CheckAndClearInterrupt(GC_REQUEST)) { if (FLAG_trace_interrupts) { PrintF("GC_REQUEST"); any_interrupt_handled = true; } isolate_->heap()->HandleGCRequest(); } if (CheckAndClearInterrupt(TERMINATE_EXECUTION)) { if (FLAG_trace_interrupts) { if (any_interrupt_handled) PrintF(", "); PrintF("TERMINATE_EXECUTION"); any_interrupt_handled = true; } return isolate_->TerminateExecution(); } if (CheckAndClearInterrupt(DEOPT_MARKED_ALLOCATION_SITES)) { if (FLAG_trace_interrupts) { if (any_interrupt_handled) PrintF(", "); PrintF("DEOPT_MARKED_ALLOCATION_SITES"); any_interrupt_handled = true; } isolate_->heap()->DeoptMarkedAllocationSites(); } if (CheckAndClearInterrupt(INSTALL_CODE)) { if (FLAG_trace_interrupts) { if (any_interrupt_handled) PrintF(", "); PrintF("INSTALL_CODE"); any_interrupt_handled = true; } DCHECK(isolate_->concurrent_recompilation_enabled()); isolate_->optimizing_compile_dispatcher()->InstallOptimizedFunctions(); } if (CheckAndClearInterrupt(API_INTERRUPT)) { if (FLAG_trace_interrupts) { if (any_interrupt_handled) PrintF(", "); PrintF("API_INTERRUPT"); any_interrupt_handled = true; } // Callbacks must be invoked outside of ExecusionAccess lock. isolate_->InvokeApiInterruptCallbacks(); } if (FLAG_trace_interrupts) { if (!any_interrupt_handled) { PrintF("No interrupt flags set"); } PrintF("]\n"); } isolate_->counters()->stack_interrupts()->Increment(); isolate_->counters()->runtime_profiler_ticks()->Increment(); isolate_->runtime_profiler()->MarkCandidatesForOptimization(); return ReadOnlyRoots(isolate_).undefined_value(); } } // namespace internal } // namespace v8
c++
code
19,402
3,800
// Copyright (c) AlgoMachines // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once namespace WorkbenchLib { #define PTR_SET_DEFINED class COMPARE_FUNCTION { public: inline COMPARE_FUNCTION () { Compare = 0; } int (*Compare)(void *obj0,void *obj1); }; #define ASSIGN_CHANGES_MADE_IMPLEMENTATION(PTR_CLASS)\ inline BOOL Assign (const PTR_CLASS &obj, BOOL &bChangesMade)\ {\ int32_t sz0 = GetStorageSizeBytes ();\ int32_t sz1 = obj.GetStorageSizeBytes ();\ \ unsigned char *b1 = new unsigned char[sz1];\ if (!b1) return FALSE;\ \ int32_t check = obj.SaveToBuffer (b1);\ if (check != sz1) return FALSE;\ \ if (sz0 != sz1)\ bChangesMade = TRUE;\ else\ {\ unsigned char *b0 = new unsigned char[sz0];\ if (!b0) return FALSE;\ check = SaveToBuffer (b0);\ if (check != sz0) return FALSE;\ \ if (BuffersAreIdentical (b0,b1,sz0) == FALSE)\ bChangesMade = TRUE;\ \ delete [] b0;\ }\ \ check = LoadFromBuffer (b1);\ delete [] b1;\ \ if (check != sz1) return FALSE;\ \ return TRUE;\ } #define ASSIGN_IMPLEMENTATION(PTR_CLASS)\ inline BOOL Assign (const PTR_CLASS &obj)\ {\ int32_t sz1 = obj.GetStorageSizeBytes ();\ \ unsigned char *b1 = new unsigned char[sz1];\ if (!b1) return FALSE;\ \ int32_t check = obj.SaveToBuffer (b1);\ if (check != sz1) return FALSE;\ \ check = LoadFromBuffer (b1);\ delete [] b1;\ \ if (check != sz1) return FALSE;\ \ return TRUE;\ } template <class PTR_CLASS, class INDEX_TYPE=uint32_t> class PtrSet { private: INDEX_TYPE m_alloc_increment_size; INDEX_TYPE m_alloc_n; INDEX_TYPE m_ptrs_n; PTR_CLASS **m_ptrs; INDEX_TYPE *m_idx; PTR_CLASS *m_block; INDEX_TYPE m_block_sz; INDEX_TYPE m_num_alt_indexes; INDEX_TYPE **m_alt_indexes; COMPARE_FUNCTION *m_alt_indexes_compare_funcs; union { BYTE m_status; struct { BYTE m_delete_objects : 1; BYTE m_create_linear_idx : 1; BYTE m_reserved0 : 1; BYTE m_unique : 1; BYTE m_memory_block_mode : 1; BYTE m_reserved : 3; }; }; public: inline PtrSet (INDEX_TYPE alloc_increment_size) { m_status = 0; m_alloc_increment_size = alloc_increment_size; m_alloc_n = 0; m_ptrs_n = 0; m_ptrs = 0; m_idx = 0; m_delete_objects = FALSE; m_create_linear_idx = TRUE; m_unique = FALSE; m_memory_block_mode = FALSE; m_block = 0; m_block_sz = 0; m_num_alt_indexes = 0; m_alt_indexes = 0; m_alt_indexes_compare_funcs = 0; } inline PTR_CLASS& operator[](INDEX_TYPE idx) { PTR_CLASS* obj = GetObject(idx); return *obj; } inline INDEX_TYPE size(void) const { return GetCount(); } inline void DoNotDeleteObjects (void) { m_delete_objects = FALSE; } inline PtrSet (void) { m_status = 0; m_alloc_increment_size = 0; m_alloc_n = 0; m_ptrs_n = 0; m_ptrs = 0; m_idx = 0; m_delete_objects = TRUE; m_create_linear_idx = TRUE; m_unique = FALSE; m_memory_block_mode = FALSE; m_block = 0; m_block_sz = 0; m_num_alt_indexes = 0; m_alt_indexes = 0; m_alt_indexes_compare_funcs = 0; } inline ~PtrSet (void) { delete_pointers (TRUE); m_ptrs_n = -1; } inline BOOL SetNumberOfAlternateIndexes (INDEX_TYPE n) { ASSERT(m_num_alt_indexes == 0); m_alt_indexes = new INDEX_TYPE*[n]; ASSERT(m_alt_indexes); memset(m_alt_indexes,0,sizeof(INDEX_TYPE*)*n); m_num_alt_indexes = n; m_alt_indexes_compare_funcs = new COMPARE_FUNCTION[n]; ASSERT(m_alt_indexes_compare_funcs); memset(m_alt_indexes,0,sizeof(COMPARE_FUNCTION)*n); return TRUE; } inline BOOL SetAlternateIndexCompareFunction (INDEX_TYPE i, int(*Compare)(void*,void*)) { if (i < 0 || i >= m_num_alt_indexes) { ASSERT(FALSE); return FALSE; } ASSERT(m_alt_indexes_compare_funcs[i].Compare == 0); m_alt_indexes_compare_funcs[i].Compare = (int(*)(void*,void*))Compare; return TRUE; } inline INDEX_TYPE GetAlternateRawIndexDirect (INDEX_TYPE i_alt_index, INDEX_TYPE index) { if (i_alt_index < 0 || i_alt_index >= m_num_alt_indexes) { ASSERT(FALSE); return 0; } if (index < 0 || index >= m_ptrs_n) { ASSERT(FALSE); return 0; } return m_alt_indexes[i_alt_index][index]; } inline BOOL AssignAsOneBlock (PTR_CLASS *array, INDEX_TYPE N) { RemoveAll (); m_create_linear_idx = FALSE; m_delete_objects = FALSE; m_memory_block_mode = TRUE; m_block = array; m_block_sz = N; return TRUE; } inline BOOL IsValid (void) { if (m_ptrs == 0) { if (m_ptrs_n || m_alloc_n) return FALSE; } else { if (AfxIsValidAddress (m_ptrs, sizeof(m_ptrs[0])*m_alloc_n) == FALSE) return FALSE; } if (m_create_linear_idx && (m_alloc_n || m_ptrs_n)) { if (AfxIsValidAddress (m_idx, sizeof(m_idx[0])*m_alloc_n) == FALSE) return FALSE; } if (m_alloc_n < m_ptrs_n) return FALSE; if (m_alloc_increment_size < 0) return FALSE; if (m_block) { if (AfxIsValidAddress (m_block, sizeof(PTR_CLASS)*m_block_sz) == FALSE) return FALSE; } return TRUE; } inline void SetStatusDeleteObjects (BOOL status) { m_delete_objects = status; } inline BOOL GetStatusDeleteObjects (void) { return m_delete_objects; } inline void SetStatusCreateLinearIndex (BOOL status) { ASSERT (m_alloc_n == 0); if (status == FALSE) m_create_linear_idx = FALSE; else m_create_linear_idx = TRUE; } inline BOOL GetStatusContainsLinearIndex (void) { return m_create_linear_idx; } inline void SetStatusUnique (BOOL status) { m_unique = status; ASSERT (m_alloc_n == 0); } inline INDEX_TYPE GetAllocSizeItems (void) { return m_alloc_n; } inline BOOL increase_allocation_if_necessary (INDEX_TYPE n) { ASSERT (m_block == 0); if (m_alloc_n <= n) { INDEX_TYPE incr = m_alloc_increment_size; if (!incr) incr = m_alloc_n; if (!incr) incr++; if (m_alloc_n + incr < n) incr = n - m_alloc_n; PTR_CLASS **tmp = new PTR_CLASS*[incr+m_alloc_n]; ASSERT (tmp); if (!tmp) FALSE; memmove (tmp,m_ptrs,sizeof(PTR_CLASS*)*m_ptrs_n); memset (&tmp[m_alloc_n],0,sizeof(PTR_CLASS*)*incr); delete m_ptrs; m_ptrs = tmp; if (m_create_linear_idx == TRUE) { INDEX_TYPE *idx = new INDEX_TYPE[m_alloc_n+incr]; ASSERT (idx); memmove (idx,m_idx,sizeof(INDEX_TYPE)*m_ptrs_n); memset (&idx[m_ptrs_n],0,sizeof(INDEX_TYPE)*incr); delete [] m_idx; m_idx = idx; // expand the alternate indexes for (INDEX_TYPE i_alt_index=0; i_alt_index<m_num_alt_indexes; i_alt_index++) { INDEX_TYPE *a_idx = m_alt_indexes[i_alt_index]; if (m_ptrs_n) ASSERT(a_idx); INDEX_TYPE *idx = new INDEX_TYPE[m_alloc_n+incr]; ASSERT (idx); if (m_ptrs_n) memmove (idx,a_idx,sizeof(INDEX_TYPE)*m_ptrs_n); memset (&idx[m_ptrs_n],0,sizeof(INDEX_TYPE)*incr); delete [] a_idx; m_alt_indexes[i_alt_index] = idx; } } m_alloc_n += incr; } return TRUE; } inline BOOL AppendIfUnique (PTR_CLASS *tr) { if (Exists (tr) == TRUE) return FALSE; return Append (tr); } inline BOOL Append (PTR_CLASS *tr) { ASSERT (m_block == 0); if (increase_allocation_if_necessary (m_ptrs_n+1) == FALSE) return FALSE; m_ptrs[m_ptrs_n] = tr; BOOL iret = UpdateIndex (m_ptrs_n,tr); if (iret == FALSE) { m_ptrs[m_ptrs_n] = 0; return FALSE; } m_ptrs_n++; return TRUE; } inline BOOL CycleIn (PTR_CLASS *tr, BOOL overwrite_existing=TRUE) { ASSERT (m_block == 0); if (m_create_linear_idx != TRUE) { ASSERT (FALSE); // Only supported for this index type return FALSE; } if (!(*tr > *m_ptrs[m_idx[m_ptrs_n-1]])) { ASSERT (FALSE); // The new item must be greater than any previous item return FALSE; } INDEX_TYPE ptr_to_replace_i = m_idx[0]; // Assign the object if (overwrite_existing == TRUE) { *m_ptrs[ptr_to_replace_i] = *tr; } else if (m_delete_objects) { delete m_ptrs[ptr_to_replace_i]; m_ptrs[ptr_to_replace_i] = tr; } // Update the index for (INDEX_TYPE i=0; i<m_ptrs_n-1; i++) m_idx[i] = m_idx[i+1]; m_idx[m_ptrs_n-1] = ptr_to_replace_i; return TRUE; } inline BOOL Insert (INDEX_TYPE i, PTR_CLASS *tr) { ASSERT (m_block == 0); ASSERT (i <= m_ptrs_n); if (i > m_ptrs_n) return FALSE; if (increase_allocation_if_necessary (m_ptrs_n+1) == FALSE) return FALSE; INDEX_TYPE j; for (j=m_ptrs_n; j>i; j--) m_ptrs[j] = m_ptrs[j-1]; m_ptrs[i] = tr; BOOL iret = UpdateIndex (i,tr); if (iret == FALSE) { /////////////////////////////////////// // Undo for (j=i; j<m_ptrs_n; j++) m_ptrs[j] = m_ptrs[j+i]; m_ptrs[m_ptrs_n] = 0; //////////////////////////////////////// return FALSE; } m_ptrs_n++; return TRUE; } inline PTR_CLASS* GetIfExists(PTR_CLASS* tr) { INDEX_TYPE idx; if (Exists(tr, &idx) == FALSE) return 0; return GetIndexedPtr(idx - 1); } inline const PTR_CLASS* GetIfExistsConst(const PTR_CLASS* tr, INDEX_TYPE *idx_ret=0) const { INDEX_TYPE idx; if (ExistsConst(tr, &idx) == FALSE) return 0; if (idx_ret) *idx_ret = idx - 1; return GetIndexedPtrConst(idx - 1); } inline BOOL Exists(PTR_CLASS *tr, INDEX_TYPE *idx = 0) { ASSERT(m_block == 0); if (m_create_linear_idx == TRUE) { BOOL exists; INDEX_TYPE i = GetIdxInsertPosition(tr, exists); if (idx) *idx = i; return exists; } for (INDEX_TYPE i = 0; i<m_ptrs_n; i++) { if ((*tr) < (*m_ptrs[i])) continue; if ((*tr) > (*m_ptrs[i])) continue; if (idx) *idx = i; return TRUE; } return FALSE; } inline BOOL ExistsConst(const PTR_CLASS *tr, INDEX_TYPE *idx = 0) const { ASSERT(m_block == 0); if (m_create_linear_idx == TRUE) { BOOL exists; INDEX_TYPE i = GetIdxInsertPositionConst(tr, exists); if (idx) *idx = i; return exists; } for (INDEX_TYPE i = 0; i<m_ptrs_n; i++) { if ((*tr) < (*m_ptrs[i])) continue; if ((*tr) > (*m_ptrs[i])) continue; if (idx) *idx = i; return TRUE; } return FALSE; } inline BOOL IsSorted (void) { ASSERT (m_block == 0); if (m_create_linear_idx) { ASSERT (FALSE); return FALSE; } for (INDEX_TYPE i=0; i<m_ptrs_n-1; i++) { if (*m_ptrs[i] > *m_ptrs[i+1]) return FALSE; } return TRUE; } inline BOOL AddSorted (PTR_CLASS *obj) { ASSERT (m_block == 0); if (m_create_linear_idx) { ASSERT(FALSE); return FALSE; } if (increase_allocation_if_necessary (m_ptrs_n+1) == FALSE) return FALSE; for (INDEX_TYPE i=m_ptrs_n-1; i>=0; i--) { if (*obj < *m_ptrs[i]) { m_ptrs[i+1] = m_ptrs[i]; continue; } m_ptrs[i+1] = obj; m_ptrs_n++; return TRUE; } m_ptrs[0] = obj; m_ptrs_n++; return TRUE; } inline BOOL Sort (void) { ASSERT (m_block == 0); PTR_CLASS **tmp_ptrs = new PTR_CLASS*[m_ptrs_n]; if (!tmp_ptrs) return FALSE; memset (tmp_ptrs,0,sizeof(PTR_CLASS*)*m_ptrs_n); if (m_create_linear_idx) { INDEX_TYPE *tmp_idx = new INDEX_TYPE[m_ptrs_n]; if (!tmp_idx) { delete [] tmp_ptrs; return FALSE; } memset (tmp_idx,0,sizeof(INDEX_TYPE)*m_ptrs_n); for (INDEX_TYPE i=0; i<m_ptrs_n; i++) { tmp_idx[i] = i; PTR_CLASS *obj = GetIndexedPtr (i); tmp_ptrs[i] = obj; } memmove (m_idx,tmp_idx,sizeof(INDEX_TYPE)*m_ptrs_n); memmove (m_ptrs,tmp_ptrs,sizeof(PTR_CLASS*)*m_ptrs_n); delete [] tmp_idx; delete [] tmp_ptrs; return TRUE; } else { for (INDEX_TYPE i=0; i<m_ptrs_n; i++) { INDEX_TYPE j; for (j=0; j<i; j++) { if (*m_ptrs[i] < *m_ptrs[j]) { for (INDEX_TYPE k=i; k>j; k--) { tmp_ptrs[k] = tmp_ptrs[k-1]; } tmp_ptrs[j] = m_ptrs[i]; break; } } if (j==i) { tmp_ptrs[j] = m_ptrs[j]; } } memmove (m_ptrs,tmp_ptrs,sizeof(PTR_CLASS*)*m_ptrs_n); delete [] tmp_ptrs; return TRUE; } } inline BOOL UpdateIndex (const INDEX_TYPE &pos, PTR_CLASS *tr) { ASSERT (m_block == 0); if (m_create_linear_idx == TRUE) { BOOL exists; INDEX_TYPE i = GetIdxInsertPosition (tr,exists); if (exists) { if (m_unique) return FALSE; } // Shift index values if necessary if (i < m_ptrs_n) { INDEX_TYPE j = m_ptrs_n; while (1) { if (j <= i) break; m_idx[j] = m_idx[j-1]; j--; } } m_idx[i] = pos; // Update the alternate indexes for (INDEX_TYPE i_alt_index=0; i_alt_index<m_num_alt_indexes; i_alt_index++) { INDEX_TYPE *a_idx = m_alt_indexes[i_alt_index]; ASSERT(a_idx); i = GetAltIdxInsertPosition (i_alt_index,tr,exists); // Shift index values if necessary if (i < m_ptrs_n) { INDEX_TYPE j = m_ptrs_n; while (1) { if (j <= i) break; a_idx[j] = a_idx[j-1]; j--; } } a_idx[i] = pos; } return TRUE; } return TRUE; } inline PTR_CLASS *GetPtrByToken (PTR_CLASS *token, BOOL &exists) { ASSERT (m_block == 0); INDEX_TYPE idx = GetIdxInsertPosition (token,exists); if (idx == 0) return 0; PTR_CLASS *item = GetIndexedPtr (idx-1); if (*token < *item) return 0; if (*token > *item) return 0; return item; } inline INDEX_TYPE GetAltIdxInsertPosition (INDEX_TYPE i_alt_index, PTR_CLASS *tr, BOOL &exists) { exists = FALSE; if (i_alt_index < 0 || i_alt_index >= m_num_alt_indexes) { ASSERT(FALSE); return 0; } ASSERT(m_create_linear_idx); int (*Compare)(void *obj0,void *obj1) = m_alt_indexes_compare_funcs[i_alt_index].Compare; ASSERT(Compare); INDEX_TYPE *a_idx = m_alt_indexes[i_alt_index]; ASSERT(a_idx); if (!m_ptrs_n) return 0; // Check to see if this is greater than the last item int icmp = Compare (tr,m_ptrs[a_idx[m_ptrs_n-1]]); if (icmp == 0) { exists = TRUE; return m_ptrs_n; } if (icmp > 0) return m_ptrs_n; INDEX_TYPE i; if (m_ptrs_n < 6) { for (i = 0; i < m_ptrs_n-1; i++) { icmp = Compare (tr,m_ptrs[a_idx[i]]); if (icmp < 0) return i; if (exists == FALSE && icmp == 0) exists = TRUE; } return i; } INDEX_TYPE istart,iend; istart = 0; iend = m_ptrs_n-1; i = m_ptrs_n / 2; while (1) { icmp = Compare (tr,m_ptrs[a_idx[i]]); if (icmp < 0) iend = i - 1; else istart = i + 1; if (iend - istart < 4) { for (i = istart; i <= iend; i++) { icmp = Compare (tr,m_ptrs[a_idx[i]]); if (icmp < 0) { if (exists == FALSE && i && !(Compare (tr,m_ptrs[a_idx[i-1]]) > 0)) exists = TRUE; return i; } if (exists == FALSE && icmp == 0) exists = TRUE; } return i; } i = (iend - istart) / 2; i += istart; } } inline BOOL GetStartAndEndIndexes (PTR_CLASS &token, INDEX_TYPE &istart, INDEX_TYPE &iend) { BOOL exists; INDEX_TYPE i = GetIdxInsertPosition (&token, exists); if (exists == FALSE) return FALSE; i--; iend = i; istart = i; while (i >= 0 && i < GetCount ()) { PTR_CLASS *obj = GetIndexedPtr (i); if (*obj < token) break; istart = i; i--; } return TRUE; } inline BOOL GetAltStartAndEndIndexes (INDEX_TYPE i_alt_index, PTR_CLASS &token, INDEX_TYPE &istart, INDEX_TYPE &iend) { BOOL exists; INDEX_TYPE i = GetAltIdxInsertPosition (i_alt_index, &token, exists); if (exists == FALSE) return FALSE; i--; iend = i; istart = i; while (i >= 0 && i < GetCount ()) { PTR_CLASS *obj = GetAltIndexedPtr (i_alt_index,i); if (m_alt_indexes_compare_funcs[i_alt_index].Compare (obj,&token) < 0) break; istart = i; i--; } return TRUE; } inline INDEX_TYPE GetIdxInsertPosition(PTR_CLASS *tr, BOOL &exists, INDEX_TYPE *raw_idx = 0) { ASSERT(m_block == 0); exists = FALSE; if (m_create_linear_idx == TRUE) { if (!m_ptrs_n) return 0; // Check to see if this is greater than the last item if (!(*tr < *m_ptrs[m_idx[m_ptrs_n - 1]])) { if (!(*tr > *m_ptrs[m_idx[m_ptrs_n - 1]])) { exists = TRUE; if (raw_idx) *raw_idx = m_idx[m_ptrs_n - 1]; } return m_ptrs_n; } INDEX_TYPE i; if (m_ptrs_n < 6) { for (i = 0; i < m_ptrs_n - 1; i++) { if (*tr < *m_ptrs[m_idx[i]]) return i; if (exists == FALSE && !(*tr > *m_ptrs[m_idx[i]])) { if (raw_idx) *raw_idx = m_idx[i]; exists = TRUE; } } return i; } INDEX_TYPE istart, iend; istart = 0; iend = m_ptrs_n - 1; i = m_ptrs_n / 2; while (1) { if (*tr < *m_ptrs[m_idx[i]]) iend = i - 1; else istart = i + 1; if (iend - istart < 4) { for (i = istart; i <= iend; i++) { if (*tr < *m_ptrs[m_idx[i]]) { if (exists == FALSE && i && !(*tr > *m_ptrs[m_idx[i - 1]])) { if (raw_idx) *raw_idx = m_idx[i - 1]; exists = TRUE; } return i; } if (exists == FALSE && !(*tr > *m_ptrs[m_idx[i]])) { if (raw_idx) *raw_idx = m_idx[i]; exists = TRUE; } } return i; } i = (iend - istart) / 2; i += istart; } } ASSERT(FALSE); return 0; } inline INDEX_TYPE GetIdxInsertPositionConst(const PTR_CLASS *tr, BOOL &exists, INDEX_TYPE *raw_idx = 0) const { ASSERT(m_block == 0); exists = FALSE; if (m_create_linear_idx == TRUE) { if (!m_ptrs_n) return 0; // Check to see if this is greater than the last item if (!(*tr < *m_ptrs[m_idx[m_ptrs_n - 1]])) { if (!(*tr > *m_ptrs[m_idx[m_ptrs_n - 1]])) { exists = TRUE; if (raw_idx) *raw_idx = m_idx[m_ptrs_n - 1]; } return m_ptrs_n; } INDEX_TYPE i; if (m_ptrs_n < 6) { for (i = 0; i < m_ptrs_n - 1; i++) { if (*tr < *m_ptrs[m_idx[i]]) return i; if (exists == FALSE && !(*tr > *m_ptrs[m_idx[i]])) { if (raw_idx) *raw_idx = m_idx[i]; exists = TRUE; } } return i; } INDEX_TYPE istart, iend; istart = 0; iend = m_ptrs_n - 1; i = m_ptrs_n / 2; while (1) { if (*tr < *m_ptrs[m_idx[i]]) iend = i - 1; else istart = i + 1; if (iend - istart < 4) { for (i = istart; i <= iend; i++) { if (*tr < *m_ptrs[m_idx[i]]) { if (exists == FALSE && i && !(*tr > *m_ptrs[m_idx[i - 1]])) { if (raw_idx) *raw_idx = m_idx[i - 1];
c++
code
19,991
4,477
#include "stdafx.h" #include "Camera.hpp" #include "Application.hpp" #include "Track.hpp" const float ROLL_AMT = 8; const float ZOOM_POW = 1.65f; Camera::Camera() { } Camera::~Camera() { } static float DampedSin(float t, float amplitude, float frequency, float decay) { return amplitude * (float)pow(Math::e, -decay * t) * sin(frequency * 2 * t * Math::pi); } static float Swing(float time) { return DampedSin(time, 120.0f / 360, 1, 3.5f); } static void Spin(float time, float &roll, float &bgAngle, float dir) { const float TSPIN = 0.75f / 2.0f; const float TRECOV = 0.75f / 2.0f; bgAngle = Math::Clamp(time * 4.0f, 0.0f, 2.0f) * dir; if (time <= TSPIN) roll = -dir * (TSPIN - time) / TSPIN; else { if (time < TSPIN + TRECOV) roll = Swing((time - TSPIN) / TRECOV) * 0.25f * dir; else roll = 0.0f; } } static Transform GetOriginTransform(float pitch, float offs, float roll) { auto origin = Transform::Rotation({ 0, 0, roll }); auto anchor = Transform::Translation({ offs, -0.9f, 0 }) * Transform::Rotation({ 1.5f, 0, 0 }); auto contnr = Transform::Translation({ 0, 0, -0.9f }) * Transform::Rotation({ -90 + pitch, 0, 0, }); return origin * anchor * contnr; }; void Camera::Tick(float deltaTime, class BeatmapPlayback& playback) { auto LerpTo = [&](float &value, float target, float speed = 10) { float diff = abs(target - value); float change = diff * deltaTime * speed; change = Math::Min(deltaTime * speed * 0.05f, change); if (target < value) value = Math::Max(value - change, target); else value = Math::Min(value + change, target); }; const TimingPoint& currentTimingPoint = playback.GetCurrentTimingPoint(); LerpTo(m_laserRoll, m_targetRoll, m_targetRoll != 0.0f ? 8 : 3); m_spinProgress = (float)(playback.GetLastTime() - m_spinStart) / m_spinDuration; // Calculate camera spin // TODO(local): spins need a progress of 1 if (m_spinProgress < 2.0f) { if (m_spinType == SpinStruct::SpinType::Full) { Spin(m_spinProgress / 2.0f, m_spinRoll, m_bgSpin, m_spinDirection); } else if (m_spinType == SpinStruct::SpinType::Quarter) { const float BG_SPIN_SPEED = 4.0f / 3.0f; m_bgSpin = Math::Clamp(m_spinProgress * BG_SPIN_SPEED / 2, 0.0f, 1.0f) * m_spinDirection; m_spinRoll = Swing(m_spinProgress / 2) * m_spinDirection; } else if (m_spinType == SpinStruct::SpinType::Bounce) { m_bgSpin = 0.0f; m_spinBounceOffset = DampedSin(m_spinProgress / 2, m_spinBounceAmplitude, m_spinBounceFrequency / 2, m_spinBounceDecay) * m_spinDirection; } m_spinProgress = Math::Clamp(m_spinProgress, 0.0f, 2.0f); } else { m_bgSpin = 0.0f; m_spinRoll = 0.0f; m_spinProgress = 0.0f; } m_totalRoll = pLaneBaseRoll + m_spinRoll + m_laserRoll; m_totalOffset = pLaneOffset / 2.0f + m_spinBounceOffset; if (!rollKeep) { m_targetRollSet = false; m_targetRoll = 0.0f; } // Update camera shake effects m_shakeOffset = Vector3(0.0f); m_shakeEffect.time -= deltaTime; if (m_shakeEffect.time >= 0.f) { float shakeProgress = m_shakeEffect.time / m_shakeEffect.duration; float shakeIntensity = sinf(powf(shakeProgress, 1.6) * Math::pi); Vector3 shakeVec = Vector3(m_shakeEffect.amplitude * shakeIntensity) * Vector3(cameraShakeX, cameraShakeY, cameraShakeZ); m_shakeOffset += shakeVec; } float lanePitch = pLanePitch * pitchUnit; worldNormal = GetOriginTransform(lanePitch, m_totalOffset, m_totalRoll * 360.0f); worldNoRoll = GetOriginTransform(lanePitch, 0, 0); auto GetZoomedTransform = [&](Transform t) { auto zoomDir = t.GetPosition(); float highwayDist = zoomDir.Length(); zoomDir = zoomDir.Normalized(); float zoomAmt; if (pLaneZoom <= 0) zoomAmt = pow(ZOOM_POW, -pLaneZoom) - 1; else zoomAmt = highwayDist * (pow(ZOOM_POW, -pow(pLaneZoom, 1.35f)) - 1); return Transform::Translation(zoomDir * zoomAmt) * t; }; track->trackOrigin = GetZoomedTransform(worldNormal); critOrigin = GetZoomedTransform(GetOriginTransform(lanePitch, m_totalOffset, m_laserRoll * 360.0f + sin(m_spinRoll * Math::pi * 2) * 20)); } void Camera::AddCameraShake(CameraShake cameraShake) { m_shakeEffect = cameraShake; } void Camera::AddRollImpulse(float dir, float strength) { m_rollVelocity += dir * strength; } void Camera::SetRollIntensity(float val) { m_rollIntensity = val; } Vector2 Camera::Project(const Vector3& pos) { Vector3 cameraSpace = m_rsLast.cameraTransform.TransformPoint(pos); Vector3 screenSpace = m_rsLast.projectionTransform.TransformPoint(cameraSpace); screenSpace.y = -screenSpace.y; screenSpace *= 0.5f; screenSpace += Vector2(0.5f, 0.5f); screenSpace *= m_rsLast.viewportSize; return screenSpace.xy(); } static float Lerp(float a, float b, float alpha) { return a + (b - a) * alpha; } RenderState Camera::CreateRenderState(bool clipped) { int portrait = g_aspectRatio > 1 ? 0 : 1; // Extension of clipping planes in outward direction float viewRangeExtension = clipped ? 0.0f : 5.0f; RenderState rs = g_application->GetRenderStateBase(); auto critDir = worldNoRoll.GetPosition().Normalized(); float rotToCrit = -atan2(critDir.y, -critDir.z) * Math::radToDeg; float fov = fovs[portrait]; float cameraRot = fov / 2 - fov * pitchOffsets[portrait]; m_actualCameraPitch = rotToCrit - cameraRot + basePitch[portrait]; auto cameraTransform = Transform::Rotation(Vector3(m_actualCameraPitch, 0, 0) + m_shakeOffset); // Calculate clipping distances Vector3 toTrackEnd = (track->trackOrigin).TransformPoint(Vector3(0.0f, track->trackLength, 0)); float distToTrackEnd = sqrtf(toTrackEnd.x * toTrackEnd.x + toTrackEnd.y * toTrackEnd.y + toTrackEnd.z * toTrackEnd.z); rs.cameraTransform = cameraTransform; rs.projectionTransform = ProjectionMatrix::CreatePerspective(fov, g_aspectRatio, 0.1f, distToTrackEnd + viewRangeExtension); m_rsLast = rs; return rs; } void Camera::SetTargetRoll(float target) { float actualTarget = target * m_rollIntensity; if(!rollKeep) { m_targetRoll = actualTarget; m_targetRollSet = true; } else { if (m_targetRoll == 0.0f || Math::Sign(m_targetRoll) == Math::Sign(actualTarget)) { if (m_targetRoll == 0) m_targetRoll = actualTarget; if (m_targetRoll < 0 && actualTarget < m_targetRoll) m_targetRoll = actualTarget; else if (m_targetRoll > 0 && actualTarget > m_targetRoll) m_targetRoll = actualTarget; } m_targetRollSet = true; } } void Camera::SetSpin(float direction, uint32 duration, uint8 type, class BeatmapPlayback& playback) { const TimingPoint& currentTimingPoint = playback.GetCurrentTimingPoint(); m_spinDirection = direction; m_spinDuration = (duration / 192.0f) * (currentTimingPoint.beatDuration) * 4; m_spinStart = playback.GetLastTime(); m_spinType = type; } void Camera::SetXOffsetBounce(float direction, uint32 duration, uint32 amplitude, uint32 frequency, float decay, class BeatmapPlayback &playback) { const TimingPoint& currentTimingPoint = playback.GetCurrentTimingPoint(); m_spinDirection = direction; // since * 2 and stuff m_spinDuration = 0.5f * (duration / 192.0f) * (currentTimingPoint.beatDuration) * 4; m_spinStart = playback.GetLastTime(); m_spinType = SpinStruct::SpinType::Bounce; m_spinBounceAmplitude = amplitude / 250.0f; m_spinBounceFrequency = frequency; m_spinBounceDecay = decay == 0 ? 0 : (decay == 1 ? 1.5f : 3.0f); } void Camera::SetLasersActive(bool lasersActive) { m_lasersActive = lasersActive; } float Camera::GetRoll() const { return m_totalRoll; } float Camera::GetLaserRoll() const { return m_laserRoll; } float Camera::GetHorizonHeight() { return (0.5 + (-(m_actualCameraPitch + pLanePitch * pitchUnit) / fovs[g_aspectRatio > 1.0f ? 0 : 1])) * m_rsLast.viewportSize.y; } Vector2i Camera::GetScreenCenter() { Vector2i ret = Vector2i(0, GetHorizonHeight()); uint8 portrait = g_aspectRatio > 1.0f ? 0 : 1; float fov = fovs[portrait]; ret.x = m_rsLast.viewportSize.x / 2; ret.x -= (m_shakeOffset.y / (fov * g_aspectRatio)) * m_rsLast.viewportSize.x; return ret; } Vector3 Camera::GetShakeOffset() { return m_shakeOffset; } float Camera::m_ClampRoll(float in) const { float ain = fabs(in); if(ain < 1.0f) return in; bool odd = ((uint32)fabs(in) % 2) == 1; float sign = Math::Sign(in); if(odd) { // Swap sign and modulo return -sign * (1.0f-fmodf(ain, 1.0f)); } else { // Keep sign and modulo return sign * fmodf(ain, 1.0f); } } CameraShake::CameraShake(float duration) : duration(duration) { time = duration; } CameraShake::CameraShake(float duration, float amplitude) : duration(duration), amplitude(amplitude) { time = duration; }
c++
code
8,583
1,887
/* * Copyright (c) 2014, Sascha Schade * Copyright (c) 2014-2017, Niklas Hauser * * This file is part of the modm project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // ---------------------------------------------------------------------------- #include <modm/board.hpp> #include <modm/processing/timer.hpp> #include <modm/processing/protothread.hpp> #include <modm/driver/temperature/tmp102.hpp> typedef I2cMaster1 MyI2cMaster; class ThreadOne : public modm::pt::Protothread { public: ThreadOne() : temp(temperatureData, 0x48) { } bool update() { temp.update(); PT_BEGIN(); // ping the device until it responds while(true) { // we wait until the task started if (PT_CALL(temp.ping())) break; // otherwise, try again in 100ms timeout.restart(100ms); PT_WAIT_UNTIL(timeout.isExpired()); } PT_CALL(temp.setUpdateRate(200)); PT_CALL(temp.enableExtendedMode()); PT_CALL(temp.configureAlertMode( modm::tmp102::ThermostatMode::Comparator, modm::tmp102::AlertPolarity::ActiveLow, modm::tmp102::FaultQueue::Faults6)); PT_CALL(temp.setLowerLimit(28.f)); PT_CALL(temp.setUpperLimit(30.f)); while (true) { { PT_CALL(temp.readComparatorMode(result)); float temperature = temperatureData.getTemperature(); uint8_t tI = (int) temperature; uint16_t tP = (temperature - tI) * 10000; MODM_LOG_INFO << "T= " << tI << "."; if (tP == 0) { MODM_LOG_INFO << "0000 C"; } else if (tP == 625) { MODM_LOG_INFO << "0" << tP << " C"; } else { MODM_LOG_INFO << tP << " C"; } if (result) { MODM_LOG_INFO << " Heat me up!"; } MODM_LOG_INFO << modm::endl; } timeout.restart(200ms); PT_WAIT_UNTIL(timeout.isExpired()); Board::LedD13::toggle(); } PT_END(); } private: bool result; modm::ShortTimeout timeout; modm::tmp102::Data temperatureData; modm::Tmp102<MyI2cMaster> temp; }; ThreadOne one; // ---------------------------------------------------------------------------- int main() { Board::initialize(); Board::LedD13::setOutput(modm::Gpio::Low); MyI2cMaster::connect<Board::D14::Sda, Board::D15::Scl>(); MyI2cMaster::initialize<Board::SystemClock, 400_kHz>(); MODM_LOG_INFO << "\n\nRESTART\n\n"; while (true) { one.update(); } return 0; }
c++
code
2,479
659
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/installer/setup/installer_crash_reporter_client.h" #include "base/debug/crash_logging.h" #include "base/environment.h" #include "base/file_version_info.h" #include "base/files/file_path.h" #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" #include "base/win/registry.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_version.h" #include "chrome/common/env_vars.h" #include "chrome/install_static/install_util.h" #include "chrome/installer/setup/installer_crash_reporting.h" #include "chrome/installer/util/google_update_settings.h" InstallerCrashReporterClient::InstallerCrashReporterClient( bool is_per_user_install) : is_per_user_install_(is_per_user_install) { } InstallerCrashReporterClient::~InstallerCrashReporterClient() = default; bool InstallerCrashReporterClient::ShouldCreatePipeName( const base::string16& process_type) { return true; } bool InstallerCrashReporterClient::GetAlternativeCrashDumpLocation( base::string16* crash_dir) { return false; } void InstallerCrashReporterClient::GetProductNameAndVersion( const base::string16& exe_path, base::string16* product_name, base::string16* version, base::string16* special_build, base::string16* channel_name) { // Report crashes under the same product name as the browser. This string // MUST match server-side configuration. *product_name = base::ASCIIToUTF16(PRODUCT_SHORTNAME_STRING); std::unique_ptr<FileVersionInfo> version_info( FileVersionInfo::CreateFileVersionInfo(base::FilePath(exe_path))); if (version_info) { *version = version_info->product_version(); *special_build = version_info->special_build(); } else { *version = L"0.0.0.0-devel"; } *channel_name = install_static::GetChromeChannelName(); } bool InstallerCrashReporterClient::ShouldShowRestartDialog( base::string16* title, base::string16* message, bool* is_rtl_locale) { // There is no UX associated with the installer, so no dialog should be shown. return false; } bool InstallerCrashReporterClient::AboutToRestart() { // The installer should never be restarted after a crash. return false; } bool InstallerCrashReporterClient::GetDeferredUploadsSupported( bool is_per_user_install) { // Copy Chrome's impl? return false; } bool InstallerCrashReporterClient::GetIsPerUserInstall() { return is_per_user_install_; } bool InstallerCrashReporterClient::GetShouldDumpLargerDumps() { // Use large dumps for all but the stable channel. return !install_static::GetChromeChannelName().empty(); } int InstallerCrashReporterClient::GetResultCodeRespawnFailed() { // The restart dialog is never shown for the installer. NOTREACHED(); return 0; } bool InstallerCrashReporterClient::GetCrashDumpLocation( base::string16* crash_dir) { base::FilePath crash_directory_path; bool ret = PathService::Get(chrome::DIR_CRASH_DUMPS, &crash_directory_path); if (ret) *crash_dir = crash_directory_path.value(); return ret; } size_t InstallerCrashReporterClient::RegisterCrashKeys() { return installer::RegisterCrashKeys(); } bool InstallerCrashReporterClient::IsRunningUnattended() { std::unique_ptr<base::Environment> env(base::Environment::Create()); return env->HasVar(env_vars::kHeadless); } bool InstallerCrashReporterClient::GetCollectStatsConsent() { #if defined(GOOGLE_CHROME_BUILD) return GoogleUpdateSettings::GetCollectStatsConsentAtLevel( !is_per_user_install_); #else return false; #endif } bool InstallerCrashReporterClient::GetCollectStatsInSample() { // TODO(grt): remove duplication of code. base::win::RegKey key(HKEY_CURRENT_USER, install_static::GetRegistryPath().c_str(), KEY_QUERY_VALUE | KEY_WOW64_32KEY); if (!key.Valid()) return true; DWORD out_value = 0; if (key.ReadValueDW(install_static::kRegValueChromeStatsSample, &out_value) != ERROR_SUCCESS) { return true; } return out_value == 1; } bool InstallerCrashReporterClient::ReportingIsEnforcedByPolicy(bool* enabled) { // From the generated policy/policy/policy_constants.cc: #if defined(GOOGLE_CHROME_BUILD) static const wchar_t kRegistryChromePolicyKey[] = L"SOFTWARE\\Policies\\Google\\Chrome"; #else static const wchar_t kRegistryChromePolicyKey[] = L"SOFTWARE\\Policies\\Chromium"; #endif static const wchar_t kMetricsReportingEnabled[] = L"MetricsReportingEnabled"; // Determine whether configuration management allows loading the crash // reporter. Since the configuration management infrastructure is not // initialized in the installer, the corresponding registry keys are read // directly. The return status indicates whether policy data was successfully // read. If it is true, |enabled| contains the value set by policy. DWORD value = 0; base::win::RegKey policy_key; static const HKEY kHives[] = { HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER }; for (HKEY hive : kHives) { if (policy_key.Open(hive, kRegistryChromePolicyKey, KEY_READ) == ERROR_SUCCESS && policy_key.ReadValueDW(kMetricsReportingEnabled, &value) == ERROR_SUCCESS) { *enabled = value != 0; return true; } } return false; } bool InstallerCrashReporterClient::EnableBreakpadForProcess( const std::string& process_type) { return true; }
c++
code
5,605
898
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "logdevice/common/configuration/nodes/ServiceDiscoveryConfig.h" #include <gtest/gtest.h> #include "logdevice/common/Sockaddr.h" #include "logdevice/common/SocketTypes.h" using namespace facebook::logdevice; using configuration::nodes::NodeServiceDiscovery; using folly::StringPiece; namespace { constexpr StringPiece kTestAddress = "127.0.0.1"; constexpr in_port_t kTestDataPort = 4440; constexpr in_port_t kTestGossipPort = 4441; constexpr in_port_t kTestServerToServerPort = 4442; constexpr in_port_t kTestDataSslPort = 4444; const Sockaddr kTestDefaultAddress = Sockaddr{kTestAddress.toString(), kTestDataPort}; const Sockaddr kTestSslAddress = Sockaddr{kTestAddress.toString(), kTestDataSslPort}; const Sockaddr kTestGossipAddress = Sockaddr{kTestAddress.toString(), kTestGossipPort}; const Sockaddr kTestServerToServerAddress = Sockaddr{kTestAddress.toString(), kTestServerToServerPort}; class ServiceDiscoveryConfigTest : public ::testing::Test {}; // When only the 'address' member is populated, getSockAddr(DATA, PLAIN, NODE) // should return the default address. TEST(ServiceDiscoveryConfigTest, getSockaddr_GetDefaultSockAddr) { NodeServiceDiscovery nodeServiceDiscovery; nodeServiceDiscovery.address = kTestDefaultAddress; const Sockaddr& actual = nodeServiceDiscovery.getSockaddr( SocketType::DATA, ConnectionType::PLAIN, PeerType::NODE, false); EXPECT_EQ(actual, kTestDefaultAddress); } // Ditto for client peer. TEST(ServiceDiscoveryConfigTest, getSockaddr_GetDefaultSockAddrClient) { NodeServiceDiscovery nodeServiceDiscovery; nodeServiceDiscovery.address = kTestDefaultAddress; nodeServiceDiscovery.ssl_address = kTestSslAddress; const Sockaddr& actual = nodeServiceDiscovery.getSockaddr( SocketType::DATA, ConnectionType::PLAIN, PeerType::CLIENT, false); EXPECT_EQ(actual, kTestDefaultAddress); } // 'use_dedicated_server_to_server_address' parameter should be ignored when the // peer is a client. TEST(ServiceDiscoveryConfigTest, getSockaddr_IgnoreServerToServerAddressParam) { NodeServiceDiscovery nodeServiceDiscovery; nodeServiceDiscovery.address = kTestDefaultAddress; nodeServiceDiscovery.server_to_server_address = kTestServerToServerAddress; const Sockaddr& actual = nodeServiceDiscovery.getSockaddr( SocketType::DATA, ConnectionType::PLAIN, PeerType::CLIENT, true); EXPECT_EQ(actual, kTestDefaultAddress); } // When only the 'address' member is populated, getSockAddr(DATA, PLAIN, NODE) // should return the default address. TEST(ServiceDiscoveryConfigTest, getSockaddr_SslAddress) { NodeServiceDiscovery nodeServiceDiscovery; nodeServiceDiscovery.address = kTestDefaultAddress; nodeServiceDiscovery.ssl_address = kTestSslAddress; const Sockaddr& actual = nodeServiceDiscovery.getSockaddr( SocketType::DATA, ConnectionType::SSL, PeerType::NODE, false); EXPECT_EQ(actual, kTestSslAddress); } // Ditto for client peer. TEST(ServiceDiscoveryConfigTest, getSockaddr_SslAddressClient) { NodeServiceDiscovery nodeServiceDiscovery; nodeServiceDiscovery.address = kTestDefaultAddress; nodeServiceDiscovery.ssl_address = kTestSslAddress; const Sockaddr& actual = nodeServiceDiscovery.getSockaddr( SocketType::DATA, ConnectionType::SSL, PeerType::CLIENT, false); EXPECT_EQ(actual, kTestSslAddress); } // When both the 'address' and 'server_to_server_address' members are populated, // getSockAddr(DATA, PLAIN, NODE) should return the default address. // This test will become the same as // getSockaddr_DedicatedServerToServerAddressIfEnabled once the 4th argument of // getSockaddr(...) is removed. TEST(ServiceDiscoveryConfigTest, getSockaddr_DefaultServerToServerIsBaseAddress) { NodeServiceDiscovery nodeServiceDiscovery; nodeServiceDiscovery.address = kTestDefaultAddress; nodeServiceDiscovery.server_to_server_address = kTestServerToServerAddress; const Sockaddr& actual = nodeServiceDiscovery.getSockaddr( SocketType::DATA, ConnectionType::PLAIN, PeerType::NODE, false); EXPECT_EQ(actual, kTestDefaultAddress); } // When both the 'address' and 'server_to_server_address' members are populated, // getSockAddr(DATA, PLAIN, NODE, true) should return the server-to-server // address. TEST(ServiceDiscoveryConfigTest, getSockaddr_DedicatedServerToServerAddressIfEnabled) { NodeServiceDiscovery nodeServiceDiscovery; nodeServiceDiscovery.address = kTestDefaultAddress; nodeServiceDiscovery.server_to_server_address = kTestServerToServerAddress; const Sockaddr& actual = nodeServiceDiscovery.getSockaddr( SocketType::DATA, ConnectionType::PLAIN, PeerType::NODE, true); EXPECT_EQ(actual, kTestServerToServerAddress); } // When all off 'address', 'ssl_address', and 'server_to_server_address' // members are populated, getSockAddr(DATA, SSL, NODE, true) should return the // server-to-server address. TEST(ServiceDiscoveryConfigTest, getSockaddr_ServerToServerOverridesSslAddress) { NodeServiceDiscovery nodeServiceDiscovery; nodeServiceDiscovery.address = kTestDefaultAddress; nodeServiceDiscovery.ssl_address = kTestSslAddress; nodeServiceDiscovery.server_to_server_address = kTestServerToServerAddress; const Sockaddr& actual = nodeServiceDiscovery.getSockaddr( SocketType::DATA, ConnectionType::SSL, PeerType::NODE, true); EXPECT_EQ(actual, kTestServerToServerAddress); } TEST(ServiceDiscoveryConfigTest, getSockaddr_gossipAddressOverridesData) { NodeServiceDiscovery nodeServiceDiscovery; nodeServiceDiscovery.address = kTestDefaultAddress; nodeServiceDiscovery.gossip_address = kTestGossipAddress; nodeServiceDiscovery.server_to_server_address = kTestServerToServerAddress; const Sockaddr& actual = nodeServiceDiscovery.getSockaddr( SocketType::GOSSIP, ConnectionType::SSL, PeerType::NODE, true); EXPECT_EQ(actual, kTestGossipAddress); } // The function should return INVALID if // 'use_dedicated_server_to_server_address' is used but the NodeServiceDiscovery // object was not constructed with a valid server_to_server_address. TEST(ServiceDiscoveryConfigTest, getSockaddr_invalidServerToServerAddress) { NodeServiceDiscovery nodeServiceDiscovery; nodeServiceDiscovery.address = kTestDefaultAddress; const Sockaddr& actual = nodeServiceDiscovery.getSockaddr( SocketType::DATA, ConnectionType::PLAIN, PeerType::NODE, true); EXPECT_EQ(actual, Sockaddr::INVALID); } // The function should return INVALID if // ConnectionType::SSL is used but the NodeServiceDiscovery // object was not constructed with a valid ssl_address. TEST(ServiceDiscoveryConfigTest, getSockaddr_invalidSslAddress) { NodeServiceDiscovery nodeServiceDiscovery; nodeServiceDiscovery.address = kTestDefaultAddress; const Sockaddr& actual = nodeServiceDiscovery.getSockaddr( SocketType::DATA, ConnectionType::SSL, PeerType::NODE, true); EXPECT_EQ(actual, Sockaddr::INVALID); } } // namespace
c++
code
7,168
1,074
/******************************************************************************* * Copyright 2016-2022 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef DNNL_TEST_COMMON_HPP #define DNNL_TEST_COMMON_HPP #include <cmath> #include <limits> #include <numeric> #include <sstream> #include <stdint.h> #include <vector> #include <type_traits> #include <unordered_map> #include "gtest/gtest.h" #if defined(_MSC_VER) && !defined(__clang__) && !defined(__INTEL_COMPILER) #define collapse(x) #endif #include "oneapi/dnnl/dnnl.hpp" #include "oneapi/dnnl/dnnl_debug.h" #if DNNL_CPU_THREADING_RUNTIME == DNNL_RUNTIME_THREADPOOL #include "oneapi/dnnl/dnnl_threadpool.hpp" #endif #if DNNL_GPU_RUNTIME == DNNL_RUNTIME_OCL || defined(DNNL_WITH_SYCL) #include "dnnl_test_common_ocl.hpp" #endif #ifdef DNNL_WITH_SYCL #include "oneapi/dnnl/dnnl_sycl.hpp" #endif // Don't move it higher than library public headers #include "dnnl_test_macros.hpp" #include "src/common/bfloat16.hpp" #include "src/common/float16.hpp" #include "src/common/memory_desc_wrapper.hpp" #include "src/common/nstl.hpp" #include "src/common/primitive_cache.hpp" #include "tests/gtests/test_malloc.hpp" #include "tests/test_thread.hpp" #include "src/cpu/platform.hpp" #define for_ for using dnnl::impl::bfloat16_t; using dnnl::impl::f16_support::float16_t; #ifdef DNNL_ENABLE_MEM_DEBUG #define DNNL_CHECK(f) \ do { \ dnnl_status_t s = (f); \ dnnl::error::wrap_c_api(s, dnnl_status2str(s)); \ } while (0) #else #define DNNL_CHECK(f) \ do { \ dnnl_status_t s = (f); \ ASSERT_EQ(s, dnnl_success); \ } while (0) #endif // XXX: Using EXPECT_NE in 'if' statement raises a warning when GCC compiler is // used: suggest explicit braces to avoid ambiguous 'else' #define GTEST_EXPECT_NE(val1, val2) \ do { \ EXPECT_NE(val1, val2); \ } while (0) using memory = dnnl::memory; bool is_current_test_failed(); #ifdef DNNL_TEST_WITH_ENGINE_PARAM dnnl::engine::kind get_test_engine_kind(); dnnl::engine get_test_engine(); #endif inline int get_vendor_id(const std::string &vendor) { if (vendor == "nvidia") { return 0x10DE; } else if (vendor == "intel") { return 0x8086; } else { return -1; } } inline bool is_nvidia_gpu(const dnnl::engine &eng) { #ifdef DNNL_WITH_SYCL if (eng.get_kind() != dnnl::engine::kind::gpu) return false; const uint32_t nvidia_vendor_id = get_vendor_id("nvidia"); const auto device = dnnl::sycl_interop::get_device(eng); const auto eng_vendor_id = device.get_info<::sycl::info::device::vendor_id>(); return eng_vendor_id == nvidia_vendor_id; #endif return false; } inline bool is_sycl_engine(dnnl::engine::kind eng_kind) { #if DNNL_CPU_RUNTIME == DNNL_RUNTIME_SYCL if (eng_kind == dnnl::engine::kind::cpu) return true; #endif #if DNNL_GPU_RUNTIME == DNNL_RUNTIME_SYCL if (eng_kind == dnnl::engine::kind::gpu) return true; #endif return false; } inline bool unsupported_data_type(memory::data_type dt, dnnl::engine eng) { bool supported = true; // optimism #if DNNL_CPU_RUNTIME != DNNL_RUNTIME_NONE dnnl::engine::kind kind = eng.get_kind(); if (kind == dnnl::engine::kind::cpu) supported = dnnl::impl::cpu::platform::has_data_type_support( memory::convert_to_c(dt)); #endif #ifdef DNNL_SYCL_CUDA if (is_nvidia_gpu(eng)) { switch (dt) { case memory::data_type::f32: return false; case memory::data_type::f16: return false; case memory::data_type::s8: return false; case memory::data_type::undef: return false; default: return true; } } #endif return !supported; } #ifdef DNNL_TEST_WITH_ENGINE_PARAM inline bool unsupported_data_type(memory::data_type dt) { return unsupported_data_type(dt, get_test_engine()); } #endif template <typename data_t> struct data_traits {}; template <> struct data_traits<float16_t> { static const auto data_type = memory::data_type::f16; using uint_type = uint16_t; }; template <> struct data_traits<bfloat16_t> { static const auto data_type = memory::data_type::bf16; using uint_type = uint16_t; }; template <> struct data_traits<float> { static const auto data_type = memory::data_type::f32; using uint_type = uint32_t; }; template <> struct data_traits<uint8_t> { static const auto data_type = memory::data_type::u8; using uint_type = uint8_t; }; template <> struct data_traits<int8_t> { static const auto data_type = memory::data_type::s8; using uint_type = uint8_t; }; template <> struct data_traits<int32_t> { static const auto data_type = memory::data_type::s32; using uint_type = uint32_t; }; template <typename T> inline void assert_eq(T a, T b); template <> inline void assert_eq<float>(float a, float b) { ASSERT_FLOAT_EQ(a, b); } #if defined(__x86_64__) || defined(_M_X64) #include <immintrin.h> inline int mxcsr_cvt(float f) { return _mm_cvtss_si32(_mm_load_ss(&f)); } #else inline int mxcsr_cvt(float f) { return (int)nearbyintf(f); } #endif template <typename data_t> data_t out_round(float x) { return (data_t)mxcsr_cvt(x); } template <> inline float out_round<float>(float x) { return x; } template <typename data_t, typename out_t> out_t saturate(const out_t &x) { out_t v = x; if (v <= std::numeric_limits<data_t>::min()) v = std::numeric_limits<data_t>::min(); if (v > std::numeric_limits<data_t>::max()) v = std::numeric_limits<data_t>::max(); return v; } inline memory::dim right_padding(memory::dim i, memory::dim o, memory::dim k, memory::dim p, memory::dim s, memory::dim d = 0) { return (o - 1) * s + (k - 1) * (d + 1) - (p + i - 1); } template <typename data_t> struct acc_t { typedef data_t type; }; template <> struct acc_t<int8_t> { typedef int type; }; template <> struct acc_t<uint8_t> { typedef int type; }; // Smart pointer for map/unmap operations with unique_ptr semantics template <typename T> struct mapped_ptr_t { using nonconst_type = typename std::remove_cv<T>::type; mapped_ptr_t(std::nullptr_t) : mem_(nullptr), ptr_(nullptr) {} mapped_ptr_t(const memory *mem) : mem_(mem) { ptr_ = mem->map_data<nonconst_type>(); } mapped_ptr_t(mapped_ptr_t &&other) : mem_(other.mem_), ptr_(other.ptr_) { other.mem_ = nullptr; other.ptr_ = nullptr; } mapped_ptr_t(const mapped_ptr_t &) = delete; mapped_ptr_t &operator=(const mapped_ptr_t &) = delete; ~mapped_ptr_t() { if (mem_ && ptr_) mem_->unmap_data(ptr_); }; operator T *() { return ptr_; } operator const T *() const { return ptr_; } operator bool() const { return ptr_ != nullptr; } private: const memory *mem_; nonconst_type *ptr_; }; template <typename T> mapped_ptr_t<T> map_memory(const memory &mem) { return mapped_ptr_t<T>(&mem); } // check_zero_tail - check on zero or set to zero padded memory template <typename data_t> void check_zero_tail(int set_zero_flag, const memory &src) { auto src_data = map_memory<data_t>(src); const memory::desc src_d = src.get_desc(); const int ndims = src_d.data.ndims; const auto *dims = src_d.data.dims; const auto *pdims = src_d.data.padded_dims; const dnnl::impl::memory_desc_wrapper mdw(src_d.data); memory::dim idx[DNNL_MAX_NDIMS] = {}, str[DNNL_MAX_NDIMS] = {}; memory::dim nelems = 1; int tail_flag = 0; for (int i = 0; i < ndims; ++i) { if (dims[ndims - i - 1] != pdims[ndims - i - 1]) tail_flag = 1; nelems *= pdims[ndims - i - 1]; idx[i] = 0; str[i] = (i == 0) ? 1 : str[i - 1] * pdims[ndims - i]; } if (tail_flag == 0) return; for (memory::dim i = 0; i < nelems; ++i) { memory::dim off = 0; bool flag = 0; for (int j = 0; j < ndims; ++j) { off += idx[j] * str[j]; if (idx[j] >= dims[ndims - j - 1]) flag = 1; } if (flag == 1) { memory::dim blk_off = mdw.off_l(off, true); if (set_zero_flag) { src_data[blk_off] = 0.0; } else { ASSERT_EQ(src_data[blk_off], 0.0) << " blk_off = " << blk_off << "off = " << off; } } /*Update idx*/ for (int j = 0; j < ndims; ++j) { idx[j]++; if (idx[j] < pdims[ndims - j - 1]) break; idx[j] = 0; } } } inline memory::desc create_md(memory::dims dims, memory::data_type data_type, memory::format_tag fmt_tag) { return memory::desc(dims, data_type, fmt_tag); } template <typename data_t> static inline data_t set_value( memory::dim index, data_t mean, data_t deviation, double sparsity) { if (data_traits<data_t>::data_type == memory::data_type::f16 || data_traits<data_t>::data_type == memory::data_type::bf16) { return data_t(set_value<float>(index, mean, deviation, sparsity)); } else if (data_traits<data_t>::data_type == memory::data_type::f32) { const memory::dim group_size = (memory::dim)(1. / sparsity); const memory::dim group = index / group_size; const memory::dim in_group = index % group_size; const bool fill = in_group == ((group % 1637) % group_size); return fill ? static_cast<data_t>( mean + deviation * sinf(float(index % 37))) : data_t {0}; } else if (data_traits<data_t>::data_type == memory::data_type::s32 || data_traits<data_t>::data_type == memory::data_type::s8) { return data_t(index * 13 % 21 - 10); } else if (data_traits<data_t>::data_type == memory::data_type::u8) { return data_t(index * 13 % 17); } assert(!"not expected"); return data_t(0); } template <typename data_t> static void fill_data(const memory::dim nelems, data_t *data, data_t mean, data_t deviation, double sparsity = 1.) { dnnl::impl::parallel_nd(nelems, [&](memory::dim n) { data[n] = set_value<data_t>(n, mean, deviation, sparsity); }); } template <typename data_t> static void fill_data(const memory::dim nelems, const memory &mem, data_t mean, data_t deviation, double sparsity = 1.) { auto data_ptr = map_memory<data_t>(mem); fill_data<data_t>(nelems, data_ptr, mean, deviation, sparsity); } inline void fill_data(memory::data_type dt, const memory &mem, float mean, float deviation, double sparsity = 1.) { size_t nelems = mem.get_desc().get_size() / memory::data_type_size(dt); switch (dt) { case memory::data_type::f32: fill_data<float>(nelems, mem, mean, deviation, sparsity); break; case memory::data_type::bf16: fill_data<bfloat16_t>(nelems, mem, mean, deviation, sparsity); break; case memory::data_type::f16: fill_data<float16_t>(nelems, mem, mean, deviation, sparsity); break; case memory::data_type::s32: fill_data<int>(nelems, mem, mean, deviation, sparsity); break; case memory::data_type::s8: fill_data<int8_t>(nelems, mem, mean, deviation, sparsity); break; case memory::data_type::u8: fill_data<uint8_t>(nelems, mem, mean, deviation, sparsity); break; default: assert(!"unsupported data type"); break; } } template <typename data_t> static void fill_data(const memory::dim nelems, data_t *data, double sparsity = 1., bool init_negs = false) { dnnl::impl::parallel_nd(nelems, [&](memory::dim n) { data[n] = set_value<data_t>(n, data_t(1), data_t(2e-1), sparsity); if (init_negs && n % 4 == 0) data[n] = static_cast<data_t>( -data[n]); // weird for unsigned types! }); } template <typename data_t> static void fill_data(const memory::dim nelems, const memory &mem, double sparsity = 1., bool init_negs = false) { auto data_ptr = map_memory<data_t>(mem); fill_data<data_t>(nelems, data_ptr, sparsity, init_negs); } template <typename data_t> static void remove_zeroes(const memory &mem) { size_t nelems = mem.get_desc().get_size() / sizeof(data_t); auto data_ptr = map_memory<data_t>(mem); dnnl::impl::parallel_nd(nelems, [&](memory::dim n) { if (data_ptr[n] == data_t(0)) data_ptr[n] += data_t(1); }); } template <typename data_t> static void compare_data( const memory &ref, const memory &dst, data_t threshold = (data_t)1e-4) { using data_type = memory::data_type; ASSERT_TRUE(data_traits<data_t>::data_type == data_type::f32 || data_traits<data_t>::data_type == data_type::f16 || data_traits<data_t>::data_type == data_type::bf16 || data_traits<data_t>::data_type == data_type::s32 || data_traits<data_t>::data_type == data_type::s8); /* Note: size_t incompatible with MSVC++ */ auto ref_desc = ref.get_desc(); auto dst_desc = dst.get_desc(); const dnnl::impl::memory_desc_wrapper mdw_ref(ref_desc.data); const dnnl::impl::memory_desc_wrapper mdw_dst(dst_desc.data); ASSERT_TRUE(ref_desc.data.ndims == dst_desc.data.ndims); auto ndims = ref_desc.data.ndims; for (auto d = 0; d < ndims; ++d) { ASSERT_TRUE(ref_desc.data.dims[d] == dst_desc.data.dims[d]); } auto dims = ref_desc.data.dims; memory::dim num = 1; for (auto d = 0; d < ndims; ++d) { num *= dims[d]; } auto ref_data = map_memory<data_t>(ref); auto dst_data = map_memory<data_t>(dst); dnnl::impl::parallel_nd(num, [&](memory::dim i) { if (is_current_test_failed()) return; data_t ref = ref_data[mdw_ref.off_l(i, true)]; data_t got = dst_data[mdw_dst.off_l(i, true)]; if (data_traits<data_t>::data_type == data_type::f32 || data_traits<data_t>::data_type == data_type::f16 || data_traits<data_t>::data_type == data_type::bf16) { const float threshold_f32 = static_cast<float>(threshold); const float ref_f32 = static_cast<float>(ref); const float got_f32 = static_cast<float>(got); const float diff_f32 = (got_f32 == ref_f32) ? 0.0f : got_f32 - ref_f32; const float e = (std::abs(ref_f32) > threshold_f32) ? diff_f32 / ref_f32 : diff_f32; ASSERT_NEAR(e, 0.0, threshold_f32) << "Index: " << i << " Total: " << num; } else { ASSERT_EQ(ref, got) << "Index: " << i << " Total: " << num; } }); } inline const char *query_impl_info(const_dnnl_primitive_desc_t pd) { const char *str; dnnl_primitive_desc_query(pd, dnnl_query_impl_info_str, 0, &str); return str; }; inline dnnl_status_t get_conv_impl_status( const_dnnl_primitive_desc_t pd, const char *match_str) { const char *conv_str = query_impl_info(pd); if (strstr(conv_str, match_str) != NULL) return dnnl_status_t::dnnl_success; return dnnl_status_t::dnnl_unimplemented; }; struct test_convolution_sizes_t { test_convolution_sizes_t(memory::dim mb, memory::dim ng, memory::dim ic, memory::dim ih, memory::dim iw, memory::dim oc, memory::dim oh, memory::dim ow, memory::dim kh, memory::dim kw, memory::dim padh, memory::dim padw, memory::dim strh, memory::dim strw, memory::dim dilh = 0, memory::dim dilw = 0) : mb(mb) , ng(ng) , ic(ic) , ih(ih) , iw(iw) , oc(oc) , oh(oh) , ow(ow) , kh(kh) , kw(kw) , padh(padh) , padw(padw) , strh(strh) , strw(strw) , dilh(dilh) , dilw(dilw) {} memory::dim mb; memory::dim ng; memory::dim ic, ih, iw; memory::dim oc, oh, ow; memory::dim kh, kw; memory::dim padh, padw; memory::dim strh, strw; memory::dim dilh, dilw; }; struct test_convolution_attr_t { struct scale_t { enum policy_t { NONE = 0, COMMON }; bool is_def() const { return policy != NONE; } scale_t(float s, policy_t p = NONE) : scale(s) { policy = p; } policy_t policy; float scale; }; void dnnl_attr_recreate() { mkl_attr = dnnl::primitive_attr(); if (oscale.is_def()) { const memory::dim count = 1; const int mask = 0; std::vector<float> s(count, oscale.scale); mkl_attr.set_output_scales(mask, s); } } test_convolution_attr_t( float s, scale_t::policy_t p = scale_t::policy_t::NONE) : oscale(s, p), mkl_attr() {} test_convolution_attr_t() : test_convolution_attr_t(1.f) {} scale_t oscale; dnnl::primitive_attr mkl_attr; }; struct test_convolution_formats_t { memory::format_tag src_format; memory::format_tag weights_format; memory::format_tag bias_format; memory::format_tag dst_format; }; struct test_convolution_params_t { dnnl::algorithm aalgorithm; test_convolution_formats_t formats; test_convolution_attr_t attr; test_convolution_sizes_t sizes; bool expect_to_fail; dnnl_status_t expected_status; }; struct test_convolution_eltwise_params_t { const dnnl::algorithm alg; dnnl::algorithm aalgorithm; const float eltwise_alpha; const float eltwise_beta; test_convolution_formats_t formats; test_convolution_attr_t attr; test_convolution_sizes_t sizes; bool expect_to_fail; dnnl_status_t expected_status; }; template <typename F> bool catch_expected_failures(const F &f, bool expect_to_fail, dnnl_status_t expected_status, bool ignore_unimplemented = false) { try { f(); } catch (const dnnl::error &e) { // Rethrow the exception if it is not expected or the error status did // not match. if (!(expect_to_fail) || e.status != (expected_status)) { // Ignore unimplemented if (ignore_unimplemented && (e.status == dnnl_unimplemented)) { // Print unimplemented but do not treat as error std::cout << "[ UNIMPL ] " << "Implementation not found" << std::endl; reset_failed_malloc_counter(); return true; } else if (test_out_of_memory() && (e.status == dnnl_out_of_memory || e.status == dnnl_unimplemented)) { // Restart if error thrown due to a malloc failed intentionally, // and increment malloc counter. // TODO: This should be valid only for `dnnl_out_of_memory` // error. Currently a failed malloc inside // gemm_pack_storage_shell_t ctor makes it unable to use the // reference RNN impl, and the iterator produces an // `dnnl_unimplemented` error. increment_failed_malloc_counter(); return catch_expected_failures(f, expect_to_fail, expected_status, ignore_unimplemented); } else { if (expect_to_fail && (e.status != expected_status)) std:
c++
code
20,000
4,635
//-------------------------------------------------------------------------------------------------- // Copyright (c) YugaByte, 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 "yb/util/bfpg/bfpg.h" #include <functional> #include <unordered_map> #include "yb/common/ql_type.h" #include "yb/util/bfpg/directory.h" using std::function; using std::vector; using std::unordered_map; using strings::Substitute; namespace yb { namespace bfpg { //-------------------------------------------------------------------------------------------------- bool IsAggregateOpcode(TSOpcode op) { switch (op) { case TSOpcode::kAvg: FALLTHROUGH_INTENDED; case TSOpcode::kCount: FALLTHROUGH_INTENDED; case TSOpcode::kMax: FALLTHROUGH_INTENDED; case TSOpcode::kMin: FALLTHROUGH_INTENDED; case TSOpcode::kSumInt8: FALLTHROUGH_INTENDED; case TSOpcode::kSumInt16: FALLTHROUGH_INTENDED; case TSOpcode::kSumInt32: FALLTHROUGH_INTENDED; case TSOpcode::kSumInt64: FALLTHROUGH_INTENDED; case TSOpcode::kSumFloat: FALLTHROUGH_INTENDED; case TSOpcode::kSumDouble: return true; default: return false; } } //-------------------------------------------------------------------------------------------------- // Check compatible type in function call. inline bool IsCompatible(DataType left, DataType right) { return QLType::IsPotentiallyConvertible(left, right); } //-------------------------------------------------------------------------------------------------- // HasExactSignature() is a predicate to check if the datatypes of actual parameters (arguments) // and formal parameters (signature) are identical. // NOTES: // PTypePtr can be a (shared_ptr<MyClass>) or a raw pointer (MyClass*) static bool HasExactTypeSignature(const std::vector<DataType>& signature, const std::vector<DataType>& actual_types) { // Check parameter count. const int formal_count = signature.size(); const int actual_count = actual_types.size(); // Check for exact match. int index; for (index = 0; index < formal_count; index++) { // Check if the signature accept varargs which can be matched with the rest of arguments. if (signature[index] == DataType::TYPEARGS) { return true; } // Return false if one of the following is true. // - The number of arguments is less than the formal count. // - The datatype of an argument is not an exact match of the signature type. if (index >= actual_count || signature[index] != actual_types[index]) { return false; } } // Assert that the number of arguments is the same as the formal count. if (index < actual_count) { return false; } return true; } //-------------------------------------------------------------------------------------------------- // HasSimilarSignature() is a predicate to check if the datatypes of actual parameters (arguments) // and formal parameters (signature) are similar. // // Similar is mainly used for integers vs floating point values. // INT8 is "similar" to INT64. // INT8 is NOT "similar" to DOUBLE. // FLOAT is "similar" to DOUBLE. // This rule is to help resolve the overloading functions between integers and float point data. // // NOTES: // PTypePtr and RTypePtr can be either a (shared_ptr<MyClass>) or a raw pointer (MyClass*) static bool HasSimilarTypeSignature(const std::vector<DataType>& signature, const std::vector<DataType>& actual_types) { const int formal_count = signature.size(); const int actual_count = actual_types.size(); // Check for exact match. int index; for (index = 0; index < formal_count; index++) { // Check if the signature accept varargs which can be matched with the rest of arguments. if (signature[index] == DataType::TYPEARGS) { return true; } // Return false if one of the following is true. // - The number of arguments is less than the formal count. // - The datatype of an argument is not an similar match of the signature type. if (index >= actual_count || !QLType::IsSimilar(signature[index], actual_types[index])) { return false; } } // Assert that the number of arguments is the same as the formal count. if (index < actual_count) { return false; } return true; } //-------------------------------------------------------------------------------------------------- // HasCompatibleSignature() is a predicate to check if the arguments is convertible to the // signature. // // TODO(neil) Needs to allow passing double to int. // NOTES: // PTypePtr and RTypePtr can be either a (shared_ptr<MyClass>) or a raw pointer (MyClass*). static bool HasCompatibleTypeSignature(const std::vector<DataType>& signature, const std::vector<DataType>& actual_types) { const int formal_count = signature.size(); const int actual_count = actual_types.size(); // Check for compatible match. int index; for (index = 0; index < formal_count; index++) { // Check if the signature accept varargs which can be matched with the rest of arguments. if (signature[index] == DataType::TYPEARGS) { return true; } // Return false if one of the following is true. // - The number of arguments is less than the formal count. // - The datatype of an argument is not a compatible match of the signature type. if (index >= actual_count || !IsCompatible(signature[index], actual_types[index])) { return false; } } // Assert that the number of arguments is the same as the formal count. if (index < actual_count) { return false; } return true; } //-------------------------------------------------------------------------------------------------- // Searches all overloading versions of a function and finds exactly one function specification // whose signature matches with the datatypes of the arguments. // NOTES: // "compare_signature" is a predicate to compare datatypes of formal and actual parameters. // PTypePtr and RTypePtr can be either a (shared_ptr<MyClass>) or a raw pointer (MyClass*) static Status FindMatch( const string& ql_name, function<bool(const std::vector<DataType>&, const std::vector<DataType>&)> compare_signature, BFOpcode max_opcode, const std::vector<DataType>& actual_types, BFOpcode *found_opcode, const BFDecl **found_decl, DataType *return_type) { // Find a compatible operator, and raise error if there's more than one match. const BFOperator *compatible_operator = nullptr; while (true) { const BFOperator *bf_operator = kBFOperators[static_cast<int>(max_opcode)].get(); DCHECK(max_opcode == bf_operator->opcode()); // Check if each parameter has compatible type match. if (compare_signature(bf_operator->param_types(), actual_types)) { // Found a compatible match. Make sure that it is the only match. if (compatible_operator != nullptr) { return STATUS(InvalidArgument, Substitute("Found too many matches for builtin function '$0'", ql_name)); } compatible_operator = bf_operator; } // Break the loop if we have processed all operators in the overloading chain. if (max_opcode == bf_operator->overloaded_opcode()) { break; } // Jump to the next overloading opcode. max_opcode = bf_operator->overloaded_opcode(); } // Returns error if no match is found. if (compatible_operator == nullptr) { return STATUS(NotFound, Substitute("Signature mismatch in call to builtin function '$0'", ql_name)); } // Returns error if the return type is not compatible. if (return_type != nullptr) { if (QLType::IsUnknown(*return_type)) { *return_type = compatible_operator->return_type(); } else if (!IsCompatible(*return_type, compatible_operator->return_type())) { return STATUS(InvalidArgument, Substitute("Return-type mismatch in call to builtin function '$0'", ql_name)); } } // Raise error if the function execution was not yet implemented. if (!compatible_operator->op_decl()->implemented()) { return STATUS(NotSupported, Substitute("Builtin function '$0' is not yet implemented", ql_name)); } *found_opcode = compatible_operator->opcode(); *found_decl = compatible_operator->op_decl(); return Status::OK(); } //-------------------------------------------------------------------------------------------------- // Find the builtin opcode, declaration, and return type for a builtin call. // Inputs: Builtin function name and parameter types. // Outputs: opcode and bfdecl. // In/Out parameter: return_type // If return_type is given, check if it is compatible with the declaration. // If not, return_type is an output parameter whose value is the return type of the builtin. Status FindOpcodeByType(const string& ql_name, const std::vector<DataType>& actual_types, BFOpcode *opcode, const BFDecl **bfdecl, DataType *return_type) { auto entry = kBfPgsqlName2Opcode.find(ql_name); if (entry == kBfPgsqlName2Opcode.end()) { VLOG(3) << strings::Substitute("Function '$0' does not exist", ql_name); return STATUS(NotFound, strings::Substitute("Function '$0' does not exist", ql_name)); } // Seek the correct overload functions in the following order: // - Find the exact signature match. // Example: // . Overload #1: FuncX(int8_t i) would be used for the call FuncX(int8_t(7)). // . Overload #2: FuncX(int16_t i) would be used for the call FuncX(int16_t(7)). // // - For "cast" operator, if exact match is not found, return error. For all other operators, // continue to the next steps. // // - Find the similar signature match. // Example: // . Overload #2: FuncY(int64_t i) would be used for FuncY(int8_t(7)). // int64_t and int8_t are both integer values. // . Overload #1: FuncY(double d) would be used for FuncY(float(7)). // double & float are both floating values. // // - Find the compatible match. Signatures are of convertible datatypes. Status s = FindMatch(ql_name, HasExactTypeSignature, entry->second, actual_types, opcode, bfdecl, return_type); VLOG(3) << "Seek exact match for function call " << ql_name << "(): " << s.ToString(); if (ql_name != kCastFuncName && s.IsNotFound()) { s = FindMatch(ql_name, HasSimilarTypeSignature, entry->second, actual_types, opcode, bfdecl, return_type); VLOG(3) << "Seek similar match for function call " << ql_name << "(): " << s.ToString(); if (s.IsNotFound()) { s = FindMatch(ql_name, HasCompatibleTypeSignature, entry->second, actual_types, opcode, bfdecl, return_type); VLOG(3) << "Seek compatible match for function call " << ql_name << "(): " << s.ToString(); } } return s; } } // namespace bfpg } // namespace yb
c++
code
11,669
2,697
#include <filesystem> #include <fstream> #include <functional> #include <random> #include "utils.hpp" #include "distances/dtw/dtw.hpp" #include "distances/dtw/pruneddtw.hpp" #include "distances/dtw/pruneddtw_ea.hpp" #include "distances/dtw/cdtw.hpp" #include "distances/dtw/wdtw.hpp" #include "distances/elementwise/elementwise.hpp" #include "distances/erp/erp.hpp" #include "distances/lcss/lcss.hpp" #include "distances/msm/msm.hpp" #include "distances/twe/twe.hpp" #include "distances/dtw/lowerbounds/envelopes.hpp" #include "distances/dtw/lowerbounds/lb_keogh.hpp" #include "distances/dtw/lowerbounds/lb_webb.hpp" #include "tseries/tseries.hpp" #include "tseries/readers/tsreader/tsreader.hpp" #define STRINGIFY_DETAIL(x) #x #define STRINGIFY(x) STRINGIFY_DETAIL(x) namespace fs = std::filesystem; using namespace std; using PRNG = mt19937_64; /** Print the usage/help on cout */ void print_usage(const string& execname, ostream& out) { out << "NN1 classification for the UCR archive - Monash University, Melbourne, Australia, 2021" << endl; out << "Command:" << endl; out << " " << execname << " <dataset> <distance> <base|eap|eap_la> [-out outfile]" << endl; out << "Dataset:" << endl; out << " -ucr <path to dir> Path to a directory containing datasets in ts format." << endl; out << " A dataset is itself a directory containing a _TRAIN.ts and a _TEST.ts files." << endl; out << " -dataset <string> Limit experiment to a given dataset. Must match the dataset's folder name." << endl; out << "Distance: -dist <distance name and args>:" << endl; out << " dtw [LB] DTW distance, optional lower bound" << endl; out << " cdtw <wr> [LB] CDTW distance with a window ratio 0<=wr<=1, optional lower bound" << endl; out << " LB:" << endl; out << " lb-none Do not use any lower bound (default)" << endl; out << " lb-keogh LB-Keogh between the query and the envelopes of the candidate" << endl; out << " lb-keogh2 LB-Keogh both way" << endl; out << " lb-webb LB-WEBB" << endl; out << " wdtw <g> WDTW distance with a weight factor 0<=g" << endl; out << " sqed Squared Euclidean distance" << endl; out << " erp <gv> <wr> ERP distance with a gap value 0<=gv and window ratio 0<=wr<=1" << endl; out << " lcss <e> <wr> LCSS distance with an epsilon 0<=e and window ratio 0<=wr<=1" << endl; out << " lcss <e> int <w> LCSS distance with an epsilon 0<=e and integer window size 0<=w" << endl; out << " msm <cost> MSM distance with a Split and Merge cost 0<=cost" << endl; out << " twe <nu> <lambda> TWE distance with a stiffness 0<=nu and a constant delete penalty 0<=lambda" << endl; out << "Note: windows are computed using the window ratio and the longest series in the dataset." << endl; out << "Run mode:" << endl; out << " base Base implementation, on a double buffer where applicable (default)" << endl; out << " base_ea Base implementation with early abandon. Not for LCSS, SQED" << endl; out << " pru Pruning only, using EAP and cutoff based on the diagonal (no early abandoning!). Not for LCSS, SQED. " << endl; out << " pru_la PRU with last alignment cutoff adjustment. Not for LCSS, SQED" << endl; out << " pruneddtw PrunedDTW implementation. Only for DTW and CDTW." << endl; out << " pruneddtw2018 PrunedDTW 2018 implementation (with early abandon). Only for DTW and CDTW. Not compatible with LB-Webb" << endl; out << " eap Early abandoned and pruned. SQED and LCSS are only early abandoned, not pruned" << endl; out << " eap_la EAP with last alignment cutoff adjustment. Not for LCSS." << endl; out << "Create an output file: '-out <outfile>'" << endl; out << "Examples:" << endl; out << " " << execname << " -dist cdtw 0.2 lb-keogh2 -ucr /path/to/Univariate_ts -dataset Crop" << endl; out << endl; } /** Print an error followed by usage, then exit */ void print_error_exit(const string& invoc_string, const string& msg, int exit_code) { std::cerr << "Error: " << msg << endl; print_usage(invoc_string, std::cerr); exit(exit_code); } /** Check if a path represent a readable file */ inline bool is_read_open(const fs::path& p) { return fs::exists(p) && ifstream(p); } enum RUNMODE { BASE, BASE_EA, PRU, PRU_LA, PRUNEDDTW, PRUNEDDTW2018, EAP, EAP_LA, }; string to_string(RUNMODE rm) { switch (rm) { case BASE: return "base"; case BASE_EA: return "base_ea"; case PRU: return "pru"; case PRU_LA: return "pru_la"; case PRUNEDDTW: return "pruneddtw"; case PRUNEDDTW2018: return "pruneddtw2018"; case EAP: return "eap"; case EAP_LA: return "eap_la"; } return ""; } enum DTW_LB { NONE, KEOGH, KEOGH2, WEBB, }; string to_string(DTW_LB lb) { switch (lb) { case NONE: return "lb-none"; case KEOGH: return "lb-keogh"; case KEOGH2: return "lb-keogh2"; case WEBB: return "lb-webb"; } return ""; } typedef const TSData& TD; #define TRAIN_TEST TD train, size_t idtrain, TD test, size_t idtest typedef std::function<double(TRAIN_TEST, double ub)> distfun_t; #define USE(s) s.data(), s.length() #define TRAIN USE(train[idtrain]) #define TEST USE(test[idtest]) struct config { optional<fs::path> path_ucr{}; optional<string> dataset{}; optional<fs::path> path_train{}; optional<fs::path> path_test{}; optional<string> distance_name{}; optional<fs::path> outpath{}; DTW_LB dtw_lb{NONE}; double cdtw_wratio{1}; // 1 by default: allow to use without change for dtw double wdtw_g{-1}; double erp_gv{-1}; double erp_wratio{-1}; double lcss_epsilon{-1}; double lcss_wratio{-1}; bool lcss_int{false}; double msm_cost{-1}; double twe_nu{-1}; double twe_lambda{-1}; RUNMODE runmode{BASE}; }; /// Type of an envelope typedef vector<double> env_t; /** Helper used to compute the upper and lower envelopes of a dataset */ void compute_envelopes(TD dataset, vector<tuple<env_t, env_t>>& envelopes, size_t w) { for (const auto& s:dataset.series) { const auto l = s.length(); vector<double> up(l); vector<double> lo(l); get_envelopes(s.data(), l, up.data(), lo.data(), w); envelopes.emplace_back(up, lo); } } /** Helper used to compute envelopes for lb Webb*/ void compute_envelopes_Webb(TD dataset, vector<tuple<env_t, env_t, env_t, env_t>>& envelopes, size_t w) { for (const auto& s:dataset.series) { const auto l = s.length(); env_t up(l); env_t lo(l); env_t lo_up(l); env_t up_lo(l); get_envelopes_Webb(s.data(), l, up.data(), lo.data(), lo_up.data(), up_lo.data(), w); envelopes.emplace_back(up, lo, lo_up, up_lo); } } /** Only for DTW and CDTW, all series with same length. * Embed a distance under a lower bound */ variant<string, distfun_t> do_lb(distfun_t&& innerdist, const config& conf, size_t maxl, size_t minl, size_t w) { // Pre-check if (conf.dtw_lb!=NONE && minl!=maxl) { return {"Lower bound require same-length series"}; } // Only for DTW and CDTW if (conf.distance_name=="dtw" || conf.distance_name=="cdtw") { switch (conf.dtw_lb) { case NONE: { return {innerdist}; } // --- --- --- case KEOGH: { // Captured state vector<tuple<vector<double>, vector<double>>> env_train; // Definition distfun_t dfun = [innerdist, env_train, w](TRAIN_TEST, double ub) mutable { // Compute envelopes once if (env_train.empty()) { compute_envelopes(train, env_train, w); } // Lb Keogh const auto&[up, lo] = env_train[idtrain]; double v = lb_Keogh(TEST, up.data(), lo.data(), ub); if (v<ub) { v = innerdist(train, idtrain, test, idtest, ub); } return v; }; return {dfun}; } // --- --- --- case KEOGH2: { // Captured state vector<tuple<vector<double>, vector<double>>> env_train; map<size_t, tuple<vector<double>, vector<double>>> env_test; // Definition distfun_t dfun = [innerdist, env_train, env_test, w](TRAIN_TEST, double ub) mutable { // Compute envelopes once if (env_train.empty()) { compute_envelopes(train, env_train, w); } // Lb Keogh 1 const auto&[up, lo] = env_train[idtrain]; double v = lb_Keogh(TEST, up.data(), lo.data(), ub); if (v<ub) { // LB Keogh 2 const auto lq = test[idtest].length(); if (!contains(env_test, idtest)) { vector<double> upq(lq); vector<double> loq(lq); get_envelopes(TEST, upq.data(), loq.data(), w); env_test.emplace(idtest, std::tuple(std::move(upq), std::move(loq))); } const auto&[upq, loq] = env_test[idtest]; v = lb_Keogh(TRAIN, upq.data(), loq.data(), ub); // Distance if (v<ub) { v = innerdist(train, idtrain, test, idtest, ub); } } return v; }; return {dfun}; } // --- --- --- case WEBB: { // Captured state vector<tuple<env_t, env_t, env_t, env_t>> env_train; map<size_t, tuple<env_t, env_t, env_t, env_t>> env_test; // Definition distfun_t dfun = [innerdist, env_train, env_test, w](TRAIN_TEST, double ub) mutable { // Compute envelopes once for the train if (env_train.empty()) { compute_envelopes_Webb(train, env_train, w); } // Retrieve candidate const auto&[up, lo, lo_up, up_lo] = env_train[idtrain]; // Compute envelopes of the query const auto lq = test[idtest].length(); if (!contains(env_test, idtest)) { env_t q_up(lq); env_t q_lo(lq); env_t q_lo_up(lq); env_t q_up_lo(lq); get_envelopes_Webb(TEST, q_up.data(), q_lo.data(), q_lo_up.data(), q_up_lo.data(), w); env_test.emplace(idtest, std::tuple(std::move(q_up), std::move(q_lo), std::move(q_lo_up), std::move(q_up_lo))); } const auto&[q_up, q_lo, q_lo_up, q_up_lo] = env_test[idtest]; // double v = lb_Webb( TEST, q_up.data(), q_lo.data(), q_lo_up.data(), q_up_lo.data(), TRAIN, up.data(), lo.data(), lo_up.data(), up_lo.data(), w, ub); // Distance if (v<ub) { v = innerdist(train, idtrain, test, idtest, ub); } return v; }; return dfun; } } } else { return {"Lower bound is incompatible with "+conf.distance_name.value()}; } return {"Should not happen at " __FILE__ ": " STRINGIFY(__LINE__)}; } /** Special treatment for PrunedDTW - adapted from similarity search */ variant<string, distfun_t> do_PrunedDTW2018(const config& conf, size_t maxl, size_t minl, size_t w) { // Pre-check if (conf.dtw_lb!=NONE && minl!=maxl) { return {"Lower bound require same-length series"}; } switch (conf.dtw_lb) { case NONE: { vector<double> cumulative(maxl, 0); distfun_t dfun = [w, cumulative](TRAIN_TEST, double ub) { return pruneddtw2018(TRAIN, TEST, cumulative.data(), w, ub); }; return {dfun}; } case KEOGH: { // Captured state and pre allocation vector<tuple<vector<double>, vector<double>>> env_train; vector<double> cumulative(maxl, 0); vector<double> dist_to_env(maxl, 0); distfun_t dfun = [maxl, w, cumulative, dist_to_env, env_train](TRAIN_TEST, double ub) mutable { // Compute envelopes once if (env_train.empty()) { compute_envelopes(train, env_train, w); } // Lb Keogh with dist to env const auto&[up, lo] = env_train[idtrain]; double v = lb_Keogh_prunedDTW2018(TEST, up.data(), lo.data(), ub, dist_to_env.data()); if (v<ub) { // Cumulative cumulate_prunedDTW2018(dist_to_env.data(), cumulative.data(), maxl); v = pruneddtw2018(TRAIN, TEST, cumulative.data(), w, ub); } return v; }; return {dfun}; } // --- --- --- case KEOGH2: { // Captured state and pre allocation vector<tuple<vector<double>, vector<double>>> env_train; map<size_t, tuple<vector<double>, vector<double>>> env_test; vector<double> cumulative(maxl, 0); vector<double> dist_to_env1(maxl, 0); vector<double> dist_to_env2(maxl, 0); distfun_t dfun = [maxl, w, cumulative, dist_to_env1, dist_to_env2, env_train, env_test](TRAIN_TEST, double ub) mutable { // Compute envelopes once if (env_train.empty()) { compute_envelopes(train, env_train, w); } // Lb Keogh with dist to env const auto&[up, lo] = env_train[idtrain]; double v = lb_Keogh_prunedDTW2018(TEST, up.data(), lo.data(), ub, dist_to_env1.data()); double v1 = v; if (v1<ub) { // LB Keogh 2 const auto lq = test[idtest].length(); if (!contains(env_test, idtest)) { vector<double> upq(lq); vector<double> loq(lq); get_envelopes(TEST, upq.data(), loq.data(), w); env_test.emplace(idtest, std::tuple(std::move(upq), std::move(loq))); } const auto&[upq, loq] = env_test[idtest]; double v2 = lb_Keogh_prunedDTW2018(TRAIN, upq.data(), loq.data(), ub, dist_to_env2.data()); v = v2; // Distance if (v<ub) { // Cumulative: pick largest if (v1>v2) { cumulate_prunedDTW2018(dist_to_env1.data(), cumulative.data(), maxl); } else { cumulate_prunedDTW2018(dist_to_env2.data(), cumulative.data(), maxl); } v = pruneddtw2018(TRAIN, TEST, cumulative.data(), w, ub); } } return v; }; return {dfun}; } // --- --- --- case WEBB: { return "PrunedDTW2018 is not compatible with LB-Webb"; } } return {"Should not happen at " __FILE__ ": " STRINGIFY(__LINE__)}; } /** Generate a distance function based on the configuration and the maximum length of the series. * The max length is used to compute the actual window sized, which is specified by a ratio */ variant<string, distfun_t> get_distfun(const config& conf, size_t maxl, size_t minl) { distfun_t dfun; if (conf.distance_name=="dtw") { switch (conf.runmode) { case BASE: { dfun = [](TRAIN_TEST, [[maybe_unused]]double ub) { return dtw_base(TRAIN, TEST); }; break; } case BASE_EA: { dfun = [](TRAIN_TEST, double ub) { return dtw_base_ea(TRAIN, TEST, ub); }; break; } case PRU: { dfun = [](TRAIN_TEST, [[maybe_unused]]double ub) { return dtw<false>(TRAIN, TEST); }; break; } case PRU_LA: { dfun = [](TRAIN_TEST, [[maybe_unused]]double ub) { return dtw<true>(TRAIN, TEST); }; break; } case PRUNEDDTW: { size_t w = conf.cdtw_wratio*maxl; dfun = [w](TRAIN_TEST, [[maybe_unused]]double ub) { return pruneddtw(TRAIN, TEST, w); }; break; } case PRUNEDDTW2018: { size_t w = conf.cdtw_wratio*maxl; return do_PrunedDTW2018(conf, maxl, minl, w); } case EAP: { dfun = [](TRAIN_TEST, double ub) { return dtw<false>(TRAIN, TEST, ub); }; break; } case EAP_LA: { dfun = [](TRAIN_TEST, double ub) { return dtw<true>(TRAIN, TEST, ub); }; break; } default: { return {conf.distance_name.value()+" distance not compatible with "+to_string(conf.runmode)}; } } size_t w = conf.cdtw_wratio*maxl; return do_lb(std::move(dfun), conf, maxl, minl, w); } else if (conf.distance_name=="cdtw") { size_t w = conf.cdtw_wratio*maxl; switch (conf.runmode) { case BASE: { dfun = [w](TRAIN_TEST, [[maybe_unused]]double ub) { return cdtw_base(TRAIN, TEST, w); }; break; } case BASE_EA: { dfun = [w](TRAIN_TEST, double ub) { return cdtw_base_ea(TRAIN, TEST, w, ub); }; break; } case PRU: { dfun = [w](TRAIN_TEST, [[maybe_unused]]double ub) { return cdtw<false>(TRAIN, TEST, w); }; break; } case PRU_LA: { dfun = [w](TRAIN_TEST, [[maybe_unused]]double ub) { return cdtw<true>(TRAIN, TEST, w); }; break; } case PRUNEDDTW: { dfun = [w](TRAIN_TEST, [[maybe_unused]]double ub) { return pruneddtw(TRAIN, TEST, w); }; break; } case PRUNEDDTW2018: { return do_PrunedDTW2018(conf, maxl, minl, w); } case EAP: { dfun = [w](TRAIN_TEST, double ub) { return cdtw<false>(TRAIN, TEST, w, ub); }; break; } case EAP_LA: { dfun = [w](TRAIN_TEST, double ub) { return cdtw<true>(TRAIN, TEST, w, ub); }; break; } default: { return {conf.distance_name.value()+" distance not compatible with "+to_string(conf.runmode)}; } } return do_lb(std::move(dfun), conf, maxl, minl, w); } else if (conf.distance_name=="wdtw") { auto weights = generate_weights(conf.wdtw_g, maxl); switch (conf.runmode) { case BASE: { dfun = [weights](TRAIN_TEST, [[maybe_unused]]double ub) { return wdtw_base(TRAIN, TEST, weights.data()); }; break; } case BASE_EA: { dfun = [weights](TRAIN_TEST, double ub) { return wdtw_base_ea(TRAIN, TEST, weights.data(), ub); }; break; } case PRU: { dfun = [weights](TRAIN_TEST, [[maybe_unused]]double ub) { return wdtw<false>(TRAIN, TEST, weights.data()); }; break; } case PRU_LA: { dfun = [weights](TRAIN_TEST, [[maybe_unused]]double ub) { return wdtw<true>(TRAIN, TEST, weights.data()); }; break; } case EAP: { dfun = [weights](TRAIN_TEST, double ub) { return wdtw<false>(TRAIN, TEST, weights.data(), ub); }; break; } case EAP_LA: { dfun = [weights](TRAIN_TEST, double ub) { return wdtw<true>(TRAIN, TEST, weights.data(), ub); }; break; } default: { return {conf.distance_name.value()+" distance not compatible with "+to_string(conf.runmode)}; } } } else if (conf.distance_name=="sqed") { switch (conf.runmode) { case BASE: { dfun = [](TRAIN_TEST, [[maybe_unused]]double ub) { return elementwise(TRAIN, TEST); }; break; } case EAP: { dfun = [](TRAIN_TEST, double ub) { return elementwise<false>(TRAIN, TEST, ub); }; break; } case EAP_LA: { dfun = [](TRAIN_TEST, double ub) { return elementwise<true>(TRAIN, TEST, ub); }; break; } default: { return {conf.distance_name.value()+" distance not compatible with "+to_string(conf.runmode)}; } } } else if (conf.distance_name=="erp") { auto gv = conf.erp_gv; auto w = conf.erp_gv*maxl; switch (conf.runmode) { case BASE: { dfun = [gv, w](TRAIN_TEST, [[maybe_unused]]double ub) { return erp_base(TRAIN, TEST, gv, w); }; break; } case BASE_EA: { dfun = [gv, w](TRAIN_TEST, double ub) { return erp_base_ea(TRAIN, TEST, gv, w, ub); }; break; } case PRU: { dfun = [gv, w](TRAIN_TEST, [[maybe_unused]]double ub) { return erp<false>(TRAIN, TEST, gv, w); }; break; } case PRU_LA: { dfun = [gv, w](TRAIN_TEST, [[maybe_unused]]double ub) { return erp<true>(TRAIN, TEST, gv, w); }; break; } case EAP: { dfun = [gv, w](TRAIN_TEST, double ub) { return erp<false>(TRAIN, TEST, gv, w, ub); }; break; } case EAP_LA: { dfun = [gv, w](TRAIN_TEST, double ub) { return erp<true>(TRAIN, TEST, gv, w, ub); }; break;
c++
code
20,000
4,973
// Copyright (C) 2011-2020 Roki. Distributed under the MIT License #ifndef INCLUDED_SROOK_CONFIG_ARCH_DECALPHA_CORE_HPP #define INCLUDED_SROOK_CONFIG_ARCH_DECALPHA_CORE_HPP #if defined(__alpha__) || defined(__alpha) || defined(_M_ALPHA) # define SROOK_ARCH_IS_DECALPHA 1 # if defined(__alpha_ev4__) # define SROOK_ALPHA_EV4 __alpha_ev4__ # else # define SROOK_ALPHA_EV4 0 # endif # if defined(__alpha_ev5__) # define SROOK_ALPHA_EV5 __alpha_ev5__ # else # define SROOK_ALPHA_EV5 0 # endif # if defined(__alpha_ev6__) # define SROOK_ALPHA_EV6 __alpha_ev6__ # else # define SROOK_ALPHA_EV6 0 # endif #else # define SROOK_ARCH_IS_DECALPHA 0 # define SROOK_ALPHA_EV4 0 # define SROOK_ALPHA_EV5 0 # define SROOK_ALPHA_EV6 0 #endif #endif
c++
code
740
115
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // 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 "graphics/dgl.h" #include "console/consoleTypes.h" #include "gui/guiDefaultControlRender.h" #include "guiSceneObjectCtrl.h" #include "debug/profiler.h" // ----------------------------------------------------------------------------- IMPLEMENT_CONOBJECT(GuiSceneObjectCtrl); // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // Constructor. // ----------------------------------------------------------------------------- GuiSceneObjectCtrl::GuiSceneObjectCtrl(void) { // Reset Scene Object Name. mSceneObjectName = StringTable->EmptyString; // Default to no render margin mMargin = 0; mCaption = StringTable->EmptyString; mStateOn = false; mButtonType = ButtonTypeRadio; // Set-up private batcher. mBatchRenderer.setDebugStats( &mDebugStats ); mBatchRenderer.setStrictOrderMode( true, true ); mBatchRenderer.setBatchEnabled( false ); } // ----------------------------------------------------------------------------- // Persistent Fields. // ----------------------------------------------------------------------------- void GuiSceneObjectCtrl::initPersistFields() { // Call Parent. Parent::initPersistFields(); // Define Fields. addGroup("GuiSceneObjectCtrl"); addField("renderMargin", TypeS32, Offset(mMargin, GuiSceneObjectCtrl)); addField("sceneObject", TypeString, Offset(mSceneObjectName, GuiSceneObjectCtrl)); endGroup("GuiSceneObjectCtrl"); } // ----------------------------------------------------------------------------- // Wake! // ----------------------------------------------------------------------------- bool GuiSceneObjectCtrl::onWake() { // Call Parent. if (!Parent::onWake()) return false; if( mProfile->constructBitmapArray() >= 36 ) mHasTexture = true; else mHasTexture = false; // Activate. setActive(true); // All Okay. return true; } // ----------------------------------------------------------------------------- // Sleep! // ----------------------------------------------------------------------------- void GuiSceneObjectCtrl::onSleep() { Parent::onSleep(); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void GuiSceneObjectCtrl::inspectPostApply() { // Call Parent. Parent::inspectPostApply(); // Set the Scene Object. setSceneObject( mSceneObjectName ); } // ----------------------------------------------------------------------------- // Set Scene Object. // ----------------------------------------------------------------------------- ConsoleMethod( GuiSceneObjectCtrl, setSceneObject, void, 3, 3, "(string obj) Set the scene-object displayed in the control." "@param obj Either the object's ID or its name." "@return No return value.") { // Set Scene Object. object->setSceneObject( argv[2] ); } // Set Scene Object. void GuiSceneObjectCtrl::setSceneObject( const char* name ) { // Reset existing object. mSelectedSceneObject = NULL; // Get Scene Name. mSceneObjectName = StringTable->insert( name ? name : "" ); // Valid Scene Object Name? if ( *mSceneObjectName ) { // Fetch Scene Object. SceneObject* pSceneObject = dynamic_cast<SceneObject*>(Sim::findObject( name )); // Valid? if ( pSceneObject ) { // Yes, so set Scene Object. mSelectedSceneObject = pSceneObject; // The scene object needs to be integrated otherwise the render OOBB which this GUI control // relies upon will be undefined. This dependency needs resolving but I suspect it never will. DebugStats debugStats; mSelectedSceneObject->preIntegrate(0.0f, 0.0f, &debugStats ); } } else mSelectedSceneObject = NULL; // Do an update. setUpdate(); } ConsoleMethod( GuiSceneObjectCtrl, getSceneObject, const char*, 2,2, "() \n@return Returns displaying sceneobject id") { SceneObject *sceneObject = object->getSceneObject(); if( !sceneObject ) return ""; return sceneObject->getIdString(); } ConsoleMethod( GuiSceneObjectCtrl, setCaption, void, 3, 3, "(string caption) Sets the object caption to specified string.\n" "@return No return value.") { object->setCaption( argv[2] ); } void GuiSceneObjectCtrl::setCaption( const char* caption ) { if( caption != NULL ) mCaption = StringTable->insert( caption ); } // // // void GuiSceneObjectCtrl::onMouseUp(const GuiEvent &event) { if( mDepressed && ( event.mouseClickCount % 2 ) == 0 ) Con::executef( this, 2, "onDoubleClick" ); Parent::onMouseUp( event ); } void GuiSceneObjectCtrl::onMouseLeave( const GuiEvent &event ) { Con::executef( this, 2, "onMouseLeave" ); Parent::onMouseLeave( event ); } void GuiSceneObjectCtrl::onMouseEnter( const GuiEvent &event ) { Con::executef( this, 2, "onMouseEnter" ); Parent::onMouseEnter( event ); } void GuiSceneObjectCtrl::onMouseDragged( const GuiEvent &event ) { Con::executef( this, 2, "onMouseDragged" ); Parent::onMouseDragged( event ); } // ----------------------------------------------------------------------------- // Render any selected Scene Object. // ----------------------------------------------------------------------------- void GuiSceneObjectCtrl::onRender(Point2I offset, const RectI& updateRect) { PROFILE_SCOPE(guiT2DObjectCtrl_onRender); RectI ctrlRect( offset, mBounds.extent ); // Draw Background if( mProfile->mOpaque ) { if( mDepressed || mStateOn ) { if( mHasTexture ) renderSizableBitmapBordersFilled( ctrlRect, 3, mProfile ); else dglDrawRectFill( ctrlRect, mProfile->mFillColorHL ); } else if ( mMouseOver ) { if( mHasTexture ) renderSizableBitmapBordersFilled( ctrlRect, 2, mProfile ); else dglDrawRectFill( ctrlRect, mProfile->mFillColorHL ); } else { if( mHasTexture ) renderSizableBitmapBordersFilled( ctrlRect, 1, mProfile ); else dglDrawRectFill( ctrlRect, mProfile->mFillColor ); } } //// Render Border. //if( mProfile->mBorder || mStateOn ) // dglDrawRect(ctrlRect, mProfile->mBorderColor); // Valid Scene Object? if ( !mSelectedSceneObject.isNull() ) { RectI objRect = updateRect; objRect.inset( mMargin, mMargin ); RectI ctrlRectInset = ctrlRect; ctrlRectInset.inset( mMargin, mMargin); // Draw Canvas color for object if ( mProfile->mOpaque ) { if( mHasTexture ) renderSizableBitmapBordersFilled( objRect, 4, mProfile ); else dglDrawRectFill( objRect, mProfile->mFillColorNA ); } // Yes, so fetch object clip boundary. const b2Vec2* pClipBoundary = mSelectedSceneObject->getRenderOOBB(); // Calculate the GUI-Control Clip Boundary. const F32 xscale = (pClipBoundary[1].x - pClipBoundary[0].x) / ctrlRectInset.extent.x; const F32 yscale = (pClipBoundary[2].y - pClipBoundary[0].y) / ctrlRectInset.extent.y; F32 x1 = pClipBoundary[0].x + ( objRect.point.x - ctrlRectInset.point.x) * xscale; F32 x2 = pClipBoundary[1].x + ( objRect.point.x + objRect.extent.x - ctrlRectInset.extent.x - ctrlRectInset.point.x) * xscale; F32 y1 = pClipBoundary[0].y + ( objRect.point.y - ctrlRectInset.point.y) * yscale; F32 y2 = pClipBoundary[2].y + ( objRect.point.y + objRect.extent.y - ctrlRectInset.extent.y - ctrlRectInset.point.y) * yscale; Vector2 size = mSelectedSceneObject->getSize(); if (size.x > size.y) { S32 center = ctrlRectInset.point.y + (ctrlRectInset.extent.y / 2); // Save the base state of the objRect before transforming it S32 baseTop = objRect.point.y; S32 baseExtent = objRect.extent.y; S32 baseBottom = baseTop + baseExtent; // Transform the objRect extent by the aspect ratio objRect.extent.y = (S32)(ctrlRectInset.extent.y * (size.y / size.x)); // Save the transformed positions of the objRect before clipping S32 targetTop = (S32)(center - ((ctrlRectInset.extent.y * (size.y / size.x)) / 2)); S32 targetExtent = (S32)(objRect.extent.y); S32 targetBottom = (S32)(targetTop + objRect.extent.y); // Set the objRect position based on its aspect ratio objRect.point.y = (S32)(center - ((ctrlRectInset.extent.y * (size.y / size.x)) / 2)); // Reset the clipping bounds y1 = pClipBoundary[0].y; y2 = pClipBoundary[2].y; // If the object clips of the top or bottom, adjust the extent and clipping bounds accordingly if (baseTop > targetTop) { // Adjust the position and extent objRect.point.y = baseTop; objRect.extent.y = getMax(targetBottom - baseTop, 0); // Set the top clipping boundary F32 clipRatio = 1.0f - ((1.0f * objRect.extent.y)/targetExtent); y1 = pClipBoundary[0].y + (pClipBoundary[2].y - pClipBoundary[0].y)*(clipRatio); } if (baseBottom < targetBottom) { // Adjust the extent objRect.extent.y = getMax(baseBottom - targetTop, 0); // Set the bottom clipping boundary F32 clipRatio = 1.0f - ((1.0f * objRect.extent.y)/targetExtent); y2 = pClipBoundary[2].y - (pClipBoundary[2].y - pClipBoundary[0].y)*(clipRatio); } } else { S32 center = ctrlRectInset.point.x + (ctrlRectInset.extent.x / 2); // Save the base state of the objRect before transforming it S32 baseLeft = objRect.point.x; S32 baseExtent = objRect.extent.x; S32 baseRight = baseLeft + baseExtent; // Transform the objRect extent by the aspect ratio objRect.extent.x = (S32)(ctrlRectInset.extent.x * (size.x / size.y)); // Save the transformed positions of the objRect before clipping S32 targetLeft = (S32)(center - ((ctrlRectInset.extent.x * (size.x / size.y)) / 2)); S32 targetExtent = (S32)(objRect.extent.x); S32 targetRight = (S32)(targetLeft + objRect.extent.x); // Set the objRect position based on its aspect ratio objRect.point.x = (S32)(center - ((ctrlRectInset.extent.x * (size.x / size.y)) / 2)); // Reset the clipping bounds x1 = pClipBoundary[0].x; x2 = pClipBoundary[1].x; // If the object clips of the left or right, adjust the extent and clipping bounds accordingly if (baseLeft > targetLeft) { // Adjust the position and extent objRect.point.x = baseLeft; objRect.extent.x = getMax(targetRight - baseLeft, 0); // Set the left clipping boundary F32 clipRatio = 1.0f - ((1.0f * objRect.extent.x)/targetExtent); x1 = pClipBoundary[0].x + (pClipBoundary[1].x - pClipBoundary[0].x)*(clipRatio); } if (baseRight < targetRight) { // Adjust the extent objRect.extent.x = getMax(baseRight - targetLeft, 0); // Set the right clipping boundary F32 clipRatio = 1.0f - ((1.0f * objRect.extent.x)/targetExtent); x2 = pClipBoundary[1].x - (pClipBoundary[1].x - pClipBoundary[0].x)*(clipRatio); } } // Negate the y-clippingpoints to convert to positive-y-up coordinate system of the object y1 *= -1; y2 *= -1; // Setup new logical coordinate system. glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); RectI viewport; dglGetViewport(&viewport); if (x1 > x2) { F32 temp = x1; x1 = x2; x2 = temp; } if (y1 > y2) { F32 temp = y1; y1 = y2; y2 = temp; } // Setup Orthographic Projection for Object Area. #if defined(TORQUE_OS_IOS) || defined(TORQUE_OS_ANDROID) glOrthof( x1, x2, y1, y2, 0.0f, MAX_LAYERS_SUPPORTED ); #else glOrtho( x1, x2, y1, y2, 0.0f, MAX_LAYERS_SUPPORTED ); #endif // Setup new viewport. dglSetViewport(objRect); // Set ModelView. glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); // Enable Alpha Test. glEnable ( GL_ALPHA_TEST ); glAlphaFunc ( GL_GREATER, 0.0f ); // Calculate maximal clip bounds. RectF clipBounds( -x1,-y1, x2-x1, y2-y1 ); DebugStats debugStats; // Render Object in GUI-space. SceneRenderState guiSceneRenderState( clipBounds, clipBounds.centre(), 0.0f, MASK_ALL, MASK_ALL, Vector2::getOne(), &debugStats, this ); SceneRenderRequest guiSceneRenderRequest; guiSceneRenderRequest.set( mSelectedSceneObject, mSelectedSceneObject->getRenderPosition(), 0.0f ); mSelectedSceneObject->sceneRender( &guiSceneRenderState, &guiSceneRenderRequest, &mBatchRenderer ); // Restore Standard Settings. glDisable ( GL_DEPTH_TEST ); glDisable ( GL_ALPHA_TEST ); // Restore Matrices. glMatrixMode(GL_MODELVIEW); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); } else { // No Object so reset name. mSceneObjectName = NULL; } RectI captionRect = ctrlRect; captionRect.point.y += (captionRect.extent.y / 8); captionRect.inset(1, 1); dglSetBitmapModulation( ColorI(0,0,0,255) ); renderJustifiedText(captionRect.point, captionRect.extent, mCaption); captionRect.inset(1, 1); dglSetBitmapModulation( mProfile->mFontColor ); renderJustifiedText(captionRect.point, captionRect.extent, mCaption); // Render Child Controls. renderChildControls(offset, updateRect); }
c++
code
15,607
3,535
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017 The Phore developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/phore-config.h" #endif #include "init.h" #include "accumulators.h" #include "activemasternode.h" #include "addrman.h" #include "amount.h" #include "checkpoints.h" #include "compat/sanity.h" #include "key.h" #include "main.h" #include "masternode-budget.h" #include "masternode-payments.h" #include "masternodeconfig.h" #include "masternodeman.h" #include "miner.h" #include "net.h" #include "rpcserver.h" #include "script/standard.h" #include "spork.h" #include "sporkdb.h" #include "txdb.h" #include "torcontrol.h" #include "ui_interface.h" #include "util.h" #include "utilmoneystr.h" #include "validationinterface.h" #ifdef ENABLE_WALLET #include "db.h" #include "wallet.h" #include "walletdb.h" #include "accumulators.h" #endif #include <fstream> #include <stdint.h> #include <stdio.h> #ifndef WIN32 #include <signal.h> #endif #include <boost/algorithm/string/predicate.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/interprocess/sync/file_lock.hpp> #include <boost/thread.hpp> #include <openssl/crypto.h> #if ENABLE_ZMQ #include "zmq/zmqnotificationinterface.h" #endif using namespace boost; using namespace std; #ifdef ENABLE_WALLET CWallet* pwalletMain = NULL; int nWalletBackups = 10; #endif volatile bool fFeeEstimatesInitialized = false; volatile bool fRestartRequested = false; // true: restart false: shutdown extern std::list<uint256> listAccCheckpointsNoDB; #if ENABLE_ZMQ static CZMQNotificationInterface* pzmqNotificationInterface = NULL; #endif #ifdef WIN32 // Win32 LevelDB doesn't use filedescriptors, and the ones used for // accessing block files, don't count towards to fd_set size limit // anyway. #define MIN_CORE_FILEDESCRIPTORS 0 #else #define MIN_CORE_FILEDESCRIPTORS 150 #endif /** Used to pass flags to the Bind() function */ enum BindFlags { BF_NONE = 0, BF_EXPLICIT = (1U << 0), BF_REPORT_ERROR = (1U << 1), BF_WHITELIST = (1U << 2), }; static const char* FEE_ESTIMATES_FILENAME = "fee_estimates.dat"; CClientUIInterface uiInterface; ////////////////////////////////////////////////////////////////////////////// // // Shutdown // // // Thread management and startup/shutdown: // // The network-processing threads are all part of a thread group // created by AppInit() or the Qt main() function. // // A clean exit happens when StartShutdown() or the SIGTERM // signal handler sets fRequestShutdown, which triggers // the DetectShutdownThread(), which interrupts the main thread group. // DetectShutdownThread() then exits, which causes AppInit() to // continue (it .joins the shutdown thread). // Shutdown() is then // called to clean up database connections, and stop other // threads that should only be stopped after the main network-processing // threads have exited. // // Note that if running -daemon the parent process returns from AppInit2 // before adding any threads to the threadGroup, so .join_all() returns // immediately and the parent exits from main(). // // Shutdown for Qt is very similar, only it uses a QTimer to detect // fRequestShutdown getting set, and then does the normal Qt // shutdown thing. // volatile bool fRequestShutdown = false; void StartShutdown() { fRequestShutdown = true; } bool ShutdownRequested() { return fRequestShutdown || fRestartRequested; } class CCoinsViewErrorCatcher : public CCoinsViewBacked { public: CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {} bool GetCoins(const uint256& txid, CCoins& coins) const { try { return CCoinsViewBacked::GetCoins(txid, coins); } catch (const std::runtime_error& e) { uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR); LogPrintf("Error reading from database: %s\n", e.what()); // Starting the shutdown sequence and returning false to the caller would be // interpreted as 'entry not found' (as opposed to unable to read data), and // could lead to invalid interpration. Just exit immediately, as we can't // continue anyway, and all writes should be atomic. abort(); } } // Writes do not need similar protection, as failure to write is handled by the caller. }; static CCoinsViewDB* pcoinsdbview = NULL; static CCoinsViewErrorCatcher* pcoinscatcher = NULL; /** Preparing steps before shutting down or restarting the wallet */ void PrepareShutdown() { fRequestShutdown = true; // Needed when we shutdown the wallet fRestartRequested = true; // Needed when we restart the wallet LogPrintf("%s: In progress...\n", __func__); static CCriticalSection cs_Shutdown; TRY_LOCK(cs_Shutdown, lockShutdown); if (!lockShutdown) return; /// Note: Shutdown() must be able to handle cases in which AppInit2() failed part of the way, /// for example if the data directory was found to be locked. /// Be sure that anything that writes files or flushes caches only does this if the respective /// module was initialized. RenameThread("phore-shutoff"); mempool.AddTransactionsUpdated(1); StopRPCThreads(); #ifdef ENABLE_WALLET if (pwalletMain) bitdb.Flush(false); GenerateBitcoins(false, NULL, 0); #endif StopNode(); InterruptTorControl(); StopTorControl(); DumpMasternodes(); DumpBudgets(); DumpMasternodePayments(); UnregisterNodeSignals(GetNodeSignals()); if (fFeeEstimatesInitialized) { boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME; CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION); if (!est_fileout.IsNull()) mempool.WriteFeeEstimates(est_fileout); else LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string()); fFeeEstimatesInitialized = false; } { LOCK(cs_main); if (pcoinsTip != NULL) { FlushStateToDisk(); //record that client took the proper shutdown procedure pblocktree->WriteFlag("shutdown", true); } delete pcoinsTip; pcoinsTip = NULL; delete pcoinscatcher; pcoinscatcher = NULL; delete pcoinsdbview; pcoinsdbview = NULL; delete pblocktree; pblocktree = NULL; delete zerocoinDB; zerocoinDB = NULL; delete pSporkDB; pSporkDB = NULL; } #ifdef ENABLE_WALLET if (pwalletMain) bitdb.Flush(true); #endif #if ENABLE_ZMQ if (pzmqNotificationInterface) { UnregisterValidationInterface(pzmqNotificationInterface); delete pzmqNotificationInterface; pzmqNotificationInterface = NULL; } #endif #ifndef WIN32 boost::filesystem::remove(GetPidFile()); #endif UnregisterAllValidationInterfaces(); } /** * Shutdown is split into 2 parts: * Part 1: shut down everything but the main wallet instance (done in PrepareShutdown() ) * Part 2: delete wallet instance * * In case of a restart PrepareShutdown() was already called before, but this method here gets * called implicitly when the parent object is deleted. In this case we have to skip the * PrepareShutdown() part because it was already executed and just delete the wallet instance. */ void Shutdown() { // Shutdown part 1: prepare shutdown if (!fRestartRequested) { PrepareShutdown(); } // Shutdown part 2: delete wallet instance #ifdef ENABLE_WALLET delete pwalletMain; pwalletMain = NULL; #endif LogPrintf("%s: done\n", __func__); } /** * Signal handlers are very limited in what they are allowed to do, so: */ void HandleSIGTERM(int) { fRequestShutdown = true; } void HandleSIGHUP(int) { fReopenDebugLog = true; } bool static InitError(const std::string& str) { uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR); return false; } bool static InitWarning(const std::string& str) { uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING); return true; } bool static Bind(const CService& addr, unsigned int flags) { if (!(flags & BF_EXPLICIT) && IsLimited(addr)) return false; std::string strError; if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) { if (flags & BF_REPORT_ERROR) return InitError(strError); return false; } return true; } std::string HelpMessage(HelpMessageMode mode) { // When adding new options to the categories, please keep and ensure alphabetical ordering. string strUsage = HelpMessageGroup(_("Options:")); strUsage += HelpMessageOpt("-?", _("This help message")); strUsage += HelpMessageOpt("-version", _("Print version and exit")); strUsage += HelpMessageOpt("-alertnotify=<cmd>", _("Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)")); strUsage += HelpMessageOpt("-alerts", strprintf(_("Receive and display P2P network alerts (default: %u)"), DEFAULT_ALERTS)); strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)")); strUsage += HelpMessageOpt("-mempoolnotify=<cmd>", _("Execute command when a new transaction is accepted to the mempool (%s in cmd is replaced by transaction hash)")); strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), 500)); strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), "phore.conf")); if (mode == HMM_BITCOIND) { #if !defined(WIN32) strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands")); #endif } strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory")); strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache)); strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file") + " " + _("on startup")); strUsage += HelpMessageOpt("-maxreorg=<n>", strprintf(_("Set the Maximum reorg depth (default: %u)"), Params(CBaseChainParams::MAIN).MaxReorganizationDepth())); strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS)); strUsage += HelpMessageOpt("-par=<n>", strprintf(_("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)"), -(int)boost::thread::hardware_concurrency(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS)); #ifndef WIN32 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), "phored.pid")); #endif strUsage += HelpMessageOpt("-reindex", _("Rebuild block chain index from current blk000??.dat files") + " " + _("on startup")); strUsage += HelpMessageOpt("-reindexaccumulators", _("Reindex the accumulator database") + " " + _("on startup")); strUsage += HelpMessageOpt("-reindexmoneysupply", _("Reindex the PHR and zPHR money supply statistics") + " " + _("on startup")); strUsage += HelpMessageOpt("-resync", _("Delete blockchain folders and resync from scratch") + " " + _("on startup")); #if !defined(WIN32) strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)")); #endif strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), 0)); strUsage += HelpMessageOpt("-addrindex", strprintf(_("Maintain a full address index, used by the searchrawtransactions rpc call (default: %u)"), 0)); strUsage += HelpMessageOpt("-forcestart", _("Attempt to force blockchain corruption recovery") + " " + _("on startup")); strUsage += HelpMessageGroup(_("Connection options:")); strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open")); strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), 100)); strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), 86400)); strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6")); strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s)")); strUsage += HelpMessageOpt("-discover", _("Discover own IP address (default: 1 when listening and no -externalip)")); strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + _("(default: 1)")); strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)")); strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address")); strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), 0)); strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)")); strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION)); strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), 125)); strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), 5000)); strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), 1000)); strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy")); strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)")); strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), 1)); strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS)); strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), 11771, 11773)); strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy")); strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), 1)); strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect")); strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT)); strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL)); strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)")); #ifdef USE_UPNP #if USE_UPNP strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening)")); #else strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0)); #endif #endif strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6")); strUsage += HelpMessageOpt("-whitelist=<netmask>", _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") + " " + _("Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway")); #ifdef ENABLE_WALLET strUsage += HelpMessageGroup(_("Wallet options:")); strUsage += HelpMessageOpt("-createwalletbackups=<n>", _("Number of automatic wallet backups (default: 10)")); strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls")); strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), 100)); if (GetBoolArg("-help-debug", false)) strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in PHR/Kb) smaller than this are considered zero fee for transaction creation (default: %s)"), FormatMoney(CWallet::minTxFee.GetFeePerK()))); strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in PHR/kB) to add to transactions you send (default: %s)"), FormatMoney(payTxFee.GetFeePerK()))); strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions") + " " + _("on startup")); strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup")); strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), 0)); strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), 1)); strUsage += HelpMessageOpt("-disablesystemnotifications", strprintf(_("Disable OS notifications for incoming transactions (default: %u)"), 0)); strUsage += HelpMessageOpt("-txconfirmtarget=<n>", strprintf(_("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)"), 1)); strUsage += HelpMessageOpt("-maxtxfee=<amt>", strprintf(_("Maximum total fees to use in a single wallet transaction, setting too low may abort large transactions (default: %s)"), FormatMoney(maxTxFee))); strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format") + " " + _("on startup")); strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), "wallet.dat")); strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)")); if (mode == HMM_BITCOIN_QT) strUsage += HelpMessageOpt("-windowtitle=<name>", _("Wallet window title")); strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") + " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)")); #endif #if ENABLE_ZMQ strUsage += HelpMessageGroup(_("ZeroMQ notification options:")); strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>")); strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>")); strUsage += HelpMessageOpt("-zmqpubhashtxlock=<address>", _("Enable publish hash transaction (locked via SwiftX) in <address>")); strUsage += HelpMess
c++
code
20,000
4,561
#include<iostream> #include<vector> using namespace std; void dfs(vector<vector<char>>& grid, vector<vector<bool>>& visited, int i, int j){ if(i < 0||j < 0 || i >= grid.size() || j >= grid.size() || grid[i][j] != '1' || visited[i][j]) return; visited[i][j] = true; dfs(grid, visited, i - 1, j); dfs(grid, visited, i + 1, j); dfs(grid, visited, i, j - 1); dfs(grid, visited, i, j + 1); } int numIsland(vector<vector<char>> & grid){ if (grid.empty()) return 0; int m = grid.size(), n = grid[0].size(), res = 0; vector<vector<bool>>visited(m, vector<bool>(n, false)); for(int i = 0;i < m;i++){ for(int j = 0;j < n;j++){ if(grid[i][j] == '1' && !visited[i][j]){ dfs(grid, visited, i, j); res++; } } } return res; } int main(){ vector<vector<char>> res ={{'1','1','1','1','0'}, {'1','1','0','1','0'}, {'1','1','0','0','0'}, {'0','0','0','0','0'}}; cout<<numIsland(res)<<endl; return 0; }
c++
code
1,125
433
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include <mrpt/comms/CServerTCPSocket.h> #include <mrpt/comms/CClientTCPSocket.h> #include <mrpt/serialization/CMessage.h> #include <mrpt/poses/CPose3D.h> #include <cstdio> // printf() #include <thread> #include <chrono> bool sockets_test_passed_ok = false; // Test payload: const mrpt::poses::CPose3D p_tx(1.0, 2.0, 3.0, 0.2, 0.4, 0.6); using mrpt::serialization::CMessage; void thread_server() { using namespace mrpt::comms; using namespace std; try { #ifdef SOCKET_TEST_VERBOSE printf("[Server] Started\n"); #endif CServerTCPSocket server( 15000, "127.0.0.1", 10, #ifdef SOCKET_TEST_VERBOSE mrpt::system::LVL_DEBUG #else mrpt::system::LVL_ERROR #endif ); std::unique_ptr<CClientTCPSocket> client = server.accept(2000); if (client) { #ifdef SOCKET_TEST_VERBOSE printf("[Server] Connection accepted\n"); #endif // Send a message with the payload: CMessage msg; msg.type = 0x10; msg.serializeObject(&p_tx); client->sendMessage(msg); std::this_thread::sleep_for(50ms); } #ifdef SOCKET_TEST_VERBOSE printf("[Server] Finish\n"); #endif } catch (std::exception& e) { cerr << e.what() << endl; } catch (...) { printf("[thread_server] Runtime error!\n"); } } void thread_client() { using namespace mrpt::comms; using namespace std; try { CClientTCPSocket sock; #ifdef SOCKET_TEST_VERBOSE printf("[Client] Connecting\n"); #endif sock.connect("127.0.0.1", 15000); #ifdef SOCKET_TEST_VERBOSE printf("[Client] Connected. Waiting for a message...\n"); #endif // cout << "pending: " << sock.getReadPendingBytes() << endl; // std::this_thread::sleep_for(4000ms); // cout << "pending: " << sock.getReadPendingBytes() << endl; CMessage msg; bool ok = sock.receiveMessage(msg, 2000, 2000); if (!ok) { printf("[Client] Error receiving message!!\n"); } else { #ifdef SOCKET_TEST_VERBOSE printf("[Client] Message received OK!:\n"); printf(" MSG Type: %i\n", msg.type); printf( " MSG Length: %u bytes\n", (unsigned int)msg.content.size()); printf("[Client] Parsing payload...\n"); #endif mrpt::poses::CPose3D p_rx; msg.deserializeIntoExistingObject(&p_rx); #ifdef SOCKET_TEST_VERBOSE printf("[Client] Received payload: %s\n", p_rx.asString().c_str()); printf("[Client] tx payload: %s\n", p_tx.asString().c_str()); printf("[Client] Done!!\n"); #endif sockets_test_passed_ok = (p_rx == p_tx); } #ifdef SOCKET_TEST_VERBOSE printf("[Client] Finish\n"); #endif } catch (std::exception& e) { cerr << e.what() << endl; } catch (...) { cerr << "[thread_client] Runtime error!" << endl; ; } } // ------------------------------------------------------ // SocketsTest // ------------------------------------------------------ void SocketsTest() { using namespace std::chrono_literals; std::thread(thread_server).detach(); std::this_thread::sleep_for(100ms); std::thread(thread_client).detach(); std::this_thread::sleep_for(1000ms); }
c++
code
3,615
937
// Copyright 2020 Erik Kouters (Falcons) // SPDX-License-Identifier: Apache-2.0 /* * cRTDBInputAdapter.cpp * * Created on: Dec 27, 2018 * Author: Erik Kouters */ #include "tracing.hpp" #include "int/motors/cRTDBInputAdapter.hpp" cRTDBInputAdapter::cRTDBInputAdapter(PeripheralsInterfaceData& piData) : _piData(piData) { TRACE(">"); _myRobotId = getRobotNumber(); _rtdb = RtDB2Store::getInstance().getRtDB2(_myRobotId); TRACE("<"); } cRTDBInputAdapter::~cRTDBInputAdapter() { } void cRTDBInputAdapter::getMotorVelocitySetpoint() { TRACE_FUNCTION(""); T_MOTOR_VELOCITY_SETPOINT motorVelSetpoint; int ageMs = 0; int r = _rtdb->get(MOTOR_VELOCITY_SETPOINT, &motorVelSetpoint, ageMs, _myRobotId); int watchDogTimeoutMs = 150; // we need watchdog behavior in case any process breaks the execution architecture stream // motor velocity setpoint would freeze in that case, so we should to not relay it to motors, better to hit the brakes then! piVelAcc vel; vel.m1_vel = 0.0; vel.m2_vel = 0.0; vel.m3_vel = 0.0; if ((r == RTDB2_SUCCESS) && (ageMs < watchDogTimeoutMs)) { vel.m1_vel = motorVelSetpoint.m1; vel.m2_vel = motorVelSetpoint.m2; vel.m3_vel = motorVelSetpoint.m3; } _piData.setVelocityInput(vel); } void cRTDBInputAdapter::getBallHandlersMotorSetpoint() { TRACE_FUNCTION(""); T_BALLHANDLERS_MOTOR_SETPOINT ballHandlersMotorSetpoint; int ageMs = 0; int r = _rtdb->get(BALLHANDLERS_MOTOR_SETPOINT, &ballHandlersMotorSetpoint, ageMs, _myRobotId); if (r == RTDB2_SUCCESS) { // BH Enabled / Disabled BallhandlerSettings settings = _piData.getBallhandlerSettings(); if (ballHandlersMotorSetpoint.enabled) { settings.controlMode = BallhandlerBoardControlMode::BALLHANDLER_CONTROL_MODE_ON; } else { settings.controlMode = BallhandlerBoardControlMode::BALLHANDLER_CONTROL_MODE_OFF; } _piData.setBallhandlerSettings(settings); // Angle and Velocity Setpoints BallhandlerSetpoints setpoints; setpoints.angleLeft = ballHandlersMotorSetpoint.bhMotorData.angleLeft; setpoints.angleRight = ballHandlersMotorSetpoint.bhMotorData.angleRight; setpoints.velocityLeft = ballHandlersMotorSetpoint.bhMotorData.velocityLeft; setpoints.velocityRight = ballHandlersMotorSetpoint.bhMotorData.velocityRight; _piData.setBallhandlerSetpoints(setpoints); } }
c++
code
2,537
413
#include "rdocview.h" #include <QPainter> #include <QPaintEvent> #include <QKeyEvent> #include <QUrl> #include <QSettings> RDocView::RDocView(QWidget *parent) : QWidget(parent), _pageIndex(0), _pageNumberEntry(0) { setFocusPolicy(Qt::StrongFocus); } RDocView::~RDocView() {} static void drawGoToDialog(QPainter &p, int number, const QRect &boxRect) { QFontMetrics metrics(p.font()); const int pad = 8; const int lineHeight = metrics.lineSpacing(); const QString prompt("Go to page:"); const int promptWidth = metrics.width(prompt); const QPoint center = boxRect.center(); p.save(); p.setBrush(QBrush(QColor(0xFF, 0xFF, 0xFF, 0xAA))); p.drawRoundedRect(boxRect, 10, 10); p.drawText(center.x() - (promptWidth / 2), center.y(), prompt); QString entry = QString("%1_").arg(number); p.drawText(boxRect.left() + pad, center.y() + lineHeight, entry); p.restore(); } void RDocView::paintEvent(QPaintEvent *event) { renderPage(_pageIndex); if (_pageNumberEntry > 0) { QPainter p(this); drawGoToDialog(p, _pageNumberEntry, _boxRect); } } void RDocView::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Up: pageUp(); return; case Qt::Key_Down: pageDown(); return; case Qt::Key_Back: if (_pageNumberEntry > 0) { if (event->modifiers() & Qt::AltModifier) { _pageNumberEntry = 0; } else { _pageNumberEntry /= 10; } update(_boxRect.adjusted(0,0,1,1)); return; } break; case Qt::Key_Return: if (_pageNumberEntry > 0) { goToPage(_pageNumberEntry - 1); } break; case Qt::Key_Plus: zoomIn(); break; case Qt::Key_Minus: zoomOut(); break; } if (event->key() >= Qt::Key_0 && event->key() <= Qt::Key_9) { _pageNumberEntry = _pageNumberEntry * 10 + (event->key() - Qt::Key_0); update(_boxRect.adjusted(0,0,1,1)); return; } QWidget::keyPressEvent(event); } void RDocView::resizeEvent(QResizeEvent *event) { QWidget::resizeEvent(event); QRectF pageRect(0, 0, width(), height()); QPoint center = pageRect.center().toPoint(); QFontMetrics metrics(font()); const int pad = 8; const int lineHeight = metrics.lineSpacing(); const int boxHeight = (lineHeight + pad) * 2; const QString prompt("Go to page:"); const int promptWidth = metrics.width(prompt); const int boxWidth = promptWidth + pad * 2; _boxRect = QRect( center.x() - (boxWidth / 2), center.y() - (boxHeight / 2), boxWidth, boxHeight ); } void RDocView::goToPage(int page) { _pageNumberEntry = 0; if (page != _pageIndex) { _pageIndex = qBound(0, page, pageCount() - 1); emit pageChanged(_pageIndex); update(); QSettings s("runcible", "viewer"); s.setValue("lastpos/" + _docBase.toString(), _pageIndex); } } void RDocView::pageUp() { goToPage(_pageIndex - 1); } void RDocView::pageDown() { goToPage(_pageIndex + 1); } void RDocView::reset() { _pageIndex = 0; _pageNumberEntry = 0; } int RDocView::pageIndex() { return _pageIndex; } void RDocView::zoomIn() { } void RDocView::zoomOut() { } void RDocView::contentsChanged(const QUrl &docBase) { _docBase = docBase; emit pageCountChanged(pageCount()); QSettings s("runcible", "viewer"); int page = s.value("lastpos/" + docBase.toString(), 0).toInt(); if (page != 0) { goToPage(page); } else { update(); } }
c++
code
3,472
919
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "modeling_tool.h" #include <chrono> #include <iostream> #include <stdexcept> #include "google/cloud/spanner/client.h" namespace spanner = ::google::cloud::spanner; static const std::int64_t BATCHSIZE = 1000; // mutations per commit int main(int argc, char* argv[]) { if(argc < 4) { std::cerr << "Usage 1: " << argv[0] << " project-id instance-id database-id\n"; std::cerr << "Usage 2: " << argv[0] << " project-id instance-id database-id --dry-run \n"; return 1; } bool dryRun = false; if(argc == 5) dryRun = true; spanner::Client readClient( spanner::MakeConnection(spanner::Database(argv[1], argv[2], argv[3]))); spanner::Client writeClient( spanner::MakeConnection(spanner::Database(argv[1], argv[2], argv[3]))); auto start = std::chrono::high_resolution_clock::now(); const auto& updateResult = modeling_tool::batchUpdateData(readClient, writeClient, BATCHSIZE, dryRun); if(!updateResult) { std::cerr << "Update error: " << updateResult.status().message() << "\n"; return 1; } auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop-start); // execution time std::cout << "Time taken: " << duration.count() << " milliseconds" << std::endl; // update stats std::cout << "Total records read : " << updateResult.value().first << std::endl; if(dryRun) { std::cout << "Total records that need to be updated : " << updateResult.value().second << std::endl; } else { std::cout << "Total updated records : " << updateResult.value().second << std::endl; } return 0; }
c++
code
2,286
576
/******************************************************************************* * Copyright 2019-2020 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef CPU_X64_JIT_UNI_BINARY_HPP #define CPU_X64_JIT_UNI_BINARY_HPP #include <assert.h> #include "common/c_types_map.hpp" #include "common/primitive.hpp" #include "common/type_helpers.hpp" #include "common/utils.hpp" #include "cpu/cpu_eltwise_pd.hpp" #include "cpu/x64/cpu_isa_traits.hpp" #include "cpu/cpu_binary_pd.hpp" namespace dnnl { namespace impl { namespace cpu { namespace x64 { struct binary_kernel_t; template <data_type_t src_type> struct jit_uni_binary_t : public primitive_t { struct pd_t : public cpu_binary_pd_t { using cpu_binary_pd_t::cpu_binary_pd_t; DECLARE_COMMON_PD_T("jit:uni", jit_uni_binary_t); status_t init(engine_t *engine) { using namespace data_type; using sm = primitive_attr_t::skip_mask_t; memory_desc_wrapper dst_md_(dst_md()); const auto &po = attr()->post_ops_; int elt_idx = po.find(primitive_kind::eltwise); bool ok = mayiuse(avx2) && IMPLICATION(src_type == bf16, mayiuse(avx512_core)) && utils::everyone_is(src_type, src_md(0)->data_type, src_md(1)->data_type) && set_default_params() == status::success && !has_zero_dim_memory() && memory_desc_wrapper(src_md(0)) == memory_desc_wrapper(dst_md(0)) && is_applicable() && attr()->has_default_values(sm::post_ops) && attr_post_ops_ok() && (elt_idx == -1 || IMPLICATION(!dst_md_.is_dense(), cpu_eltwise_fwd_pd_t:: eltwise_preserves_zero( po.entry_[elt_idx] .eltwise))); if (!ok) return status::unimplemented; return status::success; } private: bool is_applicable() { const memory_desc_wrapper src0_d(src_md(0)); const memory_desc_wrapper src1_d(src_md(1)); const memory_desc_wrapper dst_d(dst_md()); // check density first to avoid same non-dense src0 and src1 to pass // the next check bool ok = src0_d.is_dense(true) && src1_d.is_dense(true) && dst_d.is_dense(true); if (!ok) return false; // full tensor operation if (src0_d == src1_d) return true; // broadcast operation const auto ndims = src0_d.ndims(); ok = ndims >= 2; // supported case: NxCxDxHxW:{NxCx1x1x1,1xCx1x1x1,1x1x1x1x1} const auto &bcast_dims = broadcast_dims(); ok = ok && IMPLICATION(bcast_dims[0] == 0, bcast_dims[1] == 0); for (int d = 2; d < ndims; ++d) ok = ok && bcast_dims[d] == 1; if (!ok) return false; if (src0_d.is_plain() && src1_d.is_plain()) { const auto &bd0 = src0_d.blocking_desc(); const auto &bd1 = src1_d.blocking_desc(); return bd0.strides[0] >= bd0.strides[1] && IMPLICATION(bd0.strides[1] > 1, bd0.strides[1] >= bd0.strides[2]) && bd1.strides[0] >= bd1.strides[1]; } const bool point_bcast = src1_d.nelems() == 1; // check blocking_desc consistency auto valid_bd = [&](const memory_desc_wrapper &mdw) { int blksize = 8; if (mayiuse(avx512_core)) blksize = 16; const auto &bd = mdw.blocking_desc(); bool point_bcast_is_ok = true; // this is zero pad guard; the problem appears for blocked // formats when last C block has tails and `add` operation does // not preserve zero in padded area. To be considered when // implementing binary injector. if (point_bcast) point_bcast_is_ok = src0_d.dims()[1] % blksize == 0; return bd.inner_nblks == 1 && bd.inner_blks[0] == blksize && bd.inner_idxs[0] == 1 && point_bcast_is_ok; }; return valid_bd(src0_d) && valid_bd(src1_d); } }; jit_uni_binary_t(const pd_t *apd); ~jit_uni_binary_t(); status_t execute(const exec_ctx_t &ctx) const override; private: const pd_t *pd() const { return (const pd_t *)primitive_t::pd().get(); } std::unique_ptr<binary_kernel_t> kernel_; }; } // namespace x64 } // namespace cpu } // namespace impl } // namespace dnnl #endif // vim: et ts=4 sw=4 cindent cino+=l0,\:4,N-s
c++
code
5,584
1,143
#pragma once #include <Flow/Implementation/Constants.hpp> namespace Emergence::Flow { /// \brief Flow uses bitsets to optimize resource usage overlap checks. /// Therefore we need to specify maximum count of resources. static constexpr std::size_t MAX_RESOURCES = Implementation::MAX_RESOURCES; /// \brief Flow uses bitsets to optimize node reachability calculations and checking. /// Therefore we need to specify maximum count of nodes. Node is a task or checkpoint. static constexpr std::size_t MAX_GRAPH_NODES = Implementation::MAX_GRAPH_NODES; } // namespace Emergence::Flow
c++
code
595
100
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/cloudsearch/model/OptionState.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace CloudSearch { namespace Model { namespace OptionStateMapper { static const int RequiresIndexDocuments_HASH = HashingUtils::HashString("RequiresIndexDocuments"); static const int Processing_HASH = HashingUtils::HashString("Processing"); static const int Active_HASH = HashingUtils::HashString("Active"); static const int FailedToValidate_HASH = HashingUtils::HashString("FailedToValidate"); OptionState GetOptionStateForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == RequiresIndexDocuments_HASH) { return OptionState::RequiresIndexDocuments; } else if (hashCode == Processing_HASH) { return OptionState::Processing; } else if (hashCode == Active_HASH) { return OptionState::Active; } else if (hashCode == FailedToValidate_HASH) { return OptionState::FailedToValidate; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<OptionState>(hashCode); } return OptionState::NOT_SET; } Aws::String GetNameForOptionState(OptionState enumValue) { switch(enumValue) { case OptionState::RequiresIndexDocuments: return "RequiresIndexDocuments"; case OptionState::Processing: return "Processing"; case OptionState::Active: return "Active"; case OptionState::FailedToValidate: return "FailedToValidate"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return ""; } } } // namespace OptionStateMapper } // namespace Model } // namespace CloudSearch } // namespace Aws
c++
code
3,051
466
//================================================================================================= /*! // \file src/mathtest/dvecdvecinner/VHaVDb.cpp // \brief Source file for the VHaVDb dense vector/dense vector inner product math test // // Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. 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 names of the Blaze development group 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. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/DynamicVector.h> #include <blaze/math/HybridVector.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/dvecdvecinner/OperationTest.h> #include <blazetest/system/MathTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'VHaVDb'..." << std::endl; using blazetest::mathtest::TypeA; using blazetest::mathtest::TypeB; try { // Vector type definitions using VHa = blaze::HybridVector<TypeA,128UL>; using VDb = blaze::DynamicVector<TypeB>; // Creator type definitions using CVHa = blazetest::Creator<VHa>; using CVDb = blazetest::Creator<VDb>; // Running tests with small vectors for( size_t i=0UL; i<=6UL; ++i ) { RUN_DVECDVECINNER_OPERATION_TEST( CVHa( i ), CVDb( i ) ); } // Running tests with large vectors RUN_DVECDVECINNER_OPERATION_TEST( CVHa( 127UL ), CVDb( 127UL ) ); RUN_DVECDVECINNER_OPERATION_TEST( CVHa( 128UL ), CVDb( 128UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dense vector/dense vector inner product:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
c++
code
4,031
1,009
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #include "precomp.h" #include <Intsafe.h> #include "Shlwapi.h" #include "telemetry.hpp" #include <ctime> #include "history.h" #include "../interactivity/inc/ServiceLocator.hpp" TRACELOGGING_DEFINE_PROVIDER(g_hConhostV2EventTraceProvider, "Microsoft.Windows.Console.Host", // {fe1ff234-1f09-50a8-d38d-c44fab43e818} (0xfe1ff234, 0x1f09, 0x50a8, 0xd3, 0x8d, 0xc4, 0x4f, 0xab, 0x43, 0xe8, 0x18), TraceLoggingOptionMicrosoftTelemetry()); #pragma warning(push) // Disable 4351 so we can initialize the arrays to 0 without a warning. #pragma warning(disable : 4351) Telemetry::Telemetry() : _fpFindStringLengthAverage(0), _fpDirectionDownAverage(0), _fpMatchCaseAverage(0), _uiFindNextClickedTotal(0), _uiColorSelectionUsed(0), _tStartedAt(0), _wchProcessFileNames(), // Start at position 1, since the first 2 bytes contain the number of strings. _iProcessFileNamesNext(1), _iProcessConnectedCurrently(SIZE_MAX), _rgiProcessFileNameIndex(), _rguiProcessFileNamesCount(), _rgiAlphabeticalIndex(), _rguiProcessFileNamesCodesCount(), _rguiProcessFileNamesFailedCodesCount(), _rguiProcessFileNamesFailedOutsideCodesCount(), _rguiTimesApiUsed(), _rguiTimesApiUsedAnsi(), _uiNumberProcessFileNames(0), _fBashUsed(false), _fKeyboardTextEditingUsed(false), _fKeyboardTextSelectionUsed(false), _fUserInteractiveForTelemetry(false), _fCtrlPgUpPgDnUsed(false), _uiCtrlShiftCProcUsed(0), _uiCtrlShiftCRawUsed(0), _uiCtrlShiftVProcUsed(0), _uiCtrlShiftVRawUsed(0), _uiQuickEditCopyProcUsed(0), _uiQuickEditCopyRawUsed(0), _uiQuickEditPasteProcUsed(0), _uiQuickEditPasteRawUsed(0) { time(&_tStartedAt); TraceLoggingRegister(g_hConhostV2EventTraceProvider); TraceLoggingWriteStart(_activity, "ActivityStart"); // initialize wil tracelogging wil::SetResultLoggingCallback(&Tracing::TraceFailure); } #pragma warning(pop) Telemetry::~Telemetry() { TraceLoggingWriteStop(_activity, "ActivityStop"); TraceLoggingUnregister(g_hConhostV2EventTraceProvider); } void Telemetry::SetUserInteractive() { _fUserInteractiveForTelemetry = true; } void Telemetry::SetCtrlPgUpPgDnUsed() { _fCtrlPgUpPgDnUsed = true; SetUserInteractive(); } void Telemetry::LogCtrlShiftCProcUsed() { _uiCtrlShiftCProcUsed++; SetUserInteractive(); } void Telemetry::LogCtrlShiftCRawUsed() { _uiCtrlShiftCRawUsed++; SetUserInteractive(); } void Telemetry::LogCtrlShiftVProcUsed() { _uiCtrlShiftVProcUsed++; SetUserInteractive(); } void Telemetry::LogCtrlShiftVRawUsed() { _uiCtrlShiftVRawUsed++; SetUserInteractive(); } void Telemetry::LogQuickEditCopyProcUsed() { _uiQuickEditCopyProcUsed++; SetUserInteractive(); } void Telemetry::LogQuickEditCopyRawUsed() { _uiQuickEditCopyRawUsed++; SetUserInteractive(); } void Telemetry::LogQuickEditPasteProcUsed() { _uiQuickEditPasteProcUsed++; SetUserInteractive(); } void Telemetry::LogQuickEditPasteRawUsed() { _uiQuickEditPasteRawUsed++; SetUserInteractive(); } // Log usage of the Color Selection option. void Telemetry::LogColorSelectionUsed() { _uiColorSelectionUsed++; SetUserInteractive(); } void Telemetry::SetWindowSizeChanged() { SetUserInteractive(); } void Telemetry::SetContextMenuUsed() { SetUserInteractive(); } void Telemetry::SetKeyboardTextSelectionUsed() { _fKeyboardTextSelectionUsed = true; SetUserInteractive(); } void Telemetry::SetKeyboardTextEditingUsed() { _fKeyboardTextEditingUsed = true; SetUserInteractive(); } // Log an API call was used. void Telemetry::LogApiCall(const ApiCall api, const BOOLEAN fUnicode) { // Initially we thought about passing over a string (ex. "XYZ") and use a dictionary data type to hold the counts. // However we would have to search through the dictionary every time we called this method, so we decided // to use an array which has very quick access times. // The downside is we have to create an enum type, and then convert them to strings when we finally // send out the telemetry, but the upside is we should have very good performance. if (fUnicode) { _rguiTimesApiUsed[api]++; } else { _rguiTimesApiUsedAnsi[api]++; } } // Log an API call was used. void Telemetry::LogApiCall(const ApiCall api) { _rguiTimesApiUsed[api]++; } // Log usage of the Find Dialog. void Telemetry::LogFindDialogNextClicked(const unsigned int uiStringLength, const bool fDirectionDown, const bool fMatchCase) { // Don't send telemetry for every time it's used, as this will help reduce the load on our servers. // Instead just create a running average of the string length, the direction down radio // button, and match case checkbox. _fpFindStringLengthAverage = ((_fpFindStringLengthAverage * _uiFindNextClickedTotal + uiStringLength) / (_uiFindNextClickedTotal + 1)); _fpDirectionDownAverage = ((_fpDirectionDownAverage * _uiFindNextClickedTotal + (fDirectionDown ? 1 : 0)) / (_uiFindNextClickedTotal + 1)); _fpMatchCaseAverage = ((_fpMatchCaseAverage * _uiFindNextClickedTotal + (fMatchCase ? 1 : 0)) / (_uiFindNextClickedTotal + 1)); _uiFindNextClickedTotal++; } // Find dialog was closed, now send out the telemetry. void Telemetry::FindDialogClosed() { // clang-format off #pragma prefast(suppress: __WARNING_NONCONST_LOCAL, "Activity can't be const, since it's set to a random value on startup.") // clang-format on TraceLoggingWriteTagged(_activity, "FindDialogUsed", TraceLoggingValue(_fpFindStringLengthAverage, "StringLengthAverage"), TraceLoggingValue(_fpDirectionDownAverage, "DirectionDownAverage"), TraceLoggingValue(_fpMatchCaseAverage, "MatchCaseAverage"), TraceLoggingValue(_uiFindNextClickedTotal, "FindNextButtonClickedTotal"), TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES), TelemetryPrivacyDataTag(PDT_ProductAndServiceUsage)); // Get ready for the next time the dialog is used. _fpFindStringLengthAverage = 0; _fpDirectionDownAverage = 0; _fpMatchCaseAverage = 0; _uiFindNextClickedTotal = 0; } // Total up all the used VT100 codes and assign them to the last process that was attached. // We originally did this when each process disconnected, but some processes don't // disconnect when the conhost process exits. So we have to remember the last process that connected. void Telemetry::TotalCodesForPreviousProcess() { using namespace Microsoft::Console::VirtualTerminal; // Get the values even if we aren't recording the previously connected process, since we want to reset them to 0. unsigned int _uiTimesUsedCurrent = TermTelemetry::Instance().GetAndResetTimesUsedCurrent(); unsigned int _uiTimesFailedCurrent = TermTelemetry::Instance().GetAndResetTimesFailedCurrent(); unsigned int _uiTimesFailedOutsideRangeCurrent = TermTelemetry::Instance().GetAndResetTimesFailedOutsideRangeCurrent(); if (_iProcessConnectedCurrently < c_iMaxProcessesConnected) { _rguiProcessFileNamesCodesCount[_iProcessConnectedCurrently] += _uiTimesUsedCurrent; _rguiProcessFileNamesFailedCodesCount[_iProcessConnectedCurrently] += _uiTimesFailedCurrent; _rguiProcessFileNamesFailedOutsideCodesCount[_iProcessConnectedCurrently] += _uiTimesFailedOutsideRangeCurrent; // Don't total any more process connected telemetry, unless a new processes attaches that we want to gather. _iProcessConnectedCurrently = SIZE_MAX; } } // Tries to find the process name amongst our previous process names by doing a binary search. // The main difference between this and the standard bsearch library call, is that if this // can't find the string, it returns the position the new string should be inserted at. This saves // us from having an additional search through the array, and improves performance. bool Telemetry::FindProcessName(const WCHAR* pszProcessName, _Out_ size_t* iPosition) const { int iMin = 0; int iMid = 0; int iMax = _uiNumberProcessFileNames - 1; int result = 0; while (iMin <= iMax) { iMid = (iMax + iMin) / 2; // Use a case-insensitive comparison. We do support running Linux binaries now, but we haven't seen them connect // as processes, and even if they did, we don't care about the difference in running emacs vs. Emacs. result = _wcsnicmp(pszProcessName, _wchProcessFileNames + _rgiProcessFileNameIndex[_rgiAlphabeticalIndex[iMid]], MAX_PATH); if (result < 0) { iMax = iMid - 1; } else if (result > 0) { iMin = iMid + 1; } else { // Found the string. *iPosition = iMid; return true; } } // Let them know which position to insert the string at. *iPosition = (result > 0) ? iMid + 1 : iMid; return false; } // Log a process name and number of times it has connected to the console in preparation to send through telemetry. // We were considering sending out a log of telemetry when each process connects, but then the telemetry can get // complicated and spammy, especially since command line utilities like help.exe and where.exe are considered processes. // Don't send telemetry for every time a process connects, as this will help reduce the load on our servers. // Just save the name and count, and send the telemetry before the console exits. void Telemetry::LogProcessConnected(const HANDLE hProcess) { // This is a bit of processing, so don't do it for the 95% of machines that aren't being sampled. if (TraceLoggingProviderEnabled(g_hConhostV2EventTraceProvider, 0, MICROSOFT_KEYWORD_MEASURES)) { TotalCodesForPreviousProcess(); // Don't initialize wszFilePathAndName, QueryFullProcessImageName does that for us. Use QueryFullProcessImageName instead of // GetProcessImageFileName because we need the path to begin with a drive letter and not a device name. WCHAR wszFilePathAndName[MAX_PATH]; DWORD dwSize = ARRAYSIZE(wszFilePathAndName); if (QueryFullProcessImageName(hProcess, 0, wszFilePathAndName, &dwSize)) { // Stripping out the path also helps with PII issues in case they launched the program // from a path containing their username. PWSTR pwszFileName = PathFindFileName(wszFilePathAndName); size_t iFileName; if (FindProcessName(pwszFileName, &iFileName)) { // We already logged this process name, so just increment the count. _iProcessConnectedCurrently = _rgiAlphabeticalIndex[iFileName]; _rguiProcessFileNamesCount[_iProcessConnectedCurrently]++; } else if ((_uiNumberProcessFileNames < ARRAYSIZE(_rguiProcessFileNamesCount)) && (_iProcessFileNamesNext < ARRAYSIZE(_wchProcessFileNames) - 10)) { // Check if the MS released bash was used. MS bash is installed under windows\system32, and it's possible somebody else // could be installing their bash into that directory, but not likely. If the user first runs a non-MS bash, // and then runs MS bash, we won't detect the MS bash as running, but it's an acceptable compromise. if (!_fBashUsed && !_wcsnicmp(c_pwszBashExeName, pwszFileName, MAX_PATH)) { // We could have gotten the system directory once when this class starts, but we'd have to hold the memory for it // plus we're not sure we'd ever need it, so just get it when we know we're running bash.exe. WCHAR wszSystemDirectory[MAX_PATH] = L""; if (GetSystemDirectory(wszSystemDirectory, ARRAYSIZE(wszSystemDirectory))) { _fBashUsed = (PathIsSameRoot(wszFilePathAndName, wszSystemDirectory) == TRUE); } } // In order to send out a dynamic array of strings through telemetry, we have to pack the strings into a single WCHAR array. // There currently aren't any helper functions for this, and we have to pack it manually. // To understand the format of the single string, consult the documentation in the traceloggingprovider.h file. if (SUCCEEDED(StringCchCopyW(_wchProcessFileNames + _iProcessFileNamesNext, ARRAYSIZE(_wchProcessFileNames) - _iProcessFileNamesNext - 1, pwszFileName))) { // As each FileName comes in, it's appended to the end. However to improve searching speed, we have an array of indexes // that is alphabetically sorted. We could call qsort, but that would be a waste in performance since we're just adding one string // at a time and we always keep the array sorted, so just shift everything over one. for (size_t n = _uiNumberProcessFileNames; n > iFileName; n--) { _rgiAlphabeticalIndex[n] = _rgiAlphabeticalIndex[n - 1]; } // Now point to the string, and set the count to 1. _rgiAlphabeticalIndex[iFileName] = _uiNumberProcessFileNames; _rgiProcessFileNameIndex[_uiNumberProcessFileNames] = _iProcessFileNamesNext; _rguiProcessFileNamesCount[_uiNumberProcessFileNames] = 1; _iProcessFileNamesNext += wcslen(pwszFileName) + 1; _iProcessConnectedCurrently = _uiNumberProcessFileNames++; // Packed arrays start with a UINT16 value indicating the number of elements in the array. BYTE* pbFileNames = reinterpret_cast<BYTE*>(_wchProcessFileNames); pbFileNames[0] = (BYTE)_uiNumberProcessFileNames; pbFileNames[1] = (BYTE)(_uiNumberProcessFileNames >> 8); } } } } } // This Function sends final Trace log before session closes. // We're primarily sending this telemetry once at the end, and only when the user interacted with the console // so we don't overwhelm our servers by sending a constant stream of telemetry while the console is being used. void Telemetry::WriteFinalTraceLog() { const CONSOLE_INFORMATION& gci = Microsoft::Console::Interactivity::ServiceLocator::LocateGlobals().getConsoleInformation(); // This is a bit of processing, so don't do it for the 95% of machines that aren't being sampled. if (TraceLoggingProviderEnabled(g_hConhostV2EventTraceProvider, 0, MICROSOFT_KEYWORD_MEASURES)) { // Normally we would set the activity Id earlier, but since we know the parser only sends // one final log at the end, setting the activity this late should be fine. Microsoft::Console::VirtualTerminal::TermTelemetry::Instance().SetActivityId(_activity.Id()); Microsoft::Console::VirtualTerminal::TermTelemetry::Instance().SetShouldWriteFinalLog(_fUserInteractiveForTelemetry); if (_fUserInteractiveForTelemetry) { TotalCodesForPreviousProcess(); // Send this back using "measures" since we want a good sampling of our entire userbase. time_t tEndedAt; time(&tEndedAt); // clang-format off #pragma prefast(suppress: __WARNING_NONCONST_LOCAL, "Activity can't be const, since it's set to a random value on startup.") // clang-format on TraceLoggingWriteTagged(_activity, "SessionEnding", TraceLoggingBool(_fBashUsed, "BashUsed"), TraceLoggingBool(_fCtrlPgUpPgDnUsed, "CtrlPgUpPgDnUsed"), TraceLoggingBool(_fKeyboardTextEditingUsed, "KeyboardTextEditingUsed"), TraceLoggingBool(_fKeyboardTextSelectionUsed, "KeyboardTextSelectionUsed"), TraceLoggingUInt32(_uiCtrlShiftCProcUsed, "CtrlShiftCProcUsed"), TraceLoggingUInt32(_uiCtrlShiftCRawUsed, "CtrlShiftCRawUsed"), TraceLoggingUInt32(_uiCtrlShiftVProcUsed, "CtrlShiftVProcUsed"), TraceLoggingUInt32(_uiCtrlShiftVRawUsed, "CtrlShiftVRawUsed"), TraceLoggingUInt32(_uiQuickEditCopyProcUsed, "QuickEditCopyProcUsed"), TraceLoggingUInt32(_uiQuickEditCopyRawUsed, "QuickEditCopyRawUsed"), TraceLoggingUInt32(_uiQuickEditPasteProcUsed, "QuickEditPasteProcUsed"), TraceLoggingUInt32(_uiQuickEditPasteRawUsed, "QuickEditPasteRawUsed"), TraceLoggingBool(gci.GetLinkTitle().length() == 0, "LaunchedFromShortcut"), // Normally we would send out a single array containing the name and count, // but that's difficult to do with our telemetry system, so send out two separate arrays. // Casting to UINT should be fine, since our array size is only 2K. TraceLoggingPackedField(_wchProcessFileNames, static_cast<UINT>(sizeof(WCHAR) * _iProcessFileNamesNext), TlgInUNICODESTRING | TlgInVcount, "ProcessesConnected"), TraceLoggingUInt32Array(_rguiProcessFileNamesCount, _uiNumberProcessFileNames, "ProcessesConnectedCount"), TraceLoggingUInt32Array(_rguiProcessFileNamesCodesCount, _uiNumberProcessFileNames, "ProcessesConnectedCodesCount"), TraceLoggingUInt32Array(_rguiProcessFileNamesFailedCodesCount, _uiNumberProcessFileNames, "ProcessesConnectedFailedCodesCount"), TraceLoggingUInt32Array(_rguiProcessFileNamesFailedOutsideCodesCount, _uiNumberProcessFileNames, "ProcessesConnectedFailedOutsideCount"), // Send back both starting and ending times separately instead just usage time (ending - starting). // This can help us determine if they were using multiple consoles at the same time. TraceLoggingInt32(static_cast<int>(_tStartedAt), "StartedUsingAtSeconds"), TraceLoggingInt32(static_cast<int>(tEndedAt), "EndedUsingAtSeconds"), TraceLoggingUInt32(_uiColorSelectionUsed, "ColorSelectionUsed"), TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES), TelemetryPrivacyDataTag(PDT_ProductAndServiceUsage)); // Always send this back. We could only send this back when they click "OK" in the settings dialog, but sending it // back every time should give us a good idea of their current, final sett
c++
code
20,000
2,980
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE36_Absolute_Path_Traversal__wchar_t_listen_socket_ifstream_22a.cpp Label Definition File: CWE36_Absolute_Path_Traversal.label.xml Template File: sources-sink-22a.tmpl.cpp */ /* * @description * CWE: 36 Absolute Path Traversal * BadSource: listen_socket Read data using a listen socket (server side) * GoodSource: Full path and file name * Sink: ifstream * BadSink : Open the file named in data using ifstream::open() * Flow Variant: 22 Control flow: Flow controlled by value of a global variable. Sink functions are in a separate file from sources. * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #include <fstream> using namespace std; namespace CWE36_Absolute_Path_Traversal__wchar_t_listen_socket_ifstream_22 { #ifndef OMITBAD /* The global variable below is used to drive control flow in the source function. Since it is in a C++ namespace, it doesn't need a globally unique name. */ int badGlobal = 0; wchar_t * badSource(wchar_t * data); void bad() { wchar_t * data; wchar_t dataBuffer[FILENAME_MAX] = L""; data = dataBuffer; badGlobal = 1; /* true */ data = badSource(data); { ifstream inputFile; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ inputFile.open((char *)data); inputFile.close(); } ; } #endif /* OMITBAD */ #ifndef OMITGOOD /* The global variables below are used to drive control flow in the source functions. Since they are in a C++ namespace, they don't need globally unique names. */ int goodG2B1Global = 0; int goodG2B2Global = 0; /* goodG2B1() - use goodsource and badsink by setting the global variable to false instead of true */ wchar_t * goodG2B1Source(wchar_t * data); static void goodG2B1() { wchar_t * data; wchar_t dataBuffer[FILENAME_MAX] = L""; data = dataBuffer; goodG2B1Global = 0; /* false */ data = goodG2B1Source(data); { ifstream inputFile; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ inputFile.open((char *)data); inputFile.close(); } ; } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if in the source function */ wchar_t * goodG2B2Source(wchar_t * data); static void goodG2B2() { wchar_t * data; wchar_t dataBuffer[FILENAME_MAX] = L""; data = dataBuffer; goodG2B2Global = 1; /* true */ data = goodG2B2Source(data); { ifstream inputFile; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ inputFile.open((char *)data); inputFile.close(); } ; } void good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE36_Absolute_Path_Traversal__wchar_t_listen_socket_ifstream_22; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
c++
code
3,755
761
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2016-2019 Baldur Karlsson * * 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 "d3d12_device.h" #include "driver/dxgi/dxgi_common.h" #include "driver/ihv/amd/official/DXExt/AmdExtD3D.h" #include "driver/ihv/amd/official/DXExt/AmdExtD3DCommandListMarkerApi.h" #include "d3d12_command_list.h" #include "d3d12_command_queue.h" #include "d3d12_resources.h" #include "d3d12_shader_cache.h" template <typename SerialiserType> bool WrappedID3D12Device::Serialise_CreateCommandQueue(SerialiserType &ser, const D3D12_COMMAND_QUEUE_DESC *pDesc, REFIID riid, void **ppCommandQueue) { SERIALISE_ELEMENT_LOCAL(Descriptor, *pDesc).Named("pDesc"_lit); SERIALISE_ELEMENT_LOCAL(guid, riid).Named("riid"_lit); SERIALISE_ELEMENT_LOCAL(pCommandQueue, ((WrappedID3D12CommandQueue *)*ppCommandQueue)->GetResourceID()) .TypedAs("ID3D12CommandQueue *"_lit); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { ID3D12CommandQueue *ret = NULL; HRESULT hr = m_pDevice->CreateCommandQueue(&Descriptor, guid, (void **)&ret); if(FAILED(hr)) { RDCERR("Failed on resource serialise-creation, HRESULT: %s", ToStr(hr).c_str()); return false; } else { SetObjName(ret, StringFormat::Fmt("Command Queue ID %llu", pCommandQueue)); ret = new WrappedID3D12CommandQueue(ret, this, m_State); GetResourceManager()->AddLiveResource(pCommandQueue, ret); AddResource(pCommandQueue, ResourceType::Queue, "Command Queue"); WrappedID3D12CommandQueue *wrapped = (WrappedID3D12CommandQueue *)ret; if(Descriptor.Type == D3D12_COMMAND_LIST_TYPE_DIRECT && m_Queue == NULL) { m_Queue = wrapped; // we hold an extra ref on this during capture to keep it alive, for simplicity match that // behaviour here. m_Queue->AddRef(); CreateInternalResources(); } m_Queues.push_back(wrapped); // create a dummy (dummy) fence ID3D12Fence *fence = NULL; hr = this->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), (void **)&fence); RDCASSERTEQUAL(hr, S_OK); m_QueueFences.push_back(fence); } } return true; } HRESULT WrappedID3D12Device::CreateCommandQueue(const D3D12_COMMAND_QUEUE_DESC *pDesc, REFIID riid, void **ppCommandQueue) { if(ppCommandQueue == NULL) return m_pDevice->CreateCommandQueue(pDesc, riid, NULL); if(riid != __uuidof(ID3D12CommandQueue)) return E_NOINTERFACE; ID3D12CommandQueue *real = NULL; HRESULT ret; SERIALISE_TIME_CALL(ret = m_pDevice->CreateCommandQueue(pDesc, riid, (void **)&real)); if(SUCCEEDED(ret)) { WrappedID3D12CommandQueue *wrapped = new WrappedID3D12CommandQueue(real, this, m_State); if(IsCaptureMode(m_State)) { CACHE_THREAD_SERIALISER(); SCOPED_SERIALISE_CHUNK(D3D12Chunk::Device_CreateCommandQueue); Serialise_CreateCommandQueue(ser, pDesc, riid, (void **)&wrapped); m_DeviceRecord->AddChunk(scope.Get()); } else { GetResourceManager()->AddLiveResource(wrapped->GetResourceID(), wrapped); } if(pDesc->Type == D3D12_COMMAND_LIST_TYPE_DIRECT && m_Queue == NULL) { m_Queue = wrapped; // keep this queue alive even if the application frees it, for our own use m_Queue->AddRef(); InternalRef(); CreateInternalResources(); } m_Queues.push_back(wrapped); *ppCommandQueue = (ID3D12CommandQueue *)wrapped; } return ret; } template <typename SerialiserType> bool WrappedID3D12Device::Serialise_CreateCommandAllocator(SerialiserType &ser, D3D12_COMMAND_LIST_TYPE type, REFIID riid, void **ppCommandAllocator) { SERIALISE_ELEMENT(type); SERIALISE_ELEMENT_LOCAL(guid, riid).Named("riid"_lit); SERIALISE_ELEMENT_LOCAL(pCommandAllocator, ((WrappedID3D12CommandAllocator *)*ppCommandAllocator)->GetResourceID()) .TypedAs("ID3D12CommandAllocator *"_lit); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { ID3D12CommandAllocator *ret = NULL; HRESULT hr = m_pDevice->CreateCommandAllocator(type, guid, (void **)&ret); if(FAILED(hr)) { RDCERR("Failed on resource serialise-creation, HRESULT: %s", ToStr(hr).c_str()); return false; } else { ret = new WrappedID3D12CommandAllocator(ret, this); m_CommandAllocators.push_back(ret); GetResourceManager()->AddLiveResource(pCommandAllocator, ret); AddResource(pCommandAllocator, ResourceType::Pool, "Command Allocator"); } } return true; } HRESULT WrappedID3D12Device::CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE type, REFIID riid, void **ppCommandAllocator) { if(ppCommandAllocator == NULL) return m_pDevice->CreateCommandAllocator(type, riid, NULL); if(riid != __uuidof(ID3D12CommandAllocator)) return E_NOINTERFACE; ID3D12CommandAllocator *real = NULL; HRESULT ret; SERIALISE_TIME_CALL(ret = m_pDevice->CreateCommandAllocator(type, riid, (void **)&real)); if(SUCCEEDED(ret)) { WrappedID3D12CommandAllocator *wrapped = new WrappedID3D12CommandAllocator(real, this); if(IsCaptureMode(m_State)) { CACHE_THREAD_SERIALISER(); SCOPED_SERIALISE_CHUNK(D3D12Chunk::Device_CreateCommandAllocator); Serialise_CreateCommandAllocator(ser, type, riid, (void **)&wrapped); D3D12ResourceRecord *record = GetResourceManager()->AddResourceRecord(wrapped->GetResourceID()); record->type = Resource_CommandAllocator; record->Length = 0; wrapped->SetResourceRecord(record); record->AddChunk(scope.Get()); } else { GetResourceManager()->AddLiveResource(wrapped->GetResourceID(), wrapped); } *ppCommandAllocator = (ID3D12CommandAllocator *)wrapped; } return ret; } template <typename SerialiserType> bool WrappedID3D12Device::Serialise_CreateCommandList(SerialiserType &ser, UINT nodeMask, D3D12_COMMAND_LIST_TYPE type, ID3D12CommandAllocator *pCommandAllocator, ID3D12PipelineState *pInitialState, REFIID riid, void **ppCommandList) { SERIALISE_ELEMENT(nodeMask); SERIALISE_ELEMENT(type); SERIALISE_ELEMENT(pCommandAllocator); SERIALISE_ELEMENT(pInitialState); SERIALISE_ELEMENT_LOCAL(guid, riid).Named("riid"_lit); SERIALISE_ELEMENT_LOCAL(pCommandList, ((WrappedID3D12GraphicsCommandList *)*ppCommandList)->GetResourceID()) .TypedAs("ID3D12GraphicsCommandList *"_lit); // this chunk is purely for user information and consistency, the command buffer we allocate is // a dummy and is not used for anything. SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { ID3D12GraphicsCommandList *list = NULL; HRESULT hr = CreateCommandList(nodeMask, type, pCommandAllocator, pInitialState, __uuidof(ID3D12GraphicsCommandList), (void **)&list); if(FAILED(hr)) { RDCERR("Failed on resource serialise-creation, HRESULT: %s", ToStr(hr).c_str()); return false; } else if(list) { // close it immediately, we don't want to tie up the allocator list->Close(); GetResourceManager()->AddLiveResource(pCommandList, list); } AddResource(pCommandList, ResourceType::CommandBuffer, "Command List"); DerivedResource(pCommandAllocator, pCommandList); if(pInitialState) DerivedResource(pInitialState, pCommandList); } return true; } HRESULT WrappedID3D12Device::CreateCommandList(UINT nodeMask, D3D12_COMMAND_LIST_TYPE type, ID3D12CommandAllocator *pCommandAllocator, ID3D12PipelineState *pInitialState, REFIID riid, void **ppCommandList) { if(ppCommandList == NULL) return m_pDevice->CreateCommandList(nodeMask, type, Unwrap(pCommandAllocator), Unwrap(pInitialState), riid, NULL); if(riid != __uuidof(ID3D12GraphicsCommandList) && riid != __uuidof(ID3D12CommandList) && riid != __uuidof(ID3D12GraphicsCommandList1) && riid != __uuidof(ID3D12GraphicsCommandList2) && riid != __uuidof(ID3D12GraphicsCommandList3) && riid != __uuidof(ID3D12GraphicsCommandList4)) return E_NOINTERFACE; void *realptr = NULL; HRESULT ret; SERIALISE_TIME_CALL(ret = m_pDevice->CreateCommandList( nodeMask, type, Unwrap(pCommandAllocator), Unwrap(pInitialState), __uuidof(ID3D12GraphicsCommandList), &realptr)); ID3D12GraphicsCommandList *real = NULL; if(riid == __uuidof(ID3D12CommandList)) real = (ID3D12GraphicsCommandList *)(ID3D12CommandList *)realptr; else if(riid == __uuidof(ID3D12GraphicsCommandList)) real = (ID3D12GraphicsCommandList *)realptr; else if(riid == __uuidof(ID3D12GraphicsCommandList1)) real = (ID3D12GraphicsCommandList1 *)realptr; else if(riid == __uuidof(ID3D12GraphicsCommandList2)) real = (ID3D12GraphicsCommandList2 *)realptr; else if(riid == __uuidof(ID3D12GraphicsCommandList3)) real = (ID3D12GraphicsCommandList3 *)realptr; else if(riid == __uuidof(ID3D12GraphicsCommandList4)) real = (ID3D12GraphicsCommandList4 *)realptr; if(SUCCEEDED(ret)) { WrappedID3D12GraphicsCommandList *wrapped = new WrappedID3D12GraphicsCommandList(real, this, m_State); if(m_pAMDExtObject) { IAmdExtD3DCommandListMarker *markers = NULL; m_pAMDExtObject->CreateInterface(real, __uuidof(IAmdExtD3DCommandListMarker), (void **)&markers); wrapped->SetAMDMarkerInterface(markers); } if(IsCaptureMode(m_State)) { // we just serialise out command allocator creation as a reset, since it's equivalent. wrapped->SetInitParams(riid, nodeMask, type); wrapped->Reset(pCommandAllocator, pInitialState); { CACHE_THREAD_SERIALISER(); SCOPED_SERIALISE_CHUNK(D3D12Chunk::Device_CreateCommandList); Serialise_CreateCommandList(ser, nodeMask, type, pCommandAllocator, pInitialState, riid, (void **)&wrapped); wrapped->GetCreationRecord()->AddChunk(scope.Get()); } // add parents so these are always in the capture. They won't necessarily be used for replay // but we want them to be available so the creation chunk is fully realised wrapped->GetCreationRecord()->AddParent(GetRecord(pCommandAllocator)); if(pInitialState) wrapped->GetCreationRecord()->AddParent(GetRecord(pInitialState)); } // during replay, the caller is responsible for calling AddLiveResource as this function // can be called from ID3D12GraphicsCommandList::Reset serialising if(riid == __uuidof(ID3D12GraphicsCommandList)) *ppCommandList = (ID3D12GraphicsCommandList *)wrapped; else if(riid == __uuidof(ID3D12GraphicsCommandList1)) *ppCommandList = (ID3D12GraphicsCommandList1 *)wrapped; else if(riid == __uuidof(ID3D12GraphicsCommandList2)) *ppCommandList = (ID3D12GraphicsCommandList2 *)wrapped; else if(riid == __uuidof(ID3D12GraphicsCommandList3)) *ppCommandList = (ID3D12GraphicsCommandList3 *)wrapped; else if(riid == __uuidof(ID3D12GraphicsCommandList4)) *ppCommandList = (ID3D12GraphicsCommandList4 *)wrapped; else if(riid == __uuidof(ID3D12CommandList)) *ppCommandList = (ID3D12CommandList *)wrapped; else RDCERR("Unexpected riid! %s", ToStr(riid).c_str()); } return ret; } template <typename SerialiserType> bool WrappedID3D12Device::Serialise_CreateGraphicsPipelineState( SerialiserType &ser, const D3D12_GRAPHICS_PIPELINE_STATE_DESC *pDesc, REFIID riid, void **ppPipelineState) { SERIALISE_ELEMENT_LOCAL(Descriptor, *pDesc).Named("pDesc"_lit); SERIALISE_ELEMENT_LOCAL(guid, riid).Named("riid"_lit); SERIALISE_ELEMENT_LOCAL(pPipelineState, ((WrappedID3D12PipelineState *)*ppPipelineState)->GetResourceID()) .TypedAs("ID3D12PipelineState *"_lit); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { D3D12_GRAPHICS_PIPELINE_STATE_DESC unwrappedDesc = Descriptor; unwrappedDesc.pRootSignature = Unwrap(unwrappedDesc.pRootSignature); // check for bytecode - if the user is wrongly using DXIL we will fail to load the capture { D3D12_SHADER_BYTECODE *shaders[] = { &unwrappedDesc.VS, &unwrappedDesc.HS, &unwrappedDesc.DS, &unwrappedDesc.GS, &unwrappedDesc.PS, }; const char *name[] = {"VS", "HS", "DS", "GS", "PS"}; for(size_t i = 0; i < ARRAY_COUNT(shaders); i++) { if(shaders[i]->BytecodeLength > 0 && shaders[i]->pShaderBytecode) { if(!DXBC::DXBCFile::CheckForShaderCode(shaders[i]->pShaderBytecode, shaders[i]->BytecodeLength)) { RDCERR( "No shader code found in %s bytecode in pipeline state. " "DXIL is unsupported and must be checked for using CheckFeatureSupport.", name[i]); m_FailedReplayStatus = ReplayStatus::APIReplayFailed; return false; } } } } ID3D12PipelineState *ret = NULL; HRESULT hr = m_pDevice->CreateGraphicsPipelineState(&unwrappedDesc, guid, (void **)&ret); if(FAILED(hr)) { RDCERR("Failed on resource serialise-creation, HRESULT: %s", ToStr(hr).c_str()); return false; } else { ret = new WrappedID3D12PipelineState(ret, this); WrappedID3D12PipelineState *wrapped = (WrappedID3D12PipelineState *)ret; wrapped->graphics = new D3D12_EXPANDED_PIPELINE_STATE_STREAM_DESC(Descriptor); D3D12_SHADER_BYTECODE *shaders[] = { &wrapped->graphics->VS, &wrapped->graphics->HS, &wrapped->graphics->DS, &wrapped->graphics->GS, &wrapped->graphics->PS, }; AddResource(pPipelineState, ResourceType::PipelineState, "Graphics Pipeline State"); if(Descriptor.pRootSignature) DerivedResource(Descriptor.pRootSignature, pPipelineState); for(size_t i = 0; i < ARRAY_COUNT(shaders); i++) { if(shaders[i]->BytecodeLength == 0 || shaders[i]->pShaderBytecode == NULL) { shaders[i]->pShaderBytecode = NULL; shaders[i]->BytecodeLength = 0; } else { WrappedID3D12Shader *entry = WrappedID3D12Shader::AddShader(*shaders[i], this, wrapped); shaders[i]->pShaderBytecode = entry; AddResourceCurChunk(entry->GetResourceID()); DerivedResource(entry->GetResourceID(), pPipelineState); } } if(wrapped->graphics->InputLayout.NumElements) { wrapped->graphics->InputLayout.pInputElementDescs = new D3D12_INPUT_ELEMENT_DESC[wrapped->graphics->InputLayout.NumElements]; memcpy((void *)wrapped->graphics->InputLayout.pInputElementDescs, Descriptor.InputLayout.pInputElementDescs, sizeof(D3D12_INPUT_ELEMENT_DESC) * wrapped->graphics->InputLayout.NumElements); } else { wrapped->graphics->InputLayout.pInputElementDescs = NULL; } if(wrapped->graphics->StreamOutput.NumEntries) { wrapped->graphics->StreamOutput.pSODeclaration = new D3D12_SO_DECLARATION_ENTRY[wrapped->graphics->StreamOutput.NumEntries]; memcpy((void *)wrapped->graphics->StreamOutput.pSODeclaration, Descriptor.StreamOutput.pSODeclaration, sizeof(D3D12_SO_DECLARATION_ENTRY) * wrapped->graphics->StreamOutput.NumEntries); } else { wrapped->graphics->StreamOutput.pSODeclaration = NULL; } if(wrapped->graphics->StreamOutput.NumStrides) { wrapped->graphics->StreamOutput.pBufferStrides = new UINT[wrapped->graphics->StreamOutput.NumStrides]; memcpy((void *)wrapped->graphics->StreamOutput.pBufferStrides, Descriptor.StreamOutput.pBufferStrides, sizeof(UINT) * wrapped->graphics->StreamOutput.NumStrides); } else { wrapped->graphics->StreamOutput.pBufferStrides = NULL; } GetResourceManager()->AddLiveResource(pPipelineState, ret); } } return true; } HRESULT WrappedID3D12Device::CreateGraphicsPipelineState(const D3D12_GRAPHICS_PIPELINE_STATE_DESC *pDesc, REFIID riid, void **ppPipelineState) { D3D12_GRAPHICS_PIPELINE_STATE_DESC unwrappedDesc = *pDesc; unwrappedDesc.pRootSignature = Unwrap(unwrappedDesc.pRootSignature); if(ppPipelineState == NULL) return m_pDevice->CreateGraphicsPipelineState(&unwrappedDesc, riid, NULL); if(riid != __uuidof(ID3D12PipelineState)) return E_NOINTERFACE; ID3D12PipelineState *real = NULL; HRESULT ret; SERIALISE_TIME_CALL( ret = m_pDevice->CreateGraphicsPipelineState(&unwrappedDesc, riid, (void **)&real)); if(SUCCEEDED(ret)) { // check for bytecode - if the user is wrongly using DXIL we will prevent capturing { D3D12_SHADER_BYTECODE *shaders[] = { &unwrappedDesc.VS, &unwrappedDesc.HS, &unwrappedDesc.DS, &unwrappedDesc.GS, &unwrappedDesc.PS, }; const char *name[] = {"VS", "HS", "DS", "GS", "PS"}; for(size_t i = 0; i < ARRAY_COUNT(shaders); i++) { if(shaders[i]->BytecodeLength > 0 && shaders[i]->pShaderBytecode) { if(!DXBC::DXBCFile::CheckForShaderCode(shaders[i]->pShaderBytecode, shaders[i]->BytecodeLength)) { RDCERR( "No shader code found in %s bytecode in pipeline state. " "DXIL is unsupported and must be checked for using CheckFeatureSupport.", name[i]); m_InvalidPSO = true; } } } } WrappedID3D12PipelineState *wrapped = new WrappedID3D12PipelineState(real, this); if(IsCaptureMode(m_State)) { CACHE_THREAD_SERIALISER(); SCOPED_SERIALISE_CHUNK(D3D12Chunk::Device_CreateGraphicsPipeline);
c++
code
20,000
3,686
/** * Tencent is pleased to support the open source community by making Tars available. * * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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 "util/tc_thread.h" #include <sstream> #include <cerrno> #include <cassert> namespace tars { TC_ThreadControl::TC_ThreadControl(std::thread *th) : _th(th) { assert(_th != NULL); } void TC_ThreadControl::join() { if (std::this_thread::get_id() == _th->get_id()) { throw TC_ThreadThreadControl_Exception("[TC_ThreadControl::join] can't be called in the same thread"); } _th->join(); } void TC_ThreadControl::detach() { _th->detach(); } std::thread::id TC_ThreadControl::id() const { return _th->get_id(); } void TC_ThreadControl::sleep(int64_t millsecond) { std::this_thread::sleep_for(std::chrono::milliseconds(millsecond)); } void TC_ThreadControl::yield() { std::this_thread::yield(); } TC_Thread::TC_Thread() : _running(false), _th(NULL) { } TC_Thread::~TC_Thread() { if(_th != NULL) { //如果资源没有被detach或者被join,则自己释放 if (_th->joinable()) { _th->detach(); } delete _th; _th = NULL; } } void TC_Thread::threadEntry(TC_Thread *pThread) { pThread->_running = true; { TC_ThreadLock::Lock sync(pThread->_lock); pThread->_lock.notifyAll(); } try { pThread->run(); } catch (exception &ex) { pThread->_running = false; throw ex; } catch (...) { pThread->_running = false; throw; } pThread->_running = false; } TC_ThreadControl TC_Thread::start() { TC_ThreadLock::Lock sync(_lock); if (_running) { throw TC_ThreadThreadControl_Exception("[TC_Thread::start] thread has start"); } try { _th = new std::thread(&TC_Thread::threadEntry, this); } catch(...) { throw TC_ThreadThreadControl_Exception("[TC_Thread::start] thread start error"); } _lock.wait(); return TC_ThreadControl(_th); } TC_ThreadControl TC_Thread::getThreadControl() { return TC_ThreadControl(_th); } bool TC_Thread::isAlive() const { return _running; } size_t TC_Thread::CURRENT_THREADID() { static thread_local size_t threadId = 0; if(threadId == 0 ) { std::stringstream ss; ss << std::this_thread::get_id(); threadId = strtol(ss.str().c_str(), NULL, 0); } return threadId; } }
c++
code
3,035
683
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include "ifcpp/model/AttributeObject.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/model/BuildingGuid.h" #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/IFC4/include/IfcLightDistributionCurveEnum.h" #include "ifcpp/IFC4/include/IfcLightDistributionData.h" #include "ifcpp/IFC4/include/IfcLightIntensityDistribution.h" // ENTITY IfcLightIntensityDistribution IfcLightIntensityDistribution::IfcLightIntensityDistribution() {} IfcLightIntensityDistribution::IfcLightIntensityDistribution( int id ) { m_entity_id = id; } IfcLightIntensityDistribution::~IfcLightIntensityDistribution() {} shared_ptr<BuildingObject> IfcLightIntensityDistribution::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcLightIntensityDistribution> copy_self( new IfcLightIntensityDistribution() ); if( m_LightDistributionCurve ) { copy_self->m_LightDistributionCurve = dynamic_pointer_cast<IfcLightDistributionCurveEnum>( m_LightDistributionCurve->getDeepCopy(options) ); } for( size_t ii=0; ii<m_DistributionData.size(); ++ii ) { auto item_ii = m_DistributionData[ii]; if( item_ii ) { copy_self->m_DistributionData.push_back( dynamic_pointer_cast<IfcLightDistributionData>(item_ii->getDeepCopy(options) ) ); } } return copy_self; } void IfcLightIntensityDistribution::getStepLine( std::stringstream& stream ) const { stream << "#" << m_entity_id << "= IFCLIGHTINTENSITYDISTRIBUTION" << "("; if( m_LightDistributionCurve ) { m_LightDistributionCurve->getStepParameter( stream ); } else { stream << "$"; } stream << ","; writeEntityList( stream, m_DistributionData ); stream << ");"; } void IfcLightIntensityDistribution::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_entity_id; } const std::wstring IfcLightIntensityDistribution::toString() const { return L"IfcLightIntensityDistribution"; } void IfcLightIntensityDistribution::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map ) { const size_t num_args = args.size(); if( num_args != 2 ){ std::stringstream err; err << "Wrong parameter count for entity IfcLightIntensityDistribution, expecting 2, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); } m_LightDistributionCurve = IfcLightDistributionCurveEnum::createObjectFromSTEP( args[0], map ); readEntityReferenceList( args[1], m_DistributionData, map ); } void IfcLightIntensityDistribution::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) { vec_attributes.push_back( std::make_pair( "LightDistributionCurve", m_LightDistributionCurve ) ); if( m_DistributionData.size() > 0 ) { shared_ptr<AttributeObjectVector> DistributionData_vec_object( new AttributeObjectVector() ); std::copy( m_DistributionData.begin(), m_DistributionData.end(), std::back_inserter( DistributionData_vec_object->m_vec ) ); vec_attributes.push_back( std::make_pair( "DistributionData", DistributionData_vec_object ) ); } } void IfcLightIntensityDistribution::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) { } void IfcLightIntensityDistribution::setInverseCounterparts( shared_ptr<BuildingEntity> ) { } void IfcLightIntensityDistribution::unlinkFromInverseCounterparts() { }
c++
code
3,579
653
/*! @file Defines `boost::hana::make`. @copyright Louis Dionne 2013-2017 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_HANA_CORE_MAKE_HPP #define BOOST_HANA_CORE_MAKE_HPP #include <boost/hana/fwd/core/make.hpp> #include <boost/hana/config.hpp> #include <boost/hana/core/default.hpp> #include <boost/hana/core/when.hpp> namespace boost { namespace hana { //! @cond template <typename Datatype, typename> struct make_impl : make_impl<Datatype, when<true>> { }; //! @endcond template <typename Datatype, bool condition> struct make_impl<Datatype, when<condition>> : default_ { template <typename ...X> static constexpr auto make_helper(int, X&& ...x) -> decltype(Datatype(static_cast<X&&>(x)...)) { return Datatype(static_cast<X&&>(x)...); } template <typename ...X> static constexpr auto make_helper(long, X&& ...) { static_assert((sizeof...(X), false), "there exists no constructor for the given data type"); } template <typename ...X> static constexpr decltype(auto) apply(X&& ...x) { return make_helper(int{}, static_cast<X&&>(x)...); } }; }} // end namespace boost::hana #endif // !BOOST_HANA_CORE_MAKE_HPP
c++
code
1,364
301
#include "zip_tuple.hpp" #include <cassert> #include <iostream> #include <iostream> #include <memory> #include <type_traits> #include <cxxabi.h> auto main() -> int { auto a = std::vector<int>{1, 2, 3, 4, 5, 6}; auto b = std::vector<int>{1, 2, 3, 4, 5, 6, 7}; auto c = std::vector<int>{0, 0, 0, 0, 0}; auto const & d = b; for (auto && [x, y, z] : c9::zip(a, d, c)) { z = x + y; } auto expected = std::vector<int>{2, 4, 6, 8, 10}; assert(c == expected); }
c++
code
505
186
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ############################################################################## */ #ifndef DALDAP_HPP #define DALDAP_HPP interface IUserDescriptor; #define DLF_ENABLED 0x01 #define DLF_SAFE 0x02 #define DLF_SCOPESCANS 0x04 interface IDaliLdapConnection: extends IInterface { virtual SecAccessFlags getPermissions(const char *key,const char *obj,IUserDescriptor *udesc,unsigned auditflags,const char * reqSignature, CDateTime & reqUTCTimestamp)=0; virtual bool checkScopeScans() = 0; virtual unsigned getLDAPflags() = 0; virtual void setLDAPflags(unsigned flags) = 0; virtual bool clearPermissionsCache(IUserDescriptor *udesc) = 0; virtual bool enableScopeScans(IUserDescriptor *udesc, bool enable, int *err) = 0; }; extern IDaliLdapConnection *createDaliLdapConnection(IPropertyTree *proptree); #endif
c++
code
1,545
394
/* * Copyright (c) 2019, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <algorithm> #include <iostream> #include <random> #include <string> #include <vector> #include <cuda_runtime.h> #include <cudf/cudf.h> /**---------------------------------------------------------------------------* * @brief Checks if a file exists. *---------------------------------------------------------------------------**/ bool checkFile(std::string const &fname); /**---------------------------------------------------------------------------* * @brief Check a string gdf_column, including the type and values. *---------------------------------------------------------------------------**/ void checkStrColumn(gdf_column const *col, std::vector<std::string> const &refs); /**---------------------------------------------------------------------------* * @brief Generates the specified number of random values of type T. *---------------------------------------------------------------------------**/ template <typename T> inline auto random_values(size_t size) { std::vector<T> values(size); using uniform_distribution = typename std::conditional<std::is_integral<T>::value, std::uniform_int_distribution<T>, std::uniform_real_distribution<T>>::type; static constexpr auto seed = 0xf00d; static std::mt19937 engine{seed}; static uniform_distribution dist{}; std::generate_n(values.begin(), size, [&]() { return dist(engine); }); return values; } /**---------------------------------------------------------------------------* * @brief Simple test internal helper class to transfer cudf column data * from device to host for test comparisons and debugging/development. *---------------------------------------------------------------------------**/ template <typename T> class gdf_host_column { public: gdf_host_column() = delete; explicit gdf_host_column(const gdf_column *col) { m_hostdata = std::vector<T>(col->size); cudaMemcpy(m_hostdata.data(), col->data, sizeof(T) * col->size, cudaMemcpyDeviceToHost); } auto hostdata() const -> const auto & { return m_hostdata; } void print() const { for (size_t i = 0; i < m_hostdata.size(); ++i) { std::cout.precision(17); std::cout << "[" << i << "]: value=" << m_hostdata[i] << "\n"; } } private: std::vector<T> m_hostdata; };
c++
code
2,944
874
// Copyright (c) 2017-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <index/txindex.h> #include <shutdown.h> #include <ui_interface.h> #include <util.h> #include <validation.h> #include <boost/thread.hpp> constexpr char DB_BEST_BLOCK = 'B'; constexpr char DB_TXINDEX = 't'; constexpr char DB_TXINDEX_BLOCK = 'T'; std::unique_ptr<TxIndex> g_txindex; struct CDiskTxPos : public CDiskBlockPos { unsigned int nTxOffset; // after header ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITEAS(CDiskBlockPos, *this); READWRITE(VARINT(nTxOffset)); } CDiskTxPos(const CDiskBlockPos& blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) { } CDiskTxPos() { SetNull(); } void SetNull() { CDiskBlockPos::SetNull(); nTxOffset = 0; } }; /** * Access to the txindex database (indexes/txindex/) * * The database stores a block locator of the chain the database is synced to * so that the TxIndex can efficiently determine the point it last stopped at. * A locator is used instead of a simple hash of the chain tip because blocks * and block index entries may not be flushed to disk until after this database * is updated. */ class TxIndex::DB : public BaseIndex::DB { public: explicit DB(size_t n_cache_size, bool f_memory = false, bool f_wipe = false); /// Read the disk location of the transaction data with the given hash. Returns false if the /// transaction hash is not indexed. bool ReadTxPos(const uint256& txid, CDiskTxPos& pos) const; /// Write a batch of transaction positions to the DB. bool WriteTxs(const std::vector<std::pair<uint256, CDiskTxPos>>& v_pos); /// Migrate txindex data from the block tree DB, where it may be for older nodes that have not /// been upgraded yet to the new database. bool MigrateData(CBlockTreeDB& block_tree_db, const CBlockLocator& best_locator); }; TxIndex::DB::DB(size_t n_cache_size, bool f_memory, bool f_wipe) : BaseIndex::DB(GetDataDir() / "indexes" / "txindex", n_cache_size, f_memory, f_wipe) { } bool TxIndex::DB::ReadTxPos(const uint256& txid, CDiskTxPos& pos) const { return Read(std::make_pair(DB_TXINDEX, txid), pos); } bool TxIndex::DB::WriteTxs(const std::vector<std::pair<uint256, CDiskTxPos>>& v_pos) { CDBBatch batch(*this); for (const auto& tuple : v_pos) { batch.Write(std::make_pair(DB_TXINDEX, tuple.first), tuple.second); } return WriteBatch(batch); } /* * Safely persist a transfer of data from the old txindex database to the new one, and compact the * range of keys updated. This is used internally by MigrateData. */ static void WriteTxIndexMigrationBatches(CDBWrapper& newdb, CDBWrapper& olddb, CDBBatch& batch_newdb, CDBBatch& batch_olddb, const std::pair<unsigned char, uint256>& begin_key, const std::pair<unsigned char, uint256>& end_key) { // Sync new DB changes to disk before deleting from old DB. newdb.WriteBatch(batch_newdb, /*fSync=*/true); olddb.WriteBatch(batch_olddb); olddb.CompactRange(begin_key, end_key); batch_newdb.Clear(); batch_olddb.Clear(); } bool TxIndex::DB::MigrateData(CBlockTreeDB& block_tree_db, const CBlockLocator& best_locator) { // The prior implementation of txindex was always in sync with block index // and presence was indicated with a boolean DB flag. If the flag is set, // this means the txindex from a previous version is valid and in sync with // the chain tip. The first step of the migration is to unset the flag and // write the chain hash to a separate key, DB_TXINDEX_BLOCK. After that, the // index entries are copied over in batches to the new database. Finally, // DB_TXINDEX_BLOCK is erased from the old database and the block hash is // written to the new database. // // Unsetting the boolean flag ensures that if the node is downgraded to a // previous version, it will not see a corrupted, partially migrated index // -- it will see that the txindex is disabled. When the node is upgraded // again, the migration will pick up where it left off and sync to the block // with hash DB_TXINDEX_BLOCK. bool f_legacy_flag = false; block_tree_db.ReadFlag("txindex", f_legacy_flag); if (f_legacy_flag) { if (!block_tree_db.Write(DB_TXINDEX_BLOCK, best_locator)) { return error("%s: cannot write block indicator", __func__); } if (!block_tree_db.WriteFlag("txindex", false)) { return error("%s: cannot write block index db flag", __func__); } } CBlockLocator locator; if (!block_tree_db.Read(DB_TXINDEX_BLOCK, locator)) { return true; } int64_t count = 0; LogPrintf("Upgrading txindex database... [0%%]\n"); uiInterface.ShowProgress(_("Upgrading txindex database"), 0, true); int report_done = 0; const size_t batch_size = 1 << 24; // 16 MiB CDBBatch batch_newdb(*this); CDBBatch batch_olddb(block_tree_db); std::pair<unsigned char, uint256> key; std::pair<unsigned char, uint256> begin_key{DB_TXINDEX, uint256()}; std::pair<unsigned char, uint256> prev_key = begin_key; bool interrupted = false; std::unique_ptr<CDBIterator> cursor(block_tree_db.NewIterator()); for (cursor->Seek(begin_key); cursor->Valid(); cursor->Next()) { boost::this_thread::interruption_point(); if (ShutdownRequested()) { interrupted = true; break; } if (!cursor->GetKey(key)) { return error("%s: cannot get key from valid cursor", __func__); } if (key.first != DB_TXINDEX) { break; } // Log progress every 10%. if (++count % 256 == 0) { // Since txids are uniformly random and traversed in increasing order, the high 16 bits // of the hash can be used to estimate the current progress. const uint256& txid = key.second; uint32_t high_nibble = (static_cast<uint32_t>(*(txid.begin() + 0)) << 8) + (static_cast<uint32_t>(*(txid.begin() + 1)) << 0); int percentage_done = (int)(high_nibble * 100.0 / 65536.0 + 0.5); uiInterface.ShowProgress(_("Upgrading txindex database"), percentage_done, true); if (report_done < percentage_done / 10) { LogPrintf("Upgrading txindex database... [%d%%]\n", percentage_done); report_done = percentage_done / 10; } } CDiskTxPos value; if (!cursor->GetValue(value)) { return error("%s: cannot parse txindex record", __func__); } batch_newdb.Write(key, value); batch_olddb.Erase(key); if (batch_newdb.SizeEstimate() > batch_size || batch_olddb.SizeEstimate() > batch_size) { // NOTE: it's OK to delete the key pointed at by the current DB cursor while iterating // because LevelDB iterators are guaranteed to provide a consistent view of the // underlying data, like a lightweight snapshot. WriteTxIndexMigrationBatches(*this, block_tree_db, batch_newdb, batch_olddb, prev_key, key); prev_key = key; } } // If these final DB batches complete the migration, write the best block // hash marker to the new database and delete from the old one. This signals // that the former is fully caught up to that point in the blockchain and // that all txindex entries have been removed from the latter. if (!interrupted) { batch_olddb.Erase(DB_TXINDEX_BLOCK); batch_newdb.Write(DB_BEST_BLOCK, locator); } WriteTxIndexMigrationBatches(*this, block_tree_db, batch_newdb, batch_olddb, begin_key, key); if (interrupted) { LogPrintf("[CANCELLED].\n"); return false; } uiInterface.ShowProgress("", 100, false); LogPrintf("[DONE].\n"); return true; } TxIndex::TxIndex(size_t n_cache_size, bool f_memory, bool f_wipe) : m_db(MakeUnique<TxIndex::DB>(n_cache_size, f_memory, f_wipe)) { } TxIndex::~TxIndex() {} bool TxIndex::Init() { LOCK(cs_main); // Attempt to migrate txindex from the old database to the new one. Even if // chain_tip is null, the node could be reindexing and we still want to // delete txindex records in the old database. if (!m_db->MigrateData(*pblocktree, chainActive.GetLocator())) { return false; } return BaseIndex::Init(); } bool TxIndex::WriteBlock(const CBlock& block, const CBlockIndex* pindex) { CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size())); std::vector<std::pair<uint256, CDiskTxPos>> vPos; vPos.reserve(block.vtx.size()); for (const auto& tx : block.vtx) { vPos.emplace_back(tx->GetHash(), pos); pos.nTxOffset += ::GetSerializeSize(*tx, SER_DISK, CLIENT_VERSION); } return m_db->WriteTxs(vPos); } BaseIndex::DB& TxIndex::GetDB() const { return *m_db; } bool TxIndex::FindTx(const uint256& tx_hash, uint256& block_hash, CTransactionRef& tx) const { CDiskTxPos postx; if (!m_db->ReadTxPos(tx_hash, postx)) { return false; } CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION); if (file.IsNull()) { return error("%s: OpenBlockFile failed", __func__); } CBlockHeader header; try { file >> header; if (fseek(file.Get(), postx.nTxOffset, SEEK_CUR)) { return error("%s: fseek(...) failed", __func__); } file >> tx; } catch (const std::exception& e) { return error("%s: Deserialize or I/O error - %s", __func__, e.what()); } if (tx->GetHash() != tx_hash) { return error("%s: txid mismatch", __func__); } block_hash = header.GetHash(); return true; }
c++
code
10,188
2,190
/**************************************************************************** * Copyright (C) from 2009 to Present EPAM Systems. * * This file is part of Indigo toolkit. * * 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 "molecule/base_molecule.h" #include "base_cpp/crc32.h" #include "base_cpp/output.h" #include "base_cpp/scanner.h" #include "molecule/elements.h" #include "molecule/molecule_arom_match.h" #include "molecule/molecule_exact_matcher.h" #include "molecule/molecule_exact_substructure_matcher.h" #include "molecule/molecule_substructure_matcher.h" #include "molecule/query_molecule.h" #include "molecule/smiles_loader.h" #include "molecule/inchi_wrapper.h" #include "molecule/molecule_tautomer_enumerator.h" #include "molecule/smiles_saver.h" #include "graph/dfs_walk.h" using namespace indigo; IMPL_ERROR(BaseMolecule, "molecule"); BaseMolecule::BaseMolecule() { _edit_revision = 0; } BaseMolecule::~BaseMolecule() { } Molecule& BaseMolecule::asMolecule() { throw Error("casting to molecule is invalid"); } QueryMolecule& BaseMolecule::asQueryMolecule() { throw Error("casting to query molecule is invalid"); } bool BaseMolecule::isQueryMolecule() { return false; } void BaseMolecule::clear() { have_xyz = false; name.clear(); _chiral_flag = -1; stereocenters.clear(); cis_trans.clear(); allene_stereo.clear(); rgroups.clear(); _xyz.clear(); _rsite_attachment_points.clear(); _attachment_index.clear(); sgroups.clear(); tgroups.clear(); template_attachment_points.clear(); Graph::clear(); _hl_atoms.clear(); _hl_bonds.clear(); _bond_directions.clear(); custom_collections.clear(); reaction_atom_mapping.clear(); reaction_atom_inversion.clear(); reaction_atom_exact_change.clear(); reaction_bond_reacting_center.clear(); use_scsr_sgroups_only = false; remove_scsr_lgrp = false; use_scsr_name = false; expand_mod_templates = false; ignore_chem_templates = false; updateEditRevision(); } bool BaseMolecule::hasCoord(BaseMolecule& mol) { int i; for (i = mol.vertexBegin(); i != mol.vertexEnd(); i = mol.vertexNext(i)) { Vec3f& xyz = mol.getAtomXyz(i); if (fabs(xyz.x) > 0.001 || fabs(xyz.y) > 0.001 || fabs(xyz.z) > 0.001) return true; } return false; } bool BaseMolecule::hasZCoord(BaseMolecule& mol) { int i; for (i = mol.vertexBegin(); i != mol.vertexEnd(); i = mol.vertexNext(i)) if (fabs(mol.getAtomXyz(i).z) > 0.001) return true; return false; } void BaseMolecule::mergeSGroupsWithSubmolecule(BaseMolecule& mol, Array<int>& mapping) { QS_DEF(Array<int>, edge_mapping); edge_mapping.clear_resize(mol.edgeEnd()); edge_mapping.fffill(); buildEdgeMapping(mol, &mapping, &edge_mapping); mergeSGroupsWithSubmolecule(mol, mapping, edge_mapping); } void BaseMolecule::mergeSGroupsWithSubmolecule(BaseMolecule& mol, Array<int>& mapping, Array<int>& edge_mapping) { int i; for (i = mol.sgroups.begin(); i != mol.sgroups.end(); i = mol.sgroups.next(i)) { SGroup& supersg = mol.sgroups.getSGroup(i); int idx = sgroups.addSGroup(supersg.sgroup_type); SGroup& sg = sgroups.getSGroup(idx); sg.parent_idx = supersg.parent_idx; if (_mergeSGroupWithSubmolecule(sg, supersg, mol, mapping, edge_mapping)) { if (sg.sgroup_type == SGroup::SG_TYPE_DAT) { DataSGroup& dg = (DataSGroup&)sg; DataSGroup& superdg = (DataSGroup&)supersg; dg.detached = superdg.detached; dg.display_pos = superdg.display_pos; dg.data.copy(superdg.data); dg.dasp_pos = superdg.dasp_pos; dg.relative = superdg.relative; dg.display_units = superdg.display_units; dg.description.copy(superdg.description); dg.name.copy(superdg.name); dg.type.copy(superdg.type); dg.querycode.copy(superdg.querycode); dg.queryoper.copy(superdg.queryoper); dg.num_chars = superdg.num_chars; dg.tag = superdg.tag; } else if (sg.sgroup_type == SGroup::SG_TYPE_SUP) { Superatom& sa = (Superatom&)sg; Superatom& supersa = (Superatom&)supersg; if (supersa.bond_connections.size() > 0) { for (int j = 0; j < supersa.bond_connections.size(); j++) { if (supersa.bond_connections[j].bond_idx > -1 && edge_mapping[supersa.bond_connections[j].bond_idx] > -1) { Superatom::_BondConnection& bond = sa.bond_connections.push(); bond.bond_dir = supersa.bond_connections[j].bond_dir; bond.bond_idx = edge_mapping[supersa.bond_connections[j].bond_idx]; } } } sa.subscript.copy(supersa.subscript); sa.sa_class.copy(supersa.sa_class); sa.sa_natreplace.copy(supersa.sa_natreplace); sa.contracted = supersa.contracted; if (supersa.attachment_points.size() > 0) { for (int j = supersa.attachment_points.begin(); j < supersa.attachment_points.end(); j = supersa.attachment_points.next(j)) { int ap_idx = sa.attachment_points.add(); Superatom::_AttachmentPoint& ap = sa.attachment_points.at(ap_idx); int a_idx = supersa.attachment_points[j].aidx; if (a_idx > -1) ap.aidx = mapping[a_idx]; else ap.aidx = a_idx; int leave_idx = supersa.attachment_points[j].lvidx; if (leave_idx > -1) ap.lvidx = mapping[leave_idx]; else ap.lvidx = leave_idx; ap.apid.copy(supersa.attachment_points[j].apid); } } } else if (sg.sgroup_type == SGroup::SG_TYPE_SRU) { RepeatingUnit& ru = (RepeatingUnit&)sg; RepeatingUnit& superru = (RepeatingUnit&)supersg; ru.connectivity = superru.connectivity; ru.subscript.copy(superru.subscript); } else if (sg.sgroup_type == SGroup::SG_TYPE_MUL) { MultipleGroup& mg = (MultipleGroup&)sg; MultipleGroup& supermg = (MultipleGroup&)supersg; mg.multiplier = supermg.multiplier; for (int j = 0; j != supermg.parent_atoms.size(); j++) if (mapping[supermg.parent_atoms[j]] >= 0) mg.parent_atoms.push(mapping[supermg.parent_atoms[j]]); } } else { sgroups.remove(idx); } } } void BaseMolecule::clearSGroups() { sgroups.clear(); } void BaseMolecule::_mergeWithSubmolecule_Sub(BaseMolecule& mol, const Array<int>& vertices, const Array<int>* edges, Array<int>& mapping, Array<int>& edge_mapping, int skip_flags) { QS_DEF(Array<char>, apid); int i; // XYZ _xyz.resize(vertexEnd()); if (!(skip_flags & SKIP_XYZ)) { if (vertexCount() == 0) have_xyz = mol.have_xyz; else have_xyz = have_xyz || mol.have_xyz; for (i = mol.vertexBegin(); i != mol.vertexEnd(); i = mol.vertexNext(i)) { if (mapping[i] < 0) continue; _xyz[mapping[i]] = mol.getAtomXyz(i); } } else _xyz.zerofill(); reaction_atom_mapping.expandFill(vertexEnd(), 0); reaction_atom_inversion.expandFill(vertexEnd(), 0); reaction_atom_exact_change.expandFill(vertexEnd(), 0); reaction_bond_reacting_center.expandFill(edgeEnd(), 0); for (i = mol.vertexBegin(); i != mol.vertexEnd(); i = mol.vertexNext(i)) { if (mapping[i] < 0) continue; reaction_atom_mapping[mapping[i]] = mol.reaction_atom_mapping[i]; reaction_atom_inversion[mapping[i]] = mol.reaction_atom_inversion[i]; reaction_atom_exact_change[mapping[i]] = mol.reaction_atom_exact_change[i]; } for (int j = mol.edgeBegin(); j != mol.edgeEnd(); j = mol.edgeNext(j)) { const Edge& edge = mol.getEdge(j); if ((mapping[edge.beg] > -1) && (mapping[edge.end] > -1)) { int bond_idx = findEdgeIndex(mapping[edge.beg], mapping[edge.end]); if (bond_idx > -1) reaction_bond_reacting_center[bond_idx] = mol.reaction_bond_reacting_center[j]; } } _bond_directions.expandFill(mol.edgeEnd(), 0); // trick for molecules with incorrect stereochemistry, of which we do permutations if (vertexCount() == mol.vertexCount() && edgeCount() == mol.edgeCount()) { for (int j = mol.edgeBegin(); j != mol.edgeEnd(); j = mol.edgeNext(j)) { const Edge& edge = mol.getEdge(j); if (mol.getBondDirection(j) != 0) _bond_directions[findEdgeIndex(mapping[edge.beg], mapping[edge.end])] = mol.getBondDirection(j); } } // RGroups if (!(skip_flags & SKIP_RGROUPS)) { rgroups.copyRGroupsFromMolecule(mol.rgroups); for (i = 0; i < vertices.size(); i++) { if (!mol.isRSite(vertices[i])) continue; int atom_idx = mapping[vertices[i]]; if (atom_idx == -1) continue; if (mol._rsite_attachment_points.size() <= vertices[i]) continue; Array<int>& ap = mol._rsite_attachment_points[vertices[i]]; int j; for (j = 0; j < ap.size(); j++) if (ap[j] >= 0 && ap[j] < mapping.size() && mapping[ap[j]] >= 0) setRSiteAttachmentOrder(atom_idx, mapping[ap[j]], j); } } if (!(skip_flags & SKIP_ATTACHMENT_POINTS)) { if (mol.attachmentPointCount() > 0) { for (i = 1; i <= mol.attachmentPointCount(); i++) { int att_idx; int j; for (j = 0; (att_idx = mol.getAttachmentPoint(i, j)) != -1; j++) if (mapping[att_idx] != -1) this->addAttachmentPoint(i, mapping[att_idx]); } } } if (!(skip_flags & SKIP_TGROUPS)) { tgroups.copyTGroupsFromMolecule(mol.tgroups); } if (!(skip_flags & SKIP_TEMPLATE_ATTACHMENT_POINTS)) { for (i = 0; i < vertices.size(); i++) { if (mol.isTemplateAtom(vertices[i])) { for (int j = 0; j < mol.getTemplateAtomAttachmentPointsCount(vertices[i]); j++) { if ((mol.getTemplateAtomAttachmentPoint(vertices[i], j) != -1) && (mapping[mol.getTemplateAtomAttachmentPoint(vertices[i], j)] != -1)) { mol.getTemplateAtomAttachmentPointId(vertices[i], j, apid); setTemplateAtomAttachmentOrder(mapping[vertices[i]], mapping[mol.getTemplateAtomAttachmentPoint(vertices[i], j)], apid.ptr()); } } } } } // SGroups merging mergeSGroupsWithSubmolecule(mol, mapping, edge_mapping); // highlighting highlightSubmolecule(mol, mapping.ptr(), false); // subclass stuff (Molecule or QueryMolecule) _mergeWithSubmolecule(mol, vertices, edges, mapping, skip_flags); // stereo if (!(skip_flags & SKIP_STEREOCENTERS)) buildOnSubmoleculeStereocenters(mol, mapping.ptr()); else stereocenters.clear(); if (!(skip_flags & SKIP_CIS_TRANS)) buildOnSubmoleculeCisTrans(mol, mapping.ptr()); else cis_trans.clear(); buildOnSubmoleculeAlleneStereo(mol, mapping.ptr()); // subclass stuff (Molecule or QueryMolecule) _postMergeWithSubmolecule(mol, vertices, edges, mapping, skip_flags); updateEditRevision(); } void BaseMolecule::_flipSGroupBond(SGroup& sgroup, int src_bond_idx, int new_bond_idx) { int idx = sgroup.bonds.find(src_bond_idx); if (idx != -1) sgroup.bonds[idx] = new_bond_idx; } void BaseMolecule::_flipSuperatomBond(Superatom& sa, int src_bond_idx, int new_bond_idx) { if (sa.bond_connections.size() > 0) { for (int j = 0; j < sa.bond_connections.size(); j++) { Superatom::_BondConnection& bond = sa.bond_connections[j]; if (bond.bond_idx == src_bond_idx) bond.bond_idx = new_bond_idx; } } if (sa.attachment_points.size() > 0) { for (int j = sa.attachment_points.begin(); j != sa.attachment_points.end(); j = sa.attachment_points.next(j)) { Superatom::_AttachmentPoint& ap = sa.attachment_points.at(j); const Edge& edge = getEdge(new_bond_idx); if ((edge.beg == ap.aidx) || (edge.end == ap.aidx)) { int ap_aidx = -1; int ap_lvidx = -1; if (sa.atoms.find(edge.beg) != -1) { ap_aidx = edge.beg; ap_lvidx = edge.end; } else if (sa.atoms.find(edge.end) != -1) { ap_aidx = edge.end; ap_lvidx = edge.beg; } ap.aidx = ap_aidx; ap.lvidx = ap_lvidx; } } } } void BaseMolecule::_flipTemplateAtomAttachmentPoint(int idx, int atom_from, Array<char>& ap_id, int atom_to) { for (int j = template_attachment_points.begin(); j != template_attachment_points.end(); j = template_attachment_points.next(j)) { BaseMolecule::TemplateAttPoint& ap = template_attachment_points.at(j); if ((ap.ap_occur_idx == idx) && (ap.ap_aidx == atom_from) && (ap.ap_id.memcmp(ap_id) == 0)) { ap.ap_aidx = atom_to; } } } void BaseMolecule::mergeWithSubmolecule(BaseMolecule& mol, const Array<int>& vertices, const Array<int>* edges, Array<int>* mapping_out, int skip_flags) { QS_DEF(Array<int>, tmp_mapping); QS_DEF(Array<int>, edge_mapping); if (mapping_out == 0) mapping_out = &tmp_mapping; // vertices and edges _mergeWithSubgraph(mol, vertices, edges, mapping_out, &edge_mapping); // all the chemical stuff _mergeWithSubmolecule_Sub(mol, vertices, edges, *mapping_out, edge_mapping, skip_flags); } int BaseMolecule::mergeAtoms(int atom1, int atom2) { updateEditRevision(); const Vertex& v1 = getVertex(atom1); const Vertex& v2 = getVertex(atom2); int is_tetra1 = false, is_cs1 = false, cs_bond1_idx = -1; int is_tetra2 = false, is_cs2 = false, cs_bond2_idx = -1; if (stereocenters.exists(atom1)) is_tetra1 = true; if (stereocenters.exists(atom2)) is_tetra2 = true; for (int i = v1.neiBegin(); i != v1.neiEnd(); i = v1.neiNext(i)) if (MoleculeCisTrans::isGeomStereoBond(*this, v1.neiEdge(i), NULL, false)) { cs_bond1_idx = v1.neiEdge(i); is_cs1 = true; break; } for (int i = v2.neiBegin(); i != v2.neiEnd(); i = v2.neiNext(i)) if (MoleculeCisTrans::isGeomStereoBond(*this, v2.neiEdge(i), NULL, false)) { cs_bond2_idx = v2.neiEdge(i); is_cs2 = true; break; } if (((is_tetra1 || is_cs1) && (is_tetra2 || is_cs2)) || (!is_tetra1 && !is_cs1 && !is_tetra2 && !is_cs2)) { if (is_tetra1) stereocenters.remove(atom1); if (is_cs1) cis_trans.setParity(cs_bond1_idx, 0); if (is_tetra2) stereocenters.remove(atom2); if (is_cs2) cis_trans.setParity(cs_bond2_idx, 0); QS_DEF(Array<int>, neighbors); neighbors.clear(); for (int i = v2.neiBegin(); i != v2.neiEnd(); i = v2.neiNext(i)) neighbors.push(v2.neiVertex(i)); for (int i = 0; i < neighbors.size(); i++) if (findEdgeIndex(neighbors[i], atom1) == -1) flipBond(neighbors[i], atom2, atom1); removeAtom(atom2); return atom1; } if (is_tetra1 || is_cs1) { if (v2.degree() > 1) return -1; if (is_tetra1 && stereocenters.getPyramid(atom1)[3] != -1) return -1; if (is_cs1 && v1.degree() != 2) return -1; flipBond(v2.neiVertex(v2.neiBegin()), atom2, atom1); removeAtom(atom2); return atom1; } else { if (v1.degree() > 1) return -1; if (is_tetra2 && stereocenters.getPyramid(atom2)[3] != -1) return -1; if (is_cs2 && v2.degree() != 2) return -1; flipBond(v1.neiVertex(v1.neiBegin()), atom1, atom2); removeAtom(atom1); return atom2; } } void BaseMolecule::flipBond(int atom_parent, int atom_from, int atom_to) { stereocenters.flipBond(atom_parent, atom_from, atom_to); cis_trans.flipBond(*this, atom_parent, atom_from, atom_to); // subclass (Molecule or QueryMolecule) adds the new bond _flipBond(atom_parent, atom_from, atom_to); int src_bond_idx = findEdgeIndex(atom_parent, atom_from); removeEdge(src_bond_idx); int new_bond_idx = findEdgeIndex(atom_parent, atom_to); // Clear bond direction because sterecenters // should mark bond directions properly setBondDirection(new_bond_idx, 0); // sgroups int j; for (j = sgroups.begin(); j != sgroups.end(); j = sgroups.next(j)) { SGroup& sg = sgroups.getSGroup(j); _flipSGroupBond(sg, src_bond_idx, new_bond_idx); if (sg.sgroup_type == SGroup::SG_TYPE_SUP) _flipSuperatomBond((Superatom&)sg, src_bond_idx, new_bond_idx); } updateEditRevision(); } void BaseMolecule::makeSubmolecule(BaseMolecule& mol, const Array<int>& vertices, Array<int>* mapping_out, int skip_flags) { clear(); mergeWithSubmolecule(mol, vertices, 0, mapping_out, skip_flags); } void BaseMolecule::makeSubmolecule(BaseMolecule& other, const Filter& filter, Array<int>* mapping_out, Array<int>* inv_mapping, int skip_flags) { QS_DEF(Array<int>, vertices); if (mapping_out == 0) mapping_out = &vertices; filter.collectGraphVertices(other, *mapping_out); makeSubmolecule(other, *mapping_out, inv_mapping, skip_flags); } void BaseMolecule::makeEdgeSubmolecule(BaseMolecule& mol, const Array<int>& vertices, const Array<int>& edges, Array<int>* v_mapping, int skip_flags) { clear(); mergeWithSubmolecule(mol, vertices, &edges, v_mapping, skip_flags); } void BaseMolecule::clone(BaseMolecule& other, Array<int>* mapping, Array<int>* inv_mapping, int skip_flags) { QS_DEF(Array<int>, tmp_mapping); if (mapping == 0) mapping = &tmp_mapping; mapping->clear
c++
code
20,000
4,333
#include <Eigen/Dense> #include <iostream> #include <ancse/config.hpp> #include <ancse/polynomial_basis.hpp> #include <ancse/dg_handler.hpp> #include <ancse/dg_limiting.hpp> #include <ancse/cfl_condition.hpp> #include <ancse/dg_rate_of_change.hpp> #include <ancse/snapshot_writer.hpp> #include <ancse/time_loop.hpp> static int n_vars = 3; template<class F> Eigen::MatrixXd ic(const F &f, const Grid &grid, const PolynomialBasis &poly_basis, const DGHandler &dg_handler) { int n_coeff = 1 + poly_basis.get_degree(); Eigen::MatrixXd u0 = Eigen::MatrixXd::Zero (n_vars*n_coeff, grid.n_cells); auto [quad_points, quad_weights] = dg_handler.get_quadrature(); int n_quad = static_cast<int>(quad_points.size()); /// eval basis and its derivate for all quadrature points Eigen::MatrixXd basis(n_coeff, n_quad); for (int k = 0; k < n_quad; k++) { basis.col(k) = poly_basis(quad_points(k)); } // L2-projection for (int j = 0; j < grid.n_cells; ++j) { for (int k = 0; k < quad_points.size(); k++) { auto fVal = f(cell_point(grid, j, quad_points(k))); for (int i = 0; i < n_vars; i++) { u0.col(j).segment(i*n_coeff, n_coeff) += quad_weights(k)*fVal(i)*basis.col(k); } } } return u0*grid.dx; } TimeLoop make_dg(const nlohmann::json &config, const Grid &grid, const PolynomialBasis &poly_basis, const DGHandler &dg_handler, std::shared_ptr<Model> &model) { double t_end = config["t_end"]; double cfl_number = config["cfl_number"]; auto n_ghost = grid.n_ghost; auto n_cells = grid.n_cells; auto n_vars = model->get_nvars(); int n_coeff = 1 + poly_basis.get_degree(); auto simulation_time = std::make_shared<SimulationTime>(t_end); auto boundary_condition = make_boundary_condition(n_ghost, config["boundary_condition"]); auto dg_rate_of_change = make_dg_rate_of_change(config, grid, model, poly_basis, dg_handler, simulation_time); auto dg_limiting = make_dg_limiting(config, grid, dg_handler); auto time_integrator = make_runge_kutta(config, dg_rate_of_change, boundary_condition, dg_limiting, n_vars*n_coeff, n_cells); auto cfl_condition = make_cfl_condition(grid, model, dg_handler, cfl_number); auto snapshot_writer = std::make_shared<JSONSnapshotWriter <DG>> (grid, model, dg_handler, simulation_time, std::string(config["output_dir"]), std::string(config["output_file"])); return TimeLoop(simulation_time, time_integrator, cfl_condition, snapshot_writer); } void sod_shock_tube_test(const nlohmann::json &config) { int deg = int(config["degree"]); double gamma = 7./5.; std::shared_ptr<Model> model = std::make_shared<Euler>(); auto model_euler = dynamic_cast<Euler*>(model.get()); model_euler->set_gamma(gamma); auto fn = [gamma](double x) { Eigen::VectorXd u(n_vars); if (x <= 0.5) { // left state u(0) = 1; u(1) = 0; u(2) = 1/(gamma-1); } else { // right state u(0) = 0.125; u(1) = 0; u(2) = 0.1/(gamma-1); } return u; }; int n_ghost = config["n_ghost"]; int n_cells = int(config["n_interior_cells"]) + n_ghost * 2; auto grid = Grid({0.0, 1.0}, n_cells, n_ghost); auto poly_basis = PolynomialBasis(deg, 1./sqrt(grid.dx)); auto dg_handler = DGHandler(model, grid, poly_basis); auto u0 = ic(fn, grid, poly_basis, dg_handler); auto dg = make_dg(config, grid, poly_basis, dg_handler, model); dg(u0); } int main(int argc, char* const argv[]) { nlohmann::json config; std::string fileName; if (argc == 2) { fileName = argv[1]; } else { fileName = "../config.json"; } config = get_config (fileName); std::string ic_key = config["initial_conditions"]; if (ic_key == "sod_shock_tube") { sod_shock_tube_test(config); } return 0; }
c++
code
4,561
939
/** * \file src/core/impl/graph/seq_sublinear_memory.cpp * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2020 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include "./seq_sublinear_memory.h" #if MGB_ENABLE_SUBLINEAR using namespace mgb; using namespace cg; #include "megbrain/comp_node_env.h" #include "megbrain/plugin/opr_footprint.h" #include "megbrain/serialization/opr_shallow_copy.h" #include "megbrain/system.h" #include "megbrain/utils/arith_helper.h" #include "megbrain/utils/mempool.h" #include "megbrain/utils/timer.h" #include <cmath> #include <random> namespace { class RNGxorshf { uint64_t s[2]; public: #if __cplusplus >= 201703L typedef uint64_t result_type; static constexpr uint64_t min() { return 0; } static constexpr uint64_t max() { return UINT64_MAX; } #endif RNGxorshf(uint64_t seed) { std::mt19937_64 gen(seed); s[0] = gen(); s[1] = gen(); } uint64_t operator()() { uint64_t x = s[0]; uint64_t const y = s[1]; s[0] = y; x ^= x << 23; // a s[1] = x ^ y ^ (x >> 17) ^ (y >> 26); // b, c return s[1] + y; } }; bool is_bad_opr(OperatorNodeBase* opr) { using F = OperatorNodeBase::NodeProp::Flag; return opr->node_prop().contain( F::IMPURE_FUNC | F::NO_AUTOMATIC_DUP | F::FORCE_UPDATE_INPUT_VAR); } } // namespace /* ====================== Abstract Opr & Var ====================== */ struct SeqModifierForSublinearMemory::Opr { OperatorNodeBase* const orig_opr; std::vector<Var*> input, output; const size_t time; //!< index in opr sequence const bool is_endpoint; //! input vars that have been discarded and need to be recomputed before //! this opr; for internal use by apply_discard_plan() std::vector<Var*> inputs_to_recompute; //! new oprs to be inserted before this opr; setup by apply_discard_plan() std::vector<MemPool<Opr>::UniquePtr> oprs_insert_before; //! [begin, end) interval of *time* for oprs belonging to this block; setup //! by make_discard_plan() size_t block_begin_time = 0, block_end_time = 0; Opr(OperatorNodeBase* opr, size_t t) : orig_opr{opr}, time{t}, is_endpoint{opr->owner_graph() ->options() .opr_attribute.get_sublinear_memory_endpoint( opr)} {} }; struct SeqModifierForSublinearMemory::Var { //! write or read access of a var struct AccessRecord { Opr* const opr; const size_t time; size_t stride; //!< time distance until next read; 0 for last access explicit AccessRecord(Opr* o = nullptr) : opr{o}, time{o->time}, stride{0} {} }; VarNode* const orig_var; const size_t size; //!< memory usage in bytes of this var //! access_rec[0] is the creation opr, and others are reader oprs std::vector<AccessRecord> access_rec; /*! * An index in access_rec * * if valid, then the var should be discarded after * discard_tailing_access->opr finishes * * setup by make_discard_plan */ Maybe<size_t> discard_tailing_access; /*! * An index in access_rec * maintained during make_discard_plan(), for the next access relative to * current operator */ Maybe<size_t> next_access; AccessRecord* visit_discard_tailing_access() { return discard_tailing_access.valid() ? &access_rec.at(discard_tailing_access.val()) : nullptr; } AccessRecord* visit_next_access() { return next_access.valid() ? &access_rec.at(next_access.val()) : nullptr; } auto owner_opr() const { return access_rec[0].opr; } auto last_access_opr() const { return access_rec.back().opr; } Var(VarNode* var, size_t s, Opr* opr) : orig_var{var}, size{s} { access_rec.emplace_back(opr); } }; /* ====================== ModifyActionPlanner ====================== */ class SeqModifierForSublinearMemory::ModifyActionPlanner { //! special creation time used for oprs duplicated from others static constexpr size_t DUPOPR_TIME = std::numeric_limits<size_t>::max() - 1; using VarArray = std::vector<Var*>; using VarSet = ThinHashSet<Var*>; using OprArray = std::vector<Opr*>; const SeqModifierForSublinearMemory* const m_par_modifier; const OprNodeArray* m_orig_opr_seq; MemPool<Var> m_var_mempool; MemPool<Opr> m_opr_mempool; std::vector<MemPool<Var>::UniquePtr> m_var_storage; std::vector<MemPool<Opr>::UniquePtr> m_seq; size_t m_nr_endpoint_oprs = 0; VarSet m_prev_block_discard_vars; std::vector<OprArray> m_blocks; //! split_point_set to block void split_into_blocks(const SplitPointSet& split_point_set); //! setup Var::discard_tailing_access void make_discard_plan(); //! modify oprs and vars according to Var::discard_tailing_access void apply_discard_plan(); /*! * \brief cleanup request for discarding vars that are immediately * accessed in the next block * \param all_inputs all oprs in this block * \param discard_vars vars discarded after this block; this sequence * may be modified inplace, but the resulting value has no * specific meaning for the caller (i.e. as temporary var) */ void refine_block_discard_rec(const OprArray& all_oprs, size_t block_num, VarSet& discard_vars); size_t calc_bottleneck_from_discard_plan(); public: ModifyActionPlanner(SeqModifierForSublinearMemory* par) : m_par_modifier{par} {} ~ModifyActionPlanner() noexcept { m_opr_mempool.disable_freelist(); m_var_mempool.disable_freelist(); } //! init m_orig_opr_seq from opr_seq, should be called first. void init_seq(const OprNodeArray& opr_seq); //! generate split point set from thresh SplitPointSet get_split_point_set(size_t block_size_thresh); /*! * \brief get memory bottleneck after imposing a block size threshold * * The result can be retrieved by get_prev_action() */ size_t get_memory_bottleneck(const SplitPointSet& split_point_set); //! get action for previous get_memory_bottleneck() call void get_prev_action(SeqModifyAction& action); }; void SeqModifierForSublinearMemory::ModifyActionPlanner::get_prev_action( SeqModifyAction& action) { action.clear(); for (auto&& opr : m_seq) { auto&& arr = opr->oprs_insert_before; if (arr.empty()) continue; auto&& dest = action[opr->orig_opr]; dest.reserve(arr.size()); for (auto&& i : opr->oprs_insert_before) dest.push_back(i->orig_opr); } } size_t SeqModifierForSublinearMemory::ModifyActionPlanner::get_memory_bottleneck( const SplitPointSet& split_point_set) { split_into_blocks(split_point_set); make_discard_plan(); apply_discard_plan(); return calc_bottleneck_from_discard_plan(); } SeqModifierForSublinearMemory::SplitPointSet SeqModifierForSublinearMemory::ModifyActionPlanner::get_split_point_set( size_t block_size_thresh) { auto split_point_set = make_split_point_set(); size_t cur_block_usage = 0; ThinHashSet<Var*> cur_block_alive_vars; auto add_alive = [&](Var* var) { auto&& ins = cur_block_alive_vars.insert(var); mgb_assert(ins.second); cur_block_usage += var->size; }; auto remove_alive = [&](Var* var) { if (cur_block_alive_vars.erase(var)) { auto size = var->size; mgb_assert(size <= cur_block_usage); cur_block_usage -= size; } }; auto flush_block_member = [&](size_t p) { split_point_set->push_back(p); cur_block_usage = 0; cur_block_alive_vars.clear(); }; for (size_t i = 0; i < m_seq.size(); ++i) { auto opr = m_seq[i].get(); for (auto i : opr->output) add_alive(i); for (auto i : opr->input) { if (opr == i->last_access_opr()) remove_alive(i); } if (i + 1 < m_seq.size() && (cur_block_usage < block_size_thresh || (m_nr_endpoint_oprs && !opr->is_endpoint))) continue; flush_block_member(i); } return split_point_set; } void SeqModifierForSublinearMemory::ModifyActionPlanner::init_seq( const OprNodeArray& opr_seq) { m_orig_opr_seq = &opr_seq; m_var_storage.clear(); m_seq.clear(); m_var_mempool.reorder_free(); m_opr_mempool.reorder_free(); m_nr_endpoint_oprs = 0; ThinHashMap<VarNode*, Var*> varmap; for (auto orig_opr : *m_orig_opr_seq) { auto time = m_seq.size(); m_seq.emplace_back(m_opr_mempool.alloc_unique(orig_opr, time)); auto opr = m_seq.back().get(); m_nr_endpoint_oprs += opr->is_endpoint; for (auto&& dep : orig_opr->node_prop().dep_map()) { if (!OperatorNodeBase::NodeProp::is_device_value_dep(dep.second)) continue; auto iter = varmap.find(dep.first); if (iter == varmap.end()) { // input var needs not to be considered continue; } auto ivar = iter->second; bool exist = false; for (auto i : opr->input) { if (i == ivar) { exist = true; break; } } if (exist) { // same var for different inputs continue; } opr->input.push_back(ivar); auto&& prev_rec = ivar->access_rec.back(); prev_rec.stride = time - prev_rec.opr->time; ivar->access_rec.emplace_back(opr); } for (auto i : orig_opr->output()) { auto var2memsize = m_par_modifier->m_mem_opt.var2memsize(); auto iter = var2memsize->find(i); if (iter == var2memsize->end()) { // some vars are ignored; see split_into_cn2oprseq() continue; } m_var_storage.emplace_back( m_var_mempool.alloc_unique(i, iter->second, opr)); auto ovar = m_var_storage.back().get(); varmap[i] = ovar; opr->output.push_back(ovar); } mgb_assert(!opr->output.empty()); } // remove unused output for (auto&& i : m_seq) { auto&& oarr = i->output; for (size_t j = 0; j < oarr.size();) { if (oarr[j]->access_rec.size() == 1) { std::swap(oarr[j], oarr.back()); oarr.pop_back(); } else ++j; } } } size_t SeqModifierForSublinearMemory::ModifyActionPlanner:: calc_bottleneck_from_discard_plan() { size_t cur_usage = 0, max_usage = 0; size_t time = 0; // map from var to insert time // use unordered_map<> in dbg because ThinHashMap does not support copy ThinHashMap<Var*, size_t> alive_vars; auto remove_alive = [&](Opr* opr, const std::vector<Var*>& vars) { for (auto i : vars) { if (opr == i->last_access_opr()) { cur_usage -= i->size; auto nr = alive_vars.erase(i); mgb_assert(nr == 1); } } }; auto process_opr = [&](Opr* opr) { for (auto i : opr->output) { cur_usage += i->size; auto&& ins = alive_vars.insert({i, time}); mgb_assert(ins.second); } update_max(max_usage, cur_usage); if (opr->output.size() > 1) { // a single output may be unused if this opr has multiple outputs // and some of them are discarded remove_alive(opr, opr->output); } remove_alive(opr, opr->input); ++time; }; for (auto&& opr : m_seq) { for (auto&& i : opr->oprs_insert_before) process_opr(i.get()); process_opr(opr.get()); } mgb_assert(alive_vars.empty()); return max_usage; } void SeqModifierForSublinearMemory::ModifyActionPlanner::apply_discard_plan() { ThinHashSet<Var*> alive_vars; // map from original var to duplicated var ThinHashMap<Var*, Var*> var_map; auto add_alive = [&](Var* var) { auto&& ins = alive_vars.insert(var); mgb_assert(ins.second); }; auto remove_alive = [&](Var* var) { auto nr = alive_vars.erase(var); mgb_assert(nr); }; auto check_and_remove = [&](size_t timestamp, Var* var) { auto acc = var->visit_discard_tailing_access(); if (!acc || (acc && acc->opr->time >= timestamp)) { mgb_assert(var->owner_opr()->output.size() > 1); for (size_t i = 0; i < var->access_rec.size(); ++ i) { if (var->access_rec[i].time >= timestamp) { mgb_assert(i > 0); auto acc_rec_begin = var->access_rec.data(); var->access_rec.resize(i); var->discard_tailing_access = i - 1; mgb_assert(var->access_rec.data() == acc_rec_begin); break; } } } }; auto try_discard = [&](Opr* opr, Var* var) { auto acc = var->visit_discard_tailing_access(); if (acc && acc->opr == opr) { remove_alive(var); acc[1].opr->inputs_to_recompute.push_back(var); auto acc_rec_begin = var->access_rec.data(); // make this opr as the last reader for original var var->access_rec.resize(acc - acc_rec_begin + 1); mgb_assert(var->access_rec.data() == acc_rec_begin); } }; // recompute a var by inserting new oprs auto recompute = [&](Opr* reader, Var* var) { mgb_assert(!alive_vars.count(var)); auto block_begin = var->owner_opr()->block_begin_time, block_end = var->owner_opr()->block_end_time; thin_function<Var*(Var*)> add_dep; add_dep = [&](Var* var) { if (alive_vars.count(var)) return var; { auto iter = var_map.find(var); if (iter != var_map.end()) return iter->second; } auto opr = var->owner_opr(); if (opr->time < block_begin) { // do not recompute vars outside this block return var; } if (is_bad_opr(opr->orig_opr)) { return var; } mgb_assert(opr->time < block_end); auto new_opr_storage = m_opr_mempool.alloc_unique( opr->orig_opr, static_cast<size_t>(DUPOPR_TIME)); auto new_opr = new_opr_storage.get(); new_opr->input.reserve(opr->input.size()); new_opr->output.reserve(opr->output.size()); for (auto i : opr->input) { auto ivar = add_dep(i); new_opr->input.push_back(ivar); ivar->access_rec.emplace_back(new_opr); } reader->oprs_insert_before.emplace_back(std::move(new_opr_storage)); Var* new_var = nullptr; for (auto i : opr->output) { auto&& ovar = m_var_mempool.alloc_unique(i->orig_var, i->size, new_opr); new_opr->output.push_back(ovar.get()); if (i == var) new_var = ovar.get(); add_alive(ovar.get()); auto ins = var_map.insert({i, ovar.get()}); mgb_assert(ins.second); m_var_storage.emplace_back(std::move(ovar)); } mgb_assert(new_var); return new_var; }; add_dep(var); }; for (auto&& _raw_opr : m_seq) { auto opr = _raw_opr.get(); for (auto i : opr->inputs_to_recompute) recompute(opr, i); for (auto&& i : opr->input) { // find in recomputed vars and record access auto iter = var_map.find(i); if (iter != var_map.end()) { // handle the vars which haven't been discard after recomputing // try to remove access records which redirect to dup-opr check_and_remove(opr->time, i); i = iter->second; i->access_rec.emplace_back(opr); mgb_assert(alive_vars.count(i)); continue; } if (opr == i->last_access_opr()) { remove_alive(i); } else { try_discard(opr, i); } } for (auto i : opr->output) { add_alive(i); try_discard(opr, i); } } } void SeqModifierForSublinearMemory::ModifyActionPlanner::make_discard_plan() { ThinHashSet<Var*> cur_block_alive_vars; std::vector<Opr*> cur_block_member; VarSet cur_block_discard_vars; size_t nr_blocks = 0; auto flush_block_member = [&]() { nr_blocks++; auto begin = cur_block_member.front()->time, end = cur_block_member.back()->time + 1; for (auto i : cur_block_member) { i->block_begin_time = begin; i->block_end_time = end; } cur_block_member.clear(); cur_block_alive_vars.clear(); cur_block_discard_vars.clear(); }; for (auto&& block : m_blocks) { for (auto&& opr : block) { cur_block_member.push_back(opr); for (auto i : opr->output) { cur_block_alive_vars.insert(i); i->next_access = 1; } for (auto i : opr->input) { if (opr == i->last_access_opr()) { cur_block_alive_vars.erase(i); i->next_access = None; } else if (opr == i->visit_next_access()->opr) { ++i->next_access.val(); } } } // TODO: should rewrite for multi-outputs opr // This loop only make sense for single-output oprs. Since all oprs // only recompute once, it should serach best recomputing-time in opr-level // rather than find best discarding-time in var-level for multi-outputs opr. for (auto var : cur_block_alive_vars) { if (is_bad_opr(var->owner_opr()->orig_opr)) continue; Var::AccessRecord* best = nullptr; auto&& rec = var->access_rec; mgb_assert(var->next_access.val() >= 1); // find best future time to discard for (size_t i = var->next_access.val() - 1; i < rec.size() - 1; ++i) { if (!i && var->owner_opr()->output.size() == 1) { // never discard output var directly continue; } auto cur = &rec[i], next = &rec[i + 1]; if (cur->stride > next->opr->input.size()) { if (!best || cur->stride > best->stride) best = cur; } else { // if cur stride too small, it would be immediately used by // next and should not be discarded } } if (best) { var->discard_tailing_access = best
c++
code
20,000
3,961
/// @file #include <iostream> #include <meta-lexer.hpp> #include <input-resolver.hpp> #include <fstream> #include <sstream> #include <shared.hpp> int main() { const char rules_file_path[] = PROJECT_ROOT "/data/rules3.txt"; const char code_file_path[] = PROJECT_ROOT "/data/code3.txt"; // 创建解析器对象 InputFileResolver resolver; // 通过解析文件,得到语言的所有规则。包括词法规则和语法规则 Rules rules; // 错误代码,0为成功 int errcode = resolver.resolve_input_file(rules_file_path, rules); if (errcode) { // 若有错误,就输出错误消息,退出程序 std::cout << resolver.diag_msg << std::endl; return 1; } // 创建词法分析器 Lexer lexer(rules.lexer_rules); // 读取文件到字符串 std::string test_code = read_file_into_string(code_file_path); // 词法分析 std::vector<Token> tokens; errcode = lexer.analyze(test_code, tokens); if (errcode) { std::cout << lexer.diag_msg; } // 下面都是输出 for (auto &&token : tokens) { std::string token_content( test_code.begin() + token.begin, // token.begin 是单词的开始在test_code中的下标(从0开始) test_code.begin() + token.end); // token.end 是单词的结尾后一个字符test_code中的下标(从0开始) std::cout << token_content << ": " << resolver.symbol_name(token.id) << std::endl; } return 0; }
c++
code
1,282
251
/* * If not stated otherwise in this file or this component's Licenses.txt file the * following copyright and licenses apply: * * Copyright 2016 RDK Management * * 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 Components_SPDIF.cpp * @brief This source file contains the APIs of TR069 Components SBDIF. */ /** * @defgroup tr69hostif * @{ * @defgroup hostif * @{ **/ #include "dsTypes.h" #include "illegalArgumentException.hpp" #include "exception.hpp" #include "Components_SPDIF.h" #include "safec_lib.h" #define DEV_NAME "SPDIF" #define BASE_NAME "Device.Services.STBService.1.Components.SPDIF" #define UPDATE_FORMAT_STRING "%s.%d.%s" #define ENABLE_STRING "Enable" #define STATUS_STRING "Status" #define ALIAS_STRING "Alias" #define NAME_STRING "Name" #define FORCEPCM_STRING "ForcePCM" #define PASSTHROUGH_STRING "Passthrough" #define AUDIODELAY_STRING "AudioDelay" #define ENABLED_STRING "Enabled" #define DISABLED_STRING "Disabled" GHashTable * hostIf_STBServiceSPDIF::ifHash = NULL; GMutex * hostIf_STBServiceSPDIF::m_mutex = NULL; hostIf_STBServiceSPDIF* hostIf_STBServiceSPDIF::getInstance(int dev_id) { hostIf_STBServiceSPDIF* pRet = NULL; if(ifHash) { pRet = (hostIf_STBServiceSPDIF *)g_hash_table_lookup(ifHash,(gpointer) dev_id); } else { ifHash = g_hash_table_new(NULL,NULL); } if(!pRet) { try { pRet = new hostIf_STBServiceSPDIF(dev_id, device::Host::getInstance().getAudioOutputPort(std::string("SPDIF").append(int_to_string(dev_id-1)))); g_hash_table_insert(ifHash, (gpointer)dev_id, pRet); } catch (const device::IllegalArgumentException &e) { RDK_LOG(RDK_LOG_WARN,LOG_TR69HOSTIF,"Caught device::IllegalArgumentException, not able create STB service %s Interface instance %d..\n", DEV_NAME, dev_id); } catch (const int &e) { RDK_LOG(RDK_LOG_WARN,LOG_TR69HOSTIF,"Caught exception, not able create STB service %s Interface instance %d..\n", DEV_NAME, dev_id); } catch (const dsError_t &e) { RDK_LOG(RDK_LOG_ERROR,LOG_TR69HOSTIF,"Caught dsError_t %d, not able create STB service %s Interface instance %d..\n", e, DEV_NAME, dev_id); } catch (const device::Exception &e) { RDK_LOG(RDK_LOG_WARN,LOG_TR69HOSTIF,"Caught device::Exception %d \"%s\", not able create STB service %s Interface instance %d..\n", e.getCode(), e.getMessage().c_str(), DEV_NAME, dev_id); } } return pRet; } GList* hostIf_STBServiceSPDIF::getAllInstances() { if(ifHash) return g_hash_table_get_keys(ifHash); return NULL; } void hostIf_STBServiceSPDIF::closeInstance(hostIf_STBServiceSPDIF *pDev) { if(pDev) { g_hash_table_remove(ifHash, (gconstpointer)pDev->dev_id); delete pDev; } } void hostIf_STBServiceSPDIF::closeAllInstances() { if(ifHash) { GList* tmp_list = g_hash_table_get_values (ifHash); while(tmp_list) { hostIf_STBServiceSPDIF* pDev = (hostIf_STBServiceSPDIF *)tmp_list->data; tmp_list = tmp_list->next; closeInstance(pDev); } } } void hostIf_STBServiceSPDIF::getLock() { if(!m_mutex) { m_mutex = g_mutex_new(); } g_mutex_lock(m_mutex); } void hostIf_STBServiceSPDIF::releaseLock() { g_mutex_unlock(m_mutex); } /** * @brief Class Constructor of the class hostIf_STBServiceSPDIF. * * It will initialize the device id and audio output port. * * @param[in] devid Identification number of the device. * @param[in] port Audio output port number. */ hostIf_STBServiceSPDIF::hostIf_STBServiceSPDIF(int devid, device::AudioOutputPort& port) : dev_id(devid), aPort(port) { backupEnable = false; errno_t rc = -1; rc=strcpy_s(backupStatus,sizeof(backupStatus), " "); if(rc!=EOK) { ERR_CHK(rc); } backupForcePCM = false; backupPassthrough = false; backupAudioDelay = 0; bCalledEnable = false; bCalledStatus = false; bCalledAlias = false; bCalledName = false; bCalledForcePCM = false; bCalledPassthrough = false; bCalledAudioDelay = false; } /** * @brief This function set the SPDIF interface updates such as Enable, Status, Alias, * Name, ForcePCM, Pass through, AudioDelay in a connected SPDIF port. Currently ForcePCM * is handled. * * @param[in] paramName SPDIF service name string. * @param[in] stMsgData HostIf Message Request param contains the SPDIF attribute value. * * @return Returns an Integer value. * @retval 0 If successfully set the hostIf SPDIF interface attribute. * @retval -1 If Not able to set the hostIf SPDIF interface attribute. * @retval -2 If Not handle the hostIf SPDIF interface attribute. * @ingroup TR69_HOSTIF_STBSERVICES_SPDIF_API */ int hostIf_STBServiceSPDIF::handleSetMsg(const char *paramName, HOSTIF_MsgData_t *stMsgData) { int ret = NOT_HANDLED; if (strcasecmp(paramName, FORCEPCM_STRING) == 0) { ret = setForcePCM(stMsgData); } return ret; } /** * @brief This function get the SPDIF interface updates such as Enable, Status, Alias, * Name, ForcePCM, Pass through, AudioDelay in a connected SPDIF port. * * @param[in] paramName SPDIF service name string. * @param[in] stMsgData HostIf Message Request param contains the SPDIF attribute value. * * @return Returns an Integer value. * @retval 0 If successfully get the hostIf SPDIF interface attribute. * @retval -1 If Not able to get the hostIf SPDIF interface attribute. * @retval -2 If Not handle the hostIf SPDIF interface attribute. * @ingroup TR69_HOSTIF_STBSERVICES_SPDIF_API */ int hostIf_STBServiceSPDIF::handleGetMsg(const char *paramName, HOSTIF_MsgData_t *stMsgData) { int ret = NOT_HANDLED; if (strcasecmp(paramName, ENABLE_STRING) == 0) { ret = getEnable(stMsgData); } else if (strcasecmp(paramName, STATUS_STRING) == 0) { ret = getStatus(stMsgData); } else if (strcasecmp(paramName, ALIAS_STRING) == 0) { ret = getAlias(stMsgData); } else if (strcasecmp(paramName, NAME_STRING) == 0) { ret = getName(stMsgData); } else if (strcasecmp(paramName, FORCEPCM_STRING) == 0) { ret = getForcePCM(stMsgData); } else if (strcasecmp(paramName, PASSTHROUGH_STRING) == 0) { ret = getPassthrough(stMsgData); } else if (strcasecmp(paramName, AUDIODELAY_STRING) == 0) { ret = getAudioDelay(stMsgData); } return ret; } /** * @brief This function updates the SPDIF interface updates such as Enable, Status, Alias, * Name, ForcePCM, Pass through, AudioDelay in a connected SPDIF port. * * @param[in] mUpdateCallback Callback function which updates the hostIf SPDIF interface. * @ingroup TR69_HOSTIF_STBSERVICES_SPDIF_API */ void hostIf_STBServiceSPDIF::doUpdates(updateCallback mUpdateCallback) { HOSTIF_MsgData_t msgData; bool bChanged; char tmp_buff[PARAM_LEN]; memset(&msgData,0,sizeof(msgData)); memset(tmp_buff,0,PARAM_LEN); bChanged = false; msgData.instanceNum=dev_id; getEnable(&msgData,&bChanged); if(bChanged) { snprintf(tmp_buff, PARAM_LEN, UPDATE_FORMAT_STRING, BASE_NAME, dev_id, ENABLE_STRING); if(mUpdateCallback) { mUpdateCallback(IARM_BUS_TR69HOSTIFMGR_EVENT_VALUECHANGED,tmp_buff, msgData.paramValue, msgData.paramtype); } } memset(&msgData,0,sizeof(msgData)); memset(tmp_buff,0,PARAM_LEN); bChanged = false; msgData.instanceNum=dev_id; getStatus(&msgData,&bChanged); if(bChanged) { snprintf(tmp_buff, PARAM_LEN, UPDATE_FORMAT_STRING, BASE_NAME, dev_id, STATUS_STRING); if(mUpdateCallback) { mUpdateCallback(IARM_BUS_TR69HOSTIFMGR_EVENT_VALUECHANGED,tmp_buff, msgData.paramValue, msgData.paramtype); } } memset(&msgData,0,sizeof(msgData)); memset(tmp_buff,0,PARAM_LEN); bChanged = false; msgData.instanceNum=dev_id; getAlias(&msgData,&bChanged); if(bChanged) { snprintf(tmp_buff, PARAM_LEN, UPDATE_FORMAT_STRING, BASE_NAME, dev_id, ALIAS_STRING); if(mUpdateCallback) { mUpdateCallback(IARM_BUS_TR69HOSTIFMGR_EVENT_VALUECHANGED,tmp_buff, msgData.paramValue, msgData.paramtype); } } memset(&msgData,0,sizeof(msgData)); memset(tmp_buff,0,PARAM_LEN); bChanged = false; msgData.instanceNum=dev_id; getName(&msgData,&bChanged); if(bChanged) { snprintf(tmp_buff, PARAM_LEN, UPDATE_FORMAT_STRING, BASE_NAME, dev_id, NAME_STRING); if(mUpdateCallback) { mUpdateCallback(IARM_BUS_TR69HOSTIFMGR_EVENT_VALUECHANGED,tmp_buff, msgData.paramValue, msgData.paramtype); } } memset(&msgData,0,sizeof(msgData)); memset(tmp_buff,0,PARAM_LEN); bChanged = false; msgData.instanceNum=dev_id; getForcePCM(&msgData,&bChanged); if(bChanged) { snprintf(tmp_buff, PARAM_LEN, UPDATE_FORMAT_STRING, BASE_NAME, dev_id, FORCEPCM_STRING); if(mUpdateCallback) { mUpdateCallback(IARM_BUS_TR69HOSTIFMGR_EVENT_VALUECHANGED,tmp_buff, msgData.paramValue, msgData.paramtype); } } memset(&msgData,0,sizeof(msgData)); memset(tmp_buff,0,PARAM_LEN); bChanged = false; msgData.instanceNum=dev_id; getPassthrough(&msgData,&bChanged); if(bChanged) { snprintf(tmp_buff, PARAM_LEN, UPDATE_FORMAT_STRING, BASE_NAME, dev_id, PASSTHROUGH_STRING); if(mUpdateCallback) { mUpdateCallback(IARM_BUS_TR69HOSTIFMGR_EVENT_VALUECHANGED,tmp_buff, msgData.paramValue, msgData.paramtype); } } memset(&msgData,0,sizeof(msgData)); memset(tmp_buff,0,PARAM_LEN); bChanged = false; msgData.instanceNum=dev_id; getAudioDelay(&msgData,&bChanged); if(bChanged) { snprintf(tmp_buff, PARAM_LEN, UPDATE_FORMAT_STRING, BASE_NAME, dev_id, AUDIODELAY_STRING); if(mUpdateCallback) { mUpdateCallback(IARM_BUS_TR69HOSTIFMGR_EVENT_VALUECHANGED,tmp_buff, msgData.paramValue, msgData.paramtype); } } } int hostIf_STBServiceSPDIF::getNumberOfInstances(HOSTIF_MsgData_t *stMsgData) { int portCount = 0; device::List<device::AudioOutputPort> aPorts = device::Host::getInstance().getAudioOutputPorts(); for (int i = 0; i < aPorts.size() ; i++) //CID:18299 - UNINIT { if (strcasestr(aPorts.at(i).getName().c_str(), "spdif")) portCount++; } put_int(stMsgData->paramValue, portCount); stMsgData->paramtype = hostIf_UnsignedIntType; stMsgData->paramLen = sizeof(unsigned int); return OK; } // Private Impl below here. /************************************************************ * Description : Set device enable * Precondition : None * Input : stMsgData->paramValue -> 1 : Device is enabled. 0 : Device is disabled. * Return : OK -> Success NOK -> Failure ************************************************************/ int hostIf_STBServiceSPDIF::setEnable(HOSTIF_MsgData_t *stMsgData) { int ret = NOT_HANDLED; return ret; } /************************************************************ * Description : Set Alias for device * Precondition : None * Input : stMsgData->paramValue -> non volatile handle for this device. * Return : OK -> Success NOK -> Failure ************************************************************/ int hostIf_STBServiceSPDIF::setAlias(HOSTIF_MsgData_t *stMsgData) { int ret = NOT_HANDLED; return ret; } /************************************************************ * Description : Set ForcePCM * Precondition : None * Input : stMsgData->paramValue -> 1 : Force stream to be uncompressed. 0 : Allow compressed data to be sent. * Return : OK -> Success NOK -> Failure ************************************************************/ int hostIf_STBServiceSPDIF::setForcePCM(HOSTIF_MsgData_t *stMsgData) { int ret = OK; try { dsAudioEncoding_t newEncoding; if (*((bool *)stMsgData->paramValue)) newEncoding = dsAUDIO_ENC_PCM; else newEncoding = dsAUDIO_ENC_DISPLAY; aPort.setEncoding(newEncoding); } catch (const std::exception e) { RDK_LOG(RDK_LOG_WARN,LOG_TR69HOSTIF,"[%s] Exception: %s\r\n",__FUNCTION__, e.what()); ret = NOK; } return ret; } int hostIf_STBServiceSPDIF::getEnable(HOSTIF_MsgData_t *stMsgData, bool *pChanged) { int ret = NOT_HANDLED; return ret; } /************************************************************ * Description : Get status * Precondition : None * Input : stMsgData for result return. pChanged * Return : OK -> Success NOK -> Failure stMsgData->paramValue -> "Enabled", "Disabled" or "Error" ************************************************************/ int hostIf_STBServiceSPDIF::getStatus(HOSTIF_MsgData_t *stMsgData, bool *pChanged) { int ret = OK; // Since it's hard-coded. strncpy(stMsgData->paramValue, ENABLED_STRING, PARAM_LEN); stMsgData->paramValue[PARAM_LEN-1] = '\0'; stMsgData->paramtype = hostIf_StringType; stMsgData->paramLen = strlen(ENABLED_STRING); if(bCalledStatus && pChanged && strcmp(backupStatus, stMsgData->paramValue)) { *pChanged = true; } bCalledStatus = true; strncpy(backupStatus, stMsgData->paramValue, _BUF_LEN_16-1); backupStatus[_BUF_LEN_16-1] = '\0'; return ret; } /************************************************************ * Description : Get non volatile handle for device * Precondition : None * Input : stMsgData for result return. pChanged * Return : OK -> Success NOK -> Failure stMsgData->paramValue -> the alias value ************************************************************/ int hostIf_STBServiceSPDIF::getAlias(HOSTIF_MsgData_t *stMsgData, bool *pChanged) { int ret = NOT_HANDLED; return ret; } /************************************************************ * Description : Get human readable device name * Precondition : None * Input : stMsgData for result return. pChanged * Return : OK -> Success NOK -> Failure stMsgData->paramValue -> humaan readable name string. ************************************************************/ int hostIf_STBServiceSPDIF::getName(HOSTIF_MsgData_t *stMsgData, bool *pChanged) { int ret = NOT_HANDLED; return ret; } /************************************************************ * Description : Get ForcePCM setting * Precondition : None * Input : stMsgData for result return. pChanged * Return : OK -> Success NOK -> Failure stMsgData->paramValue -> 1 : Audio format is forced to be pcm 0 : Compressed audio may be sent through (passthrough) ************************************************************/ int hostIf_STBServiceSPDIF::getForcePCM(HOSTIF_MsgData_t *stMsgData, bool *pChanged) { int ret = OK; try { dsAudioEncoding_t newEncoding; if (aPort.getEncoding().getId() == dsAUDIO_ENC_PCM) { put_boolean(stMsgData->paramValue, true); } else { put_boolean(stMsgData->paramValue, false); } stMsgData->paramtype = hostIf_BooleanType; stMsgData->paramLen = sizeof(bool); if(bCalledForcePCM && pChanged && (backupForcePCM != get_boolean(stMsgData->paramValue))) { *pChanged = true; } bCalledForcePCM = true; backupForcePCM = get_boolean(stMsgData->paramValue); } catch (const std::exception e) { RDK_LOG(RDK_LOG_WARN,LOG_TR69HOSTIF,"[%s] Exception: %s\r\n",__FUNCTION__, e.what()); ret = NOK; } return ret; } /************************************************************ * Description : Get Passthrough * Precondition : None * Input : stMsgData for result return. pChanged * Return : OK -> Success NOK -> Failure stMsgData->paramValue -> 1 : Audio datastream is passed without decoding 0 : Audio stream is decoded ************************************************************/ int hostIf_STBServiceSPDIF::getPassthrough(HOSTIF_MsgData_t *stMsgData, bool *pChanged) { int ret = OK; try { dsAudioEncoding_t currentEncoding; currentEncoding = (dsAudioEncoding_t )aPort.getEncoding().getId(); if ((currentEncoding == dsAUDIO_ENC_DISPLAY) || (currentEncoding == dsAUDIO_ENC_AC3)) { put_boolean(stMsgData->paramValue, true); } else { put_boolean(stMsgData->paramValue, false); } stMsgData->paramtype = hostIf_BooleanType; stMsgData->paramLen = sizeof(bool); if(bCalledPassthrough && pChanged && (backupPassthrough != get_boolean(stMsgData->paramValue))) { *pChanged = true; } bCalledPassthrough = true; backupPassthrough = get_boolean(stMsgData->paramValue); } catch (const std::exception e) { RDK_LOG(RDK_LOG_WARN,LOG_TR69HOSTIF,"[%s] Exception: %s\r\n",__FUNCTION__, e.what()); ret = NOK; } return ret; } /************************************************************ * Description : Get Audio Delay * Precondition : None * Input : stMsgData for result return. pChanged * Return : OK -> Success NOK -> Failure stMsgData->paramValue -> Audio Delay ************************************************************/ int hostIf_STBServiceSPDIF::getAudioDelay(HOSTIF_MsgData_t *stMsgData, bool *pChanged) { int ret = NOT_HANDLED; return ret; } /** @} */ /** @} */
c++
code
18,878
4,398
// Copyright 2017 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "qemu-bus.h" #include <assert.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <zircon/threads.h> #include <ddk/binding.h> #include <ddk/debug.h> #include <ddk/device.h> #include <ddk/driver.h> #include <ddk/platform-defs.h> #include <ddk/protocol/platform/bus.h> #include <fbl/alloc_checker.h> namespace board_qemu_arm64 { static bool use_fake_display() { const char* ufd = getenv("driver.qemu_bus.use_fake_display"); return (ufd != nullptr && (!strcmp(ufd, "1") || !strcmp(ufd, "true") || !strcmp(ufd, "on"))); } int QemuArm64::Thread() { zx_status_t status; zxlogf(INFO, "qemu-bus thread running"); if (use_fake_display()) { status = DisplayInit(); if (status != ZX_OK) { zxlogf(ERROR, "%s: DisplayInit() failed %d\n", __func__, status); return thrd_error; } zxlogf(INFO, "qemu.use_fake_display=1, disabling goldfish-display"); setenv("driver.goldfish-display.disable", "true", 1); } status = PciInit(); if (status != ZX_OK) { zxlogf(ERROR, "%s: PciInit() failed %d\n", __func__, status); return thrd_error; } status = SysmemInit(); if (status != ZX_OK) { zxlogf(ERROR, "%s: SysmemInit() failed %d\n", __func__, status); return thrd_error; } status = PciAdd(); if (status != ZX_OK) { zxlogf(ERROR, "%s: PciAdd() failed %d\n", __func__, status); return thrd_error; } status = RtcInit(); if (status != ZX_OK) { zxlogf(ERROR, "%s: RtcInit() failed %d\n", __func__, status); return thrd_error; } return 0; } zx_status_t QemuArm64::Start() { auto cb = [](void* arg) -> int { return reinterpret_cast<QemuArm64*>(arg)->Thread(); }; int rc = thrd_create_with_name(&thread_, cb, this, "qemu-arm64"); return thrd_status_to_zx_status(rc); } zx_status_t QemuArm64::Create(void* ctx, zx_device_t* parent) { ddk::PBusProtocolClient pbus(parent); if (!pbus.is_valid()) { zxlogf(ERROR, "%s: Failed to get ZX_PROTOCOL_PBUS\n", __func__); return ZX_ERR_NO_RESOURCES; } fbl::AllocChecker ac; auto board = fbl::make_unique_checked<QemuArm64>(&ac, parent, pbus); if (!ac.check()) { return ZX_ERR_NO_MEMORY; } zx_status_t status; if ((status = board->DdkAdd("qemu-bus", DEVICE_ADD_NON_BINDABLE)) != ZX_OK) { zxlogf(ERROR, "%s: DdkAdd failed %d\n", __func__, status); return status; } if ((status = board->Start()) != ZX_OK) { return status; } __UNUSED auto* dummy = board.release(); return ZX_OK; } } // namespace board_qemu_arm64 static constexpr zx_driver_ops_t driver_ops = []() { zx_driver_ops_t ops = {}; ops.version = DRIVER_OPS_VERSION; ops.bind = board_qemu_arm64::QemuArm64::Create; return ops; }(); // clang-format off ZIRCON_DRIVER_BEGIN(qemu_bus, driver_ops, "zircon", "0.1", 3) BI_ABORT_IF(NE, BIND_PROTOCOL, ZX_PROTOCOL_PBUS), BI_ABORT_IF(NE, BIND_PLATFORM_DEV_VID, PDEV_VID_QEMU), BI_MATCH_IF(EQ, BIND_PLATFORM_DEV_PID, PDEV_PID_QEMU), ZIRCON_DRIVER_END(qemu_bus) //clang-format on
c++
code
3,203
758
#include <contracts.hpp> #include <eosio/asset.hpp> #include <eosio/eosio.hpp> #include <eosio/time.hpp> #include <eosio/transaction.hpp> #include <contracts.hpp> #include <utils.hpp> #include <tables/config_table.hpp> #include <tables/user_table.hpp> using namespace eosio; using std::string; using std::make_tuple; using std::distance; #define MOVE_REFERENDUM(from, to) { \ to.referendum_id = from->referendum_id; \ to.created_at = from->created_at; \ to.setting_value = from->setting_value; \ to.favour = from->favour; \ to.against = from->against; \ to.setting_name = from->setting_name; \ to.creator = from->creator; \ to.staked = from->staked; \ to.title = from->title; \ to.summary = from->summary; \ to.description = from->description; \ to.image = from->image; \ to.url = from->url; \ } CONTRACT referendums : public contract { public: using contract::contract; referendums(name receiver, name code, datastream<const char*> ds) : contract(receiver, code, ds), balances(receiver, receiver.value), config(contracts::settings, contracts::settings.value) {} ACTION reset(); ACTION create( name creator, name setting_name, uint64_t setting_value, string title, string summary, string description, string image, string url ); ACTION update( name creator, name setting_name, uint64_t setting_value, string title, string summary, string description, string image, string url ); ACTION cancel(uint64_t id); ACTION favour(name voter, uint64_t referendum_id, uint64_t amount); ACTION against(name voter, uint64_t referendum_id, uint64_t amount); ACTION stake(name from, name to, asset quantity, string memo); ACTION refundstake(name sponsor); ACTION addvoice(name account, uint64_t amount); ACTION updatevoice(uint64_t start, uint64_t batchsize); ACTION cancelvote(name voter, uint64_t referendum_id); ACTION onperiod(); private: symbol seeds_symbol = symbol("SEEDS", 4); static constexpr name high_impact = "high"_n; static constexpr name medium_impact = "med"_n; static constexpr name low_impact = "low"_n; void run_testing(); void run_active(); void run_staged(); void send_onperiod(); void send_refund_stake(name account, asset quantity); void send_burn_stake(asset quantity); void send_change_setting(name setting_name, uint64_t setting_value); void check_citizen(name account); void check_values(string title, string summary, string description, string image, string url); uint64_t get_quorum(const name & setting); uint64_t get_unity(const name & setting); TABLE voter_table { name account; uint64_t referendum_id; uint64_t amount; bool favoured; bool canceled; uint64_t primary_key()const { return account.value; } }; TABLE balance_table { name account; asset stake; uint64_t voice; uint64_t primary_key()const { return account.value; } }; TABLE referendum_table { uint64_t referendum_id; uint64_t created_at; uint64_t setting_value; uint64_t favour; uint64_t against; name setting_name; name creator; asset staked; string title; string summary; string description; string image; string url; uint64_t primary_key()const { return referendum_id; } uint64_t by_name()const { return setting_name.value; } }; DEFINE_CONFIG_TABLE DEFINE_CONFIG_TABLE_MULTI_INDEX TABLE fix_refs_table { uint64_t ref_id; string description; uint64_t primary_key()const { return ref_id; } }; typedef eosio::multi_index<"fixrefs"_n, fix_refs_table> fix_refs_tables; TABLE back_refs_table { uint64_t ref_id; string description; uint64_t primary_key()const { return ref_id; } }; typedef eosio::multi_index<"backrefs"_n, back_refs_table> back_refs_tables; typedef multi_index<"balances"_n, balance_table> balance_tables; typedef multi_index<"referendums"_n, referendum_table, indexed_by<"byname"_n, const_mem_fun<referendum_table, uint64_t, &referendum_table::by_name>> > referendum_tables; typedef multi_index<"voters"_n, voter_table> voter_tables; balance_tables balances; config_tables config; }; extern "C" void apply(uint64_t receiver, uint64_t code, uint64_t action) { if (action == name("transfer").value && code == contracts::token.value) { execute_action<referendums>(name(receiver), name(code), &referendums::stake); } else if (code == receiver) { switch (action) { EOSIO_DISPATCH_HELPER(referendums, (reset)(addvoice)(create)(update)(cancel)(favour)(against)(cancelvote)(onperiod)(updatevoice)(refundstake) ) } } }
c++
code
5,024
905
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/litedash-config.h" #endif #include "chainparams.h" #include "clientversion.h" #include "compat.h" #include "rpc/server.h" #include "init.h" #include "noui.h" #include "scheduler.h" #include "util.h" #include "masternodeconfig.h" #include "httpserver.h" #include "httprpc.h" #include "utilstrencodings.h" #include <boost/algorithm/string/predicate.hpp> #include <boost/filesystem.hpp> #include <boost/thread.hpp> #include <stdio.h> /* Introduction text for doxygen: */ /*! \mainpage Developer documentation * * \section intro_sec Introduction * * This is the developer documentation of the reference client for an experimental new digital currency called Dash (https://www.litedash.org/), * which enables instant payments to anyone, anywhere in the world. Dash uses peer-to-peer technology to operate * with no central authority: managing transactions and issuing money are carried out collectively by the network. * * The software is a community-driven open source project, released under the MIT license. * * \section Navigation * Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code. */ void WaitForShutdown(boost::thread_group* threadGroup) { bool fShutdown = ShutdownRequested(); // Tell the main threads to shutdown. while (!fShutdown) { MilliSleep(200); fShutdown = ShutdownRequested(); } if (threadGroup) { Interrupt(*threadGroup); threadGroup->join_all(); } } ////////////////////////////////////////////////////////////////////////////// // // Start // bool AppInit(int argc, char* argv[]) { boost::thread_group threadGroup; CScheduler scheduler; bool fRet = false; // // Parameters // // If Qt is used, parameters/litedash.conf are parsed in qt/litedash.cpp's main() ParseParameters(argc, argv); // Process help and version before taking care about datadir if (IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version")) { std::string strUsage = strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion() + "\n"; if (IsArgSet("-version")) { strUsage += FormatParagraph(LicenseInfo()); } else { strUsage += "\n" + _("Usage:") + "\n" + " dashd [options] " + strprintf(_("Start %s Daemon"), _(PACKAGE_NAME)) + "\n"; strUsage += "\n" + HelpMessage(HMM_BITCOIND); } fprintf(stdout, "%s", strUsage.c_str()); return true; } try { bool datadirFromCmdLine = IsArgSet("-datadir"); if (datadirFromCmdLine && !boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", GetArg("-datadir", "").c_str()); return false; } try { ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)); } catch (const std::exception& e) { fprintf(stderr,"Error reading configuration file: %s\n", e.what()); return false; } if (!datadirFromCmdLine && !boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" from config file does not exist.\n", GetArg("-datadir", "").c_str()); return EXIT_FAILURE; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { SelectParams(ChainNameFromCommandLine()); } catch (const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return false; } // parse masternode.conf std::string strErr; if(!masternodeConfig.read(strErr)) { fprintf(stderr,"Error reading masternode configuration file: %s\n", strErr.c_str()); return false; } // Command-line RPC bool fCommandLine = false; for (int i = 1; i < argc; i++) if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "litedash:")) fCommandLine = true; if (fCommandLine) { fprintf(stderr, "Error: There is no RPC client functionality in dashd anymore. Use the litedash-cli utility instead.\n"); exit(EXIT_FAILURE); } // -server defaults to true for bitcoind but not for the GUI so do this here SoftSetBoolArg("-server", true); // Set this early so that parameter interactions go to console InitLogging(); InitParameterInteraction(); if (!AppInitBasicSetup()) { // InitError will have been called with detailed error, which ends up on console exit(EXIT_FAILURE); } if (!AppInitParameterInteraction()) { // InitError will have been called with detailed error, which ends up on console exit(EXIT_FAILURE); } if (!AppInitSanityChecks()) { // InitError will have been called with detailed error, which ends up on console exit(EXIT_FAILURE); } if (GetBoolArg("-daemon", false)) { #if HAVE_DECL_DAEMON fprintf(stdout, "Dash Core server starting\n"); // Daemonize if (daemon(1, 0)) { // don't chdir (1), do close FDs (0) fprintf(stderr, "Error: daemon() failed: %s\n", strerror(errno)); return false; } #else fprintf(stderr, "Error: -daemon is not supported on this operating system\n"); return false; #endif // HAVE_DECL_DAEMON } fRet = AppInitMain(threadGroup, scheduler); } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(NULL, "AppInit()"); } if (!fRet) { Interrupt(threadGroup); // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of // the startup-failure cases to make sure they don't result in a hang due to some // thread-blocking-waiting-for-another-thread-during-startup case } else { WaitForShutdown(&threadGroup); } Shutdown(); return fRet; } int main(int argc, char* argv[]) { SetupEnvironment(); // Connect dashd signal handlers noui_connect(); return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE); }
c++
code
6,972
1,406
/* * This software is distributed under BSD 3-clause license (see LICENSE file). * * Authors: Soeren Sonnenburg, Evan Shelhamer, Bjoern Esser, Sergey Lisitsyn */ #include <stdio.h> #include <shogun/lib/config.h> #include <shogun/io/SGIO.h> #include <shogun/structure/Plif.h> #include <shogun/lib/memory.h> //#define PLIF_DEBUG using namespace shogun; Plif::Plif(int32_t l) : PlifBase() { limits=SGVector<float64_t>(); penalties=SGVector<float64_t>(); cum_derivatives=SGVector<float64_t>(); id=-1; transform=T_LINEAR; name=NULL; max_value=0; min_value=0; cache=NULL; use_svm=0; use_cache=false; len=0; do_calc = true; if (l>0) set_plif_length(l); } Plif::~Plif() { SG_FREE(name); SG_FREE(cache); } bool Plif::set_transform_type(const char *type_str) { invalidate_cache(); if (strcmp(type_str, "linear")==0) transform = T_LINEAR ; else if (strcmp(type_str, "")==0) transform = T_LINEAR ; else if (strcmp(type_str, "log")==0) transform = T_LOG ; else if (strcmp(type_str, "log(+1)")==0) transform = T_LOG_PLUS1 ; else if (strcmp(type_str, "log(+3)")==0) transform = T_LOG_PLUS3 ; else if (strcmp(type_str, "(+3)")==0) transform = T_LINEAR_PLUS3 ; else { error("unknown transform type ({})", type_str); return false ; } return true ; } void Plif::init_penalty_struct_cache() { if (!use_cache) return ; if (cache || use_svm) return ; if (max_value<=0) return ; float64_t* local_cache=SG_MALLOC(float64_t, ((int32_t) max_value) + 2); if (local_cache) { for (int32_t i=0; i<=max_value; i++) { if (i<min_value) local_cache[i] = -Math::INFTY ; else local_cache[i] = lookup_penalty(i, NULL) ; } } this->cache=local_cache ; } void Plif::set_plif_name(char *p_name) { SG_FREE(name); name=get_strdup(p_name); } char* Plif::get_plif_name() const { if (name) return name; else { char buf[20]; sprintf(buf, "plif%i", id); return get_strdup(buf); } } void Plif::delete_penalty_struct(std::vector<std::shared_ptr<Plif>>& PEN, int32_t P) { for (int32_t i=0; i<P; i++) PEN[i].reset(); PEN.clear(); } float64_t Plif::lookup_penalty_svm( float64_t p_value, float64_t *d_values) const { ASSERT(use_svm>0) float64_t d_value=d_values[use_svm-1] ; #ifdef PLIF_DEBUG io::print("{}.lookup_penalty_svm({})\n", get_name(), d_value); #endif if (!do_calc) return d_value; switch (transform) { case T_LINEAR: break ; case T_LOG: d_value = log(d_value) ; break ; case T_LOG_PLUS1: d_value = log(d_value+1) ; break ; case T_LOG_PLUS3: d_value = log(d_value+3) ; break ; case T_LINEAR_PLUS3: d_value = d_value+3 ; break ; default: error("unknown transform"); break ; } int32_t idx = 0 ; float64_t ret ; for (int32_t i=0; i<len; i++) if (limits[i]<=d_value) idx++ ; else break ; // assume it is monotonically increasing #ifdef PLIF_DEBUG io::print(" -> idx = {} ", idx); #endif if (idx==0) ret=penalties[0] ; else if (idx==len) ret=penalties[len-1] ; else { ret = (penalties[idx]*(d_value-limits[idx-1]) + penalties[idx-1]* (limits[idx]-d_value)) / (limits[idx]-limits[idx-1]) ; #ifdef PLIF_DEBUG io::print(" -> ({:1.3f}*{:1.3f}, {:1.3f}*{:1.3f})", (d_value-limits[idx-1])/(limits[idx]-limits[idx-1]), penalties[idx], (limits[idx]-d_value)/(limits[idx]-limits[idx-1]), penalties[idx-1]); #endif } #ifdef PLIF_DEBUG io::print(" -> ret={:1.3f}\n", ret); #endif return ret ; } float64_t Plif::lookup_penalty(int32_t p_value, float64_t* svm_values) const { if (use_svm) return lookup_penalty_svm(p_value, svm_values) ; if ((p_value<min_value) || (p_value>max_value)) { //io::print("Feature:{}, {}.lookup_penalty({}): return -inf min_value: {}, max_value: {}\n", name, get_name(), p_value, min_value, max_value); return -Math::INFTY ; } if (!do_calc) return p_value; if (cache!=NULL && (p_value>=0) && (p_value<=max_value)) { float64_t ret=cache[p_value] ; return ret ; } return lookup_penalty((float64_t) p_value, svm_values) ; } float64_t Plif::lookup_penalty(float64_t p_value, float64_t* svm_values) const { if (use_svm) return lookup_penalty_svm(p_value, svm_values) ; #ifdef PLIF_DEBUG io::print("{}.lookup_penalty({})\n", get_name(), p_value); #endif if ((p_value<min_value) || (p_value>max_value)) { //io::print("Feature:{}, {}.lookup_penalty({}): return -inf min_value: {}, max_value: {}\n", name, get_name(), p_value, min_value, max_value); return -Math::INFTY ; } if (!do_calc) return p_value; float64_t d_value = (float64_t) p_value ; switch (transform) { case T_LINEAR: break ; case T_LOG: d_value = log(d_value) ; break ; case T_LOG_PLUS1: d_value = log(d_value+1) ; break ; case T_LOG_PLUS3: d_value = log(d_value+3) ; break ; case T_LINEAR_PLUS3: d_value = d_value+3 ; break ; default: error("unknown transform"); break ; } #ifdef PLIF_DEBUG io::print(" -> value = {:1.4f} ", d_value); #endif int32_t idx = 0 ; float64_t ret ; for (int32_t i=0; i<len; i++) if (limits[i]<=d_value) idx++ ; else break ; // assume it is monotonically increasing #ifdef PLIF_DEBUG io::print(" -> idx = {} ", idx); #endif if (idx==0) ret=penalties[0] ; else if (idx==len) ret=penalties[len-1] ; else { ret = (penalties[idx]*(d_value-limits[idx-1]) + penalties[idx-1]* (limits[idx]-d_value)) / (limits[idx]-limits[idx-1]) ; #ifdef PLIF_DEBUG io::print(" -> ({:1.3f}*{:1.3f}, {:1.3f}*{:1.3f}) ", (d_value-limits[idx-1])/(limits[idx]-limits[idx-1]), penalties[idx], (limits[idx]-d_value)/(limits[idx]-limits[idx-1]), penalties[idx-1]); #endif } //if (p_value>=30 && p_value<150) //io::print("{} {}({}) -> {:1.2f}\n", PEN->name, p_value, idx, ret); #ifdef PLIF_DEBUG io::print(" -> ret={:1.3f}\n", ret); #endif return ret ; } void Plif::penalty_clear_derivative() { for (int32_t i=0; i<len; i++) cum_derivatives[i]=0.0 ; } void Plif::penalty_add_derivative(float64_t p_value, float64_t* svm_values, float64_t factor) { if (use_svm) { penalty_add_derivative_svm(p_value, svm_values, factor) ; return ; } if ((p_value<min_value) || (p_value>max_value)) { return ; } float64_t d_value = (float64_t) p_value ; switch (transform) { case T_LINEAR: break ; case T_LOG: d_value = log(d_value) ; break ; case T_LOG_PLUS1: d_value = log(d_value+1) ; break ; case T_LOG_PLUS3: d_value = log(d_value+3) ; break ; case T_LINEAR_PLUS3: d_value = d_value+3 ; break ; default: error("unknown transform"); break ; } int32_t idx = 0 ; for (int32_t i=0; i<len; i++) if (limits[i]<=d_value) idx++ ; else break ; // assume it is monotonically increasing if (idx==0) cum_derivatives[0]+= factor ; else if (idx==len) cum_derivatives[len-1]+= factor ; else { cum_derivatives[idx] += factor * (d_value-limits[idx-1])/(limits[idx]-limits[idx-1]) ; cum_derivatives[idx-1]+= factor*(limits[idx]-d_value)/(limits[idx]-limits[idx-1]) ; } } void Plif::penalty_add_derivative_svm(float64_t p_value, float64_t *d_values, float64_t factor) { ASSERT(use_svm>0) float64_t d_value=d_values[use_svm-1] ; if (d_value<-1e+20) return; switch (transform) { case T_LINEAR: break ; case T_LOG: d_value = log(d_value) ; break ; case T_LOG_PLUS1: d_value = log(d_value+1) ; break ; case T_LOG_PLUS3: d_value = log(d_value+3) ; break ; case T_LINEAR_PLUS3: d_value = d_value+3 ; break ; default: error("unknown transform"); break ; } int32_t idx = 0 ; for (int32_t i=0; i<len; i++) if (limits[i]<=d_value) idx++ ; else break ; // assume it is monotonically increasing if (idx==0) cum_derivatives[0]+=factor ; else if (idx==len) cum_derivatives[len-1]+=factor ; else { cum_derivatives[idx] += factor*(d_value-limits[idx-1])/(limits[idx]-limits[idx-1]) ; cum_derivatives[idx-1] += factor*(limits[idx]-d_value)/(limits[idx]-limits[idx-1]) ; } } void Plif::get_used_svms(int32_t* num_svms, int32_t* svm_ids) { if (use_svm) { svm_ids[(*num_svms)] = use_svm; (*num_svms)++; } io::print("->use_svm:{} plif_id:{} name:{} trans_type:{} ",use_svm, get_id(), get_name(), get_transform_type()); } bool Plif::get_do_calc() { return do_calc; } void Plif::set_do_calc(bool b) { do_calc = b;; }
c++
code
8,259
2,349
/* * 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. */ /*! * \file src/relay/doc.cc * \brief Doc ADT used for pretty printing. * * Reference: Philip Wadler. A Prettier Printer. Journal of Functional Programming'98 */ #include "doc.h" #include <tvm/runtime/packed_func.h> #include <sstream> #include <vector> namespace tvm { /*! * \brief Represent a piece of text in the doc. */ class DocTextNode : public DocAtomNode { public: /*! \brief The str content in the text. */ std::string str; explicit DocTextNode(std::string str_val) : str(str_val) {} static constexpr const char* _type_key = "printer.DocText"; TVM_DECLARE_FINAL_OBJECT_INFO(DocTextNode, DocAtomNode); }; TVM_REGISTER_OBJECT_TYPE(DocTextNode); class DocText : public DocAtom { public: explicit DocText(std::string str) { if (str.find_first_of("\t\n") != str.npos) { LOG(WARNING) << "text node: '" << str << "' should not have tab or newline."; } data_ = runtime::make_object<DocTextNode>(str); } TVM_DEFINE_OBJECT_REF_METHODS(DocText, DocAtom, DocTextNode); }; /*! * \brief Represent a line breaker in the doc. */ class DocLineNode : public DocAtomNode { public: /*! \brief The amount of indent in newline. */ int indent; explicit DocLineNode(int indent) : indent(indent) {} static constexpr const char* _type_key = "printer.DocLine"; TVM_DECLARE_FINAL_OBJECT_INFO(DocLineNode, DocAtomNode); }; TVM_REGISTER_OBJECT_TYPE(DocLineNode); class DocLine : public DocAtom { public: explicit DocLine(int indent) { data_ = runtime::make_object<DocLineNode>(indent); } TVM_DEFINE_OBJECT_REF_METHODS(DocLine, DocAtom, DocLineNode); }; // DSL function implementations Doc& Doc::operator<<(const Doc& right) { ICHECK(this != &right); this->stream_.insert(this->stream_.end(), right.stream_.begin(), right.stream_.end()); return *this; } Doc& Doc::operator<<(std::string right) { return *this << DocText(right); } Doc& Doc::operator<<(const DocAtom& right) { this->stream_.push_back(right); return *this; } std::string Doc::str() { std::ostringstream os; for (auto atom : this->stream_) { if (auto* text = atom.as<DocTextNode>()) { os << text->str; } else if (auto* line = atom.as<DocLineNode>()) { os << "\n" << std::string(line->indent, ' '); } else { LOG(FATAL) << "do not expect type " << atom->GetTypeKey(); } } return os.str(); } Doc Doc::NewLine(int indent) { return Doc() << DocLine(indent); } Doc Doc::Text(std::string text) { return Doc() << DocText(text); } Doc Doc::RawText(std::string text) { return Doc() << DocAtom(runtime::make_object<DocTextNode>(text)); } Doc Doc::Indent(int indent, Doc doc) { for (size_t i = 0; i < doc.stream_.size(); ++i) { if (auto* line = doc.stream_[i].as<DocLineNode>()) { doc.stream_[i] = DocLine(indent + line->indent); } } return doc; } Doc Doc::StrLiteral(const std::string& value, std::string quote) { // TODO(@M.K.): add escape. Doc doc; return doc << quote << value << quote; } Doc Doc::PyBoolLiteral(bool value) { if (value) { return Doc::Text("True"); } else { return Doc::Text("False"); } } Doc Doc::Brace(std::string open, const Doc& body, std::string close, int indent) { Doc doc; doc << open; doc << Indent(indent, NewLine() << body) << NewLine(); doc << close; return doc; } Doc Doc::Concat(const std::vector<Doc>& vec, const Doc& sep) { Doc seq; if (vec.size() != 0) { if (vec.size() == 1) return vec[0]; seq << vec[0]; for (size_t i = 1; i < vec.size(); ++i) { seq << sep << vec[i]; } } return seq; } } // namespace tvm
c++
code
4,404
1,165
// Copyright (c) 2013-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "consensus/validation.h" #include "data/sighash.json.h" #include "hash.h" #include "validation.h" // For CheckTransaction #include "random.h" #include "script/interpreter.h" #include "script/script.h" #include "serialize.h" #include "streams.h" #include "test/test_tour.h" #include "util.h" #include "utilstrencodings.h" #include "version.h" #include <iostream> #include <boost/test/unit_test.hpp> #include <univalue.h> extern UniValue read_json(const std::string& jsondata); // Old script.cpp SignatureHash function uint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType) { static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001")); if (nIn >= txTo.vin.size()) { printf("ERROR: SignatureHash(): nIn=%d out of range\n", nIn); return one; } CMutableTransaction txTmp(txTo); // In case concatenating two scripts ends up with two codeseparators, // or an extra one at the end, this prevents all those possible incompatibilities. scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR)); // Blank out other inputs' signatures for (unsigned int i = 0; i < txTmp.vin.size(); i++) txTmp.vin[i].scriptSig = CScript(); txTmp.vin[nIn].scriptSig = scriptCode; // Blank out some of the outputs if ((nHashType & 0x1f) == SIGHASH_NONE) { // Wildcard payee txTmp.vout.clear(); // Let the others update at will for (unsigned int i = 0; i < txTmp.vin.size(); i++) if (i != nIn) txTmp.vin[i].nSequence = 0; } else if ((nHashType & 0x1f) == SIGHASH_SINGLE) { // Only lock-in the txout payee at same index as txin unsigned int nOut = nIn; if (nOut >= txTmp.vout.size()) { printf("ERROR: SignatureHash(): nOut=%d out of range\n", nOut); return one; } txTmp.vout.resize(nOut+1); for (unsigned int i = 0; i < nOut; i++) txTmp.vout[i].SetNull(); // Let the others update at will for (unsigned int i = 0; i < txTmp.vin.size(); i++) if (i != nIn) txTmp.vin[i].nSequence = 0; } // Blank out other inputs completely, not recommended for open transactions if (nHashType & SIGHASH_ANYONECANPAY) { txTmp.vin[0] = txTmp.vin[nIn]; txTmp.vin.resize(1); } // Serialize and hash CHashWriter ss(SER_GETHASH, 0); ss << txTmp << nHashType; return ss.GetHash(); } void static RandomScript(CScript &script) { static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR}; script = CScript(); int ops = (insecure_rand() % 10); for (int i=0; i<ops; i++) script << oplist[insecure_rand() % (sizeof(oplist)/sizeof(oplist[0]))]; } void static RandomTransaction(CMutableTransaction &tx, bool fSingle) { tx.nVersion = insecure_rand(); tx.vin.clear(); tx.vout.clear(); tx.nLockTime = (insecure_rand() % 2) ? insecure_rand() : 0; int ins = (insecure_rand() % 4) + 1; int outs = fSingle ? ins : (insecure_rand() % 4) + 1; for (int in = 0; in < ins; in++) { tx.vin.push_back(CTxIn()); CTxIn &txin = tx.vin.back(); txin.prevout.hash = GetRandHash(); txin.prevout.n = insecure_rand() % 4; RandomScript(txin.scriptSig); txin.nSequence = (insecure_rand() % 2) ? insecure_rand() : (unsigned int)-1; } for (int out = 0; out < outs; out++) { tx.vout.push_back(CTxOut()); CTxOut &txout = tx.vout.back(); txout.nValue = insecure_rand() % 100000000; RandomScript(txout.scriptPubKey); } } BOOST_FIXTURE_TEST_SUITE(sighash_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(sighash_test) { seed_insecure_rand(false); #if defined(PRINT_SIGHASH_JSON) std::cout << "[\n"; std::cout << "\t[\"raw_transaction, script, input_index, hashType, signature_hash (result)\"],\n"; #endif int nRandomTests = 50000; #if defined(PRINT_SIGHASH_JSON) nRandomTests = 500; #endif for (int i=0; i<nRandomTests; i++) { int nHashType = insecure_rand(); CMutableTransaction txTo; RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE); CScript scriptCode; RandomScript(scriptCode); int nIn = insecure_rand() % txTo.vin.size(); uint256 sh, sho; sho = SignatureHashOld(scriptCode, txTo, nIn, nHashType); sh = SignatureHash(scriptCode, txTo, nIn, nHashType); #if defined(PRINT_SIGHASH_JSON) CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << txTo; std::cout << "\t[\"" ; std::cout << HexStr(ss.begin(), ss.end()) << "\", \""; std::cout << HexStr(scriptCode) << "\", "; std::cout << nIn << ", "; std::cout << nHashType << ", \""; std::cout << sho.GetHex() << "\"]"; if (i+1 != nRandomTests) { std::cout << ","; } std::cout << "\n"; #endif BOOST_CHECK(sh == sho); } #if defined(PRINT_SIGHASH_JSON) std::cout << "]\n"; #endif } // Goal: check that SignatureHash generates correct hash BOOST_AUTO_TEST_CASE(sighash_from_data) { UniValue tests = read_json(std::string(json_tests::sighash, json_tests::sighash + sizeof(json_tests::sighash))); for (unsigned int idx = 0; idx < tests.size(); idx++) { UniValue test = tests[idx]; std::string strTest = test.write(); if (test.size() < 1) // Allow for extra stuff (useful for comments) { BOOST_ERROR("Bad test: " << strTest); continue; } if (test.size() == 1) continue; // comment std::string raw_tx, raw_script, sigHashHex; int nIn, nHashType; uint256 sh; CTransaction tx; CScript scriptCode = CScript(); try { // deserialize test data raw_tx = test[0].get_str(); raw_script = test[1].get_str(); nIn = test[2].get_int(); nHashType = test[3].get_int(); sigHashHex = test[4].get_str(); uint256 sh; CDataStream stream(ParseHex(raw_tx), SER_NETWORK, PROTOCOL_VERSION); stream >> tx; CValidationState state; BOOST_CHECK_MESSAGE(CheckTransaction(tx, state), strTest); BOOST_CHECK(state.IsValid()); std::vector<unsigned char> raw = ParseHex(raw_script); scriptCode.insert(scriptCode.end(), raw.begin(), raw.end()); } catch (...) { BOOST_ERROR("Bad test, couldn't deserialize data: " << strTest); continue; } sh = SignatureHash(scriptCode, tx, nIn, nHashType); BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest); } } BOOST_AUTO_TEST_SUITE_END()
c++
code
7,141
1,663
/* * Copyright 2021 Google LLC. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/sksl/DSLCase.h" #include "include/private/SkSLStatement.h" namespace SkSL { namespace dsl { DSLCase::DSLCase(DSLExpression value, SkSL::StatementArray statements, PositionInfo pos) : fValue(std::move(value)) , fStatements(std::move(statements)) , fPosition(pos) {} DSLCase::DSLCase(DSLExpression value, SkTArray<DSLStatement> statements, PositionInfo pos) : fValue(std::move(value)) , fPosition(pos) { fStatements.reserve_back(statements.count()); for (DSLStatement& stmt : statements) { fStatements.push_back(stmt.release()); } } DSLCase::DSLCase(DSLCase&& other) : fValue(std::move(other.fValue)) , fStatements(std::move(other.fStatements)) {} DSLCase::~DSLCase() {} DSLCase& DSLCase::operator=(DSLCase&& other) { fValue = std::move(other.fValue); fStatements = std::move(other.fStatements); return *this; } void DSLCase::append(DSLStatement stmt) { fStatements.push_back(stmt.release()); } } // namespace dsl } // namespace SkSL
c++
code
1,169
282
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The AllCoinGuru Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "validation.h" #include "alert.h" #include "arith_uint256.h" #include "chainparams.h" #include "checkpoints.h" #include "checkqueue.h" #include "consensus/consensus.h" #include "consensus/merkle.h" #include "consensus/validation.h" #include "hash.h" #include "init.h" #include "policy/policy.h" #include "pow.h" #include "primitives/block.h" #include "primitives/transaction.h" #include "script/script.h" #include "script/sigcache.h" #include "script/standard.h" #include "timedata.h" #include "tinyformat.h" #include "txdb.h" #include "txmempool.h" #include "ui_interface.h" #include "undo.h" #include "util.h" #include "spork.h" #include "utilmoneystr.h" #include "utilstrencodings.h" #include "validationinterface.h" #include "versionbits.h" #include "instantx.h" #include "masternodeman.h" #include "masternode-payments.h" #include <sstream> #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/lexical_cast.hpp> #include <boost/math/distributions/poisson.hpp> #include <boost/thread.hpp> using namespace std; #if defined(NDEBUG) # error "AllCoinGuru Core cannot be compiled without assertions." #endif /** * Global state */ CCriticalSection cs_main; BlockMap mapBlockIndex; CChain chainActive; CBlockIndex *pindexBestHeader = NULL; CWaitableCriticalSection csBestBlock; CConditionVariable cvBlockChange; int nScriptCheckThreads = 0; bool fImporting = false; bool fReindex = false; bool fTxIndex = true; bool fAddressIndex = false; bool fTimestampIndex = false; bool fSpentIndex = false; bool fHavePruned = false; bool fPruneMode = false; bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG; bool fRequireStandard = true; unsigned int nBytesPerSigOp = DEFAULT_BYTES_PER_SIGOP; bool fCheckBlockIndex = false; bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED; size_t nCoinCacheUsage = 5000 * 300; uint64_t nPruneTarget = 0; bool fAlerts = DEFAULT_ALERTS; bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT; std::atomic<bool> fDIP0001WasLockedIn{false}; std::atomic<bool> fDIP0001ActiveAtTip{false}; uint256 hashAssumeValid; /** Fees smaller than this (in duffs) are considered zero fee (for relaying, mining and transaction creation) */ CFeeRate minRelayTxFee = CFeeRate(DEFAULT_LEGACY_MIN_RELAY_TX_FEE); CTxMemPool mempool(::minRelayTxFee); map<uint256, int64_t> mapRejectedBlocks GUARDED_BY(cs_main); /** * Returns true if there are nRequired or more blocks of minVersion or above * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards. */ static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams); static void CheckBlockIndex(const Consensus::Params& consensusParams); /** Constant stuff for coinbase transactions we create: */ CScript COINBASE_FLAGS; const string strMessageMagic = "DarkCoin Signed Message:\n"; // Internal stuff namespace { struct CBlockIndexWorkComparator { bool operator()(CBlockIndex *pa, CBlockIndex *pb) const { // First sort by most total work, ... if (pa->nChainWork > pb->nChainWork) return false; if (pa->nChainWork < pb->nChainWork) return true; // ... then by earliest time received, ... if (pa->nSequenceId < pb->nSequenceId) return false; if (pa->nSequenceId > pb->nSequenceId) return true; // Use pointer address as tie breaker (should only happen with blocks // loaded from disk, as those all have id 0). if (pa < pb) return false; if (pa > pb) return true; // Identical blocks. return false; } }; CBlockIndex *pindexBestInvalid; /** * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be * missing the data for the block. */ set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates; /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions. * Pruned nodes may have entries where B is missing data. */ multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked; CCriticalSection cs_LastBlockFile; std::vector<CBlockFileInfo> vinfoBlockFile; int nLastBlockFile = 0; /** Global flag to indicate we should check to see if there are * block/undo files that should be deleted. Set on startup * or if we allocate more file space when we're in prune mode */ bool fCheckForPruning = false; /** * Every received block is assigned a unique and increasing identifier, so we * know which one to give priority in case of a fork. */ CCriticalSection cs_nBlockSequenceId; /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */ uint32_t nBlockSequenceId = 1; /** Dirty block index entries. */ set<CBlockIndex*> setDirtyBlockIndex; /** Dirty block file entries. */ set<int> setDirtyFileInfo; } // anon namespace CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator) { // Find the first block the caller has in the main chain BOOST_FOREACH(const uint256& hash, locator.vHave) { BlockMap::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (chain.Contains(pindex)) return pindex; } } return chain.Genesis(); } CCoinsViewCache *pcoinsTip = NULL; CBlockTreeDB *pblocktree = NULL; enum FlushStateMode { FLUSH_STATE_NONE, FLUSH_STATE_IF_NEEDED, FLUSH_STATE_PERIODIC, FLUSH_STATE_ALWAYS }; // See definition for documentation bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode); bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime) { if (tx.nLockTime == 0) return true; if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime)) return true; BOOST_FOREACH(const CTxIn& txin, tx.vin) { if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL)) return false; } return true; } bool CheckFinalTx(const CTransaction &tx, int flags) { AssertLockHeld(cs_main); // By convention a negative value for flags indicates that the // current network-enforced consensus rules should be used. In // a future soft-fork scenario that would mean checking which // rules would be enforced for the next block and setting the // appropriate flags. At the present time no soft-forks are // scheduled, so no flags are set. flags = std::max(flags, 0); // CheckFinalTx() uses chainActive.Height()+1 to evaluate // nLockTime because when IsFinalTx() is called within // CBlock::AcceptBlock(), the height of the block *being* // evaluated is what is used. Thus if we want to know if a // transaction can be part of the *next* block, we need to call // IsFinalTx() with one more than chainActive.Height(). const int nBlockHeight = chainActive.Height() + 1; // BIP113 will require that time-locked transactions have nLockTime set to // less than the median time of the previous block they're contained in. // When the next block is created its previous block will be the current // chain tip, so we use that to calculate the median time passed to // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set. const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST) ? chainActive.Tip()->GetMedianTimePast() : GetAdjustedTime(); return IsFinalTx(tx, nBlockHeight, nBlockTime); } /** * Calculates the block height and previous block's median time past at * which the transaction will be considered final in the context of BIP 68. * Also removes from the vector of input heights any entries which did not * correspond to sequence locked inputs as they do not affect the calculation. */ static std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block) { assert(prevHeights->size() == tx.vin.size()); // Will be set to the equivalent height- and time-based nLockTime // values that would be necessary to satisfy all relative lock- // time constraints given our view of block chain history. // The semantics of nLockTime are the last invalid height/time, so // use -1 to have the effect of any height or time being valid. int nMinHeight = -1; int64_t nMinTime = -1; // tx.nVersion is signed integer so requires cast to unsigned otherwise // we would be doing a signed comparison and half the range of nVersion // wouldn't support BIP 68. bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2 && flags & LOCKTIME_VERIFY_SEQUENCE; // Do not enforce sequence numbers as a relative lock time // unless we have been instructed to if (!fEnforceBIP68) { return std::make_pair(nMinHeight, nMinTime); } for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) { const CTxIn& txin = tx.vin[txinIndex]; // Sequence numbers with the most significant bit set are not // treated as relative lock-times, nor are they given any // consensus-enforced meaning at this point. if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) { // The height of this input is not relevant for sequence locks (*prevHeights)[txinIndex] = 0; continue; } int nCoinHeight = (*prevHeights)[txinIndex]; if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) { int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast(); // NOTE: Subtract 1 to maintain nLockTime semantics // BIP 68 relative lock times have the semantics of calculating // the first block or time at which the transaction would be // valid. When calculating the effective block time or height // for the entire transaction, we switch to using the // semantics of nLockTime which is the last invalid block // time or height. Thus we subtract 1 from the calculated // time or height. // Time-based relative lock-times are measured from the // smallest allowed timestamp of the block containing the // txout being spent, which is the median time past of the // block prior. nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1); } else { nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1); } } return std::make_pair(nMinHeight, nMinTime); } static bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair) { assert(block.pprev); int64_t nBlockTime = block.pprev->GetMedianTimePast(); if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime) return false; return true; } bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block) { return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block)); } bool TestLockPointValidity(const LockPoints* lp) { AssertLockHeld(cs_main); assert(lp); // If there are relative lock times then the maxInputBlock will be set // If there are no relative lock times, the LockPoints don't depend on the chain if (lp->maxInputBlock) { // Check whether chainActive is an extension of the block at which the LockPoints // calculation was valid. If not LockPoints are no longer valid if (!chainActive.Contains(lp->maxInputBlock)) { return false; } } // LockPoints still valid return true; } bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints) { AssertLockHeld(cs_main); AssertLockHeld(mempool.cs); CBlockIndex* tip = chainActive.Tip(); CBlockIndex index; index.pprev = tip; // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate // height based locks because when SequenceLocks() is called within // ConnectBlock(), the height of the block *being* // evaluated is what is used. // Thus if we want to know if a transaction can be part of the // *next* block, we need to use one more than chainActive.Height() index.nHeight = tip->nHeight + 1; std::pair<int, int64_t> lockPair; if (useExistingLockPoints) { assert(lp); lockPair.first = lp->height; lockPair.second = lp->time; } else { // pcoinsTip contains the UTXO set for chainActive.Tip() CCoinsViewMemPool viewMemPool(pcoinsTip, mempool); std::vector<int> prevheights; prevheights.resize(tx.vin.size()); for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) { const CTxIn& txin = tx.vin[txinIndex]; CCoins coins; if (!viewMemPool.GetCoins(txin.prevout.hash, coins)) { return error("%s: Missing input", __func__); } if (coins.nHeight == MEMPOOL_HEIGHT) { // Assume all mempool transaction confirm in the next block prevheights[txinIndex] = tip->nHeight + 1; } else { prevheights[txinIndex] = coins.nHeight; } } lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index); if (lp) { lp->height = lockPair.first; lp->time = lockPair.second; // Also store the hash of the block with the highest height of // all the blocks which have sequence locked prevouts. // This hash needs to still be on the chain // for these LockPoint calculations to be valid // Note: It is impossible to correctly calculate a maxInputBlock // if any of the sequence locked inputs depend on unconfirmed txs, // except in the special case where the relative lock time/height // is 0, which is equivalent to no sequence lock. Since we assume // input height of tip+1 for mempool txs and test the resulting // lockPair from CalculateSequenceLocks against tip+1. We know // EvaluateSequenceLocks will fail if there was a non-zero sequence // lock on a mempool input, so we can use the return value of // CheckSequenceLocks to indicate the LockPoints validity int maxInputHeight = 0; BOOST_FOREACH(int height, prevheights) { // Can ignore mempool inputs since we'll fail if they had non-zero locks if (height != tip->nHeight+1) { maxInputHeight = std::max(maxInputHeight, height); } } lp->maxInputBlock = tip->GetAncestor(maxInputHeight); } } return EvaluateSequenceLocks(index, lockPair); } unsigned int GetLegacySigOpCount(const CTransaction& tx) { unsigned int nSigOps = 0; BOOST_FOREACH(const CTxIn& txin, tx.vin) { nSigOps += txin.scriptSig.GetSigOpCount(false); } BOOST_FOREACH(const CTxOut& txout, tx.vout) { nSigOps += txout.scriptPubKey.GetSigOpCount(false); } return nSigOps; } unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs) { if (tx.IsCoinBase()) return 0; unsigned int nSigOps = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]); if (prevout.scriptPubKey.IsPayToScriptHash()) nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig); } return nSigOps; } bool GetUTXOCoins(const COutPoint& outpoint, CCoins& coins) { LOCK(cs_main); return !(!pcoinsTip->GetCoins(outpoint.hash, coins) || (unsigned int)outpoint.n>=coins.vout.size() || coins.vout[outpoint.n].IsNull()); } int GetUTXOHeight(const COutPoint& outpoint) { // -1 means UTXO is yet unknown or already spent CCoins coins; return GetUTXOCoins(outpoint, coins) ? coins.nHeight : -1; } int GetUTXOConfirmations(const COutPoint& outpoint) { // -1 means UTXO is yet unknown or already spent LOCK(cs_main); int nPrevoutHeight = GetUTXOHeight(outpoint); return (nPrevoutHeight > -1 && chainActive.Tip()) ? chainActive.Height() - nPrevoutHeight + 1 : -1; } bool CheckTransaction(const CTransaction& tx, CValidationState &state) { // Basic checks that don't depend on any context if (tx.vin.empty()) return state.DoS(10, false, REJECT_INVALID, "bad-txns-vin-empty"); if (tx.vout.empty()) return state.DoS(10, false, REJECT_INVALID, "bad-txns-vout-empty"); // Size limits if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_LEGACY_BLOCK_SIZE) return state.DoS(100, false, REJECT_INVALID, "bad-txns-oversize"); // Check for negative or overflow output values CAmount nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, tx.vout) { if (txout.nValue < 0) return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-negative"); if (txout.nValue > MAX_MONEY) return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-toolarge"); nValueOut += txout.nValue; if (!MoneyRange(nValueOut)) return state.DoS(100, false, REJECT_INVALID, "bad-txns-txouttotal-toolarge"); } // Check for duplicate inputs set<COutPoint> vInOutPoints; BOOST_FOREACH(const CTxIn& txin, tx.vin) { if (vInOutPoints.count(txin.prevout)) return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputs-duplicate"); vInOutPoints.insert(txin.prevout); } if (tx.IsCoinBase()) { if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100) return state.DoS(100, false, REJECT_INVALID, "bad-cb-length"); } else { BOOST_FOREACH(const CTxIn& txin, tx.vin) if (txin.prevout.IsNull()) return state.DoS(10, false, REJECT_INVALID, "bad-txns-prevout-null"); } return true; } bool ContextualCheckTransaction(const CTransaction& tx, CValidationState &state, CBlockIndex * const pindexPrev) { bool fDIP0001Active_context = (VersionBitsState(pindexPrev, Params().GetConsensus(), Consensus::DEPLOYMENT_DIP0001, versionbitscache) == THRESHOLD_ACTIVE); // Size limits if (fDIP0001Active_context && ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_STANDARD_TX_SIZE) return state.DoS(100, false, REJECT_INVALID, "bad-txns-oversize"); return true; } void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) { int expired = pool.Expire(GetTime() - age); if (expired != 0) LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired); std::vector<uint256> vNoSpendsRemaining; pool.TrimToSize(limit, &vNoSpendsRemaining); BOOST_FOREACH(const uint256& removed, vNoSpendsRemaining) pcoin
c++
code
20,000
3,842
//**************************************************************************** // @Module Project Settings // @Filename XC886LM.H // @Project XC886LM.dav //---------------------------------------------------------------------------- // @Controller Infineon XC886LM // // @Compiler Keil // // @Codegenerator 0.1 // // @Description This is the include header file for all other modules. // //---------------------------------------------------------------------------- // @Date 1/25/2006 4:17:21 PM // @Date 13.03.2009 added FIXXC800 // //**************************************************************************** // USER CODE BEGIN (MAIN_Header,1) // USER CODE END #ifndef _MAIN_H_ #define _MAIN_H_ #pragma FIXXC800 // bypass SYS XC8.001 problem //**************************************************************************** // @Project Includes //**************************************************************************** // USER CODE BEGIN (MAIN_Header,2) // USER CODE END //**************************************************************************** // @Macros //**************************************************************************** // Please ensure that SCU_PAGE is switched to Page 1 before using these macros #define MAIN_vUnlockProtecReg() PASSWD = 0x9B #define MAIN_vlockProtecReg() PASSWD = 0xAB // USER CODE BEGIN (MAIN_Header,3) // USER CODE END //**************************************************************************** // @Defines //**************************************************************************** // USER CODE BEGIN (MAIN_Header,4) // USER CODE END #define bool bit #define ulong unsigned long #define uword unsigned int #define ubyte unsigned char #define KEIL //**************************************************************************** // @Prototypes Of Global Functions //**************************************************************************** // USER CODE BEGIN (MAIN_Header,5) // USER CODE END // ------------------------------------------------------------------------- // Declaration of SFRs // ------------------------------------------------------------------------- // Notes: You can avoid the problem that your compiler does not yet support // the latest derivatives if you use the SFR definitions generated // by DAvE instead of those that come along with your compiler (in // the "Register File"). // PORT SFRs are defined in file 'IO.H'. // SFR byte definitions sfr ACC = 0xE0; sfr ADC_CHCTR0 = 0xCA; sfr ADC_CHCTR1 = 0xCB; sfr ADC_CHCTR2 = 0xCC; sfr ADC_CHCTR3 = 0xCD; sfr ADC_CHCTR4 = 0xCE; sfr ADC_CHCTR5 = 0xCF; sfr ADC_CHCTR6 = 0xD2; sfr ADC_CHCTR7 = 0xD3; sfr ADC_CHINCR = 0xCB; sfr ADC_CHINFR = 0xCA; sfr ADC_CHINPR = 0xCD; sfr ADC_CHINSR = 0xCC; sfr ADC_CRCR1 = 0xCA; sfr ADC_CRMR1 = 0xCC; sfr ADC_CRPR1 = 0xCB; sfr ADC_ETRCR = 0xCF; sfr ADC_EVINCR = 0xCF; sfr ADC_EVINFR = 0xCE; sfr ADC_EVINPR = 0xD3; sfr ADC_EVINSR = 0xD2; sfr ADC_GLOBCTR = 0xCA; sfr ADC_GLOBSTR = 0xCB; sfr ADC_INPCR0 = 0xCE; sfr ADC_LCBR = 0xCD; sfr ADC_PAGE = 0xD1; sfr ADC_PRAR = 0xCC; sfr ADC_Q0R0 = 0xCF; sfr ADC_QBUR0 = 0xD2; sfr ADC_QINR0 = 0xD2; sfr ADC_QMR0 = 0xCD; sfr ADC_QSR0 = 0xCE; sfr ADC_RCR0 = 0xCA; sfr ADC_RCR1 = 0xCB; sfr ADC_RCR2 = 0xCC; sfr ADC_RCR3 = 0xCD; sfr ADC_RESR0H = 0xCB; sfr ADC_RESR0L = 0xCA; sfr ADC_RESR1H = 0xCD; sfr ADC_RESR1L = 0xCC; sfr ADC_RESR2H = 0xCF; sfr ADC_RESR2L = 0xCE; sfr ADC_RESR3H = 0xD3; sfr ADC_RESR3L = 0xD2; sfr ADC_RESRA0H = 0xCB; sfr ADC_RESRA0L = 0xCA; sfr ADC_RESRA1H = 0xCD; sfr ADC_RESRA1L = 0xCC; sfr ADC_RESRA2H = 0xCF; sfr ADC_RESRA2L = 0xCE; sfr ADC_RESRA3H = 0xD3; sfr ADC_RESRA3L = 0xD2; sfr ADC_VFCR = 0xCE; sfr B = 0xF0; sfr BCON = 0xBD; sfr BG = 0xBE; sfr CCU6_CC60RH = 0xFB; sfr CCU6_CC60RL = 0xFA; sfr CCU6_CC60SRH = 0xFB; sfr CCU6_CC60SRL = 0xFA; sfr CCU6_CC61RH = 0xFD; sfr CCU6_CC61RL = 0xFC; sfr CCU6_CC61SRH = 0xFD; sfr CCU6_CC61SRL = 0xFC; sfr CCU6_CC62RH = 0xFF; sfr CCU6_CC62RL = 0xFE; sfr CCU6_CC62SRH = 0xFF; sfr CCU6_CC62SRL = 0xFE; sfr CCU6_CC63RH = 0x9B; sfr CCU6_CC63RL = 0x9A; sfr CCU6_CC63SRH = 0x9B; sfr CCU6_CC63SRL = 0x9A; sfr CCU6_CMPMODIFH = 0xA7; sfr CCU6_CMPMODIFL = 0xA6; sfr CCU6_CMPSTATH = 0xFF; sfr CCU6_CMPSTATL = 0xFE; sfr CCU6_IENH = 0x9D; sfr CCU6_IENL = 0x9C; sfr CCU6_INPH = 0x9F; sfr CCU6_INPL = 0x9E; sfr CCU6_ISH = 0x9D; sfr CCU6_ISL = 0x9C; sfr CCU6_ISRH = 0xA5; sfr CCU6_ISRL = 0xA4; sfr CCU6_ISSH = 0xA5; sfr CCU6_ISSL = 0xA4; sfr CCU6_MCMCTR = 0xA7; sfr CCU6_MCMOUTH = 0x9B; sfr CCU6_MCMOUTL = 0x9A; sfr CCU6_MCMOUTSH = 0x9F; sfr CCU6_MCMOUTSL = 0x9E; sfr CCU6_MODCTRH = 0xFD; sfr CCU6_MODCTRL = 0xFC; sfr CCU6_PAGE = 0xA3; sfr CCU6_PISEL0H = 0x9F; sfr CCU6_PISEL0L = 0x9E; sfr CCU6_PISEL2 = 0xA4; sfr CCU6_PSLR = 0xA6; sfr CCU6_T12DTCH = 0xA5; sfr CCU6_T12DTCL = 0xA4; sfr CCU6_T12H = 0xFB; sfr CCU6_T12L = 0xFA; sfr CCU6_T12MSELH = 0x9B; sfr CCU6_T12MSELL = 0x9A; sfr CCU6_T12PRH = 0x9D; sfr CCU6_T12PRL = 0x9C; sfr CCU6_T13H = 0xFD; sfr CCU6_T13L = 0xFC; sfr CCU6_T13PRH = 0x9F; sfr CCU6_T13PRL = 0x9E; sfr CCU6_TCTR0H = 0xA7; sfr CCU6_TCTR0L = 0xA6; sfr CCU6_TCTR2H = 0xFB; sfr CCU6_TCTR2L = 0xFA; sfr CCU6_TCTR4H = 0x9D; sfr CCU6_TCTR4L = 0x9C; sfr CCU6_TRPCTRH = 0xFF; sfr CCU6_TRPCTRL = 0xFE; sfr CD_CON = 0xA1; sfr CD_CORDXH = 0x9B; sfr CD_CORDXL = 0x9A; sfr CD_CORDYH = 0x9D; sfr CD_CORDYL = 0x9C; sfr CD_CORDZH = 0x9F; sfr CD_CORDZL = 0x9E; sfr CD_STATC = 0xA0; sfr CMCON = 0xBA; sfr COCON = 0xBE; sfr DPH = 0x83; sfr DPL = 0x82; sfr EO = 0xA2; sfr EXICON0 = 0xB7; sfr EXICON1 = 0xBA; sfr FDCON = 0xE9; sfr FDRES = 0xEB; sfr FDSTEP = 0xEA; sfr FEAH = 0xBD; sfr FEAL = 0xBC; sfr HWBPDR = 0xF7; sfr HWBPSR = 0xF6; sfr ID = 0xB3; sfr IEN0 = 0xA8; sfr IEN1 = 0xE8; sfr IP = 0xB8; sfr IP1 = 0xF8; sfr IPH = 0xB9; sfr IPH1 = 0xF9; sfr IRCON0 = 0xB4; sfr IRCON1 = 0xB5; sfr IRCON2 = 0xB6; sfr IRCON3 = 0xB4; sfr IRCON4 = 0xB5; sfr MDU_MD0 = 0xB2; sfr MDU_MD1 = 0xB3; sfr MDU_MD2 = 0xB4; sfr MDU_MD3 = 0xB5; sfr MDU_MD4 = 0xB6; sfr MDU_MD5 = 0xB7; sfr MDU_MDUCON = 0xB1; sfr MDU_MDUSTAT = 0xB0; sfr MDU_MR0 = 0xB2; sfr MDU_MR1 = 0xB3; sfr MDU_MR2 = 0xB4; sfr MDU_MR3 = 0xB5; sfr MDU_MR4 = 0xB6; sfr MDU_MR5 = 0xB7; sfr MISC_CON = 0xE9; sfr MMBPCR = 0xF3; sfr MMCR = 0xF1; sfr MMCR2 = 0xE9; sfr MMDR = 0xF5; sfr MMICR = 0xF4; sfr MMSR = 0xF2; sfr MMWR1 = 0xEB; sfr MMWR2 = 0xEC; sfr MODPISEL = 0xB3; sfr MODPISEL1 = 0xB7; sfr MODPISEL2 = 0xBA; sfr MODSUSP = 0xBD; sfr NMICON = 0xBB; sfr NMISR = 0xBC; sfr OSC_CON = 0xB6; sfr P0_ALTSEL0 = 0x80; sfr P0_ALTSEL1 = 0x86; sfr P0_DATA = 0x80; sfr P0_DIR = 0x86; sfr P0_OD = 0x80; sfr P0_PUDEN = 0x86; sfr P0_PUDSEL = 0x80; sfr P1_ALTSEL0 = 0x90; sfr P1_ALTSEL1 = 0x91; sfr P1_DATA = 0x90; sfr P1_DIR = 0x91; sfr P1_OD = 0x90; sfr P1_PUDEN = 0x91; sfr P1_PUDSEL = 0x90; sfr P2_DATA = 0xA0; sfr P2_DIR = 0xA1; sfr P2_PUDEN = 0xA1; sfr P2_PUDSEL = 0xA0; sfr P3_ALTSEL0 = 0xB0; sfr P3_ALTSEL1 = 0xB1; sfr P3_DATA = 0xB0; sfr P3_DIR = 0xB1; sfr P3_OD = 0xB0; sfr P3_PUDEN = 0xB1; sfr P3_PUDSEL = 0xB0; sfr P4_ALTSEL0 = 0xC8; sfr P4_ALTSEL1 = 0xC9; sfr P4_DATA = 0xC8; sfr P4_DIR = 0xC9; sfr P4_OD = 0xC8; sfr P4_PUDEN = 0xC9; sfr P4_PUDSEL = 0xC8; sfr P5_ALTSEL0 = 0x92; sfr P5_ALTSEL1 = 0x93; sfr P5_DATA = 0x92; sfr P5_DIR = 0x93; sfr P5_OD = 0x92; sfr P5_PUDEN = 0x93; sfr P5_PUDSEL = 0x92; sfr PASSWD = 0xBB; sfr PCON = 0x87; sfr PLL_CON = 0xB7; sfr PMCON0 = 0xB4; sfr PMCON1 = 0xB5; sfr PMCON2 = 0xBB; sfr PORT_PAGE = 0xB2; sfr PSW = 0xD0; sfr SBUF = 0x99; sfr SCON = 0x98; sfr SCU_PAGE = 0xBF; sfr SP = 0x81; sfr SSC_BRH = 0xAF; sfr SSC_BRL = 0xAE; sfr SSC_CONH_O = 0xAB; sfr SSC_CONH_P = 0xAB; sfr SSC_CONL_O = 0xAA; sfr SSC_CONL_P = 0xAA; sfr SSC_PISEL = 0xA9; sfr SSC_RBL = 0xAD; sfr SSC_TBL = 0xAC; sfr SYSCON0 = 0x8F; sfr T21_RC2H = 0xC3; sfr T21_RC2L = 0xC2; sfr T21_T2CON = 0xC0; sfr T21_T2H = 0xC5; sfr T21_T2L = 0xC4; sfr T21_T2MOD = 0xC1; sfr T2_RC2H = 0xC3; sfr T2_RC2L = 0xC2; sfr T2_T2CON = 0xC0; sfr T2_T2H = 0xC5; sfr T2_T2L = 0xC4; sfr T2_T2MOD = 0xC1; sfr TCON = 0x88; sfr TH0 = 0x8C; sfr TH1 = 0x8D; sfr TL0 = 0x8A; sfr TL1 = 0x8B; sfr TMOD = 0x89; sfr UART1_BCON = 0xCA; sfr UART1_BG = 0xCB; sfr UART1_FDCON = 0xCC; sfr UART1_FDRES = 0xCE; sfr UART1_FDSTEP = 0xCD; sfr UART1_SBUF = 0xC9; sfr UART1_SCON = 0xC8; sfr WDTCON = 0xBB; // located in the mapped SFR area sfr WDTH = 0xBF; // located in the mapped SFR area sfr WDTL = 0xBE; // located in the mapped SFR area sfr WDTREL = 0xBC; // located in the mapped SFR area sfr WDTWINB = 0xBD; // located in the mapped SFR area sfr XADDRH = 0xB3; // SFR bit definitions // CD_STATC sbit CD_BSY = 0xA0; sbit DMAP = 0xA4; sbit EOC = 0xA2; sbit ERROR = 0xA1; sbit INT_EN = 0xA3; sbit KEEPX = 0xA5; sbit KEEPY = 0xA6; sbit KEEPZ = 0xA7; // IEN0 sbit EA = 0xAF; sbit ES = 0xAC; sbit ET0 = 0xA9; sbit ET1 = 0xAB; sbit ET2 = 0xAD; sbit EX0 = 0xA8; sbit EX1 = 0xAA; // IEN1 sbit EADC = 0xE8; sbit ECCIP0 = 0xEC; sbit ECCIP1 = 0xED; sbit ECCIP2 = 0xEE; sbit ECCIP3 = 0xEF; sbit ESSC = 0xE9; sbit EX2 = 0xEA; sbit EXM = 0xEB; // IP1 sbit PADC = 0xF8; sbit PCCIP0 = 0xFC; sbit PCCIP1 = 0xFD; sbit PCCIP2 = 0xFE; sbit PCCIP3 = 0xFF; sbit PSSC = 0xF9; sbit PX2 = 0xFA; sbit PXM = 0xFB; // IP sbit PS = 0xBC; sbit PT0 = 0xB9; sbit PT1 = 0xBB; sbit PT2 = 0xBD; sbit PX0 = 0xB8; sbit PX1 = 0xBA; // MDU_MDUSTAT sbit IERR = 0xB1; sbit IRDY = 0xB0; sbit MDU_BSY = 0xB2; // PSW sbit AC = 0xD6; sbit CY = 0xD7; sbit F0 = 0xD5; sbit F1 = 0xD1; sbit OV = 0xD2; sbit P = 0xD0; sbit RS0 = 0xD3; sbit RS1 = 0xD4; // SCON sbit RB8 = 0x9A; sbit REN = 0x9C; sbit RI = 0x98; sbit SM0 = 0x9F; sbit SM1 = 0x9E; sbit SM2 = 0x9D; sbit TB8 = 0x9B; sbit TI = 0x99; // T2_T2CON and T21_T2CON sbit C_T2 = 0xC1; sbit CP_RL2 = 0xC0; sbit EXEN2 = 0xC3; sbit EXF2 = 0xC6; sbit TF2 = 0xC7; sbit TR2 = 0xC2; // TCON sbit IE0 = 0x89; sbit IE1 = 0x8B; sbit IT0 = 0x88; sbit IT1 = 0x8A; sbit TF0 = 0x8D; sbit TF1 = 0x8F; sbit TR0 = 0x8C; sbit TR1 = 0x8E; // UART1_SCON sbit RB8_1 = 0xCA; sbit REN_1 = 0xCC; sbit RI_1 = 0xC8; sbit SM0_1 = 0xCF; sbit SM1_1 = 0xCE; sbit SM2_1 = 0xCD; sbit TB8_1 = 0xCB; sbit TI_1 = 0xC9; // Definition of the PAGE SFR // PORT_PAGE #define _pp0 PORT_PAGE=0 // PORT_PAGE postfix #define _pp1 PORT_PAGE=1 // PORT_PAGE postfix #define _pp2 PORT_PAGE=2 // PORT_PAGE postfix #define _pp3 PORT_PAGE=3 // PORT_PAGE postfix // ADC_PAGE #define _ad0 ADC_PAGE=0 // ADC_PAGE postfix #define _ad1 ADC_PAGE=1 // ADC_PAGE postfix #define _ad2 ADC_PAGE=2 // ADC_PAGE postfix #define _ad3 ADC_PAGE=3 // ADC_PAGE postfix #define _ad4 ADC_PAGE=4 // ADC_PAGE postfix #define _ad5 ADC_PAGE=5 // ADC_PAGE postfix #define _ad6 ADC_PAGE=6 // ADC_PAGE postfix // SCU_PAGE #define _su0 SCU_PAGE=0 // SCU_PAGE postfix #define _su1 SCU_PAGE=1 // SCU_PAGE postfix #define _su2 SCU_PAGE=2 // SCU_PAGE postfix #define _su3 SCU_PAGE=3 // SCU_PAGE postfix // CCU6_PAGE #define _cc0 CCU6_PAGE=0 // CCU6_PAGE postfix #define _cc1 CCU6_PAGE=1 // CCU6_PAGE postfix #define _cc2 CCU6_PAGE=2 // CCU6_PAGE postfix #define _cc3 CCU6_PAGE=3 // CCU6_PAGE postfix #define SST0 0x80 // Save SFR page to ST0 #define RST0 0xC0 // Restore SFR page from ST0 #define SST1 0x90 // Save SFR page to ST1 #define RST1 0xD0 // Restore SFR page from ST1 #define SST2 0xA0 // Save SFR page to ST2 #define RST2 0xE0 // Restore SFR page from ST2 #define SST3 0xB0 // Save SFR page to ST3 #define RST3 0xF0 // Restore SFR page from ST3 #define noSST 0x00 // Switch page without saving #define SFR_PAGE(pg,op) pg+op // SYSCON0_RMAP // The access to the mapped SFR area is enabled. #define SET_RMAP() SYSCON0 |= 0x01 // The access to the standard SFR area is enabled. #define RESET_RMAP() SYSCON0 &= ~0x01 //**************************************************************************** // @Typedefs //**************************************************************************** // USER CODE BEGIN (MAIN_Header,6) // USER CODE END //**************************************************************************** // @Imported Global Variables //**************************************************************************** // USER CODE BEGIN (MAIN_Header,7) // USER CODE END //**************************************************************************** // @Global Variables //**************************************************************************** // USER CODE BEGIN (MAIN_Header,8) // USER CODE END //**************************************************************************** // @Prototypes Of Global Functions //**************************************************************************** // USER CODE BEGIN (MAIN_Header,9) // USER CODE END //**************************************************************************** // @Interrupt Vectors //**************************************************************************** // USER CODE BEGIN (MAIN_Header,10) // USER CODE END //**************************************************************************** // @Project Includes //**************************************************************************** #include <intrins.h> // USER CODE BEGIN (MAIN_Header,11) // USER CODE END #endif // ifndef _MAIN_H_
c++
code
16,304
4,319
#ifndef __ROTATIONS_H #define __ROTATIONS_H template <typename Scalar> void quaternion_to_rotation(Scalar quaternion[4], Scalar (&rotation)[3][3]) { // NOTE: input quaternions are interpreted as shuster notation. rotation[0][0] = (quaternion[0]*quaternion[0]) - (quaternion[1]*quaternion[1]) - (quaternion[2]*quaternion[2]) + (quaternion[3]*quaternion[3]); rotation[0][1] = 2*(quaternion[0]*quaternion[1] + quaternion[2]*quaternion[3]); rotation[0][2] = 2*(quaternion[0]*quaternion[2] - quaternion[1]*quaternion[3]); rotation[1][0] = 2*(quaternion[0]*quaternion[1] - quaternion[2]*quaternion[3]); rotation[1][1] = -(quaternion[0]*quaternion[0]) + (quaternion[1]*quaternion[1]) - (quaternion[2]*quaternion[2]) + (quaternion[3]*quaternion[3]); rotation[1][2] = 2*(quaternion[1]*quaternion[2] + quaternion[0]*quaternion[3]); rotation[2][0] = 2*(quaternion[0]*quaternion[2] + quaternion[1]*quaternion[3]); rotation[2][1] = 2*(quaternion[1]*quaternion[2] - quaternion[0]*quaternion[3]); rotation[2][2] = -(quaternion[0]*quaternion[0]) - (quaternion[1]*quaternion[1]) + (quaternion[2]*quaternion[2]) + (quaternion[3]*quaternion[3]); } template <typename Scalar> void MatrixMultiply(Scalar A[3][3], Scalar (&B)[3][3]) { Scalar temp[3][3] = {0}; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { temp[i][j] += A[i][k] * B[k][j]; } } } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { B[i][j] = temp[i][j]; } } } // Define the rotation around the 3rd (z) axis: template <typename Scalar> void rotmat_1(Scalar angle, Scalar (&rotation_1)[3][3]){ static constexpr Scalar pi = Scalar(3.14159265359); Scalar cos = std::cos(angle*pi / Scalar(180)); Scalar sin = std::sin(angle*pi / Scalar(180)); rotation_1[0][0] = 1; rotation_1[0][1] = 0; rotation_1[0][2] = 0; rotation_1[1][0] = 0; rotation_1[1][1] = cos; rotation_1[1][2] = sin; rotation_1[2][0] = 0; rotation_1[2][1] = -sin; rotation_1[2][2] = cos; } // Define the rotation around the 2nd (y) axis: template <typename Scalar> void rotmat_2(Scalar angle, Scalar (&rotation_2)[3][3]){ static constexpr Scalar pi = Scalar(3.14159265359); Scalar cos = std::cos(angle*pi / Scalar(180)); Scalar sin = std::sin(angle*pi / Scalar(180)); rotation_2[0][0] = cos; rotation_2[0][1] = 0; rotation_2[0][2] = -sin; rotation_2[1][0] = 0; rotation_2[1][1] = 1; rotation_2[1][2] = 0; rotation_2[2][0] = sin; rotation_2[2][1] = 0; rotation_2[2][2] = cos; } // Define the rotation around the 1st (z) axis: template <typename Scalar> void rotmat_3(Scalar angle, Scalar (&rotation_3)[3][3]){ static constexpr Scalar pi = Scalar(3.14159265359); Scalar cos = std::cos(angle*pi / Scalar(180)); Scalar sin = std::sin(angle*pi / Scalar(180)); rotation_3[0][0] = cos; rotation_3[0][1] = sin; rotation_3[0][2] = 0; rotation_3[1][0] = -sin; rotation_3[1][1] = cos; rotation_3[1][2] = 0; rotation_3[2][0] = 0; rotation_3[2][1] = 0; rotation_3[2][2] = 1; } template <typename Scalar> void euler_to_rotation(Scalar euler_angles[3], const char* euler_sequence, Scalar (&rotation)[3][3]) { Scalar rotation_1[3][3]; Scalar rotation_2[3][3]; Scalar rotation_3[3][3]; // Define an initial rotation: rotation[0][0] = 1; rotation[0][1] = 0; rotation[0][2] = 0; rotation[1][0] = 0; rotation[1][1] = 1; rotation[1][2] = 0; rotation[2][0] = 0; rotation[2][1] = 0; rotation[2][2] = 1; // Obtain the first rotation: if (euler_sequence[0] == '1') { rotmat_1(euler_angles[0], rotation_1); } else if (euler_sequence[0] == '2') { rotmat_2(euler_angles[0], rotation_1); } else { rotmat_3(euler_angles[0], rotation_1); } // Obtain the second rotaiton: if (euler_sequence[1] == '1') { rotmat_1(euler_angles[1], rotation_2); } else if (euler_sequence[1] == '2') { rotmat_2(euler_angles[1], rotation_2); } else { rotmat_3(euler_angles[1], rotation_2); } // Obtain the third rotaiton: if (euler_sequence[2] == '1') { rotmat_1(euler_angles[2], rotation_3); } else if (euler_sequence[2] == '2') { rotmat_2(euler_angles[2], rotation_3); } else { rotmat_3(euler_angles[2], rotation_3); } // Apply all three rotations to the default: MatrixMultiply<Scalar>(rotation_3, rotation); MatrixMultiply<Scalar>(rotation_2, rotation); MatrixMultiply<Scalar>(rotation_1, rotation); } #endif
c++
code
4,753
1,500
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/ec2/model/CreateManagedPrefixListResponse.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/logging/LogMacros.h> #include <utility> using namespace Aws::EC2::Model; using namespace Aws::Utils::Xml; using namespace Aws::Utils::Logging; using namespace Aws::Utils; using namespace Aws; CreateManagedPrefixListResponse::CreateManagedPrefixListResponse() { } CreateManagedPrefixListResponse::CreateManagedPrefixListResponse(const Aws::AmazonWebServiceResult<XmlDocument>& result) { *this = result; } CreateManagedPrefixListResponse& CreateManagedPrefixListResponse::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result) { const XmlDocument& xmlDocument = result.GetPayload(); XmlNode rootNode = xmlDocument.GetRootElement(); XmlNode resultNode = rootNode; if (!rootNode.IsNull() && (rootNode.GetName() != "CreateManagedPrefixListResponse")) { resultNode = rootNode.FirstChild("CreateManagedPrefixListResponse"); } if(!resultNode.IsNull()) { XmlNode prefixListNode = resultNode.FirstChild("prefixList"); if(!prefixListNode.IsNull()) { m_prefixList = prefixListNode; } } if (!rootNode.IsNull()) { XmlNode requestIdNode = rootNode.FirstChild("requestId"); if (!requestIdNode.IsNull()) { m_responseMetadata.SetRequestId(StringUtils::Trim(requestIdNode.GetText().c_str())); } AWS_LOGSTREAM_DEBUG("Aws::EC2::Model::CreateManagedPrefixListResponse", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() ); } return *this; }
c++
code
1,759
329
#include "ListViewReader.h" #include "ui/UIListView.h" #include "cocostudio/CocoLoader.h" #include "cocostudio/CSParseBinary_generated.h" #include "cocostudio/FlatBuffersSerialize.h" #include "tinyxml2.h" #include "flatbuffers/flatbuffers.h" USING_NS_CC; using namespace ui; using namespace flatbuffers; namespace cocostudio { static const char* P_Direction = "direction"; static const char* P_ItemMargin = "itemMargin"; static ListViewReader* instanceListViewReader = nullptr; IMPLEMENT_CLASS_NODE_READER_INFO(ListViewReader) ListViewReader::ListViewReader() { } ListViewReader::~ListViewReader() { } ListViewReader* ListViewReader::getInstance() { if (!instanceListViewReader) { instanceListViewReader = new (std::nothrow) ListViewReader(); } return instanceListViewReader; } void ListViewReader::destroyInstance() { CC_SAFE_DELETE(instanceListViewReader); } void ListViewReader::setPropsFromBinary(cocos2d::ui::Widget *widget, CocoLoader *cocoLoader, stExpCocoNode* cocoNode) { ScrollViewReader::setPropsFromBinary(widget, cocoLoader, cocoNode); ListView* listView = static_cast<ListView*>(widget); stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader); for (int i = 0; i < cocoNode->GetChildNum(); ++i) { std::string key = stChildArray[i].GetName(cocoLoader); std::string value = stChildArray[i].GetValue(cocoLoader); if (key == P_Direction) { listView->setDirection((ScrollView::Direction)valueToInt(value)); } else if(key == P_Gravity){ listView->setGravity((ListView::Gravity)valueToInt(value)); }else if(key == P_ItemMargin){ listView->setItemsMargin(valueToFloat(value)); } } //end of for loop } void ListViewReader::setPropsFromJsonDictionary(Widget *widget, const rapidjson::Value &options) { ScrollViewReader::setPropsFromJsonDictionary(widget, options); ListView* listView = static_cast<ListView*>(widget); int direction = DICTOOL->getFloatValue_json(options, P_Direction,2); listView->setDirection((ScrollView::Direction)direction); ListView::Gravity gravity = (ListView::Gravity)DICTOOL->getIntValue_json(options, P_Gravity,3); listView->setGravity(gravity); float itemMargin = DICTOOL->getFloatValue_json(options, P_ItemMargin); listView->setItemsMargin(itemMargin); } Offset<Table> ListViewReader::createOptionsWithFlatBuffers(const tinyxml2::XMLElement *objectData, flatbuffers::FlatBufferBuilder *builder) { auto temp = WidgetReader::getInstance()->createOptionsWithFlatBuffers(objectData, builder); auto widgetOptions = *(Offset<WidgetOptions>*)(&temp); std::string path; std::string plistFile; int resourceType = 0; bool clipEnabled = false; Color3B bgColor; Color3B bgStartColor; Color3B bgEndColor; int colorType = 0; GLubyte bgColorOpacity = 255; Vec2 colorVector(0.0f, -0.5f); Rect capInsets; Size scale9Size; bool backGroundScale9Enabled = false; Size innerSize(200, 300); int direction = 0; bool bounceEnabled = false; int itemMargin = 0; std::string directionType; std::string horizontalType; std::string verticalType; // attributes auto attribute = objectData->FirstAttribute(); while (attribute) { std::string name = attribute->Name(); std::string value = attribute->Value(); if (name == "ClipAble") { clipEnabled = (value == "True") ? true : false; } else if (name == "ComboBoxIndex") { colorType = atoi(value.c_str()); } else if (name == "BackColorAlpha") { bgColorOpacity = atoi(value.c_str()); } else if (name == "Scale9Enable") { if (value == "True") { backGroundScale9Enabled = true; } } else if (name == "Scale9OriginX") { capInsets.origin.x = atof(value.c_str()); } else if (name == "Scale9OriginY") { capInsets.origin.y = atof(value.c_str()); } else if (name == "Scale9Width") { capInsets.size.width = atof(value.c_str()); } else if (name == "Scale9Height") { capInsets.size.height = atof(value.c_str()); } else if (name == "DirectionType") { directionType = value; } else if (name == "HorizontalType") { horizontalType = value; } else if (name == "VerticalType") { verticalType = value; } else if (name == "IsBounceEnabled") { bounceEnabled = (value == "True") ? true : false; } else if (name == "ItemMargin") { itemMargin = atoi(value.c_str()); } attribute = attribute->Next(); } // child elements const tinyxml2::XMLElement* child = objectData->FirstChildElement(); while (child) { std::string name = child->Name(); if (name == "InnerNodeSize") { auto attributeInnerNodeSize = child->FirstAttribute(); while (attributeInnerNodeSize) { name = attributeInnerNodeSize->Name(); std::string value = attributeInnerNodeSize->Value(); if (name == "Width") { innerSize.width = atof(value.c_str()); } else if (name == "Height") { innerSize.height = atof(value.c_str()); } attributeInnerNodeSize = attributeInnerNodeSize->Next(); } } else if (name == "Size" && backGroundScale9Enabled) { auto attributeSize = child->FirstAttribute(); while (attributeSize) { name = attributeSize->Name(); std::string value = attributeSize->Value(); if (name == "X") { scale9Size.width = atof(value.c_str()); } else if (name == "Y") { scale9Size.height = atof(value.c_str()); } attributeSize = attributeSize->Next(); } } else if (name == "SingleColor") { auto attributeSingleColor = child->FirstAttribute(); while (attributeSingleColor) { name = attributeSingleColor->Name(); std::string value = attributeSingleColor->Value(); if (name == "R") { bgColor.r = atoi(value.c_str()); } else if (name == "G") { bgColor.g = atoi(value.c_str()); } else if (name == "B") { bgColor.b = atoi(value.c_str()); } attributeSingleColor = attributeSingleColor->Next(); } } else if (name == "EndColor") { auto attributeEndColor = child->FirstAttribute(); while (attributeEndColor) { name = attributeEndColor->Name(); std::string value = attributeEndColor->Value(); if (name == "R") { bgEndColor.r = atoi(value.c_str()); } else if (name == "G") { bgEndColor.g = atoi(value.c_str()); } else if (name == "B") { bgEndColor.b = atoi(value.c_str()); } attributeEndColor = attributeEndColor->Next(); } } else if (name == "FirstColor") { auto attributeFirstColor = child->FirstAttribute(); while (attributeFirstColor) { name = attributeFirstColor->Name(); std::string value = attributeFirstColor->Value(); if (name == "R") { bgStartColor.r = atoi(value.c_str()); } else if (name == "G") { bgStartColor.g = atoi(value.c_str()); } else if (name == "B") { bgStartColor.b = atoi(value.c_str()); } attributeFirstColor = attributeFirstColor->Next(); } } else if (name == "ColorVector") { auto attributeColorVector = child->FirstAttribute(); while (attributeColorVector) { name = attributeColorVector->Name(); std::string value = attributeColorVector->Value(); if (name == "ScaleX") { colorVector.x = atof(value.c_str()); } else if (name == "ScaleY") { colorVector.y = atof(value.c_str()); } attributeColorVector = attributeColorVector->Next(); } } else if (name == "FileData") { std::string texture; std::string texturePng; auto attributeFileData = child->FirstAttribute(); while (attributeFileData) { name = attributeFileData->Name(); std::string value = attributeFileData->Value(); if (name == "Path") { path = value; } else if (name == "Type") { resourceType = getResourceType(value); } else if (name == "Plist") { plistFile = value; texture = value; } attributeFileData = attributeFileData->Next(); } if (resourceType == 1) { FlatBuffersSerialize* fbs = FlatBuffersSerialize::getInstance(); fbs->_textures.push_back(builder->CreateString(texture)); } } child = child->NextSiblingElement(); } Color f_bgColor(255, bgColor.r, bgColor.g, bgColor.b); Color f_bgStartColor(255, bgStartColor.r, bgStartColor.g, bgStartColor.b); Color f_bgEndColor(255, bgEndColor.r, bgEndColor.g, bgEndColor.b); ColorVector f_colorVector(colorVector.x, colorVector.y); CapInsets f_capInsets(capInsets.origin.x, capInsets.origin.y, capInsets.size.width, capInsets.size.height); FlatSize f_scale9Size(scale9Size.width, scale9Size.height); FlatSize f_innerSize(innerSize.width, innerSize.height); auto options = CreateListViewOptions(*builder, widgetOptions, CreateResourceData(*builder, builder->CreateString(path), builder->CreateString(plistFile), resourceType), clipEnabled, &f_bgColor, &f_bgStartColor, &f_bgEndColor, colorType, bgColorOpacity, &f_colorVector, &f_capInsets, &f_scale9Size, backGroundScale9Enabled, &f_innerSize, direction, bounceEnabled, itemMargin, builder->CreateString(directionType), builder->CreateString(horizontalType), builder->CreateString(verticalType)); return *(Offset<Table>*)(&options); } void ListViewReader::setPropsWithFlatBuffers(cocos2d::Node *node, const flatbuffers::Table *listViewOptions) { ListView* listView = static_cast<ListView*>(node); auto options = (ListViewOptions*)listViewOptions; bool clipEnabled = options->clipEnabled() != 0; listView->setClippingEnabled(clipEnabled); bool backGroundScale9Enabled = options->backGroundScale9Enabled() != 0; listView->setBackGroundImageScale9Enabled(backGroundScale9Enabled); auto f_bgColor = options->bgColor(); Color3B bgColor(f_bgColor->r(), f_bgColor->g(), f_bgColor->b()); auto f_bgStartColor = options->bgStartColor(); Color3B bgStartColor(f_bgStartColor->r(), f_bgStartColor->g(), f_bgStartColor->b()); auto f_bgEndColor = options->bgEndColor(); Color3B bgEndColor(f_bgEndColor->r(), f_bgEndColor->g(), f_bgEndColor->b()); auto f_colorVecor = options->colorVector(); Vec2 colorVector(f_colorVecor->vectorX(), f_colorVecor->vectorY()); listView->setBackGroundColorVector(colorVector); int bgColorOpacity = options->bgColorOpacity(); int colorType = options->colorType(); listView->setBackGroundColorType(Layout::BackGroundColorType(colorType)); listView->setBackGroundColor(bgStartColor, bgEndColor); listView->setBackGroundColor(bgColor); listView->setBackGroundColorOpacity(bgColorOpacity); bool fileExist = false; std::string errorFilePath = ""; auto imageFileNameDic = options->backGroundImageData(); int imageFileNameType = imageFileNameDic->resourceType(); std::string imageFileName = imageFileNameDic->path()->c_str(); if (imageFileName != "") { switch (imageFileNameType) { case 0: { if (FileUtils::getInstance()->isFileExist(imageFileName)) { fileExist = true; } else { errorFilePath = imageFileName; fileExist = false; } break; } case 1: { std::string plist = imageFileNameDic->plistFile()->c_str(); SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(imageFileName); if (spriteFrame) { fileExist = true; } else { if (FileUtils::getInstance()->isFileExist(plist)) { ValueMap value = FileUtils::getInstance()->getValueMapFromFile(plist); ValueMap metadata = value["metadata"].asValueMap(); std::string textureFileName = metadata["textureFileName"].asString(); if (!FileUtils::getInstance()->isFileExist(textureFileName)) { errorFilePath = textureFileName; } } else { errorFilePath = plist; } fileExist = false; } break; } default: break; } if (fileExist) { listView->setBackGroundImage(imageFileName, (Widget::TextureResType)imageFileNameType); } //else //{ // auto label = Label::create(); // label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString()); // listView->addChild(label); //} } auto widgetOptions = options->widgetOptions(); auto f_color = widgetOptions->color(); Color3B color(f_color->r(), f_color->g(), f_color->b()); listView->setColor(color); int opacity = widgetOptions->alpha(); listView->setOpacity(opacity); auto f_innerSize = options->innerSize(); Size innerSize(f_innerSize->width(), f_innerSize->height()); listView->setInnerContainerSize(innerSize); // int direction = options->direction(); // listView->setDirection((ScrollView::Direction)direction); bool bounceEnabled = options->bounceEnabled() != 0; listView->setBounceEnabled(bounceEnabled); // int gravityValue = options->gravity(); // ListView::Gravity gravity =
c++
code
20,000
2,928
// See the file "COPYING" in the main distribution directory for copyright. #include "zeek-config.h" #include "NVT.h" #include <stdlib.h> #include "BroString.h" #include "NetVar.h" #include "Event.h" #include "Reporter.h" #include "analyzer/protocol/tcp/TCP.h" #include "events.bif.h" #define IS_3_BYTE_OPTION(c) (c >= 251 && c <= 254) #define TELNET_OPT_SB 250 #define TELNET_OPT_SE 240 #define TELNET_OPT_IS 0 #define TELNET_OPT_SEND 1 #define TELNET_OPT_WILL 251 #define TELNET_OPT_WONT 252 #define TELNET_OPT_DO 253 #define TELNET_OPT_DONT 254 #define TELNET_IAC 255 using namespace analyzer::login; TelnetOption::TelnetOption(NVT_Analyzer* arg_endp, unsigned int arg_code) { endp = arg_endp; code = arg_code; flags = 0; active = 0; } void TelnetOption::RecvOption(unsigned int type) { TelnetOption* peer = endp->FindPeerOption(code); if ( ! peer ) { reporter->AnalyzerError(endp, "option peer missing in TelnetOption::RecvOption"); return; } // WILL/WONT/DO/DONT are messages we've *received* from our peer. switch ( type ) { case TELNET_OPT_WILL: if ( SaidDont() || peer->SaidWont() || peer->IsActive() ) InconsistentOption(type); peer->SetWill(); if ( SaidDo() ) peer->SetActive(true); break; case TELNET_OPT_WONT: if ( peer->SaidWill() && ! SaidDont() ) InconsistentOption(type); peer->SetWont(); if ( SaidDont() ) peer->SetActive(false); break; case TELNET_OPT_DO: if ( SaidWont() || peer->SaidDont() || IsActive() ) InconsistentOption(type); peer->SetDo(); if ( SaidWill() ) SetActive(true); break; case TELNET_OPT_DONT: if ( peer->SaidDo() && ! SaidWont() ) InconsistentOption(type); peer->SetDont(); if ( SaidWont() ) SetActive(false); break; default: reporter->AnalyzerError(endp, "bad option type in TelnetOption::RecvOption"); return; } } void TelnetOption::RecvSubOption(u_char* /* data */, int /* len */) { } void TelnetOption::SetActive(bool is_active) { active = is_active; } void TelnetOption::InconsistentOption(unsigned int /* type */) { endp->Event(inconsistent_option); } void TelnetOption::BadOption() { endp->Event(bad_option); } void TelnetTerminalOption::RecvSubOption(u_char* data, int len) { if ( len <= 0 ) { BadOption(); return; } if ( data[0] == TELNET_OPT_SEND ) return; if ( data[0] != TELNET_OPT_IS ) { BadOption(); return; } endp->SetTerminal(data + 1, len - 1); } #define ENCRYPT_SET_ALGORITHM 0 #define ENCRYPT_SUPPORT_ALGORITM 1 #define ENCRYPT_REPLY 2 #define ENCRYPT_STARTING_TO_ENCRYPT 3 #define ENCRYPT_NO_LONGER_ENCRYPTING 4 #define ENCRYPT_REQUEST_START_TO_ENCRYPT 5 #define ENCRYPT_REQUEST_NO_LONGER_ENCRYPT 6 #define ENCRYPT_ENCRYPT_KEY 7 #define ENCRYPT_DECRYPT_KEY 8 void TelnetEncryptOption::RecvSubOption(u_char* data, int len) { if ( ! active ) { InconsistentOption(0); return; } if ( len <= 0 ) { BadOption(); return; } unsigned int opt = data[0]; if ( opt == ENCRYPT_REQUEST_START_TO_ENCRYPT ) ++did_encrypt_request; else if ( opt == ENCRYPT_STARTING_TO_ENCRYPT ) { TelnetEncryptOption* peer = (TelnetEncryptOption*) endp->FindPeerOption(code); if ( ! peer ) { reporter->AnalyzerError(endp, "option peer missing in TelnetEncryptOption::RecvSubOption"); return; } if ( peer->DidRequest() || peer->DoingEncryption() || peer->Endpoint()->AuthenticationHasBeenAccepted() ) { endp->SetEncrypting(1); ++doing_encryption; } else InconsistentOption(0); } } #define HERE_IS_AUTHENTICATION 0 #define SEND_ME_AUTHENTICATION 1 #define AUTHENTICATION_STATUS 2 #define AUTHENTICATION_NAME 3 #define AUTH_REJECT 1 #define AUTH_ACCEPT 2 void TelnetAuthenticateOption::RecvSubOption(u_char* data, int len) { if ( len <= 0 ) { BadOption(); return; } switch ( data[0] ) { case HERE_IS_AUTHENTICATION: { TelnetAuthenticateOption* peer = (TelnetAuthenticateOption*) endp->FindPeerOption(code); if ( ! peer ) { reporter->AnalyzerError(endp, "option peer missing in TelnetAuthenticateOption::RecvSubOption"); return; } if ( ! peer->DidRequestAuthentication() ) InconsistentOption(0); } break; case SEND_ME_AUTHENTICATION: ++authentication_requested; break; case AUTHENTICATION_STATUS: if ( len <= 1 ) { BadOption(); return; } if ( data[1] == AUTH_REJECT ) endp->AuthenticationRejected(); else if ( data[1] == AUTH_ACCEPT ) endp->AuthenticationAccepted(); else { // Don't complain, there may be replies we don't // know about. } break; case AUTHENTICATION_NAME: { char* auth_name = new char[len]; safe_strncpy(auth_name, (char*) data + 1, len); endp->SetAuthName(auth_name); } break; default: BadOption(); } } #define ENVIRON_IS 0 #define ENVIRON_SEND 1 #define ENVIRON_INFO 2 #define ENVIRON_VAR 0 #define ENVIRON_VAL 1 #define ENVIRON_ESC 2 #define ENVIRON_USERVAR 3 void TelnetEnvironmentOption::RecvSubOption(u_char* data, int len) { if ( len <= 0 ) { BadOption(); return; } if ( data[0] == ENVIRON_SEND ) //### We should track the dialog and make sure both sides agree. return; if ( data[0] != ENVIRON_IS && data[0] != ENVIRON_INFO ) { BadOption(); return; } --len; // Discard code. ++data; while ( len > 0 ) { int code1, code2; char* var_name = ExtractEnv(data, len, code1); char* var_val = ExtractEnv(data, len, code2); if ( ! var_name || ! var_val || (code1 != ENVIRON_VAR && code1 != ENVIRON_USERVAR) || code2 != ENVIRON_VAL ) { // One of var_name/var_val might be set; avoid leak. delete [] var_name; delete [] var_val; BadOption(); break; } static_cast<tcp::TCP_ApplicationAnalyzer*> (endp->Parent())->SetEnv(endp->IsOrig(), var_name, var_val); } } char* TelnetEnvironmentOption::ExtractEnv(u_char*& data, int& len, int& code) { code = data[0]; if ( code != ENVIRON_VAR && code != ENVIRON_VAL && code != ENVIRON_USERVAR ) return nullptr; // Move past code. --len; ++data; // Find the end of this piece of the option. u_char* data_end = data + len; u_char* d; for ( d = data; d < data_end; ++d ) { if ( *d == ENVIRON_VAR || *d == ENVIRON_VAL || *d == ENVIRON_USERVAR ) break; if ( *d == ENVIRON_ESC ) { ++d; // move past ESC if ( d >= data_end ) return nullptr; break; } } int size = d - data; char* env = new char[size+1]; // Now copy into env. int d_ind = 0; int i; for ( i = 0; i < size; ++i ) { if ( data[d_ind] == ENVIRON_ESC ) ++d_ind; env[i] = data[d_ind]; ++d_ind; } env[i] = '\0'; data = d; len -= size; return env; } void TelnetBinaryOption::SetActive(bool is_active) { endp->SetBinaryMode(is_active); active = is_active; } void TelnetBinaryOption::InconsistentOption(unsigned int /* type */) { // I don't know why, but this gets turned on redundantly - // doesn't do any harm, so ignore it. Example is // in ex/redund-binary-opt.trace. } NVT_Analyzer::NVT_Analyzer(Connection* conn, bool orig) : tcp::ContentLine_Analyzer("NVT", conn, orig), options() { } NVT_Analyzer::~NVT_Analyzer() { for ( int i = 0; i < num_options; ++i ) delete options[i]; delete [] auth_name; } TelnetOption* NVT_Analyzer::FindOption(unsigned int code) { int i; for ( i = 0; i < num_options; ++i ) if ( options[i]->Code() == code ) return options[i]; TelnetOption* opt = nullptr; if ( i < NUM_TELNET_OPTIONS ) { // Maybe we haven't created this option yet. switch ( code ) { case TELNET_OPTION_BINARY: opt = new TelnetBinaryOption(this); break; case TELNET_OPTION_TERMINAL: opt = new TelnetTerminalOption(this); break; case TELNET_OPTION_ENCRYPT: opt = new TelnetEncryptOption(this); break; case TELNET_OPTION_AUTHENTICATE: opt = new TelnetAuthenticateOption(this); break; case TELNET_OPTION_ENVIRON: opt = new TelnetEnvironmentOption(this); break; } } if ( opt ) options[num_options++] = opt; return opt; } TelnetOption* NVT_Analyzer::FindPeerOption(unsigned int code) { assert(peer); return peer->FindOption(code); } void NVT_Analyzer::AuthenticationAccepted() { authentication_has_been_accepted = true; Event(authentication_accepted, PeerAuthName()); } void NVT_Analyzer::AuthenticationRejected() { authentication_has_been_accepted = false; Event(authentication_rejected, PeerAuthName()); } const char* NVT_Analyzer::PeerAuthName() const { assert(peer); return peer->AuthName(); } void NVT_Analyzer::SetTerminal(const u_char* terminal, int len) { if ( login_terminal ) EnqueueConnEvent(login_terminal, ConnVal(), make_intrusive<StringVal>(new BroString(terminal, len, false)) ); } void NVT_Analyzer::SetEncrypting(int mode) { encrypting_mode = mode; SetSkipDeliveries(mode); if ( mode ) Event(activating_encryption); } #define MAX_DELIVER_UNIT 128 void NVT_Analyzer::DoDeliver(int len, const u_char* data) { // This code is very similar to that for TCP_ContentLine. We // don't virtualize out the differences because some of them // would require per-character function calls, too expensive. if ( pending_IAC ) { ScanOption(seq, len, data); return; } // Add data up to IAC or end. for ( ; len > 0; --len, ++data ) { if ( offset >= buf_len ) InitBuffer(buf_len * 2); int c = data[0]; if ( binary_mode && c != TELNET_IAC ) c &= 0x7f; #define EMIT_LINE \ { \ buf[offset] = '\0'; \ ForwardStream(offset, buf, IsOrig()); \ offset = 0; \ } switch ( c ) { case '\r': if ( CRLFAsEOL() & CR_as_EOL ) EMIT_LINE else buf[offset++] = c; break; case '\n': if ( last_char == '\r' ) { if ( CRLFAsEOL() & CR_as_EOL ) // we already emited, skip ; else { --offset; // remove '\r' EMIT_LINE } } else if ( CRLFAsEOL() & LF_as_EOL ) EMIT_LINE else { if ( Conn()->FlagEvent(SINGULAR_LF) ) Conn()->Weird("line_terminated_with_single_LF"); buf[offset++] = c; } break; case '\0': if ( last_char == '\r' ) // Allow a NUL just after a \r - Solaris // Telnet servers generate these, and they // appear harmless. ; else if ( flag_NULs ) CheckNUL(); else buf[offset++] = c; break; case TELNET_IAC: pending_IAC = true; IAC_pos = offset; is_suboption = false; buf[offset++] = c; ScanOption(seq, len - 1, data + 1); return; default: buf[offset++] = c; break; } if ( ! (CRLFAsEOL() & CR_as_EOL) && last_char == '\r' && c != '\n' && c != '\0' ) { if ( Conn()->FlagEvent(SINGULAR_CR) ) Weird("line_terminated_with_single_CR"); } last_char = c; } } void NVT_Analyzer::ScanOption(int seq, int len, const u_char* data) { if ( len <= 0 ) return; if ( IAC_pos == offset - 1 ) { // All we've seen so far is the IAC. unsigned int code = data[0]; if ( code == TELNET_IAC ) { // An escaped 255, throw away the second // instance and drop the IAC state. pending_IAC = false; last_char = code; } else if ( code == TELNET_OPT_SB ) { is_suboption = true; last_was_IAC = false; if ( offset >= buf_len ) InitBuffer(buf_len * 2); buf[offset++] = code; } else if ( IS_3_BYTE_OPTION(code) ) { is_suboption = false; if ( offset >= buf_len ) InitBuffer(buf_len * 2); buf[offset++] = code; } else { // We've got the whole 2-byte option. SawOption(code); // Throw it and the IAC away. --offset; pending_IAC = false; } // Recurse to munch on the remainder. DeliverStream(len - 1, data + 1, IsOrig()); return; } if ( ! is_suboption ) { // We now have the full 3-byte option. SawOption(u_char(buf[offset-1]), data[0]); // Delete the option. offset -= 2; // code + IAC pending_IAC = false; DeliverStream(len - 1, data + 1, IsOrig()); return; } // A suboption. Spin looking for end. for ( ; len > 0; --len, ++data ) { if ( offset >= buf_len ) InitBuffer(buf_len * 2); unsigned int code = data[0]; if ( last_was_IAC ) { last_was_IAC = false; if ( code == TELNET_IAC ) { // This is an escaped IAC, eat // the second copy. continue; } if ( code != TELNET_OPT_SE ) // BSD Telnet treats this case as terminating // the suboption, so that's what we do here // too. Below we make sure to munch on the // new IAC. BadOptionTermination(code); int opt_start = IAC_pos + 2; int opt_stop = offset - 1; int opt_len = opt_stop - opt_start; SawSubOption((const char*)&buf[opt_start], opt_len); // Delete suboption. offset = IAC_pos; pending_IAC = is_suboption = false; if ( code == TELNET_OPT_SE ) DeliverStream(len - 1, data + 1, IsOrig()); else { // Munch on the new (broken) option. pending_IAC = true; IAC_pos = offset; buf[offset++] = TELNET_IAC; DeliverStream(len, data, IsOrig()); } return; } else { buf[offset++] = code; last_was_IAC = (code == TELNET_IAC); } } } void NVT_Analyzer::SawOption(unsigned int /* code */) { } void NVT_Analyzer::SawOption(unsigned int code, unsigned int subcode) { TelnetOption* opt = FindOption(subcode); if ( opt ) opt->RecvOption(code); } void NVT_Analyzer::SawSubOption(const char* subopt, int len) { unsigned int subcode = u_char(subopt[0]); ++subopt; --len; TelnetOption* opt = FindOption(subcode); if ( opt ) opt->RecvSubOption((u_char*) subopt, len); } void NVT_Analyzer::BadOptionTermination(unsigned int /* code */) { Event(bad_option_termination); }
c++
code
13,717
3,183
// Copyright (C) 2018-2020 CERN // License Apache2 - see LICENCE file #include "countmon.h" #include <string.h> #include <unistd.h> #include <fstream> #include <iostream> #include <sstream> #include "utils.h" // Constructor; uses RAII pattern to be valid // after construction countmon::countmon() : count_params{}, count_stats{}, count_peak_stats{}, count_average_stats{}, count_total_stats{}, iterations{0L} { count_params.reserve(params.size()); for (const auto& param : params) { count_params.push_back(param.get_name()); count_stats[param.get_name()] = 0; count_peak_stats[param.get_name()] = 0; count_average_stats[param.get_name()] = 0; count_total_stats[param.get_name()] = 0; } } void countmon::update_stats(const std::vector<pid_t>& pids) { for (auto& stat : count_stats) stat.second = 0; std::vector<std::string> stat_entries{}; stat_entries.reserve(prmon::stat_count_read_limit + 1); std::string tmp_str{}; for (const auto pid : pids) { std::stringstream stat_fname{}; stat_fname << "/proc/" << pid << "/stat" << std::ends; std::ifstream proc_stat{stat_fname.str()}; while (proc_stat && stat_entries.size() < prmon::stat_count_read_limit + 1) { proc_stat >> tmp_str; if (proc_stat) stat_entries.push_back(tmp_str); } if (stat_entries.size() > prmon::stat_count_read_limit) { count_stats["nprocs"] += 1L; count_stats["nthreads"] += std::stol(stat_entries[prmon::num_threads]); } stat_entries.clear(); } // Update the statistics with the new snapshot values ++iterations; for (const auto& count_param : count_params) { if (count_stats[count_param] > count_peak_stats[count_param]) count_peak_stats[count_param] = count_stats[count_param]; count_total_stats[count_param] += count_stats[count_param]; count_average_stats[count_param] = double(count_total_stats[count_param]) / iterations; } } // Return the counters std::map<std::string, unsigned long long> const countmon::get_text_stats() { return count_stats; } // For JSON return the peaks std::map<std::string, unsigned long long> const countmon::get_json_total_stats() { return count_peak_stats; } // An the averages std::map<std::string, double> const countmon::get_json_average_stats( unsigned long long elapsed_clock_ticks) { return count_average_stats; } // Collect related hardware information void const countmon::get_hardware_info(nlohmann::json& hw_json) { return; } void const countmon::get_unit_info(nlohmann::json& unit_json) { prmon::fill_units(unit_json, params); return; }
c++
code
2,650
596
// // main.cpp // 34 - Find First and Last Position of Element in Sorted Array // // Created by ynfMac on 2019/11/6. // Copyright © 2019 ynfMac. All rights reserved. // #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { // 二分收索 int start = 0; int end = 0; int n = nums.size(); int m = nums.size(); bool hasfind = false; while (start < n) { int middle = start + (n - start)/2; if (nums[middle] < target) { start = middle + 1; } else { n = middle; if (nums[middle] == target) { hasfind = true; } } } while (end < m) { int middle = end + (m - end)/2; if (nums[middle] <= target) { end = middle + 1; if (nums[middle] == target) { hasfind = true; } } else { m = middle; } } if (!hasfind) { return vector<int>{-1, -1}; } return vector<int>{start,end-1}; } }; int main(int argc, const char * argv[]) { vector<int> d = vector<int>{5,7,7,7,8,10}; vector<int> vec = Solution().searchRange(d, 7); for (int a : vec) { cout << a << " "; } std::cout << "Hello, World!\n"; return 0; }
c++
code
1,543
353
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__new_free_long_54c.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_free.label.xml Template File: sources-sinks-54c.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: Allocate data using new * GoodSource: Allocate data using malloc() * Sinks: * GoodSink: Deallocate data using delete * BadSink : Deallocate data using free() * Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__new_free_long_54 { #ifndef OMITBAD /* bad function declaration */ void badSink_d(long * data); void badSink_c(long * data) { badSink_d(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink_d(long * data); void goodG2BSink_c(long * data) { goodG2BSink_d(data); } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink_d(long * data); void goodB2GSink_c(long * data) { goodB2GSink_d(data); } #endif /* OMITGOOD */ } /* close namespace */
c++
code
1,336
233
// Copyright (c) 2012-2018 The Pyeongtaekcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util.h> #include <utiltime.h> #include <validation.h> #include <test/test_pyeongtaekcoin.h> #include <checkqueue.h> #include <boost/test/unit_test.hpp> #include <boost/thread.hpp> #include <atomic> #include <thread> #include <vector> #include <mutex> #include <condition_variable> #include <unordered_set> #include <memory> #include <random.h> // BasicTestingSetup not sufficient because nScriptCheckThreads is not set // otherwise. BOOST_FIXTURE_TEST_SUITE(checkqueue_tests, TestingSetup) static const unsigned int QUEUE_BATCH_SIZE = 128; struct FakeCheck { bool operator()() { return true; } void swap(FakeCheck& x){}; }; struct FakeCheckCheckCompletion { static std::atomic<size_t> n_calls; bool operator()() { n_calls.fetch_add(1, std::memory_order_relaxed); return true; } void swap(FakeCheckCheckCompletion& x){}; }; struct FailingCheck { bool fails; FailingCheck(bool _fails) : fails(_fails){}; FailingCheck() : fails(true){}; bool operator()() { return !fails; } void swap(FailingCheck& x) { std::swap(fails, x.fails); }; }; struct UniqueCheck { static std::mutex m; static std::unordered_multiset<size_t> results; size_t check_id; UniqueCheck(size_t check_id_in) : check_id(check_id_in){}; UniqueCheck() : check_id(0){}; bool operator()() { std::lock_guard<std::mutex> l(m); results.insert(check_id); return true; } void swap(UniqueCheck& x) { std::swap(x.check_id, check_id); }; }; struct MemoryCheck { static std::atomic<size_t> fake_allocated_memory; bool b {false}; bool operator()() { return true; } MemoryCheck(){}; MemoryCheck(const MemoryCheck& x) { // We have to do this to make sure that destructor calls are paired // // Really, copy constructor should be deletable, but CCheckQueue breaks // if it is deleted because of internal push_back. fake_allocated_memory.fetch_add(b, std::memory_order_relaxed); }; MemoryCheck(bool b_) : b(b_) { fake_allocated_memory.fetch_add(b, std::memory_order_relaxed); }; ~MemoryCheck() { fake_allocated_memory.fetch_sub(b, std::memory_order_relaxed); }; void swap(MemoryCheck& x) { std::swap(b, x.b); }; }; struct FrozenCleanupCheck { static std::atomic<uint64_t> nFrozen; static std::condition_variable cv; static std::mutex m; // Freezing can't be the default initialized behavior given how the queue // swaps in default initialized Checks. bool should_freeze {false}; bool operator()() { return true; } FrozenCleanupCheck() {} ~FrozenCleanupCheck() { if (should_freeze) { std::unique_lock<std::mutex> l(m); nFrozen.store(1, std::memory_order_relaxed); cv.notify_one(); cv.wait(l, []{ return nFrozen.load(std::memory_order_relaxed) == 0;}); } } void swap(FrozenCleanupCheck& x){std::swap(should_freeze, x.should_freeze);}; }; // Static Allocations std::mutex FrozenCleanupCheck::m{}; std::atomic<uint64_t> FrozenCleanupCheck::nFrozen{0}; std::condition_variable FrozenCleanupCheck::cv{}; std::mutex UniqueCheck::m; std::unordered_multiset<size_t> UniqueCheck::results; std::atomic<size_t> FakeCheckCheckCompletion::n_calls{0}; std::atomic<size_t> MemoryCheck::fake_allocated_memory{0}; // Queue Typedefs typedef CCheckQueue<FakeCheckCheckCompletion> Correct_Queue; typedef CCheckQueue<FakeCheck> Standard_Queue; typedef CCheckQueue<FailingCheck> Failing_Queue; typedef CCheckQueue<UniqueCheck> Unique_Queue; typedef CCheckQueue<MemoryCheck> Memory_Queue; typedef CCheckQueue<FrozenCleanupCheck> FrozenCleanup_Queue; /** This test case checks that the CCheckQueue works properly * with each specified size_t Checks pushed. */ static void Correct_Queue_range(std::vector<size_t> range) { auto small_queue = std::unique_ptr<Correct_Queue>(new Correct_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{small_queue->Thread();}); } // Make vChecks here to save on malloc (this test can be slow...) std::vector<FakeCheckCheckCompletion> vChecks; for (auto i : range) { size_t total = i; FakeCheckCheckCompletion::n_calls = 0; CCheckQueueControl<FakeCheckCheckCompletion> control(small_queue.get()); while (total) { vChecks.resize(std::min(total, (size_t) InsecureRandRange(10))); total -= vChecks.size(); control.Add(vChecks); } BOOST_REQUIRE(control.Wait()); if (FakeCheckCheckCompletion::n_calls != i) { BOOST_REQUIRE_EQUAL(FakeCheckCheckCompletion::n_calls, i); BOOST_TEST_MESSAGE("Failure on trial " << i << " expected, got " << FakeCheckCheckCompletion::n_calls); } } tg.interrupt_all(); tg.join_all(); } /** Test that 0 checks is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Zero) { std::vector<size_t> range; range.push_back((size_t)0); Correct_Queue_range(range); } /** Test that 1 check is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_One) { std::vector<size_t> range; range.push_back((size_t)1); Correct_Queue_range(range); } /** Test that MAX check is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Max) { std::vector<size_t> range; range.push_back(100000); Correct_Queue_range(range); } /** Test that random numbers of checks are correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Random) { std::vector<size_t> range; range.reserve(100000/1000); for (size_t i = 2; i < 100000; i += std::max((size_t)1, (size_t)InsecureRandRange(std::min((size_t)1000, ((size_t)100000) - i)))) range.push_back(i); Correct_Queue_range(range); } /** Test that failing checks are caught */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Catches_Failure) { auto fail_queue = std::unique_ptr<Failing_Queue>(new Failing_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{fail_queue->Thread();}); } for (size_t i = 0; i < 1001; ++i) { CCheckQueueControl<FailingCheck> control(fail_queue.get()); size_t remaining = i; while (remaining) { size_t r = InsecureRandRange(10); std::vector<FailingCheck> vChecks; vChecks.reserve(r); for (size_t k = 0; k < r && remaining; k++, remaining--) vChecks.emplace_back(remaining == 1); control.Add(vChecks); } bool success = control.Wait(); if (i > 0) { BOOST_REQUIRE(!success); } else if (i == 0) { BOOST_REQUIRE(success); } } tg.interrupt_all(); tg.join_all(); } // Test that a block validation which fails does not interfere with // future blocks, ie, the bad state is cleared. BOOST_AUTO_TEST_CASE(test_CheckQueue_Recovers_From_Failure) { auto fail_queue = std::unique_ptr<Failing_Queue>(new Failing_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{fail_queue->Thread();}); } for (auto times = 0; times < 10; ++times) { for (bool end_fails : {true, false}) { CCheckQueueControl<FailingCheck> control(fail_queue.get()); { std::vector<FailingCheck> vChecks; vChecks.resize(100, false); vChecks[99] = end_fails; control.Add(vChecks); } bool r =control.Wait(); BOOST_REQUIRE(r != end_fails); } } tg.interrupt_all(); tg.join_all(); } // Test that unique checks are actually all called individually, rather than // just one check being called repeatedly. Test that checks are not called // more than once as well BOOST_AUTO_TEST_CASE(test_CheckQueue_UniqueCheck) { auto queue = std::unique_ptr<Unique_Queue>(new Unique_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{queue->Thread();}); } size_t COUNT = 100000; size_t total = COUNT; { CCheckQueueControl<UniqueCheck> control(queue.get()); while (total) { size_t r = InsecureRandRange(10); std::vector<UniqueCheck> vChecks; for (size_t k = 0; k < r && total; k++) vChecks.emplace_back(--total); control.Add(vChecks); } } bool r = true; BOOST_REQUIRE_EQUAL(UniqueCheck::results.size(), COUNT); for (size_t i = 0; i < COUNT; ++i) r = r && UniqueCheck::results.count(i) == 1; BOOST_REQUIRE(r); tg.interrupt_all(); tg.join_all(); } // Test that blocks which might allocate lots of memory free their memory aggressively. // // This test attempts to catch a pathological case where by lazily freeing // checks might mean leaving a check un-swapped out, and decreasing by 1 each // time could leave the data hanging across a sequence of blocks. BOOST_AUTO_TEST_CASE(test_CheckQueue_Memory) { auto queue = std::unique_ptr<Memory_Queue>(new Memory_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{queue->Thread();}); } for (size_t i = 0; i < 1000; ++i) { size_t total = i; { CCheckQueueControl<MemoryCheck> control(queue.get()); while (total) { size_t r = InsecureRandRange(10); std::vector<MemoryCheck> vChecks; for (size_t k = 0; k < r && total; k++) { total--; // Each iteration leaves data at the front, back, and middle // to catch any sort of deallocation failure vChecks.emplace_back(total == 0 || total == i || total == i/2); } control.Add(vChecks); } } BOOST_REQUIRE_EQUAL(MemoryCheck::fake_allocated_memory, 0U); } tg.interrupt_all(); tg.join_all(); } // Test that a new verification cannot occur until all checks // have been destructed BOOST_AUTO_TEST_CASE(test_CheckQueue_FrozenCleanup) { auto queue = std::unique_ptr<FrozenCleanup_Queue>(new FrozenCleanup_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; bool fails = false; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{queue->Thread();}); } std::thread t0([&]() { CCheckQueueControl<FrozenCleanupCheck> control(queue.get()); std::vector<FrozenCleanupCheck> vChecks(1); // Freezing can't be the default initialized behavior given how the queue // swaps in default initialized Checks (otherwise freezing destructor // would get called twice). vChecks[0].should_freeze = true; control.Add(vChecks); control.Wait(); // Hangs here }); { std::unique_lock<std::mutex> l(FrozenCleanupCheck::m); // Wait until the queue has finished all jobs and frozen FrozenCleanupCheck::cv.wait(l, [](){return FrozenCleanupCheck::nFrozen == 1;}); } // Try to get control of the queue a bunch of times for (auto x = 0; x < 100 && !fails; ++x) { fails = queue->ControlMutex.try_lock(); } { // Unfreeze (we need lock n case of spurious wakeup) std::unique_lock<std::mutex> l(FrozenCleanupCheck::m); FrozenCleanupCheck::nFrozen = 0; } // Awaken frozen destructor FrozenCleanupCheck::cv.notify_one(); // Wait for control to finish t0.join(); tg.interrupt_all(); tg.join_all(); BOOST_REQUIRE(!fails); } /** Test that CCheckQueueControl is threadsafe */ BOOST_AUTO_TEST_CASE(test_CheckQueueControl_Locks) { auto queue = std::unique_ptr<Standard_Queue>(new Standard_Queue{QUEUE_BATCH_SIZE}); { boost::thread_group tg; std::atomic<int> nThreads {0}; std::atomic<int> fails {0}; for (size_t i = 0; i < 3; ++i) { tg.create_thread( [&]{ CCheckQueueControl<FakeCheck> control(queue.get()); // While sleeping, no other thread should execute to this point auto observed = ++nThreads; MilliSleep(10); fails += observed != nThreads; }); } tg.join_all(); BOOST_REQUIRE_EQUAL(fails, 0); } { boost::thread_group tg; std::mutex m; std::condition_variable cv; bool has_lock{false}; bool has_tried{false}; bool done{false}; bool done_ack{false}; { std::unique_lock<std::mutex> l(m); tg.create_thread([&]{ CCheckQueueControl<FakeCheck> control(queue.get()); std::unique_lock<std::mutex> ll(m); has_lock = true; cv.notify_one(); cv.wait(ll, [&]{return has_tried;}); done = true; cv.notify_one(); // Wait until the done is acknowledged // cv.wait(ll, [&]{return done_ack;}); }); // Wait for thread to get the lock cv.wait(l, [&](){return has_lock;}); bool fails = false; for (auto x = 0; x < 100 && !fails; ++x) { fails = queue->ControlMutex.try_lock(); } has_tried = true; cv.notify_one(); cv.wait(l, [&](){return done;}); // Acknowledge the done done_ack = true; cv.notify_one(); BOOST_REQUIRE(!fails); } tg.join_all(); } } BOOST_AUTO_TEST_SUITE_END()
c++
code
14,329
3,073
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2017 Sebastian Koch <[email protected]> and Daniele Panozzo <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. m.def("jet", [] ( const Eigen::MatrixXd& Z, const bool normalize, Eigen::MatrixXd& C ) { assert_is_VectorX("Z",Z); return igl::jet(Z,normalize,C); }, __doc_igl_jet, py::arg("Z"), py::arg("normalize"), py::arg("C")); m.def("jet", [] ( const Eigen::MatrixXd& Z, const double min_Z, const double max_Z, Eigen::MatrixXd& C ) { assert_is_VectorX("Z",Z); return igl::jet(Z,min_Z,max_Z,C); }, __doc_igl_jet, py::arg("Z"), py::arg("min_Z"), py::arg("max_Z"), py::arg("C"));
c++
code
876
272
// Copyright (c) 2011-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <qt/bitcoin.h> #include <qt/bitcoingui.h> #include <chainparams.h> #include <qt/clientmodel.h> #include <qt/guiconstants.h> #include <qt/guiutil.h> #include <qt/intro.h> #include <qt/networkstyle.h> #include <qt/optionsmodel.h> #include <qt/platformstyle.h> #include <qt/splashscreen.h> #include <qt/utilitydialog.h> #include <qt/winshutdownmonitor.h> #ifdef ENABLE_WALLET #include <qt/paymentserver.h> #include <qt/walletcontroller.h> #include <qt/walletmodel.h> #endif // ENABLE_WALLET #include <init.h> #include <interfaces/handler.h> #include <interfaces/node.h> #include <node/context.h> #include <node/ui_interface.h> #include <noui.h> #include <uint256.h> #include <util/system.h> #include <util/threadnames.h> #include <util/translation.h> #include <validation.h> #include <boost/signals2/connection.hpp> #include <memory> #include <QApplication> #include <QDebug> #include <QFontDatabase> #include <QLibraryInfo> #include <QLocale> #include <QMessageBox> #include <QSettings> #include <QThread> #include <QTimer> #include <QTranslator> #if defined(QT_STATICPLUGIN) #include <QtPlugin> #if defined(QT_QPA_PLATFORM_XCB) Q_IMPORT_PLUGIN(QXcbIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_WINDOWS) Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_COCOA) Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin); Q_IMPORT_PLUGIN(QMacStylePlugin); #endif #endif // Declare meta types used for QMetaObject::invokeMethod Q_DECLARE_METATYPE(bool*) Q_DECLARE_METATYPE(CAmount) Q_DECLARE_METATYPE(SynchronizationState) Q_DECLARE_METATYPE(uint256) static void RegisterMetaTypes() { // Register meta types used for QMetaObject::invokeMethod and Qt::QueuedConnection qRegisterMetaType<bool*>(); qRegisterMetaType<SynchronizationState>(); #ifdef ENABLE_WALLET qRegisterMetaType<WalletModel*>(); #endif // Register typedefs (see https://doc.qt.io/qt-5/qmetatype.html#qRegisterMetaType) // IMPORTANT: if CAmount is no longer a typedef use the normal variant above (see https://doc.qt.io/qt-5/qmetatype.html#qRegisterMetaType-1) qRegisterMetaType<CAmount>("CAmount"); qRegisterMetaType<size_t>("size_t"); qRegisterMetaType<std::function<void()>>("std::function<void()>"); qRegisterMetaType<QMessageBox::Icon>("QMessageBox::Icon"); qRegisterMetaType<interfaces::BlockAndHeaderTipInfo>("interfaces::BlockAndHeaderTipInfo"); } static QString GetLangTerritory() { QSettings settings; // Get desired locale (e.g. "de_DE") // 1) System default language QString lang_territory = QLocale::system().name(); // 2) Language from QSettings QString lang_territory_qsettings = settings.value("language", "").toString(); if(!lang_territory_qsettings.isEmpty()) lang_territory = lang_territory_qsettings; // 3) -lang command line argument lang_territory = QString::fromStdString(gArgs.GetArg("-lang", lang_territory.toStdString())); return lang_territory; } /** Set up translations */ static void initTranslations(QTranslator &qtTranslatorBase, QTranslator &qtTranslator, QTranslator &translatorBase, QTranslator &translator) { // Remove old translators QApplication::removeTranslator(&qtTranslatorBase); QApplication::removeTranslator(&qtTranslator); QApplication::removeTranslator(&translatorBase); QApplication::removeTranslator(&translator); // Get desired locale (e.g. "de_DE") // 1) System default language QString lang_territory = GetLangTerritory(); // Convert to "de" only by truncating "_DE" QString lang = lang_territory; lang.truncate(lang_territory.lastIndexOf('_')); // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) QApplication::installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) QApplication::installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) QApplication::installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) QApplication::installTranslator(&translator); } /* qDebug() message handler --> debug.log */ void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString &msg) { Q_UNUSED(context); if (type == QtDebugMsg) { LogPrint(BCLog::QT, "GUI: %s\n", msg.toStdString()); } else { LogPrintf("GUI: %s\n", msg.toStdString()); } } BitcoinCore::BitcoinCore(interfaces::Node& node) : QObject(), m_node(node) { } void BitcoinCore::handleRunawayException(const std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); Q_EMIT runawayException(QString::fromStdString(m_node.getWarnings().translated)); } void BitcoinCore::initialize() { try { util::ThreadRename("qt-init"); qDebug() << __func__ << ": Running initialization in thread"; interfaces::BlockAndHeaderTipInfo tip_info; bool rv = m_node.appInitMain(&tip_info); Q_EMIT initializeResult(rv, tip_info); } catch (const std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(nullptr); } } void BitcoinCore::shutdown() { try { qDebug() << __func__ << ": Running Shutdown in thread"; m_node.appShutdown(); qDebug() << __func__ << ": Shutdown finished"; Q_EMIT shutdownResult(); } catch (const std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(nullptr); } } static int qt_argc = 1; static const char* qt_argv = "bitcoin-qt"; BitcoinApplication::BitcoinApplication(): QApplication(qt_argc, const_cast<char **>(&qt_argv)), coreThread(nullptr), optionsModel(nullptr), clientModel(nullptr), window(nullptr), pollShutdownTimer(nullptr), returnValue(0), platformStyle(nullptr) { // Qt runs setlocale(LC_ALL, "") on initialization. RegisterMetaTypes(); setQuitOnLastWindowClosed(false); } void BitcoinApplication::setupPlatformStyle() { // UI per-platform customization // This must be done inside the BitcoinApplication constructor, or after it, because // PlatformStyle::instantiate requires a QApplication std::string platformName; platformName = gArgs.GetArg("-uiplatform", BitcoinGUI::DEFAULT_UIPLATFORM); platformStyle = PlatformStyle::instantiate(QString::fromStdString(platformName)); if (!platformStyle) // Fall back to "other" if specified name not found platformStyle = PlatformStyle::instantiate("other"); assert(platformStyle); } BitcoinApplication::~BitcoinApplication() { if(coreThread) { qDebug() << __func__ << ": Stopping thread"; coreThread->quit(); coreThread->wait(); qDebug() << __func__ << ": Stopped thread"; } delete window; window = nullptr; delete platformStyle; platformStyle = nullptr; } #ifdef ENABLE_WALLET void BitcoinApplication::createPaymentServer() { paymentServer = new PaymentServer(this); } #endif void BitcoinApplication::createOptionsModel(bool resetSettings) { optionsModel = new OptionsModel(this, resetSettings); } void BitcoinApplication::createWindow(const NetworkStyle *networkStyle) { window = new BitcoinGUI(node(), platformStyle, networkStyle, nullptr); pollShutdownTimer = new QTimer(window); connect(pollShutdownTimer, &QTimer::timeout, window, &BitcoinGUI::detectShutdown); } void BitcoinApplication::createSplashScreen(const NetworkStyle *networkStyle) { assert(!m_splash); m_splash = new SplashScreen(networkStyle); // We don't hold a direct pointer to the splash screen after creation, but the splash // screen will take care of deleting itself when finish() happens. m_splash->show(); connect(this, &BitcoinApplication::requestedInitialize, m_splash, &SplashScreen::handleLoadWallet); connect(this, &BitcoinApplication::splashFinished, m_splash, &SplashScreen::finish); connect(this, &BitcoinApplication::requestedShutdown, m_splash, &QWidget::close); } void BitcoinApplication::setNode(interfaces::Node& node) { assert(!m_node); m_node = &node; if (optionsModel) optionsModel->setNode(*m_node); if (m_splash) m_splash->setNode(*m_node); } bool BitcoinApplication::baseInitialize() { return node().baseInitialize(); } void BitcoinApplication::startThread() { if(coreThread) return; coreThread = new QThread(this); BitcoinCore *executor = new BitcoinCore(node()); executor->moveToThread(coreThread); /* communication to and from thread */ connect(executor, &BitcoinCore::initializeResult, this, &BitcoinApplication::initializeResult); connect(executor, &BitcoinCore::shutdownResult, this, &BitcoinApplication::shutdownResult); connect(executor, &BitcoinCore::runawayException, this, &BitcoinApplication::handleRunawayException); connect(this, &BitcoinApplication::requestedInitialize, executor, &BitcoinCore::initialize); connect(this, &BitcoinApplication::requestedShutdown, executor, &BitcoinCore::shutdown); /* make sure executor object is deleted in its own thread */ connect(coreThread, &QThread::finished, executor, &QObject::deleteLater); coreThread->start(); } void BitcoinApplication::parameterSetup() { // Default printtoconsole to false for the GUI. GUI programs should not // print to the console unnecessarily. gArgs.SoftSetBoolArg("-printtoconsole", false); InitLogging(gArgs); InitParameterInteraction(gArgs); } void BitcoinApplication::InitializePruneSetting(bool prune) { // If prune is set, intentionally override existing prune size with // the default size since this is called when choosing a new datadir. optionsModel->SetPruneTargetGB(prune ? DEFAULT_PRUNE_TARGET_GB : 0, true); } void BitcoinApplication::requestInitialize() { qDebug() << __func__ << ": Requesting initialize"; startThread(); Q_EMIT requestedInitialize(); } void BitcoinApplication::requestShutdown() { // Show a simple window indicating shutdown status // Do this first as some of the steps may take some time below, // for example the RPC console may still be executing a command. shutdownWindow.reset(ShutdownWindow::showShutdownWindow(window)); qDebug() << __func__ << ": Requesting shutdown"; startThread(); window->hide(); // Must disconnect node signals otherwise current thread can deadlock since // no event loop is running. window->unsubscribeFromCoreSignals(); // Request node shutdown, which can interrupt long operations, like // rescanning a wallet. node().startShutdown(); // Unsetting the client model can cause the current thread to wait for node // to complete an operation, like wait for a RPC execution to complete. window->setClientModel(nullptr); pollShutdownTimer->stop(); delete clientModel; clientModel = nullptr; // Request shutdown from core thread Q_EMIT requestedShutdown(); } void BitcoinApplication::initializeResult(bool success, interfaces::BlockAndHeaderTipInfo tip_info) { qDebug() << __func__ << ": Initialization result: " << success; // Set exit result. returnValue = success ? EXIT_SUCCESS : EXIT_FAILURE; if(success) { // Log this only after AppInitMain finishes, as then logging setup is guaranteed complete qInfo() << "Platform customization:" << platformStyle->getName(); clientModel = new ClientModel(node(), optionsModel); window->setClientModel(clientModel, &tip_info); #ifdef ENABLE_WALLET if (WalletModel::isWalletEnabled()) { m_wallet_controller = new WalletController(*clientModel, platformStyle, this); window->setWalletController(m_wallet_controller); if (paymentServer) { paymentServer->setOptionsModel(optionsModel); } } #endif // ENABLE_WALLET // If -min option passed, start window minimized (iconified) or minimized to tray if (!gArgs.GetBoolArg("-min", false)) { window->show(); } else if (clientModel->getOptionsModel()->getMinimizeToTray() && window->hasTrayIcon()) { // do nothing as the window is managed by the tray icon } else { window->showMinimized(); } Q_EMIT splashFinished(); Q_EMIT windowShown(window); #ifdef ENABLE_WALLET // Now that initialization/startup is done, process any command-line // bitcoin: URIs or payment requests: if (paymentServer) { connect(paymentServer, &PaymentServer::receivedPaymentRequest, window, &BitcoinGUI::handlePaymentRequest); connect(window, &BitcoinGUI::receivedURI, paymentServer, &PaymentServer::handleURIOrFile); connect(paymentServer, &PaymentServer::message, [this](const QString& title, const QString& message, unsigned int style) { window->message(title, message, style); }); QTimer::singleShot(100, paymentServer, &PaymentServer::uiReady); } #endif pollShutdownTimer->start(200); } else { Q_EMIT splashFinished(); // Make sure splash screen doesn't stick around during shutdown quit(); // Exit first main loop invocation } } void BitcoinApplication::shutdownResult() { quit(); // Exit second main loop invocation after shutdown finished } void BitcoinApplication::handleRunawayException(const QString &message) { QMessageBox::critical(nullptr, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. %1 can no longer continue safely and will quit.").arg(PACKAGE_NAME) + QString("<br><br>") + message); ::exit(EXIT_FAILURE); } WId BitcoinApplication::getMainWinId() const { if (!window) return 0; return window->winId(); } static void SetupUIArgs(ArgsManager& argsman) { argsman.AddArg("-choosedatadir", strprintf("Choose data directory on startup (default: %u)", DEFAULT_CHOOSE_DATADIR), ArgsManager::ALLOW_ANY, OptionsCategory::GUI); argsman.AddArg("-lang=<lang>", "Set language, for example \"de_DE\" (default: system locale)", ArgsManager::ALLOW_ANY, OptionsCategory::GUI); argsman.AddArg("-min", "Start minimized", ArgsManager::ALLOW_ANY, OptionsCategory::GUI); argsman.AddArg("-resetguisettings", "Reset all settings changed in the GUI", ArgsManager::ALLOW_ANY, OptionsCategory::GUI); argsman.AddArg("-splash", strprintf("Show splash screen on startup (default: %u)", DEFAULT_SPLASHSCREEN), ArgsManager::ALLOW_ANY, OptionsCategory::GUI); argsman.AddArg("-uiplatform", strprintf("Select platform to customize UI for (one of windows, macosx, other; default: %s)", BitcoinGUI::DEFAULT_UIPLATFORM), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::GUI); } int GuiMain(int argc, char* argv[]) { #ifdef WIN32 util::WinCmdLineArgs winArgs; std::tie(argc, argv) = winArgs.get(); #endif SetupEnvironment(); util::ThreadSetInternalName("main"); NodeContext node_context; std::unique_ptr<interfaces::Node> node = interfaces::MakeNode(&node_context); // Subscribe to global signals from core boost::signals2::scoped_connection handler_message_box = ::uiInterface.ThreadSafeMessageBox_connect(noui_ThreadSafeMessageBox); boost::signals2::scoped_connection handler_question = ::uiInterface.ThreadSafeQuestion_connect(noui_ThreadSafeQuestion); boost::signals2::scoped_connection handler_init_message = ::uiInterface.InitMessage_connect(noui_InitMessage); // Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory /// 1. Basic Qt initialization (not dependent on parameters or configuration) Q_INIT_RESOURCE(bitcoin); Q_INIT_RESOURCE(bitcoin_locale); // Generate high-dpi pixmaps QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); BitcoinApplication app; QFontDatabase::addApplicationFont(":/fonts/monospace"); /// 2. Parse command-line options. We do this after qt in order to show an error if there are problems parsing these // Command-line options take precedence: SetupServerArgs(node_context); SetupUIArgs(gArgs); std::string error; if (!gArgs.ParseParameters(argc, argv, error)) { InitError(strprintf(Untranslated("Error parsing command line arguments: %s\n"), error)); // Create a message box, because the gui has neither been created nor has subscribed to core signals QMessageBox::critical(nullptr, PACKAGE_NAME, // message can not be translated because translations have not been initialized QString::fromStdString("Error parsing command line arguments: %1.").arg(QString::fromStdString(error))); return EXIT_FAILURE; } // Now that the QApplication is setup and we have parsed our parameters, we can set the platform style app.setupPlatformStyle(); /// 3. Application identification // must be set before OptionsModel is initialized or translations are loaded, // as it is used to locate QSettings QApplication::setOrganizationName(QAPP_ORG_NAME); QApplication::setOrganizationDomain(QAPP_ORG_DOMAIN); QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT); /// 4. Initialization of translations, so that intro dialog is in user's language // Now that QSettings are accessible, initialize translations QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) { HelpMessageDialog help(nullptr, gArgs.IsArgSet("-version")); help.showOrPrint(); return EXIT_SUCCESS; } // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); /// 5. Now that settings and translations are available, ask user for data directory // User language is set up: pick a data directory bool did_show_intro = false; bool prune = false; // Intro dialog prune check box // Gracefully exit if the user cancels if (!Intro::showIfNeeded(did_show_intro, prune)) return EXIT_SUCCESS; /// 6. Determine availability of data directory and parse bitcoin.conf /// - Do not call GetDataDir(true) before this step finishes if (!CheckDataDirOption()) { InitError(strprintf(Untranslated("Specified data directory \"%s\" does not exist.\n"), gArgs.GetArg("-datadir", ""))); QMessageBox::critical(nullptr, PACKAGE_NAME, QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(gArgs.GetArg("-datadir", "")))); return EXIT_FAILURE; } if (!gArgs.ReadConfigFiles(error, true)) { InitError(strprintf(Untranslated("Error reading configuration file: %s\n"), error));
c++
code
19,991
3,930
// RUN: %clang_cc1 -triple spir64-unknown-unknown -disable-llvm-passes -fsycl-is-device -emit-llvm %s -o - | FileCheck %s // Array-specific ivdep - annotate the correspondent GEPs only // // CHECK: define {{.*}}spir_func void @_Z{{[0-9]+}}ivdep_array_no_safelenv() void ivdep_array_no_safelen() { // CHECK: %[[ARRAY_A:[0-9a-z]+]] = alloca [10 x i32] int a[10]; // CHECK: %[[ARRAY_B:[0-9a-z]+]] = alloca [10 x i32] int b[10]; [[intel::ivdep(a)]] for (int i = 0; i != 10; ++i) { // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds [10 x i32], [10 x i32] addrspace(4)* %[[ARRAY_A]].ascast, i64 0, i64 %{{[0-9a-z]+}}, !llvm.index.group ![[IDX_GROUP_ARR:[0-9]+]] a[i] = 0; // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds [10 x i32], [10 x i32] addrspace(4)* %[[ARRAY_B]].ascast, i64 0, i64 %{{[0-9a-z]+}}{{[[:space:]]}} b[i] = 0; // CHECK: br label %for.cond, !llvm.loop ![[MD_LOOP_ARR:[0-9]+]] } } // Array-specific ivdep w/ safelen - annotate the correspondent GEPs only // CHECK: define {{.*}}spir_func void @_Z{{[0-9]+}}ivdep_array_with_safelenv() void ivdep_array_with_safelen() { // CHECK: %[[ARRAY_A:[0-9a-z]+]] = alloca [10 x i32] int a[10]; // CHECK: %[[ARRAY_B:[0-9a-z]+]] = alloca [10 x i32] int b[10]; [[intel::ivdep(a, 5)]] for (int i = 0; i != 10; ++i) { // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds [10 x i32], [10 x i32] addrspace(4)* %[[ARRAY_A]].ascast, i64 0, i64 %{{[0-9a-z]+}}, !llvm.index.group ![[IDX_GROUP_ARR_SAFELEN:[0-9]+]] a[i] = 0; // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds [10 x i32], [10 x i32] addrspace(4)* %[[ARRAY_B]].ascast, i64 0, i64 %{{[0-9a-z]+}}{{[[:space:]]}} b[i] = 0; // CHECK: br label %for.cond, !llvm.loop ![[MD_LOOP_ARR_SAFELEN:[0-9]+]] } } // Multiple array-specific ivdeps - annotate the correspondent GEPs // // CHECK: define {{.*}}spir_func void @_Z{{[0-9]+}}ivdep_multiple_arraysv() void ivdep_multiple_arrays() { // CHECK: %[[ARRAY_A:[0-9a-z]+]] = alloca [10 x i32] int a[10]; // CHECK: %[[ARRAY_B:[0-9a-z]+]] = alloca [10 x i32] int b[10]; // CHECK: %[[ARRAY_C:[0-9a-z]+]] = alloca [10 x i32] int c[10]; // CHECK: %[[ARRAY_D:[0-9a-z]+]] = alloca [10 x i32] int d[10]; [[intel::ivdep(a, 5)]] [[intel::ivdep(b, 5)]] [[intel::ivdep(c)]] [[intel::ivdep(d)]] for (int i = 0; i != 10; ++i) { // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds [10 x i32], [10 x i32] addrspace(4)* %[[ARRAY_A]].ascast, i64 0, i64 %{{[0-9a-z]+}}, !llvm.index.group ![[IDX_GROUP_A_MUL_ARR:[0-9]+]] a[i] = 0; // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds [10 x i32], [10 x i32] addrspace(4)* %[[ARRAY_B]].ascast, i64 0, i64 %{{[0-9a-z]+}}, !llvm.index.group ![[IDX_GROUP_B_MUL_ARR:[0-9]+]] b[i] = 0; // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds [10 x i32], [10 x i32] addrspace(4)* %[[ARRAY_C]].ascast, i64 0, i64 %{{[0-9a-z]+}}, !llvm.index.group ![[IDX_GROUP_C_MUL_ARR:[0-9]+]] c[i] = 0; // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds [10 x i32], [10 x i32] addrspace(4)* %[[ARRAY_D]].ascast, i64 0, i64 %{{[0-9a-z]+}}, !llvm.index.group ![[IDX_GROUP_D_MUL_ARR:[0-9]+]] d[i] = 0; // CHECK: br label %for.cond, !llvm.loop ![[MD_LOOP_MUL_ARR:[0-9]+]] } } // Global ivdep with INF safelen & array-specific ivdep with the same safelen // // CHECK: define {{.*}}spir_func void @_Z{{[0-9]+}}ivdep_array_and_globalv() void ivdep_array_and_global() { // CHECK: %[[ARRAY_A:[0-9a-z]+]] = alloca [10 x i32] int a[10]; // CHECK: %[[ARRAY_B:[0-9a-z]+]] = alloca [10 x i32] int b[10]; [[intel::ivdep]] [[intel::ivdep(a)]] for (int i = 0; i != 10; ++i) { // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds [10 x i32], [10 x i32] addrspace(4)* %[[ARRAY_A]].ascast, i64 0, i64 %{{[0-9a-z]+}}, !llvm.index.group ![[IDX_GROUP_A_ARR_AND_GLOB:[0-9]+]] a[i] = 0; // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds [10 x i32], [10 x i32] addrspace(4)* %[[ARRAY_B]].ascast, i64 0, i64 %{{[0-9a-z]+}}, !llvm.index.group ![[IDX_GROUP_B_ARR_AND_GLOB:[0-9]+]] b[i] = 0; // CHECK: br label %for.cond, !llvm.loop ![[MD_LOOP_ARR_AND_GLOB:[0-9]+]] } } // Global ivdep with INF safelen & array-specific ivdep with lesser safelen // // CHECK: define {{.*}}spir_func void @_Z{{[0-9]+}}ivdep_array_and_inf_globalv() void ivdep_array_and_inf_global() { // CHECK: %[[ARRAY_A:[0-9a-z]+]] = alloca [10 x i32] int a[10]; // CHECK: %[[ARRAY_B:[0-9a-z]+]] = alloca [10 x i32] int b[10]; [[intel::ivdep]] [[intel::ivdep(a, 8)]] for (int i = 0; i != 10; ++i) { // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds [10 x i32], [10 x i32] addrspace(4)* %[[ARRAY_A]].ascast, i64 0, i64 %{{[0-9a-z]+}}, !llvm.index.group ![[IDX_GROUP_A_ARR_AND_INF_GLOB:[0-9]+]] a[i] = 0; // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds [10 x i32], [10 x i32] addrspace(4)* %[[ARRAY_B]].ascast, i64 0, i64 %{{[0-9a-z]+}}, !llvm.index.group ![[IDX_GROUP_B_ARR_AND_INF_GLOB:[0-9]+]] b[i] = 0; // CHECK: br label %for.cond, !llvm.loop ![[MD_LOOP_ARR_AND_INF_GLOB:[0-9]+]] } } // Global ivdep with specified safelen & array-specific ivdep with lesser safelen // // CHECK: define {{.*}}spir_func void @_Z{{[0-9]+}}ivdep_array_and_greater_globalv() void ivdep_array_and_greater_global() { // CHECK: %[[ARRAY_A:[0-9a-z]+]] = alloca [10 x i32] int a[10]; // CHECK: %[[ARRAY_B:[0-9a-z]+]] = alloca [10 x i32] int b[10]; [[intel::ivdep(9)]] [[intel::ivdep(a, 8)]] for (int i = 0; i != 10; ++i) { // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds [10 x i32], [10 x i32] addrspace(4)* %[[ARRAY_A]].ascast, i64 0, i64 %{{[0-9a-z]+}}, !llvm.index.group ![[IDX_GROUP_A_ARR_AND_GREAT_GLOB:[0-9]+]] a[i] = 0; // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds [10 x i32], [10 x i32] addrspace(4)* %[[ARRAY_B]].ascast, i64 0, i64 %{{[0-9a-z]+}}, !llvm.index.group ![[IDX_GROUP_B_ARR_AND_GREAT_GLOB:[0-9]+]] b[i] = 0; // CHECK: br label %for.cond, !llvm.loop ![[MD_LOOP_ARR_AND_GREAT_GLOB:[0-9]+]] } } // Global safelen, array-specific safelens // // CHECK: define {{.*}}spir_func void @_Z{{[0-9]+}}ivdep_mul_arrays_and_globalv() void ivdep_mul_arrays_and_global() { // CHECK: %[[ARRAY_A:[0-9a-z]+]] = alloca [10 x i32] int a[10]; // CHECK: %[[ARRAY_B:[0-9a-z]+]] = alloca [10 x i32] int b[10]; // CHECK: %[[ARRAY_C:[0-9a-z]+]] = alloca [10 x i32] int c[10]; [[intel::ivdep(5)]] [[intel::ivdep(b, 6)]] [[intel::ivdep(c)]] for (int i = 0; i != 10; ++i) { // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds [10 x i32], [10 x i32] addrspace(4)* %[[ARRAY_A]].ascast, i64 0, i64 %{{[0-9a-z]+}}, !llvm.index.group ![[IDX_GROUP_A_MUL_ARR_AND_GLOB:[0-9]+]] a[i] = 0; // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds [10 x i32], [10 x i32] addrspace(4)* %[[ARRAY_B]].ascast, i64 0, i64 %{{[0-9a-z]+}}, !llvm.index.group ![[IDX_GROUP_B_MUL_ARR_AND_GLOB:[0-9]+]] b[i] = 0; // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds [10 x i32], [10 x i32] addrspace(4)* %[[ARRAY_C]].ascast, i64 0, i64 %{{[0-9a-z]+}}, !llvm.index.group ![[IDX_GROUP_C_MUL_ARR_AND_GLOB:[0-9]+]] c[i] = 0; // CHECK: br label %for.cond, !llvm.loop ![[MD_LOOP_MUL_ARR_AND_GLOB:[0-9]+]] } } // CHECK: define {{.*}}spir_func void @_Z{{[0-9]+}}ivdep_ptrv() void ivdep_ptr() { int *ptr; // CHECK: %[[PTR:[0-9a-z]+]] = alloca i32 addrspace(4)* [[intel::ivdep(ptr, 5)]] for (int i = 0; i != 10; ++i) ptr[i] = 0; // CHECK: %[[PTR_LOAD:[0-9a-z]+]] = load i32 addrspace(4)*, i32 addrspace(4)* addrspace(4)* %[[PTR]] // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds i32, i32 addrspace(4)* %[[PTR_LOAD]], i64 %{{[0-9a-z]+}}, !llvm.index.group ![[IDX_GROUP_PTR:[0-9]+]] // CHECK: br label %for.cond, !llvm.loop ![[MD_LOOP_PTR:[0-9]+]] } // CHECK: define {{.*}}spir_func void @_Z{{[0-9]+}}ivdep_structv() void ivdep_struct() { struct S { int *ptr; int arr[10]; } s; // CHECK: %[[STRUCT:[0-9a-z]+]] = alloca %struct.S [[intel::ivdep(s.arr, 5)]] for (int i = 0; i != 10; ++i) s.arr[i] = 0; // CHECK: %[[STRUCT_ARR:[0-9a-z]+]] = getelementptr inbounds %struct.S, %struct.S addrspace(4)* %[[STRUCT]].ascast, i32 0, i32 1 // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds [10 x i32], [10 x i32] addrspace(4)* %[[STRUCT_ARR]], i64 0, i64 %{{[0-9a-z]+}}, !llvm.index.group ![[IDX_GROUP_STRUCT_ARR:[0-9]+]] // CHECK: br label %for.cond, !llvm.loop ![[MD_LOOP_STRUCT_ARR:[0-9]+]] [[intel::ivdep(s.ptr, 5)]] for (int i = 0; i != 10; ++i) s.ptr[i] = 0; // CHECK: %[[STRUCT_PTR:[0-9a-z]+]] = getelementptr inbounds %struct.S, %struct.S addrspace(4)* %[[STRUCT]].ascast, i32 0, i32 0 // CHECK: %[[LOAD_STRUCT_PTR:[0-9a-z]+]] = load i32 addrspace(4)*, i32 addrspace(4)* addrspace(4)* %[[STRUCT_PTR]] // CHECK: %{{[0-9a-z]+}} = getelementptr inbounds i32, i32 addrspace(4)* %[[LOAD_STRUCT_PTR]], i64 %{{[0-9a-z]+}}, !llvm.index.group ![[IDX_GROUP_STRUCT_PTR:[0-9]+]] // CHECK: br label %for.cond{{[0-9]*}}, !llvm.loop ![[MD_LOOP_STRUCT_PTR:[0-9]+]] } template <typename name, typename Func> __attribute__((sycl_kernel)) void kernel_single_task(const Func &kernelFunc) { kernelFunc(); } int main() { kernel_single_task<class kernel_function>([]() { ivdep_array_no_safelen(); ivdep_array_with_safelen(); ivdep_multiple_arrays(); ivdep_array_and_global(); ivdep_array_and_inf_global(); ivdep_array_and_greater_global(); ivdep_mul_arrays_and_global(); ivdep_ptr(); ivdep_struct(); }); return 0; } /// A particular array with no safelen specified // // CHECK-DAG: ![[IDX_GROUP_ARR]] = distinct !{} // CHECK-DAG: ![[MD_LOOP_ARR]] = distinct !{![[MD_LOOP_ARR]], ![[MP:[0-9]+]], ![[IVDEP_ARR:[0-9]+]]} // CHECK-DAG: ![[MP]] = !{!"llvm.loop.mustprogress"} // CHECK-DAG: ![[IVDEP_ARR]] = !{!"llvm.loop.parallel_access_indices", ![[IDX_GROUP_ARR]]} /// A particular array with safelen specified // // CHECK: ![[IDX_GROUP_ARR_SAFELEN]] = distinct !{} // CHECK-DAG: ![[MD_LOOP_ARR_SAFELEN]] = distinct !{![[MD_LOOP_ARR_SAFELEN]], ![[MP]], ![[IVDEP_ARR_SAFELEN:[0-9]+]]} // CHECK-DAG: ![[IVDEP_ARR_SAFELEN]] = !{!"llvm.loop.parallel_access_indices", ![[IDX_GROUP_ARR_SAFELEN]], i32 5} /// Multiple arrays. /// Index groups for arrays with matching safelens should be put into the same parallel_access_indices MD node // // CHECK-DAG: ![[IDX_GROUP_A_MUL_ARR]] = distinct !{} // CHECK-DAG: ![[IDX_GROUP_B_MUL_ARR]] = distinct !{} // CHECK-DAG: ![[IDX_GROUP_C_MUL_ARR]] = distinct !{} // CHECK-DAG: ![[IDX_GROUP_D_MUL_ARR]] = distinct !{} // CHECK-DAG: ![[MD_LOOP_MUL_ARR]] = distinct !{![[MD_LOOP_MUL_ARR]], ![[MP]], ![[IVDEP_MUL_ARR_VAL:[0-9]+]], ![[IVDEP_MUL_ARR_INF:[0-9]+]]} // CHECK-DAG: ![[IVDEP_MUL_ARR_VAL]] = !{!"llvm.loop.parallel_access_indices", ![[IDX_GROUP_A_MUL_ARR]], ![[IDX_GROUP_B_MUL_ARR]], i32 5} // CHECK-DAG: ![[IVDEP_MUL_ARR_INF]] = !{!"llvm.loop.parallel_access_indices", ![[IDX_GROUP_C_MUL_ARR]], ![[IDX_GROUP_D_MUL_ARR]]} // Find the single instance of a legacy "IVDep enable" MD node. // CHECK-DAG: ![[IVDEP_LEGACY_ENABLE:[0-9]+]] = !{!"llvm.loop.ivdep.enable"} /// Global INF safelen and specific array INF safelen /// The array-specific ivdep can be ignored, so it's the same as just global ivdep with safelen INF // // CHECK-DAG: ![[IDX_GROUP_A_ARR_AND_GLOB]] = distinct !{} // CHECK-DAG: ![[IDX_GROUP_B_ARR_AND_GLOB]] = distinct !{} // CHECK-DAG: ![[MD_LOOP_ARR_AND_GLOB]] = distinct !{![[MD_LOOP_ARR_AND_GLOB]], ![[MP]], ![[IVDEP_ARR_AND_GLOB:[0-9]+]], ![[IVDEP_LEGACY_ENABLE]]} // CHECK-DAG: ![[IVDEP_ARR_AND_GLOB]] = !{!"llvm.loop.parallel_access_indices", ![[IDX_GROUP_A_ARR_AND_GLOB]], ![[IDX_GROUP_B_ARR_AND_GLOB]]} /// Global INF safelen and specific array non-INF safelen /// The array-specific ivdep must be ignored, so it's the same as just global ivdep with safelen INF // // CHECK-DAG: ![[IDX_GROUP_A_ARR_AND_INF_GLOB]] = distinct !{} // CHECK-DAG: ![[IDX_GROUP_B_ARR_AND_INF_GLOB]] = distinct !{} // CHECK-DAG: ![[MD_LOOP_ARR_AND_INF_GLOB]] = distinct !{![[MD_LOOP_ARR_AND_INF_GLOB]], ![[MP]], ![[IVDEP_ARR_AND_INF_GLOB:[0-9]+]], ![[IVDEP_LEGACY_ENABLE]]} // CHECK-DAG: ![[IVDEP_ARR_AND_INF_GLOB]] = !{!"llvm.loop.parallel_access_indices", ![[IDX_GROUP_A_ARR_AND_INF_GLOB]], ![[IDX_GROUP_B_ARR_AND_INF_GLOB]]} /// Global safelen and specific array with lesser safelen /// The array-specific ivdep must be gnored, so it's the same as just global ivdep with its safelen // // CHECK-DAG: ![[IDX_GROUP_A_ARR_AND_GREAT_GLOB]] = distinct !{} // CHECK-DAG: ![[IDX_GROUP_B_ARR_AND_GREAT_GLOB]] = distinct !{} // CHECK-DAG: ![[MD_LOOP_ARR_AND_GREAT_GLOB]] = distinct !{![[MD_LOOP_ARR_AND_GREAT_GLOB]], ![[MP]], ![[IVDEP_ARR_AND_GREAT_GLOB:[0-9]+]], ![[IVDEP_LEGACY_ARR_AND_GREAT_GLOB:[0-9]+]]} // CHECK-DAG: ![[IVDEP_LEGACY_ARR_AND_GREAT_GLOB]] = !{!"llvm.loop.ivdep.safelen", i32 9} // CHECK-DAG: ![[IVDEP_ARR_AND_GREAT_GLOB]] = !{!"llvm.loop.parallel_access_indices", ![[IDX_GROUP_A_ARR_AND_GREAT_GLOB]], ![[IDX_GROUP_B_ARR_AND_GREAT_GLOB]], i32 9} /// Multiple arrays with specific safelens and lesser global safelen /// The array-specific safelens are kept for the correspondent arrays, the global safelen applies to the rest // // CHECK-DAG: ![[IDX_GROUP_A_MUL_ARR_AND_GLOB]] = distinct !{} // CHECK-DAG: ![[IDX_GROUP_B_MUL_ARR_AND_GLOB]] = distinct !{} // CHECK-DAG: ![[IDX_GROUP_C_MUL_ARR_AND_GLOB]] = distinct !{} // CHECK-DAG: ![[MD_LOOP_MUL_ARR_AND_GLOB]] = distinct !{![[MD_LOOP_MUL_ARR_AND_GLOB]], ![[MP]], ![[IVDEP_A_MUL_ARR_AND_GLOB:[0-9]+]], ![[IVDEP_LEGACY_MUL_ARR_AND_GLOB:[0-9]+]], ![[IVDEP_B_MUL_ARR_AND_GLOB:[0-9]+]], ![[IVDEP_C_MUL_ARR_AND_GLOB:[0-9]+]]} // CHECK-DAG: ![[IVDEP_LEGACY_MUL_ARR_AND_GLOB]] = !{!"llvm.loop.ivdep.safelen", i32 5} // CHECK-DAG: ![[IVDEP_A_MUL_ARR_AND_GLOB]] = !{!"llvm.loop.parallel_access_indices", ![[IDX_GROUP_A_MUL_ARR_AND_GLOB]], i32 5} // CHECK-DAG: ![[IVDEP_B_MUL_ARR_AND_GLOB]] = !{!"llvm.loop.parallel_access_indices", ![[IDX_GROUP_B_MUL_ARR_AND_GLOB]], i32 6} // CHECK-DAG: ![[IVDEP_C_MUL_ARR_AND_GLOB]] = !{!"llvm.loop.parallel_access_indices", ![[IDX_GROUP_C_MUL_ARR_AND_GLOB]]} // CHECK-DAG: ![[IDX_GROUP_PTR]] = distinct !{} // CHECK-DAG: ![[MD_LOOP_PTR]] = distinct !{![[MD_LOOP_PTR]], ![[MP]], ![[IVDEP_PTR:[0-9]+]]} // CHECK-DAG: ![[IVDEP_PTR]] = !{!"llvm.loop.parallel_access_indices", ![[IDX_GROUP_PTR]], i32 5} // CHECK-DAG: ![[IDX_GROUP_STRUCT_ARR]] = distinct !{} // CHECK-DAG: ![[MD_LOOP_STRUCT_ARR]] = distinct !{![[MD_LOOP_STRUCT_ARR]], ![[MP]], ![[IVDEP_STRUCT_ARR:[0-9]+]]} // CHECK-DAG: ![[IVDEP_STRUCT_ARR]] = !{!"llvm.loop.parallel_access_indices", ![[IDX_GROUP_STRUCT_ARR]], i32 5} // CHECK-DAG: ![[IDX_GROUP_STRUCT_PTR]] = distinct !{} // CHECK-DAG: ![[MD_LOOP_STRUCT_PTR]] = distinct !{![[MD_LOOP_STRUCT_PTR]], ![[MP]], ![[IVDEP_STRUCT_PTR:[0-9]+]]} // CHECK-DAG: ![[IVDEP_STRUCT_PTR]] = !{!"llvm.loop.parallel_access_indices", ![[IDX_GROUP_STRUCT_PTR]], i32 5}
c++
code
14,867
4,524
#include "test/server/listener_manager_impl_test.h" #include <chrono> #include <memory> #include <string> #include <utility> #include <vector> #include "envoy/registry/registry.h" #include "envoy/server/filter_config.h" #include "common/api/os_sys_calls_impl.h" #include "common/config/metadata.h" #include "common/network/address_impl.h" #include "common/network/io_socket_handle_impl.h" #include "common/network/utility.h" #include "common/protobuf/protobuf.h" #include "extensions/filters/listener/original_dst/original_dst.h" #include "extensions/transport_sockets/tls/ssl_socket.h" #include "test/server/utility.h" #include "test/test_common/network_utility.h" #include "test/test_common/registry.h" #include "test/test_common/utility.h" #include "absl/strings/escaping.h" #include "absl/strings/match.h" using testing::AtLeast; using testing::InSequence; using testing::Throw; namespace Envoy { namespace Server { namespace { class ListenerManagerImplWithRealFiltersTest : public ListenerManagerImplTest { public: /** * Create an IPv4 listener with a given name. */ envoy::api::v2::Listener createIPv4Listener(const std::string& name) { envoy::api::v2::Listener listener = parseListenerFromV2Yaml(R"EOF( address: socket_address: { address: 127.0.0.1, port_value: 1111 } filter_chains: - filters: )EOF"); listener.set_name(name); return listener; } /** * Used by some tests below to validate that, if a given socket option is valid on this platform * and set in the Listener, it should result in a call to setsockopt() with the appropriate * values. */ void testSocketOption(const envoy::api::v2::Listener& listener, const envoy::api::v2::core::SocketOption::SocketState& expected_state, const Network::SocketOptionName& expected_option, int expected_value, uint32_t expected_num_options = 1) { if (expected_option.has_value()) { expectCreateListenSocket(expected_state, expected_num_options); expectSetsockopt(os_sys_calls_, expected_option.level(), expected_option.option(), expected_value, expected_num_options); manager_->addOrUpdateListener(listener, "", true); EXPECT_EQ(1U, manager_->listeners().size()); } else { EXPECT_THROW_WITH_MESSAGE(manager_->addOrUpdateListener(listener, "", true), EnvoyException, "MockListenerComponentFactory: Setting socket options failed"); EXPECT_EQ(0U, manager_->listeners().size()); } } }; class MockLdsApi : public LdsApi { public: MOCK_CONST_METHOD0(versionInfo, std::string()); }; TEST_F(ListenerManagerImplWithRealFiltersTest, EmptyFilter) { const std::string yaml = R"EOF( address: socket_address: address: 127.0.0.1 port_value: 1234 filter_chains: - filters: [] )EOF"; EXPECT_CALL(server_.random_, uuid()); EXPECT_CALL(listener_factory_, createListenSocket(_, _, _, true)); manager_->addOrUpdateListener(parseListenerFromV2Yaml(yaml), "", true); EXPECT_EQ(1U, manager_->listeners().size()); EXPECT_EQ(std::chrono::milliseconds(15000), manager_->listeners().front().get().listenerFiltersTimeout()); } TEST_F(ListenerManagerImplWithRealFiltersTest, DefaultListenerPerConnectionBufferLimit) { const std::string yaml = R"EOF( address: socket_address: address: 127.0.0.1 port_value: 1234 filter_chains: - filters: [] )EOF"; EXPECT_CALL(listener_factory_, createListenSocket(_, _, _, true)); manager_->addOrUpdateListener(parseListenerFromV2Yaml(yaml), "", true); EXPECT_EQ(1024 * 1024U, manager_->listeners().back().get().perConnectionBufferLimitBytes()); } TEST_F(ListenerManagerImplWithRealFiltersTest, SetListenerPerConnectionBufferLimit) { const std::string yaml = R"EOF( address: socket_address: address: 127.0.0.1 port_value: 1234 filter_chains: - filters: [] per_connection_buffer_limit_bytes: 8192 )EOF"; EXPECT_CALL(listener_factory_, createListenSocket(_, _, _, true)); manager_->addOrUpdateListener(parseListenerFromV2Yaml(yaml), "", true); EXPECT_EQ(8192U, manager_->listeners().back().get().perConnectionBufferLimitBytes()); } TEST_F(ListenerManagerImplWithRealFiltersTest, SslContext) { const std::string yaml = TestEnvironment::substitute(R"EOF( address: socket_address: address: 127.0.0.1 port_value: 1234 filter_chains: - filters: [] tls_context: common_tls_context: tls_certificates: - certificate_chain: filename: "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_uri_cert.pem" private_key: filename: "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/san_uri_key.pem" validation_context: trusted_ca: filename: "{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/ca_cert.pem" verify_subject_alt_name: - localhost - 127.0.0.1 )EOF", Network::Address::IpVersion::v4); EXPECT_CALL(listener_factory_, createListenSocket(_, _, _, true)); manager_->addOrUpdateListener(parseListenerFromV2Yaml(yaml), "", true); EXPECT_EQ(1U, manager_->listeners().size()); auto filter_chain = findFilterChain(1234, "127.0.0.1", "", "tls", {}, "8.8.8.8", 111); ASSERT_NE(filter_chain, nullptr); EXPECT_TRUE(filter_chain->transportSocketFactory().implementsSecureTransport()); } TEST_F(ListenerManagerImplWithRealFiltersTest, UdpAddress) { const std::string proto_text = R"EOF( address: { socket_address: { protocol: UDP address: "127.0.0.1" port_value: 1234 } } filter_chains: {} )EOF"; envoy::api::v2::Listener listener_proto; EXPECT_TRUE(Protobuf::TextFormat::ParseFromString(proto_text, &listener_proto)); EXPECT_CALL(server_.random_, uuid()); EXPECT_CALL(listener_factory_, createListenSocket(_, Network::Address::SocketType::Datagram, _, true)); EXPECT_CALL(os_sys_calls_, setsockopt_(_, _, _, _, _)).Times(testing::AtLeast(1)); EXPECT_CALL(os_sys_calls_, close(_)).WillRepeatedly(Return(Api::SysCallIntResult{0, errno})); manager_->addOrUpdateListener(listener_proto, "", true); EXPECT_EQ(1u, manager_->listeners().size()); } TEST_F(ListenerManagerImplWithRealFiltersTest, BadListenerConfig) { const std::string yaml = R"EOF( address: socket_address: address: 127.0.0.1 port_value: 1234 filter_chains: - filters: [] test: a )EOF"; EXPECT_THROW_WITH_REGEX(manager_->addOrUpdateListener(parseListenerFromV2Yaml(yaml), "", true), EnvoyException, "test: Cannot find field"); } TEST_F(ListenerManagerImplWithRealFiltersTest, BadListenerConfigNoFilterChains) { const std::string yaml = R"EOF( address: socket_address: address: 127.0.0.1 port_value: 1234 )EOF"; EXPECT_THROW_WITH_REGEX(manager_->addOrUpdateListener(parseListenerFromV2Yaml(yaml), "", true), EnvoyException, "no filter chains specified"); } TEST_F(ListenerManagerImplWithRealFiltersTest, BadListenerConfig2UDPListenerFilters) { const std::string yaml = R"EOF( address: socket_address: protocol: UDP address: 127.0.0.1 port_value: 1234 listener_filters: - name: envoy.listener.tls_inspector - name: envoy.listener.original_dst )EOF"; EXPECT_THROW_WITH_REGEX(manager_->addOrUpdateListener(parseListenerFromV2Yaml(yaml), "", true), EnvoyException, "Only 1 UDP filter per listener supported"); } TEST_F(ListenerManagerImplWithRealFiltersTest, BadFilterConfig) { const std::string yaml = R"EOF( address: socket_address: address: 127.0.0.1 port_value: 1234 filter_chains: - filters: - foo: type name: name config: {} )EOF"; EXPECT_THROW_WITH_REGEX(manager_->addOrUpdateListener(parseListenerFromV2Yaml(yaml), "", true), EnvoyException, "foo: Cannot find field"); } class NonTerminalFilterFactory : public Configuration::NamedNetworkFilterConfigFactory { public: // Configuration::NamedNetworkFilterConfigFactory Network::FilterFactoryCb createFilterFactory(const Json::Object&, Configuration::FactoryContext&) override { return [](Network::FilterManager&) -> void {}; } Network::FilterFactoryCb createFilterFactoryFromProto(const Protobuf::Message&, Configuration::FactoryContext&) override { return [](Network::FilterManager&) -> void {}; } ProtobufTypes::MessagePtr createEmptyConfigProto() override { return std::make_unique<Envoy::ProtobufWkt::Empty>(); } std::string name() override { return "non_terminal"; } }; TEST_F(ListenerManagerImplWithRealFiltersTest, TerminalNotLast) { Registry::RegisterFactory<NonTerminalFilterFactory, Configuration::NamedNetworkFilterConfigFactory> registered; const std::string yaml = R"EOF( address: socket_address: address: 127.0.0.1 port_value: 1234 filter_chains: - filters: - name: non_terminal config: {} )EOF"; EXPECT_THROW_WITH_REGEX(manager_->addOrUpdateListener(parseListenerFromV2Yaml(yaml), "", true), EnvoyException, "Error: non-terminal filter non_terminal is the last " "filter in a network filter chain."); } TEST_F(ListenerManagerImplWithRealFiltersTest, NotTerminalLast) { const std::string yaml = R"EOF( address: socket_address: address: 127.0.0.1 port_value: 1234 filter_chains: - filters: - name: envoy.tcp_proxy config: {} - name: unknown_but_will_not_be_processed config: {} )EOF"; EXPECT_THROW_WITH_REGEX(manager_->addOrUpdateListener(parseListenerFromV2Yaml(yaml), "", true), EnvoyException, "Error: envoy.tcp_proxy must be the terminal network filter."); } TEST_F(ListenerManagerImplWithRealFiltersTest, BadFilterName) { const std::string yaml = R"EOF( address: socket_address: address: 127.0.0.1 port_value: 1234 filter_chains: - filters: - name: invalid config: {} )EOF"; EXPECT_THROW_WITH_MESSAGE(manager_->addOrUpdateListener(parseListenerFromV2Yaml(yaml), "", true), EnvoyException, "Didn't find a registered implementation for name: 'invalid'"); } class TestStatsConfigFactory : public Configuration::NamedNetworkFilterConfigFactory { public: // Configuration::NamedNetworkFilterConfigFactory Network::FilterFactoryCb createFilterFactory(const Json::Object&, Configuration::FactoryContext& context) override { return commonFilterFactory(context); } Network::FilterFactoryCb createFilterFactoryFromProto(const Protobuf::Message&, Configuration::FactoryContext& context) override { return commonFilterFactory(context); } ProtobufTypes::MessagePtr createEmptyConfigProto() override { return std::make_unique<Envoy::ProtobufWkt::Empty>(); } std::string name() override { return "stats_test"; } bool isTerminalFilter() override { return true; } private: Network::FilterFactoryCb commonFilterFactory(Configuration::FactoryContext& context) { context.scope().counter("bar").inc(); return [](Network::FilterManager&) -> void {}; } }; TEST_F(ListenerManagerImplWithRealFiltersTest, StatsScopeTest) { Registry::RegisterFactory<TestStatsConfigFactory, Configuration::NamedNetworkFilterConfigFactory> registered; const std::string yaml = R"EOF( address: socket_address: address: 127.0.0.1 port_value: 1234 deprecated_v1: bind_to_port: false filter_chains: - filters: - name: stats_test config: {} )EOF"; EXPECT_CALL(listener_factory_, createListenSocket(_, _, _, false)); manager_->addOrUpdateListener(parseListenerFromV2Yaml(yaml), "", true); manager_->listeners().front().get().listenerScope().counter("foo").inc(); EXPECT_EQ(1UL, server_.stats_store_.counter("bar").value()); EXPECT_EQ(1UL, server_.stats_store_.counter("listener.127.0.0.1_1234.foo").value()); } TEST_F(ListenerManagerImplTest, NotDefaultListenerFiltersTimeout) { const std::string yaml = R"EOF( name: "foo" address: socket_address: { address: 127.0.0.1, port_value: 10000 } filter_chains: - filters: listener_filters_timeout: 0s )EOF"; EXPECT_CALL(listener_factory_, createListenSocket(_, _, _, true)); EXPECT_TRUE(manager_->addOrUpdateListener(parseListenerFromV2Yaml(yaml), "", true)); EXPECT_EQ(std::chrono::milliseconds(), manager_->listeners().front().get().listenerFiltersTimeout()); } TEST_F(ListenerManagerImplTest, ModifyOnlyDrainType) { InSequence s; // Add foo listener. const std::string listener_foo_yaml = R"EOF( name: "foo" address: socket_address: { address: 127.0.0.1, port_value: 10000 } filter_chains: - filters: drain_type: MODIFY_ONLY )EOF"; ListenerHandle* listener_foo = expectListenerCreate(false, true, envoy::api::v2::Listener_DrainType_MODIFY_ONLY); EXPECT_CALL(listener_factory_, createListenSocket(_, _, _, true)); EXPECT_TRUE(manager_->addOrUpdateListener(parseListenerFromV2Yaml(listener_foo_yaml), "", true)); checkStats(1, 0, 0, 0, 1, 0); EXPECT_CALL(*listener_foo, onDestroy()); } TEST_F(ListenerManagerImplTest, AddListenerAddressNotMatching) { InSequence s; // Add foo listener. const std::string listener_foo_yaml = R"EOF( name: foo address: socket_address: address: 127.0.0.1 port_value: 1234 filter_chains: - filters: [] drain_type: default )EOF"; ListenerHandle* listener_foo = expectListenerCreate(false, true); EXPECT_CALL(listener_factory_, createListenSocket(_, _, _, true)); EXPECT_TRUE(manager_->addOrUpdateListener(parseListenerFromV2Yaml(listener_foo_yaml), "", true)); checkStats(1, 0, 0, 0, 1, 0); // Update foo listener, but with a different address. Should throw. const std::string listener_foo_different_address_yaml = R"EOF( name: foo address: socket_address: address: 127.0.0.1 port_value: 1235 filter_chains: - filters: [] drain_type: modify_only )EOF"; ListenerHandle* listener_foo_different_address = expectListenerCreate(false, true, envoy::api::v2::Listener_DrainType_MODIFY_ONLY); EXPECT_CALL(*listener_foo_different_address, onDestroy()); EXPECT_THROW_WITH_MESSAGE( manager_->addOrUpdateListener(parseListenerFromV2Yaml(listener_foo_different_address_yaml), "", true), EnvoyException, "error updating listener: 'foo' has a different address " "'127.0.0.1:1235' from existing listener"); EXPECT_CALL(*listener_foo, onDestroy()); } // Make sure that a listener creation does not fail on IPv4 only setups when FilterChainMatch is not // specified and we try to create default CidrRange. See makeCidrListEntry function for // more details. TEST_F(ListenerManagerImplTest, AddListenerOnIpv4OnlySetups) { InSequence s; NiceMock<Api::MockOsSysCalls> os_sys_calls; TestThreadsafeSingletonInjector<Api::OsSysCallsImpl> os_calls(&os_sys_calls); const std::string listener_foo_yaml = R"EOF( name: foo address: socket_address: address: 127.0.0.1 port_value: 1234 filter_chains: - filters: [] drain_type: default )EOF"; ListenerHandle* listener_foo = expectListenerCreate(false, true); ON_CALL(os_sys_calls, socket(AF_INET, _, 0)).WillByDefault(Return(Api::SysCallIntResult{5, 0})); ON_CALL(os_sys_calls, socket(AF_INET6, _, 0)).WillByDefault(Return(Api::SysCallIntResult{-1, 0})); ON_CALL(os_sys_calls, close(_)).WillByDefault(Return(Api::SysCallIntResult{0, 0})); EXPECT_CALL(listener_factory_, createListenSocket(_, _, _, true)); EXPECT_TRUE(manager_->addOrUpdateListener(parseListenerFromV2Yaml(listener_foo_yaml), "", true)); checkStats(1, 0, 0, 0, 1, 0); EXPECT_CALL(*listener_foo, onDestroy()); } // Make sure that a listener creation does not fail on IPv6 only setups when FilterChainMatch is not // specified and we try to create default CidrRange. See makeCidrListEntry function for // more details. TEST_F(ListenerManagerImplTest, AddListenerOnIpv6OnlySetups) { InSequence s; NiceMock<Api::MockOsSysCalls> os_sys_calls; TestThreadsafeSingletonInjector<Api::OsSysCallsImpl> os_calls(&os_sys_calls); const std::string listener_foo_yaml = R"EOF( name: foo address: socket_address: address: "::0001" port_value: 1234 filter_chains: - filters: [] drain_type: default )EOF"; ListenerHandle* listener_foo = expectListenerCreate(false, true); ON_CALL(os_sys_calls, socket(AF_INET, _, 0)).WillByDefault(Return(Api::SysCallIntResult{-1, 0})); ON_CALL(os_sys_calls, socket(AF_INET6, _, 0)).WillByDefault(Return(Api::SysCallIntResult{5, 0})); ON_CALL(os_sys_calls, close(_)).WillByDefault(Return(Api::SysCallIntResult{0, 0})); EXPECT_CALL(listener_factory_, createListenSocket(_, _, _, true)); EXPECT_TRUE(manager_->addOrUpdateListener(parseListenerFromV2Yaml(listener_foo_yaml), "", true)); checkStats(1, 0, 0, 0, 1, 0); EXPECT_CALL(*listener_foo, onDestroy()); } // Make sure that a listener that is not added_via_api cannot be updated or removed. TEST_F(ListenerManagerImplTest, UpdateRemoveNotModifiableListener) { time_system_.setSystemTime(std::chrono::milliseconds(1001001001001)); InSequence s; // Add foo listener. const std::string listener_foo_yaml = R"EOF( name: foo address: socket_address: address: 127.0.0.1 port_value: 1234 filter_chains: - filters: [] )EOF"; ListenerHandle* listener_foo = expectListenerCreate(false, false); EXPECT_CALL(listener_factory_, createListenSocket(_, _, _, true)); EXPECT_TRUE(manager_->addOrUpdateListener(parseListenerFromV2Yaml(listener_foo_yaml), "", false)); checkStats(1, 0, 0, 0, 1, 0); checkConfigDump(R"EOF( static_listeners: listener: name: "foo" address: socket_address: address: "127.0.0.1" port_value: 1234 filter_chains: {} last_updated: seconds: 1001001001 nanos: 1000000 dynamic_active_listeners: dynamic_warming_listeners: dynamic_draining_listeners: )EOF"); // Update foo listener. Should be blocked. const std::string listener_foo_update1_yaml = R"EOF( name: foo address: socket_address: address: 127.0.0.1 port_value: 1234 filter_chains: - filters: - name: fake config: {} )EOF"; EXPECT_FALSE( manager_->addOrUpdateListener(parseListenerFromV2Yaml(listener_foo_update1_yaml), "", false)); checkStats(1, 0, 0, 0, 1, 0); // Remove foo listener. Should be blocked. EXPECT_FALSE(manager_->removeListener("foo")); checkStats(1, 0, 0, 0, 1, 0); EXPECT_CALL(*listener_foo, onDestroy()); } TEST_F(ListenerManagerImplTest, AddOrUpdateListener) { time_system_.setSystemTime(std::chrono::milliseconds(1001001001001)); InSequence s; auto* lds_api = new MockLdsApi(); EXPECT_CALL(listener_factory_, createLdsApi_(_)).WillOnce(Return(lds_api)); envoy::api::v2::core::ConfigSource lds_config; manager_->createLdsApi(lds_config); EXPECT_CALL(*lds_api, versionInfo()).WillOnce(Return("")); checkConfigDump(R"EOF( static_listeners: dynamic_active_listeners: dynamic_warming_listeners: dynamic_draining_listeners: )EOF"); // Add foo listener. const std::string listener_foo_yaml = R"EOF( name: "foo" address: socket_address: address: "127.0.0.1" port_value: 1234 filter_chains: {} )EOF"; ListenerHandle* listener_foo = expectListenerCreate(false, true); EXPECT_CALL(listener_factory_, createListenSocket(_, _, _, true)); EXPECT_TRUE( manager_->addOrUpdateListener(parseListenerFromV2Yaml(listener_foo_yaml), "version1", true)); checkStats(1, 0, 0, 0, 1, 0); EXPECT_CALL(*lds_api, versionInfo()).WillOnce(Return("version1")); checkConfi
c++
code
20,000
3,840
/* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-18 Bradley M. Bell CppAD is distributed under the terms of the Eclipse Public License Version 2.0. This Source Code may also be made available under the following Secondary License when the conditions for such availability set forth in the Eclipse Public License, Version 2.0 are satisfied: GNU General Public License, Version 2.0 or later. ---------------------------------------------------------------------------- */ /* $begin atomic_eigen_mat_mul.cpp$$ $spell mul Eigen $$ $section Atomic Eigen Matrix Multiply: Example and Test$$ $head Description$$ The $cref ADFun$$ function object $icode f$$ for this example is $latex \[ f(x) = \left( \begin{array}{cc} 0 & 0 \\ 1 & 2 \\ x_0 & x_1 \end{array} \right) \left( \begin{array}{c} x_0 \\ x_1 \end{array} \right) = \left( \begin{array}{c} 0 \\ x_0 + 2 x_1 \\ x_0 x_0 + x_1 x_1 ) \end{array} \right) \] $$ $children% include/cppad/example/eigen_mat_mul.hpp %$$ $head Class Definition$$ This example uses the file $cref atomic_eigen_mat_mul.hpp$$ which defines matrix multiply as a $cref atomic_base$$ operation. $nospell $head Use Atomic Function$$ $srccode%cpp% */ # include <cppad/cppad.hpp> # include <cppad/example/eigen_mat_mul.hpp> bool eigen_mat_mul(void) { // typedef double scalar; typedef CppAD::AD<scalar> ad_scalar; typedef atomic_eigen_mat_mul<scalar>::ad_matrix ad_matrix; // bool ok = true; scalar eps = 10. * std::numeric_limits<scalar>::epsilon(); using CppAD::NearEqual; // /* %$$ $subhead Constructor$$ $srccode%cpp% */ // ------------------------------------------------------------------- // object that multiplies arbitrary matrices atomic_eigen_mat_mul<scalar> mat_mul; // ------------------------------------------------------------------- // declare independent variable vector x size_t n = 2; CPPAD_TESTVECTOR(ad_scalar) ad_x(n); for(size_t j = 0; j < n; j++) ad_x[j] = ad_scalar(j); CppAD::Independent(ad_x); // ------------------------------------------------------------------- // [ 0 0 ] // left = [ 1 2 ] // [ x[0] x[1] ] size_t nr_left = 3; size_t n_middle = 2; ad_matrix ad_left(nr_left, n_middle); ad_left(0, 0) = ad_scalar(0.0); ad_left(0, 1) = ad_scalar(0.0); ad_left(1, 0) = ad_scalar(1.0); ad_left(1, 1) = ad_scalar(2.0); ad_left(2, 0) = ad_x[0]; ad_left(2, 1) = ad_x[1]; // ------------------------------------------------------------------- // right = [ x[0] , x[1] ]^T size_t nc_right = 1; ad_matrix ad_right(n_middle, nc_right); ad_right(0, 0) = ad_x[0]; ad_right(1, 0) = ad_x[1]; // ------------------------------------------------------------------- // use atomic operation to multiply left * right ad_matrix ad_result = mat_mul.op(ad_left, ad_right); // ------------------------------------------------------------------- // check that first component of result is a parameter // and the other components are varaibles. ok &= Parameter( ad_result(0, 0) ); ok &= Variable( ad_result(1, 0) ); ok &= Variable( ad_result(2, 0) ); // ------------------------------------------------------------------- // declare the dependent variable vector y size_t m = 3; CPPAD_TESTVECTOR(ad_scalar) ad_y(m); for(size_t i = 0; i < m; i++) ad_y[i] = ad_result(long(i), 0); CppAD::ADFun<scalar> f(ad_x, ad_y); // ------------------------------------------------------------------- // check zero order forward mode CPPAD_TESTVECTOR(scalar) x(n), y(m); for(size_t i = 0; i < n; i++) x[i] = scalar(i + 2); y = f.Forward(0, x); ok &= NearEqual(y[0], 0.0, eps, eps); ok &= NearEqual(y[1], x[0] + 2.0 * x[1], eps, eps); ok &= NearEqual(y[2], x[0] * x[0] + x[1] * x[1], eps, eps); // ------------------------------------------------------------------- // check first order forward mode CPPAD_TESTVECTOR(scalar) x1(n), y1(m); x1[0] = 1.0; x1[1] = 0.0; y1 = f.Forward(1, x1); ok &= NearEqual(y1[0], 0.0, eps, eps); ok &= NearEqual(y1[1], 1.0, eps, eps); ok &= NearEqual(y1[2], 2.0 * x[0], eps, eps); x1[0] = 0.0; x1[1] = 1.0; y1 = f.Forward(1, x1); ok &= NearEqual(y1[0], 0.0, eps, eps); ok &= NearEqual(y1[1], 2.0, eps, eps); ok &= NearEqual(y1[2], 2.0 * x[1], eps, eps); // ------------------------------------------------------------------- // check second order forward mode CPPAD_TESTVECTOR(scalar) x2(n), y2(m); x2[0] = 0.0; x2[1] = 0.0; y2 = f.Forward(2, x2); ok &= NearEqual(y2[0], 0.0, eps, eps); ok &= NearEqual(y2[1], 0.0, eps, eps); ok &= NearEqual(y2[2], 1.0, eps, eps); // 1/2 * f_1''(x) // ------------------------------------------------------------------- // check first order reverse mode CPPAD_TESTVECTOR(scalar) w(m), d1w(n); w[0] = 0.0; w[1] = 1.0; w[2] = 0.0; d1w = f.Reverse(1, w); ok &= NearEqual(d1w[0], 1.0, eps, eps); ok &= NearEqual(d1w[1], 2.0, eps, eps); w[0] = 0.0; w[1] = 0.0; w[2] = 1.0; d1w = f.Reverse(1, w); ok &= NearEqual(d1w[0], 2.0 * x[0], eps, eps); ok &= NearEqual(d1w[1], 2.0 * x[1], eps, eps); // ------------------------------------------------------------------- // check second order reverse mode CPPAD_TESTVECTOR(scalar) d2w(2 * n); d2w = f.Reverse(2, w); // partial f_2 w.r.t. x_0 ok &= NearEqual(d2w[0 * 2 + 0], 2.0 * x[0], eps, eps); // partial f_2 w.r.t x_1 ok &= NearEqual(d2w[1 * 2 + 0], 2.0 * x[1], eps, eps); // partial f_2 w.r.t x_1, x_0 ok &= NearEqual(d2w[0 * 2 + 1], 0.0, eps, eps); // partial f_2 w.r.t x_1, x_1 ok &= NearEqual(d2w[1 * 2 + 1], 2.0, eps, eps); // ------------------------------------------------------------------- // check forward Jacobian sparsity CPPAD_TESTVECTOR( std::set<size_t> ) r(n), s(m); std::set<size_t> check_set; for(size_t j = 0; j < n; j++) r[j].insert(j); s = f.ForSparseJac(n, r); check_set.clear(); ok &= s[0] == check_set; check_set.insert(0); check_set.insert(1); ok &= s[1] == check_set; ok &= s[2] == check_set; // ------------------------------------------------------------------- // check reverse Jacobian sparsity r.resize(m); for(size_t i = 0; i < m; i++) r[i].insert(i); s = f.RevSparseJac(m, r); check_set.clear(); ok &= s[0] == check_set; check_set.insert(0); check_set.insert(1); ok &= s[1] == check_set; ok &= s[2] == check_set; // ------------------------------------------------------------------- // check forward Hessian sparsity for f_2 (x) CPPAD_TESTVECTOR( std::set<size_t> ) r2(1), s2(1), h(n); for(size_t j = 0; j < n; j++) r2[0].insert(j); s2[0].clear(); s2[0].insert(2); h = f.ForSparseHes(r2, s2); check_set.clear(); check_set.insert(0); ok &= h[0] == check_set; check_set.clear(); check_set.insert(1); ok &= h[1] == check_set; // ------------------------------------------------------------------- // check reverse Hessian sparsity for f_2 (x) CPPAD_TESTVECTOR( std::set<size_t> ) s3(1); s3[0].clear(); s3[0].insert(2); h = f.RevSparseHes(n, s3); check_set.clear(); check_set.insert(0); ok &= h[0] == check_set; check_set.clear(); check_set.insert(1); ok &= h[1] == check_set; // ------------------------------------------------------------------- return ok; } /* %$$ $$ $comment end nospell$$ $end */
c++
code
8,046
2,609
#include <bits/stdc++.h> using namespace std; #define ZERO(a) memset(a, 0, sizeof(a)) const int MAXN = 2001; typedef int Array[MAXN][MAXN]; bool a[MAXN][MAXN]; Array f, h, l, r, L, R; int main() { ios::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { cin >> a[i][j]; if ((i + j) % 2 == 0) a[i][j] ^= 1; } int max_square = 0; int max_rectangle = 0; auto getMax = [](int &a, const int &b) { if (a < b) a = b; }; auto getAnswer = [&]() { ZERO(f); ZERO(h); ZERO(l); ZERO(r); ZERO(L); ZERO(R); for (int i = 1; i <= m; i++) { R[0][i] = m + 1; } for (int i = 1; i <= n; i++) { int pre = 0; for (int j = 1; j <= m; j++) { if (a[i][j]) { l[i][j] = pre; } else { pre = j; L[i][j] = 0; } } pre = m + 1; for (int j = m; j >= 1; j--) { if (a[i][j]) { r[i][j] = pre; } else { pre = j; R[i][j] = m + 1; } } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (!a[i][j]) continue; f[i][j] = min({f[i - 1][j - 1], f[i - 1][j], f[i][j - 1]}) + 1; h[i][j] = h[i - 1][j] + 1; L[i][j] = max(L[i - 1][j], l[i][j]); R[i][j] = min(R[i - 1][j], r[i][j]); getMax(max_square, f[i][j] * f[i][j]); getMax(max_rectangle, h[i][j] * (R[i][j] - L[i][j] - 1)); } } }; getAnswer(); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) a[i][j] ^= 1; getAnswer(); cout << max_square << endl << max_rectangle << endl; return 0; }
c++
code
1,832
717
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include "base/strings/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_text_utils.h" namespace ui { TEST(AXTextUtils, FindAccessibleTextBoundaryWord) { const base::string16 text = base::UTF8ToUTF16("Hello there.This/is\ntesting."); const size_t text_length = text.length(); std::vector<int> line_start_offsets; line_start_offsets.push_back(19); size_t result; result = FindAccessibleTextBoundary(text, line_start_offsets, WORD_BOUNDARY, 0, FORWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(6UL, result); result = FindAccessibleTextBoundary(text, line_start_offsets, WORD_BOUNDARY, 5, BACKWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(0UL, result); result = FindAccessibleTextBoundary(text, line_start_offsets, WORD_BOUNDARY, 6, FORWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(12UL, result); result = FindAccessibleTextBoundary(text, line_start_offsets, WORD_BOUNDARY, 11, BACKWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(6UL, result); result = FindAccessibleTextBoundary(text, line_start_offsets, WORD_BOUNDARY, 12, BACKWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(12UL, result); result = FindAccessibleTextBoundary(text, line_start_offsets, WORD_BOUNDARY, 15, FORWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(17UL, result); result = FindAccessibleTextBoundary(text, line_start_offsets, WORD_BOUNDARY, 15, BACKWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(12UL, result); result = FindAccessibleTextBoundary(text, line_start_offsets, WORD_BOUNDARY, 16, FORWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(17UL, result); result = FindAccessibleTextBoundary(text, line_start_offsets, WORD_BOUNDARY, 17, FORWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(20UL, result); result = FindAccessibleTextBoundary(text, line_start_offsets, WORD_BOUNDARY, 20, FORWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(text_length, result); result = FindAccessibleTextBoundary(text, line_start_offsets, WORD_BOUNDARY, text_length, BACKWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(20UL, result); } TEST(AXTextUtils, FindAccessibleTextBoundaryLine) { const base::string16 text = base::UTF8ToUTF16("Line 1.\nLine 2\n\t"); const size_t text_length = text.length(); std::vector<int> line_start_offsets; line_start_offsets.push_back(8); line_start_offsets.push_back(15); size_t result; // Basic cases. result = FindAccessibleTextBoundary(text, line_start_offsets, LINE_BOUNDARY, 5, FORWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(8UL, result); result = FindAccessibleTextBoundary(text, line_start_offsets, LINE_BOUNDARY, 9, BACKWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(8UL, result); result = FindAccessibleTextBoundary(text, line_start_offsets, LINE_BOUNDARY, 10, FORWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(15UL, result); // Edge cases. result = FindAccessibleTextBoundary(text, line_start_offsets, LINE_BOUNDARY, text_length, BACKWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(15UL, result); // When the start_offset is at the start of the next line and we are searching // backwards, it should not move. result = FindAccessibleTextBoundary(text, line_start_offsets, LINE_BOUNDARY, 15, BACKWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(15UL, result); // When the start_offset is at a hard line break and we are searching // backwards, it should return the start of the previous line. result = FindAccessibleTextBoundary(text, line_start_offsets, LINE_BOUNDARY, 14, BACKWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(8UL, result); // When the start_offset is at the start of a line and we are searching // forwards, it should return the start of the next line. result = FindAccessibleTextBoundary(text, line_start_offsets, LINE_BOUNDARY, 8, FORWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(15UL, result); // When there is no previous line break and we are searching backwards, // it should return 0. result = FindAccessibleTextBoundary(text, line_start_offsets, LINE_BOUNDARY, 4, BACKWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(0UL, result); // When we are at the start of the last line and we are searching forwards. // it should return the text length. result = FindAccessibleTextBoundary(text, line_start_offsets, LINE_BOUNDARY, 15, FORWARDS_DIRECTION, ax::mojom::TextAffinity::kDownstream); EXPECT_EQ(text_length, result); } } // namespace ui
c++
code
6,559
983
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setAcceptDrops(true); } MainWindow::~MainWindow() { delete ui; } void MainWindow::dragEnterEvent(QDragEnterEvent *event) { QStringList acceptedFileTypes; acceptedFileTypes.append("jpg"); acceptedFileTypes.append("png"); acceptedFileTypes.append("bmp"); if (event->mimeData()->hasUrls() && event->mimeData()->urls().count() == 1) { QFileInfo file(event->mimeData()->urls().at(0).toLocalFile()); if(acceptedFileTypes.contains(file.suffix().toLower())) { event->acceptProposedAction(); } } } void MainWindow::dropEvent(QDropEvent *event) { QFileInfo file(event->mimeData()->urls().at(0).toLocalFile()); if(pixmap.load(file.absoluteFilePath())) { ui->label->setPixmap(pixmap.scaled(ui->label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); } else { QMessageBox::critical(this, tr("Error"), tr("The image file cannot be read!")); } } void MainWindow::resizeEvent(QResizeEvent *event) { Q_UNUSED(event); if(!pixmap.isNull()) { ui->label->setPixmap(pixmap.scaled(ui->label->width()-5, ui->label->height()-5, Qt::KeepAspectRatio, Qt::SmoothTransformation)); } }
c++
code
1,675
381
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpc/blockchain.h" #include "amount.h" #include "chain.h" #include "chainparams.h" #include "checkpoints.h" #include "coins.h" #include "consensus/validation.h" #include "core_io.h" #include "hash.h" #include "policy/feerate.h" #include "policy/policy.h" #include "primitives/transaction.h" #include "rpc/server.h" #include "streams.h" #include "sync.h" #include "txdb.h" #include "txmempool.h" #include "util.h" #include "utilstrencodings.h" #include "validation.h" #include <stdint.h> #include <univalue.h> #include <boost/thread/thread.hpp> // boost::thread::interrupt #include <condition_variable> #include <mutex> struct CUpdatedBlock { uint256 hash; int height; }; static std::mutex cs_blockchange; static std::condition_variable cond_blockchange; static CUpdatedBlock latestblock; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry); double GetDifficulty(const CBlockIndex* blockindex) { if (blockindex == nullptr) { if (chainActive.Tip() == nullptr) return 1.0; else blockindex = chainActive.Tip(); } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } UniValue blockheaderToJSON(const CBlockIndex* blockindex) { UniValue result(UniValue::VOBJ); result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", blockindex->nVersion)); result.push_back(Pair("versionHex", strprintf("%08x", blockindex->nVersion))); result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex())); result.push_back(Pair("time", (int64_t)blockindex->nTime)); result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast())); result.push_back(Pair("nonce", (uint64_t)blockindex->nNonce)); result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex())); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); CBlockIndex* pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); return result; } UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails) { UniValue result(UniValue::VOBJ); result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("strippedsize", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS))); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("weight", (int)::GetBlockWeight(block))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("versionHex", strprintf("%08x", block.nVersion))); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); UniValue txs(UniValue::VARR); for (const auto& tx : block.vtx) { if (txDetails) { UniValue objTx(UniValue::VOBJ); TxToUniv(*tx, uint256(), objTx, true, RPCSerializationFlags()); txs.push_back(objTx); } else txs.push_back(tx->GetHash().GetHex()); } result.push_back(Pair("tx", txs)); result.push_back(Pair("time", block.GetBlockTime())); result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast())); result.push_back(Pair("nonce", (uint64_t)block.nNonce)); result.push_back(Pair("bits", strprintf("%08x", block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex())); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); CBlockIndex* pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); return result; } UniValue getblockcount(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getblockcount\n" "\nReturns the number of blocks in the longest blockchain.\n" "\nResult:\n" "n (numeric) The current block count\n" "\nExamples:\n" + HelpExampleCli("getblockcount", "") + HelpExampleRpc("getblockcount", "")); LOCK(cs_main); return chainActive.Height(); } UniValue getbestblockhash(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getbestblockhash\n" "\nReturns the hash of the best (tip) block in the longest blockchain.\n" "\nResult:\n" "\"hex\" (string) the block hash hex encoded\n" "\nExamples:\n" + HelpExampleCli("getbestblockhash", "") + HelpExampleRpc("getbestblockhash", "")); LOCK(cs_main); return chainActive.Tip()->GetBlockHash().GetHex(); } void RPCNotifyBlockChange(bool ibd, const CBlockIndex* pindex) { if (pindex) { std::lock_guard<std::mutex> lock(cs_blockchange); latestblock.hash = pindex->GetBlockHash(); latestblock.height = pindex->nHeight; } cond_blockchange.notify_all(); } UniValue waitfornewblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 1) throw std::runtime_error( "waitfornewblock (timeout)\n" "\nWaits for a specific new block and returns useful info about it.\n" "\nReturns the current block on timeout or exit.\n" "\nArguments:\n" "1. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" "\nResult:\n" "{ (json object)\n" " \"hash\" : { (string) The blockhash\n" " \"height\" : { (int) Block height\n" "}\n" "\nExamples:\n" + HelpExampleCli("waitfornewblock", "1000") + HelpExampleRpc("waitfornewblock", "1000")); int timeout = 0; if (!request.params[0].isNull()) timeout = request.params[0].get_int(); CUpdatedBlock block; { std::unique_lock<std::mutex> lock(cs_blockchange); block = latestblock; if (timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&block] { return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); }); else cond_blockchange.wait(lock, [&block] { return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.push_back(Pair("hash", block.hash.GetHex())); ret.push_back(Pair("height", block.height)); return ret; } UniValue waitforblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw std::runtime_error( "waitforblock <blockhash> (timeout)\n" "\nWaits for a specific new block and returns useful info about it.\n" "\nReturns the current block on timeout or exit.\n" "\nArguments:\n" "1. \"blockhash\" (required, string) Block hash to wait for.\n" "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" "\nResult:\n" "{ (json object)\n" " \"hash\" : { (string) The blockhash\n" " \"height\" : { (int) Block height\n" "}\n" "\nExamples:\n" + HelpExampleCli("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000") + HelpExampleRpc("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")); int timeout = 0; uint256 hash = uint256S(request.params[0].get_str()); if (!request.params[1].isNull()) timeout = request.params[1].get_int(); CUpdatedBlock block; { std::unique_lock<std::mutex> lock(cs_blockchange); if (timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&hash] { return latestblock.hash == hash || !IsRPCRunning(); }); else cond_blockchange.wait(lock, [&hash] { return latestblock.hash == hash || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.push_back(Pair("hash", block.hash.GetHex())); ret.push_back(Pair("height", block.height)); return ret; } UniValue waitforblockheight(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw std::runtime_error( "waitforblockheight <height> (timeout)\n" "\nWaits for (at least) block height and returns the height and hash\n" "of the current tip.\n" "\nReturns the current block on timeout or exit.\n" "\nArguments:\n" "1. height (required, int) Block height to wait for (int)\n" "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" "\nResult:\n" "{ (json object)\n" " \"hash\" : { (string) The blockhash\n" " \"height\" : { (int) Block height\n" "}\n" "\nExamples:\n" + HelpExampleCli("waitforblockheight", "\"100\", 1000") + HelpExampleRpc("waitforblockheight", "\"100\", 1000")); int timeout = 0; int height = request.params[0].get_int(); if (!request.params[1].isNull()) timeout = request.params[1].get_int(); CUpdatedBlock block; { std::unique_lock<std::mutex> lock(cs_blockchange); if (timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&height] { return latestblock.height >= height || !IsRPCRunning(); }); else cond_blockchange.wait(lock, [&height] { return latestblock.height >= height || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.push_back(Pair("hash", block.hash.GetHex())); ret.push_back(Pair("height", block.height)); return ret; } UniValue getdifficulty(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getdifficulty\n" "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nResult:\n" "n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nExamples:\n" + HelpExampleCli("getdifficulty", "") + HelpExampleRpc("getdifficulty", "")); LOCK(cs_main); return GetDifficulty(); } std::string EntryDescriptionString() { return " \"size\" : n, (numeric) virtual transaction size as defined in BIP 141. This is different from actual serialized size for witness transactions as witness data is discounted.\n" " \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n" " \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority\n" " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n" " \"height\" : n, (numeric) block height when transaction entered pool\n" " \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n" " \"descendantsize\" : n, (numeric) virtual transaction size of in-mempool descendants (including this one)\n" " \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one)\n" " \"ancestorcount\" : n, (numeric) number of in-mempool ancestor transactions (including this one)\n" " \"ancestorsize\" : n, (numeric) virtual transaction size of in-mempool ancestors (including this one)\n" " \"ancestorfees\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one)\n" " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n" " \"transactionid\", (string) parent transaction id\n" " ... ]\n"; } void entryToJSON(UniValue& info, const CTxMemPoolEntry& e) { AssertLockHeld(mempool.cs); info.push_back(Pair("size", (int)e.GetTxSize())); info.push_back(Pair("fee", ValueFromAmount(e.GetFee()))); info.push_back(Pair("modifiedfee", ValueFromAmount(e.GetModifiedFee()))); info.push_back(Pair("time", e.GetTime())); info.push_back(Pair("height", (int)e.GetHeight())); info.push_back(Pair("descendantcount", e.GetCountWithDescendants())); info.push_back(Pair("descendantsize", e.GetSizeWithDescendants())); info.push_back(Pair("descendantfees", e.GetModFeesWithDescendants())); info.push_back(Pair("ancestorcount", e.GetCountWithAncestors())); info.push_back(Pair("ancestorsize", e.GetSizeWithAncestors())); info.push_back(Pair("ancestorfees", e.GetModFeesWithAncestors())); const CTransaction& tx = e.GetTx(); std::set<std::string> setDepends; for (const CTxIn& txin : tx.vin) { if (mempool.exists(txin.prevout.hash)) setDepends.insert(txin.prevout.hash.ToString()); } UniValue depends(UniValue::VARR); for (const std::string& dep : setDepends) { depends.push_back(dep); } info.push_back(Pair("depends", depends)); } UniValue mempoolToJSON(bool fVerbose) { if (fVerbose) { LOCK(mempool.cs); UniValue o(UniValue::VOBJ); for (const CTxMemPoolEntry& e : mempool.mapTx) { const uint256& hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.push_back(Pair(hash.ToString(), info)); } return o; } else { std::vector<uint256> vtxid; mempool.queryHashes(vtxid); UniValue a(UniValue::VARR); for (const uint256& hash : vtxid) a.push_back(hash.ToString()); return a; } } UniValue getrawmempool(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 1) throw std::runtime_error( "getrawmempool ( verbose )\n" "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n" "\nHint: use getmempoolentry to fetch a specific transaction from the mempool.\n" "\nArguments:\n" "1. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" "\nResult: (for verbose = false):\n" "[ (json array of string)\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" "]\n" "\nResult: (for verbose = true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" + EntryDescriptionString() + " }, ...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getrawmempool", "true") + HelpExampleRpc("getrawmempool", "true")); bool fVerbose = false; if (!request.params[0].isNull()) fVerbose = request.params[0].get_bool(); return mempoolToJSON(fVerbose); } UniValue getmempoolancestors(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) { throw std::runtime_error( "getmempoolancestors txid (verbose)\n" "\nIf txid is in the mempool, returns all in-mempool ancestors.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id (must be in mempool)\n" "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" "\nResult (for verbose=false):\n" "[ (json array of strings)\n" " \"transactionid\" (string) The transaction id of an in-mempool ancestor transaction\n" " ,...\n" "]\n" "\nResult (for verbose=true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" + EntryDescriptionString() + " }, ...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolancestors", "\"mytxid\"") + HelpExampleRpc("getmempoolancestors", "\"mytxid\"")); } bool fVerbose = false; if (!request.params[1].isNull()) fVerbose = request.params[1].get_bool(); uint256 hash = ParseHashV(request.params[0], "parameter 1"); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); if (it == mempool.mapTx.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool"); } CTxMemPool::setEntries setAncestors; uint64_t noLimit = std::numeric_limits<uint64_t>::max(); std::string dummy; mempool.CalculateMemPoolAncestors(*it, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false); if (!fVerbose) { UniValue o(UniValue::VARR); for (CTxMemPool::txiter ancestorIt : setAncestors) { o.push_back(ancestorIt->GetTx().GetHash().ToString()); } return o; } else { UniValue o(UniValue::VOBJ); for (CTxMemPool::txiter ancestorIt : setAncestors) { const CTxMemPoolEntry& e = *ancestorIt; const uint256& _hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.push_back(Pair(_hash.ToString(), info)); } return o; } } UniValue getmempooldescendants(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params
c++
code
20,000
4,551
// 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 <vector> #include "base/file_util.h" #include "base/json/json_string_value_serializer.h" #include "base/path_service.h" #include "base/perftimer.h" #include "base/string_util.h" #include "base/values.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/logging_chrome.h" #include "testing/gtest/include/gtest/gtest.h" namespace { class JSONValueSerializerTests : public testing::Test { protected: virtual void SetUp() { static const char* const kTestFilenames[] = { "serializer_nested_test.js", "serializer_test.js", "serializer_test_nowhitespace.js", }; // Load test cases for (size_t i = 0; i < arraysize(kTestFilenames); ++i) { FilePath filename; EXPECT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &filename)); filename = filename.AppendASCII(kTestFilenames[i]); std::string test_case; EXPECT_TRUE(file_util::ReadFileToString(filename, &test_case)); test_cases_.push_back(test_case); } } // Holds json strings to be tested. std::vector<std::string> test_cases_; }; } // namespace // Test deserialization of a json string into a Value object. We run the test // using 3 sample strings for both the current decoder and jsoncpp's decoder. TEST_F(JSONValueSerializerTests, Reading) { printf("\n"); const int kIterations = 100000; // Test chrome json implementation PerfTimeLogger chrome_timer("chrome"); for (int i = 0; i < kIterations; ++i) { for (size_t j = 0; j < test_cases_.size(); ++j) { JSONStringValueSerializer reader(test_cases_[j]); scoped_ptr<Value> root(reader.Deserialize(NULL, NULL)); ASSERT_TRUE(root.get()); } } chrome_timer.Done(); } TEST_F(JSONValueSerializerTests, CompactWriting) { printf("\n"); const int kIterations = 100000; // Convert test cases to Value objects. std::vector<Value*> test_cases; for (size_t i = 0; i < test_cases_.size(); ++i) { JSONStringValueSerializer reader(test_cases_[i]); Value* root = reader.Deserialize(NULL, NULL); ASSERT_TRUE(root); test_cases.push_back(root); } PerfTimeLogger chrome_timer("chrome"); for (int i = 0; i < kIterations; ++i) { for (size_t j = 0; j < test_cases.size(); ++j) { std::string json; JSONStringValueSerializer reader(&json); ASSERT_TRUE(reader.Serialize(*test_cases[j])); } } chrome_timer.Done(); // Clean up test cases. for (size_t i = 0; i < test_cases.size(); ++i) { delete test_cases[i]; test_cases[i] = NULL; } }
c++
code
2,700
594
//===- DeclCXX.cpp - C++ Declaration AST Node Implementation --------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the C++ related Decl classes. // //===----------------------------------------------------------------------===// #include "clang/AST/DeclCXX.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTLambda.h" #include "clang/AST/ASTMutationListener.h" #include "clang/AST/ASTUnresolvedSet.h" #include "clang/AST/Attr.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/DeclBase.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/LambdaCapture.h" #include "clang/AST/NestedNameSpecifier.h" #include "clang/AST/ODRHash.h" #include "clang/AST/Type.h" #include "clang/AST/TypeLoc.h" #include "clang/AST/UnresolvedSet.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/OperatorKinds.h" #include "clang/Basic/PartialDiagnostic.h" #include "clang/Basic/SourceLocation.h" #include "clang/Basic/Specifiers.h" #include "llvm/ADT/None.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/iterator_range.h" #include "llvm/Support/Casting.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cassert> #include <cstddef> #include <cstdint> using namespace clang; //===----------------------------------------------------------------------===// // Decl Allocation/Deallocation Method Implementations //===----------------------------------------------------------------------===// void AccessSpecDecl::anchor() {} AccessSpecDecl *AccessSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) AccessSpecDecl(EmptyShell()); } void LazyASTUnresolvedSet::getFromExternalSource(ASTContext &C) const { ExternalASTSource *Source = C.getExternalSource(); assert(Impl.Decls.isLazy() && "getFromExternalSource for non-lazy set"); assert(Source && "getFromExternalSource with no external source"); for (ASTUnresolvedSet::iterator I = Impl.begin(); I != Impl.end(); ++I) I.setDecl(cast<NamedDecl>(Source->GetExternalDecl( reinterpret_cast<uintptr_t>(I.getDecl()) >> 2))); Impl.Decls.setLazy(false); } CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D) : UserDeclaredConstructor(false), UserDeclaredSpecialMembers(0), Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false), Abstract(false), IsStandardLayout(true), IsCXX11StandardLayout(true), HasBasesWithFields(false), HasBasesWithNonStaticDataMembers(false), HasPrivateFields(false), HasProtectedFields(false), HasPublicFields(false), HasMutableFields(false), HasVariantMembers(false), HasOnlyCMembers(true), HasInClassInitializer(false), HasUninitializedReferenceMember(false), HasUninitializedFields(false), HasInheritedConstructor(false), HasInheritedAssignment(false), NeedOverloadResolutionForCopyConstructor(false), NeedOverloadResolutionForMoveConstructor(false), NeedOverloadResolutionForMoveAssignment(false), NeedOverloadResolutionForDestructor(false), DefaultedCopyConstructorIsDeleted(false), DefaultedMoveConstructorIsDeleted(false), DefaultedMoveAssignmentIsDeleted(false), DefaultedDestructorIsDeleted(false), HasTrivialSpecialMembers(SMF_All), HasTrivialSpecialMembersForCall(SMF_All), DeclaredNonTrivialSpecialMembers(0), DeclaredNonTrivialSpecialMembersForCall(0), HasIrrelevantDestructor(true), HasConstexprNonCopyMoveConstructor(false), HasDefaultedDefaultConstructor(false), DefaultedDefaultConstructorIsConstexpr(true), HasConstexprDefaultConstructor(false), DefaultedDestructorIsConstexpr(true), HasNonLiteralTypeFieldsOrBases(false), UserProvidedDefaultConstructor(false), DeclaredSpecialMembers(0), ImplicitCopyConstructorCanHaveConstParamForVBase(true), ImplicitCopyConstructorCanHaveConstParamForNonVBase(true), ImplicitCopyAssignmentHasConstParam(true), HasDeclaredCopyConstructorWithConstParam(false), HasDeclaredCopyAssignmentWithConstParam(false), IsLambda(false), IsParsingBaseSpecifiers(false), ComputedVisibleConversions(false), HasODRHash(false), Definition(D) {} CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getBasesSlowCase() const { return Bases.get(Definition->getASTContext().getExternalSource()); } CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getVBasesSlowCase() const { return VBases.get(Definition->getASTContext().getExternalSource()); } CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl) : RecordDecl(K, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl), DefinitionData(PrevDecl ? PrevDecl->DefinitionData : nullptr) {} CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl, bool DelayTypeCreation) { auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl); R->setMayHaveOutOfDateDef(C.getLangOpts().Modules); // FIXME: DelayTypeCreation seems like such a hack if (!DelayTypeCreation) C.getTypeDeclType(R, PrevDecl); return R; } CXXRecordDecl * CXXRecordDecl::CreateLambda(const ASTContext &C, DeclContext *DC, TypeSourceInfo *Info, SourceLocation Loc, bool Dependent, bool IsGeneric, LambdaCaptureDefault CaptureDefault) { auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TTK_Class, C, DC, Loc, Loc, nullptr, nullptr); R->setBeingDefined(true); R->DefinitionData = new (C) struct LambdaDefinitionData(R, Info, Dependent, IsGeneric, CaptureDefault); R->setMayHaveOutOfDateDef(false); R->setImplicit(true); C.getTypeDeclType(R, /*PrevDecl=*/nullptr); return R; } CXXRecordDecl * CXXRecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) { auto *R = new (C, ID) CXXRecordDecl( CXXRecord, TTK_Struct, C, nullptr, SourceLocation(), SourceLocation(), nullptr, nullptr); R->setMayHaveOutOfDateDef(false); return R; } /// Determine whether a class has a repeated base class. This is intended for /// use when determining if a class is standard-layout, so makes no attempt to /// handle virtual bases. static bool hasRepeatedBaseClass(const CXXRecordDecl *StartRD) { llvm::SmallPtrSet<const CXXRecordDecl*, 8> SeenBaseTypes; SmallVector<const CXXRecordDecl*, 8> WorkList = {StartRD}; while (!WorkList.empty()) { const CXXRecordDecl *RD = WorkList.pop_back_val(); for (const CXXBaseSpecifier &BaseSpec : RD->bases()) { if (const CXXRecordDecl *B = BaseSpec.getType()->getAsCXXRecordDecl()) { if (!SeenBaseTypes.insert(B).second) return true; WorkList.push_back(B); } } } return false; } void CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases) { ASTContext &C = getASTContext(); if (!data().Bases.isOffset() && data().NumBases > 0) C.Deallocate(data().getBases()); if (NumBases) { if (!C.getLangOpts().CPlusPlus17) { // C++ [dcl.init.aggr]p1: // An aggregate is [...] a class with [...] no base classes [...]. data().Aggregate = false; } // C++ [class]p4: // A POD-struct is an aggregate class... data().PlainOldData = false; } // The set of seen virtual base types. llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes; // The virtual bases of this class. SmallVector<const CXXBaseSpecifier *, 8> VBases; data().Bases = new(C) CXXBaseSpecifier [NumBases]; data().NumBases = NumBases; for (unsigned i = 0; i < NumBases; ++i) { data().getBases()[i] = *Bases[i]; // Keep track of inherited vbases for this base class. const CXXBaseSpecifier *Base = Bases[i]; QualType BaseType = Base->getType(); // Skip dependent types; we can't do any checking on them now. if (BaseType->isDependentType()) continue; auto *BaseClassDecl = cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl()); // C++2a [class]p7: // A standard-layout class is a class that: // [...] // -- has all non-static data members and bit-fields in the class and // its base classes first declared in the same class if (BaseClassDecl->data().HasBasesWithFields || !BaseClassDecl->field_empty()) { if (data().HasBasesWithFields) // Two bases have members or bit-fields: not standard-layout. data().IsStandardLayout = false; data().HasBasesWithFields = true; } // C++11 [class]p7: // A standard-layout class is a class that: // -- [...] has [...] at most one base class with non-static data // members if (BaseClassDecl->data().HasBasesWithNonStaticDataMembers || BaseClassDecl->hasDirectFields()) { if (data().HasBasesWithNonStaticDataMembers) data().IsCXX11StandardLayout = false; data().HasBasesWithNonStaticDataMembers = true; } if (!BaseClassDecl->isEmpty()) { // C++14 [meta.unary.prop]p4: // T is a class type [...] with [...] no base class B for which // is_empty<B>::value is false. data().Empty = false; } // C++1z [dcl.init.agg]p1: // An aggregate is a class with [...] no private or protected base classes if (Base->getAccessSpecifier() != AS_public) data().Aggregate = false; // C++ [class.virtual]p1: // A class that declares or inherits a virtual function is called a // polymorphic class. if (BaseClassDecl->isPolymorphic()) { data().Polymorphic = true; // An aggregate is a class with [...] no virtual functions. data().Aggregate = false; } // C++0x [class]p7: // A standard-layout class is a class that: [...] // -- has no non-standard-layout base classes if (!BaseClassDecl->isStandardLayout()) data().IsStandardLayout = false; if (!BaseClassDecl->isCXX11StandardLayout()) data().IsCXX11StandardLayout = false; // Record if this base is the first non-literal field or base. if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType(C)) data().HasNonLiteralTypeFieldsOrBases = true; // Now go through all virtual bases of this base and add them. for (const auto &VBase : BaseClassDecl->vbases()) { // Add this base if it's not already in the list. if (SeenVBaseTypes.insert(C.getCanonicalType(VBase.getType())).second) { VBases.push_back(&VBase); // C++11 [class.copy]p8: // The implicitly-declared copy constructor for a class X will have // the form 'X::X(const X&)' if each [...] virtual base class B of X // has a copy constructor whose first parameter is of type // 'const B&' or 'const volatile B&' [...] if (CXXRecordDecl *VBaseDecl = VBase.getType()->getAsCXXRecordDecl()) if (!VBaseDecl->hasCopyConstructorWithConstParam()) data().ImplicitCopyConstructorCanHaveConstParamForVBase = false; // C++1z [dcl.init.agg]p1: // An aggregate is a class with [...] no virtual base classes data().Aggregate = false; } } if (Base->isVirtual()) { // Add this base if it's not already in the list. if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType)).second) VBases.push_back(Base); // C++14 [meta.unary.prop] is_empty: // T is a class type, but not a union type, with ... no virtual base // classes data().Empty = false; // C++1z [dcl.init.agg]p1: // An aggregate is a class with [...] no virtual base classes data().Aggregate = false; // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: // A [default constructor, copy/move constructor, or copy/move assignment // operator for a class X] is trivial [...] if: // -- class X has [...] no virtual base classes data().HasTrivialSpecialMembers &= SMF_Destructor; data().HasTrivialSpecialMembersForCall &= SMF_Destructor; // C++0x [class]p7: // A standard-layout class is a class that: [...] // -- has [...] no virtual base classes data().IsStandardLayout = false; data().IsCXX11StandardLayout = false; // C++20 [dcl.constexpr]p3: // In the definition of a constexpr function [...] // -- if the function is a constructor or destructor, // its class shall not have any virtual base classes data().DefaultedDefaultConstructorIsConstexpr = false; data().DefaultedDestructorIsConstexpr = false; // C++1z [class.copy]p8: // The implicitly-declared copy constructor for a class X will have // the form 'X::X(const X&)' if each potentially constructed subobject // has a copy constructor whose first parameter is of type // 'const B&' or 'const volatile B&' [...] if (!BaseClassDecl->hasCopyConstructorWithConstParam()) data().ImplicitCopyConstructorCanHaveConstParamForVBase = false; } else { // C++ [class.ctor]p5: // A default constructor is trivial [...] if: // -- all the direct base classes of its class have trivial default // constructors. if (!BaseClassDecl->hasTrivialDefaultConstructor()) data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor; // C++0x [class.copy]p13: // A copy/move constructor for class X is trivial if [...] // [...] // -- the constructor selected to copy/move each direct base class // subobject is trivial, and if (!BaseClassDecl->hasTrivialCopyConstructor()) data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor; if (!BaseClassDecl->hasTrivialCopyConstructorForCall()) data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor; // If the base class doesn't have a simple move constructor, we'll eagerly // declare it and perform overload resolution to determine which function // it actually calls. If it does have a simple move constructor, this // check is correct. if (!BaseClassDecl->hasTrivialMoveConstructor()) data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor; if (!BaseClassDecl->hasTrivialMoveConstructorForCall()) data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor; // C++0x [class.copy]p27: // A copy/move assignment operator for class X is trivial if [...] // [...] // -- the assignment operator selected to copy/move each direct base // class subobject is trivial, and if (!BaseClassDecl->hasTrivialCopyAssignment()) data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment; // If the base class doesn't have a simple move assignment, we'll eagerly // declare it and perform overload resolution to determine which function // it actually calls. If it does have a simple move assignment, this // check is correct. if (!BaseClassDecl->hasTrivialMoveAssignment()) data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment; // C++11 [class.ctor]p6: // If that user-written default constructor would satisfy the // requirements of a constexpr constructor, the implicitly-defined // default constructor is constexpr. if (!BaseClassDecl->hasConstexprDefaultConstructor()) data().DefaultedDefaultConstructorIsConstexpr = false; // C++1z [class.copy]p8: // The implicitly-declared copy constructor for a class X will have // the form 'X::X(const X&)' if each potentially constructed subobject // has a copy constructor whose first parameter is of type // 'const B&' or 'const volatile B&' [...] if (!BaseClassDecl->hasCopyConstructorWithConstParam()) data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false; } // C++ [class.ctor]p3: // A destructor is trivial if all the direct base classes of its class // have trivial destructors. if (!BaseClassDecl->hasTrivialDestructor()) data().HasTrivialSpecialMembers &= ~SMF_Destructor; if (!BaseClassDecl->hasTrivialDestructorForCall()) data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor; if (!BaseClassDecl->hasIrrelevantDestructor()) data().HasIrrelevantDestructor = false; // C++11 [class.copy]p18: // The implicitly-declared copy assignment operator for a class X will // have the form 'X& X::operator=(const X&)' if each direct base class B // of X has a copy assignment operator whose parameter is of type 'const // B&', 'const volatile B&', or 'B' [...] if (!BaseClassDecl->hasCopyAssignmentWithConstParam()) data().ImplicitCopyAssignmentHasConstParam = false; // A class has an Objective-C object member if... or any of its bases // has an Objective-C object member. if (BaseClassDecl->hasObjectMember()) setHasObjectMember(true); if (BaseClassDecl->hasVolatileMember()) setHasVolatileMember(true); if (BaseClassDecl->getArgPassingRestrictions() == RecordDecl::APK_CanNeverPassInRegs) setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); // Keep track of the presence of mutable fields. if (BaseClassDecl->hasMutableFields()) { data().HasMutableFields = true; data().NeedOverloadResolutionForCopyConstructor = true; } if (BaseClassDecl->hasUninitializedReferenceMember()) data().HasUninitializedReferenceMember = true; if (!BaseClassDecl->allowConstDefaultInit()) data().HasUninitializedFields = true; addedClassSubobject(BaseClassDecl); } // C++2a [class]p7: // A class S is a standard-layout class if it: // -- has at most one base class subobject of any given type // // Note that we only need to check this for classes with more than one base // class. If there's only one base class, and it's standard layout, then // we know there are no repeated base classes. if (data().IsStandardLayout && NumBases > 1 && hasRepeatedBaseClass(this)) data().IsStandardLayout = false; if (VBases.empty()) { data().IsParsingBaseSpecifiers = false; return; } // Create base specifier for any direct or indirect virtual bases. data().VBases = new (C) CXXBaseSpecifier[VBases.size()]; data().NumVBases = VBases.size(); for (int I = 0, E = VBases.size(); I != E; ++I) { QualType Type = VBases[I]->getType(); if (!Type->isDependentType()) addedClassSubobject(Type->getAsCXXRecordDecl()); data().getVBases()[I] = *VBases[I]; } data().IsParsingBaseSpecifiers = false; } unsigned CXXRecordDecl::getODRHash() const { assert(hasDefinition() && "ODRHash only for records with definitions"); // Previously calculated hash is stored in DefinitionDat
c++
code
20,000
3,835
// 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. // // 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. // Note: This project has gone from C++ (when it was ported from pypgdb) to C, back to C++ (where it will stay). If // you are making modifications, feel free to move variable declarations from the top of functions to where they are // actually used. #include "pyodbc.h" #include "wrapper.h" #include "textenc.h" #include "cursor.h" #include "pyodbcmodule.h" #include "connection.h" #include "row.h" #include "buffer.h" #include "params.h" #include "errors.h" #include "getdata.h" #include "dbspecific.h" #include <datetime.h> enum { CURSOR_REQUIRE_CNXN = 0x00000001, CURSOR_REQUIRE_OPEN = 0x00000003, // includes _CNXN CURSOR_REQUIRE_RESULTS = 0x00000007, // includes _OPEN CURSOR_RAISE_ERROR = 0x00000010, }; inline bool StatementIsValid(Cursor* cursor) { return cursor->cnxn != 0 && ((Connection*)cursor->cnxn)->hdbc != SQL_NULL_HANDLE && cursor->hstmt != SQL_NULL_HANDLE; } extern PyTypeObject CursorType; inline bool Cursor_Check(PyObject* o) { return o != 0 && Py_TYPE(o) == &CursorType; } static Cursor* Cursor_Validate(PyObject* obj, DWORD flags) { // Validates that a PyObject is a Cursor (like Cursor_Check) and optionally some other requirements controlled by // `flags`. If valid and all requirements (from the flags) are met, the cursor is returned, cast to Cursor*. // Otherwise zero is returned. // // Designed to be used at the top of methods to convert the PyObject pointer and perform necessary checks. // // Valid flags are from the CURSOR_ enum above. Note that unless CURSOR_RAISE_ERROR is supplied, an exception // will not be set. (When deallocating, we really don't want an exception.) Connection* cnxn = 0; Cursor* cursor = 0; if (!Cursor_Check(obj)) { if (flags & CURSOR_RAISE_ERROR) PyErr_SetString(ProgrammingError, "Invalid cursor object."); return 0; } cursor = (Cursor*)obj; cnxn = (Connection*)cursor->cnxn; if (cnxn == 0) { if (flags & CURSOR_RAISE_ERROR) PyErr_SetString(ProgrammingError, "Attempt to use a closed cursor."); return 0; } if (IsSet(flags, CURSOR_REQUIRE_OPEN)) { if (cursor->hstmt == SQL_NULL_HANDLE) { if (flags & CURSOR_RAISE_ERROR) PyErr_SetString(ProgrammingError, "Attempt to use a closed cursor."); return 0; } if (cnxn->hdbc == SQL_NULL_HANDLE) { if (flags & CURSOR_RAISE_ERROR) PyErr_SetString(ProgrammingError, "The cursor's connection has been closed."); return 0; } } if (IsSet(flags, CURSOR_REQUIRE_RESULTS) && cursor->colinfos == 0) { if (flags & CURSOR_RAISE_ERROR) PyErr_SetString(ProgrammingError, "No results. Previous SQL was not a query."); return 0; } return cursor; } inline bool IsNumericType(SQLSMALLINT sqltype) { switch (sqltype) { case SQL_DECIMAL: case SQL_NUMERIC: case SQL_REAL: case SQL_FLOAT: case SQL_DOUBLE: case SQL_SMALLINT: case SQL_INTEGER: case SQL_TINYINT: case SQL_BIGINT: return true; } return false; } static bool create_name_map(Cursor* cur, SQLSMALLINT field_count, bool lower) { // Called after an execute to construct the map shared by rows. bool success = false; PyObject *desc = 0, *colmap = 0, *colinfo = 0, *type = 0, *index = 0, *nullable_obj=0; SQLSMALLINT nameLen = 300; ODBCCHAR *szName = NULL; SQLRETURN ret; I(cur->hstmt != SQL_NULL_HANDLE && cur->colinfos != 0); // These are the values we expect after free_results. If this function fails, we do not modify any members, so // they should be set to something Cursor_close can deal with. I(cur->description == Py_None); I(cur->map_name_to_index == 0); if (cur->cnxn->hdbc == SQL_NULL_HANDLE) { RaiseErrorV(0, ProgrammingError, "The cursor's connection was closed."); return false; } desc = PyTuple_New((Py_ssize_t)field_count); colmap = PyDict_New(); szName = (ODBCCHAR*) pyodbc_malloc((nameLen + 1) * sizeof(ODBCCHAR)); if (!desc || !colmap || !szName) goto done; for (int i = 0; i < field_count; i++) { SQLSMALLINT cchName; SQLSMALLINT nDataType; SQLULEN nColSize; // precision SQLSMALLINT cDecimalDigits; // scale SQLSMALLINT nullable; retry: Py_BEGIN_ALLOW_THREADS ret = SQLDescribeColW(cur->hstmt, (SQLUSMALLINT)(i + 1), (SQLWCHAR*)szName, nameLen, &cchName, &nDataType, &nColSize, &cDecimalDigits, &nullable); Py_END_ALLOW_THREADS if (cur->cnxn->hdbc == SQL_NULL_HANDLE) { // The connection was closed by another thread in the ALLOW_THREADS block above. RaiseErrorV(0, ProgrammingError, "The cursor's connection was closed."); goto done; } if (!SQL_SUCCEEDED(ret)) { RaiseErrorFromHandle(cur->cnxn, "SQLDescribeCol", cur->cnxn->hdbc, cur->hstmt); goto done; } // If needed, allocate a bigger column name message buffer and retry. if (cchName > nameLen - 1) { nameLen = cchName + 1; if (!pyodbc_realloc((BYTE**) &szName, (nameLen + 1) * sizeof(ODBCCHAR))) { PyErr_NoMemory(); goto done; } goto retry; } const TextEnc& enc = cur->cnxn->metadata_enc; // HACK: I don't know the exact issue, but iODBC + Teradata results in either UCS4 data // or 4-byte SQLWCHAR. I'm going to use UTF-32 as an indication that's what we have. Py_ssize_t cbName = cchName; switch (enc.optenc) { case OPTENC_UTF32: case OPTENC_UTF32LE: case OPTENC_UTF32BE: cbName *= 4; break; default: if (enc.ctype == SQL_C_WCHAR) cbName *= 2; break; } TRACE("Col %d: type=%s (%d) colsize=%d\n", (i+1), SqlTypeName(nDataType), (int)nDataType, (int)nColSize); Object name(TextBufferToObject(enc, szName, cbName)); if (!name) goto done; if (lower) { PyObject* l = PyObject_CallMethod(name, "lower", 0); if (!l) goto done; name.Attach(l); } type = PythonTypeFromSqlType(cur, nDataType); if (!type) goto done; switch (nullable) { case SQL_NO_NULLS: nullable_obj = Py_False; break; case SQL_NULLABLE: nullable_obj = Py_True; break; case SQL_NULLABLE_UNKNOWN: default: nullable_obj = Py_None; break; } // The Oracle ODBC driver has a bug (I call it) that it returns a data size of 0 when a numeric value is // retrieved from a UNION: http://support.microsoft.com/?scid=kb%3Ben-us%3B236786&x=13&y=6 // // Unfortunately, I don't have a test system for this yet, so I'm *trying* something. (Not a good sign.) If // the size is zero and it appears to be a numeric type, we'll try to come up with our own length using any // other data we can get. if (nColSize == 0 && IsNumericType(nDataType)) { // I'm not sure how if (cDecimalDigits != 0) { nColSize = (SQLUINTEGER)(cDecimalDigits + 3); } else { // I'm not sure if this is a good idea, but ... nColSize = 42; } } colinfo = Py_BuildValue("(OOOiiiO)", name.Get(), type, // type_code Py_None, // display size (int)nColSize, // internal_size (int)nColSize, // precision (int)cDecimalDigits, // scale nullable_obj); // null_ok if (!colinfo) goto done; nullable_obj = 0; index = PyInt_FromLong(i); if (!index) goto done; PyDict_SetItem(colmap, name.Get(), index); Py_DECREF(index); // SetItemString increments index = 0; PyTuple_SET_ITEM(desc, i, colinfo); colinfo = 0; // reference stolen by SET_ITEM } Py_XDECREF(cur->description); cur->description = desc; desc = 0; cur->map_name_to_index = colmap; colmap = 0; success = true; done: Py_XDECREF(nullable_obj); Py_XDECREF(desc); Py_XDECREF(colmap); Py_XDECREF(index); Py_XDECREF(colinfo); pyodbc_free(szName); return success; } enum free_results_flags { FREE_STATEMENT = 0x01, KEEP_STATEMENT = 0x02, FREE_PREPARED = 0x04, KEEP_PREPARED = 0x08, KEEP_MESSAGES = 0x10, STATEMENT_MASK = 0x03, PREPARED_MASK = 0x0C }; static bool free_results(Cursor* self, int flags) { // Internal function called any time we need to free the memory associated with query results. It is safe to call // this even when a query has not been executed. // If we ran out of memory, it is possible that we have a cursor but colinfos is zero. However, we should be // deleting this object, so the cursor will be freed when the HSTMT is destroyed. */ I((flags & STATEMENT_MASK) != 0); I((flags & PREPARED_MASK) != 0); if ((flags & PREPARED_MASK) == FREE_PREPARED) { Py_XDECREF(self->pPreparedSQL); self->pPreparedSQL = 0; } if (self->colinfos) { pyodbc_free(self->colinfos); self->colinfos = 0; } if (StatementIsValid(self)) { if ((flags & STATEMENT_MASK) == FREE_STATEMENT) { Py_BEGIN_ALLOW_THREADS SQLFreeStmt(self->hstmt, SQL_CLOSE); Py_END_ALLOW_THREADS; } else { Py_BEGIN_ALLOW_THREADS SQLFreeStmt(self->hstmt, SQL_UNBIND); SQLFreeStmt(self->hstmt, SQL_RESET_PARAMS); Py_END_ALLOW_THREADS; } if (self->cnxn->hdbc == SQL_NULL_HANDLE) { // The connection was closed by another thread in the ALLOW_THREADS block above. RaiseErrorV(0, ProgrammingError, "The cursor's connection was closed."); return false; } } if (self->description != Py_None) { Py_DECREF(self->description); self->description = Py_None; Py_INCREF(Py_None); } if (self->map_name_to_index) { Py_DECREF(self->map_name_to_index); self->map_name_to_index = 0; } if ((flags & KEEP_MESSAGES) == 0) { Py_XDECREF(self->messages); self->messages = PyList_New(0); } self->rowcount = -1; return true; } static void closeimpl(Cursor* cur) { // An internal function for the shared 'closing' code used by Cursor_close and Cursor_dealloc. // // This method releases the GIL lock while closing, so verify the HDBC still exists if you use it. free_results(cur, FREE_STATEMENT | FREE_PREPARED); FreeParameterInfo(cur); FreeParameterData(cur); if (StatementIsValid(cur)) { HSTMT hstmt = cur->hstmt; cur->hstmt = SQL_NULL_HANDLE; SQLRETURN ret; Py_BEGIN_ALLOW_THREADS ret = SQLFreeHandle(SQL_HANDLE_STMT, hstmt); Py_END_ALLOW_THREADS // If there is already an exception, don't overwrite it. if (!SQL_SUCCEEDED(ret) && !PyErr_Occurred()) RaiseErrorFromHandle(cur->cnxn, "SQLFreeHandle", cur->cnxn->hdbc, SQL_NULL_HANDLE); } Py_XDECREF(cur->pPreparedSQL); Py_XDECREF(cur->description); Py_XDECREF(cur->map_name_to_index); Py_XDECREF(cur->cnxn); Py_XDECREF(cur->messages); cur->pPreparedSQL = 0; cur->description = 0; cur->map_name_to_index = 0; cur->cnxn = 0; cur->messages = 0; } static char close_doc[] = "Close the cursor now (rather than whenever __del__ is called). The cursor will\n" "be unusable from this point forward; a ProgrammingError exception will be\n" "raised if any operation is attempted with the cursor."; static PyObject* Cursor_close(PyObject* self, PyObject* args) { UNUSED(args); Cursor* cursor = Cursor_Validate(self, CURSOR_REQUIRE_OPEN | CURSOR_RAISE_ERROR); if (!cursor) return 0; closeimpl(cursor); if (PyErr_Occurred()) return 0; Py_INCREF(Py_None); return Py_None; } static void Cursor_dealloc(Cursor* cursor) { if (Cursor_Validate((PyObject*)cursor, CURSOR_REQUIRE_CNXN)) { closeimpl(cursor); } Py_XDECREF(cursor->inputsizes); PyObject_Del(cursor); } bool InitColumnInfo(Cursor* cursor, SQLUSMALLINT iCol, ColumnInfo* pinfo) { // Initializes ColumnInfo from result set metadata. SQLRETURN ret; // REVIEW: This line fails on OS/X with the FileMaker driver : http://www.filemaker.com/support/updaters/xdbc_odbc_mac.html // // I suspect the problem is that it doesn't allow NULLs in some of the parameters, so I'm going to supply them all // to see what happens. SQLCHAR ColumnName[200]; SQLSMALLINT BufferLength = _countof(ColumnName); SQLSMALLINT NameLength = 0; SQLSMALLINT DataType = 0; SQLULEN ColumnSize = 0; SQLSMALLINT DecimalDigits = 0; SQLSMALLINT Nullable = 0; Py_BEGIN_ALLOW_THREADS ret = SQLDescribeCol(cursor->hstmt, iCol, ColumnName, BufferLength, &NameLength, &DataType, &ColumnSize, &DecimalDigits, &Nullable); Py_END_ALLOW_THREADS pinfo->sql_type = DataType; pinfo->column_size = ColumnSize; if (cursor->cnxn->hdbc == SQL_NULL_HANDLE) { // The connection was closed by another thread in the ALLOW_THREADS block above. RaiseErrorV(0, ProgrammingError, "The cursor's connection was closed."); return false; } if (!SQL_SUCCEEDED(ret)) { RaiseErrorFromHandle(cursor->cnxn, "SQLDescribeCol", cursor->cnxn->hdbc, cursor->hstmt); return false; } // If it is an integer type, determine if it is signed or unsigned. The buffer size is the same but we'll need to // know when we convert to a Python integer. switch (pinfo->sql_type) { case SQL_TINYINT: case SQL_SMALLINT: case SQL_INTEGER: case SQL_BIGINT: { SQLLEN f; Py_BEGIN_ALLOW_THREADS ret = SQLColAttribute(cursor->hstmt, iCol, SQL_DESC_UNSIGNED, 0, 0, 0, &f); Py_END_ALLOW_THREADS if (cursor->cnxn->hdbc == SQL_NULL_HANDLE) { // The connection was closed by another thread in the ALLOW_THREADS block above. RaiseErrorV(0, ProgrammingError, "The cursor's connection was closed."); return false; } if (!SQL_SUCCEEDED(ret)) { RaiseErrorFromHandle(cursor->cnxn, "SQLColAttribute", cursor->cnxn->hdbc, cursor->hstmt); return false; } pinfo->is_unsigned = (f == SQL_TRUE); break; } default: pinfo->is_unsigned = false; } return true; } static bool PrepareResults(Cursor* cur, int cCols) { // Called after a SELECT has been executed to perform pre-fetch work. // // Allocates the ColumnInfo structures describing the returned data. int i; I(cur->colinfos == 0); cur->colinfos = (ColumnInfo*)pyodbc_malloc(sizeof(ColumnInfo) * cCols); if (cur->colinfos == 0) { PyErr_NoMemory(); return false; } for (i = 0; i < cCols; i++) { if (!InitColumnInfo(cur, (SQLUSMALLINT)(i + 1), &cur->colinfos[i])) { pyodbc_free(cur->colinfos); cur->colinfos = 0; return false; } } return true; } static int GetDiagRecs(Cursor* cur) { // Retrieves all diagnostic records from the cursor and assigns them to the "messages" attribute. PyObject* msg_list; // the "messages" as a Python list of diagnostic records SQLSMALLINT iRecNumber = 1; // the index of the diagnostic records (1-based) ODBCCHAR cSQLState[6]; // five-character SQLSTATE code (plus terminating NULL) SQLINTEGER iNativeError; SQLSMALLINT iMessageLen = 1023; ODBCCHAR *cMessageText = (ODBCCHAR*) pyodbc_malloc((iMessageLen + 1) * sizeof(ODBCCHAR)); SQLSMALLINT iTextLength; SQLRETURN ret; char sqlstate_ascii[6] = ""; // ASCII version of the SQLState if (!cMessageText) { PyErr_NoMemory(); return 0; } msg_list = PyList_New(0); if (!msg_list) return 0; for (;;) { cSQLState[0] = 0; iNativeError = 0; cMessageText[0] = 0; iTextLength = 0; Py_BEGIN_ALLOW_THREADS ret = SQLGetDiagRecW( SQL_HANDLE_STMT, cur->hstmt, iRecNumber, (SQLWCHAR*)cSQLState, &iNativeError, (SQLWCHAR*)cMessageText, iMessageLen, &iTextLength ); Py_END_ALLOW_THREADS if (!SQL_SUCCEEDED(ret)) break; // If needed, allocate a bigger error message buffer and retry. if (iTextLength > iMessageLen - 1) { iMessageLen = iTextLength + 1; if (!pyodbc_realloc((BYTE**) &cMessageText, (iMessageLen + 1) * sizeof(ODBCCHAR))) { pyodbc_free(cMessageText); PyErr_NoMemory(); return 0; } Py_BEGIN_ALLOW_THREADS ret = SQLGetDiagRecW( SQL_HANDLE_STMT, cur->hstmt, iRecNumber, (SQLWCHAR*)cSQLState, &iNativeError, (SQLWCHAR*)cMessageText, iMessageLen, &iTextLength ); Py_END_ALLOW_THREADS if (!SQL_SUCCEEDED(ret)) break; } cSQLState[5] = 0; // Not always NULL terminated (MS Access) CopySqlState(cSQLState, sqlstate_ascii); PyObject* msg_class = PyUnicode_FromFormat("[%s] (%ld)", sqlstate_ascii, (long)iNativeError); // Default to UTF-16, which may not work if the driver/manager is using some other encoding const char *unicode_enc = cur->cnxn ? cur->cnxn->metadata_enc.name : ENCSTR_UTF16NE; PyObject* msg_value = PyUnicode_Decode( (char*)cMessageText, iTextLength * sizeof(ODBCCHAR), unicode_enc, "strict" ); if (!msg_value) { // If the char cannot be decoded, return something rather than nothing. Py_XDECREF(msg_value); msg_value = PyBytes_FromStringAndSize((char*)cMessageText, iTextLength * sizeof(O
c++
code
20,000
3,787
/* * Copyright (C) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "third_party/blink/renderer/core/dom/transform_source.h" #include <libxml/tree.h> namespace blink { TransformSource::TransformSource(xmlDocPtr source) : source_(source) {} TransformSource::~TransformSource() { xmlFreeDoc(source_); } } // namespace blink
c++
code
1,602
299
#pragma once #include "prog/expr/node.hpp" #include "prog/program.hpp" namespace prog::expr { // Load a function literal. class LitFuncNode final : public Node { friend auto litFuncNode(const Program& program, sym::TypeId type, sym::FuncId func) -> NodePtr; public: LitFuncNode() = delete; auto operator==(const Node& rhs) const noexcept -> bool override; auto operator!=(const Node& rhs) const noexcept -> bool override; [[nodiscard]] constexpr static auto getKind() { return NodeKind::LitFunc; } [[nodiscard]] auto operator[](unsigned int i) const -> const Node& override; [[nodiscard]] auto getChildCount() const -> unsigned int override; [[nodiscard]] auto getType() const noexcept -> sym::TypeId override; [[nodiscard]] auto toString() const -> std::string override; [[nodiscard]] auto clone(Rewriter* rewriter) const -> std::unique_ptr<Node> override; [[nodiscard]] auto getFunc() const noexcept -> sym::FuncId; auto accept(NodeVisitor* visitor) const -> void override; private: sym::TypeId m_type; sym::FuncId m_func; LitFuncNode(sym::TypeId type, sym::FuncId func); }; // Factories. auto litFuncNode(const Program& program, sym::TypeId type, sym::FuncId func) -> NodePtr; } // namespace prog::expr
c++
code
1,248
312
#include <qpdf/Pl_PNGFilter.hh> #include <qpdf/QTC.hh> #include <qpdf/QUtil.hh> #include <limits.h> #include <stdexcept> #include <string.h> static int abs_diff(int a, int b) { return a > b ? a - b : b - a; } Pl_PNGFilter::Pl_PNGFilter( char const* identifier, Pipeline* next, action_e action, unsigned int columns, unsigned int samples_per_pixel, unsigned int bits_per_sample) : Pipeline(identifier, next), action(action), cur_row(0), prev_row(0), buf1(0), buf2(0), pos(0) { if (samples_per_pixel < 1) { throw std::runtime_error( "PNGFilter created with invalid samples_per_pixel"); } if (!((bits_per_sample == 1) || (bits_per_sample == 2) || (bits_per_sample == 4) || (bits_per_sample == 8) || (bits_per_sample == 16))) { throw std::runtime_error( "PNGFilter created with invalid bits_per_sample not" " 1, 2, 4, 8, or 16"); } this->bytes_per_pixel = ((bits_per_sample * samples_per_pixel) + 7) / 8; unsigned long long bpr = ((columns * bits_per_sample * samples_per_pixel) + 7) / 8; if ((bpr == 0) || (bpr > (UINT_MAX - 1))) { throw std::runtime_error( "PNGFilter created with invalid columns value"); } this->bytes_per_row = bpr & UINT_MAX; this->buf1 = QUtil::make_shared_array<unsigned char>(this->bytes_per_row + 1); this->buf2 = QUtil::make_shared_array<unsigned char>(this->bytes_per_row + 1); memset(this->buf1.get(), 0, this->bytes_per_row + 1); memset(this->buf2.get(), 0, this->bytes_per_row + 1); this->cur_row = this->buf1.get(); this->prev_row = this->buf2.get(); // number of bytes per incoming row this->incoming = (action == a_encode ? this->bytes_per_row : this->bytes_per_row + 1); } void Pl_PNGFilter::write(unsigned char const* data, size_t len) { size_t left = this->incoming - this->pos; size_t offset = 0; while (len >= left) { // finish off current row memcpy(this->cur_row + this->pos, data + offset, left); offset += left; len -= left; processRow(); // Swap rows unsigned char* t = this->prev_row; this->prev_row = this->cur_row; this->cur_row = t ? t : this->buf2.get(); memset(this->cur_row, 0, this->bytes_per_row + 1); left = this->incoming; this->pos = 0; } if (len) { memcpy(this->cur_row + this->pos, data + offset, len); } this->pos += len; } void Pl_PNGFilter::processRow() { if (this->action == a_encode) { encodeRow(); } else { decodeRow(); } } void Pl_PNGFilter::decodeRow() { int filter = this->cur_row[0]; if (this->prev_row) { switch (filter) { case 0: break; case 1: this->decodeSub(); break; case 2: this->decodeUp(); break; case 3: this->decodeAverage(); break; case 4: this->decodePaeth(); break; default: // ignore break; } } getNext()->write(this->cur_row + 1, this->bytes_per_row); } void Pl_PNGFilter::decodeSub() { QTC::TC("libtests", "Pl_PNGFilter decodeSub"); unsigned char* buffer = this->cur_row + 1; unsigned int bpp = this->bytes_per_pixel; for (unsigned int i = 0; i < this->bytes_per_row; ++i) { unsigned char left = 0; if (i >= bpp) { left = buffer[i - bpp]; } buffer[i] = static_cast<unsigned char>(buffer[i] + left); } } void Pl_PNGFilter::decodeUp() { QTC::TC("libtests", "Pl_PNGFilter decodeUp"); unsigned char* buffer = this->cur_row + 1; unsigned char* above_buffer = this->prev_row + 1; for (unsigned int i = 0; i < this->bytes_per_row; ++i) { unsigned char up = above_buffer[i]; buffer[i] = static_cast<unsigned char>(buffer[i] + up); } } void Pl_PNGFilter::decodeAverage() { QTC::TC("libtests", "Pl_PNGFilter decodeAverage"); unsigned char* buffer = this->cur_row + 1; unsigned char* above_buffer = this->prev_row + 1; unsigned int bpp = this->bytes_per_pixel; for (unsigned int i = 0; i < this->bytes_per_row; ++i) { int left = 0; int up = 0; if (i >= bpp) { left = buffer[i - bpp]; } up = above_buffer[i]; buffer[i] = static_cast<unsigned char>(buffer[i] + (left + up) / 2); } } void Pl_PNGFilter::decodePaeth() { QTC::TC("libtests", "Pl_PNGFilter decodePaeth"); unsigned char* buffer = this->cur_row + 1; unsigned char* above_buffer = this->prev_row + 1; unsigned int bpp = this->bytes_per_pixel; for (unsigned int i = 0; i < this->bytes_per_row; ++i) { int left = 0; int up = above_buffer[i]; int upper_left = 0; if (i >= bpp) { left = buffer[i - bpp]; upper_left = above_buffer[i - bpp]; } buffer[i] = static_cast<unsigned char>( buffer[i] + this->PaethPredictor(left, up, upper_left)); } } int Pl_PNGFilter::PaethPredictor(int a, int b, int c) { int p = a + b - c; int pa = abs_diff(p, a); int pb = abs_diff(p, b); int pc = abs_diff(p, c); if (pa <= pb && pa <= pc) { return a; } if (pb <= pc) { return b; } return c; } void Pl_PNGFilter::encodeRow() { // For now, hard-code to using UP filter. unsigned char ch = 2; getNext()->write(&ch, 1); if (this->prev_row) { for (unsigned int i = 0; i < this->bytes_per_row; ++i) { ch = static_cast<unsigned char>( this->cur_row[i] - this->prev_row[i]); getNext()->write(&ch, 1); } } else { getNext()->write(this->cur_row, this->bytes_per_row); } } void Pl_PNGFilter::finish() { if (this->pos) { // write partial row processRow(); } this->prev_row = 0; this->cur_row = buf1.get(); this->pos = 0; memset(this->cur_row, 0, this->bytes_per_row + 1); getNext()->finish(); }
c++
code
6,211
1,570
/* Copyright (c) 2004-2006 Jesper Svennevid, Daniel Collin 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 "SerializableFactory.h" #include "SerializableStructure.h" namespace zenic { SerializableFactory* SerializableFactory::ms_first = 0; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// SerializableFactory::~SerializableFactory() { // detach factory from global list SerializableFactory* curr = ms_first; SerializableFactory* last = 0; for (; curr ; last = curr, curr = curr->m_next) { if (this == curr) { if (last) last->m_next = curr->m_next; else ms_first = curr->m_next; break; } } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// SerializableFactory* SerializableFactory::find(Identifier host, Identifier type) { for (SerializableFactory* factory = SerializableFactory::first(); factory; factory = factory->next()) { if ((factory->host() == host) && (factory->type() == type)) return factory; } return 0; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// SerializableStructure* SerializableFactory::findStructure(SerializableStructure::Identifier identifier) const { for (SerializableStructure* structure = m_structures; structure; structure = structure->next()) { if (structure->identifier() == identifier) return structure; } return 0; } }
c++
code
2,513
441
//////////////////////////////////////////////////////////////////////////////// // Name: blame.cpp // Purpose: Implementation of class wex::blame // Author: Anton van Wezenbeek // Copyright: (c) 2021 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wex/blame.h> #include <wex/chrono.h> #include <wex/config.h> #include <wex/log.h> #include <wex/regex.h> namespace wex { std::string build(const std::string& key, const std::string& field, bool first = false) { std::string add; if (config("blame." + key).get(true)) { if (!first) { add += " "; } add += field; } return add; } } // namespace wex wex::blame::blame(const pugi::xml_node& node) : m_blame_format(node.attribute("blame-format").value()) , m_date_format(node.attribute("date-format").value()) , m_date_print(node.attribute("date-print").as_uint()) { } std::tuple<bool, const std::string, wex::lexers::margin_style_t, int> wex::blame::get(const std::string& text) const { try { if (regex r(m_blame_format); r.search(text) >= 3) { const std::string info( build("id", r[0], true) + build("author", r[1]) + build("date", r[2].substr(0, m_date_print))); const auto line(r.size() == 4 ? std::stoi(r[3]) - 1 : -1); return {true, info.empty() ? " " : info, get_style(r[2]), line}; } } catch (std::exception& e) { log(e) << "blame:" << text; } return {false, std::string(), lexers::margin_style_t::OTHER, 0}; } wex::lexers::margin_style_t wex::blame::get_style(const std::string& text) const { lexers::margin_style_t style = lexers::margin_style_t::UNKNOWN; if (text.empty()) { return style; } if (const auto& [r, t] = chrono(m_date_format).get_time(text); r) { const time_t now = time(nullptr); const auto dt = difftime(now, t); const int seconds = 1; const int seconds_in_minute = 60 * seconds; const int seconds_in_hour = 60 * seconds_in_minute; const int seconds_in_day = 24 * seconds_in_hour; const int seconds_in_week = 7 * seconds_in_day; const int seconds_in_month = 30 * seconds_in_day; const int seconds_in_year = 365 * seconds_in_day; if (dt < seconds_in_day) { style = lexers::margin_style_t::DAY; } else if (dt < seconds_in_week) { style = lexers::margin_style_t::WEEK; } else if (dt < seconds_in_month) { style = lexers::margin_style_t::MONTH; } else if (dt < seconds_in_year) { style = lexers::margin_style_t::YEAR; } else { style = lexers::margin_style_t::OTHER; } } return style; }
c++
code
2,784
667
// -*- C++ -*- // // Package: EcalTBHodoscopeGeometryAnalyzer // Class: EcalTBHodoscopeGeometryAnalyzer // /**\class EcalTBHodoscopeGeometryAnalyzer EcalTBHodoscopeGeometryAnalyzer.cc test/EcalTBHodoscopeGeometryAnalyzer/src/EcalTBHodoscopeGeometryAnalyzer.cc Description: <one line class summary> Implementation: <Notes on implementation> */ // // system include files #include <memory> #include <cmath> // user include files #include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "Geometry/CaloGeometry/interface/CaloSubdetectorGeometry.h" #include "Geometry/CaloGeometry/interface/CaloGeometry.h" #include "Geometry/CaloGeometry/interface/CaloCellGeometry.h" #include "Geometry/Records/interface/CaloGeometryRecord.h" #include "SimDataFormats/EcalTestBeam/interface/HodoscopeDetId.h" #include "CLHEP/Vector/ThreeVector.h" #include "CLHEP/Vector/Rotation.h" #include "CLHEP/Units/GlobalSystemOfUnits.h" // // class decleration // class EcalTBHodoscopeGeometryAnalyzer : public edm::one::EDAnalyzer<> { public: explicit EcalTBHodoscopeGeometryAnalyzer( const edm::ParameterSet& ); ~EcalTBHodoscopeGeometryAnalyzer() override; void beginJob() override {} void analyze(edm::Event const& iEvent, edm::EventSetup const&) override; void endJob() override {} private: void build(const CaloGeometry& cg, DetId::Detector det, int subdetn); CLHEP::HepRotation * fromCMStoTB( const double & myEta , const double & myPhi ) const; int pass_; double eta_; double phi_; CLHEP::HepRotation * fromCMStoTB_; }; // // constants, enums and typedefs // // // static data member definitions // // // constructors and destructor // EcalTBHodoscopeGeometryAnalyzer::EcalTBHodoscopeGeometryAnalyzer( const edm::ParameterSet& iConfig ) { //now do what ever initialization is needed pass_=0; eta_ = iConfig.getUntrackedParameter<double>("eta",0.971226); phi_ = iConfig.getUntrackedParameter<double>("phi",0.115052); fromCMStoTB_ = fromCMStoTB( eta_ , phi_ ); } EcalTBHodoscopeGeometryAnalyzer::~EcalTBHodoscopeGeometryAnalyzer() { // do anything here that needs to be done at desctruction time // (e.g. close files, deallocate resources etc.) delete fromCMStoTB_; } void EcalTBHodoscopeGeometryAnalyzer::build(const CaloGeometry& cg, DetId::Detector det, int subdetn) { const CaloSubdetectorGeometry* geom(cg.getSubdetectorGeometry(det,subdetn)); int n=0; const std::vector<DetId>& ids=geom->getValidDetIds(det,subdetn); for (auto id : ids) { n++; auto cell=geom->getGeometry(id); if (det == DetId::Ecal) { if (subdetn == EcalLaserPnDiode) { CLHEP::Hep3Vector thisCellPos( cell->getPosition().x(), cell->getPosition().y(), cell->getPosition().z() ); CLHEP::Hep3Vector rotCellPos = (*fromCMStoTB_)*thisCellPos; edm::LogInfo("EcalTBGeom") << "Fiber DetId = " << HodoscopeDetId(id) << " position = " <<rotCellPos; } } } } // // member functions // // ------------ method called to produce the data ------------ void EcalTBHodoscopeGeometryAnalyzer::analyze( const edm::Event& iEvent, const edm::EventSetup& iSetup ) { std::cout << "Here I am " << std::endl; edm::ESHandle<CaloGeometry> pG; iSetup.get<CaloGeometryRecord>().get(pG); // // get the ecal & hcal geometry // if (pass_==0) { build(*pG,DetId::Ecal,EcalLaserPnDiode); } pass_++; } CLHEP::HepRotation * EcalTBHodoscopeGeometryAnalyzer::fromCMStoTB( const double & myEta , const double & myPhi ) const { double myTheta = 2.0*atan(exp(-myEta)); // rotation matrix to move from the CMS reference frame to the test beam one CLHEP::HepRotation * CMStoTB = new CLHEP::HepRotation(); double angle1 = 90.*deg - myPhi; CLHEP::HepRotationZ * r1 = new CLHEP::HepRotationZ(angle1); double angle2 = myTheta; CLHEP::HepRotationX * r2 = new CLHEP::HepRotationX(angle2); double angle3 = 90.*deg; CLHEP::HepRotationZ * r3 = new CLHEP::HepRotationZ(angle3); (*CMStoTB) *= (*r3); (*CMStoTB) *= (*r2); (*CMStoTB) *= (*r1); return CMStoTB; } //define this as a plug-in DEFINE_FWK_MODULE(EcalTBHodoscopeGeometryAnalyzer);
c++
code
4,481
883
#ifndef UTIL_H #define UTIL_H #include <deque> #include <memory> #include <stdexcept> #include <string> #include <vector> #include "exceptions.hpp" namespace util { // clang-format off #define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c" #define BYTE_TO_BINARY(byte) \ (byte & 0x80 ? '1' : '0'), \ (byte & 0x40 ? '1' : '0'), \ (byte & 0x20 ? '1' : '0'), \ (byte & 0x10 ? '1' : '0'), \ (byte & 0x08 ? '1' : '0'), \ (byte & 0x04 ? '1' : '0'), \ (byte & 0x02 ? '1' : '0'), \ (byte & 0x01 ? '1' : '0') // clang-format on /// Helper function to pop front item from deque and return it /// \note Assumes there is a value in the queue to actually pop, so length checks must be done ahead of time /// \tparam T is type of items in queue, the first of which will be returned /// \param queue queue of items to pop front item from /// \return first item in queue template <typename T> inline T pop_front(std::deque<T>& queue) { // Get front byte value and then remove it from queue auto byte = queue.front(); queue.pop_front(); return byte; } /// Helper function to pop multiple bytes from deque /// \note Assumes there are enough values in the queue to pop, so length checks must be done ahead of time /// \tparam T is type of items in queue, the first n of which will be returned /// \param queue queue of items to pop items from /// \param n number of items to pop from queue /// \return vector of values from queue template <typename T> inline std::vector<T> drain_deque(std::deque<T>& queue, size_t n) { // Store values that have been "popped" std::vector<T> retVals{ queue.begin(), queue.begin() + n }; // Remove values from queue queue.erase(queue.begin(), queue.begin() + n); return retVals; } /// Helper function to convert an array of 4 bytes in Big Endian order to uint32 /// \param bytes 4 byte array (8 bit unsigned int) in big endian order to be converted /// \return uint32 in little endian order constexpr inline uint32_t uint32FromBEBytes(uint8_t bytes[4]) { return static_cast<uint32_t>(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3] << 0); } /// Confirms that the queue passed has at least n values available, throwing an exception if not /// \tparam T type that the queue holds /// \param queue queue of elements of type T to have length checked on /// \param n minimum number of elements to confirm queue has /// \param item string of item these bytes will be used for. Used to create error message. /// \throws NDEFException if n >= number of elements in queue template <typename T> void assertHasValues(std::deque<T> queue, size_t n, std::string item) { if (queue.size() < n) { throw NDEFException("Too few elements in queue for " + item + " field: " + "require " + std::to_string(n) + " have " + std::to_string(queue.size())); } // Number of elements >= n, no exception tossing today boys return; } /// Confirms that the queue passed has at least 1 value available, throwing an exception if not. /// \note Wrapper around assertHasValues /// \tparam T type that the queue holds /// \param item string of item this byte will be used for. Used to create error message. /// \param queue queue of elements of type T to have length checked on /// \throws NDEFException if the queue is empty template <typename T> void assertHasValue(std::deque<T> queue, std::string item) { // That's all we need to know if (queue.size() > 0) return; // Oh brother, there are 0 elements in the queue... throw NDEFException("Too few elements in queue for " + item + " field: require 1 have 0"); } } // namespace util #endif // UTIL_H
c++
code
3,630
917
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "Frame.h" #include "PageGroupLoadDeferrer.h" #include "V8Proxy.h" #include <wtf/HashSet.h> #undef LOG #include "base/string_util.h" #include "webkit/glue/devtools/debugger_agent_impl.h" #include "webkit/glue/devtools/debugger_agent_manager.h" #include "webkit/glue/webdevtoolsagent_impl.h" #include "webkit/glue/webview_impl.h" #if USE(V8) #include "v8/include/v8-debug.h" #endif WebDevToolsAgent::MessageLoopDispatchHandler DebuggerAgentManager::message_loop_dispatch_handler_ = NULL; // static bool DebuggerAgentManager::in_host_dispatch_handler_ = false; // static DebuggerAgentManager::DeferrersMap DebuggerAgentManager::page_deferrers_; namespace { class CallerIdWrapper : public v8::Debug::ClientData { public: CallerIdWrapper() : caller_is_mananager_(true), caller_id_(0) {} explicit CallerIdWrapper(int caller_id) : caller_is_mananager_(false), caller_id_(caller_id) {} ~CallerIdWrapper() {} bool caller_is_mananager() const { return caller_is_mananager_; } int caller_id() const { return caller_id_; } private: bool caller_is_mananager_; int caller_id_; DISALLOW_COPY_AND_ASSIGN(CallerIdWrapper); }; } // namespace void DebuggerAgentManager::V8DebugHostDispatchHandler() { if (!DebuggerAgentManager::message_loop_dispatch_handler_ || !attached_agents_map_) { return; } if (in_host_dispatch_handler_) { return; } in_host_dispatch_handler_ = true; Vector<WebViewImpl*> views; // 1. Disable active objects and input events. for (AttachedAgentsMap::iterator it = attached_agents_map_->begin(); it != attached_agents_map_->end(); ++it) { DebuggerAgentImpl* agent = it->second; page_deferrers_.set( agent->web_view(), new WebCore::PageGroupLoadDeferrer(agent->GetPage(), true)); views.append(agent->web_view()); agent->web_view()->SetIgnoreInputEvents(true); } // 2. Process messages. DebuggerAgentManager::message_loop_dispatch_handler_(); // 3. Bring things back. for (Vector<WebViewImpl*>::iterator it = views.begin(); it != views.end(); ++it) { if (page_deferrers_.contains(*it)) { // The view was not closed during the dispatch. (*it)->SetIgnoreInputEvents(false); } } deleteAllValues(page_deferrers_); page_deferrers_.clear(); in_host_dispatch_handler_ = false; if (!attached_agents_map_) { // Remove handlers if all agents were detached within host dispatch. v8::Debug::SetMessageHandler(NULL); v8::Debug::SetHostDispatchHandler(NULL); } } // static DebuggerAgentManager::AttachedAgentsMap* DebuggerAgentManager::attached_agents_map_ = NULL; // static void DebuggerAgentManager::DebugAttach(DebuggerAgentImpl* debugger_agent) { if (!attached_agents_map_) { attached_agents_map_ = new AttachedAgentsMap(); v8::Debug::SetMessageHandler2(&DebuggerAgentManager::OnV8DebugMessage); v8::Debug::SetHostDispatchHandler( &DebuggerAgentManager::V8DebugHostDispatchHandler, 100 /* ms */); } int host_id = debugger_agent->webdevtools_agent()->host_id(); DCHECK(host_id != 0); attached_agents_map_->set(host_id, debugger_agent); } // static void DebuggerAgentManager::DebugDetach(DebuggerAgentImpl* debugger_agent) { if (!attached_agents_map_) { NOTREACHED(); return; } int host_id = debugger_agent->webdevtools_agent()->host_id(); DCHECK(attached_agents_map_->get(host_id) == debugger_agent); bool is_on_breakpoint = (FindAgentForCurrentV8Context() == debugger_agent); attached_agents_map_->remove(host_id); if (attached_agents_map_->isEmpty()) { delete attached_agents_map_; attached_agents_map_ = NULL; // Note that we do not empty handlers while in dispatch - we schedule // continue and do removal once we are out of the dispatch. Also there is // no need to send continue command in this case since removing message // handler will cause debugger unload and all breakpoints will be cleared. if (!in_host_dispatch_handler_) { v8::Debug::SetMessageHandler2(NULL); v8::Debug::SetHostDispatchHandler(NULL); } } else { // Remove all breakpoints set by the agent. std::wstring clear_breakpoint_group_cmd(StringPrintf( L"{\"seq\":1,\"type\":\"request\",\"command\":\"clearbreakpointgroup\"," L"\"arguments\":{\"groupId\":%d}}", host_id)); SendCommandToV8(WideToUTF16(clear_breakpoint_group_cmd), new CallerIdWrapper()); if (is_on_breakpoint) { // Force continue if detach happened in nessted message loop while // debugger was paused on a breakpoint(as long as there are other // attached agents v8 will wait for explicit'continue' message). SendContinueCommandToV8(); } } } // static void DebuggerAgentManager::DebugBreak(DebuggerAgentImpl* debugger_agent) { #if USE(V8) DCHECK(DebuggerAgentForHostId(debugger_agent->webdevtools_agent()->host_id()) == debugger_agent); v8::Debug::DebugBreak(); #endif } // static void DebuggerAgentManager::OnV8DebugMessage(const v8::Debug::Message& message) { v8::HandleScope scope; v8::String::Utf8Value value(message.GetJSON()); std::string out(*value, value.length()); // If caller_data is not NULL the message is a response to a debugger command. if (v8::Debug::ClientData* caller_data = message.GetClientData()) { CallerIdWrapper* wrapper = static_cast<CallerIdWrapper*>(caller_data); if (wrapper->caller_is_mananager()) { // Just ignore messages sent by this manager. return; } DebuggerAgentImpl* debugger_agent = DebuggerAgentForHostId(wrapper->caller_id()); if (debugger_agent) { debugger_agent->DebuggerOutput(out); } else if (!message.WillStartRunning()) { // Autocontinue execution if there is no handler. SendContinueCommandToV8(); } return; } // Otherwise it's an event message. DCHECK(message.IsEvent()); // Ignore unsupported event types. if (message.GetEvent() != v8::AfterCompile && message.GetEvent() != v8::Break && message.GetEvent() != v8::Exception) { return; } v8::Handle<v8::Context> context = message.GetEventContext(); // If the context is from one of the inpected tabs it should have its context // data. if (context.IsEmpty()) { // Unknown context, skip the event. return; } // If the context is from one of the inpected tabs or injected extension // scripts it must have host_id in the data field. int host_id = WebCore::V8Proxy::contextDebugId(context); if (host_id != -1) { DebuggerAgentImpl* agent = DebuggerAgentForHostId(host_id); if (agent) { agent->DebuggerOutput(out); return; } } if (!message.WillStartRunning()) { // Autocontinue execution on break and exception events if there is no // handler. SendContinueCommandToV8(); } } // static void DebuggerAgentManager::ExecuteDebuggerCommand( const std::string& command, int caller_id) { SendCommandToV8(UTF8ToUTF16(command), new CallerIdWrapper(caller_id)); } // static void DebuggerAgentManager::SetMessageLoopDispatchHandler( WebDevToolsAgent::MessageLoopDispatchHandler handler) { message_loop_dispatch_handler_ = handler; } // static void DebuggerAgentManager::SetHostId(WebFrameImpl* webframe, int host_id) { DCHECK(host_id > 0); WebCore::V8Proxy* proxy = WebCore::V8Proxy::retrieve(webframe->frame()); if (proxy) { proxy->setContextDebugId(host_id); } } // static void DebuggerAgentManager::OnWebViewClosed(WebViewImpl* webview) { if (page_deferrers_.contains(webview)) { delete page_deferrers_.get(webview); page_deferrers_.remove(webview); } } // static void DebuggerAgentManager::SendCommandToV8(const string16& cmd, v8::Debug::ClientData* data) { #if USE(V8) v8::Debug::SendCommand(reinterpret_cast<const uint16_t*>(cmd.data()), cmd.length(), data); #endif } void DebuggerAgentManager::SendContinueCommandToV8() { std::wstring continue_cmd( L"{\"seq\":1,\"type\":\"request\",\"command\":\"continue\"}"); SendCommandToV8(WideToUTF16(continue_cmd), new CallerIdWrapper()); } // static DebuggerAgentImpl* DebuggerAgentManager::FindAgentForCurrentV8Context() { if (!attached_agents_map_) { return NULL; } DCHECK(!attached_agents_map_->isEmpty()); WebCore::Frame* frame = WebCore::V8Proxy::retrieveFrameForEnteredContext(); if (!frame) { return NULL; } WebCore::Page* page = frame->page(); for (AttachedAgentsMap::iterator it = attached_agents_map_->begin(); it != attached_agents_map_->end(); ++it) { if (it->second->GetPage() == page) { return it->second; } } return NULL; } // static DebuggerAgentImpl* DebuggerAgentManager::DebuggerAgentForHostId(int host_id) { if (!attached_agents_map_) { return NULL; } return attached_agents_map_->get(host_id); }
c++
code
9,180
1,825