hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
9908aafcef0a52579b638ce492e0249706f21f20
4,374
cpp
C++
test/vector_test.cpp
felipe-lavratti/chelper
4273eedd76d8fb6dc22dd978abad5ab7636bf39b
[ "MIT" ]
4
2016-08-15T21:56:39.000Z
2017-01-18T12:54:49.000Z
test/vector_test.cpp
felipe-lavratti/chelper
4273eedd76d8fb6dc22dd978abad5ab7636bf39b
[ "MIT" ]
null
null
null
test/vector_test.cpp
felipe-lavratti/chelper
4273eedd76d8fb6dc22dd978abad5ab7636bf39b
[ "MIT" ]
null
null
null
/* * Copyright (c) 2013 Felipe Lavratti (felipe@andradeneves.com) * * 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 "CppUTest/TestHarness.h" #include "CppUTest/MemoryLeakDetector.h" extern "C" { #include "chelper/vector.h" #include "vector.c" } TEST_GROUP(vector) { vector_t cut; struct s_vector_private *icut; struct s_item{ int32_t a; uint8_t b; } clone_vector[10]; void setup() { icut = (struct s_vector_private *)&cut; vector_init(&cut, sizeof(struct s_item)); } void teardown() { vector_deinit(&cut); } }; TEST(vector, addAndRead) { for (int var = 0; var < 10; ++var) { clone_vector[var].a = var; clone_vector[var].b = var%2; vector_add(&cut, (BUFFER_PTR_RDOLY)&clone_vector[var]); unsigned int n = vector_size(&cut); CHECK_EQUAL((unsigned)var+1, n); } struct s_item *read_item; read_item = (struct s_item *)vector_at(&cut, 8); CHECK_EQUAL(clone_vector[8].a, read_item->a); CHECK_EQUAL(clone_vector[8].b, read_item->b); } TEST(vector, addthree) { CHECK_EQUAL(2, icut->buffer_total_slots); CHECK_EQUAL(0, icut->used_slots); vector_add(&cut, (uint8_t *)&clone_vector[0]); CHECK_EQUAL(1, icut->used_slots); vector_add(&cut, (uint8_t *)&clone_vector[0]); CHECK_EQUAL(2, icut->used_slots); vector_add(&cut, (uint8_t *)&clone_vector[0]); CHECK_EQUAL(3, icut->used_slots); CHECK_EQUAL(4, icut->buffer_total_slots); } TEST(vector, instance) { CHECK_EQUAL(2, icut->buffer_total_slots); } TEST(vector, addmany_remove) { vector_t vec; struct s_vector_private * ivec = ((struct s_vector_private *)&vec); vector_init(&vec, sizeof(char)); uint32_t str_size = strlen("abcdefghijklmnopqrstuvxywz") + 1; vector_add_many(&vec, (BUFFER_PTR_RDOLY)"abcdefghijklmnopqrstuvxywz", str_size); CHECK_EQUAL(str_size, ivec->used_slots); STRCMP_EQUAL("abcdefghijklmnopqrstuvxywz", (const char *)vector_data(&vec)); vector_remove(&vec, 10); /* remove letter k */ STRCMP_EQUAL("abcdefghijlmnopqrstuvxywz", (const char *)vector_data(&vec)); vector_clear(&vec); CHECK_EQUAL(0, ivec->used_slots); CHECK_EQUAL((BUFFER_PTR)0, vector_at(&vec, 0)); vector_add_many(&vec, (BUFFER_PTR_RDOLY)"abcdefghijklmnopqrstuvxywz", str_size); CHECK_EQUAL(str_size, ivec->used_slots); STRCMP_EQUAL("abcdefghijklmnopqrstuvxywz", (const char *)vector_data(&vec)); vector_remove(&vec, 10); /* remove letter k */ STRCMP_EQUAL("abcdefghijlmnopqrstuvxywz", (const char *)vector_data(&vec)); vector_deinit(&vec); } TEST(vector, addthreeremoveitem) { clone_vector[0].a = 10; clone_vector[0].b = 11; clone_vector[1].a = 20; clone_vector[1].b = 21; clone_vector[2].a = 30; clone_vector[2].b = 31; CHECK_EQUAL(2, icut->buffer_total_slots); CHECK_EQUAL(0, icut->used_slots); vector_add(&cut, (uint8_t *)&clone_vector[0]); CHECK_EQUAL(1, icut->used_slots); vector_add(&cut, (uint8_t *)&clone_vector[1]); CHECK_EQUAL(2, icut->used_slots); vector_add(&cut, (uint8_t *)&clone_vector[2]); CHECK_EQUAL(3, icut->used_slots); CHECK_EQUAL(4, icut->buffer_total_slots); vector_remove_item(&cut, (uint8_t *)&clone_vector[1]); CHECK_EQUAL(2, icut->used_slots); CHECK_TRUE((bool)(memcmp(&clone_vector[0], vector_at(&cut, 0), sizeof(struct s_item)) == 0)); CHECK_TRUE((bool)(memcmp(&clone_vector[2], vector_at(&cut, 1), sizeof(struct s_item)) == 0)); }
30.587413
94
0.721765
[ "vector" ]
990fe2a6b65c85faf0ef46d7589fa26fbad6d1c4
313,634
cc
C++
components/autofill/core/browser/personal_data_manager_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/autofill/core/browser/personal_data_manager_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/autofill/core/browser/personal_data_manager_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/autofill/core/browser/personal_data_manager.h" #include <stddef.h> #include <algorithm> #include <list> #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "base/command_line.h" #include "base/files/scoped_temp_dir.h" #include "base/guid.h" #include "base/i18n/time_formatting.h" #include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "base/synchronization/waitable_event.h" #include "base/test/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "base/test/simple_test_clock.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "build/build_config.h" #include "components/autofill/core/browser/autofill_experiments.h" #include "components/autofill/core/browser/autofill_metrics.h" #include "components/autofill/core/browser/autofill_profile.h" #include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/browser/field_types.h" #include "components/autofill/core/browser/form_structure.h" #include "components/autofill/core/browser/personal_data_manager_observer.h" #include "components/autofill/core/browser/test_autofill_clock.h" #include "components/autofill/core/browser/webdata/autofill_table.h" #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" #include "components/autofill/core/common/autofill_clock.h" #include "components/autofill/core/common/autofill_constants.h" #include "components/autofill/core/common/autofill_pref_names.h" #include "components/autofill/core/common/autofill_switches.h" #include "components/autofill/core/common/form_data.h" #include "components/os_crypt/os_crypt_mocker.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/fake_signin_manager.h" #include "components/signin/core/browser/test_signin_client.h" #include "components/signin/core/common/signin_pref_names.h" #include "components/variations/variations_params_manager.h" #include "components/webdata/common/web_data_service_base.h" #include "components/webdata/common/web_database_service.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace autofill { namespace { enum UserMode { USER_MODE_NORMAL, USER_MODE_INCOGNITO }; const char kUTF8MidlineEllipsis[] = " " "\xE2\x80\xA2\xE2\x80\x86" "\xE2\x80\xA2\xE2\x80\x86" "\xE2\x80\xA2\xE2\x80\x86" "\xE2\x80\xA2\xE2\x80\x86"; const base::Time kArbitraryTime = base::Time::FromDoubleT(25); const base::Time kSomeLaterTime = base::Time::FromDoubleT(1000); const base::Time kMuchLaterTime = base::Time::FromDoubleT(5000); ACTION(QuitMainMessageLoop) { base::MessageLoop::current()->QuitWhenIdle(); } class PersonalDataLoadedObserverMock : public PersonalDataManagerObserver { public: PersonalDataLoadedObserverMock() {} virtual ~PersonalDataLoadedObserverMock() {} MOCK_METHOD0(OnPersonalDataChanged, void()); }; template <typename T> bool CompareElements(T* a, T* b) { return a->Compare(*b) < 0; } template <typename T> bool ElementsEqual(T* a, T* b) { return a->Compare(*b) == 0; } // Verifies that two vectors have the same elements (according to T::Compare) // while ignoring order. This is useful because multiple profiles or credit // cards that are added to the SQLite DB within the same second will be returned // in GUID (aka random) order. template <typename T> void ExpectSameElements(const std::vector<T*>& expectations, const std::vector<T*>& results) { ASSERT_EQ(expectations.size(), results.size()); std::vector<T*> expectations_copy = expectations; std::sort( expectations_copy.begin(), expectations_copy.end(), CompareElements<T>); std::vector<T*> results_copy = results; std::sort(results_copy.begin(), results_copy.end(), CompareElements<T>); EXPECT_EQ(std::mismatch(results_copy.begin(), results_copy.end(), expectations_copy.begin(), ElementsEqual<T>).first, results_copy.end()); } } // anonymous namespace class PersonalDataManagerTestBase { protected: PersonalDataManagerTestBase() : autofill_table_(nullptr) {} void ResetPersonalDataManager(UserMode user_mode) { bool is_incognito = (user_mode == USER_MODE_INCOGNITO); personal_data_.reset(new PersonalDataManager("en")); personal_data_->Init( scoped_refptr<AutofillWebDataService>(autofill_database_service_), prefs_.get(), account_tracker_.get(), signin_manager_.get(), is_incognito); personal_data_->AddObserver(&personal_data_observer_); personal_data_->OnSyncServiceInitialized(nullptr); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); } void ResetProfiles() { std::vector<AutofillProfile> empty_profiles; personal_data_->SetProfiles(&empty_profiles); } void EnableWalletCardImport() { signin_manager_->SetAuthenticatedAccountInfo("12345", "syncuser@example.com"); base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableOfferStoreUnmaskedWalletCards); } void EnableAutofillProfileCleanup() { personal_data_->is_autofill_profile_cleanup_pending_ = true; } void SetupReferenceProfile() { ASSERT_EQ(0U, personal_data_->GetProfiles().size()); AutofillProfile profile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile, "Marion", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); personal_data_->AddProfile(profile); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); ASSERT_EQ(1U, personal_data_->GetProfiles().size()); } // Helper method that will add credit card fields in |form|, according to the // specified values. If a value is nullptr, the corresponding field won't get // added (empty string will add a field with an empty string as the value). void AddFullCreditCardForm(FormData* form, const char* name, const char* number, const char* month, const char* year) { FormFieldData field; if (name) { test::CreateTestFormField("Name on card:", "name_on_card", name, "text", &field); form->fields.push_back(field); } if (number) { test::CreateTestFormField("Card Number:", "card_number", number, "text", &field); form->fields.push_back(field); } if (month) { test::CreateTestFormField("Exp Month:", "exp_month", month, "text", &field); form->fields.push_back(field); } if (year) { test::CreateTestFormField("Exp Year:", "exp_year", year, "text", &field); form->fields.push_back(field); } } // Adds three local cards to the |personal_data_|. The three cards are // different: two are from different companies and the third doesn't have a // number. All three have different owners and credit card number. This allows // to test the suggestions based on name as well as on credit card number. void SetupReferenceLocalCreditCards() { ASSERT_EQ(0U, personal_data_->GetCreditCards().size()); CreditCard credit_card0("287151C8-6AB1-487C-9095-28E80BE5DA15", "https://www.example.com"); test::SetCreditCardInfo(&credit_card0, "Clyde Barrow", "347666888555" /* American Express */, "04", "2999", "1"); credit_card0.set_use_count(3); credit_card0.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(1)); personal_data_->AddCreditCard(credit_card0); CreditCard credit_card1("1141084B-72D7-4B73-90CF-3D6AC154673B", "https://www.example.com"); credit_card1.set_use_count(300); credit_card1.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(10)); test::SetCreditCardInfo(&credit_card1, "John Dillinger", "423456789012" /* Visa */, "01", "2999", "1"); personal_data_->AddCreditCard(credit_card1); CreditCard credit_card2("002149C1-EE28-4213-A3B9-DA243FFF021B", "https://www.example.com"); credit_card2.set_use_count(1); credit_card2.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(1)); test::SetCreditCardInfo(&credit_card2, "Bonnie Parker", "518765432109" /* Mastercard */, "12", "2999", "1"); personal_data_->AddCreditCard(credit_card2); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); ASSERT_EQ(3U, personal_data_->GetCreditCards().size()); } // Helper methods that simply forward the call to the private member (to avoid // having to friend every test that needs to access the private // PersonalDataManager::ImportAddressProfile or ImportCreditCard). bool ImportAddressProfiles(const FormStructure& form) { return personal_data_->ImportAddressProfiles(form); } bool ImportCreditCard( const FormStructure& form, bool should_return_local_card, std::unique_ptr<CreditCard>* imported_credit_card, bool* imported_credit_card_matches_masked_server_credit_card) { return personal_data_->ImportCreditCard( form, should_return_local_card, imported_credit_card, imported_credit_card_matches_masked_server_credit_card); } void SubmitFormAndExpectImportedCardWithData(const FormData& form, const char* exp_name, const char* exp_cc_num, const char* exp_cc_month, const char* exp_cc_year) { FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_TRUE(ImportCreditCard( form_structure, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); ASSERT_TRUE(imported_credit_card); EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_->SaveImportedCreditCard(*imported_credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); CreditCard expected(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&expected, exp_name, exp_cc_num, exp_cc_month, exp_cc_year, ""); const std::vector<CreditCard*>& results = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(0, expected.Compare(*results[0])); } // The temporary directory should be deleted at the end to ensure that // files are not used anymore and deletion succeeds. base::ScopedTempDir temp_dir_; base::MessageLoopForUI message_loop_; std::unique_ptr<PrefService> prefs_; std::unique_ptr<AccountTrackerService> account_tracker_; std::unique_ptr<FakeSigninManagerBase> signin_manager_; std::unique_ptr<TestSigninClient> signin_client_; scoped_refptr<AutofillWebDataService> autofill_database_service_; scoped_refptr<WebDatabaseService> web_database_; AutofillTable* autofill_table_; // weak ref PersonalDataLoadedObserverMock personal_data_observer_; std::unique_ptr<PersonalDataManager> personal_data_; variations::testing::VariationParamsManager variation_params_; }; class PersonalDataManagerTest : public PersonalDataManagerTestBase, public testing::Test { void SetUp() override { OSCryptMocker::SetUpWithSingleton(); prefs_ = test::PrefServiceForTesting(); ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); base::FilePath path = temp_dir_.GetPath().AppendASCII("TestWebDB"); web_database_ = new WebDatabaseService(path, base::ThreadTaskRunnerHandle::Get(), base::ThreadTaskRunnerHandle::Get()); // Setup account tracker. signin_client_.reset(new TestSigninClient(prefs_.get())); account_tracker_.reset(new AccountTrackerService()); account_tracker_->Initialize(signin_client_.get()); signin_manager_.reset(new FakeSigninManagerBase(signin_client_.get(), account_tracker_.get())); signin_manager_->Initialize(prefs_.get()); // Hacky: hold onto a pointer but pass ownership. autofill_table_ = new AutofillTable; web_database_->AddTable(std::unique_ptr<WebDatabaseTable>(autofill_table_)); web_database_->LoadDatabase(); autofill_database_service_ = new AutofillWebDataService( web_database_, base::ThreadTaskRunnerHandle::Get(), base::ThreadTaskRunnerHandle::Get(), WebDataServiceBase::ProfileErrorCallback()); autofill_database_service_->Init(); test::DisableSystemServices(prefs_.get()); ResetPersonalDataManager(USER_MODE_NORMAL); // Reset the deduping pref to its default value. personal_data_->pref_service_->SetInteger( prefs::kAutofillLastVersionDeduped, 0); personal_data_->pref_service_->SetBoolean( prefs::kAutofillProfileUseDatesFixed, false); } void TearDown() override { // Order of destruction is important as AutofillManager relies on // PersonalDataManager to be around when it gets destroyed. signin_manager_->Shutdown(); signin_manager_.reset(); account_tracker_->Shutdown(); account_tracker_.reset(); signin_client_.reset(); test::DisableSystemServices(prefs_.get()); OSCryptMocker::TearDown(); } }; TEST_F(PersonalDataManagerTest, AddProfile) { // Add profile0 to the database. AutofillProfile profile0(test::GetFullProfile()); profile0.SetRawInfo(EMAIL_ADDRESS, base::ASCIIToUTF16("j@s.com")); personal_data_->AddProfile(profile0); // Reload the database. ResetPersonalDataManager(USER_MODE_NORMAL); // Verify the addition. const std::vector<AutofillProfile*>& results1 = personal_data_->GetProfiles(); ASSERT_EQ(1U, results1.size()); EXPECT_EQ(0, profile0.Compare(*results1[0])); // Add profile with identical values. Duplicates should not get saved. AutofillProfile profile0a = profile0; profile0a.set_guid(base::GenerateGUID()); personal_data_->AddProfile(profile0a); // Reload the database. ResetPersonalDataManager(USER_MODE_NORMAL); // Verify the non-addition. const std::vector<AutofillProfile*>& results2 = personal_data_->GetProfiles(); ASSERT_EQ(1U, results2.size()); EXPECT_EQ(0, profile0.Compare(*results2[0])); // New profile with different email. AutofillProfile profile1 = profile0; profile1.set_guid(base::GenerateGUID()); profile1.SetRawInfo(EMAIL_ADDRESS, base::ASCIIToUTF16("john@smith.com")); // Add the different profile. This should save as a separate profile. // Note that if this same profile was "merged" it would collapse to one // profile with a multi-valued entry for email. personal_data_->AddProfile(profile1); // Reload the database. ResetPersonalDataManager(USER_MODE_NORMAL); // Verify the addition. std::vector<AutofillProfile*> profiles; profiles.push_back(&profile0); profiles.push_back(&profile1); ExpectSameElements(profiles, personal_data_->GetProfiles()); } // Test that a new profile has its basic information set. TEST_F(PersonalDataManagerTest, AddProfile_BasicInformation) { // Create the test clock and set the time to a specific value. TestAutofillClock test_clock; test_clock.SetNow(kArbitraryTime); // Add a profile to the database. AutofillProfile profile(test::GetFullProfile()); profile.SetRawInfo(EMAIL_ADDRESS, base::ASCIIToUTF16("j@s.com")); personal_data_->AddProfile(profile); // Reload the database. ResetPersonalDataManager(USER_MODE_NORMAL); // Verify the addition. const std::vector<AutofillProfile*>& results = personal_data_->GetProfiles(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(0, profile.Compare(*results[0])); // Make sure the use count and use date were set. EXPECT_EQ(1U, results[0]->use_count()); EXPECT_EQ(kArbitraryTime, results[0]->use_date()); EXPECT_EQ(kArbitraryTime, results[0]->modification_date()); } // Tests that SaveImportedProfile sets the modification date on new profiles. TEST_F(PersonalDataManagerTest, SaveImportedProfileSetModificationDate) { AutofillProfile profile(test::GetFullProfile()); EXPECT_NE(base::Time(), profile.modification_date()); personal_data_->SaveImportedProfile(profile); const std::vector<AutofillProfile*>& profiles = personal_data_->GetProfiles(); ASSERT_EQ(1U, profiles.size()); EXPECT_GT(base::TimeDelta::FromMilliseconds(500), AutofillClock::Now() - profiles[0]->modification_date()); } TEST_F(PersonalDataManagerTest, AddUpdateRemoveProfiles) { AutofillProfile profile0(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile0, "Marion", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St.", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); AutofillProfile profile1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile1, "Josephine", "Alicia", "Saenz", "joewayne@me.xyz", "Fox", "903 Apple Ct.", NULL, "Orlando", "FL", "32801", "US", "19482937549"); AutofillProfile profile2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile2, "Josephine", "Alicia", "Saenz", "joewayne@me.xyz", "Fox", "1212 Center.", "Bld. 5", "Orlando", "FL", "32801", "US", "19482937549"); // Add two test profiles to the database. personal_data_->AddProfile(profile0); personal_data_->AddProfile(profile1); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); std::vector<AutofillProfile*> profiles; profiles.push_back(&profile0); profiles.push_back(&profile1); ExpectSameElements(profiles, personal_data_->GetProfiles()); // Update, remove, and add. profile0.SetRawInfo(NAME_FIRST, base::ASCIIToUTF16("John")); personal_data_->UpdateProfile(profile0); personal_data_->RemoveByGUID(profile1.guid()); personal_data_->AddProfile(profile2); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); profiles.clear(); profiles.push_back(&profile0); profiles.push_back(&profile2); ExpectSameElements(profiles, personal_data_->GetProfiles()); // Reset the PersonalDataManager. This tests that the personal data was saved // to the web database, and that we can load the profiles from the web // database. ResetPersonalDataManager(USER_MODE_NORMAL); // Verify that we've loaded the profiles from the web database. ExpectSameElements(profiles, personal_data_->GetProfiles()); } TEST_F(PersonalDataManagerTest, AddUpdateRemoveCreditCards) { EnableWalletCardImport(); CreditCard credit_card0(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&credit_card0, "John Dillinger", "423456789012" /* Visa */, "01", "2999", "1"); CreditCard credit_card1(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&credit_card1, "Bonnie Parker", "518765432109" /* Mastercard */, "12", "2999", "1"); CreditCard credit_card2(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&credit_card2, "Clyde Barrow", "347666888555" /* American Express */, "04", "2999", "1"); // Add two test credit cards to the database. personal_data_->AddCreditCard(credit_card0); personal_data_->AddCreditCard(credit_card1); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); std::vector<CreditCard*> cards; cards.push_back(&credit_card0); cards.push_back(&credit_card1); ExpectSameElements(cards, personal_data_->GetCreditCards()); // Update, remove, and add. credit_card0.SetRawInfo(CREDIT_CARD_NAME_FULL, base::ASCIIToUTF16("Joe")); personal_data_->UpdateCreditCard(credit_card0); personal_data_->RemoveByGUID(credit_card1.guid()); personal_data_->AddCreditCard(credit_card2); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); cards.clear(); cards.push_back(&credit_card0); cards.push_back(&credit_card2); ExpectSameElements(cards, personal_data_->GetCreditCards()); // Reset the PersonalDataManager. This tests that the personal data was saved // to the web database, and that we can load the credit cards from the web // database. ResetPersonalDataManager(USER_MODE_NORMAL); // Verify that we've loaded the credit cards from the web database. cards.clear(); cards.push_back(&credit_card0); cards.push_back(&credit_card2); ExpectSameElements(cards, personal_data_->GetCreditCards()); // Add a full server card. CreditCard credit_card3(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&credit_card3, "Jane Doe", "4111111111111111" /* Visa */, "04", "2999", "1"); credit_card3.set_record_type(CreditCard::FULL_SERVER_CARD); credit_card3.set_server_id("server_id"); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); personal_data_->AddFullServerCreditCard(credit_card3); base::RunLoop().Run(); cards.push_back(&credit_card3); ExpectSameElements(cards, personal_data_->GetCreditCards()); // Must not add a duplicate server card with same GUID. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()).Times(0); personal_data_->AddFullServerCreditCard(credit_card3); ExpectSameElements(cards, personal_data_->GetCreditCards()); // Must not add a duplicate card with same contents as another server card. CreditCard duplicate_server_card(credit_card3); duplicate_server_card.set_guid(base::GenerateGUID()); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()).Times(0); personal_data_->AddFullServerCreditCard(duplicate_server_card); ExpectSameElements(cards, personal_data_->GetCreditCards()); } // Test that a new credit card has its basic information set. TEST_F(PersonalDataManagerTest, AddCreditCard_BasicInformation) { // Create the test clock and set the time to a specific value. TestAutofillClock test_clock; test_clock.SetNow(kArbitraryTime); // Add a credit card to the database. CreditCard credit_card(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&credit_card, "John Dillinger", "423456789012" /* Visa */, "01", "2999", "1"); personal_data_->AddCreditCard(credit_card); // Reload the database. ResetPersonalDataManager(USER_MODE_NORMAL); // Verify the addition. const std::vector<CreditCard*>& results = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(0, credit_card.Compare(*results[0])); // Make sure the use count and use date were set. EXPECT_EQ(1U, results[0]->use_count()); EXPECT_EQ(kArbitraryTime, results[0]->use_date()); EXPECT_EQ(kArbitraryTime, results[0]->modification_date()); } TEST_F(PersonalDataManagerTest, UpdateUnverifiedProfilesAndCreditCards) { // Start with unverified data. AutofillProfile profile(base::GenerateGUID(), "https://www.example.com/"); test::SetProfileInfo(&profile, "Marion", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St.", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); EXPECT_FALSE(profile.IsVerified()); CreditCard credit_card(base::GenerateGUID(), "https://www.example.com/"); test::SetCreditCardInfo(&credit_card, "John Dillinger", "423456789012" /* Visa */, "01", "2999", "1"); EXPECT_FALSE(credit_card.IsVerified()); // Add the data to the database. personal_data_->AddProfile(profile); personal_data_->AddCreditCard(credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); const std::vector<AutofillProfile*>& profiles1 = personal_data_->GetProfiles(); const std::vector<CreditCard*>& cards1 = personal_data_->GetCreditCards(); ASSERT_EQ(1U, profiles1.size()); ASSERT_EQ(1U, cards1.size()); EXPECT_EQ(0, profile.Compare(*profiles1[0])); EXPECT_EQ(0, credit_card.Compare(*cards1[0])); // Try to update with just the origin changed. AutofillProfile original_profile(profile); CreditCard original_credit_card(credit_card); profile.set_origin(kSettingsOrigin); credit_card.set_origin(kSettingsOrigin); EXPECT_TRUE(profile.IsVerified()); EXPECT_TRUE(credit_card.IsVerified()); personal_data_->UpdateProfile(profile); personal_data_->UpdateCreditCard(credit_card); // Note: No refresh, as no update is expected. const std::vector<AutofillProfile*>& profiles2 = personal_data_->GetProfiles(); const std::vector<CreditCard*>& cards2 = personal_data_->GetCreditCards(); ASSERT_EQ(1U, profiles2.size()); ASSERT_EQ(1U, cards2.size()); EXPECT_NE(profile.origin(), profiles2[0]->origin()); EXPECT_NE(credit_card.origin(), cards2[0]->origin()); EXPECT_EQ(original_profile.origin(), profiles2[0]->origin()); EXPECT_EQ(original_credit_card.origin(), cards2[0]->origin()); // Try to update with data changed as well. profile.SetRawInfo(NAME_FIRST, base::ASCIIToUTF16("John")); credit_card.SetRawInfo(CREDIT_CARD_NAME_FULL, base::ASCIIToUTF16("Joe")); personal_data_->UpdateProfile(profile); personal_data_->UpdateCreditCard(credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); const std::vector<AutofillProfile*>& profiles3 = personal_data_->GetProfiles(); const std::vector<CreditCard*>& cards3 = personal_data_->GetCreditCards(); ASSERT_EQ(1U, profiles3.size()); ASSERT_EQ(1U, cards3.size()); EXPECT_EQ(0, profile.Compare(*profiles3[0])); EXPECT_EQ(0, credit_card.Compare(*cards3[0])); EXPECT_EQ(profile.origin(), profiles3[0]->origin()); EXPECT_EQ(credit_card.origin(), cards3[0]->origin()); } // Makes sure that full cards are re-masked when full PAN storage is off. TEST_F(PersonalDataManagerTest, RefuseToStoreFullCard) { // On Linux this should be disabled automatically. Elsewhere, only if the // flag is passed. #if defined(OS_LINUX) && !defined(OS_CHROMEOS) EXPECT_FALSE(base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableOfferStoreUnmaskedWalletCards)); #else base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kDisableOfferStoreUnmaskedWalletCards); #endif std::vector<CreditCard> server_cards; server_cards.push_back(CreditCard(CreditCard::FULL_SERVER_CARD, "c789")); test::SetCreditCardInfo(&server_cards.back(), "Clyde Barrow", "347666888555" /* American Express */, "04", "2999", "1"); test::SetServerCreditCards(autofill_table_, server_cards); personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); ASSERT_EQ(1U, personal_data_->GetCreditCards().size()); EXPECT_EQ(CreditCard::MASKED_SERVER_CARD, personal_data_->GetCreditCards()[0]->record_type()); } // Makes sure that full cards are only added as masked card when full PAN // storage is disabled. TEST_F(PersonalDataManagerTest, AddFullCardAsMaskedCard) { // On Linux this should be disabled automatically. Elsewhere, only if the // flag is passed. #if defined(OS_LINUX) && !defined(OS_CHROMEOS) EXPECT_FALSE(base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableOfferStoreUnmaskedWalletCards)); #else base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kDisableOfferStoreUnmaskedWalletCards); #endif CreditCard server_card(CreditCard::FULL_SERVER_CARD, "c789"); test::SetCreditCardInfo(&server_card, "Clyde Barrow", "347666888555" /* American Express */, "04", "2999", "1"); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); personal_data_->AddFullServerCreditCard(server_card); base::RunLoop().Run(); ASSERT_EQ(1U, personal_data_->GetCreditCards().size()); EXPECT_EQ(CreditCard::MASKED_SERVER_CARD, personal_data_->GetCreditCards()[0]->record_type()); } TEST_F(PersonalDataManagerTest, OfferStoreUnmaskedCards) { #if defined(OS_CHROMEOS) || defined(OS_WIN) || defined(OS_MACOSX) || \ defined(OS_IOS) || defined(OS_ANDROID) bool should_offer = true; #elif defined(OS_LINUX) bool should_offer = false; #endif EXPECT_EQ(should_offer, OfferStoreUnmaskedCards()); } // Tests that UpdateServerCreditCard can be used to mask or unmask server cards. TEST_F(PersonalDataManagerTest, UpdateServerCreditCards) { EnableWalletCardImport(); std::vector<CreditCard> server_cards; server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "a123")); test::SetCreditCardInfo(&server_cards.back(), "John Dillinger", "9012" /* Visa */, "01", "2999", "1"); server_cards.back().SetNetworkForMaskedCard(kVisaCard); server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "b456")); test::SetCreditCardInfo(&server_cards.back(), "Bonnie Parker", "2109" /* Mastercard */, "12", "2999", "1"); server_cards.back().SetNetworkForMaskedCard(kMasterCard); server_cards.push_back(CreditCard(CreditCard::FULL_SERVER_CARD, "c789")); test::SetCreditCardInfo(&server_cards.back(), "Clyde Barrow", "347666888555" /* American Express */, "04", "2999", "1"); test::SetServerCreditCards(autofill_table_, server_cards); personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); ASSERT_EQ(3U, personal_data_->GetCreditCards().size()); if (!OfferStoreUnmaskedCards()) { for (CreditCard* card : personal_data_->GetCreditCards()) { EXPECT_EQ(CreditCard::MASKED_SERVER_CARD, card->record_type()); } // The rest of this test doesn't work if we're force-masking all unmasked // cards. return; } // The GUIDs will be different, so just compare the data. for (size_t i = 0; i < 3; ++i) EXPECT_EQ(0, server_cards[i].Compare(*personal_data_->GetCreditCards()[i])); CreditCard* unmasked_card = &server_cards.front(); unmasked_card->set_record_type(CreditCard::FULL_SERVER_CARD); unmasked_card->SetNumber(base::ASCIIToUTF16("423456789012")); EXPECT_NE(0, server_cards.front().Compare( *personal_data_->GetCreditCards().front())); personal_data_->UpdateServerCreditCard(*unmasked_card); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); for (size_t i = 0; i < 3; ++i) EXPECT_EQ(0, server_cards[i].Compare(*personal_data_->GetCreditCards()[i])); CreditCard* remasked_card = &server_cards.back(); remasked_card->set_record_type(CreditCard::MASKED_SERVER_CARD); remasked_card->SetNumber(base::ASCIIToUTF16("8555")); EXPECT_NE( 0, server_cards.back().Compare(*personal_data_->GetCreditCards().back())); personal_data_->UpdateServerCreditCard(*remasked_card); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); for (size_t i = 0; i < 3; ++i) EXPECT_EQ(0, server_cards[i].Compare(*personal_data_->GetCreditCards()[i])); } TEST_F(PersonalDataManagerTest, SavesServerCardType) { EnableWalletCardImport(); std::vector<CreditCard> server_cards; server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "a123")); test::SetCreditCardInfo(&server_cards.back(), "John Dillinger", "9012" /* Visa */, "01", "2999", "1"); server_cards.back().SetNetworkForMaskedCard(kVisaCard); server_cards.back().set_card_type(CreditCard::CARD_TYPE_DEBIT); test::SetServerCreditCards(autofill_table_, server_cards); personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); auto cards = personal_data_->GetCreditCards(); ASSERT_EQ(1U, cards.size()); EXPECT_EQ(CreditCard::CARD_TYPE_DEBIT, cards.front()->card_type()); } TEST_F(PersonalDataManagerTest, AddProfilesAndCreditCards) { AutofillProfile profile0(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile0, "Marion", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St.", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); AutofillProfile profile1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile1, "Josephine", "Alicia", "Saenz", "joewayne@me.xyz", "Fox", "903 Apple Ct.", NULL, "Orlando", "FL", "32801", "US", "19482937549"); CreditCard credit_card0(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&credit_card0, "John Dillinger", "423456789012" /* Visa */, "01", "2999", "1"); CreditCard credit_card1(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&credit_card1, "Bonnie Parker", "518765432109" /* Mastercard */, "12", "2999", "1"); // Add two test profiles to the database. personal_data_->AddProfile(profile0); personal_data_->AddProfile(profile1); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); std::vector<AutofillProfile*> profiles; profiles.push_back(&profile0); profiles.push_back(&profile1); ExpectSameElements(profiles, personal_data_->GetProfiles()); // Add two test credit cards to the database. personal_data_->AddCreditCard(credit_card0); personal_data_->AddCreditCard(credit_card1); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); std::vector<CreditCard*> cards; cards.push_back(&credit_card0); cards.push_back(&credit_card1); ExpectSameElements(cards, personal_data_->GetCreditCards()); // Determine uniqueness by inserting all of the GUIDs into a set and verifying // the size of the set matches the number of GUIDs. std::set<std::string> guids; guids.insert(profile0.guid()); guids.insert(profile1.guid()); guids.insert(credit_card0.guid()); guids.insert(credit_card1.guid()); EXPECT_EQ(4U, guids.size()); } // Test for http://crbug.com/50047. Makes sure that guids are populated // correctly on load. TEST_F(PersonalDataManagerTest, PopulateUniqueIDsOnLoad) { AutofillProfile profile0(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile0, "y", "", "", "", "", "", "", "", "", "", "", ""); // Add the profile0 to the db. personal_data_->AddProfile(profile0); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Verify that we've loaded the profiles from the web database. const std::vector<AutofillProfile*>& results2 = personal_data_->GetProfiles(); ASSERT_EQ(1U, results2.size()); EXPECT_EQ(0, profile0.Compare(*results2[0])); // Add a new profile. AutofillProfile profile1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile1, "z", "", "", "", "", "", "", "", "", "", "", ""); personal_data_->AddProfile(profile1); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Make sure the two profiles have different GUIDs, both valid. const std::vector<AutofillProfile*>& results3 = personal_data_->GetProfiles(); ASSERT_EQ(2U, results3.size()); EXPECT_NE(results3[0]->guid(), results3[1]->guid()); EXPECT_TRUE(base::IsValidGUID(results3[0]->guid())); EXPECT_TRUE(base::IsValidGUID(results3[1]->guid())); } TEST_F(PersonalDataManagerTest, SetUniqueCreditCardLabels) { CreditCard credit_card0(base::GenerateGUID(), "https://www.example.com"); credit_card0.SetRawInfo(CREDIT_CARD_NAME_FULL, base::ASCIIToUTF16("John")); CreditCard credit_card1(base::GenerateGUID(), "https://www.example.com"); credit_card1.SetRawInfo(CREDIT_CARD_NAME_FULL, base::ASCIIToUTF16("Paul")); CreditCard credit_card2(base::GenerateGUID(), "https://www.example.com"); credit_card2.SetRawInfo(CREDIT_CARD_NAME_FULL, base::ASCIIToUTF16("Ringo")); CreditCard credit_card3(base::GenerateGUID(), "https://www.example.com"); credit_card3.SetRawInfo(CREDIT_CARD_NAME_FULL, base::ASCIIToUTF16("Other")); CreditCard credit_card4(base::GenerateGUID(), "https://www.example.com"); credit_card4.SetRawInfo(CREDIT_CARD_NAME_FULL, base::ASCIIToUTF16("Ozzy")); CreditCard credit_card5(base::GenerateGUID(), "https://www.example.com"); credit_card5.SetRawInfo(CREDIT_CARD_NAME_FULL, base::ASCIIToUTF16("Dio")); // Add the test credit cards to the database. personal_data_->AddCreditCard(credit_card0); personal_data_->AddCreditCard(credit_card1); personal_data_->AddCreditCard(credit_card2); personal_data_->AddCreditCard(credit_card3); personal_data_->AddCreditCard(credit_card4); personal_data_->AddCreditCard(credit_card5); // Reset the PersonalDataManager. This tests that the personal data was saved // to the web database, and that we can load the credit cards from the web // database. ResetPersonalDataManager(USER_MODE_NORMAL); std::vector<CreditCard*> cards; cards.push_back(&credit_card0); cards.push_back(&credit_card1); cards.push_back(&credit_card2); cards.push_back(&credit_card3); cards.push_back(&credit_card4); cards.push_back(&credit_card5); ExpectSameElements(cards, personal_data_->GetCreditCards()); } TEST_F(PersonalDataManagerTest, SetEmptyProfile) { AutofillProfile profile0(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile0, "", "", "", "", "", "", "", "", "", "", "", ""); // Add the empty profile to the database. personal_data_->AddProfile(profile0); // Note: no refresh here. // Reset the PersonalDataManager. This tests that the personal data was saved // to the web database, and that we can load the profiles from the web // database. ResetPersonalDataManager(USER_MODE_NORMAL); // Verify that we've loaded the profiles from the web database. const std::vector<AutofillProfile*>& results2 = personal_data_->GetProfiles(); ASSERT_EQ(0U, results2.size()); } TEST_F(PersonalDataManagerTest, SetEmptyCreditCard) { CreditCard credit_card0(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&credit_card0, "", "", "", "", ""); // Add the empty credit card to the database. personal_data_->AddCreditCard(credit_card0); // Note: no refresh here. // Reset the PersonalDataManager. This tests that the personal data was saved // to the web database, and that we can load the credit cards from the web // database. ResetPersonalDataManager(USER_MODE_NORMAL); // Verify that we've loaded the credit cards from the web database. const std::vector<CreditCard*>& results2 = personal_data_->GetCreditCards(); ASSERT_EQ(0U, results2.size()); } TEST_F(PersonalDataManagerTest, Refresh) { AutofillProfile profile0(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile0, "Marion", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St.", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); AutofillProfile profile1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile1, "Josephine", "Alicia", "Saenz", "joewayne@me.xyz", "Fox", "903 Apple Ct.", NULL, "Orlando", "FL", "32801", "US", "19482937549"); // Add the test profiles to the database. personal_data_->AddProfile(profile0); personal_data_->AddProfile(profile1); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); std::vector<AutofillProfile*> profiles; profiles.push_back(&profile0); profiles.push_back(&profile1); ExpectSameElements(profiles, personal_data_->GetProfiles()); AutofillProfile profile2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile2, "Josephine", "Alicia", "Saenz", "joewayne@me.xyz", "Fox", "1212 Center.", "Bld. 5", "Orlando", "FL", "32801", "US", "19482937549"); autofill_database_service_->AddAutofillProfile(profile2); personal_data_->Refresh(); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); profiles.clear(); profiles.push_back(&profile0); profiles.push_back(&profile1); profiles.push_back(&profile2); ExpectSameElements(profiles, personal_data_->GetProfiles()); autofill_database_service_->RemoveAutofillProfile(profile1.guid()); autofill_database_service_->RemoveAutofillProfile(profile2.guid()); // Before telling the PDM to refresh, simulate an edit to one of the deleted // profiles via a SetProfile update (this would happen if the Autofill window // was open with a previous snapshot of the profiles, and something // [e.g. sync] removed a profile from the browser. In this edge case, we will // end up in a consistent state by dropping the write). profile0.SetRawInfo(NAME_FIRST, base::ASCIIToUTF16("Mar")); profile2.SetRawInfo(NAME_FIRST, base::ASCIIToUTF16("Jo")); personal_data_->UpdateProfile(profile0); personal_data_->AddProfile(profile1); personal_data_->AddProfile(profile2); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); const std::vector<AutofillProfile*>& results = personal_data_->GetProfiles(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(profile0, *results[0]); } // ImportAddressProfiles tests. TEST_F(PersonalDataManagerTest, ImportAddressProfiles) { FormData form; FormFieldData field; test::CreateTestFormField( "First name:", "first_name", "George", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Last name:", "last_name", "Washington", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Email:", "email", "theprez@gmail.com", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Address:", "address1", "21 Laussat St", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form.fields.push_back(field); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure)); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); AutofillProfile expected(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&expected, "George", NULL, "Washington", "theprez@gmail.com", NULL, "21 Laussat St", NULL, "San Francisco", "California", "94102", NULL, NULL); const std::vector<AutofillProfile*>& results = personal_data_->GetProfiles(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(0, expected.Compare(*results[0])); } TEST_F(PersonalDataManagerTest, ImportAddressProfiles_BadEmail) { FormData form; FormFieldData field; test::CreateTestFormField( "First name:", "first_name", "George", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Last name:", "last_name", "Washington", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Email:", "email", "bogus", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Address:", "address1", "21 Laussat St", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form.fields.push_back(field); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_FALSE(ImportAddressProfiles(form_structure)); const std::vector<AutofillProfile*>& results = personal_data_->GetProfiles(); ASSERT_EQ(0U, results.size()); } // Tests that a 'confirm email' field does not block profile import. TEST_F(PersonalDataManagerTest, ImportAddressProfiles_TwoEmails) { FormData form; FormFieldData field; test::CreateTestFormField( "Name:", "name", "George Washington", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Address:", "address1", "21 Laussat St", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Email:", "email", "example@example.com", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Confirm email:", "confirm_email", "example@example.com", "text", &field); form.fields.push_back(field); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure)); const std::vector<AutofillProfile*>& results = personal_data_->GetProfiles(); ASSERT_EQ(1U, results.size()); } // Tests two email fields containing different values blocks profile import. TEST_F(PersonalDataManagerTest, ImportAddressProfiles_TwoDifferentEmails) { FormData form; FormFieldData field; test::CreateTestFormField( "Name:", "name", "George Washington", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Address:", "address1", "21 Laussat St", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Email:", "email", "example@example.com", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Email:", "email2", "example2@example.com", "text", &field); form.fields.push_back(field); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_FALSE(ImportAddressProfiles(form_structure)); const std::vector<AutofillProfile*>& results = personal_data_->GetProfiles(); ASSERT_EQ(0U, results.size()); } // Tests that not enough filled fields will result in not importing an address. TEST_F(PersonalDataManagerTest, ImportAddressProfiles_NotEnoughFilledFields) { FormData form; FormFieldData field; test::CreateTestFormField( "First name:", "first_name", "George", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Last name:", "last_name", "Washington", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Card number:", "card_number", "4111 1111 1111 1111", "text", &field); form.fields.push_back(field); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_FALSE(ImportAddressProfiles(form_structure)); const std::vector<AutofillProfile*>& profiles = personal_data_->GetProfiles(); ASSERT_EQ(0U, profiles.size()); const std::vector<CreditCard*>& cards = personal_data_->GetCreditCards(); ASSERT_EQ(0U, cards.size()); } TEST_F(PersonalDataManagerTest, ImportAddressProfiles_MinimumAddressUSA) { // United States addresses must specifiy one address line, a city, state and // zip code. FormData form; FormFieldData field; test::CreateTestFormField("Name:", "name", "Barack Obama", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Address:", "address", "1600 Pennsylvania Avenue", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "Washington", "text", &field); form.fields.push_back(field); test::CreateTestFormField("State:", "state", "DC", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "20500", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Country:", "country", "USA", "text", &field); form.fields.push_back(field); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure)); const std::vector<AutofillProfile*>& profiles = personal_data_->GetProfiles(); ASSERT_EQ(1U, profiles.size()); } TEST_F(PersonalDataManagerTest, ImportAddressProfiles_MinimumAddressGB) { // British addresses do not require a state/province as the county is usually // not requested on forms. FormData form; FormFieldData field; test::CreateTestFormField("Name:", "name", "David Cameron", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Address:", "address", "10 Downing Street", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "London", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Postcode:", "postcode", "SW1A 2AA", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Country:", "country", "United Kingdom", "text", &field); form.fields.push_back(field); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure)); const std::vector<AutofillProfile*>& profiles = personal_data_->GetProfiles(); ASSERT_EQ(1U, profiles.size()); } TEST_F(PersonalDataManagerTest, ImportAddressProfiles_MinimumAddressGI) { // Gibraltar has the most minimal set of requirements for a valid address. // There are no cities or provinces and no postal/zip code system. FormData form; FormFieldData field; test::CreateTestFormField( "Name:", "name", "Sir Adrian Johns", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Address:", "address", "The Convent, Main Street", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Country:", "country", "Gibraltar", "text", &field); form.fields.push_back(field); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure)); const std::vector<AutofillProfile*>& profiles = personal_data_->GetProfiles(); ASSERT_EQ(1U, profiles.size()); } TEST_F(PersonalDataManagerTest, ImportAddressProfiles_PhoneNumberSplitAcrossMultipleFields) { FormData form; FormFieldData field; test::CreateTestFormField( "First name:", "first_name", "George", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Last name:", "last_name", "Washington", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Phone #:", "home_phone_area_code", "650", "text", &field); field.max_length = 3; form.fields.push_back(field); test::CreateTestFormField( "Phone #:", "home_phone_prefix", "555", "text", &field); field.max_length = 3; form.fields.push_back(field); test::CreateTestFormField( "Phone #:", "home_phone_suffix", "0000", "text", &field); field.max_length = 4; form.fields.push_back(field); test::CreateTestFormField( "Address:", "address1", "21 Laussat St", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form.fields.push_back(field); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure)); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); AutofillProfile expected(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&expected, "George", NULL, "Washington", NULL, NULL, "21 Laussat St", NULL, "San Francisco", "California", "94102", NULL, "(650) 555-0000"); const std::vector<AutofillProfile*>& results = personal_data_->GetProfiles(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(0, expected.Compare(*results[0])); } TEST_F(PersonalDataManagerTest, ImportAddressProfiles_MultilineAddress) { FormData form; FormFieldData field; test::CreateTestFormField( "First name:", "first_name", "George", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Last name:", "last_name", "Washington", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Email:", "email", "theprez@gmail.com", "text", &field); form.fields.push_back(field); test::CreateTestFormField( "Address:", "street_address", "21 Laussat St\n" "Apt. #42", "textarea", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form.fields.push_back(field); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure)); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); AutofillProfile expected(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&expected, "George", NULL, "Washington", "theprez@gmail.com", NULL, "21 Laussat St", "Apt. #42", "San Francisco", "California", "94102", NULL, NULL); const std::vector<AutofillProfile*>& results = personal_data_->GetProfiles(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(0, expected.Compare(*results[0])); } TEST_F(PersonalDataManagerTest, ImportAddressProfiles_TwoValidProfilesDifferentForms) { FormData form1; FormFieldData field; test::CreateTestFormField( "First name:", "first_name", "George", "text", &field); form1.fields.push_back(field); test::CreateTestFormField( "Last name:", "last_name", "Washington", "text", &field); form1.fields.push_back(field); test::CreateTestFormField( "Email:", "email", "theprez@gmail.com", "text", &field); form1.fields.push_back(field); test::CreateTestFormField( "Address:", "address1", "21 Laussat St", "text", &field); form1.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form1.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form1.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form1.fields.push_back(field); FormStructure form_structure1(form1); form_structure1.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure1)); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); AutofillProfile expected(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&expected, "George", NULL, "Washington", "theprez@gmail.com", NULL, "21 Laussat St", NULL, "San Francisco", "California", "94102", NULL, NULL); const std::vector<AutofillProfile*>& results1 = personal_data_->GetProfiles(); ASSERT_EQ(1U, results1.size()); EXPECT_EQ(0, expected.Compare(*results1[0])); // Now create a completely different profile. FormData form2; test::CreateTestFormField( "First name:", "first_name", "John", "text", &field); form2.fields.push_back(field); test::CreateTestFormField( "Last name:", "last_name", "Adams", "text", &field); form2.fields.push_back(field); test::CreateTestFormField( "Email:", "email", "second@gmail.com", "text", &field); form2.fields.push_back(field); test::CreateTestFormField( "Address:", "address1", "22 Laussat St", "text", &field); form2.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form2.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form2.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form2.fields.push_back(field); FormStructure form_structure2(form2); form_structure2.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure2)); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); AutofillProfile expected2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&expected2, "John", NULL, "Adams", "second@gmail.com", NULL, "22 Laussat St", NULL, "San Francisco", "California", "94102", NULL, NULL); std::vector<AutofillProfile*> profiles; profiles.push_back(&expected); profiles.push_back(&expected2); ExpectSameElements(profiles, personal_data_->GetProfiles()); } TEST_F(PersonalDataManagerTest, ImportAddressProfiles_TwoValidProfilesSameForm) { FormData form; FormFieldData field; test::CreateTestFormField("First name:", "first_name", "George", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Last name:", "last_name", "Washington", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Email:", "email", "theprez@gmail.com", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Address:", "address1", "21 Laussat St", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form.fields.push_back(field); // Different address. test::CreateTestFormField("First name:", "first_name", "John", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Last name:", "last_name", "Adams", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Email:", "email", "second@gmail.com", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Address:", "address1", "22 Laussat St", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form.fields.push_back(field); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure)); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); AutofillProfile expected(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&expected, "George", NULL, "Washington", "theprez@gmail.com", NULL, "21 Laussat St", NULL, "San Francisco", "California", "94102", NULL, NULL); AutofillProfile expected2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&expected2, "John", NULL, "Adams", "second@gmail.com", NULL, "22 Laussat St", NULL, "San Francisco", "California", "94102", NULL, NULL); const std::vector<AutofillProfile*>& results = personal_data_->GetProfiles(); ASSERT_EQ(2U, results.size()); std::vector<AutofillProfile*> profiles; profiles.push_back(&expected); profiles.push_back(&expected2); ExpectSameElements(profiles, personal_data_->GetProfiles()); } TEST_F(PersonalDataManagerTest, ImportAddressProfiles_OneValidProfileSameForm_PartsHidden) { FormData form; FormFieldData field; test::CreateTestFormField("First name:", "first_name", "George", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Last name:", "last_name", "Washington", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Email:", "email", "theprez@gmail.com", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Address:", "address1", "21 Laussat St", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form.fields.push_back(field); // There is an empty but hidden form section (this has been observed on sites // where users can choose which form section they choose by unhiding it). test::CreateTestFormField("First name:", "first_name", "", "text", &field); field.is_focusable = false; form.fields.push_back(field); test::CreateTestFormField("Last name:", "last_name", "", "text", &field); field.is_focusable = false; form.fields.push_back(field); test::CreateTestFormField("Email:", "email", "", "text", &field); field.is_focusable = false; form.fields.push_back(field); test::CreateTestFormField("Address:", "address1", "", "text", &field); field.is_focusable = false; form.fields.push_back(field); test::CreateTestFormField("City:", "city", "", "text", &field); field.is_focusable = false; form.fields.push_back(field); test::CreateTestFormField("State:", "state", "", "text", &field); field.is_focusable = false; form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "", "text", &field); field.is_focusable = false; form.fields.push_back(field); // Still able to do the import. FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure)); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); AutofillProfile expected(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&expected, "George", NULL, "Washington", "theprez@gmail.com", NULL, "21 Laussat St", NULL, "San Francisco", "California", "94102", NULL, NULL); const std::vector<AutofillProfile*>& results = personal_data_->GetProfiles(); ASSERT_EQ(1U, results.size()); std::vector<AutofillProfile*> profiles; profiles.push_back(&expected); ExpectSameElements(profiles, personal_data_->GetProfiles()); } // A maximum of two address profiles are imported per form. TEST_F(PersonalDataManagerTest, ImportAddressProfiles_ThreeValidProfilesSameForm) { FormData form; FormFieldData field; test::CreateTestFormField("First name:", "first_name", "George", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Last name:", "last_name", "Washington", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Email:", "email", "theprez@gmail.com", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Address:", "address1", "21 Laussat St", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form.fields.push_back(field); // Different address within the same form. test::CreateTestFormField("First name:", "first_name", "John", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Last name:", "last_name", "Adams", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Email:", "email", "second@gmail.com", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Address:", "address1", "22 Laussat St", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form.fields.push_back(field); // Yet another different address. test::CreateTestFormField("First name:", "first_name", "David", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Last name:", "last_name", "Cameron", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Address:", "address", "10 Downing Street", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "London", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Postcode:", "postcode", "SW1A 2AA", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Country:", "country", "United Kingdom", "text", &field); form.fields.push_back(field); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure)); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Only two are saved. AutofillProfile expected(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&expected, "George", NULL, "Washington", "theprez@gmail.com", NULL, "21 Laussat St", NULL, "San Francisco", "California", "94102", NULL, NULL); AutofillProfile expected2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&expected2, "John", NULL, "Adams", "second@gmail.com", NULL, "22 Laussat St", NULL, "San Francisco", "California", "94102", NULL, NULL); const std::vector<AutofillProfile*>& results = personal_data_->GetProfiles(); ASSERT_EQ(2U, results.size()); std::vector<AutofillProfile*> profiles; profiles.push_back(&expected); profiles.push_back(&expected2); ExpectSameElements(profiles, personal_data_->GetProfiles()); } TEST_F(PersonalDataManagerTest, ImportAddressProfiles_SameProfileWithConflict) { FormData form1; FormFieldData field; test::CreateTestFormField( "First name:", "first_name", "George", "text", &field); form1.fields.push_back(field); test::CreateTestFormField( "Last name:", "last_name", "Washington", "text", &field); form1.fields.push_back(field); test::CreateTestFormField( "Address:", "address", "1600 Pennsylvania Avenue", "text", &field); form1.fields.push_back(field); test::CreateTestFormField( "Address Line 2:", "address2", "Suite A", "text", &field); form1.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form1.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form1.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form1.fields.push_back(field); test::CreateTestFormField( "Email:", "email", "theprez@gmail.com", "text", &field); form1.fields.push_back(field); test::CreateTestFormField("Phone:", "phone", "6505556666", "text", &field); form1.fields.push_back(field); FormStructure form_structure1(form1); form_structure1.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure1)); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); AutofillProfile expected(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&expected, "George", nullptr, "Washington", "theprez@gmail.com", nullptr, "1600 Pennsylvania Avenue", "Suite A", "San Francisco", "California", "94102", nullptr, "(650) 555-6666"); const std::vector<AutofillProfile*>& results1 = personal_data_->GetProfiles(); ASSERT_EQ(1U, results1.size()); EXPECT_EQ(0, expected.Compare(*results1[0])); // Now create an updated profile. FormData form2; test::CreateTestFormField( "First name:", "first_name", "George", "text", &field); form2.fields.push_back(field); test::CreateTestFormField( "Last name:", "last_name", "Washington", "text", &field); form2.fields.push_back(field); test::CreateTestFormField( "Address:", "address", "1600 Pennsylvania Avenue", "text", &field); form2.fields.push_back(field); test::CreateTestFormField( "Address Line 2:", "address2", "Suite A", "text", &field); form2.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form2.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form2.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form2.fields.push_back(field); test::CreateTestFormField( "Email:", "email", "theprez@gmail.com", "text", &field); form2.fields.push_back(field); // Country gets added. test::CreateTestFormField("Country:", "country", "USA", "text", &field); form2.fields.push_back(field); // Same phone number with different formatting doesn't create a new profile. test::CreateTestFormField("Phone:", "phone", "650-555-6666", "text", &field); form2.fields.push_back(field); FormStructure form_structure2(form2); form_structure2.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure2)); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); const std::vector<AutofillProfile*>& results2 = personal_data_->GetProfiles(); // Full name, phone formatting and country are updated. expected.SetRawInfo(NAME_FULL, base::ASCIIToUTF16("George Washington")); expected.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, base::ASCIIToUTF16("+1 650-555-6666")); expected.SetRawInfo(ADDRESS_HOME_COUNTRY, base::ASCIIToUTF16("US")); ASSERT_EQ(1U, results2.size()); EXPECT_EQ(0, expected.Compare(*results2[0])); } TEST_F(PersonalDataManagerTest, ImportAddressProfiles_MissingInfoInOld) { FormData form1; FormFieldData field; test::CreateTestFormField( "First name:", "first_name", "George", "text", &field); form1.fields.push_back(field); test::CreateTestFormField( "Last name:", "last_name", "Washington", "text", &field); form1.fields.push_back(field); test::CreateTestFormField( "Address Line 1:", "address", "190 High Street", "text", &field); form1.fields.push_back(field); test::CreateTestFormField("City:", "city", "Philadelphia", "text", &field); form1.fields.push_back(field); test::CreateTestFormField("State:", "state", "Pennsylvania", "text", &field); form1.fields.push_back(field); test::CreateTestFormField("Zip:", "zipcode", "19106", "text", &field); form1.fields.push_back(field); FormStructure form_structure1(form1); form_structure1.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure1)); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); AutofillProfile expected(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&expected, "George", NULL, "Washington", NULL, NULL, "190 High Street", NULL, "Philadelphia", "Pennsylvania", "19106", NULL, NULL); const std::vector<AutofillProfile*>& results1 = personal_data_->GetProfiles(); ASSERT_EQ(1U, results1.size()); EXPECT_EQ(0, expected.Compare(*results1[0])); // Submit a form with new data for the first profile. FormData form2; test::CreateTestFormField( "First name:", "first_name", "George", "text", &field); form2.fields.push_back(field); test::CreateTestFormField( "Last name:", "last_name", "Washington", "text", &field); form2.fields.push_back(field); test::CreateTestFormField( "Email:", "email", "theprez@gmail.com", "text", &field); form2.fields.push_back(field); test::CreateTestFormField( "Address Line 1:", "address", "190 High Street", "text", &field); form2.fields.push_back(field); test::CreateTestFormField("City:", "city", "Philadelphia", "text", &field); form2.fields.push_back(field); test::CreateTestFormField("State:", "state", "Pennsylvania", "text", &field); form2.fields.push_back(field); test::CreateTestFormField("Zip:", "zipcode", "19106", "text", &field); form2.fields.push_back(field); FormStructure form_structure2(form2); form_structure2.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure2)); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); const std::vector<AutofillProfile*>& results2 = personal_data_->GetProfiles(); AutofillProfile expected2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&expected2, "George", NULL, "Washington", "theprez@gmail.com", NULL, "190 High Street", NULL, "Philadelphia", "Pennsylvania", "19106", NULL, NULL); expected2.SetRawInfo(NAME_FULL, base::ASCIIToUTF16("George Washington")); ASSERT_EQ(1U, results2.size()); EXPECT_EQ(0, expected2.Compare(*results2[0])); } TEST_F(PersonalDataManagerTest, ImportAddressProfiles_MissingInfoInNew) { FormData form1; FormFieldData field; test::CreateTestFormField( "First name:", "first_name", "George", "text", &field); form1.fields.push_back(field); test::CreateTestFormField( "Last name:", "last_name", "Washington", "text", &field); form1.fields.push_back(field); test::CreateTestFormField( "Company:", "company", "Government", "text", &field); form1.fields.push_back(field); test::CreateTestFormField( "Email:", "email", "theprez@gmail.com", "text", &field); form1.fields.push_back(field); test::CreateTestFormField( "Address Line 1:", "address", "190 High Street", "text", &field); form1.fields.push_back(field); test::CreateTestFormField("City:", "city", "Philadelphia", "text", &field); form1.fields.push_back(field); test::CreateTestFormField("State:", "state", "Pennsylvania", "text", &field); form1.fields.push_back(field); test::CreateTestFormField("Zip:", "zipcode", "19106", "text", &field); form1.fields.push_back(field); FormStructure form_structure1(form1); form_structure1.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure1)); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); AutofillProfile expected(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&expected, "George", NULL, "Washington", "theprez@gmail.com", "Government", "190 High Street", NULL, "Philadelphia", "Pennsylvania", "19106", NULL, NULL); const std::vector<AutofillProfile*>& results1 = personal_data_->GetProfiles(); ASSERT_EQ(1U, results1.size()); EXPECT_EQ(0, expected.Compare(*results1[0])); // Submit a form with new data for the first profile. FormData form2; test::CreateTestFormField( "First name:", "first_name", "George", "text", &field); form2.fields.push_back(field); test::CreateTestFormField( "Last name:", "last_name", "Washington", "text", &field); form2.fields.push_back(field); // Note missing Company field. test::CreateTestFormField( "Email:", "email", "theprez@gmail.com", "text", &field); form2.fields.push_back(field); test::CreateTestFormField( "Address Line 1:", "address", "190 High Street", "text", &field); form2.fields.push_back(field); test::CreateTestFormField("City:", "city", "Philadelphia", "text", &field); form2.fields.push_back(field); test::CreateTestFormField("State:", "state", "Pennsylvania", "text", &field); form2.fields.push_back(field); test::CreateTestFormField("Zip:", "zipcode", "19106", "text", &field); form2.fields.push_back(field); FormStructure form_structure2(form2); form_structure2.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure2)); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); const std::vector<AutofillProfile*>& results2 = personal_data_->GetProfiles(); // The merge operation will populate the full name if it's empty. expected.SetRawInfo(NAME_FULL, base::ASCIIToUTF16("George Washington")); ASSERT_EQ(1U, results2.size()); EXPECT_EQ(0, expected.Compare(*results2[0])); } TEST_F(PersonalDataManagerTest, ImportAddressProfiles_InsufficientAddress) { FormData form1; FormFieldData field; test::CreateTestFormField( "First name:", "first_name", "George", "text", &field); form1.fields.push_back(field); test::CreateTestFormField( "Last name:", "last_name", "Washington", "text", &field); form1.fields.push_back(field); test::CreateTestFormField( "Company:", "company", "Government", "text", &field); form1.fields.push_back(field); test::CreateTestFormField( "Email:", "email", "theprez@gmail.com", "text", &field); form1.fields.push_back(field); test::CreateTestFormField( "Address Line 1:", "address", "190 High Street", "text", &field); form1.fields.push_back(field); test::CreateTestFormField("City:", "city", "Philadelphia", "text", &field); form1.fields.push_back(field); FormStructure form_structure1(form1); form_structure1.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_FALSE(ImportAddressProfiles(form_structure1)); // Since no refresh is expected, reload the data from the database to make // sure no changes were written out. ResetPersonalDataManager(USER_MODE_NORMAL); const std::vector<AutofillProfile*>& profiles = personal_data_->GetProfiles(); ASSERT_EQ(0U, profiles.size()); const std::vector<CreditCard*>& cards = personal_data_->GetCreditCards(); ASSERT_EQ(0U, cards.size()); } // Ensure that if a verified profile already exists, aggregated profiles cannot // modify it in any way. This also checks the profile merging/matching algorithm // works: if either the full name OR all the non-empty name pieces match, the // profile is a match. TEST_F(PersonalDataManagerTest, ImportAddressProfiles_ExistingVerifiedProfileWithConflict) { // Start with a verified profile. AutofillProfile profile(base::GenerateGUID(), kSettingsOrigin); test::SetProfileInfo(&profile, "Marion", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St.", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); EXPECT_TRUE(profile.IsVerified()); // Add the profile to the database. personal_data_->AddProfile(profile); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Simulate a form submission with conflicting info. FormData form; FormFieldData field; test::CreateTestFormField("First name:", "first_name", "Marion Mitchell", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Last name:", "last_name", "Morrison", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Email:", "email", "johnwayne@me.xyz", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Address:", "address1", "123 Zoo St.", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "Hollywood", "text", &field); form.fields.push_back(field); test::CreateTestFormField("State:", "state", "CA", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "91601", "text", &field); form.fields.push_back(field); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure)); // Wait for the refresh, which in this case is a no-op. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Expect that no new profile is saved. const std::vector<AutofillProfile*>& results = personal_data_->GetProfiles(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(0, profile.Compare(*results[0])); // Try the same thing, but without "Mitchell". The profiles should still match // because the non empty name pieces (first and last) match that stored in the // profile. test::CreateTestFormField("First name:", "first_name", "Marion", "text", &field); form.fields[0] = field; FormStructure form_structure2(form); form_structure2.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure2)); // Wait for the refresh, which in this case is a no-op. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Expect that no new profile is saved. const std::vector<AutofillProfile*>& results2 = personal_data_->GetProfiles(); ASSERT_EQ(1U, results2.size()); EXPECT_EQ(0, profile.Compare(*results2[0])); } // Tests that no profile is inferred if the country is not recognized. TEST_F(PersonalDataManagerTest, ImportAddressProfiles_UnrecognizedCountry) { FormData form; FormFieldData field; test::CreateTestFormField("First name:", "first_name", "George", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Last name:", "last_name", "Washington", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Email:", "email", "theprez@gmail.com", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Address:", "address1", "21 Laussat St", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Country:", "country", "Notacountry", "text", &field); form.fields.push_back(field); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_FALSE(ImportAddressProfiles(form_structure)); // Since no refresh is expected, reload the data from the database to make // sure no changes were written out. ResetPersonalDataManager(USER_MODE_NORMAL); const std::vector<AutofillProfile*>& profiles = personal_data_->GetProfiles(); ASSERT_EQ(0U, profiles.size()); const std::vector<CreditCard*>& cards = personal_data_->GetCreditCards(); ASSERT_EQ(0U, cards.size()); } // Tests that a profile is created for countries with composed names. TEST_F(PersonalDataManagerTest, ImportAddressProfiles_CompleteComposedCountryName) { FormData form; FormFieldData field; test::CreateTestFormField("First name:", "first_name", "George", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Last name:", "last_name", "Washington", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Email:", "email", "theprez@gmail.com", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Address:", "address1", "21 Laussat St", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Country:", "country", "Myanmar [Burma]", "text", &field); form.fields.push_back(field); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_TRUE(ImportAddressProfiles(form_structure)); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); AutofillProfile expected(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&expected, "George", nullptr, "Washington", "theprez@gmail.com", nullptr, "21 Laussat St", nullptr, "San Francisco", "California", "94102", "MM", nullptr); const std::vector<AutofillProfile*>& results = personal_data_->GetProfiles(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(0, expected.Compare(*results[0])); } // TODO(crbug.com/634131): Create profiles if part of a standalone part of a // composed country name is present. // Tests that a profile is created if a standalone part of a composed country // name is present. TEST_F(PersonalDataManagerTest, ImportAddressProfiles_IncompleteComposedCountryName) { FormData form; FormFieldData field; test::CreateTestFormField("First name:", "first_name", "George", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Last name:", "last_name", "Washington", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Email:", "email", "theprez@gmail.com", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Address:", "address1", "21 Laussat St", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Country:", "country", "Myanmar", // Missing the [Burma] part "text", &field); form.fields.push_back(field); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); EXPECT_FALSE(ImportAddressProfiles(form_structure)); // Since no refresh is expected, reload the data from the database to make // sure no changes were written out. ResetPersonalDataManager(USER_MODE_NORMAL); const std::vector<AutofillProfile*>& profiles = personal_data_->GetProfiles(); ASSERT_EQ(0U, profiles.size()); const std::vector<CreditCard*>& cards = personal_data_->GetCreditCards(); ASSERT_EQ(0U, cards.size()); } // ImportCreditCard tests. // Tests that a valid credit card is extracted. TEST_F(PersonalDataManagerTest, ImportCreditCard_Valid) { // Add a single valid credit card form. FormData form; AddFullCreditCardForm(&form, "Biggie Smalls", "4111-1111-1111-1111", "01", "2999"); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_TRUE(ImportCreditCard( form_structure, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); ASSERT_TRUE(imported_credit_card); EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_->SaveImportedCreditCard(*imported_credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); CreditCard expected(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&expected, "Biggie Smalls", "4111111111111111", "01", "2999", ""); // Imported cards have not billing info. const std::vector<CreditCard*>& results = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(0, expected.Compare(*results[0])); } // Tests that an invalid credit card is not extracted. TEST_F(PersonalDataManagerTest, ImportCreditCard_Invalid) { FormData form; AddFullCreditCardForm(&form, "Jim Johansen", "1000000000000000", "02", "2999"); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_FALSE(ImportCreditCard( form_structure, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); ASSERT_FALSE(imported_credit_card); // Since no refresh is expected, reload the data from the database to make // sure no changes were written out. ResetPersonalDataManager(USER_MODE_NORMAL); const std::vector<CreditCard*>& results = personal_data_->GetCreditCards(); ASSERT_EQ(0U, results.size()); } // Tests that a valid credit card is extracted when the option text for month // select can't be parsed but its value can. TEST_F(PersonalDataManagerTest, ImportCreditCard_MonthSelectInvalidText) { // Add a single valid credit card form with an invalid option value. FormData form; AddFullCreditCardForm(&form, "Biggie Smalls", "4111-1111-1111-1111", "Feb (2)", "2999"); // Add option values and contents to the expiration month field. ASSERT_EQ(base::ASCIIToUTF16("exp_month"), form.fields[2].name); std::vector<base::string16> values; values.push_back(base::ASCIIToUTF16("1")); values.push_back(base::ASCIIToUTF16("2")); values.push_back(base::ASCIIToUTF16("3")); std::vector<base::string16> contents; contents.push_back(base::ASCIIToUTF16("Jan (1)")); contents.push_back(base::ASCIIToUTF16("Feb (2)")); contents.push_back(base::ASCIIToUTF16("Mar (3)")); form.fields[2].option_values = values; form.fields[2].option_contents = contents; FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_TRUE(ImportCreditCard( form_structure, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); ASSERT_TRUE(imported_credit_card); EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_->SaveImportedCreditCard(*imported_credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // See that the invalid option text was converted to the right value. CreditCard expected(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&expected, "Biggie Smalls", "4111111111111111", "02", "2999", ""); // Imported cards have not billing info. const std::vector<CreditCard*>& results = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(0, expected.Compare(*results[0])); } TEST_F(PersonalDataManagerTest, ImportCreditCard_TwoValidCards) { // Start with a single valid credit card form. FormData form1; AddFullCreditCardForm(&form1, "Biggie Smalls", "4111-1111-1111-1111", "01", "2999"); FormStructure form_structure1(form1); form_structure1.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_TRUE(ImportCreditCard( form_structure1, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); ASSERT_TRUE(imported_credit_card); EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_->SaveImportedCreditCard(*imported_credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); CreditCard expected(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&expected, "Biggie Smalls", "4111111111111111", "01", "2999", ""); // Imported cards have not billing info. const std::vector<CreditCard*>& results = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(0, expected.Compare(*results[0])); // Add a second different valid credit card. FormData form2; AddFullCreditCardForm(&form2, "", "5500 0000 0000 0004", "02", "2999"); FormStructure form_structure2(form2); form_structure2.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card2; EXPECT_TRUE(ImportCreditCard( form_structure2, false, &imported_credit_card2, &imported_credit_card_matches_masked_server_credit_card)); ASSERT_TRUE(imported_credit_card2); EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_->SaveImportedCreditCard(*imported_credit_card2); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); CreditCard expected2(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&expected2, "", "5500000000000004", "02", "2999", ""); // Imported cards have not billing info. std::vector<CreditCard*> cards; cards.push_back(&expected); cards.push_back(&expected2); ExpectSameElements(cards, personal_data_->GetCreditCards()); } // This form has the expiration year as one field with MM/YY. TEST_F(PersonalDataManagerTest, ImportCreditCard_Month2DigitYearCombination) { FormData form; FormFieldData field; test::CreateTestFormField("Name on card:", "name_on_card", "John MMYY", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Card Number:", "card_number", "4111111111111111", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Exp Date:", "exp_date", "05/45", "text", &field); field.autocomplete_attribute = "cc-exp"; field.max_length = 5; form.fields.push_back(field); SubmitFormAndExpectImportedCardWithData(form, "John MMYY", "4111111111111111", "05", "2045"); } // This form has the expiration year as one field with MM/YYYY. TEST_F(PersonalDataManagerTest, ImportCreditCard_Month4DigitYearCombination) { FormData form; FormFieldData field; test::CreateTestFormField("Name on card:", "name_on_card", "John MMYYYY", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Card Number:", "card_number", "4111111111111111", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Exp Date:", "exp_date", "05/2045", "text", &field); field.autocomplete_attribute = "cc-exp"; field.max_length = 7; form.fields.push_back(field); SubmitFormAndExpectImportedCardWithData(form, "John MMYYYY", "4111111111111111", "05", "2045"); } // This form has the expiration year as one field with M/YYYY. TEST_F(PersonalDataManagerTest, ImportCreditCard_1DigitMonth4DigitYear) { FormData form; FormFieldData field; test::CreateTestFormField("Name on card:", "name_on_card", "John MYYYY", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Card Number:", "card_number", "4111111111111111", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Exp Date:", "exp_date", "5/2045", "text", &field); field.autocomplete_attribute = "cc-exp"; form.fields.push_back(field); SubmitFormAndExpectImportedCardWithData(form, "John MYYYY", "4111111111111111", "05", "2045"); } // This form has the expiration year as a 2-digit field. TEST_F(PersonalDataManagerTest, ImportCreditCard_2DigitYear) { FormData form; FormFieldData field; test::CreateTestFormField("Name on card:", "name_on_card", "John Smith", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Card Number:", "card_number", "4111111111111111", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Exp Month:", "exp_month", "05", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Exp Year:", "exp_year", "45", "text", &field); field.max_length = 2; form.fields.push_back(field); SubmitFormAndExpectImportedCardWithData(form, "John Smith", "4111111111111111", "05", "2045"); } // Tests that a credit card is extracted because it only matches a masked server // card. TEST_F(PersonalDataManagerTest, ImportCreditCard_DuplicateServerCards_MaskedCard) { // Add a masked server card. std::vector<CreditCard> server_cards; server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "a123")); test::SetCreditCardInfo(&server_cards.back(), "John Dillinger", "1111" /* Visa */, "01", "2999", ""); server_cards.back().SetNetworkForMaskedCard(kVisaCard); test::SetServerCreditCards(autofill_table_, server_cards); // Type the same data as the masked card into a form. FormData form; AddFullCreditCardForm(&form, "John Dillinger", "4111111111111111", "01", "2999"); // The card should be offered to be saved locally because it only matches the // masked server card. FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_TRUE(ImportCreditCard( form_structure, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); ASSERT_TRUE(imported_credit_card); EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_->SaveImportedCreditCard(*imported_credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); } // Tests that a credit card is not extracted because it matches a full server // card. TEST_F(PersonalDataManagerTest, ImportCreditCard_DuplicateServerCards_FullCard) { // Add a full server card. std::vector<CreditCard> server_cards; server_cards.push_back(CreditCard(CreditCard::FULL_SERVER_CARD, "c789")); test::SetCreditCardInfo(&server_cards.back(), "Clyde Barrow", "347666888555" /* American Express */, "04", "2999", ""); // Imported cards have not billing info. test::SetServerCreditCards(autofill_table_, server_cards); // Type the same data as the unmasked card into a form. FormData form; AddFullCreditCardForm(&form, "Clyde Barrow", "347666888555", "04", "2999"); // The card should not be offered to be saved locally because it only matches // the full server card. FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_FALSE(ImportCreditCard( form_structure, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); ASSERT_FALSE(imported_credit_card); } TEST_F(PersonalDataManagerTest, ImportCreditCard_SameCreditCardWithConflict) { // Start with a single valid credit card form. FormData form1; AddFullCreditCardForm(&form1, "Biggie Smalls", "4111-1111-1111-1111", "01", "2998"); FormStructure form_structure1(form1); form_structure1.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_TRUE(ImportCreditCard( form_structure1, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); ASSERT_TRUE(imported_credit_card); EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_->SaveImportedCreditCard(*imported_credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); CreditCard expected(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&expected, "Biggie Smalls", "4111111111111111", "01", "2998", ""); // Imported cards have not billing info. const std::vector<CreditCard*>& results = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(0, expected.Compare(*results[0])); // Add a second different valid credit card where the year is different but // the credit card number matches. FormData form2; AddFullCreditCardForm(&form2, "Biggie Smalls", "4111 1111 1111 1111", "01", /* different year */ "2999"); FormStructure form_structure2(form2); form_structure2.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card2; EXPECT_TRUE(ImportCreditCard( form_structure2, false, &imported_credit_card2, &imported_credit_card_matches_masked_server_credit_card)); EXPECT_FALSE(imported_credit_card2); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Expect that the newer information is saved. In this case the year is // updated to "2999". CreditCard expected2(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&expected2, "Biggie Smalls", "4111111111111111", "01", "2999", ""); // Imported cards have not billing info. const std::vector<CreditCard*>& results2 = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results2.size()); EXPECT_EQ(0, expected2.Compare(*results2[0])); } TEST_F(PersonalDataManagerTest, ImportCreditCard_ShouldReturnLocalCard) { // Start with a single valid credit card form. FormData form1; AddFullCreditCardForm(&form1, "Biggie Smalls", "4111-1111-1111-1111", "01", "2998"); FormStructure form_structure1(form1); form_structure1.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_TRUE(ImportCreditCard( form_structure1, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); ASSERT_TRUE(imported_credit_card); EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_->SaveImportedCreditCard(*imported_credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); CreditCard expected(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&expected, "Biggie Smalls", "4111111111111111", "01", "2998", ""); // Imported cards have not billing info. const std::vector<CreditCard*>& results = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(0, expected.Compare(*results[0])); // Add a second different valid credit card where the year is different but // the credit card number matches. FormData form2; AddFullCreditCardForm(&form2, "Biggie Smalls", "4111 1111 1111 1111", "01", /* different year */ "2999"); FormStructure form_structure2(form2); form_structure2.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card2; EXPECT_TRUE(ImportCreditCard( form_structure2, /* should_return_local_card= */ true, &imported_credit_card2, &imported_credit_card_matches_masked_server_credit_card)); // The local card is returned after an update. EXPECT_TRUE(imported_credit_card2); EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Expect that the newer information is saved. In this case the year is // updated to "2999". CreditCard expected2(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&expected2, "Biggie Smalls", "4111111111111111", "01", "2999", ""); // Imported cards have not billing info. const std::vector<CreditCard*>& results2 = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results2.size()); EXPECT_EQ(0, expected2.Compare(*results2[0])); } TEST_F(PersonalDataManagerTest, ImportCreditCard_EmptyCardWithConflict) { // Start with a single valid credit card form. FormData form1; AddFullCreditCardForm(&form1, "Biggie Smalls", "4111-1111-1111-1111", "01", "2998"); FormStructure form_structure1(form1); form_structure1.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_TRUE(ImportCreditCard( form_structure1, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); ASSERT_TRUE(imported_credit_card); EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_->SaveImportedCreditCard(*imported_credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); CreditCard expected(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&expected, "Biggie Smalls", "4111111111111111", "01", "2998", ""); // Imported cards have not billing info. const std::vector<CreditCard*>& results = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(0, expected.Compare(*results[0])); // Add a second credit card with no number. FormData form2; AddFullCreditCardForm(&form2, "Biggie Smalls", /* no number */ nullptr, "01", "2999"); FormStructure form_structure2(form2); form_structure2.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card2; EXPECT_FALSE(ImportCreditCard( form_structure2, false, &imported_credit_card2, &imported_credit_card_matches_masked_server_credit_card)); EXPECT_FALSE(imported_credit_card2); // Since no refresh is expected, reload the data from the database to make // sure no changes were written out. ResetPersonalDataManager(USER_MODE_NORMAL); // No change is expected. CreditCard expected2(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&expected2, "Biggie Smalls", "4111111111111111", "01", "2998", ""); const std::vector<CreditCard*>& results2 = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results2.size()); EXPECT_EQ(0, expected2.Compare(*results2[0])); } TEST_F(PersonalDataManagerTest, ImportCreditCard_MissingInfoInNew) { // Start with a single valid credit card form. FormData form1; AddFullCreditCardForm(&form1, "Biggie Smalls", "4111-1111-1111-1111", "01", "2999"); FormStructure form_structure1(form1); form_structure1.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_TRUE(ImportCreditCard( form_structure1, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); ASSERT_TRUE(imported_credit_card); EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_->SaveImportedCreditCard(*imported_credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); CreditCard expected(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&expected, "Biggie Smalls", "4111111111111111", "01", "2999", ""); const std::vector<CreditCard*>& results = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(0, expected.Compare(*results[0])); // Add a second different valid credit card where the name is missing but // the credit card number matches. FormData form2; AddFullCreditCardForm(&form2, /* missing name */ nullptr, "4111-1111-1111-1111", "01", "2999"); FormStructure form_structure2(form2); form_structure2.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card2; EXPECT_TRUE(ImportCreditCard( form_structure2, false, &imported_credit_card2, &imported_credit_card_matches_masked_server_credit_card)); EXPECT_FALSE(imported_credit_card2); // Since no refresh is expected, reload the data from the database to make // sure no changes were written out. ResetPersonalDataManager(USER_MODE_NORMAL); // No change is expected. CreditCard expected2(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&expected2, "Biggie Smalls", "4111111111111111", "01", "2999", ""); const std::vector<CreditCard*>& results2 = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results2.size()); EXPECT_EQ(0, expected2.Compare(*results2[0])); // Add a third credit card where the expiration date is missing. FormData form3; AddFullCreditCardForm(&form3, "Johnny McEnroe", "5555555555554444", /* no month */ nullptr, /* no year */ nullptr); FormStructure form_structure3(form3); form_structure3.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card3; EXPECT_FALSE(ImportCreditCard( form_structure3, false, &imported_credit_card3, &imported_credit_card_matches_masked_server_credit_card)); ASSERT_FALSE(imported_credit_card3); // Since no refresh is expected, reload the data from the database to make // sure no changes were written out. ResetPersonalDataManager(USER_MODE_NORMAL); // No change is expected. CreditCard expected3(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&expected3, "Biggie Smalls", "4111111111111111", "01", "2999", ""); const std::vector<CreditCard*>& results3 = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results3.size()); EXPECT_EQ(0, expected3.Compare(*results3[0])); } TEST_F(PersonalDataManagerTest, ImportCreditCard_MissingInfoInOld) { // Start with a single valid credit card stored via the preferences. // Note the empty name. CreditCard saved_credit_card(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&saved_credit_card, "", "4111111111111111" /* Visa */, "01", "2998", "1"); personal_data_->AddCreditCard(saved_credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); const std::vector<CreditCard*>& results1 = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results1.size()); EXPECT_EQ(saved_credit_card, *results1[0]); // Add a second different valid credit card where the year is different but // the credit card number matches. FormData form; AddFullCreditCardForm(&form, "Biggie Smalls", "4111-1111-1111-1111", "01", /* different year */ "2999"); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_TRUE(ImportCreditCard( form_structure, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); EXPECT_FALSE(imported_credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Expect that the newer information is saved. In this case the year is // added to the existing credit card. CreditCard expected2(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&expected2, "Biggie Smalls", "4111111111111111", "01", "2999", "1"); const std::vector<CreditCard*>& results2 = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results2.size()); EXPECT_EQ(0, expected2.Compare(*results2[0])); } // We allow the user to store a credit card number with separators via the UI. // We should not try to re-aggregate the same card with the separators stripped. TEST_F(PersonalDataManagerTest, ImportCreditCard_SameCardWithSeparators) { // Start with a single valid credit card stored via the preferences. // Note the separators in the credit card number. CreditCard saved_credit_card(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&saved_credit_card, "Biggie Smalls", "4111 1111 1111 1111" /* Visa */, "01", "2999", ""); personal_data_->AddCreditCard(saved_credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); const std::vector<CreditCard*>& results1 = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results1.size()); EXPECT_EQ(0, saved_credit_card.Compare(*results1[0])); // Import the same card info, but with different separators in the number. FormData form; AddFullCreditCardForm(&form, "Biggie Smalls", "4111-1111-1111-1111", "01", "2999"); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_TRUE(ImportCreditCard( form_structure, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); EXPECT_FALSE(imported_credit_card); // Since no refresh is expected, reload the data from the database to make // sure no changes were written out. ResetPersonalDataManager(USER_MODE_NORMAL); // Expect that no new card is saved. const std::vector<CreditCard*>& results2 = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results2.size()); EXPECT_EQ(0, saved_credit_card.Compare(*results2[0])); } // Ensure that if a verified credit card already exists, aggregated credit cards // cannot modify it in any way. TEST_F(PersonalDataManagerTest, ImportCreditCard_ExistingVerifiedCardWithConflict) { // Start with a verified credit card. CreditCard credit_card(base::GenerateGUID(), kSettingsOrigin); test::SetCreditCardInfo(&credit_card, "Biggie Smalls", "4111 1111 1111 1111" /* Visa */, "01", "2998", ""); EXPECT_TRUE(credit_card.IsVerified()); // Add the credit card to the database. personal_data_->AddCreditCard(credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Simulate a form submission with conflicting expiration year. FormData form; AddFullCreditCardForm(&form, "Biggie Smalls", "4111 1111 1111 1111", "01", /* different year */ "2999"); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_TRUE(ImportCreditCard( form_structure, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); ASSERT_FALSE(imported_credit_card); // Since no refresh is expected, reload the data from the database to make // sure no changes were written out. ResetPersonalDataManager(USER_MODE_NORMAL); // Expect that the saved credit card is not modified. const std::vector<CreditCard*>& results = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(0, credit_card.Compare(*results[0])); } // ImportFormData tests (both addresses and credit cards). // Test that a form with both address and credit card sections imports the // address and the credit card. TEST_F(PersonalDataManagerTest, ImportFormData_OneAddressOneCreditCard) { FormData form; FormFieldData field; // Address section. test::CreateTestFormField("First name:", "first_name", "George", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Last name:", "last_name", "Washington", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Email:", "email", "theprez@gmail.com", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Address:", "address1", "21 Laussat St", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form.fields.push_back(field); // Credit card section. AddFullCreditCardForm(&form, "Biggie Smalls", "4111-1111-1111-1111", "01", "2999"); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_TRUE(personal_data_->ImportFormData( form_structure, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); ASSERT_TRUE(imported_credit_card); EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_->SaveImportedCreditCard(*imported_credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Test that the address has been saved. AutofillProfile expected_address(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&expected_address, "George", NULL, "Washington", "theprez@gmail.com", NULL, "21 Laussat St", NULL, "San Francisco", "California", "94102", NULL, NULL); const std::vector<AutofillProfile*>& results_addr = personal_data_->GetProfiles(); ASSERT_EQ(1U, results_addr.size()); EXPECT_EQ(0, expected_address.Compare(*results_addr[0])); // Test that the credit card has also been saved. CreditCard expected_card(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&expected_card, "Biggie Smalls", "4111111111111111", "01", "2999", ""); const std::vector<CreditCard*>& results_cards = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results_cards.size()); EXPECT_EQ(0, expected_card.Compare(*results_cards[0])); } // Test that a form with two address sections and a credit card section does not // import the address but does import the credit card. TEST_F(PersonalDataManagerTest, ImportFormData_TwoAddressesOneCreditCard) { FormData form; FormFieldData field; // Address section 1. test::CreateTestFormField("First name:", "first_name", "George", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Last name:", "last_name", "Washington", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Email:", "email", "theprez@gmail.com", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Address:", "address1", "21 Laussat St", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "San Francisco", "text", &field); form.fields.push_back(field); test::CreateTestFormField("State:", "state", "California", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "94102", "text", &field); form.fields.push_back(field); // Address section 2. test::CreateTestFormField("Name:", "name", "Barack Obama", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Address:", "address", "1600 Pennsylvania Avenue", "text", &field); form.fields.push_back(field); test::CreateTestFormField("City:", "city", "Washington", "text", &field); form.fields.push_back(field); test::CreateTestFormField("State:", "state", "DC", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Zip:", "zip", "20500", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Country:", "country", "USA", "text", &field); form.fields.push_back(field); // Credit card section. AddFullCreditCardForm(&form, "Biggie Smalls", "4111-1111-1111-1111", "01", "2999"); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; // Still returns true because the credit card import was successful. EXPECT_TRUE(personal_data_->ImportFormData( form_structure, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); ASSERT_TRUE(imported_credit_card); EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); personal_data_->SaveImportedCreditCard(*imported_credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Test that both addresses have been saved. EXPECT_EQ(2U, personal_data_->GetProfiles().size()); // Test that the credit card has been saved. CreditCard expected_card(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&expected_card, "Biggie Smalls", "4111111111111111", "01", "2999", ""); const std::vector<CreditCard*>& results = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(0, expected_card.Compare(*results[0])); } // Ensure that verified profiles can be saved via SaveImportedProfile, // overwriting existing unverified profiles. TEST_F(PersonalDataManagerTest, SaveImportedProfileWithVerifiedData) { // Start with an unverified profile. AutofillProfile profile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile, "Marion", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St.", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); EXPECT_FALSE(profile.IsVerified()); // Add the profile to the database. personal_data_->AddProfile(profile); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); AutofillProfile new_verified_profile = profile; new_verified_profile.set_guid(base::GenerateGUID()); new_verified_profile.set_origin(kSettingsOrigin); new_verified_profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, base::ASCIIToUTF16("1 234 567-8910")); EXPECT_TRUE(new_verified_profile.IsVerified()); personal_data_->SaveImportedProfile(new_verified_profile); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // The new profile should be merged into the existing one. const std::vector<AutofillProfile*>& results = personal_data_->GetProfiles(); ASSERT_EQ(1U, results.size()); AutofillProfile expected(new_verified_profile); expected.SetRawInfo(NAME_FULL, base::ASCIIToUTF16("Marion Mitchell Morrison")); expected.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, base::ASCIIToUTF16("+1 234-567-8910")); EXPECT_EQ(0, expected.Compare(*results[0])) << "result = {" << *results[0] << "} | expected = {" << expected << "}"; } // Ensure that verified credit cards can be saved via SaveImportedCreditCard. TEST_F(PersonalDataManagerTest, SaveImportedCreditCardWithVerifiedData) { // Start with a verified credit card. CreditCard credit_card(base::GenerateGUID(), kSettingsOrigin); test::SetCreditCardInfo(&credit_card, "Biggie Smalls", "4111 1111 1111 1111" /* Visa */, "01", "2999", ""); EXPECT_TRUE(credit_card.IsVerified()); // Add the credit card to the database. personal_data_->AddCreditCard(credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); CreditCard new_verified_card = credit_card; new_verified_card.set_guid(base::GenerateGUID()); new_verified_card.SetRawInfo(CREDIT_CARD_NAME_FULL, base::ASCIIToUTF16("B. Small")); EXPECT_TRUE(new_verified_card.IsVerified()); personal_data_->SaveImportedCreditCard(new_verified_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Expect that the saved credit card is updated. const std::vector<CreditCard*>& results = personal_data_->GetCreditCards(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(base::ASCIIToUTF16("B. Small"), results[0]->GetRawInfo(CREDIT_CARD_NAME_FULL)); } TEST_F(PersonalDataManagerTest, GetNonEmptyTypes) { // Check that there are no available types with no profiles stored. ServerFieldTypeSet non_empty_types; personal_data_->GetNonEmptyTypes(&non_empty_types); EXPECT_EQ(0U, non_empty_types.size()); // Test with one profile stored. AutofillProfile profile0(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile0, "Marion", NULL, "Morrison", "johnwayne@me.xyz", NULL, "123 Zoo St.", NULL, "Hollywood", "CA", "91601", "US", "14155678910"); personal_data_->AddProfile(profile0); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); personal_data_->GetNonEmptyTypes(&non_empty_types); EXPECT_EQ(15U, non_empty_types.size()); EXPECT_TRUE(non_empty_types.count(NAME_FIRST)); EXPECT_TRUE(non_empty_types.count(NAME_LAST)); EXPECT_TRUE(non_empty_types.count(NAME_FULL)); EXPECT_TRUE(non_empty_types.count(EMAIL_ADDRESS)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_LINE1)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_STREET_ADDRESS)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_CITY)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_STATE)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_ZIP)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_COUNTRY)); EXPECT_TRUE(non_empty_types.count(PHONE_HOME_NUMBER)); EXPECT_TRUE(non_empty_types.count(PHONE_HOME_COUNTRY_CODE)); EXPECT_TRUE(non_empty_types.count(PHONE_HOME_CITY_CODE)); EXPECT_TRUE(non_empty_types.count(PHONE_HOME_CITY_AND_NUMBER)); EXPECT_TRUE(non_empty_types.count(PHONE_HOME_WHOLE_NUMBER)); // Test with multiple profiles stored. AutofillProfile profile1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile1, "Josephine", "Alicia", "Saenz", "joewayne@me.xyz", "Fox", "903 Apple Ct.", NULL, "Orlando", "FL", "32801", "US", "16502937549"); AutofillProfile profile2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile2, "Josephine", "Alicia", "Saenz", "joewayne@me.xyz", "Fox", "1212 Center.", "Bld. 5", "Orlando", "FL", "32801", "US", "16502937549"); personal_data_->AddProfile(profile1); personal_data_->AddProfile(profile2); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); personal_data_->GetNonEmptyTypes(&non_empty_types); EXPECT_EQ(19U, non_empty_types.size()); EXPECT_TRUE(non_empty_types.count(NAME_FIRST)); EXPECT_TRUE(non_empty_types.count(NAME_MIDDLE)); EXPECT_TRUE(non_empty_types.count(NAME_MIDDLE_INITIAL)); EXPECT_TRUE(non_empty_types.count(NAME_LAST)); EXPECT_TRUE(non_empty_types.count(NAME_FULL)); EXPECT_TRUE(non_empty_types.count(EMAIL_ADDRESS)); EXPECT_TRUE(non_empty_types.count(COMPANY_NAME)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_LINE1)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_LINE2)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_STREET_ADDRESS)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_CITY)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_STATE)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_ZIP)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_COUNTRY)); EXPECT_TRUE(non_empty_types.count(PHONE_HOME_NUMBER)); EXPECT_TRUE(non_empty_types.count(PHONE_HOME_CITY_CODE)); EXPECT_TRUE(non_empty_types.count(PHONE_HOME_COUNTRY_CODE)); EXPECT_TRUE(non_empty_types.count(PHONE_HOME_CITY_AND_NUMBER)); EXPECT_TRUE(non_empty_types.count(PHONE_HOME_WHOLE_NUMBER)); // Test with credit card information also stored. CreditCard credit_card(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&credit_card, "John Dillinger", "423456789012" /* Visa */, "01", "2999", ""); personal_data_->AddCreditCard(credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); personal_data_->GetNonEmptyTypes(&non_empty_types); EXPECT_EQ(29U, non_empty_types.size()); EXPECT_TRUE(non_empty_types.count(NAME_FIRST)); EXPECT_TRUE(non_empty_types.count(NAME_MIDDLE)); EXPECT_TRUE(non_empty_types.count(NAME_MIDDLE_INITIAL)); EXPECT_TRUE(non_empty_types.count(NAME_LAST)); EXPECT_TRUE(non_empty_types.count(NAME_FULL)); EXPECT_TRUE(non_empty_types.count(EMAIL_ADDRESS)); EXPECT_TRUE(non_empty_types.count(COMPANY_NAME)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_LINE1)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_LINE2)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_STREET_ADDRESS)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_CITY)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_STATE)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_ZIP)); EXPECT_TRUE(non_empty_types.count(ADDRESS_HOME_COUNTRY)); EXPECT_TRUE(non_empty_types.count(PHONE_HOME_NUMBER)); EXPECT_TRUE(non_empty_types.count(PHONE_HOME_CITY_CODE)); EXPECT_TRUE(non_empty_types.count(PHONE_HOME_COUNTRY_CODE)); EXPECT_TRUE(non_empty_types.count(PHONE_HOME_CITY_AND_NUMBER)); EXPECT_TRUE(non_empty_types.count(PHONE_HOME_WHOLE_NUMBER)); EXPECT_TRUE(non_empty_types.count(CREDIT_CARD_NAME_FULL)); EXPECT_TRUE(non_empty_types.count(CREDIT_CARD_NAME_FIRST)); EXPECT_TRUE(non_empty_types.count(CREDIT_CARD_NAME_LAST)); EXPECT_TRUE(non_empty_types.count(CREDIT_CARD_NUMBER)); EXPECT_TRUE(non_empty_types.count(CREDIT_CARD_TYPE)); EXPECT_TRUE(non_empty_types.count(CREDIT_CARD_EXP_MONTH)); EXPECT_TRUE(non_empty_types.count(CREDIT_CARD_EXP_2_DIGIT_YEAR)); EXPECT_TRUE(non_empty_types.count(CREDIT_CARD_EXP_4_DIGIT_YEAR)); EXPECT_TRUE(non_empty_types.count(CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR)); EXPECT_TRUE(non_empty_types.count(CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR)); } TEST_F(PersonalDataManagerTest, IncognitoReadOnly) { ASSERT_TRUE(personal_data_->GetProfiles().empty()); ASSERT_TRUE(personal_data_->GetCreditCards().empty()); AutofillProfile steve_jobs(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&steve_jobs, "Steven", "Paul", "Jobs", "sjobs@apple.com", "Apple Computer, Inc.", "1 Infinite Loop", "", "Cupertino", "CA", "95014", "US", "(800) 275-2273"); personal_data_->AddProfile(steve_jobs); CreditCard bill_gates(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&bill_gates, "William H. Gates", "5555555555554444", "1", "2020", "1"); personal_data_->AddCreditCard(bill_gates); // The personal data manager should be able to read existing profiles in an // off-the-record context. ResetPersonalDataManager(USER_MODE_INCOGNITO); ASSERT_EQ(1U, personal_data_->GetProfiles().size()); ASSERT_EQ(1U, personal_data_->GetCreditCards().size()); // No adds, saves, or updates should take effect. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()).Times(0); // Add profiles or credit card shouldn't work. personal_data_->AddProfile(test::GetFullProfile()); CreditCard larry_page(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&larry_page, "Lawrence Page", "4111111111111111", "10", "2025", "1"); personal_data_->AddCreditCard(larry_page); ResetPersonalDataManager(USER_MODE_INCOGNITO); EXPECT_EQ(1U, personal_data_->GetProfiles().size()); EXPECT_EQ(1U, personal_data_->GetCreditCards().size()); // Saving or creating profiles from imported profiles shouldn't work. steve_jobs.SetRawInfo(NAME_FIRST, base::ASCIIToUTF16("Steve")); personal_data_->SaveImportedProfile(steve_jobs); bill_gates.SetRawInfo(CREDIT_CARD_NAME_FULL, base::ASCIIToUTF16("Bill Gates")); personal_data_->SaveImportedCreditCard(bill_gates); ResetPersonalDataManager(USER_MODE_INCOGNITO); EXPECT_EQ(base::ASCIIToUTF16("Steven"), personal_data_->GetProfiles()[0]->GetRawInfo(NAME_FIRST)); EXPECT_EQ( base::ASCIIToUTF16("William H. Gates"), personal_data_->GetCreditCards()[0]->GetRawInfo(CREDIT_CARD_NAME_FULL)); // Updating existing profiles shouldn't work. steve_jobs.SetRawInfo(NAME_FIRST, base::ASCIIToUTF16("Steve")); personal_data_->UpdateProfile(steve_jobs); bill_gates.SetRawInfo(CREDIT_CARD_NAME_FULL, base::ASCIIToUTF16("Bill Gates")); personal_data_->UpdateCreditCard(bill_gates); ResetPersonalDataManager(USER_MODE_INCOGNITO); EXPECT_EQ(base::ASCIIToUTF16("Steven"), personal_data_->GetProfiles()[0]->GetRawInfo(NAME_FIRST)); EXPECT_EQ( base::ASCIIToUTF16("William H. Gates"), personal_data_->GetCreditCards()[0]->GetRawInfo(CREDIT_CARD_NAME_FULL)); // Removing shouldn't work. personal_data_->RemoveByGUID(steve_jobs.guid()); personal_data_->RemoveByGUID(bill_gates.guid()); ResetPersonalDataManager(USER_MODE_INCOGNITO); EXPECT_EQ(1U, personal_data_->GetProfiles().size()); EXPECT_EQ(1U, personal_data_->GetCreditCards().size()); } TEST_F(PersonalDataManagerTest, DefaultCountryCodeIsCached) { // The return value should always be some country code, no matter what. std::string default_country = personal_data_->GetDefaultCountryCodeForNewAddress(); EXPECT_EQ(2U, default_country.size()); AutofillProfile moose(base::GenerateGUID(), kSettingsOrigin); test::SetProfileInfo(&moose, "Moose", "P", "McMahon", "mpm@example.com", "", "1 Taiga TKTR", "", "Calgary", "AB", "T2B 2K2", "CA", "(800) 555-9000"); personal_data_->AddProfile(moose); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // The value is cached and doesn't change even after adding an address. EXPECT_EQ(default_country, personal_data_->GetDefaultCountryCodeForNewAddress()); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()).Times(2); // Disabling Autofill blows away this cache and shouldn't account for Autofill // profiles. prefs_->SetBoolean(prefs::kAutofillEnabled, false); EXPECT_EQ(default_country, personal_data_->GetDefaultCountryCodeForNewAddress()); // Enabling Autofill blows away the cached value and should reflect the new // value (accounting for profiles). prefs_->SetBoolean(prefs::kAutofillEnabled, true); EXPECT_EQ(base::UTF16ToUTF8(moose.GetRawInfo(ADDRESS_HOME_COUNTRY)), personal_data_->GetDefaultCountryCodeForNewAddress()); } TEST_F(PersonalDataManagerTest, DefaultCountryCodeComesFromProfiles) { AutofillProfile moose(base::GenerateGUID(), kSettingsOrigin); test::SetProfileInfo(&moose, "Moose", "P", "McMahon", "mpm@example.com", "", "1 Taiga TKTR", "", "Calgary", "AB", "T2B 2K2", "CA", "(800) 555-9000"); personal_data_->AddProfile(moose); ResetPersonalDataManager(USER_MODE_NORMAL); EXPECT_EQ("CA", personal_data_->GetDefaultCountryCodeForNewAddress()); // Multiple profiles cast votes. AutofillProfile armadillo(base::GenerateGUID(), kSettingsOrigin); test::SetProfileInfo(&armadillo, "Armin", "Dill", "Oh", "ado@example.com", "", "1 Speed Bump", "", "Lubbock", "TX", "77500", "MX", "(800) 555-9000"); AutofillProfile armadillo2(base::GenerateGUID(), kSettingsOrigin); test::SetProfileInfo(&armadillo2, "Armin", "Dill", "Oh", "ado@example.com", "", "2 Speed Bump", "", "Lubbock", "TX", "77500", "MX", "(800) 555-9000"); personal_data_->AddProfile(armadillo); personal_data_->AddProfile(armadillo2); ResetPersonalDataManager(USER_MODE_NORMAL); EXPECT_EQ("MX", personal_data_->GetDefaultCountryCodeForNewAddress()); personal_data_->RemoveByGUID(armadillo.guid()); personal_data_->RemoveByGUID(armadillo2.guid()); ResetPersonalDataManager(USER_MODE_NORMAL); // Verified profiles count more. armadillo.set_origin("http://randomwebsite.com"); armadillo2.set_origin("http://randomwebsite.com"); personal_data_->AddProfile(armadillo); personal_data_->AddProfile(armadillo2); ResetPersonalDataManager(USER_MODE_NORMAL); EXPECT_EQ("CA", personal_data_->GetDefaultCountryCodeForNewAddress()); personal_data_->RemoveByGUID(armadillo.guid()); ResetPersonalDataManager(USER_MODE_NORMAL); // But unverified profiles can be a tie breaker. armadillo.set_origin(kSettingsOrigin); personal_data_->AddProfile(armadillo); ResetPersonalDataManager(USER_MODE_NORMAL); EXPECT_EQ("MX", personal_data_->GetDefaultCountryCodeForNewAddress()); // Invalid country codes are ignored. personal_data_->RemoveByGUID(armadillo.guid()); personal_data_->RemoveByGUID(moose.guid()); AutofillProfile space_invader(base::GenerateGUID(), kSettingsOrigin); test::SetProfileInfo(&space_invader, "Marty", "", "Martian", "mm@example.com", "", "1 Flying Object", "", "Valles Marineris", "", "", "XX", ""); personal_data_->AddProfile(moose); ResetPersonalDataManager(USER_MODE_NORMAL); EXPECT_EQ("MX", personal_data_->GetDefaultCountryCodeForNewAddress()); } TEST_F(PersonalDataManagerTest, UpdateLanguageCodeInProfile) { AutofillProfile profile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile, "Marion", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St.", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); personal_data_->AddProfile(profile); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); profile.set_language_code("en"); personal_data_->UpdateProfile(profile); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); const std::vector<AutofillProfile*>& results = personal_data_->GetProfiles(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(0, profile.Compare(*results[0])); EXPECT_EQ("en", results[0]->language_code()); } TEST_F(PersonalDataManagerTest, GetProfileSuggestions) { AutofillProfile profile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile, "Marion", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St.\nSecond Line\nThird line", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); personal_data_->AddProfile(profile); ResetPersonalDataManager(USER_MODE_NORMAL); std::vector<Suggestion> suggestions = personal_data_->GetProfileSuggestions( AutofillType(ADDRESS_HOME_STREET_ADDRESS), base::ASCIIToUTF16("123"), false, std::vector<ServerFieldType>()); ASSERT_FALSE(suggestions.empty()); EXPECT_EQ(base::ASCIIToUTF16("123 Zoo St., Second Line, Third line, unit 5"), suggestions[0].value); } TEST_F(PersonalDataManagerTest, GetProfileSuggestions_PhoneSubstring) { AutofillProfile profile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile, "Marion", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St.\nSecond Line\nThird line", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); personal_data_->AddProfile(profile); ResetPersonalDataManager(USER_MODE_NORMAL); std::vector<Suggestion> suggestions = personal_data_->GetProfileSuggestions( AutofillType(PHONE_HOME_WHOLE_NUMBER), base::ASCIIToUTF16("234"), false, std::vector<ServerFieldType>()); ASSERT_FALSE(suggestions.empty()); EXPECT_EQ(base::ASCIIToUTF16("12345678910"), suggestions[0].value); } TEST_F(PersonalDataManagerTest, GetProfileSuggestions_HideSubsets) { AutofillProfile profile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile, "Marion", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St.\nSecond Line\nThird line", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); // Dupe profile, except different in email address (irrelevant for this form). AutofillProfile profile1 = profile; profile1.set_guid(base::GenerateGUID()); profile1.SetRawInfo(EMAIL_ADDRESS, base::ASCIIToUTF16("spam_me@example.com")); // Dupe profile, except different in address state. AutofillProfile profile2 = profile; profile2.set_guid(base::GenerateGUID()); profile2.SetRawInfo(ADDRESS_HOME_STATE, base::ASCIIToUTF16("TX")); // Subset profile. AutofillProfile profile3 = profile; profile3.set_guid(base::GenerateGUID()); profile3.SetRawInfo(ADDRESS_HOME_STATE, base::string16()); // For easier results verification, make sure |profile| is suggested first. profile.set_use_count(5); personal_data_->AddProfile(profile); personal_data_->AddProfile(profile1); personal_data_->AddProfile(profile2); personal_data_->AddProfile(profile3); ResetPersonalDataManager(USER_MODE_NORMAL); // Simulate a form with street address, city and state. std::vector<ServerFieldType> types; types.push_back(ADDRESS_HOME_CITY); types.push_back(ADDRESS_HOME_STATE); std::vector<Suggestion> suggestions = personal_data_->GetProfileSuggestions( AutofillType(ADDRESS_HOME_STREET_ADDRESS), base::ASCIIToUTF16("123"), false, types); ASSERT_EQ(2U, suggestions.size()); EXPECT_EQ(base::ASCIIToUTF16("Hollywood, CA"), suggestions[0].label); EXPECT_EQ(base::ASCIIToUTF16("Hollywood, TX"), suggestions[1].label); } // Tests that GetProfileSuggestions orders its suggestions based on the frecency // formula. TEST_F(PersonalDataManagerTest, GetProfileSuggestions_Ranking) { // Set up the profiles. They are named with number suffixes X so the X is the // order in which they should be ordered by frecency. AutofillProfile profile3(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile3, "Marion3", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St.\nSecond Line\nThird line", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); profile3.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(1)); profile3.set_use_count(5); personal_data_->AddProfile(profile3); AutofillProfile profile1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile1, "Marion1", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St.\nSecond Line\nThird line", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); profile1.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(1)); profile1.set_use_count(10); personal_data_->AddProfile(profile1); AutofillProfile profile2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile2, "Marion2", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St.\nSecond Line\nThird line", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); profile2.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(15)); profile2.set_use_count(300); personal_data_->AddProfile(profile2); ResetPersonalDataManager(USER_MODE_NORMAL); std::vector<Suggestion> suggestions = personal_data_->GetProfileSuggestions( AutofillType(NAME_FIRST), base::ASCIIToUTF16("Ma"), false, std::vector<ServerFieldType>()); ASSERT_EQ(3U, suggestions.size()); EXPECT_EQ(suggestions[0].value, base::ASCIIToUTF16("Marion1")); EXPECT_EQ(suggestions[1].value, base::ASCIIToUTF16("Marion2")); EXPECT_EQ(suggestions[2].value, base::ASCIIToUTF16("Marion3")); } // Tests that GetProfileSuggestions returns all profiles suggestions by default // and only two if the appropriate field trial is set. TEST_F(PersonalDataManagerTest, GetProfileSuggestions_NumberOfSuggestions) { // Set up 3 different profiles. AutofillProfile profile1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile1, "Marion1", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St.\nSecond Line\nThird line", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); personal_data_->AddProfile(profile1); AutofillProfile profile2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile2, "Marion2", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St.\nSecond Line\nThird line", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); personal_data_->AddProfile(profile2); AutofillProfile profile3(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile3, "Marion3", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St.\nSecond Line\nThird line", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); personal_data_->AddProfile(profile3); ResetPersonalDataManager(USER_MODE_NORMAL); // Verify that all the profiles are suggested. std::vector<Suggestion> suggestions = personal_data_->GetProfileSuggestions( AutofillType(NAME_FIRST), base::string16(), false, std::vector<ServerFieldType>()); EXPECT_EQ(3U, suggestions.size()); // Verify that only two profiles are suggested. variation_params_.SetVariationParams(kFrecencyFieldTrialName, {{kFrecencyFieldTrialLimitParam, "2"}}); suggestions = personal_data_->GetProfileSuggestions( AutofillType(NAME_FIRST), base::string16(), false, std::vector<ServerFieldType>()); EXPECT_EQ(2U, suggestions.size()); } // Tests that GetProfileSuggestions returns the right number of profile // suggestions when the limit to three field trial is set and there are less // than three profiles. TEST_F(PersonalDataManagerTest, GetProfileSuggestions_LimitIsMoreThanProfileSuggestions) { variation_params_.SetVariationParams(kFrecencyFieldTrialName, {{kFrecencyFieldTrialLimitParam, "3"}}); // Set up 2 different profiles. AutofillProfile profile1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile1, "Marion1", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St.\nSecond Line\nThird line", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); personal_data_->AddProfile(profile1); AutofillProfile profile2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile2, "Marion2", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St.\nSecond Line\nThird line", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); personal_data_->AddProfile(profile2); ResetPersonalDataManager(USER_MODE_NORMAL); std::vector<Suggestion> suggestions = personal_data_->GetProfileSuggestions( AutofillType(NAME_FIRST), base::string16(), false, std::vector<ServerFieldType>()); EXPECT_EQ(2U, suggestions.size()); } // Tests that disused profiles are suppressed when supression is enabled and // the input field is empty. TEST_F(PersonalDataManagerTest, GetProfileSuggestions_SuppressDisusedProfilesOnEmptyField) { base::test::ScopedFeatureList scoped_features; scoped_features.InitAndEnableFeature(kAutofillSuppressDisusedAddresses); // Set up 2 different profiles. AutofillProfile profile1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile1, "Marion1", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St.\nSecond Line\nThird line", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); profile1.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(200)); personal_data_->AddProfile(profile1); AutofillProfile profile2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile2, "Marion2", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "456 Zoo St.\nSecond Line\nThird line", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); profile2.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(20)); personal_data_->AddProfile(profile2); ResetPersonalDataManager(USER_MODE_NORMAL); // Query with empty string only returns profile2. { std::vector<Suggestion> suggestions = personal_data_->GetProfileSuggestions( AutofillType(ADDRESS_HOME_STREET_ADDRESS), base::string16(), false, std::vector<ServerFieldType>()); EXPECT_EQ(1U, suggestions.size()); } // Query with prefix for profile1 returns profile1. { std::vector<Suggestion> suggestions = personal_data_->GetProfileSuggestions( AutofillType(ADDRESS_HOME_STREET_ADDRESS), base::ASCIIToUTF16("123"), false, std::vector<ServerFieldType>()); ASSERT_EQ(1U, suggestions.size()); EXPECT_EQ( base::ASCIIToUTF16("123 Zoo St., Second Line, Third line, unit 5"), suggestions[0].value); } // Query with prefix for profile2 returns profile2. { std::vector<Suggestion> suggestions = personal_data_->GetProfileSuggestions( AutofillType(ADDRESS_HOME_STREET_ADDRESS), base::ASCIIToUTF16("456"), false, std::vector<ServerFieldType>()); EXPECT_EQ(1U, suggestions.size()); EXPECT_EQ( base::ASCIIToUTF16("456 Zoo St., Second Line, Third line, unit 5"), suggestions[0].value); } } // Test that a masked server card is not suggested if more that six numbers have // been typed in the field. TEST_F(PersonalDataManagerTest, GetCreditCardSuggestions_MaskedCardWithMoreThan6Numbers) { EnableWalletCardImport(); // Add a masked server card. std::vector<CreditCard> server_cards; server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "b459")); test::SetCreditCardInfo(&server_cards.back(), "Emmet Dalton", "2110", "12", "2999", "1"); server_cards.back().SetNetworkForMaskedCard(kVisaCard); test::SetServerCreditCards(autofill_table_, server_cards); personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); std::vector<Suggestion> suggestions = personal_data_->GetCreditCardSuggestions(AutofillType(CREDIT_CARD_NUMBER), base::ASCIIToUTF16("12345678")); // There should be no suggestions. ASSERT_EQ(0U, suggestions.size()); } // Test that local credit cards are ordered as expected. TEST_F(PersonalDataManagerTest, GetCreditCardSuggestions_LocalCardsRanking) { SetupReferenceLocalCreditCards(); // Sublabel is card number when filling name (exact format depends on // the platform, but the last 4 digits should appear). std::vector<Suggestion> suggestions = personal_data_->GetCreditCardSuggestions( AutofillType(CREDIT_CARD_NAME_FULL), /* field_contents= */ base::string16()); ASSERT_EQ(3U, suggestions.size()); // Ordered as expected. EXPECT_EQ(base::ASCIIToUTF16("John Dillinger"), suggestions[0].value); EXPECT_TRUE(suggestions[0].label.find(base::ASCIIToUTF16("9012")) != base::string16::npos); EXPECT_EQ(base::ASCIIToUTF16("Clyde Barrow"), suggestions[1].value); EXPECT_TRUE(suggestions[1].label.find(base::ASCIIToUTF16("8555")) != base::string16::npos); EXPECT_EQ(base::ASCIIToUTF16("Bonnie Parker"), suggestions[2].value); EXPECT_TRUE(suggestions[2].label.find(base::ASCIIToUTF16("2109")) != base::string16::npos); } // Test that local and server cards are ordered as expected. TEST_F(PersonalDataManagerTest, GetCreditCardSuggestions_LocalAndServerCardsRanking) { EnableWalletCardImport(); SetupReferenceLocalCreditCards(); // Add some server cards. std::vector<CreditCard> server_cards; server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "b459")); test::SetCreditCardInfo(&server_cards.back(), "Emmet Dalton", "2110", "12", "2999", "1"); server_cards.back().set_use_count(2); server_cards.back().set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(1)); server_cards.back().SetNetworkForMaskedCard(kVisaCard); server_cards.push_back(CreditCard(CreditCard::FULL_SERVER_CARD, "b460")); test::SetCreditCardInfo(&server_cards.back(), "Jesse James", "2109", "12", "2999", "1"); server_cards.back().set_use_count(6); server_cards.back().set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(1)); test::SetServerCreditCards(autofill_table_, server_cards); personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); std::vector<Suggestion> suggestions = personal_data_->GetCreditCardSuggestions( AutofillType(CREDIT_CARD_NAME_FULL), /* field_contents= */ base::string16()); ASSERT_EQ(5U, suggestions.size()); // All cards should be ordered as expected. EXPECT_EQ(base::ASCIIToUTF16("Jesse James"), suggestions[0].value); EXPECT_EQ(base::ASCIIToUTF16("John Dillinger"), suggestions[1].value); EXPECT_EQ(base::ASCIIToUTF16("Clyde Barrow"), suggestions[2].value); EXPECT_EQ(base::ASCIIToUTF16("Emmet Dalton"), suggestions[3].value); EXPECT_EQ(base::ASCIIToUTF16("Bonnie Parker"), suggestions[4].value); } // Test that expired cards are ordered by frecency and are always suggested // after non expired cards even if they have a higher frecency score. TEST_F(PersonalDataManagerTest, GetCreditCardSuggestions_ExpiredCards) { ASSERT_EQ(0U, personal_data_->GetCreditCards().size()); // Add a never used non expired credit card. CreditCard credit_card0("002149C1-EE28-4213-A3B9-DA243FFF021B", "https://www.example.com"); test::SetCreditCardInfo(&credit_card0, "Bonnie Parker", "518765432109" /* Mastercard */, "04", "2999", "1"); personal_data_->AddCreditCard(credit_card0); // Add an expired card with a higher frecency score. CreditCard credit_card1("287151C8-6AB1-487C-9095-28E80BE5DA15", "https://www.example.com"); test::SetCreditCardInfo(&credit_card1, "Clyde Barrow", "347666888555" /* American Express */, "04", "1999", "1"); credit_card1.set_use_count(300); credit_card1.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(10)); personal_data_->AddCreditCard(credit_card1); // Add an expired card with a lower frecency score. CreditCard credit_card2("1141084B-72D7-4B73-90CF-3D6AC154673B", "https://www.example.com"); credit_card2.set_use_count(3); credit_card2.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(1)); test::SetCreditCardInfo(&credit_card2, "John Dillinger", "423456789012" /* Visa */, "01", "1998", "1"); personal_data_->AddCreditCard(credit_card2); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); ASSERT_EQ(3U, personal_data_->GetCreditCards().size()); std::vector<Suggestion> suggestions = personal_data_->GetCreditCardSuggestions( AutofillType(CREDIT_CARD_NAME_FULL), /* field_contents= */ base::string16()); ASSERT_EQ(3U, suggestions.size()); // The never used non expired card should be suggested first. EXPECT_EQ(base::ASCIIToUTF16("Bonnie Parker"), suggestions[0].value); // The expired cards should be sorted by frecency EXPECT_EQ(base::ASCIIToUTF16("Clyde Barrow"), suggestions[1].value); EXPECT_EQ(base::ASCIIToUTF16("John Dillinger"), suggestions[2].value); } // Test that a card that doesn't have a number is not shown in the suggestions // when querying credit cards by their number. TEST_F(PersonalDataManagerTest, GetCreditCardSuggestions_NumberMissing) { // Create one normal credit card and one credit card with the number missing. ASSERT_EQ(0U, personal_data_->GetCreditCards().size()); CreditCard credit_card0("287151C8-6AB1-487C-9095-28E80BE5DA15", "https://www.example.com"); test::SetCreditCardInfo(&credit_card0, "Clyde Barrow", "347666888555" /* American Express */, "04", "2999", "1"); credit_card0.set_use_count(3); credit_card0.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(1)); personal_data_->AddCreditCard(credit_card0); CreditCard credit_card1("1141084B-72D7-4B73-90CF-3D6AC154673B", "https://www.example.com"); credit_card1.set_use_count(300); credit_card1.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(10)); test::SetCreditCardInfo(&credit_card1, "John Dillinger", "", "01", "2999", "1"); personal_data_->AddCreditCard(credit_card1); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); ASSERT_EQ(2U, personal_data_->GetCreditCards().size()); // Sublabel is expiration date when filling card number. The second card // doesn't have a number so it should not be included in the suggestions. std::vector<Suggestion> suggestions = personal_data_->GetCreditCardSuggestions( AutofillType(CREDIT_CARD_NUMBER), /* field_contents= */ base::string16()); ASSERT_EQ(1U, suggestions.size()); EXPECT_EQ( base::UTF8ToUTF16(std::string("Amex") + kUTF8MidlineEllipsis + "8555"), suggestions[0].value); EXPECT_EQ(base::ASCIIToUTF16("04/99"), suggestions[0].label); } // Tests the suggestions of duplicate local and server credit cards. TEST_F(PersonalDataManagerTest, GetCreditCardSuggestions_ServerDuplicates) { EnableWalletCardImport(); SetupReferenceLocalCreditCards(); // Add some server cards. If there are local dupes, the locals should be // hidden. std::vector<CreditCard> server_cards; // This server card matches a local card, except the local card is missing the // number. This should count as a dupe and thus not be shown in the // suggestions since the locally saved card takes precedence. server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "a123")); test::SetCreditCardInfo(&server_cards.back(), "John Dillinger", "9012" /* Visa */, "01", "2999", "1"); server_cards.back().set_use_count(2); server_cards.back().set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(15)); server_cards.back().SetNetworkForMaskedCard(kVisaCard); // This server card is identical to a local card, but has a different // card type. Not a dupe and therefore both should appear in the suggestions. server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "b456")); test::SetCreditCardInfo(&server_cards.back(), "Bonnie Parker", "2109", "12", "2999", "1"); server_cards.back().set_use_count(3); server_cards.back().set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(15)); server_cards.back().SetNetworkForMaskedCard(kVisaCard); // This unmasked server card is an exact dupe of a local card. Therefore only // this card should appear in the suggestions as full server cards have // precedence over local cards. server_cards.push_back(CreditCard(CreditCard::FULL_SERVER_CARD, "c789")); test::SetCreditCardInfo(&server_cards.back(), "Clyde Barrow", "347666888555" /* American Express */, "04", "2999", "1"); server_cards.back().set_use_count(1); server_cards.back().set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(15)); test::SetServerCreditCards(autofill_table_, server_cards); personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); std::vector<Suggestion> suggestions = personal_data_->GetCreditCardSuggestions( AutofillType(CREDIT_CARD_NAME_FULL), /* field_contents= */ base::string16()); ASSERT_EQ(4U, suggestions.size()); EXPECT_EQ(base::ASCIIToUTF16("John Dillinger"), suggestions[0].value); EXPECT_EQ(base::ASCIIToUTF16("Clyde Barrow"), suggestions[1].value); EXPECT_EQ(base::ASCIIToUTF16("Bonnie Parker"), suggestions[2].value); EXPECT_EQ(base::ASCIIToUTF16("Bonnie Parker"), suggestions[3].value); suggestions = personal_data_->GetCreditCardSuggestions( AutofillType(CREDIT_CARD_NUMBER), /* field_contents= */ base::string16()); ASSERT_EQ(4U, suggestions.size()); EXPECT_EQ( base::UTF8ToUTF16(std::string("Visa") + kUTF8MidlineEllipsis + "9012"), suggestions[0].value); EXPECT_EQ( base::UTF8ToUTF16(std::string("Amex") + kUTF8MidlineEllipsis + "8555"), suggestions[1].value); EXPECT_EQ(base::UTF8ToUTF16(std::string("Mastercard") + kUTF8MidlineEllipsis + "2109"), suggestions[2].value); EXPECT_EQ( base::UTF8ToUTF16(std::string("Visa") + kUTF8MidlineEllipsis + "2109"), suggestions[3].value); } // Tests that a full server card can be a dupe of more than one local card. TEST_F(PersonalDataManagerTest, GetCreditCardSuggestions_ServerCardDuplicateOfMultipleLocalCards) { EnableWalletCardImport(); SetupReferenceLocalCreditCards(); // Add a duplicate server card. std::vector<CreditCard> server_cards; // This unmasked server card is an exact dupe of a local card. Therefore only // the local card should appear in the suggestions. server_cards.push_back(CreditCard(CreditCard::FULL_SERVER_CARD, "c789")); test::SetCreditCardInfo(&server_cards.back(), "Clyde Barrow", "347666888555" /* American Express */, "04", "2999", "1"); test::SetServerCreditCards(autofill_table_, server_cards); personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); std::vector<Suggestion> suggestions = personal_data_->GetCreditCardSuggestions( AutofillType(CREDIT_CARD_NAME_FULL), /* field_contents= */ base::string16()); ASSERT_EQ(3U, suggestions.size()); // Add a second dupe local card to make sure a full server card can be a dupe // of more than one local card. CreditCard credit_card3("4141084B-72D7-4B73-90CF-3D6AC154673B", "https://www.example.com"); test::SetCreditCardInfo(&credit_card3, "Clyde Barrow", "", "04", "", ""); personal_data_->AddCreditCard(credit_card3); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); suggestions = personal_data_->GetCreditCardSuggestions( AutofillType(CREDIT_CARD_NAME_FULL), /* field_contents= */ base::string16()); ASSERT_EQ(3U, suggestions.size()); } // Tests that server cards will shown bank name when bank name available and // feature flag on. TEST_F(PersonalDataManagerTest, GetCreditCardSuggestions_ShowBankNameOfServerCards) { // Turn on feature flag. base::test::ScopedFeatureList scoped_feature_list_; scoped_feature_list_.InitAndEnableFeature(kAutofillCreditCardBankNameDisplay); EnableWalletCardImport(); // Add a local card. CreditCard credit_card0("287151C8-6AB1-487C-9095-28E80BE5DA15", "https://www.example.com"); test::SetCreditCardInfo(&credit_card0, "Clyde Barrow", "347666888555" /* American Express */, "04", "2999", "1"); credit_card0.set_use_count(3); credit_card0.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(1)); personal_data_->AddCreditCard(credit_card0); std::vector<CreditCard> server_cards; // Add a server card without bank name. server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "b459")); test::SetCreditCardInfo(&server_cards.back(), "Emmet Dalton", "2110", "12", "2999", "1"); server_cards.back().set_use_count(2); server_cards.back().set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(1)); server_cards.back().SetNetworkForMaskedCard(kVisaCard); // Add a server card with bank name. server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "b460")); test::SetCreditCardInfo(&server_cards.back(), "Emmet Dalton", "2111", "12", "2999", "1"); server_cards.back().set_use_count(1); server_cards.back().set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(1)); server_cards.back().SetNetworkForMaskedCard(kVisaCard); server_cards.back().set_bank_name("Chase"); test::SetServerCreditCards(autofill_table_, server_cards); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); std::vector<Suggestion> suggestions = personal_data_->GetCreditCardSuggestions( AutofillType(CREDIT_CARD_NUMBER), /* field_contents= */ base::string16()); ASSERT_EQ(3U, suggestions.size()); // Local cards will show network. EXPECT_EQ( base::UTF8ToUTF16(std::string("Amex") + kUTF8MidlineEllipsis + "8555"), suggestions[0].value); // Server card without bank name will show network. EXPECT_EQ( base::UTF8ToUTF16(std::string("Visa") + kUTF8MidlineEllipsis + "2110"), suggestions[1].value); // Server card with bank name will show bank name. EXPECT_EQ( base::UTF8ToUTF16(std::string("Chase") + kUTF8MidlineEllipsis + "2111"), suggestions[2].value); } // Tests that only the full server card is kept when deduping with a local // duplicate of it. TEST_F(PersonalDataManagerTest, DedupeCreditCardToSuggest_FullServerShadowsLocal) { std::list<CreditCard*> credit_cards; // Create 3 different local credit cards. CreditCard local_card("287151C8-6AB1-487C-9095-28E80BE5DA15", "https://www.example.com"); test::SetCreditCardInfo(&local_card, "Homer Simpson", "423456789012" /* Visa */, "01", "2999", "1"); local_card.set_use_count(3); local_card.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(1)); credit_cards.push_back(&local_card); // Create a full server card that is a duplicate of one of the local cards. CreditCard full_server_card(CreditCard::FULL_SERVER_CARD, "c789"); test::SetCreditCardInfo(&full_server_card, "Homer Simpson", "423456789012" /* Visa */, "01", "2999", "1"); full_server_card.set_use_count(1); full_server_card.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(15)); credit_cards.push_back(&full_server_card); PersonalDataManager::DedupeCreditCardToSuggest(&credit_cards); ASSERT_EQ(1U, credit_cards.size()); const CreditCard* deduped_card(credit_cards.front()); EXPECT_TRUE(*deduped_card == full_server_card); } // Tests that only the local card is kept when deduping with a masked server // duplicate of it. TEST_F(PersonalDataManagerTest, DedupeCreditCardToSuggest_LocalShadowsMasked) { std::list<CreditCard*> credit_cards; CreditCard local_card("1141084B-72D7-4B73-90CF-3D6AC154673B", "https://www.example.com"); local_card.set_use_count(300); local_card.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(10)); test::SetCreditCardInfo(&local_card, "Homer Simpson", "423456789012" /* Visa */, "01", "2999", "1"); credit_cards.push_back(&local_card); // Create a masked server card that is a duplicate of a local card. CreditCard masked_card(CreditCard::MASKED_SERVER_CARD, "a123"); test::SetCreditCardInfo(&masked_card, "Homer Simpson", "9012" /* Visa */, "01", "2999", "1"); masked_card.set_use_count(2); masked_card.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(15)); masked_card.SetNetworkForMaskedCard(kVisaCard); credit_cards.push_back(&masked_card); PersonalDataManager::DedupeCreditCardToSuggest(&credit_cards); ASSERT_EQ(1U, credit_cards.size()); const CreditCard* deduped_card(credit_cards.front()); EXPECT_TRUE(*deduped_card == local_card); } // Tests that identical full server and masked credit cards are not deduped. TEST_F(PersonalDataManagerTest, DedupeCreditCardToSuggest_FullServerAndMasked) { std::list<CreditCard*> credit_cards; // Create a full server card that is a duplicate of one of the local cards. CreditCard full_server_card(CreditCard::FULL_SERVER_CARD, "c789"); test::SetCreditCardInfo(&full_server_card, "Homer Simpson", "423456789012" /* Visa */, "01", "2999", "1"); full_server_card.set_use_count(1); full_server_card.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(15)); credit_cards.push_back(&full_server_card); // Create a masked server card that is a duplicate of a local card. CreditCard masked_card(CreditCard::MASKED_SERVER_CARD, "a123"); test::SetCreditCardInfo(&masked_card, "Homer Simpson", "9012" /* Visa */, "01", "2999", "1"); masked_card.set_use_count(2); masked_card.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(15)); masked_card.SetNetworkForMaskedCard(kVisaCard); credit_cards.push_back(&masked_card); PersonalDataManager::DedupeCreditCardToSuggest(&credit_cards); EXPECT_EQ(2U, credit_cards.size()); } // Tests that slightly different local, full server, and masked credit cards are // not deduped. TEST_F(PersonalDataManagerTest, DedupeCreditCardToSuggest_DifferentCards) { std::list<CreditCard*> credit_cards; CreditCard credit_card2("002149C1-EE28-4213-A3B9-DA243FFF021B", "https://www.example.com"); credit_card2.set_use_count(1); credit_card2.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(1)); test::SetCreditCardInfo(&credit_card2, "Homer Simpson", "518765432109" /* Mastercard */, "", "", ""); credit_cards.push_back(&credit_card2); // Create a masked server card that is slightly different of the local card. CreditCard credit_card4(CreditCard::MASKED_SERVER_CARD, "b456"); test::SetCreditCardInfo(&credit_card4, "Homer Simpson", "2109", "12", "2999", "1"); credit_card4.set_use_count(3); credit_card4.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(15)); credit_card4.SetNetworkForMaskedCard(kVisaCard); credit_cards.push_back(&credit_card4); // Create a full server card that is slightly different of the two other // cards. CreditCard credit_card5(CreditCard::FULL_SERVER_CARD, "c789"); test::SetCreditCardInfo(&credit_card5, "Homer Simpson", "347666888555" /* American Express */, "04", "2999", "1"); credit_card5.set_use_count(1); credit_card5.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(15)); credit_cards.push_back(&credit_card5); PersonalDataManager::DedupeCreditCardToSuggest(&credit_cards); EXPECT_EQ(3U, credit_cards.size()); } TEST_F(PersonalDataManagerTest, RecordUseOf) { // Create the test clock and set the time to a specific value. TestAutofillClock test_clock; test_clock.SetNow(kArbitraryTime); AutofillProfile profile(test::GetFullProfile()); EXPECT_EQ(1U, profile.use_count()); EXPECT_EQ(kArbitraryTime, profile.use_date()); EXPECT_EQ(kArbitraryTime, profile.modification_date()); personal_data_->AddProfile(profile); CreditCard credit_card(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&credit_card, "John Dillinger", "423456789012" /* Visa */, "01", "2999", "1"); EXPECT_EQ(1U, credit_card.use_count()); EXPECT_EQ(kArbitraryTime, credit_card.use_date()); EXPECT_EQ(kArbitraryTime, credit_card.modification_date()); personal_data_->AddCreditCard(credit_card); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Set the current time to another value. test_clock.SetNow(kSomeLaterTime); // Notify the PDM that the profile and credit card were used. AutofillProfile* added_profile = personal_data_->GetProfileByGUID(profile.guid()); ASSERT_TRUE(added_profile); EXPECT_EQ(*added_profile, profile); EXPECT_EQ(1U, added_profile->use_count()); EXPECT_EQ(kArbitraryTime, added_profile->use_date()); EXPECT_EQ(kArbitraryTime, added_profile->modification_date()); personal_data_->RecordUseOf(profile); CreditCard* added_card = personal_data_->GetCreditCardByGUID(credit_card.guid()); ASSERT_TRUE(added_card); EXPECT_EQ(*added_card, credit_card); EXPECT_EQ(1U, added_card->use_count()); EXPECT_EQ(kArbitraryTime, added_card->use_date()); EXPECT_EQ(kArbitraryTime, added_card->modification_date()); personal_data_->RecordUseOf(credit_card); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Verify usage stats are updated. added_profile = personal_data_->GetProfileByGUID(profile.guid()); ASSERT_TRUE(added_profile); EXPECT_EQ(2U, added_profile->use_count()); EXPECT_EQ(kSomeLaterTime, added_profile->use_date()); EXPECT_EQ(kArbitraryTime, added_profile->modification_date()); added_card = personal_data_->GetCreditCardByGUID(credit_card.guid()); ASSERT_TRUE(added_card); EXPECT_EQ(2U, added_card->use_count()); EXPECT_EQ(kSomeLaterTime, added_card->use_date()); EXPECT_EQ(kArbitraryTime, added_card->modification_date()); } TEST_F(PersonalDataManagerTest, UpdateServerCreditCardUsageStats) { EnableWalletCardImport(); std::vector<CreditCard> server_cards; server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "a123")); test::SetCreditCardInfo(&server_cards.back(), "John Dillinger", "9012" /* Visa */, "01", "2999", "1"); server_cards.back().SetNetworkForMaskedCard(kVisaCard); server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "b456")); test::SetCreditCardInfo(&server_cards.back(), "Bonnie Parker", "4444" /* Mastercard */, "12", "2999", "1"); server_cards.back().SetNetworkForMaskedCard(kMasterCard); server_cards.push_back(CreditCard(CreditCard::FULL_SERVER_CARD, "c789")); test::SetCreditCardInfo(&server_cards.back(), "Clyde Barrow", "347666888555" /* American Express */, "04", "2999", "1"); // Create the test clock and set the time to a specific value. TestAutofillClock test_clock; test_clock.SetNow(kArbitraryTime); test::SetServerCreditCards(autofill_table_, server_cards); personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); ASSERT_EQ(3U, personal_data_->GetCreditCards().size()); if (!OfferStoreUnmaskedCards()) { for (CreditCard* card : personal_data_->GetCreditCards()) { EXPECT_EQ(CreditCard::MASKED_SERVER_CARD, card->record_type()); } // The rest of this test doesn't work if we're force-masking all unmasked // cards. return; } // The GUIDs will be different, so just compare the data. for (size_t i = 0; i < 3; ++i) EXPECT_EQ(0, server_cards[i].Compare(*personal_data_->GetCreditCards()[i])); CreditCard* unmasked_card = &server_cards.front(); unmasked_card->set_record_type(CreditCard::FULL_SERVER_CARD); unmasked_card->SetNumber(base::ASCIIToUTF16("423456789012")); EXPECT_NE(0, unmasked_card->Compare( *personal_data_->GetCreditCards().front())); personal_data_->UpdateServerCreditCard(*unmasked_card); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); ASSERT_EQ(3U, personal_data_->GetCreditCards().size()); for (size_t i = 0; i < 3; ++i) EXPECT_EQ(0, server_cards[i].Compare(*personal_data_->GetCreditCards()[i])); // For an unmasked card, usage data starts out as 2 because of the unmasking // which is considered a use. The use date should now be the specified Now() // time kArbitraryTime. EXPECT_EQ(2U, personal_data_->GetCreditCards()[0]->use_count()); EXPECT_EQ(kArbitraryTime, personal_data_->GetCreditCards()[0]->use_date()); EXPECT_EQ(1U, personal_data_->GetCreditCards()[1]->use_count()); EXPECT_NE(kArbitraryTime, personal_data_->GetCreditCards()[1]->use_date()); // Having unmasked this card, usage stats should be 2 and // kArbitraryTime. EXPECT_EQ(2U, personal_data_->GetCreditCards()[2]->use_count()); EXPECT_EQ(kArbitraryTime, personal_data_->GetCreditCards()[2]->use_date()); // Change the Now() value for a second time. test_clock.SetNow(kSomeLaterTime); server_cards.back().set_guid(personal_data_->GetCreditCards()[2]->guid()); personal_data_->RecordUseOf(server_cards.back()); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); ASSERT_EQ(3U, personal_data_->GetCreditCards().size()); EXPECT_EQ(2U, personal_data_->GetCreditCards()[0]->use_count()); EXPECT_EQ(kArbitraryTime, personal_data_->GetCreditCards()[0]->use_date()); EXPECT_EQ(1U, personal_data_->GetCreditCards()[1]->use_count()); EXPECT_NE(kArbitraryTime, personal_data_->GetCreditCards()[1]->use_date()); // The RecordUseOf call should have incremented the use_count to 3 and set the // use_date to kSomeLaterTime. EXPECT_EQ(3U, personal_data_->GetCreditCards()[2]->use_count()); EXPECT_EQ(kSomeLaterTime, personal_data_->GetCreditCards()[2]->use_date()); // Can record usage stats on masked cards. server_cards[1].set_guid(personal_data_->GetCreditCards()[1]->guid()); personal_data_->RecordUseOf(server_cards[1]); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); ASSERT_EQ(3U, personal_data_->GetCreditCards().size()); EXPECT_EQ(2U, personal_data_->GetCreditCards()[1]->use_count()); EXPECT_EQ(kSomeLaterTime, personal_data_->GetCreditCards()[1]->use_date()); // Change Now()'s return value for a third time. test_clock.SetNow(kMuchLaterTime); // Upgrading to unmasked retains the usage stats (and increments them). CreditCard* unmasked_card2 = &server_cards[1]; unmasked_card2->set_record_type(CreditCard::FULL_SERVER_CARD); unmasked_card2->SetNumber(base::ASCIIToUTF16("5555555555554444")); personal_data_->UpdateServerCreditCard(*unmasked_card2); server_cards[1].set_guid(personal_data_->GetCreditCards()[1]->guid()); personal_data_->RecordUseOf(server_cards[1]); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); ASSERT_EQ(3U, personal_data_->GetCreditCards().size()); EXPECT_EQ(3U, personal_data_->GetCreditCards()[1]->use_count()); EXPECT_EQ(kMuchLaterTime, personal_data_->GetCreditCards()[1]->use_date()); } TEST_F(PersonalDataManagerTest, ClearAllServerData) { // Add a server card. std::vector<CreditCard> server_cards; server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "a123")); test::SetCreditCardInfo(&server_cards.back(), "John Dillinger", "9012" /* Visa */, "01", "2999", "1"); server_cards.back().SetNetworkForMaskedCard(kVisaCard); test::SetServerCreditCards(autofill_table_, server_cards); personal_data_->Refresh(); // Need to set the google services username EnableWalletCardImport(); // The card and profile should be there. ResetPersonalDataManager(USER_MODE_NORMAL); EXPECT_FALSE(personal_data_->GetCreditCards().empty()); personal_data_->ClearAllServerData(); // Reload the database, everything should be gone. ResetPersonalDataManager(USER_MODE_NORMAL); EXPECT_TRUE(personal_data_->GetCreditCards().empty()); } TEST_F(PersonalDataManagerTest, AllowDuplicateMaskedServerCardIfFlagEnabled) { EnableWalletCardImport(); // Turn on feature flag. base::test::ScopedFeatureList scoped_feature_list_; scoped_feature_list_.InitAndEnableFeature( kAutofillOfferLocalSaveIfServerCardManuallyEntered); std::vector<CreditCard> server_cards; server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "a123")); test::SetCreditCardInfo(&server_cards.back(), "John Dillinger", "1881" /* Visa */, "01", "2999", ""); server_cards.back().SetNetworkForMaskedCard(kVisaCard); server_cards.push_back(CreditCard(CreditCard::FULL_SERVER_CARD, "c789")); test::SetCreditCardInfo(&server_cards.back(), "Clyde Barrow", "347666888555" /* American Express */, "04", "2999", ""); test::SetServerCreditCards(autofill_table_, server_cards); personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // A valid credit card form. A user re-enters one of their masked cards. // We should offer to save locally so that user can fill future credit card // forms without unmasking. FormData form; FormFieldData field; test::CreateTestFormField("Name on card:", "name_on_card", "John Dillinger", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Card Number:", "card_number", "4012888888881881", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Exp Month:", "exp_month", "01", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Exp Year:", "exp_year", "2999", "text", &field); form.fields.push_back(field); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_TRUE(personal_data_->ImportFormData( form_structure, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); ASSERT_TRUE(imported_credit_card); EXPECT_TRUE(imported_credit_card_matches_masked_server_credit_card); personal_data_->SaveImportedCreditCard(*imported_credit_card); // Verify that the web database has been updated and the notification sent. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); CreditCard local_card(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&local_card, "John Dillinger", "4012888888881881", "01", "2999", ""); const std::vector<CreditCard*>& results = personal_data_->GetLocalCreditCards(); ASSERT_EQ(1U, results.size()); EXPECT_EQ(0, local_card.Compare(*results[0])); EXPECT_EQ(3U, personal_data_->GetCreditCards().size()); } TEST_F(PersonalDataManagerTest, DontDuplicateMaskedServerCard) { EnableWalletCardImport(); std::vector<CreditCard> server_cards; server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "a123")); test::SetCreditCardInfo(&server_cards.back(), "John Dillinger", "1881" /* Visa */, "01", "2999", ""); server_cards.back().SetNetworkForMaskedCard(kVisaCard); server_cards.push_back(CreditCard(CreditCard::FULL_SERVER_CARD, "c789")); test::SetCreditCardInfo(&server_cards.back(), "Clyde Barrow", "347666888555" /* American Express */, "04", "2999", ""); test::SetServerCreditCards(autofill_table_, server_cards); personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // A valid credit card form. A user re-enters one of their masked cards. // We should not offer to save locally because the // AutofillOfferLocalSaveIfServerCardManuallyEntered flag is not enabled. FormData form; FormFieldData field; test::CreateTestFormField("Name on card:", "name_on_card", "John Dillinger", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Card Number:", "card_number", "4012888888881881", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Exp Month:", "exp_month", "01", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Exp Year:", "exp_year", "2999", "text", &field); form.fields.push_back(field); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_FALSE(personal_data_->ImportFormData( form_structure, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); ASSERT_FALSE(imported_credit_card); EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); } TEST_F(PersonalDataManagerTest, DontDuplicateFullServerCard) { EnableWalletCardImport(); std::vector<CreditCard> server_cards; server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "a123")); test::SetCreditCardInfo(&server_cards.back(), "John Dillinger", "1881" /* Visa */, "01", "2999", "1"); server_cards.back().SetNetworkForMaskedCard(kVisaCard); server_cards.push_back(CreditCard(CreditCard::FULL_SERVER_CARD, "c789")); test::SetCreditCardInfo(&server_cards.back(), "Clyde Barrow", "347666888555" /* American Express */, "04", "2999", "1"); test::SetServerCreditCards(autofill_table_, server_cards); personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // A user re-types (or fills with) an unmasked card. Don't offer to save // here, either. Since it's unmasked, we know for certain that it's the same // card. FormData form; FormFieldData field; test::CreateTestFormField("Name on card:", "name_on_card", "Clyde Barrow", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Card Number:", "card_number", "347666888555", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Exp Month:", "exp_month", "04", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Exp Year:", "exp_year", "2999", "text", &field); form.fields.push_back(field); FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_FALSE(personal_data_->ImportFormData( form_structure, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); EXPECT_FALSE(imported_credit_card); EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); } TEST_F(PersonalDataManagerTest, Metrics_SubmittedServerCardExpirationStatus_FullServerCardMatch) { EnableWalletCardImport(); std::vector<CreditCard> server_cards; server_cards.push_back(CreditCard(CreditCard::FULL_SERVER_CARD, "c789")); test::SetCreditCardInfo(&server_cards.back(), "Clyde Barrow", "4444333322221111" /* Visa */, "04", "2111", "1"); test::SetServerCreditCards(autofill_table_, server_cards); personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // A user fills/enters the card's information on a checkout form. Ensure that // an expiration date match is recorded. FormData form; FormFieldData field; test::CreateTestFormField("Name on card:", "name_on_card", "Clyde Barrow", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Card Number:", "card_number", "4444333322221111", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Exp Month:", "exp_month", "04", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Exp Year:", "exp_year", "2111", "text", &field); form.fields.push_back(field); base::HistogramTester histogram_tester; FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_FALSE(personal_data_->ImportFormData( form_structure, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); EXPECT_FALSE(imported_credit_card); EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); histogram_tester.ExpectUniqueSample( "Autofill.SubmittedServerCardExpirationStatus", AutofillMetrics::FULL_SERVER_CARD_EXPIRATION_DATE_MATCHED, 1); } TEST_F(PersonalDataManagerTest, Metrics_SubmittedServerCardExpirationStatus_FullServerCardMismatch) { EnableWalletCardImport(); std::vector<CreditCard> server_cards; server_cards.push_back(CreditCard(CreditCard::FULL_SERVER_CARD, "c789")); test::SetCreditCardInfo(&server_cards.back(), "Clyde Barrow", "4444333322221111" /* Visa */, "04", "2111", "1"); test::SetServerCreditCards(autofill_table_, server_cards); personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // A user fills/enters the card's information on a checkout form but changes // the expiration date of the card. Ensure that an expiration date mismatch // is recorded. FormData form; FormFieldData field; test::CreateTestFormField("Name on card:", "name_on_card", "Clyde Barrow", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Card Number:", "card_number", "4444333322221111", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Exp Month:", "exp_month", "04", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Exp Year:", "exp_year", "2345", "text", &field); form.fields.push_back(field); base::HistogramTester histogram_tester; FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_FALSE(personal_data_->ImportFormData( form_structure, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); EXPECT_FALSE(imported_credit_card); EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); histogram_tester.ExpectUniqueSample( "Autofill.SubmittedServerCardExpirationStatus", AutofillMetrics::FULL_SERVER_CARD_EXPIRATION_DATE_DID_NOT_MATCH, 1); } TEST_F(PersonalDataManagerTest, Metrics_SubmittedServerCardExpirationStatus_MaskedServerCardMatch) { EnableWalletCardImport(); std::vector<CreditCard> server_cards; server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "a123")); test::SetCreditCardInfo(&server_cards.back(), "John Dillinger", "1111" /* Visa */, "01", "2111", ""); server_cards.back().SetNetworkForMaskedCard(kVisaCard); test::SetServerCreditCards(autofill_table_, server_cards); personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // A user fills/enters the card's information on a checkout form. Ensure that // an expiration date match is recorded. FormData form; FormFieldData field; test::CreateTestFormField("Name on card:", "name_on_card", "Clyde Barrow", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Card Number:", "card_number", "4444333322221111", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Exp Month:", "exp_month", "01", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Exp Year:", "exp_year", "2111", "text", &field); form.fields.push_back(field); base::HistogramTester histogram_tester; FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_FALSE(personal_data_->ImportFormData( form_structure, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); EXPECT_FALSE(imported_credit_card); EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); histogram_tester.ExpectUniqueSample( "Autofill.SubmittedServerCardExpirationStatus", AutofillMetrics::MASKED_SERVER_CARD_EXPIRATION_DATE_MATCHED, 1); } TEST_F(PersonalDataManagerTest, Metrics_SubmittedServerCardExpirationStatus_MaskedServerCardMismatch) { EnableWalletCardImport(); std::vector<CreditCard> server_cards; server_cards.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "a123")); test::SetCreditCardInfo(&server_cards.back(), "John Dillinger", "1111" /* Visa */, "01", "2111", ""); server_cards.back().SetNetworkForMaskedCard(kVisaCard); test::SetServerCreditCards(autofill_table_, server_cards); personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // A user fills/enters the card's information on a checkout form but changes // the expiration date of the card. Ensure that an expiration date mismatch // is recorded. FormData form; FormFieldData field; test::CreateTestFormField("Name on card:", "name_on_card", "Clyde Barrow", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Card Number:", "card_number", "4444333322221111", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Exp Month:", "exp_month", "04", "text", &field); form.fields.push_back(field); test::CreateTestFormField("Exp Year:", "exp_year", "2345", "text", &field); form.fields.push_back(field); base::HistogramTester histogram_tester; FormStructure form_structure(form); form_structure.DetermineHeuristicTypes(nullptr /* ukm_service */); std::unique_ptr<CreditCard> imported_credit_card; bool imported_credit_card_matches_masked_server_credit_card; EXPECT_FALSE(personal_data_->ImportFormData( form_structure, false, &imported_credit_card, &imported_credit_card_matches_masked_server_credit_card)); EXPECT_FALSE(imported_credit_card); EXPECT_FALSE(imported_credit_card_matches_masked_server_credit_card); histogram_tester.ExpectUniqueSample( "Autofill.SubmittedServerCardExpirationStatus", AutofillMetrics::MASKED_SERVER_CARD_EXPIRATION_DATE_DID_NOT_MATCH, 1); } // Tests the SaveImportedProfile method with different profiles to make sure the // merge logic works correctly. typedef struct { autofill::ServerFieldType field_type; std::string field_value; } ProfileField; typedef std::vector<ProfileField> ProfileFields; typedef struct { // Each test starts with a default pre-existing profile and applies these // changes to it. ProfileFields changes_to_original; // Each test saves a second profile. Applies these changes to the default // values before saving. ProfileFields changes_to_new; // For tests with profile merging, makes sure that these fields' values are // the ones we expect (depending on the test). ProfileFields changed_field_values; } SaveImportedProfileTestCase; class SaveImportedProfileTest : public PersonalDataManagerTestBase, public testing::TestWithParam<SaveImportedProfileTestCase> { public: SaveImportedProfileTest() {} ~SaveImportedProfileTest() override {} void SetUp() override { OSCryptMocker::SetUpWithSingleton(); prefs_ = test::PrefServiceForTesting(); ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); base::FilePath path = temp_dir_.GetPath().AppendASCII("TestWebDB"); web_database_ = new WebDatabaseService(path, base::ThreadTaskRunnerHandle::Get(), base::ThreadTaskRunnerHandle::Get()); // Setup account tracker. signin_client_.reset(new TestSigninClient(prefs_.get())); account_tracker_.reset(new AccountTrackerService()); account_tracker_->Initialize(signin_client_.get()); signin_manager_.reset(new FakeSigninManagerBase(signin_client_.get(), account_tracker_.get())); signin_manager_->Initialize(prefs_.get()); // Hacky: hold onto a pointer but pass ownership. autofill_table_ = new AutofillTable; web_database_->AddTable(std::unique_ptr<WebDatabaseTable>(autofill_table_)); web_database_->LoadDatabase(); autofill_database_service_ = new AutofillWebDataService( web_database_, base::ThreadTaskRunnerHandle::Get(), base::ThreadTaskRunnerHandle::Get(), WebDataServiceBase::ProfileErrorCallback()); autofill_database_service_->Init(); test::DisableSystemServices(prefs_.get()); ResetPersonalDataManager(USER_MODE_NORMAL); // Reset the deduping pref to its default value. personal_data_->pref_service_->SetInteger( prefs::kAutofillLastVersionDeduped, 0); personal_data_->pref_service_->SetBoolean( prefs::kAutofillProfileUseDatesFixed, false); } void TearDown() override { // Order of destruction is important as AutofillManager relies on // PersonalDataManager to be around when it gets destroyed. signin_manager_->Shutdown(); signin_manager_.reset(); account_tracker_->Shutdown(); account_tracker_.reset(); signin_client_.reset(); test::DisableSystemServices(prefs_.get()); OSCryptMocker::TearDown(); } }; TEST_P(SaveImportedProfileTest, SaveImportedProfile) { // Create the test clock. TestAutofillClock test_clock; auto test_case = GetParam(); // Set the time to a specific value. test_clock.SetNow(kArbitraryTime); SetupReferenceProfile(); const std::vector<AutofillProfile*>& initial_profiles = personal_data_->GetProfiles(); // Apply changes to the original profile (if applicable). for (ProfileField change : test_case.changes_to_original) { initial_profiles.front()->SetRawInfo(change.field_type, base::UTF8ToUTF16(change.field_value)); } // Set the time to a bigger value. test_clock.SetNow(kSomeLaterTime); AutofillProfile profile2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile2, "Marion", "Mitchell", "Morrison", "johnwayne@me.xyz", "Fox", "123 Zoo St", "unit 5", "Hollywood", "CA", "91601", "US", "12345678910"); // Apply changes to the second profile (if applicable). for (ProfileField change : test_case.changes_to_new) { profile2.SetRawInfo(change.field_type, base::UTF8ToUTF16(change.field_value)); } personal_data_->SaveImportedProfile(profile2); const std::vector<AutofillProfile*>& saved_profiles = personal_data_->GetProfiles(); // If there are no merge changes to verify, make sure that two profiles were // saved. if (test_case.changed_field_values.empty()) { EXPECT_EQ(2U, saved_profiles.size()); } else { EXPECT_EQ(1U, saved_profiles.size()); // Make sure the new information was merged correctly. for (ProfileField changed_field : test_case.changed_field_values) { EXPECT_EQ(base::UTF8ToUTF16(changed_field.field_value), saved_profiles.front()->GetRawInfo(changed_field.field_type)); } // Verify that the merged profile's use count, use date and modification // date were properly updated. EXPECT_EQ(1U, saved_profiles.front()->use_count()); EXPECT_EQ(kSomeLaterTime, saved_profiles.front()->use_date()); EXPECT_EQ(kSomeLaterTime, saved_profiles.front()->modification_date()); } // Erase the profiles for the next test. ResetProfiles(); } INSTANTIATE_TEST_CASE_P( PersonalDataManagerTest, SaveImportedProfileTest, testing::Values( // Test that saving an identical profile except for the name results // in two profiles being saved. SaveImportedProfileTestCase{ProfileFields(), {{NAME_FIRST, "Marionette"}}}, // Test that saving an identical profile except with the middle name // initial instead of the full middle name results in the profiles // getting merged and the full middle name being kept. SaveImportedProfileTestCase{ProfileFields(), {{NAME_MIDDLE, "M"}}, {{NAME_MIDDLE, "Mitchell"}, {NAME_FULL, "Marion Mitchell Morrison"}}}, // Test that saving an identical profile except with the full middle // name instead of the middle name initial results in the profiles // getting merged and the full middle name replacing the initial. SaveImportedProfileTestCase{{{NAME_MIDDLE, "M"}}, {{NAME_MIDDLE, "Mitchell"}}, {{NAME_MIDDLE, "Mitchell"}}}, // Test that saving an identical profile except with no middle name // results in the profiles getting merged and the full middle name // being kept. SaveImportedProfileTestCase{ProfileFields(), {{NAME_MIDDLE, ""}}, {{NAME_MIDDLE, "Mitchell"}}}, // Test that saving an identical profile except with a middle name // initial results in the profiles getting merged and the middle name // initial being saved. SaveImportedProfileTestCase{{{NAME_MIDDLE, ""}}, {{NAME_MIDDLE, "M"}}, {{NAME_MIDDLE, "M"}}}, // Test that saving an identical profile except with a middle name // results in the profiles getting merged and the full middle name // being saved. SaveImportedProfileTestCase{{{NAME_MIDDLE, ""}}, {{NAME_MIDDLE, "Mitchell"}}, {{NAME_MIDDLE, "Mitchell"}}}, // Test that saving a identical profile except with the full name set // instead of the name parts results in the two profiles being merged // and all the name parts kept and the full name being added. SaveImportedProfileTestCase{ { {NAME_FIRST, "Marion"}, {NAME_MIDDLE, "Mitchell"}, {NAME_LAST, "Morrison"}, {NAME_FULL, ""}, }, { {NAME_FIRST, ""}, {NAME_MIDDLE, ""}, {NAME_LAST, ""}, {NAME_FULL, "Marion Mitchell Morrison"}, }, { {NAME_FIRST, "Marion"}, {NAME_MIDDLE, "Mitchell"}, {NAME_LAST, "Morrison"}, {NAME_FULL, "Marion Mitchell Morrison"}, }, }, // Test that saving a identical profile except with the name parts set // instead of the full name results in the two profiles being merged // and the full name being kept and all the name parts being added. SaveImportedProfileTestCase{ { {NAME_FIRST, ""}, {NAME_MIDDLE, ""}, {NAME_LAST, ""}, {NAME_FULL, "Marion Mitchell Morrison"}, }, { {NAME_FIRST, "Marion"}, {NAME_MIDDLE, "Mitchell"}, {NAME_LAST, "Morrison"}, {NAME_FULL, ""}, }, { {NAME_FIRST, "Marion"}, {NAME_MIDDLE, "Mitchell"}, {NAME_LAST, "Morrison"}, {NAME_FULL, "Marion Mitchell Morrison"}, }, }, // Test that saving a profile that has only a full name set does not // get merged with a profile with only the name parts set if the names // are different. SaveImportedProfileTestCase{ { {NAME_FIRST, "Marion"}, {NAME_MIDDLE, "Mitchell"}, {NAME_LAST, "Morrison"}, {NAME_FULL, ""}, }, { {NAME_FIRST, ""}, {NAME_MIDDLE, ""}, {NAME_LAST, ""}, {NAME_FULL, "John Thompson Smith"}, }, }, // Test that saving a profile that has only the name parts set does // not get merged with a profile with only the full name set if the // names are different. SaveImportedProfileTestCase{ { {NAME_FIRST, ""}, {NAME_MIDDLE, ""}, {NAME_LAST, ""}, {NAME_FULL, "John Thompson Smith"}, }, { {NAME_FIRST, "Marion"}, {NAME_MIDDLE, "Mitchell"}, {NAME_LAST, "Morrison"}, {NAME_FULL, ""}, }, }, // Test that saving an identical profile except for the first address // line results in two profiles being saved. SaveImportedProfileTestCase{ProfileFields(), {{ADDRESS_HOME_LINE1, "123 Aquarium St."}}}, // Test that saving an identical profile except for the second address // line results in two profiles being saved. SaveImportedProfileTestCase{ProfileFields(), {{ADDRESS_HOME_LINE2, "unit 7"}}}, // Tests that saving an identical profile that has a new piece of // information (company name) results in a merge and that the original // empty value gets overwritten by the new information. SaveImportedProfileTestCase{{{COMPANY_NAME, ""}}, ProfileFields(), {{COMPANY_NAME, "Fox"}}}, // Tests that saving an identical profile except a loss of information // results in a merge but the original value is not overwritten (no // information loss). SaveImportedProfileTestCase{ProfileFields(), {{COMPANY_NAME, ""}}, {{COMPANY_NAME, "Fox"}}}, // Tests that saving an identical profile except a slightly different // postal code results in a merge with the new value kept. SaveImportedProfileTestCase{{{ADDRESS_HOME_ZIP, "R2C 0A1"}}, {{ADDRESS_HOME_ZIP, "R2C0A1"}}, {{ADDRESS_HOME_ZIP, "R2C0A1"}}}, SaveImportedProfileTestCase{{{ADDRESS_HOME_ZIP, "R2C0A1"}}, {{ADDRESS_HOME_ZIP, "R2C 0A1"}}, {{ADDRESS_HOME_ZIP, "R2C 0A1"}}}, SaveImportedProfileTestCase{{{ADDRESS_HOME_ZIP, "r2c 0a1"}}, {{ADDRESS_HOME_ZIP, "R2C0A1"}}, {{ADDRESS_HOME_ZIP, "R2C0A1"}}}, // Tests that saving an identical profile plus a new piece of // information on the address line 2 results in a merge and that the // original empty value gets overwritten by the new information. SaveImportedProfileTestCase{{{ADDRESS_HOME_LINE2, ""}}, ProfileFields(), {{ADDRESS_HOME_LINE2, "unit 5"}}}, // Tests that saving an identical profile except a loss of information // on the address line 2 results in a merge but that the original // value gets not overwritten (no information loss). SaveImportedProfileTestCase{ProfileFields(), {{ADDRESS_HOME_LINE2, ""}}, {{ADDRESS_HOME_LINE2, "unit 5"}}}, // Tests that saving an identical except with more punctuation in the // fist address line, while the second is empty, results in a merge // and that the original address gets overwritten. SaveImportedProfileTestCase{ {{ADDRESS_HOME_LINE2, ""}}, {{ADDRESS_HOME_LINE2, ""}, {ADDRESS_HOME_LINE1, "123, Zoo St."}}, {{ADDRESS_HOME_LINE1, "123, Zoo St."}}}, // Tests that saving an identical profile except with less punctuation // in the fist address line, while the second is empty, results in a // merge and that the longer address is retained. SaveImportedProfileTestCase{ {{ADDRESS_HOME_LINE2, ""}, {ADDRESS_HOME_LINE1, "123, Zoo St."}}, {{ADDRESS_HOME_LINE2, ""}}, {{ADDRESS_HOME_LINE1, "123 Zoo St"}}}, // Tests that saving an identical profile except additional // punctuation in the two address lines results in a merge and that // the newer address is retained. SaveImportedProfileTestCase{ProfileFields(), {{ADDRESS_HOME_LINE1, "123, Zoo St."}, {ADDRESS_HOME_LINE2, "unit. 5"}}, {{ADDRESS_HOME_LINE1, "123, Zoo St."}, {ADDRESS_HOME_LINE2, "unit. 5"}}}, // Tests that saving an identical profile except less punctuation in // the two address lines results in a merge and that the newer address // is retained. SaveImportedProfileTestCase{{{ADDRESS_HOME_LINE1, "123, Zoo St."}, {ADDRESS_HOME_LINE2, "unit. 5"}}, ProfileFields(), {{ADDRESS_HOME_LINE1, "123 Zoo St"}, {ADDRESS_HOME_LINE2, "unit 5"}}}, // Tests that saving an identical profile with accented characters in // the two address lines results in a merge and that the newer address // is retained. SaveImportedProfileTestCase{ProfileFields(), {{ADDRESS_HOME_LINE1, "123 Zôö St"}, {ADDRESS_HOME_LINE2, "üñìt 5"}}, {{ADDRESS_HOME_LINE1, "123 Zôö St"}, {ADDRESS_HOME_LINE2, "üñìt 5"}}}, // Tests that saving an identical profile without accented characters // in the two address lines results in a merge and that the newer // address is retained. SaveImportedProfileTestCase{{{ADDRESS_HOME_LINE1, "123 Zôö St"}, {ADDRESS_HOME_LINE2, "üñìt 5"}}, ProfileFields(), {{ADDRESS_HOME_LINE1, "123 Zoo St"}, {ADDRESS_HOME_LINE2, "unit 5"}}}, // Tests that saving an identical profile except that the address line // 1 is in the address line 2 results in a merge and that the // multi-lne address is retained. SaveImportedProfileTestCase{ProfileFields(), {{ADDRESS_HOME_LINE1, "123 Zoo St, unit 5"}, {ADDRESS_HOME_LINE2, ""}}, {{ADDRESS_HOME_LINE1, "123 Zoo St"}, {ADDRESS_HOME_LINE2, "unit 5"}}}, // Tests that saving an identical profile except that the address line // 2 contains part of the old address line 1 results in a merge and // that the original address lines of the reference profile get // overwritten. SaveImportedProfileTestCase{{{ADDRESS_HOME_LINE1, "123 Zoo St, unit 5"}, {ADDRESS_HOME_LINE2, ""}}, ProfileFields(), {{ADDRESS_HOME_LINE1, "123 Zoo St"}, {ADDRESS_HOME_LINE2, "unit 5"}}}, // Tests that saving an identical profile except that the state is the // abbreviation instead of the full form results in a merge and that // the original state gets overwritten. SaveImportedProfileTestCase{{{ADDRESS_HOME_STATE, "California"}}, ProfileFields(), {{ADDRESS_HOME_STATE, "CA"}}}, // Tests that saving an identical profile except that the state is the // full form instead of the abbreviation results in a merge and that // the abbreviated state is retained. SaveImportedProfileTestCase{ProfileFields(), {{ADDRESS_HOME_STATE, "California"}}, {{ADDRESS_HOME_STATE, "CA"}}}, // Tests that saving and identical profile except that the company // name has different punctuation and case results in a merge and that // the syntax of the new profile replaces the old one. SaveImportedProfileTestCase{{{COMPANY_NAME, "Stark inc"}}, {{COMPANY_NAME, "Stark Inc."}}, {{COMPANY_NAME, "Stark Inc."}}})); // Tests that MergeProfile tries to merge the imported profile into the // existing profile in decreasing order of frecency. TEST_F(PersonalDataManagerTest, MergeProfile_Frecency) { // Create two very similar profiles except with different company names. std::unique_ptr<AutofillProfile> profile1 = base::MakeUnique<AutofillProfile>( base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(profile1.get(), "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "SNP", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "US", "12345678910"); AutofillProfile* profile2 = new AutofillProfile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(profile2, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "Fox", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "US", "12345678910"); // Give the "Fox" profile a bigger frecency score. profile2->set_use_count(15); // Create the |existing_profiles| vector. std::vector<std::unique_ptr<AutofillProfile>> existing_profiles; existing_profiles.push_back(std::move(profile1)); existing_profiles.push_back(base::WrapUnique(profile2)); // Create a new imported profile with no company name. AutofillProfile imported_profile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&imported_profile, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "US", "12345678910"); // Merge the imported profile into the existing profiles. std::vector<AutofillProfile> profiles; std::string guid = personal_data_->MergeProfile( imported_profile, &existing_profiles, "US-EN", &profiles); // The new profile should be merged into the "fox" profile. EXPECT_EQ(profile2->guid(), guid); } // Tests that MergeProfile produces a merged profile with the expected usage // statistics. // Flaky on TSan, see crbug.com/686226. #if defined(THREAD_SANITIZER) #define MAYBE_MergeProfile_UsageStats DISABLED_MergeProfile_UsageStats #else #define MAYBE_MergeProfile_UsageStats MergeProfile_UsageStats #endif TEST_F(PersonalDataManagerTest, MAYBE_MergeProfile_UsageStats) { // Create the test clock and set the time to a specific value. TestAutofillClock test_clock; test_clock.SetNow(kArbitraryTime); // Create an initial profile with a use count of 10, an old use date and an // old modification date of 4 days ago. AutofillProfile* profile = new AutofillProfile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(profile, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "SNP", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "US", "12345678910"); profile->set_use_count(4U); EXPECT_EQ(kArbitraryTime, profile->use_date()); EXPECT_EQ(kArbitraryTime, profile->modification_date()); // Create the |existing_profiles| vector. std::vector<std::unique_ptr<AutofillProfile>> existing_profiles; existing_profiles.push_back(base::WrapUnique(profile)); // Change the current date. test_clock.SetNow(kSomeLaterTime); // Create a new imported profile that will get merged with the existing one. AutofillProfile imported_profile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&imported_profile, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "US", "12345678910"); // Change the current date. test_clock.SetNow(kMuchLaterTime); // Merge the imported profile into the existing profiles. std::vector<AutofillProfile> profiles; std::string guid = personal_data_->MergeProfile( imported_profile, &existing_profiles, "US-EN", &profiles); // The new profile should be merged into the existing profile. EXPECT_EQ(profile->guid(), guid); // The use count should have be max(4, 1) => 4. EXPECT_EQ(4U, profile->use_count()); // The use date should be the one of the most recent profile, which is // kSecondArbitraryTime. EXPECT_EQ(kSomeLaterTime, profile->use_date()); // Since the merge is considered a modification, the modification_date should // be set to kMuchLaterTime. EXPECT_EQ(kMuchLaterTime, profile->modification_date()); } // Tests that DedupeProfiles sets the correct profile guids to // delete after merging similar profiles. TEST_F(PersonalDataManagerTest, DedupeProfiles_ProfilesToDelete) { // Create the profile for which to find duplicates. It has the highest // frecency. AutofillProfile* profile1 = new AutofillProfile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(profile1, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "", "742. Evergreen Terrace", "", "Springfield", "IL", "91601", "US", "12345678910"); profile1->set_use_count(9); // Create a different profile that should not be deduped (different address). AutofillProfile* profile2 = new AutofillProfile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(profile2, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "Fox", "1234 Other Street", "", "Springfield", "IL", "91601", "US", "12345678910"); profile2->set_use_count(7); // Create a profile similar to profile1 which should be deduped. AutofillProfile* profile3 = new AutofillProfile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(profile3, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "US", "12345678910"); profile3->set_use_count(5); // Create another different profile that should not be deduped (different // name). AutofillProfile* profile4 = new AutofillProfile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(profile4, "Marjorie", "Jacqueline", "Simpson", "homer.simpson@abc.com", "Fox", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "US", "12345678910"); profile4->set_use_count(3); // Create another profile similar to profile1. Since that one has the lowest // frecency, the result of the merge should be in this profile at the end of // the test. AutofillProfile* profile5 = new AutofillProfile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(profile5, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "Fox", "742 Evergreen Terrace.", "", "Springfield", "IL", "91601", "US", "12345678910"); profile5->set_use_count(1); // Add the profiles. std::vector<std::unique_ptr<AutofillProfile>> existing_profiles; existing_profiles.push_back(base::WrapUnique(profile1)); existing_profiles.push_back(base::WrapUnique(profile2)); existing_profiles.push_back(base::WrapUnique(profile3)); existing_profiles.push_back(base::WrapUnique(profile4)); existing_profiles.push_back(base::WrapUnique(profile5)); // Enable the profile cleanup. EnableAutofillProfileCleanup(); base::HistogramTester histogram_tester; std::unordered_map<std::string, std::string> guids_merge_map; std::unordered_set<AutofillProfile*> profiles_to_delete; personal_data_->DedupeProfiles(&existing_profiles, &profiles_to_delete, &guids_merge_map); // 5 profiles were considered for dedupe. histogram_tester.ExpectUniqueSample( "Autofill.NumberOfProfilesConsideredForDedupe", 5, 1); // 2 profiles were removed (profiles 1 and 3). histogram_tester.ExpectUniqueSample( "Autofill.NumberOfProfilesRemovedDuringDedupe", 2, 1); // Profile1 should be deleted because it was sent as the profile to merge and // thus was merged into profile3 and then into profile5. EXPECT_TRUE(profiles_to_delete.count(profile1)); // Profile3 should be deleted because profile1 was merged into it and the // resulting profile was then merged into profile5. EXPECT_TRUE(profiles_to_delete.count(profile3)); // Only these two profiles should be deleted. EXPECT_EQ(2U, profiles_to_delete.size()); // All profiles should still be present in |existing_profiles|. EXPECT_EQ(5U, existing_profiles.size()); } // Tests that DedupeProfiles sets the correct merge mapping for billing address // id references. TEST_F(PersonalDataManagerTest, DedupeProfiles_GuidsMergeMap) { // Create the profile for which to find duplicates. It has the highest // frecency. AutofillProfile* profile1 = new AutofillProfile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(profile1, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "", "742. Evergreen Terrace", "", "Springfield", "IL", "91601", "US", "12345678910"); profile1->set_use_count(9); // Create a different profile that should not be deduped (different address). AutofillProfile* profile2 = new AutofillProfile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(profile2, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "Fox", "1234 Other Street", "", "Springfield", "IL", "91601", "US", "12345678910"); profile2->set_use_count(7); // Create a profile similar to profile1 which should be deduped. AutofillProfile* profile3 = new AutofillProfile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(profile3, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "US", "12345678910"); profile3->set_use_count(5); // Create another different profile that should not be deduped (different // name). AutofillProfile* profile4 = new AutofillProfile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(profile4, "Marjorie", "Jacqueline", "Simpson", "homer.simpson@abc.com", "Fox", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "US", "12345678910"); profile4->set_use_count(3); // Create another profile similar to profile1. Since that one has the lowest // frecency, the result of the merge should be in this profile at the end of // the test. AutofillProfile* profile5 = new AutofillProfile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(profile5, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "Fox", "742 Evergreen Terrace.", "", "Springfield", "IL", "91601", "US", "12345678910"); profile5->set_use_count(1); // Add the profiles. std::vector<std::unique_ptr<AutofillProfile>> existing_profiles; existing_profiles.push_back(base::WrapUnique(profile1)); existing_profiles.push_back(base::WrapUnique(profile2)); existing_profiles.push_back(base::WrapUnique(profile3)); existing_profiles.push_back(base::WrapUnique(profile4)); existing_profiles.push_back(base::WrapUnique(profile5)); // Enable the profile cleanup. EnableAutofillProfileCleanup(); std::unordered_map<std::string, std::string> guids_merge_map; std::unordered_set<AutofillProfile*> profiles_to_delete; personal_data_->DedupeProfiles(&existing_profiles, &profiles_to_delete, &guids_merge_map); // The two profile merges should be recorded in the map. EXPECT_EQ(2U, guids_merge_map.size()); // Profile 1 was merged into profile 3. ASSERT_TRUE(guids_merge_map.count(profile1->guid())); EXPECT_TRUE(guids_merge_map.at(profile1->guid()) == profile3->guid()); // Profile 3 was merged into profile 5. ASSERT_TRUE(guids_merge_map.count(profile3->guid())); EXPECT_TRUE(guids_merge_map.at(profile3->guid()) == profile5->guid()); } // Tests that UpdateCardsBillingAddressReference sets the correct billing // address id as specified in the map. TEST_F(PersonalDataManagerTest, UpdateCardsBillingAddressReference) { /* The merges will be as follow: A -> B F (not merged) \ -> E / C -> D */ std::unordered_map<std::string, std::string> guids_merge_map; guids_merge_map.insert(std::pair<std::string, std::string>("A", "B")); guids_merge_map.insert(std::pair<std::string, std::string>("C", "D")); guids_merge_map.insert(std::pair<std::string, std::string>("B", "E")); guids_merge_map.insert(std::pair<std::string, std::string>("D", "E")); // Create cards that use A, D, E and F as their billing address id. CreditCard* credit_card1 = new CreditCard(base::GenerateGUID(), "https://www.example.com"); credit_card1->set_billing_address_id("A"); CreditCard* credit_card2 = new CreditCard(base::GenerateGUID(), "https://www.example.com"); credit_card2->set_billing_address_id("D"); CreditCard* credit_card3 = new CreditCard(base::GenerateGUID(), "https://www.example.com"); credit_card3->set_billing_address_id("E"); CreditCard* credit_card4 = new CreditCard(base::GenerateGUID(), "https://www.example.com"); credit_card4->set_billing_address_id("F"); // Add the credit cards to the database. personal_data_->local_credit_cards_.push_back(base::WrapUnique(credit_card1)); personal_data_->server_credit_cards_.push_back( base::WrapUnique(credit_card2)); personal_data_->local_credit_cards_.push_back(base::WrapUnique(credit_card3)); personal_data_->server_credit_cards_.push_back( base::WrapUnique(credit_card4)); personal_data_->UpdateCardsBillingAddressReference(guids_merge_map); // The first card's billing address should now be E. EXPECT_EQ("E", credit_card1->billing_address_id()); // The second card's billing address should now be E. EXPECT_EQ("E", credit_card2->billing_address_id()); // The third card's billing address should still be E. EXPECT_EQ("E", credit_card3->billing_address_id()); // The fourth card's billing address should still be F. EXPECT_EQ("F", credit_card4->billing_address_id()); } // Tests that ApplyDedupingRoutine updates the credit cards' billing address id // based on the deduped profiles. TEST_F(PersonalDataManagerTest, ApplyDedupingRoutine_CardsBillingAddressIdUpdated) { // A set of 6 profiles will be created. They should merge in this way: // 1 -> 2 -> 3 // 4 -> 5 // 6 // Set their frencency score so that profile 3 has a higher score than 5, and // 5 has a higher score than 6. This will ensure a deterministic order when // verifying results. // Create a set of 3 profiles to be merged together. // Create a profile with a higher frecency score. AutofillProfile profile1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile1, "Homer", "J", "Simpson", "homer.simpson@abc.com", "", "742. Evergreen Terrace", "", "Springfield", "IL", "91601", "US", ""); profile1.set_use_count(12); profile1.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(1)); // Create a profile with a medium frecency score. AutofillProfile profile2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile2, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "", "12345678910"); profile2.set_use_count(5); profile2.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(3)); // Create a profile with a lower frecency score. AutofillProfile profile3(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile3, "Homer", "J", "Simpson", "homer.simpson@abc.com", "Fox", "742 Evergreen Terrace.", "", "Springfield", "IL", "91601", "", ""); profile3.set_use_count(3); profile3.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(5)); // Create a set of two profiles to be merged together. // Create a profile with a higher frecency score. AutofillProfile profile4(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile4, "Marge", "B", "Simpson", "marge.simpson@abc.com", "", "742. Evergreen Terrace", "", "Springfield", "IL", "91601", "US", ""); profile4.set_use_count(11); profile4.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(1)); // Create a profile with a lower frecency score. AutofillProfile profile5(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile5, "Marge", "B", "Simpson", "marge.simpson@abc.com", "Fox", "742 Evergreen Terrace.", "", "Springfield", "IL", "91601", "", ""); profile5.set_use_count(5); profile5.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(3)); // Create a unique profile. AutofillProfile profile6(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile6, "Bart", "J", "Simpson", "bart.simpson@abc.com", "Fox", "742 Evergreen Terrace.", "", "Springfield", "IL", "91601", "", ""); profile6.set_use_count(10); profile6.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(1)); // Add three credit cards. Give them a frecency score so that they are // suggested in order (1, 2, 3). This will ensure a deterministic order for // verifying results. CreditCard credit_card1(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&credit_card1, "Clyde Barrow", "347666888555" /* American Express */, "04", "2999", "1"); credit_card1.set_use_count(10); CreditCard credit_card2(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&credit_card2, "John Dillinger", "423456789012" /* Visa */, "01", "2999", "1"); credit_card2.set_use_count(5); CreditCard credit_card3(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&credit_card3, "Bonnie Parker", "518765432109" /* Mastercard */, "12", "2999", "1"); credit_card3.set_use_count(1); // Associate the first card with profile1. credit_card1.set_billing_address_id(profile1.guid()); // Associate the second card with profile4. credit_card2.set_billing_address_id(profile4.guid()); // Associate the third card with profile6. credit_card3.set_billing_address_id(profile6.guid()); personal_data_->AddProfile(profile1); personal_data_->AddProfile(profile2); personal_data_->AddProfile(profile3); personal_data_->AddProfile(profile4); personal_data_->AddProfile(profile5); personal_data_->AddProfile(profile6); personal_data_->AddCreditCard(credit_card1); personal_data_->AddCreditCard(credit_card2); personal_data_->AddCreditCard(credit_card3); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Make sure the 6 profiles and 3 credit cards were saved. EXPECT_EQ(6U, personal_data_->GetProfiles().size()); EXPECT_EQ(3U, personal_data_->GetCreditCards().size()); // Enable the profile cleanup now. Otherwise it would be triggered by the // calls to AddProfile. EnableAutofillProfileCleanup(); EXPECT_TRUE(personal_data_->ApplyDedupingRoutine()); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Get the profiles and cards sorted by frecency to have a deterministic // order. std::vector<AutofillProfile*> profiles = personal_data_->GetProfilesToSuggest(); std::vector<CreditCard*> credit_cards = personal_data_->GetCreditCardsToSuggest(); // |profile1| should have been merged into |profile2| which should then have // been merged into |profile3|. |profile4| should have been merged into // |profile5| and |profile6| should not have merged. Therefore there should be // 3 profile left. ASSERT_EQ(3U, profiles.size()); // Make sure the remaining profiles are the expected ones. EXPECT_EQ(profile3.guid(), profiles[0]->guid()); EXPECT_EQ(profile5.guid(), profiles[1]->guid()); EXPECT_EQ(profile6.guid(), profiles[2]->guid()); // |credit_card1|'s billing address should now be profile 3. EXPECT_EQ(profile3.guid(), credit_cards[0]->billing_address_id()); // |credit_card2|'s billing address should now be profile 5. EXPECT_EQ(profile5.guid(), credit_cards[1]->billing_address_id()); // |credit_card3|'s billing address should still be profile 6. EXPECT_EQ(profile6.guid(), credit_cards[2]->billing_address_id()); } // Tests that ApplyDedupingRoutine merges the profile values correctly, i.e. // never lose information and keep the syntax of the profile with the higher // frecency score. TEST_F(PersonalDataManagerTest, ApplyDedupingRoutine_MergedProfileValues) { // Create a profile with a higher frecency score. AutofillProfile profile1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile1, "Homer", "J", "Simpson", "homer.simpson@abc.com", "", "742. Evergreen Terrace", "", "Springfield", "IL", "91601", "US", ""); profile1.set_use_count(10); profile1.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(1)); // Create a profile with a medium frecency score. AutofillProfile profile2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile2, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "", "12345678910"); profile2.set_use_count(5); profile2.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(3)); // Create a profile with a lower frecency score. AutofillProfile profile3(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile3, "Homer", "J", "Simpson", "homer.simpson@abc.com", "Fox", "742 Evergreen Terrace.", "", "Springfield", "IL", "91601", "", ""); profile3.set_use_count(3); profile3.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(5)); personal_data_->AddProfile(profile1); personal_data_->AddProfile(profile2); personal_data_->AddProfile(profile3); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Make sure the 3 profiles were saved; EXPECT_EQ(3U, personal_data_->GetProfiles().size()); // Enable the profile cleanup now. Otherwise it would be triggered by the // calls to AddProfile. EnableAutofillProfileCleanup(); base::HistogramTester histogram_tester; EXPECT_TRUE(personal_data_->ApplyDedupingRoutine()); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); std::vector<AutofillProfile*> profiles = personal_data_->GetProfiles(); // |profile1| should have been merged into |profile2| which should then have // been merged into |profile3|. Therefore there should only be 1 saved // profile. ASSERT_EQ(1U, profiles.size()); // 3 profiles were considered for dedupe. histogram_tester.ExpectUniqueSample( "Autofill.NumberOfProfilesConsideredForDedupe", 3, 1); // 2 profiles were removed (profiles 1 and 2). histogram_tester.ExpectUniqueSample( "Autofill.NumberOfProfilesRemovedDuringDedupe", 2, 1); // Since profiles with higher frecency scores are merged into profiles with // lower frecency scores, the result of the merge should be contained in // profile3 since it had a lower frecency score compared to profile1. EXPECT_EQ(profile3.guid(), profiles[0]->guid()); // The address syntax that results from the merge should be the one from the // imported profile (highest frecency). EXPECT_EQ(base::UTF8ToUTF16("742. Evergreen Terrace"), profiles[0]->GetRawInfo(ADDRESS_HOME_LINE1)); // The middle name should be full, even if the profile with the higher // frecency only had an initial (no loss of information). EXPECT_EQ(base::UTF8ToUTF16("Jay"), profiles[0]->GetRawInfo(NAME_MIDDLE)); // The specified phone number from profile1 should be kept (no loss of // information). EXPECT_EQ(base::UTF8ToUTF16("12345678910"), profiles[0]->GetRawInfo(PHONE_HOME_WHOLE_NUMBER)); // The specified company name from profile2 should be kept (no loss of // information). EXPECT_EQ(base::UTF8ToUTF16("Fox"), profiles[0]->GetRawInfo(COMPANY_NAME)); // The specified country from the imported profile shoudl be kept (no loss of // information). EXPECT_EQ(base::UTF8ToUTF16("US"), profiles[0]->GetRawInfo(ADDRESS_HOME_COUNTRY)); // The use count that results from the merge should be the max of all the // profiles use counts. EXPECT_EQ(10U, profiles[0]->use_count()); // The use date that results from the merge should be the one from the // profile1 since it was the most recently used profile. EXPECT_LT(profile1.use_date() - base::TimeDelta::FromSeconds(10), profiles[0]->use_date()); } // Tests that ApplyDedupingRoutine only keeps the verified profile with its // original data when deduping with similar profiles, even if it has a higher // frecency score. TEST_F(PersonalDataManagerTest, ApplyDedupingRoutine_VerifiedProfileFirst) { // Create a verified profile with a higher frecency score. AutofillProfile profile1(base::GenerateGUID(), kSettingsOrigin); test::SetProfileInfo(&profile1, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "", "12345678910"); profile1.set_use_count(7); profile1.set_use_date(kMuchLaterTime); // Create a similar non verified profile with a medium frecency score. AutofillProfile profile2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile2, "Homer", "J", "Simpson", "homer.simpson@abc.com", "", "742. Evergreen Terrace", "", "Springfield", "IL", "91601", "US", ""); profile2.set_use_count(5); profile2.set_use_date(kSomeLaterTime); // Create a similar non verified profile with a lower frecency score. AutofillProfile profile3(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile3, "Homer", "J", "Simpson", "homer.simpson@abc.com", "Fox", "742 Evergreen Terrace.", "", "Springfield", "IL", "91601", "", ""); profile3.set_use_count(3); profile3.set_use_date(kArbitraryTime); personal_data_->AddProfile(profile1); personal_data_->AddProfile(profile2); personal_data_->AddProfile(profile3); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Make sure the 3 profiles were saved. EXPECT_EQ(3U, personal_data_->GetProfiles().size()); // Enable the profile cleanup now. Otherwise it would be triggered by the // calls to AddProfile. EnableAutofillProfileCleanup(); base::HistogramTester histogram_tester; EXPECT_TRUE(personal_data_->ApplyDedupingRoutine()); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); std::vector<AutofillProfile*> profiles = personal_data_->GetProfiles(); // |profile2| should have merged with |profile3|. |profile3| // should then have been discarded because it is similar to the verified // |profile1|. ASSERT_EQ(1U, profiles.size()); // 3 profiles were considered for dedupe. histogram_tester.ExpectUniqueSample( "Autofill.NumberOfProfilesConsideredForDedupe", 3, 1); // 2 profile were removed (profiles 2 and 3). histogram_tester.ExpectUniqueSample( "Autofill.NumberOfProfilesRemovedDuringDedupe", 2, 1); // Only the verified |profile1| with its original data should have been kept. EXPECT_EQ(profile1.guid(), profiles[0]->guid()); EXPECT_TRUE(profile1 == *profiles[0]); EXPECT_EQ(profile1.use_count(), profiles[0]->use_count()); EXPECT_EQ(profile1.use_date(), profiles[0]->use_date()); } // Tests that ApplyDedupingRoutine only keeps the verified profile with its // original data when deduping with similar profiles, even if it has a lower // frecency score. TEST_F(PersonalDataManagerTest, ApplyDedupingRoutine_VerifiedProfileLast) { // Create a profile to dedupe with a higher frecency score. AutofillProfile profile1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile1, "Homer", "J", "Simpson", "homer.simpson@abc.com", "", "742. Evergreen Terrace", "", "Springfield", "IL", "91601", "US", ""); profile1.set_use_count(5); profile1.set_use_date(kMuchLaterTime); // Create a similar non verified profile with a medium frecency score. AutofillProfile profile2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile2, "Homer", "J", "Simpson", "homer.simpson@abc.com", "Fox", "742 Evergreen Terrace.", "", "Springfield", "IL", "91601", "", ""); profile2.set_use_count(5); profile2.set_use_date(kSomeLaterTime); // Create a similar verified profile with a lower frecency score. AutofillProfile profile3(base::GenerateGUID(), kSettingsOrigin); test::SetProfileInfo(&profile3, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "", "12345678910"); profile3.set_use_count(3); profile3.set_use_date(kArbitraryTime); personal_data_->AddProfile(profile1); personal_data_->AddProfile(profile2); personal_data_->AddProfile(profile3); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Make sure the 3 profiles were saved. EXPECT_EQ(3U, personal_data_->GetProfiles().size()); // Enable the profile cleanup now. Otherwise it would be triggered by the // calls to AddProfile. EnableAutofillProfileCleanup(); base::HistogramTester histogram_tester; EXPECT_TRUE(personal_data_->ApplyDedupingRoutine()); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); std::vector<AutofillProfile*> profiles = personal_data_->GetProfiles(); // |profile1| should have merged with |profile2|. |profile2| // should then have been discarded because it is similar to the verified // |profile3|. ASSERT_EQ(1U, profiles.size()); // 3 profiles were considered for dedupe. histogram_tester.ExpectUniqueSample( "Autofill.NumberOfProfilesConsideredForDedupe", 3, 1); // 2 profile were removed (profiles 1 and 2). histogram_tester.ExpectUniqueSample( "Autofill.NumberOfProfilesRemovedDuringDedupe", 2, 1); // Only the verified |profile3| with it's original data should have been kept. EXPECT_EQ(profile3.guid(), profiles[0]->guid()); EXPECT_TRUE(profile3 == *profiles[0]); EXPECT_EQ(profile3.use_count(), profiles[0]->use_count()); EXPECT_EQ(profile3.use_date(), profiles[0]->use_date()); } // Tests that ApplyDedupingRoutine does not merge unverified data into // a verified profile. Also tests that two verified profiles don't get merged. TEST_F(PersonalDataManagerTest, ApplyDedupingRoutine_MultipleVerifiedProfiles) { // Create a profile to dedupe with a higher frecency score. AutofillProfile profile1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile1, "Homer", "J", "Simpson", "homer.simpson@abc.com", "", "742. Evergreen Terrace", "", "Springfield", "IL", "91601", "US", ""); profile1.set_use_count(5); profile1.set_use_date(kMuchLaterTime); // Create a similar verified profile with a medium frecency score. AutofillProfile profile2(base::GenerateGUID(), kSettingsOrigin); test::SetProfileInfo(&profile2, "Homer", "J", "Simpson", "homer.simpson@abc.com", "Fox", "742 Evergreen Terrace.", "", "Springfield", "IL", "91601", "", ""); profile2.set_use_count(5); profile2.set_use_date(kSomeLaterTime); // Create a similar verified profile with a lower frecency score. AutofillProfile profile3(base::GenerateGUID(), kSettingsOrigin); test::SetProfileInfo(&profile3, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "", "12345678910"); profile3.set_use_count(3); profile3.set_use_date(kArbitraryTime); personal_data_->AddProfile(profile1); personal_data_->AddProfile(profile2); personal_data_->AddProfile(profile3); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Make sure the 3 profiles were saved. EXPECT_EQ(3U, personal_data_->GetProfiles().size()); // Enable the profile cleanup now. Otherwise it would be triggered by the // calls to AddProfile. EnableAutofillProfileCleanup(); base::HistogramTester histogram_tester; EXPECT_TRUE(personal_data_->ApplyDedupingRoutine()); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Get the profiles, sorted by frecency to have a deterministic order. std::vector<AutofillProfile*> profiles = personal_data_->GetProfilesToSuggest(); // |profile1| should have been discarded because the saved profile with the // highest frecency score is verified (|profile2|). Therefore, |profile1|'s // data should not have been merged with |profile2|'s data. Then |profile2| // should have been compared to |profile3| but they should not have merged // because both profiles are verified. ASSERT_EQ(2U, profiles.size()); // 3 profiles were considered for dedupe. histogram_tester.ExpectUniqueSample( "Autofill.NumberOfProfilesConsideredForDedupe", 3, 1); // 1 profile was removed (|profile1|). histogram_tester.ExpectUniqueSample( "Autofill.NumberOfProfilesRemovedDuringDedupe", 1, 1); EXPECT_EQ(profile2.guid(), profiles[0]->guid()); EXPECT_EQ(profile3.guid(), profiles[1]->guid()); // The profiles should have kept their original data. EXPECT_TRUE(profile2 == *profiles[0]); EXPECT_TRUE(profile3 == *profiles[1]); EXPECT_EQ(profile2.use_count(), profiles[0]->use_count()); EXPECT_EQ(profile3.use_count(), profiles[1]->use_count()); EXPECT_EQ(profile2.use_date(), profiles[0]->use_date()); EXPECT_EQ(profile3.use_date(), profiles[1]->use_date()); } // Tests that ApplyProfileUseDatesFix sets the use date of profiles from an // incorrect value of 0 to [two weeks from now]. Also tests that SetProfiles // does not modify any other profiles. TEST_F(PersonalDataManagerTest, ApplyProfileUseDatesFix) { // Set the kAutofillProfileUseDatesFixed pref to true so that the fix is not // applied just yet. personal_data_->pref_service_->SetBoolean( prefs::kAutofillProfileUseDatesFixed, true); // Create a profile. The use date will be set to now automatically. AutofillProfile profile1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile1, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "SNP", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "US", "12345678910"); profile1.set_use_date(kArbitraryTime); // Create another profile and set its use date to the default value. AutofillProfile profile2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile2, "Marge", "", "Simpson", "homer.simpson@abc.com", "SNP", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "US", "12345678910"); profile2.set_use_date(base::Time()); personal_data_->AddProfile(profile1); personal_data_->AddProfile(profile2); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Get a sorted list of profiles. |profile1| will be first and |profile2| will // be second. std::vector<AutofillProfile*> saved_profiles = personal_data_->GetProfilesToSuggest(); ASSERT_EQ(2U, saved_profiles.size()); // The use dates should not have been modified. EXPECT_EQ(profile1.use_date(), saved_profiles[0]->use_date()); EXPECT_EQ(profile2.use_date(), saved_profiles[1]->use_date()); // Set the pref to false to indicate the fix has never been run. personal_data_->pref_service_->SetBoolean( prefs::kAutofillProfileUseDatesFixed, false); // Create the test clock and set the time to a specific value. TestAutofillClock test_clock; test_clock.SetNow(kSomeLaterTime); personal_data_->ApplyProfileUseDatesFix(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Get a sorted list of profiles. saved_profiles = personal_data_->GetProfilesToSuggest(); ASSERT_EQ(2U, saved_profiles.size()); // |profile1|'s use date should not have been modified. EXPECT_LE(profile1.use_date(), saved_profiles[0]->use_date()); // |profile2|'s use date should have been set to two weeks before now. EXPECT_EQ(kSomeLaterTime - base::TimeDelta::FromDays(14), saved_profiles[1]->use_date()); } // Tests that ApplyProfileUseDatesFix does apply the fix if it's already been // applied. TEST_F(PersonalDataManagerTest, ApplyProfileUseDatesFix_NotAppliedTwice) { // Set the kAutofillProfileUseDatesFixed pref which means the fix has already // been applied. personal_data_->pref_service_->SetBoolean( prefs::kAutofillProfileUseDatesFixed, true); // Create two profiles. AutofillProfile profile1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile1, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "SNP", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "US", "12345678910"); profile1.set_use_date(kArbitraryTime); AutofillProfile profile2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile2, "Marge", "", "Simpson", "homer.simpson@abc.com", "SNP", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "US", "12345678910"); profile2.set_use_date(base::Time()); personal_data_->AddProfile(profile1); personal_data_->AddProfile(profile2); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Get a sorted list of profiles. |profile1| will be first and |profile2| will // be second. std::vector<AutofillProfile*> saved_profiles = personal_data_->GetProfilesToSuggest(); ASSERT_EQ(2U, saved_profiles.size()); // The use dates should not have been modified. EXPECT_EQ(profile1.use_date(), saved_profiles[0]->use_date()); EXPECT_EQ(base::Time(), saved_profiles[1]->use_date()); } // Tests that ApplyDedupingRoutine works as expected in a realistic scenario. // Tests that it merges the diffent set of similar profiles independently and // that the resulting profiles have the right values, has no effect on the other // profiles and that the data of verified profiles is not modified. TEST_F(PersonalDataManagerTest, ApplyDedupingRoutine_MultipleDedupes) { // Create a Homer home profile with a higher frecency score than other Homer // profiles. AutofillProfile Homer1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&Homer1, "Homer", "J", "Simpson", "homer.simpson@abc.com", "", "742. Evergreen Terrace", "", "Springfield", "IL", "91601", "US", ""); Homer1.set_use_count(10); Homer1.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(1)); // Create a Homer home profile with a medium frecency score compared to other // Homer profiles. AutofillProfile Homer2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&Homer2, "Homer", "Jay", "Simpson", "homer.simpson@abc.com", "", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "", "12345678910"); Homer2.set_use_count(5); Homer2.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(3)); // Create a Homer home profile with a lower frecency score than other Homer // profiles. AutofillProfile Homer3(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&Homer3, "Homer", "J", "Simpson", "homer.simpson@abc.com", "Fox", "742 Evergreen Terrace.", "", "Springfield", "IL", "91601", "", ""); Homer3.set_use_count(3); Homer3.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(5)); // Create a Homer work profile (different address). AutofillProfile Homer4(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&Homer4, "Homer", "J", "Simpson", "homer.simpson@abc.com", "Fox", "12 Nuclear Plant.", "", "Springfield", "IL", "91601", "US", "9876543"); Homer4.set_use_count(3); Homer4.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(5)); // Create a Marge profile with a lower frecency score that other Marge // profiles. AutofillProfile Marge1(base::GenerateGUID(), kSettingsOrigin); test::SetProfileInfo(&Marge1, "Marjorie", "J", "Simpson", "marge.simpson@abc.com", "", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "", "12345678910"); Marge1.set_use_count(4); Marge1.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(3)); // Create a verified Marge home profile with a lower frecency score that the // other Marge profile. AutofillProfile Marge2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&Marge2, "Marjorie", "Jacqueline", "Simpson", "marge.simpson@abc.com", "", "742 Evergreen Terrace", "", "Springfield", "IL", "91601", "", "12345678910"); Marge2.set_use_count(2); Marge2.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(3)); // Create a Barney profile (guest user). AutofillProfile Barney(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&Barney, "Barney", "", "Gumble", "barney.gumble@abc.com", "ABC", "123 Other Street", "", "Springfield", "IL", "91601", "", ""); Barney.set_use_count(1); Barney.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(180)); personal_data_->AddProfile(Homer1); personal_data_->AddProfile(Homer2); personal_data_->AddProfile(Homer3); personal_data_->AddProfile(Homer4); personal_data_->AddProfile(Marge1); personal_data_->AddProfile(Marge2); personal_data_->AddProfile(Barney); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Make sure the 7 profiles were saved; EXPECT_EQ(7U, personal_data_->GetProfiles().size()); // Enable the profile cleanup now. Otherwise it would be triggered by the // calls to AddProfile. EnableAutofillProfileCleanup(); base::HistogramTester histogram_tester; // |Homer1| should get merged into |Homer2| which should then be merged into // |Homer3|. |Marge2| should be discarded in favor of |Marge1| which is // verified. |Homer4| and |Barney| should not be deduped at all. EXPECT_TRUE(personal_data_->ApplyDedupingRoutine()); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Get the profiles, sorted by frecency to have a deterministic order. std::vector<AutofillProfile*> profiles = personal_data_->GetProfilesToSuggest(); // The 2 duplicates Homer home profiles with the higher frecency and the // unverified Marge profile should have been deduped. ASSERT_EQ(4U, profiles.size()); // 7 profiles were considered for dedupe. histogram_tester.ExpectUniqueSample( "Autofill.NumberOfProfilesConsideredForDedupe", 7, 1); // 3 profile were removed (|Homer1|, |Homer2| and |Marge2|). histogram_tester.ExpectUniqueSample( "Autofill.NumberOfProfilesRemovedDuringDedupe", 3, 1); // The remaining profiles should be |Homer3|, |Marge1|, |Homer4| and |Barney| // in this order of frecency. EXPECT_EQ(Homer3.guid(), profiles[0]->guid()); EXPECT_EQ(Marge1.guid(), profiles[1]->guid()); EXPECT_EQ(Homer4.guid(), profiles[2]->guid()); EXPECT_EQ(Barney.guid(), profiles[3]->guid()); // |Homer3|'s data: // The address should be saved with the syntax of |Homer1| since it has the // highest frecency score. EXPECT_EQ(base::UTF8ToUTF16("742. Evergreen Terrace"), profiles[0]->GetRawInfo(ADDRESS_HOME_LINE1)); // The middle name should be the full version found in |Homer2|, EXPECT_EQ(base::UTF8ToUTF16("Jay"), profiles[0]->GetRawInfo(NAME_MIDDLE)); // The phone number from |Homer2| should be kept (no loss of information). EXPECT_EQ(base::UTF8ToUTF16("12345678910"), profiles[0]->GetRawInfo(PHONE_HOME_WHOLE_NUMBER)); // The company name from |Homer3| should be kept (no loss of information). EXPECT_EQ(base::UTF8ToUTF16("Fox"), profiles[0]->GetRawInfo(COMPANY_NAME)); // The country from |Homer1| profile should be kept (no loss of information). EXPECT_EQ(base::UTF8ToUTF16("US"), profiles[0]->GetRawInfo(ADDRESS_HOME_COUNTRY)); // The use count that results from the merge should be the max of Homer 1, 2 // and 3's respective use counts. EXPECT_EQ(10U, profiles[0]->use_count()); // The use date that results from the merge should be the one from the // |Homer1| since it was the most recently used profile. EXPECT_LT(Homer1.use_date() - base::TimeDelta::FromSeconds(5), profiles[0]->use_date()); EXPECT_GT(Homer1.use_date() + base::TimeDelta::FromSeconds(5), profiles[0]->use_date()); // The other profiles should not have been modified. EXPECT_TRUE(Marge1 == *profiles[1]); EXPECT_TRUE(Homer4 == *profiles[2]); EXPECT_TRUE(Barney == *profiles[3]); } // Tests that ApplyDedupingRoutine is not run if the feature is disabled. TEST_F(PersonalDataManagerTest, ApplyDedupingRoutine_FeatureDisabled) { // Create a profile to dedupe. AutofillProfile profile1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile1, "Homer", "J", "Simpson", "homer.simpson@abc.com", "", "742. Evergreen Terrace", "", "Springfield", "IL", "91601", "US", ""); // Create a similar profile. AutofillProfile profile2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile2, "Homer", "J", "Simpson", "homer.simpson@abc.com", "Fox", "742 Evergreen Terrace.", "", "Springfield", "IL", "91601", "", ""); personal_data_->AddProfile(profile1); personal_data_->AddProfile(profile2); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Make sure both profiles were saved. EXPECT_EQ(2U, personal_data_->GetProfiles().size()); // The deduping routine should not be run. EXPECT_FALSE(personal_data_->ApplyDedupingRoutine()); // Both profiles should still be present. EXPECT_EQ(2U, personal_data_->GetProfiles().size()); } TEST_F(PersonalDataManagerTest, ApplyDedupingRoutine_NopIfZeroProfiles) { EXPECT_TRUE(personal_data_->GetProfiles().empty()); EnableAutofillProfileCleanup(); EXPECT_FALSE(personal_data_->ApplyDedupingRoutine()); } TEST_F(PersonalDataManagerTest, ApplyDedupingRoutine_NopIfOneProfile) { // Create a profile to dedupe. AutofillProfile profile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile, "Homer", "J", "Simpson", "homer.simpson@abc.com", "", "742. Evergreen Terrace", "", "Springfield", "IL", "91601", "US", ""); personal_data_->AddProfile(profile); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); EXPECT_EQ(1U, personal_data_->GetProfiles().size()); // Enable the profile cleanup now. Otherwise it would be triggered by the // calls to AddProfile. EnableAutofillProfileCleanup(); EXPECT_FALSE(personal_data_->ApplyDedupingRoutine()); } // Tests that ApplyDedupingRoutine is not run a second time on the same major // version. TEST_F(PersonalDataManagerTest, ApplyDedupingRoutine_OncePerVersion) { // Create a profile to dedupe. AutofillProfile profile1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile1, "Homer", "J", "Simpson", "homer.simpson@abc.com", "", "742. Evergreen Terrace", "", "Springfield", "IL", "91601", "US", ""); // Create a similar profile. AutofillProfile profile2(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile2, "Homer", "J", "Simpson", "homer.simpson@abc.com", "Fox", "742 Evergreen Terrace.", "", "Springfield", "IL", "91601", "", ""); personal_data_->AddProfile(profile1); personal_data_->AddProfile(profile2); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); EXPECT_EQ(2U, personal_data_->GetProfiles().size()); // Enable the profile cleanup now. Otherwise it would be triggered by the // calls to AddProfile. EnableAutofillProfileCleanup(); // The deduping routine should be run a first time. EXPECT_TRUE(personal_data_->ApplyDedupingRoutine()); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); std::vector<AutofillProfile*> profiles = personal_data_->GetProfiles(); // The profiles should have been deduped EXPECT_EQ(1U, profiles.size()); // Add another duplicate profile. AutofillProfile profile3(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile3, "Homer", "J", "Simpson", "homer.simpson@abc.com", "Fox", "742 Evergreen Terrace.", "", "Springfield", "IL", "91601", "", ""); personal_data_->AddProfile(profile3); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Make sure |profile3| was saved. EXPECT_EQ(2U, personal_data_->GetProfiles().size()); // Re-enable the profile cleanup now that the profile was added. EnableAutofillProfileCleanup(); // The deduping routine should not be run. EXPECT_FALSE(personal_data_->ApplyDedupingRoutine()); // The two duplicate profiles should still be present. EXPECT_EQ(2U, personal_data_->GetProfiles().size()); } // Tests that a new local profile is created if no existing one is a duplicate // of the server address. Also tests that the billing address relationship was // transferred to the converted address. TEST_F(PersonalDataManagerTest, ConvertWalletAddressesAndUpdateWalletCards_NewProfile) { /////////////////////////////////////////////////////////////////////// // Setup. /////////////////////////////////////////////////////////////////////// EnableWalletCardImport(); base::HistogramTester histogram_tester; const std::string kServerAddressId("server_address1"); // Add two different profiles, a local and a server one. Set the use stats so // the server profile has a higher frecency, to have a predictable ordering to // validate results. AutofillProfile local_profile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&local_profile, "Josephine", "Alicia", "Saenz", "joewayne@me.xyz", "Fox", "1212 Center.", "Bld. 5", "Orlando", "FL", "32801", "US", "19482937549"); local_profile.set_use_count(1); personal_data_->AddProfile(local_profile); // Add a different server profile. std::vector<AutofillProfile> GetServerProfiles; GetServerProfiles.push_back( AutofillProfile(AutofillProfile::SERVER_PROFILE, kServerAddressId)); test::SetProfileInfo(&GetServerProfiles.back(), "John", "", "Doe", "", "ACME Corp", "500 Oak View", "Apt 8", "Houston", "TX", "77401", "US", ""); // Wallet only provides a full name, so the above first and last names // will be ignored when the profile is written to the DB. GetServerProfiles.back().SetRawInfo(NAME_FULL, base::ASCIIToUTF16("John Doe")); GetServerProfiles.back().set_use_count(100); autofill_table_->SetServerProfiles(GetServerProfiles); // Add a server and a local card that have the server address as billing // address. CreditCard local_card("287151C8-6AB1-487C-9095-28E80BE5DA15", "https://www.example.com"); test::SetCreditCardInfo(&local_card, "Clyde Barrow", "347666888555" /* American Express */, "04", "2999", "1"); local_card.set_billing_address_id(kServerAddressId); personal_data_->AddCreditCard(local_card); std::vector<CreditCard> server_cards; server_cards.push_back( CreditCard(CreditCard::MASKED_SERVER_CARD, "server_card1")); test::SetCreditCardInfo(&server_cards.back(), "John Dillinger", "1111" /* Visa */, "01", "2999", "1"); server_cards.back().SetNetworkForMaskedCard(kVisaCard); server_cards.back().set_billing_address_id(kServerAddressId); test::SetServerCreditCards(autofill_table_, server_cards); // Make sure everything is setup correctly. personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); EXPECT_EQ(1U, personal_data_->web_profiles().size()); EXPECT_EQ(1U, personal_data_->GetServerProfiles().size()); EXPECT_EQ(2U, personal_data_->GetCreditCards().size()); /////////////////////////////////////////////////////////////////////// // Tested method. /////////////////////////////////////////////////////////////////////// personal_data_->ConvertWalletAddressesAndUpdateWalletCards(); /////////////////////////////////////////////////////////////////////// // Validation. /////////////////////////////////////////////////////////////////////// EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // The Wallet address should have been added as a new local profile. EXPECT_EQ(2U, personal_data_->web_profiles().size()); EXPECT_EQ(1U, personal_data_->GetServerProfiles().size()); histogram_tester.ExpectUniqueSample("Autofill.WalletAddressConversionType", AutofillMetrics::CONVERTED_ADDRESS_ADDED, 1); // The conversion should be recorded in the Wallet address. EXPECT_TRUE(personal_data_->GetServerProfiles().back()->has_converted()); // Get the profiles, sorted by frecency to have a deterministic order. std::vector<AutofillProfile*> profiles = personal_data_->GetProfilesToSuggest(); // Make sure that the two profiles have not merged. ASSERT_EQ(2U, profiles.size()); EXPECT_EQ(base::UTF8ToUTF16("John"), profiles[0]->GetRawInfo(NAME_FIRST)); EXPECT_EQ(local_profile, *profiles[1]); // Make sure that the billing address id of the two cards now point to the // converted profile. EXPECT_EQ(profiles[0]->guid(), personal_data_->GetCreditCards()[0]->billing_address_id()); EXPECT_EQ(profiles[0]->guid(), personal_data_->GetCreditCards()[1]->billing_address_id()); // Make sure that the added address has the email address of the currently // signed-in user. EXPECT_EQ(base::UTF8ToUTF16("syncuser@example.com"), profiles[0]->GetRawInfo(EMAIL_ADDRESS)); } // Tests that the converted wallet address is merged into an existing local // profile if they are considered equivalent. Also tests that the billing // address relationship was transferred to the converted address. TEST_F(PersonalDataManagerTest, ConvertWalletAddressesAndUpdateWalletCards_MergedProfile) { /////////////////////////////////////////////////////////////////////// // Setup. /////////////////////////////////////////////////////////////////////// EnableWalletCardImport(); base::HistogramTester histogram_tester; const std::string kServerAddressId("server_address1"); // Add two similar profile, a local and a server one. Set the use stats so // the server card has a higher frecency, to have a predicatble ordering to // validate results. // Add a local profile. AutofillProfile local_profile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&local_profile, "John", "", "Doe", "john@doe.com", "", "1212 Center.", "Bld. 5", "Orlando", "FL", "32801", "US", "19482937549"); local_profile.set_use_count(1); personal_data_->AddProfile(local_profile); // Add a different server profile. std::vector<AutofillProfile> GetServerProfiles; GetServerProfiles.push_back( AutofillProfile(AutofillProfile::SERVER_PROFILE, kServerAddressId)); test::SetProfileInfo(&GetServerProfiles.back(), "John", "", "Doe", "", "Fox", "1212 Center", "Bld. 5", "Orlando", "FL", "", "US", ""); // Wallet only provides a full name, so the above first and last names // will be ignored when the profile is written to the DB. GetServerProfiles.back().SetRawInfo(NAME_FULL, base::ASCIIToUTF16("John Doe")); GetServerProfiles.back().set_use_count(100); autofill_table_->SetServerProfiles(GetServerProfiles); // Add a server and a local card that have the server address as billing // address. CreditCard local_card("287151C8-6AB1-487C-9095-28E80BE5DA15", "https://www.example.com"); test::SetCreditCardInfo(&local_card, "Clyde Barrow", "347666888555" /* American Express */, "04", "2999", "1"); local_card.set_billing_address_id(kServerAddressId); personal_data_->AddCreditCard(local_card); std::vector<CreditCard> server_cards; server_cards.push_back( CreditCard(CreditCard::MASKED_SERVER_CARD, "server_card1")); test::SetCreditCardInfo(&server_cards.back(), "John Dillinger", "1111" /* Visa */, "01", "2999", "1"); server_cards.back().SetNetworkForMaskedCard(kVisaCard); server_cards.back().set_billing_address_id(kServerAddressId); test::SetServerCreditCards(autofill_table_, server_cards); // Make sure everything is setup correctly. personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); EXPECT_EQ(1U, personal_data_->web_profiles().size()); EXPECT_EQ(1U, personal_data_->GetServerProfiles().size()); EXPECT_EQ(2U, personal_data_->GetCreditCards().size()); /////////////////////////////////////////////////////////////////////// // Tested method. /////////////////////////////////////////////////////////////////////// personal_data_->ConvertWalletAddressesAndUpdateWalletCards(); /////////////////////////////////////////////////////////////////////// // Validation. /////////////////////////////////////////////////////////////////////// EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // The Wallet address should have been merged with the existing local profile. EXPECT_EQ(1U, personal_data_->web_profiles().size()); EXPECT_EQ(1U, personal_data_->GetServerProfiles().size()); histogram_tester.ExpectUniqueSample("Autofill.WalletAddressConversionType", AutofillMetrics::CONVERTED_ADDRESS_MERGED, 1); // The conversion should be recorded in the Wallet address. EXPECT_TRUE(personal_data_->GetServerProfiles().back()->has_converted()); // Get the profiles, sorted by frecency to have a deterministic order. std::vector<AutofillProfile*> profiles = personal_data_->GetProfilesToSuggest(); // Make sure that the two profiles have merged. ASSERT_EQ(1U, profiles.size()); // Check that the values were merged. EXPECT_EQ(base::UTF8ToUTF16("john@doe.com"), profiles[0]->GetRawInfo(EMAIL_ADDRESS)); EXPECT_EQ(base::UTF8ToUTF16("Fox"), profiles[0]->GetRawInfo(COMPANY_NAME)); EXPECT_EQ(base::UTF8ToUTF16("32801"), profiles[0]->GetRawInfo(ADDRESS_HOME_ZIP)); // Make sure that the billing address id of the two cards now point to the // converted profile. EXPECT_EQ(profiles[0]->guid(), personal_data_->GetCreditCards()[0]->billing_address_id()); EXPECT_EQ(profiles[0]->guid(), personal_data_->GetCreditCards()[1]->billing_address_id()); } // Tests that a Wallet address that has already converted does not get converted // a second time. TEST_F(PersonalDataManagerTest, ConvertWalletAddressesAndUpdateWalletCards_AlreadyConverted) { /////////////////////////////////////////////////////////////////////// // Setup. /////////////////////////////////////////////////////////////////////// EnableWalletCardImport(); base::HistogramTester histogram_tester; const std::string kServerAddressId("server_address1"); // Add a server profile that has already been converted. std::vector<AutofillProfile> GetServerProfiles; GetServerProfiles.push_back( AutofillProfile(AutofillProfile::SERVER_PROFILE, kServerAddressId)); test::SetProfileInfo(&GetServerProfiles.back(), "John", "Ray", "Doe", "john@doe.com", "Fox", "1212 Center", "Bld. 5", "Orlando", "FL", "32801", "US", ""); GetServerProfiles.back().set_has_converted(true); // Wallet only provides a full name, so the above first and last names // will be ignored when the profile is written to the DB. autofill_table_->SetServerProfiles(GetServerProfiles); // Make sure everything is setup correctly. personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); EXPECT_EQ(0U, personal_data_->web_profiles().size()); EXPECT_EQ(1U, personal_data_->GetServerProfiles().size()); /////////////////////////////////////////////////////////////////////// // Tested method. /////////////////////////////////////////////////////////////////////// personal_data_->ConvertWalletAddressesAndUpdateWalletCards(); /////////////////////////////////////////////////////////////////////// // Validation. /////////////////////////////////////////////////////////////////////// // Since there should be no change in data, OnPersonalDataChanged should not // have been called. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()).Times(0); personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // There should be no local profiles added. EXPECT_EQ(0U, personal_data_->web_profiles().size()); EXPECT_EQ(1U, personal_data_->GetServerProfiles().size()); } // Tests that when the user has multiple similar Wallet addresses, they get // merged into a single local profile, and that the billing address relationship // is merged too. TEST_F( PersonalDataManagerTest, ConvertWalletAddressesAndUpdateWalletCards_MultipleSimilarWalletAddresses) { /////////////////////////////////////////////////////////////////////// // Setup. /////////////////////////////////////////////////////////////////////// EnableWalletCardImport(); base::HistogramTester histogram_tester; const std::string kServerAddressId("server_address1"); const std::string kServerAddressId2("server_address2"); // Add a unique local profile and two similar server profiles. Set the use // stats to have a predicatble ordering to validate results. // Add a local profile. AutofillProfile local_profile(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&local_profile, "Bob", "", "Doe", "", "Fox", "1212 Center.", "Bld. 5", "Orlando", "FL", "32801", "US", "19482937549"); local_profile.set_use_count(1); personal_data_->AddProfile(local_profile); // Add a server profile. std::vector<AutofillProfile> GetServerProfiles; GetServerProfiles.push_back( AutofillProfile(AutofillProfile::SERVER_PROFILE, kServerAddressId)); test::SetProfileInfo(&GetServerProfiles.back(), "John", "", "Doe", "", "", "1212 Center", "Bld. 5", "Orlando", "FL", "32801", "US", ""); // Wallet only provides a full name, so the above first and last names // will be ignored when the profile is written to the DB. GetServerProfiles.back().SetRawInfo(NAME_FULL, base::ASCIIToUTF16("John Doe")); GetServerProfiles.back().set_use_count(100); // Add a similar server profile. GetServerProfiles.push_back( AutofillProfile(AutofillProfile::SERVER_PROFILE, kServerAddressId2)); test::SetProfileInfo(&GetServerProfiles.back(), "John", "", "Doe", "john@doe.com", "Fox", "1212 Center", "Bld. 5", "Orlando", "FL", "", "US", ""); // Wallet only provides a full name, so the above first and last names // will be ignored when the profile is written to the DB. GetServerProfiles.back().SetRawInfo(NAME_FULL, base::ASCIIToUTF16("John Doe")); GetServerProfiles.back().set_use_count(200); autofill_table_->SetServerProfiles(GetServerProfiles); // Add a server and a local card that have the first and second Wallet address // as a billing address. CreditCard local_card("287151C8-6AB1-487C-9095-28E80BE5DA15", "https://www.example.com"); test::SetCreditCardInfo(&local_card, "Clyde Barrow", "347666888555" /* American Express */, "04", "2999", "1"); local_card.set_billing_address_id(kServerAddressId); personal_data_->AddCreditCard(local_card); std::vector<CreditCard> server_cards; server_cards.push_back( CreditCard(CreditCard::MASKED_SERVER_CARD, "server_card1")); test::SetCreditCardInfo(&server_cards.back(), "John Dillinger", "1111" /* Visa */, "01", "2999", "1"); server_cards.back().SetNetworkForMaskedCard(kVisaCard); server_cards.back().set_billing_address_id(kServerAddressId2); test::SetServerCreditCards(autofill_table_, server_cards); // Make sure everything is setup correctly. personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); EXPECT_EQ(1U, personal_data_->web_profiles().size()); EXPECT_EQ(2U, personal_data_->GetServerProfiles().size()); EXPECT_EQ(2U, personal_data_->GetCreditCards().size()); /////////////////////////////////////////////////////////////////////// // Tested method. /////////////////////////////////////////////////////////////////////// personal_data_->ConvertWalletAddressesAndUpdateWalletCards(); /////////////////////////////////////////////////////////////////////// // Validation. /////////////////////////////////////////////////////////////////////// EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // The first Wallet address should have been added as a new local profile and // the second one should have merged with the first. EXPECT_EQ(2U, personal_data_->web_profiles().size()); EXPECT_EQ(2U, personal_data_->GetServerProfiles().size()); histogram_tester.ExpectBucketCount("Autofill.WalletAddressConversionType", AutofillMetrics::CONVERTED_ADDRESS_ADDED, 1); histogram_tester.ExpectBucketCount("Autofill.WalletAddressConversionType", AutofillMetrics::CONVERTED_ADDRESS_MERGED, 1); // The conversion should be recorded in the Wallet addresses. EXPECT_TRUE(personal_data_->GetServerProfiles()[0]->has_converted()); EXPECT_TRUE(personal_data_->GetServerProfiles()[1]->has_converted()); // Get the profiles, sorted by frecency to have a deterministic order. std::vector<AutofillProfile*> profiles = personal_data_->GetProfilesToSuggest(); // Make sure that the two Wallet addresses merged together and were added as // a new local profile. ASSERT_EQ(2U, profiles.size()); EXPECT_EQ(base::UTF8ToUTF16("John"), profiles[0]->GetRawInfo(NAME_FIRST)); EXPECT_EQ(local_profile, *profiles[1]); // Check that the values were merged. EXPECT_EQ(base::UTF8ToUTF16("Fox"), profiles[0]->GetRawInfo(COMPANY_NAME)); EXPECT_EQ(base::UTF8ToUTF16("32801"), profiles[0]->GetRawInfo(ADDRESS_HOME_ZIP)); // Make sure that the billing address id of the two cards now point to the // converted profile. EXPECT_EQ(profiles[0]->guid(), personal_data_->GetCreditCards()[0]->billing_address_id()); EXPECT_EQ(profiles[0]->guid(), personal_data_->GetCreditCards()[1]->billing_address_id()); } // Tests a new server card's billing address is updated propely even if the // address was already converted in the past. TEST_F( PersonalDataManagerTest, ConvertWalletAddressesAndUpdateWalletCards_NewCrd_AddressAlreadyConverted) { /////////////////////////////////////////////////////////////////////// // Setup. /////////////////////////////////////////////////////////////////////// // Go through the conversion process for a server address and card. Then add // a new server card that refers to the already converted server address as // its billing address. EnableWalletCardImport(); base::HistogramTester histogram_tester; const std::string kServerAddressId("server_address1"); // Add a server profile. std::vector<AutofillProfile> GetServerProfiles; GetServerProfiles.push_back( AutofillProfile(AutofillProfile::SERVER_PROFILE, kServerAddressId)); test::SetProfileInfo(&GetServerProfiles.back(), "John", "", "Doe", "", "Fox", "1212 Center", "Bld. 5", "Orlando", "FL", "", "US", ""); // Wallet only provides a full name, so the above first and last names // will be ignored when the profile is written to the DB. GetServerProfiles.back().SetRawInfo(NAME_FULL, base::ASCIIToUTF16("John Doe")); GetServerProfiles.back().set_use_count(100); autofill_table_->SetServerProfiles(GetServerProfiles); // Add a server card that have the server address as billing address. std::vector<CreditCard> server_cards; server_cards.push_back( CreditCard(CreditCard::MASKED_SERVER_CARD, "server_card1")); test::SetCreditCardInfo(&server_cards.back(), "John Dillinger", "1111" /* Visa */, "01", "2999", "1"); server_cards.back().SetNetworkForMaskedCard(kVisaCard); server_cards.back().set_billing_address_id(kServerAddressId); test::SetServerCreditCards(autofill_table_, server_cards); // Make sure everything is setup correctly. personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); EXPECT_EQ(1U, personal_data_->GetServerProfiles().size()); EXPECT_EQ(1U, personal_data_->GetCreditCards().size()); // Run the conversion. personal_data_->ConvertWalletAddressesAndUpdateWalletCards(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // The Wallet address should have been converted to a new local profile. EXPECT_EQ(1U, personal_data_->web_profiles().size()); // The conversion should be recorded in the Wallet address. EXPECT_TRUE(personal_data_->GetServerProfiles().back()->has_converted()); // Make sure that the billing address id of the card now point to the // converted profile. std::vector<AutofillProfile*> profiles = personal_data_->GetProfilesToSuggest(); ASSERT_EQ(1U, profiles.size()); EXPECT_EQ(profiles[0]->guid(), personal_data_->GetCreditCards()[0]->billing_address_id()); // Add a new server card that has the same billing address as the old one. server_cards.push_back( CreditCard(CreditCard::MASKED_SERVER_CARD, "server_card2")); test::SetCreditCardInfo(&server_cards.back(), "John Dillinger", "1112" /* Visa */, "01", "2888", "1"); server_cards.back().SetNetworkForMaskedCard(kVisaCard); server_cards.back().set_billing_address_id(kServerAddressId); test::SetServerCreditCards(autofill_table_, server_cards); // Make sure everything is setup correctly. personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); EXPECT_EQ(1U, personal_data_->web_profiles().size()); EXPECT_EQ(2U, personal_data_->GetCreditCards().size()); /////////////////////////////////////////////////////////////////////// // Tested method. /////////////////////////////////////////////////////////////////////// personal_data_->ConvertWalletAddressesAndUpdateWalletCards(); /////////////////////////////////////////////////////////////////////// // Validation. /////////////////////////////////////////////////////////////////////// EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // The conversion should still be recorded in the Wallet address. EXPECT_TRUE(personal_data_->GetServerProfiles().back()->has_converted()); // Get the profiles, sorted by frecency to have a deterministic order. profiles = personal_data_->GetProfilesToSuggest(); // Make sure that there is still only one profile. ASSERT_EQ(1U, profiles.size()); // Make sure that the billing address id of the first server card still refers // to the converted address. EXPECT_EQ(profiles[0]->guid(), personal_data_->GetCreditCards()[0]->billing_address_id()); // Make sure that the billing address id of the new server card still refers // to the converted address. EXPECT_EQ(profiles[0]->guid(), personal_data_->GetCreditCards()[1]->billing_address_id()); } TEST_F(PersonalDataManagerTest, RemoveByGUID_ResetsBillingAddress) { /////////////////////////////////////////////////////////////////////// // Setup. /////////////////////////////////////////////////////////////////////// EnableWalletCardImport(); std::vector<CreditCard> server_cards; // Add two different profiles AutofillProfile profile0(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile0, "Bob", "", "Doe", "", "Fox", "1212 Center.", "Bld. 5", "Orlando", "FL", "32801", "US", "19482937549"); AutofillProfile profile1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile1, "Seb", "", "Doe", "", "ACME", "1234 Evergreen Terrace", "Bld. 5", "Springfield", "IL", "32801", "US", "15151231234"); // Add a local and a server card that have profile0 as their billing address. CreditCard local_card0(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&local_card0, "John Dillinger", "4111111111111111" /* Visa */, "01", "2999", profile0.guid()); CreditCard server_card0(CreditCard::FULL_SERVER_CARD, "c789"); test::SetCreditCardInfo(&server_card0, "John Barrow", "347666888555" /* American Express */, "04", "2999", profile0.guid()); server_cards.push_back(server_card0); // Do the same but for profile1. CreditCard local_card1(base::GenerateGUID(), "https://www.example.com"); test::SetCreditCardInfo(&local_card1, "Seb Dillinger", "4111111111111111" /* Visa */, "01", "2999", profile1.guid()); CreditCard server_card1(CreditCard::FULL_SERVER_CARD, "c789"); test::SetCreditCardInfo(&server_card1, "John Barrow", "347666888555" /* American Express */, "04", "2999", profile1.guid()); server_cards.push_back(server_card1); // Add the data to the database. personal_data_->AddProfile(profile0); personal_data_->AddProfile(profile1); personal_data_->AddCreditCard(local_card0); personal_data_->AddCreditCard(local_card1); test::SetServerCreditCards(autofill_table_, server_cards); personal_data_->Refresh(); EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Make sure everything was saved properly. EXPECT_EQ(2U, personal_data_->GetProfiles().size()); EXPECT_EQ(4U, personal_data_->GetCreditCards().size()); /////////////////////////////////////////////////////////////////////// // Tested method. /////////////////////////////////////////////////////////////////////// personal_data_->RemoveByGUID(profile0.guid()); /////////////////////////////////////////////////////////////////////// // Validation. /////////////////////////////////////////////////////////////////////// // Wait for the data to be refreshed. EXPECT_CALL(personal_data_observer_, OnPersonalDataChanged()) .WillOnce(QuitMainMessageLoop()); base::RunLoop().Run(); // Make sure only profile0 was deleted. ASSERT_EQ(1U, personal_data_->GetProfiles().size()); EXPECT_EQ(profile1.guid(), personal_data_->GetProfiles()[0]->guid()); EXPECT_EQ(4U, personal_data_->GetCreditCards().size()); for (CreditCard* card : personal_data_->GetCreditCards()) { if (card->guid() == local_card0.guid() || card->guid() == server_card0.guid()) { // The billing address id of local_card0 and server_card0 should have been // reset. EXPECT_EQ("", card->billing_address_id()); } else { // The billing address of local_card1 and server_card1 should still refer // to profile1. EXPECT_EQ(profile1.guid(), card->billing_address_id()); } } } TEST_F(PersonalDataManagerTest, LogStoredProfileMetrics_NoStoredProfiles) { base::HistogramTester histogram_tester; ResetPersonalDataManager(USER_MODE_NORMAL); EXPECT_TRUE(personal_data_->GetProfiles().empty()); histogram_tester.ExpectTotalCount("Autofill.StoredProfileCount", 1); histogram_tester.ExpectBucketCount("Autofill.StoredProfileCount", 0, 1); histogram_tester.ExpectTotalCount("Autofill.StoredProfileDisusedCount", 0); histogram_tester.ExpectTotalCount("Autofill.DaysSinceLastUse.StoredProfile", 0); } TEST_F(PersonalDataManagerTest, LogStoredProfileMetrics) { // Add a recently used (3 days ago) profile. AutofillProfile profile0(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile0, "Bob", "", "Doe", "", "Fox", "1212 Center.", "Bld. 5", "Orlando", "FL", "32801", "US", "19482937549"); profile0.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(3)); personal_data_->AddProfile(profile0); // Add a profile used a long time (200 days) ago. AutofillProfile profile1(base::GenerateGUID(), "https://www.example.com"); test::SetProfileInfo(&profile1, "Seb", "", "Doe", "", "ACME", "1234 Evergreen Terrace", "Bld. 5", "Springfield", "IL", "32801", "US", "15151231234"); profile1.set_use_date(AutofillClock::Now() - base::TimeDelta::FromDays(200)); personal_data_->AddProfile(profile1); // Reload the database, which will log the stored profile counts. base::HistogramTester histogram_tester; ResetPersonalDataManager(USER_MODE_NORMAL); EXPECT_EQ(2u, personal_data_->GetProfiles().size()); histogram_tester.ExpectTotalCount("Autofill.StoredProfileCount", 1); histogram_tester.ExpectBucketCount("Autofill.StoredProfileCount", 2, 1); histogram_tester.ExpectTotalCount("Autofill.StoredProfileDisusedCount", 1); histogram_tester.ExpectBucketCount("Autofill.StoredProfileDisusedCount", 1, 1); histogram_tester.ExpectTotalCount("Autofill.DaysSinceLastUse.StoredProfile", 2); histogram_tester.ExpectBucketCount("Autofill.DaysSinceLastUse.StoredProfile", 3, 1); histogram_tester.ExpectBucketCount("Autofill.DaysSinceLastUse.StoredProfile", 200, 1); } TEST_F(PersonalDataManagerTest, RemoveProfilesNotUsedSinceTimestamp) { const char kHistogramName[] = "Autofill.AddressesSuppressedForDisuse"; const base::Time kNow = AutofillClock::Now(); constexpr size_t kNumProfiles = 10; // Setup the profile vectors with last use dates ranging from |now| to 270 // days ago, in 30 day increments. Note that the profiles are sorted by // decreasing last use date. std::vector<AutofillProfile> all_profile_data; std::vector<AutofillProfile*> all_profile_ptrs; all_profile_data.reserve(kNumProfiles); all_profile_ptrs.reserve(kNumProfiles); for (size_t i = 0; i < kNumProfiles; ++i) { constexpr base::TimeDelta k30Days = base::TimeDelta::FromDays(30); all_profile_data.emplace_back(base::GenerateGUID(), "https://example.com"); all_profile_data.back().set_use_date(kNow - (i * k30Days)); all_profile_ptrs.push_back(&all_profile_data.back()); } // Verify that disused profiles get removed from the end. Note that the last // four profiles have use dates more than 175 days ago. { // Create a working copy of the profile pointers. std::vector<AutofillProfile*> profiles(all_profile_ptrs); // The first 6 have use dates more recent than 175 days ago. std::vector<AutofillProfile*> expected_profiles(profiles.begin(), profiles.begin() + 6); // Filter the profiles while capturing histograms. base::HistogramTester histogram_tester; PersonalDataManager::RemoveProfilesNotUsedSinceTimestamp( kNow - base::TimeDelta::FromDays(175), &profiles); // Validate that we get the expected filtered profiles and histograms. EXPECT_EQ(expected_profiles, profiles); histogram_tester.ExpectTotalCount(kHistogramName, 1); histogram_tester.ExpectBucketCount(kHistogramName, 4, 1); } // Reverse the profile order and verify that disused profiles get removed // from the beginning. Note that the first five profiles, post reversal, have // use dates more then 145 days ago. { // Create a reversed working copy of the profile pointers. std::vector<AutofillProfile*> profiles(all_profile_ptrs.rbegin(), all_profile_ptrs.rend()); // The last 5 profiles have use dates more recent than 145 days ago. std::vector<AutofillProfile*> expected_profiles(profiles.begin() + 5, profiles.end()); // Filter the profiles while capturing histograms. base::HistogramTester histogram_tester; PersonalDataManager::RemoveProfilesNotUsedSinceTimestamp( kNow - base::TimeDelta::FromDays(145), &profiles); // Validate that we get the expected filtered profiles and histograms. EXPECT_EQ(expected_profiles, profiles); histogram_tester.ExpectTotalCount(kHistogramName, 1); histogram_tester.ExpectBucketCount(kHistogramName, 5, 1); } // Randomize the profile order and validate that the filtered list retains // that order. Note that the six profiles have use dates more then 115 days // ago. { // A handy constant. const base::Time k115DaysAgo = kNow - base::TimeDelta::FromDays(115); // Created a shuffled master copy of the profile pointers. std::vector<AutofillProfile*> shuffled_profiles(all_profile_ptrs); std::random_shuffle(shuffled_profiles.begin(), shuffled_profiles.end()); // Copy the shuffled profile pointer collections to use as the working set. std::vector<AutofillProfile*> profiles(shuffled_profiles); // Filter the profiles while capturing histograms. base::HistogramTester histogram_tester; PersonalDataManager::RemoveProfilesNotUsedSinceTimestamp(k115DaysAgo, &profiles); // Validate that we have the right profiles. Iterate of the the shuffled // master copy and the filtered copy at the same time. making sure that the // elements in the filtered copy occur in the same order as the shuffled // master. Along the way, validate that the elements in and out of the // filtered copy have appropriate use dates. EXPECT_EQ(4u, profiles.size()); auto it = shuffled_profiles.begin(); for (const AutofillProfile* profile : profiles) { for (; it != shuffled_profiles.end() && (*it) != profile; ++it) { EXPECT_LT((*it)->use_date(), k115DaysAgo); } ASSERT_TRUE(it != shuffled_profiles.end()); EXPECT_GT(profile->use_date(), k115DaysAgo); ++it; } for (; it != shuffled_profiles.end(); ++it) { EXPECT_LT((*it)->use_date(), k115DaysAgo); } // Validate the histograms. histogram_tester.ExpectTotalCount(kHistogramName, 1); histogram_tester.ExpectBucketCount(kHistogramName, 6, 1); } } } // namespace autofill
44.493403
80
0.690097
[ "object", "vector" ]
9910db682ddd2922286568fc7a392701cab592b9
27,800
cpp
C++
Sourcecode/ProteinAbsoluteQuan/ProteinAbsoluteQuan/BasicClass.cpp
bertrandboudaud/LFAQ
5be4f71700c361764b5ac8bd9629adc176667e0c
[ "Artistic-1.0-Perl" ]
2
2018-02-27T02:16:25.000Z
2021-12-26T01:02:14.000Z
Sourcecode/ProteinAbsoluteQuan/ProteinAbsoluteQuan/BasicClass.cpp
bertrandboudaud/LFAQ
5be4f71700c361764b5ac8bd9629adc176667e0c
[ "Artistic-1.0-Perl" ]
null
null
null
Sourcecode/ProteinAbsoluteQuan/ProteinAbsoluteQuan/BasicClass.cpp
bertrandboudaud/LFAQ
5be4f71700c361764b5ac8bd9629adc176667e0c
[ "Artistic-1.0-Perl" ]
2
2021-06-27T18:27:34.000Z
2022-02-11T06:27:58.000Z
/* # Copyright(C) 2015-2018 all rights reserved # This program is a free software; you can redistribute it and / or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the # GNU General Public License for more details. # # A copy of the GNU General Public License is available at # http://www.gnu.org/Licenses/ */ #pragma once #include"stdafx.h" #include"BasicClass.h" int UniquePeptidesTrainThreshold=5; // Default value CProtein::CProtein() { m_dPeptidesIntensityMax = 0.0; m_dPeptidesIntensityMedian = 0.0; m_dProteinLFAQpep = 0.0; m_dProteinLFAQpro = 0.0; m_dProteinQfactor = 0.0; m_dMaxQuantiBAQ = 0.0; m_dReCalculateiBAQ = 0.0; m_iPeptidesNumber = 0; m_dPeptidesIntensitySum = 0.0; m_dCVNative = 0.0; m_dCVAfterCorrected = 0.0; m_bIfCalculateLFAQpep = false; m_bIfCalculateLFAQpro = false; m_dPredictedMolOfLFAQpep = 0.0; m_dPredictedMolOfLFAQpro=0.0; m_dPredictedMolOfiBAQ=0.0; m_dProteinIntensityTop3 = 0.0; m_dPredictedMolOfTop3=0.0; m_bIfInTrainSet = false; } void CProtein::Clear() { m_vPeptidesIDs.clear(); m_vPeptidesSequencesWithFlankingRegion.clear(); m_vPeptidesSequences.clear(); m_vPeptidesFeatures.clear(); m_vPeptideExperimentalQFactors.clear(); m_vPeptidesNativeIntensity.clear(); m_vPeptidesCombinedIntensity.clear(); m_vPeptidesCorrectedIntensity.clear(); m_dPeptidesIntensityMedian = 0.0; m_dPeptidesIntensityMax = 0.0; m_mapPeptidesSequenceAndCorrespondRawFiles.clear(); m_mapExperimentAndPeptidesIntensity.clear(); m_vPeptideQfactors.clear(); m_vecdMaxQuantiBAQ.clear(); m_dMaxQuantiBAQ = 0.0; m_vdPeptidesMW.clear(); m_dReCalculateiBAQ = 0.0; m_bIfInTrainSet = false; } string CProtein::mf_GetPeptidesAdjacentSequence(string PeptideSequence) { string::size_type peptideLocation = 0, begin = 0, Getwidth = 0, end; end = PeptideSequence.find("{"); PeptideSequence = PeptideSequence.substr(0, end); peptideLocation = m_strProteinSequence.find(PeptideSequence); if (peptideLocation != m_strProteinSequence.npos) { if ((peptideLocation >= FlankingRegionWidth) && (peptideLocation <= m_strProteinSequence.size() - PeptideSequence.size() - FlankingRegionWidth)) { begin = peptideLocation - FlankingRegionWidth; Getwidth = PeptideSequence.size() + 2 * FlankingRegionWidth; } else if (peptideLocation < FlankingRegionWidth) { begin = 0; Getwidth = peptideLocation + PeptideSequence.size() + FlankingRegionWidth; } else if (peptideLocation > m_strProteinSequence.size() - PeptideSequence.size() - FlankingRegionWidth) { begin = peptideLocation - FlankingRegionWidth; Getwidth = m_strProteinSequence.size() - peptideLocation - 1 + PeptideSequence.size() + FlankingRegionWidth; } return m_strProteinSequence.substr(begin, Getwidth); } else { cout << "\tWarning:\tCannot find peptide " << PeptideSequence << " in protein " << m_strProteinID << endl; cout << "The protein sequence is " << m_strProteinSequence << endl; flog.mf_Input("\tWarning:\tCannot find peptide " + PeptideSequence + " in protein " + m_strProteinID +"\n"); flog.mf_Input("The protein sequence is " + m_strProteinSequence + "\n"); return "NULL"; } } // judge if RelatedProtein A is the subset of RelatedProtein B; bool CRelatedProtein::mf_ifSubset(CRelatedProtein& A) { vector<string> vecA; vector<string> vecB; for (size_t i = 0; i < A.vecPeptides.size(); i++) { vecA.push_back(A.vecPeptides[i]); } for (size_t j = 0; j < this->vecPeptides.size(); j++) { vecB.push_back(this->vecPeptides[j]); } if (ifSubset(vecA,vecB)) { return true; } else { return false; } } void CRelatedProtein::Clear() { bIfSubSet = false; strProteinID=""; vecPeptides.clear(); vecSubsetProteinIDs.clear(); vecBIfPeptideGroupUnique.clear(); } void Cpeptides::mf_Clear() { m_mapPeptideIDAndSequence.clear(); m_mapPeptideIDAndIntensity.clear(); m_mapPeptideSequenceAndIntensity.clear(); m_mapPeptideSequencuAndIfUse.clear(); m_mapPeptideSequenceAndAttribute.clear(); m_mapPeptideIDAndIntensitys.clear(); } void CMergedProtein::Clear() { m_vecExperiments.clear(); m_vecMaxQuantiBAQOfExperiments.clear(); m_vecReCaliBAQOfExperiments.clear(); m_vecLFAQproOfExperiments.clear(); m_vecLFAQpepOfExperiments.clear(); m_vecTop3OfExperiments.clear(); m_vecPredictedMolsByLFAQpepOfExperiments.clear(); m_vecPredictedMolsByLFAQproOfExperiments.clear(); m_vecPredictedMolsByiBAQOfExperiments.clear(); m_vecPredictedMolsByTop3OfExperiments.clear(); m_mapExperimentsAndPeptidesIntensity.clear(); } void CMergedProteins::mf_ExperimentsAnalysis() { double dCVTemp; for (size_t i = 0; i < m_vecMergedProteins.size(); i++) { dCVTemp = CalculatelogCV(m_vecMergedProteins[i].m_vecMaxQuantiBAQOfExperiments); m_vecMaxQuantiBAQCV.push_back(dCVTemp); dCVTemp = CalculatelogCV(m_vecMergedProteins[i].m_vecReCaliBAQOfExperiments); m_vecReCaliBAQCV.push_back(dCVTemp); dCVTemp = CalculatelogCV(m_vecMergedProteins[i].m_vecLFAQpepOfExperiments); m_vecLFAQpepCV.push_back(dCVTemp); dCVTemp = CalculatelogCV(m_vecMergedProteins[i].m_vecLFAQproOfExperiments); m_vecLFAQproCV.push_back(dCVTemp); dCVTemp = CalculatelogCV(m_vecMergedProteins[i].m_vecTop3OfExperiments); m_vecTop3CV.push_back(dCVTemp); } } string AddDecorateStar(const string& strProjectName) { string strTemp; for (int i = 0; i < 80; i++) { strTemp += "*"; } strTemp += "\n"; for (int i = 0; i < 25; i++) { strTemp += " "; } strTemp += strProjectName; strTemp += "\n"; for (int i = 0; i < 80; i++) { strTemp += "*"; } strTemp += "\n"; return strTemp; } string Unicode2Multibyte(_TCHAR * chars) { DWORD dwNum = WideCharToMultiByte(CP_OEMCP, NULL, chars, -1, NULL, 0, NULL, FALSE); char *psText; psText = new char[dwNum]; if (!psText) { delete[]psText; } WideCharToMultiByte(CP_OEMCP, NULL, chars, -1, psText, dwNum, NULL, FALSE); string strTemp = psText; delete[]psText; psText = NULL; return strTemp; } map<string, string> GetParametersFromFile(const string &ParamFilePath) { map<string,string> mapAttributeNameAndValues; ifstream fin(ParamFilePath.c_str()); if (!fin) { cout << "Error:\tCannot open parameter file: " << ParamFilePath << endl; if (flog.m_bIfReady) { flog.mf_Input("Error:\tCannot open parameter file: " + ParamFilePath + ".\n"); flog.mf_Destroy(); exit(1); } } string strAttributeName, strAtributeValue; string strTemp = ""; int iTemp1 = 0, iTemp2 = 0; while (getline(fin, strTemp)) { if (strTemp == "") { continue; } iTemp2 = strTemp.find("=", 0); strAttributeName = strTemp.substr(0, iTemp2); iTemp1 = strTemp.find("\""); if (iTemp1 == strTemp.npos) { cout << "Error:\tCannot read parameter from " << strTemp << endl; if (flog.m_bIfReady) { flog.mf_Input("Error:\tCannot read parameter from " + strTemp + ".\n"); flog.mf_Destroy(); exit(1); } return mapAttributeNameAndValues; } iTemp2 = strTemp.find("\"", iTemp1 + 1); if (iTemp2 == strTemp.npos) { cout << "Error:\tCannot read parameter from " << strTemp << endl; if (flog.m_bIfReady) { flog.mf_Input("Error:\tCannot read parameter from " + strTemp + ".\n"); flog.mf_Destroy(); exit(1); } return mapAttributeNameAndValues; } strAtributeValue = strTemp.substr(iTemp1 + 1, iTemp2 - iTemp1 - 1); transform(strAttributeName.begin(), strAttributeName.end(), strAttributeName.begin(), ::tolower);//change AttributeNameto lowcase mapAttributeNameAndValues.insert(pair<string, string>(strAttributeName, strAtributeValue)); } return mapAttributeNameAndValues; } string GetResultPath(string ParamFilePath) { map<string, string> mapAttributeNameAndValues; map<string, string>::iterator mapAttributeNameAndValuesIter; mapAttributeNameAndValues = GetParametersFromFile(ParamFilePath); mapAttributeNameAndValuesIter = mapAttributeNameAndValues.find("resultpath"); string strAtributeValue; if (mapAttributeNameAndValuesIter != mapAttributeNameAndValues.end()) { return mapAttributeNameAndValuesIter->second; } else { return "NULL"; } } // check if the file exist and if it contain double quotation marks bool CheckFilePath(string& filepath) { if (filepath.at(0) == '\"'&&filepath.at(filepath.size() - 1) == '\"') { filepath = filepath.substr(1, filepath.size() - 2); } fstream fc(filepath); if (!fc) { return false; } return true; } bool bPrefix(string str, string prefix) { if (prefix.size() > str.size()) { return false; } if (prefix.empty()) { return true; } return str.compare(0, prefix.size(), prefix) == 0; } string stringTrim(string str) { //search for the begin of truncated string string::iterator begin = str.begin(); while (begin != str.end() && (*begin == ' ' || *begin == '\t' || *begin == '\n' || *begin == '\r')) { ++begin; } //all characters are whitespaces if (begin == str.end()) { str.clear(); return str; } //search for the end of truncated string string::iterator end = str.end(); end--; while (end != begin && (*end == ' ' || *end == '\n' || *end == '\t' || *end == '\r')) { --end; } ++end; //no characters are whitespaces if (begin == str.begin() && end == str.end()) { return str; } str=string(begin, end); return str; } string removestringWhitespaces(string str) { bool contains_ws = false; for (string::const_iterator it = str.begin(); it != str.end(); ++it) { char c = *it; if (c == ' ' || c == '\t' || c == '\n' || c == '\r') { contains_ws = true; break; } } if (contains_ws) { string tmp; tmp.reserve(str.size()); for (string::const_iterator it = str.begin(); it != str.end(); ++it) { char c = *it; if (c != ' ' && c != '\t' && c != '\n' && c != '\r') tmp += c; } str.swap(tmp); } return str; } string stringtoLower(string str) { std::transform(str.begin(), str.end(), str.begin(), (int(*)(int))tolower); return str; } string PrefixOfstring(string str, char delim) { size_t pos = str.find(delim); if (pos == string::npos) //char not found { cout << "Error:\tCannot find delimiter " << delim << endl; flog.mf_Input("Error:\tCannot find delimiter " + delim ); flog.mf_Input("\n"); flog.mf_Destroy(); } return str.substr(0, pos); } string SuffixOfstring(string str, char delim) { size_t pos = str.rfind(delim); if (pos == string::npos) //char not found { cout << "Error:\tCannot find delimiter " << delim << endl; flog.mf_Input("Error:\tCannot find delimiter " + delim); flog.mf_Input("\n"); flog.mf_Destroy(); } return str.substr(++pos); } bool stringSplit(string str, const string splitter, vector<string>& substrings) { substrings.clear(); if (str.empty()) return false; if (splitter.empty()) // split after every character: { substrings.resize(str.size()); for (size_t i = 0; i < str.size(); ++i) substrings[i] = str[i]; return true; } size_t len = splitter.size(), start = 0, pos = str.find(splitter); if (len == 0) len = 1; while (pos != string::npos) { substrings.push_back(str.substr(start, pos - start)); start = pos + len; pos = str.find(splitter, start); } substrings.push_back(str.substr(start, str.size() - start)); return substrings.size() > 1; } double Average(double *Array, int Number) { double ave = 0.0; for (int i = 0; i < Number; i++) { ave += Array[i]; } return ave / Number; } double Average(vector<double> Array) { if (Array.size() == 0) { return 0.0; } double ave = 0.0; vector<double>::iterator doubleIter; for (doubleIter = Array.begin(); doubleIter != Array.end(); doubleIter++) { ave += *doubleIter; } double len = Array.size(); return ave / len; } void quickSort(double v[], int indexTemp[], int left, int right) { // A problem: Stack overflow may happen in the sort function when the dataset is too big. if (left < right) { double key = v[left]; int indexKey = indexTemp[left]; int low = left; int high = right; while (low < high) { while (low < high && v[high] <= key) { high--; } if (low < high) { v[low] = v[high]; indexTemp[low] = indexTemp[high]; low++; } while (low < high && v[low] > key) { low++; } if (low < high) { v[high] = v[low]; indexTemp[high] = indexTemp[low]; high--; } } v[low] = key; indexTemp[low] = indexKey; quickSort(v, indexTemp, left, low - 1); quickSort(v, indexTemp, low + 1, right); } } void quickSort(vector<size_t> &v, vector<size_t> &indexTemp, int left, int right) { if (left < right) { size_t key = v[left]; size_t indexKey = indexTemp[left]; int low = left; int high = right; while (low < high) { while (low < high && v[high] <= key) { high--; } if (low < high) { v[low] = v[high]; indexTemp[low] = indexTemp[high]; low++; } while (low < high && v[low] > key) { low++; } if (low < high) { v[high] = v[low]; indexTemp[high] = indexTemp[low]; high--; } } v[low] = key; indexTemp[low] = indexKey; quickSort(v, indexTemp, left, low - 1); quickSort(v, indexTemp, low + 1, right); } } void quickSort(vector<double> &v, vector<size_t> &indexTemp, int left, int right) { if (left < right) { double key = v[left]; size_t indexKey = indexTemp[left]; int low = left; int high = right; while (low < high) { while (low < high && v[high] <= key) { high--; } if (low < high) { v[low] = v[high]; indexTemp[low] = indexTemp[high]; low++; } while (low < high && v[low] > key) { low++; } if (low < high) { v[high] = v[low]; indexTemp[high] = indexTemp[low]; high--; } } v[low] = key; indexTemp[low] = indexKey; quickSort(v, indexTemp, left, low - 1); quickSort(v, indexTemp, low + 1, right); } } double spearsonCorrelation(double s1[], double s2[], int NumberOfSamples) { double dCorrelation = 0.0; double means2 = 0.0; double means1 = 0.0; double sd1 = 0.0, sd2 = 0.0; means1 = Average(s1, NumberOfSamples); for (int i = 0; i < NumberOfSamples; i++) means2 += s2[i]; means2 = means2 / NumberOfSamples; for (int i = 0; i < NumberOfSamples; i++) dCorrelation += (s2[i] - means2)*(s1[i] - means1); for (int i = 0; i < NumberOfSamples; i++) { sd1 += (s1[i] - means1)*(s1[i] - means1); sd2 += (s2[i] - means2)*(s2[i] - means2); } dCorrelation = dCorrelation / sqrt(sd1*sd2); if (sd1*sd2 <= 0) return -1; else return dCorrelation; } double spearsonCorrelation(vector<double> s1, double s2[]) { double dCorrelation = 0.0; double means2 = 0.0; double means1 = 0.0; double sd1 = 0.0, sd2 = 0.0; int NumberOfSamples = s1.size(); means1 = Average(s1); means2 = Average(s2, NumberOfSamples); for (int i = 0; i < NumberOfSamples; i++) dCorrelation += (s2[i] - means2)*(s1[i] - means1); for (int i = 0; i < NumberOfSamples; i++) { sd1 += (s1[i] - means1)*(s1[i] - means1); sd2 += (s2[i] - means2)*(s2[i] - means2); } dCorrelation = dCorrelation / sqrt(sd1*sd2); if (sd1*sd2 <= 0) return -1; else return dCorrelation; } double spearsonCorrelation(vector<double> s1, vector<double> s2) { double dCorrelation = 0.0; double means2 = 0.0; double means1 = 0.0; double sd1 = 0.0, sd2 = 0.0; int NumberOfSamples = s1.size(); means1 = Average(s1); means2 = Average(s2); for (int i = 0; i < NumberOfSamples; i++) dCorrelation += (s2[i] - means2)*(s1[i] - means1); for (int i = 0; i < NumberOfSamples; i++) { sd1 += (s1[i] - means1)*(s1[i] - means1); sd2 += (s2[i] - means2)*(s2[i] - means2); } dCorrelation = dCorrelation / sqrt(sd1*sd2); if (sd1*sd2 <= 0) return 0; else return dCorrelation; } double CalculatelogCV(const vector<double>&s) { // add log 20170607 vector<double> nonZeroS; nonZeroS.clear(); for (int i = 0; i < s.size(); i++) { if (s[i] != 0.0) { nonZeroS.push_back(s[i]); } } double mean = 0.0; double sd = 0.0, sd2 = 0.0; int len = nonZeroS.size(); for (int i = 0; i < len; i++) { nonZeroS[i] = log10(nonZeroS[i]); mean += (nonZeroS[i]); } if (len <= 1) return 0.0; else { mean = mean / len; for (int i = 0; i < len; i++) { sd += ((nonZeroS[i]) - mean)*((nonZeroS[i]) - mean); } } sd = sqrt(sd / len); if (mean <= 0) return -1; else return sd / mean; } void Discretization(double *TestY, int m_iTestSampleNumber, int iBinNum) { vector <pair<double, int>> vctemp; int bin_volume = m_iTestSampleNumber / iBinNum; for (int i = 0; i < m_iTestSampleNumber; i++) { vctemp.push_back(make_pair(TestY[i], i)); } sort(vctemp.begin(), vctemp.end()); double dBinGap = 1 / (double)iBinNum; for (int i = 0; i < m_iTestSampleNumber; i++) { TestY[vctemp[i].second] = int(i / bin_volume + 1)*dBinGap; if (TestY[vctemp[i].second]>1) TestY[vctemp[i].second] = 1; } } void Discretization(vector<double> &TestY,int iBinNum) { vector <pair<double, int>> vctemp; int m_iTestSampleNumber = TestY.size(); int bin_volume = m_iTestSampleNumber / iBinNum; for (int i = 0; i < m_iTestSampleNumber; i++) { vctemp.push_back(make_pair(TestY[i], i)); } sort(vctemp.begin(), vctemp.end()); double dBinGap = 1 / (double)iBinNum; for (int i = 0; i < m_iTestSampleNumber; i++) { TestY[vctemp[i].second] = int(i / bin_volume + 1)*dBinGap; if (TestY[vctemp[i].second]>1) TestY[vctemp[i].second] = 1; } } double GetMaxValue(const vector<double> PeptidesIntensity) { double dMaxIntensitytemp = 0.0; for (size_t i = 0; i < PeptidesIntensity.size(); i++) { if (dMaxIntensitytemp < PeptidesIntensity.at(i)) { dMaxIntensitytemp = PeptidesIntensity.at(i); } } return dMaxIntensitytemp; } double GetMaxValue(double *PeptidesIntensity, int iNum) { double dMaxIntensitytemp = 0.0; for (size_t i = 0; i < iNum; i++) { if (dMaxIntensitytemp < PeptidesIntensity[i]) { dMaxIntensitytemp = PeptidesIntensity[i]; } } return dMaxIntensitytemp; } double GetMinValue(vector<double> PeptidesIntensity) { double dMinTemp = 1e15; for (size_t i = 0; i < PeptidesIntensity.size(); i++) { if (dMinTemp > PeptidesIntensity.at(i)) { dMinTemp = PeptidesIntensity.at(i); } } return dMinTemp; } double GetMinValue(double *PeptidesIntensity, int iNum) { double dMinTemp = 1e15; for (size_t i = 0; i < iNum; i++) { if (dMinTemp > PeptidesIntensity[i]) { dMinTemp = PeptidesIntensity[i]; } } return dMinTemp; } double GetSum(vector<double> vec) { double dSumTemp = 0.0; for (size_t i = 0; i < vec.size(); i++) { dSumTemp += vec[i]; } return dSumTemp; } int GetMaxIndex(vector<double> vec) { double dMaxIntensitytemp = 0.0; int iMaxIndex = 0; for (size_t i = 0; i < vec.size(); i++) { if (dMaxIntensitytemp < vec.at(i)) { dMaxIntensitytemp = vec.at(i); iMaxIndex = i; } } return iMaxIndex; } double GetMedianIntensity(vector<double> PeptidesIntensity) { sort(PeptidesIntensity.begin(), PeptidesIntensity.end()); size_t len = PeptidesIntensity.size(); if (len == 0) return 0.0; if (len % 2 == 0) return (PeptidesIntensity.at(len / 2) + PeptidesIntensity.at((len - 2) / 2)) / 2; else return PeptidesIntensity.at(floor(len / 2)); } //Ensure that there is not negative and zeros; void Assertion(vector<double> &TestY) { for (size_t i = 0; i < TestY.size(); i++) { if (TestY.at(i) <= 0.1) TestY.at(i) = 0.1; if (TestY.at(i) > 1.0) TestY.at(i) = 1.0; } } //Ensure that there is not negative and zeros; void Assertion(double *TestY, int m_iTestSampleNumber) { for (int i = 0; i < m_iTestSampleNumber; i++) { if (TestY[i] <= 0.1) { TestY[i] = 0.1; } if (TestY[i] > 1.0) TestY[i] = 1.0; } } void Scaling(vector<double> &TestY) { double dMax = GetMaxValue(TestY); double dMin = GetMinValue(TestY); for (size_t i = 0; i < TestY.size(); i++) { TestY[i] = ((TestY[i] - dMin)*0.9) / dMax + 0.1; } } void Scaling(double *TestY, int m_iTestSampleNumber) { double dMax = GetMaxValue(TestY,m_iTestSampleNumber); double dMin = GetMinValue(TestY, m_iTestSampleNumber); double t = 0.05; for (size_t i = 0; i < m_iTestSampleNumber; i++) { TestY[i] = ((TestY[i] - dMin)*(1-t)) / (dMax-dMin) + t; } } //integral using trapzoid formular double IntegralFromVector(vector<double> Values, vector<double> times) { double result = 0.0; if (Values.size() != times.size()) { cout << "Error:\tThe size of Values does not correspond to times'" << endl; flog.mf_Input("Error:\tThe size of Values does not correspond to times'\n"); flog.mf_Destroy(); exit(1); } for (size_t i = 1; i < times.size(); i++) { result = result + Values.at(i)*(times.at(i) - times.at(i - 1)) / 2; } return result; } void GetQuantiles(vector<double> PeptidesIntensity, double &FirstQ, double &median, double &ThirdQ) { sort(PeptidesIntensity.begin(), PeptidesIntensity.end()); int len = PeptidesIntensity.size(); if (len ==0) { FirstQ = 0.0; median = 0.0; ThirdQ = 0.0; } else if (len == 1) { FirstQ = PeptidesIntensity.front(); median = PeptidesIntensity.front(); ThirdQ = PeptidesIntensity.front(); } else if (len == 2) { FirstQ = PeptidesIntensity.at(0); median = (PeptidesIntensity.at(0) + PeptidesIntensity.at(1)) / 2; ThirdQ = PeptidesIntensity.at(1); } else if (len == 3) { FirstQ = PeptidesIntensity.at(0); median = PeptidesIntensity.at(1); ThirdQ = PeptidesIntensity.at(2); } else if (len % 4 == 0) { FirstQ = (PeptidesIntensity.at(len/4)+PeptidesIntensity.at(len/4-1))/2; median = (PeptidesIntensity.at(len / 2) + PeptidesIntensity.at(len /2-1))/ 2; ThirdQ = (PeptidesIntensity.at(3 * (len / 4)) + PeptidesIntensity.at(3 * (len / 4) - 1)) / 2; } else if (len % 4 == 1) { FirstQ = (PeptidesIntensity.at(floor(len / 4)) + PeptidesIntensity.at(ceil(len / 4))) / 2; median = PeptidesIntensity.at(floor(len / 2)); ThirdQ = (PeptidesIntensity.at(floor(3 * (len / 4))) + PeptidesIntensity.at(ceil(3 * (len / 4) ))) / 2; } else if (len % 4 == 2) { FirstQ = PeptidesIntensity.at(floor(len / 4)) ; median = (PeptidesIntensity.at(len / 2) + PeptidesIntensity.at(len / 2 - 1)) / 2; ThirdQ = PeptidesIntensity.at(floor(3 * (len / 4))) ; } else if (len % 4 == 3) { FirstQ = PeptidesIntensity.at(floor(len / 4)); median = PeptidesIntensity.at(ceil(len / 2)); ThirdQ = PeptidesIntensity.at(floor(3 * (len / 4))); } } void GetAttributesFromFirstRow(char * pstr, map<string, int>& mapAttributesAndColumns, string sep) { char *pstr1; int icolumns = 0; pstr1 = strstr(pstr, sep.c_str()); while (pstr1 != NULL) { if (pstr1 != NULL) { *pstr1 = '\0'; } else { cout << "Error:\tThe format is wrong.\n"; exit(1); } mapAttributesAndColumns.insert(pair<string, int>(pstr, icolumns)); icolumns++; pstr = pstr1 + 1; pstr1 = strstr(pstr, sep.c_str()); } pstr1 = strstr(pstr, "\n"); if (pstr1 != NULL) { *pstr1 = '\0'; } else { cout << "Error:\tThe format is wrong.\n"; exit(1); } mapAttributesAndColumns.insert(pair<string, int>(pstr, icolumns)); } void GetAttributesFromFirstRow(string str, map<string, int>& mapAttributesAndColumns, string sep) { mapAttributesAndColumns.clear(); if (str == "") { return; } int iColumn = 0; int iBegin = 0, iEnd = 0; iEnd = str.find(sep, iBegin); string strsub; while (iEnd!=str.npos && iBegin < str.size() - 1) { strsub = str.substr(iBegin, iEnd - iBegin); mapAttributesAndColumns.insert(pair<string, int>(strsub, iColumn)); iColumn++; iBegin = iEnd + 1; iEnd = str.find(sep, iBegin); } if (iBegin < str.size() - 1) { iEnd = str.size(); strsub = str.substr(iBegin, iEnd - iBegin); mapAttributesAndColumns.insert(pair<string, int>(strsub, iColumn)); } } bool fStringToBool(string str, bool &bl) { transform(str.begin(), str.end(), str.begin(), ::tolower); if (str == "true") bl = true; else if (str == "false") bl= false; else { return false; } return true; } string fInt2String(int i) { char buf[10]; sprintf(buf, "%d", i); string str = buf; return str; } string fSize_t2String(size_t si) { int iTemp = si; string str = fInt2String(iTemp); return str; } string fDouble2String(double d) { ostringstream os; os << d; return os.str(); } bool is_dir(const char* path) { struct _stat buf = { 0 }; _stat(path, &buf); return buf.st_mode & _S_IFDIR; } bool is_file(const char* FILENAME) { fstream _file; _file.open(FILENAME, ios::in); if (!_file) { return false; } else { return true; } } //remove the whitespace at the end of the string or at the begin of the string string strim(string &str) { int ilocation = str.find_last_of(' '); if (ilocation != -1) { //remove the whitespace at the end of the string str.erase(str.find_last_not_of(' ') + 1); } ilocation = str.find_first_not_of(' '); //remove the whitespace at the begin of the string str.erase(0, ilocation); return str; } std::vector<string> split(const string &strLine, const string& splitter) { std::vector<string> substrings; substrings.clear(); string str = strLine; //delete the newline character if it has if (str.at(str.size() - 1) == '\n') { str = str.substr(0, str.size() - 1); } // split after every character: if (splitter.empty()) { substrings.resize(str.size()); for (size_t i = 0; i < str.size(); ++i) substrings[i] = str[i]; return substrings; } size_t len = splitter.size(), start = 0, pos = str.find(splitter); if (len == 0) len = 1; while (pos != string::npos) { substrings.push_back(str.substr(start, pos - start)); start = pos + len; pos = str.find(splitter, start); } substrings.push_back(str.substr(start, str.size() - start)); return substrings; } void SaveVector(string path, vector<double> vec) { ofstream oFile(path); if (!oFile) { cout << "Cannot open " << path << endl; exit(-1); } for (int i = 0; i < vec.size(); i++) { oFile << vec.at(i) << endl; } oFile.close(); } void SaveVector(string path, vector<string> vec) { ofstream oFile(path); if (!oFile) { cout << "Cannot open " << path << endl; exit(-1); } for (int i = 0; i < vec.size(); i++) { oFile << vec.at(i) << endl; } oFile.close(); } void SaveArray(string path, double * arr, int len) { ofstream oFile(path); if (!oFile) { cout << "Cannot open " << path << endl; exit(-1); } for (int i = 0; i < len; i++) { oFile << arr[i] << endl; } oFile.close(); } // Judge if vector A is the subset of vector B; bool ifSubset(vector<string>&vecA, vector<string>& vecB) { int iNumA = vecA.size(); int iNumB = vecB.size(); if (iNumA > iNumB) { return false; } vector<string>A; vector<string>B; for (int i = 0; i < iNumA; i++) { A.push_back(vecA[i]); } for (int j = 0; j <iNumB; j++) { B.push_back(vecB[j]); } sort(A.begin(), A.end()); sort(B.begin(), B.end()); int iA = 0, iB = 0; while (iA < iNumA&&iB < iNumB) { if (B[iB] < A[iA]) { iB++; } else if (A[iA] == B[iB]) { iA++; iB++; } else if (B[iB]>A[iA]) { return false; } } if (iA < iNumA) { return false; } else { return true; } } bool MoreThan(double a, double b) { return a > b; } double round(double number, unsigned int bits) { double integerPart = floor(number); number -= integerPart; for (unsigned int i = 0; i < bits; i++) { number *= 10; } number = floor(number + 0.5); for (unsigned int i = 0; i < bits; i++) { number /= 10; } return number + integerPart; }
23.108894
146
0.64536
[ "vector", "transform" ]
9912da836fc50d550fd28b4850c2201e573149cb
4,715
cpp
C++
collada2bin.cpp
NoImaginationGuy/graphcore
43b8c8e991e9cf3b5e4ce89706b3d6c98be056ba
[ "MIT" ]
null
null
null
collada2bin.cpp
NoImaginationGuy/graphcore
43b8c8e991e9cf3b5e4ce89706b3d6c98be056ba
[ "MIT" ]
null
null
null
collada2bin.cpp
NoImaginationGuy/graphcore
43b8c8e991e9cf3b5e4ce89706b3d6c98be056ba
[ "MIT" ]
null
null
null
// // => collada2bin.cpp // // GraphCore // // Copyright (c) 2018 Lorenzo Laneve // // 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 <iostream> #include <fstream> #include <string> #include <netinet/in.h> #include "scene.h" #include "Importer.hpp" #include "postprocess.h" #define min(a,b) (a>b ? b : a) using namespace std; using namespace Assimp; enum : unsigned int { TYPE_ENDFILE = 0, TYPE_MESH = 1, }; enum : unsigned int { VERTEX_ATTRIB_ENDMESH = 0, VERTEX_ATTRIB_POS = 1, VERTEX_ATTRIB_NORMAL = 2, VERTEX_ATTRIB_UV2 = 3, VERTEX_ATTRIB_UV3 = 4, VERTEX_ATTRIB_COLOR = 5 }; void writeByte(ostream &os, uint8_t x) { os.write((const char *)&x, 1); } void writeInt16(ostream &os, uint16_t x) { const uint8_t data[2] { (uint8_t)((x >> 8) & 255), (uint8_t)(x & 255) }; os.write((const char *)data, 2); } void writeInt32(ostream &os, uint32_t x) { const uint8_t data[4] = { (uint8_t)((x >> 24) & 255), (uint8_t)((x >> 16) & 255), (uint8_t)((x >> 8) & 255), (uint8_t)(x & 255) }; os.write((const char *)data, 4); } void writeFloat(ostream &os, float x) { uint32_t ix = *((uint32_t *)&x); const uint8_t data[4] = { (uint8_t)((ix >> 24) & 255), (uint8_t)((ix >> 16) & 255), (uint8_t)((ix >> 8) & 255), (uint8_t)(ix & 255) }; os.write((const char *)data, 4); } inline void writeVec3(ostream &os, float x, float y, float z) { writeFloat(os, z); writeFloat(os, y); writeFloat(os, -x); } inline void writeVec2(ostream &os, float x, float y) { writeFloat(os, x); writeFloat(os, y); } int main(int argc, const char * argv[]) { if (argc < 2) { cout << "File name not specified." << endl; return 0; } Importer imp; const aiScene *scene = imp.ReadFile(argv[1], aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph); ofstream os(std::string(argv[1]) + ".mdl", ios::binary); writeByte(os, scene->mNumMeshes); writeByte(os, 0); // animations count for (int i = 0; i < scene->mNumMeshes; i++) { aiMesh *mesh = scene->mMeshes[i]; writeByte(os, TYPE_MESH); // Type = MESH writeByte(os, i); // MeshID writeInt32(os, mesh->mNumVertices); // Number of vertices if (mesh->HasPositions()) { writeByte(os, VERTEX_ATTRIB_POS); // VertexAttrib = POSITION for (int j = 0; j < mesh->mNumVertices; j++) { aiVector3D &vertex = mesh->mVertices[j]; writeVec3(os, vertex.x, vertex.y, vertex.z); } } if (mesh->HasNormals()) { writeByte(os, VERTEX_ATTRIB_NORMAL); // VertexAttrib = NORMAL for (int j = 0; j < mesh->mNumVertices; j++) { aiVector3D &normal = mesh->mNormals[j]; writeVec3(os, normal.x, normal.y, normal.z); } } int texIndex = 0; while (mesh->HasTextureCoords(texIndex)) { writeByte(os, VERTEX_ATTRIB_UV2); // VertexAttrib = UV2 writeByte(os, texIndex); // TextureIndex for (int j = 0; j < mesh->mNumVertices; j++) { aiVector3D &texCoords = mesh->mTextureCoords[texIndex][j]; writeVec2(os, texCoords.x, texCoords.y); } texIndex++; } writeByte(os, VERTEX_ATTRIB_ENDMESH); } writeByte(os, TYPE_ENDFILE); return 0; }
28.403614
101
0.581548
[ "mesh" ]
9914b255de91d3b4e747788f5b16c31ef3f7327c
9,016
cpp
C++
src/print.cpp
dblommesteijn/oolib
b93a3cc74571f4b7cffb6546d6930eeb1f489e6c
[ "BSD-2-Clause" ]
null
null
null
src/print.cpp
dblommesteijn/oolib
b93a3cc74571f4b7cffb6546d6930eeb1f489e6c
[ "BSD-2-Clause" ]
null
null
null
src/print.cpp
dblommesteijn/oolib
b93a3cc74571f4b7cffb6546d6930eeb1f489e6c
[ "BSD-2-Clause" ]
null
null
null
// // ooprint.cpp WJ112 // /* * Copyright (c) 2014, Walter de Jong * 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 OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "oo/print.h" #include "oo/Base.h" #include "oo/Error.h" #include "oo/String.h" #include "oo/Mutex.h" #include <iostream> #include <iomanip> namespace oo { // the printer lock ensures screen output of multiple threads doesn't get messed up static Mutex printer_lock; void vssprint(std::stringstream& s, const char *fmt, std::va_list ap) { if (fmt == nullptr) { throw ReferenceError(); } if (!*fmt) { return; } int width; bool long_argument, size_argument; while(*fmt) { if (*fmt == '%') { // parse the format string fmt++; width = 0; long_argument = false; size_argument = false; // by default, right justified s << std::setiosflags(std::ios::right) << std::resetiosflags(std::ios::left) << std::setfill(' ') << std::dec << std::setiosflags(std::ios::fixed) << std::setprecision(6); // justify left if (*fmt == '-') { fmt++; s << std::setiosflags(std::ios::left) << std::resetiosflags(std::ios::right); } // leading zero's while(*fmt == '0') { fmt++; s << std::setfill('0'); } // width specifier while(*fmt >= '0' && *fmt <= '9') { width *= 10; width += (*fmt - '0'); fmt++; } if (*fmt == '*') { // variable width width = va_arg(ap, int); if (width < 0) { width = -width; s << std::setiosflags(std::ios::left) << std::resetiosflags(std::ios::right); } fmt++; } // floating point precision specifier if (*fmt == '.') { int precision = 0; bool precision_ok = false; fmt++; if (*fmt == '*') { precision = va_arg(ap, int); if (precision < 0) precision = -precision; fmt++; precision_ok = true; } else { while(*fmt == '0') { // skip leading zeroes precision = 0; fmt++; precision_ok = true; } if (*fmt >= '1' && *fmt <= '9') { precision = *fmt - '0'; fmt++; precision_ok = true; } while(*fmt >= '0' && *fmt <= '9') { precision *= 10; precision += (*fmt - '0'); fmt++; precision_ok = true; } } // else error in format string if (!precision_ok) { throw ValueError("format string error (in precision field)"); } // set precision s << std::setiosflags(std::ios::fixed) << std::setprecision(precision); } // 'long' argument if (*fmt == 'l') { fmt++; long_argument = true; } // 'size_t' argument if (*fmt == 'z') { fmt++; size_argument = true; } if (width > 0) { s << std::setw(width); } // format specifier switch(*fmt) { // print integer value case 'd': if (long_argument) { s << va_arg(ap, long); } else { if (size_argument) { s << va_arg(ap, ssize_t); } else { s << va_arg(ap, int); } } break; case 'x': s << std::hex; if (long_argument) { s << va_arg(ap, long); } else { if (size_argument) { s << va_arg(ap, size_t); } else { s << va_arg(ap, int); } } break; case 'X': s << std::uppercase << std::hex; if (long_argument) { s << va_arg(ap, long); } else { if (size_argument) { s << va_arg(ap, size_t); } else { s << va_arg(ap, int); } } s << std::nouppercase; break; case 'o': s << std::oct; if (long_argument) { s << va_arg(ap, long); } else { if (size_argument) { s << va_arg(ap, size_t); } else { s << va_arg(ap, int); } } break; case 'u': if (long_argument) { s << va_arg(ap, unsigned long); } else { if (size_argument) { s << va_arg(ap, size_t); } else { s << va_arg(ap, unsigned int); } } break; // print floating point values case 'e': case 'E': case 'f': case 'F': case 'g': case 'G': case 'a': case 'A': // note: this is nowhere near as versatile as printf() s << va_arg(ap, double); break; case 'C': long_argument = true; // fall through case 'c': if (long_argument) { throw ValueError("format string error (wchar_t is considered a broken type)"); } else { s << (char)va_arg(ap, int); } break; case 'S': long_argument = true; // fall through case 's': if (long_argument) { throw ValueError("format string error (wchar_t* is considered a broken type)"); } else { char *cs = va_arg(ap, char *); if (cs == nullptr) { s << "(nullptr)"; } else { s << cs; } } break; // print an object's repr() case 'q': { Base *q = va_arg(ap, Base *); s << q->repr(); } break; // print an object's str() case 'v': { Base *v = va_arg(ap, Base *); s << v->str(); } break; // print pointer value case 'p': { long p = (long)va_arg(ap, void *); if (!p) { s << "(nullptr)"; } else { s << std::hex << std::showbase << p << std::noshowbase; } } break; // boolean value case 't': s << ((bool)va_arg(ap, int) ? "true" : "false"); break; // unicode value case 'U': s << "U+" << std::setfill('0') << std::setw(4) << std::hex << std::noshowbase << (rune)va_arg(ap, rune); break; // rune case 'r': { String rs((rune)va_arg(ap, rune)); s << rs.str(); } break; // the percent sign case '%': s << '%'; break; default: throw ValueError("format string error (unsupported modifier)"); } } else { s << *fmt; } if (*fmt) { fmt++; } } } void ssprint(std::stringstream& s, const char *fmt, ...) { if (fmt == nullptr) { throw ReferenceError(); } if (!*fmt) { return; } std::va_list ap; va_start(ap, fmt); vssprint(s, fmt, ap); va_end(ap); } // vprint to output stream void vosprint(std::ostream& os, const char *fmt, std::va_list ap) { if (fmt == nullptr) { throw ReferenceError(); } if (!*fmt) { return; } std::stringstream s; vssprint(s, fmt, ap); printer_lock.lock(); os << s.str() << std::endl; printer_lock.unlock(); } // vprint to output stream without newline void vosprintn(std::ostream& os, const char *fmt, std::va_list ap) { if (fmt == nullptr) { throw ReferenceError(); } if (!*fmt) { return; } std::stringstream s; vssprint(s, fmt, ap); printer_lock.lock(); os << s.str(); printer_lock.unlock(); } void print(void) { printer_lock.lock(); std::cout << std::endl; printer_lock.unlock(); } void print(const char *fmt, ...) { if (fmt == nullptr) { throw ReferenceError(); } std::va_list ap; va_start(ap, fmt); vosprint(std::cout, fmt, ap); va_end(ap); } void printn(const char *fmt, ...) { if (fmt == nullptr) { throw ReferenceError(); } std::va_list ap; va_start(ap, fmt); vosprintn(std::cout, fmt, ap); va_end(ap); } void printerr(void) { printer_lock.lock(); std::cerr << std::endl; printer_lock.unlock(); } void printerr(const char *fmt, ...) { if (fmt == nullptr) { throw ReferenceError(); } std::va_list ap; va_start(ap, fmt); vosprint(std::cerr, fmt, ap); va_end(ap); } void printnerr(const char *fmt, ...) { if (fmt == nullptr) { throw ReferenceError(); } std::va_list ap; va_start(ap, fmt); vosprintn(std::cerr, fmt, ap); va_end(ap); } } // namespace // EOB
20.125
85
0.548248
[ "object" ]
9917c6534f00effa143f181744e43fd6063c0a33
637
cpp
C++
1101-9999/1626. Best Team With No Conflicts.cpp
erichuang1994/leetcode-solution
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
[ "MIT" ]
null
null
null
1101-9999/1626. Best Team With No Conflicts.cpp
erichuang1994/leetcode-solution
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
[ "MIT" ]
null
null
null
1101-9999/1626. Best Team With No Conflicts.cpp
erichuang1994/leetcode-solution
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
[ "MIT" ]
null
null
null
class Solution { public: int bestTeamScore(vector<int> &scores, vector<int> &ages) { vector<pair<int, int>> vec; int len = ages.size(); int maxAge = INT_MIN; for (int i = 0; i < len; i++) { vec.emplace_back(scores[i], ages[i]); maxAge = max(maxAge, ages[i]); } sort(vec.begin(), vec.end()); vector<int> f(maxAge + 1, 0); for (auto &p : vec) { int v = p.first; for (int i = 0; i <= p.second; i++) { v = max(v, f[i] + p.first); } f[p.second] = v; } int ret = INT_MIN; for (auto &n : f) ret = max(ret, n); return ret; } };
21.233333
59
0.485086
[ "vector" ]
991e8fe63dd34ddbbcec770cd05424968f72b077
3,211
hpp
C++
blast/include/objtools/readers/microarray_reader.hpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
blast/include/objtools/readers/microarray_reader.hpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
blast/include/objtools/readers/microarray_reader.hpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
/* $Id: microarray_reader.hpp 632526 2021-06-02 17:25:01Z ivanov $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Frank Ludwig * * File Description: * BED file reader * */ #ifndef OBJTOOLS_READERS___MICROARRAYREADER__HPP #define OBJTOOLS_READERS___MICROARRAYREADER__HPP #include <corelib/ncbistd.hpp> #include <objects/seq/Seq_annot.hpp> #include <objtools/readers/reader_base.hpp> BEGIN_NCBI_SCOPE BEGIN_objects_SCOPE class CReaderListener; // ---------------------------------------------------------------------------- class NCBI_XOBJREAD_EXPORT CMicroArrayReader // ---------------------------------------------------------------------------- : public CReaderBase { public: enum { fDefaults = 0, fReadAsBed = (1 << 0), // discard MicroArray specific columns // and produce regular BED seq-annot }; public: CMicroArrayReader( int =fDefaults, CReaderListener* = nullptr ); virtual ~CMicroArrayReader(); virtual CRef<CSeq_annot> ReadSeqAnnot( ILineReader&, ILineErrorListener* = nullptr ); protected: virtual CRef<CSeq_annot> xCreateSeqAnnot(); virtual void xGetData( ILineReader&, TReaderData&); virtual void xProcessData( const TReaderData&, CSeq_annot&); virtual bool xProcessTrackLine( const string&); bool xProcessFeature( const string&, CSeq_annot&); void xSetFeatureLocation( CRef<CSeq_feat>&, const vector<string>& ); void xSetFeatureDisplayData( CRef<CSeq_feat>&, const vector<string>& ); static void xCleanColumnValues( vector<string>&); protected: string m_currentId; vector<string>::size_type m_columncount; bool m_usescore; string m_strExpNames; int m_iExpScale; int m_iExpStep; }; END_objects_SCOPE END_NCBI_SCOPE #endif // OBJTOOLS_READERS___MICROARRAYREADER__HPP
28.669643
80
0.620367
[ "vector" ]
992465696f4aaf902928bb5bf4476ee8b313c767
24,496
hpp
C++
Sisyphe/cppbase/src/interpreter/cppFileInterpreterAccess_impl.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
Sisyphe/cppbase/src/interpreter/cppFileInterpreterAccess_impl.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
Sisyphe/cppbase/src/interpreter/cppFileInterpreterAccess_impl.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
#define A(str) encode<EncodingT,ansi>(str) #define C(str) encode<ansi,EncodingT>(str) NAMESPACE_BEGIN(interp) template <class EncodingT> CppFileInterpreterAccess<EncodingT>::CppFileInterpreterAccess() { m_object = _CppFileAccess<EncodingT>::getInstance(); m_error = false; } template <class EncodingT> typename EncodingT::string_t CppFileInterpreterAccess<EncodingT>::toString() const { return EncodingT::EMPTY; } template <class EncodingT> boost::shared_ptr< Base<EncodingT> > CppFileInterpreterAccess<EncodingT>::clone() const { return boost::shared_ptr< Base<EncodingT> >(new CppFileInterpreterAccess<EncodingT>()); } template <class EncodingT> typename EncodingT::string_t CppFileInterpreterAccess<EncodingT>::getClassName() const { return UCS("CppFileAccess"); } template <class EncodingT> boost::shared_ptr< Base<EncodingT> > CppFileInterpreterAccess<EncodingT>::invoke(const typename EncodingT::string_t& method, std::vector< boost::shared_ptr< Base<EncodingT> > >& params) { boost::shared_ptr< Base<EncodingT> > obj(new Base<EncodingT>()); ParameterArray args, ret; if (check_parameters_array(params, args)) { if (tryInvoke(this, UCS("CppFileAccess"), method, args, ret) || tryInvoke(this, UCS("Base"), method, args, ret)) { find_parameter(ret, FACTORY_RETURN_PARAMETER, obj); for (size_t i = 0; i < params.size(); ++i) { find_parameter(ret, i, params[i]); } } else { Category* logger = &Category::getInstance(LOGNAME); logger->errorStream() << "Unexpected call in CppFileAccess, no method \"" << A(method) << "\" exists."; } } return obj; } template <class EncodingT> boost::shared_ptr< Base<EncodingT> > CppFileInterpreterAccess<EncodingT>::convert_array(const std::vector< boost::shared_ptr< _CppFile<EncodingT> > >& value) const { boost::shared_ptr< Array<EncodingT> > arr(new Array<EncodingT>()); for (size_t i=0; i<value.size(); ++i) { arr->addValue(boost::shared_ptr< Base<EncodingT> >(new CppFileInterpreter<EncodingT>(value[i]))); } return arr; } template <class EncodingT> boost::shared_ptr< Base<EncodingT> > CppFileInterpreterAccess<EncodingT>::getAllCppFiles() { boost::shared_ptr< Base<EncodingT> > res(new Array<EncodingT>()); clearError(); try { res = convert_array(m_object->getAllCppFiles()); } catch (std::exception& e) { setError(e); } return res; } template <class EncodingT> boost::shared_ptr< Base<EncodingT> > CppFileInterpreterAccess<EncodingT>::getManyCppFiles(const boost::shared_ptr< Base<EncodingT> >& filter) { boost::shared_ptr< Base<EncodingT> > res(new Array<EncodingT>()); clearError(); try { typename EncodingT::string_t nativeFilter; if (check_string<EncodingT>(filter, nativeFilter)) { res = convert_array(m_object->getManyCppFiles(nativeFilter)); } } catch (std::exception& e) { setError(e); } return res; } template <class EncodingT> boost::shared_ptr< Base<EncodingT> > CppFileInterpreterAccess<EncodingT>::getOneCppFile(boost::shared_ptr< Base<EncodingT> > const& identifier) { boost::shared_ptr< CppFileInterpreter<EncodingT> > res(new CppFileInterpreter<EncodingT>()); clearError(); try { long long nativeIdentifier; if (check_numeric_i(identifier, nativeIdentifier)) { res->value(m_object->getOneCppFile(nativeIdentifier)); } } catch (std::exception& e) { setError(e); } return res; } template <class EncodingT> boost::shared_ptr< Base<EncodingT> > CppFileInterpreterAccess<EncodingT>::selectOneCppFile(boost::shared_ptr< Base<EncodingT> > const& identifier, const boost::shared_ptr< Base<EncodingT> >& nowait) { boost::shared_ptr< CppFileInterpreter<EncodingT> > res(new CppFileInterpreter<EncodingT>()); clearError(); try { bool nativeNoWait; long long nativeIdentifier; if (check_numeric_i(identifier, nativeIdentifier) && check_bool(nowait, nativeNoWait)) { res->value(m_object->selectOneCppFile(nativeIdentifier, nativeNoWait)); } } catch (std::exception& e) { setError(e); } return res; } template <class EncodingT> boost::shared_ptr< Base<EncodingT> > CppFileInterpreterAccess<EncodingT>::selectManyCppFiles(const boost::shared_ptr< Base<EncodingT> >& filter, const boost::shared_ptr< Base<EncodingT> >& nowait) { boost::shared_ptr< Base<EncodingT> > res(new Array<EncodingT>()); clearError(); try { typename EncodingT::string_t nativeFilter; bool nativeNoWait; if (check_string<EncodingT>(filter, nativeFilter) && check_bool(nowait, nativeNoWait)) { res = convert_array(m_object->selectManyCppFiles(nativeFilter, nativeNoWait)); } } catch (std::exception& e) { setError(e); } return res; } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::cancelSelection() { clearError(); try { m_object->cancelSelection(); } catch (std::exception& e) { setError(e); } } template <class EncodingT> boost::shared_ptr< Base<EncodingT> > CppFileInterpreterAccess<EncodingT>::isSelectedCppFile(const boost::shared_ptr< Base<EncodingT> >& cppFile) { boost::shared_ptr< Bool<EncodingT> > res(new Bool<EncodingT>()); clearError(); try { boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile)) { res->value(m_object->isSelectedCppFile(nativeCppFile)); } } catch (std::exception& e) { setError(e); } return res; } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillTextFile(boost::shared_ptr< Base<EncodingT> >& cppFile) { clearError(); try { boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile)) { m_object->fillTextFile(nativeCppFile); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillCppFileType(boost::shared_ptr< Base<EncodingT> >& cppFile) { clearError(); try { boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile)) { m_object->fillCppFileType(nativeCppFile); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillAllCppDeclarationFunctions(boost::shared_ptr< Base<EncodingT> >& cppFile, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile) && check_bool(nowait, nativeNoWait)) { m_object->fillAllCppDeclarationFunctions(nativeCppFile, nativeNoWait); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillAllCppDefinitionFunctions(boost::shared_ptr< Base<EncodingT> >& cppFile, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile) && check_bool(nowait, nativeNoWait)) { m_object->fillAllCppDefinitionFunctions(nativeCppFile, nativeNoWait); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillAllCppClasss(boost::shared_ptr< Base<EncodingT> >& cppFile, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile) && check_bool(nowait, nativeNoWait)) { m_object->fillAllCppClasss(nativeCppFile, nativeNoWait); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillAllCppIncludes(boost::shared_ptr< Base<EncodingT> >& cppFile, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile) && check_bool(nowait, nativeNoWait)) { m_object->fillAllCppIncludes(nativeCppFile, nativeNoWait); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillAllCppVariables(boost::shared_ptr< Base<EncodingT> >& cppFile, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile) && check_bool(nowait, nativeNoWait)) { m_object->fillAllCppVariables(nativeCppFile, nativeNoWait); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillAllCppEnums(boost::shared_ptr< Base<EncodingT> >& cppFile, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile) && check_bool(nowait, nativeNoWait)) { m_object->fillAllCppEnums(nativeCppFile, nativeNoWait); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillAllCMacros(boost::shared_ptr< Base<EncodingT> >& cppFile, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile) && check_bool(nowait, nativeNoWait)) { m_object->fillAllCMacros(nativeCppFile, nativeNoWait); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillAllCppNotices(boost::shared_ptr< Base<EncodingT> >& cppFile, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile) && check_bool(nowait, nativeNoWait)) { m_object->fillAllCppNotices(nativeCppFile, nativeNoWait); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillOneCppDeclarationFunction(boost::shared_ptr< Base<EncodingT> >& refCppFile, const boost::shared_ptr< Base<EncodingT> >& identifier, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; boost::shared_ptr< _CppFile<EncodingT> > nativeRefCppFile; long long nativeIdentifier; if (check_cppFile(refCppFile, nativeRefCppFile) && check_numeric_i(identifier, nativeIdentifier) && check_bool(nowait, nativeNoWait)) { m_object->fillOneCppDeclarationFunction(nativeRefCppFile, nativeIdentifier, nativeNoWait); reset_cppFile(refCppFile, nativeRefCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillOneCppDefinitionFunction(boost::shared_ptr< Base<EncodingT> >& refCppFile, const boost::shared_ptr< Base<EncodingT> >& identifier, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; boost::shared_ptr< _CppFile<EncodingT> > nativeRefCppFile; long long nativeIdentifier; if (check_cppFile(refCppFile, nativeRefCppFile) && check_numeric_i(identifier, nativeIdentifier) && check_bool(nowait, nativeNoWait)) { m_object->fillOneCppDefinitionFunction(nativeRefCppFile, nativeIdentifier, nativeNoWait); reset_cppFile(refCppFile, nativeRefCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillOneCppClass(boost::shared_ptr< Base<EncodingT> >& refCppFile, const boost::shared_ptr< Base<EncodingT> >& identifier, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; boost::shared_ptr< _CppFile<EncodingT> > nativeRefCppFile; long long nativeIdentifier; if (check_cppFile(refCppFile, nativeRefCppFile) && check_numeric_i(identifier, nativeIdentifier) && check_bool(nowait, nativeNoWait)) { m_object->fillOneCppClass(nativeRefCppFile, nativeIdentifier, nativeNoWait); reset_cppFile(refCppFile, nativeRefCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillOneCppInclude(boost::shared_ptr< Base<EncodingT> >& refCppFile, const boost::shared_ptr< Base<EncodingT> >& identifier, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; boost::shared_ptr< _CppFile<EncodingT> > nativeRefCppFile; long long nativeIdentifier; if (check_cppFile(refCppFile, nativeRefCppFile) && check_numeric_i(identifier, nativeIdentifier) && check_bool(nowait, nativeNoWait)) { m_object->fillOneCppInclude(nativeRefCppFile, nativeIdentifier, nativeNoWait); reset_cppFile(refCppFile, nativeRefCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillOneCppVariable(boost::shared_ptr< Base<EncodingT> >& refCppFile, const boost::shared_ptr< Base<EncodingT> >& identifier, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; boost::shared_ptr< _CppFile<EncodingT> > nativeRefCppFile; long long nativeIdentifier; if (check_cppFile(refCppFile, nativeRefCppFile) && check_numeric_i(identifier, nativeIdentifier) && check_bool(nowait, nativeNoWait)) { m_object->fillOneCppVariable(nativeRefCppFile, nativeIdentifier, nativeNoWait); reset_cppFile(refCppFile, nativeRefCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillOneCppEnum(boost::shared_ptr< Base<EncodingT> >& refCppFile, const boost::shared_ptr< Base<EncodingT> >& identifier, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; boost::shared_ptr< _CppFile<EncodingT> > nativeRefCppFile; long long nativeIdentifier; if (check_cppFile(refCppFile, nativeRefCppFile) && check_numeric_i(identifier, nativeIdentifier) && check_bool(nowait, nativeNoWait)) { m_object->fillOneCppEnum(nativeRefCppFile, nativeIdentifier, nativeNoWait); reset_cppFile(refCppFile, nativeRefCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillOneCMacro(boost::shared_ptr< Base<EncodingT> >& refCppFile, const boost::shared_ptr< Base<EncodingT> >& identifier, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; boost::shared_ptr< _CppFile<EncodingT> > nativeRefCppFile; long long nativeIdentifier; if (check_cppFile(refCppFile, nativeRefCppFile) && check_numeric_i(identifier, nativeIdentifier) && check_bool(nowait, nativeNoWait)) { m_object->fillOneCMacro(nativeRefCppFile, nativeIdentifier, nativeNoWait); reset_cppFile(refCppFile, nativeRefCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillOneCppNotice(boost::shared_ptr< Base<EncodingT> >& refCppFile, const boost::shared_ptr< Base<EncodingT> >& identifier, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; boost::shared_ptr< _CppFile<EncodingT> > nativeRefCppFile; long long nativeIdentifier; if (check_cppFile(refCppFile, nativeRefCppFile) && check_numeric_i(identifier, nativeIdentifier) && check_bool(nowait, nativeNoWait)) { m_object->fillOneCppNotice(nativeRefCppFile, nativeIdentifier, nativeNoWait); reset_cppFile(refCppFile, nativeRefCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillManyCppDeclarationFunctions(boost::shared_ptr< Base<EncodingT> >& cppFile, const boost::shared_ptr< Base<EncodingT> >& filter, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; typename EncodingT::string_t nativeFilter; boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile) && check_string<EncodingT>(filter, nativeFilter) && check_bool(nowait, nativeNoWait)) { m_object->fillManyCppDeclarationFunctions(nativeCppFile, nativeFilter, nativeNoWait); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillManyCppDefinitionFunctions(boost::shared_ptr< Base<EncodingT> >& cppFile, const boost::shared_ptr< Base<EncodingT> >& filter, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; typename EncodingT::string_t nativeFilter; boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile) && check_string<EncodingT>(filter, nativeFilter) && check_bool(nowait, nativeNoWait)) { m_object->fillManyCppDefinitionFunctions(nativeCppFile, nativeFilter, nativeNoWait); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillManyCppClasss(boost::shared_ptr< Base<EncodingT> >& cppFile, const boost::shared_ptr< Base<EncodingT> >& filter, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; typename EncodingT::string_t nativeFilter; boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile) && check_string<EncodingT>(filter, nativeFilter) && check_bool(nowait, nativeNoWait)) { m_object->fillManyCppClasss(nativeCppFile, nativeFilter, nativeNoWait); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillManyCppIncludes(boost::shared_ptr< Base<EncodingT> >& cppFile, const boost::shared_ptr< Base<EncodingT> >& filter, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; typename EncodingT::string_t nativeFilter; boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile) && check_string<EncodingT>(filter, nativeFilter) && check_bool(nowait, nativeNoWait)) { m_object->fillManyCppIncludes(nativeCppFile, nativeFilter, nativeNoWait); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillManyCppVariables(boost::shared_ptr< Base<EncodingT> >& cppFile, const boost::shared_ptr< Base<EncodingT> >& filter, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; typename EncodingT::string_t nativeFilter; boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile) && check_string<EncodingT>(filter, nativeFilter) && check_bool(nowait, nativeNoWait)) { m_object->fillManyCppVariables(nativeCppFile, nativeFilter, nativeNoWait); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillManyCppEnums(boost::shared_ptr< Base<EncodingT> >& cppFile, const boost::shared_ptr< Base<EncodingT> >& filter, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; typename EncodingT::string_t nativeFilter; boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile) && check_string<EncodingT>(filter, nativeFilter) && check_bool(nowait, nativeNoWait)) { m_object->fillManyCppEnums(nativeCppFile, nativeFilter, nativeNoWait); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillManyCMacros(boost::shared_ptr< Base<EncodingT> >& cppFile, const boost::shared_ptr< Base<EncodingT> >& filter, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; typename EncodingT::string_t nativeFilter; boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile) && check_string<EncodingT>(filter, nativeFilter) && check_bool(nowait, nativeNoWait)) { m_object->fillManyCMacros(nativeCppFile, nativeFilter, nativeNoWait); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::fillManyCppNotices(boost::shared_ptr< Base<EncodingT> >& cppFile, const boost::shared_ptr< Base<EncodingT> >& filter, const boost::shared_ptr< Base<EncodingT> >& nowait) { clearError(); try { bool nativeNoWait; typename EncodingT::string_t nativeFilter; boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile) && check_string<EncodingT>(filter, nativeFilter) && check_bool(nowait, nativeNoWait)) { m_object->fillManyCppNotices(nativeCppFile, nativeFilter, nativeNoWait); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> boost::shared_ptr< Base<EncodingT> > CppFileInterpreterAccess<EncodingT>::isModifiedCppFile(const boost::shared_ptr< Base<EncodingT> >& cppFile) { boost::shared_ptr< Bool<EncodingT> > res(new Bool<EncodingT>()); clearError(); try { boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile)) { res->value(m_object->isModifiedCppFile(nativeCppFile)); } } catch (std::exception& e) { setError(e); } return res; } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::updateCppFile(boost::shared_ptr< Base<EncodingT> >& cppFile) { clearError(); try { boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile)) { m_object->updateCppFile(nativeCppFile); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::insertCppFile(boost::shared_ptr< Base<EncodingT> >& cppFile) { clearError(); try { boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile)) { m_object->insertCppFile(nativeCppFile); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::deleteCppFile(boost::shared_ptr< Base<EncodingT> >& cppFile) { clearError(); try { boost::shared_ptr< _CppFile<EncodingT> > nativeCppFile; if (check_cppFile(cppFile, nativeCppFile)) { m_object->deleteCppFile(nativeCppFile); reset_cppFile(cppFile, nativeCppFile); } } catch (std::exception& e) { setError(e); } } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::setError(const std::exception& error) { m_error = true; m_errorText = error.what(); } template <class EncodingT> void CppFileInterpreterAccess<EncodingT>::clearError() { m_error = false; m_errorText.clear(); } template <class EncodingT> boost::shared_ptr< Base<EncodingT> > CppFileInterpreterAccess<EncodingT>::getError(boost::shared_ptr< Base<EncodingT> >& text) const { boost::shared_ptr< String<EncodingT> > str = dynamic_pointer_cast< String<EncodingT> >(text); if (str) { str->value(C(m_errorText)); } return boost::shared_ptr< Base<EncodingT> >(new Bool<EncodingT>(m_error)); } NAMESPACE_END #undef C #undef A
26.713195
224
0.738161
[ "vector" ]
992799ef8d3f7c766aa93a9c0260504f67f9e136
473
cpp
C++
InterviewBit/Greedy Algorithm/Distribute Candy.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
InterviewBit/Greedy Algorithm/Distribute Candy.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
InterviewBit/Greedy Algorithm/Distribute Candy.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
// https://www.interviewbit.com/problems/distribute-candy/ int Solution::candy(vector<int> &A) { int n = A.size(); int choc[n]; fill_n(choc, n, 1); for(int i=1;i<n;i++) { if(A[i]>A[i-1]) choc[i]= choc[i-1]+1; } for(int i=n-2;i>=0;i--) if(A[i]>A[i+1] && choc[i]<=choc[i+1]) choc[i] = 1+choc[i+1]; int ans = 0; for(int i=0;i<n;i++) ans += choc[i]; return ans; }
18.92
59
0.439746
[ "vector" ]
992b8ede8ea8133ec80c6155d9ed9131dcb88f6c
6,621
cpp
C++
cores/n64/custom/GLideN64/mupenplus/Config_mupenplus.cpp
wulfebw/retro
dad4b509e99e729e39a2f27e9ee4120e3b607f58
[ "MIT-0", "MIT" ]
7
2020-07-20T12:11:35.000Z
2021-12-23T02:09:19.000Z
cores/n64/custom/GLideN64/mupenplus/Config_mupenplus.cpp
wulfebw/retro
dad4b509e99e729e39a2f27e9ee4120e3b607f58
[ "MIT-0", "MIT" ]
null
null
null
cores/n64/custom/GLideN64/mupenplus/Config_mupenplus.cpp
wulfebw/retro
dad4b509e99e729e39a2f27e9ee4120e3b607f58
[ "MIT-0", "MIT" ]
1
2020-08-29T16:36:48.000Z
2020-08-29T16:36:48.000Z
#include "GLideN64_mupenplus.h" #include "GLideN64_libretro.h" #include <assert.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <algorithm> #include "../Config.h" #include "../GLideN64.h" #include "../GBI.h" #include "../RSP.h" #include "../Log.h" extern "C" { #include "main/util.h" #include "GLideN64.custom.ini.h" } Config config; std::string replaceChars(std::string myString) { for (size_t pos = myString.find(' '); pos != std::string::npos; pos = myString.find(' ', pos)) { myString.replace(pos, 1, "%20"); } for (size_t pos = myString.find('\''); pos != std::string::npos; pos = myString.find('\'', pos)) { myString.replace(pos, 1, "%27"); } return myString; } void LoadCustomSettings(bool internal) { std::string myString = replaceChars(RSP.romname); bool found = false; char buffer[256]; char* line; FILE* fPtr; std::transform(myString.begin(), myString.end(), myString.begin(), ::toupper); if (internal) { line = strtok(customini, "\n"); } else { const char *pathname = ConfigGetSharedDataFilepath("GLideN64.custom.ini"); if (pathname == NULL || (fPtr = fopen(pathname, "rb")) == NULL) return; } while (true) { if (!internal) { if (fgets(buffer, 255, fPtr) == NULL) break; else line = buffer; } ini_line l = ini_parse_line(&line); switch (l.type) { case INI_SECTION: { if (myString == replaceChars(l.name)) found = true; else found = false; } case INI_PROPERTY: { if (found) { if (!strcmp(l.name, "video\\multisampling")) config.video.multisampling = atoi(l.value); else if (!strcmp(l.name, "frameBufferEmulation\\aspect")) config.frameBufferEmulation.aspect = atoi(l.value); else if (!strcmp(l.name, "frameBufferEmulation\\nativeResFactor")) config.frameBufferEmulation.nativeResFactor = atoi(l.value); else if (!strcmp(l.name, "frameBufferEmulation\\copyToRDRAM")) config.frameBufferEmulation.copyToRDRAM = atoi(l.value); else if (!strcmp(l.name, "frameBufferEmulation\\copyFromRDRAM")) config.frameBufferEmulation.copyFromRDRAM = atoi(l.value); else if (!strcmp(l.name, "frameBufferEmulation\\copyDepthToRDRAM")) config.frameBufferEmulation.copyDepthToRDRAM = atoi(l.value); else if (!strcmp(l.name, "frameBufferEmulation\\copyAuxToRDRAM")) config.frameBufferEmulation.copyAuxToRDRAM = atoi(l.value); else if (!strcmp(l.name, "frameBufferEmulation\\fbInfoDisabled")) config.frameBufferEmulation.fbInfoDisabled = atoi(l.value); else if (!strcmp(l.name, "frameBufferEmulation\\N64DepthCompare")) config.frameBufferEmulation.N64DepthCompare = atoi(l.value); else if (!strcmp(l.name, "frameBufferEmulation\\bufferSwapMode")) config.frameBufferEmulation.bufferSwapMode = atoi(l.value); else if (!strcmp(l.name, "texture\\bilinearMode")) config.texture.bilinearMode = atoi(l.value); else if (!strcmp(l.name, "texture\\maxAnisotropy")) config.texture.maxAnisotropy = atoi(l.value); else if (!strcmp(l.name, "generalEmulation\\enableNativeResTexrects")) config.graphics2D.enableNativeResTexrects = atoi(l.value); else if (!strcmp(l.name, "generalEmulation\\correctTexrectCoords")) config.graphics2D.correctTexrectCoords = atoi(l.value); else if (!strcmp(l.name, "generalEmulation\\enableLegacyBlending")) config.generalEmulation.enableLegacyBlending = atoi(l.value); else if (!strcmp(l.name, "generalEmulation\\enableFragmentDepthWrite")) config.generalEmulation.enableFragmentDepthWrite = atoi(l.value); } } } if (internal) { line = strtok(NULL, "\n"); if (line == NULL) break; } } } extern "C" void Config_LoadConfig() { u32 hacks = config.generalEmulation.hacks; config.resetToDefaults(); config.frameBufferEmulation.aspect = AspectRatio; config.frameBufferEmulation.enable = EnableFBEmulation; config.frameBufferEmulation.N64DepthCompare = EnableN64DepthCompare; config.texture.bilinearMode = bilinearMode; config.generalEmulation.enableHWLighting = EnableHWLighting; config.generalEmulation.enableLegacyBlending = enableLegacyBlending; config.generalEmulation.enableNoise = EnableNoiseEmulation; config.generalEmulation.enableLOD = EnableLODEmulation; config.frameBufferEmulation.copyDepthToRDRAM = EnableCopyDepthToRDRAM; #if defined(GLES2) && !defined(ANDROID) config.frameBufferEmulation.copyToRDRAM = Config::ctDisable; #else config.frameBufferEmulation.copyToRDRAM = EnableCopyColorToRDRAM; #endif #ifdef HAVE_OPENGLES config.frameBufferEmulation.bufferSwapMode = Config::bsOnColorImageChange; #endif #ifdef HAVE_OPENGLES2 config.generalEmulation.enableFragmentDepthWrite = 0; #else config.generalEmulation.enableFragmentDepthWrite = EnableFragmentDepthWrite; #endif #ifdef VC config.generalEmulation.enableShadersStorage = 0; #else config.generalEmulation.enableShadersStorage = EnableShadersStorage; #endif config.textureFilter.txSaveCache = EnableTextureCache; config.textureFilter.txFilterMode = txFilterMode; config.textureFilter.txEnhancementMode = txEnhancementMode; config.textureFilter.txFilterIgnoreBG = txFilterIgnoreBG; config.textureFilter.txHiresEnable = txHiresEnable; config.textureFilter.txCacheCompression = EnableTxCacheCompression; config.textureFilter.txHiresFullAlphaChannel = txHiresFullAlphaChannel; config.video.fxaa = EnableFXAA; config.video.multisampling = MultiSampling; // Overscan config.frameBufferEmulation.enableOverscan = EnableOverscan; // NTSC config.frameBufferEmulation.overscanNTSC.left = OverscanLeft; config.frameBufferEmulation.overscanNTSC.right = OverscanRight; config.frameBufferEmulation.overscanNTSC.top = OverscanTop; config.frameBufferEmulation.overscanNTSC.bottom = OverscanBottom; // PAL config.frameBufferEmulation.overscanPAL.left = OverscanLeft; config.frameBufferEmulation.overscanPAL.right = OverscanRight; config.frameBufferEmulation.overscanPAL.top = OverscanTop; config.frameBufferEmulation.overscanPAL.bottom = OverscanBottom; config.graphics2D.correctTexrectCoords = CorrectTexrectCoords; config.graphics2D.enableNativeResTexrects = enableNativeResTexrects; config.graphics2D.bgMode = BackgroundMode; config.textureFilter.txEnhancedTextureFileStorage = EnableEnhancedTextureStorage; config.textureFilter.txHiresTextureFileStorage = EnableEnhancedHighResStorage; config.frameBufferEmulation.nativeResFactor = EnableNativeResFactor; config.generalEmulation.hacks = hacks; LoadCustomSettings(true); LoadCustomSettings(false); }
35.596774
97
0.747621
[ "transform" ]
992f9bee0c5076e6577881f92b851363ff437061
4,694
cpp
C++
smart-darkgdk/include/Sprite.cpp
endel/smart-darkgdk
6235288b8aab505577223f9544a6e5a7eb6bf6cd
[ "MIT" ]
null
null
null
smart-darkgdk/include/Sprite.cpp
endel/smart-darkgdk
6235288b8aab505577223f9544a6e5a7eb6bf6cd
[ "MIT" ]
null
null
null
smart-darkgdk/include/Sprite.cpp
endel/smart-darkgdk
6235288b8aab505577223f9544a6e5a7eb6bf6cd
[ "MIT" ]
null
null
null
#include "Commonobject.h" #include "../Game.h" #include "Sprite.h" #include "DarkGDK.h" Sprite::Sprite(char* filename, int x, int y) { this->setId(Game::getSpriteId()); Image* img = new Image(filename); dbSprite(this->id, x, y, img->id); resetTextureOffset(); } Sprite::Sprite(int n) { setId(n); } //-- Sprite::Sprite(int p_x, int p_y, Image* p_image) { this->setId(Game::getSpriteId()); dbSprite(this->id, 0, 0, p_image->id); dbOffsetSprite(this->id, p_x, p_y); resetTextureOffset(); } //-- Sprite::Sprite(int p_x, int p_y, Image* p_image, int p_framesAcross, int p_framesDown, char* name) { this->setId(Game::getSpriteId()); dbCreateAnimatedSprite(this->id, name, p_framesAcross, p_framesDown, p_image->id); dbSprite(this->id, p_x, p_y, p_image->id); resetTextureOffset(); } //-- Sprite::Sprite(char* filename, char* animation_name, int p_framesAcross, int p_framesDown) { this->setId(Game::getSpriteId()); Image* img = new Image(filename); dbCreateAnimatedSprite(this->id, animation_name, p_framesAcross, p_framesDown, img->id); resetTextureOffset(); } //-- Sprite::~Sprite(void) { dbDeleteSprite(this->id); } void Sprite::resetTextureOffset() { this->offsetTextureU = 0; this->offsetTextureV = 0; } void Sprite::load(char* filename, int x, int y) { this->setId(Game::getSpriteId()); Image* img = new Image(filename); dbSprite(this->id, x, y, img->id); resetTextureOffset(); } //------------------------------------------------ // TRANSFORM //------------------------------------------------ void Sprite::position(int p_x, int p_y) { dbOffsetSprite(this->id, -p_x, -p_y); } //-- void Sprite::translate(int p_x, int p_y) { dbOffsetSprite(this->id, dbSpriteOffsetX(this->id) - p_x, dbSpriteOffsetY(this->id) - p_y); } //-- void Sprite::rotation(float p_angle) { dbRotateSprite(this->id, p_angle); } //-- void Sprite::rotate(float p_angle) { dbRotateSprite(this->id, dbSpriteAngle(this->id) + p_angle); } //-- void Sprite::scale(int p_x, int p_y) { dbSizeSprite(this->id, p_x, p_y); } //-- void Sprite::mirror(bool p_x, bool p_y) { if(p_x) dbMirrorSprite(this->id); if(p_y) dbFlipSprite(this->id); } //-- //------------------------------------------------ // VISIBILITY //------------------------------------------------ void Sprite::play(int p_start, int p_end, int p_delay) { dbPlaySprite(this->id, p_start, p_end, p_delay); } //-- void Sprite::changeImage(Image* p_image) { dbSetSpriteImage(this->id, p_image->id); } //-- void Sprite::offsetTexture(float p_offestU, float p_offsetV, float p_velocity) { offsetTextureU += p_offestU * p_velocity; offsetTextureV += p_offsetV * p_velocity; dbSetSpriteTextureCoord(this->id, 0, 0 + offsetTextureU, 0 + offsetTextureV); dbSetSpriteTextureCoord(this->id, 1, 1 + offsetTextureU, 0 + offsetTextureV); dbSetSpriteTextureCoord(this->id, 2, 0 + offsetTextureU, 1 + offsetTextureV); dbSetSpriteTextureCoord(this->id, 3, 1 + offsetTextureU, 1 + offsetTextureV); } //-- void Sprite::color(int p_r, int p_g, int p_b) { dbSetSpriteDiffuse(this->id, p_r, p_g, p_b); } //-- void Sprite::show() { dbShowSprite(this->id); } //-- void Sprite::hide() { dbHideSprite(this->id); } //-- void Sprite::toggle() { if (isVisible()) hide(); else show(); } //------------------------------------------------ // GETTERS //------------------------------------------------ Sprite* Sprite::hit() { return new Sprite( dbSpriteHit(this->id, 0) ); } Sprite* Sprite::collision() { return new Sprite( dbSpriteCollision(this->id, 0) ); } bool Sprite::hit(Sprite *s) { return (bool) dbSpriteHit(this->id, s->id); } bool Sprite::collision(Sprite *s) { return (bool) dbSpriteCollision(this->id, s->id); } bool Sprite::exists() { return dbSpriteExist(this->id); } int Sprite::getPositionX() { return dbSpriteOffsetX(this->id); } //-- int Sprite::getPositionY() { return dbSpriteOffsetY(this->id); } //-- int Sprite::getWidth() { return dbSpriteWidth(this->id); } //-- int Sprite::getHeight() { return dbSpriteHeight(this->id); } //-- float Sprite::getAngle() { return dbSpriteAngle(this->id); } //-- int Sprite::isVisible() { return dbSpriteVisible(this->id); } //-- int Sprite::getColorR() { return dbSpriteRed(this->id); } //-- int Sprite::getColorG() { return dbSpriteGreen(this->id); } //-- int Sprite::getColorB() { return dbSpriteBlue(this->id); } //--
16.186207
99
0.588837
[ "transform" ]
9935f4eeed45ee059bc20dbd5ce34c680bd89094
2,201
cpp
C++
src/brew/fileio/LocalFileSystem.cpp
grrrrunz/brew
13e17e2f6c9fb0f612c3a0bcabd233085ca15867
[ "MIT" ]
1
2018-02-09T16:20:50.000Z
2018-02-09T16:20:50.000Z
src/brew/fileio/LocalFileSystem.cpp
grrrrunz/brew
13e17e2f6c9fb0f612c3a0bcabd233085ca15867
[ "MIT" ]
null
null
null
src/brew/fileio/LocalFileSystem.cpp
grrrrunz/brew
13e17e2f6c9fb0f612c3a0bcabd233085ca15867
[ "MIT" ]
null
null
null
/** * * |_ _ _ * |_)| (/_VV * * Copyright 2017 r.acc * * LocalDirectory.cpp * * Created on: Feb 11, 2016 * Author: void */ #include <brew/fileio/LocalFileSystem.h> #include <brew/fileio/VirtualFileSystem.h> #include <fstream> #include <dirent.h> #include <fcntl.h> #include <unistd.h> namespace brew { LocalDirectory::LocalDirectory(const String& real_path) : real_path(VirtualFileSystem::normalizePath(real_path+VirtualFileSystem::directory_separator)) { if(this->real_path.empty()) this->real_path = "./"; } std::unique_ptr<Directory> LocalDirectory::getDirectory(const String& dir) const { String path = VirtualFileSystem::normalizePath(real_path+dir); DIR* dh =opendir(path.c_str()); if(!dh) { throw IOException("Cannot open local directory '" + path + '"'); } closedir(dh); return std::make_unique<LocalDirectory>(path); } std::unique_ptr<File> LocalDirectory::getFile(const String& file) const { if(!exists(file)) throw IOException("No such local file '" + real_path + file + "'"); if(isDirectory(file)) throw IOException("'" + real_path + file + "' is a directory."); return std::make_unique<LocalFile>(real_path+VirtualFileSystem::directory_separator+file); }; std::vector<String> LocalDirectory::getEntries() const { std::vector<String> r; DIR* dh =opendir(real_path.c_str()); dirent* e; while((e = readdir(dh)) != NULL) { String filename = e->d_name; if(filename == "." || filename == "..") continue; //filename = real_path + filename; r.push_back(filename); } closedir(dh); return r; } bool LocalDirectory::exists(const String& file) const { if(isDirectory(file)) return true; int ok = access((real_path + file).c_str(), F_OK); return ok != -1; } bool LocalDirectory::isDirectory(const String& file) const { DIR* dh =opendir((real_path+ file).c_str()); if(!dh) return false; closedir(dh); return true; } LocalFile::LocalFile(const String& real_path) : real_path(real_path) { } std::unique_ptr<FileStream> LocalFile::open(const std::ios::openmode& mode) const { std::filebuf* buf = new std::filebuf(); buf->open(real_path, mode); return std::make_unique<FileStream>(buf); } } /* namespace brew */
22.690722
97
0.687869
[ "vector" ]
99399082f9926a0ae6b833ec295c0aa563a836e0
4,289
cpp
C++
src/WindowManager.cpp
shourai-softwares/dive
8cee92002a319bb16cc1ee4f506d33fa166987c2
[ "MIT" ]
null
null
null
src/WindowManager.cpp
shourai-softwares/dive
8cee92002a319bb16cc1ee4f506d33fa166987c2
[ "MIT" ]
null
null
null
src/WindowManager.cpp
shourai-softwares/dive
8cee92002a319bb16cc1ee4f506d33fa166987c2
[ "MIT" ]
null
null
null
#include <chrono> #include <thread> #include <iostream> #include <exception> #include <glm/gtc/matrix_transform.hpp> #include <tiny_obj_loader.h> #include "Scene.h" #include "WindowManager.h" using namespace std; WindowManager::WindowManager() { try { this->initializeWindow(); } catch(exception& e) { cout << e.what() << '\n'; } } WindowManager::~WindowManager() { glfwTerminate(); } void WindowManager::run(GLuint program) { Scene scene; glUseProgram(program); glm::vec3 position = glm::vec3( 0, 0, 5 ); float horizontalAngle = 3.14f; float verticalAngle = 0.0f; float speed = 3.0f; float mouseSpeed = 3.0f; glm::mat4 Model = glm::mat4(1.0f); GLint MatrixID = glGetUniformLocation(program, "MVP"); double lastX = 0, lastY = 0; glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); scene.load(); int maxFPS = 144; double waitTime = 1.0 / (maxFPS); double lastRenderTime = glfwGetTime(); while(!glfwWindowShouldClose(window)) { double x, y; glfwGetCursorPos(window, &x, &y); double currentTime = glfwGetTime(); auto deltaTime = float(currentTime - lastRenderTime); horizontalAngle += mouseSpeed * deltaTime * float(lastX - x); verticalAngle += mouseSpeed * deltaTime * float(lastY - y); if(deltaTime < waitTime) { this_thread::sleep_for(chrono::milliseconds(1000 * (int) (waitTime - deltaTime))); } lastRenderTime = currentTime; lastX = x; lastY = y; glm::vec3 direction( cos(verticalAngle) * sin(horizontalAngle), sin(verticalAngle), cos(verticalAngle) * cos(horizontalAngle) ); glm::vec3 right = glm::vec3( sin(horizontalAngle - 3.14f/2.0f), 0, cos(horizontalAngle - 3.14f/2.0f) ); glm::vec3 up = glm::cross( right, direction ); if (glfwGetKey(this->window, GLFW_KEY_W) == GLFW_PRESS){ position += direction * deltaTime * speed; } if (glfwGetKey(this->window, GLFW_KEY_S) == GLFW_PRESS){ position -= direction * deltaTime * speed; } if (glfwGetKey(this->window, GLFW_KEY_D) == GLFW_PRESS){ position += right * deltaTime * speed; } if (glfwGetKey(this->window, GLFW_KEY_A) == GLFW_PRESS){ position -= right * deltaTime * speed; } glm::mat4 Projection = glm::perspective(glm::radians(45.0f), 4.0f/3.0f, 0.1f, 100.0f); glm::mat4 View = glm::lookAt(position, position + direction, up); glm::mat4 mvp = Projection * View * Model; glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &mvp[0][0]); scene.render(); glfwSwapBuffers(window); glfwPollEvents(); glClearBufferfv(GL_COLOR, 0, scene.getBackgroundColor()); glClear(GL_DEPTH_BUFFER_BIT); } scene.unload(); glDisableVertexAttribArray(0); } void WindowManager::initializeWindow() { // Initialise GLFW if( !glfwInit() ) { fprintf( stderr, "Failed to initialize GLFW\n" ); getchar(); } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_RESIZABLE,GL_FALSE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Open a window and create its OpenGL context this->window = glfwCreateWindow(1024, 768, "Dive", nullptr, nullptr); if(this->window == nullptr) { fprintf( stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n" ); getchar(); glfwTerminate(); } glfwMakeContextCurrent(this->window); if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); return; } // Ensure we can capture the escape key being pressed below glfwSetInputMode(this->window, GLFW_STICKY_KEYS, GL_TRUE); // Dark blue background glClearColor(0.0f, 0.0f, 0.4f, 0.0f); }
29.57931
152
0.61786
[ "render", "model" ]
994bcfa9096c5a9618def192175b2bb9ce041e12
2,363
hpp
C++
src/tree.hpp
yatisht/strain_phylogenetics
eb978ace4e78624b330fa38ddd02f6d32f34f5fd
[ "MIT" ]
7
2020-07-02T16:40:56.000Z
2022-01-31T17:50:45.000Z
src/tree.hpp
yatisht/strain_phylogenetics
eb978ace4e78624b330fa38ddd02f6d32f34f5fd
[ "MIT" ]
3
2020-06-05T03:06:15.000Z
2020-09-19T02:22:10.000Z
src/tree.hpp
yatisht/strain_phylogenetics
eb978ace4e78624b330fa38ddd02f6d32f34f5fd
[ "MIT" ]
2
2020-05-28T20:41:45.000Z
2020-05-31T21:16:57.000Z
#include <fstream> #include <unordered_map> #include <string> #include <sstream> #include <vector> #include <queue> #include <stack> #include <algorithm> #include <cassert> class Node { public: size_t level; float branch_length; std::string identifier; Node* parent; std::vector<Node*> children; bool is_leaf(); bool is_root(); Node(); Node(std::string id, float l); Node(std::string id, Node* p, float l); }; class Tree { private: void remove_node_helper (std::string nid, bool move_level); void depth_first_expansion_helper(Node* node, std::vector<Node*>& vec); std::unordered_map <std::string, Node*> all_nodes; public: Tree() { max_level = 0; root = NULL; all_nodes.clear(); } Tree (Node* n); size_t max_level; Node* root; size_t curr_internal_node; size_t get_max_level (); void rename_node(std::string old_nid, std::string new_nid); std::vector<Node*> get_leaves(); std::vector<Node*> get_leaves(std::string nid); size_t get_num_leaves(Node* node); size_t get_num_leaves(); void create_node (std::string identifier, float branch_length = -1.0); void create_node (std::string identifier, std::string parent_id, float branch_length = -1.0); Node* get_node (std::string identifier); bool is_ancestor (std::string anc_id, std::string nid); std::vector<Node*> rsearch (std::string nid); void remove_node (std::string nid, bool move_level); void move_node (std::string source, std::string destination); std::vector<Node*> breadth_first_expansion(); std::vector<Node*> breadth_first_expansion(std::string nid); std::vector<Node*> depth_first_expansion(); std::vector<Node*> depth_first_expansion(Node* node); }; namespace TreeLib { std::string get_newick_string(Tree& T, bool b1, bool b2); std::string get_newick_string(Tree& T, Node* node, bool b1, bool b2); Tree create_tree_from_newick (std::string filename); Tree create_tree_from_newick_string (std::string newick_string); void split(std::string s, char delim, std::vector<std::string>& words); void split(std::string s, std::vector<std::string>& words); }
32.819444
101
0.637325
[ "vector" ]
9951ec54160f7ba8f7d5ef7f482b6833ecfd6c75
1,278
cpp
C++
Contests/Vjudge/EstructurasBasicas/f.cpp
searleser97/Algorithms
af791541d416c29867213d705375cbb3361f486c
[ "Apache-2.0" ]
7
2019-06-06T17:54:20.000Z
2021-03-24T02:31:55.000Z
Contests/Vjudge/EstructurasBasicas/f.cpp
searleser97/Algorithms
af791541d416c29867213d705375cbb3361f486c
[ "Apache-2.0" ]
null
null
null
Contests/Vjudge/EstructurasBasicas/f.cpp
searleser97/Algorithms
af791541d416c29867213d705375cbb3361f486c
[ "Apache-2.0" ]
1
2021-03-24T02:31:57.000Z
2021-03-24T02:31:57.000Z
#include <bits/stdc++.h> using namespace std; #define endl '\n' #define forr(_, x, n) for (int _ = x; _ > n; _--) #define fos(_, x, n, s) for (int _ = x; _ < n; _ += s) #define forn(_, x, n) fos(_, x, n, 1) #define rep(_, n) forn(_, 0, n) #define fi first #define se second #define pb push_back #define pairii pair<int, int> #define cerr(s) cerr << "\033[48;5;196m\033[38;5;15m" << s << "\033[0m" // typedef __int128_t lli; typedef long long int li; typedef long double ld; // 12 void _main(int tc) { string s; cin >> s; vector<set<int>> poss(26); for (int i = 0; i < s.size(); i++) { poss[s[i] - 'a'].insert(i); } int q; cin >> q; rep(i, q) { int type; cin >> type; if (type == 1) { int pos; cin >> pos; pos--; char c; cin >> c; poss[s[pos] - 'a'].erase(pos); poss[c - 'a'].insert(pos); s[pos] = c; } else { int l, r; cin >> l >> r; l--, r--; int cnt = 0; for (int i = 0; i < 26; i++) { auto it = poss[i].lower_bound(l); if (it != poss[i].end() && (*it) <= r) cnt++; } cout << cnt << endl; } } } int main() { ios_base::sync_with_stdio(0), cin.tie(0); _main(0); return 0; int tc; cin >> tc; rep(i, tc) _main(i + 1); }
21.3
71
0.489828
[ "vector" ]
995f26b779e360e290ca48f7d795e0492cb7148f
11,255
cpp
C++
Tools/Davisloading.cpp
marcorax/Energy_model
0656cb9cbdb876e6134ec514c8d90ca5229453ac
[ "MIT" ]
null
null
null
Tools/Davisloading.cpp
marcorax/Energy_model
0656cb9cbdb876e6134ec514c8d90ca5229453ac
[ "MIT" ]
null
null
null
Tools/Davisloading.cpp
marcorax/Energy_model
0656cb9cbdb876e6134ec514c8d90ca5229453ac
[ "MIT" ]
null
null
null
#include <stdlib.h> #include <fstream> #include <iostream> #include <string> #include <opencv2/opencv.hpp> #include <Davisloading.hpp> #define MAXVALUE 65535 //max decimal value of unsigned int (the original pixel type) Used to tormalize pixel values to 1 //The class is supposed to deal with AEDAT 3.1 files. // To know more and to understand what is going on in the lines underneat // please refer to page https://inivation.com/support/software/fileformat/#aedat-31 void skip_header(std::ifstream & file, const int & verbose){ std::string first_letter = "#"; std::string line; std::getline(file,line); int header_found = 0; while (first_letter=="#") { if(line=="#!END-HEADER\r" && verbose){ std::cout<<"Header successfully skipped"<<std::endl; header_found=1; break; } else{ std::getline(file,line); first_letter = line[0]; } } if(header_found==0) std::cout<<"Header end not found"<<std::endl; } int read_frames(std::ifstream & file, int XDIM, int YDIM, std::vector <cv::Mat_<float>> & frames, std::vector <unsigned int> & start_ts, std::vector <unsigned int> & end_ts){ unsigned short eventtype, eventsource; unsigned int eventsize, eventoffset, eventtsoverflow, eventcapacity, eventnumber, eventvalid, next_read; next_read = eventcapacity*eventsize; unsigned char * event_head = new unsigned char [28]; file.read((char*) event_head, 28); if(file.tellg()==EOF){ return -1; } //The machine is supposed to be little endian. eventtype = (unsigned short) ((event_head[1]) << 8 | (event_head[0])); eventsource = (unsigned short) ((event_head[3]) << 8 | (event_head[2])); eventsize = (unsigned int) ((event_head[7]) << 24 | (event_head[6]<<16)| (event_head[5]) << 8 | (event_head[4])); eventoffset = (unsigned int) ((event_head[11]) << 24 | (event_head[10]<<16)| (event_head[9]) << 8 | (event_head[8])); eventtsoverflow = (unsigned int) ((event_head[15]) << 24 | (event_head[14]<<16)| (event_head[13]) << 8 | (event_head[12])); eventcapacity = (unsigned int) ((event_head[19]) << 24 | (event_head[18]<<16)| (event_head[17]) << 8 | (event_head[16])); eventnumber = (unsigned int) ((event_head[23]) << 24 | (event_head[22]<<16)| (event_head[21]) << 8 | (event_head[20])); eventvalid = (unsigned int) ((event_head[27]) << 24 | (event_head[26]<<16)| (event_head[25]) << 8 | (event_head[24])); unsigned char * data = new unsigned char [eventsize]; if(eventtype == 2){ unsigned int pixelcounter=36; int posx = 0; int posy = 0; for(int i=0; i<eventcapacity;i++){ file.read((char*) data, eventsize); posx=0; posy=0; cv::Mat_<float> tmpframe(YDIM, XDIM, CV_32FC1); while(pixelcounter<eventsize){ tmpframe.at<float>(posy,posx)=((float) ((data[(pixelcounter)+1]) << 8 | (data[(pixelcounter)]))/MAXVALUE); posx++; if(posx==XDIM){ posx=0; posy++; } pixelcounter += 2; } frames.push_back(tmpframe); start_ts.push_back((unsigned int) ((data[7]) << 24 | (data[6]<<16)| (data[5]) << 8 | (data[4]))); end_ts.push_back((unsigned int) ((data[11]) << 24 | (data[10]<<16)| (data[9]) << 8 | (data[8]))); } return 0; } if(eventtype==0){ //special event, the class is not developed to deal with this type, here for debugging only. std::vector <unsigned int> spec_ts; std::vector <unsigned short> spec_type; for(int i=0; i<eventcapacity;i++){ file.read((char*) data, eventsize); spec_ts.push_back((unsigned int) ((data[7]) << 24 | (data[6]<<16)| (data[5]) << 8 | (data[4]))); spec_type.push_back((unsigned short)(data[0])); } return 0; } } int read_events(std::ifstream & file, std::vector <unsigned short> & polarity, std::vector <unsigned int> & timestamp, std::vector <unsigned int> & x_addr, std::vector <unsigned int> & y_addr){ unsigned short eventtype, eventsource; unsigned int eventsize, eventoffset, eventtsoverflow, eventcapacity, eventnumber, eventvalid, next_read; next_read = eventcapacity*eventsize; unsigned char * event_head = new unsigned char [28]; file.read((char*) event_head, 28); if(file.tellg()==EOF){ return -1; } //The machine is supposed to be little endian. eventtype = (unsigned short) ((event_head[1]) << 8 | (event_head[0])); eventsource = (unsigned short) ((event_head[3]) << 8 | (event_head[2])); eventsize = (unsigned int) ((event_head[7]) << 24 | (event_head[6]<<16)| (event_head[5]) << 8 | (event_head[4])); eventoffset = (unsigned int) ((event_head[11]) << 24 | (event_head[10]<<16)| (event_head[9]) << 8 | (event_head[8])); eventtsoverflow = (unsigned int) ((event_head[15]) << 24 | (event_head[14]<<16)| (event_head[13]) << 8 | (event_head[12])); eventcapacity = (unsigned int) ((event_head[19]) << 24 | (event_head[18]<<16)| (event_head[17]) << 8 | (event_head[16])); eventnumber = (unsigned int) ((event_head[23]) << 24 | (event_head[22]<<16)| (event_head[21]) << 8 | (event_head[20])); eventvalid = (unsigned int) ((event_head[27]) << 24 | (event_head[26]<<16)| (event_head[25]) << 8 | (event_head[24])); unsigned char * data = new unsigned char [eventsize]; if(eventtype == 1){ unsigned int event_data; for(int i=0; i<eventcapacity;i++){ file.read((char*) data, eventsize); event_data = (unsigned int) ((data[3]) << 24 | (data[2]<<16)| (data[1]) << 8 | (data[0])); timestamp.push_back((unsigned int) ((data[7]) << 24 | (data[6]<<16)| (data[5]) << 8 | (data[4]))); x_addr.push_back((unsigned int)(event_data >> 17) & 0x00007FFF); y_addr.push_back((unsigned int)(event_data >> 2) & 0x00007FFF); polarity.push_back((unsigned short)(event_data >> 1) & 0x00000001); } return 0; } if(eventtype==0){ //special event, the class is not developed to deal with this type, here for debugging only. std::vector <unsigned int> spec_ts; std::vector <unsigned short> spec_type; for(int i=0; i<eventcapacity;i++){ file.read((char*) data, eventsize); spec_ts.push_back((unsigned int) ((data[7]) << 24 | (data[6]<<16)| (data[5]) << 8 | (data[4]))); spec_type.push_back((unsigned short)(data[0])); } return 0; } } DAVISFrames::DAVISFrames(std::string fn, int dimx, int dimy, const int & verbose){ filename=fn; xdim=dimx; ydim=dimy; int eof_flag = 0; std::ifstream aedat_file; aedat_file.open(filename); if(!aedat_file.is_open()) { std::cout<<"Huston we have a problem! File not found or inaccessible"<<std::endl; } else{ skip_header(aedat_file, verbose); while(!(eof_flag)){ eof_flag = read_frames(aedat_file, xdim, ydim, frames, start_ts, end_ts); } } aedat_file.close(); } DAVISEvents::DAVISEvents(std::string fn, const int & verbose){ filename=fn; int eof_flag = 0; std::ifstream aedat_file; aedat_file.open(filename); if(!aedat_file.is_open()) { std::cout<<"Huston we have a problem! File not found or inaccessible"<<std::endl; } else{ skip_header(aedat_file, verbose); while(!(eof_flag)){ eof_flag = read_events(aedat_file, polarity, timestamp, x_addr, y_addr); } } aedat_file.close(); } /*Function for frame syncing, as at the moment of writing Davis sensors cannot be synchronized (each frame is taken independently and only the timestamps use the same clock and reference) meaning that the setup might have different exposure time and consequentely frame rate per camera. Thus the two files might present a different number of frames. This function removes the less synchronized frames, pairing the number of pictures contained in each DAVISframes object. Since it has been developed for Stereo Setups the function is expected to work with couples of objects, called respectively frames_r and frames_l */ void sync_frames(DAVISFrames & frames_r, DAVISFrames & frames_l){ unsigned int count; int time_diff, next_time_diff; if(frames_l.frames.size()>frames_r.frames.size()){ for(unsigned int i=0; i<frames_r.frames.size(); i++){ count = 0; time_diff = (int) frames_l.end_ts[i]-frames_r.end_ts[i]; next_time_diff = (int) frames_l.end_ts[i+1]-frames_r.end_ts[i]; //I want to pop out the most desinchronized frames, I count them in order to remove them right after while(abs(time_diff)>abs(next_time_diff) && count+1<frames_l.end_ts.size()){ count++; time_diff = (int) frames_l.end_ts[i+count]-frames_r.end_ts[i]; next_time_diff = (int) frames_l.end_ts[i+1+count]-frames_r.end_ts[i]; } if(count>0){ frames_l.frames.erase(frames_l.frames.begin() + count + i); frames_l.start_ts.erase(frames_l.start_ts.begin() + count + i); frames_l.end_ts.erase(frames_l.end_ts.begin() + count + i); } } } if(frames_l.frames.size()<frames_r.frames.size()){ for(unsigned int i=0; i<frames_l.frames.size(); i++){ count = 0; time_diff = (int) frames_r.end_ts[i]-frames_l.end_ts[i]; next_time_diff = (int) frames_r.end_ts[i+1]-frames_l.end_ts[i]; //I want to pop out the most desinchronized frames, I count them in order to remove them right after while(abs(time_diff)>abs(next_time_diff) && count+1<frames_r.end_ts.size()){ count++; time_diff = (int) frames_r.end_ts[i+count]-frames_l.end_ts[i]; next_time_diff = (int) frames_r.end_ts[i+1+count]-frames_l.end_ts[i]; } if(count>0){ frames_r.frames.erase(frames_r.frames.begin() + count + i); frames_r.start_ts.erase(frames_r.start_ts.begin() + count + i); frames_r.end_ts.erase(frames_r.end_ts.begin() + count + i); } } } }
40.631769
120
0.560373
[ "object", "vector" ]
9975d26c7269f4ff68dff62ccfa2975cc7c51f46
11,308
cpp
C++
src/qpid/broker/HeadersExchange.cpp
gcsideal/debian-qpid-cpp
e4d034036f29408f940805f5505ae62ce89650cc
[ "Apache-2.0" ]
null
null
null
src/qpid/broker/HeadersExchange.cpp
gcsideal/debian-qpid-cpp
e4d034036f29408f940805f5505ae62ce89650cc
[ "Apache-2.0" ]
null
null
null
src/qpid/broker/HeadersExchange.cpp
gcsideal/debian-qpid-cpp
e4d034036f29408f940805f5505ae62ce89650cc
[ "Apache-2.0" ]
null
null
null
/* * * 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. * */ #include "qpid/broker/HeadersExchange.h" #include "qpid/framing/FieldValue.h" #include "qpid/framing/reply_exceptions.h" #include "qpid/log/Statement.h" #include <algorithm> using namespace qpid::broker; using std::string; using namespace qpid::framing; using namespace qpid::sys; namespace _qmf = qmf::org::apache::qpid::broker; // TODO aconway 2006-09-20: More efficient matching algorithm. // The current search algorithm really sucks. // Fieldtables are heavy, maybe use shared_ptr to do handle-body. using namespace qpid::broker; namespace { const std::string x_match("x-match"); // possible values for x-match const std::string all("all"); const std::string any("any"); const std::string empty; // federation related args and values const std::string qpidFedOp("qpid.fed.op"); const std::string qpidFedTags("qpid.fed.tags"); const std::string qpidFedOrigin("qpid.fed.origin"); const std::string fedOpBind("B"); const std::string fedOpUnbind("U"); const std::string fedOpReorigin("R"); const std::string fedOpHello("H"); } HeadersExchange::HeadersExchange(const string& _name, Manageable* _parent, Broker* b) : Exchange(_name, _parent, b) { if (mgmtExchange != 0) mgmtExchange->set_type (typeName); } HeadersExchange::HeadersExchange(const std::string& _name, bool _durable, const FieldTable& _args, Manageable* _parent, Broker* b) : Exchange(_name, _durable, _args, _parent, b) { if (mgmtExchange != 0) mgmtExchange->set_type (typeName); } std::string HeadersExchange::getMatch(const FieldTable* args) { if (!args) { throw InternalErrorException(QPID_MSG("No arguments given.")); } FieldTable::ValuePtr what = args->get(x_match); if (!what) { return empty; } if (!what->convertsTo<std::string>()) { throw InternalErrorException(QPID_MSG("Invalid x-match binding format to headers exchange. Must be a string [\"all\" or \"any\"]")); } return what->get<std::string>(); } bool HeadersExchange::bind(Queue::shared_ptr queue, const string& bindingKey, const FieldTable* args) { string fedOp(fedOpBind); string fedTags; string fedOrigin; if (args) { fedOp = args->getAsString(qpidFedOp); fedTags = args->getAsString(qpidFedTags); fedOrigin = args->getAsString(qpidFedOrigin); } bool propagate = false; // The federation args get propagated directly, so we need to identify // the non federation args in case a federated propagate is needed FieldTable extra_args; getNonFedArgs(args, extra_args); if (fedOp.empty() || fedOp == fedOpBind) { // x-match arg MUST be present for a bind call std::string x_match_value = getMatch(args); if (x_match_value != all && x_match_value != any) { throw InternalErrorException(QPID_MSG("Invalid or missing x-match value binding to headers exchange. Must be a string [\"all\" or \"any\"]")); } { Mutex::ScopedLock l(lock); //NOTE: do not include the fed op/tags/origin in the //arguments as when x-match is 'all' these would prevent //matching (they are internally added properties //controlling binding propagation but not relevant to //actual routing) Binding::shared_ptr binding (new Binding (bindingKey, queue, this, extra_args)); BoundKey bk(binding); if (bindings.add_unless(bk, MatchArgs(queue, &extra_args))) { binding->startManagement(); propagate = bk.fedBinding.addOrigin(queue->getName(), fedOrigin); if (mgmtExchange != 0) { mgmtExchange->inc_bindingCount(); } } else { bk.fedBinding.addOrigin(queue->getName(), fedOrigin); return false; } } // lock dropped } else if (fedOp == fedOpUnbind) { Mutex::ScopedLock l(lock); FedUnbindModifier modifier(queue->getName(), fedOrigin); bindings.modify_if(MatchKey(queue, bindingKey), modifier); propagate = modifier.shouldPropagate; if (modifier.shouldUnbind) { unbind(queue, bindingKey, args); } } else if (fedOp == fedOpReorigin) { Bindings::ConstPtr p = bindings.snapshot(); if (p.get()) { Mutex::ScopedLock l(lock); for (std::vector<BoundKey>::const_iterator i = p->begin(); i != p->end(); ++i) { if ((*i).fedBinding.hasLocal()) { propagateFedOp( (*i).binding->key, string(), fedOpBind, string()); } } } } routeIVE(); if (propagate) { FieldTable * prop_args = (extra_args.count() != 0 ? &extra_args : 0); propagateFedOp(bindingKey, fedTags, fedOp, fedOrigin, prop_args); } return true; } bool HeadersExchange::unbind(Queue::shared_ptr queue, const string& bindingKey, const FieldTable *args){ bool propagate = false; string fedOrigin(args ? args->getAsString(qpidFedOrigin) : ""); { Mutex::ScopedLock l(lock); FedUnbindModifier modifier(queue->getName(), fedOrigin); MatchKey match_key(queue, bindingKey); bindings.modify_if(match_key, modifier); propagate = modifier.shouldPropagate; if (modifier.shouldUnbind) { if (bindings.remove_if(match_key)) { if (mgmtExchange != 0) { mgmtExchange->dec_bindingCount(); } } else { return false; } } } if (propagate) { propagateFedOp(bindingKey, string(), fedOpUnbind, string()); } return true; } void HeadersExchange::route(Deliverable& msg) { const FieldTable* args = msg.getMessage().getApplicationHeaders(); if (!args) { //can't match if there were no headers passed in if (mgmtExchange != 0) { mgmtExchange->inc_msgReceives(); mgmtExchange->inc_byteReceives(msg.contentSize()); mgmtExchange->inc_msgDrops(); mgmtExchange->inc_byteDrops(msg.contentSize()); if (brokerMgmtObject) brokerMgmtObject->inc_discardsNoRoute(); } return; } PreRoute pr(msg, this); BindingList b(new std::vector<boost::shared_ptr<qpid::broker::Exchange::Binding> >); Bindings::ConstPtr p = bindings.snapshot(); if (p.get()) { for (std::vector<BoundKey>::const_iterator i = p->begin(); i != p->end(); ++i) { if (match((*i).binding->args, *args)) { b->push_back((*i).binding); } } } doRoute(msg, b); } bool HeadersExchange::isBound(Queue::shared_ptr queue, const string* const, const FieldTable* const args) { Bindings::ConstPtr p = bindings.snapshot(); if (p.get()){ for (std::vector<BoundKey>::const_iterator i = p->begin(); i != p->end(); ++i) { if ( (!args || equal((*i).binding->args, *args)) && (!queue || (*i).binding->queue == queue)) { return true; } } } return false; } void HeadersExchange::getNonFedArgs(const FieldTable* args, FieldTable& nonFedArgs) { if (!args) { return; } for (qpid::framing::FieldTable::ValueMap::const_iterator i=args->begin(); i != args->end(); ++i) { const string & name(i->first); if (name == qpidFedOp || name == qpidFedTags || name == qpidFedOrigin) { continue; } nonFedArgs.insert((*i)); } } HeadersExchange::~HeadersExchange() {} const std::string HeadersExchange::typeName("headers"); namespace { bool match_values(const FieldValue& bind, const FieldValue& msg) { return bind.getType() == 0xf0 || bind == msg; } } bool HeadersExchange::match(const FieldTable& bind, const FieldTable& msg) { typedef FieldTable::ValueMap Map; std::string what = getMatch(&bind); if (what == all) { for (Map::const_iterator i = bind.begin(); i != bind.end(); ++i) { if (i->first != x_match) { Map::const_iterator j = msg.find(i->first); if (j == msg.end()) return false; if (!match_values(*(i->second), *(j->second))) return false; } } return true; } else if (what == any) { for (Map::const_iterator i = bind.begin(); i != bind.end(); ++i) { if (i->first != x_match) { Map::const_iterator j = msg.find(i->first); if (j != msg.end()) { if (match_values(*(i->second), *(j->second))) return true; } } } return false; } else { return false; } } bool HeadersExchange::equal(const FieldTable& a, const FieldTable& b) { typedef FieldTable::ValueMap Map; for (Map::const_iterator i = a.begin(); i != a.end(); ++i) { Map::const_iterator j = b.find(i->first); if (j == b.end()) return false; if (!match_values(*(i->second), *(j->second))) return false; } return true; } //--------- HeadersExchange::MatchArgs::MatchArgs(Queue::shared_ptr q, const qpid::framing::FieldTable* a) : queue(q), args(a) {} bool HeadersExchange::MatchArgs::operator()(BoundKey & bk) { return bk.binding->queue == queue && bk.binding->args == *args; } //--------- HeadersExchange::MatchKey::MatchKey(Queue::shared_ptr q, const std::string& k) : queue(q), key(k) {} bool HeadersExchange::MatchKey::operator()(BoundKey & bk) { return bk.binding->queue == queue && bk.binding->key == key; } //---------- HeadersExchange::FedUnbindModifier::FedUnbindModifier(const string& queueName, const string& origin) : queueName(queueName), fedOrigin(origin), shouldUnbind(false), shouldPropagate(false) {} HeadersExchange::FedUnbindModifier::FedUnbindModifier() : shouldUnbind(false), shouldPropagate(false) {} bool HeadersExchange::FedUnbindModifier::operator()(BoundKey & bk) { shouldPropagate = bk.fedBinding.delOrigin(queueName, fedOrigin); if (bk.fedBinding.countFedBindings(queueName) == 0) { shouldUnbind = true; } return true; }
32.033994
190
0.601963
[ "vector" ]
9978e6f6d4c77943159b9669e2205fbcd28b972b
7,400
cpp
C++
SQLiteWrapper.cpp
GamePad64/lvsqlite3
94cafdf49765ba28eacbba0c94a4f9f2b84d129d
[ "CC0-1.0" ]
1
2017-09-05T02:15:01.000Z
2017-09-05T02:15:01.000Z
SQLiteWrapper.cpp
GamePad64/lvsqlite3
94cafdf49765ba28eacbba0c94a4f9f2b84d129d
[ "CC0-1.0" ]
null
null
null
SQLiteWrapper.cpp
GamePad64/lvsqlite3
94cafdf49765ba28eacbba0c94a4f9f2b84d129d
[ "CC0-1.0" ]
null
null
null
/* Written in 2015 by Alexander Shishenko <alex@shishenko.com> * * LVSQLite - SQLite wrapper, used in Librevault. * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication * along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "SQLiteWrapper.h" namespace librevault { // SQLValue SQLValue::SQLValue() : value_type(ValueType::NULL_VALUE) {} SQLValue::SQLValue(int64_t int_val) : value_type(ValueType::INT), int_val(int_val) {} SQLValue::SQLValue(uint64_t int_val) : value_type(ValueType::INT), int_val((int64_t)int_val) {} SQLValue::SQLValue(double double_val) : value_type(ValueType::DOUBLE), double_val(double_val) {} SQLValue::SQLValue(const std::string& text_val) : value_type(ValueType::TEXT), text_val(text_val.data()), size(text_val.size()) {} SQLValue::SQLValue(const char* text_ptr, uint64_t text_size) : value_type(ValueType::TEXT), text_val(text_ptr), size(text_size) {} SQLValue::SQLValue(const std::vector<uint8_t>& blob_val) : value_type(ValueType::BLOB), blob_val(blob_val.data()), size(blob_val.size()){} SQLValue::SQLValue(const uint8_t* blob_ptr, uint64_t blob_size) : value_type(ValueType::BLOB), blob_val(blob_ptr), size(blob_size) {} // SQLiteResultIterator SQLiteResultIterator::SQLiteResultIterator(sqlite3_stmt* prepared_stmt, std::shared_ptr<int64_t> shared_idx, std::shared_ptr<std::vector<std::string>> cols, int rescode) : prepared_stmt(prepared_stmt), shared_idx(shared_idx), cols(cols), rescode(rescode) { current_idx = *shared_idx; fill_result(); } SQLiteResultIterator::SQLiteResultIterator(int rescode) : rescode(rescode){} void SQLiteResultIterator::fill_result() const { if(rescode != SQLITE_ROW) return; result.resize(0); result.reserve(cols->size()); for(unsigned iCol = 0; iCol < cols->size(); iCol++){ switch((SQLValue::ValueType)sqlite3_column_type(prepared_stmt, iCol)){ case SQLValue::ValueType::INT: result.push_back(SQLValue((int64_t)sqlite3_column_int64(prepared_stmt, iCol))); break; case SQLValue::ValueType::DOUBLE: result.push_back(SQLValue((double)sqlite3_column_double(prepared_stmt, iCol))); break; case SQLValue::ValueType::TEXT: result.push_back(SQLValue(std::string((const char*)sqlite3_column_text(prepared_stmt, iCol)))); break; case SQLValue::ValueType::BLOB: { const uint8_t* blob_ptr = (const uint8_t*)sqlite3_column_blob(prepared_stmt, iCol); auto blob_size = sqlite3_column_bytes(prepared_stmt, iCol); result.push_back(SQLValue(blob_ptr, blob_size)); } break; case SQLValue::ValueType::NULL_VALUE: result.push_back(SQLValue()); break; } } } SQLiteResultIterator& SQLiteResultIterator::operator++() { rescode = sqlite3_step(prepared_stmt); (*shared_idx)++; current_idx = *shared_idx; fill_result(); return *this; } SQLiteResultIterator SQLiteResultIterator::operator++(int) { SQLiteResultIterator orig = *this; ++(*this); return orig; } bool SQLiteResultIterator::operator==(const SQLiteResultIterator& lvalue) { return prepared_stmt == lvalue.prepared_stmt && current_idx == lvalue.current_idx; } bool SQLiteResultIterator::operator!=(const SQLiteResultIterator& lvalue) { if((lvalue.result_code() == SQLITE_DONE || lvalue.result_code() == SQLITE_OK) && (result_code() == SQLITE_DONE || result_code() == SQLITE_OK)){ return false; }else if(prepared_stmt == lvalue.prepared_stmt && current_idx == lvalue.current_idx){ return false; } return true; } const SQLiteResultIterator::value_type& SQLiteResultIterator::operator*() const { return result; } const SQLiteResultIterator::value_type* SQLiteResultIterator::operator->() const { return &result; } SQLValue SQLiteResultIterator::operator[](size_t pos) const { return result[pos]; } // SQLiteResult SQLiteResult::SQLiteResult(sqlite3_stmt* prepared_stmt) : prepared_stmt(prepared_stmt) { rescode = sqlite3_step(prepared_stmt); shared_idx = std::make_shared<int64_t>(); *shared_idx = 0; cols = std::make_shared<std::vector<std::string>>(0); if(have_rows()){ auto total_cols = sqlite3_column_count(prepared_stmt); cols->resize(total_cols); for(int col_idx = 0; col_idx < total_cols; col_idx++){ cols->at(col_idx) = sqlite3_column_name(prepared_stmt, col_idx); } }else{ finalize(); } } SQLiteResult::~SQLiteResult(){ finalize(); } void SQLiteResult::finalize(){ sqlite3_finalize(prepared_stmt); prepared_stmt = 0; } SQLiteResultIterator SQLiteResult::begin() { return SQLiteResultIterator(prepared_stmt, shared_idx, cols, rescode); } SQLiteResultIterator SQLiteResult::end() { return SQLiteResultIterator(SQLITE_DONE); } // SQLiteDB SQLiteDB::SQLiteDB(const boost::filesystem::path& db_path) { open(db_path); } SQLiteDB::SQLiteDB(const char* db_path) { open(db_path); } SQLiteDB::~SQLiteDB() { close(); } void SQLiteDB::open(const boost::filesystem::path& db_path) { open(db_path.string().c_str()); } void SQLiteDB::open(const char* db_path) { sqlite3_open(db_path, &db); } void SQLiteDB::close() { sqlite3_close(db); } SQLiteResult SQLiteDB::exec(const std::string& sql, std::map<std::string, SQLValue> values){ sqlite3_stmt* sqlite_stmt; sqlite3_prepare_v2(db, sql.c_str(), (int)sql.size()+1, &sqlite_stmt, 0); for(auto value : values){ switch(value.second.get_type()){ case SQLValue::ValueType::INT: sqlite3_bind_int64(sqlite_stmt, sqlite3_bind_parameter_index(sqlite_stmt, value.first.c_str()), value.second.as_int()); break; case SQLValue::ValueType::DOUBLE: sqlite3_bind_double(sqlite_stmt, sqlite3_bind_parameter_index(sqlite_stmt, value.first.c_str()), value.second.as_double()); break; case SQLValue::ValueType::TEXT: { auto text_data = value.second.as_text(); sqlite3_bind_text64(sqlite_stmt, sqlite3_bind_parameter_index(sqlite_stmt, value.first.c_str()), text_data.data(), text_data.size(), SQLITE_TRANSIENT, SQLITE_UTF8); } break; case SQLValue::ValueType::BLOB: { auto blob_data = value.second.as_blob(); sqlite3_bind_blob64(sqlite_stmt, sqlite3_bind_parameter_index(sqlite_stmt, value.first.c_str()), blob_data.data(), blob_data.size(), SQLITE_TRANSIENT); } break; case SQLValue::ValueType::NULL_VALUE: sqlite3_bind_null(sqlite_stmt, sqlite3_bind_parameter_index(sqlite_stmt, value.first.c_str())); break; } } return SQLiteResult(sqlite_stmt); } int64_t SQLiteDB::last_insert_rowid(){ return sqlite3_last_insert_rowid(db); } SQLiteSavepoint::SQLiteSavepoint(SQLiteDB& db, const std::string savepoint_name) : db(db), name(savepoint_name) { db.exec(std::string("SAVEPOINT ")+name); } SQLiteSavepoint::SQLiteSavepoint(SQLiteDB* db, const std::string savepoint_name) : db(*db), name(savepoint_name) { db->exec(std::string("SAVEPOINT ")+name); } SQLiteSavepoint::~SQLiteSavepoint(){ db.exec(std::string("RELEASE ")+name); } SQLiteLock::SQLiteLock(SQLiteDB& db) : db(db) { sqlite3_mutex_enter(sqlite3_db_mutex(db.sqlite3_handle())); } SQLiteLock::SQLiteLock(SQLiteDB* db) : db(*db) { sqlite3_mutex_enter(sqlite3_db_mutex(db->sqlite3_handle())); } SQLiteLock::~SQLiteLock(){ sqlite3_mutex_leave(sqlite3_db_mutex(db.sqlite3_handle())); } } /* namespace librevault */
33.035714
144
0.748108
[ "vector" ]
99799c1fdabc65fd56cc3cf007731d02f7be3069
1,881
cc
C++
screen-capture-utils/kmsvnc_utils_test.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
screen-capture-utils/kmsvnc_utils_test.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
screen-capture-utils/kmsvnc_utils_test.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2021 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <gtest/gtest.h> #include <vector> #include "screen-capture-utils/kmsvnc_utils.h" namespace screenshot { void runConvertBuffer(uint32_t crtc_width, uint32_t crtc_height) { uint32_t stride = crtc_width * kBytesPerPixel; uint32_t vnc_width = getVncWidth(crtc_width); uint32_t vnc_height = crtc_height; // Display buffer initialized with dummy val of 'A' char dummyDisplayValue = 'A'; std::vector<char> displayBuffer(crtc_width * crtc_height * kBytesPerPixel, dummyDisplayValue); std::vector<char> vncBuffer(vnc_width * vnc_height * kBytesPerPixel); DisplayBuffer::Result display{crtc_width, crtc_height, stride}; display.buffer = displayBuffer.data(); ConvertBuffer(display, vncBuffer.data(), vnc_width); int index = 0; bool bufferMatched = true; int padIdx = crtc_width * kBytesPerPixel; for (char c : vncBuffer) { int displayIdx = index % (vnc_width * kBytesPerPixel); if (displayIdx < padIdx) { if (c != dummyDisplayValue) { bufferMatched = false; break; } } else { if (c != 0) { bufferMatched = false; break; } } index++; } EXPECT_EQ(bufferMatched, true); } TEST(VncServerTest, HandlesPadding) { EXPECT_EQ(getVncWidth(5), 8); EXPECT_EQ(getVncWidth(12), 12); } TEST(VncServerTest, ConvertBuffer) { // Given: A display (W x H) // When: Convert display buffer to VNC Buffer where width is a mult of 4 // Then: VNC Buffer contains display buffer data, but right padded with 0 // if display width is not a multiple of 4 runConvertBuffer(40, 2); runConvertBuffer(1366, 768); // width not a mult of 4 } } // namespace screenshot
27.661765
76
0.682084
[ "vector" ]
5f53f0ed83b6e2b185b7f70b5ffe25b902762be2
58,871
cpp
C++
src/compile/compile_p4.cpp
eniac/Mantis
aca2542d02655c1cdec29a32b258901c2b0b8866
[ "MIT" ]
15
2020-08-12T12:57:23.000Z
2021-11-04T16:11:31.000Z
src/compile/compile_p4.cpp
eniac/Mantis
aca2542d02655c1cdec29a32b258901c2b0b8866
[ "MIT" ]
null
null
null
src/compile/compile_p4.cpp
eniac/Mantis
aca2542d02655c1cdec29a32b258901c2b0b8866
[ "MIT" ]
null
null
null
/* Copyright 2020-present University of Pennsylvania * * 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 <unordered_map> #include <vector> #include <math.h> #include "../../include/find_nodes.h" #include "../../include/helper.h" #include "compile_p4.h" #include "compile_const.h" void transformPragma(vector<AstNode*>* astNodes) { // For now, a simple increment of stage index for (auto node : *astNodes) { if(typeContains(node, "TableNode")) { if (typeContains(node, "P4R")) { P4RMalleableTableNode* tablenode = dynamic_cast<P4RMalleableTableNode*>(node); tablenode->transformPragma(); } else { TableNode* tablenode = dynamic_cast<TableNode*>(node); tablenode->transformPragma(); } } } } int inferIsoOptForIng(vector<AstNode*>* nodeArray, bool forIng) { int inferred_iso = -1; bool require_meas_iso = true; bool require_react_iso = true; vector<ReactionArgNode*> reaction_args = findReactionArgs(*nodeArray); int num_args = 0; bool has_regarg = false; bool has_fieldarg = false; for (auto ra : reaction_args) { if(forIng) { if (ra->argType_==ReactionArgNode::REGISTER) { if(findRegargInIng(ra, *nodeArray)) { num_args += 1; has_regarg = true; } } if (ra->argType_==ReactionArgNode::INGRESS_FIELD || ra->argType_==ReactionArgNode::INGRESS_MBL_FIELD) { num_args += 1; has_fieldarg = true; } } else { if (ra->argType_==ReactionArgNode::REGISTER) { if(!findRegargInIng(ra, *nodeArray)) { num_args += 1; has_regarg = true; } } if (ra->argType_==ReactionArgNode::EGRESS_FIELD || ra->argType_==ReactionArgNode::EGRESS_MBL_FIELD) { num_args += 1; has_fieldarg = true; } } } if (num_args <= 1) { require_meas_iso = false; } else { // Potentially being false after bin-packing (single packed register, 2 single element reg) // Also single element 32b reg could be packed with field arg into a single 64b reg } // Simple static analysis to differentiate the case requiring no update isolation P4RReactionNode * react_node = findReaction(*nodeArray); string user_dialogue = ""; if (react_node != 0) { user_dialogue = react_node->body_->toString(); } bool foundMblOperation = false; // If malleable table operations specified, break if any for (auto node : *nodeArray) { if(typeContains(node, "P4RMalleableTableNode")) { P4RMalleableTableNode* table = dynamic_cast<P4RMalleableTableNode*>(node); string table_name = *(table->table_->name_->word_); if(forIng) { if(!findTblInIng(table_name, *nodeArray)) { continue; } } else { if(findTblInIng(table_name, *nodeArray)) { continue; } } if(user_dialogue.find(table_name+"_mod")!=std::string::npos || user_dialogue.find(table_name+"_add")!=std::string::npos || user_dialogue.find(table_name+"_del")!=std::string::npos) { foundMblOperation = true; break; } } } if (!foundMblOperation) { require_react_iso = false; } if (require_meas_iso && require_react_iso) { inferred_iso = 3; } else if (require_meas_iso && !require_react_iso) { inferred_iso = 1; } else if (!require_meas_iso && require_react_iso) { inferred_iso = 2; } else { inferred_iso = 0; } if(forIng) { PRINT_VERBOSE("Inferred ing isolation option: %d\n", inferred_iso); } else { PRINT_VERBOSE("Inferred egr isolation option: %d\n", inferred_iso); } return inferred_iso; } // Wrap ingress with calls to setup and finalize bool augmentIngress(vector<AstNode*>* astNodes) { // Fetch ingress P4ExprNode* ingressNode = findIngress(*astNodes); if (!ingressNode) { PANIC("Error: could not find the egress control block. Perhaps you didn't call it 'ingress'?\n"); exit(1); } // Rename ingress ingressNode->name1_->word_ = new string(kOrigIngControlName); // Generate new ingress function that wraps original ostringstream oss; oss << "control ingress {\n" // Separate ing and egr for cases when queueing > PCIe latency (large packet buffer+congested link) << " " << kSetmblIngControlName << "();\n" << " " << kOrigIngControlName << "();\n" << " " << kSetargsIngControlName << "();\n" << " " << kRegArgGateIngControlName << "();\n" << "}\n\n"; StrNode* newIngressNode = new StrNode(new string(oss.str())); // Inject wrapper right before original InputNode* firstInput = dynamic_cast<InputNode*>(ingressNode->parent_); InputNode* secondInput = new InputNode(firstInput->next_, firstInput->expression_); firstInput->next_ = secondInput; secondInput->parent_ = firstInput; firstInput->expression_ = newIngressNode; astNodes->push_back(secondInput); return true; } // Wrap ingress with calls to setup and finalize bool augmentEgress(vector<AstNode*>* astNodes) { // Fetch egress P4ExprNode* egressNode = findEgress(*astNodes); if (!egressNode) { PANIC("Error: could not find the egress control block. Perhaps you didn't call it 'egress'?\n"); exit(1); } // Rename egress egressNode->name1_->word_ = new string(kOrigEgrControlName); // Generate new ingress function that wraps original ostringstream oss; oss << "control egress {\n" << " " << kSetmblEgrControlName << "();\n" << " " << kOrigEgrControlName << "();\n" << " " << kSetargsEgrControlName << "();\n" << " " << kRegArgGateEgrControlName << "();\n" << "}\n\n"; StrNode* newEgressNode = new StrNode(new string(oss.str())); // Inject wrapper right before original InputNode* firstInput = dynamic_cast<InputNode*>(egressNode->parent_); InputNode* secondInput = new InputNode(firstInput->next_, firstInput->expression_); firstInput->next_ = secondInput; secondInput->parent_ = firstInput; firstInput->expression_ = newEgressNode; astNodes->push_back(secondInput); return true; } // Current generic approach can be expensive in terms of TCAM usage (even when user uses exact match for the mbl field) // Alternatives: // 1. Use dynamic masking of exact match table (tofino feature) // 2. Match on a given-width helper meta data and in the preceeding table (extra table cost), assign corresponding values to it static void transformTableWithRefRead(MblRefNode* ref, TableNode* table, const P4RMalleableFieldNode& variable) { auto readStmtsNode = dynamic_cast<TableReadStmtsNode*>(ref->parent_->parent_); // Assemble list of alts vector<FieldNode*> alts = findAllAlts(variable); bool first = true; TableReadStmtNode::MatchType matchType; for (FieldNode* fn : alts) { const string& headerName = *fn->headerName_->word_; const string& fieldName = *fn->fieldName_->word_; if (first) { ref->transform(headerName, fieldName); auto readStmt = dynamic_cast<TableReadStmtNode*>(ref->parent_); if (readStmt->matchType_ == TableReadStmtNode::EXACT) { readStmt->matchType_ = TableReadStmtNode::TERNARY; } matchType = readStmt->matchType_; first = false; } else { auto newStmtNode = new TableReadStmtNode(matchType, fn); readStmtsNode->push_back(newStmtNode); } } // Add exact match bit for the meta field of the variable const string variableName = *ref->name_->word_; ostringstream oss; oss << kP4rIngMetadataName << "." << variableName << kP4rIndexSuffix; if (!findTableReadStmt(*table, oss.str())) { auto newReadStmtNode = new TableReadStmtNode(TableReadStmtNode::EXACT, new StrNode(new string(oss.str()))); table->reads_->push_back(newReadStmtNode); } } // For small number of mbls and alts, specialized action approach avoids atomicity and extra table and possibily stage overhead // Even when multiple mbls are used, one typically splits the usage into separate tables static void duplicateActions(MblRefNode* ref, ActionNode* action, vector<MblRefNode*>* mblRefs, vector<AstNode*>* nodeArray, const P4RMalleableFieldNode& variable) { const string actionName = *action->name_->word_; const string variableName = *ref->name_->word_; // Assemble list of alts vector<FieldNode*> alts = findAllAlts(variable); // Instantiate the duplicate actions // Keep a copy of the names for when we fiddle with the table actions vector<string> altNames = vector<string>(); bool first = true; for (FieldNode* fn : alts) { const string& headerName = *fn->headerName_->word_; const string& fieldName = *fn->fieldName_->word_; if (first) { ostringstream oss; oss << "__" << headerName << "__" << fieldName << "__" << actionName; altNames.push_back(oss.str()); // Change action to the instantiated name *action->name_->word_ = oss.str(); // Replace the varref inside the alt with an actual ref findAndTransformMblRefsInAction(action, NULL, variableName, headerName, fieldName); first = false; } else { ostringstream oss; oss << "__" << headerName << "__" << fieldName << "__" << actionName; altNames.push_back(oss.str()); // Create action with the instantiated name ActionNode* newAction = action->duplicateAction(oss.str()); // Inject Action right after the first InputNode* firstInput = dynamic_cast<InputNode*>(action->parent_); InputNode* secondInput = new InputNode(firstInput->next_, newAction); firstInput->next_ = secondInput; secondInput->parent_ = firstInput; newAction->parent_ = secondInput; // Add any newly created mblRefs from the action findAndTransformMblRefsInAction(newAction, mblRefs, variableName, headerName, fieldName); } } // Modify all tables that use the original action auto actionStmtMap = findTableActionStmts(*nodeArray, actionName); for (auto kv : actionStmtMap) { // Change all tables to have all possible actions first = true; for (auto altName : altNames) { if (first) { *kv.first->name_->word_ = altName; first = false; } else { auto newActionStmtNode = new TableActionStmtNode(new NameNode(new string(altName))); kv.second->actions_->push_back(newActionStmtNode); } } // Add the alt field match to the table if it does not already exist ostringstream oss; oss << kP4rIngMetadataName << "." << variableName << kP4rIndexSuffix; if (!findTableReadStmt(*kv.second, oss.str())) { auto newReadStmtNode = new TableReadStmtNode(TableReadStmtNode::EXACT, new StrNode(new string(oss.str()))); kv.second->reads_->push_back(newReadStmtNode); } } } static void transformMalleableFieldRef(MblRefNode* ref, vector<MblRefNode*>* mblRefs, vector<AstNode*>* nodeArray, const P4RMalleableFieldNode& variable) { // malleable field references can be in (1) actions, (2) table match fields, // and (3) reaction arguments AstNode* parent = ref->parent_; while (parent != NULL) { if (typeContains(parent, "ActionNode")) { ActionNode* action = dynamic_cast<ActionNode*>(parent); duplicateActions(ref, action, mblRefs, nodeArray, variable); return; } else if (typeContains(parent, "TableNode")) { TableNode* table = dynamic_cast<TableNode*>(parent); transformTableWithRefRead(ref, table, variable); return; } else if (typeContains(parent, "P4RReactionNode")) { return; } parent = parent->parent_; } PANIC("Syntax Error: Could not find parent of variable reference\n"); exit(1); } void findMalleableUsage( vector<MblRefNode*> mblRefs, const unordered_map<string, P4RMalleableValueNode*> mblValues, const unordered_map<string, P4RMalleableFieldNode*> mblFields, vector<AstNode*>* nodeArray, unordered_map<string, int>* mblUsage) { while (!mblRefs.empty()) { MblRefNode* varRef = mblRefs.front(); mblRefs.erase(mblRefs.begin()); string* varName = varRef->name_->word_; if(mblUsage->find(*varName) != mblUsage->end()) { continue; } // Find the usage index: 0 - ingress, 1 - egress, 2 - both bool in_ingress = false; bool in_egress = false; // One var could be used in multiple tbls for (auto node : *nodeArray) { // Though filter P4RMalleableTableNode, its table node is still searched if(typeContains(node, "TableNode") && !typeContains(node, "P4R")) { TableNode* table = dynamic_cast<TableNode*>(node); string table_name = *(table->name_->word_); // Try to determine if the table uses the mblRef bool useMblRef = false; if(table->toString().find(*varName) != string::npos) { useMblRef = true; } else { // Check if used actions for (auto action : *table->actions_->list_) { for (auto tmp_node : *nodeArray) { if(typeContains(tmp_node, "ActionNode")) { ActionNode* tmp_action_node = dynamic_cast<ActionNode*>(tmp_node); string tmp_action_name = tmp_action_node->name_->toString(); if(tmp_action_name.compare(action->name_->toString())==0) { if(tmp_action_node->toString().find(*varName) != string::npos) { useMblRef = true; break; } } } } if(useMblRef) { break; } } } if(useMblRef) { if(findTblInIng(table_name, *nodeArray)) { in_ingress = true; } else { in_egress = true; } } } } if(in_ingress && in_egress) { mblUsage->emplace(*varName, USAGE::BOTH); } else if (in_ingress) { mblUsage->emplace(*varName, USAGE::INGRESS); } else if (in_egress) { mblUsage->emplace(*varName, USAGE::EGRESS); } else { PANIC("Can not find the target mblRef %s usage\n", varName->c_str()); } } PRINT_VERBOSE("mbl usage dict:\n"); for (auto i : *mblUsage) { PRINT_VERBOSE(" %s : %d\n", i.first.c_str(), i.second); } } void transformMalleableRefs( vector<MblRefNode*>* mblRefs, const unordered_map<string, P4RMalleableValueNode*>& mblValues, const unordered_map<string, P4RMalleableFieldNode*>& mblFields, vector<AstNode*>* nodeArray) { while (!mblRefs->empty()) { MblRefNode* varRef = mblRefs->front(); mblRefs->erase(mblRefs->begin()); if (varRef->transformed_) { // We must have processed this variable reference in a previous pass // e.g., multiple references in the same action continue; } string* varName = varRef->name_->word_; if (mblValues.find(*varName) != mblValues.end()) { // we should treat variable value references in reaction and others differently bool is_in_reaction = false; AstNode* parent = varRef->parent_; while (parent != NULL) { if (typeContains(parent, "P4RReactionNode")) { is_in_reaction = true; break; } parent = parent->parent_; } if (is_in_reaction) { // For c code, we skip the transformation varRef->inReaction_ = true; } else { // Otherwise, transform it to valid meta data varRef->transform(string(kP4rIngMetadataName), *varRef->name_->word_); } } else if (mblFields.find(*varName) != mblFields.end()) { // Reference to a variable field transformMalleableFieldRef(varRef, mblRefs, nodeArray, *mblFields.find(*varName)->second); } else { PANIC("Unknown malleable ref!"); } } } void transformMalleableTables(unordered_map<string, P4RMalleableTableNode*>* varTables, vector<AstNode*> nodeArray, int ing_iso_opt, int egr_iso_opt) { for (auto t : *varTables) { // Check if mbl table in ing/egr if(findTblInIng(t.second->table_->name_->toString(), nodeArray)) { if (((unsigned int)ing_iso_opt) & 0b10) { auto field = new FieldNode(new NameNode(new string(kP4rIngMetadataName)), new NameNode(new string("__vv"))); auto readstmt = new TableReadStmtNode(TableReadStmtNode::EXACT, field); t.second->table_->reads_->list_->push_back(readstmt); } } else { if (((unsigned int)egr_iso_opt) & 0b10) { auto field = new FieldNode(new NameNode(new string(kP4rEgrMetadataName)), new NameNode(new string("__vv"))); auto readstmt = new TableReadStmtNode(TableReadStmtNode::EXACT, field); t.second->table_->reads_->list_->push_back(readstmt); } } } } void generateExportControl(vector<AstNode*>* newNodes, const vector<ReactionArgBin>& argBinsIng, const vector<ReactionArgBin>& argBinsEgr){ ostringstream oss; oss << "control " << kSetargsIngControlName << " {\n"; for (int i = 0; i < argBinsIng.size(); ++i) { oss << " apply(__tiPack" << i << ");\n"; oss << " apply(__tiSetArgs" << i << ");\n"; } oss << "}\n\n"; newNodes->push_back(new UnanchoredNode(new string(oss.str()), new string("control"), new string(kSetargsIngControlName))); oss.str(""); oss << "control " << kSetargsEgrControlName << " {\n"; for (int i = 0; i < argBinsEgr.size(); ++i) { oss << " apply(__tePack" << i << ");\n"; oss << " apply(__teSetArgs" << i << ");\n"; } oss << "}\n\n"; newNodes->push_back(new UnanchoredNode(new string(oss.str()), new string("control"), new string(kSetargsEgrControlName))); } void generateRegArgGateControl(vector<AstNode*>* newNodes, vector<AstNode*>* nodeArray, const vector<ReactionArgNode*>& reaction_args, int ing_iso_opt, int egr_iso_opt) { // Generate control flow branching on mv bit ostringstream oss; oss << "control " << kRegArgGateIngControlName << " {\n"; // An alternative is to use single reg with double the size and index elements with original_index<<1+mv // Though less memory overhead but larger latency if (((unsigned int)ing_iso_opt) & 0b1) { for (auto ra : reaction_args) { if (ra->argType_==ReactionArgNode::REGISTER && findRegargInIng(ra, *nodeArray)) { oss << " if (" << kP4rIngMetadataName << ".__mv == 0 ) {\n" << " apply (" << kP4rRegReplicasTablePrefix << ra->toString() << kP4rRegReplicasSuffix0 << ");\n" << " }\n" << " else { \n" << " apply (" << kP4rRegReplicasTablePrefix << ra->toString() << kP4rRegReplicasSuffix1 << ");\n" << " }\n"; } } } oss << "}\n\n"; newNodes->push_back(new UnanchoredNode(new string(oss.str()), new string("control"), new string(kRegArgGateIngControlName))); oss.str(""); oss << "control " << kRegArgGateEgrControlName << " {\n"; if (((unsigned int)egr_iso_opt) & 0b1) { for (auto ra : reaction_args) { if (ra->argType_==ReactionArgNode::REGISTER && !findRegargInIng(ra, *nodeArray)) { oss << " if (" << kP4rEgrMetadataName << ".__mv == 0 ) {\n" << " apply (" << kP4rRegReplicasTablePrefix << ra->toString() << kP4rRegReplicasSuffix0 << ");\n" << " }\n" << " else { \n" << " apply (" << kP4rRegReplicasTablePrefix << ra->toString() << kP4rRegReplicasSuffix1 << ");\n" << " }\n"; } } } oss << "}\n\n"; newNodes->push_back(new UnanchoredNode(new string(oss.str()), new string("control"), new string(kRegArgGateEgrControlName))); } void generateDupRegArgProg(vector<AstNode*>* newNodes, vector<AstNode*>* nodeArray, const vector<ReactionArgNode*>& reaction_args, int ing_iso_opt, int egr_iso_opt) { ostringstream oss; vector<P4RegisterNode*> regNodes = findP4RegisterNode(*nodeArray); vector<P4ExprNode*> blackboxes = findBlackbox(*nodeArray); for (auto ra : reaction_args) { if (ra->argType_==ReactionArgNode::REGISTER) { if ((findRegargInIng(ra, *nodeArray) && (((unsigned int)ing_iso_opt) & 0b1)) || (!findRegargInIng(ra, *nodeArray) && (((unsigned int)egr_iso_opt) & 0b1)) ) { PRINT_VERBOSE("Duplicate for %s\n", ra->toString().c_str()); } else { continue; } } else { continue; } for(auto reg : regNodes) { if(reg->name_->toString().compare(ra->toString())==0) { // Duplicate registers oss.str(""); oss << "register " << reg->name_->toString() << kP4rRegReplicasSuffix0 << "{\n" << " width : 64;\n" << " instance_count : " << reg->instanceCount_ << ";\n" << "}\n\n"; newNodes->push_back(new UnanchoredNode(new string(oss.str()), new string("register"), new string(reg->name_->toString()+kP4rRegReplicasSuffix0))); oss.str(""); oss << "register " << reg->name_->toString() << kP4rRegReplicasSuffix1 << "{\n" << " width : 64;\n" << " instance_count : " << reg->instanceCount_ << ";\n" << "}\n\n"; newNodes->push_back(new UnanchoredNode(new string(oss.str()), new string("register"), new string(reg->name_->toString()+kP4rRegReplicasSuffix1))); // Duplicate blackbox // Currently assuming 32b reg with only LO, for 64b, extra tstamp reg required oss.str(""); oss << "blackbox stateful_alu " << kP4rRegReplicasBlackboxPrefix << reg->name_->toString() << kP4rRegReplicasSuffix0 << "{\n" << " reg : " << reg->name_->toString() << kP4rRegReplicasSuffix0 << ";\n" << " update_hi_1_value : register_hi + 1;\n" << " update_lo_1_value : " << kP4rIngRegMetadataName << "." << reg->name_->toString() << kP4rRegMetadataOutputSuffix << ";\n" << "}\n\n"; newNodes->push_back(new UnanchoredNode(new string(oss.str()), new string("blackbox"), new string(kP4rRegReplicasBlackboxPrefix+reg->name_->toString()+kP4rRegReplicasSuffix0))); oss.str(""); oss << "blackbox stateful_alu " << kP4rRegReplicasBlackboxPrefix << reg->name_->toString() << kP4rRegReplicasSuffix1 << "{\n" << " reg : " << reg->name_->toString() << kP4rRegReplicasSuffix1 << ";\n" << " update_hi_1_value : register_hi + 1;\n" << " update_lo_1_value : " << kP4rIngRegMetadataName << "." << reg->name_->toString() << kP4rRegMetadataOutputSuffix << ";\n" << "}\n\n"; newNodes->push_back(new UnanchoredNode(new string(oss.str()), new string("blackbox"), new string(kP4rRegReplicasBlackboxPrefix+reg->name_->toString()+kP4rRegReplicasSuffix1))); // Duplicate actions oss.str(""); oss << "action " << kP4rRegReplicasActionPrefix << reg->name_->toString() << kP4rRegReplicasSuffix0 << "(){\n" << " " << kP4rRegReplicasBlackboxPrefix << reg->name_->toString() << kP4rRegReplicasSuffix0 << ".execute_stateful_alu(" << kP4rIngRegMetadataName << "." << reg->name_->toString() << kP4rRegMetadataIndexSuffix << ");\n" << "}\n\n"; newNodes->push_back(new UnanchoredNode(new string(oss.str()), new string("action"), new string(kP4rRegReplicasActionPrefix+reg->name_->toString()+kP4rRegReplicasSuffix0))); oss.str(""); oss << "action " << kP4rRegReplicasActionPrefix << reg->name_->toString() << kP4rRegReplicasSuffix1 << "(){\n" << " " << kP4rRegReplicasBlackboxPrefix << reg->name_->toString() << kP4rRegReplicasSuffix1 << ".execute_stateful_alu(" << kP4rIngRegMetadataName << "." << reg->name_->toString() << kP4rRegMetadataIndexSuffix << ");\n" << "}\n\n"; newNodes->push_back(new UnanchoredNode(new string(oss.str()), new string("action"), new string(kP4rRegReplicasActionPrefix+reg->name_->toString()+kP4rRegReplicasSuffix1))); // Duplicate tables oss.str(""); oss << "table " << kP4rRegReplicasTablePrefix << reg->name_->toString() << kP4rRegReplicasSuffix0 << "{\n" << " actions {\n" << " " << kP4rRegReplicasActionPrefix << reg->name_->toString() << kP4rRegReplicasSuffix0 << ";\n" << "}\n" << " default_action: " << kP4rRegReplicasActionPrefix << reg->name_->toString() << kP4rRegReplicasSuffix0 << "();\n" << "}\n\n"; newNodes->push_back(new UnanchoredNode(new string(oss.str()), new string("table"), new string(kP4rRegReplicasTablePrefix+reg->name_->toString()+kP4rRegReplicasSuffix0))); oss.str(""); oss << "table " << kP4rRegReplicasTablePrefix << reg->name_->toString() << kP4rRegReplicasSuffix1 << "{\n" << " actions {\n" << " " << kP4rRegReplicasActionPrefix << reg->name_->toString() << kP4rRegReplicasSuffix1 << ";\n" << "}\n" << " default_action: " << kP4rRegReplicasActionPrefix << reg->name_->toString() << kP4rRegReplicasSuffix1 << "();\n" << "}\n\n"; newNodes->push_back(new UnanchoredNode(new string(oss.str()), new string("table"), new string(kP4rRegReplicasTablePrefix+reg->name_->toString()+kP4rRegReplicasSuffix1))); break; } } } } void augmentRegisterArgProgForIng(vector<AstNode*>* newNodes, vector<AstNode*>* nodeArray, const vector<ReactionArgNode*>& reaction_args, int iso_opt, bool forIng) { string p4rRegMetadataType; string p4rRegMetadataName; if(forIng) { p4rRegMetadataType = string(kP4rIngRegMetadataType); p4rRegMetadataName = string(kP4rIngRegMetadataName); } else { p4rRegMetadataType = string(kP4rEgrRegMetadataType); p4rRegMetadataName = string(kP4rEgrRegMetadataName); } // Generate meta data for storing latest value of register index, value if (((unsigned int)iso_opt) & 0b1) { ostringstream oss; oss << "header_type "<< p4rRegMetadataType << " {\n" << " fields {\n"; vector<P4RegisterNode*> regNodes = findP4RegisterNode(*nodeArray); for (auto ra : reaction_args) { if (ra->argType_==ReactionArgNode::REGISTER) { if(forIng) { if(!findRegargInIng(ra, *nodeArray)) { continue; } } else { if(findRegargInIng(ra, *nodeArray)) { continue; } } for(auto reg : regNodes) { if(reg->name_->toString().compare(ra->toString())==0) { oss << " " << ra->toString() << kP4rRegMetadataOutputSuffix << " : "<< reg->width_ << ";\n"; int index_width = int(ceil(log2(reg->instanceCount_))); if (index_width==0) { index_width = 1; } oss << " " << ra->toString() << kP4rRegMetadataIndexSuffix << " : "<< index_width << ";\n"; break; } } } } oss << " }" << endl; oss << "}" << endl; oss << "metadata " << p4rRegMetadataType << " " << p4rRegMetadataName << ";\n\n"; newNodes->push_back(new UnanchoredNode(new string(oss.str()), new string("metadata"), new string(p4rRegMetadataName))); // Transform original blackbox program // Currently assume the reg to isolation has no HI member and no output instruction // If original blackbox has output instruction already, just mirror that the output meta data vector<P4ExprNode*> blackboxes = findBlackbox(*nodeArray); for (auto blackbox : blackboxes) { std::string prog_name = blackbox->name2_->toString(); std::stringstream ss(blackbox->body_->toString()); std::string reg_name; std::string item; while (std::getline(ss, item, ';')) { std::stringstream ss_(item); std::string item_; while (std::getline(ss_, item_, ':')) { boost::algorithm::trim(item_); if(item_.compare("reg")==0) { std::getline(ss_, item_, ':'); boost::algorithm::trim(item_); reg_name = item_; } } } ostringstream oss_dst_field, oss_index_field; oss_dst_field << p4rRegMetadataName << "." << reg_name << kP4rRegMetadataOutputSuffix; oss_index_field << p4rRegMetadataName << "." << reg_name << kP4rRegMetadataIndexSuffix; ostringstream oss_cmd; oss_cmd << " " << "output_value : alu_lo;\n" << " " << "output_dst : " << oss_dst_field.str() << ";\n"; string newbodystr = blackbox->body_->toString()+oss_cmd.str(); blackbox->body_ = new BodyNode(NULL, NULL, new BodyWordNode(BodyWordNode::STRING, new StrNode(new string(newbodystr)))); // Singleton action that executes the prog // Locate the action that executes the stateful prog and mirror the index to meta bool transformed = false; for (auto tmp_node : *nodeArray) { if(typeContains(tmp_node, "ActionNode") && !typeContains(tmp_node, "P4R")) { ActionNode* tmp_action_node = dynamic_cast<ActionNode*>(tmp_node); string tmp_action_name = tmp_action_node->name_->toString(); ActionStmtsNode* actionstmts = tmp_action_node->stmts_; for (ActionStmtNode* as : *actionstmts->list_) { if(as->toString().find("execute_stateful_alu")!=string::npos && as->toString().find(prog_name)!=string::npos) { // Extract the index or index metadata/field unsigned first = as->toString().find("("); unsigned last = as->toString().find(")"); string index = as->toString().substr (first+1,last-first-1); // Mirror the index to p4r reg metadata auto tmp_args = new ArgsNode(); tmp_args->push_back(new BodyWordNode( BodyWordNode::STRING, new StrNode(new string(oss_index_field.str())))); tmp_args->push_back(new BodyWordNode( BodyWordNode::STRING, new StrNode(new string(index)))); actionstmts->push_back(new ActionStmtNode( new NameNode(new string("modify_field")), tmp_args, ActionStmtNode::NAME_ARGLIST, NULL, NULL )); transformed = true; break; } } if (transformed) { break; } } } } } } static vector<ReactionArgBin> runBinPackForIng( vector<pair<ReactionArgNode*, int> >* argSizes, vector<AstNode*> nodeArray, bool forIng) { sort(argSizes->begin(), argSizes->end(), [](const pair<ReactionArgNode*, int>& l, const pair<ReactionArgNode*, int>& r) { if (l.second != r.second) { return l.second > r.second; } return l.first > r.first; }); vector<ReactionArgBin> bins; for (const pair<ReactionArgNode*, int>& p : *argSizes) { assert(p.second <= REGISTER_SIZE); // Packing if(forIng) { if(p.first->argType_!=ReactionArgNode::INGRESS_FIELD && p.first->argType_!=ReactionArgNode::INGRESS_MBL_FIELD) { continue; } } else { if(p.first->argType_!=ReactionArgNode::EGRESS_FIELD && p.first->argType_!=ReactionArgNode::EGRESS_MBL_FIELD) { continue; } } bool added = false; for (ReactionArgBin& bin : bins) { if (p.second + bin.second <= REGISTER_SIZE) { bin.first.push_back(p); bin.second += p.second; added = true; break; } } if (!added) { vector<ReactionArgSize> newBin; newBin.push_back(p); bins.emplace_back(move(newBin), p.second); } } return bins; } static void generateArgRegistersForIng(vector<AstNode*>* newNodes, const vector<ReactionArgBin>& bins, int ing_iso_opt, bool forIng) { string p4rArgHdrName; string p4rMetaName; string p4rSetArgsTableNameBase; string p4rSetArgsActionNameBase; string p4rSetArgsBlackboxNameBase; string p4rSetArgsRegNameBase; if(forIng) { p4rArgHdrName = std::string(kP4rIngArghdrName); p4rMetaName = std::string(kP4rIngMetadataName); p4rSetArgsTableNameBase = "__tiSetArgs"; p4rSetArgsActionNameBase = "__aiSetArgs"; p4rSetArgsBlackboxNameBase = "__biSetArgs"; p4rSetArgsRegNameBase = "__riSetArgs"; } else { p4rArgHdrName = std::string(kP4rEgrArghdrName); p4rMetaName = std::string(kP4rEgrMetadataName); p4rSetArgsTableNameBase = "__teSetArgs"; p4rSetArgsActionNameBase = "__aeSetArgs"; p4rSetArgsBlackboxNameBase = "__beSetArgs"; p4rSetArgsRegNameBase = "__reSetArgs"; } for (int i = 0; i < bins.size(); ++i) { ostringstream oss; oss << "table " << p4rSetArgsTableNameBase << i << " {\n" << " actions { " << p4rSetArgsActionNameBase << i << "; }\n" << " default_action : " << p4rSetArgsActionNameBase << i << "();\n" << "}\n\n" << "action " << p4rSetArgsActionNameBase << i << "() {\n"; if (((unsigned int)ing_iso_opt) & 0b1) { oss << " " << p4rSetArgsBlackboxNameBase << i << ".execute_stateful_alu("<< p4rMetaName << ".__mv);\n"; } else { oss << " " << p4rSetArgsBlackboxNameBase << i << ".execute_stateful_alu(0);\n"; } oss << "}\n\n" << "blackbox stateful_alu " << p4rSetArgsBlackboxNameBase << i << " {\n" << " reg : " << p4rSetArgsRegNameBase << i << ";\n" << " update_lo_1_value : " << p4rArgHdrName << ".reg" << i << ";\n" << "}\n\n" << "register " << p4rSetArgsRegNameBase << i << " {\n" << " width : " << bins[i].second << ";\n" << " instance_count : 2;\n" << "}\n\n"; auto newSetArgsNode = new UnanchoredNode(new string(oss.str()), new string("table"), new string("__tiSetArgs")); newNodes->push_back(newSetArgsNode); } } static vector<MblRefNode*> generatePackingTablesForIng(vector<AstNode*>* newNodes, const vector<ReactionArgBin>& bins, bool forIng) { vector<MblRefNode*> reactionArgRefs; string p4rArgHdrType; string p4rArgHdrName; string p4rPackTableNameBase; string p4rPackActionNameBase; string p4rPackFlcNameBase; string p4rPackFlNameBase; if(forIng) { p4rArgHdrType = std::string(kP4rIngArghdrType); p4rArgHdrName = std::string(kP4rIngArghdrName); p4rPackTableNameBase = "__tiPack"; p4rPackActionNameBase = "__aiPack"; p4rPackFlcNameBase = "__flci_packedArgs_reg"; p4rPackFlNameBase = "__fli_packedArgs_reg"; } else { p4rArgHdrType = std::string(kP4rEgrArghdrType); p4rArgHdrName = std::string(kP4rEgrArghdrName); p4rPackTableNameBase = "__tePack"; p4rPackActionNameBase = "__aePack"; p4rPackFlcNameBase = "__flce_packedArgs_reg"; p4rPackFlNameBase = "__fle_packedArgs_reg"; } // Generate packed fields ostringstream oss_fld; oss_fld << "header_type " << p4rArgHdrType << " {\n" << " fields {\n"; for (int i = 0; i < bins.size(); ++i) { oss_fld << " reg" << i << " : " << bins[i].second << ";\n"; } oss_fld << " }\n" << "}\n\n" << "metadata " << p4rArgHdrType << " " << p4rArgHdrName << ";\n\n"; auto packedMetaNode = new UnanchoredNode( new string(oss_fld.str()), new string("metadata"), new string(p4rArgHdrType)); newNodes->push_back(packedMetaNode); // Synthesize table/action for each pack for (int i = 0; i < bins.size(); ++i) { // Generate packing table auto tiPackName = new NameNode(new string(p4rPackTableNameBase+std::to_string(i))); auto tiPackReads = new TableReadStmtsNode(); auto tiPackActions = new TableActionStmtsNode(); tiPackActions->push_back( new TableActionStmtNode(new NameNode(new string(p4rPackActionNameBase+std::to_string(i))))); auto tiPackTable = new TableNode(tiPackName, tiPackReads, tiPackActions, " default_action : "+p4rPackActionNameBase+std::to_string(i)+"();\nsize:1;", ""); newNodes->push_back(tiPackTable); // Generate packing action auto aiPackName = new NameNode(new string(p4rPackActionNameBase+std::to_string(i))); auto aiPackParams = new ActionParamsNode(); auto aiPackStmts = new ActionStmtsNode(); // Actual size of the reg (<= 32) int regsize = 0; // Generate field list node ostringstream oss_fl; oss_fl << "field_list " << p4rPackFlNameBase << i << "{\n"; for (int j = 0; j < bins[i].first.size(); ++j) { AstNode* arg = bins[i].first[j].first->arg_; int width = bins[i].first[j].second; regsize += width; if (typeContains(arg, "FieldNode")) { oss_fl << arg->toString() << ";\n"; } else if (typeContains(arg, "MblRefNode")) { oss_fl << arg->toString() << ";\n"; // Mark this ref for future processing // Currently not supporting field list and hash duplication reactionArgRefs.push_back(dynamic_cast<MblRefNode*>(arg)); } else { assert(false); } } // Close field_list oss_fl << "\n}\n\n"; newNodes->push_back( new UnanchoredNode( new string(oss_fl.str()), new string("field_list"), new string("field_list"+std::to_string(i))) ); // Generate field_list_calculation ostringstream oss_flc; oss_flc << "field_list_calculation " << p4rPackFlcNameBase << i << " {\n" << " input {\n" << " " << p4rPackFlNameBase << i << ";\n" << " }\n" << " algorithm : identity;\n" << " output_width : " << regsize << ";\n" << "}\n\n"; newNodes->push_back( new UnanchoredNode( new string(oss_flc.str()), new string("field_list_calc"), new string(p4rPackFlcNameBase+std::to_string(i))) ); // Example: modify_field_with_hash_based_offset(dst, 0, __flce_packedArgs_reg0, 4294967296); // Note: alternative approach using (modify - shift_left - add_to_field) would not fit into a single action due to data plane constraints auto aiPackStmtName = new NameNode(new string("modify_field_with_hash_based_offset")); auto aiPackStmtArgs = new ArgsNode(); // dst ostringstream oss_postfix; oss_postfix << "reg" << i; BodyWordNode* targetBodyWord = new BodyWordNode( BodyWordNode::FIELD, new FieldNode( new NameNode(new string(p4rArgHdrName)), new NameNode(new string(oss_postfix.str())))); aiPackStmtArgs->push_back(targetBodyWord); // base aiPackStmtArgs->push_back( new BodyWordNode( BodyWordNode::INTEGER, new IntegerNode(new string(to_string(0))))); // __calc_packedArgs_regx aiPackStmtArgs->push_back( new BodyWordNode( BodyWordNode::STRING, new StrNode(new string(p4rPackFlcNameBase+std::to_string(i))))); // size (power of 2) aiPackStmtArgs->push_back( new BodyWordNode( BodyWordNode::INTEGER, new IntegerNode(new string(to_string((long long)(pow(2, regsize))))))); aiPackStmts->push_back( new ActionStmtNode(aiPackStmtName, aiPackStmtArgs, ActionStmtNode::NAME_ARGLIST, NULL, NULL)); auto aiPackAction = new ActionNode(aiPackName, aiPackParams, aiPackStmts); auto aiPackActionWrapper = new InputNode(NULL, aiPackAction); newNodes->push_back(aiPackActionWrapper); } return reactionArgRefs; } vector<ReactionArgBin> generateIngDigestPacking( vector<AstNode*>* newNodes, const vector<ReactionArgNode*>& reaction_args, const HeaderDecsMap& headerDecsMap, const unordered_map<string, P4RMalleableValueNode*>& mblValues, const unordered_map<string, P4RMalleableFieldNode*>& mblFields, const vector<AstNode*>& astNodes, int* ing_iso_opt) { if (reaction_args.size() == 0) { return vector<ReactionArgBin>(); } vector<pair<ReactionArgNode*, int> > argSizes = findAllReactionArgSizes(reaction_args, headerDecsMap, mblValues, mblFields); // Currently pack arguments into 32-bit bins // Note HW target could support 64-bit reg --- further reducing the number of packed regs by half (therefore latency) vector<ReactionArgBin> argBins = runBinPackForIng(&argSizes, astNodes, true); vector<MblRefNode*> mblRefs = generatePackingTablesForIng(newNodes, argBins, true); // Update meas isolation option if(argBins.size()<=1) { vector<ReactionArgNode*> reaction_args = findReactionArgs(astNodes); bool has_regarg = false; for (auto ra : reaction_args) { if (ra->argType_==ReactionArgNode::REGISTER) { if(findRegargInIng(ra, astNodes)) { has_regarg = true; } } } if(!has_regarg) { if((*ing_iso_opt)==1) { *ing_iso_opt = 0; } else if ((*ing_iso_opt)==3) { *ing_iso_opt = 2; } PRINT_VERBOSE("Update ing isolation opt to %d\n", *ing_iso_opt); } } generateArgRegistersForIng(newNodes, argBins, *ing_iso_opt, true); // Redo the transformations to capture any malleable references in the generated code PRINT_VERBOSE("Found %d generated malleable refs for ing\n", mblRefs.size()); transformMalleableRefs(&mblRefs, mblValues, mblFields, newNodes); return argBins; } vector<ReactionArgBin> generateEgrDigestPacking( vector<AstNode*>* newNodes, const vector<ReactionArgNode*>& reaction_args, const HeaderDecsMap& headerDecsMap, const unordered_map<string, P4RMalleableValueNode*>& mblValues, const unordered_map<string, P4RMalleableFieldNode*>& mblFields, const vector<AstNode*>& astNodes, int* egr_iso_opt) { if (reaction_args.size() == 0) { return vector<ReactionArgBin>(); } // Get all reaction argument sizes vector<pair<ReactionArgNode*, int> > argSizes = findAllReactionArgSizes(reaction_args, headerDecsMap, mblValues, mblFields); vector<ReactionArgBin> argBins = runBinPackForIng(&argSizes, astNodes, false); vector<MblRefNode*> mblRefs = generatePackingTablesForIng(newNodes, argBins, false); // Update meas isolation if(argBins.size()<=1) { vector<ReactionArgNode*> reaction_args = findReactionArgs(astNodes); bool has_regarg = false; for (auto ra : reaction_args) { if (ra->argType_==ReactionArgNode::REGISTER) { if(findRegargInIng(ra, astNodes)) { has_regarg = true; } } } if(!has_regarg) { if((*egr_iso_opt)==1) { *egr_iso_opt = 0; } else if ((*egr_iso_opt)==3) { *egr_iso_opt = 2; } PRINT_VERBOSE("Update ing isolation opt to %d\n", *egr_iso_opt); } } generateArgRegistersForIng(newNodes, argBins, *egr_iso_opt, false); PRINT_VERBOSE("Found %d generated malleable refs for egr\n", mblRefs.size()); transformMalleableRefs(&mblRefs, mblValues, mblFields, newNodes); return argBins; } // Generate metadata for dynamic variables void generateMetadata(vector<AstNode*>* newNodes, const unordered_map<string, P4RMalleableValueNode*>& mblValues, const unordered_map<string, P4RMalleableFieldNode*>& mblFields, int ing_iso_opt, int egr_iso_opt) { ostringstream oss; // Ing oss << "header_type "<< kP4rIngMetadataType << " {\n" << " fields {\n"; if (((unsigned int)ing_iso_opt) & 0b1) { oss << " __mv : 1;\n"; } if (((unsigned int)ing_iso_opt) & 0b10) { oss << " __vv : 1;\n"; } // Presume malleables at ing for (auto kv : mblValues){ // Values need to be as wide as specified VarWidthNode* widthNode = dynamic_cast<VarWidthNode*>(kv.second->varWidth_); string varWidth = widthNode->val_->toString(); oss << " " << kv.first << " : " << varWidth << ";" << endl; } for (auto kv : mblFields){ // Ref-vars only need to be wide enough to store an index auto alts = findAllAlts(*kv.second); int indexWidth = 1; if(alts.size()!=1) { indexWidth = int(ceil(log2(alts.size()))); } oss << " " << kv.first << kP4rIndexSuffix << " : " << indexWidth << ";" << endl; } oss << " }" << endl; oss << "}" << endl; oss << "metadata " << kP4rIngMetadataType << " " << kP4rIngMetadataName << ";\n\n"; newNodes->push_back(new UnanchoredNode(new string(oss.str()), new string("metadata"), new string(kP4rIngMetadataName))); // Egr oss.str(""); oss << "header_type "<< kP4rEgrMetadataType << " {\n" << " fields {\n"; if (((unsigned int)egr_iso_opt) & 0b1) { oss << " __mv : 1;\n"; } oss << " }" << endl; oss << "}" << endl; oss << "metadata " << kP4rEgrMetadataType << " " << kP4rEgrMetadataName << ";\n\n"; newNodes->push_back(new UnanchoredNode(new string(oss.str()), new string("metadata"), new string(kP4rEgrMetadataName))); } int generateInitTableForIng(unordered_map<string, int>* mblUsages, vector<AstNode*>* newNodes, const unordered_map<string, P4RMalleableValueNode*>& mblValues, const unordered_map<string, P4RMalleableFieldNode*>& mblFields, int iso_opt, bool forIng) { // As the set of mbls in practice is small, currently a monolithic init for ing or egr ostringstream oss; string p4rInitActionName; string p4rSetVarTblName; string p4rMetadataName; if(forIng) { p4rInitActionName = string(kP4rIngInitAction); p4rSetVarTblName = "__tiSetVars"; p4rMetadataName = string(kP4rIngMetadataName); } else { p4rInitActionName = string(kP4rEgrInitAction); p4rSetVarTblName = "__teSetVars"; p4rMetadataName = string(kP4rEgrMetadataName); } oss << "action " << p4rInitActionName << "("; bool first = true; bool has_var = false; int num_vars = 0; for (auto kv : mblValues) { if(forIng && mblUsages->at(kv.first)==USAGE::EGRESS) { continue; } if(!forIng && mblUsages->at(kv.first)==USAGE::INGRESS) { continue; } if (first) { first = false; } else { oss << ", "; } has_var = true; oss << "p__" << kv.first; num_vars += 1; } for (auto kv : mblFields) { if(forIng && mblUsages->at(kv.first)==USAGE::EGRESS) { continue; } if(!forIng && mblUsages->at(kv.first)==USAGE::INGRESS) { continue; } if (first) { first = false; } else { oss << ", "; } has_var = true; oss << "p__" << kv.first << kP4rIndexSuffix; num_vars += 1; } if(has_var && iso_opt != 0) { oss << ", "; } if(iso_opt == 1) { oss << "__mv"; num_vars += 1; } else if(iso_opt == 2) { oss << "__vv"; num_vars += 1; } else if (iso_opt == 3) { oss << "__mv , __vv"; num_vars += 2; } if(forIng) { PRINT_VERBOSE("Number of ing vars to set in init: %d\n", num_vars); } else { PRINT_VERBOSE("Number of egr vars to set in init: %d\n", num_vars); } oss << ") {\n"; for (auto kv : mblValues) { if(forIng && mblUsages->at(kv.first)==USAGE::EGRESS) { continue; } if(!forIng && mblUsages->at(kv.first)==USAGE::INGRESS) { continue; } oss << " modify_field(" << p4rMetadataName << "." << kv.first << ", p__" << kv.first << ");\n"; } for (auto kv : mblFields) { if(forIng && mblUsages->at(kv.first)==USAGE::EGRESS) { continue; } if(!forIng && mblUsages->at(kv.first)==USAGE::INGRESS) { continue; } oss << " modify_field(" << p4rMetadataName << "." << kv.first << kP4rIndexSuffix << ", p__" << kv.first << kP4rIndexSuffix << ");\n"; } if(((unsigned int)iso_opt) & 0b1) { oss << " modify_field(" << p4rMetadataName << "." << "__mv, __mv" << ");\n"; } if (((unsigned int)iso_opt) & 0b10) { oss << " modify_field(" << p4rMetadataName << "." << "__vv, __vv" << ");\n"; } // pragma stage 0 not required due to the match dependency of later tables matching on __vv, __mv, field_alt oss << "}\n\n" << "table " << p4rSetVarTblName << " {\n" << " actions {\n" << " " << p4rInitActionName << ";\n" << " }\n" << " size : 1;\n" << "}\n\n"; string* codeStr = new string(oss.str()); string* objType = new string("table"); string* tableName = new string(p4rSetVarTblName); newNodes->push_back(new UnanchoredNode(codeStr, objType, tableName)); return num_vars; } void generateSetvarControl(vector<AstNode*>* newNodes) { ostringstream oss; oss << "control "<< kSetmblIngControlName << " {\n"; oss << " apply(__tiSetVars);\n"; oss << "}\n\n"; newNodes->push_back(new UnanchoredNode(new string(oss.str()), new string("control"), new string(kSetmblIngControlName))); oss.str(""); oss << "control "<< kSetmblEgrControlName << " {\n"; oss << " apply(__teSetVars);\n"; oss << "}\n\n"; newNodes->push_back(new UnanchoredNode(new string(oss.str()), new string("control"), new string(kSetmblEgrControlName))); }
41.990728
194
0.523331
[ "vector", "transform" ]
5f58db67e2fdfda60a5c1ab73fde9ab471321b68
318
cpp
C++
C++/Single-Number-II.cpp
shreyventure/LeetCode-Solutions
74423d65702b78974e390f17c9d6365d17e6eed5
[ "MIT" ]
388
2020-06-29T08:41:27.000Z
2022-03-31T22:55:05.000Z
C++/Single-Number-II.cpp
shreyventure/LeetCode-Solutions
74423d65702b78974e390f17c9d6365d17e6eed5
[ "MIT" ]
178
2020-07-16T17:15:28.000Z
2022-03-09T21:01:50.000Z
C++/Single-Number-II.cpp
shreyventure/LeetCode-Solutions
74423d65702b78974e390f17c9d6365d17e6eed5
[ "MIT" ]
263
2020-07-13T18:33:20.000Z
2022-03-28T13:54:10.000Z
// Leetcode URL: https://leetcode.com/problems/single-number-ii /* * Runtime - 4ms * Memory - 9.5 */ class Solution { public: int singleNumber(vector<int>& nums) { int a=0, b=0; for(int num: nums) { a = b & (a^num); b = a | (b^num); } return b; } };
18.705882
63
0.481132
[ "vector" ]
5f5a57b7a652e7a809acc8a2977bb8a9a67eb7c8
24,586
cpp
C++
ProjectX/Ddutil.cpp
ForsakenW/forsaken
f06e2b9031e96a9fd219ab1326ad4eacbab37d44
[ "MIT" ]
7
2015-06-21T13:01:03.000Z
2020-08-09T19:53:26.000Z
ProjectX/Ddutil.cpp
ForsakenW/forsaken
f06e2b9031e96a9fd219ab1326ad4eacbab37d44
[ "MIT" ]
3
2015-06-26T01:35:18.000Z
2016-05-11T22:50:48.000Z
ProjectX/Ddutil.cpp
ForsakenW/forsaken
f06e2b9031e96a9fd219ab1326ad4eacbab37d44
[ "MIT" ]
null
null
null
/* * The X Men, June 1996 * Copyright (c) 1996 Probe Entertainment Limited * All Rights Reserved * * Authors: Philipy */ /*========================================================================== * * Copyright (C) 1995-1996 Microsoft Corporation. All Rights Reserved. * * File: ddutil.cpp * Content: Routines for loading bitmap and palettes from resources * ***************************************************************************/ #define WIN32_EXTRA_LEAN #include <windows.h> #include <windowsx.h> #include <ddraw.h> #include "ddutil.h" #include "ddsurfhand.h" #include "math.h" /* * Defines */ #define MAXMIPMAP 8 #define MIPMAPMIN 16 extern "C" void DebugPrintf( const char * format, ... ); extern "C" void AddCommentToBat( const char * format, ... ); extern "C" void AddFileToBat( char * Filename ); extern "C" void AddCommandToBat( const char * format, ... ); extern "C" BOOL bPrimaryPalettized; extern "C" double Gamma; /* * DDLoadBitmap * * create a DirectDrawSurface from a bitmap resource. * */ #ifdef DEBUG_ON IDirectDrawSurface * DDLoadBitmapDebug(IDirectDraw *pdd, LPCSTR szBitmap, int dx, int dy, char *in_file, int in_line ) { HBITMAP hbm; BITMAP bm; DDSURFACEDESC ddsd; IDirectDrawSurface *pdds; static int bitmaps; // // try to load the bitmap as a resource, if that fails, try it as a file // // hbm = (HBITMAP)LoadImage(GetModuleHandle(NULL), szBitmap, IMAGE_BITMAP, dx, dy, LR_CREATEDIBSECTION); // if (hbm == NULL) hbm = (HBITMAP)LoadImage(NULL, szBitmap, IMAGE_BITMAP, dx, dy, LR_LOADFROMFILE|LR_CREATEDIBSECTION); if (hbm == NULL) return NULL; DebugPrintf( "DDLoadBitmap: bitmap %2d = %s\n", bitmaps++, szBitmap ); AddFileToBat( (char *) szBitmap ); // // get size of the bitmap // GetObject(hbm, sizeof(bm), &bm); // get size of bitmap // // create a DirectDrawSurface for this bitmap // ZeroMemory(&ddsd, sizeof(ddsd)); ddsd.dwSize = sizeof(ddsd); ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT |DDSD_WIDTH; ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN; ddsd.dwWidth = bm.bmWidth; ddsd.dwHeight = bm.bmHeight; if ( !MakeDDSurf( pdd, &ddsd, &pdds, NULL, in_file, in_line ) ) return NULL; DDCopyBitmap(pdds, hbm, 0, 0, 0, 0); DeleteObject(hbm); return pdds; } #else IDirectDrawSurface * DDLoadBitmap(IDirectDraw *pdd, LPCSTR szBitmap, int dx, int dy) { HBITMAP hbm; BITMAP bm; DDSURFACEDESC ddsd; IDirectDrawSurface *pdds; static int bitmaps; // // try to load the bitmap as a resource, if that fails, try it as a file // // hbm = (HBITMAP)LoadImage(GetModuleHandle(NULL), szBitmap, IMAGE_BITMAP, dx, dy, LR_CREATEDIBSECTION); // if (hbm == NULL) hbm = (HBITMAP)LoadImage(NULL, szBitmap, IMAGE_BITMAP, dx, dy, LR_LOADFROMFILE|LR_CREATEDIBSECTION); if (hbm == NULL) return NULL; DebugPrintf( "DDLoadBitmap: bitmap %2d = %s\n", bitmaps++, szBitmap ); AddFileToBat( (char *) szBitmap ); // // get size of the bitmap // GetObject(hbm, sizeof(bm), &bm); // get size of bitmap // // create a DirectDrawSurface for this bitmap // ZeroMemory(&ddsd, sizeof(ddsd)); ddsd.dwSize = sizeof(ddsd); ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT |DDSD_WIDTH; ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN; ddsd.dwWidth = bm.bmWidth; ddsd.dwHeight = bm.bmHeight; if (pdd->CreateSurface(&ddsd, &pdds, NULL) != DD_OK) return NULL; DDCopyBitmap(pdds, hbm, 0, 0, 0, 0); DeleteObject(hbm); return pdds; } #endif // DEBUG_ON /* * DDLoadBitmapOverlay * * create a DirectDrawSurface from a bitmap resource. * */ extern "C" IDirectDrawSurface * DDLoadBitmapOverlay(IDirectDraw *pdd, LPCSTR szBitmap, int dx, int dy) { HBITMAP hbm; BITMAP bm; DDSURFACEDESC ddsd; IDirectDrawSurface *pdds; // // try to load the bitmap as a resource, if that fails, try it as a file // // hbm = (HBITMAP)LoadImage(GetModuleHandle(NULL), szBitmap, IMAGE_BITMAP, dx, dy, LR_CREATEDIBSECTION); // if (hbm == NULL) hbm = (HBITMAP)LoadImage(NULL, szBitmap, IMAGE_BITMAP, dx, dy, LR_LOADFROMFILE|LR_CREATEDIBSECTION); if (hbm == NULL) return NULL; // // get size of the bitmap // GetObject(hbm, sizeof(bm), &bm); // get size of bitmap // // create a DirectDrawSurface for this bitmap // ZeroMemory(&ddsd, sizeof(ddsd)); ddsd.dwSize = sizeof(ddsd); ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT |DDSD_WIDTH; ddsd.ddsCaps.dwCaps = DDSCAPS_OVERLAY; ddsd.dwWidth = bm.bmWidth; ddsd.dwHeight = bm.bmHeight; ddsd.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT); ddsd.ddpfPixelFormat.dwFlags = DDPF_RGB; ddsd.ddpfPixelFormat.dwFourCC = BI_RGB; ddsd.ddpfPixelFormat.dwRGBBitCount = 16; if (pdd->CreateSurface(&ddsd, &pdds, NULL) != DD_OK) return NULL; DDCopyBitmap(pdds, hbm, 0, 0, 0, 0); DeleteObject(hbm); return pdds; } /* * DDReLoadBitmap * * load a bitmap from a file or resource into a directdraw surface. * normaly used to re-load a surface after a restore. * */ HRESULT DDReLoadBitmap(IDirectDrawSurface *pdds, LPCSTR szBitmap) { HBITMAP hbm; HRESULT hr; // // try to load the bitmap as a resource, if that fails, try it as a file // // hbm = (HBITMAP)LoadImage(GetModuleHandle(NULL), szBitmap, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION); // if (hbm == NULL) hbm = (HBITMAP)LoadImage(NULL, szBitmap, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE|LR_CREATEDIBSECTION); if (hbm == NULL) { OutputDebugString("handle is null\n"); return E_FAIL; } hr = DDCopyBitmap(pdds, hbm, 0, 0, 0, 0); if (hr != DD_OK) { OutputDebugString("ddcopybitmap failed\n"); } DeleteObject(hbm); return hr; } HRESULT HBitmapToDirectDrawSurface(LPDIRECTDRAWSURFACE pdds, HBITMAP hbm) { HRESULT hr; hr = DDCopyTextureBitmap(pdds, hbm, 0, 0, 0, 0); return hr; } /* * DDCopyBitmap * * draw a bitmap into a DirectDrawSurface * */ extern "C" HRESULT DDCopyBitmap(IDirectDrawSurface *pdds, HBITMAP hbm, int x, int y, int dx, int dy) { HDC hdcImage; HDC hdc; BITMAP bm; DDSURFACEDESC ddsd; HRESULT hr; RGBQUAD Colours[256]; int numofcolours; int i; BYTE GammaTab[256]; double k; int r,g,b; unsigned long m; int s; int red_shift, red_scale; int green_shift, green_scale; int blue_shift, blue_scale; if (hbm == NULL || pdds == NULL) return E_FAIL; // recover in release build if (Gamma <= 0) Gamma = 1.0; k = 255.0/pow(255.0, 1.0/Gamma); for (i = 0; i <= 255; i++) { GammaTab[i] = (BYTE)(k*(pow((double)i, 1.0/Gamma))); if( i ) { if( !GammaTab[i] ) GammaTab[i] = 1; } } // // make sure this surface is restored. // pdds->Restore(); // // select bitmap into a memoryDC so we can use it. // hdcImage = CreateCompatibleDC(NULL); if (!hdcImage) OutputDebugString("createcompatible dc failed\n"); SelectObject(hdcImage, hbm); // // get size of the bitmap // GetObject(hbm, sizeof(bm), &bm); // get size of bitmap dx = dx == 0 ? bm.bmWidth : dx; // use the passed size, unless zero dy = dy == 0 ? bm.bmHeight : dy; // // get size of surface. // memset(&ddsd, 0, sizeof(DDSURFACEDESC)); ddsd.dwSize = sizeof(DDSURFACEDESC); ddsd.dwFlags = DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT; pdds->GetSurfaceDesc(&ddsd); if( ddsd.ddpfPixelFormat.dwRBitMask ) { for (s = 0, m = ddsd.ddpfPixelFormat.dwRBitMask; !(m & 1); s++, m >>= 1); red_shift = s; red_scale = 255 / (ddsd.ddpfPixelFormat.dwRBitMask >> s); }else{ red_scale = 0; } if( ddsd.ddpfPixelFormat.dwGBitMask ) { for (s = 0, m = ddsd.ddpfPixelFormat.dwGBitMask; !(m & 1); s++, m >>= 1); green_shift = s; green_scale = 255 / (ddsd.ddpfPixelFormat.dwGBitMask >> s); }else{ green_scale = 0; } if( ddsd.ddpfPixelFormat.dwBBitMask ) { for (s = 0, m = ddsd.ddpfPixelFormat.dwBBitMask; !(m & 1); s++, m >>= 1); blue_shift = s; blue_scale = 255 / (ddsd.ddpfPixelFormat.dwBBitMask >> s); }else{ blue_scale = 0; } blue_scale *= 2; red_scale *= 2; green_scale *= 2; if( bm.bmBitsPixel <= 8 ) { numofcolours = GetDIBColorTable( hdcImage, // handle of device context whose DIB is of interest 0, // color table index of first entry to retrieve 256, // number of color table entries to retrieve &Colours[0]); // pointer to buffer that receives color table entries for( i = 0 ; i < numofcolours ; i ++ ) { r = Colours[i].rgbRed; g = Colours[i].rgbGreen; b = Colours[i].rgbBlue; Colours[i].rgbRed = GammaTab[Colours[i].rgbRed]; Colours[i].rgbGreen = GammaTab[Colours[i].rgbGreen]; Colours[i].rgbBlue = GammaTab[Colours[i].rgbBlue]; if( ( r + g + b ) != 0 ) { if( ( Colours[i].rgbRed <= red_scale ) && ( Colours[i].rgbGreen <= green_scale ) && ( Colours[i].rgbBlue <= blue_scale ) ) { Colours[i].rgbBlue = blue_scale; } } } SetDIBColorTable( hdcImage, // handle of device context whose DIB is of interest 0, // color table index of first entry to retrieve numofcolours, // number of color table entries to retrieve &Colours[0]); // pointer to buffer that receives color table entries } if ((hr = pdds->GetDC(&hdc)) == DD_OK) { SetStretchBltMode( hdc, HALFTONE ); SetBrushOrgEx( hdc , 0 , 0 , NULL ); SetStretchBltMode( hdcImage, HALFTONE ); SetBrushOrgEx( hdcImage , 0 , 0 , NULL ); StretchBlt(hdc, 0, 0, ddsd.dwWidth, ddsd.dwHeight, hdcImage, x, y, dx, dy, SRCCOPY); pdds->ReleaseDC(hdc); } DeleteDC(hdcImage); return hr; } extern "C" HRESULT DDCopyTextureBitmap(IDirectDrawSurface *pdds, HBITMAP hbm, int x, int y, int dx, int dy) { HDC hdcImage; HDC hdc; DDSURFACEDESC ddsd; HRESULT hr; DIBSECTION dib; if (hbm == NULL || pdds == NULL) return E_FAIL; // // make sure this surface is restored. // pdds->Restore(); // // select bitmap into a memoryDC so we can use it. // hdcImage = CreateCompatibleDC(NULL); if (!hdcImage) OutputDebugString("createcompatible dc failed\n"); SelectObject(hdcImage, hbm); // // get size of the bitmap // GetObject(hbm, sizeof(dib), &dib); // get size of bitmap dx = dx == 0 ? dib.dsBm.bmWidth : dx; // use the passed size, unless zero dy = dy == 0 ? dib.dsBm.bmHeight : dy; // // get size of surface. // ddsd.dwSize = sizeof(ddsd); pdds->GetSurfaceDesc(&ddsd); if ((hr = pdds->GetDC(&hdc)) == DD_OK) { StretchBlt(hdc, 0, 0, ddsd.dwWidth, ddsd.dwHeight, hdcImage, x, y, dx, dy, SRCCOPY); pdds->ReleaseDC(hdc); } DeleteDC(hdcImage); return hr; } // // DDLoadPalette // // Create a DirectDraw palette object from a bitmap resoure // // if the resource does not exist or NULL is passed create a // default 332 palette. // extern "C" IDirectDrawPalette * DDLoadPalette(IDirectDraw *pdd, LPCSTR szBitmap) { IDirectDrawPalette* ddpal; int i; int n; int fh; // HRSRC h; // LPBITMAPINFOHEADER lpbi; PALETTEENTRY ape[256]; // RGBQUAD * prgb; // // build a 332 palette as the default. // for (i=0; i<256; i++) { ape[i].peRed = (BYTE)(((i >> 5) & 0x07) * 255 / 7); ape[i].peGreen = (BYTE)(((i >> 2) & 0x07) * 255 / 7); ape[i].peBlue = (BYTE)(((i >> 0) & 0x03) * 255 / 3); ape[i].peFlags = (BYTE)0; } // // get a pointer to the bitmap resource. // #if 0 if (szBitmap && (h = FindResource(NULL, szBitmap, RT_BITMAP))) { lpbi = (LPBITMAPINFOHEADER)LockResource(LoadResource(NULL, h)); if (!lpbi) OutputDebugString("lock resource failed\n"); prgb = (RGBQUAD*)((BYTE*)lpbi + lpbi->biSize); if (lpbi == NULL || lpbi->biSize < sizeof(BITMAPINFOHEADER)) n = 0; else if (lpbi->biBitCount > 8) n = 0; else if (lpbi->biClrUsed == 0) n = 1 << lpbi->biBitCount; else n = lpbi->biClrUsed; // // a DIB color table has its colors stored BGR not RGB // so flip them around. // for(i=0; i<n; i++ ) { ape[i].peRed = prgb[i].rgbRed; ape[i].peGreen = prgb[i].rgbGreen; ape[i].peBlue = prgb[i].rgbBlue; ape[i].peFlags = 0; } } else #endif if (szBitmap && (fh = _lopen(szBitmap, OF_READ)) != -1) { BITMAPFILEHEADER bf; BITMAPINFOHEADER bi; _lread(fh, &bf, sizeof(bf)); _lread(fh, &bi, sizeof(bi)); _lread(fh, ape, sizeof(ape)); _lclose(fh); if (bi.biSize != sizeof(BITMAPINFOHEADER)) n = 0; else if (bi.biBitCount > 8) n = 0; else if (bi.biClrUsed == 0) n = 1 << bi.biBitCount; else n = bi.biClrUsed; // // a DIB color table has its colors stored BGR not RGB // so flip them around. // for(i=0; i<n; i++ ) { BYTE r = ape[i].peRed; ape[i].peRed = ape[i].peBlue; ape[i].peBlue = r; } } pdd->CreatePalette(DDPCAPS_8BIT | DDPCAPS_ALLOW256 , ape, &ddpal, NULL); return ddpal; } /* * DDColorMatch * * convert a RGB color to a pysical color. * * we do this by leting GDI SetPixel() do the color matching * then we lock the memory and see what it got mapped to. */ extern "C" DWORD DDColorMatch(IDirectDrawSurface *pdds, COLORREF rgb) { COLORREF rgbT; HDC hdc; DWORD dw = CLR_INVALID; DDSURFACEDESC ddsd; HRESULT hres; // // use GDI SetPixel to color match for us // if (rgb != CLR_INVALID && pdds->GetDC(&hdc) == DD_OK) { rgbT = GetPixel(hdc, 0, 0); // save current pixel value SetPixel(hdc, 0, 0, rgb); // set our value pdds->ReleaseDC(hdc); } // // now lock the surface so we can read back the converted color // ddsd.dwSize = sizeof(ddsd); while ((hres = pdds->Lock(NULL, &ddsd, 0, NULL)) == DDERR_WASSTILLDRAWING) ; if (hres == DD_OK) { dw = *(DWORD *)ddsd.lpSurface; // get DWORD dw &= (1 << ddsd.ddpfPixelFormat.dwRGBBitCount)-1; // mask it to bpp pdds->Unlock(NULL); } // // now put the color that was there back. // if (rgb != CLR_INVALID && pdds->GetDC(&hdc) == DD_OK) { SetPixel(hdc, 0, 0, rgbT); pdds->ReleaseDC(hdc); } return dw; } /* * DDSetColorKey * * set a color key for a surface, given a RGB. * if you pass CLR_INVALID as the color key, the pixel * in the upper-left corner will be used. */ extern "C" HRESULT DDSetColorKey(IDirectDrawSurface *pdds, COLORREF rgb) { DDCOLORKEY ddck; ddck.dwColorSpaceLowValue = DDColorMatch(pdds, rgb); ddck.dwColorSpaceHighValue = ddck.dwColorSpaceLowValue; return pdds->SetColorKey(DDCKEY_SRCBLT, &ddck); } IDirectDrawSurface * DDLoadBitmapTexture(IDirectDraw *pdd, LPCSTR szBitmap, LPDDSURFACEDESC ddsd , int Scale , BOOL bSquareOnly) { HBITMAP hbm; BITMAP bm; IDirectDrawSurface *pdds; DDSURFACEDESC ddsd2; DWORD dwWidth, dwHeight; LPDIRECTDRAWPALETTE ddpal; ddsd2 = *ddsd; ddsd2.dwFlags |= DDSD_CAPS; ddsd2.ddsCaps.dwCaps |= DDSCAPS_SYSTEMMEMORY; int XScale,YScale; hbm = (HBITMAP)LoadImage(NULL, szBitmap, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE|LR_CREATEDIBSECTION); if (hbm == NULL) return NULL; AddFileToBat( (char *) szBitmap ); // // get size of the bitmap // GetObject(hbm, sizeof(bm), &bm); // get size of bitmap dwWidth = bm.bmWidth; dwHeight = bm.bmHeight; // // create a DirectDrawSurface for this bitmap // memcpy(&ddsd2, ddsd, sizeof(DDSURFACEDESC)); ddsd2.dwSize = sizeof(DDSURFACEDESC); ddsd2.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT; ddsd2.ddsCaps.dwCaps = DDSCAPS_TEXTURE | DDSCAPS_SYSTEMMEMORY; XScale = Scale; YScale = Scale; // PowerVR Only Like Square Textures... if( bSquareOnly ) { if( dwHeight != dwWidth ) { if( dwHeight > dwWidth ) YScale++; if( dwWidth > dwHeight ) XScale++; } } ddsd2.dwHeight = dwHeight / ( 1 << YScale ); ddsd2.dwWidth = dwWidth / ( 1 << XScale ); if (pdd->CreateSurface(&ddsd2, &pdds, NULL) != DD_OK) return NULL; if (bPrimaryPalettized) { ddpal = DDLoadPalette( pdd ,"data\\pictures\\pal.bmp"); }else{ ddpal = DDLoadPalette( pdd , szBitmap ); } pdds->SetPalette( ddpal ); DDCopyBitmap(pdds, hbm, 0, 0, 0, 0); DeleteObject(hbm); return pdds; } /*Build the MipMaps for a MIPMAPDESC structure with the toplevel filled*/ int FindMipMapLod( int Width , int Height , int Count ) { Width /= 2; Height /= 2; if( Width < MIPMAPMIN || Height < MIPMAPMIN || Count >= MAXMIPMAP ) return Count; return FindMipMapLod( Width , Height , Count+1 ); } IDirectDrawSurface * DDLoadBitmapTextureMipMap(IDirectDraw *pdd, LPCSTR szBitmap, LPDDSURFACEDESC ddsd , int Scale , BOOL bSquareOnly) { HBITMAP hbm; BITMAP bm; IDirectDrawSurface *pdds; DDSURFACEDESC ddsd2; DWORD dwWidth, dwHeight; LPDIRECTDRAWPALETTE ddpal; int LodCount; int LOD; int XScale,YScale; DDSCAPS ddscaps; HRESULT ddrval; LPDIRECTDRAWSURFACE lpDDS_top; ddsd2 = *ddsd; ddsd2.dwFlags |= DDSD_CAPS; ddsd2.ddsCaps.dwCaps |= DDSCAPS_SYSTEMMEMORY; hbm = (HBITMAP)LoadImage(NULL, szBitmap, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE|LR_CREATEDIBSECTION); if (hbm == NULL) return NULL; AddFileToBat( (char *) szBitmap ); // // get size of the bitmap // GetObject(hbm, sizeof(bm), &bm); // get size of bitmap dwWidth = bm.bmWidth; dwHeight = bm.bmHeight; // // create a DirectDrawSurface for this bitmap // ddsd2 = *ddsd; ddsd2.dwSize = sizeof(DDSURFACEDESC); XScale = Scale; YScale = Scale; // PowerVR Only Like Square Textures... if( bSquareOnly ) { if( dwHeight != dwWidth ) { if( dwHeight > dwWidth ) YScale++; if( dwWidth > dwHeight ) XScale++; } } ddsd2.dwHeight = dwHeight / ( 1 << YScale ); ddsd2.dwWidth = dwWidth / ( 1 << XScale ); ddsd2.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | DDSD_MIPMAPCOUNT; ddsd2.dwMipMapCount= LodCount = FindMipMapLod( ddsd2.dwWidth , ddsd2.dwHeight , 1 ); ddsd2.ddsCaps.dwCaps = DDSCAPS_TEXTURE | DDSCAPS_COMPLEX | DDSCAPS_MIPMAP | DDSCAPS_SYSTEMMEMORY; ddsd2.dwHeight = dwHeight; ddsd2.dwWidth = dwWidth; if (pdd->CreateSurface(&ddsd2, &pdds, NULL) != DD_OK) return NULL; lpDDS_top = pdds; if (bPrimaryPalettized) { ddpal = DDLoadPalette( pdd ,"data\\pictures\\pal.bmp"); }else{ ddpal = DDLoadPalette( pdd , szBitmap ); } pdds->SetPalette( ddpal ); ddscaps.dwCaps=DDSCAPS_TEXTURE | DDSCAPS_MIPMAP; for(LOD=0;LOD<LodCount;LOD++) { #if 0 memset(&ddsd2, 0, sizeof(DDSURFACEDESC)); ddsd2.dwSize = sizeof(DDSURFACEDESC); ddrval = pdds->Lock( NULL, &ddsd2, 0, NULL); if (ddrval != DD_OK) { switch( ddrval ) { case DDERR_INVALIDOBJECT: pdds->Release(); return NULL; case DDERR_INVALIDPARAMS: pdds->Release(); return NULL; case DDERR_OUTOFMEMORY: pdds->Release(); return NULL; case DDERR_SURFACEBUSY: pdds->Release(); return NULL; case DDERR_SURFACELOST: pdds->Release(); return NULL; case DDERR_WASSTILLDRAWING: pdds->Release(); return NULL; } pdds->Release(); return NULL; } #endif DDCopyBitmap(pdds, hbm, 0, 0, 0, 0); /*Get the next mipmap level*/ ddrval=pdds->GetAttachedSurface( &ddscaps, &pdds); if(ddrval!=DD_OK && pdds!=NULL) { pdds->Release(); return NULL; } } DeleteObject(hbm); return lpDDS_top; } // // DDLoadPalette // // Create a DirectDraw palette object from a bitmap resoure // // if the resource does not exist or NULL is passed create a // default 332 palette. // extern "C" BOOL HasBmpGotRealBlack( LPCSTR szBitmap) { int i; int n = 0; int fh; // HRSRC h; // LPBITMAPINFOHEADER lpbi; PALETTEENTRY ape[256]; // RGBQUAD * prgb; BOOL RealBlack = FALSE; // // get a pointer to the bitmap resource. // #if 0 if (szBitmap && (h = FindResource(NULL, szBitmap, RT_BITMAP))) { lpbi = (LPBITMAPINFOHEADER)LockResource(LoadResource(NULL, h)); if (!lpbi) OutputDebugString("lock resource failed\n"); prgb = (RGBQUAD*)((BYTE*)lpbi + lpbi->biSize); if (lpbi == NULL || lpbi->biSize < sizeof(BITMAPINFOHEADER)) n = 0; else if (lpbi->biBitCount > 8) n = 0; else if (lpbi->biClrUsed == 0) n = 1 << lpbi->biBitCount; else n = lpbi->biClrUsed; // // a DIB color table has its colors stored BGR not RGB // so flip them around. // for(i=0; i<n; i++ ) { ape[i].peRed = prgb[i].rgbRed; ape[i].peGreen = prgb[i].rgbGreen; ape[i].peBlue = prgb[i].rgbBlue; ape[i].peFlags = 0; } } else #endif if (szBitmap && (fh = _lopen(szBitmap, OF_READ)) != -1) { BITMAPFILEHEADER bf; BITMAPINFOHEADER bi; _lread(fh, &bf, sizeof(bf)); _lread(fh, &bi, sizeof(bi)); _lread(fh, ape, sizeof(ape)); _lclose(fh); if (bi.biSize != sizeof(BITMAPINFOHEADER)) n = 0; else if (bi.biBitCount > 8) n = 0; else if (bi.biClrUsed == 0) n = 1 << bi.biBitCount; else n = bi.biClrUsed; // // a DIB color table has its colors stored BGR not RGB // so flip them around. // for(i=0; i<n; i++ ) { BYTE r = ape[i].peRed; ape[i].peRed = ape[i].peBlue; ape[i].peBlue = r; } } // Only check the first colour... if( n ) n = 1; for(i=0; i<n; i++ ) { if( ape[i].peRed == 0 && ape[i].peGreen == 0 && ape[i].peBlue == 0 ) return TRUE; } return FALSE; }
26.465016
141
0.550679
[ "object" ]
5f64301e8b8ff39dd6adb685d6189c6bb5822b48
8,746
cpp
C++
src/field.cpp
spokendotcpp/Generation_Terrain
661ff594653b82d93ae018158756c03b1a960b82
[ "MIT" ]
null
null
null
src/field.cpp
spokendotcpp/Generation_Terrain
661ff594653b82d93ae018158756c03b1a960b82
[ "MIT" ]
null
null
null
src/field.cpp
spokendotcpp/Generation_Terrain
661ff594653b82d93ae018158756c03b1a960b82
[ "MIT" ]
null
null
null
#include "../include/field.h" #include <iostream> Field::Field(float _width, float _height, float _length, size_t power) :width(_width), height(_height), length(_length), size(0), map(nullptr) { if( power >= 16 ) power = 8; // default // pow(2, power) + 1 size = (1 << power) + 1; map = new float*[size]; for(size_t i=0; i < size; ++i){ map[i] = new float[size]; for(size_t j=0; j < size; ++j) map[i][j] = 0; } } Field::~Field() { if( map != nullptr ){ for(size_t i=0; i < size; ++i){ delete [] map[i]; map[i] = nullptr; } delete [] map; map = nullptr; } } template<typename T> void median_filter(T** data, int width, int height, int window_width) { if( window_width % 2 == 0 ) window_width = 3; int x, y, k_idx; int window_size = window_width*window_width; int offset = window_width/2; T* window = new T[window_size]; T** map = new T*[height]; for(int i=0; i < height; ++i) map[i] = new T[width]; for(int j=0; j < height; ++j){ for(int i=0; i < width; ++i){ k_idx = 0; for(int l=-offset; l < offset; ++l){ y = j+l; if( y < 0 || y >= height ) y = j-l; for(int k=-offset; k < offset; ++k){ x = i+k; if( x < 0 || x >= height ) x = i-k; window[k_idx++] = data[y][x]; } } // Bubble sort for(int m=0; m < window_size; ++m){ for(int n=m+1; n < window_size; ++n){ if( window[m] > window[n] ){ T tmp = window[m]; window[m] = window[n]; window[n] = tmp; } } } // Get median value map[j][i] = window[window_size/2]; } } for(int j=0; j < height; ++j){ for(int i=0; i < width; ++i){ data[j][i] = map[j][i]; } delete map[j]; map[j] = nullptr; } delete [] map; map = nullptr; delete [] window; window = nullptr; } void Field::diamond_square() { if( map == nullptr ) return; float yMin = -(height/2.0f); float yMax = (height/2.0f); std::random_device random_device; std::mt19937 engine { random_device() }; std::uniform_real_distribution<float> random_number(yMin, yMax); // Init first 4 corners size_t last = size-1; map[0][0] = random_number(engine); map[0][last] = random_number(engine); map[last][0] = random_number(engine); map[last][last] = random_number(engine); size_t step = last; while( step > 1 ){ size_t half = step/2; yMax /= 2.0f; yMin /= 2.0f; // Modify the random range (make it smaller) random_number.param( std::uniform_real_distribution<float>::param_type(yMin, yMax) ); // Diamond step for(size_t j=half; j < size; j+=step){ for(size_t i=half; i < size; i+=step){ // Compute the current value of the map (j, i) // mean of neighbours + random value float mean = ( map[j-half][i-half] // top-left + map[j-half][i+half] // top-right + map[j+half][i-half] // bot-left + map[j+half][i+half] // bot-right ) / 4; map[j][i] = mean + random_number(engine); } } // Square step size_t offset = 0; for(size_t j=0; j < size; j+=half){ // Departure of our row if( offset == 0 ) offset = half; else offset = 0; for(size_t i=offset; i < size; i+=step){ float sum = 0; int n = 0; // edge test to ensure // we stay into the range of map[][]. if( i >= half ){ sum += map[j][i-half]; ++n; } if( i + half < size ){ sum += map[j][i+half]; ++n; } if( j >= half ){ sum += map[j-half][i]; ++n; } if( j + half < size ){ sum += map[j+half][i]; ++n; } if( n == 0 ) n = 1; map[j][i] = (sum/n) + random_number(engine); } } step = half; } // 5x5 median filter | filter bigest noise median_filter(map, int(size), int(size), 5); } bool Field::build(QOpenGLShaderProgram* program) { diamond_square(); MyMesh mesh; mesh.request_face_normals(); mesh.request_vertex_normals(); _vertices = size * size; _faces = ((size-1)*(size-1))*2; GLfloat* positions = new GLfloat[_vertices*3]; // Square mesh = (n-1)² squares // Triangle mesh = (n-1)² * 2 // One triangle has 3 indices // R = (n-1)² * 2 * 3 size_t nb_indices = _faces * 3; size_t it = 0; GLuint* indices = new GLuint[nb_indices]; float init_x = -(width/2.0f); float init_z = -(length/2.0f); float step_x = width/size; float step_z = length/size; float x = init_x; float z = init_z; for(size_t j=0; j < size; ++j){ for(size_t i=0; i < size; ++i){ size_t idx = (j*size + i); positions[(idx*3)+0] = x; positions[(idx*3)+1] = map[j][i]; positions[(idx*3)+2] = z; x += step_x; mesh.add_vertex( MyMesh::Point( positions[(idx*3)+0], positions[(idx*3)+1], positions[(idx*3)+2]) ); if( j < size-1 && i < size-1 ){ indices[it++] = GLuint(idx); indices[it++] = GLuint(idx+size); indices[it++] = GLuint(idx+1); indices[it++] = GLuint(idx+size); indices[it++] = GLuint(idx+size+1); indices[it++] = GLuint(idx+1); } } z += step_z; x = init_x; } // Add faces to OpenMesh struct so we can compute faces normals // (and then vertices normals). for(size_t i=0; i < nb_indices; i+=3){ mesh.add_face( MyMesh::VertexHandle(int(indices[i+0])), MyMesh::VertexHandle(int(indices[i+1])), MyMesh::VertexHandle(int(indices[i+2])) ); } // compute normals mesh.update_face_normals(); mesh.update_vertex_normals(); GLfloat* normals = new GLfloat[_vertices*3]; size_t i = 0; for(const auto& v: mesh.vertices()){ MyMesh::Normal n = mesh.normal(v); for(size_t j = 0; j < 3; ++j, ++i){ normals[i] = n[j]; } } // Tells OpenMesh to release memory mesh.release_vertex_normals(); mesh.release_face_normals(); // COLORS GLfloat* colors = new GLfloat[_vertices*3]; float top = height/2.0f; for(size_t j=0; j < size; ++j){ for(size_t i=0; i < size; ++i){ size_t idx = (j*size)+i; float r, g, b; float pos = positions[(idx*3)+1]; if( pos > (top * 0.80f) ){ float coeff = pos/top; r = 1.0f * coeff; g = 1.0f * coeff; b = 1.0f * coeff; } else if( pos > (top * 0.20f) ){ float coeff = 1.0f - (pos/top); r = 0.4f * (1.0f - coeff); g = 1.0f * coeff; b = 0.4f * coeff; } else if( pos > 0.0f ){ float coeff = 1.0f - (pos/top); r = 1.0f * coeff; g = 1.0f * coeff; b = 0.5f * coeff; } else { float coeff = (pos + top)/top; r = 0.1f * coeff; g = 0.4f * coeff; b = 1.0f * coeff; } colors[(idx*3)+0] = r; colors[(idx*3)+1] = g; colors[(idx*3)+2] = b; } } set_vertices_geometry(program->attributeLocation("position"), positions, indices); set_vertices_colors(program->attributeLocation("color"), colors); set_vertices_normals(program->attributeLocation("normal"), normals); return initialize(_vertices, nb_indices, 3); }
26.264264
86
0.439401
[ "mesh" ]
5f6ad036dc2c4e8badbb675da848d6a445b9fb3e
2,825
cc
C++
sentinel-core/slot/base/default_slot_chain_impl_unittests.cc
windrunner123/sentinel-cpp
7957e692466db0b7b83b7218602757113e9f2d22
[ "Apache-2.0" ]
121
2019-02-22T06:50:31.000Z
2022-01-22T23:23:42.000Z
sentinel-core/slot/base/default_slot_chain_impl_unittests.cc
windrunner123/sentinel-cpp
7957e692466db0b7b83b7218602757113e9f2d22
[ "Apache-2.0" ]
24
2019-05-07T08:58:38.000Z
2022-01-26T02:36:06.000Z
sentinel-core/slot/base/default_slot_chain_impl_unittests.cc
windrunner123/sentinel-cpp
7957e692466db0b7b83b7218602757113e9f2d22
[ "Apache-2.0" ]
36
2019-03-19T09:46:08.000Z
2021-11-24T13:20:56.000Z
#include <memory> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "sentinel-core/common/string_resource_wrapper.h" #include "sentinel-core/common/entry.h" #include "sentinel-core/slot/base/default_slot_chain_impl.h" #include "sentinel-core/test/mock/slot/mock.h" #include "sentinel-core/test/mock/statistic/node/mock.h" using testing::_; using testing::InSequence; using testing::Return; namespace Sentinel { namespace Slot { TEST(DefaultSlotChainImplTest, Basic) { const std::vector<absl::any> myParams; { DefaultSlotChainImpl slot_chain; Stat::NodeSharedPtr node = std::make_shared<Stat::MockNode>(); auto mock_rule_checker_slot = std::make_unique<MockRuleCheckerSlot>(); auto mock_stat_slot = std::make_unique<MockStatsSlot>(); InSequence s; EXPECT_CALL(*mock_rule_checker_slot.get(), Entry(_, _, _, _, _, _)) .WillOnce(Return(TokenResult::Blocked("test"))); EXPECT_CALL(*mock_stat_slot.get(), Entry(_, _, _, _, _, _)).Times(1); slot_chain.AddLast(std::move(mock_rule_checker_slot)); slot_chain.AddLast(std::move(mock_stat_slot)); auto context = std::make_shared<EntryContext>("my_context"); ResourceWrapperSharedPtr test_resource = std::make_shared<StringResourceWrapper>("test_resource", EntryType::IN); auto entry = std::make_shared<Entry>(test_resource, context); slot_chain.Entry(entry, test_resource, node, 1, 1, myParams); } { DefaultSlotChainImpl slot_chain; Stat::NodeSharedPtr node = std::make_shared<Stat::MockNode>(); auto mock_rule_checker_slot1 = std::make_unique<MockRuleCheckerSlot>(); auto mock_rule_checker_slot2 = std::make_unique<MockRuleCheckerSlot>(); auto mock_stat_slot1 = std::make_unique<MockStatsSlot>(); auto mock_stat_slot2 = std::make_unique<MockStatsSlot>(); InSequence s; EXPECT_CALL(*mock_rule_checker_slot1.get(), Entry(_, _, _, _, _, _)) .WillOnce(Return(TokenResult::Blocked("test"))); EXPECT_CALL(*mock_rule_checker_slot2.get(), Entry(_, _, _, _, _, _)) .Times(0); EXPECT_CALL(*mock_stat_slot1.get(), Entry(_, _, _, _, _, _)).Times(1); EXPECT_CALL(*mock_stat_slot2.get(), Entry(_, _, _, _, _, _)).Times(1); slot_chain.AddLast(std::move(mock_rule_checker_slot1)); slot_chain.AddLast(std::move(mock_rule_checker_slot2)); slot_chain.AddLast(std::move(mock_stat_slot1)); slot_chain.AddLast(std::move(mock_stat_slot2)); auto context = std::make_shared<EntryContext>("my_context"); ResourceWrapperSharedPtr test_resource = std::make_shared<StringResourceWrapper>("test_resource", EntryType::IN); auto entry = std::make_shared<Entry>(test_resource, context); slot_chain.Entry(entry, test_resource, node, 1, 1, myParams); } } } // namespace Slot } // namespace Sentinel
37.666667
80
0.718938
[ "vector" ]
5f78031f36522a0534c139e7aac7cbbc45c59386
1,934
cpp
C++
Chapter20-22/Space Invaders ++ 2/InputHandler.cpp
Gerraleslie/Beginning-C-game-programming-learn-to-program-with-C-by-building-fun-games
3bfdc3ce64850c43a1362688d990135ad8a8dee7
[ "MIT" ]
77
2019-12-18T12:34:23.000Z
2022-03-10T08:44:59.000Z
Chapter20-22/Space Invaders ++ 2/InputHandler.cpp
Gerraleslie/Beginning-C-game-programming-learn-to-program-with-C-by-building-fun-games
3bfdc3ce64850c43a1362688d990135ad8a8dee7
[ "MIT" ]
1
2020-10-19T08:12:05.000Z
2020-10-19T09:36:37.000Z
Chapter20-22/Space Invaders ++ 2/InputHandler.cpp
Gerraleslie/Beginning-C-game-programming-learn-to-program-with-C-by-building-fun-games
3bfdc3ce64850c43a1362688d990135ad8a8dee7
[ "MIT" ]
47
2019-11-25T15:18:08.000Z
2022-03-26T21:56:35.000Z
#include <sstream> #include "InputHandler.h" using namespace sf; using namespace std; void InputHandler::initialiseInputHandler( ScreenManagerRemoteControl* sw, vector<shared_ptr<Button>> buttons, View* pointerToUIView, Screen* parentScreen) { m_ScreenManagerRemoteControl = sw; m_Buttons = buttons; m_PointerToUIPanelView = pointerToUIView; m_ParentScreen = parentScreen; } void InputHandler::handleInput(RenderWindow& window, Event& event) { // Handle any key presses if (event.type == Event::KeyPressed) { handleKeyPressed(event, window); } if (event.type == Event::KeyReleased) { handleKeyReleased(event, window); } // Handle any left mouse click released if (event.type == Event::MouseButtonReleased) { auto end = m_Buttons.end(); for (auto i = m_Buttons.begin(); i != end; ++i) { if ((*i)->m_Collider.contains( window.mapPixelToCoords(Mouse::getPosition(), (*getPointerToUIView())))) { // Capture the text of the button that was interacted // with and pass it to the specialised version // of this class if implemented handleLeftClick((*i)->m_Text, window); break; } } } handleGamepad(); } void InputHandler::handleGamepad() {}// Do nothing unless handled by a derived class void InputHandler::handleKeyPressed(Event& event, RenderWindow& window) {}// Do nothing unless handled by a derived class void InputHandler::handleKeyReleased(Event& event, RenderWindow& window) {}// Do nothing unless handled by a derived class void InputHandler::handleLeftClick(std:: string& buttonInteractedWith, RenderWindow& window) {}// Do nothing unless handled by a derived class View* InputHandler::getPointerToUIView() { return m_PointerToUIPanelView; } ScreenManagerRemoteControl* InputHandler::getPointerToScreenManagerRemoteControl() { return m_ScreenManagerRemoteControl; } Screen* InputHandler::getmParentScreen() { return m_ParentScreen; }
22.229885
58
0.738883
[ "vector" ]
5f7aeb8541a46419498949eae6b0946b2bd73081
6,939
hpp
C++
include/grid.hpp
gerzin/parallel-cellular-automata
dcaf220fa89e8348486aa17d46a864d6ee64e46d
[ "MIT" ]
null
null
null
include/grid.hpp
gerzin/parallel-cellular-automata
dcaf220fa89e8348486aa17d46a864d6ee64e46d
[ "MIT" ]
null
null
null
include/grid.hpp
gerzin/parallel-cellular-automata
dcaf220fa89e8348486aa17d46a864d6ee64e46d
[ "MIT" ]
null
null
null
/** * @file grid.hpp * @author Gerardo Zinno (g.zinno@studenti.unipi.it) * @brief Definition of the grid of the automaton. * @version 0.1 * @date 2022-01-07 * * @copyright Copyright (c) 2022 * */ #ifndef PARALLEL_CELLULAR_AUTOMATA_GRID_HPP #define PARALLEL_CELLULAR_AUTOMATA_GRID_HPP #include <exception> #include <fstream> #include <iostream> #include <memory> #include <string> #include <vector> namespace ca { /** * @brief Grid of the cellular automaton. * * @tparam T type of the cell. */ template <typename T> class Grid { public: /** * @brief Construct a new Grid object. * * @param rows number of rows of the grid. * @param cols number of columns of the grid. * @throws invalid_argument if either rows or cols are zero. */ Grid(size_t rows, size_t cols) : grid(rows * cols), nrows(rows), ncols(cols) { if (!grid.size()) { throw std::invalid_argument("Grid constructor has 0 size."); } } /** * @brief Construct a new Grid object. * * @param grid_ vector containing the elements of the grid. * @param rows number of rows of the grid. * @note the number of columns will be calculated as grid_.size() / rows. * @pre rows >= 1 && rows * @pre rows divides grid_.size() */ Grid(std::vector<T> grid_, size_t rows) : grid(grid_), nrows(rows), ncols(grid.size() / rows) { if (!rows) { throw std::invalid_argument("Grid cannot have 0 rows."); } } /** * @brief Construct a new Grid object. * * @param other grid to copy. */ Grid(const Grid &other) { nrows = other.nrows; ncols = other.ncols; grid = other.grid; } /** * @brief Construct a new Grid object. * * @param other grid to copy. */ Grid(Grid &&other) { nrows = other.nrows; ncols = other.ncols; grid = std::move(other.grid); } /** * @brief Return a grid of the same dimension of the grid passed as argument. * * @param other Grid whose dimension has to be taken. * @return Grid new grid of same dimension. */ static Grid newWithSameSize(const Grid &other) { return Grid(other.nrows, other.ncols); } /** * @brief Load a grid from a file. * * The file must contain the number of rows, the number of columns and then the elements of the grid. * * @param filepath path to the file. * @return Grid grid initialized with the content of the file. */ static Grid newFromFile(std::string filepath) { std::ifstream f(filepath); if (f) { unsigned rows, columns; f >> rows; f >> columns; std::vector<T> v; v.reserve(rows * columns); T value; while (f >> value) { v.push_back(value); } for (auto e : v) { std::cout << e << " "; } return Grid(std::move(v), rows, columns); } else { throw std::invalid_argument("Invalid filepath"); } } /** * @brief Writes the grid to a file. * * @param filepath path of the file. */ void toFile(std::string filepath) { std::ofstream file(filepath); if (file) { file << nrows << " " << ncols << std::endl; for (const auto elem : grid) { file << elem << " "; } } else { throw std::invalid_argument("Invalid filepath"); } } /** * @brief Get the element in position row,col. * * @param row row number. * @param col column number. * @pre 0 <= rows < this->nrows * @pre 0 <= col < this->ncols * @return T& reference to the element in position row,col */ T &operator()(unsigned row, unsigned col) { return grid[ncols * row + col]; } /** * @brief Get the element in position row,col. * * @param row row number. * @param col column number. * @pre 0 <= rows < this->nrows * @pre 0 <= col < this->ncols * @return T& reference to the element in position row,col */ T operator()(unsigned row, unsigned col) const { return grid[ncols * row + col]; } /** * @brief Returns the number of rows of the grid. * * @return size_t number of rows. */ inline size_t rows() const { return this->nrows; } /** * @brief Returns the number of columns of the grid. * * @return size_t number of columns. */ inline size_t columns() const { return this->ncols; } /** * @brief Prints the grid on the stream, with the elements in a row separated by a whitespace and the rows separated * by a newline. * * @param os output stream on which to print. * @param grid grid to print. * @return std::ostream& */ friend std::ostream &operator<<(std::ostream &os, const Grid &grid) { for (size_t i = 0; i < grid.nrows; ++i) { for (size_t j = 0; j < grid.ncols; ++j) { os << grid(i, j) << " "; } os << std::endl; } return os; } /** * @brief Compare two grids for equality. * * @return true if the grids are equal. * @return false if the grids differ. */ friend bool operator==(const Grid &lhs, const Grid &rhs) { return (lhs.nrows == rhs.nrows) && (lhs.ncols == rhs.ncols) && std::equal(lhs.grid.begin(), lhs.grid.end(), rhs.grid.begin()); } /** * @brief Swap the content of the grid with the one of another grid. * * @param other grid to swap. */ void swap(Grid &other) { using std::swap; swap(nrows, other.nrows); swap(ncols, other.ncols); grid.swap(other.grid); } /** * @brief Get a reference to the vector representing the grid. * * @return std::vector<T>& vector representing the grid. */ std::vector<T> &getInnerVector() { return grid; } private: Grid(std::vector<T> &&v, size_t rows, size_t cols) : grid(std::move(v)), nrows(rows), ncols(cols) { if (!(getInnerVector().size() && rows && cols)) { throw std::invalid_argument("Empty vector or invalid dimension"); } } /** * @brief The grid is represented as a 1D vector. * */ std::vector<T> grid; /** * @brief Number of rows of the grid. * */ size_t nrows; /** * @brief Number of columns of the grid. * */ size_t ncols; }; } // namespace ca #endif
24.09375
120
0.527454
[ "object", "vector" ]
5f7c425e1dd9ed76ef7898f65556a9199c019bc0
11,708
hpp
C++
src/vector.hpp
pip010/talg
58212bb0a216f54987448f7fa0622f46a3e9b61e
[ "MIT" ]
1
2016-03-18T09:54:31.000Z
2016-03-18T09:54:31.000Z
src/vector.hpp
pip010/talg
58212bb0a216f54987448f7fa0622f46a3e9b61e
[ "MIT" ]
null
null
null
src/vector.hpp
pip010/talg
58212bb0a216f54987448f7fa0622f46a3e9b61e
[ "MIT" ]
null
null
null
#pragma once #include <initializer_list> #include <array> #include <iostream> #include <cassert> #include <cmath> #include <limits> namespace talg { /* Decoration for templated vectors */ class vtag {}; class vtag_xy {}; class vtag_xyz {}; class vtag_xyzw {}; class vtag_ij {}; class vtag_ijk {}; class vtag_rgb {}; class vtag_rgba {}; class vtag_adsp {}; namespace details { template<int N, typename T, typename Tcat> struct TVdata { //std::array<T, N> data; T data[N]; TVdata() = default; //TVdata(const T&) = default; //TVdata(T&&) = default; //T& operator=(const T&) = default; //T& operator=(T&&) = default; TVdata(const std::initializer_list<T>&& il) { std::copy(il.begin(), il.end(), data); } // //template <typename T, typename... Types> //TVdata(T t, Types... ts) : data{ { t, ts... } } //{} // //template<typename ...T> //TVdata(T&&...t):data{ std::forward<T>(t)... } //{ //} //template <class U, class... Ts> //X(U n, Ts... rest) : X(rest...) { ..the recursive work .. } }; template<typename T> struct TVdata<2, T, vtag_ij> { union { struct { T i; T j; }; //std::array<T, 3> data; T data[2]; }; TVdata() = default; TVdata(T t1, T t2) : i(t1), j(t2) {} }; template<typename T> struct TVdata<3, T, vtag_ijk> { union { struct { T i; T j; T k; }; //std::array<T, 3> data; T data[3]; }; TVdata() = default; TVdata(T t1, T t2, T t3) : i(t1), j(t2), k(t3) {} }; template<typename T> struct TVdata<2, T, vtag_xy> { union { struct { T x; T y; }; //std::array<T, 3> data; T data[2]; }; TVdata() = default; TVdata(T t1, T t2) : x(t1), y(t2) {} }; template<typename T> struct TVdata<3, T, vtag_xyz> { union { struct { T x; T y; T z; }; //std::array<T, 3> data; T data[3]; }; TVdata() = default; TVdata(T t1, T t2, T t3) : x(t1), y(t2), z(t3) {} }; template<typename T> struct TVdata<4, T, vtag_xyzw> { union { struct { T x; T y; T z; T w; }; //std::array<T, 4> data; T data[4]; }; TVdata() = default; TVdata(T t1, T t2, T t3, T t4) : x(t1), y(t2), z(t3), w(t4) { } }; template<typename T> struct TVdata<3, T, vtag_rgb> { union { struct { T r; T g; T b; }; //std::array<T, 3> data; T data[3]; }; TVdata() = default; TVdata(T t1, T t2, T t3) : r(t1), g(t2), b(t3) {} }; template<typename T> struct TVdata<4, T, vtag_rgba> { union { struct { T r; T g; T b; T a; }; //std::array<T, 4> data; T data[4]; }; TVdata() = default; TVdata(T t1, T t2, T t3, T t4) : r(t1), g(t2), b(t3), a(t4) { } }; template<typename T> struct TVdata<4, T, vtag_adsp> { union { struct { T a; T d; T s; T p; }; //std::array<T, 4> data; T data[4]; }; TVdata() = default; TVdata(T t1, T t2, T t3, T t4) : a(t1), d(t2), s(t3), p(t4) { } }; } template<int N, typename T, typename Tcat = vtag> struct TVector : public details::TVdata<N, T, Tcat> { typedef Tcat tag_type; typedef T value_type; typedef size_t size_type; //typedef ptrdiff_t difference_type; typedef T* pointer; using ptr = pointer; typedef const T* const_pointer; using cptr = const_pointer; typedef T& reference; using ref = reference; typedef const T& const_reference; using cref = const_reference; TVector() = default; //forward brace initializer using details::TVdata<N, T, Tcat>::TVdata; using details::TVdata<N, T, Tcat>::data; //TODO most likely drop it, no colapse to pointer, use inner data member //http://en.cppreference.com/w/cpp/language/cast_operator //operator const T*() const //{ // return data.data(); //} //operator T*() //{ // return data.data(); //} T& operator[](size_t index) { //out of range check DEBUG assert(index < N && "INDEX OUT OF RANGE"); return data[index]; } const T& operator[](size_t index) const { //out of range check DEBUG assert(index < N && "INDEX OUT OF RANGE"); return data[index]; } T& operator()(size_t index) { //out of range check DEBUG assert(index < N && "INDEX OUT OF RANGE"); return data[index]; } const T& operator()(size_t index) const { //out of range check DEBUG assert(index < N && "INDEX OUT OF RANGE"); return data[index]; } T& at(size_t index) { assert(index < N && "INDEX OUT OF RANGE"); if (index < N) throw std::out_of_range(); return data[index]; } const T& at(size_t index) const { assert(index < N && "INDEX OUT OF RANGE"); if (index < N) throw std::out_of_range(); return data[index]; } constexpr size_t size() const { return N; } cptr begin() const { return data; } cptr end() const { return data+N; } ptr begin() { return data; } ptr end() { return data+N; } }; //SFINAE //http://eli.thegreenplace.net/2014/sfinae-and-enable_if/ //http://en.cppreference.com/w/cpp/types/enable_if //forbiden for real numbers //inline bool operator==(const X& lhs, const X& rhs){ /* do actual comparison */ } //inline bool operator!=(const X& lhs, const X& rhs){ return !(lhs == rhs); } template<int N, typename T, typename Tcat> bool operator==(const TVector<N, T, Tcat>& lhs, const typename std::enable_if<std::is_integral<T>::value, TVector<N, T, Tcat> >::type& rhs) { for (size_t i = 0; i < N; ++i) { if (lhs[i] != rhs[i]) return false; } return true; } template<int N, typename T, typename Tcat> bool operator!=(const TVector<N, T, Tcat>& lhs, const TVector<N, T, Tcat>& rhs) { return !(lhs == rhs); } //TODO does this makes sense? (component wise comparison) /* inline bool operator< (const TVector& lhs, const TVector& rhs) { for (size_t i = 0; i < N; i++) { if (lhs[i] > rhs[i]) return false; } return true; } inline bool operator> (const TVector& lhs, const TVector& rhs) { return rhs < lhs; } inline bool operator<=(const TVector& lhs, const TVector& rhs) { return !(lhs > rhs); } inline bool operator>=(const TVector& lhs, const TVector& rhs) { return !(lhs < rhs); } */ template<int N, typename T, typename Tcat> inline bool operator< (const TVector<N, T, Tcat>& lhs, const T& rhs) { return magnitude(lhs) < rhs; } template<int N, typename T, typename Tcat> bool operator> (const TVector<N, T, Tcat>& lhs, const T& rhs) { return rhs < lhs; } template<int N, typename T, typename Tcat> bool operator<=(const TVector<N, T, Tcat>& lhs, const T& rhs) { return !(lhs > rhs); } template<int N, typename T, typename Tcat> bool operator>=(const TVector<N, T, Tcat>& lhs, const T& rhs) { return !(lhs < rhs); } template<int N, typename T, typename Tcat> TVector<N, T, Tcat>& operator += (TVector<N, T, Tcat>& lhs, const TVector<N, T, Tcat> &rhs) { for (int i = 0; i < N; ++i) { lhs[i] = lhs[i] + rhs[i]; } return lhs; } template<int N, typename T, typename Tcat> TVector<N, T, Tcat> operator + (TVector<N, T, Tcat> lhs, const TVector<N, T, Tcat> &rhs) { lhs += rhs; return lhs; } template<int N, typename T, typename Tcat> TVector<N, T, Tcat>& operator += (TVector<N, T, Tcat>& lhs, const T& rhs) { for (int i = 0; i < N; ++i) { lhs[i] = lhs[i] + rhs; } return lhs; } template<int N, typename T, typename Tcat> TVector<N, T, Tcat> operator + (TVector<N, T, Tcat> lhs, const T& rhs) { lhs += rhs; return lhs; } template<int N, typename T, typename Tcat> TVector<N, T, Tcat>& operator -= (TVector<N, T, Tcat>& lhs, const TVector<N, T, Tcat> &rhs) { for (int i = 0; i < N; ++i) { lhs[i] = lhs[i] - rhs[i]; } return lhs; } template<int N, typename T, typename Tcat> TVector<N, T, Tcat> operator - (TVector<N, T, Tcat> lhs, const TVector<N, T, Tcat> &rhs) { lhs -= rhs; return lhs; } template<int N, typename T, typename Tcat> TVector<N, T, Tcat>& operator -= (TVector<N, T, Tcat>& lhs, const T& rhs) { for (int i = 0; i < N; ++i) { lhs[i] = lhs[i] - rhs; } return lhs; } template<int N, typename T, typename Tcat> TVector<N, T, Tcat> operator - (TVector<N, T, Tcat> lhs, const T& rhs) { lhs -= rhs; return lhs; } template<int N, typename T, typename Tcat> TVector<N, T, Tcat>& operator *= (TVector<N, T, Tcat>& lhs, const T& rhs) { for (size_t i = 0; i < N; ++i) { lhs[i] = lhs[i] * rhs; } return lhs; } template<int N, typename T, typename Tcat> TVector<N, T, Tcat> operator * (TVector<N, T, Tcat> lhs, const T& rhs) { lhs *= rhs; return lhs; } template<int N, typename T, typename Tcat> TVector<N, T, Tcat>& operator /= (TVector<N, T, Tcat>& lhs, const T& rhs) { assert(rhs!=0 && "DIV BY 0"); for (size_t i = 0; i < N; ++i) { lhs[i] = lhs[i] / rhs; } return lhs; } template<int N, typename T, typename Tcat> TVector<N, T, Tcat> operator / (TVector<N, T, Tcat> lhs, const T& rhs) { lhs /= rhs; return lhs; } template<int N, typename T, typename Tcat> T dot(const TVector<N, T, Tcat>& lhs, const TVector<N, T, Tcat>& rhs) { T ret{}; for (int i = 0; i < N; ++i) { ret += (lhs.data[i] * rhs.data[i]); } return ret; } template<typename T, typename Tcat> TVector<3, T, Tcat> cross(const TVector<3, T, Tcat>& lhs, const TVector<3, T, Tcat>& rhs) { //return{ lhs.y*other.z - z*other.y, z*other.x - x*other.z, x*other.y - y*other.x, 1.0 }; return{ lhs[1]*rhs[2] - lhs[2]*rhs[1], lhs[2]*rhs[0] - lhs[0]*rhs[2], lhs[0]*rhs[1] - lhs[1]*rhs[0] }; } //This is not really a 4D vector cross ( it assumes 4D as homogenious x,y,z,w) //http://math.stackexchange.com/questions/720813/do-four-dimensional-vectors-have-a-cross-product-property //http://math.stackexchange.com/questions/185991/is-the-vector-cross-product-only-defined-for-3d template<typename T, typename Tcat> TVector<4, T, Tcat> cross(const TVector<4, T, Tcat>& lhs, const TVector<4, T, Tcat>& rhs) { //return{ lhs.y*other.z - z*other.y, z*other.x - x*other.z, x*other.y - y*other.x, 1.0 }; return { lhs[1] * rhs[2] - lhs[2] * rhs[1], lhs[2] * rhs[0] - lhs[0] * rhs[2], lhs[0] * rhs[1] - lhs[1] * rhs[0], 1.0 }; } template<int N, typename T, typename Tcat> T magnitude(const TVector<N, T, Tcat>& vec) { return sqrt(dot(vec, vec)); } template<int N, typename T, typename Tcat> T norm(const TVector<N, T, Tcat>& vec) { return magnitude(vec); } // implicit type deduction fails with alias !? //template<int N, typename T, typename Tcat> //T norm = magnitude; template<int N, typename T, typename Tcat> void normalize(TVector<N, T, Tcat>& vec) { T mag = magnitude(vec); assert(mag != 0.0); T fac = 1.0 / mag; vec *= fac; } template<int N, typename T, typename Tcat> TVector<N, T, Tcat> normal(TVector<N, T, Tcat> vec) { normalize(vec); return vec; } template<int N, typename Tcat> bool eq(const TVector<N, double, Tcat>& lhs, const TVector<N, double, Tcat>& rhs, double epsilon = (std::numeric_limits<double>::epsilon()*100) ) { for (size_t i = 0; i < lhs.size(); ++i) { if (abs(lhs[i] - rhs[i]) > epsilon) return false; } return true; } //namespace io //{ template<int N, typename T, typename Tcat> std::ostream& operator << (std::ostream &os, const TVector<N, T, Tcat> &v) { for (auto a : v.data) os << a << " "; return os; } template<int N, typename T, typename Tcat> std::istream& operator>>(std::istream& is, const TVector<N,T,Tcat>& v) { for (auto a : v.data) is >> a; return is; } //} }
19.644295
146
0.581397
[ "vector", "3d" ]
5f7db5295bb87646183ba76ba1c690266cb3bf9d
3,978
cc
C++
smc/src/model/DescribeReplicationJobsRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
smc/src/model/DescribeReplicationJobsRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
smc/src/model/DescribeReplicationJobsRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/smc/model/DescribeReplicationJobsRequest.h> using AlibabaCloud::Smc::Model::DescribeReplicationJobsRequest; DescribeReplicationJobsRequest::DescribeReplicationJobsRequest() : RpcServiceRequest("smc", "2019-06-01", "DescribeReplicationJobs") { setMethod(HttpRequest::Method::Post); } DescribeReplicationJobsRequest::~DescribeReplicationJobsRequest() {} int DescribeReplicationJobsRequest::getPageNumber()const { return pageNumber_; } void DescribeReplicationJobsRequest::setPageNumber(int pageNumber) { pageNumber_ = pageNumber; setParameter("PageNumber", std::to_string(pageNumber)); } std::string DescribeReplicationJobsRequest::getAccessKeyId()const { return accessKeyId_; } void DescribeReplicationJobsRequest::setAccessKeyId(const std::string& accessKeyId) { accessKeyId_ = accessKeyId; setParameter("AccessKeyId", accessKeyId); } std::vector<std::string> DescribeReplicationJobsRequest::getJobId()const { return jobId_; } void DescribeReplicationJobsRequest::setJobId(const std::vector<std::string>& jobId) { jobId_ = jobId; for(int dep1 = 0; dep1!= jobId.size(); dep1++) { setParameter("JobId."+ std::to_string(dep1), jobId.at(dep1)); } } std::string DescribeReplicationJobsRequest::getRegionId()const { return regionId_; } void DescribeReplicationJobsRequest::setRegionId(const std::string& regionId) { regionId_ = regionId; setParameter("RegionId", regionId); } int DescribeReplicationJobsRequest::getPageSize()const { return pageSize_; } void DescribeReplicationJobsRequest::setPageSize(int pageSize) { pageSize_ = pageSize; setParameter("PageSize", std::to_string(pageSize)); } std::vector<std::string> DescribeReplicationJobsRequest::getSourceId()const { return sourceId_; } void DescribeReplicationJobsRequest::setSourceId(const std::vector<std::string>& sourceId) { sourceId_ = sourceId; for(int dep1 = 0; dep1!= sourceId.size(); dep1++) { setParameter("SourceId."+ std::to_string(dep1), sourceId.at(dep1)); } } std::string DescribeReplicationJobsRequest::getBusinessStatus()const { return businessStatus_; } void DescribeReplicationJobsRequest::setBusinessStatus(const std::string& businessStatus) { businessStatus_ = businessStatus; setParameter("BusinessStatus", businessStatus); } std::string DescribeReplicationJobsRequest::getResourceOwnerAccount()const { return resourceOwnerAccount_; } void DescribeReplicationJobsRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount) { resourceOwnerAccount_ = resourceOwnerAccount; setParameter("ResourceOwnerAccount", resourceOwnerAccount); } long DescribeReplicationJobsRequest::getOwnerId()const { return ownerId_; } void DescribeReplicationJobsRequest::setOwnerId(long ownerId) { ownerId_ = ownerId; setParameter("OwnerId", std::to_string(ownerId)); } std::string DescribeReplicationJobsRequest::getName()const { return name_; } void DescribeReplicationJobsRequest::setName(const std::string& name) { name_ = name; setParameter("Name", name); } std::string DescribeReplicationJobsRequest::getStatus()const { return status_; } void DescribeReplicationJobsRequest::setStatus(const std::string& status) { status_ = status; setParameter("Status", status); }
25.664516
102
0.756159
[ "vector", "model" ]
5f88b9ed1b373e64eb4082b5306f37c0ce890a7d
2,283
hpp
C++
include/ros2_daemon_client_cpp/Ros2DaemonClient.hpp
bponsler/ros2_daemon_client_cpp
abd2da1fb26c137076aa907162a3850d621712c5
[ "Apache-2.0" ]
null
null
null
include/ros2_daemon_client_cpp/Ros2DaemonClient.hpp
bponsler/ros2_daemon_client_cpp
abd2da1fb26c137076aa907162a3850d621712c5
[ "Apache-2.0" ]
null
null
null
include/ros2_daemon_client_cpp/Ros2DaemonClient.hpp
bponsler/ros2_daemon_client_cpp
abd2da1fb26c137076aa907162a3850d621712c5
[ "Apache-2.0" ]
null
null
null
#ifndef ROS2_DAEMON_CLIENT_CPP__ROS2DAEMONCLIENT_HPP_ #define ROS2_DAEMON_CLIENT_CPP__ROS2DAEMONCLIENT_HPP_ // standard headers #include <string> #include <vector> // xml rpc headers #include <xmlrpcpp/XmlRpcClient.h> // rclcpp headers #include <rclcpp/node.hpp> namespace ros2_daemon_client_cpp { /** * \brief The TopicData structure * * This struct contains data pertaining to a single ROS 2 topic. */ struct TopicData { /** The topic. */ std::string topic; /** The type of data published on this topic. */ std::string type; }; // various types typedef std::vector<std::string> StringVector; typedef std::vector<TopicData> TopicDataVector; /** * \brief The Ros2DaemonClient class * * The Ros2DaemonClient class implements a basic XML-RPC client * for the ROS 2 daemon. */ class Ros2DaemonClient { public: /** * \brief Constructor * * Create a Ros2DaemonClient object. * * \param[in] host is the hostname for the ROS 2 daemon * \param[in] port is the port for the ROS 2 daemon * \param[in] rmwImplId is the RMW implementation identifier */ Ros2DaemonClient( const std::string& host="localhost", const int& port=11511, const std::string& rmwImplId=rmw_get_implementation_identifier()); /** * \brief Deconstructor * * Destroy the Ros2DaemonClient object. */ virtual ~Ros2DaemonClient(); /** * \brief Determine if the daemon client is connected * * Determine if the daemon client is connected. * * \return true if connected, false otherwise */ bool isConnected() const; /** * \brief Get the list of running nodes * * Get the list of running nodes. * * \return the list of running nodes */ StringVector getNodes(); /** * \brief Get topic names and types * * Get ROS 2 topic names and types. * * \return the list of topic data */ TopicDataVector getTopics(); /** * \brief Get service names and types * * Get ROS 2 service names and types. * * \return the list of service data */ TopicDataVector getServices(); protected: /** XML RPC client to the ROS 2 daemon. */ XmlRpc::XmlRpcClient m_client; }; } // namespace ros2_daemon_client_cpp #endif // ROS2_DAEMON_CLIENT_CPP__ROS2DAEMONCLIENT_HPP_
19.681034
70
0.683749
[ "object", "vector" ]
5f93d84c2ebb5b3b115d84dd238218a37dd10abf
5,561
cpp
C++
SubdivisionAlgorithms/Liepa.cpp
Pseudomanifold/psalm
b9c3bc83950efb6efab8bb4775bf0421bee474d3
[ "BSD-2-Clause" ]
7
2019-07-21T14:53:01.000Z
2021-08-18T09:12:54.000Z
SubdivisionAlgorithms/Liepa.cpp
Pseudomanifold/psalm
b9c3bc83950efb6efab8bb4775bf0421bee474d3
[ "BSD-2-Clause" ]
null
null
null
SubdivisionAlgorithms/Liepa.cpp
Pseudomanifold/psalm
b9c3bc83950efb6efab8bb4775bf0421bee474d3
[ "BSD-2-Clause" ]
2
2020-03-08T01:25:20.000Z
2021-06-29T17:37:29.000Z
/*! * @file Liepa.cpp * @brief Implementation of Liepa's subdivision scheme */ #include <cmath> #include "Liepa.h" namespace psalm { /*! * Sets default values for Liepa subdivision. */ Liepa::Liepa() { alpha = sqrt(2); } /*! * Sets current value of density parameter for the algorithm. * * @param alpha New value for density parameter */ void Liepa::set_alpha(double alpha) { this->alpha = alpha; } /*! * @returns Current value of density parameter for the algorithm. */ double Liepa::get_alpha() { return(alpha); } /*! * Applies Liepa's subdivision scheme to the given mesh. The mesh will be * irreversibly _changed_ by this function. * * @param input_mesh Mesh on which the algorithm is applied * @return true on success, else false */ bool Liepa::apply_to(mesh& input_mesh) { /* Compute scale attribute as the average length of the edges adjacent to a vertex. ASSUMPTION: Mesh consists of a single triangulated hole, i.e. _all_ vertices are boundary vertices. */ for(size_t i = 0; i < input_mesh.num_vertices(); i++) { vertex* v = input_mesh.get_vertex(i); size_t n = v->valency(); double attribute = 0.0; bool found_first_boundary_edge = false; // in the triangulated mesh, there are // only two boundary edges per vertex; // if we have found those two, the search // may be stopped. for(size_t i = 0; i < n; i++) { edge* e = v->get_edge(i); if(e->is_on_boundary()) { attribute += 0.5*e->calc_length(); // break if we have already seen a boundary // edge -- see discussion above if(found_first_boundary_edge) break; else found_first_boundary_edge = true; } } // If the scale attributes have already been seeded, their // average is taken to be the new scale attribute... double old_attribute = v->get_scale_attribute(); if(old_attribute != 0.0) v->set_scale_attribute(0.5*(old_attribute + attribute)); else v->set_scale_attribute(attribute); } bool created_new_triangle; do { // if no new triangle has been created, the algorithm // terminates created_new_triangle = false; // Need to store the number of faces here because new faces // might be created within the for-loop below. These must _not_ // be considered in the same iteration. size_t num_faces = input_mesh.num_faces(); // Compute scale attribute for each face of the mesh for(size_t i = 0; i < num_faces; i++) { face* f = input_mesh.get_face(i); if(f->num_edges() != 3) { std::cerr << "psalm: Input mesh contains non-triangular face. Liepa's subdivision scheme is not applicable.\n"; return(false); } vertex* vertices[3]; vertices[0] = f->get_vertex(0); vertices[1] = f->get_vertex(1); vertices[2] = f->get_vertex(2); // Compute centroid and scale attribute. If the scale // attribute test fails, replace the triangle. v3ctor centroid_pos; double centroid_scale_attribute = 0.0; for(size_t j = 0; j < 3; j++) { centroid_pos += vertices[j]->get_position()/3.0; centroid_scale_attribute += vertices[j]->get_scale_attribute()/3.0; } size_t tests_failed = 0; for(size_t j = 0; j < 3; j++) { double scaled_distance = alpha*(centroid_pos - vertices[j]->get_position()).length(); if( scaled_distance > centroid_scale_attribute && scaled_distance > vertices[j]->get_scale_attribute()) { // We will replace the triangle only if // _all_ three tests failed tests_failed++; } } // Replace old triangle with three smaller triangles if(tests_failed == 3) { created_new_triangle = true; vertex* centroid_vertex = input_mesh.add_vertex(centroid_pos); centroid_vertex->set_scale_attribute(centroid_scale_attribute); // Remove old face and replace it by three new // faces. Calling remove_face() will ensure // that the edges are updated correctly. input_mesh.remove_face(f); delete f; face* new_face1 = input_mesh.add_face(vertices[0], vertices[1], centroid_vertex, true); face* new_face2 = input_mesh.add_face(centroid_vertex, vertices[1], vertices[2], true); face* new_face3 = input_mesh.add_face(vertices[0], centroid_vertex, vertices[2], true); if(!new_face1 || !new_face2 || !new_face3) { std::cerr << "psalm: Error: Liepa::apply_to(): Unable to add new face\n"; return(false); } num_faces--; i--; // Relax edges afterwards to maintain // Delaunay-like mesh input_mesh.relax_edge(new_face1->get_edge(0).e); input_mesh.relax_edge(new_face2->get_edge(1).e); input_mesh.relax_edge(new_face3->get_edge(2).e); } } if(!created_new_triangle) return(true); // Relax interior edges bool relaxed_edge; do { relaxed_edge = false; for(size_t i = 0; i < input_mesh.num_edges(); i++) { if(input_mesh.relax_edge(input_mesh.get_edge(i))) relaxed_edge = true; } } while(relaxed_edge); /* XXX: This might lead to wrong results... // Calculate new scaling attributes. TODO: This should become a // function. for(size_t i = 0; i < input_mesh.num_vertices(); i++) { vertex* v = input_mesh.get_vertex(i); size_t n = v->valency(); if(!v->is_on_boundary()) continue; double attribute = 0.0; for(size_t i = 0; i < n; i++) attribute += v->get_edge(i)->calc_length()/static_cast<double>(n); v->set_scale_attribute(attribute); } */ if(!relaxed_edge) continue; } while(created_new_triangle); return(true); } } // end of namespace "psalm"
24.283843
115
0.666607
[ "mesh" ]
5f96aca36f255c19b36f52e2c6678980c3707234
14,761
cpp
C++
src/mfx/pi/flancho/FlanchoChn.cpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
69
2017-01-17T13:17:31.000Z
2022-03-01T14:56:32.000Z
src/mfx/pi/flancho/FlanchoChn.cpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
1
2020-11-03T14:52:45.000Z
2020-12-01T20:31:15.000Z
src/mfx/pi/flancho/FlanchoChn.cpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
8
2017-02-08T13:30:42.000Z
2021-12-09T08:43:09.000Z
/***************************************************************************** FlanchoChn.cpp Author: Laurent de Soras, 2016 --- Legal stuff --- This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://sam.zoy.org/wtfpl/COPYING for more details. *Tab=3***********************************************************************/ #if defined (_MSC_VER) #pragma warning (1 : 4130 4223 4705 4706) #pragma warning (4 : 4355 4786 4800) #endif /*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ #include "mfx/dsp/iir/TransSZBilin.h" #include "mfx/dsp/mix/Generic.h" #include "mfx/dsp/rspl/InterpolatorInterface.h" #include "mfx/pi/flancho/FlanchoChn.h" #include <algorithm> #include <cassert> #include <cmath> namespace mfx { namespace pi { namespace flancho { /*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ FlanchoChn::FlanchoChn (dsp::rspl::InterpolatorInterface &interp, float dly_buf_ptr [], int dly_buf_len, float render_buf_ptr [], int render_buf_len) : _dly_line () , _voice_arr () , _sample_freq (44100) , _rel_phase (0) , _tmp_buf_arr () , _nbr_voices (1) , _voice_vol (1) , _period (1) , _delay (Cst::_delay_max * 0.5e-6) , _depth (0.5) , _feedback (0) , _wf_shape (0) , _wf_type (WfType_SINE) , _neg_flag (false) , _max_proc_len (0) , _mpl_lfo (0) , _feedback_old (0) , _sat_in_a (1) , _sat_in_b (0) , _sat_out_a (1) , _sat_out_b (0) { assert (dly_buf_ptr != nullptr); assert (dly_buf_len > 0); assert (render_buf_ptr != nullptr); assert (render_buf_len > 0); dsp::mix::Generic::setup (); _tmp_buf_arr [TmpBufType_DLY_READ]._ptr = dly_buf_ptr; _tmp_buf_arr [TmpBufType_DLY_READ]._len = dly_buf_len; _tmp_buf_arr [TmpBufType_RENDER ]._ptr = render_buf_ptr; _tmp_buf_arr [TmpBufType_RENDER ]._len = render_buf_len; _dly_line.set_sample_freq (_sample_freq, 0); _dly_line.set_interpolator (interp); _dly_line.set_max_delay_time (Cst::_delay_max * 2e-6); for (int v_cnt = 0; v_cnt < Cst::_max_nbr_voices; ++v_cnt) { Voice & voice = _voice_arr [v_cnt]; voice._dly_reader.set_delay_line (_dly_line); voice._dly_reader.set_tmp_buf ( _tmp_buf_arr [TmpBufType_DLY_READ]._ptr, _tmp_buf_arr [TmpBufType_DLY_READ]._len ); voice._dly_reader.set_crossfade (256, nullptr); voice._dly_reader.set_resampling_range (-4.0, +4.0); voice._rel_phase = 2 * pow (5.0 / 7.0, v_cnt); voice._lfo.set_type (dsp::ctrl::lfo::LfoModule::Type_SINE); } update_shape (); } void FlanchoChn::set_sample_freq (double sample_freq, bool fast_flag, dsp::rspl::InterpolatorInterface &interp) { _sample_freq = sample_freq; _dly_line.set_sample_freq (_sample_freq, 0); _dly_line.set_interpolator (interp); const float hpf_freq = 80; // HPF cutoff static const float b_s [2] = { 0, 1 }; static const float a_s [2] = { 1, 1 }; float b_z [2]; float a_z [2]; if (fast_flag) { const float k = dsp::iir::TransSZBilin::compute_k_approx ( hpf_freq / float (_sample_freq) ); dsp::iir::TransSZBilin::map_s_to_z_one_pole_approx ( b_z, a_z, b_s, a_s, k ); } else { dsp::iir::TransSZBilin::map_s_to_z_one_pole ( b_z, a_z, b_s, a_s, hpf_freq, _sample_freq ); } for (int v_cnt = 0; v_cnt < Cst::_max_nbr_voices; ++v_cnt) { Voice & voice = _voice_arr [v_cnt]; voice._lfo.set_sample_freq (_sample_freq); voice._hpf.set_z_eq (b_z, a_z); voice._hpf.clear_buffers (); } update_max_proc_len (); update_mpl_lfo (); for (auto &voice : _voice_arr) { voice._dly_reader.clip_times (); } } void FlanchoChn::set_rel_phase (double rel_phase) { assert (rel_phase >= 0); assert (rel_phase < 1); const double dif = rel_phase - _rel_phase; _rel_phase = rel_phase; for (int v_cnt = 0; v_cnt < Cst::_max_nbr_voices; ++v_cnt) { Voice & voice = _voice_arr [v_cnt]; double phase = voice._lfo.get_phase (); phase += dif; phase -= floor (phase); voice._lfo.set_phase (phase); } } void FlanchoChn::set_nbr_voices (int nbr_voices) { assert (nbr_voices > 0); assert (nbr_voices <= Cst::_max_nbr_voices); if (_nbr_voices < nbr_voices) { const double base_phase = estimate_base_phase (); for (int v_cnt = _nbr_voices; v_cnt < nbr_voices; ++v_cnt) { Voice & voice = _voice_arr [v_cnt]; set_wf_type (voice._lfo, _wf_type); voice._lfo.set_period (_period); update_phase (voice, base_phase); voice._dly_reader.clip_times (); } } _nbr_voices = nbr_voices; _voice_vol = sqrt (2.0f / float (_nbr_voices + 1)); } void FlanchoChn::set_period (double period) { _period = period; for (int v_cnt = 0; v_cnt < Cst::_max_nbr_voices; ++v_cnt) { Voice & voice = _voice_arr [v_cnt]; voice._lfo.set_period (_period); } update_mpl_lfo (); } void FlanchoChn::set_speed (double freq) { assert (freq > 0); set_period (1 / freq); } void FlanchoChn::set_delay (double delay) { assert (delay * 1e6 >= Cst::_delay_min); assert (delay * 1e6 <= Cst::_delay_max); _delay = delay; update_max_proc_len (); } void FlanchoChn::set_depth (double depth) { assert (depth >= 0); assert (depth <= 1); _depth = depth; update_max_proc_len (); } void FlanchoChn::set_wf_type (WfType wf_type) { assert (wf_type >= 0); assert (wf_type < WfType_NBR_ELT); _wf_type = wf_type; for (int v_cnt = 0; v_cnt < Cst::_max_nbr_voices; ++v_cnt) { Voice & voice = _voice_arr [v_cnt]; set_wf_type (voice._lfo, _wf_type); } } void FlanchoChn::set_wf_shape (double shape) { assert (shape >= -1); assert (shape <= +1); _wf_shape = shape; update_shape (); } void FlanchoChn::set_feedback (double fdbk) { assert (fdbk > -1); assert (fdbk < +1); _feedback = fdbk; } void FlanchoChn::set_polarity (bool neg_flag) { _neg_flag = neg_flag; } void FlanchoChn::resync (double base_phase) { assert (base_phase >= 0); assert (base_phase < 1); for (int v_cnt = 0; v_cnt < Cst::_max_nbr_voices; ++v_cnt) { Voice & voice = _voice_arr [v_cnt]; update_phase (voice, base_phase); } } void FlanchoChn::process_block (float out_ptr [], const float in_ptr [], int nbr_spl) { assert (_max_proc_len > 0); assert (out_ptr != nullptr); assert (in_ptr != nullptr); assert (nbr_spl > 0); const double fdbk_step = (_feedback - _feedback_old) / nbr_spl; double fdbk_cur = _feedback_old; float * render_ptr = _tmp_buf_arr [TmpBufType_RENDER]._ptr; int block_pos = 0; do { int work_len = nbr_spl - block_pos; work_len = std::min (work_len, _max_proc_len); work_len = std::min (work_len, _mpl_lfo); const double fdbk_new = fdbk_cur + fdbk_step * work_len; // We scan the voices in reverse order because: // 1. We want to process feedback last, when it already has been read on // the delay line. // 2. We want to generate the feedback from the first voice, to ensure // signal continuity when number of voices varies. const int last_voice = _nbr_voices - 1; for (int v_cnt = last_voice; v_cnt >= 0; --v_cnt) { Voice & voice = _voice_arr [v_cnt]; voice._lfo.tick (work_len); const double delay_time_new = compute_delay_time (voice._lfo); voice._dly_reader.set_delay_time (delay_time_new, work_len); // render_ptr contains the delay line output. voice._dly_reader.read_data (render_ptr, work_len, 0); float vol = float (_voice_vol); if (_neg_flag) { vol = -vol; } if (work_len == 1) { float val = render_ptr [0]; const float val_vol = val * vol; if (v_cnt == last_voice) { out_ptr [block_pos] = val_vol; } else { out_ptr [block_pos] += val_vol; } if (v_cnt == 0) { // Feedback processing val *= float (fdbk_cur); val = voice._hpf.process_sample (val); val += in_ptr [block_pos]; _dly_line.push_sample (val); } } else { if (v_cnt == last_voice) { // Copies to the output if (vol != 1) { dsp::mix::Generic::copy_1_1_v ( out_ptr + block_pos, render_ptr, work_len, vol ); } else { dsp::mix::Generic::copy_1_1 ( out_ptr + block_pos, render_ptr, work_len ); } } // Other voices: just mix the output else { if (vol != 1) { dsp::mix::Generic::mix_1_1_v ( out_ptr + block_pos, render_ptr, work_len, vol ); } else { dsp::mix::Generic::mix_1_1 ( out_ptr + block_pos, render_ptr, work_len ); } } if (v_cnt == 0) { // Feedback processing dsp::mix::Generic::scale_1_vlrauto ( render_ptr, work_len, float (fdbk_cur), float (fdbk_new) ); dsp::mix::Generic::mix_1_1 ( render_ptr, in_ptr + block_pos, work_len ); _dly_line.push_block (render_ptr, work_len); } } } fdbk_cur = fdbk_new; block_pos += work_len; } while (block_pos < nbr_spl); _feedback_old = _feedback; } void FlanchoChn::clear_buffers () { _dly_line.clear_buffers (); for (int v_cnt = 0; v_cnt < Cst::_max_nbr_voices; ++v_cnt) { Voice & voice = _voice_arr [v_cnt]; const double phase = voice._lfo.get_phase (); voice._lfo.clear_buffers (); voice._lfo.set_phase (phase); const double delay_time_new = compute_delay_time (voice._lfo); voice._dly_reader.set_delay_time (delay_time_new, 0); voice._dly_reader.clear_buffers (); voice._hpf.clear_buffers (); } _feedback_old = _feedback; } /*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ /*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ double FlanchoChn::estimate_base_phase () const { const Voice & voice = _voice_arr [0]; double phase = voice._lfo.get_phase (); phase -= voice._rel_phase; phase -= _rel_phase; phase -= floor (phase); return phase; } void FlanchoChn::set_wf_type (dsp::ctrl::lfo::LfoModule &lfo, WfType wf_type) { assert (wf_type >= 0); assert (wf_type < WfType_NBR_ELT); dsp::ctrl::lfo::LfoModule::Type lfo_type = dsp::ctrl::lfo::LfoModule::Type_SINE; bool inv_flag = false; double chaos = 0; switch (wf_type) { case WfType_SINE: lfo_type = dsp::ctrl::lfo::LfoModule::Type_SINE; break; case WfType_TRI: lfo_type = dsp::ctrl::lfo::LfoModule::Type_VARISLOPE; break; case WfType_PARABOLA: lfo_type = dsp::ctrl::lfo::LfoModule::Type_PARABOLA; break; case WfType_PARABOLA_INV: lfo_type = dsp::ctrl::lfo::LfoModule::Type_PARABOLA; inv_flag = true; break; case WfType_RAMP_UP: lfo_type = dsp::ctrl::lfo::LfoModule::Type_SAW; break; case WfType_RAMP_DOWN: lfo_type = dsp::ctrl::lfo::LfoModule::Type_SAW; inv_flag = true; break; case WfType_RND: lfo_type = dsp::ctrl::lfo::LfoModule::Type_SINE; chaos = 80.0 / 256; break; default: assert (false); break; } lfo.set_type (lfo_type); lfo.set_sign (inv_flag); lfo.set_chaos (chaos); update_lfo_param (); } double FlanchoChn::compute_delay_time (const dsp::ctrl::lfo::LfoModule &lfo) { double lfo_val = lfo.get_val (); if (_wf_type != WfType_TRI) { // Scales from [-1 ; 1] to the shaper input range lfo_val *= _sat_in_a; lfo_val += _sat_in_b; // Shapes the signal lfo_val = SatFnc::saturate (lfo_val); // Back to [-1 ; 1] lfo_val *= _sat_out_a; lfo_val += _sat_out_b; } double delay_time = _delay * (1 + lfo_val * _depth); const double delay_limit = _dly_line.get_min_delay_time (); delay_time = std::max (delay_time, delay_limit); return delay_time; } void FlanchoChn::update_phase (Voice &voice, double base_phase) { double phase = base_phase + _rel_phase + voice._rel_phase; phase -= floor (phase); voice._lfo.set_phase (phase); } void FlanchoChn::update_shape () { update_lfo_param (); update_shaper_data (); } // Principle: // When _wf_shape is close to 0, we work in the nearly-linear zone of // the waveshaper (MapSaturate). The input signal is scaled to a // small range around 0. // When _wf_shape is close to 1 or -1, we put the waveshaper knee of // the correspounding polarity at the center of the input range, so the // symmetric shape of the input signal turns into an asymmetric shape. // Therefore the minimum input level keeps staying close to 0, and the // maximum input level becomes close to the waveshaper maximum input // level. // Inbetween both cases, one of the range bound is moved, depending on // the _wf_shape polarity. void FlanchoChn::update_shaper_data () { const double wp = std::max (_wf_shape, 0.0); const double wn = std::max (-_wf_shape, 0.0); const double lin_limit = 1.0 / 64; const double scale = SatFnc::get_xs () - lin_limit; const double a = 0.875; const double b = 1 - a; const double wp_m = (a * wp * wp + b) * wp; const double wn_m = (a * wn * wn + b) * wn; const double x_min = -lin_limit - wn_m * scale; const double x_max = +lin_limit + wp_m * scale; _sat_in_a = (x_max - x_min) * 0.5; _sat_in_b = x_min - _sat_in_a * -1; const double y_min = SatFnc::saturate (x_min); const double y_max = SatFnc::saturate (x_max); _sat_out_a = 2 / (y_max - y_min); _sat_out_b = -1 - _sat_out_a * y_min; } void FlanchoChn::update_lfo_param () { if (_wf_type == WfType_TRI) { const double var_time = (_wf_shape + 1) * 0.5; for (int v_cnt = 0; v_cnt < Cst::_max_nbr_voices; ++v_cnt) { Voice & voice = _voice_arr [v_cnt]; voice._lfo.set_variation ( dsp::ctrl::lfo::OscInterface::Variation_TIME, var_time ); voice._lfo.set_variation ( dsp::ctrl::lfo::OscInterface::Variation_SHAPE, 0 ); } } } void FlanchoChn::update_max_proc_len () { double dly_min = _delay * (1 - _depth); const double delay_limit = _dly_line.get_min_delay_time (); dly_min = std::max (dly_min, delay_limit); _max_proc_len = _dly_line.estimate_max_one_shot_proc_w_feedback (dly_min); assert (_max_proc_len > 0); _max_proc_len = std::min (_max_proc_len, _tmp_buf_arr [TmpBufType_RENDER]._len); } void FlanchoChn::update_mpl_lfo () { float p_spl = float (_period * _sample_freq); const int seg = fstb::round_int (p_spl * (1.0f / 64)); _mpl_lfo = fstb::limit (seg, 2, 256); } } // namespace flancho } // namespace pi } // namespace mfx /*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
21.208333
149
0.634849
[ "shape" ]
5fad3fd6646b968d59feedcc08236d28b01e971a
4,155
cpp
C++
SeriousSkaStudio/DlgCSoundEffectProperty.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
1
2022-02-14T15:46:44.000Z
2022-02-14T15:46:44.000Z
SeriousSkaStudio/DlgCSoundEffectProperty.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
null
null
null
SeriousSkaStudio/DlgCSoundEffectProperty.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
2
2022-01-10T22:17:06.000Z
2022-01-17T09:34:08.000Z
// DlgCSoundEffectProperty.cpp : implementation file // #include "stdafx.h" #include "seriousskastudio.h" #include "DlgCSoundEffectProperty.h" #include <Engine/Effect/CSoundEffect.h> #include <Engine/Effect/CEffectManager.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ULONG GetFlagsByLB(CListBox &lb, int bitOffset = 0) { ULONG ulRet = 0; for(int i=0; i<lb.GetCount(); ++i) { ulRet |= (lb.GetSel(i) > 0) << (i + bitOffset); } return ulRet; } void SetFlagsToLB(ULONG flags, CListBox &lb, int bitOffset = 0) { for(int i=bitOffset; i<32; ++i) { if( (1 << i) & flags ) { lb.SetSel(i - bitOffset, TRUE); } } } ///////////////////////////////////////////////////////////////////////////// // CDlgCSoundEffectProperty dialog CDlgCSoundEffectProperty::CDlgCSoundEffectProperty(CWnd* pParent /*=NULL*/) : CDialog(CDlgCSoundEffectProperty::IDD, pParent) { //{{AFX_DATA_INIT(CDlgCSoundEffectProperty) m_fFallOff = 0.0f; m_strSndFileName = _T(""); m_fHotSpot = 0.0f; m_fVolume = 0.0f; m_fPitch = 0.0f; //}}AFX_DATA_INIT } void CDlgCSoundEffectProperty::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDlgCSoundEffectProperty) DDX_Control(pDX, IDC_SND_FLAGS, m_listSndFlag); DDX_Text(pDX, IDC_SND_FALLOFF, m_fFallOff); DDX_Text(pDX, IDC_SND_FILENAME, m_strSndFileName); DDX_Text(pDX, IDC_SND_HOTSPOT, m_fHotSpot); DDX_Text(pDX, IDC_SND_VOLUME, m_fVolume); DDX_Text(pDX, IDC_SND_PITCH, m_fPitch); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CDlgCSoundEffectProperty, CDialog) //{{AFX_MSG_MAP(CDlgCSoundEffectProperty) ON_BN_CLICKED(IDC_BTN_SND_FILEFIND, OnBtnSndFilefind) //}}AFX_MSG_MAP ON_WM_REGISTER_EFFECT() ON_WM_SELECT_EFFECT() ON_WM_CLEAR_FORM() END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDlgCSoundEffectProperty message handlers #define SND_FLAG_CNT 7 BOOL CDlgCSoundEffectProperty::OnInitDialog() { CDialog::OnInitDialog(); // TODO: Add extra initialization here m_listSndFlag.AddString("Loop"); m_listSndFlag.AddString("3D"); m_listSndFlag.AddString("Volumetric"); m_listSndFlag.AddString("Local"); m_listSndFlag.AddString("Music"); m_listSndFlag.AddString("Non-Game"); m_listSndFlag.AddString("Voice"); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CDlgCSoundEffectProperty::OnBtnSndFilefind() { // TODO: Add your control notification handler code here FILESELECTDLG(m_strSndFileName, "wav"); } void CDlgCSoundEffectProperty::OnClearForm() { m_fFallOff = 0.0f; m_strSndFileName = _T(""); m_fHotSpot = 0.0f; m_fVolume = 0.0f; m_fPitch = 0.0f; SetFlagsToLB(0, m_listSndFlag); this->UpdateData(SAVETOFORM); } LRESULT CDlgCSoundEffectProperty::OnRegisterEffect(WPARAM wp, LPARAM lp) { if(wp == 0) return 0; CDlgCEffectProperty &ep = *(CDlgCEffectProperty*)wp; this->UpdateData(SAVETOOBJECT); if(m_strSndFileName == "") return 0; ULONG ulFlag = GetFlagsByLB(m_listSndFlag); CSoundEffect se; CTFileName fnmSnd = m_strSndFileName; se.SetSound(fnmSnd); se.Set3DParameter(m_fFallOff, m_fHotSpot, m_fVolume, m_fPitch); se.SetSoundPlayFlag(ulFlag); ep.RegisterEffect(se); return 0; } LRESULT CDlgCSoundEffectProperty::OnSelectEffect(WPARAM wp, LPARAM lp) { if(wp == 0) return 0; CDlgCEffectProperty &ep = *(CDlgCEffectProperty*)wp; CString strName; int index = ep.m_cbRegisteredName.GetCurSel(); if(index != CB_ERR) { ep.m_cbRegisteredName.GetLBText( index, strName ); CSoundEffect *pSE = (CSoundEffect*)CEffectManager::Instance().Create( strName.GetBuffer(0) ); if(pSE == NULL) return 0; this->m_fFallOff = pSE->GetFallOff(); this->m_fHotSpot = pSE->GetHotSpot(); this->m_fVolume = pSE->GetVolume(); this->m_fPitch = pSE->GetPitch(); this->m_strSndFileName = pSE->GetSoundFileName().str_String; ULONG ulFlag = pSE->GetSoundPlayFlag(); SetFlagsToLB(ulFlag, m_listSndFlag); this->UpdateData(SAVETOFORM); ep.SetEffectInfo(*pSE); CEffectManager::Instance().Destroy((CEffect *&)pSE); } return 0; }
25.335366
95
0.712635
[ "3d" ]
5fb150a81dcc556ac83d639fce8ccc9ad52e596b
5,374
hpp
C++
include/CLinearSystem.hpp
seraco/HeatConduction
357180848d3de2798e47359691293979f8446500
[ "MIT" ]
3
2018-04-13T11:16:27.000Z
2021-05-24T02:51:00.000Z
include/CLinearSystem.hpp
seraco/HeatConduction
357180848d3de2798e47359691293979f8446500
[ "MIT" ]
null
null
null
include/CLinearSystem.hpp
seraco/HeatConduction
357180848d3de2798e47359691293979f8446500
[ "MIT" ]
null
null
null
/*! * @file CLinearSystem.hpp * @brief Headers of the main subroutines for solving linear systems of equations. * The implementation is in the <i>CLinearSystem.cpp</i> file. * @author S.Ramon (seraco) * @version 0.0.1 * * Copyright 2018 S.Ramon * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef __CLINEARSYSTEM_HPP #define __CLINEARSYSTEM_HPP #include "CMatrix.hpp" #include "CMatrixSymmetric.hpp" #define F77NAME(x) x##_ extern "C" { void F77NAME(dgesv)(const int& n, const int& nrhs, const double* A, const int& lda, int* ipiv, double* B, const int& ldb, int& info); double F77NAME(ddot) (const int& n, const double *x, const int& incx, const double *y, const int& incy); double F77NAME(dnrm2) (const int& n, const double *x, const int& incx); void F77NAME(dgemv) (const char& trans, const int& nrowsa, const int& ncolsa, const double& alpha, const double* A, const int& lda, const double* x, const int& incx, const double& beta, double* y, const int& incy); void F77NAME(dsymv) (const char& trans, const int& nrowsa, const double& alpha, const double* A, const int& lda, const double* x, const int& incx, const double& beta, double* y, const int& incy); void F77NAME(dspmv) (const char& trans, const int& nrowsa, const double& alpha, const double* A, const double* x, const int& incx, const double& beta, double* y, const int& incy); void F77NAME(daxpy) (const int& n, const double& alpha, const double* x, const int& incx, double* y, const int& incy); void F77NAME(dcopy) (const int& n, const double* x, const int& incx, double* y, const int& incy); } /*! * @class CLinearSystem * @brief Class to solve linear systems of equations. */ template <typename T> class CLinearSystem { private: T lhsMatrix; /*!< @brief A matrix of the system.*/ CMatrix rhsVector; /*!< @brief b vector of the system.*/ /*! * @brief Subroutine to know if the system is valid to solve. * @return Boolean to know if the system is valid to solve. */ bool isSystemValid(); /*! * @brief Parallel dot product of two vectors. * @param[in] x - First vector. * @param[in] y - Second vector. * @param[in] n - Size of the vectors. */ double parallelDot(double* x, double* y, unsigned n); void parallelMul(const CMatrix& A, double* x, double* y, unsigned n, double alpha, double beta); void parallelMul(const CMatrixSymmetric& A, double* x, double* y, unsigned n, double alpha, double beta); public: /*! * @brief Constructor of the class. * @param[in] A - LHS matrix of coefficients. * @param[in] b - RHS vector. */ CLinearSystem(const T& A, const CMatrix& b); /*! * @brief Destructor of the class. */ virtual ~CLinearSystem(); /*! * @brief Get LHS matrix of coefficients. * @return LHS matrix of coefficients. */ T getLhsMatrix(); /*! * @brief Get RHS vector. * @return RHS vector. */ CMatrix getRhsVector(); /*! * @brief Direct solution of the system with LU decomposition. * @return Vector of unknowns. */ CMatrix directSolve(); /*! * @brief Iterative solution of the system with CG method. * @return Vector of unknowns. */ CMatrix iterativeSolve(); }; #include "../src/CLinearSystem.cpp" #endif
36.808219
82
0.553964
[ "vector" ]
5fb5e30e786908d231ae4eaf03ee0fb8602c03a5
2,438
cpp
C++
tests/PhiCore/unittests/src/core/monitor.test.cpp
AMS21/Phi
d62d7235dc5307dd18607ade0f95432ae3a73dfd
[ "MIT" ]
3
2020-12-21T13:47:35.000Z
2022-03-16T23:53:21.000Z
tests/PhiCore/unittests/src/core/monitor.test.cpp
AMS21/Phi
d62d7235dc5307dd18607ade0f95432ae3a73dfd
[ "MIT" ]
53
2020-08-07T07:46:57.000Z
2022-02-12T11:07:08.000Z
tests/PhiCore/unittests/src/core/monitor.test.cpp
AMS21/Phi
d62d7235dc5307dd18607ade0f95432ae3a73dfd
[ "MIT" ]
1
2020-08-19T15:50:02.000Z
2020-08-19T15:50:02.000Z
#include "phi/compiler_support/warning.hpp" #include <phi/test/test_macros.hpp> #include <phi/compiler_support/compiler.hpp> #include <phi/core/forward.hpp> #include <phi/core/monitor.hpp> #include <thread> #include <utility> #include <vector> PHI_GCC_SUPPRESS_WARNING_PUSH() PHI_GCC_SUPPRESS_WARNING("-Wuseless-cast") struct A { A() : val(1) {} A(int /*unused*/, double /*unused*/) : val(2) {} int val; }; constexpr std::size_t test_thread_count{20}; constexpr std::size_t test_write_count{10000}; static void test_function(phi::monitor<A>& a) { for (std::size_t i = 0; i < test_write_count; ++i) { a->val++; } } TEST_CASE("monitor", "[Core][monitor]") { SECTION("monitor(ArgsT)") { phi::monitor<A> mon(3, 3.14); CHECK(mon->val == 2); } SECTION("monitor(T)") { A a; phi::monitor<A> mon(a); CHECK(mon->val == 1); } SECTION("operator->") { phi::monitor<A> mon(3, 3.14); CHECK(mon->val == 2); } #if PHI_HAS_FEATURE_DECLTYPE_AUTO() SECTION("operator()") { phi::monitor<A> mon(3, 3.14); mon([](A& a) { a.val += 1; }); CHECK(mon->val == 3); } #endif SECTION("ManualLock") { phi::monitor<A> mon(3, 3.14); auto lock = mon.ManuallyLock(); CHECK(lock->val == 2); CHECK(lock.m_monitor == &mon); } SECTION("GetThreadUnsafeAccess") { phi::monitor<A> mon(3, 3.14); A& a = mon.GetThreadUnsafeAccess(); a.val += 3; CHECK(a.val == 5); CHECK(mon->val == 5); } SECTION("Thread safety") { #if PHI_COMPILER_IS(EMCC) // Skip thread safety test in emscripten since the support for multiple threads is not very great, // See: https://emscripten.org/docs/porting/pthreads.html return; #else phi::monitor<A> mon; std::vector<std::thread> threads; threads.reserve(test_thread_count); for (std::size_t i = 0; i < test_thread_count; ++i) { threads.emplace_back(test_function, std::ref(mon)); } for (auto& thread : threads) { thread.join(); } constexpr int expected_value = 1 + (test_thread_count * test_write_count); CHECK(mon->val == expected_value); #endif } } PHI_GCC_SUPPRESS_WARNING_POP()
19.504
106
0.556604
[ "vector" ]
5fb833a73a1384c35293a9d1989e2769c0bbc1d5
1,780
cpp
C++
Unreal/CarlaUE4/Source/CarlaUE4/eSoftSim/ROSTextSubscriberTest.cpp
Garazbolg/carla
1cd2e7b159597bc9879083a37c921ee593ec4a54
[ "MIT" ]
null
null
null
Unreal/CarlaUE4/Source/CarlaUE4/eSoftSim/ROSTextSubscriberTest.cpp
Garazbolg/carla
1cd2e7b159597bc9879083a37c921ee593ec4a54
[ "MIT" ]
null
null
null
Unreal/CarlaUE4/Source/CarlaUE4/eSoftSim/ROSTextSubscriberTest.cpp
Garazbolg/carla
1cd2e7b159597bc9879083a37c921ee593ec4a54
[ "MIT" ]
null
null
null
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma de Barcelona (UAB). This work is licensed under the terms of the MIT license. For a copy, see <https://opensource.org/licenses/MIT>. #include "CarlaUE4.h" #include "ROSTextSubscriberTest.h" #include "ROSIntegration/Classes/RI/Topic.h" #include "ROSIntegration/Classes/ROSIntegrationGameInstance.h" #include "ROSIntegration/Public/std_msgs/String.h" // Sets default values AROSTextSubscriberTest::AROSTextSubscriberTest() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; } // Called when the game starts or when spawned void AROSTextSubscriberTest::BeginPlay() { Super::BeginPlay(); // Initialize a topic ExampleTopic = NewObject<UTopic>(UTopic::StaticClass()); UROSIntegrationGameInstance* rosinst = Cast<UROSIntegrationGameInstance>(GetGameInstance()); ExampleTopic->Init(rosinst->ROSIntegrationCore, TEXT("/example_topic"), TEXT("std_msgs/String")); // Create a std::function callback object std::function<void(TSharedPtr<FROSBaseMsg>)> SubscribeCallback = [](TSharedPtr<FROSBaseMsg> msg) -> void { UE_LOG(LogTemp,Log,TEXT("ROS String Message Received !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")); auto Concrete = StaticCastSharedPtr<ROSMessages::std_msgs::String>(msg); if (Concrete.IsValid()) { UE_LOG(LogTemp, Log, TEXT("Incoming string was: %s"), (*(Concrete->_Data))); } return; }; // Subscribe to the topic ExampleTopic->Subscribe(SubscribeCallback); UE_LOG(LogTemp,Log,TEXT("Subscribing !!!!!!!!!!!!!!!!!!!!!!")) } // Called every frame void AROSTextSubscriberTest::Tick(float DeltaTime) { Super::Tick(DeltaTime); }
33.584906
211
0.715169
[ "object" ]
5fbf77192f9db2a4f47b84bb7d34137c46814ae0
16,150
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/internal/view/menu/ActionMenuItemView.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/internal/view/menu/ActionMenuItemView.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/internal/view/menu/ActionMenuItemView.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include <Elastos.CoreLibrary.Utility.h> #include "Elastos.Droid.Content.h" #include "elastos/droid/graphics/CRect.h" #include "elastos/droid/internal/view/menu/ActionMenuItemView.h" #include "elastos/droid/R.h" #include "elastos/droid/text/TextUtils.h" #include "elastos/droid/widget/Toast.h" #include <elastos/core/Math.h> using Elastos::Droid::Content::Res::IResources; using Elastos::Droid::Content::Res::ITypedArray; using Elastos::Droid::Graphics::CRect; using Elastos::Droid::Text::TextUtils; using Elastos::Droid::Utility::IDisplayMetrics; using Elastos::Droid::View::IGravity; using Elastos::Droid::View::IMenuItem; using Elastos::Droid::View::EIID_IViewOnClickListener; using Elastos::Droid::View::EIID_IViewOnLongClickListener; using Elastos::Droid::View::Accessibility::IAccessibilityRecord; using Elastos::Droid::Widget::IToast; using Elastos::Droid::Widget::Toast; using Elastos::Droid::Widget::EIID_IActionMenuChildView; namespace Elastos { namespace Droid { namespace Internal { namespace View { namespace Menu { CAR_INTERFACE_IMPL_2(ActionMenuItemView::MyListener, Object, IViewOnClickListener, IViewOnLongClickListener) ActionMenuItemView::MyListener::MyListener( /* [in] */ ActionMenuItemView* owner) : mOwner(owner) {} ECode ActionMenuItemView::MyListener::OnClick( /* [in] */ IView* v) { return mOwner->OnClick(v); } ECode ActionMenuItemView::MyListener::OnLongClick( /* [in] */ IView* v, /* [out] */ Boolean* result) { return mOwner->OnLongClick(v, result); } ActionMenuItemView::ActionMenuItemForwardingListener::ActionMenuItemForwardingListener( /* [in] */ ActionMenuItemView* owner) : mOwner(owner) { ListPopupWindow::ForwardingListener::constructor(owner); } ECode ActionMenuItemView::ActionMenuItemForwardingListener::GetPopup( /* [out] */ IListPopupWindow** window) { VALIDATE_NOT_NULL(window) if (mOwner->mPopupCallback != NULL) { return mOwner->mPopupCallback->GetPopup(window); } *window = NULL; return NOERROR; } Boolean ActionMenuItemView::ActionMenuItemForwardingListener::OnForwardingStarted() { Boolean res; // Call the invoker, then check if the expected popup is showing. if (mOwner->mItemInvoker != NULL && (mOwner->mItemInvoker->InvokeItem(mOwner->mItemData, &res), res)) { AutoPtr<IListPopupWindow> popup; GetPopup((IListPopupWindow**)&popup); return popup != NULL && (popup->IsShowing(&res), res); } return FALSE; } Boolean ActionMenuItemView::ActionMenuItemForwardingListener::OnForwardingStopped() { AutoPtr<IListPopupWindow> popup; GetPopup((IListPopupWindow**)&popup); if (popup != NULL) { popup->Dismiss(); return TRUE; } return FALSE; } String ActionMenuItemView::TAG("ActionMenuItemView"); const Int32 ActionMenuItemView::MAX_ICON_SIZE = 32; // dp CAR_INTERFACE_IMPL_5(ActionMenuItemView, TextView, IActionMenuItemView, IMenuItemView, IViewOnClickListener, IViewOnLongClickListener, IActionMenuChildView) ActionMenuItemView::ActionMenuItemView() : mAllowTextWithIcon(FALSE) , mExpandedFormat(FALSE) , mMinWidth(0) , mSavedPaddingLeft(0) , mMaxIconSize(0) { } ECode ActionMenuItemView::constructor( /* [in] */ IContext* context) { return constructor(context, NULL); } ECode ActionMenuItemView::constructor( /* [in] */ IContext* context, /* [in] */ IAttributeSet* attrs) { return constructor(context, attrs, 0); } ECode ActionMenuItemView::constructor( /* [in] */ IContext* context, /* [in] */ IAttributeSet* attrs, /* [in] */ Int32 defStyleAttr) { return constructor(context, attrs, defStyleAttr, 0); } ECode ActionMenuItemView::constructor( /* [in] */ IContext* context, /* [in] */ IAttributeSet* attrs, /* [in] */ Int32 defStyleAttr, /* [in] */ Int32 defStyleRes) { FAIL_RETURN(TextView::constructor(context, attrs, defStyleAttr, defStyleRes)) AutoPtr<IResources> res; context->GetResources((IResources**)&res); res->GetBoolean(R::bool_::config_allowActionMenuItemTextWithIcon, &mAllowTextWithIcon); AutoPtr<ArrayOf<Int32> > attrIds = TO_ATTRS_ARRAYOF(R::styleable::ActionMenuItemView); AutoPtr<ITypedArray> a; context->ObtainStyledAttributes(attrs, attrIds, defStyleAttr, defStyleRes, (ITypedArray**)&a); a->GetDimensionPixelSize(R::styleable::ActionMenuItemView_minWidth, 0, &mMinWidth); a->Recycle(); AutoPtr<IDisplayMetrics> metrics; res->GetDisplayMetrics((IDisplayMetrics**)&metrics); Float density = 0.f; metrics->GetDensity(&density); mMaxIconSize = (Int32) (MAX_ICON_SIZE * density + 0.5f); AutoPtr<MyListener> listener = new MyListener(this); SetOnClickListener(listener); SetOnLongClickListener(listener); mSavedPaddingLeft = -1; return NOERROR; } ECode ActionMenuItemView::OnConfigurationChanged( /* [in] */ IConfiguration* newConfig) { TextView::OnConfigurationChanged(newConfig); AutoPtr<IContext> context; GetContext((IContext**)&context); AutoPtr<IResources> res; context->GetResources((IResources**)&res); res->GetBoolean(R::bool_::config_allowActionMenuItemTextWithIcon, &mAllowTextWithIcon); UpdateTextButtonVisibility(); return NOERROR; } ECode ActionMenuItemView::SetPadding( /* [in] */ Int32 l, /* [in] */ Int32 t, /* [in] */ Int32 r, /* [in] */ Int32 b) { mSavedPaddingLeft = l; return TextView::SetPadding(l, t, r, b); } ECode ActionMenuItemView::GetItemData( /* [out] */ IMenuItemImpl** itemData) { assert(itemData != NULL); *itemData = mItemData; REFCOUNT_ADD(*itemData); return NOERROR; } ECode ActionMenuItemView::Initialize( /* [in] */ IMenuItemImpl* _itemData, /* [in] */ Int32 menuType) { mItemData = _itemData; IMenuItem* itemData = IMenuItem::Probe(_itemData); AutoPtr<IDrawable> icon; itemData->GetIcon((IDrawable**)&icon); SetIcon(icon); AutoPtr<ICharSequence> title; _itemData->GetTitleForItemView(this, (ICharSequence**)&title); SetTitle(title); // Title only takes effect if there is no icon Int32 id = 0; itemData->GetItemId(&id); SetId(id); Boolean visible = FALSE; itemData->IsVisible(&visible); SetVisibility(visible ? IView::VISIBLE : IView::GONE); Boolean enabled = FALSE; itemData->IsEnabled(&enabled); SetEnabled(enabled); Boolean hasSubMenu; if (itemData->HasSubMenu(&hasSubMenu), hasSubMenu) { if (mForwardingListener == NULL) { mForwardingListener = new ActionMenuItemForwardingListener(this); } } return NOERROR; } ECode ActionMenuItemView::OnTouchEvent( /* [in] */ IMotionEvent* e, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) Boolean hasSubMenu; IMenuItem::Probe(mItemData)->HasSubMenu(&hasSubMenu); Boolean res; if (hasSubMenu && mForwardingListener != NULL && (mForwardingListener->OnTouch(this, e, &res), res)) { *result = TRUE; return NOERROR; } return TextView::OnTouchEvent(e, result); } ECode ActionMenuItemView::OnClick( /* [in] */ IView* v) { if (mItemInvoker != NULL) { Boolean state = FALSE; return mItemInvoker->InvokeItem(mItemData, &state); } return NOERROR; } ECode ActionMenuItemView::SetItemInvoker( /* [in] */ IMenuBuilderItemInvoker* invoker) { mItemInvoker = invoker; return NOERROR; } ECode ActionMenuItemView::SetPopupCallback( /* [in] */ IPopupCallback* popupCallback) { mPopupCallback = popupCallback; return NOERROR; } ECode ActionMenuItemView::PrefersCondensedTitle( /* [out] */ Boolean* supported) { VALIDATE_NOT_NULL(supported) *supported = TRUE; return NOERROR; } ECode ActionMenuItemView::SetCheckable( /* [in] */ Boolean checkable) { // TODO Support checkable action items return NOERROR; } ECode ActionMenuItemView::SetChecked( /* [in] */ Boolean checked) { // TODO Support checkable action items return NOERROR; } ECode ActionMenuItemView::SetExpandedFormat( /* [in] */ Boolean expandedFormat) { if (mExpandedFormat != expandedFormat) { mExpandedFormat = expandedFormat; if (mItemData != NULL) { return mItemData->ActionFormatChanged(); } } return NOERROR; } void ActionMenuItemView::UpdateTextButtonVisibility() { Boolean visible = !TextUtils::IsEmpty(mTitle); Boolean tmp = FALSE; visible &= mIcon == NULL || ((mItemData->ShowsTextAsAction(&tmp), tmp) && (mAllowTextWithIcon || mExpandedFormat)); SetText(visible ? mTitle : NULL); } ECode ActionMenuItemView::SetIcon( /* [in] */ IDrawable* icon) { mIcon = icon; if (icon != NULL) { Int32 width = 0; icon->GetIntrinsicWidth(&width); Int32 height = 0; icon->GetIntrinsicHeight(&height); if (width > mMaxIconSize) { Float scale = (Float) mMaxIconSize / width; width = mMaxIconSize; height *= scale; } if (height > mMaxIconSize) { Float scale = (Float) mMaxIconSize / height; height = mMaxIconSize; width *= scale; } icon->SetBounds(0, 0, width, height); } SetCompoundDrawables(icon, NULL, NULL, NULL); UpdateTextButtonVisibility(); return NOERROR; } ECode ActionMenuItemView::HasText( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) AutoPtr<ICharSequence> text; GetText((ICharSequence**)&text); *result = !TextUtils::IsEmpty(text); return NOERROR; } ECode ActionMenuItemView::SetShortcut( /* [in] */ Boolean showShortcut, /* [in] */ Char32 shortcutKey) { // Action buttons don't show text for shortcut keys. return NOERROR; } ECode ActionMenuItemView::SetTitle( /* [in] */ ICharSequence* title) { mTitle = title; SetContentDescription(mTitle); UpdateTextButtonVisibility(); return NOERROR; } ECode ActionMenuItemView::DispatchPopulateAccessibilityEvent( /* [in] */ IAccessibilityEvent* event, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) OnPopulateAccessibilityEvent(event); *result = TRUE; return NOERROR; } ECode ActionMenuItemView::OnPopulateAccessibilityEvent( /* [in] */ IAccessibilityEvent* event) { FAIL_RETURN(TextView::OnPopulateAccessibilityEvent(event)) AutoPtr<ICharSequence> cdesc; GetContentDescription((ICharSequence**)&cdesc); if (!TextUtils::IsEmpty(cdesc)) { AutoPtr<IList> texts; IAccessibilityRecord::Probe(event)->GetText((IList**)&texts); assert(texts != NULL); texts->Add(cdesc); } return NOERROR; } Boolean ActionMenuItemView::DispatchHoverEvent( /* [in] */ IMotionEvent* event) { // Don't allow children to hover; we want this to be treated as a single component. Boolean result; OnHoverEvent(event, &result); return result; } ECode ActionMenuItemView::ShowsIcon( /* [out] */ Boolean* shows) { VALIDATE_NOT_NULL(shows) *shows = TRUE; return NOERROR; } ECode ActionMenuItemView::NeedsDividerBefore( /* [out] */ Boolean* need) { VALIDATE_NOT_NULL(need) AutoPtr<IDrawable> icon; Boolean hasNext; *need = (HasText(&hasNext), hasNext) && (IMenuItem::Probe(mItemData)->GetIcon((IDrawable**)&icon), icon) == NULL; return NOERROR; } ECode ActionMenuItemView::NeedsDividerAfter( /* [out] */ Boolean* need) { VALIDATE_NOT_NULL(need) return HasText(need); } ECode ActionMenuItemView::OnLongClick( /* [in] */ IView* v, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) Boolean hasNext; if (HasText(&hasNext), hasNext) { // Don't show the cheat sheet for items that already show text. *result = FALSE; return NOERROR; } AutoPtr<ArrayOf<Int32> > screenPos; GetLocationOnScreen((ArrayOf<Int32>**)&screenPos); AutoPtr<IRect> displayFrame; CRect::New((IRect**)&displayFrame); GetWindowVisibleDisplayFrame(displayFrame); AutoPtr<IContext> context; GetContext((IContext**)&context); Int32 width; GetWidth(&width); Int32 height; GetHeight(&height); Int32 midy = (*screenPos)[1] + height / 2; Int32 referenceX = (*screenPos)[0] + width / 2; Int32 direct; v->GetLayoutDirection(&direct); if (direct == IView::LAYOUT_DIRECTION_LTR) { AutoPtr<IResources> res; context->GetResources((IResources**)&res); AutoPtr<IDisplayMetrics> metrics; res->GetDisplayMetrics((IDisplayMetrics**)&metrics); Int32 screenWidth = 0; metrics->GetWidthPixels(&screenWidth); referenceX = screenWidth - referenceX; // mirror } AutoPtr<ICharSequence> title; IMenuItem::Probe(mItemData)->GetTitle((ICharSequence**)&title); AutoPtr<IToast> cheatSheet; Toast::MakeText(context, title, IToast::LENGTH_SHORT, (IToast**)&cheatSheet); Int32 fHeight = 0; if (midy < (displayFrame->GetHeight(&fHeight), fHeight)) { // Show along the top; follow action buttons cheatSheet->SetGravity(IGravity::TOP | IGravity::END, referenceX, height); } else { // Show along the bottom center cheatSheet->SetGravity(IGravity::BOTTOM | IGravity::CENTER_HORIZONTAL, 0, height); } cheatSheet->Show(); *result = TRUE; return NOERROR; } ECode ActionMenuItemView::OnMeasure( /* [in] */ Int32 widthMeasureSpec, /* [in] */ Int32 heightMeasureSpec) { Boolean textVisible; HasText(&textVisible); if (textVisible && mSavedPaddingLeft >= 0) { Int32 t, r, b; GetPaddingTop(&t); GetPaddingRight(&r); GetPaddingBottom(&b); TextView::SetPadding(mSavedPaddingLeft, t, r, b); } TextView::OnMeasure(widthMeasureSpec, heightMeasureSpec); const Int32 widthMode = MeasureSpec::GetMode(widthMeasureSpec); const Int32 widthSize = MeasureSpec::GetSize(widthMeasureSpec); Int32 oldMeasuredWidth; GetMeasuredWidth(&oldMeasuredWidth); const Int32 targetWidth = widthMode == MeasureSpec::AT_MOST ? Elastos::Core::Math::Min(widthSize, mMinWidth) : mMinWidth; if (widthMode != MeasureSpec::EXACTLY && mMinWidth > 0 && oldMeasuredWidth < targetWidth) { // Remeasure at exactly the minimum width. TextView::OnMeasure(MeasureSpec::MakeMeasureSpec(targetWidth, MeasureSpec::EXACTLY), heightMeasureSpec); } if (!textVisible && mIcon != NULL) { // TextView won't center compound drawables in both dimensions without // a little coercion. Pad in to center the icon after we've measured. Int32 w; GetMeasuredWidth(&w); AutoPtr<IRect> bounds; mIcon->GetBounds((IRect**)&bounds); assert(bounds != NULL); Int32 dw = 0; bounds->GetWidth(&dw); Int32 t, r, b; GetPaddingTop(&t); GetPaddingRight(&r); GetPaddingBottom(&b); TextView::SetPadding((w - dw) / 2, t, r, b); } return NOERROR; } ECode ActionMenuItemView::SetEnabled( /* [in] */ Boolean enabled) { return TextView::SetEnabled(enabled); } } // namespace Menu } // namespace View } // namespace Internal } // namespace Droid } // namespace Elastos
27.989601
112
0.666378
[ "object" ]
5fc399346bd9f885833d6a8b30951f2750e16fa1
18,110
cpp
C++
Source/MediaInfo/Export/Export_Graph.cpp
mypopydev/MediaInfoLib
ec97c77e9196433838d2aaf28e84b9a5364ee706
[ "BSD-2-Clause" ]
null
null
null
Source/MediaInfo/Export/Export_Graph.cpp
mypopydev/MediaInfoLib
ec97c77e9196433838d2aaf28e84b9a5364ee706
[ "BSD-2-Clause" ]
null
null
null
Source/MediaInfo/Export/Export_Graph.cpp
mypopydev/MediaInfoLib
ec97c77e9196433838d2aaf28e84b9a5364ee706
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ //--------------------------------------------------------------------------- // Pre-compilation #include "MediaInfo/PreComp.h" #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Setup.h" //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #if defined(MEDIAINFO_GRAPH_YES) //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Export/Export_Graph.h" #include "MediaInfo/File__Analyse_Automatic.h" #include "MediaInfo/MediaInfo_Config.h" #include "MediaInfo/OutputHelpers.h" #include <ctime> #include <cmath> #ifdef MEDIAINFO_GRAPHVIZ_YES #ifdef MEDIAINFO_GRAPHVIZ_DLL_RUNTIME #include "MediaInfo/Export/Export_Graph_gvc_Include.h" #else #include <gvc.h> #endif //MEDIAINFO_GRAPHVIZ_DLL_RUNTIME #endif //MEDIAINFO_GRAPHVIZ_YES using namespace std; //--------------------------------------------------------------------------- namespace MediaInfoLib { //*************************************************************************** // Helpers //*************************************************************************** //--------------------------------------------------------------------------- Ztring NewLine(size_t Level) { return __T('\n')+Ztring(4*Level, __T(' ')); } //--------------------------------------------------------------------------- Ztring Element2Html(MediaInfo_Internal &MI, stream_t StreamKind, size_t StreamPos, Ztring Element, Ztring FG, Ztring BG, Ztring HFG, Ztring HBG) { Ztring ToReturn; ToReturn+=__T("<table border='0' cellborder='0' cellspacing='0'>"); ToReturn+=__T("<tr>"); ToReturn+=__T("<td colspan='2' bgcolor='")+HBG+__T("'>"); ToReturn+=__T("<font color='")+HFG+__T("'>"); ToReturn+=__T("<b>")+XML_Encode(MI.Get(StreamKind, StreamPos, Element, Info_Name_Text))+__T("</b>"); ToReturn+=__T("<br/>"); Ztring Sub=XML_Encode(MI.Get(StreamKind, StreamPos, Element, Info_Text)); if (Sub.size() && Sub[Sub.size()-1]==__T(')')) { if (Sub.FindAndReplace(__T("("), __T("<br/>"), 0)) Sub.erase(Sub.size()-1); } Sub.FindAndReplace(__T(" / "), __T("<br/>"), 0, Ztring_Recursive); ToReturn+=Sub; ToReturn+=__T("</font>"); ToReturn+=__T("</td>"); ToReturn+=__T("</tr>"); for (size_t Pos=0; Pos<MI.Count_Get(StreamKind, StreamPos); Pos++) { Ztring Name=MI.Get(StreamKind, StreamPos, Pos, Info_Name); if (Name.find(Element+__T(" "))==0 && Name.SubString(Element+__T(" "), __T("")).find(__T(" "))==string::npos) { Ztring Text=XML_Encode(MI.Get(StreamKind, StreamPos, Pos, Info_Text)); Text.FindAndReplace(__T(" / "), __T("<br align='left'/>"), 0, Ztring_Recursive); if (Text.empty() || Name.find(Element+__T(" LinkedTo_"))==0 || Name.find(Element+__T(" Title"))==0 || (MI.Get(StreamKind, StreamPos, Pos, Info_Options)[InfoOption_ShowInInform]!=__T('Y') && !MediaInfoLib::Config.Complete_Get())) continue; ToReturn+=__T("<tr>"); ToReturn+=__T("<td align='text' bgcolor='")+BG+__T("'>"); ToReturn+=__T("<font color='")+FG+__T("'>")+XML_Encode(MI.Get(StreamKind, StreamPos, Pos, Info_Name_Text))+=__T("</font><br align='left'/>"); ToReturn+=__T("</td>"); ToReturn+=__T("<td align='text' bgcolor='")+BG+__T("'>"); ToReturn+=__T("<font color='")+FG+__T("'>")+Text+=__T("</font><br align='left'/>"); ToReturn+=__T("</td>"); ToReturn+=__T("</tr>"); } } ToReturn+=__T("</table>"); return ToReturn; } //--------------------------------------------------------------------------- #ifdef MEDIAINFO_GRAPHVIZ_YES Ztring Dot2Svg(const Ztring& Dot) { Ztring ToReturn; GVC_t* Context=NULL; graph_t* Graph=NULL; char* Buffer=NULL; unsigned int Size; if (!Export_Graph::Load()) return ToReturn; if (Dot.empty()) return ToReturn; Context=gvContext(); if (!Context) return ToReturn; Graph=agmemread(Dot.To_UTF8().c_str()); if (!Graph) { gvFinalize(Context); gvFreeContext(Context); return ToReturn; } if (gvLayout(Context, Graph, "dot")!=0) { agclose(Graph); gvFinalize(Context); gvFreeContext(Context); return ToReturn; } gvRenderData(Context, Graph, "svg", &Buffer, &Size); if (Buffer && Size) ToReturn=Ztring().From_UTF8(Buffer); gvFreeRenderData(Buffer); gvFreeLayout(Context, Graph); agclose(Graph); gvFinalize(Context); gvFreeContext(Context); return ToReturn; } #endif //MEDIAINFO_GRAPHVIZ_YES //*************************************************************************** // Constructor/Destructor //*************************************************************************** //--------------------------------------------------------------------------- Export_Graph::Export_Graph () { } //--------------------------------------------------------------------------- Export_Graph::~Export_Graph () { } //*************************************************************************** // Dynamic load stuff //*************************************************************************** bool Export_Graph::Load() { //TODO: detect if graphviz library is usable #if defined(MEDIAINFO_GRAPHVIZ_DLL_RUNTIME) if (!gvc_Module) { DLOPEN(gvc_Module, GVCDLL_NAME) if (!gvc_Module) return false; bool Error=false; ASSIGN(gvc_Module, gvContext) ASSIGN(gvc_Module, gvFreeContext) ASSIGN(gvc_Module, gvLayout) ASSIGN(gvc_Module, gvFreeLayout) ASSIGN(gvc_Module, gvRenderData) ASSIGN(gvc_Module, gvFreeRenderData) ASSIGN(gvc_Module, gvFinalize) if (Error) { DLCLOSE(gvc_Module); return false; } } if (!cgraph_Module) { DLOPEN(cgraph_Module, CGRAPHDLL_NAME) if (!cgraph_Module) { DLCLOSE(gvc_Module); return false; } bool Error=false; ASSIGN(cgraph_Module, agmemread) ASSIGN(cgraph_Module, agclose) if (Error) { DLCLOSE(gvc_Module); DLCLOSE(cgraph_Module); return false; } } return true; #elif defined(MEDIAINFO_GRAPHVIZ_YES) return true; #else return false; #endif //defined(MEDIAINFO_GRAPHVIZ_DLL_RUNTIME) } //*************************************************************************** // Generators //*************************************************************************** #define OBJECT_START(NAME, COUNTER, FOREGROUND_COLOR, BACKGROUND_COLOR, TITLE_FOREGROUND_COLOR, TITLE_BACKGROUND_COLOR) \ {\ Temp+=NewLine(Level++)+__T("rank=same {"); \ size_t NAME##s=MI.Get(Stream_Audio, StreamPos, __T(COUNTER), Info_Text).To_int64u(); \ if (NAME##s) Empty=false; \ for (size_t NAME##Pos=NAME##s; NAME##Pos; NAME##Pos--) \ {\ Ztring Object=__T(#NAME)+Ztring().Ztring::ToZtring(NAME##Pos-1); \ Temp+=NewLine(Level++)+Stream+__T("_")+Object+__T(" ["); \ Temp+=NewLine(Level)+__T("shape=plaintext"); \ Temp+=NewLine(Level)+__T("label=<"); \ Temp+=Element2Html(MI, Stream_Audio, StreamPos, Object, __T(FOREGROUND_COLOR), __T(BACKGROUND_COLOR), __T(TITLE_FOREGROUND_COLOR), __T(TITLE_BACKGROUND_COLOR)); \ Temp+=__T(">");\ Temp+=NewLine(--Level)+__T("]"); #define OBJECT_LINK_TO(NAME, COLOR) \ { \ ZtringList Linked##NAME##s; \ Linked##NAME##s.Separator_Set(0, __T(" + ")); \ Linked##NAME##s.Write(MI.Get(Stream_Audio, StreamPos, Object+__T(" LinkedTo_" #NAME "_Pos"), Info_Text)); \ for (size_t NAME##Pos=0; NAME##Pos<Linked##NAME##s.size(); NAME##Pos++) \ Relations.push_back(relation(Stream+__T("_")+Object, Stream+__T("_" #NAME)+Linked##NAME##s[NAME##Pos], __T("[color=\"" COLOR "\"]"))); \ } #define OBJECT_END() \ } \ Temp+=NewLine(--Level)+__T("}"); \ } //--------------------------------------------------------------------------- #if defined(MEDIAINFO_AC4_YES) Ztring Export_Graph::Ac4_Graph(MediaInfo_Internal &MI, size_t StreamPos, size_t Level) { Ztring ToReturn; if (MI.Get(Stream_Audio, StreamPos, Audio_Format)!=__T("AC-4")) return ToReturn; vector<relation> Relations; Ztring Stream=MI.Get(Stream_Audio, StreamPos, __T("StreamKind"))+MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")); int8u Version=MI.Get(Stream_Audio, StreamPos, __T("Format_Version"), Info_Text).SubString(__T("Version "), __T("")).To_int8u(); bool Empty=true; Ztring Temp; Temp+=NewLine(Level++)+__T("subgraph cluster_")+Ztring().From_Number(StreamPos)+__T(" {"); Temp+=NewLine(Level)+__T("label=<<b>")+MI.Get(Stream_Audio, StreamPos, __T("StreamKind/String")); if (!MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")).empty()) Temp+=__T(" ")+MediaInfoLib::Config.Language_Get(__T(" Config_Text_NumberTag"))+MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")); Temp+=__T(" (")+MI.Get(Stream_Audio, StreamPos, Audio_Format)+__T(")</b>>"); OBJECT_START(Presentation, "NumberOfPresentations", "#000000", "#c5cae9", "#ffffff", "#303f9f") if (Version<2) OBJECT_LINK_TO(Substream, "#c5cae9") else OBJECT_LINK_TO(Group, "#c5cae9") OBJECT_END() if (Version>=2) { OBJECT_START(Group, "NumberOfGroups", "#000000", "#bbdefb", "#ffffff", "#1976d2") OBJECT_LINK_TO(Substream, "#bbdefb") OBJECT_END() } OBJECT_START(Substream, "NumberOfSubstreams", "#000000", "#b3e5fc", "#ffffff", "#0288d1") OBJECT_END() for (size_t Pos=0; Pos<Relations.size(); Pos++) Temp+=NewLine(Level)+Relations[Pos].Src+__T("--")+Relations[Pos].Dst+__T(" ")+Relations[Pos].Opts; Temp+=NewLine(--Level)+__T("}"); if (!Empty) ToReturn+=Temp; return ToReturn; } #endif //defined(MEDIAINFO_AC4_YES) //--------------------------------------------------------------------------- #if defined(MEDIAINFO_ADM_YES) Ztring Export_Graph::Adm_Graph(MediaInfo_Internal &MI, size_t StreamPos, size_t Level) { Ztring ToReturn; if (MI.Get(Stream_Audio, StreamPos, Audio_Format)!=__T("ADM")) return ToReturn; vector<relation> Relations; Ztring Stream=MI.Get(Stream_Audio, StreamPos, __T("StreamKind"))+MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")); bool Empty=true; Ztring Temp; Temp+=NewLine(Level++)+__T("subgraph cluster_")+Ztring().From_Number(StreamPos)+__T(" {"); Temp+=NewLine(Level)+__T("label=<<b>")+MI.Get(Stream_Audio, StreamPos, __T("StreamKind/String")); if (!MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")).empty()) Temp+=__T(" ")+MediaInfoLib::Config.Language_Get(__T(" Config_Text_NumberTag"))+MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")); Temp+=__T(" (")+MI.Get(Stream_Audio, StreamPos, Audio_Format)+__T(")</b>>"); OBJECT_START(Programme, "NumberOfProgrammes", "#000000", "#c5cae9", "#ffffff", "#303f9f") OBJECT_LINK_TO(Content, "#c5cae9") OBJECT_END() OBJECT_START(Content, "NumberOfContents", "#000000", "#bbdefb", "#ffffff", "#1976d2") OBJECT_LINK_TO(Object, "#bbdefb") OBJECT_END() OBJECT_START(Object, "NumberOfObjects", "#000000", "#b3e5fc", "#ffffff", "#0288d1") OBJECT_LINK_TO(PackFormat, "#b3e5fc") if (MediaInfoLib::Config.Graph_Adm_ShowTrackUIDs_Get()) OBJECT_LINK_TO(TrackUID, "#b3e5fc") OBJECT_END() if (MediaInfoLib::Config.Graph_Adm_ShowTrackUIDs_Get()) { OBJECT_START(TrackUID, "NumberOfTrackUIDs", "#000000", "#b2ebf2", "#ffffff", "#0097a7") OBJECT_LINK_TO(PackFormat, "#b2ebf2") OBJECT_LINK_TO(TrackFormat, "#b2ebf2") OBJECT_END() OBJECT_START(TrackFormat, "NumberOfTrackFormats", "#000000", "#b2dfdb", "#ffffff", "#00796b") OBJECT_LINK_TO(StreamFormat, "#b2dfdb") OBJECT_END() OBJECT_START(StreamFormat, "NumberOfStreamFormats", "#000000", "#c8e6c9", "#ffffff", "#388e3c") OBJECT_LINK_TO(ChannelFormat, "#c8e6c9") OBJECT_LINK_TO(PackFormat, "#c8e6c9") OBJECT_LINK_TO(TrackFormat, "#c8e6c9") OBJECT_END() } OBJECT_START(PackFormat, "NumberOfPackFormats", "#000000", "#dcedc8", "#ffffff", "#689f38") if (MediaInfoLib::Config.Graph_Adm_ShowChannelFormats_Get()) OBJECT_LINK_TO(ChannelFormat, "#dcedc8") OBJECT_END() if (MediaInfoLib::Config.Graph_Adm_ShowChannelFormats_Get()) { OBJECT_START(ChannelFormat, "NumberOfChannelFormats", "#000000", "#f0f4c3", "#ffffff", "#afb42b") OBJECT_END() } for (size_t Pos=0; Pos<Relations.size(); Pos++) Temp+=NewLine(Level)+Relations[Pos].Src+__T("--")+Relations[Pos].Dst+__T(" ")+Relations[Pos].Opts; Temp+=NewLine(--Level)+__T("}"); if (!Empty) ToReturn+=Temp; return ToReturn; } #endif //defined(MEDIAINFO_ADM_YES) //--------------------------------------------------------------------------- #if defined(MEDIAINFO_MPEGH3DA_YES) Ztring Export_Graph::Mpegh3da_Graph(MediaInfo_Internal &MI, size_t StreamPos, size_t Level) { Ztring ToReturn; if (MI.Get(Stream_Audio, StreamPos, Audio_Format)!=__T("MPEG-H 3D Audio")) return ToReturn; vector<relation> Relations; Ztring Stream=MI.Get(Stream_Audio, StreamPos, __T("StreamKind"))+MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")); bool Empty=true; Ztring Temp; Temp+=NewLine(Level++)+__T("subgraph cluster_")+Ztring().From_Number(StreamPos)+__T(" {"); Temp+=NewLine(Level)+__T("label=<<b>")+MI.Get(Stream_Audio, StreamPos, __T("StreamKind/String")); if (!MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")).empty()) Temp+=__T(" ")+MediaInfoLib::Config.Language_Get(__T(" Config_Text_NumberTag"))+MI.Get(Stream_Audio, StreamPos, __T("StreamKindPos")); Temp+=__T(" (")+MI.Get(Stream_Audio, StreamPos, Audio_Format)+__T(")</b>>"); OBJECT_START(SwitchGroup, "SwitchGroupCount", "#000000", "#c5cae9", "#ffffff", "#303f9f") OBJECT_LINK_TO(Group, "#c5cae9") OBJECT_END() OBJECT_START(Group, "GroupCount", "#000000", "#bbdefb", "#ffffff", "#1976d2") OBJECT_LINK_TO(SignalGroup, "#bbdefb") OBJECT_END() OBJECT_START(SignalGroup, "SignalGroupCount", "#000000", "#b3e5fc", "#ffffff", "#0288d1") OBJECT_END() for (size_t Pos=0; Pos<Relations.size(); Pos++) Temp+=NewLine(Level)+Relations[Pos].Src+__T("--")+Relations[Pos].Dst+__T(" ")+Relations[Pos].Opts; Temp+=NewLine(--Level)+__T("}"); if (!Empty) ToReturn+=Temp; return ToReturn; } #endif //defined(MEDIAINFO_MPEGH3DA_YES) //*************************************************************************** // Input //*************************************************************************** //--------------------------------------------------------------------------- Ztring Export_Graph::Transform(MediaInfo_Internal &MI, Export_Graph::graph Graph, Export_Graph::format Format) { Ztring ToReturn; size_t Level=1; bool ExpandSub_Old=MI.Config.File_ExpandSubs_Get(); MI.Config.File_ExpandSubs_Set(false); ToReturn+=__T("graph {"); ToReturn+=NewLine(Level)+__T("color=\"#1565c0\""); ToReturn+=NewLine(Level)+__T("fontcolor=\"#1565c0\""); ToReturn+=NewLine(Level)+__T("labelloc=t"); ToReturn+=NewLine(Level)+__T("label=<<b>")+XML_Encode(MI.Get(Stream_General, 0, General_FileNameExtension))+__T("</b>>"); for (size_t StreamPos=0; StreamPos<(size_t)MI.Count_Get(Stream_Audio); StreamPos++) { #if defined(MEDIAINFO_AC4_YES) if (Graph==Graph_All || Graph==Graph_Ac4) ToReturn+=Ac4_Graph(MI, StreamPos, Level); #endif //defined(MEDIAINFO_AC4_YES) #if defined(MEDIAINFO_ADM_YES) if (Graph==Graph_All || Graph==Graph_Adm) ToReturn+=Adm_Graph(MI, StreamPos, Level); #endif //defined(MEDIAINFO_ADM_YES) #if defined(MEDIAINFO_MPEGH3DA_YES) if (Graph==Graph_All || Graph==Graph_Mpegh3da) ToReturn+=Mpegh3da_Graph(MI, StreamPos, Level); #endif //defined(MEDIAINFO_MPEGH3DA_YES) } ToReturn+=__T("\n}"); #ifdef MEDIAINFO_GRAPHVIZ_YES if (Format==Format_Svg) ToReturn=Dot2Svg(ToReturn); #endif //MEDIAINFO_GRAPHVIZ_YES MI.Config.File_ExpandSubs_Set(ExpandSub_Old); return ToReturn; } //*************************************************************************** // //*************************************************************************** } //NameSpace #endif
37.572614
175
0.53153
[ "object", "shape", "vector", "transform", "3d" ]
5fd8911cae8abb63263b3be1d20a4a02d54def41
5,416
cpp
C++
src/lib/src/ffi.cpp
Techatrix/RGE
cff1d7fea06544ee0e3fed78099e2abd758b204a
[ "WTFPL" ]
null
null
null
src/lib/src/ffi.cpp
Techatrix/RGE
cff1d7fea06544ee0e3fed78099e2abd758b204a
[ "WTFPL" ]
2
2020-09-29T18:37:30.000Z
2020-12-29T11:16:52.000Z
src/lib/src/ffi.cpp
Techatrix/RGE
cff1d7fea06544ee0e3fed78099e2abd758b204a
[ "WTFPL" ]
null
null
null
#include "include/ffi.h" #ifndef M_PI #define M_PI (3.14159265358979323846) #endif #include <cmath> #include <random> #include <algorithm> using namespace rge; void generateStarNode(Graph &graph, size_t degree, size_t depth) { if (depth > 0) { uID nodeID = graph.ids.size() - 1; graph.connections[nodeID].reserve(degree); for (size_t i = 0; i < degree; i++) { uID newNodeID = graph.ids.size(); graph.ids.push_back(newNodeID); graph.positions.push_back(Vector2{0.0, 0.0}); graph.connections.push_back(std::vector<Connection>()); graph.connections[nodeID].push_back(Connection{newNodeID, 1.0}); generateStarNode(graph, degree, depth - 1); } } } std::unique_ptr<Graph> generateStarGraph(size_t degree, size_t depth) { std::unique_ptr<Graph> graph_ptr = std::make_unique<Graph>(); Graph &graph = *graph_ptr; size_t nodeCount = pow(degree, depth); graph.ids.reserve(nodeCount); graph.positions.reserve(nodeCount); graph.connections.reserve(nodeCount); graph.ids.push_back(0); graph.positions.push_back(Vector2{0.0, 0.0}); graph.connections.push_back(std::vector<Connection>()); generateStarNode(graph, degree, depth); return graph_ptr; } std::unique_ptr<rge::Graph> generateGridGraph(size_t width, size_t height, float distance) { std::unique_ptr<Graph> graph_ptr = std::make_unique<Graph>(); Graph &graph = *graph_ptr; size_t nodeCount = width * height; graph.ids = std::vector<uID>(nodeCount); graph.positions = std::vector<Vector2>(nodeCount); graph.connections = std::vector<std::vector<Connection>>(nodeCount); for (size_t i = 0; i < nodeCount; i++) graph.ids[i] = i; for (size_t y = 0; y < height; y++) for (size_t x = 0; x < width; x++) { auto index = y * width + x; graph.positions[index] = {x * distance, y * distance}; auto c = graph.connections[index]; if (x != 0) // Left c.push_back({(uID)(y * width + (x - 1)), distance}); if (x != (width - 1)) // Right c.push_back({(uID)(y * width + (x + 1)), distance}); if (y != 0) // Up c.push_back({(uID)((y - 1) * width + x), distance}); if (y != (height - 1)) // Down c.push_back({(uID)((y + 1) * width + x), distance}); } return graph_ptr; } std::unique_ptr<rge::Graph> generateGridGraphFromGrid(std::vector<std::vector<bool>>& grid, float distance) { std::unique_ptr<Graph> graph_ptr = std::make_unique<Graph>(); Graph &graph = *graph_ptr; size_t width = grid[0].size(); size_t height = grid.size(); { size_t maxNodeCount = width * height; graph.ids.reserve(maxNodeCount); graph.positions.reserve(maxNodeCount); graph.connections.reserve(maxNodeCount); } size_t i = 0; for (size_t y = 0; y < height; y++) for (size_t x = 0; x < width; x++) { if(grid[y][x]) { graph.ids.push_back(i++); graph.positions.push_back({x * distance, y * distance}); std::vector<Connection> c; if (x != 0 && grid[y][x-1]) // Left c.push_back({(uID)(y * width + (x - 1)), distance}); if (x != (width - 1) && grid[y][x+1]) // Right c.push_back({(uID)(y * width + (x + 1)), distance}); if (y != 0 && grid[y-1][x]) // Up c.push_back({(uID)((y - 1) * width + x), distance}); if (y != (height - 1) && grid[y+1][x]) // Down c.push_back({(uID)((y + 1) * width + x), distance}); graph.connections.push_back(std::move(c)); } } return graph_ptr; } std::unique_ptr<rge::Graph> generateHierarchicalGraph(size_t depth) { std::unique_ptr<Graph> graph_ptr = std::make_unique<Graph>(); return graph_ptr; } std::unique_ptr<Graph> generateRandomGraph(size_t nodeCount) { std::random_device rd; std::mt19937 gen(rd()); std::unique_ptr<Graph> graph_ptr = std::make_unique<Graph>(); Graph &graph = *graph_ptr; graph.ids = std::vector<uID>(nodeCount); graph.positions = std::vector<Vector2>(nodeCount); std::uniform_real_distribution<float> unFloatDist; float radius = sqrt(1000.0f * nodeCount / M_PI); for (size_t i = 0; i < nodeCount; i++) { float a = unFloatDist(gen) * 2 * M_PI; float r = radius * std::sqrt(unFloatDist(gen)); float x = r * std::cos(a); float y = r * std::sin(a); graph.ids[i] = i; graph.positions[i] = {x, y}; } float mean = nodeCount / 2.0; float dev = mean / 3.0f; std::normal_distribution<float> noIntDist(mean, dev); std::uniform_int_distribution<size_t> unIntDist(0, nodeCount - 1); graph.connections = std::vector<std::vector<Connection>>(nodeCount); std::vector<bool> isUsed(nodeCount); for (size_t i = 0; i < nodeCount; i++) { auto &origin = graph.positions[i]; size_t connectionCount = std::clamp(noIntDist(gen), 0.0f, (float)nodeCount) * 40.0f / nodeCount; connectionCount = std::min(connectionCount, nodeCount - 1); graph.connections[i] = std::vector<Connection>(connectionCount); std::fill(isUsed.begin(), isUsed.end(), false); isUsed[i] = true; size_t j = 0; while (j < connectionCount) { uID targetid = unIntDist(gen); if (!isUsed[targetid]) { auto &target = graph.positions[targetid]; float dx = (target.x - origin.x); float dy = (target.y - origin.y); float distance1 = std::sqrt(dx * dx + dy * dy); float distance2 = distance1 / (radius / 2); float max = 0.5f * exp(-0.5f * distance2 * distance2); if (unFloatDist(gen) < max) { isUsed[targetid] = true; graph.connections[i][j++] = {targetid, distance1}; } } } } return graph_ptr; }
26.419512
107
0.64291
[ "vector" ]
5fda9af7bb880366fd85eed728981a64e54772f2
2,438
cpp
C++
test/test_neural_network.cpp
kilasuelika/DynAutoDiff
1da36182e93f4893201389c5841941500586e3ea
[ "Unlicense" ]
1
2021-07-26T06:13:56.000Z
2021-07-26T06:13:56.000Z
test/test_neural_network.cpp
kilasuelika/DynAutoDiff
1da36182e93f4893201389c5841941500586e3ea
[ "Unlicense" ]
null
null
null
test/test_neural_network.cpp
kilasuelika/DynAutoDiff
1da36182e93f4893201389c5841941500586e3ea
[ "Unlicense" ]
null
null
null
#include "../DynAutoDiff/DynAutoDiff.hpp" #include <algorithm> #include <boost/test/tools/old/interface.hpp> #include <eigen3/Eigen/Core> #include <iostream> #include <vector> #define BOOST_TEST_MODULE NeuralNetwork_Test #include <boost/test/included/unit_test.hpp> #include <boost/test/tools/floating_point_comparison.hpp> #define TL 1e-10 using namespace Eigen; using namespace std; using namespace DynAutoDiff; BOOST_AUTO_TEST_SUITE(test) BOOST_AUTO_TEST_CASE(neuralnet_test) { struct NN { TMat<> X, y; shared_ptr<Var<>> A1, b1, A2, b2, A3, b3, xi, yi, y_pred, residual; GraphManager<> gm; NN(const TMat<> &X, const Eigen::VectorXd &y) : X(X), y(y), A1(pmat(3, 2)), b1(pmat(3, 1)), A2(pmat(3, 3)), b2(pmat(3, 1)), A3(pmat(1, 3)), b3(pmat(1, 1)), xi(cmat(2, 1)), yi(cmat(1, 1)) { auto x1 = A1 * xi + b1; auto y1 = sigmoid(x1); auto y2 = sigmoid(A2 * y1 + b2) + x1; y_pred = A3 * y2 + b3; residual = pow(yi - y_pred, 2); gm.set_root(residual); }; double loss(const double *parm, double *grad) { bind_seq(const_cast<double *>(parm), grad, {A1, b1, A2, b2, A3, b3}); double loss = 0; for (int i = 0; i < X.rows(); ++i) { *xi = X.row(i).transpose(); *yi = y.row(i); gm.run(false); loss += residual->v(); } return loss; }; }; // Create data matrix. TMat X(5, 2); X << 1, 10, 2, 20, 3, 30, 4, 40, 5, 50; TVecd y(5); y << 32, 64, 96, 128, 160; // y=2*x1+3*x2 // Generating parameter buffer and NN. TVecd parm_data(25); parm_data << 0.043984, -0.800526, 0.960126, -0.0287914, -0.520941, 0.635809, 0.584603, -0.443382, 0.224304, 0.97505, 0.666392, -0.911053, -0.824084, -0.498828, -0.230156, 0.2363, -0.781428, -0.136367, 0.263425, 0.841535, 0.920342, 0.65629, 0.848248, -0.748697, 0.21522; TVecd grad_data(25); NN net(X, y); auto loss = net.loss(parm_data.data(), grad_data.data()); BOOST_CHECK_CLOSE(loss, 92030.0564, 1e-2); BOOST_CHECK_CLOSE(net.A1->g(0, 0), -2953.05, 1e-2); BOOST_CHECK_CLOSE(net.b3->g(0, 0), -1226.47, 1e-2); } BOOST_AUTO_TEST_CASE(minus_test) {} BOOST_AUTO_TEST_CASE(times_test) {} BOOST_AUTO_TEST_CASE(division_test) {} BOOST_AUTO_TEST_SUITE_END()
31.25641
99
0.5726
[ "vector" ]
270314711a4ff9c9ced182a0ef338e5abdb80318
4,300
cpp
C++
kernel/fs/ext2/dir.cpp
ethan4984/rock
751b9af1009b622bedf384c1f80970b333c436c3
[ "BSD-2-Clause" ]
207
2020-05-27T21:57:28.000Z
2022-02-26T15:17:27.000Z
kernel/fs/ext2/dir.cpp
ethan4984/crepOS
751b9af1009b622bedf384c1f80970b333c436c3
[ "BSD-2-Clause" ]
3
2020-07-26T18:14:05.000Z
2020-12-09T05:32:07.000Z
kernel/fs/ext2/dir.cpp
ethan4984/rock
751b9af1009b622bedf384c1f80970b333c436c3
[ "BSD-2-Clause" ]
17
2020-07-05T19:08:48.000Z
2021-10-13T12:30:13.000Z
#include <fs/ext2/ext2.hpp> namespace ext2 { ssize_t dir::search_relative(inode *parent, lib::string path) { uint8_t *buffer = new uint8_t[parent->raw.size32l]; parent->read(0, parent->raw.size32l, buffer); for(uint32_t i = 0; i < parent->raw.size32l;) { raw_dir *dir_cur = reinterpret_cast<raw_dir*>(buffer + i); if(dir_cur->name_length == 0) { delete buffer; return -1; } lib::string name(reinterpret_cast<char*>(dir_cur->name), dir_cur->name_length); if(path == name) { if(dir_cur->inode == 0) { delete buffer; return -1; } raw = dir_cur; return 0; } i += dir_cur->entry_size; } delete buffer; return -1; } dir::dir(inode *parent_inode, lib::string path, bool find) : raw(NULL), parent_inode(parent_inode), path(path), exists(false) { lib::vector<lib::string> sub_paths = [&]() { size_t start = 0; size_t end = path.find_first('/'); lib::vector<lib::string> ret; while(end != lib::string::npos) { lib::string token = path.substr(start, end - start); if(!token.empty()) ret.push(token); start = end + 1; end = path.find_first('/', start); } lib::string token = path.substr(start, end); if(!token.empty()) ret.push(path.substr(start, end)); return ret; } (); if(find == true) { inode *save = new inode; *save = *parent_inode; for(size_t i = 0; i < sub_paths.size(); i++) { if(search_relative(save, sub_paths[i]) == -1) { exists = false; return; } *save = inode(parent_inode->parent, raw->inode); } delete save; } else { if(delete_relative(parent_inode, sub_paths.last()) == -1) { exists = false; return; } } exists = true; } dir::dir(inode *parent_inode, uint32_t new_inode, uint8_t type, char *name) : parent_inode(parent_inode), exists(false) { uint8_t *buffer = new uint8_t[parent_inode->raw.size32l]; parent_inode->read(0, parent_inode->raw.size32l, buffer); bool found = false; for(uint32_t i = 0; i < parent_inode->raw.size32l;) { raw_dir *dir_cur = reinterpret_cast<raw_dir*>(buffer + i); if(found) { dir_cur->inode = new_inode; dir_cur->type = type; dir_cur->name_length = strlen(name); dir_cur->entry_size = parent_inode->parent->block_size - i; memcpy8((uint8_t*)dir_cur->name, (uint8_t*)name, dir_cur->name_length); i += dir_cur->entry_size; dir_cur = (raw_dir*)(buffer + i); memset8((uint8_t*)dir_cur, 0, sizeof(raw_dir)); parent_inode->write(0, parent_inode->raw.size32l, buffer); exists = true; } uint32_t expected_size = align_up(sizeof(raw_dir) + dir_cur->name_length, 4); if(dir_cur->entry_size != expected_size) { dir_cur->entry_size = expected_size; i += expected_size; dir_cur->entry_size = expected_size; found = 1; continue; } i += dir_cur->entry_size; } } ssize_t dir::delete_relative(inode *parent, lib::string path) { uint8_t *buffer = new uint8_t[parent->raw.size32l]; parent->read(0, parent->raw.size32l, buffer); for(uint32_t i = 0; i < parent->raw.size32l;) { raw_dir *dir_cur = reinterpret_cast<raw_dir*>(buffer + i); lib::string name(reinterpret_cast<char*>(dir_cur->name), dir_cur->name_length); if(name == path) { memset8((uint8_t*)dir_cur->name, 0, dir_cur->name_length); inode dir_parent_inode(parent->parent, dir_cur->inode); dir_parent_inode.remove(); dir_cur->inode = 0; parent->write(0, parent->raw.size32l, buffer); return 0; } uint32_t expected_size = align_up(sizeof(raw_dir) + dir_cur->name_length, 4); if(dir_cur->entry_size != expected_size) break; i += dir_cur->entry_size; } return -1; } }
28.289474
127
0.550233
[ "vector" ]
dfd295d168402076ba8a9a1b892cda4207b15792
2,444
cpp
C++
Build/hosServer/User.cpp
Game-institute-1st-While-true/PLUXER
4ec9ad0ccb1bdf4b221afa135482a458f06205b1
[ "MIT" ]
1
2021-07-27T04:14:40.000Z
2021-07-27T04:14:40.000Z
Build/hosServer/User.cpp
Game-institute-1st-While-true/PLUXER
4ec9ad0ccb1bdf4b221afa135482a458f06205b1
[ "MIT" ]
null
null
null
Build/hosServer/User.cpp
Game-institute-1st-While-true/PLUXER
4ec9ad0ccb1bdf4b221afa135482a458f06205b1
[ "MIT" ]
1
2021-07-27T04:14:44.000Z
2021-07-27T04:14:44.000Z
#include "User.h" User::User() :uuid(-1), Ready(false), transform(nullptr), move(nullptr), network(nullptr) { } User::~User() { } void User::SetId(int id) { uuid = id; } int User::GetId() { return uuid; } void User::PositionUdpate(Vector3 pos, Rotator rot) { transform->SetPosition(pos); transform->SetRotation(rot); } void User::SetNetwork(Networkcomponent* network) { this->network = network; } void User::MakeMovePacket(hos::Packet::MOVE_DIR dir_toggle, bool dash) { if (network == nullptr) return; flatbuffers::FlatBufferBuilder builder; Vec3 foward(transform->GetForward().x, transform->GetForward().y, transform->GetForward().z); Vec3 rotation(transform->GetRotation().x, transform->GetRotation().y, transform->GetRotation().z); auto data = CreateMoveProtocol(builder, uuid, &foward, &rotation, dir_toggle, dash); builder.Finish(data); auto buffer = builder.GetBufferPointer(); PACKET pack; pack.head.size = PACKET_HEADER_SIZE; pack.head.protocol = static_cast<unsigned char>(HOS_PROTOCOL::MOVE); pack.Make(pack, pack.head, reinterpret_cast<char*>(buffer), builder.GetSize()); network->SendMsg(pack); builder.Clear(); } void User::MoveUpdate(const hos::Packet::MoveProtocol* move_protocol) { Vector3 foward(move_protocol->foward()->x(), move_protocol->foward()->y(), move_protocol->foward()->z()); Rotator rotation(move_protocol->rotation()->x(), move_protocol->rotation()->y(), move_protocol->rotation()->z()); if (move->IsDir(move_protocol->direction()) == true) { move->SetMoveData(move_protocol->direction(), false, move_protocol->dash(), foward, rotation); } else { move->SetMoveData(move_protocol->direction(), true, move_protocol->dash(), foward, rotation); } } void User::Awake() { network = m_GameObject->GetComponent<Networkcomponent>(); if (network == nullptr) { Logger::GetIns()->LogConsole(L"data", L"network component is null"); } transform = m_GameObject->GetComponent<Transform>(); if (transform == nullptr) { Logger::GetIns()->LogConsole(L"data", L"transform component is null"); } move = m_GameObject->GetComponent<PlayerBehaivor>(); if (move == nullptr) { Logger::GetIns()->LogConsole(L"data", L"move component is null"); } m_GameObject->GetComponent<Transform>()->Reset(); m_GameObject->GetComponent<Transform>()->SetPosition(Vector3(uuid * -2, 0, 0)); Ready = false; } void User::Start() { } void User::OnEnable() { } void User::OnDisable() { }
23.27619
114
0.70581
[ "transform" ]
dfd668f35679c83308791e8ab46aebc456d496e4
16,742
cc
C++
sstmac/hardware/snappr/snappr_outport.cc
jjwilke/sst-macro
d5139c0e2e6c0055bd2ef6dc9ac565a6ec1fd4d9
[ "BSD-Source-Code" ]
null
null
null
sstmac/hardware/snappr/snappr_outport.cc
jjwilke/sst-macro
d5139c0e2e6c0055bd2ef6dc9ac565a6ec1fd4d9
[ "BSD-Source-Code" ]
null
null
null
sstmac/hardware/snappr/snappr_outport.cc
jjwilke/sst-macro
d5139c0e2e6c0055bd2ef6dc9ac565a6ec1fd4d9
[ "BSD-Source-Code" ]
null
null
null
#ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #include <sstmac/hardware/snappr/snappr_outport.h> #include <sstmac/common/stats/ftq.h> #include <sstmac/common/event_scheduler.h> #include <sstmac/common/event_callback.h> #include <sstmac/common/stats/ftq.h> #include <sstmac/common/stats/ftq_tag.h> #include <queue> #define pkt_debug(...) \ debug_printf(sprockit::dbg::snappr, "snappr port %s:%d %s", \ portName_.c_str(), number_, sprockit::printf(__VA_ARGS__).c_str()) #define port_debug(...) \ debug_printf(sprockit::dbg::snappr, __VA_ARGS__) namespace sstmac { namespace hw { SnapprOutPort::SnapprOutPort(SST::Params& params, const std::string &arb, const std::string& subId, const std::string& portName, int number, TimeDelta byt_delay, bool congestion, bool flow_control, Component* parent) : arbitration_scheduled(false), byte_delay(byt_delay), state_ftq(nullptr), queue_depth_ftq(nullptr), inports(nullptr), parent_(parent), flow_control_(flow_control), congestion_(congestion), portName_(subId), number_(number), notifier_(nullptr) { arb_ = sprockit::create<SnapprPortArbitrator>("macro", arb, byte_delay, params); xmit_active = parent->registerStatistic<uint64_t>(params, "xmit_active", subId); xmit_idle = parent->registerStatistic<uint64_t>(params, "xmit_idle", subId); xmit_stall = parent->registerStatistic<uint64_t>(params, "xmit_stall", subId); bytes_sent = parent->registerStatistic<uint64_t>(params, "bytes_sent", subId); #if !SSTMAC_INTEGRATED_SST_CORE state_ftq = dynamic_cast<FTQCalendar*>( parent->registerMultiStatistic<int,uint64_t,uint64_t>(params, "state", subId)); queue_depth_ftq = dynamic_cast<FTQCalendar*>( parent->registerMultiStatistic<int,uint64_t,uint64_t>(params, "queue_depth", subId)); #endif ftq_idle_state = FTQTag::allocateCategoryId("idle:" + portName); ftq_active_state = FTQTag::allocateCategoryId("active:" + portName); ftq_stalled_state = FTQTag::allocateCategoryId("stalled:" + portName); } void SnapprOutPort::handle(Event *ev) { handleCredit(static_cast<SnapprCredit*>(ev)); } std::string SnapprOutPort::toString() const { return sprockit::printf("SNAPPR OutPort %d", number_); } void SnapprOutPort::handleCredit(SnapprCredit* credit) { addCredits(credit->virtualLane(), credit->numBytes()); pkt_debug("crediting port=%d vl=%d with %" PRIu32" credits", number_, credit->virtualLane(), credit->numBytes()); delete credit; if (!arbitration_scheduled && !empty()){ requestArbitration(); } } void SnapprOutPort::send(SnapprPacket* pkt, Timestamp now) { #if SSTMAC_SANITY_CHECK if (next_free > now){ spkt_abort_printf("Internal error: port %s:%d sending packet at time %llu < %llu", portName_.c_str(), number_, now.time.ticks(), next_free.time.ticks()); } #endif if (!stall_start.empty()){ TimeDelta stall_time = now - stall_start; xmit_stall->addData(stall_time.ticks()); #if !SSTMAC_INTEGRATED_SST_CORE if (state_ftq){ state_ftq->addData(ftq_stalled_state, stall_start.time.ticks(), stall_time.ticks()); } #endif if (stall_start > next_free){ //we also have idle time TimeDelta idle_time = stall_start -next_free; xmit_idle->addData(idle_time.ticks()); #if !SSTMAC_INTEGRATED_SST_CORE if (state_ftq){ state_ftq->addData(ftq_idle_state, next_free.time.ticks(), idle_time.ticks()); } #endif } stall_start = Timestamp(); } else if (now > next_free){ TimeDelta idle_time = now - next_free; xmit_idle->addData(idle_time.ticks()); #if !SSTMAC_INTEGRATED_SST_CORE if (state_ftq){ state_ftq->addData(ftq_idle_state, next_free.time.ticks(), idle_time.ticks()); } #endif } TimeDelta time_to_send = pkt->numBytes() * byte_delay; bytes_sent->addData(pkt->numBytes()); xmit_active->addData(time_to_send.ticks()); #if !SSTMAC_INTEGRATED_SST_CORE if (state_ftq){ state_ftq->addData(ftq_active_state, now.time.ticks(), time_to_send.ticks()); } #endif next_free = now + time_to_send; pkt->setTimeToSend(time_to_send); pkt->accumulateCongestionDelay(now); #if SSTMAC_SANITY_CHECK if (!link){ spkt_abort_printf("trying send on null link going to %d: %s", pkt->toaddr(), pkt->toString().c_str()); } #endif link->send(pkt); if (flow_control_ && inports){ auto& inport = inports[pkt->inport()]; auto* credit = new SnapprCredit(pkt->byteLength(), pkt->inputVirtualLane(), inport.src_outport); pkt_debug("sending credit to port=%d on vl=%d at t=%8.4e: %s", inport.src_outport, pkt->inputVirtualLane(), next_free.sec(), pkt->toString().c_str()); inport.link->send(time_to_send, credit); } else { //immediately add the credits back - we don't worry about credits here addCredits(pkt->virtualLane(), pkt->byteLength()); } if (notifier_ && pkt->isTail()){ notifier_->notify(next_free, pkt); } pkt_debug("packet leaving port=%d vl=%d at t=%8.4e: %s", number_, pkt->virtualLane(), next_free.sec(), pkt->toString().c_str()); if (ready()){ scheduleArbitration(); } } void SnapprOutPort::scheduleArbitration() { #if SSTMAC_SANITY_CHECK if (arbitration_scheduled){ spkt_abort_printf("arbitration already scheduled on port %s:%d", portName_.c_str(), number_); } if (queueLength() == 0){ spkt_abort_printf("scheduling arbitration on port with nothing queued"); } #endif pkt_debug("scheduling arbitrate from port %d at t=%8.4e with %d queued", number_, next_free.sec(), queueLength()); //schedule this port to pull another packet auto* ev = newCallback(this, &SnapprOutPort::arbitrate); parent_->sendExecutionEvent(next_free, ev); arbitration_scheduled = true; } void SnapprOutPort::requestArbitration() { #if SSTMAC_SANITY_CHECK if (empty()){ spkt_abort_printf("SnapprSwitch::arbitrate: incorrectly requesting arbitrate from empty port %s:%d", portName_.c_str(), number_); } if (arbitration_scheduled){ spkt_abort_printf("SnapprSwitch::arbitrate: incorrectly requesting arbitrate from port %s:%d with arbitrate scheduled already", portName_.c_str(), number_); } #endif Timestamp now_ = parent_->now(); if (next_free > now_){ scheduleArbitration(); } else { arbitrate(); } } void SnapprOutPort::arbitrate() { #if SSTMAC_SANITY_CHECK if (empty()){ spkt_abort_printf("SnapprOutPort::arbitrate: incorrectly arbitrate from empty port %d", number_); } if (next_free > parent_->now()){ spkt_abort_printf("SnapprOutPort::arbitrate: arbitrating before port %d is free to send", number_); } #endif arbitration_scheduled = false; if (ready()){ logQueueDepth(); pkt_debug("arbitrating packet from port %d with %d queued", number_, queueLength()); SnapprPacket* pkt = popReady(); send(pkt, parent_->now()); } else { if (stall_start.empty()){ stall_start = parent_->now(); } pkt_debug("insufficient credits to send on port %d with %d queued", number_, queueLength()); } } void SnapprOutPort::logQueueDepth() { #if !SSTMAC_INTEGRATED_SST_CORE if (queue_depth_ftq){ Timestamp now = parent_->now(); TimeDelta dt = now - last_queue_depth_collection; queue_depth_ftq->addData(queueLength(), last_queue_depth_collection.time.ticks(), dt.ticks()); last_queue_depth_collection = now; } #endif } void SnapprOutPort::tryToSendPacket(SnapprPacket* pkt) { pkt_debug("trying to send payload %s on inport %d:%d going to port %d:%d:%d", pkt->toString().c_str(), pkt->inport(), pkt->inputVirtualLane(), pkt->nextPort(), pkt->virtualLane(), pkt->deadlockVC()); Timestamp now = parent_->now(); pkt->setArrival(now); if (!congestion_){ TimeDelta time_to_send = pkt->numBytes() * byte_delay; pkt->setTimeToSend(time_to_send); link->send(pkt); } else { logQueueDepth(); queue(pkt); pkt_debug("incoming packet on port=%d vl=%d -> queue=%d", number_, pkt->virtualLane(), queueLength()); if (!arbitration_scheduled){ requestArbitration(); } } } struct FifoPortArbitrator : public SnapprPortArbitrator { struct VirtualLane { uint32_t credits; int occupancy; std::queue<SnapprPacket*> pending; VirtualLane() : occupancy(0){} }; public: SPKT_REGISTER_DERIVED( SnapprPortArbitrator, FifoPortArbitrator, "macro", "fifo", "implements a FIFO strategy for queuing packets") FifoPortArbitrator(TimeDelta /*link_byte_delay*/, SST::Params& /*params*/){} void insert(uint64_t /*cycle*/, SnapprPacket *pkt) override { VirtualLane& vl = vls_[pkt->virtualLane()]; vl.occupancy += 1; if (vl.credits >= pkt->numBytes()){ port_debug("FIFO %p VL %d queueing with %u credits - packet %s", this, pkt->virtualLane(), vl.credits, pkt->toString().c_str()); vl.credits -= pkt->numBytes(); port_queue_.push(pkt); } else { vl.pending.push(pkt); port_debug("FIFO %p VL %d stalling with %u credits - packet %s", this, pkt->virtualLane(), vl.credits, pkt->toString().c_str()); } } int queueLength(int vl) const override { auto& v = vls_[vl]; return v.pending.size(); } void scale(double factor) override { for (VirtualLane& vl : vls_){ vl.credits *= factor; } } void setVirtualLanes(int num_vl, uint32_t total_credits) override { uint32_t credits_per_vl = total_credits / num_vl; vls_.resize(num_vl); for (VirtualLane& vl : vls_){ vl.credits = credits_per_vl; } } void addCredits(int vl, uint32_t credits) override { VirtualLane& v = vls_[vl]; v.credits += credits; port_debug("FIFO %p VL %d adding credits up to %u", this, vl, v.credits); while (!v.pending.empty() && v.pending.front()->numBytes() <= v.credits){ SnapprPacket* pkt = v.pending.front(); port_debug("FIFO %p VL %d now has enough credits to send packet %s", this, pkt->virtualLane(), pkt->toString().c_str()); port_queue_.push(pkt); v.credits -= pkt->numBytes(); v.pending.pop(); } } SnapprPacket* pop(uint64_t /*cycle*/) override { SnapprPacket* pkt = port_queue_.front(); port_debug("FIFO %p VL %d popping packet", this, pkt->virtualLane()); port_queue_.pop(); return pkt; } bool empty() const override { return port_queue_.empty(); } private: std::vector<VirtualLane> vls_; std::queue<SnapprPacket*> port_queue_; }; struct ScatterPortArbitrator : public SnapprPortArbitrator { struct VirtualLane { uint32_t credits; std::queue<SnapprPacket*> pending; }; public: ScatterPortArbitrator(SST::Params& /*params*/){ //nothing to do } void insert(uint64_t /*cycle*/, SnapprPacket *pkt) override { VirtualLane& vl = vls_[pkt->virtualLane()]; if (vl.credits >= pkt->numBytes()){ port_queue_.emplace(pkt); vl.credits -= pkt->numBytes(); } else { vl.pending.push(pkt); } } SnapprPacket* pop(uint64_t /*cycle*/) override { SnapprPacket* pkt = port_queue_.top(); port_queue_.pop(); return pkt; } void addCredits(int vl, uint32_t credits) override { VirtualLane& v = vls_[vl]; v.credits += credits; while (!v.pending.empty() && v.pending.front()->numBytes() <= v.credits){ SnapprPacket* pkt = v.pending.front(); v.pending.pop(); port_queue_.emplace(pkt); v.credits -= pkt->numBytes(); } } bool empty() const override { return port_queue_.empty(); } private: struct priority_is_lower { bool operator()(const SnapprPacket* l, const SnapprPacket* r) const { //prioritize packets with lower offsets return l->offset() > r->offset(); } }; std::vector<VirtualLane> vls_; std::priority_queue<SnapprPacket*, std::vector<SnapprPacket*>, priority_is_lower> port_queue_; }; struct WRR_PortArbitrator : public SnapprPortArbitrator { public: SPKT_REGISTER_DERIVED( SnapprPortArbitrator, WRR_PortArbitrator, "macro", "wrr", "implements a WRR strategy for queuing packets with bandwidth sharing weights") WRR_PortArbitrator(TimeDelta link_byte_delay, SST::Params& params){ std::vector<double> weights; params.find_array("vl_weights", weights); // Set W = BW weight for VL // Set D = max delay until send starts // Set T = time to send // T / (T + D) = W // T = W*T + W*D // (1-W)*T = W*D // D = (1-W) * T / W vls_.resize(weights.size()); for (int vl=0; vl < weights.size(); ++vl){ VirtualLane& v = vls_[vl]; double weight = weights[vl]; double weight_factor = (1 - weight) / weight; v.max_byte_delay = weight_factor * link_byte_delay.ticks(); v.blocked_deadline = 0; } } void setVirtualLanes(int num_vl, uint32_t total_credits) override { if (num_vl != int(vls_.size())){ spkt_abort_printf("WRR arbitrator got %d VLs, but weight vector of size %d", num_vl, int(vls_.size())); } uint32_t credits_per = total_credits / num_vl; for (int vl=0; vl < num_vl; ++vl){ vls_[vl].credits = credits_per; } } int queueLength(int vl) const override { return vls_[vl].pending.size(); } void scale(double factor) override { for (VirtualLane& vl : vls_){ vl.credits *= factor; //if bandwidth is scaled up, shrink my max delay vl.max_byte_delay /= factor; } } void insert(uint64_t cycle, SnapprPacket *pkt) override { int vl = pkt->virtualLane(); VirtualLane& v = vls_[vl]; if (v.pending.empty()){ //always enough credits when empty - better be uint64_t deadline = cycle + pkt->numBytes() * v.max_byte_delay; port_debug("WRR %p VL %d is empty and emplacing at deadline=%" PRIu64 " on cycle=%" PRIu64 ": %s", this, vl, deadline, cycle, pkt->toString().c_str()); port_queue_.emplace(deadline, vl); } vls_[vl].pending.push(pkt); } SnapprPacket* pop(uint64_t cycle) override { #if SSTMAC_SANITY_CHECK if (port_queue_.empty()){ spkt_abort_printf("pulling snappr packet from empty queue"); } #endif int next_vl = port_queue_.top().second; port_queue_.pop(); VirtualLane& vl = vls_[next_vl]; SnapprPacket* pkt = vl.pending.front(); vl.pending.pop(); vl.credits -= pkt->numBytes(); port_debug("WRR %p VL %d sending on cycle=%" PRIu64 ": %s", this, next_vl, cycle, pkt->toString().c_str()); if (!vl.pending.empty()){ SnapprPacket* pkt = vl.pending.front(); uint64_t deadline = cycle + pkt->numBytes() * vl.max_byte_delay; if (vl.credits >= pkt->numBytes()){ port_debug("WRR %p VL %d has enough credits=%u to emplace at deadline=%" PRIu64 " on cycle=%" PRIu64 ": %s", this, next_vl, deadline, cycle, vl.credits, pkt->toString().c_str()); port_queue_.emplace(deadline, next_vl); } else { port_debug("WRR %p VL %d has insufficient credits=%u for deadline=%" PRIu64 " on cycle=%" PRIu64 ": %s", this, next_vl, vl.credits, deadline, cycle, pkt->toString().c_str(), deadline); vl.blocked_deadline = deadline; } } return pkt; } void addCredits(int vl, uint32_t credits) override { VirtualLane& v = vls_[vl]; v.credits += credits; if (v.blocked_deadline){ SnapprPacket* pkt = v.pending.front(); if (pkt->numBytes() <= v.credits){ port_debug("WRR %p VL %d now has enough credits to emplace %s for deadline %" PRIu64, this, vl, pkt->toString().c_str(), v.blocked_deadline); port_queue_.emplace(v.blocked_deadline, vl); v.blocked_deadline = 0; } } } bool empty() const override { return port_queue_.empty(); } private: struct VirtualLane { std::queue<SnapprPacket*> pending; uint64_t max_byte_delay; uint32_t credits; uint64_t blocked_deadline; }; struct priority_is_lower { bool operator()(const std::pair<uint64_t,int>& l, const std::pair<uint64_t,int>& r) const { return l.first > r.first; } }; std::priority_queue<std::pair<uint64_t,int>, std::vector<std::pair<uint64_t,int>>, priority_is_lower> port_queue_; std::vector<VirtualLane> vls_; }; } }
30.220217
131
0.648728
[ "vector" ]
dfd959e489f9fd7ee51ebc3c41f678c289cc5e3a
596
cpp
C++
c-plus-plus-yellow-belt/week_4/iterator_introduction/vector_part/vector_part/vector_part.cpp
codearchive/coursera-c-plus-plus-specialization
c599126e510182e5e6a8c5f29a31f1eecda8b8a5
[ "Apache-2.0" ]
null
null
null
c-plus-plus-yellow-belt/week_4/iterator_introduction/vector_part/vector_part/vector_part.cpp
codearchive/coursera-c-plus-plus-specialization
c599126e510182e5e6a8c5f29a31f1eecda8b8a5
[ "Apache-2.0" ]
null
null
null
c-plus-plus-yellow-belt/week_4/iterator_introduction/vector_part/vector_part/vector_part.cpp
codearchive/coursera-c-plus-plus-specialization
c599126e510182e5e6a8c5f29a31f1eecda8b8a5
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> using namespace std; void PrintVectorPart(const vector<int>& numbers); void PrintVectorPart(const vector<int>& numbers) { auto it = find_if(begin(numbers), end(numbers), [](int x) { return x < 0; }); while (it != begin(numbers)) { --it; cout << *it << ' '; } } int main() { PrintVectorPart({ 6, 1, 8, -5, 4 }); cout << endl; PrintVectorPart({ -6, 1, 8, -5, 4 }); // ничего не выведется cout << endl; PrintVectorPart({ 6, 1, 8, 5, 4 }); cout << endl; return 0; }
19.866667
65
0.553691
[ "vector" ]
dfd97c1a27ea9824a83ffc2fd50b7b0f94031c52
2,111
hpp
C++
fileid/document/excel/ExcelExtensionInfo.hpp
DBHeise/fileid
3e3bacf859445020999d0fc30301ac86973c3737
[ "MIT" ]
13
2016-03-13T17:57:46.000Z
2021-12-21T12:11:41.000Z
fileid/document/excel/ExcelExtensionInfo.hpp
DBHeise/fileid
3e3bacf859445020999d0fc30301ac86973c3737
[ "MIT" ]
9
2016-04-07T13:07:58.000Z
2020-05-30T13:31:59.000Z
fileid/document/excel/ExcelExtensionInfo.hpp
DBHeise/fileid
3e3bacf859445020999d0fc30301ac86973c3737
[ "MIT" ]
5
2017-04-20T14:47:55.000Z
2021-03-08T03:27:17.000Z
#pragma once #include <map> #include "../../oless/pole.h" #include "../../common.hpp" #include "../../oless/OleCommon.hpp" #include "MSExcel.common.hpp" #include "SubStream.hpp" #include "Sheet.hpp" #include "records/Record.Parser.hpp" #include "ParseEngine.hpp" namespace oless { namespace excel { class ExcelExtensionInfo : public OLESSExtensionInfo { public: //Global SubStream SubStream* global; std::vector<Sheet> sheets; ExcelExtensionInfo() : OLESSExtensionInfo() { this->Extension = "xls"; this->Name = "Microsoft Office Excel Workbook"; } virtual std::string ToJson() const override { std::ostringstream str; str << "{"; str << this->buildBaseJson(); if (this->global != nullptr) { str << ", \"globals\": { " << this->global->ToJson() << "}"; } if (this->sheets.size() > 0) { str << ", \"sheets\": ["; for (std::vector<Sheet>::const_iterator i = this->sheets.begin(); i != this->sheets.end(); i++) { if (i != this->sheets.begin()) str << ","; str << (*i).ToJson(); } str << "]"; } str << "}"; return str.str(); } virtual std::string ToXml() const override { std::ostringstream str; str << "<item>"; str << this->buildBaseXml(); if (this->global != nullptr) { str << "<globals>"; str << this->global->ToXml(); str << "</globals>"; } if (this->sheets.size() > 0) { str << "<sheets>"; for (std::vector<Sheet>::const_iterator i = this->sheets.begin(); i != this->sheets.end(); i++) { str << (*i).ToXml(); } str << "</sheets>"; } str << "</item>"; return str.str(); } }; void Detailer(common::ExtensionInfo*& e, const std::string filename, const POLE::Storage* storage, const std::wstring streamName, const std::vector<uint8_t> stream) { auto p = new ParseEngine(); p->ParseStream(stream); auto xl = new ExcelExtensionInfo(); xl->global = p->global; xl->sheets = p->sheets; xl->Version = p->Version; xl->VersionName = p->VersionName; xl->SubType = p->SubType; e = xl; } } }
26.061728
168
0.572241
[ "vector" ]
dfdaff114b65dad1a483b6b78a29dd396d538dad
4,857
cpp
C++
src/tree.cpp
sproberts92/neuron-model
3c11b3749da876f4008131c977cfa22158825b74
[ "MIT" ]
null
null
null
src/tree.cpp
sproberts92/neuron-model
3c11b3749da876f4008131c977cfa22158825b74
[ "MIT" ]
null
null
null
src/tree.cpp
sproberts92/neuron-model
3c11b3749da876f4008131c977cfa22158825b74
[ "MIT" ]
null
null
null
#include "tree.hpp" Tree::Tree(std::valarray<std::pair<double, double>> b, int cr, std::vector<Node*> &a, std::vector<Synapse*> &s) : bounds(b), all(&a), all_s(&s) { root = new Neuron(r_vec(bounds), cr); all->push_back(root); // Generate and normalise a vector in a random direction along which the // axon will be grown. grow_dir = r_vec(unit_box(bounds.size())); normalise(grow_dir); } Neuron *Tree::get_root(void){ return root; } std::valarray<double> Tree::get_grow_dir(void){ return grow_dir; } double Tree::find_shortest(const Tree &target, Node **shortest_ptr, std::valarray<double> &vec_r, user_config_t &cf) { Node *list_ptr = target.root; double shortest_r = std::numeric_limits<double>::infinity(); // Move along the axon originating from target.root while(!list_ptr->get_next().empty()) { // Because of the periodic boundary conditions, if a particular target // node is more than box_l/2 away from the root of this tree we need to // wrap around and get distance as if it was wrapped around. This is // achieved by creating a temp node, shifting it into the adjacent cell // and then measuring the distance to that instead. auto temp = list_ptr->get_pos() - root->get_pos(); for (int i = 0; i < size(temp); ++i) { auto box_l = cf.bounds[2*i + 1] - cf.bounds[2 * i]; // Impose periodic boundary conditions. Isn't it beautiful? temp[i] -= ((temp[i] > box_l/2) - (temp[i] < -box_l/2)) * box_l; } double r = (temp * temp).sum(); // Compare r^2 values, don't need to waste time with sqrt. if(r < shortest_r) { shortest_r = r; *shortest_ptr = list_ptr; vec_r = temp; } list_ptr = list_ptr->get_next().front(); } return sqrt(shortest_r); } std::valarray<double> Tree::r_vec(std::valarray<std::pair<double, double>> box) { std::valarray<double> vec(box.size()); static rand_gen<double> r_gen(0, 1); // Generate a random number for each element of the vector then scale and // translate appropriately such that if lies in the box. for (int i = 0; i < vec.size(); ++i) vec[i] = (box[i].second - box[i].first) * (r_gen.get_rnum() + box[i].first); return vec; } std::valarray<std::pair<double, double>> Tree::unit_box(size_t d) { // To do: replace this entirely with a compile-time template. std::valarray<std::pair<double, double>> box(d); box = std::make_pair(-1, 1); return box; } void Tree::normalise(std::valarray<double> &v) { v /= sqrt((v * v).sum()); } Node *Tree::add_node(Node *add_at, std::valarray<double> rel_pos) { // The new position is calculated relative to the position of add_at, if // it lies outside the system box then it needs to be wrapped to the other // side of the box. auto new_pos = rel_pos + add_at->get_pos(); impose_bc(new_pos); Node *new_axon = new Node(new_pos); add_at->push_next(*new_axon); all->push_back(new_axon); return new_axon; } Synapse *Tree::add_synapse(Node *add_at, std::valarray<double> rel_pos, int t) { // To do: The functionality here is so close to Tree::add_node, it should // be possible to combine them to reduce duplication. auto new_pos = rel_pos + add_at->get_pos(); impose_bc(new_pos); Synapse *new_axon = new Synapse(new_pos, t); add_at->push_next(*new_axon); all->push_back(new_axon); all_s->push_back(new_axon); return new_axon; } void Tree::grow_axon(double l) { Node *list_ptr = root; while(!list_ptr->get_next().empty()) list_ptr = list_ptr->get_next().front(); add_node(list_ptr, l * grow_dir); } void Tree::impose_bc(std::valarray<double> &p) { for (int i = 0; i < p.size(); i++) { if(p[i] < bounds[i].first) p[i] += (bounds[i].second - bounds[i].first); if(p[i] > bounds[i].second) p[i] -= (bounds[i].second - bounds[i].first); } } Node *Tree::grow_branch(Tree &target, user_config_t &cf) { // Encapsulates the process of selecting the point to grow the branch // (dendrite) to, deciding whether a branch will actually be grown (with // Gaussian probability) and then growing the branch. Node *shortest = nullptr; std::valarray<double> vec_r; double r = find_shortest(target, &shortest, vec_r, cf); // Decide whether the branch will be created, short circuits to avoid // actually drawing the random variable and calculating the Gaussian if // it's not necessary. static rand_gen<double> r_gen = rand_gen<double>(0, 1); if(r != 0 && cf.link_fwhm_param != 0 && r_gen.get_rnum() < gaussian(r, cf.link_fwhm_param)) { vec_r = cf.schwann_l * vec_r / r; Synapse *synapse = add_synapse(shortest, vec_r, cf.target_age); Node *dendrite_head = synapse; for (int i = 0; i < (int)(r / cf.schwann_l - 1); ++i) dendrite_head = add_node(dendrite_head, vec_r); dendrite_head->push_next(*root); return dendrite_head; } else return nullptr; } double Tree::gaussian(double x, double c) { return exp(-(x * x)/(2 * c * c)); }
28.075145
79
0.680461
[ "vector" ]
dfded8252cad311424063624e7cda2dcd2211047
440
cpp
C++
simple-callables-func.cpp
kobi-ca/lambda-9-2020
8f06dafc29e15d15bccf4e1667fd9bc2dc106417
[ "MIT" ]
null
null
null
simple-callables-func.cpp
kobi-ca/lambda-9-2020
8f06dafc29e15d15bccf4e1667fd9bc2dc106417
[ "MIT" ]
null
null
null
simple-callables-func.cpp
kobi-ca/lambda-9-2020
8f06dafc29e15d15bccf4e1667fd9bc2dc106417
[ "MIT" ]
null
null
null
#include <type_traits> // callable object void f(){} int g() { return 0;} typedef int (*func_ptr) (int, char); // or in modern C++ using func_ptr1 = int (*) (int, char); // or even more using func_ptr2 = std::add_pointer_t<int (int, char)>; int my_func(int, char) { return 0; } int main() { func_ptr2 funcPtr2 = my_func; auto ret = funcPtr2(3, 'a'); func_ptr2 funcPtr3 = &my_func; ret = funcPtr3(7, 'b'); return 0; }
20.952381
54
0.622727
[ "object" ]
dfe52b4bc5ebe54498780eb6fbc9c4e402a3b93b
3,285
cpp
C++
Source/ModelData.cpp
chuckeles/metal-pacman
78f20fff1e2f578932014e349a5e81b1f6eb7d7c
[ "MIT" ]
1
2019-05-10T06:37:54.000Z
2019-05-10T06:37:54.000Z
Source/ModelData.cpp
chuckeles/metal-pacman
78f20fff1e2f578932014e349a5e81b1f6eb7d7c
[ "MIT" ]
null
null
null
Source/ModelData.cpp
chuckeles/metal-pacman
78f20fff1e2f578932014e349a5e81b1f6eb7d7c
[ "MIT" ]
null
null
null
#include "ModelData.hpp" #include <fstream> #include "../Libraries/tinyply.h" #include "Error.hpp" void ModelData::Load(std::string path) { std::ifstream file(path); if (!file.is_open()) { THROW_ERROR(std::string("Could not find a model file: ") + path); } tinyply::PlyFile plyFile(file); std::vector<unsigned char> rawColors; plyFile.request_properties_from_element("vertex", { "x", "y", "z" }, mVertices); plyFile.request_properties_from_element("vertex", { "nx", "ny", "nz" }, mNormals); plyFile.request_properties_from_element("vertex", { "red", "green", "blue" }, rawColors); plyFile.request_properties_from_element("vertex", { "s", "t" }, mTexCoords); plyFile.request_properties_from_element("face", { "vertex_indices" }, mIndices, 3); plyFile.read(file); // normalize or create colors if (rawColors.size() > 0) { // convert from [0-256] to [0-1] which is what OpenGL expects mColors.reserve(rawColors.size()); for (auto c : rawColors) { mColors.push_back((float) c / 255); } } else { mColors.resize(mVertices.size(), 1); } // calculate tangent mTangents.reserve(mVertices.size()); for (auto i = 0; i < mIndices.size() / 3; ++i) { // indices auto i1 = mIndices[i * 3 + 0]; auto i2 = mIndices[i * 3 + 1]; auto i3 = mIndices[i * 3 + 2]; // vertex positions auto v1x = mVertices[i1 * 3 + 0]; auto v1y = mVertices[i1 * 3 + 1]; auto v1z = mVertices[i1 * 3 + 2]; auto v2x = mVertices[i2 * 3 + 0]; auto v2y = mVertices[i2 * 3 + 1]; auto v2z = mVertices[i2 * 3 + 2]; auto v3x = mVertices[i3 * 3 + 0]; auto v3y = mVertices[i3 * 3 + 1]; auto v3z = mVertices[i3 * 3 + 2]; // vertex tex coords auto v1u = mTexCoords[i1 * 2 + 0]; auto v1v = mTexCoords[i1 * 2 + 1]; auto v2u = mTexCoords[i2 * 2 + 0]; auto v2v = mTexCoords[i2 * 2 + 1]; auto v3u = mTexCoords[i3 * 2 + 0]; auto v3v = mTexCoords[i3 * 2 + 1]; float x1 = v2x - v1x; float x2 = v3x - v1x; float y1 = v2y - v1y; float y2 = v3y - v1y; float z1 = v2z - v1z; float z2 = v3z - v1z; float s1 = v2u - v1u; float s2 = v3u - v1u; float t1 = v2v - v1v; float t2 = v3v - v1v; float r = 1.f / (s1 * t2 - s2 * t1); float sdirx = (t2 * x1 - t1 * x2) * r; float sdiry = (t2 * y1 - t1 * y2) * r; float sdirz = (t2 * z1 - t1 * z2) * r; mTangents.push_back(sdirx); mTangents.push_back(sdiry); mTangents.push_back(sdirz); } } const std::vector<float> &ModelData::GetVertices() const { return mVertices; } const std::vector<float> &ModelData::GetNormals() const { return mNormals; } const std::vector<float> &ModelData::GetColors() const { return mColors; } const std::vector<float> &ModelData::GetTexCoords() const { return mTexCoords; } const std::vector<float> &ModelData::GetTangents() const { return mTangents; } const std::vector<unsigned int> &ModelData::GetIndices() const { return mIndices; } ModelData::ModelData(std::string name) : Resource(name) {}
28.815789
93
0.567428
[ "vector", "model" ]
dfe6bc500759893aecc850b649ab9f0dbccfd770
3,117
cpp
C++
HW4 - C++/main.cpp
muratyldzxc/CSE241
35b3fb6de1fa0aebe3f77353c1e4e4256fd2e36b
[ "MIT" ]
null
null
null
HW4 - C++/main.cpp
muratyldzxc/CSE241
35b3fb6de1fa0aebe3f77353c1e4e4256fd2e36b
[ "MIT" ]
null
null
null
HW4 - C++/main.cpp
muratyldzxc/CSE241
35b3fb6de1fa0aebe3f77353c1e4e4256fd2e36b
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <cstdlib> #include <ctime> #include <string> #include <fstream> #include <vector> #include "NPuzzle.h" using namespace std ; int NPuzzle :: Board :: CountOfBoards = 0 ; // init Board object counter int main( int argc, char *argv[] ){ int size ; char option ; string file_name ; bool validMove ; NPuzzle Puzzle ; ifstream fin ; srand( time(NULL) ); if ( argv[1] == NULL){ // set board for HW1 do{ cout << "\nPlease enter the problem size: " ; cin >> size ; cout << endl ; }while( !Puzzle.setSize ( size ) ) ; Puzzle.reset () ; // init the board to final solution Puzzle.Find_Ecell() ; Puzzle.shuffle( size * size * size ) ; Puzzle.Find_Ecell() ; } else if( argv[1] != NULL ){ // set board for HW2 fin.open( argv[1] ) ; fin << Puzzle ; fin.close() ; } do{ cout >> Puzzle ; cout <<"\n Your option : " ; cin >> option ; switch ( option ){ case 'V' : Puzzle.solvePuzzle() ; break ; case 'T' : Puzzle.printReport() ; break ; case 'E' : cout << "\nPlease enter the file name : " ; cin >> file_name ; Puzzle.writeToFile( file_name ) ; break ; case 'O' : cout << "\nPlease enter the file name : " ; cin >> file_name ; fin.open( file_name ) ; fin << Puzzle ; fin.close() ; break ; case 'L' : validMove = Puzzle.move( option ) ; if( !validMove ) cout << "\nYou can not go out of the puzzle.\n" ; break ; case 'R' : validMove = Puzzle.move( option ) ; if( !validMove ) cout << "\nYou can not go out of the puzzle.\n" ; break ; case 'U' : validMove = Puzzle.move( option ) ; if( !validMove ) cout << "\nYou can not go out of the puzzle.\n" ; break ; case 'D' : validMove = Puzzle.move( option ) ; if( !validMove ) cout << "\nYou can not go out of the puzzle.\n" ; break ; case 'S' : size = Puzzle.getSize() ; Puzzle.shuffle( size * size ) ; break ; case 'Q' : break ; default: cout << "\n You entered an invalid choice. Please give it again.\n" ; } }while( option != 'Q' && !Puzzle.isSolved() ) ; if( Puzzle.isSolved() && option != 'V' ) Puzzle.printReport() ; else if( option == 'Q' ) cout << "\n You quit from the program.\n\n" ; return 0 ; }
25.975
85
0.424126
[ "object", "vector" ]
dfe917276365d02a8840bc61d7d2702a6def1eb5
2,064
cpp
C++
Year-1/TIIT-traditional-intelligent-information-technologies/Course Work/1.11/iw-1.11.cpp
Ellanity/university
239b050deb4b35cdd855ab55d793988224190a57
[ "Apache-2.0" ]
null
null
null
Year-1/TIIT-traditional-intelligent-information-technologies/Course Work/1.11/iw-1.11.cpp
Ellanity/university
239b050deb4b35cdd855ab55d793988224190a57
[ "Apache-2.0" ]
null
null
null
Year-1/TIIT-traditional-intelligent-information-technologies/Course Work/1.11/iw-1.11.cpp
Ellanity/university
239b050deb4b35cdd855ab55d793988224190a57
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int main() { setlocale(LC_ALL, "Russian"); int n, m; cout << "Количество вершин: "; cin >> n; cout << "Количество ребер: "; cin >> m; // cout << "Nodes quantity: "; cin >> n; // cout << "Edges quantity: "; cin >> m; // Заполнение двумерного вектора нулями // Filling a two-dimensional vector with zeros vector <vector <int>> graph(m, vector <int>(n, 0)); // Заполнение матрицы инцидентности // Filling the incidence matrix int a, b; for (int i = 0; i < m; i++) { cin >> a >> b; a--; b--; if (a != b && a < n && b < n && a >= 0 && b >= 0) { graph[i][a] = 1; graph[i][b] = 2; } } // Вывод матрицы инцидентности // Output of the incidence matrix /*for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) cout << graph[i][j] << " "; cout << "\n"; }*/ vector <int> symmetric_edges; for (int i = 0; i < m; i++) { int p1 = 0, p2 = 0; for (int j = 0; j < n; j++) { if (graph[i][j] == 1) p1 = j; if (graph[i][j] == 2) p2 = j; } if (p1 != p2) for (int j = 0; j < m; j++) if (graph[j][p1] == 2 && graph[j][p2] == 1) { symmetric_edges.push_back(i); //cout << j << " " << p1 << " " << p2 << "\n"; break; } } /*for (int i = 0; i < symmetric_edges.size(); i++) cout << symmetric_edges[i] + 1 << " "; cout << "\n";*/ int nse = symmetric_edges.size(); if (nse == 0) cout << "Граф антисимметричный\n"; // cout << "Antisymmetric graph\n"; else if (nse != m) cout << "Граф частично симметричный\n"; // cout << "Partially symmetric graph\n"; else if (nse == m) cout << "Граф симметричный\n"; // cout << "Symmetric graph\n"; return 0; } /******************| _______TESTS_______| | _PARTLY__SYMMETRIC_| 5 5 1 2 2 3 4 3 5 4 3 4 | _____SYMMETRIC_____| 4 8 1 2 2 3 3 4 4 1 1 4 4 3 3 2 2 1 | ___ANTISYMMETRIC___| 3 2 1 2 3 2 | _____LITERATURE____| https://habr.com/ru/post/519998/ http://khpi-iip.mipk.kharkiv.edu/library/datastr/book_sod/kgsu/din_0087.html *******************/
19.657143
76
0.532461
[ "vector" ]
dfeb3c91f79906fe15df794da1ead506fff8da4c
340
hpp
C++
Pathfinder/utils.hpp
tqdv/time_filling
f280fe96136d5dc69f7487c89ac58c372eea3cb2
[ "MIT" ]
null
null
null
Pathfinder/utils.hpp
tqdv/time_filling
f280fe96136d5dc69f7487c89ac58c372eea3cb2
[ "MIT" ]
null
null
null
Pathfinder/utils.hpp
tqdv/time_filling
f280fe96136d5dc69f7487c89ac58c372eea3cb2
[ "MIT" ]
null
null
null
#ifndef TFILL_UTILS_HPP #define TFILL_UTILS_HPP #include <vector> #include <optional> template <typename T> using Maybe = std::optional<T>; template <typename T> using constref = const T&; template <typename T> void print_vector (const std::vector<T> &v); /* Pretty prints a vector */ #include "utils.ipp" #endif // TFILL_UTILS_HPP
16.190476
44
0.729412
[ "vector" ]
dff518eeba139fa84fb8eec735c68a146d849d79
2,712
cpp
C++
FaceAlignment/python/pyFaceAlignment.cpp
jnulzl/SeetaFaceEngine
693273585397df32b68418d0544dec565a959a44
[ "BSD-2-Clause" ]
2
2021-02-05T07:00:59.000Z
2021-02-05T08:49:45.000Z
FaceAlignment/python/pyFaceAlignment.cpp
jnulzl/SeetaFaceEngine
693273585397df32b68418d0544dec565a959a44
[ "BSD-2-Clause" ]
null
null
null
FaceAlignment/python/pyFaceAlignment.cpp
jnulzl/SeetaFaceEngine
693273585397df32b68418d0544dec565a959a44
[ "BSD-2-Clause" ]
null
null
null
#include<iostream> #include<pybind11/pybind11.h> #include<pybind11/stl.h> #include<pybind11/numpy.h> #include "face_alignment.h" namespace py = pybind11; class PyFaceAlignment { public: PyFaceAlignment(const std::string& model_path, int num_point = 5, int dim_point = 2):faceAlignment_(model_path.c_str()) { num_point_ = num_point; dim_point_ = dim_point; points_.resize(num_point_); points_float_.resize(num_point_ * dim_point_); } ~PyFaceAlignment() { } std::vector<std::vector<float>> PointDetectLandmarks(const py::array_t<uint8_t>& img , const std::vector<std::vector<float>>& faceinfos) { py::buffer_info img_buf = img.request(); if(2 != img_buf.ndim) { throw std::runtime_error("Input image must be gray image!"); } seeta::ImageData img_data; img_data.data = reinterpret_cast<uint8_t*>(img_buf.ptr); img_data.width = img_buf.shape[1]; img_data.height = img_buf.shape[0]; img_data.num_channels = 1; std::vector<std::vector<float>> pointses; for (int idx = 0; idx < faceinfos.size(); ++idx) { seeta::FaceInfo faceInfo; // x, y, width, height, roll, pitch, yaw, score faceInfo.bbox.x = faceinfos[idx][0]; faceInfo.bbox.y = faceinfos[idx][1]; faceInfo.bbox.width = faceinfos[idx][2]; faceInfo.bbox.height = faceinfos[idx][3]; faceInfo.roll = faceinfos[idx][4]; faceInfo.pitch = faceinfos[idx][5]; faceInfo.yaw = faceinfos[idx][6]; faceInfo.score = faceinfos[idx][7]; faceAlignment_.PointDetectLandmarks(img_data, faceInfo, points_.data()); for (int idy = 0; idy < num_point_; ++idy) { points_float_[dim_point_ * idy + 0] = points_[idy].x; points_float_[dim_point_ * idy + 1] = points_[idy].y; } pointses.push_back(points_float_); } return pointses; } private: int num_point_; int dim_point_; seeta::FaceAlignment faceAlignment_; std::vector<seeta::FacialLandmark> points_; std::vector<float> points_float_; }; PYBIND11_MODULE(MODEL_NAME, m) { m.doc() = "Face alignment python api"; //wrapper C++ PyFaceAlignment to python PyFaceAlignment py::class_<PyFaceAlignment>(m, "PyFaceAlignment") .def(py::init<const std::string&, int ,int >()) .def("PointDetectLandmarks", &PyFaceAlignment::PointDetectLandmarks); }
31.172414
124
0.580015
[ "shape", "vector" ]
dff5f94123b45fe66b58f22dcab24a95c7af6f70
5,563
cpp
C++
src/DynamicRank.FreeForm.Library/libs/Expression/Function.cpp
ltxtech/lightgbm-transform
ca3bdaae4e594c1bf74503c5ec151f2b794f855c
[ "MIT" ]
17
2021-11-02T13:52:10.000Z
2022-02-10T07:43:38.000Z
src/DynamicRank.FreeForm.Library/libs/Expression/Function.cpp
ltxtech/lightgbm-transform
ca3bdaae4e594c1bf74503c5ec151f2b794f855c
[ "MIT" ]
2
2022-01-23T16:15:40.000Z
2022-03-07T15:54:34.000Z
src/DynamicRank.FreeForm.Library/libs/Expression/Function.cpp
ltxtech/lightgbm-transform
ca3bdaae4e594c1bf74503c5ec151f2b794f855c
[ "MIT" ]
1
2022-01-21T09:42:59.000Z
2022-01-21T09:42:59.000Z
/*! * Copyright (c) 2021 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for * license information. */ #include "Function.h" #include "FreeForm2Assert.h" #include "FunctionType.h" #include "RefExpression.h" #include "Visitor.h" FreeForm2::FunctionExpression::FunctionExpression( const Annotations &p_annotations, const FunctionType &p_type, const std::string &p_name, const std::vector<Parameter> &p_parameters, const Expression &p_body) : Expression(p_annotations), m_type(p_type), m_name(p_name), m_parameters(p_parameters), m_body(p_body) {} const FreeForm2::FunctionType &FreeForm2::FunctionExpression::GetFunctionType() const { return m_type; } const FreeForm2::TypeImpl &FreeForm2::FunctionExpression::GetType() const { return m_type; } const std::string &FreeForm2::FunctionExpression::GetName() const { return m_name; } size_t FreeForm2::FunctionExpression::GetNumChildren() const { return GetNumParameters() + 1; } size_t FreeForm2::FunctionExpression::GetNumParameters() const { return m_parameters.size(); } const FreeForm2::Expression &FreeForm2::FunctionExpression::GetBody() const { return m_body; } const std::vector<FreeForm2::FunctionExpression::Parameter> &FreeForm2::FunctionExpression::GetParameters() const { return m_parameters; } void FreeForm2::FunctionExpression::Accept(Visitor &p_visitor) const { size_t stackSize = p_visitor.StackSize(); if (!p_visitor.AlternativeVisit(*this)) { for (size_t i = 0; i < m_parameters.size(); i++) { m_parameters[i].m_parameter->Accept(p_visitor); } m_body.Accept(p_visitor); p_visitor.Visit(*this); } FF2_ASSERT(p_visitor.StackSize() == stackSize + p_visitor.StackIncrement()); } FreeForm2::FunctionCallExpression::FunctionCallExpression( const Annotations &p_annotations, const Expression &p_function, const std::vector<const Expression *> &p_parameters) : Expression(p_annotations), m_function(p_function), m_numParameters(p_parameters.size()) { m_type = static_cast<const FunctionType *>(&p_function.GetType()); // Note that we rely on this ctor not throwing exceptions during // allocation below. // We rely on our allocator to size this object to be big enough to // hold all children, and enforce this forcing construction via Alloc. for (size_t i = 0; i < m_numParameters; i++) { m_parameters[i] = p_parameters[i]; } } void FreeForm2::FunctionCallExpression::Accept(Visitor &p_visitor) const { size_t stackSize = p_visitor.StackSize(); if (!p_visitor.AlternativeVisit(*this)) { m_function.Accept(p_visitor); for (size_t i = 0; i < m_numParameters; i++) { if (GetFunctionType().BeginParameters()[i]->IsConst()) { m_parameters[i]->Accept(p_visitor); } else { m_parameters[i]->AcceptReference(p_visitor); } } p_visitor.Visit(*this); } FF2_ASSERT(p_visitor.StackSize() == stackSize + p_visitor.StackIncrement()); } const FreeForm2::FunctionType & FreeForm2::FunctionCallExpression::GetFunctionType() const { return *m_type; } const FreeForm2::Expression &FreeForm2::FunctionCallExpression::GetFunction() const { return m_function; } const FreeForm2::TypeImpl &FreeForm2::FunctionCallExpression::GetType() const { return m_type->GetReturnType(); } size_t FreeForm2::FunctionCallExpression::GetNumChildren() const { return GetNumParameters() + 1; } size_t FreeForm2::FunctionCallExpression::GetNumParameters() const { return m_numParameters; } const FreeForm2::Expression *const * FreeForm2::FunctionCallExpression::GetParameters() const { return &m_parameters[0]; } boost::shared_ptr<FreeForm2::FunctionCallExpression> FreeForm2::FunctionCallExpression::Alloc( const Annotations &p_annotations, const Expression &p_function, const std::vector<const Expression *> &p_parameters) { FF2_ASSERT(p_function.GetType().Primitive() == Type::Function); size_t bytes = sizeof(FunctionCallExpression) + (std::max((size_t)1ULL, p_parameters.size()) - 1) * sizeof(Expression *); // Allocate a shared_ptr that deletes an FunctionCallExpression // allocated in a char[]. boost::shared_ptr<FunctionCallExpression> exp( new (new char[bytes]) FunctionCallExpression(p_annotations, p_function, p_parameters), DeleteAlloc); return exp; } void FreeForm2::FunctionCallExpression::DeleteAlloc( FunctionCallExpression *p_allocated) { // Manually call dtor for operator expression. p_allocated->~FunctionCallExpression(); // Dispose of memory, which we allocated in a char[]. char *mem = reinterpret_cast<char *>(p_allocated); delete[] mem; } FreeForm2::ReturnExpression::ReturnExpression(const Annotations &p_annotations, const Expression &p_value) : Expression(p_annotations), m_value(p_value) {} void FreeForm2::ReturnExpression::Accept(Visitor &p_visitor) const { size_t stackSize = p_visitor.StackSize(); if (!p_visitor.AlternativeVisit(*this)) { m_value.Accept(p_visitor); p_visitor.Visit(*this); } FF2_ASSERT(p_visitor.StackSize() == stackSize + p_visitor.StackIncrement()); } size_t FreeForm2::ReturnExpression::GetNumChildren() const { return 1; } const FreeForm2::TypeImpl &FreeForm2::ReturnExpression::GetType() const { return m_value.GetType().AsConstType(); } const FreeForm2::Expression &FreeForm2::ReturnExpression::GetValue() const { return m_value; }
29.590426
79
0.725688
[ "object", "vector" ]
5f053a3bf6b3beaf3a486e6ad7a6b89939cda53e
17,862
cpp
C++
adept/Stack.cpp
yairchu/Adept-2
3b4f898c74139618464ccd8e8df0934aed9ed6a2
[ "Apache-2.0" ]
131
2016-07-06T04:06:49.000Z
2022-03-19T22:34:47.000Z
adept/Stack.cpp
yairchu/Adept-2
3b4f898c74139618464ccd8e8df0934aed9ed6a2
[ "Apache-2.0" ]
19
2016-06-20T20:20:23.000Z
2022-02-15T14:55:01.000Z
adept/Stack.cpp
yairchu/Adept-2
3b4f898c74139618464ccd8e8df0934aed9ed6a2
[ "Apache-2.0" ]
31
2017-10-07T00:07:49.000Z
2022-03-05T17:51:17.000Z
/* Stack.cpp -- Stack for storing automatic differentiation information Copyright (C) 2012-2014 University of Reading Copyright (C) 2015 European Centre for Medium-Range Weather Forecasts Author: Robin Hogan <r.j.hogan@ecmwf.int> This file is part of the Adept library. */ #include <iostream> #include <cstring> // For memcpy #ifdef _OPENMP #include <omp.h> #endif #include <adept/Stack.h> namespace adept { using namespace internal; // Global pointers to the current thread, the second of which is // thread safe. The first is only used if ADEPT_STACK_THREAD_UNSAFE // is defined. ADEPT_THREAD_LOCAL Stack* _stack_current_thread = 0; Stack* _stack_current_thread_unsafe = 0; // MEMBER FUNCTIONS OF THE STACK CLASS // Destructor: frees dynamically allocated memory (if any) Stack::~Stack() { // If this is the currently active stack then set to NULL as // "this" is shortly to become invalid if (is_thread_unsafe_) { if (_stack_current_thread_unsafe == this) { _stack_current_thread_unsafe = 0; } } else if (_stack_current_thread == this) { _stack_current_thread = 0; } #ifndef ADEPT_STACK_STORAGE_STL if (gradient_) { delete[] gradient_; } #endif } // Make this stack "active" by copying its "this" pointer to a // global variable; this makes it the stack that aReal objects // subsequently interact with when being created and participating // in mathematical expressions void Stack::activate() { // Check that we don't already have an active stack in this thread if ((is_thread_unsafe_ && _stack_current_thread_unsafe && _stack_current_thread_unsafe != this) || ((!is_thread_unsafe_) && _stack_current_thread && _stack_current_thread != this)) { throw(stack_already_active()); } else { if (!is_thread_unsafe_) { _stack_current_thread = this; } else { _stack_current_thread_unsafe = this; } } } // Set the maximum number of threads to be used in Jacobian // calculations, if possible. A value of 1 indicates that OpenMP // will not be used, while a value of 0 indicates that the number // will match the number of available processors. Returns the // maximum that will be used, which will be 1 if the Adept library // was compiled without OpenMP support. Note that a value of 1 will // disable the use of OpenMP with Adept, so Adept will then use no // OpenMP directives or function calls. Note that if in your program // you use OpenMP with each thread performing automatic // differentiaion with its own independent Adept stack, then // typically only one OpenMP thread is available for each Jacobian // calculation, regardless of whether you call this function. int Stack::set_max_jacobian_threads(int n) { #ifdef _OPENMP if (have_openmp_) { if (n == 1) { openmp_manually_disabled_ = true; return 1; } else if (n < 1) { openmp_manually_disabled_ = false; omp_set_num_threads(omp_get_num_procs()); return omp_get_max_threads(); } else { openmp_manually_disabled_ = false; omp_set_num_threads(n); return omp_get_max_threads(); } } #endif return 1; } // Return maximum number of OpenMP threads to be used in Jacobian // calculation int Stack::max_jacobian_threads() const { #ifdef _OPENMP if (have_openmp_) { if (openmp_manually_disabled_) { return 1; } else { return omp_get_max_threads(); } } #endif return 1; } // Perform to adjoint computation (reverse mode). It is assumed that // some gradients have been assigned already, otherwise the function // returns with an error. void Stack::compute_adjoint() { if (gradients_are_initialized()) { // Loop backwards through the derivative statements for (uIndex ist = n_statements_-1; ist > 0; ist--) { const Statement& statement = statement_[ist]; // We copy the RHS gradient (LHS in the original derivative // statement but swapped in the adjoint equivalent) to "a" in // case it appears on the LHS in any of the following statements Real a = gradient_[statement.index]; gradient_[statement.index] = 0.0; // By only looping if a is non-zero we gain a significant speed-up if (a != 0.0) { // Loop over operations for (uIndex i = statement_[ist-1].end_plus_one; i < statement.end_plus_one; i++) { gradient_[index_[i]] += multiplier_[i]*a; } } } } else { throw(gradients_not_initialized()); } } // Perform tangent linear computation (forward mode). It is assumed // that some gradients have been assigned already, otherwise the // function returns with an error. void Stack::compute_tangent_linear() { if (gradients_are_initialized()) { // Loop forward through the statements for (uIndex ist = 1; ist < n_statements_; ist++) { const Statement& statement = statement_[ist]; // We copy the LHS to "a" in case it appears on the RHS in any // of the following statements Real a = 0.0; for (uIndex i = statement_[ist-1].end_plus_one; i < statement.end_plus_one; i++) { a += multiplier_[i]*gradient_[index_[i]]; } gradient_[statement.index] = a; } } else { throw(gradients_not_initialized()); } } // Register n gradients uIndex Stack::do_register_gradients(const uIndex& n) { n_gradients_registered_ += n; if (!gap_list_.empty()) { uIndex return_val; // Insert in a gap, if there is one big enough for (GapListIterator it = gap_list_.begin(); it != gap_list_.end(); it++) { uIndex len = it->end + 1 - it->start; if (len > n) { // Gap a bit larger than needed: reduce its size return_val = it->start; it->start += n; return return_val; } else if (len == n) { // Gap exactly the size needed: fill it and remove from list return_val = it->start; if (most_recent_gap_ == it) { gap_list_.erase(it); most_recent_gap_ = gap_list_.end(); } else { gap_list_.erase(it); } return return_val; } } } // No suitable gap found; instead add to end of gradient vector i_gradient_ += n; if (i_gradient_ > max_gradient_) { max_gradient_ = i_gradient_; } return i_gradient_ - n; } // If an aReal object is deleted, its gradient_index is // unregistered from the stack. If this is at the top of the stack // then this is easy and is done inline; this is the usual case // since C++ trys to deallocate automatic objects in the reverse // order to that in which they were allocated. If it is not at the // top of the stack then a non-inline function is called to ensure // that the gap list is adjusted correctly. void Stack::unregister_gradient_not_top(const uIndex& gradient_index) { enum { ADDED_AT_BASE, ADDED_AT_TOP, NEW_GAP, NOT_FOUND } status = NOT_FOUND; // First try to find if the unregistered element is at the // start or end of an existing gap if (!gap_list_.empty() && most_recent_gap_ != gap_list_.end()) { // We have a "most recent" gap - check whether the gradient // to be unregistered is here Gap& current_gap = *most_recent_gap_; if (gradient_index == current_gap.start - 1) { current_gap.start--; status = ADDED_AT_BASE; } else if (gradient_index == current_gap.end + 1) { current_gap.end++; status = ADDED_AT_TOP; } // Should we check for erroneous removal from middle of gap? } if (status == NOT_FOUND) { // Search other gaps for (GapListIterator it = gap_list_.begin(); it != gap_list_.end(); it++) { if (gradient_index <= it->end + 1) { // Gradient to unregister is either within the gap // referenced by iterator "it", or it is between "it" // and the previous gap in the list if (gradient_index == it->start - 1) { status = ADDED_AT_BASE; it->start--; most_recent_gap_ = it; } else if (gradient_index == it->end + 1) { status = ADDED_AT_TOP; it->end++; most_recent_gap_ = it; } else { // Insert a new gap of width 1; note that list::insert // inserts *before* the specified location most_recent_gap_ = gap_list_.insert(it, Gap(gradient_index)); status = NEW_GAP; } break; } } if (status == NOT_FOUND) { gap_list_.push_back(Gap(gradient_index)); most_recent_gap_ = gap_list_.end(); most_recent_gap_--; } } // Finally check if gaps have merged if (status == ADDED_AT_BASE && most_recent_gap_ != gap_list_.begin()) { // Check whether the gap has merged with the next one GapListIterator it = most_recent_gap_; it--; if (it->end == most_recent_gap_->start - 1) { // Merge two gaps most_recent_gap_->start = it->start; gap_list_.erase(it); } } else if (status == ADDED_AT_TOP) { GapListIterator it = most_recent_gap_; it++; if (it != gap_list_.end() && it->start == most_recent_gap_->end + 1) { // Merge two gaps most_recent_gap_->end = it->end; gap_list_.erase(it); } } } // Unregister n gradients starting at gradient_index void Stack::unregister_gradients(const uIndex& gradient_index, const uIndex& n) { n_gradients_registered_ -= n; if (gradient_index+n == i_gradient_) { // Gradient to be unregistered is at the top of the stack i_gradient_ -= n; if (!gap_list_.empty()) { Gap& last_gap = gap_list_.back(); if (i_gradient_ == last_gap.end+1) { // We have unregistered the elements between the "gap" of // unregistered element and the top of the stack, so can set // the variables indicating the presence of the gap to zero i_gradient_ = last_gap.start; GapListIterator it = gap_list_.end(); it--; if (most_recent_gap_ == it) { most_recent_gap_ = gap_list_.end(); } gap_list_.pop_back(); } } } else { // Gradients to be unregistered not at top of stack. enum { ADDED_AT_BASE, ADDED_AT_TOP, NEW_GAP, NOT_FOUND } status = NOT_FOUND; // First try to find if the unregistered element is at the start // or end of an existing gap if (!gap_list_.empty() && most_recent_gap_ != gap_list_.end()) { // We have a "most recent" gap - check whether the gradient // to be unregistered is here Gap& current_gap = *most_recent_gap_; if (gradient_index == current_gap.start - n) { current_gap.start -= n; status = ADDED_AT_BASE; } else if (gradient_index == current_gap.end + 1) { current_gap.end += n; status = ADDED_AT_TOP; } /* else if (gradient_index > current_gap.start - n && gradient_index < current_gap.end + 1) { std::cout << "** Attempt to find " << gradient_index << " in gaps "; print_gaps(); std::cout << "\n"; throw invalid_operation("Gap list corruption"); } */ // Should we check for erroneous removal from middle of gap? } if (status == NOT_FOUND) { // Search other gaps for (GapListIterator it = gap_list_.begin(); it != gap_list_.end(); it++) { if (gradient_index <= it->end + 1) { // Gradient to unregister is either within the gap // referenced by iterator "it", or it is between "it" and // the previous gap in the list if (gradient_index == it->start - n) { status = ADDED_AT_BASE; it->start -= n; most_recent_gap_ = it; } else if (gradient_index == it->end + 1) { status = ADDED_AT_TOP; it->end += n; most_recent_gap_ = it; } /* else if (gradient_index > it->start - n) { std::cout << "*** Attempt to find " << gradient_index << " in gaps "; print_gaps(); std::cout << "\n"; throw invalid_operation("Gap list corruption"); } */ else { // Insert a new gap; note that list::insert inserts // *before* the specified location most_recent_gap_ = gap_list_.insert(it, Gap(gradient_index, gradient_index+n-1)); status = NEW_GAP; } break; } } if (status == NOT_FOUND) { gap_list_.push_back(Gap(gradient_index, gradient_index+n-1)); most_recent_gap_ = gap_list_.end(); most_recent_gap_--; } } // Finally check if gaps have merged if (status == ADDED_AT_BASE && most_recent_gap_ != gap_list_.begin()) { // Check whether the gap has merged with the next one GapListIterator it = most_recent_gap_; it--; if (it->end == most_recent_gap_->start - 1) { // Merge two gaps most_recent_gap_->start = it->start; gap_list_.erase(it); } } else if (status == ADDED_AT_TOP) { GapListIterator it = most_recent_gap_; it++; if (it != gap_list_.end() && it->start == most_recent_gap_->end + 1) { // Merge two gaps most_recent_gap_->end = it->end; gap_list_.erase(it); } } } } // Print each derivative statement to the specified stream (standard // output if omitted) void Stack::print_statements(std::ostream& os) const { for (uIndex ist = 1; ist < n_statements_; ist++) { const Statement& statement = statement_[ist]; os << ist << ": d[" << statement.index << "] = "; if (statement_[ist-1].end_plus_one == statement_[ist].end_plus_one) { os << "0\n"; } else { for (uIndex i = statement_[ist-1].end_plus_one; i < statement.end_plus_one; i++) { os << " + " << multiplier_[i] << "*d[" << index_[i] << "]"; } os << "\n"; } } } // Print the current gradient list to the specified stream (standard // output if omitted) bool Stack::print_gradients(std::ostream& os) const { if (gradients_are_initialized()) { for (uIndex i = 0; i < max_gradient_; i++) { if (i%10 == 0) { if (i != 0) { os << "\n"; } os << i << ":"; } os << " " << gradient_[i]; } os << "\n"; return true; } else { os << "No gradients initialized\n"; return false; } } // Print the list of gaps in the gradient list to the specified // stream (standard output if omitted) void Stack::print_gaps(std::ostream& os) const { for (std::list<Gap>::const_iterator it = gap_list_.begin(); it != gap_list_.end(); it++) { os << it->start << "-" << it->end << " "; } } #ifndef ADEPT_STACK_STORAGE_STL // Initialize the vector of gradients ready for the adjoint // calculation void Stack::initialize_gradients() { if (max_gradient_ > 0) { if (n_allocated_gradients_ < max_gradient_) { if (gradient_) { delete[] gradient_; } gradient_ = new Real[max_gradient_]; n_allocated_gradients_ = max_gradient_; } for (uIndex i = 0; i < max_gradient_; i++) { gradient_[i] = 0.0; } } gradients_initialized_ = true; } #else void Stack::initialize_gradients() { gradient_.resize(max_gradient_+10, 0.0); gradients_initialized_ = true; } #endif // Report information about the stack to the specified stream, or // standard output if omitted; note that this is synonymous with // sending the Stack object to a stream using the "<<" operator. void Stack::print_status(std::ostream& os) const { os << "Automatic Differentiation Stack (address " << this << "):\n"; if ((!is_thread_unsafe_) && _stack_current_thread == this) { os << " Currently attached - thread safe\n"; } else if (is_thread_unsafe_ && _stack_current_thread_unsafe == this) { os << " Currently attached - thread unsafe\n"; } else { os << " Currently detached\n"; } os << " Recording status:\n"; if (is_recording_) { os << " Recording is ON\n"; } else { os << " Recording is PAUSED\n"; } // Account for the null statement at the start by subtracting one os << " " << n_statements()-1 << " statements (" << n_allocated_statements() << " allocated)"; os << " and " << n_operations() << " operations (" << n_allocated_operations() << " allocated)\n"; os << " " << n_gradients_registered() << " gradients currently registered "; os << "and a total of " << max_gradients() << " needed (current index " << i_gradient() << ")\n"; if (gap_list_.empty()) { os << " Gradient list has no gaps\n"; } else { os << " Gradient list has " << gap_list_.size() << " gaps ("; print_gaps(os); os << ")\n"; } os << " Computation status:\n"; if (gradients_are_initialized()) { os << " " << max_gradients() << " gradients assigned (" << n_allocated_gradients() << " allocated)\n"; } else { os << " 0 gradients assigned (" << n_allocated_gradients() << " allocated)\n"; } os << " Jacobian size: " << n_dependents() << "x" << n_independents() << "\n"; if (n_dependents() <= 10 && n_independents() <= 10) { os << " Independent indices:"; for (std::size_t i = 0; i < independent_index_.size(); ++i) { os << " " << independent_index_[i]; } os << "\n Dependent indices: "; for (std::size_t i = 0; i < dependent_index_.size(); ++i) { os << " " << dependent_index_[i]; } os << "\n"; } #ifdef _OPENMP if (have_openmp_) { if (openmp_manually_disabled_) { os << " Parallel Jacobian calculation manually disabled\n"; } else { os << " Parallel Jacobian calculation can use up to " << omp_get_max_threads() << " threads\n"; os << " Each thread treats " << ADEPT_MULTIPASS_SIZE << " (in)dependent variables\n"; } } else { #endif os << " Parallel Jacobian calculation not available\n"; #ifdef _OPENMP } #endif } } // End namespace adept
28.670947
87
0.624678
[ "object", "vector" ]
5f14b1227ea6ae1601612abfc27979e0b6add6a7
10,254
cc
C++
RecoVertex/KinematicFit/src/ConstrainedTreeBuilder.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
RecoVertex/KinematicFit/src/ConstrainedTreeBuilder.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
RecoVertex/KinematicFit/src/ConstrainedTreeBuilder.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#include "RecoVertex/KinematicFit/interface/ConstrainedTreeBuilder.h" #include "DataFormats/CLHEP/interface/Migration.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" ConstrainedTreeBuilder::ConstrainedTreeBuilder() { pFactory = new VirtualKinematicParticleFactory(); vFactory = new KinematicVertexFactory(); } ConstrainedTreeBuilder::~ConstrainedTreeBuilder() { delete pFactory; delete vFactory; } RefCountedKinematicTree ConstrainedTreeBuilder::buildTree(const std::vector<RefCountedKinematicParticle> & initialParticles, const std::vector<KinematicState> & finalStates, const RefCountedKinematicVertex vertex, const AlgebraicMatrix& fullCov) const { if (!vertex->vertexIsValid()) { LogDebug("ConstrainedTreeBuilder") << "Vertex is invalid\n"; return ReferenceCountingPointer<KinematicTree>(new KinematicTree()); } AlgebraicVector3 vtx; vtx(0) = vertex->position().x(); vtx(1) = vertex->position().y(); vtx(2) = vertex->position().z(); AlgebraicMatrix33 vertexCov = asSMatrix<3,3>(fullCov.sub(1,3,1,3)); // cout << fullCov<<endl; // cout << "RecoVertex/ConstrainedTreeBuilder"<<vtx<<endl; double ent = 0.; int charge = 0; AlgebraicVector7 virtualPartPar; virtualPartPar(0) = vertex->position().x(); virtualPartPar(1) = vertex->position().y(); virtualPartPar(2) = vertex->position().z(); //making refitted particles out of refitted states. //none of the operations above violates the order of particles ROOT::Math::SMatrix<double,7,7,ROOT::Math::MatRepStd<double,7,7> > aMatrix; aMatrix(3,3) = 1; aMatrix(4,4) = 1; aMatrix(5,5) = 1; aMatrix(6,6) = 1; ROOT::Math::SMatrix<double,7,3,ROOT::Math::MatRepStd<double,7,3> > bMatrix; bMatrix(0,0) = 1; bMatrix(1,1) = 1; bMatrix(2,2) = 1; AlgebraicMatrix77 trackParCov; ROOT::Math::SMatrix<double,3,7,ROOT::Math::MatRepStd<double,3,7> > vtxTrackCov; AlgebraicMatrix77 nCovariance; std::vector<RefCountedKinematicParticle>::const_iterator i = initialParticles.begin(); std::vector<KinematicState>::const_iterator iStates = finalStates.begin(); std::vector<RefCountedKinematicParticle> rParticles; int n=0; for( ; i != initialParticles.end() && iStates != finalStates.end(); ++i,++iStates) { AlgebraicVector7 p = iStates->kinematicParameters().vector(); double a = - iStates->particleCharge() * iStates->magneticField()->inInverseGeV(iStates->globalPosition()).z(); aMatrix(4,0) = -a; aMatrix(3,1) = a; bMatrix(4,0) = a; bMatrix(3,1) = -a; AlgebraicVector7 par = aMatrix*p + bMatrix * vtx; trackParCov = asSMatrix<7,7>(fullCov.sub(4+n*7,10+n*7,4+n*7,10+n*7)); vtxTrackCov = asSMatrix<3,7>(fullCov.sub(1,3,4+n*7,10+n*7));; nCovariance = aMatrix * trackParCov * ROOT::Math::Transpose(aMatrix) + aMatrix * ROOT::Math::Transpose(vtxTrackCov) * ROOT::Math::Transpose(bMatrix) + bMatrix * vtxTrackCov * ROOT::Math::Transpose(aMatrix)+ bMatrix * vertexCov * ROOT::Math::Transpose(bMatrix); KinematicState stateAtVertex(KinematicParameters(par), KinematicParametersError(AlgebraicSymMatrix77(nCovariance.LowerBlock())), iStates->particleCharge(), iStates->magneticField()); rParticles.push_back((*i)->refittedParticle(stateAtVertex, vertex->chiSquared(), vertex->degreesOfFreedom())); virtualPartPar(3) += par(3); virtualPartPar(4) += par(4); virtualPartPar(5) += par(5); ent += sqrt(par(6)*par(6) + par(3)*par(3)+par(4)*par(4)+par(5)*par(5) ); charge += iStates->particleCharge(); ++n; } //total reconstructed mass double differ = ent*ent - (virtualPartPar(3)*virtualPartPar(3) + virtualPartPar(5)*virtualPartPar(5) + virtualPartPar(4)*virtualPartPar(4)); if(differ>0.) { virtualPartPar(6) = sqrt(differ); } else { LogDebug("ConstrainedTreeBuilder") << "Fit failed: Current precision does not allow to calculate the mass\n"; return ReferenceCountingPointer<KinematicTree>(new KinematicTree()); } // covariance matrix: AlgebraicMatrix77 cov = asSMatrix<7,7>(covarianceMatrix(rParticles,virtualPartPar,fullCov)); KinematicState nState(KinematicParameters(virtualPartPar), KinematicParametersError(AlgebraicSymMatrix77(cov.LowerBlock())), charge, initialParticles[0]->magneticField()); //newborn kinematic particle float chi2 = vertex->chiSquared(); float ndf = vertex->degreesOfFreedom(); KinematicParticle * zp = 0; RefCountedKinematicParticle virtualParticle = pFactory->particle(nState,chi2,ndf,zp); return buildTree(virtualParticle, vertex, rParticles); } RefCountedKinematicTree ConstrainedTreeBuilder::buildTree(const RefCountedKinematicParticle virtualParticle, const RefCountedKinematicVertex vtx, const std::vector<RefCountedKinematicParticle> & particles) const { //making a resulting tree: RefCountedKinematicTree resTree = ReferenceCountingPointer<KinematicTree>(new KinematicTree()); //fake production vertex: RefCountedKinematicVertex fVertex = vFactory->vertex(); resTree->addParticle(fVertex, vtx, virtualParticle); //adding final state for(std::vector<RefCountedKinematicParticle>::const_iterator il = particles.begin(); il != particles.end(); il++) { if((*il)->previousParticle()->correspondingTree() != 0) { KinematicTree * tree = (*il)->previousParticle()->correspondingTree(); tree->movePointerToTheTop(); tree->replaceCurrentParticle(*il); RefCountedKinematicVertex cdVertex = resTree->currentDecayVertex(); resTree->addTree(cdVertex, tree); }else{ RefCountedKinematicVertex ffVertex = vFactory->vertex(); resTree->addParticle(vtx,ffVertex,*il); } } return resTree; } AlgebraicMatrix ConstrainedTreeBuilder::covarianceMatrix(const std::vector<RefCountedKinematicParticle> &rPart, const AlgebraicVector7& newPar, const AlgebraicMatrix& fitCov)const { //constructing the full matrix using the simple fact //that we have never broken the order of tracks // during our fit. int size = rPart.size(); //global propagation to the vertex position //Jacobian is done for all the parameters together AlgebraicMatrix jac(3+7*size,3+7*size,0); jac(1,1) = 1; jac(2,2) = 1; jac(3,3) = 1; int i_int=0; for(std::vector<RefCountedKinematicParticle>::const_iterator i = rPart.begin(); i != rPart.end(); i++) { //vertex position related components of the matrix double a_i = - (*i)->currentState().particleCharge() * (*i)->magneticField()->inInverseGeV((*i)->currentState().globalPosition()).z(); AlgebraicMatrix upper(3,7,0); AlgebraicMatrix diagonal(7,7,0); upper(1,1) = 1; upper(2,2) = 1; upper(3,3) = 1; upper(2,4) = -a_i; upper(1,5) = a_i; jac.sub(1,4+i_int*7,upper); diagonal(4,4) = 1; diagonal(5,5) = 1; diagonal(6,6) = 1; diagonal(7,7) = 1; diagonal(2,4) = a_i; diagonal(1,5) = -a_i; jac.sub(4+i_int*7,4+i_int*7,diagonal); i_int++; } // jacobian is constructed in such a way, that // right operation for transformation will be // fitCov.similarityT(jac) // WARNING: normal similarity operation is // not valid in this case //now making reduced matrix: int vSize = rPart.size(); AlgebraicSymMatrix fit_cov_sym(7*vSize+3,0); for(int i = 1; i<7*vSize+4; ++i) { for(int j = 1; j<7*vSize+4; ++j) {if(i<=j) fit_cov_sym(i,j) = fitCov(i,j);} } AlgebraicMatrix reduced(3+4*size,3+4*size,0); AlgebraicMatrix transform = fit_cov_sym.similarityT(jac); //jacobian to add matrix components AlgebraicMatrix jac_t(7,7+4*(size-1)); jac_t(1,1) = 1.; jac_t(2,2) = 1.; jac_t(3,3) = 1.; //debug code: //CLHEP bugs: avoiding the // HepMatrix::sub method use AlgebraicMatrix reduced_tm(7,7,0); for(int i = 1; i<8;++i) { for(int j =1; j<8; ++j) {reduced_tm(i,j) = transform(i+3, j+3);} } //left top corner // reduced.sub(1,1,transform.sub(4,10,4,10)); //debug code: //CLHEP bugs: avoiding the // HepMatrix::sub method use reduced.sub(1,1,reduced_tm); // cout<<"reduced matrix"<<reduced<<endl; int il_int = 0; double energy_global = sqrt(newPar(3)*newPar(3)+newPar(4)*newPar(4) + newPar(5)*newPar(5)+newPar(6)*newPar(6)); for(std::vector<RefCountedKinematicParticle>::const_iterator rs = rPart.begin(); rs!=rPart.end();rs++) { //jacobian components: AlgebraicMatrix jc_el(4,4,0); jc_el(1,1) = 1.; jc_el(2,2) = 1.; jc_el(3,3) = 1.; //non-trival elements: mass correlations: AlgebraicVector7 l_Par = (*rs)->currentState().kinematicParameters().vector(); double energy_local = sqrt(l_Par(6)*l_Par(6) + l_Par(3)*l_Par(3) + l_Par(4)*l_Par(4) + l_Par(5)*l_Par(5)); jc_el(4,4) = energy_global*l_Par(6)/(newPar(6)*energy_local); jc_el(4,1) = ((energy_global*l_Par(3)/energy_local) - newPar(3))/newPar(6); jc_el(4,2) = ((energy_global*l_Par(4)/energy_local) - newPar(4))/newPar(6); jc_el(4,3) = ((energy_global*l_Par(5)/energy_local) - newPar(5))/newPar(6); jac_t.sub(4,il_int*4+4,jc_el); il_int++; } // cout<<"jac_t"<<jac_t<<endl; //debug code //CLHEP bugs workaround // cout<<"Transform matrix"<< transform<<endl; for(int i = 1; i<size; i++) { //non-trival elements: mass correlations: //upper row and right column AlgebraicMatrix transform_sub1(3,4,0); AlgebraicMatrix transform_sub2(4,3,0); for(int l1 = 1; l1<4;++l1) { for(int l2 = 1; l2<5;++l2) {transform_sub1(l1,l2) = transform(3+l1,6+7*i +l2);} } for(int l1 = 1; l1<5;++l1) { for(int l2 = 1; l2<4;++l2) {transform_sub2(l1,l2) = transform(6+7*i+l1,3+l2);} } AlgebraicMatrix transform_sub3(4,4,0); for(int l1 = 1; l1<5;++l1) { for(int l2 = 1; l2<5;++l2) {transform_sub3(l1,l2) = transform(6+7*i+l1, 6+7*i+l2); } } reduced.sub(1,4+4*i,transform_sub1); reduced.sub(4+4*i,1,transform_sub2); //diagonal elements reduced.sub(4+4*i,4+4*i,transform_sub3); //off diagonal elements for(int j = 1; j<size; j++) { AlgebraicMatrix transform_sub4(4,4,0); AlgebraicMatrix transform_sub5(4,4,0); for(int l1 = 1; l1<5;++l1) { for(int l2 = 1; l2<5;++l2) { transform_sub4(l1,l2) = transform(6+7*(i-1)+l1,6+7*j+l2); transform_sub5(l1,l2) = transform(6+7*j+l1, 6+7*(i-1)+l2); } } reduced.sub(4+4*(i-1),4+4*j,transform_sub4); reduced.sub(4+4*j,4+4*(i-1),transform_sub5); } } return jac_t*reduced*jac_t.T(); }
32.449367
142
0.688707
[ "vector", "transform" ]
5f350a333668841333f39595c848d8d5df5ccee5
7,039
cpp
C++
src/tools/attilaASM/optimizer.cpp
attila-sim/attila-sim
a64b57240b4e10dc4df7f21eff0232b28df09532
[ "BSD-3-Clause" ]
23
2016-01-14T04:47:13.000Z
2022-01-13T14:02:08.000Z
src/tools/attilaASM/optimizer.cpp
attila-sim/attila-sim
a64b57240b4e10dc4df7f21eff0232b28df09532
[ "BSD-3-Clause" ]
2
2018-03-25T14:39:20.000Z
2022-03-18T05:11:21.000Z
src/tools/attilaASM/optimizer.cpp
attila-sim/attila-sim
a64b57240b4e10dc4df7f21eff0232b28df09532
[ "BSD-3-Clause" ]
17
2016-02-13T05:35:35.000Z
2022-03-24T16:05:40.000Z
#include "GPUTypes.h" #include "OptimizedDynamicMemory.h" #include "ShaderInstruction.h" #include "ShaderOptimization.h" #include <cstdio> #include <vector> #include <fstream> #include <string> using namespace gpu3d; int main(int argc, char *argv[]) { if (argc < 3) { printf("Usage : \n"); printf(" optimize [-lda|-soa|-setwaitpoints|-norename|-notrail|-verbose] <input file> <output file>\n"); return -1; } bool verbose = false; bool useLDA = false; bool AOStoSOA = false; bool noTrailNOPs = false; bool noRename = false; bool setWaitPoints = false; bool endOptionSection = false; u32bit nextParameter = 1; for(; !endOptionSection && (nextParameter < argc); nextParameter++) { string parameter(argv[nextParameter]); // Check if the parameter is an option flag. if (parameter[0] == '-') { if (parameter.compare("-lda") == 0) useLDA = true; else if (parameter.compare("-soa") == 0) AOStoSOA = true; else if (parameter.compare("-setwaitpoints") == 0) setWaitPoints = true; else if (parameter.compare("-norename") == 0) noRename = true; else if (parameter.compare("-notrail") == 0) noTrailNOPs = true; else if (parameter.compare("-verbose") == 0) verbose = true; else { printf("Usage : \n"); printf(" optimize [-lda|-soa|-setwaitpoints|-norename|-notrail|-verbose] <input file> <output file>\n"); return -1; } } else endOptionSection = true; } if (nextParameter == argc) { printf("Usage : \n"); printf(" optimize [-lda|-soa|-setwaitpoints|-norename|-notrail|-verbose] <input file> <output file>\n"); return -1; } if (endOptionSection) nextParameter--; string inputFileName = argv[nextParameter]; ifstream inputFile; inputFile.open(inputFileName.c_str(), ios_base::binary); if (!inputFile.is_open()) { printf("Error opening input file \"%s\"\n", inputFileName.c_str()); return -1; } nextParameter++; string outputFileName = argv[nextParameter]; ofstream outputFile; outputFile.open(outputFileName.c_str(), ios_base::binary); if (!outputFile.is_open()) { printf("Error opening output file \"%s\"\n", outputFileName.c_str()); return -1; } // Initialize the dynamic memory manager. OptimizedDynamicMemory::initialize(512, 4096, 1024, 1024, 4096, 1024); u32bit instruction = 1; bool endFlaggedInstructionFound = false; vector<ShaderInstruction *> inputProgram; // Read until the end of the input file. while(!inputFile.eof()) { ShaderInstruction *shInstr; u8bit instrCode[16]; // Read an instruction from the input file. inputFile.read((char *) instrCode, 16); // Check if all the instruction bytes were read. if ((inputFile.gcount() == 0) && (inputFile.eof())) { // End loop. } else if (inputFile.gcount() != 16) { printf("Error reading instruction %d\n", instruction); return -1; } else { // Decode the instruction shInstr = new ShaderInstruction(instrCode); // Check if the instruction is beyond the last instruction in the program. if (endFlaggedInstructionFound && noTrailNOPs) { // Ignore the instruction. Generate a warning if the instruction is not a NOP. if (shInstr->getOpcode() != NOP) printf("Warning: Instruction %d after program END is not a NOP\n", instruction); } else { // Add instruction to the program. inputProgram.push_back(shInstr); } // Check if the instruction is the last instruction in the program. endFlaggedInstructionFound = endFlaggedInstructionFound || shInstr->isEnd(); // Update the instruction counter. instruction++; } } if (verbose) { printf("Input program : \n"); printf("----------------------------------------\n"); ShaderOptimization::printProgram(inputProgram); printf("\n"); } vector<ShaderInstruction *> programTemp1; vector<ShaderInstruction *> programTemp2; vector<ShaderInstruction *> programOptimized; vector<ShaderInstruction *> programFinal; if (useLDA) { ShaderOptimization::attribute2lda(inputProgram, programTemp1); if (verbose) { printf("Convert input registers to LDA : \n"); printf("----------------------------------------\n"); ShaderOptimization::printProgram(programTemp1); printf("\n"); } } else ShaderOptimization::copyProgram(inputProgram, programTemp1); if (AOStoSOA) { ShaderOptimization::aos2soa(programTemp1, programTemp2); ShaderOptimization::deleteProgram(programTemp1); ShaderOptimization::copyProgram(programTemp2, programTemp1); ShaderOptimization::deleteProgram(programTemp2); if (verbose) { printf("AOS to SOA conversion : \n"); printf("----------------------------------------\n"); ShaderOptimization::printProgram(programTemp1); printf("\n"); } } u32bit maxLiveRegs = 0; ShaderOptimization::optimize(programTemp1, programOptimized, maxLiveRegs, noRename, AOStoSOA, verbose); ShaderOptimization::deleteProgram(programTemp1); if (verbose) { printf("Optimized program : \n"); printf("----------------------------------------\n"); ShaderOptimization::printProgram(programOptimized); printf("\n"); } if (setWaitPoints) { ShaderOptimization::assignWaitPoints(programOptimized, programFinal); if (verbose) { printf("Program with wait points : \n"); printf("----------------------------------------\n"); ShaderOptimization::printProgram(programFinal); printf("\n"); } } else { ShaderOptimization::copyProgram(programOptimized, programFinal); } ShaderOptimization::deleteProgram(programOptimized); // Write the final version of the program to the output file. for(u32bit instr = 0; instr < programFinal.size(); instr++) { u8bit instrCode[16]; // Get the instruction code. programFinal[instr]->getCode(instrCode); // Write the code to the output file. outputFile.write((char *) instrCode, 16); } inputFile.close(); outputFile.close(); }
26.866412
121
0.558034
[ "vector" ]
5f3813af7fd14f15837bb4bfd03a889d5f270c0e
5,994
cpp
C++
testbench/decpt_dtw_aes/mpi/empty.cpp
Arka2009/LOCUS
a0ef0bc9a25456668ef381734b17385da738805a
[ "BSD-3-Clause" ]
8
2017-09-16T10:07:04.000Z
2021-07-27T06:07:28.000Z
testbench/decpt_dtw_aes/mpi/empty.cpp
tancheng/iot-kernels-locus
82da0214bf52061f2739dffd2713dc8691e82b18
[ "BSD-3-Clause" ]
3
2018-08-17T13:13:11.000Z
2018-12-04T03:05:16.000Z
testbench/decpt_dtw_aes/mpi/empty.cpp
tancheng/iot-kernels-locus
82da0214bf52061f2739dffd2713dc8691e82b18
[ "BSD-3-Clause" ]
1
2021-08-08T04:30:55.000Z
2021-08-08T04:30:55.000Z
#include <stdlib.h> #include <iostream> #include <vector> #define DUMP #ifdef DUMP #include "mpi.h" #include <m5op.h> #endif #ifndef DUMP #include <mpi/mpi.h> #endif #define TAG 0 using namespace std; //#define SIZE 513 //#define SIZE 1025 #define SIZE 101 #define NUM 10 int S[SIZE]; //int *S; int T[SIZE]; //int *T; int DTW[SIZE+1][(SIZE-1)/NUM+2]; int numprocs, myid; MPI_Status status; MPI_Request request; int minimum(int a, int b, int c) { int min = 65536; if(a<b) { min = a; }else{ min = b; } if(min>c) { min = c; } return min; } int minimum(int a, int b) { int min = 65536; if(a<b) { min = a; }else{ min = b; } return min; } int maximum(int a, int b, int c) { int max = 0; if(a<b) { max = b; }else{ max = a; } if(max<c) { max = c; } return max; } int maximum(int a, int b) { int max = 0; if(a<b) { max = b; }else{ max = a; } return max; } int absolute(int v) { if(v<0) { v = -v; } return v; } void output() { for(int i=SIZE;i<SIZE+1;++i) { cout<<"["<<i<<"] "; for(int j=(SIZE-1)/NUM;j<(SIZE-1)/NUM+2;++j) { cout<<DTW[i][j]<<"\t"; } cout<<endl; } } void get_data(int len, int **sa, int **ta) { char filename_std[256] = {"input_dtw/input_std"}; char filename_smp[256] = {"input_dtw/input_smp"}; int base_fname_length = 18; // char rank_str[20]; // sprintf(rank_str, "%d", rank); // for(i = 0; rank_str[i] != '\0'; i++) // filename[base_fname_length + i] = rank_str[i]; filename_std[base_fname_length + 1] = '\0'; FILE *fp = fopen(filename_std, "r"); if(fp == NULL) { printf("\ncannot open file \"%s\".\n", filename_std); exit(1); } int *data = (int*)malloc(sizeof(int) * len); int length = len; int *p = data; float t = 0; float ign = 0; while (len--) { fscanf(fp, "%f,%f", &t, &ign); *p = (int)t; // printf("core %d std value read = %d\n", rank, *p); //scanf("%f", p); //scanf("%" DATA_FMT, p); p++; } fclose(fp); *sa = data; fp = fopen(filename_smp, "r"); if(fp == NULL) { printf("\ncannot open file \"%s\".\n", filename_smp); exit(1); } len = length; data = (int*)malloc(sizeof(int) * len); p = data; t = 0; ign = 0; while (len--) { fscanf(fp, "%f,%f", &t, &ign); *p = (int)t; //scanf("%f", p); //scanf("%" DATA_FMT, p); // printf("core %d smp value read = %d\n", rank, *p); p++; } fclose(fp); *ta = data; } void initialize(int id) { int temp_s[SIZE];// = {1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7}; for(int i=0;i<SIZE;++i) { temp_s[i] = i+1; } // if(myid == 0) // cout <<"S:\t"; for(int i=0;i<SIZE;++i) { S[i] = temp_s[i]; // if(myid == 0) // cout << temp_s[i] << "\t"; } int temp_t[SIZE];// = {2,3,4,5,6,7,8,9,11,3,4,5,6,7,8,9,10}; for(int i=0; i<SIZE; ++i) { temp_t[i] = i+3; } // if(myid == 0) // cout <<"\nT:\t"; for(int j=0;j<SIZE;++j) { T[j] = temp_t[j]; // if(myid == 0) // cout << temp_t[j] << "\t"; } // get_data(SIZE, &S, &T); if(id == 0) { for(int i=1; i<SIZE+1; ++i) { DTW[i][0] = 65536; DTW[i][1] = 65536; } cout << "\n-------------------------------------------------------" << endl; } int j = ((SIZE-1)/NUM) * (id%NUM) + 1; for(int x=1; x<(SIZE-1)/NUM+2; ++x) { DTW[0][x] = 65536; } if(j == 1) { DTW[0][0] = 0; DTW[1][0] = 65536; }else{ DTW[0][0] = 65536; DTW[1][0] = absolute(S[0] - T[j-2]); } for(int x=1; x<(SIZE-1)/NUM+2; ++x) { DTW[1][x] = absolute(S[0] - T[j+x-2]); } } void DTWVariation(int id, int base) { int cost[(SIZE-1)/NUM]; int j = ((SIZE-1)/NUM) * id + 1; int tmp[2]; //m5_opt_set_send(id+1, 1, MPI_INT); for(int i=1; i<SIZE; ++i) { for(int x=0; x<(SIZE-1)/NUM; ++x) { cost[x] = absolute(S[i]-T[j+x]); } // if(((i-1)%20) == 0) // MPI_Barrier(MPI_COMM_WORLD); if(id != 0) { MPI_Recv(&DTW[i+1][0], 2, MPI_INT, id-1 + base, 0, MPI_COMM_WORLD, &status); } else { MPI_Recv(tmp, 2, MPI_INT, id-1 + base, 0, MPI_COMM_WORLD, &status); } int x; for(x=0; x<(SIZE-1)/NUM; ++x) { DTW[i+1][x+2] = cost[x] + minimum(DTW[i-1][x+1], DTW[i][x+1], DTW[i][x]); } /* DTW[i+1][x+2] = cost[x] + minimum(DTW[i-1][x+1], DTW[i][x+1], DTW[i][x]); m5_opt_send(); ++x; DTW[i+1][x+2] = cost[x] + minimum(DTW[i-1][x+1], DTW[i][x+1], DTW[i][x]); m5_opt_send(); */ if(id != NUM-1) { MPI_Send(&DTW[i+1][(SIZE-1)/NUM], 2, MPI_INT, id+1 + base, 0, MPI_COMM_WORLD); } if(((i-1)%20) == 0) MPI_Barrier(MPI_COMM_WORLD); } } int main(int argc, char **argv) { MPI_Init(&argc, &argv);/* MPI programs start with MPI_Init; all 'N' processes exist thereafter */ MPI_Comm_size(MPI_COMM_WORLD, &numprocs);/* find out how big the SPMD world is */ MPI_Comm_rank(MPI_COMM_WORLD, &myid);/* and this process' rank is */ int base = 6; initialize(myid - base); if(myid == base) { cout<<"================= DTW variation=============="<<endl; } else { cout<<"core id = "<<myid<<" inited for dtw..."<<endl; } MPI_Barrier(MPI_COMM_WORLD); if(myid == 0) { #ifdef DUMP m5_dump_stats(0, 0); m5_reset_stats(0, 0); #endif } // MPI_Barrier(MPI_COMM_WORLD); DTWVariation(myid-base, base); if(myid == numprocs-1) { #ifdef DUMP m5_dump_stats(0, 0); m5_reset_stats(0, 0); #endif } // MPI_Barrier(MPI_COMM_WORLD); if(myid == numprocs-1){ cout << "-------------------- focus the last column ---------------------" << endl; output(); } // MPI_Barrier(MPI_COMM_WORLD); return 0; }
18.27439
98
0.475976
[ "vector" ]
5f3be28eba1883aaaabedc77b8c826dda5469ccc
1,273
cpp
C++
algorithms/strings/WeightedUniformStrings.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
algorithms/strings/WeightedUniformStrings.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
algorithms/strings/WeightedUniformStrings.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; vector<string> weightedUniformStrings(string s, vector<int> queries) { vector<bool> u (1e7); int cur, factor=1, w, last=0; for(int i=0; i<s.size(); i++) { cur = s[i] - 'a' + 1; if(cur==last) factor++; else factor = 1; last = cur; w = cur * factor; u[w] = true; } vector<string> results (0); for(auto q : queries) { if(u[q] == true) results.push_back("Yes"); else results.push_back("No"); } return results; } int main() { ofstream fout(getenv("OUTPUT_PATH")); string s; getline(cin, s); int queries_count; cin >> queries_count; cin.ignore(numeric_limits<streamsize>::max(), '\n'); vector<int> queries(queries_count); for (int i = 0; i < queries_count; i++) { int queries_item; cin >> queries_item; cin.ignore(numeric_limits<streamsize>::max(), '\n'); queries[i] = queries_item; } vector<string> result = weightedUniformStrings(s, queries); for (int i = 0; i < result.size(); i++) { fout << result[i]; if (i != result.size() - 1) { fout << "\n"; } } fout << "\n"; fout.close(); return 0; }
20.532258
70
0.527887
[ "vector" ]
5f4b98534a185377be0e097cd502360d20628739
3,218
hpp
C++
inc/actuators.hpp
samuelluohaoen1/gTest-Example-with-Makefile
7d0062da05382fddec2b8522dde4eedd7c16a333
[ "MIT" ]
null
null
null
inc/actuators.hpp
samuelluohaoen1/gTest-Example-with-Makefile
7d0062da05382fddec2b8522dde4eedd7c16a333
[ "MIT" ]
null
null
null
inc/actuators.hpp
samuelluohaoen1/gTest-Example-with-Makefile
7d0062da05382fddec2b8522dde4eedd7c16a333
[ "MIT" ]
null
null
null
#ifndef __ACTUATORS_H #define __ACTUATORS_H #include "common.hpp" #include "sensors.hpp" class GrSim_Console{ private: typedef boost::asio::ip::udp udp; typedef boost::asio::io_service io_service; typedef boost::shared_ptr<udp::socket> socket_ptr; // smart pointer(no need to mannually deallocate static const unsigned int BUF_SIZE = 256; io_service *ios; udp::endpoint *ep; socket_ptr socket; public: GrSim_Console(io_service& io_srvs, udp::endpoint& endpoint); ~GrSim_Console(); void send_command(bool is_team_yellow, int id, float upper_left_wheel_speed, float lower_left_wheel_speed, float lower_right_wheel_speed, float upper_right_wheel_speed, // float x, float y, float omega, float kick_speed_x, float kick_speed_y, bool spinner); }; class Actuator_System { private: typedef boost::asio::ip::udp udp; typedef boost::asio::io_service io_service; typedef boost::shared_ptr<GrSim_Console> GrSim_Console_ptr; typedef boost::shared_ptr<boost::thread> thread_ptr; typedef boost::shared_ptr<boost::asio::deadline_timer> timer_ptr; team_color_t color; int id; GrSim_Console_ptr console; thread_ptr v_thread; boost::mutex mu; boost::condition_variable_any cond_init_finished; unsigned int ctrl_period_ms = 10; // milliseconds timer_ptr timer; arma::vec unit_vec_A = {0, 0}; // left-upper direction arma::vec unit_vec_B = {0, 0}; // right upper direction double max_trans = 0.00; double max_rot = 0.00; bool param_loaded = false; void send_cmd_thread(udp::endpoint& c_ep); void timer_expire_callback(); public: float wheel_upper_left_vel = 0.00, wheel_lower_left_vel = 0.00, wheel_lower_right_vel = 0.00, wheel_upper_right_vel = 0.00; float kick_speed_x = 0.00, kick_speed_y = 0.00; bool dribbler_on = false; Actuator_System(team_color_t color, int robot_id, udp::endpoint& grsim_console_ep); void load_robot_params(arma::vec left_vec, arma::vec right_vec, double max_trans_mms, double max_rotat_ds); void set_ctrl_freq(float freq_Hz); void set_ctrl_period(float period_ms); // unit: rad/s inline void set_wheels_speeds(float upper_left, float lower_left, float lower_right, float upper_right) { wheel_upper_left_vel = upper_left; wheel_lower_left_vel = lower_left; wheel_lower_right_vel = lower_right; wheel_upper_right_vel = upper_right; } inline void turn_on_dribbler() { dribbler_on = true; } inline void turn_off_dribbler() { dribbler_on = false; } inline void kick(float speed_x, float speed_y) { kick_speed_x = speed_x; kick_speed_y = speed_y; } void stop(); void rotate(float angular_velocity); void move(arma::vec vec_2d); // cartesian vector void move(float angle, float speed); // polor coord /* Note: when coupled with pid, move is called by mobilize & sprint */ }; #endif
31.242718
103
0.660037
[ "vector" ]
5f51339568df9779ba658c185341b9fc6eb07d38
2,575
hpp
C++
Code/Engine/Physics2D/Collider2D.hpp
yixuan-wei/PersonalEngine
6f3b1df3ddeb662fbf65ca8b3ea7ddb446ef5a20
[ "MIT" ]
1
2021-06-11T06:41:29.000Z
2021-06-11T06:41:29.000Z
Code/Engine/Physics2D/Collider2D.hpp
yixuan-wei/PersonalEngine
6f3b1df3ddeb662fbf65ca8b3ea7ddb446ef5a20
[ "MIT" ]
1
2022-02-25T07:46:54.000Z
2022-02-25T07:46:54.000Z
Code/Engine/Physics2D/Collider2D.hpp
yixuan-wei/PersonalEngine
6f3b1df3ddeb662fbf65ca8b3ea7ddb446ef5a20
[ "MIT" ]
null
null
null
#pragma once #include "Engine/Core/Rgba8.hpp" #include "Engine/Core/Delegate.hpp" #include "Engine/Math/Vec2.hpp" #include "Engine/Math/Disc2.hpp" #include "Engine/Physics2D/PhysicsMaterial.hpp" #include <vector> struct Vertex_PCU; class Physics2D; class Rigidbody2D; struct Manifold2; enum eSimulationMode : int; ////////////////////////////////////////////////////////////////////////// enum eCollider2DType { COLLIDER2D_DISC, COLLIDER2D_POLYGON, NUM_COLLIDER2D_TYPES }; ////////////////////////////////////////////////////////////////////////// class Collider2D { friend class Physics2D; public: Delegate<Collider2D const*, Collider2D const*> OnTriggerEnter; Delegate<Collider2D const*, Collider2D const*> OnTriggerStay; Delegate<Collider2D const*, Collider2D const*> OnTriggerLeave; public: // Interface Collider2D() = default; // cache off the world shape representation of this object // taking into account the owning rigidbody (if no owner, local is world) virtual void UpdateWorldShape() = 0; virtual void Move(Vec2 const& moveDelta) = 0; // queries virtual Disc2 GetWorldBounds() const = 0; virtual Vec2 GetSupport(Vec2 const& direction) const = 0; virtual Vec2 GetClosestPoint( Vec2 pos ) const = 0; virtual bool Contains( Vec2 pos ) const = 0; virtual float CalculateMomentInertia(float mass) const = 0; // debug helpers virtual void AddVertsForDebugRender( std::vector<Vertex_PCU>& verts, Rgba8 const& borderColor, Rgba8 const& fillColor, bool drawBounds = false, float borderWidth = .2f, float scale=1.f ) = 0; protected: virtual ~Collider2D(); // private - make sure this is virtual so correct deconstructor gets called public: // any helpers you want to add eCollider2DType GetType() const { return m_type; } bool IsTrigger() const { return m_isTrigger; } bool Intersects(Collider2D const* other) const; bool GetManifold(Collider2D const* other, Manifold2* outManifold)const; float GetBounceWith(Collider2D const* other) const; float GetFrictionWith(Collider2D const* other) const; float GetMass() const; eSimulationMode GetSimulationMode() const; void SetIsTrigger(bool isTrigger); public: eCollider2DType m_type; // keep track of the type - will help with collision later Physics2D* m_system = nullptr; // system who created or destr Rigidbody2D* m_rigidbody = nullptr; // owning rigidbody, used for calculating world shape PhysicsMaterial m_physicsMaterial; private: bool m_isDestroyed = false; bool m_isTrigger = false; };
33.012821
120
0.700971
[ "object", "shape", "vector" ]
34fda547563fb551f4d391187fab68c0323da95f
17,441
cpp
C++
src/main.cpp
lmish001/rshell
b892987386efa6685fdd9adcc9beda20cc2ae210
[ "BSD-3-Clause" ]
null
null
null
src/main.cpp
lmish001/rshell
b892987386efa6685fdd9adcc9beda20cc2ae210
[ "BSD-3-Clause" ]
null
null
null
src/main.cpp
lmish001/rshell
b892987386efa6685fdd9adcc9beda20cc2ae210
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <string> #include <cstring> #include <vector> #include <unistd.h> #include <limits.h> #include "stdio.h" #include <stdlib.h> #include <stack> #include <limits> #include <sstream> #include<boost/tokenizer.hpp> using namespace std; #include "Parse.h" // Parse separates userInput and should construct a tree of commands to be executed std::vector<std::string> separator(const std::string & userInput, const std::vector<std::string> & connectors); // Eliminates any possible spacing related issue void fixVectorSpacing(std::vector<std::string> &); // Function that helps check for invalid syntax bool syntaxChecker(std::vector<std::string> &); // Converts vector or userinput into postfix notation std::vector<std::string> postfixConverter(const std::vector<std::string> &v); // Function that will be used to help handle quotations being passed in from user bool findMatch(const std::string &userInput, unsigned i, unsigned &addAmt, const char); // Function used to help handle brackets being passed in bool findMatchBracket(const std::string &userInput, unsigned i, unsigned &j); // Function checks to make sure quotations are balanced and parentheses and brackets are balanced. Outputs an error if not. bool balancedSyntax(const std::string &userInput); // Function that checks to make sure parentheses are correct syntactically. Should be final syntax checker bool properSyntax(const std::vector<std::string> & v); // Adds parentheses to fix order of execution for io redirection void fix_io(std::vector<std::string> & v); int main(){ std::string userInput; std::vector<std::string> connectors; connectors.push_back("&&"); connectors.push_back("||"); connectors.push_back("#"); connectors.push_back(";"); connectors.push_back(">>"); // Output_Redir2 connectors.push_back(">"); // Output_Redir1 connectors.push_back("<"); // Input_Redir connectors.push_back("|"); // Pipe int exit; Parse* p; system("./name.sh"); // pipeCreator.cpp is the file we use to help handle piping. system("rm -rf pipeCreator.cpp"); system("rm -rf pipeCreator.out"); while ( getline(std::cin, userInput)){ if (userInput.size() != 0){ std::vector<std::string> separated_V = separator(userInput, connectors); fixVectorSpacing(separated_V); if (syntaxChecker(separated_V) && properSyntax(separated_V)){ fix_io(separated_V); std::vector<std::string> v1 = postfixConverter(separated_V); if (!v1.empty()){ p = new Parse(v1); p->createTree(); exit = p->run(); separated_V.clear(); std::cout << flush; system("rm -rf pipeCreator.cpp"); if (exit == 2){ break; } } } } system("./name.sh"); } return 0; } std::vector<std::string> separator (const std::string &userInput, const std::vector<std::string> &connectors){ std::vector<std::string> complexParsed; std::string temp; std::string conn_temp; char conn_temp2; if (!balancedSyntax(userInput)){ return complexParsed; } for (unsigned i = 0; i < userInput.size(); ++i){ bool flag = false; unsigned addAmt = 0; for (unsigned j = 0; j < connectors.size(); ++j){ if (!flag){ conn_temp = connectors.at(j); conn_temp2 = conn_temp.at(0); if ( ((userInput.at(i) == '\"') && findMatch(userInput, i, addAmt, '\"')) || ((userInput.at(i) == '\'') && findMatch(userInput, i, addAmt, '\'')) ){ ++i; while (addAmt > 0 && i < userInput.size()){ temp += userInput.at(i); i++; addAmt--; } ++i; if (i >= userInput.size()){ complexParsed.push_back(temp); return complexParsed; } } else if ((userInput.at(i) == '[') && findMatchBracket(userInput, i, addAmt)){ if (!temp.empty()){ complexParsed.push_back(temp); temp.clear(); } ++i; temp += "test"; while (addAmt > 0 && i < userInput.size()){ temp += userInput.at(i); i++; addAmt--; } if (userInput.at(i - 1) != ' ' ){ //std::cout << "bash: [: missing `]\'" << std::endl; temp = "test -f -d -e syntaxStuff"; complexParsed.push_back(temp); temp.clear(); } else { complexParsed.push_back(temp); temp.clear(); } i++; if (i >= userInput.size()){ return complexParsed; } } if ((userInput.at(i) == '(') || (userInput.at(i) == ')')){ if (!temp.empty()){ complexParsed.push_back(temp); temp.clear(); } temp += userInput.at(i); complexParsed.push_back(temp); temp.clear(); flag = true; } else if (userInput.at(i) == conn_temp2){ bool enter = true; if (conn_temp.size() == 1){ if (!temp.empty()){ // Prevents a single space from being pushed into its own spot in the vector if (!(temp.size() == 1 && temp.at(0) == ' ')){ complexParsed.push_back(temp); } temp.clear(); } if (conn_temp2 == '#'){ if (i == 0){ return complexParsed; } else if (userInput.at(i - 1) == ' '){ return complexParsed; } else { enter = false; flag = true; temp += "#"; } } if (enter){ complexParsed.push_back(conn_temp); flag = true; } } else if (i + 1 < userInput.size() && userInput.at(i + 1) == conn_temp2){ if (!temp.empty()){ // Prevents a single space from being pushed into its own spot in the vector if (!(temp.size() == 1 && temp.at(0) == ' ')){ complexParsed.push_back(temp); } temp.clear(); } complexParsed.push_back(conn_temp); flag = true; i++; } } } } // Makes sure a connector doesnt get re-added to the vector in another spot if(!flag) { temp += userInput.at(i); } } if (!temp.empty()){ complexParsed.push_back(temp); } return complexParsed; } void fixVectorSpacing(std::vector<std::string> &v){ for (unsigned i = 0; i < v.size(); ++i){ if (v.at(i).empty()){ v.erase(v.begin() + i); } else if (v.at(i).at(0) == ' ' || v.at(i).at(v.at(i).size() - 1) == ' '){ if (v.at(i).at(0) == ' '){ unsigned j = 0; // Counts number of spaces while (j < v.at(i).size() && v.at(i).at(j) == ' '){ ++j; } // If a v.at(i) contains solely spaces, v.at(i) is deleted if (v.at(i).size() == j){ v.erase(v.begin() + i); } // Otherwise, the beginning spaces are removed else if (j > 0){ v.at(i) = v.at(i).substr(j,v.at(i).size() - j); } } while (!(v.at(i).empty()) && v.at(i).at(v.at(i).size() - 1) == ' '){ v.at(i).erase(v.at(i).size() - 1); } if (v.at(i).empty()){ v.erase(v.begin() + i); } } else if (v.at(i).at(0) == '#'){ v.at(i - 1) += v.at(i); v.erase(v.begin() + i); } } } bool findMatch(const std::string &userInput, unsigned i, unsigned &addAmt, const char grouper){ ++i; for(; i < userInput.size(); ++i){ ++addAmt; if (userInput.at(i) == grouper){ --addAmt; return true; } } addAmt = 0; return false; } bool findMatchBracket(const std::string &userInput, unsigned i, unsigned &j){ unsigned numInstances = 1; ++i; for(; i < userInput.size(); ++i){ ++j; if (userInput.at(i) == '['){ ++numInstances; } if (userInput.at(i) == ']'){ if (numInstances == 1){ --j; return true; } else { --numInstances; } } } j = 0; return false; } bool balancedSyntax(const std::string &userInput){ bool doubleQuoteBalanced = true; int parenCounter = 0; for(unsigned i = 0; i < userInput.size(); ++i){ if (userInput.at(i) == '\"'){ doubleQuoteBalanced = !doubleQuoteBalanced; } else if (doubleQuoteBalanced && userInput.at(i) == '('){ parenCounter++; } else if (doubleQuoteBalanced && userInput.at(i) == ')'){ if (parenCounter <= 0){ std::cout << "error: parentheses are unbalanced" << std::endl; return false; } else { parenCounter--; } } } if (parenCounter != 0){ std::cout << "syntax error: parentheses are unbalanced" << std::endl; return false; } else if (!doubleQuoteBalanced){ std::cout << "syntax error: double quotes are unbalanced" << std::endl; return false; } return true; } std::vector<std::string> postfixConverter(const std::vector<std::string> &v){ std::vector<std::string> postfix; std::vector<std::string> temp; std::stack<std::string> s; std::string c; for(unsigned i = 0; i < v.size();++i){ c = v.at(i); if (c == "&&" || c == "||" || c == ";" || c == ">>" || c == ">" || c == "<" || c == "|" || c == "(" || c == ")"){ //c is an operator if ( c == "("){ s.push(c); } else if (c == ")"){ while (s.top() != "("){ postfix.push_back(s.top()); s.pop(); } s.pop(); } else{ while (!s.empty()){ if (s.top() == "("){ break; } postfix.push_back(s.top()); s.pop(); } s.push(c); } } else{ postfix.push_back(c); } } while (!s.empty()){ postfix.push_back(s.top()); s.pop(); } return postfix; } bool syntaxChecker(std::vector<std::string> &v){ // Need special checker for ()'s' int counter = 0; int parenCounter = 0; bool io_flag = false; if (v.empty()){ // No syntax exists to be checked return true; } // The first item in the vector should never be a connector if (v.at(0) == "&&" || v.at(0) == "||" || v.at(0) == ";" || v.at(0) == ">>" || v.at(0) == ">" || v.at(0) == "<" || v.at(0) == "|"){ std::cout << "bash: syntax error near unexpected token: " << v.at(0) << std::endl; return false; } if (v.size() == 1 && (v.at(0) == "(" || v.at(0) == ")")){ std::cout << "bash: syntax error near unexpected token: " << v.at(0) << std::endl; return false; } // This loop will check to make sure "connectors" are not placed consecutively after each other for (unsigned i = 0; i < v.size(); ++i){ if (v.at(i) == "&&" || v.at(i) == "||" || v.at(i) == ";" || v.at(i) == ">>" || v.at(i) == ">" || v.at(i) == "<" || v.at(i) == "|"){ ++counter; // Certain connectors cannot be followed by anything in parentheses if(v.at(i) == ">>" || v.at(i) == ">" || v.at(i) == "<" || v.at(i) == "|"){ io_flag = true; } } else if (v.at(i) == "(" || v.at(i) == ")"){ if (io_flag){ std::cout << "bash: syntax error near unexpected token: " << v.at(i) << std::endl; return false; } if (v.at(i) == "("){ ++parenCounter; } else { if (parenCounter > 0){ --parenCounter; } else { std::cout << "bash: syntax error near unexpected token: " << v.at(i) << std::endl; return false; } } } else { counter = 0; io_flag = false; } if (counter >= 2){ std::cout << "bash: syntax error near unexpected token: " << v.at(i) << std::endl; return false; } // Makes sure a "connector" is not the last item passed from userInput if (i == v.size() - 1){ if (v.at(i) == "&&" || v.at(i) == "||" || v.at(i) == ">>" || v.at(i) == ">" || v.at(i) == "<" || v.at(i) == "|"){ std::cout << "bash: syntax error near unexpected token: " << v.at(i) << std::endl; return false; } else if (v.at(i) == ";"){ v.pop_back(); } } } if (parenCounter != 0){ // Parentheses were unbalanced std::cout << "bash: syntax error near unexpected token: (" << std::endl; return false; } return true; } bool properSyntax(const std::vector<std::string> & v){ std::string p; bool flag = false; for (unsigned i = 0; i < v.size(); ++i){ p = v.at(i); if (p == "("){ if (i > 0){ if (v.at(i - 1) != "(" && !(v.at(i - 1) == "&&" || v.at(i - 1) == "||" || v.at(i - 1) == ";" || v.at(i - 1) == ">>" || v.at(i - 1) == ">" || v.at(i - 1) == "<" || v.at(i - 1) == "|")){ std::cout << "bash: syntax error near unexpected token: " << v.at(i - 1) << std::endl; return false; } } flag = true; } else if (p == ")"){ if (v.at(i - 1) == "&&" || v.at(i - 1) == "||" || v.at(i - 1) == ";" || v.at(i - 1) == ">>" || v.at(i - 1) == ">" || v.at(i - 1) == "<" || v.at(i - 1) == "|" || v.at(i - 1) == "("){ std::cout << "bash: syntax error near unexpected token: " << v.at(i - 1) << std::endl; return false; } flag = false; } else if (flag){ if (p == "&&" || p == "||" || p == ";" || p == ">>" || p == ">" || p == "<" || p == "|"){ std::cout << "bash: syntax error near unexpected token: " << p << std::endl; return false; } flag = false; } } return true; } void fix_io(std::vector<std::string> & v){ //std::cout << "Fixme: fix_io: need to be able to handle consecutive uses" << std::endl; int lastSeen = 0; bool flag = false; for (unsigned i = 0; i < v.size(); ++i){ if (v.at(i) == "&&" || v.at(i) == "||" || v.at(i) == ";" || v.at(i) == ">>" || v.at(i) == ">" || v.at(i) == "<" || v.at(i) == "|"){ if((v.at(i) == ">>" || v.at(i) == ">" || v.at(i) == "<" || v.at(i) == "|") && v.at(i - 1) != ")" ){ lastSeen = i; v.insert((v.begin() + i - 1), "("); v.insert((v.begin() + i + 3), ")"); ++i; flag = true; } else if((v.at(i) == "&&" || v.at(i) == "||" || v.at(i) == ";" ) && v.at(i - 1) == ")" ){ flag = false; } else if(flag){ v.insert((v.begin() + lastSeen - 1), "("); v.insert((v.begin() + i + 3), ")"); ++i; } } } }
35.092555
200
0.407603
[ "vector" ]
55120b59a1656cbcc463eaeefd087f8940d6df75
254
hpp
C++
lib/binding/cpu.hpp
Time1ess/StatsGenius
9f6e83d7b6b18aa6ea77b5f795e3473f23530648
[ "MIT" ]
null
null
null
lib/binding/cpu.hpp
Time1ess/StatsGenius
9f6e83d7b6b18aa6ea77b5f795e3473f23530648
[ "MIT" ]
null
null
null
lib/binding/cpu.hpp
Time1ess/StatsGenius
9f6e83d7b6b18aa6ea77b5f795e3473f23530648
[ "MIT" ]
null
null
null
#pragma once #include <nan.h> #include <vector> using namespace std; namespace StatsGenius { NAN_METHOD(V8GetAverageLoad); NAN_METHOD(V8GetCPUTotalUsage); NAN_METHOD(V8GetCPUCoresUsage); NAN_METHOD(V8GetCPUCoresTemperature); NAN_METHOD(V8GetUptime); }
18.142857
37
0.818898
[ "vector" ]
551dfd45fb0e94442fec8ca0b240db6721544cec
8,123
cpp
C++
XLib-v1.2.0/src/Graph/Host/GraphSTD_Read.cpp
mangrove-univr/Mangrove
3d95096c7adfad5eb27625b020c222487e91ab4e
[ "MIT" ]
1
2019-12-28T09:30:24.000Z
2019-12-28T09:30:24.000Z
XLib-v1.2.0/src/Graph/Host/GraphSTD_Read.cpp
mangrove-univr/Mangrove
3d95096c7adfad5eb27625b020c222487e91ab4e
[ "MIT" ]
1
2020-08-25T10:57:11.000Z
2020-08-25T10:57:11.000Z
XLib-v1.2.0/src/Graph/Host/GraphSTD_Read.cpp
mangrove-univr/Mangrove
3d95096c7adfad5eb27625b020c222487e91ab4e
[ "MIT" ]
null
null
null
/*------------------------------------------------------------------------------ Copyright © 2016 by Nicola Bombieri XLib is provided under the terms of The MIT License (MIT): 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. ------------------------------------------------------------------------------*/ /** * @author Federico Busato * Univerity of Verona, Dept. of Computer Science * federico.busato@univr.it */ #include <sstream> #include <cstring> //std::strtok #include "Base/Host/fUtil.hpp" #include "Base/Host/file_util.hpp" #if __linux__ #include <stdio.h> #include <sys/types.h> #include <sys/mman.h> #include <fcntl.h> #include <sys/stat.h> #include <unistd.h> #endif namespace graph { template<typename node_t, typename edge_t, typename dist_t> void GraphSTD<node_t, edge_t, dist_t> ::readMatrixMarket(std::ifstream& fin, bool randomize) { coo_edges = GraphBase<node_t, edge_t>::getMatrixMarketHeader(fin); Allocate(); xlib::Progress progress(static_cast<std::size_t>(coo_edges)); for (int lines = 0; lines < coo_edges; lines++) { node_t index1, index2; fin >> index1 >> index2; COO_Edges[lines][0] = index1 - 1; COO_Edges[lines][1] = index2 - 1; progress.next(static_cast<std::size_t>(lines + 1)); xlib::skipLines(fin); } ToCSR(randomize); } template<typename node_t, typename edge_t, typename dist_t> void GraphSTD<node_t, edge_t, dist_t>::readDimacs9(std::ifstream& fin, bool randomize) { coo_edges = GraphBase<node_t, edge_t>::getDimacs9Header(fin); Allocate(); xlib::Progress progress(static_cast<std::size_t>(coo_edges)); int c; int lines = 0; std::string nil; while ((c = fin.peek()) != EOF) { if (c == static_cast<int>('a')) { node_t index1, index2; fin >> nil >> index1 >> index2; COO_Edges[lines][0] = index1 - 1; COO_Edges[lines][1] = index2 - 1; progress.next(static_cast<std::size_t>(++lines)); } xlib::skipLines(fin); } ToCSR(randomize); } template<typename node_t, typename edge_t, typename dist_t> void GraphSTD<node_t, edge_t, dist_t>::readKonect(std::ifstream& fin, bool randomize) { GraphBase<node_t, edge_t>::getKonectHeader(fin); xlib::UniqueMap<node_t> unique_map; std::vector<node_t> COO_Edges_v; int n_of_lines = 0; while (fin.good()) { node_t index1, index2; fin >> index1 >> index2; unique_map.insertValue(index1); unique_map.insertValue(index2); COO_Edges_v.push_back(index1 - 1); COO_Edges_v.push_back(index2 - 1); n_of_lines++; } V = static_cast<node_t>(unique_map.size()); E = n_of_lines; coo_edges = n_of_lines; Allocate(); std::copy(COO_Edges_v.begin(), COO_Edges_v.end(), (node_t*) COO_Edges); ToCSR(randomize); } template<typename node_t, typename edge_t, typename dist_t> void GraphSTD<node_t, edge_t, dist_t>::readNetRepo(std::ifstream& fin, bool randomize) { GraphBase<node_t, edge_t>::getNetRepoHeader(fin); xlib::UniqueMap<node_t> unique_map; std::vector<node_t> COO_Edges_v; int n_of_lines = 0; while (!fin.eof()) { node_t index1, index2; fin >> index1; fin.ignore(1, ','); fin >> index2; unique_map.insertValue(index1); unique_map.insertValue(index2); COO_Edges_v.push_back(index1 - 1); COO_Edges_v.push_back(index2 - 1); n_of_lines++; } V = static_cast<node_t>(unique_map.size()); E = n_of_lines; coo_edges = n_of_lines; Allocate(); std::copy(COO_Edges_v.begin(), COO_Edges_v.end(), (node_t*) COO_Edges); ToCSR(randomize); } template<typename node_t, typename edge_t, typename dist_t> void GraphSTD<node_t, edge_t, dist_t>::readDimacs10(std::ifstream& fin) { GraphBase<node_t, edge_t>::getDimacs10Header(fin); coo_edges = E; Allocate(); xlib::Progress progress(static_cast<std::size_t>(coo_edges)); OutOffset[0] = 0; int countEdges = 0; for (int lines = 0; lines < V; lines++) { std::string str; std::getline(fin, str); int degree = 0; char* token = std::strtok(const_cast<char*>(str.c_str()), " "); while (token != NULL) { degree++; node_t dest = std::stoi(token) - 1; OutEdges[countEdges] = dest; COO_Edges[countEdges][0] = lines; COO_Edges[countEdges][1] = dest; if (Direction == EdgeType::DIRECTED) InDegrees[dest]++; countEdges++; token = std::strtok(NULL, " "); } OutDegrees[lines] = degree; progress.next(static_cast<std::size_t>(lines + 1)); } OutOffset[0] = 0; std::partial_sum(OutDegrees, OutDegrees + V, OutOffset + 1); if (Direction == EdgeType::DIRECTED) { InOffset[0] = 0; std::partial_sum(InDegrees, InDegrees + V, InOffset + 1); degree_t* TMP = new degree_t[V](); for (int i = 0; i < E; i++) { const node_t dest = COO_Edges[i][1]; InEdges[ InOffset[dest] + TMP[dest]++ ] = COO_Edges[i][0]; } delete[] TMP; } std::cout << std::endl << std::endl; } template<typename node_t, typename edge_t, typename dist_t> void GraphSTD<node_t, edge_t, dist_t>::readSnap(std::ifstream& fin, bool randomize) { coo_edges = GraphBase<node_t, edge_t>::getSnapHeader(fin); Allocate(); xlib::Progress progress(static_cast<std::size_t>(coo_edges)); while (fin.peek() == '#') xlib::skipLines(fin); xlib::UniqueMap<node_t, node_t> Map; for (int lines = 0; lines < coo_edges; lines++) { node_t ID1, ID2; fin >> ID1 >> ID2; COO_Edges[lines][0] = Map.insertValue(ID1); COO_Edges[lines][1] = Map.insertValue(ID2); progress.next(static_cast<std::size_t>(lines + 1)); } ToCSR(randomize); } #if __linux__ template<typename node_t, typename edge_t, typename dist_t> void GraphSTD<node_t, edge_t, dist_t>::readBinary(const char* File) { const int fd = ::open(File, O_RDONLY, S_IRUSR); const size_t file_size = xlib::fileSize(File); void* memory_mapped = ::mmap(NULL, file_size, PROT_READ, MAP_SHARED, fd, 0); if (memory_mapped == MAP_FAILED) __ERROR("memory_mapped error"); ::madvise(memory_mapped, file_size, MADV_SEQUENTIAL); V = *((node_t*) memory_mapped); memory_mapped = (char*) memory_mapped + sizeof(node_t); E = *((edge_t*) memory_mapped); memory_mapped = (char*) memory_mapped + sizeof(edge_t); Direction = *((EdgeType*) memory_mapped); memory_mapped = (char*) memory_mapped + sizeof(EdgeType); Allocate(); xlib::Batch batch(file_size - sizeof(node_t) - sizeof(edge_t) - sizeof(EdgeType)); batch.readBinary(memory_mapped, OutOffset, V + 1, InOffset, V + 1, OutDegrees, V, InDegrees, V, OutEdges, E, InEdges, E); ::munmap(memory_mapped, file_size); ::close(fd); std::cout << std::endl; } #endif } //@graph
33.566116
88
0.629693
[ "vector" ]
5520ecb90a55bdcf1ccac3cfdba50d2988dc81d7
3,058
cpp
C++
src/Morrigu/Renderer/APIs/Vulkan/Shader.cpp
Ithyx/Morrigu
dc98809467fef2c7f74b81886563abc9e38e157f
[ "MIT" ]
6
2020-08-23T22:53:33.000Z
2021-04-03T20:53:44.000Z
src/Morrigu/Renderer/APIs/Vulkan/Shader.cpp
Ithyx/Morrigu
dc98809467fef2c7f74b81886563abc9e38e157f
[ "MIT" ]
null
null
null
src/Morrigu/Renderer/APIs/Vulkan/Shader.cpp
Ithyx/Morrigu
dc98809467fef2c7f74b81886563abc9e38e157f
[ "MIT" ]
2
2020-09-15T21:01:55.000Z
2021-04-05T13:19:36.000Z
#include "Shader.h" #include "Debug/Instrumentor.h" #include "Renderer/APIs/Vulkan/Helper.h" #include "Renderer/Renderer2D.h" #include <filesystem> #include <ios> namespace { [[nodiscard]] std::vector<char> readFile(const std::string& fileName) { std::ifstream file(fileName, std::ios::ate | std::ios::binary); if (!file.is_open()) { throw std::runtime_error("Could not open file!"); } std::size_t fileSize = static_cast<std::size_t>(file.tellg()); std::vector<char> buffer(fileSize); file.seekg(0); file.read(buffer.data(), fileSize); file.close(); return buffer; } [[nodiscard]] VkShaderModule createShader(const std::vector<char>& code, VkDevice device) { VkShaderModule returnShader; VkShaderModuleCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; createInfo.codeSize = code.size(); createInfo.pCode = reinterpret_cast<const uint32_t*>(code.data()); MRG_VKVALIDATE(vkCreateShaderModule(device, &createInfo, nullptr, &returnShader), "failed to create shader!") return returnShader; } } // namespace namespace MRG::Vulkan { Shader::Shader(const std::string& filePath) { MRG_PROFILE_FUNCTION() std::filesystem::path shaderDir{filePath}; std::filesystem::path vertFile{filePath + "/vert.spv"}; std::filesystem::path fragFile{filePath + "/frag.spv"}; MRG_CORE_ASSERT(std::filesystem::exists(shaderDir), fmt::format("Directory '{}' does not exist!", filePath)) MRG_CORE_ASSERT(std::filesystem::is_directory(shaderDir), fmt::format("Specified path '{}' doesn't reference a directory!", filePath)) MRG_CORE_ASSERT(std::filesystem::exists(vertFile) && std::filesystem::exists(fragFile), fmt::format("Directory '{}' does not contain vulkan shader files!", filePath)) m_name = shaderDir.stem().string(); const auto vertShaderSrc = readFile(vertFile.string()); const auto fragShaderSrc = readFile(fragFile.string()); const auto data = static_cast<WindowProperties*>(glfwGetWindowUserPointer(Renderer2D::getGLFWWindow())); vertexShaderModule = createShader(vertShaderSrc, data->device); fragmentShaderModule = createShader(fragShaderSrc, data->device); } Shader::~Shader() { Shader::destroy(); } void Shader::destroy() { MRG_PROFILE_FUNCTION() if (m_isDestroyed) { return; } const auto data = static_cast<WindowProperties*>(glfwGetWindowUserPointer(Renderer2D::getGLFWWindow())); vkDestroyShaderModule(data->device, vertexShaderModule, nullptr); vkDestroyShaderModule(data->device, fragmentShaderModule, nullptr); m_isDestroyed = true; } void Shader::bind() const {} void Shader::unbind() const {} void Shader::upload(const std::string&, int) {} void Shader::upload(const std::string&, int*, std::size_t) {} void Shader::upload(const std::string&, float) {} void Shader::upload(const std::string&, const glm::vec3&) {} void Shader::upload(const std::string&, const glm::vec4&) {} void Shader::upload(const std::string&, const glm::mat4&) {} } // namespace MRG::Vulkan
31.525773
111
0.716808
[ "vector" ]
5527a49a20c59a246ae9bd02d8613616b062cf88
3,941
cpp
C++
pkg/cmd/src/opt_mgr.cpp
DavidLin2015/AtpgSystem
818b6233cbdfb850c880a328e124e5fde3612f30
[ "CECILL-B" ]
null
null
null
pkg/cmd/src/opt_mgr.cpp
DavidLin2015/AtpgSystem
818b6233cbdfb850c880a328e124e5fde3612f30
[ "CECILL-B" ]
null
null
null
pkg/cmd/src/opt_mgr.cpp
DavidLin2015/AtpgSystem
818b6233cbdfb850c880a328e124e5fde3612f30
[ "CECILL-B" ]
1
2021-01-26T08:26:15.000Z
2021-01-26T08:26:15.000Z
#include <opt_mgr.h> using namespace std; using namespace TCLAP; using namespace CmdNs; bool OptMgr::regArg(const string &name, const string &desc, const string &type_desc, const string &flag, bool is_req, bool is_multi) { if(name_set_.find(name)==name_set_.end()) { //Arg *arg; if(flag.empty()) { if(!is_multi) { ValueArg<string> *arg; arg = new UnlabeledValueArg<string> (name, desc, is_req, "", type_desc); opt_->add(arg); arg_map_[name] = arg; } else { MultiArg<string> *arg; arg = new UnlabeledMultiArg<string> (name, desc, is_req, type_desc); opt_->add(arg); multi_map_[name] = arg; } } else { if(flag_set_.find(flag)==flag_set_.end()) { flag_set_.insert(flag); } else return false; if(!is_multi) { ValueArg<string> *arg; arg = new ValueArg<string> (flag, name, desc, is_req, "", type_desc); opt_->add(arg); arg_map_[name] = arg; } else { MultiArg<string> *arg; arg = new MultiArg<string> (flag, name, desc, is_req, type_desc); opt_->add(arg); multi_map_[name] = arg; } } name_set_.insert(name); return true; } else return false; } bool OptMgr::regOpt(const string &name, const string &desc, bool val, const string &flag) { if(name_set_.find(name)==name_set_.end()) { string f = (flag=="")?name.substr(1):flag; if(flag_set_.find(f)==flag_set_.end()) { SwitchArg *arg = new SwitchArg(f, name, desc, val); opt_->add(arg); flag_set_.insert(f); name_set_.insert(name); opt_map_[name] = arg; return true; } else return false; } else return false; } void OptMgr::parse(vector<string> &args) { opt_->parse(args); } string OptMgr::getVal(const string &name) const { ArgMap::const_iterator it = arg_map_.find(name); if(it!=arg_map_.end()) { return it->second->getValue(); } else { //TODO return ""; } } const vector<string>* OptMgr::getMultiVal(const string &name) const { MultiMap::const_iterator it = multi_map_.find(name); if(it!=multi_map_.end()) { return &(it->second->getValue()); } else { //TODO return NULL; } } bool OptMgr::getOptVal(const string &name) const { OptMap::const_iterator it = opt_map_.find(name); if(it!=opt_map_.end()) { return it->second->getValue(); } else { //TODO return false; } }
29.410448
71
0.375032
[ "vector" ]
5529b9d9f9d891272d498e67224cc952f29e46cd
1,279
cc
C++
src/io.cc
shin1m/xemmai
dbeb22058ffdec0dda7d2575b86e750b87ed4197
[ "MIT", "Unlicense" ]
5
2015-11-01T22:08:39.000Z
2021-06-08T04:44:38.000Z
src/io.cc
shin1m/xemmai
dbeb22058ffdec0dda7d2575b86e750b87ed4197
[ "MIT", "Unlicense" ]
null
null
null
src/io.cc
shin1m/xemmai
dbeb22058ffdec0dda7d2575b86e750b87ed4197
[ "MIT", "Unlicense" ]
null
null
null
#include <xemmai/io.h> #include <xemmai/convert.h> namespace xemmai { void t_io::f_scan(t_scan a_scan) { a_scan(v_symbol_close); a_scan(v_symbol_read); a_scan(v_symbol_write); a_scan(v_symbol_flush); a_scan(v_symbol_read_line); a_scan(v_symbol_write_line); a_scan(v_type_file); a_scan(v_type_reader); a_scan(v_type_writer); a_scan(v_type_path); } std::vector<std::pair<t_root, t_rvalue>> t_io::f_define() { v_symbol_close = t_symbol::f_instantiate(L"close"sv); v_symbol_read = t_symbol::f_instantiate(L"read"sv); v_symbol_write = t_symbol::f_instantiate(L"write"sv); v_symbol_flush = t_symbol::f_instantiate(L"flush"sv); v_symbol_read_line = t_symbol::f_instantiate(L"read_line"sv); v_symbol_write_line = t_symbol::f_instantiate(L"write_line"sv); t_type_of<io::t_file>::f_define(this); v_type_file->v_builtin = true; t_type_of<io::t_reader>::f_define(this); v_type_reader->v_builtin = true; t_type_of<io::t_writer>::f_define(this); v_type_writer->v_builtin = true; t_type_of<portable::t_path>::f_define(this); v_type_path->v_builtin = true; return t_define(this) (L"File"sv, t_object::f_of(v_type_file)) (L"Reader"sv, t_object::f_of(v_type_reader)) (L"Writer"sv, t_object::f_of(v_type_writer)) (L"Path"sv, t_object::f_of(v_type_path)) ; } }
27.804348
64
0.755278
[ "vector" ]
552baed00ddb3935d39dd0a6de168e0eab20935b
1,912
cpp
C++
FMEGraphics/src/InputManager.cpp
FullMetalNicky/FullMetalEngine
26fbdd14332f9ab158180efea176e7aaa47f570c
[ "MIT" ]
12
2018-08-05T17:55:40.000Z
2021-08-22T07:17:12.000Z
FMEGraphics/src/InputManager.cpp
FullMetalNicky/FullMetalEngine
26fbdd14332f9ab158180efea176e7aaa47f570c
[ "MIT" ]
null
null
null
FMEGraphics/src/InputManager.cpp
FullMetalNicky/FullMetalEngine
26fbdd14332f9ab158180efea176e7aaa47f570c
[ "MIT" ]
1
2020-06-08T10:46:05.000Z
2020-06-08T10:46:05.000Z
#include "InputManager.h" using namespace FME::Graphics; void defaultKeyCallbackWrapper(GLFWwindow* window, int key, int scancode, int action, int mode); void defaultMouseCallbackWrapper(GLFWwindow* window, double xpos, double ypos); std::shared_ptr<InputManager> InputManager::m_instance = nullptr; std::shared_ptr<InputManager> InputManager::Instance() { if (m_instance == nullptr) { m_instance = std::shared_ptr<InputManager>(new InputManager()); } return m_instance; } void InputManager::SetWindow(glm::ivec2 windowSize, GLFWwindow* window) { m_lastX = windowSize.x / 2; m_lastY = windowSize.y / 2; m_window = window; glfwSetKeyCallback(m_window, defaultKeyCallbackWrapper); glfwSetCursorPosCallback(m_window, defaultMouseCallbackWrapper); } InputManager::InputManager() { m_keys = std::vector<bool>(1024, false); } void InputManager::defaultKeyCallback(int key, int scancode, int action, int mode) { if (action == GLFW_PRESS) m_keys[key] = true; else if (action == GLFW_RELEASE) m_keys[key] = false; } void InputManager::defaultMouseCallback(double xpos, double ypos) { if (m_firstMouse) { m_lastX = xpos; m_lastY = ypos; m_firstMouse = false; } double xoffset = xpos - m_lastX; double yoffset = m_lastY - ypos; // Reversed since y-coordinates go from bottom to left m_lastX = xpos; m_lastY = ypos; } void defaultKeyCallbackWrapper(GLFWwindow* window, int key, int scancode, int action, int mode) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); InputManager::Instance()->defaultKeyCallback(key, scancode, action, mode); } void defaultMouseCallbackWrapper(GLFWwindow* window, double xpos, double ypos) { InputManager::Instance()->defaultMouseCallback(xpos, ypos); } void InputManager::Update() { glfwPollEvents(); }
23.036145
97
0.714435
[ "vector" ]
552d3a314f4a436cd39cad4184931b6bdb2880ed
3,449
cpp
C++
Sources/AGEngine/Render/Pipelining/Pipelines/CustomRenderPass/DeferredMerging.cpp
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
47
2015-03-29T09:44:25.000Z
2020-11-30T10:05:56.000Z
Sources/AGEngine/Render/Pipelining/Pipelines/CustomRenderPass/DeferredMerging.cpp
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
313
2015-01-01T18:16:30.000Z
2015-11-30T07:54:07.000Z
Sources/AGEngine/Render/Pipelining/Pipelines/CustomRenderPass/DeferredMerging.cpp
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
9
2015-06-07T13:21:54.000Z
2020-08-25T09:50:07.000Z
#include <Render/Pipelining/Pipelines/CustomRenderPass/DeferredMerging.hh> #include <Render/Textures/Texture2D.hh> #include <Render/OpenGLTask/OpenGLState.hh> #include <Render/GeometryManagement/Painting/Painter.hh> #include <Render/ProgramResources/Types/Uniform/Mat4.hh> #include <Render/ProgramResources/Types/Uniform/Sampler/Sampler2D.hh> #include <Render/ProgramResources/Types/Uniform/Vec3.hh> #include <Threads/RenderThread.hpp> #include <Threads/ThreadManager.hpp> #include <Core/ConfigurationManager.hpp> #include <Core/Engine.hh> #include "Render/GeometryManagement/SimpleGeometry.hh" #define DEFERRED_SHADING_MERGING_VERTEX "deferred_shading/deferred_shading_merge.vp" #define DEFERRED_SHADING_MERGING_FRAG "deferred_shading/deferred_shading_merge.fp" namespace AGE { enum Programs { PROGRAM_MERGING = 0, PROGRAM_NBR }; DeferredMerging::DeferredMerging(glm::uvec2 const &screenSize, std::shared_ptr<PaintingManager> painterManager, std::shared_ptr<Texture2D> diffuse, std::shared_ptr<Texture2D> lightAccumulation, std::shared_ptr<Texture2D> shinyAccumulation) : FrameBufferRender(screenSize.x, screenSize.y, painterManager) { _diffuseInput = diffuse; _lightAccuInput = lightAccumulation; _shinyAccuInput = shinyAccumulation; push_storage_output(GL_COLOR_ATTACHMENT0, diffuse); _programs.resize(PROGRAM_NBR); auto confManager = GetEngine()->getInstance<ConfigurationManager>(); auto shaderPath = confManager->getConfiguration<std::string>("ShadersPath"); // you have to set shader directory in configuration path AGE_ASSERT(shaderPath != nullptr); auto vertexShaderPath = shaderPath->getValue() + DEFERRED_SHADING_MERGING_VERTEX; auto fragmentShaderPath = shaderPath->getValue() + DEFERRED_SHADING_MERGING_FRAG; _programs[PROGRAM_MERGING] = std::make_shared<Program>(Program(std::string("basic_3d_render"), { std::make_shared<UnitProg>(vertexShaderPath, GL_VERTEX_SHADER), std::make_shared<UnitProg>(fragmentShaderPath, GL_FRAGMENT_SHADER) })); Key<Painter> quadPainterKey; GetRenderThread()->getQuadGeometry(_quadVertices, quadPainterKey); _quadPainter = _painterManager->get_painter(quadPainterKey); } void DeferredMerging::setAmbient(glm::vec3 const &ambient) { _ambientColor = ambient; } void DeferredMerging::renderPass(const DRBCameraDrawableList &infos) { SCOPE_profile_gpu_i("DefferedMerging pass"); SCOPE_profile_cpu_i("RenderTimer", "DefferedMerging pass"); { SCOPE_profile_gpu_i("Overhead Pipeline"); SCOPE_profile_cpu_i("RenderTimer", "Overhead Pipeline"); _programs[PROGRAM_MERGING]->use(); _programs[PROGRAM_MERGING]->get_resource<Sampler2D>(StringID("diffuse_map", 0x1930bc220c3b5c20)).set(_diffuseInput); _programs[PROGRAM_MERGING]->get_resource<Sampler2D>(StringID("light_buffer", 0x37fe4435679ee18a)).set(_lightAccuInput); _programs[PROGRAM_MERGING]->get_resource<Sampler2D>(StringID("shiny_buffer", 0xb4ca9d8f47190a0b)).set(_shinyAccuInput); _programs[PROGRAM_MERGING]->get_resource<Vec3> (StringID("ambient_color", 0x0bd5d46725794843)).set(_ambientColor); } OpenGLState::glDisable(GL_BLEND); OpenGLState::glDisable(GL_CULL_FACE); OpenGLState::glDisable(GL_DEPTH_TEST); OpenGLState::glDisable(GL_STENCIL_TEST); _quadPainter->uniqueDrawBegin(_programs[PROGRAM_MERGING]); _quadPainter->uniqueDraw(GL_TRIANGLES, _programs[PROGRAM_MERGING], _quadVertices); _quadPainter->uniqueDrawEnd(); } }
38.752809
122
0.796753
[ "render" ]
553295ee6b893ff8f6732a2da9386e77e8f1734c
438
cpp
C++
8/832. Flipping an Image.cpp
eagleoflqj/LeetCode
ca5dd06cad4c7fe5bf679cca7ee60f4348b316e9
[ "MIT" ]
null
null
null
8/832. Flipping an Image.cpp
eagleoflqj/LeetCode
ca5dd06cad4c7fe5bf679cca7ee60f4348b316e9
[ "MIT" ]
1
2021-12-25T10:33:23.000Z
2022-02-16T00:34:05.000Z
8/832. Flipping an Image.cpp
eagleoflqj/LeetCode
ca5dd06cad4c7fe5bf679cca7ee60f4348b316e9
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) { for(auto &row : A) { int i = 0, j = row.size() - 1; while(i < j) { int t = row[i]; row[i] = !row[j]; row[j] = !t; ++i; --j; } if(i == j) row[i] = !row[i]; } return A; } };
23.052632
68
0.324201
[ "vector" ]
553e7184b74545145b77af8b1c429338c98dddcc
4,736
cpp
C++
component/oai-ausf/src/api_server/impl/DefaultApiImpl.cpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-ausf/src/api_server/impl/DefaultApiImpl.cpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-ausf/src/api_server/impl/DefaultApiImpl.cpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
/** * AUSF API * AUSF UE Authentication Service. © 2020, 3GPP Organizational Partners (ARIB, * ATIS, CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved. * * The version of the OpenAPI document: 1.1.1 * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ /* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the OAI 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.openairinterface.org/?page_id=698 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * contact@openairinterface.org */ #include "DefaultApiImpl.h" #include "OCTET_STRING.h" #include "authentication_algorithms_with_5gaka.hpp" #include "logger.hpp" #include <iostream> #include "conversions.hpp" #include "sha256.hpp" #include "UEAuthenticationCtx.h" #include "ConfirmationDataResponse.h" #include "AuthenticationInfo.h" #include <typeinfo> #include <map> #include "ausf_config.hpp" #include "ausf_client.hpp" #include "ProblemDetails.h" using namespace config; extern ausf_config ausf_cfg; using namespace std; namespace oai { namespace ausf_server { namespace api { using namespace oai::ausf_server::model; DefaultApiImpl::DefaultApiImpl( std::shared_ptr<Pistache::Rest::Router> rtr, ausf_app* ausf_app_inst, std::string address) : DefaultApi(rtr), m_ausf_app(ausf_app_inst), m_address(address) {} void DefaultApiImpl::eap_auth_method( const std::string& authCtxId, const EapSession& eapSession, Pistache::Http::ResponseWriter& response) { Logger::ausf_server().info("eap_auth_method"); response.send( Pistache::Http::Code::Not_Implemented, "eap_auth_method API has not been implemented yet!\n"); } void DefaultApiImpl::rg_authentications_post( const RgAuthenticationInfo& rgAuthenticationInfo, Pistache::Http::ResponseWriter& response) { Logger::ausf_server().info("rg_authentications_post"); response.send( Pistache::Http::Code::Not_Implemented, "rg_authentications_post API has not been implemented yet!\n"); } void DefaultApiImpl::ue_authentications_auth_ctx_id5g_aka_confirmation_put( const std::string& authCtxId, const ConfirmationData& confirmationData, Pistache::Http::ResponseWriter& response) { Pistache::Http::Code code = {}; nlohmann::json json_data = {}; m_ausf_app->handle_ue_authentications_confirmation( authCtxId, confirmationData, json_data, code); // ausf --> seaf Logger::ausf_server().debug( "5g-aka-confirmation response:\n %s", json_data.dump().c_str()); Logger::ausf_server().info( "Send 5g-aka-confirmation response to SEAF (Code %d)", code); response.send(code, json_data.dump().c_str()); } void DefaultApiImpl::ue_authentications_deregister_post( const DeregistrationInfo& deregistrationInfo, Pistache::Http::ResponseWriter& response) { Logger::ausf_server().info("ue_authentications_deregister_post"); response.send( Pistache::Http::Code::Not_Implemented, "ue_authentications_deregister_post API has not been implemented yet!\n"); } void DefaultApiImpl::ue_authentications_post( const AuthenticationInfo& authenticationInfo, Pistache::Http::ResponseWriter& response) { // Getting params std::string reponse_from_udm = {}; std::string location = {}; UEAuthenticationCtx ue_auth_ctx = {}; nlohmann::json UEAuthCtx_json = {}; Pistache::Http::Code code = {}; m_ausf_app->handle_ue_authentications( authenticationInfo, UEAuthCtx_json, location, code); Logger::ausf_server().debug( "Auth response:\n %s", UEAuthCtx_json.dump().c_str()); Logger::ausf_server().info("Send Auth response to SEAF (Code %d)", code); response.headers().add<Pistache::Http::Header::Location>(location); response.send(code, UEAuthCtx_json.dump().c_str()); } } // namespace api } // namespace ausf_server } // namespace oai
34.071942
81
0.72614
[ "model" ]
55498b29103b18e3179206a16e2b20112f48638b
16,910
cpp
C++
src/compiler/Symbol Table/Attribute.cpp
dimashky/compiler
0b772d16aec1a327698886b1f28f3abdfa60c1a1
[ "MIT" ]
5
2018-07-06T04:05:05.000Z
2021-08-05T23:59:44.000Z
src/compiler/Symbol Table/Attribute.cpp
maheralkassir/compiler
0b772d16aec1a327698886b1f28f3abdfa60c1a1
[ "MIT" ]
4
2018-07-05T22:19:30.000Z
2018-07-05T22:19:30.000Z
src/compiler/Symbol Table/Attribute.cpp
maheralkassir/compiler
0b772d16aec1a327698886b1f28f3abdfa60c1a1
[ "MIT" ]
3
2018-12-08T10:13:32.000Z
2021-03-27T02:04:18.000Z
#include "Attribute.h" #include "../Error Handler/error_handler.h" #include<vector> set<string > Attribute::classModifiers = set<string>({ "PUBLIC", "PRIVATE", "PROTECTED", "STATIC", "INTERNAL","NEW","SEALED","ABSTRACT" }); set<string > Attribute::methodModifiers = set<string>({ "PUBLIC", "PRIVATE", "PROTECTED", "STATIC", "INTERNAL","NEW","SEALED","VIRTUAL","OVERRIDE","EXTERN","ABSTRACT" }); set<string > Attribute::fieldModifiers = set<string>({ "PUBLIC", "PRIVATE", "PROTECTED", "STATIC", "INTERNAL","NEW","READONLY","CONST","VOLATILE" }); set<string > Attribute::interfaceModifiers = set<string>({ "PUBLIC", "PRIVATE", "PROTECTED", "INTERNAL" }); extern errorHandler error_handler; Attribute::Attribute(string type, int line_no, int col_no) { typeKeyword = type; errorDuplicate = false; errorAccess = false; oneAccess = false; errorAbstract = false; errorStaticSealed = false; errorPrivate = false; errorConst = false; this->line_no = line_no; this->col_no = col_no; } Attribute::Attribute(string type, string return_type,int line_no,int col_no) { typeKeyword = type; errorDuplicate = false; errorAccess = false; oneAccess = false; errorAbstract = false; errorStaticSealed = false; errorPrivate = false; errorConst = false; this->line_no = line_no; this->col_no = col_no; this->return_type = return_type; } bool Attribute::add(string nameAtt,int sizeAtt) { int number = whatHave.size(); if (typeKeyword == "class") { set<string>::iterator it = classModifiers.find(nameAtt); if (it != classModifiers.end()) // inside type { set<string>::iterator it1 = whatHave.find(nameAtt); if (it1 == whatHave.end() || whatHave.size() == 0) // not Duplicate { if ((nameAtt == "PUBLIC" || nameAtt == "PRIVATE" || nameAtt == "PROTECTED"))// not more Access { if ((oneAccess) && (!errorAccess)) { error_handler.add(error(line_no, col_no, "attributes error, More than one protection modifier")); errorAccess = true; return false; } oneAccess = true; } else if (nameAtt == "INTERNAL") { // no more Access set<string>::iterator it3 = whatHave.find("PRIVATE"); set<string>::iterator it4 = whatHave.find("PUBLIC"); if ((it3 != whatHave.end() || it4 != whatHave.end()) && !errorAccess) { error_handler.add(error(line_no, col_no, "attribute error, more than one protection modifier")); errorAccess = true; return false; } } else if (nameAtt == "ABSTRACT") { // no sealed or STATIC set<string>::iterator it5 = whatHave.find("SEALED"); set<string>::iterator it6 = whatHave.find("STATIC"); if ((it5 != whatHave.end() || it6 != whatHave.end()) && !errorAbstract) { error_handler.add(error(line_no, col_no, "attribute error, an abstract class cannot be sealed or static")); errorAbstract = true; return false; } } else if (nameAtt == "STATIC") { // no sealed or STATIC set<string>::iterator it7 = whatHave.find("ABSTRACT"); if (it7 != whatHave.end() && !errorAbstract) { error_handler.add(error(line_no, col_no, "attribute error, an abstract class cannot be sealed or static")); errorAbstract = true; return false; } set<string>::iterator it8 = whatHave.find("SEALED"); if (it8 != whatHave.end() && !errorStaticSealed) { error_handler.add(error(line_no, col_no, "attribute error, a class cannot be both static and sealed")); errorStaticSealed = true; return false; } } else if (nameAtt == "SEALED") { // no sealed or static set<string>::iterator it9 = whatHave.find("ABSTRACT"); if (it9 != whatHave.end() && !errorAbstract) { error_handler.add(error(line_no, col_no, "attribute error, an abstract class cannot be sealed or static")); errorAbstract = true; return false; } set<string>::iterator it10 = whatHave.find("static"); if (it10 != whatHave.end() && !errorStaticSealed) { error_handler.add(error(line_no, col_no, "attribute error, a class cannot be both static and sealed")); errorStaticSealed = true; return false; } } } else if (!errorDuplicate) { errorDuplicate = true; string m = "attribute error, duplicate '" + nameAtt + "' modifier"; error_handler.add(error(line_no, col_no, m.c_str())); return false; } } else { string m = "attribute error, the modifier '" + nameAtt + "' is not valid for this item"; error_handler.add(error(line_no, col_no, m.c_str())); return false; } } else if (typeKeyword == "interface") { set<string>::iterator it = interfaceModifiers.find(nameAtt); if (it != interfaceModifiers.end()) // inside type { set<string>::iterator it1 = whatHave.find(nameAtt); if (it1 == whatHave.end() || whatHave.size() == 0) // not Duplicate { if ((nameAtt == "PUBLIC" || nameAtt == "PRIVATE" || nameAtt == "PROTECTED"))// not more Access { if ((oneAccess) && (!errorAccess)) { error_handler.add(error(line_no, col_no, "attribute error, More than one protection modifier")); errorAccess = true; return false; } oneAccess = true; } else if (nameAtt == "INTERNAL") { // no more Access set<string>::iterator it3 = whatHave.find("PRIVATE"); set<string>::iterator it4 = whatHave.find("PUBLIC"); if ((it3 != whatHave.end() || it4 != whatHave.end()) && !errorAccess) { error_handler.add(error(line_no, col_no, "attribute error, More than one protection modifier")); errorAccess = true; return false; } } } else if (!errorDuplicate) { errorDuplicate = true; string m = "attribute error, Duplicate '" + nameAtt + "' modifier"; error_handler.add(error(line_no, col_no, m.c_str())); return false; } } else { string m = "attribute error, The modifier '" + nameAtt + "' is not valid for this item"; error_handler.add(error(line_no, col_no, m.c_str())); return false; } } else if (typeKeyword == "method") { set<string>::iterator it = methodModifiers.find(nameAtt); if (it != methodModifiers.end() && (return_type != "" || (return_type == "") && (nameAtt != "NEW" && nameAtt != "SEALED" && nameAtt != "VIRTUAL" && nameAtt != "OVERRIDE" && nameAtt != "EXTERN" && nameAtt != "ABSTRACT"))) // inside type { set<string>::iterator it1 = whatHave.find(nameAtt); if (it1 == whatHave.end() || whatHave.size() == 0) // not Duplicate { if ((nameAtt == "PUBLIC" || nameAtt == "PRIVATE" || nameAtt == "PROTECTED"))// not more Access { if ((oneAccess) && (!errorAccess)) { error_handler.add(error(line_no, col_no, "attribute error, More than one protection modifier")); errorAccess = true; return false; } else if (nameAtt == "PRIVATE") { set<string>::iterator iti = whatHave.find("VIRTUAL"); set<string>::iterator iti1 = whatHave.find("ABSTRACT"); set<string>::iterator iti2 = whatHave.find("OVERRIDE"); if ((iti != whatHave.end() || iti1 != whatHave.end() || iti2 != whatHave.end()) && (!errorPrivate)) { error_handler.add(error(line_no, col_no, "attribute error, virtual or abstract members cannot be private")); errorPrivate = true; return false; } } oneAccess = true; } else if (nameAtt == "INTERNAL") { // no more Access set<string>::iterator it3 = whatHave.find("PRIVATE"); set<string>::iterator it4 = whatHave.find("PUBLIC"); if ((it3 != whatHave.end() || it4 != whatHave.end()) && !errorAccess) { error_handler.add(error(line_no, col_no, "attribute error, More than one protection modifier")); errorAccess = true; return false; } } else if (nameAtt == "VIRTUAL") { set<string>::iterator it51 = whatHave.find("PUBLIC"); set<string>::iterator it52 = whatHave.find("PROTECTED"); set<string>::iterator it53 = whatHave.find("INTERNAL"); if (it51 == whatHave.end() && it52 == whatHave.end() && it53 == whatHave.end() ) { error_handler.add(error(line_no, col_no, "attribute error, virtual or abstract members cannot be private")); return false; } set<string>::iterator it6 = whatHave.find("STATIC"); if (it6 != whatHave.end()) { error_handler.add(error(line_no, col_no, "attribute error, STATIC member cannot be marked as override, virtual, or abstract")); return false; } set<string>::iterator it7 = whatHave.find("ABSTRACT"); if (it7 != whatHave.end()) { error_handler.add(error(line_no, col_no, "attribute error, The abstract method cannot be marked virtual")); return false; } set<string>::iterator it8 = whatHave.find("OVERRIDE"); if (it8 != whatHave.end()) { error_handler.add(error(line_no, col_no, "attribute error, member marked as override cannot be marked as new or virtual")); return false; } } else if (nameAtt == "STATIC") { // no sealed or STATIC set<string>::iterator iti = whatHave.find("VIRTUAL"); set<string>::iterator iti1 = whatHave.find("ABSTRACT"); set<string>::iterator iti2 = whatHave.find("OVERRIDE"); if (iti != whatHave.end() || iti1 != whatHave.end() || iti2 != whatHave.end()) { error_handler.add(error(line_no, col_no, "attribute error, STATIC member cannot be marked as override, virtual, or abstract")); return false; } } else if (nameAtt == "SEALED" ); else if (nameAtt == "OVERRIDE") { set<string>::iterator itr1 = whatHave.find("PUBLIC"); set<string>::iterator itr2 = whatHave.find("PROTECTED"); set<string>::iterator itr3 = whatHave.find("INTERNAL"); if (itr1 != whatHave.end() || itr2 != whatHave.end() || itr3 != whatHave.end()) { set<string>::iterator ite1 = whatHave.find("NEW"); set<string>::iterator ite2 = whatHave.find("VIRTUAL"); if (ite1 != whatHave.end() || ite2 != whatHave.end()) { error_handler.add(error(line_no, col_no, "attribute error, member marked as override cannot be marked as new or virtual")); return false; } else { set<string>::iterator ite4 = whatHave.find("STATIC"); if (ite4 != whatHave.end()) { error_handler.add(error(line_no, col_no, "attribute error, STATIC member cannot be marked as override, virtual, or abstract")); return false; } } } else if (!errorPrivate) { error_handler.add(error(line_no, col_no, "attribute error, virtual or abstract members cannot be PRIVATE")); errorPrivate = true; return false; } } else if (nameAtt == "NEW") { set<string>::iterator ite32 = whatHave.find("OVERRIDE"); if (ite32 != whatHave.end()) { error_handler.add(error(line_no, col_no, "attribute error, member marked as override cannot be marked as NEW or virtual")); return false; } } else if (nameAtt == "ABSTRACT") { set<string>::iterator itr1 = whatHave.find("PUBLIC"); set<string>::iterator itr2 = whatHave.find("PROTECTED"); set<string>::iterator itr3 = whatHave.find("INTERNAL"); if (itr1 != whatHave.end() || itr2 != whatHave.end() || itr3 != whatHave.end()) { set<string>::iterator ite2 = whatHave.find("VIRTUAL"); if (ite2 != whatHave.end()) { error_handler.add(error(line_no, col_no, "attribute error, The abstract method cannot be marked virtual")); return false; } else { set<string>::iterator ite34 = whatHave.find("SEALED"); if (ite34 != whatHave.end()) { error_handler.add(error(line_no, col_no, "attribute error, cannot be both abstract and sealed")); return false; } else { set<string>::iterator ite324 = whatHave.find("EXTERN"); if (ite324 != whatHave.end()) { error_handler.add(error(line_no, col_no, "attribute error, cannot be both abstract and extern")); return false; } } } } else { error_handler.add(error(line_no, col_no, "attribute error, cannot be abstract because it is a private method")); return false; } } else if (nameAtt == "EXTERN") { set<string>::iterator ite324 = whatHave.find("ABSTRACT"); if (ite324 != whatHave.end()) { error_handler.add(error(line_no, col_no, "attribute error, cannot be both abstract and extern")); return false; } } } else if (!errorDuplicate) { errorDuplicate = true; string m = "attribute error, Duplicate '" + nameAtt + "' modifier"; error_handler.add(error(line_no, col_no, m.c_str())); return false; } } else { string m = "attribute error, The modifier '" + nameAtt + "' is not valid for this item"; error_handler.add(error(line_no, col_no, m.c_str())); return false; } } else if (typeKeyword == "field") { set<string>::iterator it = fieldModifiers.find(nameAtt); if (it != fieldModifiers.end()) // inside type { set<string>::iterator it1 = whatHave.find(nameAtt); if (it1 == whatHave.end() || whatHave.size() == 0) // not Duplicate { if ((nameAtt == "PUBLIC" || nameAtt == "PRIVATE" || nameAtt == "PROTECTED"))// not more Access { if ((oneAccess) && (!errorAccess)) { error_handler.add(error(line_no, col_no, "attribute error, More than one protection modifier")); errorAccess = true; return false; } oneAccess = true; } else if (nameAtt == "INTERNAL") { // no more Access set<string>::iterator it3 = whatHave.find("PRIVATE"); set<string>::iterator it4 = whatHave.find("PUBLIC"); if ((it3 != whatHave.end() || it4 != whatHave.end()) && !errorAccess) { error_handler.add(error(line_no, col_no, "attribute error, More than one protection modifier")); errorAccess = true; return false; } } else if (nameAtt == "CONST") { // no more Access set<string>::iterator it4 = whatHave.find("STATIC"); if (it4 != whatHave.end()) { error_handler.add(error(line_no, col_no, "attribute error, The constant cannot be marked static")); return false; } else { set<string>::iterator it41 = whatHave.find("READONLY"); if ((it41 != whatHave.end()) && !errorConst) { error_handler.add(error(line_no, col_no, "attribute error, The modifier 'readonly' is not valid for this item")); errorConst = true; return false; } else { set<string>::iterator it42 = whatHave.find("VOLATILE"); if (it42 != whatHave.end()) { error_handler.add(error(line_no, col_no, "attribute error, The modifier 'volatile' is not valid for this item")); return false; } } } } else if (nameAtt == "STATIC") { set<string>::iterator it4 = whatHave.find("CONST"); if (it4 != whatHave.end()) { error_handler.add(error(line_no, col_no, "attribute error, const field requires a value to be provided")); return false; } } else if (nameAtt == "READONLY") { set<string>::iterator it4 = whatHave.find("CONST"); if (it4 != whatHave.end()) { error_handler.add(error(line_no, col_no, "attribute error, const field requires a value to be provided")); return false; } else { set<string>::iterator it45 = whatHave.find("VOLATILE"); if (it45 != whatHave.end()) { error_handler.add(error(line_no, col_no, "attribute error, field cannot be both volatile and readonly")); return false; } } } else if (nameAtt == "VOLATILE") { set<string>::iterator it45 = whatHave.find("READONLY"); if (it45 != whatHave.end()) { error_handler.add(error(line_no, col_no, "attribute error, field cannot be both volatile and readonly")); return false; } else { set<string>::iterator it42 = whatHave.find("CONST"); if (it42 != whatHave.end()) { error_handler.add(error(line_no, col_no, "attribute error, const field requires a value to be provided")); return false; } } } } else if (!errorDuplicate) { errorDuplicate = true; string m = "attribute error, Duplicate '" + nameAtt + "' modifier"; error_handler.add(error(line_no, col_no, m.c_str())); return false; } } else { string m = "attribute error, The modifier '" + nameAtt + "' is not valid for this item"; error_handler.add(error(line_no, col_no, m.c_str())); return false; } } whatHave.insert(nameAtt); if (sizeAtt == 1 && typeKeyword=="method") { set<string>::iterator itiS = whatHave.find("SEALED"); if (itiS != whatHave.end()) { set<string>::iterator iti = whatHave.find("OVERRIDE"); if (iti == whatHave.end()) { error_handler.add(error(line_no, col_no, "attribute error, cannot be sealed because it is not an override")); return false; } } } return true; } Attribute::~Attribute() { //dtor }
37.246696
240
0.625074
[ "vector" ]
554b3ea57b5bfa5c20e9c7fae789f7267f97f128
2,535
cpp
C++
src/main.cpp
bggd/Arena
c27565a218e3ca27cca056f73181e757f188b099
[ "BSL-1.0" ]
null
null
null
src/main.cpp
bggd/Arena
c27565a218e3ca27cca056f73181e757f188b099
[ "BSL-1.0" ]
null
null
null
src/main.cpp
bggd/Arena
c27565a218e3ca27cca056f73181e757f188b099
[ "BSL-1.0" ]
null
null
null
#define SDL_MAIN_HANDLED #include "game_app.hpp" #include "model.hpp" #include "gmath.hpp" #include "camera.hpp" #include "game_object/game_object.hpp" struct Player : GameObject { Model model; void onUpdate(float dt) override { model.updateAnimation(dt); model.updateMesh(getWorldMatrix()); model.draw(); } }; Camera gCam; Model gModel; SceneTree gScene; void initOpenGL() { glEnable(GL_BLEND); glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); glEnable(GL_TEXTURE_2D); glEnable(GL_DEPTH_TEST); //glFrontFace(GL_CCW); glEnable(GL_CULL_FACE); //glCullFace(GL_BACK); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } void onInit() { initOpenGL(); gCam.setAspectRatio(640.0F / 480.0F); //gCam.fov = deg2Rad(80.0F); gCam.position = vec3(0.0F, -20.0F, 0.0F); gCam.farClip = 1000.0F; } void onUpdate(const GameAppState& appState) { float scale = 1.0F; Matrix4 model = mat4CreateScale(vec3(scale, scale, scale)); //model = mat4Multiply(mat4CreateFromAxisAngle(vec3(0.0F, 0.0F, 1.0F), deg2Rad(45.0F)), model); gModel.updateAnimation(appState.dt); gModel.updateMesh(model); gCam.updateMVP(); glViewport(0, 0, 640, 480); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadMatrixf(mat4Ptr(gCam.mvp)); gModel.draw(); gScene.propagateTransform(); gScene.updateGameObjects(1.0F / 60.0F); } int main() { gModel.load("cube.gltf"); gModel.animation.setCurrentAction("RunCycle"); //gModel.animation.setCurrentAction("Armature|RunCycle"); Player obj; obj.setPosition(vec3(0.0F, 0.0F, 1.0F)); obj.model.load("cube.gltf"); obj.model.animation.setCurrentAction("RunCycle"); obj.setScale(vec3(2.0F, 2.0F, 2.0F)); obj.setRotation(quatCreateAxisAngle(vec3(0.0F, 1.0F, 0.0F), deg2Rad(90.0F))); obj.addObject(new Player()); static_cast<Player*>(obj.objects[0])->setPosition(vec3(0.0F, 0.0F, 1.0F)); static_cast<Player*>(obj.objects[0])->model.load("cube.gltf"); static_cast<Player*>(obj.objects[0])->model.animation.setCurrentAction("RunCycle"); //static_cast<Player*>(obj.objects[0])->setScale(vec3(2.0F, 2.0F, 2.0F)); gScene.setRoot(&obj); //gScene.updateGameObjects(1.0F/60.0F); GameAppConfig appConfig; appConfig.width = 640; appConfig.height = 480; appConfig.title = "bhr"; GameApp app = {}; app.onInit = onInit; app.onUpdate = onUpdate; runGameApp(app, appConfig); return 0; }
27.857143
99
0.674556
[ "model" ]
55515294d2816d13629553745c8e4ff748fd7737
27,562
cpp
C++
GROMACS/nonbonded_benchmark/gromacs_source_code/src/gromacs/ewald/tests/pmetestcommon.cpp
berkhess/bioexcel-exascale-co-design-benchmarks
c32f811d41a93fb69e49b3e7374f6028e37970d2
[ "MIT" ]
1
2020-04-20T04:33:11.000Z
2020-04-20T04:33:11.000Z
GROMACS/nonbonded_benchmark/gromacs_source_code/src/gromacs/ewald/tests/pmetestcommon.cpp
berkhess/bioexcel-exascale-co-design-benchmarks
c32f811d41a93fb69e49b3e7374f6028e37970d2
[ "MIT" ]
8
2019-07-10T15:18:21.000Z
2019-07-31T13:38:09.000Z
GROMACS/nonbonded_benchmark/gromacs_source_code/src/gromacs/ewald/tests/pmetestcommon.cpp
berkhess/bioexcel-exascale-co-design-benchmarks
c32f811d41a93fb69e49b3e7374f6028e37970d2
[ "MIT" ]
3
2019-07-10T10:50:25.000Z
2020-12-08T13:42:52.000Z
/* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2016,2017,2018,2019, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * GROMACS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief * Implements common routines for PME tests. * * \author Aleksei Iupinov <a.yupinov@gmail.com> * \ingroup module_ewald */ #include "gmxpre.h" #include "pmetestcommon.h" #include <cstring> #include <algorithm> #include "gromacs/domdec/domdec.h" #include "gromacs/ewald/pme_gather.h" #include "gromacs/ewald/pme_gpu_internal.h" #include "gromacs/ewald/pme_grid.h" #include "gromacs/ewald/pme_internal.h" #include "gromacs/ewald/pme_redistribute.h" #include "gromacs/ewald/pme_solve.h" #include "gromacs/ewald/pme_spread.h" #include "gromacs/fft/parallel_3dfft.h" #include "gromacs/gpu_utils/gpu_utils.h" #include "gromacs/math/invertmatrix.h" #include "gromacs/mdtypes/commrec.h" #include "gromacs/pbcutil/pbc.h" #include "gromacs/topology/topology.h" #include "gromacs/utility/exceptions.h" #include "gromacs/utility/gmxassert.h" #include "gromacs/utility/logger.h" #include "gromacs/utility/stringutil.h" #include "testutils/testasserts.h" namespace gmx { namespace test { bool pmeSupportsInputForMode(const gmx_hw_info_t &hwinfo, const t_inputrec *inputRec, CodePath mode) { bool implemented; gmx_mtop_t mtop; switch (mode) { case CodePath::CPU: implemented = true; break; case CodePath::GPU: implemented = (pme_gpu_supports_build(nullptr) && pme_gpu_supports_hardware(hwinfo, nullptr) && pme_gpu_supports_input(*inputRec, mtop, nullptr)); break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } return implemented; } uint64_t getSplineModuliDoublePrecisionUlps(int splineOrder) { /* Arbitrary ulp tolerance for sine/cosine implementation. It's * hard to know what to pick without testing lots of * implementations. */ const uint64_t sineUlps = 10; return 4 * (splineOrder - 2) + 2 * sineUlps * splineOrder; } //! PME initialization - internal static PmeSafePointer pmeInitInternal(const t_inputrec *inputRec, CodePath mode, const gmx_device_info_t *gpuInfo, PmeGpuProgramHandle pmeGpuProgram, const Matrix3x3 &box, real ewaldCoeff_q = 1.0f, real ewaldCoeff_lj = 1.0f ) { const MDLogger dummyLogger; const auto runMode = (mode == CodePath::CPU) ? PmeRunMode::CPU : PmeRunMode::Mixed; t_commrec dummyCommrec = {0}; NumPmeDomains numPmeDomains = { 1, 1 }; gmx_pme_t *pmeDataRaw = gmx_pme_init(&dummyCommrec, numPmeDomains, inputRec, false, false, true, ewaldCoeff_q, ewaldCoeff_lj, 1, runMode, nullptr, gpuInfo, pmeGpuProgram, dummyLogger); PmeSafePointer pme(pmeDataRaw); // taking ownership // TODO get rid of this with proper matrix type matrix boxTemp; for (int i = 0; i < DIM; i++) { for (int j = 0; j < DIM; j++) { boxTemp[i][j] = box[i * DIM + j]; } } const char *boxError = check_box(-1, boxTemp); GMX_RELEASE_ASSERT(boxError == nullptr, boxError); switch (mode) { case CodePath::CPU: invertBoxMatrix(boxTemp, pme->recipbox); break; case CodePath::GPU: pme_gpu_set_testing(pme->gpu, true); pme_gpu_update_input_box(pme->gpu, boxTemp); break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } return pme; } //! Simple PME initialization based on input, no atom data PmeSafePointer pmeInitEmpty(const t_inputrec *inputRec, CodePath mode, const gmx_device_info_t *gpuInfo, PmeGpuProgramHandle pmeGpuProgram, const Matrix3x3 &box, real ewaldCoeff_q, real ewaldCoeff_lj ) { return pmeInitInternal(inputRec, mode, gpuInfo, pmeGpuProgram, box, ewaldCoeff_q, ewaldCoeff_lj); // hiding the fact that PME actually needs to know the number of atoms in advance } //! PME initialization with atom data PmeSafePointer pmeInitAtoms(const t_inputrec *inputRec, CodePath mode, const gmx_device_info_t *gpuInfo, PmeGpuProgramHandle pmeGpuProgram, const CoordinatesVector &coordinates, const ChargesVector &charges, const Matrix3x3 &box ) { const index atomCount = coordinates.size(); GMX_RELEASE_ASSERT(atomCount == charges.ssize(), "Mismatch in atom data"); PmeSafePointer pmeSafe = pmeInitInternal(inputRec, mode, gpuInfo, pmeGpuProgram, box); PmeAtomComm *atc = nullptr; switch (mode) { case CodePath::CPU: atc = &(pmeSafe->atc[0]); atc->x = coordinates; atc->coefficient = charges; gmx_pme_reinit_atoms(pmeSafe.get(), atomCount, charges.data()); /* With decomposition there would be more boilerplate atc code here, e.g. do_redist_pos_coeffs */ break; case CodePath::GPU: // TODO: Avoid use of atc in the GPU code path atc = &(pmeSafe->atc[0]); // We need to set atc->n for passing the size in the tests atc->setNumAtoms(atomCount); gmx_pme_reinit_atoms(pmeSafe.get(), atomCount, charges.data()); pme_gpu_copy_input_coordinates(pmeSafe->gpu, as_rvec_array(coordinates.data())); break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } return pmeSafe; } //! Getting local PME real grid pointer for test I/O static real *pmeGetRealGridInternal(const gmx_pme_t *pme) { const size_t gridIndex = 0; return pme->fftgrid[gridIndex]; } //! Getting local PME real grid dimensions static void pmeGetRealGridSizesInternal(const gmx_pme_t *pme, CodePath mode, IVec &gridSize, //NOLINT(google-runtime-references) IVec &paddedGridSize) //NOLINT(google-runtime-references) { const size_t gridIndex = 0; IVec gridOffsetUnused; switch (mode) { case CodePath::CPU: gmx_parallel_3dfft_real_limits(pme->pfft_setup[gridIndex], gridSize, gridOffsetUnused, paddedGridSize); break; case CodePath::GPU: pme_gpu_get_real_grid_sizes(pme->gpu, &gridSize, &paddedGridSize); break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } } //! Getting local PME complex grid pointer for test I/O static t_complex *pmeGetComplexGridInternal(const gmx_pme_t *pme) { const size_t gridIndex = 0; return pme->cfftgrid[gridIndex]; } //! Getting local PME complex grid dimensions static void pmeGetComplexGridSizesInternal(const gmx_pme_t *pme, IVec &gridSize, //NOLINT(google-runtime-references) IVec &paddedGridSize) //NOLINT(google-runtime-references) { const size_t gridIndex = 0; IVec gridOffsetUnused, complexOrderUnused; gmx_parallel_3dfft_complex_limits(pme->pfft_setup[gridIndex], complexOrderUnused, gridSize, gridOffsetUnused, paddedGridSize); //TODO: what about YZX ordering? } //! Getting the PME grid memory buffer and its sizes - template definition template<typename ValueType> static void pmeGetGridAndSizesInternal(const gmx_pme_t * /*unused*/, CodePath /*unused*/, ValueType * & /*unused*/, IVec & /*unused*/, IVec & /*unused*/) //NOLINT(google-runtime-references) { GMX_THROW(InternalError("Deleted function call")); // explicitly deleting general template does not compile in clang/icc, see https://llvm.org/bugs/show_bug.cgi?id=17537 } //! Getting the PME real grid memory buffer and its sizes template<> void pmeGetGridAndSizesInternal<real>(const gmx_pme_t *pme, CodePath mode, real * &grid, IVec &gridSize, IVec &paddedGridSize) { grid = pmeGetRealGridInternal(pme); pmeGetRealGridSizesInternal(pme, mode, gridSize, paddedGridSize); } //! Getting the PME complex grid memory buffer and its sizes template<> void pmeGetGridAndSizesInternal<t_complex>(const gmx_pme_t *pme, CodePath /*unused*/, t_complex * &grid, IVec &gridSize, IVec &paddedGridSize) { grid = pmeGetComplexGridInternal(pme); pmeGetComplexGridSizesInternal(pme, gridSize, paddedGridSize); } //! PME spline calculation and charge spreading void pmePerformSplineAndSpread(gmx_pme_t *pme, CodePath mode, // TODO const qualifiers elsewhere bool computeSplines, bool spreadCharges) { GMX_RELEASE_ASSERT(pme != nullptr, "PME data is not initialized"); PmeAtomComm *atc = &(pme->atc[0]); const size_t gridIndex = 0; const bool computeSplinesForZeroCharges = true; real *fftgrid = spreadCharges ? pme->fftgrid[gridIndex] : nullptr; real *pmegrid = pme->pmegrid[gridIndex].grid.grid; switch (mode) { case CodePath::CPU: spread_on_grid(pme, atc, &pme->pmegrid[gridIndex], computeSplines, spreadCharges, fftgrid, computeSplinesForZeroCharges, gridIndex); if (spreadCharges && !pme->bUseThreads) { wrap_periodic_pmegrid(pme, pmegrid); copy_pmegrid_to_fftgrid(pme, pmegrid, fftgrid, gridIndex); } break; case CodePath::GPU: pme_gpu_spread(pme->gpu, gridIndex, fftgrid, computeSplines, spreadCharges); break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } } //! Getting the internal spline data buffer pointer static real *pmeGetSplineDataInternal(const gmx_pme_t *pme, PmeSplineDataType type, int dimIndex) { GMX_ASSERT((0 <= dimIndex) && (dimIndex < DIM), "Invalid dimension index"); const PmeAtomComm *atc = &(pme->atc[0]); const size_t threadIndex = 0; real *splineBuffer = nullptr; switch (type) { case PmeSplineDataType::Values: splineBuffer = atc->spline[threadIndex].theta.coefficients[dimIndex]; break; case PmeSplineDataType::Derivatives: splineBuffer = atc->spline[threadIndex].dtheta.coefficients[dimIndex]; break; default: GMX_THROW(InternalError("Unknown spline data type")); } return splineBuffer; } //! PME solving void pmePerformSolve(const gmx_pme_t *pme, CodePath mode, PmeSolveAlgorithm method, real cellVolume, GridOrdering gridOrdering, bool computeEnergyAndVirial) { t_complex *h_grid = pmeGetComplexGridInternal(pme); const bool useLorentzBerthelot = false; const size_t threadIndex = 0; switch (mode) { case CodePath::CPU: if (gridOrdering != GridOrdering::YZX) { GMX_THROW(InternalError("Test not implemented for this mode")); } switch (method) { case PmeSolveAlgorithm::Coulomb: solve_pme_yzx(pme, h_grid, cellVolume, computeEnergyAndVirial, pme->nthread, threadIndex); break; case PmeSolveAlgorithm::LennardJones: solve_pme_lj_yzx(pme, &h_grid, useLorentzBerthelot, cellVolume, computeEnergyAndVirial, pme->nthread, threadIndex); break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } break; case CodePath::GPU: switch (method) { case PmeSolveAlgorithm::Coulomb: pme_gpu_solve(pme->gpu, h_grid, gridOrdering, computeEnergyAndVirial); break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } } //! PME force gathering void pmePerformGather(gmx_pme_t *pme, CodePath mode, PmeForceOutputHandling inputTreatment, ForcesVector &forces) { PmeAtomComm *atc = &(pme->atc[0]); const index atomCount = atc->numAtoms(); GMX_RELEASE_ASSERT(forces.ssize() == atomCount, "Invalid force buffer size"); const bool forceReductionWithInput = (inputTreatment == PmeForceOutputHandling::ReduceWithInput); const real scale = 1.0; const size_t threadIndex = 0; const size_t gridIndex = 0; real *pmegrid = pme->pmegrid[gridIndex].grid.grid; real *fftgrid = pme->fftgrid[gridIndex]; switch (mode) { case CodePath::CPU: atc->f = forces; if (atc->nthread == 1) { // something which is normally done in serial spline computation (make_thread_local_ind()) atc->spline[threadIndex].n = atomCount; } copy_fftgrid_to_pmegrid(pme, fftgrid, pmegrid, gridIndex, pme->nthread, threadIndex); unwrap_periodic_pmegrid(pme, pmegrid); gather_f_bsplines(pme, pmegrid, !forceReductionWithInput, atc, &atc->spline[threadIndex], scale); break; case CodePath::GPU: { // Variable initialization needs a non-switch scope PmeOutput output = pme_gpu_getOutput(*pme, GMX_PME_CALC_F); GMX_ASSERT(forces.size() == output.forces_.size(), "Size of force buffers did not match"); if (forceReductionWithInput) { std::copy(std::begin(forces), std::end(forces), std::begin(output.forces_)); } pme_gpu_gather(pme->gpu, inputTreatment, reinterpret_cast<float *>(fftgrid)); std::copy(std::begin(output.forces_), std::end(output.forces_), std::begin(forces)); } break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } } //! PME test finalization before fetching the outputs void pmeFinalizeTest(const gmx_pme_t *pme, CodePath mode) { switch (mode) { case CodePath::CPU: break; case CodePath::GPU: pme_gpu_synchronize(pme->gpu); break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } } //! Setting atom spline values/derivatives to be used in spread/gather void pmeSetSplineData(const gmx_pme_t *pme, CodePath mode, const SplineParamsDimVector &splineValues, PmeSplineDataType type, int dimIndex) { const PmeAtomComm *atc = &(pme->atc[0]); const index atomCount = atc->numAtoms(); const index pmeOrder = pme->pme_order; const index dimSize = pmeOrder * atomCount; GMX_RELEASE_ASSERT(dimSize == splineValues.ssize(), "Mismatch in spline data"); real *splineBuffer = pmeGetSplineDataInternal(pme, type, dimIndex); switch (mode) { case CodePath::CPU: std::copy(splineValues.begin(), splineValues.end(), splineBuffer); break; case CodePath::GPU: std::copy(splineValues.begin(), splineValues.end(), splineBuffer); pme_gpu_transform_spline_atom_data(pme->gpu, atc, type, dimIndex, PmeLayoutTransform::HostToGpu); break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } } //! Setting gridline indices to be used in spread/gather void pmeSetGridLineIndices(gmx_pme_t *pme, CodePath mode, const GridLineIndicesVector &gridLineIndices) { PmeAtomComm *atc = &(pme->atc[0]); const index atomCount = atc->numAtoms(); GMX_RELEASE_ASSERT(atomCount == gridLineIndices.ssize(), "Mismatch in gridline indices size"); IVec paddedGridSizeUnused, gridSize(0, 0, 0); pmeGetRealGridSizesInternal(pme, mode, gridSize, paddedGridSizeUnused); for (const auto &index : gridLineIndices) { for (int i = 0; i < DIM; i++) { GMX_RELEASE_ASSERT((0 <= index[i]) && (index[i] < gridSize[i]), "Invalid gridline index"); } } switch (mode) { case CodePath::GPU: memcpy(pme->gpu->staging.h_gridlineIndices, gridLineIndices.data(), atomCount * sizeof(gridLineIndices[0])); break; case CodePath::CPU: atc->idx.resize(gridLineIndices.size()); std::copy(gridLineIndices.begin(), gridLineIndices.end(), atc->idx.begin()); break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } } //! Getting plain index into the complex 3d grid inline size_t pmeGetGridPlainIndexInternal(const IVec &index, const IVec &paddedGridSize, GridOrdering gridOrdering) { size_t result; switch (gridOrdering) { case GridOrdering::YZX: result = (index[YY] * paddedGridSize[ZZ] + index[ZZ]) * paddedGridSize[XX] + index[XX]; break; case GridOrdering::XYZ: result = (index[XX] * paddedGridSize[YY] + index[YY]) * paddedGridSize[ZZ] + index[ZZ]; break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } return result; } //! Setting real or complex grid template<typename ValueType> static void pmeSetGridInternal(const gmx_pme_t *pme, CodePath mode, GridOrdering gridOrdering, const SparseGridValuesInput<ValueType> &gridValues) { IVec gridSize(0, 0, 0), paddedGridSize(0, 0, 0); ValueType *grid; pmeGetGridAndSizesInternal<ValueType>(pme, mode, grid, gridSize, paddedGridSize); switch (mode) { case CodePath::GPU: // intentional absence of break, the grid will be copied from the host buffer in testing mode case CodePath::CPU: std::memset(grid, 0, paddedGridSize[XX] * paddedGridSize[YY] * paddedGridSize[ZZ] * sizeof(ValueType)); for (const auto &gridValue : gridValues) { for (int i = 0; i < DIM; i++) { GMX_RELEASE_ASSERT((0 <= gridValue.first[i]) && (gridValue.first[i] < gridSize[i]), "Invalid grid value index"); } const size_t gridValueIndex = pmeGetGridPlainIndexInternal(gridValue.first, paddedGridSize, gridOrdering); grid[gridValueIndex] = gridValue.second; } break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } } //! Setting real grid to be used in gather void pmeSetRealGrid(const gmx_pme_t *pme, CodePath mode, const SparseRealGridValuesInput &gridValues) { pmeSetGridInternal<real>(pme, mode, GridOrdering::XYZ, gridValues); } //! Setting complex grid to be used in solve void pmeSetComplexGrid(const gmx_pme_t *pme, CodePath mode, GridOrdering gridOrdering, const SparseComplexGridValuesInput &gridValues) { pmeSetGridInternal<t_complex>(pme, mode, gridOrdering, gridValues); } //! Getting the single dimension's spline values or derivatives SplineParamsDimVector pmeGetSplineData(const gmx_pme_t *pme, CodePath mode, PmeSplineDataType type, int dimIndex) { GMX_RELEASE_ASSERT(pme != nullptr, "PME data is not initialized"); const PmeAtomComm *atc = &(pme->atc[0]); const size_t atomCount = atc->numAtoms(); const size_t pmeOrder = pme->pme_order; const size_t dimSize = pmeOrder * atomCount; real *sourceBuffer = pmeGetSplineDataInternal(pme, type, dimIndex); SplineParamsDimVector result; switch (mode) { case CodePath::GPU: pme_gpu_transform_spline_atom_data(pme->gpu, atc, type, dimIndex, PmeLayoutTransform::GpuToHost); result = arrayRefFromArray(sourceBuffer, dimSize); break; case CodePath::CPU: result = arrayRefFromArray(sourceBuffer, dimSize); break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } return result; } //! Getting the gridline indices GridLineIndicesVector pmeGetGridlineIndices(const gmx_pme_t *pme, CodePath mode) { GMX_RELEASE_ASSERT(pme != nullptr, "PME data is not initialized"); const PmeAtomComm *atc = &(pme->atc[0]); const size_t atomCount = atc->numAtoms(); GridLineIndicesVector gridLineIndices; switch (mode) { case CodePath::GPU: gridLineIndices = arrayRefFromArray(reinterpret_cast<IVec *>(pme->gpu->staging.h_gridlineIndices), atomCount); break; case CodePath::CPU: gridLineIndices = atc->idx; break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } return gridLineIndices; } //! Getting real or complex grid - only non zero values template<typename ValueType> static SparseGridValuesOutput<ValueType> pmeGetGridInternal(const gmx_pme_t *pme, CodePath mode, GridOrdering gridOrdering) { IVec gridSize(0, 0, 0), paddedGridSize(0, 0, 0); ValueType *grid; pmeGetGridAndSizesInternal<ValueType>(pme, mode, grid, gridSize, paddedGridSize); SparseGridValuesOutput<ValueType> gridValues; switch (mode) { case CodePath::GPU: // intentional absence of break case CodePath::CPU: gridValues.clear(); for (int ix = 0; ix < gridSize[XX]; ix++) { for (int iy = 0; iy < gridSize[YY]; iy++) { for (int iz = 0; iz < gridSize[ZZ]; iz++) { IVec temp(ix, iy, iz); const size_t gridValueIndex = pmeGetGridPlainIndexInternal(temp, paddedGridSize, gridOrdering); const ValueType value = grid[gridValueIndex]; if (value != ValueType {}) { auto key = formatString("Cell %d %d %d", ix, iy, iz); gridValues[key] = value; } } } } break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } return gridValues; } //! Getting the real grid (spreading output of pmePerformSplineAndSpread()) SparseRealGridValuesOutput pmeGetRealGrid(const gmx_pme_t *pme, CodePath mode) { return pmeGetGridInternal<real>(pme, mode, GridOrdering::XYZ); } //! Getting the complex grid output of pmePerformSolve() SparseComplexGridValuesOutput pmeGetComplexGrid(const gmx_pme_t *pme, CodePath mode, GridOrdering gridOrdering) { return pmeGetGridInternal<t_complex>(pme, mode, gridOrdering); } //! Getting the reciprocal energy and virial PmeOutput pmeGetReciprocalEnergyAndVirial(const gmx_pme_t *pme, CodePath mode, PmeSolveAlgorithm method) { PmeOutput output; switch (mode) { case CodePath::CPU: switch (method) { case PmeSolveAlgorithm::Coulomb: get_pme_ener_vir_q(pme->solve_work, pme->nthread, &output); break; case PmeSolveAlgorithm::LennardJones: get_pme_ener_vir_lj(pme->solve_work, pme->nthread, &output); break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } break; case CodePath::GPU: switch (method) { case PmeSolveAlgorithm::Coulomb: output = pme_gpu_getEnergyAndVirial(*pme); break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } break; default: GMX_THROW(InternalError("Test not implemented for this mode")); } return output; } } // namespace test } // namespace gmx
38.227462
218
0.596873
[ "3d" ]
555458f8d9e1d2396118bffca9ecf2af1365cd18
2,716
cc
C++
modules/ifpen_solvers/src/alien/kernels/ifp/data_structure/IFPSolverInternal.cc
cedricga91/alien_legacy_plugins
459701026d76dbe1e8a6b20454f6b50ec9722f7f
[ "Apache-2.0" ]
4
2021-12-02T09:06:38.000Z
2022-01-10T14:22:35.000Z
modules/ifpen_solvers/src/alien/kernels/ifp/data_structure/IFPSolverInternal.cc
cedricga91/alien_legacy_plugins
459701026d76dbe1e8a6b20454f6b50ec9722f7f
[ "Apache-2.0" ]
null
null
null
modules/ifpen_solvers/src/alien/kernels/ifp/data_structure/IFPSolverInternal.cc
cedricga91/alien_legacy_plugins
459701026d76dbe1e8a6b20454f6b50ec9722f7f
[ "Apache-2.0" ]
7
2021-11-23T14:50:58.000Z
2022-03-17T13:23:07.000Z
#include "IFPSolverInternal.h" /* Author : havep at Fri Jul 20 13:21:25 2012 * Generated by createNew */ #include <IFPSolver.h> #include <alien/core/impl/MultiVectorImpl.h> /*---------------------------------------------------------------------------*/ BEGIN_IFPSOLVERINTENRAL_NAMESPACE /*---------------------------------------------------------------------------*/ const MultiMatrixImpl* MatrixInternal::m_static_multi_impl = NULL; bool VectorInternal::m_static_representation_switch = false; const MultiVectorImpl* VectorInternal::m_static_multi_impl = NULL; int VectorInternal::m_static_init_rhs = 0; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ MatrixInternal::MatrixInternal(const MultiMatrixImpl* matrix_impl, Int64 timestamp) : m_timestamp(timestamp) { if (m_static_multi_impl != NULL) throw FatalErrorException( A_FUNCINFO, "Cannot build two instances of vector with IFPSolver"); m_static_multi_impl = matrix_impl; } /*---------------------------------------------------------------------------*/ MatrixInternal::~MatrixInternal() { F2C(ifpmatrixfreedata)(); F2C(ifpsolverfreegraph)(); m_static_multi_impl = NULL; } void MatrixInternal::init() { m_filled = false; m_extra_filled = false; } /*---------------------------------------------------------------------------*/ VectorInternal::VectorInternal(const MultiVectorImpl* vector_impl) : m_offset(0) , m_local_size(0) , m_rows(0) , m_filled(false) , m_extra_filled(false) { // if (m_static_multi_impl != NULL) // throw FatalErrorException(A_FUNCINFO,"Cannot build two instances of vector with // IFPSolver"); m_static_multi_impl = vector_impl; } /*---------------------------------------------------------------------------*/ VectorInternal::~VectorInternal() { delete[] m_rows; // m_static_multi_impl = NULL; } /*---------------------------------------------------------------------------*/ void VectorInternal::setRepresentationSwitch(const bool s) { m_static_representation_switch = s; } /*---------------------------------------------------------------------------*/ bool VectorInternal::hasRepresentationSwitch() { return m_static_representation_switch; } void VectorInternal::initRHS(const bool s) { m_static_init_rhs = s ? 1 : 0; } int VectorInternal::isRHS() { return m_static_init_rhs; } /*---------------------------------------------------------------------------*/ END_IFPSOLVERINTERNAL_NAMESPACE /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
26.115385
85
0.494109
[ "vector" ]
555720a85d5f59586967a97549179a5fff3bd6e1
2,017
cpp
C++
strings_attribute_parser.cpp
pysogge/cpp_script_projects
58578106ed0f33cc60de11df8eb4886fc3595797
[ "MIT" ]
1
2022-03-10T15:24:36.000Z
2022-03-10T15:24:36.000Z
strings_attribute_parser.cpp
pysogge/cpp_script_projects
58578106ed0f33cc60de11df8eb4886fc3595797
[ "MIT" ]
null
null
null
strings_attribute_parser.cpp
pysogge/cpp_script_projects
58578106ed0f33cc60de11df8eb4886fc3595797
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; struct Attribute { string name; string value; }; struct Tag { string name; vector<Attribute> attributes; vector<Tag> *children; Tag *parent; }; Tag parseTokens(string line) { Tag tag; string token = ""; string value = ""; int i = 0; while (line[i] != '\0') { while (line[i] != '<' && line[i] != '\0') i++; while (!isalnum(line[i]) && line[i] != '\0') i++; while (isalnum(line[i]) && line[i] != '\0') token += line[i++]; // cout << "name: " << token << endl; tag.name = token; token = ""; while (line[i] != '>' && line[i] != '\0') { while (!isalnum(line[i]) && line[i] != '\0') i++; while (isalnum(line[i]) && line[i] != '\0') token += line[i++]; // cout << "token: " << token << endl; while ((line[i] != '=') && line[i] != '\0') i++; while (!isalnum(line[i]) && line[i] != '\0') i++; while (isalnum(line[i]) && line[i] != '\0') value += line[i++]; // cout << "value: " << value << endl; if (!token.empty() && !value.empty()) { Attribute attribute; attribute.name = token; attribute.value = value; tag.attributes.push_back(attribute); } token = ""; value = ""; i++; // final increment } i++; } return tag; } Tag parseTags(int n) { Tag root; string line; while (line.empty()) { getline(cin, line); } root = parseTokens(line); return root; } int main() { int n, q; scanf("%d %d", &n, &q); Tag root = parseTags(n); cout << "root.name: " << root.name << endl; return 0; }
22.164835
56
0.422905
[ "vector" ]
555808da815376386a95fb2cc996e9ddee9927df
1,944
cpp
C++
Problem Solving Paradigms/Complete Search/416 LED Test.cpp
satvik007/UvaRevision
b2473130eb17435ac55132083e85262491db3d1b
[ "MIT" ]
null
null
null
Problem Solving Paradigms/Complete Search/416 LED Test.cpp
satvik007/UvaRevision
b2473130eb17435ac55132083e85262491db3d1b
[ "MIT" ]
null
null
null
Problem Solving Paradigms/Complete Search/416 LED Test.cpp
satvik007/UvaRevision
b2473130eb17435ac55132083e85262491db3d1b
[ "MIT" ]
null
null
null
#define BZ #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/detail/standard_policies.hpp> using ll = int64_t; using ld = long double; using ull = uint64_t; using namespace std; using namespace __gnu_pbds; typedef vector <int> vi; typedef pair <int, int> ii; const int INF = 1 << 30; #define maxn 100010 int n; vector <string> a; map <int, string> segment; int main() { #ifdef BZ freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); #endif ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cout.setf(ios::fixed); cout.precision(20); segment[0] = "1111110"; segment[1] = "0110000"; segment[2] = "1101101"; segment[3] = "1111001"; segment[4] = "0110011"; segment[5] = "1011011"; segment[6] = "1011111"; segment[7] = "1110000"; segment[8] = "1111111"; segment[9] = "1111011"; while(cin >> n, n) { a.resize(n); for(int i = 0; i < n; i++) { cin >> a[i]; for(int j = 0; j < a[i].size(); j++) { if(a[i][j] == 'Y') a[i][j] = '1'; else a[i][j] = '0'; } } bool flag1 = false; bool fused[12]; for(int i = 9; i >= n - 1; i--) { bool flag2 = true; memset(fused, 0, sizeof fused); for(int j = 0; j < n && flag2; j++) { string s = segment[i - j]; for(int k = 0; k < s.size(); k++) { if(fused[k] == 1 && a[j][k] == '1') flag2 = false; if(s[k] == '1' && a[j][k] == '0') fused[k] = 1; if(s[k] == '0' && a[j][k] == '1') flag2 = false; } } if(flag2) { flag1 = true; break; } } if(flag1) { cout << "MATCH\n"; } else { cout << "MISMATCH\n"; } } }
25.246753
117
0.454218
[ "vector" ]
555da3d85bbff068d986987403ce26ca99f23d73
3,094
cpp
C++
ImportantExample/QRestClient/responsewidget.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
3
2018-12-24T19:35:52.000Z
2022-02-04T14:45:59.000Z
ImportantExample/QRestClient/responsewidget.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
null
null
null
ImportantExample/QRestClient/responsewidget.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
1
2019-05-09T02:42:40.000Z
2019-05-09T02:42:40.000Z
/*************************************************************************** * Copyright (C) 2014 by Peter Komar * * udldevel@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "responsewidget.h" #include "qjsonview.h" #include "qcsvview.h" #include <QTextEdit> #include <QDebug> ResponseWidget::ResponseWidget(QWidget *parent) : QStackedWidget(parent) { m_textView = new QTextEdit; m_textView->setAcceptRichText(false); m_textView->setReadOnly(true); addWidget(m_textView); m_jsonView = new QJsonView; addWidget(m_jsonView); m_csvView = new QCsvView; addWidget(m_csvView); setCurrentIndex(0); m_text = ""; } void ResponseWidget::setText(const QString& text) { m_text = text; } void ResponseWidget::append(const QString& text) { m_text += text; } ResponseWidget::type ResponseWidget::render(type typeResponse) { type index = TYPE_TEXT; QString body = m_text; try{ switch(typeResponse) { case TYPE_JSON : body.replace(">", "&gt;").replace("<", "&lt;"); m_jsonView->setJson(body); index = TYPE_JSON; break; case TYPE_TEXT: index = TYPE_TEXT; m_textView->setText(body); break; case TYPE_CSV: index = TYPE_CSV; m_csvView->setText(body); break; } } catch(...) { index = TYPE_TEXT; m_textView->setText(body); } setCurrentIndex(index); return index; } QString ResponseWidget::toText() { return m_text; } void ResponseWidget::clear() { m_textView->clear(); m_jsonView->clear(); m_text.clear(); }
30.038835
77
0.480608
[ "render" ]
5562749583583e258068f10119f5c6de4720d7f5
21,121
cpp
C++
test/PowerBalancerAgentTest.cpp
alawibaba/geopm
dc5dd54cf260b0b51d517bb50d1ba5db9e013c71
[ "BSD-3-Clause" ]
null
null
null
test/PowerBalancerAgentTest.cpp
alawibaba/geopm
dc5dd54cf260b0b51d517bb50d1ba5db9e013c71
[ "BSD-3-Clause" ]
null
null
null
test/PowerBalancerAgentTest.cpp
alawibaba/geopm
dc5dd54cf260b0b51d517bb50d1ba5db9e013c71
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015, 2016, 2017, 2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <memory> #include "gtest/gtest.h" #include "gmock/gmock.h" #include "MockPowerGovernor.hpp" #include "MockPowerBalancer.hpp" #include "MockPlatformIO.hpp" #include "MockPlatformTopo.hpp" #include "PowerBalancerAgent.hpp" #include "Helper.hpp" #include "geopm_test.hpp" #include "config.h" using geopm::PowerBalancerAgent; using geopm::IPlatformTopo; using ::testing::_; using ::testing::DoAll; using ::testing::SetArgReferee; using ::testing::ContainerEq; using ::testing::Return; using ::testing::Sequence; using ::testing::InvokeWithoutArgs; using ::testing::InSequence; class PowerBalancerAgentTest : public ::testing::Test { protected: enum { M_SIGNAL_EPOCH_COUNT, M_SIGNAL_EPOCH_RUNTIME, }; MockPlatformIO m_platform_io; MockPlatformTopo m_platform_topo; std::unique_ptr<MockPowerGovernor> m_power_gov; std::unique_ptr<MockPowerBalancer> m_power_bal; std::unique_ptr<PowerBalancerAgent> m_agent; const double M_POWER_PACKAGE_MAX = 325; const int M_NUM_PKGS = 1; const std::vector<int> M_FAN_IN = {2, 2}; }; TEST_F(PowerBalancerAgentTest, power_balancer_agent) { const std::vector<std::string> exp_pol_names = {"POWER_CAP", "STEP_COUNT", "MAX_EPOCH_RUNTIME", "POWER_SLACK"}; const std::vector<std::string> exp_smp_names = {"STEP_COUNT", "MAX_EPOCH_RUNTIME", "SUM_POWER_SLACK", "MIN_POWER_HEADROOM"}; m_agent = geopm::make_unique<PowerBalancerAgent>(m_platform_io, m_platform_topo, std::move(m_power_gov), std::move(m_power_bal)); PowerBalancerAgent::make_plugin(); EXPECT_EQ("power_balancer", m_agent->plugin_name()); EXPECT_EQ(exp_pol_names, m_agent->policy_names()); EXPECT_EQ(exp_smp_names, m_agent->sample_names()); m_agent->report_header(); m_agent->report_node(); m_agent->report_region(); m_agent->wait(); GEOPM_EXPECT_THROW_MESSAGE(m_agent->init(0, {}, false), GEOPM_ERROR_RUNTIME, "single node job detected, user power_governor."); } TEST_F(PowerBalancerAgentTest, tree_root_agent) { const bool IS_ROOT = true; int level = 2; int num_children = M_FAN_IN[level - 1]; EXPECT_CALL(m_platform_io, read_signal("POWER_PACKAGE_MIN", IPlatformTopo::M_DOMAIN_PACKAGE, 0)) .WillOnce(Return(50)); EXPECT_CALL(m_platform_io, read_signal("POWER_PACKAGE_MAX", IPlatformTopo::M_DOMAIN_PACKAGE, 0)) .WillOnce(Return(200)); EXPECT_CALL(m_platform_io, control_domain_type("POWER_PACKAGE")) .WillOnce(Return(IPlatformTopo::M_DOMAIN_PACKAGE)); EXPECT_CALL(m_platform_topo, num_domain(IPlatformTopo::M_DOMAIN_PACKAGE)) .WillOnce(Return(2)); m_agent = geopm::make_unique<PowerBalancerAgent>(m_platform_io, m_platform_topo, std::move(m_power_gov), std::move(m_power_bal)); m_agent->init(level, M_FAN_IN, IS_ROOT); std::vector<double> in_policy; std::vector<std::vector<double> > exp_out_policy; std::vector<std::vector<double> > in_sample; std::vector<double> exp_out_sample; std::vector<std::vector<double> > out_policy = std::vector<std::vector<double> >(num_children, {NAN, NAN, NAN, NAN}); std::vector<double> out_sample = {NAN, NAN, NAN, NAN}; #ifdef GEOPM_DEBUG GEOPM_EXPECT_THROW_MESSAGE(m_agent->adjust_platform(in_policy), GEOPM_ERROR_LOGIC, "was called on non-leaf agent"); GEOPM_EXPECT_THROW_MESSAGE(m_agent->sample_platform(out_sample), GEOPM_ERROR_LOGIC, "was called on non-leaf agent"); GEOPM_EXPECT_THROW_MESSAGE(m_agent->trace_names(), GEOPM_ERROR_LOGIC, "was called on non-leaf agent"); std::vector<double> trace_data; GEOPM_EXPECT_THROW_MESSAGE(m_agent->trace_values(trace_data), GEOPM_ERROR_LOGIC, "was called on non-leaf agent"); #endif int ctl_step = 0; double curr_cap = 300; double curr_cnt = (double) ctl_step; double curr_epc = 0.0; double curr_slk = 0.0; double curr_hrm = 0.0; bool exp_descend_ret = true; bool exp_ascend_ret = true; bool desc_ret; bool ascend_ret; /// M_STEP_SEND_DOWN_LIMIT { in_policy = {curr_cap, curr_cnt, curr_epc, curr_slk}; exp_out_policy = std::vector<std::vector<double> >(num_children, {curr_cap, curr_cnt, curr_epc, curr_slk}); in_sample = std::vector<std::vector<double> >(num_children, {(double)ctl_step, curr_epc, curr_slk, curr_hrm}); exp_out_sample = {(double)ctl_step, curr_epc, curr_slk, curr_hrm}; #ifdef GEOPM_DEBUG std::vector<std::vector<double> > inv_out_policy = {}; GEOPM_EXPECT_THROW_MESSAGE(m_agent->descend({}, out_policy), GEOPM_ERROR_LOGIC, "policy vectors are not correctly sized."); GEOPM_EXPECT_THROW_MESSAGE(m_agent->descend(in_policy, inv_out_policy), GEOPM_ERROR_LOGIC, "policy vectors are not correctly sized."); #endif desc_ret = m_agent->descend(in_policy, out_policy); EXPECT_EQ(exp_descend_ret, desc_ret); EXPECT_THAT(out_policy, ContainerEq(exp_out_policy)); #ifdef GEOPM_DEBUG std::vector<double> inv_out_sample = {}; GEOPM_EXPECT_THROW_MESSAGE(m_agent->ascend({}, out_sample), GEOPM_ERROR_LOGIC, "sample vectors not correctly sized."); GEOPM_EXPECT_THROW_MESSAGE(m_agent->ascend(in_sample, inv_out_sample), GEOPM_ERROR_LOGIC, "sample vectors not correctly sized."); #endif ascend_ret = m_agent->ascend(in_sample, out_sample); EXPECT_EQ(exp_ascend_ret, ascend_ret); EXPECT_THAT(out_sample, ContainerEq(exp_out_sample)); } ctl_step = 1; curr_cnt = (double) ctl_step; /// M_STEP_MEASURE_RUNTIME { in_policy = {curr_cap, 0.0, 0.0, 0.0}; exp_out_policy = std::vector<std::vector<double> >(num_children, {0.0, curr_cnt, curr_epc, curr_slk}); curr_epc = 22.0; in_sample = std::vector<std::vector<double> >(num_children, {(double)ctl_step, curr_epc, curr_slk, curr_hrm}); exp_out_sample = {(double)ctl_step, curr_epc, curr_slk, curr_hrm}; desc_ret = m_agent->descend(in_policy, out_policy); EXPECT_EQ(exp_descend_ret, desc_ret); EXPECT_THAT(out_policy, ContainerEq(exp_out_policy)); ascend_ret = m_agent->ascend(in_sample, out_sample); EXPECT_EQ(exp_ascend_ret, ascend_ret); EXPECT_THAT(out_sample, ContainerEq(exp_out_sample)); } ctl_step = 2; curr_cnt = (double) ctl_step; /// M_STEP_REDUCE_LIMIT { in_policy = {curr_cap, 0.0, 0.0, 0.0}; exp_out_policy = std::vector<std::vector<double> >(num_children, {0.0, curr_cnt, curr_epc, curr_slk}); curr_slk = 9.0; in_sample = std::vector<std::vector<double> >(num_children, {(double)ctl_step, curr_epc, curr_slk, curr_hrm}); exp_out_sample = {(double)ctl_step, curr_epc, num_children * curr_slk, curr_hrm};///@todo update when/if updated to use unique child sample inputs desc_ret = m_agent->descend(in_policy, out_policy); EXPECT_EQ(exp_descend_ret, desc_ret); EXPECT_THAT(out_policy, ContainerEq(exp_out_policy)); ascend_ret = m_agent->ascend(in_sample, out_sample); EXPECT_EQ(exp_ascend_ret, ascend_ret); EXPECT_THAT(out_sample, ContainerEq(exp_out_sample)); } ctl_step = 3; curr_cnt = (double) ctl_step; curr_slk = 0.0;///@todo exp_out_policy = std::vector<std::vector<double> >(num_children, {0.0, curr_cnt, curr_epc, curr_slk}); /// M_STEP_SEND_DOWN_LIMIT { desc_ret = m_agent->descend(in_policy, out_policy); EXPECT_EQ(exp_descend_ret, desc_ret); EXPECT_THAT(out_policy, ContainerEq(exp_out_policy)); } } TEST_F(PowerBalancerAgentTest, tree_agent) { const bool IS_ROOT = false; int level = 1; int num_children = M_FAN_IN[level - 1]; m_agent = geopm::make_unique<PowerBalancerAgent>(m_platform_io, m_platform_topo, std::move(m_power_gov), std::move(m_power_bal)); m_agent->init(level, M_FAN_IN, IS_ROOT); std::vector<double> in_policy; std::vector<std::vector<double> > exp_out_policy; std::vector<std::vector<double> > in_sample; std::vector<double> exp_out_sample; std::vector<std::vector<double> > out_policy = std::vector<std::vector<double> >(num_children, {NAN, NAN, NAN, NAN}); std::vector<double> out_sample = {NAN, NAN, NAN, NAN}; #ifdef GEOPM_DEBUG GEOPM_EXPECT_THROW_MESSAGE(m_agent->adjust_platform(in_policy), GEOPM_ERROR_LOGIC, "was called on non-leaf agent"); GEOPM_EXPECT_THROW_MESSAGE(m_agent->sample_platform(out_sample), GEOPM_ERROR_LOGIC, "was called on non-leaf agent"); GEOPM_EXPECT_THROW_MESSAGE(m_agent->trace_names(), GEOPM_ERROR_LOGIC, "was called on non-leaf agent"); std::vector<double> trace_data; GEOPM_EXPECT_THROW_MESSAGE(m_agent->trace_values(trace_data), GEOPM_ERROR_LOGIC, "was called on non-leaf agent"); #endif int ctl_step = 0; double curr_cap = 300; double curr_cnt = (double) ctl_step; double curr_epc = 0.0; double curr_slk = 0.0; double curr_hrm = 0.0; bool exp_descend_ret = true; bool exp_ascend_ret = true; bool desc_ret; bool ascend_ret; /// M_STEP_SEND_DOWN_LIMIT { in_policy = {curr_cap, curr_cnt, curr_epc, curr_slk}; exp_out_policy = std::vector<std::vector<double> >(num_children, {curr_cap, curr_cnt, curr_epc, curr_slk}); in_sample = std::vector<std::vector<double> >(num_children, {(double)ctl_step, curr_epc, curr_slk, curr_hrm}); exp_out_sample = {(double)ctl_step, curr_epc, 0.0, 0.0}; #ifdef GEOPM_DEBUG std::vector<std::vector<double> > inv_out_policy = {}; GEOPM_EXPECT_THROW_MESSAGE(m_agent->descend({}, out_policy), GEOPM_ERROR_LOGIC, "policy vectors are not correctly sized."); GEOPM_EXPECT_THROW_MESSAGE(m_agent->descend(in_policy, inv_out_policy), GEOPM_ERROR_LOGIC, "policy vectors are not correctly sized."); #endif desc_ret = m_agent->descend(in_policy, out_policy); EXPECT_EQ(exp_descend_ret, desc_ret); EXPECT_THAT(out_policy, ContainerEq(exp_out_policy)); #ifdef GEOPM_DEBUG std::vector<double> inv_out_sample = {}; GEOPM_EXPECT_THROW_MESSAGE(m_agent->ascend({}, out_sample), GEOPM_ERROR_LOGIC, "sample vectors not correctly sized."); GEOPM_EXPECT_THROW_MESSAGE(m_agent->ascend(in_sample, inv_out_sample), GEOPM_ERROR_LOGIC, "sample vectors not correctly sized."); #endif ascend_ret = m_agent->ascend(in_sample, out_sample); EXPECT_EQ(exp_ascend_ret, ascend_ret); EXPECT_THAT(out_sample, ContainerEq(exp_out_sample)); } ctl_step = 1; curr_cnt = (double) ctl_step; /// M_STEP_MEASURE_RUNTIME { in_policy = {0.0, curr_cnt, 0.0, 0.0}; exp_out_policy = std::vector<std::vector<double> >(num_children, {0.0, curr_cnt, curr_epc, curr_slk}); curr_epc = 22.0; in_sample = std::vector<std::vector<double> >(num_children, {(double)ctl_step, curr_epc, curr_slk, curr_hrm}); exp_out_sample = {(double)ctl_step, curr_epc, curr_slk, curr_hrm}; desc_ret = m_agent->descend(in_policy, out_policy); EXPECT_EQ(exp_descend_ret, desc_ret); EXPECT_THAT(out_policy, ContainerEq(exp_out_policy)); ascend_ret = m_agent->ascend(in_sample, out_sample); EXPECT_EQ(exp_ascend_ret, ascend_ret); EXPECT_THAT(out_sample, ContainerEq(exp_out_sample)); } ctl_step = 2; curr_cnt = (double) ctl_step; /// M_STEP_REDUCE_LIMIT { in_policy = {0.0, curr_cnt, curr_epc, 0.0}; exp_out_policy = std::vector<std::vector<double> >(num_children, {0.0, curr_cnt, curr_epc, curr_slk}); curr_slk = 9.0; in_sample = std::vector<std::vector<double> >(num_children, {(double)ctl_step, curr_epc, curr_slk, curr_hrm}); exp_out_sample = {(double)ctl_step, curr_epc, num_children * curr_slk, curr_hrm};///@todo update when/if updated to use unique child sample inputs desc_ret = m_agent->descend(in_policy, out_policy); EXPECT_EQ(exp_descend_ret, desc_ret); EXPECT_THAT(out_policy, ContainerEq(exp_out_policy)); ascend_ret = m_agent->ascend(in_sample, out_sample); EXPECT_EQ(exp_ascend_ret, ascend_ret); EXPECT_THAT(out_sample, ContainerEq(exp_out_sample)); } ctl_step = 3; curr_cnt = (double) ctl_step; curr_slk /= num_children; exp_out_policy = std::vector<std::vector<double> >(num_children, {0.0, curr_cnt, 0.0, curr_slk}); /// M_STEP_SEND_DOWN_LIMIT { in_policy = {0.0, curr_cnt, 0.0, curr_slk}; desc_ret = m_agent->descend(in_policy, out_policy); EXPECT_EQ(exp_descend_ret, desc_ret); EXPECT_THAT(out_policy, ContainerEq(exp_out_policy)); } } TEST_F(PowerBalancerAgentTest, leaf_agent) { const bool IS_ROOT = false; int level = 0; int num_children = 1; int counter = 0; std::vector<double> trace_vals(7, NAN); std::vector<double> exp_trace_vals(7, NAN); const std::vector<std::string> trace_cols = {"epoch_runtime", "power_limit", "policy_power_cap", "policy_step_count", "policy_max_epoch_runtime", "policy_power_slack", "policy_power_limit"}; std::vector<double> epoch_rt = {2.0, 2.19}; EXPECT_CALL(m_platform_topo, num_domain(IPlatformTopo::M_DOMAIN_PACKAGE)) .WillOnce(Return(M_NUM_PKGS)); EXPECT_CALL(m_platform_io, read_signal("POWER_PACKAGE_MAX", IPlatformTopo::M_DOMAIN_PACKAGE, _)) .WillOnce(Return(M_POWER_PACKAGE_MAX)); EXPECT_CALL(m_platform_io, push_signal("EPOCH_COUNT", IPlatformTopo::M_DOMAIN_BOARD, 0)) .WillOnce(Return(M_SIGNAL_EPOCH_COUNT)); EXPECT_CALL(m_platform_io, push_signal("EPOCH_RUNTIME", IPlatformTopo::M_DOMAIN_BOARD, 0)) .WillOnce(Return(M_SIGNAL_EPOCH_RUNTIME)); EXPECT_CALL(m_platform_io, sample(M_SIGNAL_EPOCH_COUNT)) .WillRepeatedly(InvokeWithoutArgs([&counter]() { return (double) ++counter; })); Sequence pio_seq; for (size_t x = 0; x < epoch_rt.size(); ++x) { EXPECT_CALL(m_platform_io, sample(M_SIGNAL_EPOCH_RUNTIME)) .InSequence(pio_seq) .WillOnce(Return(epoch_rt[x])); } m_power_gov = geopm::make_unique<MockPowerGovernor>(); EXPECT_CALL(*m_power_gov, init_platform_io()); EXPECT_CALL(*m_power_gov, sample_platform()) .Times(4); double actual_limit = 299.0; EXPECT_CALL(*m_power_gov, adjust_platform(300.0, _)) .Times(4) .WillRepeatedly(DoAll(SetArgReferee<1>(actual_limit), Return(true))); m_power_bal = geopm::make_unique<MockPowerBalancer>(); EXPECT_CALL(*m_power_bal, power_limit_adjusted(actual_limit)) .Times(4); EXPECT_CALL(*m_power_bal, target_runtime(epoch_rt[0])); EXPECT_CALL(*m_power_bal, calculate_runtime_sample()).Times(2); EXPECT_CALL(*m_power_bal, runtime_sample()) .WillRepeatedly(Return(epoch_rt[0])); EXPECT_CALL(*m_power_bal, is_runtime_stable(epoch_rt[0])) .WillOnce(Return(true)); EXPECT_CALL(*m_power_bal, is_target_met(epoch_rt[1])) .WillRepeatedly(Return(true)); EXPECT_CALL(*m_power_bal, power_cap(300.0)) .Times(2); EXPECT_CALL(*m_power_bal, power_cap()) .WillRepeatedly(Return(300.0)); EXPECT_CALL(*m_power_bal, power_limit()) .WillRepeatedly(Return(300.0)); m_agent = geopm::make_unique<PowerBalancerAgent>(m_platform_io, m_platform_topo, std::move(m_power_gov), std::move(m_power_bal)); m_agent->init(level, M_FAN_IN, IS_ROOT); EXPECT_EQ(trace_cols, m_agent->trace_names()); std::vector<double> in_policy; std::vector<double> exp_out_sample; std::vector<std::vector<double> > out_policy = std::vector<std::vector<double> >(num_children, {NAN, NAN, NAN, NAN}); std::vector<double> out_sample = {NAN, NAN, NAN, NAN}; #ifdef GEOPM_DEBUG std::vector<double> err_trace_vals, err_out_sample; GEOPM_EXPECT_THROW_MESSAGE(m_agent->trace_values(err_trace_vals), GEOPM_ERROR_LOGIC, "values vector not correctly sized."); GEOPM_EXPECT_THROW_MESSAGE(m_agent->adjust_platform({}), GEOPM_ERROR_LOGIC, "policy vector incorrectly sized."); GEOPM_EXPECT_THROW_MESSAGE(m_agent->sample_platform(err_out_sample), GEOPM_ERROR_LOGIC, "out_sample vector not correctly sized."); GEOPM_EXPECT_THROW_MESSAGE(m_agent->descend({} ,out_policy), GEOPM_ERROR_LOGIC, "was called on non-tree agent"); GEOPM_EXPECT_THROW_MESSAGE(m_agent->ascend({}, out_sample), GEOPM_ERROR_LOGIC, "was called on non-tree agent"); #endif int ctl_step = 0; double curr_cap = 300; double curr_cnt = (double) ctl_step; double curr_epc = 0.0; double curr_slk = 0.0; bool exp_adj_plat_ret = true; bool exp_smp_plat_ret = true; bool adj_ret; bool smp_ret; /// M_STEP_SEND_DOWN_LIMIT { in_policy = {curr_cap, curr_cnt, curr_epc, curr_slk}; exp_out_sample = {(double)ctl_step, curr_epc, 0.0, 0.0}; adj_ret = m_agent->adjust_platform(in_policy); EXPECT_EQ(exp_adj_plat_ret, adj_ret); smp_ret = m_agent->sample_platform(out_sample); EXPECT_EQ(exp_smp_plat_ret, smp_ret); EXPECT_EQ(out_sample, exp_out_sample); m_agent->trace_values(trace_vals); //EXPECT_EQ(exp_trace_vals, trace_vals); } ctl_step = 1; curr_cnt = (double) ctl_step; /// M_STEP_MEASURE_RUNTIME { in_policy = {0.0, curr_cnt, curr_epc, curr_slk}; curr_epc = epoch_rt[ctl_step - 1]; exp_out_sample = {(double)ctl_step, curr_epc, 0.0, 0.0}; adj_ret = m_agent->adjust_platform(in_policy); EXPECT_EQ(exp_adj_plat_ret, adj_ret); smp_ret = m_agent->sample_platform(out_sample); EXPECT_EQ(exp_smp_plat_ret, smp_ret); EXPECT_EQ(out_sample, exp_out_sample); } ctl_step = 2; curr_cnt = (double) ctl_step; /// M_STEP_REDUCE_LIMIT { in_policy = {0.0, curr_cnt, curr_epc, curr_slk}; exp_out_sample = {(double)ctl_step, curr_epc, 0.0, 25.0}; adj_ret = m_agent->adjust_platform(in_policy); EXPECT_EQ(exp_adj_plat_ret, adj_ret); smp_ret = m_agent->sample_platform(out_sample); EXPECT_EQ(exp_smp_plat_ret, smp_ret); EXPECT_EQ(out_sample, exp_out_sample); } ctl_step = 3; curr_cnt = (double) ctl_step; /// M_STEP_SEND_DOWN_LIMIT { in_policy = {0.0, curr_cnt, curr_epc, curr_slk}; exp_out_sample = {(double)ctl_step, curr_epc, 0.0, 25.0}; adj_ret = m_agent->adjust_platform(in_policy); EXPECT_EQ(exp_adj_plat_ret, adj_ret); smp_ret = m_agent->sample_platform(out_sample); EXPECT_EQ(exp_smp_plat_ret, smp_ret); EXPECT_EQ(out_sample, exp_out_sample); } }
41.741107
150
0.673595
[ "vector" ]
556bc54025bfc5a5179f9b16625691372b218355
6,303
cpp
C++
src/shader/compiler.cpp
SleepKiller/shaderpatch
4bda848df0273993c96f1d20a2cf79161088a77d
[ "MIT" ]
13
2019-03-25T09:40:12.000Z
2022-03-13T16:12:39.000Z
src/shader/compiler.cpp
SleepKiller/shaderpatch
4bda848df0273993c96f1d20a2cf79161088a77d
[ "MIT" ]
110
2018-10-16T09:05:43.000Z
2022-03-16T23:32:28.000Z
src/shader/compiler.cpp
SleepKiller/swbfii-shaderpatch
b49ce3349d4dd09b19237ff4766652166ba1ffd4
[ "MIT" ]
1
2020-02-06T20:32:50.000Z
2020-02-06T20:32:50.000Z
#include "compiler.hpp" #include "../logger.hpp" #include "retry_dialog.hpp" #include <type_traits> #include <absl/container/inlined_vector.h> #include <d3dcompiler.h> using namespace std::literals; namespace sp::shader { namespace { using Shader_defines = absl::InlinedVector<D3D_SHADER_MACRO, 64>; class Includer : public ID3DInclude { public: explicit Includer(const Source_file_store& file_store) : _file_store{file_store} { } auto __stdcall Open([[maybe_unused]] D3D_INCLUDE_TYPE include_type, LPCSTR file_name, [[maybe_unused]] LPCVOID parent_data, LPCVOID* data_out, UINT* data_size_out) noexcept -> HRESULT override { auto data = _file_store.data(file_name); if (!data) return E_FAIL; static_assert(std::is_same_v<std::size_t, UINT>); *data_out = data->data(); *data_size_out = data->size(); return S_OK; } auto __stdcall Close(LPCVOID) noexcept -> HRESULT override { return S_OK; } private: const Source_file_store& _file_store; }; auto get_stage_define(const Entrypoint_description& entrypoint) -> D3D_SHADER_MACRO { switch (entrypoint.stage) { // clang-format off case Stage::compute: return {"__COMPUTE_SHADER__", "1"}; case Stage::vertex: return {"__VERTEX_SHADER__", "1"}; case Stage::hull: return {"__HULL_SHADER__", "1"}; case Stage::domain: return {"__DOMAIN_SHADER__", "1"}; case Stage::geometry: return {"__GEOMETRY_SHADER__", "1"}; case Stage::pixel: return {"__PIXEL_SHADER__", "1"}; // clang-format on } std::terminate(); } void get_vertex_shader_defines(const Entrypoint_description& entrypoint, const Vertex_shader_flags vertex_shader_flags, Shader_defines& output) { const auto input_state = entrypoint.vertex_state.generic_input_state; const bool compressed = ((vertex_shader_flags & Vertex_shader_flags::compressed) != Vertex_shader_flags::none) || input_state.always_compressed; const bool hard_skinned = ((vertex_shader_flags & Vertex_shader_flags::hard_skinned) != Vertex_shader_flags::none) && input_state.skinned; const bool color = ((vertex_shader_flags & Vertex_shader_flags::color) != Vertex_shader_flags::none) && input_state.color; if (compressed) { output.emplace_back("__VERTEX_INPUT_IS_COMPRESSED__", "1"); } if (input_state.position) { output.emplace_back("__VERTEX_INPUT_POSITION__", "1"); } if (hard_skinned) { output.emplace_back("__VERTEX_INPUT_BLEND_INDICES__", "1"); } if (input_state.normal) { output.emplace_back("__VERTEX_INPUT_NORMAL__", "1"); } if (input_state.tangents) { output.emplace_back("__VERTEX_INPUT_TANGENTS__", "1"); } if (color) { output.emplace_back("__VERTEX_INPUT_COLOR__", "1"); } if (input_state.texture_coords) { output.emplace_back("__VERTEX_INPUT_TEXCOORDS__", "1"); } output.emplace_back(hard_skinned ? "__VERTEX_TRANSFORM_HARD_SKINNED__" : "__VERTEX_TRANSFORM_UNSKINNED__", "1"); } auto get_shader_defines(const Entrypoint_description& entrypoint, const std::uint64_t static_flags, const Vertex_shader_flags vertex_shader_flags) -> Shader_defines { Shader_defines d3d_shader_defines; d3d_shader_defines.emplace_back(get_stage_define(entrypoint)); if (entrypoint.stage == Stage::vertex) { get_vertex_shader_defines(entrypoint, vertex_shader_flags, d3d_shader_defines); } entrypoint.static_flags.get_flags_defines(static_flags, d3d_shader_defines); for (const auto& define : entrypoint.preprocessor_defines) { d3d_shader_defines.emplace_back(define.name.data(), define.definition.data()); } d3d_shader_defines.emplace_back(nullptr, nullptr); return d3d_shader_defines; } auto get_target(const Entrypoint_description& entrypoint) -> const char* { switch (entrypoint.stage) { // clang-format off case Stage::compute: return "cs_5_0"; case Stage::vertex: return "vs_5_0"; case Stage::hull: return "hs_5_0"; case Stage::domain: return "ds_5_0"; case Stage::geometry: return "gs_5_0"; case Stage::pixel: return "ps_5_0"; // clang-format on } std::terminate(); } } auto compile(Source_file_store& file_store, const Entrypoint_description& entrypoint, const std::uint64_t static_flags, const Vertex_shader_flags vertex_shader_flags) noexcept -> Bytecode_blob { auto source = file_store.data(entrypoint.source_name); if (!source) { log_and_terminate("Unable to get shader source code. Can't compile."); } auto shader_defines = get_shader_defines(entrypoint, static_flags, vertex_shader_flags); Includer includer{file_store}; Com_ptr<ID3DBlob> bytecode_result; Com_ptr<ID3DBlob> error_messages; auto result = D3DCompile(source->data(), source->size(), file_store.file_path(entrypoint.source_name).data(), shader_defines.data(), &includer, entrypoint.function_name.data(), get_target(entrypoint), D3DCOMPILE_OPTIMIZATION_LEVEL2 | D3DCOMPILE_WARNINGS_ARE_ERRORS, 0, bytecode_result.clear_and_assign(), error_messages.clear_and_assign()); if (FAILED(result)) { const std::string_view error_message_view = {static_cast<const char*>( error_messages->GetBufferPointer()), error_messages->GetBufferSize()}; if (retry_dialog("Shader Compile Error"s, error_message_view)) { file_store.reload(); return compile(file_store, entrypoint, static_flags, vertex_shader_flags); } log_and_terminate("Unable to compile shader!\n", error_message_view); } log_debug("Compiled shader {}:{}({:x})"sv, entrypoint.source_name, entrypoint.function_name, static_flags); return Bytecode_blob{std::move(bytecode_result)}; } }
30.746341
91
0.659686
[ "geometry" ]
557154928c7c54059661719b86f10667654efb4f
13,498
cpp
C++
catkin_ws/src/aist_modules/aist_motion_detector/src/MotionDetector.cpp
mitdo/o2ac-ur
74c82a54a693bf6a3fc995ff63e7c91ac1fda6fd
[ "MIT" ]
32
2021-09-02T12:29:47.000Z
2022-03-30T21:44:10.000Z
catkin_ws/src/aist_modules/aist_motion_detector/src/MotionDetector.cpp
kroglice/o2ac-ur
f684f21fd280a22ec061dc5d503801f6fefb2422
[ "MIT" ]
4
2021-09-22T00:51:14.000Z
2022-01-30T11:54:19.000Z
catkin_ws/src/aist_modules/aist_motion_detector/src/MotionDetector.cpp
kroglice/o2ac-ur
f684f21fd280a22ec061dc5d503801f6fefb2422
[ "MIT" ]
7
2021-11-02T12:26:09.000Z
2022-02-01T01:45:22.000Z
// Software License Agreement (BSD License) // // Copyright (c) 2021, National Institute of Advanced Industrial Science and Technology (AIST) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of National Institute of Advanced Industrial // Science and Technology (AIST) nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Author: Toshio Ueshiba // /*! * \file MotionDetector.cpp * \author Toshio Ueshiba * \brief ROS node for tracking corners in 2D images */ #include "MotionDetector.h" #include <sensor_msgs/image_encodings.h> #include <opencv2/calib3d.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/bgsegm.hpp> namespace aist_motion_detector { /************************************************************************ * static functions * ************************************************************************/ template <class T> static inline cv::Point3_<T> pointTFToCV(const tf::Point& p) { return {p.x(), p.y(), p.z()}; } template <class T> static inline cv::Vec<T, 3> vector3TFToCV(const tf::Vector3& v) { return {v.x(), v.y(), v.z()}; } template <class T> static inline tf::Vector3 vector3CVToTF(const cv::Vec<T, 3>& v) { return {v(0), v(1), v(2)}; } static inline bool withinImage(const cv::Point& p, const cv::Mat& image) { return (0 <= p.x && p.x < image.cols && 0 <= p.y && p.y < image.rows); } template <class T> T distance(const cv::Mat& image, int label, const TU::Plane<T, 2>& line) { auto dmin = std::numeric_limits<T>::max(); for (int v = 0; v < image.rows; ++v) { auto p = image.ptr<int>(v, 0); for (int u = 0; u < image.cols; ++u, ++p) if (*p == label) { const auto d = line.distance({u, v}); if (d < dmin) dmin = d; } } return dmin; } static int findLargestRegion(const cv::Mat& labels, const cv::Mat& stats, int nlabels, const TU::Plane<float, 2>& finger_tip) { int amax = 0; auto lmax = 0; for (int label = 1; label < nlabels; ++label) { const auto d = distance(labels, label, finger_tip); if (d < 2) { using cc_t = cv::ConnectedComponentsTypes; const auto stat = stats.ptr<int>(label); const auto area = stat[cc_t::CC_STAT_AREA]; if (area > amax) { amax = area; lmax = label; } } } return lmax; } template <class T> static cv::Vec<T, 2> crossPoint(const TU::Plane<T, 2>& l1, const TU::Plane<T, 2>& l2) { const cv::Vec<T, 3> h1(l1.normal()(0), l1.normal()(1), l1.distance()); const cv::Vec<T, 3> h2(l2.normal()(0), l2.normal()(1), l2.distance()); const auto p = h1.cross(h2); return {p[0]/p[2], p[1]/p[2]}; } static std::ostream& operator <<(std::ostream& out, const tf::Vector3& v) { return out << ' ' << v.x() << ' ' << v.y() << ' ' << v.z() << std::endl; } /************************************************************************ * class MotionDetector * ************************************************************************/ MotionDetector::MotionDetector(const ros::NodeHandle& nh) :_nh(nh), _it(_nh), _camera_info_sub(_nh, "/camera_info", 1), _image_sub(_it, "/image", 1), _depth_sub(_it, "/depth", 1), _sync(sync_policy_t(10), _camera_info_sub, _image_sub, _depth_sub), _image_pub(_it.advertise("image", 1)), _camera_pub(_it.advertiseCamera("depth", 1)), _listener(), _broadcaster(), _find_cabletip_srv(_nh, "find_cabletip", false), _current_goal(nullptr), _ddr(_nh), _bgsub(cv::createBackgroundSubtractorMOG2()), _search_top(_nh.param("search_top", 0.005)), _search_bottom(_nh.param("search_bottom", 0.030)), _search_width(_nh.param("search_width", 0.050)) { // Setup FindCabletip action server. _find_cabletip_srv.registerGoalCallback(boost::bind(&goal_cb, this)); _find_cabletip_srv.registerPreemptCallback(boost::bind(&preempt_cb, this)); _find_cabletip_srv.start(); // Setup callback for synced camera_info and depth. _sync.registerCallback(&image_cb, this); // Setup parameters and ddynamic_reconfigure server. _ddr.registerVariable<double>("search_top", &_search_top, "Top of search area in meters", -0.010, 0.010); _ddr.registerVariable<double>("search_bottom", &_search_bottom, "Bottom of search area in meters", 0.005, 0.050); _ddr.registerVariable<double>("search_width", &_search_width, "Width of search area in meters", 0.005, 0.080); _ddr.publishServicesTopics(); } MotionDetector::~MotionDetector() { } void MotionDetector::run() { ros::spin(); } void MotionDetector::goal_cb() { _current_goal = _find_cabletip_srv.acceptNewGoal(); ROS_INFO_STREAM("(MotionDetector) Given a goal[" << _current_goal->target_frame << ']'); } void MotionDetector::preempt_cb() { _find_cabletip_srv.setPreempted(); ROS_INFO_STREAM("(MotionDetector) Cancelled a goal"); } void MotionDetector::image_cb(const camera_info_cp& camera_info, const image_cp& image, const image_cp& depth) { const auto cv_image = cv_bridge::toCvCopy(image); if (_find_cabletip_srv.isActive()) { try { const auto cv_depth = cv_bridge::toCvCopy(depth); const auto T = find_cabletip(cv_image->image, cv_depth->image, _current_goal->target_frame, camera_info); geometry_msgs::Pose pose; tf::poseTFToMsg(T, pose); FindCabletipFeedback feedback; feedback.pose.header.frame_id = _current_goal->target_frame; feedback.pose.header.stamp = ros::Time::now(); feedback.pose.pose = pose; _find_cabletip_srv.publishFeedback(feedback); _broadcaster.sendTransform({T, feedback.pose.header.stamp, feedback.pose.header.frame_id, "cabletip_link"}); _camera_pub.publish(cv_depth->toImageMsg(), camera_info); } catch (const tf::TransformException& err) { ROS_ERROR_STREAM("(MotionDetector) TransformException: " << err.what()); } catch (const cv_bridge::Exception& err) { ROS_ERROR_STREAM("(MotionDetector) cv_bridge exception: " << err.what()); } catch (const std::exception& err) { ROS_ERROR_STREAM("(MotionDetector) " << err.what()); } } _image_pub.publish(cv_image->toImageMsg()); } tf::Transform MotionDetector::find_cabletip(cv::Mat& image, cv::Mat& depth, const std::string& target_frame, const camera_info_cp& camera_info) const { // Create foregroud mask. cv::Mat mask; _bgsub->apply(image, mask); // Binarize mask image. for (int v = 0; v < mask.rows; ++v) { auto p = mask.ptr<uint8_t>(v, 0); for (const auto pe = p + mask.cols; p < pe; ++p) if (*p < 255) *p = 0; } // Get transform from the target frame to camera frame. tf::StampedTransform Tct; _listener.waitForTransform(camera_info->header.frame_id, target_frame, camera_info->header.stamp, ros::Duration(1.0)); _listener.lookupTransform(camera_info->header.frame_id, target_frame, camera_info->header.stamp, Tct); // Transfrom ROI corners to camera frame. const tf::Point pts[] = {{_search_top, 0.0, -_search_width/2}, {_search_top, 0.0, _search_width/2}, {_search_bottom, 0.0, _search_width/2}, {_search_bottom, 0.0, -_search_width/2}}; cv::Mat_<point3_t> pt3s(1, 4); for (size_t i = 0; i < 4; ++i) pt3s(i) = pointTFToCV<value_t>(Tct * pts[i]); // Project ROI corners onto the image. cv::Mat_<value_t> K(3, 3); std::copy_n(std::begin(camera_info->K), 9, K.begin()); cv::Mat_<value_t> D(1, 4); std::copy_n(std::begin(camera_info->D), 4, D.begin()); const auto zero = cv::Mat_<value_t>::zeros(1, 3); cv::Mat_<point2_t> pt2s(1, 4); cv::projectPoints(pt3s, zero, zero, K, D, pt2s); point_t corners[] = {point_t(pt2s(0)), point_t(pt2s(1)), point_t(pt2s(2)), point_t(pt2s(3))}; // Confirm that all the projected corners are included within the image. if (!withinImage(corners[0], mask) || !withinImage(corners[1], mask) || !withinImage(corners[2], mask) || !withinImage(corners[3], mask)) throw std::runtime_error("ROI in 3D space projects onto the outside of image"); // Fill the outside of ROI with zero. const point_t outer[] = {{0, 0}, {mask.cols-1, 0}, {mask.cols-1, mask.rows-1}, {0, mask.rows-1}}; const point_t* borders[] = {outer, corners}; const int npoints[] = {4, 4}; cv::fillPoly(mask, borders, npoints, 2, cv::Scalar(0), cv::LINE_8); // Paint motion mask over the input RGB image. for (int v = 0; v < mask.rows; ++v) { auto p = mask.ptr<uint8_t>(v, 0); auto q = image.ptr<cv::Vec3b>(v, 0); for (const auto pe = p + mask.cols; p < pe; ++p, ++q) if (*p >= 255) (*q)[1] = 255; } // Create a line of finger-tip border. const cv::Vec<value_t, 2> ends[] = {pt2s(0), pt2s(1)}; const line_t fingertip(ends, ends + 2); // Assign labels to the binarized mask image. cv::Mat labels, stats, centroids; const auto nlabels = cv::connectedComponentsWithStats(mask, labels, stats, centroids); // Find a largest region close to the finger-tip border. const auto lmax = findLargestRegion(labels, stats, nlabels, fingertip); // Fit a line to the points in the region. std::vector<cv::Vec<value_t, 2> > cable_points; for (int v = 0; v < labels.rows; ++v) { auto p = labels.ptr<int>(v, 0); auto q = mask.ptr<uint8_t>(v, 0); for (int u = 0; u < labels.cols; ++u, ++p, ++q) if (*p == lmax) { cable_points.push_back({u, v}); *q = 255; } else *q = 0; } line_t cable(cable_points.begin(), cable_points.end()); // Compute cross point between finger-tip border and cable. const auto root = crossPoint(fingertip, cable); // Find a point in the region farest from the cross point. value_t dmax = 0; point2_t cabletip; for (const auto& cable_point : cable_points) { const auto p = cable.projection(cable_point); const auto d = cv::norm(p, root); if (d > dmax) { dmax = d; cabletip = p; } } // Plane including fingertip described w.r.t. camera frame. const auto nc = vector3TFToCV<value_t>(Tct.getBasis() .getColumn(1)); const auto tc = vector3TFToCV<value_t>(Tct.getOrigin()); const plane_t plane(nc, -nc.dot(tc)); // Compute cross point between the plane and view vectors // for root and fingertip. const auto root3 = Tct.inverse() * vector3CVToTF(plane.cross_point( view_vector(camera_info, root(0), root(1)))); const auto tip3 = Tct.inverse() * vector3CVToTF(plane.cross_point( view_vector(camera_info, cabletip.x, cabletip.y))); const auto rx = (tip3 - root3).normalize(); const tf::Vector3 ry(0, 1, 0); const auto rz = rx.cross(ry).normalize(); // Paint motion mask over the input RGB image. for (int v = 0; v < mask.rows; ++v) { auto p = mask.ptr<uint8_t>(v, 0); auto q = image.ptr<cv::Vec3b>(v, 0); auto r = depth.ptr<float>(v, 0); for (const auto pe = p + mask.cols; p < pe; ++p, ++q, ++r) if (*p) { //(*q)[0] = 0; (*q)[1] = 196; (*q)[2] = 196; } else *r = 0; } cv::drawMarker(image, point_t(root), cv::Scalar(0, 255, 255), cv::MARKER_CROSS, 20, 2); cv::drawMarker(image, point_t(cabletip), cv::Scalar(0, 255, 255), cv::MARKER_CROSS, 20, 2); return tf::Transform({rx.x(), ry.x(), rz.x(), rx.y(), ry.y(), rz.y(), rx.z(), ry.z(), rz.z()}, tip3); } MotionDetector::vector3_t MotionDetector::view_vector(const camera_info_cp& camera_info, const value_t u, value_t v) { cv::Mat_<value_t> K(3, 3); std::copy_n(std::begin(camera_info->K), 9, K.begin()); cv::Mat_<value_t> D(1, 4); std::copy_n(std::begin(camera_info->D), 4, D.begin()); cv::Mat_<point2_t> uv(1, 1), xy(1, 1); uv(0) = {u, v}; cv::undistortPoints(uv, xy, K, D); return {xy(0).x, xy(0).y, value_t(1)}; } } // namespace aist_motion_detector
30.469526
94
0.62513
[ "vector", "transform", "3d" ]
55744a575c444de43d6273a503551a2895ab8c26
9,972
hpp
C++
src/UI/UI.hpp
Strife-AI/Strife.Engine
6b83e762f28acb3f4440d5b7763beccfd08dfc8f
[ "NCSA" ]
12
2020-12-27T22:13:58.000Z
2021-03-14T09:03:02.000Z
src/UI/UI.hpp
Strife-AI/Strife.Engine
6b83e762f28acb3f4440d5b7763beccfd08dfc8f
[ "NCSA" ]
10
2021-01-14T15:14:31.000Z
2021-05-24T22:01:09.000Z
src/UI/UI.hpp
Strife-AI/Strife.Engine
6b83e762f28acb3f4440d5b7763beccfd08dfc8f
[ "NCSA" ]
null
null
null
#pragma once #include "Renderer/Renderer.hpp" #include <memory> #include "System/Input.hpp" #include "UiElement.hpp" class Input; class Renderer; struct LabelStyle { LabelStyle() = default; LabelStyle(const FontSettings& font_) : font(font_) { } FontSettings font; std::string text; }; class Label : public UiElement { public: Label* SetStyle(std::shared_ptr<LabelStyle> labelStyle) { _labelStyle = labelStyle; _text = labelStyle->text; RequireReformat(); return this; } Label* SetText(const std::string& text) { _text = text; RequireReformat(); return this; } private: void DoRendering(Renderer* renderer) override { auto position = GetAbsolutePosition(); renderer->RenderString(_labelStyle->font, _text.c_str(), position.XY(), position.z); } void UpdateSize() override { _size = _labelStyle->font.spriteFont->Get() .MeasureStringWithNewlines(_text.c_str(), 1) .AsVectorOfType<float>(); } private: std::shared_ptr<LabelStyle> _labelStyle; std::string _text; }; enum class ButtonType { Text }; struct ButtonStyles { std::shared_ptr<BackgroundStyle> releasedStyle; std::shared_ptr<BackgroundStyle> pressedStyle; std::shared_ptr<BackgroundStyle> hoverStyle; }; struct LabelButtonStyle { std::shared_ptr<LabelStyle> labelStyle; std::shared_ptr<ButtonStyles> buttonStyle; float padding = 0; }; class ButtonStylesBuilder { public: ButtonStylesBuilder& ReleasedStyle(std::shared_ptr<BackgroundStyle> releasedStyle) { _style->releasedStyle = releasedStyle; return *this; } ButtonStylesBuilder& PressedStyle(std::shared_ptr<BackgroundStyle> pressedStyle) { _style->pressedStyle = pressedStyle; return *this; } ButtonStylesBuilder& HoverStyle(std::shared_ptr<BackgroundStyle> hoverStyle) { _style->hoverStyle = hoverStyle; return *this; } std::shared_ptr<ButtonStyles> Build() { return _style; } private: std::shared_ptr<ButtonStyles> _style = std::make_shared<ButtonStyles>(); }; struct PaddingStyle { float top = 0, bottom = 0, left = 0, right = 0; }; class Button : public UiElement { public: Button(); virtual ~Button() = default; Button* SetStyle(std::shared_ptr<ButtonStyles> buttonStyles); void SetInternalPadding(PaddingStyle paddingStyle); void UseLabel(std::shared_ptr<LabelStyle> labelSyle); EventHandler onClicked; EventHandler onHover; EventHandler onHoveredAway; private: enum class ButtonState { Released, Pressed, Hovering }; void DoUpdate(Input* input, float deltaTime) override; void SetState(ButtonState state); std::shared_ptr<ButtonStyles> _buttonStyles; ButtonState _state = ButtonState::Released; PaddingStyle _paddingStyle; }; class Checkbox : public Button { public: Checkbox() { onClicked += [=] { if (!_isRadioButton) { SetIsChecked(!_isChecked); } else if (!_isChecked) { GetRootElement()->VisitElementAndChildren<Checkbox>([=](Checkbox* checkbox) { if (checkbox->_isRadioButton && checkbox->_groupName == this->_groupName) { checkbox->SetIsChecked(false); } }); SetIsChecked(true); } }; } Checkbox* SetIsChecked(bool isChecked) { if (isChecked != _isChecked) { _isChecked = isChecked; if (_isChecked) onChecked.Invoke(); else onUnchecked.Invoke(); } return this; } void AddToRadioButtonGroup(const std::string& groupName) { _isRadioButton = true; _groupName = groupName; } std::string GroupName() const { return _groupName; } bool IsChecked() const { return _isChecked; } EventHandler onChecked; EventHandler onUnchecked; private: bool _isChecked = false; std::string _groupName; bool _isRadioButton = false; }; enum class StackedLayoutDimension { Horizontal = 0, Vertical = 1 }; class PaddingPanel : public UiElement { public: PaddingPanel() : _paddingTop(0), _paddingBottom(0), _paddingLeft(0), _paddingRight(0) { UiElement::AddExistingChild(_childPanel); } void SetPadding(PaddingStyle& style) { SetPadding(style.top, style.bottom, style.left, style.right); } PaddingPanel* SetPadding(float top = 0, float bottom = 0, float left = 0, float right = 0) { _paddingTop = top; _paddingBottom = bottom; _paddingLeft = left; _paddingRight = right; _childPanel->SetRelativePosition(Vector2(left, top)); RequireReformat(); return this; } void UpdateSize() override { UiElement::UpdateSize(); _size += Vector2(_paddingRight, _paddingBottom); } UiElementPtr AddExistingChild(UiElementPtr element) override { _childPanel->AddExistingChild(element); RequireReformat(); return element; } private: std::shared_ptr<UiElement> _childPanel = std::make_shared<UiElement>(); float _paddingTop; float _paddingBottom; float _paddingLeft; float _paddingRight; }; class StackedLayoutPanel : public UiElement { public: StackedLayoutPanel* SetOrientation(StackedLayoutDimension orientation) { _layout = orientation; RequireReformat(); return this; } StackedLayoutPanel* SetSpacing(float spacing) { _spacing = spacing; RequireReformat(); return this; } private: void UpdateSize() override { int layoutDimension = (int)_layout; int otherDimension = !layoutDimension; Vector2 newSize; for (auto& element : _children) { auto size = element->GetSize(); newSize[layoutDimension] += size[layoutDimension]; newSize[otherDimension] = Max(newSize[otherDimension], size[otherDimension]); } if (!_children.empty()) { newSize[layoutDimension] += _spacing * (_children.size() - 1); } _size = newSize; } void DoFormatting() override { UiElement::DoFormatting(); Vector2 position; int layoutDimension = (int)_layout; int otherDimension = !layoutDimension; for (auto& child : _children) { position[otherDimension] = child->GetRelativePositionInternal().XY()[otherDimension]; child->SetRelativeOffsetInternal(position); position[layoutDimension] += _spacing + child->GetSize()[layoutDimension]; } } StackedLayoutDimension _layout = StackedLayoutDimension::Vertical; float _spacing = 0; }; class HiddenPanel : public UiElement { public: UiElementPtr AddExistingChild(UiElementPtr element) override { UiElement::AddExistingChild(element); if (_isHidden) { _children.clear(); _hiddenElements.push_back(element); } return element; } HiddenPanel* SetIsHidden(bool isHidden) { if (isHidden != _isHidden) { std::swap(_hiddenElements, _children); _isHidden = isHidden; RequireReformat(); } return this; } private: std::vector<UiElementPtr> _hiddenElements; bool _isHidden = true; }; class ProgressBar : public UiElement { public: void SetProgress(float percentage) { _percentage = Clamp(percentage, 0.0f, 1.0f); } private: void DoRendering(Renderer* renderer) override { auto rectangle = GetAbsoluteBounds(); rectangle.SetSize(Vector2(_percentage * rectangle.Width(), rectangle.Height())); renderer->RenderRectangle(rectangle, Color::Red(), GetAbsolutePosition().z); } float _percentage = 0; }; class Slider : public UiElement { public: Slider(); float min = 0; float max = 1; float value = 0; EventHandler onChanged; private: void DoRendering(Renderer* renderer) override; void DoUpdate(Input* input, float deltaTime) override; bool _isSliding = false; }; class UiCanvas { public: UiCanvas(); std::shared_ptr<UiElement> RootPanel() const { return _rootPanel; } void Render(Renderer* renderer); void Update(Input* input, float deltaTime); void Reset(); UiElementPtr defaultElement; EventHandler onReset; std::function<void(Input* input, float deltaTime)> onUpdate; std::function<void(Renderer* renderer)> onRender; static SoundEmitter* GetSoundEmitter(); static void Initialize(SoundManager* soundManager); private: std::shared_ptr<UiElement> _rootRootPanel; std::shared_ptr<UiElement> _rootPanel; UiElementPtr _hoveredElement; Vector2 _oldScreenSize; Vector2 _oldMousePosition; }; inline UiElement* GetSelectedRadioButton(UiElement* container, const std::string& groupName) { UiElement* selectedElement = nullptr; container->VisitElementAndChildren<Checkbox>([&](Checkbox* checkbox) { if (checkbox->GroupName() == groupName && checkbox->IsChecked()) { selectedElement = checkbox; } }); return selectedElement; } inline void SetSelectedRadioButton(UiElement* container, const std::string& groupName, const std::string& selectedName) { container->VisitElementAndChildren<Checkbox>([&](Checkbox* checkbox) { if (checkbox->GroupName() == groupName) { checkbox->SetIsChecked(checkbox->name == selectedName); } }); }
22.061947
119
0.627657
[ "render", "vector" ]
5575705573ec89b57dcc7216529bf2e392c881d8
3,646
hpp
C++
src/ttauri/audio/audio_device_win32.hpp
RustWorks/ttauri
4b093eb16465091d01d80159e23fd26e5d4e4c03
[ "BSL-1.0" ]
279
2021-02-17T09:53:40.000Z
2022-03-22T04:08:40.000Z
src/ttauri/audio/audio_device_win32.hpp
RustWorks/ttauri
4b093eb16465091d01d80159e23fd26e5d4e4c03
[ "BSL-1.0" ]
269
2021-02-17T12:53:15.000Z
2022-03-29T22:10:49.000Z
src/ttauri/audio/audio_device_win32.hpp
RustWorks/ttauri
4b093eb16465091d01d80159e23fd26e5d4e4c03
[ "BSL-1.0" ]
25
2021-02-17T17:14:10.000Z
2022-03-16T04:13:00.000Z
// Copyright Take Vos 2020. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #pragma once #include "audio_device.hpp" #include "audio_stream_format.hpp" struct IMMDevice; struct IPropertyStore; struct IMMEndpoint; struct IAudioEndpointVolume; struct IAudioMeterInformation; struct IAudioClient; namespace tt::inline v1 { /*! A class representing an audio device on the system. */ class audio_device_win32 : public audio_device { public: audio_device_win32(IMMDevice *device); ~audio_device_win32(); [[nodiscard]] std::string name() const noexcept override; [[nodiscard]] tt::label label() const noexcept override; [[nodiscard]] audio_device_state state() const noexcept override; [[nodiscard]] audio_direction direction() const noexcept override; [[nodiscard]] bool exclusive() const noexcept override; void set_exclusive(bool exclusive) noexcept override; [[nodiscard]] double sample_rate() const noexcept override; void set_sample_rate(double sample_rate) noexcept override; [[nodiscard]] tt::speaker_mapping input_speaker_mapping() const noexcept override; void set_input_speaker_mapping(tt::speaker_mapping speaker_mapping) noexcept override; [[nodiscard]] std::vector<tt::speaker_mapping> available_input_speaker_mappings() const noexcept override; [[nodiscard]] tt::speaker_mapping output_speaker_mapping() const noexcept override; void set_output_speaker_mapping(tt::speaker_mapping speaker_mapping) noexcept override; [[nodiscard]] std::vector<tt::speaker_mapping> available_output_speaker_mappings() const noexcept override; [[nodiscard]] bool supports_format(audio_stream_format const &format) const noexcept; /** Get the device id for the given win32 audio end-point. */ [[nodiscard]] static audio_device_id get_id(IMMDevice *device) noexcept; private: audio_direction _direction; bool _exclusive = false; double _sample_rate = 0.0; tt::speaker_mapping _speaker_mapping = tt::speaker_mapping::none; audio_stream_format _current_stream_format; IMMDevice *_device = nullptr; IMMEndpoint *_end_point = nullptr; IPropertyStore *_property_store = nullptr; IAudioClient *_audio_client = nullptr; /** Get a user friendly name of the audio device. * This is the name of the audio device itself, such as * "Realtek High Definition Audio". */ std::string device_name() const noexcept; /** Get a user friendly name of the audio end-point device. * This is the name of the end point, such as "Microphone". */ std::string end_point_name() const noexcept; /** Find a stream format based on the prototype_stream_format. * * This function looks for a supported stream format when the device is used in exclusive-mode. * The prototype consists of a sample-rate and speaker mapping. From this the best sample format * is selected: int24 -> float32 -> int20 -> int16. int24 is selected above float, so that ttauri * will handle dithering. * * @param sample_rate The sample rate selected by the user. * @param speaker_mapping The speaker mapping selected by the user. * @return A supported audio_stream_format or empty. */ [[nodiscard]] audio_stream_format find_exclusive_stream_format(double sample_rate, tt::speaker_mapping speaker_mapping) noexcept; /** Get the shared stream format for the device. */ [[nodiscard]] audio_stream_format shared_stream_format() const; }; } // namespace tt::inline v1
40.511111
111
0.741086
[ "vector" ]
5578ad8a2375d03b0e3a7f998f119eea613bd38c
6,016
cpp
C++
src/ioPlacer/src/Netlist.cpp
agorararmard/OpenROAD
efae571392875c1e45c59e358b94d89b9b0735f8
[ "BSD-3-Clause-Clear" ]
null
null
null
src/ioPlacer/src/Netlist.cpp
agorararmard/OpenROAD
efae571392875c1e45c59e358b94d89b9b0735f8
[ "BSD-3-Clause-Clear" ]
null
null
null
src/ioPlacer/src/Netlist.cpp
agorararmard/OpenROAD
efae571392875c1e45c59e358b94d89b9b0735f8
[ "BSD-3-Clause-Clear" ]
1
2022-01-31T10:05:39.000Z
2022-01-31T10:05:39.000Z
///////////////////////////////////////////////////////////////////////////// // // BSD 3-Clause License // // Copyright (c) 2019, University of California, San Diego. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////// #include "Netlist.h" #include "Slots.h" #include "ioplacer/IOPlacer.h" namespace ppl { Netlist::Netlist() { _netPointer.push_back(0); } void Netlist::addIONet(const IOPin& ioPin, const std::vector<InstancePin>& instPins) { _ioPins.push_back(ioPin); _instPins.insert(_instPins.end(), instPins.begin(), instPins.end()); _netPointer.push_back(_instPins.size()); } void Netlist::forEachIOPin(std::function<void(int idx, IOPin&)> func) { for (int idx = 0; idx < _ioPins.size(); ++idx) { func(idx, _ioPins[idx]); } } void Netlist::forEachIOPin( std::function<void(int idx, const IOPin&)> func) const { for (int idx = 0; idx < _ioPins.size(); ++idx) { func(idx, _ioPins[idx]); } } void Netlist::forEachSinkOfIO(int idx, std::function<void(InstancePin&)> func) { int netStart = _netPointer[idx]; int netEnd = _netPointer[idx + 1]; for (int idx = netStart; idx < netEnd; ++idx) { func(_instPins[idx]); } } void Netlist::forEachSinkOfIO( int idx, std::function<void(const InstancePin&)> func) const { int netStart = _netPointer[idx]; int netEnd = _netPointer[idx + 1]; for (int idx = netStart; idx < netEnd; ++idx) { func(_instPins[idx]); } } int Netlist::numSinksOfIO(int idx) { int netStart = _netPointer[idx]; int netEnd = _netPointer[idx + 1]; return netEnd - netStart; } int Netlist::numIOPins() { return _ioPins.size(); } Rect Netlist::getBB(int idx, Point slotPos) { int netStart = _netPointer[idx]; int netEnd = _netPointer[idx + 1]; int minX = slotPos.x(); int minY = slotPos.y(); int maxX = slotPos.x(); int maxY = slotPos.y(); for (int idx = netStart; idx < netEnd; ++idx) { Point pos = _instPins[idx].getPos(); minX = std::min(minX, pos.x()); maxX = std::max(maxX, pos.x()); minY = std::min(minY, pos.y()); maxY = std::max(maxY, pos.y()); } Point upperBounds = Point(maxX, maxY); Point lowerBounds = Point(minX, minY); Rect netBBox(lowerBounds, upperBounds); return netBBox; } int Netlist::computeIONetHPWL(int idx, Point slotPos) { int netStart = _netPointer[idx]; int netEnd = _netPointer[idx + 1]; int minX = slotPos.x(); int minY = slotPos.y(); int maxX = slotPos.x(); int maxY = slotPos.y(); for (int idx = netStart; idx < netEnd; ++idx) { Point pos = _instPins[idx].getPos(); minX = std::min(minX, pos.x()); maxX = std::max(maxX, pos.x()); minY = std::min(minY, pos.y()); maxY = std::max(maxY, pos.y()); } int x = maxX - minX; int y = maxY - minY; return (x + y); } int Netlist::computeIONetHPWL(int idx, Point slotPos, Edge edge, std::vector<Constraint>& constraints) { int hpwl; if (checkSlotForPin(_ioPins[idx], edge, slotPos, constraints)) { hpwl = computeIONetHPWL(idx, slotPos); } else { hpwl = std::numeric_limits<int>::max(); } return hpwl; } int Netlist::computeDstIOtoPins(int idx, Point slotPos) { int netStart = _netPointer[idx]; int netEnd = _netPointer[idx + 1]; int totalDistance = 0; for (int idx = netStart; idx < netEnd; ++idx) { Point pinPos = _instPins[idx].getPos(); totalDistance += std::abs(pinPos.x() - slotPos.x()) + std::abs(pinPos.y() - slotPos.y()); } return totalDistance; } bool Netlist::checkSlotForPin(IOPin& pin, Edge edge, odb::Point& point, std::vector<Constraint> constraints) { bool validSlot = true; for (Constraint constraint : constraints) { int pos = (edge == Edge::Top || edge == Edge::Bottom) ? point.x() : point.y(); if (pin.getDirection() == constraint.direction) { validSlot = checkInterval(constraint, edge, pos); } else if (pin.getName() == constraint.name) { validSlot = checkInterval(constraint, edge, pos); } } return validSlot; } bool Netlist::checkInterval(Constraint constraint, Edge edge, int pos) { return (constraint.interval.getEdge() == edge && pos >= constraint.interval.getBegin() && pos <= constraint.interval.getEnd()); } void Netlist::clear() { _instPins.clear(); _netPointer.clear(); _ioPins.clear(); } } // namespace ppl
27.981395
80
0.643451
[ "vector" ]
5578ec845869be072159a1b85103025aa6fe72ea
1,342
cpp
C++
src/View/GameWindow.cpp
Raffson/Space-Invaders
5c390f0989e7354943c384059ce5d1d63d0a6100
[ "MIT" ]
1
2020-05-24T02:42:47.000Z
2020-05-24T02:42:47.000Z
src/View/GameWindow.cpp
Raffson/Space-Invaders
5c390f0989e7354943c384059ce5d1d63d0a6100
[ "MIT" ]
null
null
null
src/View/GameWindow.cpp
Raffson/Space-Invaders
5c390f0989e7354943c384059ce5d1d63d0a6100
[ "MIT" ]
null
null
null
/* * GameWindow.cpp * * Created on: Nov 18, 2013 * Author: raffson */ #include "GameWindow.h" namespace AR { GameWindow::GameWindow() { sf::ContextSettings settings; settings.antialiasingLevel = 8; window.create(sf::VideoMode(800, 600), "Game Window", sf::Style::Default, settings); window.clear(); window.setVisible(true); view.setCenter(0, 0); window.setView( view ); window.display(); //initialize a window that has a start-button or something like that // -> do this in draw/update function // -> check the game-state, if yet to be started do 'this', otherwise do 'that' } GameWindow::~GameWindow() { } sf::RenderWindow& GameWindow::getWindow() { return window; } const bool GameWindow::Open() const { return window.isOpen(); } void GameWindow::Close() { window.close(); } void GameWindow::Update(const bool& started, const bool& paused, const bool& gameOver, const std::vector<std::shared_ptr<Object> >& data, const unsigned int& lvl) { sf::Font font; font.loadFromFile("default.ttf"); sf::Text message("Generic GameWindow", font); message.setCharacterSize(60); message.setStyle(sf::Text::Bold); message.setColor(sf::Color::Green); message.setPosition(-315, 0); window.clear(); window.draw(message); view.setCenter(0, 0); window.setView( view ); window.display(); } } // namespace AR
20.646154
86
0.695976
[ "object", "vector" ]
557921093f757ac279429b99b2b9998880bce4e4
174
cpp
C++
easy/69. Sqrt(x).cpp
xuan-415/leetcode
3777b12e6f574947506ec358108937f8be975289
[ "MIT" ]
null
null
null
easy/69. Sqrt(x).cpp
xuan-415/leetcode
3777b12e6f574947506ec358108937f8be975289
[ "MIT" ]
null
null
null
easy/69. Sqrt(x).cpp
xuan-415/leetcode
3777b12e6f574947506ec358108937f8be975289
[ "MIT" ]
null
null
null
#include<vector> #include<map> #include<string> #include<algorithm> using namespace std; class Solution { public: int mySqrt(int x) { return sqrt(x); } };
15.818182
27
0.643678
[ "vector" ]
535718207fcccad406fb806059c62a0e87a19196
412
cpp
C++
leetcode/monthly-challenge/2020/november-challenge/week-2/Flipping-an-Image.cpp
leohr/competitive-programming
f97488e0cb777c1df78257ce2644ac4ff8191267
[ "MIT" ]
1
2020-10-08T19:28:40.000Z
2020-10-08T19:28:40.000Z
leetcode/november-challenge/week-2/Flipping-an-Image.cpp
leohr/competitive-programming
f97488e0cb777c1df78257ce2644ac4ff8191267
[ "MIT" ]
null
null
null
leetcode/november-challenge/week-2/Flipping-an-Image.cpp
leohr/competitive-programming
f97488e0cb777c1df78257ce2644ac4ff8191267
[ "MIT" ]
1
2020-10-24T02:32:27.000Z
2020-10-24T02:32:27.000Z
class Solution { public: vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) { vector<vector<int>> B; for (int i = 0; i < A.size(); ++i) { vector<int> v = A[i]; vector<int> u; for (int j = 0; j < v.size(); ++j) { u.push_back(1-v[v.size()-1-j]); } B.push_back(u); } return B; } };
27.466667
68
0.419903
[ "vector" ]
53650146fe77801b06081c3c47884ae78030a4db
4,532
cpp
C++
src/khorne/Skullreapers.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
5
2019-02-01T01:41:19.000Z
2021-06-17T02:16:13.000Z
src/khorne/Skullreapers.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
2
2020-01-14T16:57:42.000Z
2021-04-01T00:53:18.000Z
src/khorne/Skullreapers.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
1
2019-03-02T20:03:51.000Z
2019-03-02T20:03:51.000Z
/* * Warhammer Age of Sigmar battle simulator. * * Copyright (C) 2019 by Rick Weyrauch - rpweyrauch@gmail.com * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include <khorne/Skullreapers.h> #include <UnitFactory.h> #include <Board.h> #include "KhornePrivate.h" namespace Khorne { static const int g_basesize = 40; static const int g_wounds = 3; static const int g_minUnitSize = 5; static const int g_maxUnitSize = 15; static const int g_pointsPerBlock = 205; static const int g_pointsMaxUnitSize = g_pointsPerBlock * 3; bool Skullreapers::s_registered = false; Skullreapers::Skullreapers(SlaughterHost host, int numModels, bool iconBearer, int points) : KhorneBase("Skullreapers", 5, g_wounds, 7, 4, false, points) { m_keywords = {CHAOS, MORTAL, KHORNE, BLOODBOUND, SKULLREAPERS}; m_weapons = {&m_blades, &m_viciousMutation}; setSlaughterHost(host); // TODO: make this buff dynamic if (iconBearer) { m_bravery += 1; } auto skullseeker = new Model(g_basesize, wounds()); skullseeker->addMeleeWeapon(&m_viciousMutation); skullseeker->addMeleeWeapon(&m_blades); addModel(skullseeker); int currentModelCount = (int) m_models.size(); for (auto i = currentModelCount; i < numModels; i++) { auto model = new Model(g_basesize, wounds()); model->addMeleeWeapon(&m_blades); if (iconBearer) { model->setName(Model::IconBearer); iconBearer = false; } addModel(model); } } Unit *Skullreapers::Create(const ParameterList &parameters) { int numModels = GetIntParam("Models", parameters, g_minUnitSize); bool iconBearer = GetBoolParam("Icon Bearer", parameters, true); auto host = (SlaughterHost) GetEnumParam("Slaughter Host", parameters, g_slaughterHost[0]); return new Skullreapers(host, numModels, iconBearer, ComputePoints(parameters)); } void Skullreapers::Init() { if (!s_registered) { static FactoryMethod factoryMethod = { Skullreapers::Create, KhorneBase::ValueToString, KhorneBase::EnumStringToInt, Skullreapers::ComputePoints, { IntegerParameter("Models", g_minUnitSize, g_minUnitSize, g_maxUnitSize, g_minUnitSize), BoolParameter("Icon Bearer"), EnumParameter("Slaughter Host", g_slaughterHost[0], g_slaughterHost) }, CHAOS, {KHORNE} }; s_registered = UnitFactory::Register("Skullreapers", factoryMethod); } } Rerolls Skullreapers::toHitRerolls(const Weapon *weapon, const Unit *target) const { // Trial of skulls. if (target->remainingModels() >= 5) { return Rerolls::Failed; } return KhorneBase::toHitRerolls(weapon, target); } Wounds Skullreapers::weaponDamage(const Model* attackingModel, const Weapon *weapon, const Unit *target, int hitRoll, int woundRoll) const { // Daemonforged Weapons if ((weapon->name() == m_blades.name()) && (hitRoll == 6)) { Wounds wounds = {weapon->damage(), 1, Wounds::Source::Weapon_Melee, weapon}; return wounds; } return KhorneBase::weaponDamage(attackingModel, weapon, target, hitRoll, woundRoll); } int Skullreapers::ComputePoints(const ParameterList& parameters) { int numModels = GetIntParam("Models", parameters, g_minUnitSize); auto points = numModels / g_minUnitSize * g_pointsPerBlock; if (numModels == g_maxUnitSize) { points = g_pointsMaxUnitSize; } return points; } void Skullreapers::onFriendlyModelSlain(int numSlain, Unit *attacker, Wounds::Source source) { KhorneBase::onFriendlyModelSlain(numSlain, attacker, source); // Murderous to the Last if (source == Wounds::Source::Weapon_Melee) { auto unit = Board::Instance()->getNearestUnit(this, GetEnemyId(owningPlayer())); if (unit && distanceTo(unit) <= 1.0) { if (Dice::RollD6() >= 5) { unit->applyDamage({0, Dice::RollD3()}, this); } } } } } //namespace Khorne
38.084034
144
0.603266
[ "model" ]
536ab0f5297b4dfdb5c921b92d20b88e15658d45
12,022
cpp
C++
texada-src/tests/simpleparser_test.cpp
emmableu/texada
b299e842b1334b4fe8b5d02f41fb5e3087bd96a3
[ "BSD-3-Clause" ]
13
2020-05-26T06:51:49.000Z
2022-03-21T02:55:46.000Z
texada-src/tests/simpleparser_test.cpp
emmableu/texada
b299e842b1334b4fe8b5d02f41fb5e3087bd96a3
[ "BSD-3-Clause" ]
3
2021-06-02T18:47:00.000Z
2022-03-09T16:29:53.000Z
texada-src/tests/simpleparser_test.cpp
emmableu/texada
b299e842b1334b4fe8b5d02f41fb5e3087bd96a3
[ "BSD-3-Clause" ]
6
2020-11-02T07:21:54.000Z
2022-03-16T11:17:06.000Z
#include <gtest/gtest.h> #include "../src/parsers/linearparser.h" #include "../src/parsers/mapparser.h" #include "../src/parsers/prefixtreeparser.h" #include <fstream> #include <iostream> #include <stdlib.h> // Tests that the linear parser correctly parses a small trace TEST(SimpleParserTest, SmallFile) { if (getenv("TEXADA_HOME") == NULL){ std::cerr << "Error: TEXADA_HOME is undefined. \n"; FAIL(); } std::ifstream infile( std::string(getenv("TEXADA_HOME")) + "/traces/vary-tracelen/smalltrace.txt"); texada::linear_parser * parser = new texada::linear_parser; parser->parse(infile); std::shared_ptr<std::multiset<std::vector<texada::event>>>trace_set = parser->return_vec_trace(); std::shared_ptr<std::set<std::string>> events = parser->return_props(); delete parser; parser = NULL; std::vector<texada::event> trace_vec = *trace_set->begin(); ASSERT_TRUE(trace_vec[0].is_satisfied("e1")); ASSERT_TRUE(trace_vec[1].is_satisfied("e2")); ASSERT_TRUE(trace_vec[2].is_satisfied("e3")); ASSERT_TRUE(trace_vec[3].is_satisfied("e2")); ASSERT_TRUE(trace_vec[4].is_terminal()); ASSERT_EQ(events->size(), 3); ASSERT_TRUE(events->find("e1") != events->end()); ASSERT_TRUE(events->find("e2") != events->end()); ASSERT_TRUE(events->find("e3") != events->end()); } // Test that the linear parser separates multiple traces as it should TEST(SimpleParserTest, MultipleTracesOneFile) { if (getenv("TEXADA_HOME") == NULL){ std::cerr << "Error: TEXADA_HOME is undefined. \n"; FAIL(); } std::ifstream infile( std::string(getenv("TEXADA_HOME")) + "/traces/vary-tracelen/etypes-10_events-250_execs-20.txt"); texada::linear_parser * parser = new texada::linear_parser; parser->parse(infile); std::shared_ptr<std::multiset<std::vector<texada::event>>>trace_set = parser->return_vec_trace(); delete parser; parser = NULL; ASSERT_EQ(trace_set->size(),20)<< "Unexpected number of traces parsed"; for (std::multiset<std::vector<texada::event> >::iterator it = trace_set->begin(); it != trace_set->end(); it++) { std::vector<texada::event> current_vector = *it; ASSERT_EQ(current_vector.size(), 251); } } // Checks that the map parser parses a small file properly TEST(SimpleParserTest, MapTraceSmallFile) { if (getenv("TEXADA_HOME") == NULL){ std::cerr << "Error: TEXADA_HOME is undefined. \n"; FAIL(); } std::ifstream infile( std::string(getenv("TEXADA_HOME")) + "/traces/vary-tracelen/smalltrace.txt"); texada::map_parser * parser = new texada::map_parser; parser->parse(infile); std::shared_ptr< std::set<std::map<texada::event, std::vector<long>>> >trace_set = parser->return_map_trace(); delete parser; parser = NULL; ASSERT_EQ(trace_set->size(), 1); std::map<texada::event, std::vector<long>> trace = *trace_set->begin(); ASSERT_EQ(trace.size(), 4); ASSERT_EQ(trace.at(texada::event("e1")).size(), 1); ASSERT_EQ(trace.at(texada::event("e2")).size(), 2); ASSERT_EQ(trace.at(texada::event("e3")).size(), 1); ASSERT_EQ(trace.at(texada::event()).size(), 1); } // checks that the map parser divides the traces properly, and // that they're the right length (by checking the position of the terminal event) TEST(SimpleParserTest, MapTraceLargeFile) { if (getenv("TEXADA_HOME") == NULL){ std::cerr << "Error: TEXADA_HOME is undefined. \n"; FAIL(); } std::ifstream infile( std::string(getenv("TEXADA_HOME")) + "/traces/vary-tracelen/etypes-10_events-250_execs-20.txt"); texada::map_parser * parser = new texada::map_parser; parser->parse(infile); std::shared_ptr< std::set<std::map<texada::event, std::vector<long>>> >trace_set = parser->return_map_trace(); delete parser; parser = NULL; ASSERT_EQ(trace_set->size(),20)<< "Unexpected number of traces parsed"; for (std::set<std::map<texada::event, std::vector<long>> >::iterator it = trace_set->begin(); it != trace_set->end(); it++) { std::vector<long> end_vector = it->at(texada::event()); ASSERT_EQ(end_vector[0], 250); } } TEST(SimpleParserTest, PreTreeTrace) { if (getenv("TEXADA_HOME") == NULL){ std::cerr << "Error: TEXADA_HOME is undefined. \n"; FAIL(); } std::ifstream infile( std::string(getenv("TEXADA_HOME")) + "/traces/parsing-tests/simple-pre-tree.txt"); texada::prefix_tree_parser parser; parser.parse(infile); std::shared_ptr<texada::prefix_tree> trace_set = parser.return_prefix_trees(); ASSERT_TRUE(trace_set->get_trace_start(texada::event("a")) != NULL); ASSERT_TRUE(trace_set->get_trace_start(texada::event("a"))->get_child(texada::event("b")) != NULL); //trace1 ASSERT_TRUE(trace_set->get_trace_start(1)->is_satisfied("a")); ASSERT_TRUE(trace_set->get_trace_start(1)->get_child(1)->is_satisfied("b")); ASSERT_TRUE(trace_set->get_trace_start(1)->get_child(1)->get_child(1)->is_satisfied("c")); ASSERT_TRUE(trace_set->get_trace_start(1)->get_child(1)->get_child(1)->get_child( 1)->is_satisfied("d")); //trace 2 ASSERT_TRUE(trace_set->get_trace_start(2)->is_satisfied("a")); ASSERT_TRUE(trace_set->get_trace_start(2)->get_child(2)->is_satisfied("b")); ASSERT_TRUE(trace_set->get_trace_start(2)->get_child(2)->get_child(2)->is_satisfied("d")); ASSERT_TRUE(trace_set->get_trace_start(2)->get_child(2)->get_child(2)->get_child( 2)->is_satisfied("e")); //trace 3 ASSERT_TRUE(trace_set->get_trace_start(3)->is_satisfied("a")); ASSERT_TRUE(trace_set->get_trace_start(3)->get_child(3)->is_satisfied("c")); ASSERT_TRUE(trace_set->get_trace_start(3)->get_child(3)->get_child(3)->is_satisfied("e")); ASSERT_TRUE(trace_set->get_trace_start(3)->get_child(3)->get_child(3)->get_child( 3)->is_satisfied("e")); ASSERT_TRUE(trace_set->get_trace_start(3)->get_child(3)->get_child(3)->get_child( 3)->get_child(3)->is_satisfied("f")); //trace 4 ASSERT_TRUE(trace_set->get_trace_start(4)->is_satisfied("a")); ASSERT_TRUE(trace_set->get_trace_start(4)->get_child(4)->is_satisfied("c")); ASSERT_TRUE(trace_set->get_trace_start(4)->get_child(4)->get_child(4)->is_satisfied("e")); ASSERT_TRUE(trace_set->get_trace_start(4)->get_child(4)->get_child(4)->get_child( 4)->is_satisfied("d")); ASSERT_TRUE(trace_set->get_trace_start(4)->get_child(4)->get_child(4)->get_child( 4)->get_child(4)->is_satisfied("EndOfTraceVar")); } // Checks that the parser can be configured for custom separator line TEST(SimpleParserTest, CustomSeparator) { if (getenv("TEXADA_HOME") == NULL){ std::cerr << "Error: TEXADA_HOME is undefined. \n"; FAIL(); } std::ifstream infile( std::string(getenv("TEXADA_HOME")) + "/traces/regex-parsing-tests/custom-separator.txt"); texada::linear_parser * parser = new texada::linear_parser; parser->set_trace_separator("break"); parser->parse(infile); std::shared_ptr<std::multiset<std::vector<texada::event>>>trace_set = parser->return_vec_trace(); delete parser; parser = NULL; ASSERT_EQ(trace_set->size(),20)<< "Unexpected number of traces parsed"; for (std::multiset<std::vector<texada::event> >::iterator it = trace_set->begin(); it != trace_set->end(); it++) { std::vector<texada::event> current_vector = *it; ASSERT_EQ(current_vector.size(), 251); } } // Checks that the parser can be configured to recognize event types using the regex option TEST(SimpleParserTest, RegexOption) { if (getenv("TEXADA_HOME") == NULL){ std::cerr << "Error: TEXADA_HOME is undefined. \n"; FAIL(); } std::ifstream infile( std::string(getenv("TEXADA_HOME")) + "/traces/regex-parsing-tests/small-structured-trace.txt"); texada::linear_parser * parser = new texada::linear_parser; std::vector<std::string> etypes; etypes.push_back("(?<USER>.*)(?<ETYPE>e[0-9])"); parser->set_prop_types(etypes); parser->parse(infile); std::shared_ptr<std::multiset<std::vector<texada::event>>>trace_set = parser->return_vec_trace(); std::shared_ptr<std::set<std::string>> events = parser->return_props(); delete parser; parser = NULL; std::vector<texada::event> trace_vec = *trace_set->begin(); ASSERT_TRUE(trace_vec[0].is_satisfied("e1")); ASSERT_TRUE(trace_vec[1].is_satisfied("e2")); ASSERT_TRUE(trace_vec[2].is_satisfied("e3")); ASSERT_TRUE(trace_vec[3].is_satisfied("e2")); ASSERT_TRUE(trace_vec[4].is_terminal()); ASSERT_EQ(events->size(), 3); ASSERT_TRUE(events->find("e1") != events->end()); ASSERT_TRUE(events->find("e2") != events->end()); ASSERT_TRUE(events->find("e3") != events->end()); } // Checks that the parser can be configured using multiple regular expressions TEST(SimpleParserTest, MultipleRegexOptions) { if (getenv("TEXADA_HOME") == NULL){ std::cerr << "Error: TEXADA_HOME is undefined. \n"; FAIL(); } std::ifstream infile( std::string(getenv("TEXADA_HOME")) + "/traces/regex-parsing-tests/small-structured-trace2.txt"); texada::linear_parser * parser = new texada::linear_parser; std::vector<std::string> etypes; etypes.push_back("--> (?<ETYPE>e[0-9])"); etypes.push_back("<-- (?<ETYPE>e[0-9])"); parser->set_prop_types(etypes); parser->parse(infile); std::shared_ptr<std::multiset<std::vector<texada::event>>>trace_set = parser->return_vec_trace(); std::shared_ptr<std::set<std::string>> events = parser->return_props(); delete parser; parser = NULL; std::vector<texada::event> trace_vec = *trace_set->begin(); ASSERT_TRUE(trace_vec[0].is_satisfied("e1")); ASSERT_TRUE(trace_vec[1].is_satisfied("e2")); ASSERT_TRUE(trace_vec[2].is_satisfied("e3")); ASSERT_TRUE(trace_vec[3].is_satisfied("e2")); ASSERT_TRUE(trace_vec[4].is_terminal()); ASSERT_EQ(events->size(), 3); ASSERT_TRUE(events->find("e1") != events->end()); ASSERT_TRUE(events->find("e2") != events->end()); ASSERT_TRUE(events->find("e3") != events->end()); } // Checks that the parser can be configured to ignore non matching lines TEST(SimpleParserTest, IgnoreNMLines) { if (getenv("TEXADA_HOME") == NULL){ std::cerr << "Error: TEXADA_HOME is undefined. \n"; FAIL(); } std::ifstream infile( std::string(getenv("TEXADA_HOME")) + "/traces/regex-parsing-tests/ignore-nm-lines-trace.txt"); texada::linear_parser * parser = new texada::linear_parser; parser->ignore_nm_lines(); std::vector<std::string> etypes; etypes.push_back("--> (?<ETYPE>e[0-9])"); parser->set_prop_types(etypes); parser->parse(infile); std::shared_ptr<std::multiset<std::vector<texada::event>>>trace_set = parser->return_vec_trace(); std::shared_ptr<std::set<std::string>> events = parser->return_props(); delete parser; parser = NULL; std::vector<texada::event> trace_vec = *trace_set->begin(); ASSERT_TRUE(trace_vec[0].is_satisfied("e1")); ASSERT_TRUE(trace_vec[1].is_satisfied("e2")); ASSERT_TRUE(trace_vec[2].is_satisfied("e3")); ASSERT_TRUE(trace_vec[3].is_satisfied("e2")); ASSERT_TRUE(trace_vec[4].is_terminal()); ASSERT_EQ(events->size(), 3); ASSERT_TRUE(events->find("e1") != events->end()); ASSERT_TRUE(events->find("e2") != events->end()); ASSERT_TRUE(events->find("e3") != events->end()); }
38.408946
103
0.639744
[ "vector" ]
537a55a2bba7872545c9733f6c33bf4d52c200a6
23,837
cpp
C++
SofaKernel/modules/SofaBaseTopology/QuadSetTopologyContainer.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
SofaKernel/modules/SofaBaseTopology/QuadSetTopologyContainer.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
SofaKernel/modules/SofaBaseTopology/QuadSetTopologyContainer.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include <SofaBaseTopology/QuadSetTopologyContainer.h> #include <sofa/core/visual/VisualParams.h> #include <sofa/core/ObjectFactory.h> namespace sofa { namespace component { namespace topology { using namespace std; using namespace sofa::defaulttype; SOFA_DECL_CLASS(QuadSetTopologyContainer) int QuadSetTopologyContainerClass = core::RegisterObject("Quad set topology container") .add< QuadSetTopologyContainer >() ; QuadSetTopologyContainer::QuadSetTopologyContainer() : EdgeSetTopologyContainer() , d_quad(initData(&d_quad, "quads", "List of quad indices")) { } void QuadSetTopologyContainer::addQuad( int a, int b, int c, int d ) { helper::WriteAccessor< Data< sofa::helper::vector<Quad> > > m_quad = d_quad; m_quad.push_back(Quad(a,b,c,d)); if (a >= getNbPoints()) setNbPoints( a+1 ); if (b >= getNbPoints()) setNbPoints( b+1 ); if (c >= getNbPoints()) setNbPoints( c+1 ); if (d >= getNbPoints()) setNbPoints( d+1 ); } void QuadSetTopologyContainer::init() { EdgeSetTopologyContainer::init(); d_quad.updateIfDirty(); // make sure m_quad is up to date } void QuadSetTopologyContainer::createQuadSetArray() { #ifndef NDEBUG sout << "Error. [QuadSetTopologyContainer::createQuadSetArray] This method must be implemented by a child topology." << sendl; #endif } void QuadSetTopologyContainer::createQuadsAroundVertexArray() { if(!hasQuads()) // this method should only be called when quads exist { #ifndef NDEBUG sout << "Warning. [QuadSetTopologyContainer::createQuadsAroundVertexArray] quad array is empty." << sendl; #endif createQuadSetArray(); } if(hasQuadsAroundVertex()) { clearQuadsAroundVertex(); } m_quadsAroundVertex.resize( getNbPoints() ); helper::ReadAccessor< Data< sofa::helper::vector<Quad> > > m_quad = d_quad; for (size_t i=0; i<m_quad.size(); ++i) { // adding quad i in the quad shell of all points for (size_t j=0; j<4; ++j) { m_quadsAroundVertex[ m_quad[i][j] ].push_back((unsigned int)i); } } } void QuadSetTopologyContainer::createQuadsAroundEdgeArray() { if(!hasQuads()) // this method should only be called when quads exist { #ifndef NDEBUG sout << "Warning. [QuadSetTopologyContainer::createQuadsAroundEdgeArray] quad array is empty." << sendl; #endif createQuadSetArray(); } if(!hasEdges()) // this method should only be called when edges exist { #ifndef NDEBUG sout << "Warning. [QuadSetTopologyContainer::createQuadsAroundEdgeArray] edge array is empty." << sendl; #endif createEdgeSetArray(); } if(!hasEdgesInQuad()) createEdgesInQuadArray(); const size_t numQuads = getNumberOfQuads(); const size_t numEdges = getNumberOfEdges(); if(hasQuadsAroundEdge()) { clearQuadsAroundEdge(); } m_quadsAroundEdge.resize(numEdges); for (size_t i=0; i<numQuads; ++i) { // adding quad i in the quad shell of all edges for (size_t j=0; j<4; ++j) { m_quadsAroundEdge[ m_edgesInQuad[i][j] ].push_back((unsigned int)i); } } } void QuadSetTopologyContainer::createEdgeSetArray() { if(!hasQuads()) // this method should only be called when quads exist { #ifndef NDEBUG sout << "Warning. [QuadSetTopologyContainer::createEdgeSetArray] quad array is empty." << sendl; #endif createQuadSetArray(); } if(hasEdges()) { #ifndef NDEBUG sout << "Warning. [QuadSetTopologyContainer::createEdgeSetArray] edge array is not empty." << sendl; #endif // clear edges and all shells that depend on edges EdgeSetTopologyContainer::clear(); if(hasEdgesInQuad()) clearEdgesInQuad(); if(hasQuadsAroundEdge()) clearQuadsAroundEdge(); } // create a temporary map to find redundant edges std::map<Edge, unsigned int> edgeMap; helper::WriteAccessor< Data< sofa::helper::vector<Edge> > > m_edge = d_edge; helper::ReadAccessor< Data< sofa::helper::vector<Quad> > > m_quad = d_quad; for (size_t i=0; i<m_quad.size(); ++i) { const Quad &t = m_quad[i]; for(size_t j=0; j<4; ++j) { const unsigned int v1 = t[(j+1)%4]; const unsigned int v2 = t[(j+2)%4]; // sort vertices in lexicographic order const Edge e = ((v1<v2) ? Edge(v1,v2) : Edge(v2,v1)); if(edgeMap.find(e) == edgeMap.end()) { // edge not in edgeMap so create a new one const unsigned int edgeIndex = (unsigned int)edgeMap.size(); edgeMap[e] = edgeIndex; m_edge.push_back(e); } } } } void QuadSetTopologyContainer::createEdgesInQuadArray() { if(!hasQuads()) // this method should only be called when quads exist { #ifndef NDEBUG sout << "Warning. [QuadSetTopologyContainer::createEdgesInQuadArray] quad array is empty." << sendl; #endif createQuadSetArray(); } if(!hasEdges()) // this method should only be called when edges exist { #ifndef NDEBUG sout << "Warning. [QuadSetTopologyContainer::createEdgesInQuadArray] edge array is empty." << sendl; #endif createEdgeSetArray(); } if(hasEdgesInQuad()) clearEdgesInQuad(); const size_t numQuads = getNumberOfQuads(); m_edgesInQuad.resize( numQuads ); helper::ReadAccessor< Data< sofa::helper::vector<Quad> > > m_quad = d_quad; for(size_t i=0; i<numQuads; ++i) { const Quad &t = m_quad[i]; // adding edge i in the edge shell of both points for (size_t j=0; j<4; ++j) { const int edgeIndex = getEdgeIndex(t[(j+1)%4],t[(j+2)%4]); m_edgesInQuad[i][j]=edgeIndex; } } } const sofa::helper::vector<QuadSetTopologyContainer::Quad> &QuadSetTopologyContainer::getQuadArray() { if(!hasQuads() && getNbPoints()>0) { #ifndef NDEBUG sout << "Warning. [QuadSetTopologyContainer::getQuadArray] creating quad array." << sendl; #endif createQuadSetArray(); } return d_quad.getValue(); } const QuadSetTopologyContainer::Quad QuadSetTopologyContainer::getQuad (QuadID i) { if(!hasQuads()) createQuadSetArray(); return (d_quad.getValue())[i]; } int QuadSetTopologyContainer::getQuadIndex(PointID v1, PointID v2, PointID v3, PointID v4) { if(!hasQuadsAroundVertex()) createQuadsAroundVertexArray(); sofa::helper::vector<unsigned int> set1 = getQuadsAroundVertex(v1); sofa::helper::vector<unsigned int> set2 = getQuadsAroundVertex(v2); sofa::helper::vector<unsigned int> set3 = getQuadsAroundVertex(v3); sofa::helper::vector<unsigned int> set4 = getQuadsAroundVertex(v4); sort(set1.begin(), set1.end()); sort(set2.begin(), set2.end()); sort(set3.begin(), set3.end()); sort(set4.begin(), set4.end()); // The destination vector must be large enough to contain the result. sofa::helper::vector<unsigned int> out1(set1.size()+set2.size()); sofa::helper::vector<unsigned int>::iterator result1; result1 = std::set_intersection(set1.begin(),set1.end(),set2.begin(),set2.end(),out1.begin()); out1.erase(result1,out1.end()); sofa::helper::vector<unsigned int> out2(set3.size()+out1.size()); sofa::helper::vector<unsigned int>::iterator result2; result2 = std::set_intersection(set3.begin(),set3.end(),out1.begin(),out1.end(),out2.begin()); out2.erase(result2,out2.end()); sofa::helper::vector<unsigned int> out3(set4.size()+out2.size()); sofa::helper::vector<unsigned int>::iterator result3; result3 = std::set_intersection(set4.begin(),set4.end(),out2.begin(),out2.end(),out3.begin()); out3.erase(result3,out3.end()); #ifndef NDEBUG if(out3.size() > 1) sout << "Warning. [QuadSetTopologyContainer::getQuadIndex] more than one quad found" << sendl; #endif if(out3.size()==1) return (int) (out3[0]); else return -1; } unsigned int QuadSetTopologyContainer::getNumberOfQuads() const { helper::ReadAccessor< Data< sofa::helper::vector<Quad> > > m_quad = d_quad; return (unsigned int)m_quad.size(); } unsigned int QuadSetTopologyContainer::getNumberOfElements() const { return this->getNumberOfQuads(); } const sofa::helper::vector< sofa::helper::vector<unsigned int> > &QuadSetTopologyContainer::getQuadsAroundVertexArray() { if(!hasQuadsAroundVertex()) // this method should only be called when the shell array exists { #ifndef NDEBUG sout << "Warning. [QuadSetTopologyContainer::getQuadsAroundVertexArray] quad vertex shell array is empty." << sendl; #endif createQuadsAroundVertexArray(); } return m_quadsAroundVertex; } const sofa::helper::vector< sofa::helper::vector<unsigned int> > &QuadSetTopologyContainer::getQuadsAroundEdgeArray() { if(!hasQuadsAroundEdge()) // this method should only be called when the shell array exists { #ifndef NDEBUG sout << "Warning. [QuadSetTopologyContainer::getQuadsAroundEdgeArray] quad edge shell array is empty." << sendl; #endif createQuadsAroundEdgeArray(); } return m_quadsAroundEdge; } const sofa::helper::vector< QuadSetTopologyContainer::EdgesInQuad> &QuadSetTopologyContainer::getEdgesInQuadArray() { if(m_edgesInQuad.empty()) createEdgesInQuadArray(); return m_edgesInQuad; } const QuadSetTopologyContainer::QuadsAroundVertex& QuadSetTopologyContainer::getQuadsAroundVertex(PointID i) { if(!hasQuadsAroundVertex()) // this method should only be called when the shell array exists { #ifndef NDEBUG sout << "Warning. [QuadSetTopologyContainer::getQuadsAroundVertex] quad vertex shell array is empty." << sendl; #endif createQuadsAroundVertexArray(); } else if( i >= m_quadsAroundVertex.size()) { #ifndef NDEBUG sout << "Error. [QuadSetTopologyContainer::getQuadsAroundVertex] index out of bounds." << sendl; #endif createQuadsAroundVertexArray(); } return m_quadsAroundVertex[i]; } const QuadSetTopologyContainer::QuadsAroundEdge& QuadSetTopologyContainer::getQuadsAroundEdge(EdgeID i) { if(!hasQuadsAroundEdge()) // this method should only be called when the shell array exists { #ifndef NDEBUG sout << "Warning. [QuadSetTopologyContainer::getQuadsAroundEdge] quad edge shell array is empty." << sendl; #endif createQuadsAroundEdgeArray(); } else if( i >= m_quadsAroundEdge.size()) { #ifndef NDEBUG sout << "Error. [QuadSetTopologyContainer::getQuadsAroundEdge] index out of bounds." << sendl; #endif createQuadsAroundEdgeArray(); } return m_quadsAroundEdge[i]; } const QuadSetTopologyContainer::EdgesInQuad &QuadSetTopologyContainer::getEdgesInQuad(const unsigned int i) { if(m_edgesInQuad.empty()) createEdgesInQuadArray(); if( i >= m_edgesInQuad.size()) { #ifndef NDEBUG sout << "Error. [QuadSetTopologyContainer::getEdgesInQuad] index out of bounds." << sendl; #endif createEdgesInQuadArray(); } return m_edgesInQuad[i]; } int QuadSetTopologyContainer::getVertexIndexInQuad(const Quad &t, unsigned int vertexIndex) const { if(t[0]==vertexIndex) return 0; else if(t[1]==vertexIndex) return 1; else if(t[2]==vertexIndex) return 2; else if(t[3]==vertexIndex) return 3; else return -1; } int QuadSetTopologyContainer::getEdgeIndexInQuad(const EdgesInQuad &t, unsigned int edgeIndex) const { if(t[0]==edgeIndex) return 0; else if(t[1]==edgeIndex) return 1; else if(t[2]==edgeIndex) return 2; else if(t[3]==edgeIndex) return 3; else return -1; } sofa::helper::vector< unsigned int > &QuadSetTopologyContainer::getQuadsAroundEdgeForModification(const unsigned int i) { if(!hasQuadsAroundEdge()) // this method should only be called when the shell array exists { #ifndef NDEBUG sout << "Warning. [QuadSetTopologyContainer::getQuadsAroundEdgeForModification] quad edge shell array is empty." << sendl; #endif createQuadsAroundEdgeArray(); } if( i >= m_quadsAroundEdge.size()) { #ifndef NDEBUG sout << "Error. [QuadSetTopologyContainer::getQuadsAroundEdgeForModification] index out of bounds." << sendl; #endif createQuadsAroundEdgeArray(); } return m_quadsAroundEdge[i]; } sofa::helper::vector< unsigned int > &QuadSetTopologyContainer::getQuadsAroundVertexForModification(const unsigned int i) { if(!hasQuadsAroundVertex()) // this method should only be called when the shell array exists { #ifndef NDEBUG sout << "Warning. [QuadSetTopologyContainer::getQuadsAroundVertexForModification] quad vertex shell array is empty." << sendl; #endif createQuadsAroundVertexArray(); } if( i >= m_quadsAroundVertex.size()) { #ifndef NDEBUG sout << "Error. [QuadSetTopologyContainer::getQuadsAroundVertexForModification] index out of bounds." << sendl; #endif createQuadsAroundVertexArray(); } return m_quadsAroundVertex[i]; } bool QuadSetTopologyContainer::checkTopology() const { #ifndef NDEBUG bool ret = true; helper::ReadAccessor< Data< sofa::helper::vector<Quad> > > m_quad = d_quad; if(hasQuadsAroundVertex()) { for (size_t i=0; i<m_quadsAroundVertex.size(); ++i) { const sofa::helper::vector<unsigned int> &tvs = m_quadsAroundVertex[i]; for (size_t j=0; j<tvs.size(); ++j) { if((m_quad[tvs[j]][0]!=i) && (m_quad[tvs[j]][1]!=i) && (m_quad[tvs[j]][2]!=i) && (m_quad[tvs[j]][3]!=i)) { ret = false; std::cout << "*** CHECK FAILED : check_quad_vertex_shell, i = " << i << " , j = " << j << std::endl; } } } } if(hasQuadsAroundEdge()) { for (size_t i=0; i<m_quadsAroundEdge.size(); ++i) { const sofa::helper::vector<unsigned int> &tes = m_quadsAroundEdge[i]; for (size_t j=0; j<tes.size(); ++j) { if((m_edgesInQuad[tes[j]][0]!=i) && (m_edgesInQuad[tes[j]][1]!=i) && (m_edgesInQuad[tes[j]][2]!=i) && (m_edgesInQuad[tes[j]][3]!=i)) { ret = false; std::cout << "*** CHECK FAILED : check_quad_edge_shell, i = " << i << " , j = " << j << std::endl; } } } } return ret && EdgeSetTopologyContainer::checkTopology(); #else return true; #endif } /// Get information about connexity of the mesh /// @{ bool QuadSetTopologyContainer::checkConnexity() { size_t nbr = this->getNbQuads(); if (nbr == 0) { #ifndef NDEBUG serr << "Warning. [QuadSetTopologyContainer::checkConnexity] Can't compute connexity as there are no Quads" << sendl; #endif return false; } VecQuadID elemAll = this->getConnectedElement(0); if (elemAll.size() != nbr) { serr << "Warning: in computing connexity, Quads are missings. There is more than one connexe component." << sendl; return false; } return true; } unsigned int QuadSetTopologyContainer::getNumberOfConnectedComponent() { size_t nbr = this->getNbQuads(); if (nbr == 0) { #ifndef NDEBUG serr << "Warning. [QuadSetTopologyContainer::getNumberOfConnectedComponent] Can't compute connexity as there are no Quads" << sendl; #endif return 0; } VecQuadID elemAll = this->getConnectedElement(0); unsigned int cpt = 1; while (elemAll.size() < nbr) { std::sort(elemAll.begin(), elemAll.end()); QuadID other_QuadID = (QuadID)elemAll.size(); for (QuadID i = 0; i<elemAll.size(); ++i) if (elemAll[i] != i) { other_QuadID = i; break; } VecQuadID elemTmp = this->getConnectedElement(other_QuadID); cpt++; elemAll.insert(elemAll.begin(), elemTmp.begin(), elemTmp.end()); } return cpt; } const QuadSetTopologyContainer::VecQuadID QuadSetTopologyContainer::getConnectedElement(QuadID elem) { if(!hasQuadsAroundVertex()) // this method should only be called when the shell array exists { #ifndef NDEBUG serr << "Warning. [QuadSetTopologyContainer::getConnectedElement] Quad vertex shell array is empty." << sendl; #endif createQuadsAroundVertexArray(); } VecQuadID elemAll; VecQuadID elemOnFront, elemPreviousFront, elemNextFront; bool end = false; size_t cpt = 0; size_t nbr = this->getNbQuads(); // init algo elemAll.push_back(elem); elemOnFront.push_back(elem); elemPreviousFront.clear(); cpt++; while (!end && cpt < nbr) { // First Step - Create new region elemNextFront = this->getElementAroundElements(elemOnFront); // for each QuadID on the propagation front // Second Step - Avoid backward direction for (size_t i = 0; i<elemNextFront.size(); ++i) { bool find = false; QuadID id = elemNextFront[i]; for (size_t j = 0; j<elemAll.size(); ++j) if (id == elemAll[j]) { find = true; break; } if (!find) { elemAll.push_back(id); elemPreviousFront.push_back(id); } } // cpt for connexity cpt +=elemPreviousFront.size(); if (elemPreviousFront.empty()) { end = true; #ifndef NDEBUG serr << "Loop for computing connexity has reach end." << sendl; #endif } // iterate elemOnFront = elemPreviousFront; elemPreviousFront.clear(); } return elemAll; } const QuadSetTopologyContainer::VecQuadID QuadSetTopologyContainer::getElementAroundElement(QuadID elem) { VecQuadID elems; if (!hasQuadsAroundVertex()) { #ifndef NDEBUG serr << "Warning. [QuadSetTopologyContainer::getElementAroundElement] Quad vertex shell array is empty." << sendl; #endif createQuadsAroundVertexArray(); } Quad the_quad = this->getQuad(elem); for(size_t i = 0; i<4; ++i) // for each node of the Quad { QuadsAroundVertex quadAV = this->getQuadsAroundVertex(the_quad[i]); for (size_t j = 0; j<quadAV.size(); ++j) // for each Quad around the node { bool find = false; QuadID id = quadAV[j]; if (id == elem) continue; for (size_t k = 0; k<elems.size(); ++k) // check no redundancy if (id == elems[k]) { find = true; break; } if (!find) elems.push_back(id); } } return elems; } const QuadSetTopologyContainer::VecQuadID QuadSetTopologyContainer::getElementAroundElements(VecQuadID elems) { VecQuadID elemAll; VecQuadID elemTmp; if (!hasQuadsAroundVertex()) { #ifndef NDEBUG serr << "Warning. [QuadSetTopologyContainer::getElementAroundElements] Quad vertex shell array is empty." << sendl; #endif createQuadsAroundVertexArray(); } for (size_t i = 0; i <elems.size(); ++i) // for each QuadId of input vector { VecQuadID elemTmp2 = this->getElementAroundElement(elems[i]); elemTmp.insert(elemTmp.end(), elemTmp2.begin(), elemTmp2.end()); } for (size_t i = 0; i<elemTmp.size(); ++i) // for each Quad Id found { bool find = false; QuadID id = elemTmp[i]; for (size_t j = 0; j<elems.size(); ++j) // check no redundancy with input vector if (id == elems[j]) { find = true; break; } if (!find) { for (size_t j = 0; j<elemAll.size(); ++j) // check no redundancy in output vector if (id == elemAll[j]) { find = true; break; } } if (!find) elemAll.push_back(id); } return elemAll; } /// @} bool QuadSetTopologyContainer::hasQuads() const { d_quad.updateIfDirty(); return !(d_quad.getValue()).empty(); } bool QuadSetTopologyContainer::hasEdgesInQuad() const { return !m_edgesInQuad.empty(); } bool QuadSetTopologyContainer::hasQuadsAroundVertex() const { return !m_quadsAroundVertex.empty(); } bool QuadSetTopologyContainer::hasQuadsAroundEdge() const { return !m_quadsAroundEdge.empty(); } void QuadSetTopologyContainer::clearQuadsAroundVertex() { for(size_t i=0; i<m_quadsAroundVertex.size(); ++i) m_quadsAroundVertex[i].clear(); m_quadsAroundVertex.clear(); } void QuadSetTopologyContainer::clearQuadsAroundEdge() { for(size_t i=0; i<m_quadsAroundEdge.size(); ++i) m_quadsAroundEdge[i].clear(); m_quadsAroundEdge.clear(); } void QuadSetTopologyContainer::clearEdgesInQuad() { m_edgesInQuad.clear(); } void QuadSetTopologyContainer::clearQuads() { helper::WriteAccessor< Data< sofa::helper::vector<Quad> > > m_quad = d_quad; m_quad.clear(); } void QuadSetTopologyContainer::clear() { clearQuadsAroundVertex(); clearQuadsAroundEdge(); clearEdgesInQuad(); clearQuads(); EdgeSetTopologyContainer::clear(); } void QuadSetTopologyContainer::updateTopologyEngineGraph() { // calling real update Data graph function implemented once in PointSetTopologyModifier this->updateDataEngineGraph(this->d_quad, this->m_enginesList); // will concatenate with edges one: EdgeSetTopologyContainer::updateTopologyEngineGraph(); } } // namespace topology } // namespace component } // namespace sofa
28.823458
140
0.613584
[ "mesh", "vector" ]
53817f2cbcfdf68db79f87354ca04fda8ea5c7ae
7,765
cpp
C++
src/+cv/private/Boost_.cpp
schloegl/mexopencv
b7a34df8f844ceb5bebb93f439eb35135e9c074d
[ "BSD-3-Clause" ]
87
2016-10-28T18:36:43.000Z
2022-02-03T08:34:45.000Z
src/+cv/private/Boost_.cpp
schloegl/mexopencv
b7a34df8f844ceb5bebb93f439eb35135e9c074d
[ "BSD-3-Clause" ]
17
2016-11-06T10:36:35.000Z
2021-07-15T11:37:14.000Z
src/+cv/private/Boost_.cpp
schloegl/mexopencv
b7a34df8f844ceb5bebb93f439eb35135e9c074d
[ "BSD-3-Clause" ]
23
2016-10-30T11:48:55.000Z
2021-03-22T10:33:27.000Z
/** * @file Boost_.cpp * @brief mex interface for Boost * @author Kota Yamaguchi * @date 2012 */ #include "mexopencv.hpp" using namespace std; using namespace cv; // Persistent objects namespace { /// Last object id to allocate int last_id = 0; /// Object container map<int,CvBoost> obj_; /// Option values for Boost types const ConstMap<std::string,int> BoostType = ConstMap<std::string,int> ("Discrete", CvBoost::DISCRETE) ("Real", CvBoost::REAL) ("Logit", CvBoost::LOGIT) ("Gentle", CvBoost::GENTLE); /// Option values for Inverse boost types const ConstMap<int,std::string> InvBoostType = ConstMap<int,std::string> (CvBoost::DISCRETE, "Discrete") (CvBoost::REAL, "Real") (CvBoost::LOGIT, "Logit") (CvBoost::GENTLE, "Gentle"); /** Obtain CvBoostParams object from input arguments * @param it iterator at the beginning of the argument vector * @param end iterator at the end of the argument vector * @return CvBoostParams objects */ CvBoostParams getParams(vector<MxArray>::iterator it, vector<MxArray>::iterator end) { CvBoostParams params; for (;it<end;it+=2) { string key((*it).toString()); MxArray& val = *(it+1); if (key=="BoostType") params.boost_type = BoostType[val.toString()]; else if (key=="WeakCount") params.weak_count = val.toInt(); else if (key=="WeightTrimRate") params.weight_trim_rate = val.toDouble(); else if (key=="MaxDepth") params.max_depth = val.toInt(); else if (key=="UseSurrogates") params.use_surrogates = val.toBool(); //else // mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option"); } return params; } /** Create a new mxArray* from CvBoostParams * @param params CvBoostParams object * @return MxArray objects */ MxArray paramsToMxArray(const CvBoostParams& params) { const char* fields[] = {"BoostType", "WeakCount", "WeightTrimRate", "MaxDepth", "UseSurrogates", "MaxCategories", "MinSampleCount", "CVFolds", "Use1seRule", "TruncatePrunedTree", "RegressionAccuracy"}; MxArray m(fields,11); m.set("BoostType",InvBoostType[params.boost_type]); m.set("WeakCount",params.weak_count); m.set("WeightTrimRate",params.weight_trim_rate); m.set("MaxDepth",params.max_depth); m.set("UseSurrogates",params.use_surrogates); m.set("MaxCategories",params.max_categories); m.set("MinSampleCount",params.min_sample_count); m.set("CVFolds",params.cv_folds); m.set("Use1seRule",params.use_1se_rule); m.set("TruncatePrunedTree",params.truncate_pruned_tree); m.set("RegressionAccuracy",params.regression_accuracy); return m; } } /** * Main entry called from Matlab * @param nlhs number of left-hand-side arguments * @param plhs pointers to mxArrays in the left-hand-side * @param nrhs number of right-hand-side arguments * @param prhs pointers to mxArrays in the right-hand-side */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { if (nlhs>1) mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments"); // Determine argument format between constructor or (id,method,...) vector<MxArray> rhs(prhs,prhs+nrhs); int id = 0; string method; if (nrhs==0) { // Constructor is called. Create a new object from argument obj_[++last_id] = CvBoost(); plhs[0] = MxArray(last_id); return; } else if (rhs[0].isNumeric() && rhs[0].numel()==1 && nrhs>1) { id = rhs[0].toInt(); method = rhs[1].toString(); } else mexErrMsgIdAndTxt("mexopencv:error","Invalid arguments"); // Big operation switch CvBoost& obj = obj_[id]; if (method == "delete") { if (nrhs!=2 || nlhs!=0) mexErrMsgIdAndTxt("mexopencv:error","Output not assigned"); obj_.erase(id); } else if (method == "clear") { if (nrhs!=2 || nlhs!=0) mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments"); obj.clear(); } else if (method == "load") { if (nrhs!=3 || nlhs!=0) mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments"); obj.load(rhs[2].toString().c_str()); } else if (method == "save") { if (nrhs!=3 || nlhs!=0) mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments"); obj.save(rhs[2].toString().c_str()); } else if (method == "train") { if (nrhs<4 || nlhs>1) mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments"); Mat trainData(rhs[2].toMat(CV_32F)); Mat responses(rhs[3].toMat(CV_32F)); Mat varIdx, sampleIdx, missingMask; Mat varType(1,trainData.cols+1,CV_8U,Scalar(CV_VAR_ORDERED)); varType.at<uchar>(0,trainData.cols) = CV_VAR_CATEGORICAL; CvBoostParams params = getParams(rhs.begin()+4,rhs.end()); vector<float> priors; bool update=false; for (int i=4; i<nrhs; i+=2) { string key(rhs[i].toString()); if (key=="VarIdx") varIdx = rhs[i+1].toMat(CV_32S); else if (key=="SampleIdx") sampleIdx = rhs[i+1].toMat(CV_32S); else if (key=="VarType") { if (rhs[i+1].isChar()) varType.at<uchar>(0,trainData.cols) = (rhs[i+1].toString()=="Categorical") ? CV_VAR_CATEGORICAL : CV_VAR_ORDERED; else if (rhs[i+1].isNumeric()) varType = rhs[i+1].toMat(CV_8U); } else if (key=="MissingMask") missingMask = rhs[i+1].toMat(CV_8U); else if (key=="Priors") { MxArray& m = rhs[i+1]; priors.reserve(m.numel()); for (int j=0; j<m.numel(); ++j) priors.push_back(m.at<float>(j)); params.priors = &priors[0]; } else if (key=="Update") update = rhs[i+1].toBool(); } bool b = obj.train(trainData, CV_ROW_SAMPLE, responses, varIdx, sampleIdx, varType, missingMask, params, update); plhs[0] = MxArray(b); } else if (method == "predict") { if (nrhs<3 || nlhs>1) mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments"); Mat samples(rhs[2].toMat(CV_32F)), missing; Range slice = Range::all(); bool rawMode=false, returnSum=false; for (int i=3; i<nrhs; i+=2) { string key(rhs[i].toString()); if (key=="MissingMask") missing = rhs[i+1].toMat(CV_8U); else if (key=="Slice") slice = rhs[i+1].toRange(); else if (key=="RawMode") rawMode = rhs[i+1].toBool(); else if (key=="ReturnSum") returnSum = rhs[i+1].toBool(); } Mat results(samples.rows,1,CV_64F); if (missing.empty()) for (int i=0; i<samples.rows; ++i) results.at<double>(i,0) = obj.predict(samples.row(i),missing,slice,rawMode,returnSum); else for (int i=0; i<samples.rows; ++i) results.at<double>(i,0) = obj.predict(samples.row(i),missing.row(i),slice,rawMode,returnSum); plhs[0] = MxArray(results); } else if (method == "get_params") { if (nrhs!=2 || nlhs>1) mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments"); plhs[0] = paramsToMxArray(obj.get_params()); } else mexErrMsgIdAndTxt("mexopencv:error","Unrecognized operation"); }
36.455399
109
0.580296
[ "object", "vector" ]
538429b5c4ee7763f1f2db65a7eda35d3be605c2
22,657
cpp
C++
parameter.cpp
vbillys/pose-estimation
e1b57da68d9c961358a6f8fd37706ed521c5c256
[ "MIT" ]
63
2017-03-30T23:56:47.000Z
2022-03-20T10:30:32.000Z
parameter.cpp
vbillys/pose-estimation
e1b57da68d9c961358a6f8fd37706ed521c5c256
[ "MIT" ]
2
2017-07-10T14:14:50.000Z
2020-07-10T10:08:04.000Z
parameter.cpp
aviate/pose-estimation
e1b57da68d9c961358a6f8fd37706ed521c5c256
[ "MIT" ]
15
2017-03-30T23:56:52.000Z
2021-10-12T12:08:20.000Z
#include <fstream> #include <boost/algorithm/string/join.hpp> #include <pcl/io/pcd_io.h> #include <pcl/console/parse.h> #include "json.hpp" #include "parameter.h" #include "logger.h" using namespace PoseEstimation; using Json = nlohmann::json; Parameter::Parameter(const std::string &category, const std::string &name, const SupportedValue &value, const std::string &description, std::initializer_list<std::shared_ptr<ParameterConstraint> > constraints) : _name(name), _description(description), _category(category), _value(value), _constraints(constraints) { static bool firstTime = true; if (firstTime) { firstTime = false; _allArgs = std::map<std::string, Parameter*>(); _categorized = std::map<std::string, std::vector<Parameter*> >(); _categories = std::map<std::string, std::string>(); _modules = std::map<PipelineModuleType::Type, std::vector<std::string> >(); } const std::string id = parseName(); if (!isValid()) { Logger::warning(boost::format("Parameter %1% has been initialized with invalid parameter %2%") % id % _value); } if (_allArgs.find(id) != _allArgs.end()) { _allArgs[id]->_value = value; //Logger::debug(boost::format("Value of argument \"%1%\" has been updated to [%2%] %3%.") // % id % _type_name(value) % value); return; } else _allArgs[id] = this; if (_categories.find(category) == _categories.end()) { //Logger::debug(boost::format("Adding category %s") % category); _categories[category] = ""; _categorized[category] = std::vector<Parameter*>(); if (_modules.find(PipelineModuleType::Miscellaneous) == _modules.end()) _modules[PipelineModuleType::Miscellaneous] = std::vector<std::string>(); _modules[PipelineModuleType::Miscellaneous].push_back(category); } _categorized[category].push_back(this); //Logger::debug(boost::format("Parameter \"%1%\" has been initialized with [%2%] %3%.") // % id % _type_name(value) % value); } std::string &Parameter::name() { return _name; } std::string &Parameter::description() { return _description; } ParameterCategory Parameter::category() { PipelineModuleType::Type mt = PipelineModuleType::Miscellaneous; for (auto &&mit : _modules) { if (std::find(mit.second.begin(), mit.second.end(), _category) != mit.second.end()) { mt = mit.first; break; } } return ParameterCategory(_category, _categories[_category], mt); } double Parameter::numericalValue() const { if (_value.type() == typeid(int)) return (double)boost::get<int>(_value); if (_value.type() == typeid(float)) return (double)boost::get<float>(_value); if (_value.type() == typeid(bool)) return (double)(int)boost::get<bool>(_value); return std::nan("Parameter type is not numerical"); } bool Parameter::setNumericalValue(double value) { if (_value.type() == typeid(int)) { _value = (int)round(value); return true; } if (_value.type() == typeid(float)) { _value = (float)value; return true; } if (_value.type() == typeid(bool)) { _value = (bool)(int)round(value); return true; } return false; } std::vector<std::shared_ptr<ParameterConstraint> > &Parameter::constraints() { return _constraints; } bool Parameter::isValid() { for (auto &&constraint : _constraints) { if (!constraint->isFulfilled(this)) { Logger::warning(boost::format("Constraint %s %s is not satisfied.") % parseName() % constraint->str()); return false; } } return true; } double Parameter::lowerBound(double defaultValue) const { bool found = false; double lb; for (auto constraint : _constraints) { if (constraint->type() == ParameterConstraintType::GreaterThanOrEqual || constraint->type() == ParameterConstraintType::GreaterThan) { if (!found) { found = true; lb = constraint->resolveNumericalValue(); } else lb = std::max(lb, constraint->resolveNumericalValue()); } } return found ? lb : defaultValue; } double Parameter::upperBound(double defaultValue) const { bool found = false; double ub; for (auto constraint : _constraints) { if (constraint->type() == ParameterConstraintType::LessThanOrEqual || constraint->type() == ParameterConstraintType::LessThan) { if (!found) { found = true; ub = constraint->resolveNumericalValue(); } else ub = std::min(ub, constraint->resolveNumericalValue()); } } return found ? ub : defaultValue; } std::string Parameter::parseName() const { return (boost::format("%s_%s") % _category % _name).str(); } bool Parameter::isNumber() const { return _value.type() == typeid(int) || _value.type() == typeid(float) || _value.type() == typeid(bool); } std::string Parameter::_type_name(const PoseEstimation::SupportedValue &v) { if (v.type() == typeid(int)) return "int"; if (v.type() == typeid(float)) return "float"; if (v.type() == typeid(bool)) return "bool"; if (v.type() == typeid(std::string)) return "string"; if (v.type() == typeid(Enum)) return "enum"; return "unknown"; } void Parameter::_display(int indent) { while (indent-- > 0) std::cout << " "; std::cout << std::left << std::setw(26) << std::setfill(' ') << parseName() << std::left << std::setw(58) << std::setfill(' ') << description() << " ([" << _type_name(_value) << "] " << boost::lexical_cast<std::string>(_value) << ")"; if (!_constraints.empty()) { std::cout << " constraints: "; size_t i = 0; for (auto &constraint : _constraints) { std::cout << "(" << constraint->str() << ")"; if (++i < _constraints.size()) std::cout << ", "; } } std::cout << std::endl; } /** * @brief Prints all registered arguments with their descriptions and default values * to stdout. */ void Parameter::displayAll() { //Logger::debug(boost::format("There are %d modules and %d parameters") % _modules.size() % _allArgs.size()); for (auto &&mit : _modules) { std::string moduleName = PipelineModuleType::str(mit.first); std::cout << moduleName << std::endl; for (std::string &category : mit.second) { std::cout << " " << category; if (!_categories[category].empty()) std::cout << " (" << _categories[category] << ")"; std::cout << std::endl; for (Parameter *arg : _categorized[category]) { arg->_display(2); } } } } /** * @brief Parses all registered arguments from the command-line. * @param argc Number of command-line strings. * @param argv Array of command-line strings. */ void Parameter::parseAll(int argc, char *argv[]) { for (auto it = _allArgs.begin(); it != _allArgs.end(); ++it) { it->second->_parse(argc, argv); } } Parameter *Parameter::get(std::string parseName) { if (_allArgs.find(parseName) == _allArgs.end()) return NULL; return _allArgs[parseName]; } bool Parameter::set(std::string parseName, SupportedValue value) { Parameter *p = get(parseName); if (!p) return false; return p->setValue(value); } std::vector<Parameter *> Parameter::getAll(const std::string &category) { if (_categorized.find(category) == _categorized.end()) { Logger::warning(boost::format("Category \"%s\" was not found.") % category); return std::vector<Parameter*>(); } return _categorized[category]; } std::vector<Parameter *> Parameter::getAll(PipelineModuleType::Type moduleType) { std::vector<Parameter*> r; if (_modules.find(moduleType) == _modules.end()) { Logger::warning(boost::format("No parameters for module type %1% were found.") % moduleType); return r; } for (std::string &category : _modules[moduleType]) { std::vector<Parameter*> parameters = getAll(category); r.insert(r.end(), parameters.begin(), parameters.end()); } return r; } void _set_json_arg_value(Json &jarg, SupportedValue &value) { if (value.type() == typeid(int)) jarg["value"] = boost::get<int>(value); else if (value.type() == typeid(float)) jarg["value"] = boost::get<float>(value); else if (value.type() == typeid(std::string)) jarg["value"] = boost::get<std::string>(value); else if (value.type() == typeid(bool)) jarg["value"] = boost::get<bool>(value); else if (value.type() == typeid(Enum)) jarg["value"] = boost::get<Enum>(value).valueName(); } bool Parameter::saveAll(const std::string &filename) { Json j; j["configuration"] = std::vector<Json>(); for (auto &&mit : _modules) { std::string moduleName = PipelineModuleType::str(mit.first); Json mj; mj["module"] = moduleName; mj["categories"] = std::vector<Json>(); for (std::string &category : mit.second) { // create category Json cj; cj["description"] = _categories[category]; cj["parameters"] = std::vector<Json>(); cj["name"] = category; for (Parameter *arg : _categorized[category]) { Json aj; aj["name"] = arg->name(); _set_json_arg_value(aj, arg->_value); std::string desc = arg->description(); if (!arg->constraints().empty()) { desc += ", constraints: "; size_t i = 0; for (auto &constraint : arg->constraints()) { desc += "(" + constraint->str() + ")"; if (++i < arg->constraints().size()) desc += ", "; } } if (arg->unconvertedValue().type() == typeid(Enum)) { desc += ", possible values: " + boost::algorithm::join(arg->value<Enum>().names(), "|"); } aj["description"] = desc; cj["parameters"].push_back(aj); } mj["categories"].push_back(cj); } j["configuration"].push_back(mj); } std::ofstream fout(filename); if (!fout) { Logger::error(boost::format("Could not save parameters to \"%s\".") % filename); return false; } else { Logger::log(boost::format("Parameters saved successfully to \"%s\".") % filename); } std::string r = j.dump(4); fout << r << std::endl; return true; } bool Parameter::loadAll(const std::string &filename) { std::ifstream fin(filename); if (!fin) { Logger::error(boost::format("Could not load parameters from \"%s\".") % filename); return false; } Json j(fin); if (j.empty()) { Logger::warning(boost::format("Configuration file \"%s\" is empty.") % filename); return true; } for (auto &module : j["configuration"]) { //Logger::debug(boost::format("Found module %s.") % module["module"]); for (auto &category : module["categories"]) { for (auto &parameter : category["parameters"]) { // handle Enum parameter std::string id = (boost::format("%s_%s") % category["name"].get<std::string>() % parameter["name"].get<std::string>()).str(); Parameter *p = Parameter::get(id); if (!p) { Logger::error(boost::format("Could not load parameter \"%s\"") % id); continue; } if (p->_value.type() == typeid(Enum)) { Enum en = p->value<Enum>(); en.set(parameter["value"].get<std::string>()); p->_value = en; } else if (p->_value.type() == typeid(int)) p->_value = (int)parameter["value"]; else if (p->_value.type() == typeid(float)) p->_value = (float)parameter["value"]; else if (p->_value.type() == typeid(std::string)) p->_value = parameter["value"].get<std::string>(); else if (p->_value.type() == typeid(bool)) p->_value = (bool)parameter["value"]; } } } Logger::log(boost::format("Configuration has been read successfully from \"%s\".") % filename); } int Parameter::_parse(int argc, char *argv[]) { //TODO parse enum parameters from CLI if (_value.type() == typeid(int)) return _parse_helper<int>(argc, argv); if (_value.type() == typeid(float)) return _parse_helper<float>(argc, argv); if (_value.type() == typeid(std::string)) return _parse_helper<std::string>(argc, argv); if (_value.type() == typeid(bool)) { int activated = _parse_helper<int>(argc, argv); if (activated == 1) _value = true; else if (activated == 0) _value = false; return 1; } } void Parameter::_defineCategory(const std::string &name, const std::string &description, PipelineModuleType::Type moduleType) { static bool firstTime = true; if (firstTime) { firstTime = false; _allArgs = std::map<std::string, Parameter*>(); _categorized = std::map<std::string, std::vector<Parameter*> >(); _categories = std::map<std::string, std::string>(); _modules = std::map<PipelineModuleType::Type, std::vector<std::string> >(); //Logger::debug("Initialized static parameter category members."); } //Logger::debug(boost::format("Defining parameter category %s...") % name); if (_categories.find(name) == _categories.end() || _categories[name].empty()) _categories.insert({name, description}); if (_modules.find(moduleType) == _modules.end()) _modules[moduleType] = std::vector<std::string>(); if (_categorized.find(name) == _categorized.end()) _categorized[name] = std::vector<Parameter*>(); if (_modules.find(PipelineModuleType::Miscellaneous) != _modules.end() && std::find(_modules[PipelineModuleType::Miscellaneous].begin(), _modules[PipelineModuleType::Miscellaneous].end(), name) != _modules[PipelineModuleType::Miscellaneous].end()) { // category already exists, reassign it to the correct module type std::vector<std::string> &cats = _modules[PipelineModuleType::Miscellaneous]; auto it = std::find(cats.begin(), cats.end(), name); if (it != cats.end()) cats.erase(it); } else if (std::find(_modules[moduleType].begin(), _modules[moduleType].end(), name) == _modules[moduleType].end()) { _modules[moduleType].push_back(name); //Logger::debug(boost::format("Category %s has been defined.") % name); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ParameterCategory::ParameterCategory(const std::string &name, const std::string &description, PipelineModuleType::Type moduleType) : _name(name), _moduleType(moduleType) { if (name != "empty") Parameter::_defineCategory(name, description, moduleType); } ParameterCategory::ParameterCategory(const ParameterCategory &category) : _name(category._name) { } std::vector<Parameter*> ParameterCategory::parameters() const { return Parameter::getAll(_name); } std::string ParameterCategory::name() const { return _name; } std::string ParameterCategory::description() const { return Parameter::_categories[_name]; } PipelineModuleType::Type ParameterCategory::moduleType() const { return _moduleType; } ParameterCategory *_emptyCategory = nullptr; ParameterCategory& ParameterCategory::EmptyCategory() { if (!_emptyCategory) _emptyCategory = new ParameterCategory("empty", ""); return *_emptyCategory; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// EnumParameter::EnumParameter(const std::string &category, const std::string &name, std::initializer_list<std::string> value, const std::string &description, std::initializer_list<std::shared_ptr<ParameterConstraint> > constraints) : Parameter(category, name, Enum::define(value), description, constraints) { } EnumParameter::EnumParameter(const std::string &category, const std::string &name, Enum &value, const std::string &description, std::initializer_list<std::shared_ptr<ParameterConstraint> > constraints) : Parameter(category, name, value, description, constraints) { } bool EnumParameter::setValue(const std::string &value) { int id; Enum en = boost::get<Enum>(_value); if (en.get(value, id)) { en.set(value); _value = en; return true; } return false; } bool EnumParameter::setValue(const std::initializer_list<std::string> &value) { _value = Enum::define(value); return true; } bool EnumParameter::setValue(const Enum &value) { _value = value; return true; } void EnumParameter::_display(int indent) { while (indent-- > 0) std::cout << '\t'; Enum val = boost::get<Enum>(_value); std::cout << std::left << std::setw(26) << std::setfill(' ') << parseName() << std::left << std::setw(58) << std::setfill(' ') << description() << " ([" << boost::algorithm::join(val.names(), "|") << "] " << val.valueName() << ")" << std::endl; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Enum::Enum() { value = 0; } std::string Enum::valueName() const { if (value >= _map.size()) { throw std::exception(); } return _map.left.at(value); } bool Enum::get(std::string name, int &id) const { if (_map.right.find(name) == _map.right.end()) return false; id = _map.right.at(name); return true; } bool Enum::get(int id, std::string &name) const { if (_map.left.find(id) == _map.left.end()) return false; name = _map.left.at(id); return true; } bool Enum::set(const std::string &name) { int v; if (get(name, v)) value = v; } bool Enum::set(int id) { value = id; } size_t Enum::size() const { return _map.size(); } std::vector<std::string> Enum::names() const { std::vector<std::string> ns; for (auto name : _map.right) ns.push_back(name.first); return ns; } Enum Enum::define(std::initializer_list<std::string> _names) { Enum e; int i = 0; for (auto name : _names) { e._map.insert(boost::bimap<int, std::string>::value_type(i, name)); ++i; } return e; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ParameterConstraint::ParameterConstraint(ParameterConstraintType::Type t) : _type(t) { } ParameterConstraintType::Type ParameterConstraint::type() const { return _type; } bool ParameterConstraint::_basicFulfillmentTest(double value, Parameter *parameter) const { switch (_type) { case ParameterConstraintType::GreaterThan: return parameter->numericalValue() > value; case ParameterConstraintType::GreaterThanOrEqual: return parameter->numericalValue() >= value; case ParameterConstraintType::LessThan: return parameter->numericalValue() < value; case ParameterConstraintType::LessThanOrEqual: return parameter->numericalValue() <= value; case ParameterConstraintType::Equal: return std::abs(parameter->numericalValue() - value) <= std::numeric_limits<float>::epsilon(); case ParameterConstraintType::NotEqual: return std::abs(parameter->numericalValue() - value) > std::numeric_limits<float>::epsilon(); } return false; } ConstantConstraint::ConstantConstraint(ParameterConstraintType::Type t, double constant) : ParameterConstraint(t), _constant(constant) { } bool ConstantConstraint::isFulfilled(Parameter *parameter) const { return _basicFulfillmentTest(_constant, parameter); } std::string ConstantConstraint::str() const { std::string _str = (boost::format("%s %d") % ParameterConstraintType::str(_type) % _constant).str(); return _str; } double ConstantConstraint::resolveNumericalValue() const { return _constant; } VariableConstraint::VariableConstraint(ParameterConstraintType::Type t, const std::string &parameterName) : ParameterConstraint(t), _parameterName(parameterName) { } bool VariableConstraint::isFulfilled(Parameter *parameter) const { Parameter *p = Parameter::get(_parameterName); if (!p) { Logger::warning(boost::format("Parameter \"%s\" could not be found for constraint satisfaction test.") % _parameterName); return false; } return _basicFulfillmentTest(p->numericalValue(), parameter); } std::string VariableConstraint::str() const { std::string _str = (boost::format("%s %s") % ParameterConstraintType::str(_type) % _parameterName).str(); return _str; } double VariableConstraint::resolveNumericalValue() const { return Parameter::get(_parameterName)->numericalValue(); } std::string ParameterConstraintType::str(ParameterConstraintType::Type t) { static std::string names[] = { ">", "<", ">=", "<=", "=", "!=" }; return names[(size_t)t]; }
29.424675
141
0.564991
[ "vector" ]
53a049634105cbabf022f1d1fbc6bfa12a37d3b7
1,442
cpp
C++
MonoNative.Tests/mscorlib/System/Resources/mscorlib_System_Resources_IResourceWriter_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
7
2015-03-10T03:36:16.000Z
2021-11-05T01:16:58.000Z
MonoNative.Tests/mscorlib/System/Resources/mscorlib_System_Resources_IResourceWriter_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
1
2020-06-23T10:02:33.000Z
2020-06-24T02:05:47.000Z
MonoNative.Tests/mscorlib/System/Resources/mscorlib_System_Resources_IResourceWriter_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
null
null
null
// Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System.Resources // Name: IResourceWriter // C++ Typed Name: mscorlib::System::Resources::IResourceWriter #include <gtest/gtest.h> #include <mscorlib/System/Resources/mscorlib_System_Resources_IResourceWriter.h> #include <mscorlib/System/mscorlib_System_String.h> #include <mscorlib/System/mscorlib_System_Byte.h> namespace mscorlib { namespace System { namespace Resources { //Public Methods Tests // Method AddResource // Signature: mscorlib::System::String name, std::vector<mscorlib::System::Byte*> value TEST(mscorlib_System_Resources_IResourceWriter_Fixture,AddResource_1_Test) { } // Method AddResource // Signature: mscorlib::System::String name, mscorlib::System::Object value TEST(mscorlib_System_Resources_IResourceWriter_Fixture,AddResource_2_Test) { } // Method AddResource // Signature: mscorlib::System::String name, mscorlib::System::String value TEST(mscorlib_System_Resources_IResourceWriter_Fixture,AddResource_3_Test) { } // Method Close // Signature: TEST(mscorlib_System_Resources_IResourceWriter_Fixture,Close_Test) { } // Method Generate // Signature: TEST(mscorlib_System_Resources_IResourceWriter_Fixture,Generate_Test) { } } } }
21.205882
91
0.721221
[ "object", "vector" ]
53a3a43048044e7663db6b249b7f2b82d7a6f34e
3,808
cpp
C++
sample_loader_app/render/raytracing.cpp
msu-graphics-group/scenes
802d800125faa90c18b23b402c073cf58c97992f
[ "MIT" ]
1
2021-11-03T17:37:13.000Z
2021-11-03T17:37:13.000Z
sample_loader_app/render/raytracing.cpp
msu-graphics-group/scenes
802d800125faa90c18b23b402c073cf58c97992f
[ "MIT" ]
3
2021-11-14T19:24:12.000Z
2022-01-26T12:42:34.000Z
sample_loader_app/render/raytracing.cpp
msu-graphics-group/scenes
802d800125faa90c18b23b402c073cf58c97992f
[ "MIT" ]
null
null
null
#include <cfloat> #include "raytracing.h" #include "../loader/hydraxml.h" #include "../loader/cmesh.h" void RayTracer::CastSingleRay(uint32_t tidX, uint32_t tidY, uint32_t* out_color) { LiteMath::float4 rayPosAndNear, rayDirAndFar; kernel_InitEyeRay(tidX, tidY, &rayPosAndNear, &rayDirAndFar); kernel_RayTrace(tidX, tidY, &rayPosAndNear, &rayDirAndFar, out_color); } void RayTracer::kernel_InitEyeRay(uint32_t tidX, uint32_t tidY, LiteMath::float4* rayPosAndNear, LiteMath::float4* rayDirAndFar) { *rayPosAndNear = to_float4(m_camPos, 1.0f); const LiteMath::float3 rayDir = EyeRayDir(float(tidX), float(tidY), float(m_width), float(m_height), m_invProjView); *rayDirAndFar = to_float4(rayDir, FLT_MAX); } void RayTracer::kernel_RayTrace(uint32_t tidX, uint32_t tidY, const LiteMath::float4* rayPosAndNear, const LiteMath::float4* rayDirAndFar, uint32_t* out_color) { const LiteMath::float4 rayPos = *rayPosAndNear; const LiteMath::float4 rayDir = *rayDirAndFar ; CRT_Hit hit = m_pAccelStruct->RayQuery_NearestHit(rayPos, rayDir); out_color[tidY * m_width + tidX] = m_palette[hit.instId % palette_size]; } bool RayTracer::LoadScene(const std::string& path) { m_pAccelStruct = std::shared_ptr<ISceneObject>(CreateSceneRT("")); m_pAccelStruct->ClearGeom(); hydra_xml::HydraScene scene; if(scene.LoadState(path) < 0) return false; for(auto cam : scene.Cameras()) { float aspect = float(m_width) / float(m_height); auto proj = perspectiveMatrix(cam.fov, aspect, cam.nearPlane, cam.farPlane); auto worldView = lookAt(float3(cam.pos), float3(cam.lookAt), float3(cam.up)); m_invProjView = LiteMath::inverse4x4(proj * transpose(inverse4x4(worldView))); m_camPos = float3(cam.pos); break; // take first cam } m_pAccelStruct->ClearGeom(); for(auto meshPath : scene.MeshFiles()) { std::cout << "[LoadScene]: mesh = " << meshPath.c_str() << std::endl; auto currMesh = cmesh::LoadMeshFromVSGF(meshPath.c_str()); auto geomId = m_pAccelStruct->AddGeom_Triangles4f(currMesh.vPos4f.data(), currMesh.vPos4f.size(), currMesh.indices.data(), currMesh.indices.size()); (void)geomId; // silence "unused variable" compiler warnings } m_pAccelStruct->ClearScene(); for(auto inst : scene.InstancesGeom()) { m_pAccelStruct->AddInstance(inst.geomId, inst.matrix); } m_pAccelStruct->CommitScene(); return true; } LiteMath::float3 EyeRayDir(float x, float y, float w, float h, LiteMath::float4x4 a_mViewProjInv) { LiteMath::float4 pos = LiteMath::make_float4(2.0f * (x + 0.5f) / w - 1.0f, 2.0f * (y + 0.5f) / h - 1.0f, 0.0f, 1.0f ); pos = a_mViewProjInv * pos; pos /= pos.w; pos.y *= (-1.0f); return normalize(to_float3(pos)); } LiteMath::float4x4 perspectiveMatrix(float fovy, float aspect, float zNear, float zFar) { const float ymax = zNear * tanf(fovy * 3.14159265358979323846f / 360.0f); const float xmax = ymax * aspect; const float left = -xmax; const float right = +xmax; const float bottom = -ymax; const float top = +ymax; const float temp = 2.0f * zNear; const float temp2 = right - left; const float temp3 = top - bottom; const float temp4 = zFar - zNear; LiteMath::float4x4 res; res.m_col[0] = LiteMath::float4{ temp / temp2, 0.0f, 0.0f, 0.0f }; res.m_col[1] = LiteMath::float4{ 0.0f, temp / temp3, 0.0f, 0.0f }; res.m_col[2] = LiteMath::float4{ (right + left) / temp2, (top + bottom) / temp3, (-zFar - zNear) / temp4, -1.0 }; res.m_col[3] = LiteMath::float4{ 0.0f, 0.0f, (-temp * zFar) / temp4, 0.0f }; return res; }
35.259259
128
0.653361
[ "mesh" ]
53a869f85690a88e4c459ea9ec835e79c535e1ac
3,070
cpp
C++
LiveArchive/WhosTheBoss.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
1
2018-08-28T19:58:40.000Z
2018-08-28T19:58:40.000Z
LiveArchive/WhosTheBoss.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
2
2017-04-16T00:48:05.000Z
2017-08-03T20:12:26.000Z
LiveArchive/WhosTheBoss.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
4
2016-03-04T19:42:00.000Z
2018-01-08T11:42:00.000Z
#include <iostream> #include <string> #include <sstream> #include <vector> #include <set> #include <map> #include <list> #include <queue> #include <stack> #include <memory> #include <iomanip> #include <functional> #include <new> #include <algorithm> #include <cmath> #include <cstring> #include <cstdlib> #include <cstdio> #include <climits> #include <cctype> #include <ctime> #define REP(i, n) for(int (i) = 0; i < n; i++) #define FOR(i, a, n) for(int (i) = a; i < n; i++) #define FORR(i, a, n) for(int (i) = a; i <= n; i++) #define for_each(q, s) for(typeof(s.begin()) q=s.begin(); q!=s.end(); q++) #define sz(n) n.size() #define pb(n) push_back(n) #define all(n) n.begin(), n.end() template<typename T> T gcd(T a, T b) { if(!b) return a; return gcd(b, a % b); } template<typename T> T lcm(T a, T b) { return a * b / gcd(a, b); } using namespace std; typedef long long ll; typedef long double ld; const int MAXN = 300010; int T, M, Q, id, sal, ta; vector<int> graph[MAXN]; int parent[MAXN] = {-1}; int i_id[MAXN]; int id_i[MAXN]; int dp[MAXN]; int dfs(int now) { int ans = 1; REP(i, graph[now].size()) { ans += dfs(graph[now][i]); } return dp[now] = ans; } struct employee { int id, salary, tall; employee(){} employee(int _id, int _salary, int _tall) { id = _id; salary = _salary; tall = _tall; } bool operator<(const employee& e) const { return salary > e.salary; } }; employee ve[MAXN]; inline void fastRead_int(int &x) { register int c = getchar_unlocked(); x = 0; int neg = 0; for (; ((c<48 || c>57) && c != '-'); c = getchar_unlocked()); if (c=='-') { neg = 1; c = getchar_unlocked(); } for ( ; c>47 && c<58 ; c = getchar_unlocked()) { x = (x<<1) + (x<<3) + c - 48; } if (neg) { x = -x; } } int main(void) { fastRead_int(T); for( ; T-- ; ) { fastRead_int(M); fastRead_int(Q); REP(i, M) { graph[i].clear(); parent[i] = -1; } REP(i, M) { fastRead_int(id); fastRead_int(sal); fastRead_int(ta); i_id[i] = id; id_i[id] = i; ve[i] = employee(i, sal, ta); } sort(ve, ve + M); int root = ve[0].id; for(int i = 1; i < M; i++) { for(int j = i - 1; j >= 0; j--) { if(ve[i].salary < ve[j].salary && ve[i].tall <= ve[j].tall) { parent[ve[i].id] = ve[j].id; graph[ve[j].id].push_back(ve[i].id); break; } } } dfs(root); REP(i, Q) { fastRead_int(id); id = id_i[id]; int boss = parent[id], go = dp[id]-1; boss = i_id[boss]; if(boss == -1) boss = 0; printf("%d %d\n", boss, go); } } return 0; }
21.468531
78
0.466124
[ "vector" ]
53aa6917eb016a68ce87a559653cdad9179e3aaa
12,651
cpp
C++
tools/remote_demo.cpp
derp-caf/external_skia
b09dc92e00edce8366085aaad7dcce94ceb11b69
[ "BSD-3-Clause" ]
1
2019-05-29T09:54:38.000Z
2019-05-29T09:54:38.000Z
tools/remote_demo.cpp
derp-caf/external_skia
b09dc92e00edce8366085aaad7dcce94ceb11b69
[ "BSD-3-Clause" ]
null
null
null
tools/remote_demo.cpp
derp-caf/external_skia
b09dc92e00edce8366085aaad7dcce94ceb11b69
[ "BSD-3-Clause" ]
8
2019-01-12T23:06:45.000Z
2021-09-03T00:15:46.000Z
/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkCanvas.h" #include "SkPathEffect.h" #include "SkMaskFilter.h" #include "SkData.h" #include "SkDescriptor.h" #include "SkGraphics.h" #include "SkSemaphore.h" #include "SkPictureRecorder.h" #include "SkSerialProcs.h" #include "SkSurface.h" #include "SkTypeface.h" #include "SkWriteBuffer.h" #include <chrono> #include <ctype.h> #include <err.h> #include <memory> #include <stdio.h> #include <thread> #include <iostream> #include <unordered_map> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <sys/mman.h> #include "SkTypeface_remote.h" #include "SkRemoteGlyphCache.h" #include "SkMakeUnique.h" static const size_t kPageSize = 4096; static bool gUseGpu = true; static bool gPurgeFontCaches = true; static bool gUseProcess = true; enum class OpCode : int32_t { kFontMetrics = 0, kGlyphMetrics = 1, kGlyphImage = 2, kGlyphPath = 3, kGlyphMetricsAndImage = 4, }; class Op { public: Op(OpCode opCode, SkFontID typefaceId, const SkScalerContextRec& rec) : opCode{opCode} , typefaceId{typefaceId} , descriptor{rec} { } const OpCode opCode; const SkFontID typefaceId; const SkScalerContextRecDescriptor descriptor; union { // op 0 SkPaint::FontMetrics fontMetrics; // op 1 and 2 SkGlyph glyph; // op 3 struct { SkGlyphID glyphId; size_t pathSize; }; }; }; class RemoteScalerContextFIFO : public SkRemoteScalerContext { public: explicit RemoteScalerContextFIFO(int readFd, int writeFd) : fReadFd{readFd} , fWriteFd{writeFd} { } void generateFontMetrics(const SkTypefaceProxy& tf, const SkScalerContextRec& rec, SkPaint::FontMetrics* metrics) override { Op* op = this->createOp(OpCode::kFontMetrics, tf, rec); write(fWriteFd, fBuffer, sizeof(*op)); read(fReadFd, fBuffer, sizeof(fBuffer)); memcpy(metrics, &op->fontMetrics, sizeof(op->fontMetrics)); op->~Op(); } void generateMetrics(const SkTypefaceProxy& tf, const SkScalerContextRec& rec, SkGlyph* glyph) override { Op* op = this->createOp(OpCode::kGlyphMetrics, tf, rec); memcpy(&op->glyph, glyph, sizeof(*glyph)); write(fWriteFd, fBuffer, sizeof(*op)); read(fReadFd, fBuffer, sizeof(fBuffer)); memcpy(glyph, &op->glyph, sizeof(op->glyph)); op->~Op(); } void generateImage(const SkTypefaceProxy& tf, const SkScalerContextRec& rec, const SkGlyph& glyph) override { SK_ABORT("generateImage should not be called."); Op* op = this->createOp(OpCode::kGlyphImage, tf, rec); memcpy(&op->glyph, &glyph, sizeof(glyph)); write(fWriteFd, fBuffer, sizeof(*op)); read(fReadFd, fBuffer, sizeof(fBuffer)); memcpy(glyph.fImage, fBuffer + sizeof(Op), glyph.rowBytes() * glyph.fHeight); op->~Op(); } void generateMetricsAndImage(const SkTypefaceProxy& tf, const SkScalerContextRec& rec, SkArenaAlloc* alloc, SkGlyph* glyph) override { Op* op = this->createOp(OpCode::kGlyphMetricsAndImage, tf, rec); memcpy(&op->glyph, glyph, sizeof(op->glyph)); write(fWriteFd, fBuffer, sizeof(*op)); read(fReadFd, fBuffer, sizeof(fBuffer)); memcpy(glyph, &op->glyph, sizeof(*glyph)); glyph->allocImage(alloc); memcpy(glyph->fImage, fBuffer + sizeof(Op), glyph->rowBytes() * glyph->fHeight); op->~Op(); } void generatePath(const SkTypefaceProxy& tf, const SkScalerContextRec& rec, SkGlyphID glyph, SkPath* path) override { Op* op = this->createOp(OpCode::kGlyphPath, tf, rec); op->glyphId = glyph; write(fWriteFd, fBuffer, sizeof(*op)); read(fReadFd, fBuffer, sizeof(fBuffer)); path->readFromMemory(fBuffer + sizeof(Op), op->pathSize); op->~Op(); } private: Op* createOp(OpCode opCode, const SkTypefaceProxy& tf, const SkScalerContextRec& rec) { Op* op = new (fBuffer) Op(opCode, tf.fontID(), rec); return op; } const int fReadFd, fWriteFd; uint8_t fBuffer[1024 * kPageSize]; }; static void final_draw(std::string outFilename, SkDeserialProcs* procs, uint8_t* picData, size_t picSize) { auto pic = SkPicture::MakeFromData(picData, picSize, procs); auto cullRect = pic->cullRect(); auto r = cullRect.round(); auto s = SkSurface::MakeRasterN32Premul(r.width(), r.height()); auto c = s->getCanvas(); auto picUnderTest = SkPicture::MakeFromData(picData, picSize, procs); std::chrono::duration<double> total_seconds{0.0}; for (int i = 0; i < 20; i++) { if (gPurgeFontCaches) { SkGraphics::PurgeFontCache(); } auto start = std::chrono::high_resolution_clock::now(); c->drawPicture(picUnderTest); auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsed_seconds = end-start; total_seconds += elapsed_seconds; } std::cout << "useProcess: " << gUseProcess << " useGPU: " << gUseGpu << " purgeCache: " << gPurgeFontCaches << std::endl; std::cerr << "elapsed time: " << total_seconds.count() << "s\n"; auto i = s->makeImageSnapshot(); auto data = i->encodeToData(); SkFILEWStream f(outFilename.c_str()); f.write(data->data(), data->size()); } static void gpu(int readFd, int writeFd) { size_t picSize = 0; ssize_t r = read(readFd, &picSize, sizeof(picSize)); if (r > 0) { static constexpr size_t kBufferSize = 10 * 1024 * kPageSize; std::unique_ptr<uint8_t[]> picBuffer{new uint8_t[kBufferSize]}; size_t readSoFar = 0; while (readSoFar < picSize) { ssize_t readSize; if ((readSize = read(readFd, &picBuffer[readSoFar], kBufferSize - readSoFar)) <= 0) { if (readSize == 0) return; err(1, "gpu pic read error %d", errno); } readSoFar += readSize; } SkRemoteGlyphCacheGPU rc{ skstd::make_unique<RemoteScalerContextFIFO>(readFd, writeFd) }; SkDeserialProcs procs; rc.prepareDeserializeProcs(&procs); final_draw("test.png", &procs, picBuffer.get(), picSize); } close(writeFd); close(readFd); } static int renderer( const std::string& skpName, int readFd, int writeFd) { std::string prefix{"skps/"}; std::string fileName{prefix + skpName + ".skp"}; auto skp = SkData::MakeFromFileName(fileName.c_str()); std::cout << "skp stream is " << skp->size() << " bytes long " << std::endl; SkRemoteGlyphCacheRenderer rc; SkSerialProcs procs; sk_sp<SkData> stream; if (gUseGpu) { auto pic = SkPicture::MakeFromData(skp.get()); rc.prepareSerializeProcs(&procs); stream = pic->serialize(&procs); } else { stream = skp; } std::cout << "stream is " << stream->size() << " bytes long" << std::endl; size_t picSize = stream->size(); uint8_t* picBuffer = (uint8_t*) stream->data(); if (!gUseGpu) { final_draw("test-direct.png", nullptr, picBuffer, picSize); close(writeFd); close(readFd); return 0; } write(writeFd, &picSize, sizeof(picSize)); size_t writeSoFar = 0; while (writeSoFar < picSize) { ssize_t writeSize = write(writeFd, &picBuffer[writeSoFar], picSize - writeSoFar); if (writeSize <= 0) { if (writeSize == 0) { std::cout << "Exit" << std::endl; return 1; } perror("Can't write picture from render to GPU "); return 1; } writeSoFar += writeSize; } std::cout << "Waiting for scaler context ops." << std::endl; static constexpr size_t kBufferSize = 1024 * kPageSize; std::unique_ptr<uint8_t[]> glyphBuffer{new uint8_t[kBufferSize]}; Op* op = (Op*)glyphBuffer.get(); while (true) { ssize_t size = read(readFd, glyphBuffer.get(), sizeof(*op)); if (size <= 0) { std::cout << "Exit op loop" << std::endl; break;} size_t writeSize = sizeof(*op); auto sc = rc.generateScalerContext(op->descriptor, op->typefaceId); switch (op->opCode) { case OpCode::kFontMetrics : { sc->getFontMetrics(&op->fontMetrics); break; } case OpCode::kGlyphMetrics : { sc->getMetrics(&op->glyph); break; } case OpCode::kGlyphImage : { // TODO: check for buffer overflow. op->glyph.fImage = &glyphBuffer[sizeof(Op)]; sc->getImage(op->glyph); writeSize += op->glyph.rowBytes() * op->glyph.fHeight; break; } case OpCode::kGlyphPath : { // TODO: check for buffer overflow. SkPath path; sc->getPath(op->glyphId, &path); op->pathSize = path.writeToMemory(&glyphBuffer[sizeof(Op)]); writeSize += op->pathSize; break; } case OpCode::kGlyphMetricsAndImage : { // TODO: check for buffer overflow. sc->getMetrics(&op->glyph); if (op->glyph.fWidth <= 0 || op->glyph.fWidth >= kMaxGlyphWidth) { op->glyph.fImage = nullptr; break; } op->glyph.fImage = &glyphBuffer[sizeof(Op)]; sc->getImage(op->glyph); writeSize += op->glyph.rowBytes() * op->glyph.fHeight; break; } default: SK_ABORT("Bad op"); } write(writeFd, glyphBuffer.get(), writeSize); } close(readFd); close(writeFd); std::cout << "Returning from render" << std::endl; return 0; } enum direction : int {kRead = 0, kWrite = 1}; static void start_gpu(int render_to_gpu[2], int gpu_to_render[2]) { std::cout << "gpu - Starting GPU" << std::endl; close(gpu_to_render[kRead]); close(render_to_gpu[kWrite]); gpu(render_to_gpu[kRead], gpu_to_render[kWrite]); } static void start_render(std::string& skpName, int render_to_gpu[2], int gpu_to_render[2]) { std::cout << "renderer - Starting Renderer" << std::endl; close(render_to_gpu[kRead]); close(gpu_to_render[kWrite]); renderer(skpName, gpu_to_render[kRead], render_to_gpu[kWrite]); } int main(int argc, char** argv) { std::string skpName = argc > 1 ? std::string{argv[1]} : std::string{"desk_nytimes"}; int mode = argc > 2 ? atoi(argv[2]) : -1; printf("skp: %s\n", skpName.c_str()); int render_to_gpu[2], gpu_to_render[2]; for (int m = 0; m < 8; m++) { int r = pipe(render_to_gpu); if (r < 0) { perror("Can't write picture from render to GPU "); return 1; } r = pipe(gpu_to_render); if (r < 0) { perror("Can't write picture from render to GPU "); return 1; } gPurgeFontCaches = (m & 4) == 4; gUseGpu = (m & 2) == 2; gUseProcess = (m & 1) == 1; if (mode >= 0 && mode < 8 && mode != m) { continue; } if (gUseProcess) { pid_t child = fork(); SkGraphics::Init(); if (child == 0) { start_gpu(render_to_gpu, gpu_to_render); } else { start_render(skpName, render_to_gpu, gpu_to_render); waitpid(child, nullptr, 0); } } else { SkGraphics::Init(); std::thread(gpu, render_to_gpu[kRead], gpu_to_render[kWrite]).detach(); renderer(skpName, gpu_to_render[kRead], render_to_gpu[kWrite]); } } return 0; }
31.866499
97
0.556873
[ "render" ]
53ad764415cce095dbf1dfe59f506deecaeadbbf
17,694
cxx
C++
test/clogMessage.cxx
mrab/CLog
a096e15c72c7a608e5fcd69bd07fb2263cfbd4d5
[ "MIT" ]
null
null
null
test/clogMessage.cxx
mrab/CLog
a096e15c72c7a608e5fcd69bd07fb2263cfbd4d5
[ "MIT" ]
null
null
null
test/clogMessage.cxx
mrab/CLog
a096e15c72c7a608e5fcd69bd07fb2263cfbd4d5
[ "MIT" ]
null
null
null
/** * @copyright (c) 2019 mrab * * This library is free software; you can redistribute it and/or modify it * under the terms of the MIT license. See LICENSE for details. * * @author Melchior Rabe (oss@mrab.de) * @brief * @date 2019-09-16 * * @file */ #include <gmock/gmock.h> #include <gtest/gtest.h> #include "clog.h" #include "testUtils.h" using namespace ::testing; #define DEFAULT_TAGS(F) \ F(COMMUNICATION) \ F(IO) class CLogMessageTest : public ::testing::Test { protected: // longest string that shall fit in is "Fatal Error" // which requires 12 bytes static const size_t BufferSize = 12; static const size_t GuardSize = 3; char buffer[BufferSize + GuardSize]; CLogAdapter adapters[1] = {{CLogMessageTest::filter, CLogMessageTest::printer}}; CLogContext ctx = { adapters, ARRAY_LENGTH(adapters), TagsNames, ARRAY_LENGTH(TagsNames), CLOG_LOFF, buffer, BufferSize, }; CLOG_ENUM_WITH_NAMES(Tags, DEFAULT_TAGS) void SetUp() override { memset(buffer, 0, ARRAY_LENGTH(buffer)); for (size_t i = 0; i < GuardSize; i++) { buffer[BufferSize + i] = '\xFF'; } mock = new MockAdapter(); } void TearDown() override { delete mock; mock = nullptr; } bool isGuardOk() { for (size_t i = 0; i < GuardSize; i++) { if (buffer[BufferSize + i] != '\xFF') { return false; } } return true; } static MockAdapter *mock; static bool filter(const CLogMessage *message) { return mock->filter(message); }; static void printer(const CLogMessage *message) { mock->printer(message); }; }; MockAdapter *CLogMessageTest::mock; TEST_F(CLogMessageTest, logMsgParamsAllSet) { CLogContext *pCtx = &ctx; ctx.minLevel = CLOG_LTRC; CLogLevel level = CLOG_LWRN; size_t tag = 0U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = "foo()"; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(1).WillRepeatedly(Return(true)); EXPECT_CALL(*mock, printer(AllOf(Field(&CLogMessage::file, StrEq(file)), Field(&CLogMessage::function, StrEq(function)), Field(&CLogMessage::level, Eq(CLOG_LWRN)), Field(&CLogMessage::line, Eq(line)), Field(&CLogMessage::message, StrEq(message)), Field(&CLogMessage::tag, StrEq(ctx.tagNames[0]))))) .Times(1); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); } TEST_F(CLogMessageTest, logMsgNoContext) { CLogContext *pCtx = nullptr; CLogLevel level = CLOG_LWRN; size_t tag = 0U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = "foo()"; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(0); EXPECT_CALL(*mock, printer(_)).Times(0); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); // Buffer shall be untouched ASSERT_THAT(std::vector<char>(buffer, buffer + BufferSize), Each(0)); } TEST_F(CLogMessageTest, logMsgNoAdapter) { CLogContext customCtx = { nullptr, 5, // deliberately set an invalid adapter length TagsNames, ARRAY_LENGTH(TagsNames), CLOG_LTRC, buffer, BufferSize, }; CLogContext *pCtx = &customCtx; CLogLevel level = CLOG_LWRN; size_t tag = 0U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = "foo()"; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(0); EXPECT_CALL(*mock, printer(_)).Times(0); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); // Buffer shall be untouched ASSERT_THAT(std::vector<char>(buffer, buffer + BufferSize), Each(0)); } TEST_F(CLogMessageTest, logMsgZeroAdapterLength) { CLogContext customCtx = { adapters, 0, // deliberately set adapter length to 0 TagsNames, ARRAY_LENGTH(TagsNames), CLOG_LTRC, buffer, BufferSize, }; CLogContext *pCtx = &customCtx; CLogLevel level = CLOG_LWRN; size_t tag = 0U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = "foo()"; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(0); EXPECT_CALL(*mock, printer(_)).Times(0); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); // Buffer shall be untouched ASSERT_THAT(std::vector<char>(buffer, buffer + BufferSize), Each(0)); } TEST_F(CLogMessageTest, logMsgFileNullPtr) { CLogContext *pCtx = &ctx; ctx.minLevel = CLOG_LTRC; CLogLevel level = CLOG_LWRN; size_t tag = 0U; const char *file = nullptr; const unsigned int line = 123U; const char *function = "foo()"; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(1).WillRepeatedly(Return(true)); EXPECT_CALL(*mock, printer(AllOf(Field(&CLogMessage::file, Eq(file)), Field(&CLogMessage::function, StrEq(function)), Field(&CLogMessage::level, Eq(CLOG_LWRN)), Field(&CLogMessage::line, Eq(line)), Field(&CLogMessage::message, StrEq(message)), Field(&CLogMessage::tag, StrEq(ctx.tagNames[0]))))) .Times(1); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); } TEST_F(CLogMessageTest, logMsgFunctionNullPtr) { CLogContext *pCtx = &ctx; ctx.minLevel = CLOG_LTRC; CLogLevel level = CLOG_LWRN; size_t tag = 0U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = nullptr; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(1).WillRepeatedly(Return(true)); EXPECT_CALL(*mock, printer(AllOf(Field(&CLogMessage::file, StrEq(file)), Field(&CLogMessage::function, Eq(function)), Field(&CLogMessage::level, Eq(CLOG_LWRN)), Field(&CLogMessage::line, Eq(line)), Field(&CLogMessage::message, StrEq(message)), Field(&CLogMessage::tag, StrEq(ctx.tagNames[0]))))) .Times(1); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); } TEST_F(CLogMessageTest, logMsgAdapterPrinterIsNull) { CLogAdapter adapter[] = {{CLogMessageTest::filter, nullptr}}; CLogContext customCtx = { adapter, 1, TagsNames, ARRAY_LENGTH(TagsNames), CLOG_LTRC, buffer, BufferSize, }; CLogContext *pCtx = &customCtx; CLogLevel level = CLOG_LWRN; size_t tag = 0U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = nullptr; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(0); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); // Buffer shall be untouched ASSERT_THAT(std::vector<char>(buffer, buffer + BufferSize), Each(0)); } TEST_F(CLogMessageTest, logMsgMsgNullPtr) { CLogContext *pCtx = &ctx; ctx.minLevel = CLOG_LTRC; CLogLevel level = CLOG_LWRN; size_t tag = 0U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = "foo()"; const char *message = nullptr; EXPECT_CALL(*mock, filter(_)).Times(0); EXPECT_CALL(*mock, printer(_)).Times(0); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); } TEST_F(CLogMessageTest, logMsgTagOutOfRange) { CLogContext *pCtx = &ctx; ctx.minLevel = CLOG_LTRC; CLogLevel level = CLOG_LWRN; size_t tag = 123U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = "foo()"; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(1).WillRepeatedly(Return(true)); EXPECT_CALL(*mock, printer(AllOf(Field(&CLogMessage::file, StrEq(file)), Field(&CLogMessage::function, StrEq(function)), Field(&CLogMessage::level, Eq(CLOG_LWRN)), Field(&CLogMessage::line, Eq(line)), Field(&CLogMessage::message, StrEq(message)), Field(&CLogMessage::tag, StrEq(""))))) .Times(1); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); } TEST_F(CLogMessageTest, logMsgLevelOutOfRange) { CLogContext *pCtx = &ctx; ctx.minLevel = CLOG_LTRC; CLogLevel level = static_cast<CLogLevel>(static_cast<int>(CLOG_LUKN) + 1); size_t tag = 1U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = "foo()"; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(1).WillRepeatedly(Return(true)); EXPECT_CALL(*mock, printer(AllOf(Field(&CLogMessage::file, StrEq(file)), Field(&CLogMessage::function, StrEq(function)), Field(&CLogMessage::level, Eq(CLOG_LUKN)), Field(&CLogMessage::line, Eq(line)), Field(&CLogMessage::message, StrEq(message)), Field(&CLogMessage::tag, StrEq("IO"))))) .Times(1); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); } TEST_F(CLogMessageTest, logMsgLevelBelowMinLevel) { CLogContext *pCtx = &ctx; ctx.minLevel = CLOG_LERR; CLogLevel level = CLOG_LWRN; size_t tag = 1U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = "foo()"; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(0); EXPECT_CALL(*mock, printer(_)).Times(0); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); } TEST_F(CLogMessageTest, logMsgLevelUnknown) { CLogContext *pCtx = &ctx; ctx.minLevel = CLOG_LTRC; CLogLevel level = CLOG_LUKN; size_t tag = 1U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = "foo()"; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(1).WillRepeatedly(Return(true)); EXPECT_CALL(*mock, printer(AllOf(Field(&CLogMessage::file, StrEq(file)), Field(&CLogMessage::function, StrEq(function)), Field(&CLogMessage::level, Eq(CLOG_LUKN)), Field(&CLogMessage::line, Eq(line)), Field(&CLogMessage::message, StrEq(message)), Field(&CLogMessage::tag, StrEq("IO"))))) .Times(1); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); } TEST_F(CLogMessageTest, logMsgLevelOff) { CLogContext *pCtx = &ctx; ctx.minLevel = CLOG_LTRC; CLogLevel level = CLOG_LOFF; size_t tag = 1U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = "foo()"; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(1).WillRepeatedly(Return(true)); EXPECT_CALL(*mock, printer(AllOf(Field(&CLogMessage::file, StrEq(file)), Field(&CLogMessage::function, StrEq(function)), Field(&CLogMessage::level, Eq(CLOG_LUKN)), Field(&CLogMessage::line, Eq(line)), Field(&CLogMessage::message, StrEq(message)), Field(&CLogMessage::tag, StrEq("IO"))))) .Times(1); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); } TEST_F(CLogMessageTest, noAdapters) { CLogContext context = { nullptr, 5, TagsNames, ARRAY_LENGTH(TagsNames), CLOG_LTRC, buffer, BufferSize, }; CLogContext *pCtx = &context; ctx.minLevel = CLOG_LTRC; CLogLevel level = CLOG_LOFF; size_t tag = 1U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = "foo()"; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(0); EXPECT_CALL(*mock, printer(_)).Times(0); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); } TEST_F(CLogMessageTest, noAdapterLength) { CLogContext context = { adapters, 0, TagsNames, ARRAY_LENGTH(TagsNames), CLOG_LTRC, buffer, BufferSize, }; CLogContext *pCtx = &context; ctx.minLevel = CLOG_LTRC; CLogLevel level = CLOG_LOFF; size_t tag = 1U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = "foo()"; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(0); EXPECT_CALL(*mock, printer(_)).Times(0); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); } TEST_F(CLogMessageTest, logAdapterNoPrinter) { CLogAdapter testAdapters[1] = {{CLogMessageTest::filter, nullptr}}; CLogContext context = { testAdapters, ARRAY_LENGTH(testAdapters), TagsNames, ARRAY_LENGTH(TagsNames), CLOG_LTRC, buffer, BufferSize, }; CLogContext *pCtx = &context; ctx.minLevel = CLOG_LTRC; CLogLevel level = CLOG_LWRN; size_t tag = 0U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = "foo()"; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(0); EXPECT_CALL(*mock, printer(_)) .Times(0); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); } TEST_F(CLogMessageTest, logAdapterNoFilter) { CLogAdapter testAdapters[1] = {{nullptr, CLogMessageTest::printer}};; CLogContext context = { testAdapters, ARRAY_LENGTH(testAdapters), TagsNames, ARRAY_LENGTH(TagsNames), CLOG_LTRC, buffer, BufferSize, }; CLogContext *pCtx = &context; ctx.minLevel = CLOG_LTRC; CLogLevel level = CLOG_LWRN; size_t tag = 0U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = "foo()"; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(0); EXPECT_CALL(*mock, printer(AllOf(Field(&CLogMessage::file, StrEq(file)), Field(&CLogMessage::function, StrEq(function)), Field(&CLogMessage::level, Eq(CLOG_LWRN)), Field(&CLogMessage::line, Eq(line)), Field(&CLogMessage::message, StrEq(message)), Field(&CLogMessage::tag, StrEq("COMMUNICATION"))))) .Times(1); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); } TEST_F(CLogMessageTest, noTags) { CLogContext context = { adapters, ARRAY_LENGTH(adapters), nullptr, ARRAY_LENGTH(TagsNames), CLOG_LOFF, buffer, BufferSize, }; CLogContext *pCtx = &context; ctx.minLevel = CLOG_LTRC; CLogLevel level = CLOG_LOFF; size_t tag = 1U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = "foo()"; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(0); EXPECT_CALL(*mock, printer(_)).Times(0); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); } TEST_F(CLogMessageTest, noTagsLength) { CLogContext context = { adapters, ARRAY_LENGTH(adapters), TagsNames, 0, CLOG_LOFF, buffer, BufferSize, }; CLogContext *pCtx = &context; ctx.minLevel = CLOG_LTRC; CLogLevel level = CLOG_LOFF; size_t tag = 1U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = "foo()"; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(0); EXPECT_CALL(*mock, printer(_)).Times(0); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); } TEST_F(CLogMessageTest, noBuffer) { CLogContext context = { adapters, ARRAY_LENGTH(adapters), TagsNames, ARRAY_LENGTH(TagsNames), CLOG_LOFF, nullptr, BufferSize, }; CLogContext *pCtx = &context; ctx.minLevel = CLOG_LTRC; CLogLevel level = CLOG_LOFF; size_t tag = 1U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = "foo()"; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(0); EXPECT_CALL(*mock, printer(_)).Times(0); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); } TEST_F(CLogMessageTest, noBufferLength) { CLogContext context = { adapters, ARRAY_LENGTH(adapters), TagsNames, ARRAY_LENGTH(TagsNames), CLOG_LOFF, buffer, 0, }; CLogContext *pCtx = &context; ctx.minLevel = CLOG_LTRC; CLogLevel level = CLOG_LOFF; size_t tag = 1U; const char *file = "myFile.c"; const unsigned int line = 123U; const char *function = "foo()"; const char *message = "some msg"; EXPECT_CALL(*mock, filter(_)).Times(0); EXPECT_CALL(*mock, printer(_)).Times(0); clog_logMessage(pCtx, level, tag, file, line, function, message); ASSERT_TRUE(isGuardOk()); }
28.677472
82
0.626936
[ "vector" ]
53b2a4a62bcf72bbd5afee1f94a7e427f67e5665
2,929
cc
C++
src/capture/gather_images_by_match.cc
puyoai/puyoai
575068dffab021cd42b0178699d480a743ca4e1f
[ "CC-BY-4.0" ]
115
2015-02-21T15:08:26.000Z
2022-02-05T01:38:10.000Z
src/capture/gather_images_by_match.cc
haripo/puyoai
575068dffab021cd42b0178699d480a743ca4e1f
[ "CC-BY-4.0" ]
214
2015-01-16T04:53:35.000Z
2019-03-23T11:39:59.000Z
src/capture/gather_images_by_match.cc
haripo/puyoai
575068dffab021cd42b0178699d480a743ca4e1f
[ "CC-BY-4.0" ]
56
2015-01-16T05:14:13.000Z
2020-09-22T07:22:49.000Z
#include <algorithm> #include <iostream> #include <string> #include <vector> #include <gflags/gflags.h> #include <glog/logging.h> #include <SDL.h> #include <SDL_image.h> #include <sys/stat.h> #include <sys/types.h> #include "base/file/path.h" #include "base/strings.h" #include "capture/ac_analyzer.h" #include "gui/unique_sdl_surface.h" using namespace std; bool listBMPsRecursively(const std::string& root, std::vector<std::string>* files) { cout << root << endl; vector<string> tmp_files; if (!file::listFiles(root, &tmp_files)) return false; for (const auto& f : tmp_files) { if (f == "." || f == "..") continue; string p = file::joinPath(root, f); if (strings::hasSuffix(f, ".bmp")) { files->push_back(p); continue; } if (!file::isDirectory(p)) { LOG(INFO) << "Unknown file: " << p << endl; continue; } if (!listBMPsRecursively(p, files)) { return false; } } return true; } int main(int argc, char* argv[]) { google::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); if (argc < 2) { fprintf(stderr, "Usage: %s <root directory>\n", argv[0]); exit(EXIT_FAILURE); } // list files. vector<string> files; CHECK(listBMPsRecursively(argv[1], &files)); std::sort(files.begin(), files.end()); cout << "file listed: size=" << files.size() << endl; ACAnalyzer analyzer; int match_no = 0; bool game_end_detected = false; for (size_t i = 0; i < files.size(); ++i) { const auto& f = files[i]; UniqueSDLSurface surface = makeUniqueSDLSurface(IMG_Load(f.c_str())); CaptureGameState state = analyzer.detectGameState(surface.get()); if (state == CaptureGameState::LEVEL_SELECT) { // game start if (game_end_detected) { match_no += 1; game_end_detected = false; cout << "match found: " << match_no << " file=" << f << endl; char path[1024]; sprintf(path, "out/%d", match_no); (void)mkdir(path, 0755); } } else if (isGameFinishedState(state)) { if (!game_end_detected) { cout << "match end: " << f << endl; game_end_detected = true; } } #if 1 // Will enable this later. // Copy image. char dest_path[1024]; sprintf(dest_path, "out/%d/%s", match_no, file::basename(f).c_str()); cout << dest_path << endl; PCHECK(symlink(f.c_str(), dest_path) == 0) << "target=" << f << " dest_path=" << dest_path; #endif #if 0 CHECK(file::copyFile(f, dest_path)) << "src=" << f << " dest=" << dest_path; #endif } return 0; }
25.034188
82
0.534995
[ "vector" ]
53ba98b889b31fe964dbf7969a67680d93f95f70
1,142
cc
C++
ext/candc/src/lib/tree/node.cc
TeamSPoon/logicmoo_nlu
5c3e5013a3048da7d68a8a43476ad84d3ea4bb47
[ "MIT" ]
6
2020-01-27T12:08:02.000Z
2020-02-28T19:30:28.000Z
pack/logicmoo_nlu/prolog/candc/src/lib/tree/node.cc
logicmoo/old_logicmoo_workspace
44025b6e389e2f2f7d86b46c1301cab0604bba26
[ "MIT" ]
2
2017-03-13T02:56:09.000Z
2019-07-27T02:47:29.000Z
ext/candc/src/lib/tree/node.cc
TeamSPoon/logicmoo_nlu
5c3e5013a3048da7d68a8a43476ad84d3ea4bb47
[ "MIT" ]
1
2020-11-25T06:09:33.000Z
2020-11-25T06:09:33.000Z
// C&C NLP tools // Copyright (c) Universities of Edinburgh, Oxford and Sydney // Copyright (c) James R. Curran // // This software is covered by a non-commercial use licence. // See LICENCE.txt for the full text of the licence. // // If LICENCE.txt is not included in this distribution // please email candc@it.usyd.edu.au to obtain a copy. #include <cctype> #include <cmath> #include <string> #include <vector> #include <iostream> #include <iomanip> #include <limits> using namespace std; #include "utils.h" #include "exception.h" #include "pool.h" #include "tree/feature.h" #include "tree/node.h" namespace NLP { namespace Tree { double DisjNode::viterbi(void){ if(outside != 0.0) return inside; double max_score = -numeric_limits<double>::max(); double score; ConjNode *node max_node; for(ConjNode *node = begin; node != end; ++node){ // use the inside field to record max node node->inside = 0.0; score = node->viterbi(); if(score > max_score){ max_score = score; max_node = node; } max_node->inside = -1.0; } outside = 1.0; inside = max_score; return max_score; } } }
20.392857
61
0.670753
[ "vector" ]
53c4a08c4725d679811420401510a9e5ac4d8016
2,528
cpp
C++
src/game/src/ec/entity_container.cpp
Sampas/cavez
b89185554477b92bf987c9e5d26b0a8abe1ae568
[ "MIT" ]
2
2019-03-11T11:26:52.000Z
2019-09-26T07:50:55.000Z
src/game/src/ec/entity_container.cpp
Sampas/cavez
b89185554477b92bf987c9e5d26b0a8abe1ae568
[ "MIT" ]
1
2020-10-29T15:44:47.000Z
2020-10-29T15:44:47.000Z
src/game/src/ec/entity_container.cpp
Sampas/cavez
b89185554477b92bf987c9e5d26b0a8abe1ae568
[ "MIT" ]
1
2020-10-28T18:56:46.000Z
2020-10-28T18:56:46.000Z
/// Copyright (c) 2019 Joni Louhela /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to /// deal in the Software without restriction, including without limitation the /// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or /// sell copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING /// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS /// IN THE SOFTWARE. #include "component_container.hpp" #include "entity_container.hpp" #include "logger/logger.hpp" // TODO set up for each entity, along with free namespace { void free_component(Component_container& component_container, const Component_id id, const std::size_t index) { switch (id) { case Component_id::physics: component_container.physics_components.free(index); break; case Component_id::render: component_container.render_components.free(index); break; default: LOG_WARN << "Unhandled free_component type : " << static_cast<std::underlying_type<Component_id>::type>(id); } } } // namespace Entity_container::Entity_container(Component_container& component_container) { std::size_t index = 0; for (auto& entity : m_container) { entity.second.set_free_function( [& container = m_container, index]() { container.free(index); }); entity.second.set_free_component_function( [&component_container](const Component_id id, const std::size_t index) { free_component(component_container, id, index); }); } } Entity& Entity_container::get_new_entity() { const auto res = m_container.get_free_elem(); auto& entity = res.second.get(); entity.set_id(m_next_free_id++); return entity; }
37.176471
84
0.698972
[ "render" ]
53c6fada54b38cf572d814034a3e29daf6b27ad7
6,115
cpp
C++
tools/editor/source/project/property.cpp
pixelballoon/pixelboost
085873310050ce62493df61142b7d4393795bdc2
[ "MIT" ]
6
2015-04-21T11:30:52.000Z
2020-04-29T00:10:04.000Z
tools/editor/source/project/property.cpp
pixelballoon/pixelboost
085873310050ce62493df61142b7d4393795bdc2
[ "MIT" ]
null
null
null
tools/editor/source/project/property.cpp
pixelballoon/pixelboost
085873310050ce62493df61142b7d4393795bdc2
[ "MIT" ]
null
null
null
#include "project/entity.h" #include "project/project.h" #include "project/property.h" #include "project/record.h" #include "project/struct.h" Property::Property(ProjectStruct* s, const SchemaProperty* schemaProperty) : _Struct(s) , _SchemaProperty(schemaProperty) { } Property::~Property() { } const SchemaProperty* Property::GetSchemaProperty() { return _SchemaProperty; } PropertyAtom* Property::AsAtom() { return 0; } const PropertyAtom* Property::AsAtom() const { return 0; } PropertyArray* Property::AsArray() { return 0; } const PropertyArray* Property::AsArray() const { return 0; } PropertyPointer* Property::AsPointer() { return 0; } const PropertyPointer* Property::AsPointer() const { return 0; } PropertyReference* Property::AsReference() { return 0; } const PropertyReference* Property::AsReference() const { return 0; } PropertyAtom::PropertyAtom(ProjectStruct* s, const SchemaProperty* schemaProperty) : Property(s, schemaProperty) { } PropertyAtom::~PropertyAtom() { } Property::PropertyType PropertyAtom::GetType() const { return kPropertyAtom; } PropertyAtom* PropertyAtom::AsAtom() { return this; } const PropertyAtom* PropertyAtom::AsAtom() const { return this; } void PropertyAtom::SetBoolValue(bool value) { _Value = value ? "1" : "0"; _Struct->propertyChanged(_Struct, this); } void PropertyAtom::SetFloatValue(float value) { char tmp[64]; snprintf(tmp, 64, "%f", value); _Value = tmp; _Struct->propertyChanged(_Struct, this); } void PropertyAtom::SetIntValue(int value) { char tmp[64]; snprintf(tmp, 64, "%d", value); _Value = tmp; _Struct->propertyChanged(_Struct, this); } void PropertyAtom::SetStringValue(const std::string& value) { _Value = value; _Struct->propertyChanged(_Struct, this); } bool PropertyAtom::GetBoolValue() const { return _Value == "1"; } float PropertyAtom::GetFloatValue() const { return atof(_Value.c_str()); } int PropertyAtom::GetIntValue() const { return atoi(_Value.c_str()); } const std::string& PropertyAtom::GetStringValue() const { return _Value; } PropertyPointer::PropertyPointer(ProjectStruct* s, const SchemaProperty* schemaProperty) : Property(s, schemaProperty) { } PropertyPointer::~PropertyPointer() { } Property::PropertyType PropertyPointer::GetType() const { return kPropertyPointer; } PropertyPointer* PropertyPointer::AsPointer() { return this; } const PropertyPointer* PropertyPointer::AsPointer() const { return this; } Uid PropertyPointer::GetPointerValue() const { return _Value; } void PropertyPointer::SetPointerValue(Uid uid) { _Value = uid; _Struct->propertyChanged(_Struct, this); } ProjectEntity* PropertyPointer::ResolvePointer() const { Project* project = _Struct->GetProject(); return project->GetEntity(_Value); } PropertyReference::PropertyReference(ProjectStruct* s, const SchemaProperty* schemaProperty) : Property(s, schemaProperty) { } PropertyReference::~PropertyReference() { } Property::PropertyType PropertyReference::GetType() const { return kPropertyReference; } PropertyReference* PropertyReference::AsReference() { return this; } const PropertyReference* PropertyReference::AsReference() const { return this; } Uid PropertyReference::GetReferenceValue() const { return _Value; } void PropertyReference::SetReferenceValue(Uid uid) { _Value = uid; _Struct->propertyChanged(_Struct, this); } ProjectRecord* PropertyReference::ResolveReference() const { Project* project = _Struct->GetProject(); return project->GetRecord(_Value); } PropertyArray::PropertyArray(ProjectStruct* s, const SchemaProperty* schemaProperty) : Property(s, schemaProperty) { } PropertyArray::~PropertyArray() { } Property::PropertyType PropertyArray::GetType() const { return kPropertyArray; } PropertyArray* PropertyArray::AsArray() { return this; } const PropertyArray* PropertyArray::AsArray() const { return this; } unsigned int PropertyArray::GetElementCount() const { return _ArrayElements.size(); } unsigned int PropertyArray::GetElementIdByIndex(unsigned int index) const { if (index < _ArrayElements.size()) return _ArrayElements[index]; return 0; } bool PropertyArray::DoesContainElement(unsigned int elementId) const { for (std::vector<unsigned int>::const_iterator it = _ArrayElements.begin(); it != _ArrayElements.end(); ++it) { if (*it == elementId) return true; } return false; } unsigned int PropertyArray::AddElement(unsigned int elementId) { if (elementId == 0) { elementId = rand(); while (DoesContainElement(elementId)) elementId = rand(); } _ArrayElements.push_back(elementId); _Struct->propertyChanged(_Struct, this); return elementId; } unsigned int PropertyArray::AddElementBeforeIndex(unsigned int index, unsigned int elementId) { if (elementId == 0) { elementId = rand(); while (DoesContainElement(elementId)) elementId = rand(); } std::vector<unsigned int>::iterator it = _ArrayElements.begin() + index; _ArrayElements.insert(it, elementId); _Struct->propertyChanged(_Struct, this); return elementId; } void PropertyArray::RemoveElementById(unsigned int elementId) { for (std::vector<unsigned int>::iterator it = _ArrayElements.begin(); it != _ArrayElements.end(); ++it) { if (*it == elementId) { _ArrayElements.erase(it); _Struct->propertyChanged(_Struct, this); return; } } } void PropertyArray::RemoveElementByIndex(unsigned int index) { if (index >= _ArrayElements.size()) return; std::vector<unsigned int>::iterator it = _ArrayElements.begin(); for (int i = 0; i < index; i++) it++; _ArrayElements.erase(it); _Struct->propertyChanged(_Struct, this); }
18.145401
113
0.680948
[ "vector" ]
53cc816929bd74f8fef77ad850056743982d2d88
16,190
cpp
C++
src/hsail_conformance/core/MemoryFenceTests.cpp
HSAFoundation/HSA-Conformance-Tests-PRM
1c383ba31c826a0745b4caba4903e51c4cb3c0d1
[ "Apache-2.0" ]
2
2017-05-22T17:21:19.000Z
2018-08-31T14:26:08.000Z
src/hsail_conformance/core/MemoryFenceTests.cpp
HSAFoundation/HSA-Conformance-Tests-PRM
1c383ba31c826a0745b4caba4903e51c4cb3c0d1
[ "Apache-2.0" ]
1
2017-07-01T08:56:55.000Z
2017-07-01T08:56:55.000Z
src/hsail_conformance/core/MemoryFenceTests.cpp
HSAFoundation/HSA-Conformance-Tests-PRM
1c383ba31c826a0745b4caba4903e51c4cb3c0d1
[ "Apache-2.0" ]
2
2018-03-09T09:13:21.000Z
2020-05-03T22:16:54.000Z
/* Copyright 2014-2015 Heterogeneous System Architecture (HSA) Foundation 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 "MemoryFenceTests.hpp" #include "BrigEmitter.hpp" #include "BasicHexlTests.hpp" #include "HCTests.hpp" #include "Brig.h" #include <sstream> namespace hsail_conformance { using namespace HSAIL_ASM; using namespace hexl; using namespace hexl::emitter; class MemoryFenceTest : public Test { public: MemoryFenceTest(Grid geometry_, BrigType type_, BrigMemoryOrder memoryOrder1_, BrigMemoryOrder memoryOrder2_, BrigSegment segment_, BrigMemoryScope memoryScope_) : Test(KERNEL, geometry_), type(type_), memoryOrder1(memoryOrder1_), memoryOrder2(memoryOrder2_), segment(segment_), memoryScope(memoryScope_), initialValue(0), s_label_skip_store("@skip_store"), s_label_skip_memfence("@skip_memfence"), globalVarName("global_var"), globalFlagName("global_flag") {} void Name(std::ostream& out) const { out << segment2str(segment) << "_" << type2str(type) << "/" << opcode2str(BRIG_OPCODE_ST) << "_" << opcode2str(BRIG_OPCODE_MEMFENCE) << "_" << memoryOrder2str(memoryOrder1) << "_" << memoryScope2str(memoryScope) << "__" << opcode2str(BRIG_OPCODE_LD) << "_" << opcode2str(BRIG_OPCODE_MEMFENCE) << "_" << memoryOrder2str(memoryOrder2) << "_" << memoryScope2str(memoryScope) << "/" << geometry; } protected: BrigType type; BrigMemoryOrder memoryOrder1; BrigMemoryOrder memoryOrder2; BrigSegment segment; BrigMemoryScope memoryScope; int64_t initialValue; std::string s_label_skip_store; std::string s_label_skip_memfence; std::string globalVarName; std::string globalFlagName; DirectiveVariable globalVar; DirectiveVariable globalFlag; Buffer input; TypedReg inputReg; BrigType ResultType() const { return type; } bool IsValid() const { if (cc->Profile() == BRIG_PROFILE_BASE && type == BRIG_TYPE_F64) return false; if (BRIG_SEGMENT_GROUP == segment && geometry->WorkgroupSize() != geometry->GridSize()) return false; if (BRIG_MEMORY_ORDER_SC_ACQUIRE == memoryOrder1) return false; if (BRIG_MEMORY_ORDER_SC_RELEASE == memoryOrder2) return false; return true; } virtual Value GetInputValueForWI(uint64_t wi) const { return Value(Brig2ValueType(type), 7); } Value ExpectedResult(uint64_t i) const { return Value(Brig2ValueType(type), 7); } void Init() { Test::Init(); input = kernel->NewBuffer("input", HOST_INPUT_BUFFER, Brig2ValueType(type), geometry->GridSize()); for (uint64_t i = 0; i < uint64_t(geometry->GridSize()); ++i) { input->AddData(GetInputValueForWI(i)); } } virtual void ModuleVariables() { switch (segment) { case BRIG_SEGMENT_GROUP: globalVarName = "group_var"; break; default: break; } globalVar = be.EmitVariableDefinition(globalVarName, segment, type); globalFlag = be.EmitVariableDefinition(globalFlagName, BRIG_SEGMENT_GLOBAL, be.PointerType()); if (segment != BRIG_SEGMENT_GROUP) { globalVar.init() = be.Immed(type, initialValue, false); } } void EmitInstrToTest(BrigOpcode opcode, BrigSegment seg, BrigType t, TypedReg reg, DirectiveVariable var) { OperandAddress globalVarAddr = be.Address(var); switch (opcode) { case BRIG_OPCODE_LD: be.EmitLoad(seg, t, reg->Reg(), globalVarAddr); break; case BRIG_OPCODE_ST: be.EmitStore(seg, t, reg->Reg(), globalVarAddr); break; default: assert(false); break; } } TypedReg Result() { TypedReg result = be.AddTReg(ResultType()); inputReg = be.AddTReg(type); input->EmitLoadData(inputReg); TypedReg wiID = be.EmitWorkitemFlatAbsId(true); be.EmitArith(BRIG_OPCODE_DIV, wiID, wiID, be.Wavesize()); TypedReg cReg = be.AddTReg(BRIG_TYPE_B1); uint64_t lastWaveFront = geometry->GridSize()/te->CoreCfg()->Wavesize() - 1; be.EmitCmp(cReg->Reg(), wiID, be.Immed(wiID->Type(), lastWaveFront), BRIG_COMPARE_NE); TypedReg flagReg = be.AddTReg(be.PointerType()); be.EmitCbr(cReg, s_label_skip_store); EmitInstrToTest(BRIG_OPCODE_ST, segment, type, inputReg, globalVar); be.EmitMov(flagReg, 1); be.EmitMemfence(memoryOrder1, memoryScope, memoryScope, BRIG_MEMORY_SCOPE_NONE); OperandAddress flagAddr = be.Address(globalFlag); be.EmitAtomic(NULL, flagAddr, flagReg, NULL, BRIG_ATOMIC_ST, BRIG_MEMORY_ORDER_RELAXED, be.AtomicMemoryScope(BRIG_MEMORY_SCOPE_SYSTEM, segment), BRIG_SEGMENT_GLOBAL); be.EmitBr(s_label_skip_memfence); be.EmitLabel(s_label_skip_store); TypedReg flagReg2 = be.AddTReg(be.PointerType()); be.EmitAtomic(flagReg2, flagAddr, NULL, NULL, BRIG_ATOMIC_LD, BRIG_MEMORY_ORDER_RELAXED, be.AtomicMemoryScope(BRIG_MEMORY_SCOPE_SYSTEM, segment), BRIG_SEGMENT_GLOBAL); be.EmitCmp(cReg->Reg(), flagReg2, be.Immed(flagReg2->Type(), 1), BRIG_COMPARE_NE); be.EmitCbr(cReg, s_label_skip_store); be.EmitMemfence(memoryOrder2, memoryScope, memoryScope, BRIG_MEMORY_SCOPE_NONE); be.EmitLabel(s_label_skip_memfence); EmitInstrToTest(BRIG_OPCODE_LD, segment, type, result, globalVar); return result; } }; class MemoryFenceArrayTest : public MemoryFenceTest { public: MemoryFenceArrayTest(Grid geometry_, BrigType type_, BrigMemoryOrder memoryOrder1_, BrigMemoryOrder memoryOrder2_, BrigSegment segment_, BrigMemoryScope memoryScope_) : MemoryFenceTest(geometry_, type_, memoryOrder1_, memoryOrder2_, segment_, memoryScope_) {} protected: Value ExpectedResult(uint64_t i) const { uint64_t val = geometry->GridSize()-i-1; ValueType valType = Brig2ValueType(type); switch (valType) { #ifdef MBUFFER_PASS_PLAIN_F16_AS_U32 case MV_PLAIN_FLOAT16: #endif case MV_FLOAT16: return Value(valType, H(hexl::half(float(val)))); case MV_FLOAT: return Value(float(val)); case MV_DOUBLE: return Value(double(val)); default: return Value(valType, val); } } void Init() { Test::Init(); } bool IsValid() const { if (!MemoryFenceTest::IsValid()) return false; if (BRIG_TYPE_F16 == type) return false; if (segment == BRIG_SEGMENT_GROUP) return false; return true; } virtual void ModuleVariables() { switch (segment) { case BRIG_SEGMENT_GROUP: globalVarName = "group_var"; break; default: break; } globalVar = be.EmitVariableDefinition(globalVarName, segment, elementType2arrayType(type), 0, geometry->GridSize()); globalFlag = be.EmitVariableDefinition(globalFlagName, BRIG_SEGMENT_GLOBAL, elementType2arrayType(be.PointerType()), 0, geometry->GridSize()); } void EmitVectorInstrToTest(BrigOpcode opcode, BrigType t, TypedReg reg, DirectiveVariable var, TypedReg offsetReg) { switch (opcode) { case BRIG_OPCODE_LD: be.EmitLoad(reg, var, offsetReg->Reg(), 0, true); break; case BRIG_OPCODE_ST: be.EmitStore(reg, var, offsetReg->Reg(), 0, true); break; default: assert(false); break; } } TypedReg Result() { TypedReg result = be.AddTReg(ResultType()); TypedReg wiID = be.EmitWorkitemFlatAbsId(te->CoreCfg()->IsLarge()); unsigned bytes = getBrigTypeNumBytes(type); unsigned pow = unsigned(std::log(bytes)/std::log(2)); TypedReg offsetReg = be.AddTReg(wiID->Type()); be.EmitArith(BRIG_OPCODE_SHL, offsetReg, wiID, be.Immed(BRIG_TYPE_U32, pow)); unsigned bytesFlag = getBrigTypeNumBytes(be.PointerType()); unsigned powFlag = unsigned(std::log(bytesFlag)/std::log(2)); TypedReg offsetFlagReg = be.AddTReg(wiID->Type()); be.EmitArith(BRIG_OPCODE_SHL, offsetFlagReg, wiID, be.Immed(BRIG_TYPE_U32, powFlag)); TypedReg wiID_ld = be.AddTReg(wiID->Type()); TypedReg offsetReg_ld = be.AddTReg(wiID->Type()); TypedReg offsetFlagReg_ld = be.AddTReg(wiID->Type()); be.EmitArith(BRIG_OPCODE_SUB, wiID_ld, be.Immed(wiID->Type(), geometry->GridSize()-1), wiID->Reg()); be.EmitArith(BRIG_OPCODE_SHL, offsetReg_ld, wiID_ld, be.Immed(BRIG_TYPE_U32, pow)); be.EmitArith(BRIG_OPCODE_SHL, offsetFlagReg_ld, wiID_ld, be.Immed(BRIG_TYPE_U32, powFlag)); TypedReg idReg = be.AddTReg(type); be.EmitCvtOrMov(idReg, wiID); EmitVectorInstrToTest(BRIG_OPCODE_ST, type, idReg, globalVar, offsetReg); be.EmitMemfence(memoryOrder1, memoryScope, memoryScope, BRIG_MEMORY_SCOPE_NONE); be.EmitAtomic(NULL, be.Address(globalFlag, offsetFlagReg->Reg(), 0), wiID, NULL, BRIG_ATOMIC_ST, BRIG_MEMORY_ORDER_RELAXED, be.AtomicMemoryScope(BRIG_MEMORY_SCOPE_SYSTEM, segment), BRIG_SEGMENT_GLOBAL); be.EmitLabel(s_label_skip_store); TypedReg flagReg2 = be.AddTReg(be.PointerType()); be.EmitAtomic(flagReg2, be.Address(globalFlag, offsetFlagReg_ld->Reg(), 0), NULL, NULL, BRIG_ATOMIC_LD, BRIG_MEMORY_ORDER_RELAXED, be.AtomicMemoryScope(BRIG_MEMORY_SCOPE_SYSTEM, segment), BRIG_SEGMENT_GLOBAL); TypedReg cReg = be.AddTReg(BRIG_TYPE_B1); be.EmitCmp(cReg->Reg(), flagReg2, wiID_ld->Reg(), BRIG_COMPARE_NE); be.EmitCbr(cReg, s_label_skip_store); be.EmitMemfence(memoryOrder2, memoryScope, memoryScope, BRIG_MEMORY_SCOPE_NONE); EmitVectorInstrToTest(BRIG_OPCODE_LD, type, result, globalVar, offsetReg_ld); return result; } }; class MemoryFenceCompoundTest : public MemoryFenceTest { protected: BrigType type2; BrigSegment segment2; Buffer input2; TypedReg inputReg2; DirectiveVariable globalVar2; public: MemoryFenceCompoundTest(Grid geometry_, BrigType type_, BrigType type2_, BrigMemoryOrder memoryOrder1_, BrigMemoryOrder memoryOrder2_, BrigSegment segment_, BrigSegment segment2_, BrigMemoryScope memoryScope_) : MemoryFenceTest(geometry_, type_, memoryOrder1_, memoryOrder2_, segment_, memoryScope_), type2(type2_), segment2(segment2_) {} void Name(std::ostream& out) const { out << segment2str(segment) << "_" << type2str(type) << "__" << segment2str(segment2) << "_" << type2str(type2) << "/" << opcode2str(BRIG_OPCODE_ST) << "_" << opcode2str(BRIG_OPCODE_MEMFENCE) << "_" << memoryOrder2str(memoryOrder1) << "_" << memoryScope2str(memoryScope) << "__" << opcode2str(BRIG_OPCODE_LD) << "_" << opcode2str(BRIG_OPCODE_MEMFENCE) << "_" << memoryOrder2str(memoryOrder2) << "_" << memoryScope2str(memoryScope) << "/" << geometry; } BrigType ResultType2() const { return type2; } bool IsValid() const { if (!MemoryFenceTest::IsValid()) return false; if (type != type2) return false; //if (isFloatType(type) || isFloatType(type2)) // return false; if (BRIG_SEGMENT_GROUP == segment2 && geometry->WorkgroupSize() != geometry->GridSize()) return false; return true; } //NB //NB Base profile requires FTZ, so test values for f32 and f64 should not include subnormal values //NB Value GetInputValueForWI(uint64_t wi) const override { uint64_t val = 7; if (cc->Profile() == BRIG_PROFILE_BASE) { // Avoid using subnormal values if (type == BRIG_TYPE_F16) val = 0x3C00; // 1.0h else if (type == BRIG_TYPE_F32) val = 0x3F800000; // 1.0f } return Value(Brig2ValueType(type), val); } Value GetInputValue2ForWI(uint64_t wi) const { uint64_t val = 3; if (cc->Profile() == BRIG_PROFILE_BASE) { // Avoid using subnormal values if (type == BRIG_TYPE_F16) val = 0x4000; // 2.0h else if (type == BRIG_TYPE_F32) val = 0x40000000; // 2.0f } return Value(Brig2ValueType(type), val); } Value ExpectedResult(uint64_t i) const { uint64_t val = 10; if (cc->Profile() == BRIG_PROFILE_BASE) { if (type == BRIG_TYPE_F16) val = 0x4200; // 3.0h else if (type == BRIG_TYPE_F32) val = 0x40400000; // 3.0f } return Value(Brig2ValueType(type), val); } void Init() { MemoryFenceTest::Init(); input2 = kernel->NewBuffer("input2", HOST_INPUT_BUFFER, Brig2ValueType(type2), geometry->GridSize()); for (uint64_t i = 0; i < uint64_t(geometry->GridSize()); ++i) { input2->AddData(GetInputValue2ForWI(i)); } } void ModuleVariables() { MemoryFenceTest::ModuleVariables(); std::string globalVarName = "global_var_2"; switch (segment2) { case BRIG_SEGMENT_GROUP: globalVarName = "group_var_2"; break; default: break; } globalVar2 = be.EmitVariableDefinition(globalVarName, segment2, type2); if (segment2 != BRIG_SEGMENT_GROUP) globalVar2.init() = be.Immed(type2, initialValue, false); } TypedReg Result() { TypedReg result = be.AddTReg(ResultType()); TypedReg result2 = be.AddTReg(ResultType2()); inputReg = be.AddTReg(type); inputReg2 = be.AddTReg(type2); input->EmitLoadData(inputReg); input2->EmitLoadData(inputReg2); TypedReg wiID = be.EmitWorkitemFlatAbsId(true); be.EmitArith(BRIG_OPCODE_DIV, wiID, wiID, be.Wavesize()); TypedReg cReg = be.AddTReg(BRIG_TYPE_B1); uint64_t lastWaveFront = geometry->GridSize()/te->CoreCfg()->Wavesize() - 1; be.EmitCmp(cReg->Reg(), wiID, be.Immed(wiID->Type(), lastWaveFront), BRIG_COMPARE_NE); TypedReg flagReg = be.AddTReg(be.PointerType()); be.EmitCbr(cReg, s_label_skip_store); EmitInstrToTest(BRIG_OPCODE_ST, segment, type, inputReg, globalVar); EmitInstrToTest(BRIG_OPCODE_ST, segment2, type2, inputReg2, globalVar2); be.EmitMov(flagReg, 1); be.EmitMemfence(memoryOrder1, memoryScope, memoryScope, BRIG_MEMORY_SCOPE_NONE); OperandAddress flagAddr = be.Address(globalFlag); be.EmitAtomic(NULL, flagAddr, flagReg, NULL, BRIG_ATOMIC_ST, BRIG_MEMORY_ORDER_RELAXED, be.AtomicMemoryScope(BRIG_MEMORY_SCOPE_SYSTEM, segment), BRIG_SEGMENT_GLOBAL); be.EmitBr(s_label_skip_memfence); be.EmitLabel(s_label_skip_store); TypedReg flagReg2 = be.AddTReg(be.PointerType()); be.EmitAtomic(flagReg2, flagAddr, NULL, NULL, BRIG_ATOMIC_LD, BRIG_MEMORY_ORDER_RELAXED, be.AtomicMemoryScope(BRIG_MEMORY_SCOPE_SYSTEM, segment), BRIG_SEGMENT_GLOBAL); be.EmitCmp(cReg->Reg(), flagReg2, be.Immed(flagReg2->Type(), 1), BRIG_COMPARE_NE); be.EmitCbr(cReg, s_label_skip_store); be.EmitMemfence(memoryOrder2, memoryScope, memoryScope, BRIG_MEMORY_SCOPE_NONE); be.EmitLabel(s_label_skip_memfence); EmitInstrToTest(BRIG_OPCODE_LD, segment, type, result, globalVar); EmitInstrToTest(BRIG_OPCODE_LD, segment2, type2, result2, globalVar2); TypedReg result1 = be.AddTReg(type); be.EmitCvtOrMov(result1, result2); if (cc->Profile() == BRIG_PROFILE_FULL) { be.EmitArith(BRIG_OPCODE_ADD, result, result->Reg(), result1->Reg()); } else { // ftz and default rounding are required for Base profile be.EmitArithBase(BRIG_OPCODE_ADD, result, result->Reg(), result1->Reg()); } return result; } }; void MemoryFenceTests::Iterate(TestSpecIterator& it) { CoreConfig* cc = CoreConfig::Get(context); Arena* ap = cc->Ap(); TestForEach<MemoryFenceTest>(ap, it, "memfence/basic", cc->Grids().MemfenceSet(), cc->Types().Memfence(), cc->Memory().MemfenceMemoryOrders(), cc->Memory().MemfenceMemoryOrders(), cc->Memory().MemfenceSegments(), cc->Memory().MemfenceMemoryScopes()); TestForEach<MemoryFenceArrayTest>(ap, it, "memfence/array", cc->Grids().MemfenceSet(), cc->Types().Memfence(), cc->Memory().MemfenceMemoryOrders(), cc->Memory().MemfenceMemoryOrders(), cc->Memory().MemfenceSegments(), cc->Memory().MemfenceMemoryScopes()); TestForEach<MemoryFenceCompoundTest>(ap, it, "memfence/compound", cc->Grids().MemfenceSet(), cc->Types().Memfence(), cc->Types().Memfence(), cc->Memory().MemfenceMemoryOrders(), cc->Memory().MemfenceMemoryOrders(), cc->Memory().MemfenceSegments(), cc->Memory().MemfenceSegments(), cc->Memory().MemfenceMemoryScopes()); } }
42.051948
320
0.714392
[ "geometry" ]