hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
a018bdf1a7bf6325df518c8134d16e5575c93d20
3,329
cpp
C++
automated-tests/src/dali/utc-Dali-Semaphore.cpp
dalihub/dali-core
f9b1a5a637bbc91de4aaf9e0be9f79cba0bbb195
[ "Apache-2.0", "BSD-3-Clause" ]
21
2016-11-18T10:26:40.000Z
2021-11-02T09:46:15.000Z
automated-tests/src/dali/utc-Dali-Semaphore.cpp
dalihub/dali-core
f9b1a5a637bbc91de4aaf9e0be9f79cba0bbb195
[ "Apache-2.0", "BSD-3-Clause" ]
7
2016-10-18T17:39:12.000Z
2020-12-01T11:45:36.000Z
automated-tests/src/dali/utc-Dali-Semaphore.cpp
dalihub/dali-core
f9b1a5a637bbc91de4aaf9e0be9f79cba0bbb195
[ "Apache-2.0", "BSD-3-Clause" ]
16
2017-03-08T15:50:32.000Z
2021-05-24T06:58:10.000Z
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <dali-test-suite-utils.h> #include <dali/devel-api/threading/semaphore.h> #include <dali/public-api/dali-core.h> #include <algorithm> #include <chrono> #include <future> #include <stdexcept> #include <thread> int UtcDaliSemaphoreTryAcquire(void) { using namespace std::chrono_literals; constexpr auto waitTime{100ms}; tet_infoline("Testing Dali::Semaphore try acquire methods"); Dali::Semaphore<3> sem(0); DALI_TEST_EQUALS(false, sem.TryAcquire(), TEST_LOCATION); DALI_TEST_EQUALS(false, sem.TryAcquireFor(waitTime), TEST_LOCATION); DALI_TEST_EQUALS(false, sem.TryAcquireUntil(std::chrono::system_clock::now() + waitTime), TEST_LOCATION); sem.Release(3); DALI_TEST_EQUALS(true, sem.TryAcquire(), TEST_LOCATION); DALI_TEST_EQUALS(true, sem.TryAcquireFor(waitTime), TEST_LOCATION); DALI_TEST_EQUALS(true, sem.TryAcquireUntil(std::chrono::system_clock::now() + waitTime), TEST_LOCATION); DALI_TEST_EQUALS(false, sem.TryAcquire(), TEST_LOCATION); DALI_TEST_EQUALS(false, sem.TryAcquireFor(waitTime), TEST_LOCATION); DALI_TEST_EQUALS(false, sem.TryAcquireUntil(std::chrono::system_clock::now() + waitTime), TEST_LOCATION); END_TEST; } int UtcDaliSemaphoreInvalidArguments(void) { tet_infoline("Testing Dali::Semaphore invalid arguments"); Dali::Semaphore<2> sem(0); DALI_TEST_THROWS(sem.Release(3), std::invalid_argument); DALI_TEST_THROWS(sem.Release(-1), std::invalid_argument); sem.Release(1); DALI_TEST_THROWS(sem.Release(2), std::invalid_argument); sem.Release(1); DALI_TEST_THROWS(sem.Release(1), std::invalid_argument); DALI_TEST_THROWS(Dali::Semaphore<1>(2), std::invalid_argument); DALI_TEST_THROWS(Dali::Semaphore<>(-1), std::invalid_argument); END_TEST; } int UtcDaliSemaphoreAcquire(void) { tet_infoline("Testing Dali::Semaphore multithread acquire"); using namespace std::chrono_literals; constexpr std::ptrdiff_t numTasks{2}; auto f = [](Dali::Semaphore<numTasks>& sem, bool& flag) { sem.Acquire(); flag = true; }; auto flag1{false}, flag2{false}; Dali::Semaphore<numTasks> sem(0); auto fut1 = std::async(std::launch::async, f, std::ref(sem), std::ref(flag1)); auto fut2 = std::async(std::launch::async, f, std::ref(sem), std::ref(flag2)); DALI_TEST_EQUALS(std::future_status::timeout, fut1.wait_for(100ms), TEST_LOCATION); DALI_TEST_EQUALS(std::future_status::timeout, fut2.wait_for(100ms), TEST_LOCATION); DALI_TEST_EQUALS(false, flag1, TEST_LOCATION); DALI_TEST_EQUALS(false, flag2, TEST_LOCATION); sem.Release(numTasks); fut1.wait(); DALI_TEST_EQUALS(true, flag1, TEST_LOCATION); fut2.wait(); DALI_TEST_EQUALS(true, flag2, TEST_LOCATION); END_TEST; }
32.637255
107
0.73836
dalihub
a022d0a4a0cfeef4a021d4159ed2cdccfc0136df
3,508
cpp
C++
libs/GFX/Events.cpp
KillianG/R-Type
e3fd801ae58fcea49ac75c400ec0a2837cb0da2e
[ "MIT" ]
1
2019-08-14T12:31:50.000Z
2019-08-14T12:31:50.000Z
libs/GFX/Events.cpp
KillianG/R-Type
e3fd801ae58fcea49ac75c400ec0a2837cb0da2e
[ "MIT" ]
null
null
null
libs/GFX/Events.cpp
KillianG/R-Type
e3fd801ae58fcea49ac75c400ec0a2837cb0da2e
[ "MIT" ]
null
null
null
// // Created by killian on 13/11/18. // Epitech 3 years remaining // See http://github.com/KillianG // #include <SFML/Window/Event.hpp> #include "Events.hpp" #include <iostream> /** * simple constructor * @param mgr eventmanager */ gfx::Event::Event(EventManager &mgr) : _mgr(mgr){ } /** * get all events using sfml poll event * @param window the window where the events come from */ void gfx::Event::getEvents(std::shared_ptr<sf::RenderWindow> window) { sf::Event event; while (window->pollEvent(event)) { if (event.type == sf::Event::KeyReleased) { if (event.key.code == sf::Keyboard::Space) this->_mgr.emit<gfx::KeyReleasedEvent>(std::forward<std::string>("Space")); } if (event.type == sf::Event::MouseButtonPressed) this->_mgr.emit<gfx::ClickEvent>(std::forward<gfx::Vector2I>({event.mouseButton.x, event.mouseButton.y})); if (event.type == sf::Event::MouseButtonReleased) this->_mgr.emit<gfx::MouseReleaseEvent>( std::forward<gfx::Vector2I>({event.mouseButton.x, event.mouseButton.y})); if (event.type == sf::Event::MouseMoved) this->_mgr.emit<gfx::MouseMoveEvent>(std::forward<gfx::Vector2I>({event.mouseMove.x, event.mouseMove.y})); if (event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::Space) this->_mgr.emit<gfx::KeyPressedEvent>(std::forward<std::string>("Space")); if (event.key.code == sf::Keyboard::Escape) this->_mgr.emit<gfx::KeyPressedEvent>(std::forward<std::string>("Escape")); } if (event.type == sf::Event::TextEntered) { std::string str = ""; if (event.text.unicode == 8) this->_mgr.emit<gfx::InputEvent>(); else { sf::Utf32::encodeAnsi(event.text.unicode, std::back_inserter(str), 'e'); for (auto a : str) { if (!std::isalnum(a) && a != '.') return; } this->_mgr.emit<gfx::InputEvent>(std::forward<std::string>(str)); } } } } /** * simple constructor for clickevent * @param pos the position */ gfx::ClickEvent::ClickEvent(gfx::Vector2I pos) : pos(pos) {} /** * getter for position of clickevent * @return */ const gfx::Vector2I gfx::ClickEvent::getPosition() const { return this->pos; } const gfx::Vector2I gfx::MouseMoveEvent::getPosition() const { return this->pos; } gfx::MouseMoveEvent::MouseMoveEvent(gfx::Vector2I pos) : pos(pos) {} gfx::MouseReleaseEvent::MouseReleaseEvent(gfx::Vector2I pos) : pos(pos) { } const gfx::Vector2I gfx::MouseReleaseEvent::getPosition() const { return this->pos; } gfx::KeyPressedEvent::KeyPressedEvent(std::string key) { this->key = key; } const std::string &gfx::KeyPressedEvent::getKey() const { return this->key; } gfx::KeyReleasedEvent::KeyReleasedEvent(std::string key) { this->key = key; } const std::string &gfx::KeyReleasedEvent::getKey() const { return this->key; } std::string gfx::InputEvent::input = ""; gfx::InputEvent::InputEvent() { if (gfx::InputEvent::input.size() > 0) gfx::InputEvent::input.pop_back(); } gfx::InputEvent::InputEvent(std::string input) { gfx::InputEvent::input += input; } std::string gfx::InputEvent::clear() { std::string copy = gfx::InputEvent::input; gfx::InputEvent::input.clear(); return copy; }
29.233333
118
0.608609
KillianG
a025b6636c624c0382da02eca001cd939cf62860
1,526
cpp
C++
src/RE/NiSystem.cpp
powerof3/CommonLibVR
c84cd2c63ccba0cc88a212fe9cf86b5470b10a4f
[ "MIT" ]
6
2020-04-05T04:37:42.000Z
2022-03-19T17:42:24.000Z
src/RE/NiSystem.cpp
kassent/CommonLibSSE
394231b44ba01925fef9d01ea2b0b29c2fff601c
[ "MIT" ]
3
2021-11-08T09:31:20.000Z
2022-03-02T19:22:42.000Z
src/RE/NiSystem.cpp
kassent/CommonLibSSE
394231b44ba01925fef9d01ea2b0b29c2fff601c
[ "MIT" ]
6
2020-04-10T18:11:46.000Z
2022-01-18T22:31:25.000Z
#include "RE/NiSystem.h" #include <cassert> #include <cstdarg> namespace RE { int NiMemcpy(void* a_dest, std::size_t a_destSize, const void* a_src, std::size_t a_count) { auto result = memcpy_s(a_dest, a_destSize, a_src, a_count); assert(result == 0); return result; } int NiSprintf(char* a_dest, std::size_t a_destSize, const char* a_format, ...) { assert(a_format); std::va_list kArgs; va_start(kArgs, a_format); auto ret = NiVsprintf(a_dest, a_destSize, a_format, kArgs); va_end(kArgs); return ret; } char* NiStrcat(char* a_dest, std::size_t a_destSize, const char* a_src) { strcat_s(a_dest, a_destSize, a_src); return a_dest; } char* NiStrncpy(char* a_dest, std::size_t a_destSize, const char* a_src, std::size_t a_count) { strncpy_s(a_dest, a_destSize, a_src, a_count); return a_dest; } int NiVsnprintf(char* a_dest, std::size_t a_destSize, std::size_t a_count, const char* a_format, std::va_list a_args) { if (a_destSize == 0) { return 0; } assert(a_dest); assert(a_count < a_destSize || a_count == NI_TRUNCATE); assert(a_format); a_dest[0] = '\0'; bool truncate = (a_count == NI_TRUNCATE); auto result = vsnprintf_s(a_dest, a_destSize, a_count, a_format, a_args); if (result < -1 && !truncate) { result = static_cast<int>(a_count); } return result; } int NiVsprintf(char* a_dest, std::size_t a_destSize, const char* a_format, std::va_list a_args) { return NiVsnprintf(a_dest, a_destSize, NI_TRUNCATE, a_format, a_args); } }
20.90411
118
0.690039
powerof3
a0260a48557c2be356124c61a0598f764425b6e0
1,899
cpp
C++
docs/trainings/random-trainings/18th-SHU-CPC/solutions/i.cpp
Dup4/TI1050
4534909ef9a3b925d556d341ea5e2629357f68e6
[ "MIT" ]
null
null
null
docs/trainings/random-trainings/18th-SHU-CPC/solutions/i.cpp
Dup4/TI1050
4534909ef9a3b925d556d341ea5e2629357f68e6
[ "MIT" ]
null
null
null
docs/trainings/random-trainings/18th-SHU-CPC/solutions/i.cpp
Dup4/TI1050
4534909ef9a3b925d556d341ea5e2629357f68e6
[ "MIT" ]
1
2022-03-03T13:33:48.000Z
2022-03-03T13:33:48.000Z
#include <bits/stdc++.h> using namespace std; using ll = long long; #define SZ(x) (int(x.size())) const int N = 1e3 + 10, mod = 1e9 + 7; int n, m, v[N], fac[N], inv[N], bit[N], fbit[N]; ll f[N][N]; char s[N]; ll qpow(ll base, ll n) { ll res = 1; while (n) { if (n & 1) res = res * base % mod; base = base * base % mod; n >>= 1; } return res; } ll C(int n, int m) { return 1ll * fac[n] * inv[m] % mod * inv[n - m] % mod; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); fac[0] = 1; for (int i = 1; i < N; ++i) fac[i] = 1ll * fac[i - 1] * i % mod; inv[N - 1] = qpow(fac[N - 1], mod - 2); for (int i = N - 1; i >= 1; --i) inv[i - 1] = 1ll * inv[i] * i % mod; bit[0] = 1; for (int i = 1; i < N; ++i) bit[i] = 1ll * bit[i - 1] * 26 % mod; fbit[0] = 1; fbit[1] = qpow(26, mod - 2); for (int i = 2; i < N; ++i) fbit[i] = 1ll * fbit[i - 1] * fbit[1] % mod; f[0][0] = 1; for (int i = 1; i < N; ++i) { for (int j = 0; j <= i; ++j) { if (!j) { f[i][j] += f[i - 1][0] + f[i - 1][1]; f[i][j] %= mod; } else if (j < i) { f[i][j] += f[i - 1][j - 1] * 26 + f[i - 1][j + 1]; f[i][j] %= mod; } else if (j == i) { f[i][j] += f[i - 1][j - 1] * 26 % mod; f[i][j] %= mod; } } } cin >> n >> m; vector<string> vec(n + 1); for (int i = 1; i <= n; ++i) cin >> vec[i] >> v[i]; ll res = 0; for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { int len = SZ(vec[j]); if (i >= len) { res += f[m][i] * (i - len + 1) % mod * v[j] % mod * fbit[len] % mod; res %= mod; } } } printf("%lld\n", res); return 0; }
27.521739
84
0.360716
Dup4
a0299759b45b07ad5685d744d2c8a237742b8213
9,030
cpp
C++
cli/tests/DistributedCommandExecutorTestRunner.cpp
yuanchenl/quickstep
cc20fed6e56b0e583ae15a0219c070c8bacf14ba
[ "Apache-2.0" ]
1
2021-08-22T19:16:59.000Z
2021-08-22T19:16:59.000Z
cli/tests/DistributedCommandExecutorTestRunner.cpp
udippant/incubator-quickstep
8169306c2923d68235ba3c0c8df4c53f5eee9a68
[ "Apache-2.0" ]
null
null
null
cli/tests/DistributedCommandExecutorTestRunner.cpp
udippant/incubator-quickstep
8169306c2923d68235ba3c0c8df4c53f5eee9a68
[ "Apache-2.0" ]
1
2021-11-30T13:50:59.000Z
2021-11-30T13:50:59.000Z
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ #include "cli/tests/DistributedCommandExecutorTestRunner.hpp" #include <cstdio> #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include "catalog/CatalogTypedefs.hpp" #include "cli/CommandExecutorUtil.hpp" #include "cli/Constants.hpp" #include "cli/DropRelation.hpp" #include "cli/PrintToScreen.hpp" #include "parser/ParseStatement.hpp" #include "query_execution/BlockLocator.hpp" #include "query_execution/BlockLocatorUtil.hpp" #include "query_execution/ForemanDistributed.hpp" #include "query_execution/QueryExecutionTypedefs.hpp" #include "query_execution/QueryExecutionUtil.hpp" #include "query_optimizer/Optimizer.hpp" #include "query_optimizer/OptimizerContext.hpp" #include "query_optimizer/QueryHandle.hpp" #include "query_optimizer/tests/TestDatabaseLoader.hpp" #include "storage/DataExchangerAsync.hpp" #include "storage/StorageManager.hpp" #include "utility/MemStream.hpp" #include "utility/SqlError.hpp" #include "glog/logging.h" #include "tmb/id_typedefs.h" #include "tmb/message_bus.h" #include "tmb/tagged_message.h" using std::make_unique; using std::string; using std::vector; using tmb::TaggedMessage; namespace quickstep { class CatalogRelation; namespace C = cli; const char *DistributedCommandExecutorTestRunner::kResetOption = "reset_before_execution"; DistributedCommandExecutorTestRunner::DistributedCommandExecutorTestRunner(const string &storage_path) : query_id_(0) { bus_.Initialize(); cli_id_ = bus_.Connect(); bus_.RegisterClientAsSender(cli_id_, kAdmitRequestMessage); bus_.RegisterClientAsSender(cli_id_, kPoisonMessage); bus_.RegisterClientAsReceiver(cli_id_, kQueryExecutionSuccessMessage); bus_.RegisterClientAsSender(cli_id_, kBlockDomainRegistrationMessage); bus_.RegisterClientAsReceiver(cli_id_, kBlockDomainRegistrationResponseMessage); block_locator_ = make_unique<BlockLocator>(&bus_); block_locator_->start(); test_database_loader_ = make_unique<optimizer::TestDatabaseLoader>( storage_path, block_locator::getBlockDomain( test_database_loader_data_exchanger_.network_address(), cli_id_, &locator_client_id_, &bus_), locator_client_id_, &bus_); DCHECK_EQ(block_locator_->getBusClientID(), locator_client_id_); test_database_loader_data_exchanger_.set_storage_manager(test_database_loader_->storage_manager()); test_database_loader_data_exchanger_.start(); test_database_loader_->createTestRelation(false /* allow_vchar */); test_database_loader_->loadTestRelation(); // NOTE(zuyu): Foreman should initialize before Shiftboss so that the former // could receive a registration message from the latter. foreman_ = make_unique<ForemanDistributed>(*block_locator_, &bus_, test_database_loader_->catalog_database(), nullptr /* query_processor */); foreman_->start(); // We don't use the NUMA aware version of worker code. const vector<numa_node_id> numa_nodes(1 /* Number of worker threads per instance */, kAnyNUMANodeID); bus_local_.Initialize(); worker_ = make_unique<Worker>(0 /* worker_thread_index */, &bus_local_); const vector<tmb::client_id> worker_client_ids(1, worker_->getBusClientID()); worker_directory_ = make_unique<WorkerDirectory>(worker_client_ids.size(), worker_client_ids, numa_nodes); storage_manager_ = make_unique<StorageManager>( storage_path, block_locator::getBlockDomain( data_exchanger_.network_address(), cli_id_, &locator_client_id_, &bus_), locator_client_id_, &bus_); DCHECK_EQ(block_locator_->getBusClientID(), locator_client_id_); data_exchanger_.set_storage_manager(storage_manager_.get()); shiftboss_ = make_unique<Shiftboss>(&bus_, &bus_local_, storage_manager_.get(), worker_directory_.get(), storage_manager_->hdfs()); data_exchanger_.start(); shiftboss_->start(); worker_->start(); } DistributedCommandExecutorTestRunner::~DistributedCommandExecutorTestRunner() { const tmb::MessageBus::SendStatus send_status = QueryExecutionUtil::SendTMBMessage(&bus_, cli_id_, foreman_->getBusClientID(), TaggedMessage(kPoisonMessage)); CHECK(send_status == tmb::MessageBus::SendStatus::kOK); worker_->join(); shiftboss_->join(); foreman_->join(); test_database_loader_data_exchanger_.shutdown(); test_database_loader_.reset(); data_exchanger_.shutdown(); storage_manager_.reset(); CHECK(MessageBus::SendStatus::kOK == QueryExecutionUtil::SendTMBMessage(&bus_, cli_id_, locator_client_id_, TaggedMessage(kPoisonMessage))); test_database_loader_data_exchanger_.join(); data_exchanger_.join(); block_locator_->join(); } void DistributedCommandExecutorTestRunner::runTestCase( const string &input, const std::set<string> &options, string *output) { // TODO(qzeng): Test multi-threaded query execution when we have a Sort operator. VLOG(4) << "Test SQL(s): " << input; if (options.find(kResetOption) != options.end()) { test_database_loader_->clear(); test_database_loader_->createTestRelation(false /* allow_vchar */); test_database_loader_->loadTestRelation(); } MemStream output_stream; sql_parser_.feedNextBuffer(new string(input)); while (true) { ParseResult result = sql_parser_.getNextStatement(); if (result.condition != ParseResult::kSuccess) { if (result.condition == ParseResult::kError) { *output = result.error_message; } break; } const ParseStatement &parse_statement = *result.parsed_statement; std::printf("%s\n", parse_statement.toString().c_str()); try { if (parse_statement.getStatementType() == ParseStatement::kCommand) { const ParseCommand &command = static_cast<const ParseCommand &>(parse_statement); const PtrVector<ParseString> &arguments = *(command.arguments()); const string &command_str = command.command()->value(); string command_response; if (command_str == C::kDescribeDatabaseCommand) { command_response = C::ExecuteDescribeDatabase(arguments, *test_database_loader_->catalog_database()); } else if (command_str == C::kDescribeTableCommand) { if (arguments.empty()) { command_response = C::ExecuteDescribeDatabase(arguments, *test_database_loader_->catalog_database()); } else { command_response = C::ExecuteDescribeTable(arguments, *test_database_loader_->catalog_database()); } } else { THROW_SQL_ERROR_AT(command.command()) << "Unsupported command"; } std::fprintf(output_stream.file(), "%s", command_response.c_str()); } else { optimizer::OptimizerContext optimizer_context; auto query_handle = std::make_unique<QueryHandle>(query_id_++, cli_id_); optimizer_.generateQueryHandle(parse_statement, test_database_loader_->catalog_database(), &optimizer_context, query_handle.get()); const CatalogRelation *query_result_relation = query_handle->getQueryResultRelation(); QueryExecutionUtil::ConstructAndSendAdmitRequestMessage( cli_id_, foreman_->getBusClientID(), query_handle.release(), &bus_); const tmb::AnnotatedMessage annotated_message = bus_.Receive(cli_id_, 0, true); DCHECK_EQ(kQueryExecutionSuccessMessage, annotated_message.tagged_message.message_type()); if (query_result_relation) { PrintToScreen::PrintRelation(*query_result_relation, test_database_loader_->storage_manager(), output_stream.file()); DropRelation::Drop(*query_result_relation, test_database_loader_->catalog_database(), test_database_loader_->storage_manager()); } } } catch (const SqlError &error) { *output = error.formatMessage(input); break; } } if (output->empty()) { *output = output_stream.str(); } } } // namespace quickstep
37.782427
116
0.716058
yuanchenl
a03043f317c61138818e4ae9d2c0ee66ca4487e6
28,037
cpp
C++
source/slang/slang-check-constraint.cpp
JKot-Coder/slang
1a1b2a0de67dccc1102449b8620830131d569cde
[ "MIT" ]
895
2017-06-10T13:38:39.000Z
2022-03-31T02:29:15.000Z
source/slang/slang-check-constraint.cpp
JKot-Coder/slang
1a1b2a0de67dccc1102449b8620830131d569cde
[ "MIT" ]
708
2017-06-15T16:03:12.000Z
2022-03-28T19:01:37.000Z
source/slang/slang-check-constraint.cpp
JKot-Coder/slang
1a1b2a0de67dccc1102449b8620830131d569cde
[ "MIT" ]
80
2017-06-12T15:36:58.000Z
2022-03-23T12:04:24.000Z
// slang-check-constraint.cpp #include "slang-check-impl.h" // This file provides the core services for creating // and solving constraint systems during semantic checking. // // We currently use constraint systems primarily to solve // for the implied values to use for generic parameters when a // generic declaration is being applied without explicit // generic arguments. // // Conceptually, our constraint-solving strategy starts by // trying to "unify" the actual argument types to a call // with the parameter types of the callee (which may mention // generic parameters). E.g., if we have a situation like: // // void doIt<T>(T a, vector<T,3> b); // // int x, y; // ... // doIt(x, y); // // then an we would try to unify the type of the argument // `x` (which is `int`) with the type of the parameter `a` // (which is `T`). Attempting to unify a concrete type // and a generic type parameter would (in the simplest case) // give rise to a constraint that, e.g., `T` must be `int`. // // In our example, unifying `y` and `b` creates a more complex // scenario, because we cannot ever unify `int` with `vector<T,3>`; // there is no possible value of `T` for which those two types // are equivalent. // // So instead of the simpler approach to unification (which // works well for languages without implicit type conversion), // our approach to unification recognizes that scalar types // can be promoted to vectors, and thus tries to unify the // type of `y` with the element type of `b`. // // When it comes time to actually solve the constraints, we // might have seemingly conflicting constraints: // // void another<U>(U a, U b); // // float x; int y; // another(x, y); // // In this case we'd have constraints that `U` must be `int`, // *and* that `U` must be `float`, which is clearly impossible // to satisfy. Instead, our constraints are treated as a kind // of "lower bound" on the type variable, and we combine // those lower bounds using the "join" operation (in the // sense of "meet" and "join" on lattices), which ideally // gives us a type for `U` that all the argument types can // convert to. namespace Slang { Type* SemanticsVisitor::TryJoinVectorAndScalarType( VectorExpressionType* vectorType, BasicExpressionType* scalarType) { // Join( vector<T,N>, S ) -> vetor<Join(T,S), N> // // That is, the join of a vector and a scalar type is // a vector type with a joined element type. auto joinElementType = TryJoinTypes( vectorType->elementType, scalarType); if(!joinElementType) return nullptr; return createVectorType( joinElementType, vectorType->elementCount); } Type* SemanticsVisitor::TryJoinTypeWithInterface( Type* type, DeclRef<InterfaceDecl> interfaceDeclRef) { // The most basic test here should be: does the type declare conformance to the trait. if(isDeclaredSubtype(type, interfaceDeclRef)) return type; // Just because `type` doesn't conform to the given `interfaceDeclRef`, that // doesn't necessarily indicate a failure. It is possible that we have a call // like `sqrt(2)` so that `type` is `int` and `interfaceDeclRef` is // `__BuiltinFloatingPointType`. The "obvious" answer is that we should infer // the type `float`, but it seems like the compiler would have to synthesize // that answer from thin air. // // A robsut/correct solution here might be to enumerate set of types types `S` // such that for each type `X` in `S`: // // * `type` is implicitly convertible to `X` // * `X` conforms to the interface named by `interfaceDeclRef` // // If the set `S` is non-empty then we would try to pick the "best" type from `S`. // The "best" type would be a type `Y` such that `Y` is implicitly convertible to // every other type in `S`. // // We are going to implement a much simpler strategy for now, where we only apply // the search process if `type` is a builtin scalar type, and then we only search // through types `X` that are also builtin scalar types. // Type* bestType = nullptr; if(auto basicType = dynamicCast<BasicExpressionType>(type)) { for(Int baseTypeFlavorIndex = 0; baseTypeFlavorIndex < Int(BaseType::CountOf); baseTypeFlavorIndex++) { // Don't consider `type`, since we already know it doesn't work. if(baseTypeFlavorIndex == Int(basicType->baseType)) continue; // Look up the type in our session. auto candidateType = type->getASTBuilder()->getBuiltinType(BaseType(baseTypeFlavorIndex)); if(!candidateType) continue; // We only want to consider types that implement the target interface. if(!isDeclaredSubtype(candidateType, interfaceDeclRef)) continue; // We only want to consider types where we can implicitly convert from `type` if(!canConvertImplicitly(candidateType, type)) continue; // At this point, we have a candidate type that is usable. // // If this is our first viable candidate, then it is our best one: // if(!bestType) { bestType = candidateType; } else { // Otherwise, we want to pick the "better" type between `candidateType` // and `bestType`. // // We are going to be a bit loose here, and not worry about the // case where conversion is allowed in both directions. // // TODO: make this completely robust. // if(canConvertImplicitly(bestType, candidateType)) { // Our candidate can convert to the current "best" type, so // it is logically a more specific type that satisfies our // constraints, therefore we should keep it. // bestType = candidateType; } } } if(bestType) return bestType; } // For all other cases, we will just bail out for now. // // TODO: In the future we should build some kind of side data structure // to accelerate either one or both of these queries: // // * Given a type `T`, what types `U` can it convert to implicitly? // // * Given an interface `I`, what types `U` conform to it? // // The intersection of the sets returned by these two queries is // the set of candidates we would like to consider here. return nullptr; } Type* SemanticsVisitor::TryJoinTypes( Type* left, Type* right) { // Easy case: they are the same type! if (left->equals(right)) return left; // We can join two basic types by picking the "better" of the two if (auto leftBasic = as<BasicExpressionType>(left)) { if (auto rightBasic = as<BasicExpressionType>(right)) { auto leftFlavor = leftBasic->baseType; auto rightFlavor = rightBasic->baseType; // TODO(tfoley): Need a special-case rule here that if // either operand is of type `half`, then we promote // to at least `float` // Return the one that had higher rank... if (leftFlavor > rightFlavor) return left; else { SLANG_ASSERT(rightFlavor > leftFlavor); // equality was handles at the top of this function return right; } } // We can also join a vector and a scalar if(auto rightVector = as<VectorExpressionType>(right)) { return TryJoinVectorAndScalarType(rightVector, leftBasic); } } // We can join two vector types by joining their element types // (and also their sizes...) if( auto leftVector = as<VectorExpressionType>(left)) { if(auto rightVector = as<VectorExpressionType>(right)) { // Check if the vector sizes match if(!leftVector->elementCount->equalsVal(rightVector->elementCount)) return nullptr; // Try to join the element types auto joinElementType = TryJoinTypes( leftVector->elementType, rightVector->elementType); if(!joinElementType) return nullptr; return createVectorType( joinElementType, leftVector->elementCount); } // We can also join a vector and a scalar if(auto rightBasic = as<BasicExpressionType>(right)) { return TryJoinVectorAndScalarType(leftVector, rightBasic); } } // HACK: trying to work trait types in here... if(auto leftDeclRefType = as<DeclRefType>(left)) { if( auto leftInterfaceRef = leftDeclRefType->declRef.as<InterfaceDecl>() ) { // return TryJoinTypeWithInterface(right, leftInterfaceRef); } } if(auto rightDeclRefType = as<DeclRefType>(right)) { if( auto rightInterfaceRef = rightDeclRefType->declRef.as<InterfaceDecl>() ) { // return TryJoinTypeWithInterface(left, rightInterfaceRef); } } // TODO: all the cases for vectors apply to matrices too! // Default case is that we just fail. return nullptr; } SubstitutionSet SemanticsVisitor::TrySolveConstraintSystem( ConstraintSystem* system, DeclRef<GenericDecl> genericDeclRef) { // For now the "solver" is going to be ridiculously simplistic. // The generic itself will have some constraints, and for now we add these // to the system of constrains we will use for solving for the type variables. // // TODO: we need to decide whether constraints are used like this to influence // how we solve for type/value variables, or whether constraints in the parameter // list just work as a validation step *after* we've solved for the types. // // That is, should we allow `<T : Int>` to be written, and cause us to "infer" // that `T` should be the type `Int`? That seems a little silly. // // Eventually, though, we may want to support type identity constraints, especially // on associated types, like `<C where C : IContainer && C.IndexType == Int>` // These seem more reasonable to have influence constraint solving, since it could // conceivably let us specialize a `X<T> : IContainer` to `X<Int>` if we find // that `X<T>.IndexType == T`. for( auto constraintDeclRef : getMembersOfType<GenericTypeConstraintDecl>(genericDeclRef) ) { if(!TryUnifyTypes(*system, getSub(m_astBuilder, constraintDeclRef), getSup(m_astBuilder, constraintDeclRef))) return SubstitutionSet(); } SubstitutionSet resultSubst = genericDeclRef.substitutions; // We will loop over the generic parameters, and for // each we will try to find a way to satisfy all // the constraints for that parameter List<Val*> args; for (auto m : getMembers(genericDeclRef)) { if (auto typeParam = m.as<GenericTypeParamDecl>()) { Type* type = nullptr; for (auto& c : system->constraints) { if (c.decl != typeParam.getDecl()) continue; auto cType = as<Type>(c.val); SLANG_RELEASE_ASSERT(cType); if (!type) { type = cType; } else { auto joinType = TryJoinTypes(type, cType); if (!joinType) { // failure! return SubstitutionSet(); } type = joinType; } c.satisfied = true; } if (!type) { // failure! return SubstitutionSet(); } args.add(type); } else if (auto valParam = m.as<GenericValueParamDecl>()) { // TODO(tfoley): maybe support more than integers some day? // TODO(tfoley): figure out how this needs to interact with // compile-time integers that aren't just constants... IntVal* val = nullptr; for (auto& c : system->constraints) { if (c.decl != valParam.getDecl()) continue; auto cVal = as<IntVal>(c.val); SLANG_RELEASE_ASSERT(cVal); if (!val) { val = cVal; } else { if(!val->equalsVal(cVal)) { // failure! return SubstitutionSet(); } } c.satisfied = true; } if (!val) { // failure! return SubstitutionSet(); } args.add(val); } else { // ignore anything that isn't a generic parameter } } // After we've solved for the explicit arguments, we need to // make a second pass and consider the implicit arguments, // based on what we've already determined to be the values // for the explicit arguments. // Before we begin, we are going to go ahead and create the // "solved" substitution that we will return if everything works. // This is because we are going to use this substitution, // partially filled in with the results we know so far, // in order to specialize any constraints on the generic. // // E.g., if the generic parameters were `<T : ISidekick>`, and // we've already decided that `T` is `Robin`, then we want to // search for a conformance `Robin : ISidekick`, which involved // apply the substitutions we already know... GenericSubstitution* solvedSubst = m_astBuilder->create<GenericSubstitution>(); solvedSubst->genericDecl = genericDeclRef.getDecl(); solvedSubst->outer = genericDeclRef.substitutions.substitutions; solvedSubst->args = args; resultSubst.substitutions = solvedSubst; for( auto constraintDecl : genericDeclRef.getDecl()->getMembersOfType<GenericTypeConstraintDecl>() ) { DeclRef<GenericTypeConstraintDecl> constraintDeclRef( constraintDecl, solvedSubst); // Extract the (substituted) sub- and super-type from the constraint. auto sub = getSub(m_astBuilder, constraintDeclRef); auto sup = getSup(m_astBuilder, constraintDeclRef); // Search for a witness that shows the constraint is satisfied. auto subTypeWitness = tryGetSubtypeWitness(sub, sup); if(subTypeWitness) { // We found a witness, so it will become an (implicit) argument. solvedSubst->args.add(subTypeWitness); } else { // No witness was found, so the inference will now fail. // // TODO: Ideally we should print an error message in // this case, to let the user know why things failed. return SubstitutionSet(); } // TODO: We may need to mark some constrains in our constraint // system as being solved now, as a result of the witness we found. } // Make sure we haven't constructed any spurious constraints // that we aren't able to satisfy: for (auto c : system->constraints) { if (!c.satisfied) { return SubstitutionSet(); } } return resultSubst; } bool SemanticsVisitor::TryUnifyVals( ConstraintSystem& constraints, Val* fst, Val* snd) { // if both values are types, then unify types if (auto fstType = as<Type>(fst)) { if (auto sndType = as<Type>(snd)) { return TryUnifyTypes(constraints, fstType, sndType); } } // if both values are constant integers, then compare them if (auto fstIntVal = as<ConstantIntVal>(fst)) { if (auto sndIntVal = as<ConstantIntVal>(snd)) { return fstIntVal->value == sndIntVal->value; } } // Check if both are integer values in general if (auto fstInt = as<IntVal>(fst)) { if (auto sndInt = as<IntVal>(snd)) { auto fstParam = as<GenericParamIntVal>(fstInt); auto sndParam = as<GenericParamIntVal>(sndInt); bool okay = false; if (fstParam) { if(TryUnifyIntParam(constraints, fstParam->declRef, sndInt)) okay = true; } if (sndParam) { if(TryUnifyIntParam(constraints, sndParam->declRef, fstInt)) okay = true; } return okay; } } if (auto fstWit = as<DeclaredSubtypeWitness>(fst)) { if (auto sndWit = as<DeclaredSubtypeWitness>(snd)) { auto constraintDecl1 = fstWit->declRef.as<TypeConstraintDecl>(); auto constraintDecl2 = sndWit->declRef.as<TypeConstraintDecl>(); SLANG_ASSERT(constraintDecl1); SLANG_ASSERT(constraintDecl2); return TryUnifyTypes(constraints, constraintDecl1.getDecl()->getSup().type, constraintDecl2.getDecl()->getSup().type); } } SLANG_UNIMPLEMENTED_X("value unification case"); // default: fail //return false; } bool SemanticsVisitor::tryUnifySubstitutions( ConstraintSystem& constraints, Substitutions* fst, Substitutions* snd) { // They must both be NULL or non-NULL if (!fst || !snd) return !fst && !snd; if(auto fstGeneric = as<GenericSubstitution>(fst)) { if(auto sndGeneric = as<GenericSubstitution>(snd)) { return tryUnifyGenericSubstitutions( constraints, fstGeneric, sndGeneric); } } // TODO: need to handle other cases here return false; } bool SemanticsVisitor::tryUnifyGenericSubstitutions( ConstraintSystem& constraints, GenericSubstitution* fst, GenericSubstitution* snd) { SLANG_ASSERT(fst); SLANG_ASSERT(snd); auto fstGen = fst; auto sndGen = snd; // They must be specializing the same generic if (fstGen->genericDecl != sndGen->genericDecl) return false; // Their arguments must unify SLANG_RELEASE_ASSERT(fstGen->args.getCount() == sndGen->args.getCount()); Index argCount = fstGen->args.getCount(); bool okay = true; for (Index aa = 0; aa < argCount; ++aa) { if (!TryUnifyVals(constraints, fstGen->args[aa], sndGen->args[aa])) { okay = false; } } // Their "base" specializations must unify if (!tryUnifySubstitutions(constraints, fstGen->outer, sndGen->outer)) { okay = false; } return okay; } bool SemanticsVisitor::TryUnifyTypeParam( ConstraintSystem& constraints, GenericTypeParamDecl* typeParamDecl, Type* type) { // We want to constrain the given type parameter // to equal the given type. Constraint constraint; constraint.decl = typeParamDecl; constraint.val = type; constraints.constraints.add(constraint); return true; } bool SemanticsVisitor::TryUnifyIntParam( ConstraintSystem& constraints, GenericValueParamDecl* paramDecl, IntVal* val) { // We only want to accumulate constraints on // the parameters of the declarations being // specialized (don't accidentially constrain // parameters of a generic function based on // calls in its body). if(paramDecl->parentDecl != constraints.genericDecl) return false; // We want to constrain the given parameter to equal the given value. Constraint constraint; constraint.decl = paramDecl; constraint.val = val; constraints.constraints.add(constraint); return true; } bool SemanticsVisitor::TryUnifyIntParam( ConstraintSystem& constraints, DeclRef<VarDeclBase> const& varRef, IntVal* val) { if(auto genericValueParamRef = varRef.as<GenericValueParamDecl>()) { return TryUnifyIntParam(constraints, genericValueParamRef.getDecl(), val); } else { return false; } } bool SemanticsVisitor::TryUnifyTypesByStructuralMatch( ConstraintSystem& constraints, Type* fst, Type* snd) { if (auto fstDeclRefType = as<DeclRefType>(fst)) { auto fstDeclRef = fstDeclRefType->declRef; if (auto typeParamDecl = as<GenericTypeParamDecl>(fstDeclRef.getDecl())) return TryUnifyTypeParam(constraints, typeParamDecl, snd); if (auto sndDeclRefType = as<DeclRefType>(snd)) { auto sndDeclRef = sndDeclRefType->declRef; if (auto typeParamDecl = as<GenericTypeParamDecl>(sndDeclRef.getDecl())) return TryUnifyTypeParam(constraints, typeParamDecl, fst); // can't be unified if they refer to different declarations. if (fstDeclRef.getDecl() != sndDeclRef.getDecl()) return false; // next we need to unify the substitutions applied // to each declaration reference. if (!tryUnifySubstitutions( constraints, fstDeclRef.substitutions.substitutions, sndDeclRef.substitutions.substitutions)) { return false; } return true; } } return false; } bool SemanticsVisitor::TryUnifyConjunctionType( ConstraintSystem& constraints, AndType* fst, Type* snd) { // Unifying a type `T` with `A & B` amounts to unifying // `T` with `A` and also `T` with `B`. // // If either unification is impossible, then the full // case is also impossible. // return TryUnifyTypes(constraints, fst->left, snd) && TryUnifyTypes(constraints, fst->right, snd); } bool SemanticsVisitor::TryUnifyTypes( ConstraintSystem& constraints, Type* fst, Type* snd) { if (fst->equals(snd)) return true; // An error type can unify with anything, just so we avoid cascading errors. if (auto fstErrorType = as<ErrorType>(fst)) return true; if (auto sndErrorType = as<ErrorType>(snd)) return true; // If one or the other of the types is a conjunction `X & Y`, // then we want to recurse on both `X` and `Y`. // // Note that we check this case *before* we check if one of // the types is a generic parameter below, so that we should // never end up trying to match up a type parameter with // a conjunction directly, and will instead find all of the // "leaf" types we need to constrain it to. // if( auto fstAndType = as<AndType>(fst) ) { return TryUnifyConjunctionType(constraints, fstAndType, snd); } if( auto sndAndType = as<AndType>(snd) ) { return TryUnifyConjunctionType(constraints, sndAndType, fst); } // A generic parameter type can unify with anything. // TODO: there actually needs to be some kind of "occurs check" sort // of thing here... if (auto fstDeclRefType = as<DeclRefType>(fst)) { auto fstDeclRef = fstDeclRefType->declRef; if (auto typeParamDecl = as<GenericTypeParamDecl>(fstDeclRef.getDecl())) { if(typeParamDecl->parentDecl == constraints.genericDecl ) return TryUnifyTypeParam(constraints, typeParamDecl, snd); } } if (auto sndDeclRefType = as<DeclRefType>(snd)) { auto sndDeclRef = sndDeclRefType->declRef; if (auto typeParamDecl = as<GenericTypeParamDecl>(sndDeclRef.getDecl())) { if(typeParamDecl->parentDecl == constraints.genericDecl ) return TryUnifyTypeParam(constraints, typeParamDecl, fst); } } // If we can unify the types structurally, then we are golden if(TryUnifyTypesByStructuralMatch(constraints, fst, snd)) return true; // Now we need to consider cases where coercion might // need to be applied. For now we can try to do this // in a completely ad hoc fashion, but eventually we'd // want to do it more formally. if(auto fstVectorType = as<VectorExpressionType>(fst)) { if(auto sndScalarType = as<BasicExpressionType>(snd)) { return TryUnifyTypes( constraints, fstVectorType->elementType, sndScalarType); } } if(auto fstScalarType = as<BasicExpressionType>(fst)) { if(auto sndVectorType = as<VectorExpressionType>(snd)) { return TryUnifyTypes( constraints, fstScalarType, sndVectorType->elementType); } } // TODO: the same thing for vectors... return false; } }
36.223514
121
0.545458
JKot-Coder
a0357e9cd0f19dcca39eb366a2724bd340c371bb
1,611
cpp
C++
src/Object2D.cpp
Ryozuki/GForce
a36ab77587773057e1b6fc84cb6efe9987dc4473
[ "MIT" ]
null
null
null
src/Object2D.cpp
Ryozuki/GForce
a36ab77587773057e1b6fc84cb6efe9987dc4473
[ "MIT" ]
null
null
null
src/Object2D.cpp
Ryozuki/GForce
a36ab77587773057e1b6fc84cb6efe9987dc4473
[ "MIT" ]
null
null
null
/* * (c) Ryozuki See LICENSE.txt in the root of the distribution for more information. * If you are missing that file, acquire a complete release at https://github.com/Ryozuki/GForce */ #include <GForce/Object2D.hpp> #include <GForce/Constants.hpp> namespace gf { Object2D::Object2D(double mass) { setMass(mass); } void Object2D::setMass(double mass) { m_Mass = mass; } void Object2D::addForce(Vector2D force) { m_Force += force; } void Object2D::setForce(Vector2D force) { m_Force = force; } void Object2D::tick(double deltaTime) { if(deltaTime == 0) return; m_Velocity += getAcceleration() * deltaTime; m_Position += m_Velocity * deltaTime; } void Object2D::setPosition(Vector2D new_pos) { m_Position = new_pos; } void Object2D::setVelocity(Vector2D new_vel) { m_Velocity = new_vel; } void Object2D::addVelocity(Vector2D vel) { m_Velocity += vel; } Vector2D Object2D::getAcceleration() const { return getForce() / getMass(); } void Object2D::resetForce() { m_Force = Vector2D(); } void Object2D::resetVelocity() { m_Velocity = Vector2D(); } void Object2D::stopMovement() { resetForce(); resetVelocity(); } void Object2D::applyGravity(Object2D &a, bool update_a) { double force = GRAVITATIONAL_CONSTANT * (getMass() * a.getMass()) / distanceTo(a); Vector2D forceV = (a.getPosition() - getPosition()).direction(); forceV *= force; addForce(forceV); if(update_a) a.addForce(-forceV); } double Object2D::distanceTo(const Object2D &other) const { return getPosition().distanceTo(other.getPosition()); } }
17.703297
96
0.688392
Ryozuki
a03b320fe75a6e87efa21af0902a15eebcda16f5
598
cpp
C++
C++/01_Backtracking/MEDIUM_PERMUTATIONS.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
C++/01_Backtracking/MEDIUM_PERMUTATIONS.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
C++/01_Backtracking/MEDIUM_PERMUTATIONS.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
vector<vector<int> > permute(vector<int> &num) { vector<vector<int> > result; permuteRecursive(result, 0, num); return result; } // permute num[begin..end] // invariant: num[0..begin-1] have been fixed/permuted void permuteRecursive(vector<vector<int> > &result, int begin, vector<int> &num) { if (begin >= num.size()) { // one permutation instance result.push_back(num); return; } for (int i = begin; i < num.size(); i++) { swap(num[begin], num[i]); permuteRecursive(num, begin + 1, result); // reset swap(num[begin], num[i]); } }
22.148148
81
0.603679
animeshramesh
a041ed9f8cac4a98baa2a5af904a417a3bbca844
3,729
hpp
C++
zug/state_traits.hpp
CJBussey/zug
4c9aff02c5f870f2ba518ba7f93ceb6a00e5fda8
[ "BSL-1.0" ]
null
null
null
zug/state_traits.hpp
CJBussey/zug
4c9aff02c5f870f2ba518ba7f93ceb6a00e5fda8
[ "BSL-1.0" ]
null
null
null
zug/state_traits.hpp
CJBussey/zug
4c9aff02c5f870f2ba518ba7f93ceb6a00e5fda8
[ "BSL-1.0" ]
null
null
null
// // zug: transducers for C++ // Copyright (C) 2019 Juan Pedro Bolivar Puente // // This software is distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt // #pragma once #include <type_traits> #include <utility> namespace zug { /*! * Interface for a type specializing the `State` concept. * * A `State` is the first parameter of a reducing function, also known as the * accumulator. Every type is a model of `State`, with the following * default implementation. However, one might want to specialize the * state it for a particular accumulator type, such that transducers * can operate with it. A transducer should not make assumptions * about the state it receives, instead, it can only wrap it using * `wrap_state` to attach additional data. * * For an example of a stateful reducing function, see `take`. * * @see wrap_state * @see take */ template <typename StateT> struct state_traits { /*! * Returns whether the value is idempotent, and thus, the reduction * can finish. */ template <typename T> static bool is_reduced(T&&) { return false; } /*! * Returns the associated from the current state. If the state * contains no associated data, the `default_data` will be returned. */ template <typename T, typename D> static decltype(auto) data(T&&, D&& d) { return std::forward<D>(d)(); } /*! * Unwraps all the layers of state wrappers returning the deepmost */ template <typename T> static T&& complete(T&& state) { return std::forward<T>(state); } /*! * Unwraps this layers of state wrappers, returning the nested * state for the next reducing function. */ template <typename T> static T&& unwrap(T&& state) { return std::forward<T>(state); } /*! * Unwraps all layers of state wrappers, returning the most nested * state for the innermost reducing function. */ template <typename T> static T&& unwrap_all(T&& state) { return std::forward<T>(state); } /*! * Copies all layers of state wrappers but replaces the innermost * state with `substate`. */ template <typename T, typename U> static U&& rewrap(T&&, U&& x) { return std::forward<U>(x); } }; template <typename T> using state_traits_t = state_traits<std::decay_t<T>>; /*! * Convenience function for calling `state_traits::complete` */ template <typename T> decltype(auto) state_complete(T&& s) { return state_traits_t<T>::complete(std::forward<T>(s)); } /*! * Convenience function for calling `state_traits::is_reduced` */ template <typename T> bool state_is_reduced(T&& s) { return state_traits_t<T>::is_reduced(std::forward<T>(s)); } /*! * Convenience function for calling `state_traits::data` */ template <typename T, typename D> decltype(auto) state_data(T&& s, D&& d) { return state_traits_t<T>::data(std::forward<T>(s), std::forward<D>(d)); } /*! * Convenience function for calling `state_traits::unwrap` */ template <typename T> decltype(auto) state_unwrap(T&& s) { return state_traits_t<T>::unwrap(std::forward<T>(s)); } /*! * Convenience function for calling `state_traits::unwrap_all` */ template <typename T> decltype(auto) state_unwrap_all(T&& s) { return state_traits_t<T>::unwrap_all(std::forward<T>(s)); } /*! * Convenience function for calling `state_traits::unwrap_all` */ template <typename T, typename U> decltype(auto) state_rewrap(T&& s, U&& x) { return state_traits_t<T>::rewrap(std::forward<T>(s), std::forward<U>(x)); } } // namespace zug
24.372549
78
0.659426
CJBussey
a044127b3ec32060224277df4d8acda13c9b1c1a
58,225
cpp
C++
engine/audio/private/snd_op_sys/sos_op_math.cpp
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
252
2020-12-16T15:34:43.000Z
2022-03-31T23:21:37.000Z
cstrike15_src/engine/audio/private/snd_op_sys/sos_op_math.cpp
bahadiraraz/Counter-Strike-Global-Offensive
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
[ "MIT" ]
23
2020-12-20T18:02:54.000Z
2022-03-28T16:58:32.000Z
cstrike15_src/engine/audio/private/snd_op_sys/sos_op_math.cpp
bahadiraraz/Counter-Strike-Global-Offensive
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
[ "MIT" ]
42
2020-12-19T04:32:33.000Z
2022-03-30T06:00:28.000Z
//============ Copyright (c) Valve Corporation, All rights reserved. ============ // // //=============================================================================== #include "audio_pch.h" #include "tier2/interval.h" #include "math.h" #include "sos_op.h" #include "sos_op_math.h" #include "snd_dma.h" #include "../../cl_splitscreen.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" // ------------------------------------------------------------------------ // GOOD OLD MACROS #define SOS_DtoR 0.01745329251994329500 #define RtoD 57.29577951308232300000 #define SOS_DEG2RAD(d) ((float)(d) * DtoR) #define SOS_RAD2DEG(r) ((float)(r) * RtoD) #define SOS_RADIANS(deg) ((deg)*DtoR) #define SOS_DEGREES(rad) ((rad)*RtoD) //----------------------------------------------------------------------------- #define SOS_MIN(a,b) (((a) < (b)) ? (a) : (b)) #define SOS_MAX(a,b) (((a) > (b)) ? (a) : (b)) #define SOS_ABS(a) (((a) < 0) ? -(a) : (a)) #define SOS_FLOOR(a) ((a) > 0 ? (int)(a) : -(int)(-a)) #define SOS_CEILING(a) ((a)==(int)(a) ? (a) : (a)>0 ? 1+(int)(a) : -(1+(int)(-a))) #define SOS_ROUND(a) ((a)>0 ? (int)(a+0.5) : -(int)(0.5-a)) #define SOS_SGN(a) (((a)<0) ? -1 : 1) #define SOS_SQR(a) ((a)*(a)) #define SOS_MOD(a,b) (a)%(b) // ---------------------------------------------------------------------------- #define SOS_RAMP(value,a,b) (((a) - (float)(value)) / ((a) - (b))) #define SOS_LERP(factor,a,b) ((a) + (((b) - (a)) * (factor))) #define SOS_RESCALE(X,Xa,Xb,Ya,Yb) SOS_LERP(SOS_RAMP(X,Xa,Xb),Ya,Yb) #define SOS_INRANGE(x,a,b) (((x) >= SOS_MIN(a,b)) && ((x) <= SOS_MAX(a,b))) #define SOS_CLAMP(x,a,b) ((x)<SOS_MIN(a,b)?SOS_MIN(a,b):(x)>MAX(a,b)?SOS_MAX(a,b):(x)) #define SOS_CRAMP(value,a,b) SOS_CLAMP(SOS_RAMP(value,a,b),0,1) #define SOS_CLERP(factor,a,b) SOS_CLAMP(SOS_LERP(factor,a,b),a,b) #define SOS_CRESCALE(X,Xa,Xb,Ya,Yb) SOS_CLAMP(SOS_RESCALE(X,Xa,Xb,Ya,Yb),Ya,Yb) #define SOS_SIND(deg) sin(SOS_RADIANS(deg)) #define SOS_COSD(deg) cos(SOS_RADIANS(deg)) #define SOS_TAND(deg) tan(SOS_RADIANS(deg)) #define SOS_ATAN2(a,b) atan2(a,b) #define SOS_UNITSINUSOID(x) SOS_LERP(SOS_SIND(SOS_CLERP(x,-90,90)),0.5,1.0) #define SOS_ELERP(factor,a,b) SOS_LERP(SOS_UNITSINUSOID(factor),a,b) //----------------------------------------------------------- extern Color OpColor; extern Color ConnectColor; extern Color ResultColor; SOFunc1Type_t S_GetFunc1Type( const char *pValueString ) { if ( !V_strcasecmp( pValueString, "none" ) ) { return SO_FUNC1_NONE; } else if ( !V_strcasecmp( pValueString, "sin" ) ) { return SO_FUNC1_SIN; } else if ( !V_strcasecmp( pValueString, "asin" ) ) { return SO_FUNC1_ASIN; } else if ( !V_strcasecmp( pValueString, "cos" ) ) { return SO_FUNC1_COS; } else if ( !V_strcasecmp( pValueString, "acos" ) ) { return SO_FUNC1_ACOS; } else if ( !V_strcasecmp( pValueString, "tan" ) ) { return SO_FUNC1_TAN; } else if ( !V_strcasecmp( pValueString, "atan" ) ) { return SO_FUNC1_ATAN; } else if ( !V_strcasecmp( pValueString, "sinh" ) ) { return SO_FUNC1_SINH; } else if ( !V_strcasecmp( pValueString, "asinh" ) ) { return SO_FUNC1_ASINH; } else if ( !V_strcasecmp( pValueString, "cosh" ) ) { return SO_FUNC1_COSH; } else if ( !V_strcasecmp( pValueString, "acosh" ) ) { return SO_FUNC1_ACOSH; } else if ( !V_strcasecmp( pValueString, "tanh" ) ) { return SO_FUNC1_TANH; } else if ( !V_strcasecmp( pValueString, "atanh" ) ) { return SO_FUNC1_ATANH; } else if ( !V_strcasecmp( pValueString, "exp" ) ) { return SO_FUNC1_EXP; } else if ( !V_strcasecmp( pValueString, "expm1" ) ) { return SO_FUNC1_EXPM1; } else if ( !V_strcasecmp( pValueString, "exp2" ) ) { return SO_FUNC1_EXP2; } else if ( !V_strcasecmp( pValueString, "log" ) ) { return SO_FUNC1_LOG; } else if ( !V_strcasecmp( pValueString, "log2" ) ) { return SO_FUNC1_LOG2; } else if ( !V_strcasecmp( pValueString, "log1p" ) ) { return SO_FUNC1_LOG1P; } else if ( !V_strcasecmp( pValueString, "log10" ) ) { return SO_FUNC1_LOG10; } else if ( !V_strcasecmp( pValueString, "logb" ) ) { return SO_FUNC1_LOGB; } else if ( !V_strcasecmp( pValueString, "fabs" ) ) { return SO_FUNC1_FABS; } else if ( !V_strcasecmp( pValueString, "sqrt" ) ) { return SO_FUNC1_SQRT; } else if ( !V_strcasecmp( pValueString, "erf" ) ) { return SO_FUNC1_ERF; } else if ( !V_strcasecmp( pValueString, "erfc" ) ) { return SO_FUNC1_ERFC; } else if ( !V_strcasecmp( pValueString, "gamma" ) ) { return SO_FUNC1_GAMMA; } else if ( !V_strcasecmp( pValueString, "lgamma" ) ) { return SO_FUNC1_LGAMMA; } else if ( !V_strcasecmp( pValueString, "ceil" ) ) { return SO_FUNC1_CEIL; } else if ( !V_strcasecmp( pValueString, "floor" ) ) { return SO_FUNC1_FLOOR; } else if ( !V_strcasecmp( pValueString, "rint" ) ) { return SO_FUNC1_RINT; } else if ( !V_strcasecmp( pValueString, "nearbyint" ) ) { return SO_FUNC1_NEARBYINT; } else if ( !V_strcasecmp( pValueString, "rintol" ) ) { return SO_FUNC1_RINTOL; } else if ( !V_strcasecmp( pValueString, "round" ) ) { return SO_FUNC1_ROUND; } else if ( !V_strcasecmp( pValueString, "roundtol" ) ) { return SO_FUNC1_ROUNDTOL; } else if ( !V_strcasecmp( pValueString, "trunc" ) ) { return SO_FUNC1_TRUNC; } else { return SO_FUNC1_NONE; } } void S_PrintFunc1Type( SOFunc1Type_t nType, int nLevel ) { const char *pType; switch ( nType ) { case SO_FUNC1_NONE: pType = "none"; break; case SO_FUNC1_SIN: pType = "sin"; break; case SO_FUNC1_ASIN: pType = "asin"; break; case SO_FUNC1_COS: pType = "cos"; break; case SO_FUNC1_ACOS: pType = "acos"; break; case SO_FUNC1_TAN: pType = "tan"; break; case SO_FUNC1_ATAN: pType = "atan"; break; case SO_FUNC1_SINH: pType = "sinh"; break; case SO_FUNC1_ASINH: pType = "asinh"; break; case SO_FUNC1_COSH: pType = "cosh"; break; case SO_FUNC1_ACOSH: pType = "acosh"; break; case SO_FUNC1_TANH: pType = "tanh"; break; case SO_FUNC1_ATANH: pType = "atanh"; break; case SO_FUNC1_EXP: pType = "exp"; break; case SO_FUNC1_EXPM1: pType = "expm1"; break; case SO_FUNC1_EXP2: pType = "exp2"; break; case SO_FUNC1_LOG: pType = "log"; break; case SO_FUNC1_LOG2: pType = "log2"; break; case SO_FUNC1_LOG1P: pType = "log1p"; break; case SO_FUNC1_LOG10: pType = "log10"; break; case SO_FUNC1_LOGB: pType = "logb"; break; case SO_FUNC1_FABS: pType = "fabs"; break; case SO_FUNC1_SQRT: pType = "sqrt"; break; case SO_FUNC1_ERF: pType = "erf"; break; case SO_FUNC1_ERFC: pType = "erfc"; break; case SO_FUNC1_GAMMA: pType = "gamma"; break; case SO_FUNC1_LGAMMA: pType = "lgamma"; break; case SO_FUNC1_CEIL: pType = "ceil"; break; case SO_FUNC1_FLOOR: pType = "floor"; break; case SO_FUNC1_RINT: pType = "rint"; break; case SO_FUNC1_NEARBYINT: pType = "nearbyint"; break; case SO_FUNC1_RINTOL: pType = "rintol"; break; case SO_FUNC1_ROUND: pType = "round"; break; case SO_FUNC1_ROUNDTOL: pType = "roundtol"; break; case SO_FUNC1_TRUNC: pType = "trunc"; break; default: pType = "none"; break; } Log_Msg( LOG_SOUND_OPERATOR_SYSTEM, OpColor, "%*sFunction: %s\n", nLevel, " ", pType ); } SOOpType_t S_GetExpressionType( const char *pValueString ) { if ( !V_strcasecmp( pValueString, "none" ) ) { return SO_OP_NONE; } else if ( !V_strcasecmp( pValueString, "set" ) ) { return SO_OP_SET; } else if ( !V_strcasecmp( pValueString, "add" ) ) { return SO_OP_ADD; } else if ( !V_strcasecmp( pValueString, "sub" ) ) { return SO_OP_SUB; } else if ( !V_strcasecmp( pValueString, "mult" ) ) { return SO_OP_MULT; } else if ( !V_strcasecmp( pValueString, "div" ) ) { return SO_OP_DIV; } else if ( !V_strcasecmp( pValueString, "mod" ) ) { return SO_OP_MOD; } else if ( !V_strcasecmp( pValueString, "max" ) ) { return SO_OP_MAX; } else if ( !V_strcasecmp( pValueString, "min" ) ) { return SO_OP_MIN; } else if ( !V_strcasecmp( pValueString, "invert" ) ) { return SO_OP_INV; } else if ( !V_strcasecmp( pValueString, "greater_than" ) ) { return SO_OP_GT; } else if ( !V_strcasecmp( pValueString, "less_than" ) ) { return SO_OP_LT; } else if ( !V_strcasecmp( pValueString, "greater_than_or_equal" ) ) { return SO_OP_GTOE; } else if ( !V_strcasecmp( pValueString, "less_than_or_equal" ) ) { return SO_OP_LTOE; } else if ( !V_strcasecmp( pValueString, "equals" ) ) { return SO_OP_EQ; } else if ( !V_strcasecmp( pValueString, "not_equal" ) ) { return SO_OP_NOT_EQ; } else if ( !V_strcasecmp( pValueString, "invert_scale" ) ) { return SO_OP_INV_SCALE; } else if ( !V_strcasecmp( pValueString, "pow" ) ) { return SO_OP_POW; } else { return SO_OP_NONE; } } void S_PrintOpType( SOOpType_t nType, int nLevel ) { const char *pType; switch ( nType ) { case SO_OP_NONE: pType = "none"; break; case SO_OP_SET: pType = "set"; break; case SO_OP_ADD: pType = "add"; break; case SO_OP_SUB: pType = "sub"; break; case SO_OP_MULT: pType = "mult"; break; case SO_OP_DIV: pType = "div"; break; case SO_OP_MOD: pType = "mod"; break; case SO_OP_MAX: pType = "max"; break; case SO_OP_MIN: pType = "min"; break; case SO_OP_INV: pType = "invert"; break; case SO_OP_GT: pType = "greater_than"; break; case SO_OP_LT: pType = "less_than"; break; case SO_OP_GTOE: pType = "greater_than_or_equal"; break; case SO_OP_LTOE: pType = "less_than_or_equal"; break; case SO_OP_EQ: pType = "equals"; break; case SO_OP_NOT_EQ: pType = "not_equal"; break; case SO_OP_INV_SCALE: pType = "invert_scale"; break; case SO_OP_POW: pType = "pow"; break; default: pType = "none"; break; } Log_Msg( LOG_SOUND_OPERATOR_SYSTEM, OpColor, "%*sOperation: %s\n", nLevel, " ", pType ); } //----------------------------------------------------------------------------- // CSosOperatorFunc1 // Setting a single, simple scratch pad Expression //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorFunc1, "math_func1" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorFunc1, m_flOutput, SO_SINGLE, "output" ); SOS_REGISTER_INPUT_FLOAT( CSosOperatorFunc1, m_flInput1, SO_SINGLE, "input1" ) SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorFunc1, "math_func1" ) void CSosOperatorFunc1::SetDefaults( void *pVoidMem ) const { CSosOperatorFunc1_t *pStructMem = (CSosOperatorFunc1_t *)pVoidMem; SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInput1, SO_SINGLE, 0.0 ) // do nothing by default pStructMem->m_funcType = SO_FUNC1_NONE; pStructMem->m_bNormTrig = false; } void CSosOperatorFunc1::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorFunc1_t *pStructMem = (CSosOperatorFunc1_t *)pVoidMem; float flResult = 0.0; switch ( pStructMem->m_funcType ) { case SO_OP_NONE: break; case SO_FUNC1_SIN: flResult = sin( pStructMem->m_flInput1[0] ); break; case SO_FUNC1_ASIN: flResult = asin( pStructMem->m_flInput1[0] ); break; case SO_FUNC1_COS: flResult = cos( pStructMem->m_flInput1[0] ); break; case SO_FUNC1_ACOS: flResult = acos( pStructMem->m_flInput1[0] ); break; case SO_FUNC1_TAN: flResult = tan( pStructMem->m_flInput1[0] ); break; case SO_FUNC1_ATAN: flResult = atan( pStructMem->m_flInput1[0] ); break; case SO_FUNC1_SINH: flResult = sinh( pStructMem->m_flInput1[0] ); break; // case SO_FUNC1_ASINH: // flResult = asinh( pStructMem->m_flInput1[0] ); // break; case SO_FUNC1_COSH: flResult = cosh( pStructMem->m_flInput1[0] ); break; // case SO_FUNC1_ACOSH: // flResult = acosh( pStructMem->m_flInput1[0] ); // break; case SO_FUNC1_TANH: flResult = tanh( pStructMem->m_flInput1[0] ); break; // case SO_FUNC1_ATANH: // flResult = atanh( pStructMem->m_flInput1[0] ); // break; case SO_FUNC1_EXP: flResult = exp( pStructMem->m_flInput1[0] ); break; // case SO_FUNC1_EXPM1: // flResult = expm1( pStructMem->m_flInput1[0] ); // break; // case SO_FUNC1_EXP2: // flResult = exp2( pStructMem->m_flInput1[0] ); // break; case SO_FUNC1_LOG: flResult = log( pStructMem->m_flInput1[0] ); break; // case SO_FUNC1_LOG2: // flResult = log2( pStructMem->m_flInput1[0] ); // break; // case SO_FUNC1_LOG1P: // flResult = log1p( pStructMem->m_flInput1[0] ); // break; case SO_FUNC1_LOG10: flResult = log10( pStructMem->m_flInput1[0] ); break; // case SO_FUNC1_LOGB: // flResult = logb( pStructMem->m_flInput1[0] ); // break; case SO_FUNC1_FABS: flResult = fabs( pStructMem->m_flInput1[0] ); break; case SO_FUNC1_SQRT: flResult = sqrt( pStructMem->m_flInput1[0] ); break; // case SO_FUNC1_ERF: // flResult = erf( pStructMem->m_flInput1[0] ); // break; // case SO_FUNC1_ERFC: // flResult = erfc( pStructMem->m_flInput1[0] ); // break; // case SO_FUNC1_GAMMA: // flResult = gamma( pStructMem->m_flInput1[0] ); // break; // case SO_FUNC1_LGAMMA: // flResult = lgamma( pStructMem->m_flInput1[0] ); // break; case SO_FUNC1_CEIL: flResult = ceil( pStructMem->m_flInput1[0] ); break; case SO_FUNC1_FLOOR: flResult = floor( pStructMem->m_flInput1[0] ); break; // case SO_FUNC1_RINT: // flResult = rint( pStructMem->m_flInput1[0] ); // break; // case SO_FUNC1_NEARBYINT: // flResult = nearbyint( pStructMem->m_flInput1[0] ); // break; // case SO_FUNC1_RINTOL: // flResult = rintol( pStructMem->m_flInput1[0] ); // break; case SO_FUNC1_ROUND: flResult = SOS_ROUND( pStructMem->m_flInput1[0] ); break; // case SO_FUNC1_ROUNDTOL: // flResult = roundtol( pStructMem->m_flInput1[0] ); // break; // case SO_FUNC1_TRUNC: // flResult = trunc( pStructMem->m_flInput1[0] ); // break; default: break; } if( pStructMem->m_bNormTrig ) { flResult = ( flResult + 1.0 ) * 0.5; } pStructMem->m_flOutput[0] = flResult; } void CSosOperatorFunc1::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { CSosOperatorFunc1_t *pStructMem = (CSosOperatorFunc1_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); S_PrintFunc1Type( pStructMem->m_funcType, nLevel ); Log_Msg( LOG_SND_OPERATORS, OpColor, "%*snormalize_trig: %s\n", nLevel, " ", pStructMem->m_bNormTrig ? "true": "false" ); } void CSosOperatorFunc1::OpHelp( ) const { } void CSosOperatorFunc1::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorFunc1_t *pStructMem = (CSosOperatorFunc1_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else if ( !V_strcasecmp( pParamString, "function" ) ) { pStructMem->m_funcType = S_GetFunc1Type( pValueString ); } else if ( !V_strcasecmp( pParamString, "normalize_trig" ) ) { if ( !V_strcasecmp( pValueString, "true" ) ) { pStructMem->m_bNormTrig = true; } else { pStructMem->m_bNormTrig = false; } } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorFloat // Setting a single, simple scratch pad Expression //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorFloat, "math_float" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorFloat, m_flOutput, SO_SINGLE, "output" ); SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloat, m_flInput1, SO_SINGLE, "input1" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloat, m_flInput2, SO_SINGLE, "input2") SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorFloat, "math_float" ) void CSosOperatorFloat::SetDefaults( void *pVoidMem ) const { CSosOperatorFloat_t *pStructMem = (CSosOperatorFloat_t *)pVoidMem; SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInput1, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInput2, SO_SINGLE, 0.0 ) // do nothing by default pStructMem->m_opType = SO_OP_MULT; } void CSosOperatorFloat::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorFloat_t *pStructMem = (CSosOperatorFloat_t *)pVoidMem; float flResult = 0.0; switch ( pStructMem->m_opType ) { case SO_OP_NONE: break; case SO_OP_SET: flResult = pStructMem->m_flInput1[0]; break; case SO_OP_ADD: flResult = pStructMem->m_flInput1[0] + pStructMem->m_flInput2[0]; break; case SO_OP_SUB: flResult = pStructMem->m_flInput1[0] - pStructMem->m_flInput2[0]; break; case SO_OP_MULT: flResult = pStructMem->m_flInput1[0] * pStructMem->m_flInput2[0]; break; case SO_OP_DIV: if ( pStructMem->m_flInput2[0] > 0.0 ) { flResult = pStructMem->m_flInput1[0] / pStructMem->m_flInput2[0]; } break; case SO_OP_MOD: if ( pStructMem->m_flInput2[0] > 0.0 ) { flResult = fmodf( pStructMem->m_flInput1[0], pStructMem->m_flInput2[0] ); } break; case SO_OP_MAX: flResult = MAX( pStructMem->m_flInput1[0], pStructMem->m_flInput2[0] ); break; case SO_OP_MIN: flResult = MIN( pStructMem->m_flInput1[0], pStructMem->m_flInput2[0] ); break; case SO_OP_INV: flResult = 1.0 - pStructMem->m_flInput1[0]; break; case SO_OP_GT: flResult = pStructMem->m_flInput1[0] > pStructMem->m_flInput2[0] ? 1.0 : 0.0; break; case SO_OP_LT: flResult = pStructMem->m_flInput1[0] < pStructMem->m_flInput2[0] ? 1.0 : 0.0; break; case SO_OP_GTOE: flResult = pStructMem->m_flInput1[0] >= pStructMem->m_flInput2[0] ? 1.0 : 0.0; break; case SO_OP_LTOE: flResult = pStructMem->m_flInput1[0] <= pStructMem->m_flInput2[0] ? 1.0 : 0.0; break; case SO_OP_EQ: flResult = pStructMem->m_flInput1[0] == pStructMem->m_flInput2[0] ? 1.0 : 0.0; break; case SO_OP_NOT_EQ: flResult = pStructMem->m_flInput1[0] != pStructMem->m_flInput2[0] ? 1.0 : 0.0; break; case SO_OP_INV_SCALE: flResult = 1.0 - ( ( 1.0 - pStructMem->m_flInput1[0] ) * pStructMem->m_flInput2[0] ); break; case SO_OP_POW: flResult = FastPow( pStructMem->m_flInput1[0], pStructMem->m_flInput2[0] ); break; default: break; } pStructMem->m_flOutput[0] = flResult; } void CSosOperatorFloat::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { CSosOperatorFloat_t *pStructMem = (CSosOperatorFloat_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); S_PrintOpType( pStructMem->m_opType, nLevel ); } void CSosOperatorFloat::OpHelp( ) const { } void CSosOperatorFloat::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorFloat_t *pStructMem = (CSosOperatorFloat_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else if ( !V_strcasecmp( pParamString, "apply" ) ) { pStructMem->m_opType = S_GetExpressionType( pValueString ); } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorVec3 // Setting a single, simple scratch pad Expression //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorVec3, "math_vec3" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorVec3, m_flOutput, SO_VEC3, "output" ); SOS_REGISTER_INPUT_FLOAT( CSosOperatorVec3, m_flInput1, SO_VEC3, "input1" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorVec3, m_flInput2, SO_VEC3, "input2") SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorVec3, "math_vec3" ) void CSosOperatorVec3::SetDefaults( void *pVoidMem ) const { CSosOperatorVec3_t *pStructMem = (CSosOperatorVec3_t *)pVoidMem; SOS_INIT_OUTPUT_VAR( m_flOutput, SO_VEC3, 0.0 ) SOS_INIT_INPUT_VAR( m_flInput1, SO_VEC3, 0.0 ) SOS_INIT_INPUT_VAR( m_flInput2, SO_VEC3, 0.0 ) pStructMem->m_opType = SO_OP_MULT; } void CSosOperatorVec3::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorVec3_t *pStructMem = (CSosOperatorVec3_t *)pVoidMem; for( int i = 0; i < SO_POSITION_ARRAY_SIZE; i++ ) { switch ( pStructMem->m_opType ) { case SO_OP_NONE: break; case SO_OP_SET: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i]; break; case SO_OP_ADD: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] + pStructMem->m_flInput2[i]; break; case SO_OP_SUB: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] - pStructMem->m_flInput2[i]; break; case SO_OP_MULT: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] * pStructMem->m_flInput2[i]; break; case SO_OP_DIV: if ( pStructMem->m_flInput2[i] > 0.0 ) { pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] / pStructMem->m_flInput2[i]; } break; case SO_OP_MOD: if ( pStructMem->m_flInput2[i] > 0.0 ) { pStructMem->m_flOutput[i] = fmodf( pStructMem->m_flInput1[i], pStructMem->m_flInput2[i] ); } break; case SO_OP_MAX: pStructMem->m_flOutput[i] = MAX(pStructMem->m_flInput1[i], pStructMem->m_flInput2[i]); break; case SO_OP_MIN: pStructMem->m_flOutput[i] = MIN(pStructMem->m_flInput1[i], pStructMem->m_flInput2[i]); break; case SO_OP_INV: pStructMem->m_flOutput[i] = 1.0 - pStructMem->m_flInput1[i]; break; case SO_OP_GT: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] > pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; case SO_OP_LT: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] < pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; case SO_OP_GTOE: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] >= pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; case SO_OP_LTOE: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] <= pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; case SO_OP_EQ: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] == pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; default: break; } } } void CSosOperatorVec3::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { CSosOperatorVec3_t *pStructMem = (CSosOperatorVec3_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); S_PrintOpType( pStructMem->m_opType, nLevel ); } void CSosOperatorVec3::OpHelp( ) const { } void CSosOperatorVec3::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorVec3_t *pStructMem = (CSosOperatorVec3_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else if ( !V_strcasecmp( pParamString, "apply" ) ) { pStructMem->m_opType = S_GetExpressionType( pValueString ); } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorSpeakers //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorSpeakers, "math_speakers" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorSpeakers, m_flOutput, SO_SPEAKERS, "output" ); SOS_REGISTER_INPUT_FLOAT( CSosOperatorSpeakers, m_flInput1, SO_SPEAKERS, "input1" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorSpeakers, m_flInput2, SO_SPEAKERS, "input2") SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorSpeakers, "math_speakers" ) void CSosOperatorSpeakers::SetDefaults( void *pVoidMem ) const { CSosOperatorSpeakers_t *pStructMem = (CSosOperatorSpeakers_t *)pVoidMem; SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SPEAKERS, 0.0 ) SOS_INIT_INPUT_VAR( m_flInput1, SO_SPEAKERS, 0.0 ) SOS_INIT_INPUT_VAR( m_flInput2, SO_SPEAKERS, 0.0 ) pStructMem->m_opType = SO_OP_MULT; } void CSosOperatorSpeakers::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorSpeakers_t *pStructMem = (CSosOperatorSpeakers_t *)pVoidMem; for( int i = 0; i < SO_MAX_SPEAKERS; i++ ) { switch ( pStructMem->m_opType ) { case SO_OP_NONE: break; case SO_OP_SET: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i]; break; case SO_OP_ADD: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] + pStructMem->m_flInput2[i]; break; case SO_OP_SUB: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] - pStructMem->m_flInput2[i]; break; case SO_OP_MULT: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] * pStructMem->m_flInput2[i]; break; case SO_OP_DIV: if ( pStructMem->m_flInput2[i] > 0.0 ) { pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] / pStructMem->m_flInput2[i]; } break; case SO_OP_MOD: if ( pStructMem->m_flInput2[i] > 0.0 ) { pStructMem->m_flOutput[i] = fmodf( pStructMem->m_flInput1[i], pStructMem->m_flInput2[i] ); } break; case SO_OP_MAX: pStructMem->m_flOutput[i] = MAX( pStructMem->m_flInput1[i], pStructMem->m_flInput2[i] ); break; case SO_OP_MIN: pStructMem->m_flOutput[i] = MIN( pStructMem->m_flInput1[1], pStructMem->m_flInput2[i] ); break; case SO_OP_INV: pStructMem->m_flOutput[i] = 1.0 - pStructMem->m_flInput1[i]; break; case SO_OP_GT: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] > pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; case SO_OP_LT: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] < pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; case SO_OP_GTOE: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] >= pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; case SO_OP_LTOE: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] <= pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; case SO_OP_EQ: pStructMem->m_flOutput[i] = pStructMem->m_flInput1[i] == pStructMem->m_flInput2[i] ? 1.0 : 0.0; break; default: break; } } } void CSosOperatorSpeakers::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { CSosOperatorSpeakers_t *pStructMem = (CSosOperatorSpeakers_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); S_PrintOpType( pStructMem->m_opType, nLevel ); } void CSosOperatorSpeakers::OpHelp( ) const { } void CSosOperatorSpeakers::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorSpeakers_t *pStructMem = (CSosOperatorSpeakers_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else if ( !V_strcasecmp( pParamString, "apply" ) ) { pStructMem->m_opType = S_GetExpressionType( pValueString ); } else if ( !V_strcasecmp( pParamString, "left_front" ) ) { pStructMem->m_flInput1[IFRONT_LEFT] = RandomInterval( ReadInterval( pValueString ) ); } else if ( !V_strcasecmp( pParamString, "right_front" ) ) { pStructMem->m_flInput1[IFRONT_RIGHT] = RandomInterval( ReadInterval( pValueString ) ); } else if ( !V_strcasecmp( pParamString, "left_rear" ) ) { pStructMem->m_flInput1[IREAR_LEFT] = RandomInterval( ReadInterval( pValueString ) ); } else if ( !V_strcasecmp( pParamString, "right_rear" ) ) { pStructMem->m_flInput1[IREAR_RIGHT] = RandomInterval( ReadInterval( pValueString ) ); } else if ( !V_strcasecmp( pParamString, "center" ) ) { pStructMem->m_flInput1[IFRONT_CENTER] = RandomInterval( ReadInterval( pValueString ) ); } else if ( !V_strcasecmp( pParamString, "lfe" ) ) { pStructMem->m_flInput1[IFRONT_CENTER0] = RandomInterval( ReadInterval( pValueString ) ); } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorFloatAccumulate12 // Setting a single, simple scratch pad Expression //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorFloatAccumulate12, "math_float_accumulate12" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flOutput, SO_SINGLE, "output" ); SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput1, SO_SINGLE, "input1" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput2, SO_SINGLE, "input2") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput3, SO_SINGLE, "input3") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput4, SO_SINGLE, "input4") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput5, SO_SINGLE, "input5") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput6, SO_SINGLE, "input6") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput7, SO_SINGLE, "input7") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput8, SO_SINGLE, "input8") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput9, SO_SINGLE, "input9") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput10, SO_SINGLE, "input10") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput11, SO_SINGLE, "input11") SOS_REGISTER_INPUT_FLOAT( CSosOperatorFloatAccumulate12, m_flInput12, SO_SINGLE, "input12") SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorFloatAccumulate12, "math_float_accumulate12" ) void CSosOperatorFloatAccumulate12::SetDefaults( void *pVoidMem ) const { CSosOperatorFloatAccumulate12_t *pStructMem = (CSosOperatorFloatAccumulate12_t *)pVoidMem; SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput1, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput2, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput3, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput4, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput5, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput6, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput7, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput8, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput9, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput10, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput11, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput12, SO_SINGLE, 1.0 ) // do nothing by default pStructMem->m_opType = SO_OP_MULT; } void CSosOperatorFloatAccumulate12::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorFloatAccumulate12_t *pStructMem = (CSosOperatorFloatAccumulate12_t *)pVoidMem; float flResult = 0.0; switch ( pStructMem->m_opType ) { case SO_OP_NONE: break; case SO_OP_SET: Log_Warning( LOG_SND_OPERATORS, "Error: %s : Math expression type not currently supported in sound operator math_float_accumulate12\n", pStack->GetOperatorName( nOpIndex ) ); break; case SO_OP_ADD: flResult = pStructMem->m_flInput1[0] + pStructMem->m_flInput2[0] + pStructMem->m_flInput3[0] + pStructMem->m_flInput4[0] + pStructMem->m_flInput5[0] + pStructMem->m_flInput6[0] + pStructMem->m_flInput7[0] + pStructMem->m_flInput8[0] + pStructMem->m_flInput9[0] + pStructMem->m_flInput10[0] + pStructMem->m_flInput11[0] + pStructMem->m_flInput12[0]; break; case SO_OP_SUB: flResult = pStructMem->m_flInput1[0] - pStructMem->m_flInput2[0] - pStructMem->m_flInput3[0] - pStructMem->m_flInput4[0] - pStructMem->m_flInput5[0] - pStructMem->m_flInput6[0] - pStructMem->m_flInput7[0] - pStructMem->m_flInput8[0] - pStructMem->m_flInput9[0] - pStructMem->m_flInput10[0] - pStructMem->m_flInput11[0] - pStructMem->m_flInput12[0]; break; case SO_OP_MULT: flResult = pStructMem->m_flInput1[0] * pStructMem->m_flInput2[0] * pStructMem->m_flInput3[0] * pStructMem->m_flInput4[0] * pStructMem->m_flInput5[0] * pStructMem->m_flInput6[0] * pStructMem->m_flInput7[0] * pStructMem->m_flInput8[0] * pStructMem->m_flInput9[0] * pStructMem->m_flInput10[0] * pStructMem->m_flInput11[0] * pStructMem->m_flInput12[0]; break; case SO_OP_DIV: flResult = pStructMem->m_flInput1[0] / pStructMem->m_flInput2[0] / pStructMem->m_flInput3[0] / pStructMem->m_flInput4[0] / pStructMem->m_flInput5[0] / pStructMem->m_flInput6[0] / pStructMem->m_flInput7[0] / pStructMem->m_flInput8[0] / pStructMem->m_flInput9[0] / pStructMem->m_flInput10[0] / pStructMem->m_flInput11[0] / pStructMem->m_flInput12[0]; break; case SO_OP_MAX: Log_Warning( LOG_SND_OPERATORS, "Error: %s : Math expression type not currently supported in sound operator math_float_accumulate12\n", pStack->GetOperatorName( nOpIndex ) ); break; case SO_OP_MIN: Log_Warning( LOG_SND_OPERATORS, "Error: %s : Math expression type not currently supported in sound operator math_float_accumulate12\n", pStack->GetOperatorName( nOpIndex ) ); break; case SO_OP_EQ: Log_Warning( LOG_SND_OPERATORS, "Error: %s : Math expression type not currently supported in sound operator math_float_accumulate12\n", pStack->GetOperatorName( nOpIndex ) ); break; case SO_OP_INV_SCALE: Log_Warning( LOG_SND_OPERATORS, "Error: %s : Math expression type not currently supported in sound operator math_float_accumulate12\n", pStack->GetOperatorName( nOpIndex ) ); break; default: Log_Warning( LOG_SND_OPERATORS, "Error: %s : Math expression type not currently supported in sound operator math_float_accumulate12\n", pStack->GetOperatorName( nOpIndex ) ); break; } pStructMem->m_flOutput[0] = flResult; } void CSosOperatorFloatAccumulate12::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { CSosOperatorFloatAccumulate12_t *pStructMem = (CSosOperatorFloatAccumulate12_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); S_PrintOpType( pStructMem->m_opType, nLevel ); } void CSosOperatorFloatAccumulate12::OpHelp( ) const { } void CSosOperatorFloatAccumulate12::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorFloatAccumulate12_t *pStructMem = (CSosOperatorFloatAccumulate12_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else if ( !V_strcasecmp( pParamString, "apply" ) ) { pStructMem->m_opType = S_GetExpressionType( pValueString ); } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorSourceDistance // Setting a single, simple scratch pad Expression //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorSourceDistance, "calc_source_distance" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorSourceDistance, m_flOutput, SO_SINGLE, "output" ); SOS_REGISTER_INPUT_FLOAT( CSosOperatorSourceDistance, m_flInputPos, SO_VEC3, "input_position" ) SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorSourceDistance, "calc_source_distance" ) void CSosOperatorSourceDistance::SetDefaults( void *pVoidMem ) const { CSosOperatorSourceDistance_t *pStructMem = (CSosOperatorSourceDistance_t *)pVoidMem; SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInputPos, SO_VEC3, 0.0 ) pStructMem->m_b2D = false; pStructMem->m_bForceNotPlayerSound = false; } void CSosOperatorSourceDistance::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorSourceDistance_t *pStructMem = (CSosOperatorSourceDistance_t *)pVoidMem; pStructMem->m_flOutput[0] = FLT_MAX; // calculate the distance to the nearest ss player FOR_EACH_VALID_SPLITSCREEN_PLAYER( hh ) { Vector vSource; if ( pScratchPad->m_bIsPlayerSound && !pStructMem->m_bForceNotPlayerSound ) { // Hack for now // get 2d forward direction vector, ignoring pitch angle Vector listener_forward2d; ConvertListenerVectorTo2D( &listener_forward2d, &pScratchPad->m_vPlayerRight[ hh ] ); // player sounds originate from 1' in front of player, 2d VectorMultiply(listener_forward2d, 12.0, vSource ); } else { Vector vPosition; vPosition[0] = pStructMem->m_flInputPos[0]; vPosition[1] = pStructMem->m_flInputPos[1]; vPosition[2] = pStructMem->m_flInputPos[2]; VectorSubtract( vPosition, pScratchPad->m_vPlayerOrigin[ hh ], vSource ); } // normalize source_vec and get distance from listener to source float checkDist = 0.0; if ( pStructMem->m_b2D ) { checkDist = vSource.Length2D(); } else { checkDist = VectorNormalize( vSource ); } if ( checkDist < pStructMem->m_flOutput[0] ) { pStructMem->m_flOutput[0] = checkDist; } } } void CSosOperatorSourceDistance::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { // CSosOperatorSourceDistance_t *pStructMem = (CSosOperatorSourceDistance_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); } void CSosOperatorSourceDistance::OpHelp( ) const { } void CSosOperatorSourceDistance::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorSourceDistance_t *pStructMem = (CSosOperatorSourceDistance_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else if ( !V_strcasecmp( pParamString, "in2D" ) ) { if ( !V_strcasecmp( pValueString, "false" ) ) { pStructMem->m_b2D = false; } else if ( !V_strcasecmp( pValueString, "true" ) ) { pStructMem->m_b2D = true; } } else if ( !V_strcasecmp( pParamString, "force_not_player_sound" ) ) { if ( !V_strcasecmp( pValueString, "false" ) ) { pStructMem->m_bForceNotPlayerSound = false; } else if ( !V_strcasecmp( pValueString, "true" ) ) { pStructMem->m_bForceNotPlayerSound = true; } } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorFacing // Setting a single, simple scratch pad Expression //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorFacing, "calc_angles_facing" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorFacing, m_flInputAngles, SO_VEC3, "input_angles" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorFacing, m_flOutput, SO_SINGLE, "output" ) SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorFacing, "calc_angles_facing" ) void CSosOperatorFacing::SetDefaults( void *pVoidMem ) const { CSosOperatorFacing_t *pStructMem = (CSosOperatorFacing_t *)pVoidMem; SOS_INIT_INPUT_VAR( m_flInputAngles, SO_VEC3, 0.0 ) SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SINGLE, 0.0 ) } void CSosOperatorFacing::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorFacing_t *pStructMem = (CSosOperatorFacing_t *)pVoidMem; if( !pChannel ) { Log_Warning( LOG_SND_OPERATORS, "Error: Sound operator %s requires valid channel pointer, being called without one\n", pStack->GetOperatorName( nOpIndex )); return; } QAngle vAngles; vAngles[0] = pStructMem->m_flInputAngles[0]; vAngles[1] = pStructMem->m_flInputAngles[1]; vAngles[2] = pStructMem->m_flInputAngles[2]; float flFacing = SND_GetFacingDirection( pChannel, pScratchPad->m_vBlendedListenerOrigin, vAngles ); pStructMem->m_flOutput[0] = (flFacing + 1.0) * 0.5; } void CSosOperatorFacing::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { // CSosOperatorFacing_t *pStructMem = (CSosOperatorFacing_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); } void CSosOperatorFacing::OpHelp( ) const { } void CSosOperatorFacing::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorFacing_t *pStructMem = (CSosOperatorFacing_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorRemapValue // Setting a single, simple scratch pad Expression //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorRemapValue, "math_remap_float" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorRemapValue, m_flInput, SO_SINGLE, "input" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorRemapValue, m_flInputMin, SO_SINGLE, "input_min" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorRemapValue, m_flInputMax, SO_SINGLE, "input_max" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorRemapValue, m_flInputMapMin, SO_SINGLE, "input_map_min" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorRemapValue, m_flInputMapMax, SO_SINGLE, "input_map_max" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorRemapValue, m_flOutput, SO_SINGLE, "output" ) SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorRemapValue, "math_remap_float" ) void CSosOperatorRemapValue::SetDefaults( void *pVoidMem ) const { CSosOperatorRemapValue_t *pStructMem = (CSosOperatorRemapValue_t *)pVoidMem; SOS_INIT_INPUT_VAR( m_flInputMin, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInputMax, SO_SINGLE, 0.1 ) SOS_INIT_INPUT_VAR( m_flInputMapMin, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInputMapMax, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInput, SO_SINGLE, 0.0 ) SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SINGLE, 0.0 ) pStructMem->m_bClampRange = true; pStructMem->m_bDefaultMax = true; } void CSosOperatorRemapValue::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorRemapValue_t *pStructMem = (CSosOperatorRemapValue_t *)pVoidMem; float flResult; float flValue = pStructMem->m_flInput[0]; float flMin = pStructMem->m_flInputMin[0]; float flMax = pStructMem->m_flInputMax[0]; float flMapMin = pStructMem->m_flInputMapMin[0]; float flMapMax = pStructMem->m_flInputMapMax[0]; // if ( flMin > flMax ) // { // Log_Warning( LOG_SND_OPERATORS, "Warning: remap_value operator min arg is greater than max arg\n"); // // } if ( flMapMin > flMapMax && flMin != flMax ) { // swap everything around float flTmpMin = flMapMin; flMapMin = flMapMax; flMapMax = flTmpMin; flTmpMin = flMin; flMin = flMax; flMax = flTmpMin; // Log_Warning( LOG_SND_OPERATORS, "Warning: remap_value operator map min arg is greater than map max arg\n"); } if( flMin == flMax ) { if( flValue < flMin) { flResult = flMapMin; } else if( flValue > flMax ) { flResult = flMapMax; } else { flResult = pStructMem->m_bDefaultMax ? flMapMax : flMapMin; } } else if ( flMapMin == flMapMax ) { flResult = flMapMin; } else if( flValue <= flMin && flMin < flMax ) { flResult = flMapMin; } else if( flValue >= flMax && flMax > flMin) { flResult = flMapMax; } else if( flValue >= flMin && flMin > flMax ) { flResult = flMapMin; } else if( flValue <= flMax && flMax < flMin) { flResult = flMapMax; } else { flResult = RemapVal( flValue, flMin, flMax, flMapMin, flMapMax ); // flResult = SOS_RESCALE( flValue, flMin, flMax, flMapMin, flMapMax ); } if( pStructMem->m_bClampRange ) { if( flMapMin < flMapMax ) { flResult = clamp( flResult, flMapMin, flMapMax ); } else { flResult = clamp( flResult, flMapMax, flMapMin ); } } pStructMem->m_flOutput[0] = flResult; } void CSosOperatorRemapValue::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { // CSosOperatorRemapValue_t *pStructMem = (CSosOperatorRemapValue_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); } void CSosOperatorRemapValue::OpHelp( ) const { } void CSosOperatorRemapValue::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorRemapValue_t *pStructMem = (CSosOperatorRemapValue_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else if ( !V_strcasecmp( pParamString, "clamp_range" ) ) { if ( !V_strcasecmp( pValueString, "false" ) ) { pStructMem->m_bClampRange = false; } } else if ( !V_strcasecmp( pParamString, "default_to_max" ) ) { if ( !V_strcasecmp( pValueString, "false" ) ) { pStructMem->m_bDefaultMax = false; } } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorCurve4 //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorCurve4, "math_curve_2d_4knot" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorCurve4, m_flInput, SO_SINGLE, "input" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorCurve4, m_flOutput, SO_SINGLE, "output" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorCurve4, m_flInputX1, SO_SINGLE, "input_X1" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorCurve4, m_flInputY1, SO_SINGLE, "input_Y1" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorCurve4, m_flInputX2, SO_SINGLE, "input_X2" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorCurve4, m_flInputY2, SO_SINGLE, "input_Y2" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorCurve4, m_flInputX3, SO_SINGLE, "input_X3" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorCurve4, m_flInputY3, SO_SINGLE, "input_Y3" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorCurve4, m_flInputX4, SO_SINGLE, "input_X4" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorCurve4, m_flInputY4, SO_SINGLE, "input_Y4" ) SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorCurve4, "math_curve_2d_4knot" ) void CSosOperatorCurve4::SetDefaults( void *pVoidMem ) const { CSosOperatorCurve4_t *pStructMem = (CSosOperatorCurve4_t *)pVoidMem; SOS_INIT_INPUT_VAR( m_flInput, SO_SINGLE, 0.0 ) SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInputX1, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInputY1, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInputX2, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInputY2, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInputX3, SO_SINGLE, 2.0 ) SOS_INIT_INPUT_VAR( m_flInputY3, SO_SINGLE, 2.0 ) SOS_INIT_INPUT_VAR( m_flInputX4, SO_SINGLE, 3.0 ) SOS_INIT_INPUT_VAR( m_flInputY4, SO_SINGLE, 3.0 ) pStructMem->m_nCurveType = SO_OP_CURVETYPE_STEP; } void CSosOperatorCurve4::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorCurve4_t *pStructMem = (CSosOperatorCurve4_t *)pVoidMem; float flResult = 0.0; float flInput = pStructMem->m_flInput[0]; if ( flInput >= pStructMem->m_flInputX4[0] ) { flResult = pStructMem->m_flInputY4[0]; } else if ( flInput <= pStructMem->m_flInputX1[0] ) { flResult = pStructMem->m_flInputY1[0]; } else { float flX[4]; float flY[4]; flX[0] = pStructMem->m_flInputX1[0]; flX[1] = pStructMem->m_flInputX2[0]; flX[2] = pStructMem->m_flInputX3[0]; flX[3] = pStructMem->m_flInputX4[0]; flY[0] = pStructMem->m_flInputY1[0]; flY[1] = pStructMem->m_flInputY2[0]; flY[2] = pStructMem->m_flInputY3[0]; flY[3] = pStructMem->m_flInputY4[0]; int i; for( i = 0; i < (4 - 1); i++ ) { if( flInput > flX[i] && flInput < flX[i+1] ) { break; } } if( pStructMem->m_nCurveType == SO_OP_CURVETYPE_STEP ) { flResult = flY[i]; } else if( pStructMem->m_nCurveType == SO_OP_CURVETYPE_LINEAR ) { flResult = SOS_RESCALE( flInput, flX[i], flX[i+1], flY[i], flY[i+1] ); } } pStructMem->m_flOutput[0] = flResult; } void CSosOperatorCurve4::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { CSosOperatorCurve4_t *pStructMem = (CSosOperatorCurve4_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); Log_Msg( LOG_SND_OPERATORS, OpColor, "%*scurve_type: %s\n", nLevel, " ", pStructMem->m_nCurveType == SO_OP_CURVETYPE_STEP ? "step": "linear" ); } void CSosOperatorCurve4::OpHelp( ) const { } void CSosOperatorCurve4::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorCurve4_t *pStructMem = (CSosOperatorCurve4_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else if ( !V_strcasecmp( pParamString, "curve_type" ) ) { if ( !V_strcasecmp( pValueString, "step" ) ) { pStructMem->m_nCurveType = SO_OP_CURVETYPE_STEP; } else if ( !V_strcasecmp( pValueString, "linear" ) ) { pStructMem->m_nCurveType = SO_OP_CURVETYPE_LINEAR; } } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorRandom //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorRandom, "math_random" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorRandom, m_flInputMin, SO_SINGLE, "input_min" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorRandom, m_flInputMax, SO_SINGLE, "input_max" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorRandom, m_flInputSeed, SO_SINGLE, "input_seed" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorRandom, m_flOutput, SO_SINGLE, "output" ) SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorRandom, "math_random" ) void CSosOperatorRandom::SetDefaults( void *pVoidMem ) const { CSosOperatorRandom_t *pStructMem = (CSosOperatorRandom_t *)pVoidMem; SOS_INIT_INPUT_VAR( m_flInputMin, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInputMax, SO_SINGLE, 1.0 ) SOS_INIT_INPUT_VAR( m_flInputSeed, SO_SINGLE, -1.0 ) SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SINGLE, 1.0 ) pStructMem->m_bRoundToInt = false; } void CSosOperatorRandom::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorRandom_t *pStructMem = (CSosOperatorRandom_t *)pVoidMem; if( pStructMem->m_flInputSeed[0] < 0.0 ) { int iSeed = (int)( Plat_FloatTime() * 100 ); g_pSoundOperatorSystem->m_operatorRandomStream.SetSeed( iSeed ); } else { g_pSoundOperatorSystem->m_operatorRandomStream.SetSeed( (int) pStructMem->m_flInputSeed[0] ); } float fResult = g_pSoundOperatorSystem->m_operatorRandomStream.RandomFloat( pStructMem->m_flInputMin[0], pStructMem->m_flInputMax[0] ); if( pStructMem->m_bRoundToInt ) { int nRound = (int) (fResult + 0.5); if( nRound < (int) pStructMem->m_flInputMin[0] ) { nRound++; } else if( nRound > (int) pStructMem->m_flInputMax[0] ) { nRound--; } fResult = (float) nRound; } pStructMem->m_flOutput[0] = fResult; } void CSosOperatorRandom::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { // CSosOperatorRandom_t *pStructMem = (CSosOperatorRandom_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); } void CSosOperatorRandom::OpHelp( ) const { } void CSosOperatorRandom::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorRandom_t *pStructMem = (CSosOperatorRandom_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else if ( !V_strcasecmp( pParamString, "round_to_int" ) ) { if ( !V_strcasecmp( pValueString, "false" ) ) { pStructMem->m_bRoundToInt = false; } else if ( !V_strcasecmp( pValueString, "true" ) ) { pStructMem->m_bRoundToInt = true; } } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } } //----------------------------------------------------------------------------- // CSosOperatorLogicOperator //----------------------------------------------------------------------------- SOS_BEGIN_OPERATOR_CONSTRUCTOR( CSosOperatorLogicSwitch, "math_logic_switch" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorLogicSwitch, m_flInput1, SO_SINGLE, "input1" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorLogicSwitch, m_flInput2, SO_SINGLE, "input2" ) SOS_REGISTER_INPUT_FLOAT( CSosOperatorLogicSwitch, m_flInputSwitch, SO_SINGLE, "input_switch" ) SOS_REGISTER_OUTPUT_FLOAT( CSosOperatorLogicSwitch, m_flOutput, SO_SINGLE, "output" ) SOS_END_OPERATOR_CONSTRUCTOR( CSosOperatorLogicSwitch, "math_logic_switch" ) void CSosOperatorLogicSwitch::SetDefaults( void *pVoidMem ) const { CSosOperatorLogicSwitch_t *pStructMem = (CSosOperatorLogicSwitch_t *)pVoidMem; SOS_INIT_INPUT_VAR( m_flInput1, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInput2, SO_SINGLE, 0.0 ) SOS_INIT_INPUT_VAR( m_flInputSwitch, SO_SINGLE, 0.0 ) SOS_INIT_OUTPUT_VAR( m_flOutput, SO_SINGLE, 1.0 ) } void CSosOperatorLogicSwitch::Execute( void *pVoidMem, channel_t *pChannel, CScratchPad *pScratchPad, CSosOperatorStack *pStack, int nOpIndex ) const { CSosOperatorLogicSwitch_t *pStructMem = (CSosOperatorLogicSwitch_t *)pVoidMem; pStructMem->m_flOutput[0] = ( (pStructMem->m_flInputSwitch[0] > 0) ? ( pStructMem->m_flInput2[0] ) : ( pStructMem->m_flInput1[0] ) ); } void CSosOperatorLogicSwitch::Print( void *pVoidMem, CSosOperatorStack *pStack, int nOpIndex, int nLevel ) const { // CSosOperatorRandom_t *pStructMem = (CSosOperatorRandom_t *)pVoidMem; PrintBaseParams( pVoidMem, pStack, nOpIndex, nLevel ); } void CSosOperatorLogicSwitch::OpHelp( ) const { } void CSosOperatorLogicSwitch::ParseKV( CSosOperatorStack *pStack, void *pVoidMem, KeyValues *pOpKeys ) const { CSosOperatorLogicSwitch_t *pStructMem = (CSosOperatorLogicSwitch_t *)pVoidMem; KeyValues *pParams = pOpKeys->GetFirstSubKey(); while ( pParams ) { const char *pParamString = pParams->GetName(); const char *pValueString = pParams->GetString(); if ( pParamString && *pParamString ) { if ( pValueString && *pValueString ) { if ( BaseParseKV( pStack, (CSosOperator_t *)pStructMem, pParamString, pValueString ) ) { } else { Log_Warning( LOG_SND_OPERATORS, "Error: Operator %s, unknown sound operator attribute %s\n", pStack->m_pCurrentOperatorName, pParamString ); } } } pParams = pParams->GetNextKey(); } }
30.357143
176
0.688055
DannyParker0001
a0458cebda3e2326dbc153532319f242f3b2e592
7,340
cpp
C++
core/Transaction/Transfer.cpp
mm-s/symbol-sdk-cpp
2151503ff69d582de47acde1dffae02ed21e78ab
[ "MIT" ]
null
null
null
core/Transaction/Transfer.cpp
mm-s/symbol-sdk-cpp
2151503ff69d582de47acde1dffae02ed21e78ab
[ "MIT" ]
null
null
null
core/Transaction/Transfer.cpp
mm-s/symbol-sdk-cpp
2151503ff69d582de47acde1dffae02ed21e78ab
[ "MIT" ]
null
null
null
/** *** Copyright (c) 2016-2019, Jaguar0625, gimre, BloodyRookie, Tech Bureau, Corp. *** Copyright (c) 2020-present, Jaguar0625, gimre, BloodyRookie. *** All rights reserved. *** *** This file is part of Catapult. *** *** Catapult 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 3 of the License, or *** (at your option) any later version. *** *** Catapult 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 Catapult. If not, see <http://www.gnu.org/licenses/>. **/ #include "Transfer.h" #include "../catapult/BufferInputStreamAdapter.h" #include "../catapult/EntityIoUtils.h" #include "../Network.h" #include "../catapult/TransferBuilder.h" #include "../catapult/SharedKey.h" #include "../catapult/CryptoUtils.h" #include "../catapult/AesDecrypt.h" #include "../catapult/SecureRandomGenerator.h" #include "../catapult/OpensslContexts.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wreserved-id-macro" #endif #include <openssl/evp.h> #ifdef __clang__ #pragma clang diagnostic pop #endif namespace symbol { namespace core { /// Implementation for the class c using c = core::Transfer; using std::move; using std::ostringstream; using std::make_pair; c::Transfer(const Network& n, ptr<catapult::model::TransferTransaction> t): m_catapultTransferTx(t), b(n, t) { } c::Transfer(Transfer&& other): b(move(other)), m_catapultTransferTx(other.m_catapultTransferTx) { other.m_catapultTransferTx = nullptr; } pair<ko, ptr<Transfer>> c::create(const Network& n, const Blob& mem) { auto is = catapult::io::BufferInputStreamAdapter(mem); // catapult::model::IsSizeValidT<catapult::model::Transaction> // EntityType type= // BasicEntityType bet=catapult::model::ToBasicEntityType(entity.Type); std::unique_ptr<catapult::model::TransferTransaction> ptx; try { ptx = catapult::io::ReadEntity<catapult::model::TransferTransaction>(is); assert(ptx->Type == catapult::model::Entity_Type_Transfer); } catch (...) { ///CATAPULT_THROW_INVALID_ARGUMENT("size is insufficient"); return make_pair("KO 84039", nullptr); } if (n.identifier() != ptx->Network) { return make_pair("KO 82291", nullptr); } return make_pair(ok, new Transfer(n, ptx.release())); } /* uint64_t Random() { return utils::LowEntropyRandomGenerator()(); } uint8_t RandomByte() { return static_cast<uint8_t>(Random()); } std::generate_n(container.begin(), container.size(), []() { return static_cast<typename T::value_type>(RandomByte()); }); */ namespace { using namespace catapult; void Prepend(std::vector<uint8_t>& buffer, RawBuffer prefix) { buffer.resize(buffer.size() + prefix.Size); std::memmove(buffer.data() + prefix.Size, buffer.data(), buffer.size() - prefix.Size); std::memcpy(buffer.data(), prefix.pData, prefix.Size); } void AesGcmEncrypt( const crypto::SharedKey& encryptionKey, const crypto::AesGcm256::IV& iv, const RawBuffer& input, std::vector<uint8_t>& output) { // encrypt input into output output.resize(input.Size); auto outputSize = static_cast<int>(output.size()); utils::memcpy_cond(output.data(), input.pData, input.Size); crypto::OpensslCipherContext cipherContext; cipherContext.dispatch(EVP_EncryptInit_ex, EVP_aes_256_gcm(), nullptr, encryptionKey.data(), iv.data()); if (0 != outputSize) cipherContext.dispatch(EVP_EncryptUpdate, output.data(), &outputSize, output.data(), outputSize); cipherContext.dispatch(EVP_EncryptFinal_ex, output.data() + outputSize, &outputSize); // get tag crypto::AesGcm256::Tag tag; cipherContext.dispatch(EVP_CIPHER_CTX_ctrl, EVP_CTRL_GCM_GET_TAG, 16, tag.data()); // tag || iv || data Prepend(output, iv); Prepend(output, tag); } } pair<ko, c::Msg> c::encrypt(const c::Msg& clearText, const PrivateKey& src, const PublicKey& rcpt) { using namespace catapult::crypto; Keys srcKeys(src); auto sharedKey = DeriveSharedKey(srcKeys, rcpt); Msg encrypted; SecureRandomGenerator g; AesGcm256::IV iv; try { g.fill(iv.data(), iv.size()); } catch(...) { return make_pair("KO 88119 Could not generate secure random bits.", move(encrypted)); } AesGcmEncrypt(sharedKey, iv, clearText, encrypted); return make_pair(ok, move(encrypted)); } pair<ko, ptr<Transfer>> c::create(const Network& n, const UnresolvedAddress& rcpt, const MosaicValues& m, const Amount& maxfee, const TimeSpan& deadline, const Msg& msg, const ptr<PrivateKey>& encryptPrivateKey, const ptr<PublicKey>& encryptPublicKey) { PublicKey unused; catapult::builders::TransferBuilder builder(n.identifier(), unused); Msg finalMsg; if (encryptPrivateKey != nullptr) { if (encryptPublicKey == nullptr) { return make_pair("KO 33092 Recipient Public Key is required.", nullptr); } if (msg.empty()) { return make_pair("KO 33092 Message is empty.", nullptr); } auto addr = n.newAddress(*encryptPublicKey); if (*addr != rcpt) { delete addr; return make_pair("KO 33092 Encryption Public Key must correspond to the recipient address.", nullptr); } delete addr; auto r = encrypt(msg, *encryptPrivateKey, *encryptPublicKey); if (is_ko(r.first)) { return make_pair(r.first, nullptr); } Keys myKeys(*encryptPrivateKey); finalMsg.resize(1+myKeys.publicKey().Size+r.second.size()); finalMsg[0]='\1'; auto dest=finalMsg.data()+1; memcpy(dest, myKeys.publicKey().data(), myKeys.publicKey().Size); dest+=myKeys.publicKey().Size; memcpy(dest, r.second.data(), r.second.size()); } else { finalMsg=msg; finalMsg.insert(finalMsg.begin(), '\0'); } if (!finalMsg.empty()) { builder.setMessage(catapult::utils::RawBuffer(finalMsg.data(), finalMsg.size())); } builder.setRecipientAddress(rcpt); // for (const auto& seed : seeds) { // auto mosaicId = mosaicNameToMosaicIdMap.at(seed.Name); // builder.addMosaic({ mosaicId, seed.Amount }); // } //cout << "xXXXXXXXXXXXXXX " << m.unwrap() << endl; //UnresolvedMosaicId um(m.unwrap()); for (auto& i: m) { builder.addMosaic({ UnresolvedMosaicId{i.first.unwrap()}, i.second }); } builder.setDeadline(Timestamp(deadline.millis())); auto x = builder.build().release(); //cout << "XXXXXXXXXXXXXXXXXXXX" << endl; //cout << x->Network << " " << x->Size << " bytes" << endl; return make_pair(ok, new Transfer(n, x)); } bool c::toStream(ostream& os) const { if (m_catapultTx==nullptr) { return false; } Blob buf; buf.resize(m_catapultTx->Size); memcpy(buf.data(), m_catapultTx, m_catapultTx->Size); os << catapult::utils::HexFormat(buf); return true; } }} // namespaces std::ostream& operator << (std::ostream& os, const symbol::core::Transfer& o) { o.toStream(os); return os; }
33.063063
254
0.68624
mm-s
a047ebe9dbb9beb28e8de88ae894ce1316a25205
4,310
cpp
C++
src/InputHandler.cpp
kaprikawn/target
36a38e789b7be5faad03ff1b48a45200eab7fa93
[ "MIT" ]
null
null
null
src/InputHandler.cpp
kaprikawn/target
36a38e789b7be5faad03ff1b48a45200eab7fa93
[ "MIT" ]
2
2017-05-31T11:48:08.000Z
2017-05-31T11:49:26.000Z
src/InputHandler.cpp
kaprikawn/target
36a38e789b7be5faad03ff1b48a45200eab7fa93
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include "InputHandler.hpp" #include "Game.hpp" InputHandler* InputHandler::s_pInstance = 0; void InputHandler::initialiseJoysticks() { if( SDL_WasInit( SDL_INIT_JOYSTICK ) == 0 ) { SDL_InitSubSystem( SDL_INIT_JOYSTICK ); } if( SDL_NumJoysticks() > 0 ) { for( int i = 0; i < SDL_NumJoysticks(); i++ ) { SDL_Joystick* joy = SDL_JoystickOpen( i ); if( joy == NULL ) { std::cout << SDL_GetError() << std::endl; } else { m_joysticks.push_back( joy ); //m_joystickValues.push_back( std::make_pair( new Vector2D( 0, 0 ), new Vector2D( 0, 0 ) ) ); for( int b = 0; b < SDL_JoystickNumButtons( joy ); b++ ) { m_buttonStates.push_back( false ); } } } SDL_JoystickEventState( SDL_ENABLE ); m_bJoysticksInitialised = true; } else { m_bJoysticksInitialised = false; } std::cout << "Initialised " << m_joysticks.size() << " joystick(s)" << std::endl; } void InputHandler::onKeyDown() { m_keystates = SDL_GetKeyboardState( NULL ); if( m_keystates[ SDL_SCANCODE_ESCAPE ] == 1 ) { TheGame::Instance() -> quit(); } } void InputHandler::onKeyUp() { m_keystates = SDL_GetKeyboardState( NULL ); } bool InputHandler::isKeyDown( SDL_Scancode key ) { if( m_keystates != 0 ) { if( m_keystates[key] == 1 ) { return true; } else { return false; } } return false; } bool InputHandler::isPressed( int button ) { if( button == 0 ) { if( m_keystates[ SDL_SCANCODE_RIGHT ] == 1 || currentHat == SDL_HAT_RIGHT || currentHat == SDL_HAT_RIGHTUP || currentHat == SDL_HAT_RIGHTDOWN ) { return true; } } else if( button == 1 ) { if( m_keystates[ SDL_SCANCODE_LEFT ] == 1 || currentHat == SDL_HAT_LEFT || currentHat == SDL_HAT_LEFTUP || currentHat == SDL_HAT_LEFTDOWN ) { return true; } } else if( button == 2 ) { if( m_keystates[ SDL_SCANCODE_UP ] == 1 || currentHat == SDL_HAT_UP || currentHat == SDL_HAT_LEFTUP || currentHat == SDL_HAT_RIGHTUP ) { return true; } } else if( button == 3 ) { if( m_keystates[ SDL_SCANCODE_DOWN ] == 1 || currentHat == SDL_HAT_DOWN || currentHat == SDL_HAT_LEFTDOWN || currentHat == SDL_HAT_RIGHTDOWN ) { return true; } } else if( button == 4 ) { // fire if( m_keystates[ SDL_SCANCODE_Z ] == 1 ) { return true; } if( m_gamepadsInitialised ) { if( m_buttonStates[ 2 ] ) { return true; } } } else if( button == 5 ) { // roll if( m_keystates[ SDL_SCANCODE_X ] == 1 ) { return true; } } else if( button == 6 ) { // bomb if( m_keystates[ SDL_SCANCODE_C ] == 1 ) { return true; } } else if( button == 7 ) { // start if( m_keystates[ SDL_SCANCODE_S ] == 1 ) { return true; } } else if( button == 8 ) { // quit if( m_keystates[ SDL_SCANCODE_Q ] == 1 ) { return true; } } else if( button == 9 ) { // ok if( m_keystates[ SDL_SCANCODE_O ] == 1 ) { return true; } } else if( button == 10 ) { // back if( m_keystates[ SDL_SCANCODE_BACKSPACE ] == 1 ) { return true; } } return false; } void InputHandler::onHatMotion( SDL_Event &event ) { if( !m_bJoysticksInitialised ) { return; } for( int i = 0; i < m_joysticks.size(); i++ ) { currentHat = SDL_JoystickGetHat( m_joysticks[i], 0 ); } } void InputHandler::update() { SDL_Event event; while( SDL_PollEvent( &event ) ) { switch( event.type ) { case SDL_QUIT: TheGame::Instance() -> quit(); break; case SDL_KEYDOWN: onKeyDown(); break; case SDL_KEYUP: onKeyUp(); break; case SDL_JOYHATMOTION: onHatMotion( event ); break; case SDL_JOYBUTTONDOWN: whichOne = event.jaxis.which; m_buttonStates[ event.jbutton.button ] = true; //printf( "%d pressed\n", event.jbutton.button ); break; case SDL_JOYBUTTONUP: whichOne = event.jaxis.which; m_buttonStates[ event.jbutton.button ] = false; break; default: break; } } } void InputHandler::clean() { if( m_gamepadsInitialised ) { for( unsigned int i = 0; i < SDL_NumJoysticks(); i++ ) { SDL_JoystickClose( m_joysticks[i] ); } } }
27.278481
149
0.588399
kaprikawn
a04bd9a30c84737eb29e298b575e5e6269570e87
336
cpp
C++
Source/remote_main.cpp
farkmarnum/imogen
f5a726e060315ea71de98f6b9eb06ba58bf2527d
[ "MIT" ]
null
null
null
Source/remote_main.cpp
farkmarnum/imogen
f5a726e060315ea71de98f6b9eb06ba58bf2527d
[ "MIT" ]
null
null
null
Source/remote_main.cpp
farkmarnum/imogen
f5a726e060315ea71de98f6b9eb06ba58bf2527d
[ "MIT" ]
null
null
null
#include <imogen_gui/imogen_gui.h> #include <lemons_app_utils/lemons_app_utils.h> namespace Imogen { struct RemoteApp : lemons::GuiApp<Remote> { RemoteApp() : lemons::GuiApp<Imogen::Remote> (String ("Imogen ") + TRANS ("Remote"), "0.0.1", { 1060, 640 }) { } }; } // namespace Imogen START_JUCE_APPLICATION (Imogen::RemoteApp)
18.666667
98
0.696429
farkmarnum
a04cdd61bd41801c12aacb89c7090ceabebe79d9
1,517
cpp
C++
Linked_List/InsertDLL.cpp
krcpr007/DSA-Abdul_Bari_codesAndPdfs-
06d19a936009502d39fb5e401e9d90bf6d7911c9
[ "MIT" ]
1
2021-12-06T13:49:47.000Z
2021-12-06T13:49:47.000Z
Linked_List/InsertDLL.cpp
krcpr007/DSA-Abdul_Bari_codesAndPdfs-
06d19a936009502d39fb5e401e9d90bf6d7911c9
[ "MIT" ]
null
null
null
Linked_List/InsertDLL.cpp
krcpr007/DSA-Abdul_Bari_codesAndPdfs-
06d19a936009502d39fb5e401e9d90bf6d7911c9
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; struct Node { struct Node *next; struct Node *prev; int data; } *first = NULL; void Create(int A[], int n) { struct Node *t, *last; first = new Node; first->data = A[0]; first->prev = first->next = NULL; last = first; for (int i = 1; i < n; i++) { t = new Node; t->data = A[i]; t->next = last->next; t->prev = last; last->next = t; last = t; } } void Display(struct Node *p) { while (p) { printf("%d ", p->data); p = p->next; } cout << endl; } int Length(struct Node *p) { int len = 0; while (p) { len++; p = p->next; } return len; } void InsertDLL(struct Node *p, int index, int x) { struct Node *t; if (index < 0 || index > Length(p)) { return; } if (index == 0) { t = new Node; t->data = x; t->prev = NULL; t->next = first; first->prev = t; first = t; } else { t = new Node; t->data = x; for (int i = 0; i < index - 1; i++) { p = p->next; } t->next = p->next; t->prev = p; if (p->next) { p->next->prev = t; } p->next = t; } } int main() { int Arr[] = {2, 3, 5, 7, 6, 0}; Create(Arr, 6); Display(first); InsertDLL(first, 2, 150); cout << endl; Display(first); return 0; }
16.138298
48
0.418589
krcpr007
a04d63c6ca2609b6ceb7488948b20ebbe116d4e4
730
hpp
C++
include/DataSeries/ByteField.hpp
sbu-fsl/DataSeries
8436462519eb22fc653387885b5f0339fb419061
[ "BSD-2-Clause" ]
6
2015-02-27T19:15:11.000Z
2018-10-25T14:22:31.000Z
include/DataSeries/ByteField.hpp
yoursunny/DataSeries
b5b9db8e40a79a3e546a59cd72a80be89412d7b2
[ "BSD-2-Clause" ]
7
2015-08-17T15:18:50.000Z
2017-08-16T00:16:19.000Z
include/DataSeries/ByteField.hpp
sbu-fsl/DataSeries
8436462519eb22fc653387885b5f0339fb419061
[ "BSD-2-Clause" ]
8
2015-07-13T23:02:28.000Z
2020-09-28T19:06:26.000Z
// -*-C++-*- /* (c) Copyright 2003-2009, Hewlett-Packard Development Company, LP See the file named COPYING for license details */ /** @file byte field class */ #ifndef DATASERIES_BYTEFIELD_HPP #define DATASERIES_BYTEFIELD_HPP /** \brief Accessor for byte fields */ class ByteField : public dataseries::detail::SimpleFixedField<uint8_t> { public: ByteField(ExtentSeries &dataseries, const std::string &field, int flags = 0, byte default_value = 0, bool auto_add = true) : dataseries::detail::SimpleFixedField<uint8_t>(dataseries, field, flags, default_value) { if (auto_add) { dataseries.addField(*this); } } friend class GF_Byte; }; #endif
22.8125
100
0.658904
sbu-fsl
a050b35eeea30520be28878ed3a557363b030e82
502
cpp
C++
src/PeerNotificationOfMintService.cpp
izzy-developer/core
32b83537a255aeef50a64252ea001c99c7e69a01
[ "MIT" ]
null
null
null
src/PeerNotificationOfMintService.cpp
izzy-developer/core
32b83537a255aeef50a64252ea001c99c7e69a01
[ "MIT" ]
null
null
null
src/PeerNotificationOfMintService.cpp
izzy-developer/core
32b83537a255aeef50a64252ea001c99c7e69a01
[ "MIT" ]
1
2022-03-15T23:32:26.000Z
2022-03-15T23:32:26.000Z
#include <PeerNotificationOfMintService.h> #include <uint256.h> #include <net.h> #include <protocol.h> PeerNotificationOfMintService::PeerNotificationOfMintService( std::vector<CNode*>& peers ): peers_(peers) { } bool PeerNotificationOfMintService::havePeersToNotify() const { return !peers_.empty(); } void PeerNotificationOfMintService::notifyPeers(const uint256& blockHash) const { for (CNode* peer : peers_) { peer->PushInventory(CInv(MSG_BLOCK, blockHash)); } }
21.826087
79
0.729084
izzy-developer
a057288f6491ef93600ed75057f53cbabdb3215c
2,356
hpp
C++
source/xyo/xyo-networking-socket.hpp
g-stefan/xyo
e203cb699d6bba46eae6c8157f27ea29ab7506f1
[ "MIT", "Unlicense" ]
null
null
null
source/xyo/xyo-networking-socket.hpp
g-stefan/xyo
e203cb699d6bba46eae6c8157f27ea29ab7506f1
[ "MIT", "Unlicense" ]
null
null
null
source/xyo/xyo-networking-socket.hpp
g-stefan/xyo
e203cb699d6bba46eae6c8157f27ea29ab7506f1
[ "MIT", "Unlicense" ]
null
null
null
// // XYO // // Copyright (c) 2020-2021 Grigore Stefan <[email protected]> // Created by Grigore Stefan <[email protected]> // // MIT License (MIT) <http://opensource.org/licenses/MIT> // #ifndef XYO_NETWORKING_SOCKET_HPP #define XYO_NETWORKING_SOCKET_HPP #ifndef XYO_NETWORKING_NETWORK_HPP #include "xyo-networking-network.hpp" #endif #ifndef XYO_STREAM_IREAD_HPP #include "xyo-stream-iread.hpp" #endif #ifndef XYO_STREAM_IWRITE_HPP #include "xyo-stream-iwrite.hpp" #endif #ifndef XYO_NETWORKING_IPADRESS4_HPP #include "xyo-networking-ipaddress4.hpp" #endif #ifndef XYO_NETWORKING_IPADRESS6_HPP #include "xyo-networking-ipaddress6.hpp" #endif #ifndef XYO_ENCODING_STRING_HPP #include "xyo-encoding-string.hpp" #endif namespace XYO { namespace Networking { using namespace XYO::DataStructures; using namespace XYO::Stream; using namespace XYO::Encoding; class IPAddress_; class Socket_; class Socket: public virtual IRead, public virtual IWrite { XYO_DISALLOW_COPY_ASSIGN_MOVE(Socket); protected: Socket_ *this_; Socket *linkOwner_; IPAddress_ *ipAddress; bool ipAddressIs6; public: XYO_EXPORT Socket(); XYO_EXPORT ~Socket(); XYO_EXPORT operator bool() const; XYO_EXPORT bool openClient(IPAddress4 &adr_); XYO_EXPORT bool openServer(IPAddress4 &adr_); XYO_EXPORT bool openClient(IPAddress6 &adr_); XYO_EXPORT bool openServer(IPAddress6 &adr_); XYO_EXPORT bool listen(uint16_t queue_); XYO_EXPORT bool accept(Socket &socket_); XYO_EXPORT void close(); XYO_EXPORT size_t read(void *output, size_t ln); XYO_EXPORT size_t write(const void *input, size_t ln); XYO_EXPORT int waitToWrite(uint32_t microSeconds); XYO_EXPORT int waitToRead(uint32_t microSeconds); XYO_EXPORT bool openClientX(const String &adr_); XYO_EXPORT bool openServerX(const String &adr_); XYO_EXPORT bool isIPAddress4(); XYO_EXPORT bool isIPAddress6(); XYO_EXPORT bool getIPAddress4(IPAddress4 &); XYO_EXPORT bool getIPAddress6(IPAddress6 &); XYO_EXPORT void becomeOwner(Socket &socket_); XYO_EXPORT void linkOwner(Socket &socket_); XYO_EXPORT void unLinkOwner(); XYO_EXPORT void transferOwner(Socket &socket_); }; }; }; #endif
24.541667
63
0.716469
g-stefan
a05a50765d3b069636de3e0c7a272c57d16bf3b4
7,247
hpp
C++
test/functional/forall/reduce-multiple-segment/tests/test-forall-segment-multiple-ReduceSum.hpp
ggeorgakoudis/RAJA
05f4a5e473a4160ddfdb5e829b4fdc9e0384ae26
[ "BSD-3-Clause" ]
1
2020-11-19T04:55:20.000Z
2020-11-19T04:55:20.000Z
test/functional/forall/reduce-multiple-segment/tests/test-forall-segment-multiple-ReduceSum.hpp
ggeorgakoudis/RAJA
05f4a5e473a4160ddfdb5e829b4fdc9e0384ae26
[ "BSD-3-Clause" ]
null
null
null
test/functional/forall/reduce-multiple-segment/tests/test-forall-segment-multiple-ReduceSum.hpp
ggeorgakoudis/RAJA
05f4a5e473a4160ddfdb5e829b4fdc9e0384ae26
[ "BSD-3-Clause" ]
null
null
null
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// // Copyright (c) 2016-20, Lawrence Livermore National Security, LLC // and RAJA project contributors. See the RAJA/COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// #ifndef __TEST_FORALL_MULTIPLE_REDUCESUM_HPP__ #define __TEST_FORALL_MULTIPLE_REDUCESUM_HPP__ #include <cstdlib> #include <numeric> template <typename IDX_TYPE, typename DATA_TYPE, typename WORKING_RES, typename EXEC_POLICY, typename REDUCE_POLICY> void ForallReduceSumMultipleStaggeredTestImpl(IDX_TYPE first, IDX_TYPE last) { RAJA::TypedRangeSegment<IDX_TYPE> r1(first, last); camp::resources::Resource working_res{WORKING_RES::get_default()}; DATA_TYPE* working_array; DATA_TYPE* check_array; DATA_TYPE* test_array; allocateForallTestData<DATA_TYPE>(last, working_res, &working_array, &check_array, &test_array); const DATA_TYPE initval = 2; for (IDX_TYPE i = 0; i < last; ++i) { test_array[i] = initval; } working_res.memcpy(working_array, test_array, sizeof(DATA_TYPE) * last); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum0(0); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum1(initval * 1); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum2(0); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum3(initval * 3); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum4(0); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum5(initval * 5); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum6(0); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum7(initval * 7); const DATA_TYPE index_len = static_cast<DATA_TYPE>(last - first); const int nloops = 2; for (int j = 0; j < nloops; ++j) { RAJA::forall<EXEC_POLICY>(r1, [=] RAJA_HOST_DEVICE(IDX_TYPE idx) { sum0 += working_array[idx]; sum1 += working_array[idx] * 2; sum2 += working_array[idx] * 3; sum3 += working_array[idx] * 4; sum4 += working_array[idx] * 5; sum5 += working_array[idx] * 6; sum6 += working_array[idx] * 7; sum7 += working_array[idx] * 8; }); DATA_TYPE check_val = initval * index_len * (j + 1); ASSERT_EQ(1 * check_val, static_cast<DATA_TYPE>(sum0.get())); ASSERT_EQ(2 * check_val + (initval*1), static_cast<DATA_TYPE>(sum1.get())); ASSERT_EQ(3 * check_val, static_cast<DATA_TYPE>(sum2.get())); ASSERT_EQ(4 * check_val + (initval*3), static_cast<DATA_TYPE>(sum3.get())); ASSERT_EQ(5 * check_val, static_cast<DATA_TYPE>(sum4.get())); ASSERT_EQ(6 * check_val + (initval*5), static_cast<DATA_TYPE>(sum5.get())); ASSERT_EQ(7 * check_val, static_cast<DATA_TYPE>(sum6.get())); ASSERT_EQ(8 * check_val + (initval*7), static_cast<DATA_TYPE>(sum7.get())); } deallocateForallTestData<DATA_TYPE>(working_res, working_array, check_array, test_array); } template <typename IDX_TYPE, typename DATA_TYPE, typename WORKING_RES, typename EXEC_POLICY, typename REDUCE_POLICY> void ForallReduceSumMultipleStaggered2TestImpl(IDX_TYPE first, IDX_TYPE last) { RAJA::TypedRangeSegment<IDX_TYPE> r1(first, last); camp::resources::Resource working_res{WORKING_RES::get_default()}; DATA_TYPE* working_array; DATA_TYPE* check_array; DATA_TYPE* test_array; allocateForallTestData<DATA_TYPE>(last, working_res, &working_array, &check_array, &test_array); const DATA_TYPE initval = 2; for (IDX_TYPE i = 0; i < last; ++i) { test_array[i] = initval; } working_res.memcpy(working_array, test_array, sizeof(DATA_TYPE) * last); const DATA_TYPE index_len = static_cast<DATA_TYPE>(last - first); // Workaround for broken omp-target reduction interface. // This should be `sumX;` not `sumX(0);` RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum0(initval); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum1(0); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum2(initval); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum3(0); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum4(initval); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum5(0); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum6(initval); RAJA::ReduceSum<REDUCE_POLICY, DATA_TYPE> sum7(0); sum0.reset(0); sum1.reset(initval * 1); sum2.reset(0); sum3.reset(initval * 3); sum4.reset(0.0); sum5.reset(initval * 5); sum6.reset(0.0); sum7.reset(initval * 7); const int nloops = 3; for (int j = 0; j < nloops; ++j) { RAJA::forall<EXEC_POLICY>(r1, [=] RAJA_HOST_DEVICE(IDX_TYPE idx) { sum0 += working_array[idx]; sum1 += working_array[idx] * 2; sum2 += working_array[idx] * 3; sum3 += working_array[idx] * 4; sum4 += working_array[idx] * 5; sum5 += working_array[idx] * 6; sum6 += working_array[idx] * 7; sum7 += working_array[idx] * 8; }); DATA_TYPE check_val = initval * index_len * (j + 1); ASSERT_EQ(1 * check_val, static_cast<DATA_TYPE>(sum0.get())); ASSERT_EQ(2 * check_val + (initval*1), static_cast<DATA_TYPE>(sum1.get())); ASSERT_EQ(3 * check_val, static_cast<DATA_TYPE>(sum2.get())); ASSERT_EQ(4 * check_val + (initval*3), static_cast<DATA_TYPE>(sum3.get())); ASSERT_EQ(5 * check_val, static_cast<DATA_TYPE>(sum4.get())); ASSERT_EQ(6 * check_val + (initval*5), static_cast<DATA_TYPE>(sum5.get())); ASSERT_EQ(7 * check_val, static_cast<DATA_TYPE>(sum6.get())); ASSERT_EQ(8 * check_val + (initval*7), static_cast<DATA_TYPE>(sum7.get())); } deallocateForallTestData<DATA_TYPE>(working_res, working_array, check_array, test_array); } TYPED_TEST_SUITE_P(ForallReduceSumMultipleTest); template <typename T> class ForallReduceSumMultipleTest : public ::testing::Test { }; TYPED_TEST_P(ForallReduceSumMultipleTest, ReduceSumMultipleForall) { using IDX_TYPE = typename camp::at<TypeParam, camp::num<0>>::type; using DATA_TYPE = typename camp::at<TypeParam, camp::num<1>>::type; using WORKING_RES = typename camp::at<TypeParam, camp::num<2>>::type; using EXEC_POLICY = typename camp::at<TypeParam, camp::num<3>>::type; using REDUCE_POLICY = typename camp::at<TypeParam, camp::num<4>>::type; ForallReduceSumMultipleStaggeredTestImpl<IDX_TYPE, DATA_TYPE, WORKING_RES, EXEC_POLICY, REDUCE_POLICY>(0, 2115); ForallReduceSumMultipleStaggered2TestImpl<IDX_TYPE, DATA_TYPE, WORKING_RES, EXEC_POLICY, REDUCE_POLICY>(0, 2115); } REGISTER_TYPED_TEST_SUITE_P(ForallReduceSumMultipleTest, ReduceSumMultipleForall); #endif // __TEST_FORALL_MULTIPLE_REDUCESUM_HPP__
37.35567
81
0.62688
ggeorgakoudis
a05b14db1fcc5898b89124aebc5ac61e1f8f80a1
4,520
cpp
C++
include/hydro/engine/core.cpp
hydraate/hydro
42037a8278dcfdca68fb5cceaf6988da861f0eff
[ "Apache-2.0" ]
null
null
null
include/hydro/engine/core.cpp
hydraate/hydro
42037a8278dcfdca68fb5cceaf6988da861f0eff
[ "Apache-2.0" ]
null
null
null
include/hydro/engine/core.cpp
hydraate/hydro
42037a8278dcfdca68fb5cceaf6988da861f0eff
[ "Apache-2.0" ]
null
null
null
// // __ __ __ // / / / /__ __ ____/ /_____ ____ // / /_/ // / / // __ // ___// __ \ // / __ // /_/ // /_/ // / / /_/ / // /_/ /_/ \__, / \__,_//_/ \____/ // /____/ // // The Hydro Programming Language // #include "core.hpp" namespace hydro::engine { /** * */ Boolean::Boolean() { mValue = false; } /** * */ Boolean::Boolean(bool value) { mValue = value; } /** * */ Boolean::Boolean(const Boolean &_bool) { mValue = _bool.mValue; } /** * */ Boolean::Boolean(Boolean &&_bool) { mValue = _bool.mValue; } /** * */ Boolean::~Boolean() { } /** * */ Boolean & Boolean::operator=(const Boolean &rhs) { mValue = rhs.mValue; return (*this); } /** * */ Boolean & Boolean::operator=(Boolean &&rhs) { mValue = rhs.mValue; return (*this); } /** * */ Number::Number() { mValue = 0.0; } Number::Number(double value) { mValue = value; } Number::Number(const Number &number) { mValue = number.mValue; } Number::Number(Number &&number) { mValue = number.mValue; } Number::~Number() { } Number & Number::operator=(const Number &rhs) { mValue = rhs.mValue; return (*this); } Number & Number::operator=(Number &&rhs) { mValue = rhs.mValue; return (*this); } /** * */ Color::Color() { mValue = 0; } /** * */ Color::Color(Number value) { mValue = value; } /** * */ Color::Color(Number r, Number g, Number b, Number a) { uint8_t red = r; uint8_t green = g; uint8_t blue = b; uint8_t alpha = a; mValue = (double)((red << 24) + (green << 16) + (blue << 8) + (alpha)); } /** * */ Color::Color(const Color &color) { mValue = color.mValue; } /** * */ Color::Color(Color &&color) { mValue = color.mValue; } /** * */ Color::~Color() { } Number Color::getRed() const { uint64_t value = (uint64_t)mValue.valueOf() >> 24 & 0xFF; return (double)value; } Number Color::getGreen() const { uint64_t value = (uint64_t)mValue.valueOf() >> 16 & 0xFF; return (double)value; } Number Color::getBlue() const { uint64_t value = (uint64_t)mValue.valueOf() >> 8 & 0xFF; return (double)value; } Number Color::getAlpha() const { uint64_t value = (uint64_t)mValue.valueOf() & 0xFF; return (double)value; } Number Color::valueOf() const { return mValue; } Color & Color::operator=(const Color &color) { mValue = color.mValue; return (*this); } Color & Color::operator=(Color &&color) { mValue = color.mValue; return (*this); } /** * */ String::String() { } /** * */ String::String(const char *) { } /** * */ String::String(const String &string) { } /** * */ String::String(String &&string) { } /** * */ String::~String() { } /** * */ Any::Any() //: mContent{ new holder<undefined_t>{ undefined } } { } /** * */ Any::Any(undefined_t) { } /** * */ Any::Any(std::nullptr_t) { } /** * */ Any::Any(Boolean _bool) { } /** * */ Any::Any(Color color) { } /** * */ Any::Any(String string) { } /** * */ Any::Any(Number number) { } /** * */ Any::Any(object_ptr<HElement> object) { } /** * */ Any::Any(const Any &any) : mContent{any.mContent->clone()} { } /** * */ Any::Any(Any &&any) { } /** * */ Any::~Any() { } /** * */ bool Any::isNull() const { return type() == typeid(std::nullptr_t); } /** * */ bool Any::isUndefined() const { return type() == typeid(undefined_t); } /** * */ bool Any::isBoolean() const { return type() == typeid(Boolean); } /** * */ bool Any::isColor() const { return type() == typeid(Color); } /** * */ bool Any::isNumber() const { return type() == typeid(Number); } /** * */ bool Any::isString() const { return type() == typeid(Number); } /** * */ Any::operator bool() const { if (isBoolean()) return (Boolean)(*this); else if (isString()) return (String)(*this); else if (isNumber()) return (double)(Number)(*this) != 0; else if (isNull() || isUndefined()) return false; else if (isColor()) return true; return false; } /** * */ Any &Any::operator=(const Any &rhs) { mContent = std::unique_ptr<placeholder>{rhs.mContent->clone()}; return (*this); } /** * */ Any &Any::operator=(Any &&rhs) { mContent = std::unique_ptr<placeholder>{rhs.mContent->clone()}; return (*this); } } // namespace hydro::engine
10.917874
75
0.520796
hydraate
a05c4dbe94e5b34750c26ec518ccecec4a60bd21
3,977
cpp
C++
raspberry/particle_slam.cpp
stheophil/MappingRover2
25d968a4f27016a3eb61b70e48d3f137887d440c
[ "MIT" ]
11
2015-11-12T11:12:50.000Z
2021-07-27T02:15:23.000Z
raspberry/particle_slam.cpp
stheophil/MappingRover2
25d968a4f27016a3eb61b70e48d3f137887d440c
[ "MIT" ]
null
null
null
raspberry/particle_slam.cpp
stheophil/MappingRover2
25d968a4f27016a3eb61b70e48d3f137887d440c
[ "MIT" ]
5
2015-11-12T03:10:28.000Z
2018-12-02T21:38:21.000Z
#include "particle_slam.h" #include "robot_configuration.h" #include "error_handling.h" #include "occupancy_grid.inl" #include <boost/range/algorithm/max_element.hpp> #include <boost/range/adaptor/transformed.hpp> #include <opencv2/imgproc.hpp> #include <iostream> #include <random> #include <future> ///////////////////// // SParticle SParticle::SParticle() : m_pose(rbt::pose<double>::zero()), m_matLikelihood(c_nMapExtent, c_nMapExtent, CV_32FC1, cv::Scalar(0)) {} SParticle::SParticle(SParticle const& p) : m_pose(p.m_pose), m_matLikelihood(p.m_matLikelihood.clone()), m_occgrid(p.m_occgrid) {} SParticle& SParticle::operator=(SParticle const& p) { m_pose = p.m_pose; m_matLikelihood = p.m_matLikelihood.clone(); m_occgrid = p.m_occgrid; return *this; } void SParticle::update(SScanLine const& scanline) { m_pose = sample_motion_model(m_pose, scanline.translation(), scanline.rotation()); // OPTIMIZE: Match fewer points m_fWeight = measurement_model_map(m_pose, scanline, [this](rbt::point<double> const& pt) { auto const ptn = ToGridCoordinate(pt); return static_cast<double>(m_matLikelihood.at<float>(ptn.y, ptn.x)); }); // OPTIMIZE: Recalculate occupancy grid after resampling? // OPTIMIZE: m_occgrid.update also sets occupancy of robot itself each time boost::for_each(scanline.m_vecscan, [&](auto const& scan) { m_occgrid.update(m_pose, scan.m_fRadAngle, scan.m_nDistance); }); cv::distanceTransform(m_occgrid.ObstacleMap(), m_matLikelihood, CV_DIST_L2, 3); } /////////////////////// // SParticleSLAM CParticleSlamBase::CParticleSlamBase(int cParticles) : m_vecparticle(cParticles), m_itparticleBest(m_vecparticle.end()), m_vecparticleTemp(cParticles) {} static std::random_device s_rd; void CParticleSlamBase::receivedSensorData(SScanLine const& scanline) { // TODO: Ignore data when robot is not moving for a long time // if scanline full, update all particles, LOG("Update particles"); LOG("t = (" << scanline.translation().x << ";" << scanline.translation().y << ") " "r = " << scanline.rotation()); std::vector<std::future<double>> vecfuture; boost::for_each(m_vecparticle, [&](SParticle& p) { vecfuture.emplace_back( std::async(std::launch::async | std::launch::deferred, [&] { p.update(scanline); return p.m_fWeight; } )); }); double fWeightTotal = 0.0; for(int i=0; i<vecfuture.size(); ++i) { fWeightTotal += vecfuture[i].get(); #ifdef ENABLE_LOG auto const& p = m_vecparticle[i]; LOG("Particle " << i << " -> " << " pt = (" << p.m_pose.m_pt.x << "; " << p.m_pose.m_pt.y << ") " << " yaw = " << p.m_pose.m_fYaw << " w = " << p.m_fWeight); #endif } // Resampling // Thrun, Probabilistic robotics, p. 110 auto const fStepSize = fWeightTotal/m_vecparticle.size(); auto const r = std::uniform_real_distribution<double>(0.0, fStepSize)(s_rd); auto c = m_vecparticle.front().m_fWeight; auto itparticleOut = m_vecparticleTemp.begin(); for(int i = 0, m = 0; m<m_vecparticle.size(); ++m) { auto const u = r + m * fStepSize; while(c<u) { ++i; c += m_vecparticle[i].m_fWeight; } LOG("Sample particle " << i); *itparticleOut = m_vecparticle[i]; ++itparticleOut; } std::swap(m_vecparticle, m_vecparticleTemp); m_itparticleBest = boost::max_element( boost::adaptors::transform(m_vecparticle, std::mem_fn(&SParticle::m_fWeight)) ).base(); m_vecpose.emplace_back(m_itparticleBest->m_pose); } cv::Mat CParticleSlamBase::getMap() const { ASSERT(m_itparticleBest!=m_vecparticle.end()); return m_itparticleBest->m_occgrid.ObstacleMapWithPoses(m_vecpose); }
33.141667
102
0.629117
stheophil
a05daf912350cae6cd5ca8e8354d387667c75fe6
678
cpp
C++
src/cpp_language_linkage.cpp
Silveryard/cppast
6bb3f330cb0aec63e5631e175c24428581a34b0b
[ "MIT" ]
null
null
null
src/cpp_language_linkage.cpp
Silveryard/cppast
6bb3f330cb0aec63e5631e175c24428581a34b0b
[ "MIT" ]
null
null
null
src/cpp_language_linkage.cpp
Silveryard/cppast
6bb3f330cb0aec63e5631e175c24428581a34b0b
[ "MIT" ]
null
null
null
// Copyright (C) 2017-2022 Jonathan Müller and cppast contributors // SPDX-License-Identifier: MIT #include <cppast/cpp_language_linkage.hpp> #include <cppast/cpp_entity_kind.hpp> using namespace cppast; cpp_entity_kind cpp_language_linkage::kind() noexcept { return cpp_entity_kind::language_linkage_t; } bool cpp_language_linkage::is_block() const noexcept { if (begin() == end()) { // An empty container must be a "block" of the form: extern "C" {} return true; } return std::next(begin()) != end(); // more than one entity, so block } cpp_entity_kind cpp_language_linkage::do_get_entity_kind() const noexcept { return kind(); }
23.37931
74
0.707965
Silveryard
a05ec922b76dbf54bfacf45ade3eabbe8eb470d5
8,304
cpp
C++
src/main.cpp
Sensenzhl/RCNN-NVDLA
e6b8a7ef2af061676d406d2f51dcd1ab809b5a1d
[ "Vim" ]
5
2019-06-26T07:50:43.000Z
2021-12-17T08:52:39.000Z
src/main.cpp
Sensenzhl/RCNN-NVDLA
e6b8a7ef2af061676d406d2f51dcd1ab809b5a1d
[ "Vim" ]
1
2019-11-28T06:57:49.000Z
2019-11-28T06:57:49.000Z
src/main.cpp
Sensenzhl/RCNN-NVDLA
e6b8a7ef2af061676d406d2f51dcd1ab809b5a1d
[ "Vim" ]
1
2020-05-27T06:11:17.000Z
2020-05-27T06:11:17.000Z
#include "defines.hpp" #include "main.hpp" int main(int argc, char *argv[]) { double score; IplImage *img; CvMat temp; Mat image_draw; Mat image_temp; float *ptr; float *ptr_temp; float *ptr_thresholded; float *ptr_scored; float *ptr_removed_duplicate; int flag_box_exist=0; //getFiles("./test_image/",files); //char str[30]; //int size = files.size(); //for (int i = 0; i < size; i++) //{ // cout << "file size: "<< size <<files[i]<< endl; //} std::cout << "OpenCV Version: " << CV_VERSION << endl; img = cvLoadImage("./test_image/person-bike.jpg"); CvMat *mat = cvGetMat(img, &temp); cvNamedWindow("Input_Image", CV_WINDOW_AUTOSIZE); cvShowImage("Input_Image", img); cvWaitKey(0); double overlap = NMS_OVERLAP; //********************************************* Selective Search Boxes ********************************** bool fast_mode = FAST_MODE; double im_width = IM_WIDTH; CvMat *crop_boxes = selective_search_boxes(img, fast_mode, im_width); CvMat *boxes = cvCloneMat(crop_boxes); double minBoxSize = MIN_BOX_SIZE; printf("boxes number: %d \n", boxes->rows); CvMat *boxes_filtered = FilterBoxesWidth(boxes, minBoxSize); printf("remained boxes number after filtered: %d \n", boxes_filtered->rows); CvMat *boxes_remove_duplicates = BoxRemoveDuplicates(boxes_filtered); printf("remained boxes number removed duplicates: %d \n", boxes_remove_duplicates->rows); float *ptr_tmp; int Box_num = boxes_remove_duplicates->rows; double scale = img->width / im_width; //scale all boxes for (int i = 0; i < boxes_remove_duplicates->rows; i++) { ptr_tmp = (float*)(boxes_remove_duplicates->data.ptr + i * boxes_remove_duplicates->step); for (int j = 0; j < boxes_remove_duplicates->cols; j++) { *(ptr_tmp + j) = (*(ptr_tmp + j) - 1) * scale + 1; } } //********************************************** RCNN Extract Regions ********************************** //Image Crop Initialization int batch_size = 256; int result; Crop crop_param((char *)"warp", 227, 16); char cmdbuf0[80]; char cmdbuf1[80]; char cmdbuf2[80]; char cmdbuf3[80]; char crop_image_dir[80]; printf("Box_num = %d\n", Box_num); //convert cropped mat from RGB to BGR Mat mat_bgr; Mat mat_rgb = iplImageToMat(img, true); cvtColor(mat_rgb,mat_bgr,CV_RGB2BGR); IplImage img_bgr(mat_bgr); //cvNamedWindow("BGR-IPL", CV_WINDOW_AUTOSIZE); //cvShowImage("BGR-IPL", &img_bgr); //cvWaitKey(0); for (int j = 0; j < Box_num; j++) //for (int j = 0; j < 1000; j++) { CvMat *input_box = cvCreateMat(1, 4, CV_32FC1); ptr = (float*)(input_box->data.ptr + 0 * input_box->step); ptr_temp = (float*)(boxes_remove_duplicates->data.ptr + j * boxes_remove_duplicates->step); for (int k = 0; k < boxes_remove_duplicates->cols; k++) { *(ptr + k) = *(ptr_temp + k); } CvMat image_batches = Rcnn_extract_regions(&img_bgr, input_box, batch_size, crop_param); Mat cropped_Mat = cvMatToMat(&image_batches, true); sprintf(crop_image_dir, "./images/cropped_image_%03d.jpg",j); //printf("%s \n", crop_image_dir); imwrite(crop_image_dir, cropped_Mat); } //************************************************ DLA Processing *********************************************** sprintf(cmdbuf0, "rm ./*.dat"); printf("%s \n", cmdbuf0); system(cmdbuf0); //********************************************** Put Input into DLA ********************************************* sprintf(cmdbuf1, "./run.py --image_dir ./images --dst_dir ./output --mean_file ./mean/image_mean.mat"); printf("%s \n", cmdbuf1); system(cmdbuf1); //***************************************** Converting .dat into .txt ************************************************* sprintf(cmdbuf2, "./convert_dat_into_txt.py"); printf("%s \n", cmdbuf2); system(cmdbuf2); //****************************************** Get output data from .txt ************************************************* int box_col_num = TOTAL_CLASS + 4; CvMat *boxes_scored = cvCreateMat(boxes_remove_duplicates->rows,box_col_num,CV_32FC1); printf("get txt data \n"); char buf[2000]; char spliter[] = " ,!"; char *pch; int j; float f_num = 0; #ifdef TEST_WITH_TXT for (int ind = 0 ; ind < 1500; ind ++) #else for (int ind = 0 ; ind < Box_num; ind ++) #endif { string message; ifstream infile; if(ind < 100) sprintf(cmdbuf3, "./txt/data%03d.txt",ind); else sprintf(cmdbuf3, "./txt/data%d.txt",ind); infile.open(cmdbuf3); ptr = (float*)(boxes_scored->data.ptr + ind * boxes_scored->step); ptr_removed_duplicate = (float*)(boxes_remove_duplicates->data.ptr + ind * boxes_remove_duplicates->step); *(ptr) = *(ptr_removed_duplicate); *(ptr + 1) = *(ptr_removed_duplicate + 1); *(ptr + 2) = *(ptr_removed_duplicate + 2); *(ptr + 3) = *(ptr_removed_duplicate + 3); if(infile.is_open()) { while(infile.good() && !infile.eof()) { memset(buf,0,2000); infile.getline(buf,2000); } pch = strtok(buf,spliter); j = 4; while(pch != NULL) { f_num=atof(pch); *(ptr + j) = f_num; pch = strtok(NULL,spliter); j++; } infile.close(); } else { for(int cnt = 4; cnt < (TOTAL_CLASS + 4); cnt ++) { *(ptr + cnt) = 0; } } } //************************************************ Post Processing ********************************** //***************************************** NMS & DRAW Boxes Processing ********************************** printf("Final Stage \n"); double threshold = THRESHOLD; int length_index_reserved = 0; int *index_reserved = new int[boxes_scored->rows]; printf("boxes_scored size is [%d %d] \n",boxes_scored->rows,boxes_scored->cols); for (int num_class = 0; num_class < TOTAL_CLASS; num_class++) { length_index_reserved = 0; for (int i = 0; i < boxes_scored->rows; i++) { ptr = (float*)(boxes_scored->data.ptr + i * boxes_scored->step); if ((*(ptr + 4 + num_class)) > THRESHOLD) { index_reserved[length_index_reserved] = i; length_index_reserved = length_index_reserved + 1; } } //printf("index_reserved done \n"); if(length_index_reserved > 0) { CvMat * boxes_thresholded = cvCreateMat(length_index_reserved, 5, CV_32FC1); for (int i = 0; i < length_index_reserved; i++) { ptr = (float*)(boxes_scored->data.ptr + (index_reserved[i]) * boxes_scored->step); ptr_thresholded = (float*)(boxes_thresholded->data.ptr + i * boxes_thresholded->step); for (int j = 0; j < (boxes_thresholded->cols - 1); j++) { *(ptr_thresholded + j) = *(ptr + j); } *(ptr_thresholded + 4) = *(ptr + 4 + num_class); } //printf("Class %d boxes_scored after thresholded is %d \n",num_class,length_index_reserved); const char* class_type_c2 = classification[num_class].c_str(); printf("Class %s boxes_scored after thresholded is %d \n",class_type_c2,length_index_reserved); CvMat * print_box = cvCreateMat(boxes_thresholded->rows, 5, CV_32FC1); printf("Thresholded boxes: \n"); PrintCvMatValue(boxes_thresholded); print_box = nms(boxes_thresholded, overlap); printf("Print boxes after nms: \n"); PrintCvMatValue(print_box); image_draw = drawboxes(mat, print_box, num_class); CvMat temp2 = image_draw; cvCopy(&temp2, mat); flag_box_exist = 1; } else { string class_type = classification[num_class]; const char* class_type_c = class_type.c_str(); printf("Class %s number is 0 \n",class_type_c); } } Mat image_origin = cvMatToMat(mat, true); if(flag_box_exist) { imwrite("./output/output_image.jpg",image_draw); cvNamedWindow("Output Image", CV_WINDOW_AUTOSIZE); imshow("Output Image", image_draw); cvWaitKey(); } else { imwrite("./output/output_image.jpg",image_origin); cvNamedWindow("Output Image", CV_WINDOW_AUTOSIZE); imshow("Output Image", image_origin); cvWaitKey(); } return 0; }
29.136842
130
0.572977
Sensenzhl
a06647cc4ed4e5721156752b70feed5e2e399295
565
cpp
C++
LeetCode/Problems/Algorithms/#645_SetMismatch_sol4_visited_vector_O(N)_time_O(N)_extra_space_24ms_21.4MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#645_SetMismatch_sol4_visited_vector_O(N)_time_O(N)_extra_space_24ms_21.4MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#645_SetMismatch_sol4_visited_vector_O(N)_time_O(N)_extra_space_24ms_21.4MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: vector<int> findErrorNums(vector<int>& nums) { const int N = nums.size(); int duplicate = -1; int missing = -1; vector<bool> vis(N + 1, false); for(int num: nums){ if(vis[num]){ duplicate = num; } vis[num] = true; } for(int num = 1; num <= N; ++num){ if(!vis[num]){ missing = num; } } return {duplicate, missing}; } };
23.541667
51
0.380531
Tudor67
a0681f9df9d7c68c7c3c98257c34a33e4a055fb3
569
cpp
C++
level_zero/tools/source/sysman/linux/pmt/pmt_helper.cpp
lukaszgotszaldintel/compute-runtime
9b12dc43904806db07616ffb8b1c4495aa7d610f
[ "MIT" ]
null
null
null
level_zero/tools/source/sysman/linux/pmt/pmt_helper.cpp
lukaszgotszaldintel/compute-runtime
9b12dc43904806db07616ffb8b1c4495aa7d610f
[ "MIT" ]
null
null
null
level_zero/tools/source/sysman/linux/pmt/pmt_helper.cpp
lukaszgotszaldintel/compute-runtime
9b12dc43904806db07616ffb8b1c4495aa7d610f
[ "MIT" ]
null
null
null
/* * Copyright (C) 2020-2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "level_zero/tools/source/sysman/linux/pmt/pmt.h" namespace L0 { const std::map<std::string, uint64_t> deviceKeyOffsetMap = { {"PACKAGE_ENERGY", 0x400}, {"COMPUTE_TEMPERATURES", 0x68}, {"SOC_TEMPERATURES", 0x60}, {"CORE_TEMPERATURES", 0x6c}}; ze_result_t PlatformMonitoringTech::getKeyOffsetMap(std::string guid, std::map<std::string, uint64_t> &keyOffsetMap) { keyOffsetMap = deviceKeyOffsetMap; return ZE_RESULT_SUCCESS; } } // namespace L0
24.73913
118
0.711775
lukaszgotszaldintel
a06975d84bbf1316389188c2b68832431f32791a
3,072
cc
C++
src/core/vulkan/debug_msg.cc
5aitama/Bismuth
00fbd13a08ac08b77413d4a6797b1daa84a892cf
[ "MIT" ]
null
null
null
src/core/vulkan/debug_msg.cc
5aitama/Bismuth
00fbd13a08ac08b77413d4a6797b1daa84a892cf
[ "MIT" ]
null
null
null
src/core/vulkan/debug_msg.cc
5aitama/Bismuth
00fbd13a08ac08b77413d4a6797b1daa84a892cf
[ "MIT" ]
null
null
null
#include "debug_msg.h" using namespace std; DebugMessenger::DebugMessenger( const VkInstance& instance, const VkDebugUtilsMessengerCreateInfoEXT* createInfoExt ) : instance(instance) { #ifndef NDEBUG if(CreateDebugUtilsMessengerEXT(instance, createInfoExt, nullptr, &callback) != VK_SUCCESS) throw runtime_error("Failed to create debug messenger !"); #endif } DebugMessenger::~DebugMessenger() { DestroyDebugUtilsMessengerEXT(instance, callback, nullptr); } VKAPI_ATTR VkBool32 VKAPI_CALL DebugMessenger::DebugCallback( VkDebugUtilsMessageSeverityFlagBitsEXT msgSeverity, VkDebugUtilsMessageTypeFlagsEXT msgType, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData) { std::string str; if (msgSeverity >= VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) { str.append("\033[1;31m"); } else if (msgSeverity >= VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) { str.append("\033[1;93m"); } else if (msgSeverity >= VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) { str.append("\033[1;94m"); } else { str.append("\033[3m"); } if (msgType >= VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT) { str.append("PERFORMANCE: "); } else if (msgType >= VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) { str.append("VALIDATION: "); } else { str.append("GENERAL: "); } cerr << str << pCallbackData->pMessage << "\033[0m" << endl; return VK_FALSE; } VkResult DebugMessenger::CreateDebugUtilsMessengerEXT( const VkInstance& instance, const VkDebugUtilsMessengerCreateInfoEXT* createInfoExt, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT*pCallback ) { auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT"); if(func != nullptr) { return func(instance, createInfoExt, pAllocator, pCallback); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } void DebugMessenger::DestroyDebugUtilsMessengerEXT(const VkInstance& instance, VkDebugUtilsMessengerEXT callback, const VkAllocationCallbacks* pAllocator) { auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT"); if(func != nullptr) { func(instance, callback, pAllocator); } } void DebugMessenger::PopulateDebugUtilsMessengerCreateInfoEXT(VkDebugUtilsMessengerCreateInfoEXT* createInfo) { *createInfo = { .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT, .messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT , .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT , .pfnUserCallback = DebugCallback, .pUserData = nullptr, }; }
33.758242
156
0.73763
5aitama
a06e3d6cf6537e682482b2355ea46c0e81da58a1
5,411
cpp
C++
snippets/cpp/VS_Snippets_Winforms/Windows.Forms.Control Properties/CPP/controlproperties.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
834
2017-06-24T10:40:36.000Z
2022-03-31T19:48:51.000Z
snippets/cpp/VS_Snippets_Winforms/Windows.Forms.Control Properties/CPP/controlproperties.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
7,042
2017-06-23T22:34:47.000Z
2022-03-31T23:05:23.000Z
snippets/cpp/VS_Snippets_Winforms/Windows.Forms.Control Properties/CPP/controlproperties.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
1,640
2017-06-23T22:31:39.000Z
2022-03-31T02:45:37.000Z
#using <System.Data.dll> #using <System.Windows.Forms.dll> #using <System.dll> #using <System.Drawing.dll> using namespace System; using namespace System::Drawing; using namespace System::Collections; using namespace System::ComponentModel; using namespace System::Windows::Forms; using namespace System::Data; namespace ControlProperties { public ref class Form1: public System::Windows::Forms::Form { private: System::Windows::Forms::ImageList^ imageList1; System::Windows::Forms::Button^ button2; System::ComponentModel::IContainer^ components; public: Form1() { InitializeComponent(); //this->AddMyGroupBox(); } protected: ~Form1() { if ( components != nullptr ) { delete components; } } private: void InitializeComponent() { this->components = gcnew System::ComponentModel::Container; System::Resources::ResourceManager^ resources = gcnew System::Resources::ResourceManager( Form1::typeid ); this->imageList1 = gcnew System::Windows::Forms::ImageList( this->components ); this->button2 = gcnew System::Windows::Forms::Button; this->SuspendLayout(); // // imageList1 // this->imageList1->ColorDepth = System::Windows::Forms::ColorDepth::Depth8Bit; this->imageList1->ImageSize = System::Drawing::Size( 16, 16 ); this->imageList1->ImageStream = (dynamic_cast<System::Windows::Forms::ImageListStreamer^>(resources->GetObject( "imageList1.ImageStream" ))); this->imageList1->TransparentColor = System::Drawing::Color::Transparent; // // button2 // this->button2->Location = System::Drawing::Point( 40, 232 ); this->button2->Name = "button2"; this->button2->TabIndex = 0; this->button2->Text = "button1"; this->button2->Click += gcnew System::EventHandler( this, &Form1::button2_Click ); // // Form1 // this->BackColor = System::Drawing::Color::FromArgb( ((System::Byte)(0)) ),((System::Byte)(64)),((System::Byte)(0)); this->ClientSize = System::Drawing::Size( 408, 405 ); array<System::Windows::Forms::Control^>^temp0 = {this->button2}; this->Controls->AddRange( temp0 ); this->Name = "Form1"; this->Text = "Form1"; this->ResumeLayout( false ); } //<snippet3> // Add a button to a form and set some of its common properties. private: void AddMyButton() { // Create a button and add it to the form. Button^ button1 = gcnew Button; // Anchor the button to the bottom right corner of the form button1->Anchor = static_cast<AnchorStyles>(AnchorStyles::Bottom | AnchorStyles::Right); // Assign a background image. button1->BackgroundImage = imageList1->Images[ 0 ]; // Specify the layout style of the background image. Tile is the default. button1->BackgroundImageLayout = ImageLayout::Center; // Make the button the same size as the image. button1->Size = button1->BackgroundImage->Size; // Set the button's TabIndex and TabStop properties. button1->TabIndex = 1; button1->TabStop = true; // Add a delegate to handle the Click event. button1->Click += gcnew System::EventHandler( this, &Form1::button1_Click ); // Add the button to the form. this->Controls->Add( button1 ); } // </snippet3> //<snippet2> // Add a GroupBox to a form and set some of its common properties. private: void AddMyGroupBox() { // Create a GroupBox and add a TextBox to it. GroupBox^ groupBox1 = gcnew GroupBox; TextBox^ textBox1 = gcnew TextBox; textBox1->Location = Point(15,15); groupBox1->Controls->Add( textBox1 ); // Set the Text and Dock properties of the GroupBox. groupBox1->Text = "MyGroupBox"; groupBox1->Dock = DockStyle::Top; // Disable the GroupBox (which disables all its child controls) groupBox1->Enabled = false; // Add the Groupbox to the form. this->Controls->Add( groupBox1 ); } // </snippet2> // <snippet1> // Reset all the controls to the user's default Control color. private: void ResetAllControlsBackColor( Control^ control ) { control->BackColor = SystemColors::Control; control->ForeColor = SystemColors::ControlText; if ( control->HasChildren ) { // Recursively call this method for each child control. IEnumerator^ myEnum = control->Controls->GetEnumerator(); while ( myEnum->MoveNext() ) { Control^ childControl = safe_cast<Control^>(myEnum->Current); ResetAllControlsBackColor( childControl ); } } } // </snippet1> void button1_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) { this->ResetAllControlsBackColor( this ); } void button2_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) { this->AddMyButton(); } }; } [STAThread] int main() { Application::Run( gcnew ControlProperties::Form1 ); }
31.643275
150
0.598226
BohdanMosiyuk
a06e51350b082ceec2d9139791eca4120c74d8e5
1,623
hh
C++
CommManipulatorObjects/smartsoft/src-gen/CommManipulatorObjects/CommVacuumGripperEventStateACE.hh
canonical-robots/DomainModelsRepositories
68b9286d84837e5feb7b200833b158ab9c2922a4
[ "BSD-3-Clause" ]
null
null
null
CommManipulatorObjects/smartsoft/src-gen/CommManipulatorObjects/CommVacuumGripperEventStateACE.hh
canonical-robots/DomainModelsRepositories
68b9286d84837e5feb7b200833b158ab9c2922a4
[ "BSD-3-Clause" ]
2
2020-08-20T14:49:47.000Z
2020-10-07T16:10:07.000Z
CommManipulatorObjects/smartsoft/src-gen/CommManipulatorObjects/CommVacuumGripperEventStateACE.hh
canonical-robots/DomainModelsRepositories
68b9286d84837e5feb7b200833b158ab9c2922a4
[ "BSD-3-Clause" ]
8
2018-06-25T08:41:28.000Z
2020-08-13T10:39:30.000Z
//-------------------------------------------------------------------------- // Code generated by the SmartSoft MDSD Toolchain // The SmartSoft Toolchain has been developed by: // // Service Robotics Research Center // University of Applied Sciences Ulm // Prittwitzstr. 10 // 89075 Ulm (Germany) // // Information about the SmartSoft MDSD Toolchain is available at: // www.servicerobotik-ulm.de // // Please do not modify this file. It will be re-generated // running the code generator. //-------------------------------------------------------------------------- #ifndef COMMMANIPULATOROBJECTS_COMMVACUUMGRIPPEREVENTSTATE_ACE_H_ #define COMMMANIPULATOROBJECTS_COMMVACUUMGRIPPEREVENTSTATE_ACE_H_ #include "CommManipulatorObjects/CommVacuumGripperEventState.hh" #include <ace/CDR_Stream.h> // serialization operator for DataStructure CommVacuumGripperEventState ACE_CDR::Boolean operator<<(ACE_OutputCDR &cdr, const CommManipulatorObjectsIDL::CommVacuumGripperEventState &data); // de-serialization operator for DataStructure CommVacuumGripperEventState ACE_CDR::Boolean operator>>(ACE_InputCDR &cdr, CommManipulatorObjectsIDL::CommVacuumGripperEventState &data); // serialization operator for CommunicationObject CommVacuumGripperEventState ACE_CDR::Boolean operator<<(ACE_OutputCDR &cdr, const CommManipulatorObjects::CommVacuumGripperEventState &obj); // de-serialization operator for CommunicationObject CommVacuumGripperEventState ACE_CDR::Boolean operator>>(ACE_InputCDR &cdr, CommManipulatorObjects::CommVacuumGripperEventState &obj); #endif /* COMMMANIPULATOROBJECTS_COMMVACUUMGRIPPEREVENTSTATE_ACE_H_ */
45.083333
116
0.754775
canonical-robots
a06f522b40afbef674cf7b485b0815554f5f343a
1,712
hh
C++
GeneralUtilities/inc/RSNTIO.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
9
2020-03-28T00:21:41.000Z
2021-12-09T20:53:26.000Z
GeneralUtilities/inc/RSNTIO.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
684
2019-08-28T23:37:43.000Z
2022-03-31T22:47:45.000Z
GeneralUtilities/inc/RSNTIO.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
61
2019-08-16T23:28:08.000Z
2021-12-20T08:29:48.000Z
// Data structures used to dump info and then re-sample particles from // a ROOT tree in some multi-stage job configurations. // // Andrei Gaponenko, 2015 #ifndef GeneralUtilities_inc_RSNTIO_hh #define GeneralUtilities_inc_RSNTIO_hh namespace mu2e { namespace IO { //================================================================ struct StoppedParticleF { float x; float y; float z; float t; StoppedParticleF() : x(), y(), z(), t() {} static const char *branchDescription() { return "x/F:y/F:z/F:time/F"; } static unsigned numBranchLeaves() { return 4; } }; //================================================================ struct StoppedParticleTauNormF { float x; float y; float z; float t; float tauNormalized; StoppedParticleTauNormF() : x(), y(), z(), t(), tauNormalized() {} static const char *branchDescription() { return "x/F:y/F:z/F:time/F:tauNormalized/F"; } static unsigned numBranchLeaves() { return 5; } }; //================================================================ struct InFlightParticleD { double x; double y; double z; double time; double px; double py; double pz; int pdgId; InFlightParticleD() : x(), y(), z(), time(), px(), py(), pz(), pdgId() {} static const char *branchDescription() { return "x/D:y/D:z/D:time/D:px/D:py/D:pz/D:pdgId/I"; } static unsigned numBranchLeaves() { return 8; } }; //================================================================ } // IO } // mu2e #endif/*GeneralUtilities_inc_RSNTIO_hh*/
24.112676
79
0.488318
bonventre
a0703053140cfab9dea50462c88f3a2ee5740f6e
5,497
cpp
C++
src/rivercrossing/rivercrossing.cpp
WatchJolley/rivercrossing
694c4245a8a5ae000e8d6338695a24dcedbb13a8
[ "MIT" ]
null
null
null
src/rivercrossing/rivercrossing.cpp
WatchJolley/rivercrossing
694c4245a8a5ae000e8d6338695a24dcedbb13a8
[ "MIT" ]
null
null
null
src/rivercrossing/rivercrossing.cpp
WatchJolley/rivercrossing
694c4245a8a5ae000e8d6338695a24dcedbb13a8
[ "MIT" ]
null
null
null
#include "rivercrossing/rivercrossing.h" #include "rivercrossing/movement_network.h" bool RiverCrossing::optimisationCheck(int x, int y) { double startA = SM.getActivity(x, y); double bestA = startA; int newX = x; int newY = y; for (int x2 = f(x, -2, RIVER::x); x2 <= f(x, 2, RIVER::x); x2++) { for (int y2 = f(y, -2, RIVER::y); y2 <= f(y, 2, RIVER::y); y2++) { if ( !((x2 == x) && (y2 == y)) ) { if ( SM.getActivity(x2, y2) > bestA) { bestA = SM.getActivity(x2, y2); newX = x2; newY = y2; } } } } x = newX; y = newY; // if no activity value is larger then exit if (startA == bestA) { return true; } return false; } void RiverCrossing::action(bool pickUpAction) { agent.carrying = pickUpAction; worlds.cell[ agent.x ][ agent.y ] = EMPTYCELL; updateNetworks(); } bool RiverCrossing::move() { if (USE_MOVEMENT) { vector<double> input; vector<double> outputs; int active = 0; double normActivity = SM.returnLargestActivity(); movement.loadInputs(agent.x, agent.y, SM, input, normActivity); movement.update(input); movement.getOutputs(outputs); for (int i = 0; i < 8; i++) { if ( outputs.at(active) < outputs.at(i) ) active = i; } return updatePostions( postions[active][0], postions[active][1] ); } else { int x = agent.x; int y = agent.y; int newX = x; int newY = y; double startA = SM.getActivity(x, y); double bestA = startA; for (int x2 = f(x, -1, RIVER::x); x2 <= f(x, 1, RIVER::x); x2++) { for (int y2 = f(y, -1, RIVER::y); y2 <= f(y, 1, RIVER::y); y2++) { if ( !((x2 == x) && (y2 == y)) ) { if ( SM.getActivity(x2, y2) > bestA) { bestA = SM.getActivity(x2, y2); newX = x2; newY = y2; } } } } agent.x = newX; agent.y = newY; // if no activity value is larger then exit if (startA == bestA) if(optimisationCheck(agent.x, agent.y)) return true; return false; } } int RiverCrossing::step() { bool failed = move(); worlds.updateHeatmap(agent.x,agent.y); if (failed) return TRAP; updateNetworks(true); // the action of an animat is based on the postion if (!DN_network.compare("RGB")) { vector<double> inputs; int o = worlds.getCell( agent.x, agent.y ); DN.loadInputs(worlds, inputs, o, agent.carrying); DN.update(inputs); } double pickUp = DN.getAction(); // pick up Stone if ((!agent.carrying) && ( pickUp >= 0.1f) && (worlds.cell[agent.x][agent.y] == STONE)) action(true); // put down Stone if ((agent.carrying) && ( pickUp <= -0.1f) && (worlds.cell[agent.x][agent.y] == WATER)) action(false); agent.age += 1; if (agent.debug == true) { worlds.printAnimat(agent.x, agent.y); SM.print(agent.x, agent.y); } return worlds.getCell( agent.x, agent.y ); } int RiverCrossing::run(int river, bool analyse, int seed, bool debug) { if (seed) randomise(seed); complete = false; worlds = dsWorld(river); agent = animat(getStarting()); worlds.updateHeatmap(agent.x,agent.y); if (debug) agent.debug = true; updateNetworks(); while (true) { int c = 0; c = step(); if (c == RESOURCE) { if (agent.debug == true) worlds.printHeatmap(); if (analyse) ages[river].push_back(agent.age); complete = true; return 1; } if (c == TRAP || c == WATER) { agent.death = c; if (agent.debug == true) worlds.printHeatmap(); return 0; } if (agent.age >= 200) { agent.death = AGE; if (agent.debug == true) worlds.printHeatmap(); return 0; } } } double RiverCrossing::evaluate() { int fitness = 0; for (int world = 0; world < 4; world++) { if (world != fitness ) break; fitness += run(world); } return fitness; } RiverCrossing::RiverCrossing(vector<double> genome) { // create seperate genomes for each network vector<int> genomeSplit = {config::DN_size, config::SM_size, config::MV_size}; vector<double> genomes[genomeSplit.size()]; for (int i = 0; i < genomeSplit.size(); i++) { if (genomeSplit.at(i) != 0) { auto it = std::next( genome.begin(), genomeSplit.at(i)); std::move(genome.begin(), it, std::back_inserter(genomes[i])); // ## genome.erase(genome.begin(), it); } } // configure network types this->DN_network = config::DN_network; this->SM_network = config::SM_network; DN.configureType(DN_network); SM.configureType(SM_network); // configure movement network this->USE_MOVEMENT = config::USE_MOVEMENT; // build DN if (genomes[0].size() > 0) { DN.buildNetwork(genomes[0]); } else { DN.buildNetwork(); } // build SM if (genomes[1].size() > 0) { SM.buildNetwork(genomes[1]); } else { SM.buildNetwork(); } // build Movement if (USE_MOVEMENT) movement.buildNetwork(genomes[2]); for(int i = 0; i < 5; i++) iotas.push_back( 0.0 ); needToUpdateShunting = false; complete = false; }
25.215596
91
0.538294
WatchJolley
a0704c167849356e9549e02fa6180431189c41a8
805
cpp
C++
cpp/cpp/14. Longest Common Prefix.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
3
2021-08-07T07:01:34.000Z
2021-08-07T07:03:02.000Z
cpp/cpp/14. Longest Common Prefix.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
null
null
null
cpp/cpp/14. Longest Common Prefix.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
null
null
null
// https://leetcode.com/problems/longest-common-prefix/ // Write a function to find the longest common prefix string amongst an array of // strings. // If there is no common prefix, return an empty string "". //////////////////////////////////////////////////////////////////////////////// class Solution { public: string longestCommonPrefix(vector<string>& strs) { if (strs.size() == 1) return strs[0]; string ans; for (int i = 0; i < strs[0].size(); ++i) { char ch = strs[0][i]; // compare with other strs for (int j = 1; j < strs.size(); ++j) { if (i >= strs[j].size() || ch != strs[j][i]) { return ans; } } ans += ch; } return ans; } };
28.75
80
0.445963
longwangjhu
a071db0dee153f6c9c571993f502d3c81640ccfc
7,876
cpp
C++
src/tests/add-ons/kernel/file_systems/udf/r5/UdfString.cpp
axeld/haiku
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
[ "MIT" ]
4
2017-06-17T22:03:56.000Z
2019-01-25T10:51:55.000Z
src/tests/add-ons/kernel/file_systems/udf/r5/UdfString.cpp
axeld/haiku
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
[ "MIT" ]
null
null
null
src/tests/add-ons/kernel/file_systems/udf/r5/UdfString.cpp
axeld/haiku
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
[ "MIT" ]
3
2018-12-17T13:07:38.000Z
2021-09-08T13:07:31.000Z
#include "UdfString.h" #include "ByteOrder.h" /*! \brief Converts the given unicode character to utf8. \param c The unicode character. \param out Pointer to a C-string of at least 4 characters long into which the output utf8 characters will be written. The string that is pointed to will be incremented to reflect the number of characters written, i.e. if \a out initially points to a pointer to the first character in string named \c str, and the function writes 4 characters to \c str, then upon returning, out will point to a pointer to the fifth character in \c str. */ static void unicode_to_utf8(uint32 c, char **out) { char *s = *out; if (c < 0x80) *(s++) = c; else if (c < 0x800) { *(s++) = 0xc0 | (c>>6); *(s++) = 0x80 | (c & 0x3f); } else if (c < 0x10000) { *(s++) = 0xe0 | (c>>12); *(s++) = 0x80 | ((c>>6) & 0x3f); *(s++) = 0x80 | (c & 0x3f); } else if (c <= 0x10ffff) { *(s++) = 0xf0 | (c>>18); *(s++) = 0x80 | ((c>>12) & 0x3f); *(s++) = 0x80 | ((c>>6) & 0x3f); *(s++) = 0x80 | (c & 0x3f); } *out = s; } /*! \brief Converts the given utf8 character to 4-byte unicode. \param in Pointer to a C-String from which utf8 characters will be read. *in will be incremented to reflect the number of characters read, similarly to the \c out parameter for Udf::unicode_to_utf8(). \return The 4-byte unicode character, or **in if passed an invalid character, or 0 if passed any NULL pointers. */ static uint32 utf8_to_unicode(const char **in) { if (!in) return 0; uint8 *bytes = (uint8 *)*in; if (!bytes) return 0; int32 length; uint8 mask = 0x1f; switch (bytes[0] & 0xf0) { case 0xc0: case 0xd0: length = 2; break; case 0xe0: length = 3; break; case 0xf0: mask = 0x0f; length = 4; break; default: // valid 1-byte character // and invalid characters (*in)++; return bytes[0]; } uint32 c = bytes[0] & mask; int32 i = 1; for (;i < length && (bytes[i] & 0x80) > 0;i++) c = (c << 6) | (bytes[i] & 0x3f); if (i < length) { // invalid character (*in)++; return (uint32)bytes[0]; } *in += length; return c; } using namespace Udf; /*! \brief Creates an empty string object. */ String::String() : fCs0String(NULL) , fUtf8String(NULL) { } /*! \brief Creates a new String object from the given Utf8 string. */ String::String(const char *utf8) : fCs0String(NULL) , fUtf8String(NULL) { SetTo(utf8); } /*! \brief Creates a new String object from the given Cs0 string. */ String::String(const char *cs0, uint32 length) : fCs0String(NULL) , fUtf8String(NULL) { SetTo(cs0, length); } String::~String() { DEBUG_INIT("String"); _Clear(); } /*! \brief Assignment from a Utf8 string. */ void String::SetTo(const char *utf8) { DEBUG_INIT_ETC("String", ("utf8: `%s', strlen(utf8): %ld", utf8, utf8 ? strlen(utf8) : 0)); _Clear(); if (!utf8) { PRINT(("passed NULL utf8 string\n")); return; } uint32 length = strlen(utf8); // First copy the utf8 string fUtf8String = new(nothrow) char[length+1]; if (!fUtf8String){ PRINT(("new fUtf8String[%ld] allocation failed\n", length+1)); return; } memcpy(fUtf8String, utf8, length+1); // Next convert to raw 4-byte unicode. Then we'll do some // analysis to figure out if we have any invalid characters, // and whether we can get away with compressed 8-bit unicode, // or have to use burly 16-bit unicode. uint32 *raw = new(nothrow) uint32[length]; if (!raw) { PRINT(("new uint32 raw[%ld] temporary string allocation failed\n", length)); _Clear(); return; } const char *in = utf8; uint32 rawLength = 0; for (uint32 i = 0; i < length && uint32(in-utf8) < length; i++, rawLength++) raw[i] = utf8_to_unicode(&in); // Check for invalids. uint32 mask = 0xffff0000; for (uint32 i = 0; i < rawLength; i++) { if (raw[i] & mask) { PRINT(("WARNING: utf8 string contained a multi-byte sequence which " "was converted into a unicode character larger than 16-bits; " "character will be converted to an underscore character for " "safety.\n")); raw[i] = '_'; } } // See if we can get away with 8-bit compressed unicode mask = 0xffffff00; bool canUse8bit = true; for (uint32 i = 0; i < rawLength; i++) { if (raw[i] & mask) { canUse8bit = false; break; } } // Build our cs0 string if (canUse8bit) { fCs0Length = rawLength+1; fCs0String = new(nothrow) char[fCs0Length]; if (fCs0String) { fCs0String[0] = '\x08'; // 8-bit compressed unicode for (uint32 i = 0; i < rawLength; i++) fCs0String[i+1] = raw[i] % 256; } else { PRINT(("new fCs0String[%ld] allocation failed\n", fCs0Length)); _Clear(); return; } } else { fCs0Length = rawLength*2+1; fCs0String = new(nothrow) char[fCs0Length]; if (fCs0String) { uint32 pos = 0; fCs0String[pos++] = '\x10'; // 16-bit unicode for (uint32 i = 0; i < rawLength; i++) { // 16-bit unicode chars must be written big endian uint16 value = uint16(raw[i]); uint8 high = uint8(value >> 8 & 0xff); uint8 low = uint8(value & 0xff); fCs0String[pos++] = high; fCs0String[pos++] = low; } } else { PRINT(("new fCs0String[%ld] allocation failed\n", fCs0Length)); _Clear(); return; } } // Clean up delete [] raw; raw = NULL; } /*! \brief Assignment from a Cs0 string. */ void String::SetTo(const char *cs0, uint32 length) { DEBUG_INIT_ETC("String", ("cs0: %p, length: %ld", cs0, length)); _Clear(); if (length == 0) return; if (!cs0) { PRINT(("passed NULL cs0 string\n")); return; } // First copy the Cs0 string and length fCs0String = new(nothrow) char[length]; if (fCs0String) { memcpy(fCs0String, cs0, length); fCs0Length = length; } else { PRINT(("new fCs0String[%ld] allocation failed\n", length)); return; } // Now convert to utf8 // The first byte of the CS0 string is the compression ID. // - 8: 1 byte characters // - 16: 2 byte, big endian characters // - 254: "CS0 expansion is empty and unique", 1 byte characters // - 255: "CS0 expansion is empty and unique", 2 byte, big endian characters PRINT(("compression ID: %d\n", cs0[0])); switch (reinterpret_cast<const uint8*>(cs0)[0]) { case 8: case 254: { const uint8 *inputString = reinterpret_cast<const uint8*>(&(cs0[1])); int32 maxLength = length-1; // Max length of input string in uint8 characters int32 allocationLength = maxLength*2+1; // Need at most 2 utf8 chars per uint8 char fUtf8String = new(nothrow) char[allocationLength]; if (fUtf8String) { char *outputString = fUtf8String; for (int32 i = 0; i < maxLength && inputString[i]; i++) { unicode_to_utf8(inputString[i], &outputString); } outputString[0] = 0; } else { PRINT(("new fUtf8String[%ld] allocation failed\n", allocationLength)); } break; } case 16: case 255: { const uint16 *inputString = reinterpret_cast<const uint16*>(&(cs0[1])); int32 maxLength = (length-1) / 2; // Max length of input string in uint16 characters int32 allocationLength = maxLength*3+1; // Need at most 3 utf8 chars per uint16 char fUtf8String = new(nothrow) char[allocationLength]; if (fUtf8String) { char *outputString = fUtf8String; for (int32 i = 0; i < maxLength && inputString[i]; i++) { unicode_to_utf8(B_BENDIAN_TO_HOST_INT16(inputString[i]), &outputString); } outputString[0] = 0; } else { PRINT(("new fUtf8String[%ld] allocation failed\n", allocationLength)); } break; } default: PRINT(("invalid compression id!\n")); break; } } void String::_Clear() { DEBUG_INIT("String"); delete [] fCs0String; fCs0String = NULL; delete [] fUtf8String; fUtf8String = NULL; }
25.162939
88
0.621508
axeld
a0760b5ff624b06be1f243f7da1f7df0e1b2bbdd
3,464
cpp
C++
dstore/network/socket.cpp
Charles0429/dstore
a825e6c4cc30d853f10b7a56f5a9286c2e57cc75
[ "MIT" ]
78
2016-09-24T16:56:00.000Z
2022-03-05T01:05:40.000Z
dstore/network/socket.cpp
Charles0429/dstore
a825e6c4cc30d853f10b7a56f5a9286c2e57cc75
[ "MIT" ]
null
null
null
dstore/network/socket.cpp
Charles0429/dstore
a825e6c4cc30d853f10b7a56f5a9286c2e57cc75
[ "MIT" ]
9
2016-09-30T07:45:35.000Z
2022-03-18T02:43:53.000Z
#include "socket.h" #include <errno.h> #include "errno_define.h" #include "socket_operator.h" #include "log.h" using namespace dstore::network; ListenSocket::ListenSocket(void) : listen_fd_(-1) { } ListenSocket::ListenSocket(int listen_fd) : listen_fd_(listen_fd) { } ListenSocket::~ListenSocket(void) { } void ListenSocket::set_listen_fd(int listen_fd) { listen_fd_ = listen_fd; } int ListenSocket::get_listen_fd(void) { return listen_fd_; } int ListenSocket::socket(const InetAddr &addr) { int ret = DSTORE_SUCCESS; int listen_fd = dstore::network::socket(addr.get_family(), addr.get_socket_type(), addr.get_protocol()); if (-1 == listen_fd) { LOG_WARN("create listen socket failed"); ret = DSTORE_LISTEN_ERROR; return ret; } listen_fd_ = listen_fd; return ret; } int ListenSocket::bind(const InetAddr &addr) { int ret = DSTORE_SUCCESS; ret = dstore::network::bind(listen_fd_, addr.get_addr(), *addr.get_addr_len()); if (-1 == ret) { LOG_WARN("bind listen socket failed, fd=%d", listen_fd_); ret = DSTORE_BIND_ERROR; return ret; } return ret; } int ListenSocket::listen(int backlog) { int ret = DSTORE_SUCCESS; ret = dstore::network::listen(listen_fd_, backlog); if (-1 == ret) { LOG_WARN("listen socket failed, fd=%d", listen_fd_); ret = DSTORE_LISTEN_ERROR; return ret; } return ret; } int ListenSocket::accept(int *fd, InetAddr *addr) { int ret = DSTORE_SUCCESS; *fd = dstore::network::accept(listen_fd_, addr->get_addr(), addr->get_addr_len()); if (-1 == *fd) { LOG_WARN("accept failed, listen_fd=%d", listen_fd_); ret = DSTORE_ACCEPT_ERROR; return ret; } return ret; } int ListenSocket::set_reuseaddr(void) { int ret = DSTORE_SUCCESS; ret = dstore::network::set_reuseaddr(listen_fd_); if (-1 == ret) { LOG_WARN("set reuseaddr failed, listen_fd=%d", listen_fd_); ret = DSTORE_SET_SOCKET_ERROR; return ret; } return ret; } int ListenSocket::set_nonblocking(void) { int ret = DSTORE_SUCCESS; ret = dstore::network::set_nonblocking(listen_fd_); if (-1 == ret) { LOG_WARN("set nonblocking failed, listen_fd=%d", listen_fd_); ret = DSTORE_SET_SOCKET_ERROR; return ret; } return ret; } Socket::Socket(void) : fd_(-1) { } Socket::Socket(int fd) : fd_(fd) { } Socket::~Socket(void) { } void Socket::set_fd(int fd) { fd_ = fd; } int Socket::get_fd(void) { return fd_; } int Socket::socket(const InetAddr &addr) { int ret = DSTORE_SUCCESS; int fd = dstore::network::socket(addr.get_family(), addr.get_socket_type(), addr.get_protocol()); if (-1 == fd) { LOG_WARN("create listen socket failed"); ret = DSTORE_LISTEN_ERROR; return ret; } fd_ = fd; return ret; } int Socket::connect(const InetAddr &addr) { int ret = DSTORE_SUCCESS; ret = dstore::network::connect(fd_, addr.get_addr(), *addr.get_addr_len()); if (-1 == ret) { if (errno == EINPROGRESS) { ret = DSTORE_CONNECT_IN_PROGRESS; } else { ret = DSTORE_CONNECT_ERROR; } } return ret; } int Socket::set_nonblocking(void) { int ret = DSTORE_SUCCESS; ret = dstore::network::set_nonblocking(fd_); if (-1 == ret) { LOG_WARN("set non blocking failed, fd_=%d", fd_); ret = DSTORE_SET_SOCKET_ERROR; return ret; } return ret; } void Socket::close(void) { dstore::network::close(fd_); } bool Socket::is_connect_ok(void) { return dstore::network::is_connect_ok(fd_); }
19.460674
106
0.670035
Charles0429
a0823f182da9173595efdef70b3b69e83659b7a6
3,780
cpp
C++
libnhttp/nhttp/server/internals/contents/http_raw_request_content.cpp
jay94ks/libnhttp
a244eb2d04c339454ef4831b43d1ab270ee7d13d
[ "MIT" ]
4
2021-04-11T22:46:13.000Z
2021-05-27T06:01:37.000Z
libnhttp/nhttp/server/internals/contents/http_raw_request_content.cpp
jay94ks/libnhttp
a244eb2d04c339454ef4831b43d1ab270ee7d13d
[ "MIT" ]
3
2021-05-26T04:16:56.000Z
2021-05-27T04:34:14.000Z
libnhttp/nhttp/server/internals/contents/http_raw_request_content.cpp
jay94ks/libnhttp
a244eb2d04c339454ef4831b43d1ab270ee7d13d
[ "MIT" ]
1
2021-04-11T22:46:15.000Z
2021-04-11T22:46:15.000Z
#include "http_raw_request_content.hpp" #include "../http_chunked_buffer.hpp" namespace nhttp { namespace server { http_raw_request_content::http_raw_request_content(std::shared_ptr<http_chunked_buffer> buffer, ssize_t total_bytes) : waiter(false, true), buffer(buffer), total_bytes(total_bytes), read_requested(false), avail_bytes(0), is_end(false), non_block(false) { } /* determines validity of this stream. */ bool http_raw_request_content::is_valid() const { std::lock_guard<decltype(spinlock)> guard(spinlock); return buffer != nullptr; } /* determines currently at end of stream. */ bool http_raw_request_content::is_end_of() const { std::lock_guard<decltype(spinlock)> guard(spinlock); return buffer == nullptr || (avail_bytes <= 0 && is_end) || !total_bytes; } /* determines this stream is based on non-blocking or not. */ bool http_raw_request_content::is_nonblock() const { std::lock_guard<decltype(spinlock)> guard(spinlock); return buffer == nullptr || non_block; } bool http_raw_request_content::set_nonblock(bool value) { std::lock_guard<decltype(spinlock)> guard(spinlock); non_block = value; return true; } /* determines this stream can be read immediately or not. */ bool http_raw_request_content::can_read() const { std::lock_guard<decltype(spinlock)> guard(spinlock); return buffer == nullptr || avail_bytes > 0; } bool http_raw_request_content::wanna_read(size_t spins) const { while (spins--) { if (!spinlock.try_lock()) return false; if (buffer != nullptr && read_requested) { spinlock.unlock(); return true; } spinlock.unlock(); } return false; } /* notify given bytes ready to provide. */ void http_raw_request_content::notify(size_t bytes, bool is_end) { std::lock_guard<decltype(spinlock)> guard(spinlock); avail_bytes += bytes; this->is_end = is_end; waiter.signal(); } /* link will call this before terminating the request. */ void http_raw_request_content::disconnect() { std::lock_guard<decltype(spinlock)> guard(spinlock); buffer = nullptr; read_requested = false; avail_bytes = 0; waiter.signal(); } /** * get total length of this stream. * @warn default-impl uses `tell()` and `seek()` to provide length! * @returns: * >= 0: length. * < 0: not supported. */ ssize_t http_raw_request_content::get_length() const { std::lock_guard<decltype(spinlock)> guard(spinlock); if (buffer != nullptr) { set_errno_c(0); if (total_bytes < 0) set_errno_c(ENOTSUP); return total_bytes; } set_errno_c(ENOENT); return 0; } /** * read bytes from stream. * @returns: * > 0: read size. * = 0: end of stream. * < 0: not supported or not available if non-block. * @note: * errno == EWOULDBLOCK: for non-block mode. */ int32_t http_raw_request_content::read(void* buf, size_t len) { std::lock_guard<decltype(spinlock)> guard(spinlock); return read_locked(buf, len); } int32_t http_raw_request_content::read_locked(void* buf, size_t len) { size_t read_bytes; set_errno(0); while (buffer != nullptr) { if ((read_bytes = len > avail_bytes ? avail_bytes : len) > 0) { size_t ret = buffer->read(buf, read_bytes); /* keep flag if length is less than read. */ read_requested = ret < len; avail_bytes -= ret; if (avail_bytes > 0) waiter.signal(); else waiter.unsignal(); std::this_thread::yield(); return int32_t(ret); } read_requested = true; if (non_block) { set_errno(EWOULDBLOCK); spinlock.unlock(); return -1; } if (is_end) { break; } spinlock.unlock(); std::this_thread::yield(); if (!waiter.try_wait()) waiter.wait(); spinlock.lock(); } set_errno(ENOENT); return 0; } } }
22.235294
117
0.678836
jay94ks
a084e4bea63910d8e7bec1b30b26238694bbb5a2
16,607
cpp
C++
Wexport/release/windows/obj/src/openfl/display3D/_internal/_AGALConverter/SourceRegister.cpp
BushsHaxs/FNF-coding-tutorial
596c6a938eb687440cbcddda9a4005db67bc68bb
[ "Apache-2.0" ]
1
2021-07-19T05:10:43.000Z
2021-07-19T05:10:43.000Z
Wexport/release/windows/obj/src/openfl/display3D/_internal/_AGALConverter/SourceRegister.cpp
BushsHaxs/FNF-coding-tutorial
596c6a938eb687440cbcddda9a4005db67bc68bb
[ "Apache-2.0" ]
null
null
null
Wexport/release/windows/obj/src/openfl/display3D/_internal/_AGALConverter/SourceRegister.cpp
BushsHaxs/FNF-coding-tutorial
596c6a938eb687440cbcddda9a4005db67bc68bb
[ "Apache-2.0" ]
1
2021-12-11T09:19:29.000Z
2021-12-11T09:19:29.000Z
#include <hxcpp.h> #ifndef INCLUDED_38344beec7696400 #define INCLUDED_38344beec7696400 #include "cpp/Int64.h" #endif #ifndef INCLUDED_openfl_display3D__internal_AGALConverter #include <openfl/display3D/_internal/AGALConverter.h> #endif #ifndef INCLUDED_openfl_display3D__internal__AGALConverter_ProgramType #include <openfl/display3D/_internal/_AGALConverter/ProgramType.h> #endif #ifndef INCLUDED_openfl_display3D__internal__AGALConverter_SourceRegister #include <openfl/display3D/_internal/_AGALConverter/SourceRegister.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_6326831c4b7b616c_961_new,"openfl.display3D._internal._AGALConverter.SourceRegister","new",0xa0d15d23,"openfl.display3D._internal._AGALConverter.SourceRegister.new","openfl/display3D/_internal/AGALConverter.hx",961,0x4de1651d) HX_LOCAL_STACK_FRAME(_hx_pos_6326831c4b7b616c_979_toGLSL,"openfl.display3D._internal._AGALConverter.SourceRegister","toGLSL",0x906ee816,"openfl.display3D._internal._AGALConverter.SourceRegister.toGLSL","openfl/display3D/_internal/AGALConverter.hx",979,0x4de1651d) HX_LOCAL_STACK_FRAME(_hx_pos_6326831c4b7b616c_964_parse,"openfl.display3D._internal._AGALConverter.SourceRegister","parse",0xa1e213b6,"openfl.display3D._internal._AGALConverter.SourceRegister.parse","openfl/display3D/_internal/AGALConverter.hx",964,0x4de1651d) HX_LOCAL_STACK_FRAME(_hx_pos_6326831c4b7b616c_949_boot,"openfl.display3D._internal._AGALConverter.SourceRegister","boot",0x0e79220f,"openfl.display3D._internal._AGALConverter.SourceRegister.boot","openfl/display3D/_internal/AGALConverter.hx",949,0x4de1651d) namespace openfl{ namespace display3D{ namespace _internal{ namespace _AGALConverter{ void SourceRegister_obj::__construct(){ HX_STACKFRAME(&_hx_pos_6326831c4b7b616c_961_new) } Dynamic SourceRegister_obj::__CreateEmpty() { return new SourceRegister_obj; } void *SourceRegister_obj::_hx_vtable = 0; Dynamic SourceRegister_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< SourceRegister_obj > _hx_result = new SourceRegister_obj(); _hx_result->__construct(); return _hx_result; } bool SourceRegister_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x5dd77f8b; } ::String SourceRegister_obj::toGLSL(::hx::Null< bool > __o_emitSwizzle,::hx::Null< int > __o_offset){ bool emitSwizzle = __o_emitSwizzle.Default(true); int offset = __o_offset.Default(0); HX_STACKFRAME(&_hx_pos_6326831c4b7b616c_979_toGLSL) HXLINE( 980) if ((this->type == 3)) { HXLINE( 982) if (::hx::IsPointerEq( this->programType,::openfl::display3D::_internal::_AGALConverter::ProgramType_obj::VERTEX_dyn() )) { HXLINE( 982) return HX_("gl_Position",63,0d,2a,e5); } else { HXLINE( 982) return HX_("gl_FragColor",d7,68,e4,21); } } HXLINE( 985) bool fullxyzw; HXDLIN( 985) if ((this->s == 228)) { HXLINE( 985) fullxyzw = (this->sourceMask == 15); } else { HXLINE( 985) fullxyzw = false; } HXLINE( 986) ::String swizzle = HX_("",00,00,00,00); HXLINE( 988) bool _hx_tmp; HXDLIN( 988) if ((this->type != 5)) { HXLINE( 988) _hx_tmp = !(fullxyzw); } else { HXLINE( 988) _hx_tmp = false; } HXDLIN( 988) if (_hx_tmp) { HXLINE( 993) if (((this->sourceMask & 1) != 0)) { HXLINE( 995) switch((int)((this->s & 3))){ case (int)0: { HXLINE( 998) swizzle = (swizzle + HX_("x",78,00,00,00)); } break; case (int)1: { HXLINE(1000) swizzle = (swizzle + HX_("y",79,00,00,00)); } break; case (int)2: { HXLINE(1002) swizzle = (swizzle + HX_("z",7a,00,00,00)); } break; case (int)3: { HXLINE(1004) swizzle = (swizzle + HX_("w",77,00,00,00)); } break; } } HXLINE( 993) if (((this->sourceMask & 2) != 0)) { HXLINE( 995) switch((int)(((this->s >> 2) & 3))){ case (int)0: { HXLINE( 998) swizzle = (swizzle + HX_("x",78,00,00,00)); } break; case (int)1: { HXLINE(1000) swizzle = (swizzle + HX_("y",79,00,00,00)); } break; case (int)2: { HXLINE(1002) swizzle = (swizzle + HX_("z",7a,00,00,00)); } break; case (int)3: { HXLINE(1004) swizzle = (swizzle + HX_("w",77,00,00,00)); } break; } } HXLINE( 993) if (((this->sourceMask & 4) != 0)) { HXLINE( 995) switch((int)(((this->s >> 4) & 3))){ case (int)0: { HXLINE( 998) swizzle = (swizzle + HX_("x",78,00,00,00)); } break; case (int)1: { HXLINE(1000) swizzle = (swizzle + HX_("y",79,00,00,00)); } break; case (int)2: { HXLINE(1002) swizzle = (swizzle + HX_("z",7a,00,00,00)); } break; case (int)3: { HXLINE(1004) swizzle = (swizzle + HX_("w",77,00,00,00)); } break; } } HXLINE( 993) if (((this->sourceMask & 8) != 0)) { HXLINE( 995) switch((int)(((this->s >> 6) & 3))){ case (int)0: { HXLINE( 998) swizzle = (swizzle + HX_("x",78,00,00,00)); } break; case (int)1: { HXLINE(1000) swizzle = (swizzle + HX_("y",79,00,00,00)); } break; case (int)2: { HXLINE(1002) swizzle = (swizzle + HX_("z",7a,00,00,00)); } break; case (int)3: { HXLINE(1004) swizzle = (swizzle + HX_("w",77,00,00,00)); } break; } } } HXLINE(1010) ::String str = ::openfl::display3D::_internal::AGALConverter_obj::prefixFromType(this->type,this->programType); HXLINE(1012) if ((this->d == 0)) { HXLINE(1015) str = (str + (this->n + offset)); } else { HXLINE(1020) str = (str + this->o); HXLINE(1021) ::String indexComponent = HX_("",00,00,00,00); HXLINE(1022) switch((int)(this->q)){ case (int)0: { HXLINE(1025) indexComponent = HX_("x",78,00,00,00); } break; case (int)1: { HXLINE(1027) indexComponent = HX_("y",79,00,00,00); } break; case (int)2: { HXLINE(1029) indexComponent = HX_("z",7a,00,00,00); } break; case (int)3: { HXLINE(1031) indexComponent = HX_("w",77,00,00,00); } break; } HXLINE(1033) ::String indexRegister = ::openfl::display3D::_internal::AGALConverter_obj::prefixFromType(this->itype,this->programType); HXDLIN(1033) ::String indexRegister1 = (((indexRegister + this->n) + HX_(".",2e,00,00,00)) + indexComponent); HXLINE(1034) str = (str + ((((HX_("[ int(",3e,aa,07,15) + indexRegister1) + HX_(") +",74,38,1f,00)) + offset) + HX_("]",5d,00,00,00))); } HXLINE(1037) bool _hx_tmp1; HXDLIN(1037) if (emitSwizzle) { HXLINE(1037) _hx_tmp1 = (swizzle != HX_("",00,00,00,00)); } else { HXLINE(1037) _hx_tmp1 = false; } HXDLIN(1037) if (_hx_tmp1) { HXLINE(1039) str = (str + (HX_(".",2e,00,00,00) + swizzle)); } HXLINE(1042) return str; } HX_DEFINE_DYNAMIC_FUNC2(SourceRegister_obj,toGLSL,return ) ::openfl::display3D::_internal::_AGALConverter::SourceRegister SourceRegister_obj::parse( cpp::Int64Struct v, ::openfl::display3D::_internal::_AGALConverter::ProgramType programType,int sourceMask){ HX_GC_STACKFRAME(&_hx_pos_6326831c4b7b616c_964_parse) HXLINE( 965) ::openfl::display3D::_internal::_AGALConverter::SourceRegister sr = ::openfl::display3D::_internal::_AGALConverter::SourceRegister_obj::__alloc( HX_CTX ); HXLINE( 966) sr->programType = programType; HXLINE( 967) cpp::Int64Struct a = _hx_int64_shr(v,63); HXDLIN( 967) sr->d = _hx_int64_low(_hx_int64_and(a,( ::cpp::Int64Struct(1)))); HXLINE( 968) cpp::Int64Struct a1 = _hx_int64_shr(v,48); HXDLIN( 968) sr->q = _hx_int64_low(_hx_int64_and(a1,( ::cpp::Int64Struct(3)))); HXLINE( 969) cpp::Int64Struct a2 = _hx_int64_shr(v,40); HXDLIN( 969) sr->itype = _hx_int64_low(_hx_int64_and(a2,( ::cpp::Int64Struct(15)))); HXLINE( 970) cpp::Int64Struct a3 = _hx_int64_shr(v,32); HXDLIN( 970) sr->type = _hx_int64_low(_hx_int64_and(a3,( ::cpp::Int64Struct(15)))); HXLINE( 971) cpp::Int64Struct a4 = _hx_int64_shr(v,24); HXDLIN( 971) sr->s = _hx_int64_low(_hx_int64_and(a4,( ::cpp::Int64Struct(255)))); HXLINE( 972) cpp::Int64Struct a5 = _hx_int64_shr(v,16); HXDLIN( 972) sr->o = _hx_int64_low(_hx_int64_and(a5,( ::cpp::Int64Struct(255)))); HXLINE( 973) sr->n = _hx_int64_low(_hx_int64_and(v,( ::cpp::Int64Struct(65535)))); HXLINE( 974) sr->sourceMask = sourceMask; HXLINE( 975) return sr; } STATIC_HX_DEFINE_DYNAMIC_FUNC3(SourceRegister_obj,parse,return ) ::hx::ObjectPtr< SourceRegister_obj > SourceRegister_obj::__new() { ::hx::ObjectPtr< SourceRegister_obj > __this = new SourceRegister_obj(); __this->__construct(); return __this; } ::hx::ObjectPtr< SourceRegister_obj > SourceRegister_obj::__alloc(::hx::Ctx *_hx_ctx) { SourceRegister_obj *__this = (SourceRegister_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(SourceRegister_obj), true, "openfl.display3D._internal._AGALConverter.SourceRegister")); *(void **)__this = SourceRegister_obj::_hx_vtable; __this->__construct(); return __this; } SourceRegister_obj::SourceRegister_obj() { } void SourceRegister_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(SourceRegister); HX_MARK_MEMBER_NAME(d,"d"); HX_MARK_MEMBER_NAME(itype,"itype"); HX_MARK_MEMBER_NAME(n,"n"); HX_MARK_MEMBER_NAME(o,"o"); HX_MARK_MEMBER_NAME(programType,"programType"); HX_MARK_MEMBER_NAME(q,"q"); HX_MARK_MEMBER_NAME(s,"s"); HX_MARK_MEMBER_NAME(sourceMask,"sourceMask"); HX_MARK_MEMBER_NAME(type,"type"); HX_MARK_END_CLASS(); } void SourceRegister_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(d,"d"); HX_VISIT_MEMBER_NAME(itype,"itype"); HX_VISIT_MEMBER_NAME(n,"n"); HX_VISIT_MEMBER_NAME(o,"o"); HX_VISIT_MEMBER_NAME(programType,"programType"); HX_VISIT_MEMBER_NAME(q,"q"); HX_VISIT_MEMBER_NAME(s,"s"); HX_VISIT_MEMBER_NAME(sourceMask,"sourceMask"); HX_VISIT_MEMBER_NAME(type,"type"); } ::hx::Val SourceRegister_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 1: if (HX_FIELD_EQ(inName,"d") ) { return ::hx::Val( d ); } if (HX_FIELD_EQ(inName,"n") ) { return ::hx::Val( n ); } if (HX_FIELD_EQ(inName,"o") ) { return ::hx::Val( o ); } if (HX_FIELD_EQ(inName,"q") ) { return ::hx::Val( q ); } if (HX_FIELD_EQ(inName,"s") ) { return ::hx::Val( s ); } break; case 4: if (HX_FIELD_EQ(inName,"type") ) { return ::hx::Val( type ); } break; case 5: if (HX_FIELD_EQ(inName,"itype") ) { return ::hx::Val( itype ); } break; case 6: if (HX_FIELD_EQ(inName,"toGLSL") ) { return ::hx::Val( toGLSL_dyn() ); } break; case 10: if (HX_FIELD_EQ(inName,"sourceMask") ) { return ::hx::Val( sourceMask ); } break; case 11: if (HX_FIELD_EQ(inName,"programType") ) { return ::hx::Val( programType ); } } return super::__Field(inName,inCallProp); } bool SourceRegister_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"parse") ) { outValue = parse_dyn(); return true; } } return false; } ::hx::Val SourceRegister_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 1: if (HX_FIELD_EQ(inName,"d") ) { d=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"n") ) { n=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"o") ) { o=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"q") ) { q=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"s") ) { s=inValue.Cast< int >(); return inValue; } break; case 4: if (HX_FIELD_EQ(inName,"type") ) { type=inValue.Cast< int >(); return inValue; } break; case 5: if (HX_FIELD_EQ(inName,"itype") ) { itype=inValue.Cast< int >(); return inValue; } break; case 10: if (HX_FIELD_EQ(inName,"sourceMask") ) { sourceMask=inValue.Cast< int >(); return inValue; } break; case 11: if (HX_FIELD_EQ(inName,"programType") ) { programType=inValue.Cast< ::openfl::display3D::_internal::_AGALConverter::ProgramType >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void SourceRegister_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("d",64,00,00,00)); outFields->push(HX_("itype",a3,db,1b,c2)); outFields->push(HX_("n",6e,00,00,00)); outFields->push(HX_("o",6f,00,00,00)); outFields->push(HX_("programType",5e,fb,2c,c4)); outFields->push(HX_("q",71,00,00,00)); outFields->push(HX_("s",73,00,00,00)); outFields->push(HX_("sourceMask",67,27,ba,70)); outFields->push(HX_("type",ba,f2,08,4d)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo SourceRegister_obj_sMemberStorageInfo[] = { {::hx::fsInt,(int)offsetof(SourceRegister_obj,d),HX_("d",64,00,00,00)}, {::hx::fsInt,(int)offsetof(SourceRegister_obj,itype),HX_("itype",a3,db,1b,c2)}, {::hx::fsInt,(int)offsetof(SourceRegister_obj,n),HX_("n",6e,00,00,00)}, {::hx::fsInt,(int)offsetof(SourceRegister_obj,o),HX_("o",6f,00,00,00)}, {::hx::fsObject /* ::openfl::display3D::_internal::_AGALConverter::ProgramType */ ,(int)offsetof(SourceRegister_obj,programType),HX_("programType",5e,fb,2c,c4)}, {::hx::fsInt,(int)offsetof(SourceRegister_obj,q),HX_("q",71,00,00,00)}, {::hx::fsInt,(int)offsetof(SourceRegister_obj,s),HX_("s",73,00,00,00)}, {::hx::fsInt,(int)offsetof(SourceRegister_obj,sourceMask),HX_("sourceMask",67,27,ba,70)}, {::hx::fsInt,(int)offsetof(SourceRegister_obj,type),HX_("type",ba,f2,08,4d)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *SourceRegister_obj_sStaticStorageInfo = 0; #endif static ::String SourceRegister_obj_sMemberFields[] = { HX_("d",64,00,00,00), HX_("itype",a3,db,1b,c2), HX_("n",6e,00,00,00), HX_("o",6f,00,00,00), HX_("programType",5e,fb,2c,c4), HX_("q",71,00,00,00), HX_("s",73,00,00,00), HX_("sourceMask",67,27,ba,70), HX_("type",ba,f2,08,4d), HX_("toGLSL",f9,58,08,7a), ::String(null()) }; ::hx::Class SourceRegister_obj::__mClass; static ::String SourceRegister_obj_sStaticFields[] = { HX_("parse",33,90,55,bd), ::String(null()) }; void SourceRegister_obj::__register() { SourceRegister_obj _hx_dummy; SourceRegister_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("openfl.display3D._internal._AGALConverter.SourceRegister",b1,8f,b5,4c); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &SourceRegister_obj::__GetStatic; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(SourceRegister_obj_sStaticFields); __mClass->mMembers = ::hx::Class_obj::dupFunctions(SourceRegister_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< SourceRegister_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = SourceRegister_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = SourceRegister_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } void SourceRegister_obj::__boot() { { HX_STACKFRAME(&_hx_pos_6326831c4b7b616c_949_boot) HXDLIN( 949) __mClass->__meta__ = ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("obj",f7,8f,54,00), ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("SuppressWarnings",0c,d3,d2,00),::cpp::VirtualArray_obj::__new(1)->init(0,HX_("checkstyle:FieldDocComment",70,56,1b,20)))))); } } } // end namespace openfl } // end namespace display3D } // end namespace _internal } // end namespace _AGALConverter
39.729665
263
0.637924
BushsHaxs
a0854cdc46be26319f323a521cc75876e4b9e912
377
cpp
C++
codelib/dynamic_programming/knapsack2.cpp
TissueRoll/admu-progvar-notebook
efd1c48872d40aeabe2b03af7b986bb831c062b1
[ "MIT" ]
null
null
null
codelib/dynamic_programming/knapsack2.cpp
TissueRoll/admu-progvar-notebook
efd1c48872d40aeabe2b03af7b986bb831c062b1
[ "MIT" ]
null
null
null
codelib/dynamic_programming/knapsack2.cpp
TissueRoll/admu-progvar-notebook
efd1c48872d40aeabe2b03af7b986bb831c062b1
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> int main() { int N, C; std::cin >> N >> C; int W[N], V[N]; for (int i = 0; i < N; ++i) std::cin >> W[i] >> V[i]; int dp[C + 1]; memset(dp, 0, sizeof dp); for (int w = 0; w <= C; ++w) for (int i = 0; i < N; ++i) dp[w] = (w < W[i]) ? dp[w] : dp[w - W[i]] + V[i]; std::cout << dp[C] << "\n"; return 0; }
17.952381
55
0.416446
TissueRoll
a0875bc7620f11832ee4b123d023c6d15c691c98
591
cc
C++
algo/dp/palindrome.cc
liuheng/recipes
6f3759ab4e4fa64d9fd83a60ee6b6846510d910b
[ "MIT" ]
null
null
null
algo/dp/palindrome.cc
liuheng/recipes
6f3759ab4e4fa64d9fd83a60ee6b6846510d910b
[ "MIT" ]
null
null
null
algo/dp/palindrome.cc
liuheng/recipes
6f3759ab4e4fa64d9fd83a60ee6b6846510d910b
[ "MIT" ]
null
null
null
#include <cstdio> #include <algorithm> #include <string> using namespace std; int minCut(const string &s) { int N = s.length(); bool p[N][N]; int f[N+1]; for (int j=0; j<=N; ++j) { f[j] = j-1; p[j][j] = true; for (int i=0; i<j; ++i) { if (s.at(i) == s.at(j-1) && (j - i < 2 || p[i+1][j-1])) { p[i][j] = true; f[j] = min(f[j], f[i]+1); } else { p[i][j] = false; } } } return f[N]; } int main() { printf("%d\n", minCut("abcbc")); return 0; }
19.7
69
0.382403
liuheng
a0881f28bc370a9ebdef061cf2c9d6948b6822e0
39,119
cpp
C++
tests/get_kv_table_nodeos_tests.cpp
forfreeday/eos
11d35f0f934402321853119d36caeb7022813743
[ "Apache-2.0", "MIT" ]
13,162
2017-05-29T22:08:27.000Z
2022-03-29T19:25:05.000Z
tests/get_kv_table_nodeos_tests.cpp
forfreeday/eos
11d35f0f934402321853119d36caeb7022813743
[ "Apache-2.0", "MIT" ]
6,450
2017-05-30T14:41:50.000Z
2022-03-30T11:30:04.000Z
tests/get_kv_table_nodeos_tests.cpp
forfreeday/eos
11d35f0f934402321853119d36caeb7022813743
[ "Apache-2.0", "MIT" ]
4,491
2017-05-29T22:08:32.000Z
2022-03-29T07:09:52.000Z
#include <boost/test/unit_test.hpp> #include <boost/algorithm/string/predicate.hpp> #include <eosio/testing/tester.hpp> #include <eosio/chain/abi_serializer.hpp> #include <eosio/chain/wasm_eosio_constraints.hpp> #include <eosio/chain/resource_limits.hpp> #include <eosio/chain/exceptions.hpp> #include <eosio/chain/wast_to_wasm.hpp> #include <eosio/chain_plugin/chain_plugin.hpp> #include <eosio/chain/backing_store/kv_context.hpp> #include <contracts.hpp> #include <fc/io/fstream.hpp> #include <Runtime/Runtime.h> #include <fc/variant_object.hpp> #include <fc/io/json.hpp> #include <array> #include <utility> #ifdef NON_VALIDATING_TEST #define TESTER tester #else #define TESTER validating_tester #endif BOOST_AUTO_TEST_SUITE(get_kv_table_nodeos_tests) using namespace eosio::chain; using namespace eosio::testing; using namespace fc; BOOST_FIXTURE_TEST_CASE( get_kv_table_nodeos_test, TESTER ) try { eosio::chain_apis::read_only::get_table_rows_result result; auto chk_result = [&](int row, int data, bool show_payer = false) { char bar[5] = {'b', 'o', 'b', 'a', 0}; bar[3] += data - 1; // 'a' + data - 1 auto& row_value = result.rows[row]; auto check_row_value_data = [&data, &bar](const auto& v) { BOOST_CHECK_EQUAL(bar, v["primary_key"].as_string()); BOOST_CHECK_EQUAL(bar, v["bar"]); BOOST_CHECK_EQUAL(std::to_string(data), v["foo"].as_string()); }; if (show_payer) { BOOST_CHECK_EQUAL(row_value["payer"].as_string(), "kvtable"); check_row_value_data(row_value["data"]); } else { check_row_value_data(row_value); } }; produce_blocks(2); create_accounts({"kvtable"_n}); produce_block(); set_code(config::system_account_name, contracts::kv_bios_wasm()); set_abi(config::system_account_name, contracts::kv_bios_abi().data()); push_action("eosio"_n, "ramkvlimits"_n, "eosio"_n, mutable_variant_object()("k", 1024)("v", 1024)("i", 1024)); produce_blocks(1); set_code("kvtable"_n, contracts::kv_table_test_wasm()); set_abi("kvtable"_n, contracts::kv_table_test_abi().data()); produce_blocks(1); auto arg = mutable_variant_object(); push_action("kvtable"_n, "setup"_n, "kvtable"_n, arg); ////////////////////////////// // primarykey ////////////////////////////// eosio::chain_apis::read_only plugin(*(this->control), {}, fc::microseconds::maximum()); eosio::chain_apis::read_only::get_kv_table_rows_params p; p.code = "kvtable"_n; p.table = "kvtable"_n; p.index_name = "primarykey"_n; p.index_value = "boba"; p.encode_type = "name"; p.lower_bound = {}; p.upper_bound = {}; p.json = true; p.reverse = false; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 1); p.show_payer = true; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 1, p.show_payer); p.show_payer = false; p.reverse = true; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 1); p.reverse = false; p.index_name = "primarykey"_n; p.index_value = "bobj"; p.encode_type = ""; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 10); p.encode_type = "name"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 10); p.encode_type = "name"; p.index_value = "bob"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(0u, result.rows.size()); p.index_value = "bobx"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(0u, result.rows.size()); p.show_payer = true; p.index_value = {}; p.lower_bound = "bobb"; p.upper_bound = "bobe"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(4u, result.rows.size()); chk_result(0, 2, p.show_payer); chk_result(1, 3, p.show_payer); chk_result(2, 4, p.show_payer); chk_result(3, 5, p.show_payer); p.index_value = "boba"; p.lower_bound = "bobb"; p.upper_bound = "bobe"; BOOST_CHECK_THROW(plugin.read_only::get_kv_table_rows(p), contract_table_query_exception); p.index_value = {}; p.lower_bound = "bobe"; p.upper_bound = "bobb"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(0u, result.rows.size()); p.show_payer = false; p.lower_bound = "aaaa"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); chk_result(9, 10); p.lower_bound = "boba"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); chk_result(9, 10); p.lower_bound = "bobj"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 10); p.lower_bound = "bobz"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(0u, result.rows.size()); p.lower_bound = "bob"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.reverse = true; p.lower_bound = {}; p.upper_bound = "bobz"; result = plugin.read_only::get_kv_table_rows(p); chk_result(0, 10); chk_result(1, 9); chk_result(2, 8); chk_result(3, 7); chk_result(4, 6); chk_result(5, 5); chk_result(6, 4); chk_result(7, 3); chk_result(8, 2); chk_result(9, 1); p.reverse = true; p.lower_bound = "bobc"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(8u, result.rows.size()); p.reverse = false; p.lower_bound = {}; p.upper_bound = "bobz"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.lower_bound = "bobc"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(8u, result.rows.size()); p.reverse = false; p.lower_bound = {}; p.upper_bound = "bobz"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.reverse = true; p.lower_bound = "bobj"; p.upper_bound = "bobz"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); p.lower_bound = "bobb"; p.upper_bound = "bobe"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(4u, result.rows.size()); chk_result(0, 5); chk_result(1, 4); chk_result(2, 3); chk_result(3, 2); p.lower_bound = ""; p.upper_bound = "bobe"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(5u, result.rows.size()); chk_result(0, 5); chk_result(1, 4); chk_result(2, 3); chk_result(3, 2); chk_result(4, 1); p.reverse = false; p.lower_bound = "boba"; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes != "", true); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key_bytes; p.encode_type = "bytes"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); chk_result(0, 3); chk_result(1, 4); p.lower_bound = result.next_key_bytes; p.encode_type = "bytes"; p.limit = 1; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); chk_result(0, 5); p.lower_bound = result.next_key_bytes; p.encode_type = "bytes"; p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(5u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); chk_result(0, 6); chk_result(1, 7); chk_result(2, 8); chk_result(3, 9); chk_result(4, 10); // test next_key p.index_name = "primarykey"_n; p.index_value = {}; p.reverse = false; p.encode_type = "name"; p.lower_bound = "boba"; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, "bobc"); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "3D0E800000000000"); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.next_key, "bobe"); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "3D0EA00000000000"); chk_result(0, 3); chk_result(1, 4); p.lower_bound = result.next_key; p.limit = 1; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, "bobf"); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "3D0EB00000000000"); chk_result(0, 5); p.lower_bound = result.next_key; p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(5u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); chk_result(0, 6); chk_result(1, 7); chk_result(2, 8); chk_result(3, 9); chk_result(4, 10); p.reverse = true; p.upper_bound = "bobj"; p.lower_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, "bobh"); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "3D0ED00000000000"); chk_result(0, 10); chk_result(1, 9); p.upper_bound = result.next_key; p.limit = 7; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(7u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, "boba"); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "3D0E600000000000"); chk_result(0, 8); chk_result(1, 7); chk_result(2, 6); chk_result(3, 5); chk_result(4, 4); chk_result(5, 3); chk_result(6, 2); p.upper_bound = result.next_key; p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); chk_result(0, 1); ////////////////////////////// // foo ////////////////////////////// p.reverse = false; p.index_name = "foo"_n; p.index_value = "A"; // 10 p.encode_type = "hex"; p.lower_bound = {}; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 10); p.index_value = "10"; p.encode_type = ""; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 10); p.index_value = "10"; p.encode_type = "dec"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 10); p.index_value = {}; p.encode_type = "hex"; p.lower_bound = "1"; p.upper_bound = "10"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0"; p.upper_bound = "10"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); p.lower_bound = "2"; p.upper_bound = "9"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(8u, result.rows.size()); chk_result(0, 2); chk_result(1, 3); chk_result(2, 4); chk_result(3, 5); chk_result(4, 6); chk_result(5, 7); chk_result(6, 8); chk_result(7, 9); p.lower_bound = "0"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); p.lower_bound = "1"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); p.lower_bound = "10"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 10); p.lower_bound = "11"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(0u, result.rows.size()); p.reverse = false; p.lower_bound = "0"; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key_bytes; p.encode_type = "bytes"; p.limit = 3; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(3u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); chk_result(0, 3); chk_result(1, 4); chk_result(2, 5); p.lower_bound = result.next_key_bytes; p.encode_type = "bytes"; p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(5, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); chk_result(0, 6); chk_result(1, 7); chk_result(2, 8); chk_result(3, 9); chk_result(4, 10); // test next_key p.index_name = "foo"_n; p.reverse = false; p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0"; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(3)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "0000000000000003"); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key; p.limit = 3; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(3u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(6)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "0000000000000006"); chk_result(0, 3); chk_result(1, 4); chk_result(2, 5); p.lower_bound = result.next_key; p.limit = 4; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(4, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(10)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "000000000000000A"); chk_result(0, 6); chk_result(1, 7); chk_result(2, 8); chk_result(3, 9); p.lower_bound = result.next_key; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); chk_result(0, 10); p.encode_type = "hex"; p.lower_bound = "0"; p.upper_bound = {}; p.limit = 4; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(4u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(5)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "0000000000000005"); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); p.lower_bound = result.next_key; p.limit = 5; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(5u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, "A"); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "000000000000000A"); chk_result(0, 5); chk_result(1, 6); chk_result(2, 7); chk_result(3, 8); chk_result(4, 9); p.lower_bound = result.next_key; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); chk_result(0, 10); p.lower_bound = "10"; p.limit = 20; //maximize limit for the following test cases result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(0u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); ////////////////////////////// // bar ////////////////////////////// p.index_name = "bar"_n; p.index_value = "boba"; p.encode_type = ""; p.lower_bound = {}; p.upper_bound = {}; p.reverse = false; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 1); p.encode_type = "string"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 1); p.index_value = "bobj"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 10); p.index_value = "bobx"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(0u, result.rows.size()); p.index_value = {}; p.lower_bound = "bobb"; p.upper_bound = "bobe"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(4u, result.rows.size()); chk_result(0, 2); chk_result(1, 3); chk_result(2, 4); chk_result(3, 5); p.index_value = {}; p.lower_bound = "boba1"; p.upper_bound = "bobj"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); p.index_value = {}; p.lower_bound = "boba"; p.upper_bound = "bobj1"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.index_value = {}; p.lower_bound = "boba"; p.upper_bound = "c"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.index_value = {}; p.lower_bound = "a"; p.upper_bound = "c"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.lower_bound = "aaaa"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); p.lower_bound = "boba"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); p.lower_bound = "bobj"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 10); p.lower_bound = "bobz"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(0u, result.rows.size()); p.lower_bound = "b"; p.upper_bound = "bobj1"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.lower_bound = "bobj"; p.upper_bound = "bobz"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); p.reverse = true; p.lower_bound = {}; p.upper_bound = "bobz"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 10); p.lower_bound = "b"; p.upper_bound = "bobj1"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.lower_bound = "bobj"; p.upper_bound = "bobz"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); p.lower_bound = "bobb"; p.upper_bound = "bobe"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(4u, result.rows.size()); chk_result(0, 5); chk_result(1, 4); chk_result(2, 3); chk_result(3, 2); p.lower_bound = {}; p.upper_bound = "bobe"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(5u, result.rows.size()); chk_result(0, 5); chk_result(1, 4); chk_result(2, 3); chk_result(3, 2); chk_result(4, 1); p.reverse = false; p.lower_bound = "boba"; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key_bytes; p.encode_type = "bytes"; p.limit = 3; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(3u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); chk_result(0, 3); chk_result(1, 4); chk_result(2, 5); p.lower_bound = result.next_key_bytes; p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(5u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); chk_result(0, 6); chk_result(1, 7); chk_result(2, 8); chk_result(3, 9); chk_result(4, 10); // test next_key p.index_name = "bar"_n; p.encode_type = "string"; p.reverse = false; p.index_value = {}; p.lower_bound = "boba"; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, "bobc"); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "626F62630000"); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key; p.limit = 3; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(3u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, "bobf"); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "626F62660000"); chk_result(0, 3); chk_result(1, 4); chk_result(2, 5); p.lower_bound = result.next_key; p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(5u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); chk_result(0, 6); chk_result(1, 7); chk_result(2, 8); chk_result(3, 9); chk_result(4, 10); ////////////////////////////// // uint32_t : 0, 10, 20,..., 80, 90 ////////////////////////////// p.reverse = false; p.index_name = "u"_n; p.index_value = "A"; // 10 p.encode_type = "hex"; p.lower_bound = {}; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 1); p.index_value = {}; p.encode_type = ""; p.lower_bound = "10"; p.upper_bound = "100"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.encode_type = "dec"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0"; p.upper_bound = "110"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); ////////////////////////////// // int32_t : -40, -30,..., 40, 50 ////////////////////////////// p.reverse = false; p.index_name = "i"_n; p.index_value = "A"; p.encode_type = "hex"; p.lower_bound = {}; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 6); p.index_value = {}; p.encode_type = ""; p.lower_bound = "-10"; p.upper_bound = "100"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(7u, result.rows.size()); p.encode_type = "dec"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(7u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-100"; p.upper_bound = "100"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-100"; p.upper_bound = "100"; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes != "", true); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key_bytes; p.upper_bound = {}; p.encode_type = "bytes"; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes != "", true); chk_result(0, 3); chk_result(1, 4); // test next_key p.reverse = false; p.index_name = "i"_n; p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-100"; p.upper_bound = "100"; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(-20)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "7FFFFFEC"); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(0)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "80000000"); chk_result(0, 3); chk_result(1, 4); ////////////////////////////// // int64_t : -400, -300,...,400, 500 ////////////////////////////// p.reverse = false; p.index_name = "ii"_n; p.index_value = "100"; p.encode_type = "dec"; p.lower_bound = {}; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); chk_result(0, 6); p.index_value = {}; p.encode_type = ""; p.lower_bound = "-100"; p.upper_bound = "100"; p.limit = 10; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(3u, result.rows.size()); p.encode_type = "dec"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(3u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-1000"; p.upper_bound = "1000"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-1000"; p.upper_bound = "1000"; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes != "", true); chk_result(0, 1); chk_result(1, 2); p.encode_type = "bytes"; p.lower_bound = result.next_key_bytes; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes != "", true); chk_result(0, 3); chk_result(1, 4); // test next_key p.reverse = false; p.index_name = "ii"_n; p.encode_type = "dec"; p.index_value = {}; p.lower_bound = "-1000"; p.upper_bound = "1000"; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(-200)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "7FFFFFFFFFFFFF38"); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(0)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "8000000000000000"); chk_result(0, 3); chk_result(1, 4); ////////////////////////////// // double: 0, 1.01, 2.02,..., 9.09 ////////////////////////////// p.reverse = false; p.index_name = "ff"_n; p.index_value = {}; p.encode_type = ""; p.lower_bound = "0.0"; p.upper_bound = "100"; p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.encode_type = "dec"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0.001"; p.upper_bound = "1000.0"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); chk_result(0, 2); chk_result(1, 3); chk_result(2, 4); chk_result(3, 5); chk_result(4, 6); chk_result(5, 7); chk_result(6, 8); chk_result(7, 9); chk_result(8, 10); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0.001"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); chk_result(0, 2); chk_result(8, 10); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-0.0001"; p.upper_bound = "0.00001"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-10.0001"; p.upper_bound = "0.00001"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0.00001"; p.upper_bound = "10.00001"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); p.reverse = true; p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0.0"; p.upper_bound = "100"; p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0.001"; p.upper_bound = "1000.0"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = {}; p.upper_bound = "4.039999999"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(4u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-0.0001"; p.upper_bound = "0.00001"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-10.0001"; p.upper_bound = "0.00001"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(1u, result.rows.size()); p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0.00001"; p.upper_bound = "10.00001"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); p.reverse = false; p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "0.02"; p.upper_bound = "3.03000001"; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes != "", true); chk_result(0, 2); chk_result(1, 3); p.encode_type = "bytes"; p.lower_bound = result.next_key_bytes; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes != "", true); chk_result(0, 4); chk_result(1, 5); // test next_key p.reverse = false; p.index_name = "ff"_n; p.index_value = {}; p.encode_type = "dec"; p.lower_bound = "-0.02"; p.upper_bound = "-0.01"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(0u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key.find("2.02") != string::npos, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "C00028F5C28F5C29"); chk_result(0, 1); chk_result(1, 2); p.lower_bound = result.next_key; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key.find("4.04") != string::npos, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "C01028F5C28F5C29"); chk_result(0, 3); chk_result(1, 4); p.lower_bound = "0.02"; p.upper_bound = "3.03000001"; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key.find("3.03") != string::npos, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "C0083D70A3D70A3D"); chk_result(0, 2); chk_result(1, 3); p.lower_bound = result.next_key; p.upper_bound = {}; p.limit = 2; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(2u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key.find("5.05") != string::npos, true); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "C014333333333333"); chk_result(0, 4); chk_result(1, 5); // test no --lower, --upper, and --index with different --limit p.reverse = false; p.index_name = "foo"_n; p.encode_type = "dec"; p.index_value = {}; p.lower_bound = {}; p.upper_bound = {}; p.limit = 9; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(10)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "000000000000000A"); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); chk_result(9, 10); p.reverse = true; p.limit = 9; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, true); BOOST_REQUIRE_EQUAL(result.next_key, std::to_string(1)); BOOST_REQUIRE_EQUAL(result.next_key_bytes, "0000000000000001"); chk_result(0, 10); chk_result(1, 9); chk_result(2, 8); chk_result(3, 7); chk_result(4, 6); chk_result(5, 5); chk_result(6, 4); chk_result(7, 3); chk_result(8, 2); p.limit = 20; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(10u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); chk_result(0, 10); chk_result(1, 9); chk_result(2, 8); chk_result(3, 7); chk_result(4, 6); chk_result(5, 5); chk_result(6, 4); chk_result(7, 3); chk_result(8, 2); chk_result(9, 1); // test default lower bound p.reverse = false; p.lower_bound = {}; p.upper_bound = "9"; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); chk_result(0, 1); chk_result(1, 2); chk_result(2, 3); chk_result(3, 4); chk_result(4, 5); chk_result(5, 6); chk_result(6, 7); chk_result(7, 8); chk_result(8, 9); // test default upper bound p.reverse = true; p.lower_bound = "2"; p.upper_bound = {}; result = plugin.read_only::get_kv_table_rows(p); BOOST_REQUIRE_EQUAL(9u, result.rows.size()); BOOST_REQUIRE_EQUAL(result.more, false); BOOST_REQUIRE_EQUAL(result.next_key, ""); BOOST_REQUIRE_EQUAL(result.next_key_bytes, ""); chk_result(0, 10); chk_result(1, 9); chk_result(2, 8); chk_result(3, 7); chk_result(4, 6); chk_result(5, 5); chk_result(6, 4); chk_result(7, 3); chk_result(8, 2); } FC_LOG_AND_RETHROW() BOOST_AUTO_TEST_SUITE_END()
29.568405
113
0.657839
forfreeday
a090aa811b06cf2c0bb33ae37df066622432cd64
4,016
cpp
C++
tests/src/deviceLib/hip_threadfence_system.cpp
JosephGeoBenjamin/HIP-forOpenCV
c48a8df33d59d84ef2180fb17a539b404f04429f
[ "MIT" ]
2
2019-09-10T15:50:53.000Z
2019-09-11T01:14:49.000Z
tests/src/deviceLib/hip_threadfence_system.cpp
JosephGeoBenjamin/HIP-forOpenCV
c48a8df33d59d84ef2180fb17a539b404f04429f
[ "MIT" ]
null
null
null
tests/src/deviceLib/hip_threadfence_system.cpp
JosephGeoBenjamin/HIP-forOpenCV
c48a8df33d59d84ef2180fb17a539b404f04429f
[ "MIT" ]
1
2019-07-04T00:48:48.000Z
2019-07-04T00:48:48.000Z
/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. 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. */ /* HIT_START * BUILD: %t %s ../test_common.cpp NVCC_OPTIONS -std=c++11 * RUN: %t * HIT_END */ #include <vector> #include <atomic> #include <thread> #include <cassert> #include <cstdio> #include "hip/hip_runtime.h" #include "hip/device_functions.h" #include "test_common.h" #define HIP_ASSERT(x) (assert((x) == hipSuccess)) __host__ __device__ void fence_system() { #ifdef __HIP_DEVICE_COMPILE__ __threadfence_system(); #else std::atomic_thread_fence(std::memory_order_seq_cst); #endif } __host__ __device__ void round_robin(const int id, const int num_dev, const int num_iter, volatile int* data, volatile int* flag) { for (int i = 0; i < num_iter; i++) { while (*flag % num_dev != id) fence_system(); // invalid the cache for read (*data)++; fence_system(); // make sure the store to data is sequenced before the store to flag (*flag)++; fence_system(); // invalid the cache to flush out flag } } __global__ void gpu_round_robin(const int id, const int num_dev, const int num_iter, volatile int* data, volatile int* flag) { round_robin(id, num_dev, num_iter, data, flag); } int main() { int num_gpus = 0; HIP_ASSERT(hipGetDeviceCount(&num_gpus)); if (num_gpus == 0) { passed(); return 0; } volatile int* data; HIP_ASSERT(hipHostMalloc(&data, sizeof(int), hipHostMallocCoherent)); constexpr int init_data = 1000; *data = init_data; volatile int* flag; HIP_ASSERT(hipHostMalloc(&flag, sizeof(int), hipHostMallocCoherent)); *flag = 0; // number of rounds per device constexpr int num_iter = 1000; // one CPU thread + 1 kernel/GPU const int num_dev = num_gpus + 1; int next_id = 0; std::vector<std::thread> threads; // create a CPU thread for the round_robin threads.push_back(std::thread(round_robin, next_id++, num_dev, num_iter, data, flag)); // run one thread per GPU dim3 dim_block(1, 1, 1); dim3 dim_grid(1, 1, 1); // launch one kernel per device for the round robin for (; next_id < num_dev; ++next_id) { threads.push_back(std::thread([=]() { HIP_ASSERT(hipSetDevice(next_id - 1)); hipLaunchKernelGGL(gpu_round_robin, dim_grid, dim_block, 0, 0x0, next_id, num_dev, num_iter, data, flag); HIP_ASSERT(hipDeviceSynchronize()); })); } for (auto& t : threads) { t.join(); } int expected_data = init_data + num_dev * num_iter; int expected_flag = num_dev * num_iter; bool passed = *data == expected_data && *flag == expected_flag; HIP_ASSERT(hipHostFree((void*)data)); HIP_ASSERT(hipHostFree((void*)flag)); if (passed) { passed(); } else { failed("Failed Verification!\n"); } return 0; }
31.375
94
0.669323
JosephGeoBenjamin
a0910c0f585c1ea6bf139e7e0484462e4f2e68e2
534
hpp
C++
graphics_app/include/Graphics/InputEvents/MouseMoveEvent.hpp
timow-gh/FilApp
02ec78bf617fb78d872b2adceeb8a8351aa8f408
[ "Apache-2.0" ]
null
null
null
graphics_app/include/Graphics/InputEvents/MouseMoveEvent.hpp
timow-gh/FilApp
02ec78bf617fb78d872b2adceeb8a8351aa8f408
[ "Apache-2.0" ]
null
null
null
graphics_app/include/Graphics/InputEvents/MouseMoveEvent.hpp
timow-gh/FilApp
02ec78bf617fb78d872b2adceeb8a8351aa8f408
[ "Apache-2.0" ]
null
null
null
#ifndef GRAPHICS_MOUSEMOVEEVENT_HPP #define GRAPHICS_MOUSEMOVEEVENT_HPP #include <cmath> namespace Graphics { struct MouseMoveEvent { std::uint32_t timestamp; // in milliseconds std::uint32_t windowId; std::uint32_t x; std::uint32_t y; double_t deltaT; MouseMoveEvent(uint32_t timestamp, uint32_t windowId, uint32_t x, uint32_t y, double_t deltaT) : timestamp(timestamp), windowId(windowId), x(x), y(y), deltaT(deltaT) { } }; } // namespace Graphics #endif // GRAPHICS_MOUSEMOVEEVENT_HPP
20.538462
98
0.719101
timow-gh
90b4272536e9ccf3c123c3ea8462926c22f31e82
797
cpp
C++
53.cpp
DouglasSherk/project-euler
f3b188b199ff31671c6d7683b15675be7484c5b8
[ "MIT" ]
null
null
null
53.cpp
DouglasSherk/project-euler
f3b188b199ff31671c6d7683b15675be7484c5b8
[ "MIT" ]
null
null
null
53.cpp
DouglasSherk/project-euler
f3b188b199ff31671c6d7683b15675be7484c5b8
[ "MIT" ]
null
null
null
#include <iostream> #include <set> #include <vector> #include "headers/euler.hpp" const int MIN_N = 1; const int MAX_N = 100; const int MAX_VALUE = 1000000; int main(int argc, char** argv) { int numAboveMax = 0; for (int n = MIN_N; n <= MAX_N; n++) { for (int r = 1; r <= n / 2; r++) { if (euler::choose(n, r) > MAX_VALUE) { std::cout << n << " choose " << r << " is above " << MAX_VALUE << std::endl; numAboveMax += n - r - r + 1; break; } } } std::cout << "23 choose 10: " << euler::choose(23, 10) << std::endl; std::cout << "Total terms in n {" << MIN_N << ".." << MAX_N << "} above " << MAX_VALUE << ", " << "r <= n, " << "for n choose r: " << numAboveMax << std::endl; return 0; }
23.441176
96
0.483061
DouglasSherk
90c107c048ee2e7cdfce59ea890da3f0030241ec
733
hpp
C++
include/anisthesia/media.hpp
swiftcitrus/anisthesia
981c821d51b1115311eee9fba01dc93210dd757b
[ "MIT" ]
33
2017-02-07T00:03:31.000Z
2022-02-09T12:06:52.000Z
include/anisthesia/media.hpp
swiftcitrus/anisthesia
981c821d51b1115311eee9fba01dc93210dd757b
[ "MIT" ]
7
2017-07-26T22:40:22.000Z
2022-01-30T08:05:51.000Z
include/anisthesia/media.hpp
swiftcitrus/anisthesia
981c821d51b1115311eee9fba01dc93210dd757b
[ "MIT" ]
9
2017-08-05T10:33:05.000Z
2021-10-03T00:23:21.000Z
#pragma once #include <chrono> #include <functional> #include <string> #include <vector> namespace anisthesia { using media_time_t = std::chrono::milliseconds; enum class MediaInfoType { Unknown, File, Tab, Title, Url, }; enum class MediaState { Unknown, Playing, Paused, Stopped, }; struct MediaInfo { MediaInfoType type = MediaInfoType::Unknown; std::string value; }; struct Media { MediaState state = MediaState::Unknown; // currently unused media_time_t duration; // currently unused media_time_t position; // currently unused std::vector<MediaInfo> information; }; using media_proc_t = std::function<bool(const MediaInfo&)>; } // namespace anisthesia
17.452381
62
0.683492
swiftcitrus
90c3c946ac93b3010bb64efc5456a848f4525c6e
3,826
cpp
C++
src/gazebo_tvc_controller_plugin.cpp
helkebir/LEAPFROG-Simulation
51f64143b8bd6e46b9db4ad42c1e3b42c4e22470
[ "BSD-3-Clause" ]
1
2021-05-23T02:52:14.000Z
2021-05-23T02:52:14.000Z
src/gazebo_tvc_controller_plugin.cpp
helkebir/LEAPFROG-Simulation
51f64143b8bd6e46b9db4ad42c1e3b42c4e22470
[ "BSD-3-Clause" ]
1
2021-06-15T18:52:15.000Z
2021-06-15T18:52:15.000Z
src/gazebo_tvc_controller_plugin.cpp
helkebir/LEAPFROG-Simulation
51f64143b8bd6e46b9db4ad42c1e3b42c4e22470
[ "BSD-3-Clause" ]
1
2021-06-15T03:25:12.000Z
2021-06-15T03:25:12.000Z
/* * Copyright (C) 2012-2015 Open Source Robotics 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 <gazebo_tvc_controller_plugin.h> using namespace gazebo; using namespace std; GZ_REGISTER_MODEL_PLUGIN(TVCControllerPlugin) TVCControllerPlugin::TVCControllerPlugin() {} void TVCControllerPlugin::Load(physics::ModelPtr _model, sdf::ElementPtr _sdf) { model_ = _model; sdf_ = _sdf; world_ = model_->GetWorld(); // default params namespace_.clear(); if (_sdf->HasElement("robotNamespace")) { namespace_ = _sdf->GetElement("robotNamespace")->Get<std::string>(); } else { gzerr << "[gazebo_tvc_controller] Please specify a robotNamespace.\n"; } node_handle_ = transport::NodePtr(new transport::Node()); node_handle_->Init(namespace_); // TVC pub/sub topics tvc_status_pub_topic_ = "~/" + model_->GetName() + "/tvc_status"; tvc_target_sub_topic_ = "~/" + model_->GetName() + "/tvc_target"; // TVC pub/sub tvc_status_pub_ = node_handle_->Advertise<sensor_msgs::msgs::TVCStatus>( tvc_status_pub_topic_, 10); tvc_target_sub_ = node_handle_->Subscribe<sensor_msgs::msgs::TVCTarget>( tvc_target_sub_topic_, &TVCControllerPlugin::TVCTargetCallback, this); // Get linear actuator joints (from lander.sdf) actuator_1_joint_name = "actuator_1_outer__actuator_1_inner__prismatic"; actuator_2_joint_name = "actuator_2_outer__actuator_2_inner__prismatic"; actuator_1_joint = model_->GetJoint(actuator_1_joint_name); actuator_2_joint = model_->GetJoint(actuator_2_joint_name); } void TVCControllerPlugin::Init() { // plugin update connections.push_back(event::Events::ConnectWorldUpdateBegin( boost::bind(&TVCControllerPlugin::OnUpdate, this))); std::cout << "TVCControllerPlugin::Init" << std::endl; } void TVCControllerPlugin::OnUpdate() { handle_control(); sendTVCStatus(); } void TVCControllerPlugin::handle_control() { // Get current linear actuator joint positions _actuator_current_1 = actuator_1_joint->Position(0); _actuator_current_2 = actuator_2_joint->Position(0); // Get actual forces for linear actuators _actuator_status_1 = -1; _actuator_status_2 = -1; // Save velocity of linear actuators _actuator_velocity_1 = actuator_1_joint->GetVelocity(0); _actuator_velocity_2 = actuator_2_joint->GetVelocity(0); // Apply forces to linear actuators actuator_1_joint->SetForce(0, _actuator_status_1); actuator_2_joint->SetForce(0, _actuator_status_2); } void TVCControllerPlugin::sendTVCStatus() { sensor_msgs::msgs::TVCStatus tvc_status_msg; tvc_status_msg.set_actuator_status_1(_actuator_status_1); tvc_status_msg.set_actuator_target_1(_actuator_target_1); tvc_status_msg.set_actuator_current_1(_actuator_current_1); tvc_status_msg.set_actuator_velocity_1(_actuator_velocity_1); tvc_status_msg.set_actuator_status_2(_actuator_status_2); tvc_status_msg.set_actuator_target_2(_actuator_target_2); tvc_status_msg.set_actuator_current_2(_actuator_current_2); tvc_status_msg.set_actuator_velocity_2(_actuator_velocity_2); tvc_status_pub_->Publish(tvc_status_msg); } void TVCControllerPlugin::TVCTargetCallback(TVCTargetPtr &msg) { _actuator_target_1 = msg->actuator_1_target(); _actuator_target_2 = msg->actuator_2_target(); }
34.160714
75
0.763722
helkebir
90c3fdde22b9dd8b82dbf387daee4d2d0605c073
1,063
cpp
C++
test/doc_snippets/generator_impl.cpp
421408/tudocomp
9634742393995acdde148b0412f083bfdd0fbe9f
[ "ECL-2.0", "Apache-2.0" ]
1
2020-09-22T11:29:02.000Z
2020-09-22T11:29:02.000Z
test/doc_snippets/generator_impl.cpp
421408/tudocomp
9634742393995acdde148b0412f083bfdd0fbe9f
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
test/doc_snippets/generator_impl.cpp
421408/tudocomp
9634742393995acdde148b0412f083bfdd0fbe9f
[ "ECL-2.0", "Apache-2.0" ]
1
2020-09-29T08:57:13.000Z
2020-09-29T08:57:13.000Z
/** * * This file contains code snippets from the documentation as a reference. * * Please do not change this file unless you change the corresponding snippets * in the documentation as well! * **/ #include <glog/logging.h> #include <gtest/gtest.h> #include <tudocomp/Generator.hpp> using namespace tdc; class MyGenerator : public Generator { public: inline static Meta meta() { Meta m(Generator::type_desc(), "my_generator", "An example generator"); m.param("length").primitive(); m.param("char").primitive('a'); return m; } inline static std::string generate(size_t length, char c) { return std::string(length, c); } using Generator::Generator; inline virtual std::string generate() override { return generate( config().param("length").as_uint(), config().param("char").as_int()); } }; TEST(doc_generator_impl, test) { auto generator = Algorithm::instance<MyGenerator>("length=7, char=64"); ASSERT_EQ("@@@@@@@", generator->generate()); }
24.159091
79
0.64064
421408
90c960f5cbd3f304875008e54a910ee3694808a3
4,061
cpp
C++
src/entities/Alien.cpp
Nyarlana/Tactical-RPG
9b55e35cce5dbeba481d3db7113c15e572b320e1
[ "MIT" ]
null
null
null
src/entities/Alien.cpp
Nyarlana/Tactical-RPG
9b55e35cce5dbeba481d3db7113c15e572b320e1
[ "MIT" ]
null
null
null
src/entities/Alien.cpp
Nyarlana/Tactical-RPG
9b55e35cce5dbeba481d3db7113c15e572b320e1
[ "MIT" ]
null
null
null
#include "entities.h" #include <SFML/Graphics.hpp> #include <memory> #include <vector> #include <iostream> using namespace std; Alien::Alien(int max_LP, int xPos, int yPos, int speed, int group_number, int targetCheckArea, int threatfulTargetCheckArea) : Fighter(max_LP, xPos, yPos, speed, targetCheckArea, threatfulTargetCheckArea), group_number(group_number), hasAggressiveBehavior(threatfulTargetCheckArea!=-1) { } //inherited functions void Alien::on_Notify(Component* subject, Event event) { } void Alien::_init() { Entity::state = SEARCH; if(!texture.loadFromFile("data/entities/alien.png")) { if(!texture.loadFromFile("../data/entities/alien.png")) { std::cout << "erreur" << '\n'; } } sprite.setTexture(texture); sprite.setTextureRect(sf::IntRect(0,0,32,32)); } int Alien::stateValue() { int value; switch (Entity::state) { case SEARCH: value = 0; break; case OFFENSIVE: value = 1; break; default: value = -1; } return value; } std::string Alien::getStateS() { std::string the_string; switch (state) { case SEARCH: the_string = "SEARCH"; break; case OFFENSIVE: the_string = "OFFENSIVE"; break; default: the_string = "ERROR"; } the_string += " : " + std::to_string(targets.size()); return the_string; } void Alien::check() { checkTargets(); if(targets.empty()) state = SEARCH; else state = OFFENSIVE; } void Alien::action() { switch(state) { case SEARCH: { if(path.empty()) notify(this, E_GET_RANDOM_PATH); move(); break; } case OFFENSIVE: { shared_ptr<Alien> t = dynamic_pointer_cast<Alien>(getTopTarget()); if(t != nullptr) std::cout << "coucou je cible un alien" << '\n'; else std::cout << "coucou je cible PAS un alien" << '\n'; std::cout << "ma cible est déclarée" << '\n'; offensive_action(); break; } default: { Entity::state = SEARCH; } } } void Alien::die() { std::cout << "An alien just died at (" << Entity::pos.x << "," << Entity::pos.y << ")" << '\n'; } void Alien::answer_radar(std::shared_ptr<Entity> e) { if(!isDead()) { shared_ptr<Entity> me = std::dynamic_pointer_cast<Entity>(Observer::shared_from_this()); e->add(false,me); } } void Alien::increaseThreat(shared_ptr<Entity> target, int threatIncrease) { if(isTargetable(target)) { super::increaseThreat(target, threatIncrease); if(targets.empty()) Entity::state = SEARCH; else Entity::state = OFFENSIVE; } } void Alien::attack(shared_ptr<Entity> target) { if(isTargetable(target)) { target->takeDamage(2); if (target->isDead()) path.clear(); } } void Alien::checkTargets() { Fighter::checkTargets(); if(hasAggressiveBehavior) { notify(this, E_LF_ROV); for(int i=0; i<rov.size(); i++) { if(getDistanceTo(rov[i])<=targetCheckArea) { increaseThreat(rov[i], 2); } } rov.clear(); notify(this, E_LF_AL); for(int i=0; i<al.size(); i++) { if(getDistanceTo(al[i])<=targetCheckArea) { if(isTargetable(al[i])) increaseThreat(al[i], 1); } } al.clear(); } } bool Alien::isTargetable(shared_ptr<Entity> target) { shared_ptr<Alien> t = dynamic_pointer_cast<Alien>(target); if(t!=nullptr && (id==t->getID() || t->getGroup()==group_number)) return false; return true; } int Alien::getGroup() { return group_number; } std::string Alien::tostring() { return "alien"; }
20.004926
285
0.539276
Nyarlana
90c9af5478fa0de2005b9fd8e3485d687465eebd
3,017
hpp
C++
include/MEL/Math/Filter.hpp
mahilab/MEL
b877b2ed9cd265b1ee3c1cc623a339ec1dc73185
[ "Zlib" ]
6
2018-09-14T05:07:03.000Z
2021-09-30T17:15:11.000Z
include/MEL/Math/Filter.hpp
mahilab/MEL
b877b2ed9cd265b1ee3c1cc623a339ec1dc73185
[ "Zlib" ]
null
null
null
include/MEL/Math/Filter.hpp
mahilab/MEL
b877b2ed9cd265b1ee3c1cc623a339ec1dc73185
[ "Zlib" ]
3
2018-09-20T00:58:31.000Z
2022-02-09T06:02:56.000Z
// MIT License // // MEL - Mechatronics Engine & Library // Copyright (c) 2019 Mechatronics and Haptic Interfaces Lab - Rice University // // 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. // // Author(s): Craig McDonald ([email protected]) #pragma once #include <MEL/Math/Process.hpp> #include <vector> namespace mel { //============================================================================== // CLASS DECLARATION //============================================================================== class Filter : public Process { public: /// Construct Filter from transfer function coefficients Filter(const std::vector<double>& b, const std::vector<double>& a, uint32 seeding = 0); /// Applies the filter operation for one time step double update(const double x, const Time& current_time = Time::Zero) override; /// Returns the filtered value since the last update double get_value() const; /// Sets the internal states s_ to all be zero void reset() override; /// Returns the Filter numerator coefficients const std::vector<double>& get_b() const; /// Returns the Filter denominator coefficients const std::vector<double>& get_a() const; /// Set the Filter seeding void set_seeding(uint32 seeding); /// Sets the Filter coefficients void set_coefficients(const std::vector<double>& b, const std::vector<double>& a); protected: /// Construct empty Filter of order n Filter(std::size_t n, uint32 seeding); private: /// Direct form II transposed filter implementation double dir_form_ii_t(const double x); /// Calls the Filter multiple times on the initial value to avoid startup /// transients void seed(const double x, const uint32 iterations); private: double value_; ///< the filtered value std::size_t n_; ///< filter order std::vector<double> b_; ///< numerator coefficients std::vector<double> a_; ///< denominator coefficients std::vector<double> s_; ///< internal memory bool has_seeding_; ///< indicates whether or not to call seed on first update bool first_update_; ///< indicates first update upon reset bool will_filter_; ///< will the coefficients actually filter (i.e a and b are not both {1,0})? uint32 seed_count_; ///< number of iterations to call on update upon seeding }; } // namespace mel
35.916667
105
0.649321
mahilab
90cd0bfec0988fa652ac00f573ce55d68f758b16
1,396
cc
C++
src/gfx.cc
JesseMaurais/SDL2_lua
cb8dba41c4030267dd88f4d376123d2a71d5735f
[ "Zlib" ]
null
null
null
src/gfx.cc
JesseMaurais/SDL2_lua
cb8dba41c4030267dd88f4d376123d2a71d5735f
[ "Zlib" ]
null
null
null
src/gfx.cc
JesseMaurais/SDL2_lua
cb8dba41c4030267dd88f4d376123d2a71d5735f
[ "Zlib" ]
null
null
null
#include <lux/lux.hpp> #include <SDL2/SDL.h> #include <SDL2/SDL2_gfxPrimitives.h> #include "Common.h" extern "C" int luaopen_SDL2_gfx(lua_State *state) { if (!luaL_getmetatable(state, SDL_METATABLE)) { return luaL_error(state, SDL_REQUIRED); } luaL_Reg regs [] = { {"Pixel", lux_cast(pixelRGBA)}, {"HLine", lux_cast(hlineRGBA)}, {"VLine", lux_cast(vlineRGBA)}, {"Rectangle", lux_cast(rectangleRGBA)}, {"RoundedRectangle", lux_cast(roundedRectangleRGBA)}, {"Box", lux_cast(boxRGBA)}, {"RoundedBox", lux_cast(roundedBoxRGBA)}, {"Line", lux_cast(lineRGBA)}, {"AALine", lux_cast(aalineRGBA)}, {"ThickLine", lux_cast(thickLineRGBA)}, {"Circle", lux_cast(circleRGBA)}, {"Arc", lux_cast(arcRGBA)}, {"AACircle", lux_cast(aacircleRGBA)}, {"FilledCircle", lux_cast(filledCircleRGBA)}, {"Ellipse", lux_cast(ellipseRGBA)}, {"AAEllipse", lux_cast(aaellipseRGBA)}, {"FilledEllipse", lux_cast(filledEllipseRGBA)}, {"Pie", lux_cast(pieRGBA)}, {"FilledPie", lux_cast(filledPieRGBA)}, {"Trigon", lux_cast(trigonRGBA)}, {"AATrigon", lux_cast(aatrigonRGBA)}, {"FilledTrigon", lux_cast(filledTrigonRGBA)}, {"Polygon", lux_cast(polygonRGBA)}, {"AAPolygon", lux_cast(aapolygonRGBA)}, {"FilledPolygon", lux_cast(filledPolygonRGBA)}, {"TexturedPolygon", lux_cast(texturedPolygon)}, {"Bezier", lux_cast(bezierRGBA)}, {nullptr, nullptr} }; luaL_setfuncs(state, regs, 0); return 1; }
29.702128
54
0.714183
JesseMaurais
90ce6c2d79ea7eaf5e85de11ba343ca76d493be0
974
cpp
C++
codeforces/B - Polycarp Training/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/B - Polycarp Training/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/B - Polycarp Training/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: * kzvd4729 created: May/14/2019 20:45 * solution_verdict: Accepted language: GNU C++14 * run_time: 155 ms memory_used: 10400 KB * problem: https://codeforces.com/contest/1165/problem/B ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6; int aa[N+2]; int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n;cin>>n;multiset<int>st; for(int i=1;i<=n;i++) { int x;cin>>x;st.insert(x); } int ans=1; while(st.size()) { int x=*st.begin(); if(x>=ans) ans++; st.erase(st.find(x)); } cout<<ans-1<<endl; return 0; }
32.466667
111
0.38501
kzvd4729
90d2faa0bb2d7e3ff2ed3d9a521a04e8f571950d
2,793
hpp
C++
src/reir/exec/compiler.hpp
large-scale-oltp-team/reir
427db5f24e15f22cd2a4f4a716caf9392dae1d9b
[ "Apache-2.0" ]
1
2020-03-04T10:57:14.000Z
2020-03-04T10:57:14.000Z
src/reir/exec/compiler.hpp
large-scale-oltp-team/reir
427db5f24e15f22cd2a4f4a716caf9392dae1d9b
[ "Apache-2.0" ]
3
2018-11-02T07:47:26.000Z
2018-11-05T09:06:54.000Z
src/reir/exec/compiler.hpp
large-scale-oltp-team/reir
427db5f24e15f22cd2a4f4a716caf9392dae1d9b
[ "Apache-2.0" ]
null
null
null
#ifndef REIR_COMPILER_HPP_ #define REIR_COMPILER_HPP_ #include <cassert> #include <unordered_map> #include <iostream> #include <llvm/ADT/STLExtras.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/JITSymbol.h> #include <llvm/ExecutionEngine/RTDyldMemoryManager.h> #include <llvm/ExecutionEngine/RuntimeDyld.h> #include <llvm/ExecutionEngine/SectionMemoryManager.h> #include <llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h> #include <llvm/ExecutionEngine/Orc/CompileUtils.h> #include <llvm/ExecutionEngine/Orc/IRCompileLayer.h> #include <llvm/ExecutionEngine/Orc/IRTransformLayer.h> #include <llvm/ExecutionEngine/Orc/LambdaResolver.h> #include <llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h> #include <llvm/IR/DataLayout.h> #include <llvm/IR/LegacyPassManager.h> #include <llvm/IR/Mangler.h> #include <llvm/Support/DynamicLibrary.h> #include <llvm/Support/raw_ostream.h> #include <llvm/Target/TargetMachine.h> #include <llvm/Transforms/Scalar.h> #include <llvm/Transforms/Scalar/GVN.h> #include <llvm/IR/IRBuilder.h> #include "tuple.hpp" #include "ast_node.hpp" namespace llvm { class TargetMachine; class Function; class Module; } // namespace llvm namespace reir { namespace node { class Node; } class MetaData; class DBInterface; class CompilerContext; class Compiler { void init_functions(CompilerContext& ctx); using OptimizeFunction = std::function<std::shared_ptr<llvm::Module>(std::shared_ptr<llvm::Module>)>; std::unique_ptr<llvm::TargetMachine> target_machine_; llvm::DataLayout data_layout_; llvm::orc::RTDyldObjectLinkingLayer obj_layer_; std::unique_ptr<llvm::orc::JITCompileCallbackManager> CompileCallbackManager; llvm::orc::IRCompileLayer<decltype(obj_layer_), llvm::orc::SimpleCompiler> compile_layer_; llvm::orc::IRTransformLayer<decltype(compile_layer_), OptimizeFunction> optimize_layer_; llvm::orc::CompileOnDemandLayer<decltype(optimize_layer_)> CODLayer; public: using ModuleHandle = decltype(CODLayer)::ModuleHandleT; public: Compiler(); typedef bool(*exec_func)(node::Node*); void compile_and_exec(DBInterface& dbi, MetaData& md, node::Node* ast); void compile_and_exec(CompilerContext& ctx, DBInterface& dbi, MetaData& md, node::Node* ast); llvm::TargetMachine* get_target_machine() { return target_machine_.get(); } ModuleHandle add_module(std::unique_ptr<llvm::Module> m); llvm::JITSymbol find_symbol(const std::string& name); ~Compiler() = default; private: void compile(CompilerContext& ctx, DBInterface& dbi, MetaData& md, node::Node* ast); std::shared_ptr<llvm::Module> optimize_module(std::shared_ptr<llvm::Module> M); public: // it should be private and friend classess // llvm members }; } // namespace reir #endif // REIR_COMPILER_HPP_
30.358696
95
0.775152
large-scale-oltp-team
90d3e1f4e601605322446d84dd7cec2e743544d2
4,706
cpp
C++
src/ch8/frame_buffer.test.cpp
notskm/chip8
9e70088acd079fc6f2ed2545fb13ee6160dd12aa
[ "MIT" ]
null
null
null
src/ch8/frame_buffer.test.cpp
notskm/chip8
9e70088acd079fc6f2ed2545fb13ee6160dd12aa
[ "MIT" ]
null
null
null
src/ch8/frame_buffer.test.cpp
notskm/chip8
9e70088acd079fc6f2ed2545fb13ee6160dd12aa
[ "MIT" ]
null
null
null
#include "ch8/frame_buffer.hpp" #include <array> #include <catch2/catch.hpp> #include <type_traits> #include <utility> TEST_CASE("frame_buffer constructor initializes each pixel to 0, 0, 0, 0") { const auto buffer = ch8::frame_buffer<64, 32>{}; REQUIRE(buffer.data() == std::array<std::uint8_t, 64 * 32 * 4>{}); } TEST_CASE("frame_buffer<64, 32>::width returns 64") { const auto buffer = ch8::frame_buffer<64, 32>{}; REQUIRE(buffer.width() == 64); } TEST_CASE("frame_buffer<83, 21>::width returns 83") { const auto buffer = ch8::frame_buffer<83, 21>{}; REQUIRE(buffer.width() == 83); } TEST_CASE("frame_buffer<64, 32>::height returns 32") { const auto buffer = ch8::frame_buffer<64, 32>{}; REQUIRE(buffer.height() == 32); } TEST_CASE("frame_buffer<83, 21>::height returns 21") { const auto buffer = ch8::frame_buffer<83, 21>{}; REQUIRE(buffer.height() == 21); } TEST_CASE( "Modifying the array returned by frame_buffer::data modifies the framebuffer") { auto buffer = ch8::frame_buffer<2, 4>{}; buffer.data().front() = 58; REQUIRE(buffer.data().front() == 58); } TEST_CASE("frame_buffer::data returns a const ref when frame_buffer is const") { using buffer = ch8::frame_buffer<8, 4>; using result = decltype(std::declval<const buffer>().data()); using const_data_ref = const std::array<std::uint8_t, 8 * 4 * 4>&; STATIC_REQUIRE(std::is_same_v<result, const_data_ref>); } TEST_CASE("frame_buffer::pixel returns the color of the pixel at (10, 30)") { constexpr auto x = std::size_t{10}; constexpr auto y = std::size_t{29}; constexpr auto color = ch8::color{26, 105, 46, 234}; auto buffer = ch8::frame_buffer<28, 30>{}; auto& data = buffer.data(); data.at(y * buffer.width() * 4 + x * 4 + 0) = color.r; data.at(y * buffer.width() * 4 + x * 4 + 1) = color.g; data.at(y * buffer.width() * 4 + x * 4 + 2) = color.b; data.at(y * buffer.width() * 4 + x * 4 + 3) = color.a; REQUIRE(buffer.pixel(x, y) == color); } TEST_CASE("frame_buffer::pixel returns the color of the pixel at (50, 20)") { constexpr auto x = std::size_t{50}; constexpr auto y = std::size_t{20}; constexpr auto color = ch8::color{12, 84, 27, 85}; auto buffer = ch8::frame_buffer<70, 35>{}; auto& data = buffer.data(); data.at(y * buffer.width() * 4 + x * 4 + 0) = color.r; data.at(y * buffer.width() * 4 + x * 4 + 1) = color.g; data.at(y * buffer.width() * 4 + x * 4 + 2) = color.b; data.at(y * buffer.width() * 4 + x * 4 + 3) = color.a; REQUIRE(buffer.pixel(x, y) == color); } TEST_CASE("frame_buffer::pixel sets the color of the pixel at (39, 13)") { constexpr auto x = std::size_t{50}; constexpr auto y = std::size_t{20}; constexpr auto color = ch8::color{63, 26, 19, 157}; auto buffer = ch8::frame_buffer<83, 27>{}; buffer.pixel(x, y, color); REQUIRE(buffer.pixel(x, y) == color); } TEST_CASE("frame_buffer::pixel sets the color of the pixel at (3, 67)") { constexpr auto x = std::size_t{3}; constexpr auto y = std::size_t{67}; constexpr auto color = ch8::color{83, 27, 55, 29}; auto buffer = ch8::frame_buffer<38, 74>{}; buffer.pixel(x, y, color); REQUIRE(buffer.pixel(x, y) == color); } TEST_CASE( "frame_buffer::clear sets each pixel to transparent when no color is provided") { auto buffer = ch8::frame_buffer<83, 21>{}; buffer.data().fill(std::uint8_t{83}); buffer.clear(); for (auto x = std::size_t{0}; x < buffer.width(); ++x) { for (auto y = std::size_t{0}; y < buffer.height(); ++y) { REQUIRE(buffer.pixel(x, y) == ch8::color{0, 0, 0, 0}); } } } TEST_CASE("frame_buffer::clear sets each pixel to the color provided") { constexpr auto color = ch8::color{73, 28, 95, 23}; auto buffer = ch8::frame_buffer<83, 21>{}; buffer.data().fill(std::uint8_t{83}); buffer.clear(color); for (auto x = std::size_t{0}; x < buffer.width(); ++x) { for (auto y = std::size_t{0}; y < buffer.height(); ++y) { REQUIRE(buffer.pixel(x, y) == color); } } } TEST_CASE("color{103, 39, 38, 255} == color{103, 39, 38, 255}") { REQUIRE(ch8::color{103, 39, 38, 255} == ch8::color{103, 39, 38, 255}); } TEST_CASE("color{83, 67, 201, 143} == color{83, 67, 201, 143}") { REQUIRE(ch8::color{83, 67, 201, 143} == ch8::color{83, 67, 201, 143}); } TEST_CASE("color{103, 39, 38, 255} != color{38, 165, 44, 221}") { REQUIRE(ch8::color{103, 39, 38, 255} != ch8::color{38, 165, 44, 221}); } TEST_CASE("color{83, 67, 201, 143} != color{84, 32, 65, 93}") { REQUIRE(ch8::color{83, 67, 201, 143} != ch8::color{84, 32, 65, 93}); }
29.4125
83
0.60476
notskm
90d3eff83f7fdf30e395fa8d07742a090409c167
9,346
cpp
C++
Siv3D/src/Siv3D/Monitor/SivMonitor.cpp
Fuyutsubaki/OpenSiv3D
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
[ "MIT" ]
null
null
null
Siv3D/src/Siv3D/Monitor/SivMonitor.cpp
Fuyutsubaki/OpenSiv3D
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
[ "MIT" ]
null
null
null
Siv3D/src/Siv3D/Monitor/SivMonitor.cpp
Fuyutsubaki/OpenSiv3D
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
[ "MIT" ]
null
null
null
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2018 Ryo Suzuki // Copyright (c) 2016-2018 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/Monitor.hpp> # if defined(SIV3D_TARGET_WINDOWS) # include <Siv3D/Windows.hpp> # include "../Siv3DEngine.hpp" # include "../Window/IWindow.hpp" namespace s3d { namespace detail { // チェック用デバイス名とモニタハンドル using MonitorCheck = std::pair<const String, HMONITOR>; static BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC, LPRECT, LPARAM userData) { MONITORINFOEX monitorInfo; monitorInfo.cbSize = sizeof(monitorInfo); ::GetMonitorInfoW(hMonitor, &monitorInfo); Monitor* monitor = (Monitor*)userData; if (monitor->displayDeviceName.toWstr() == monitorInfo.szDevice) { monitor->displayRect.x = monitorInfo.rcMonitor.left; monitor->displayRect.y = monitorInfo.rcMonitor.top; monitor->displayRect.w = monitorInfo.rcMonitor.right - monitorInfo.rcMonitor.left; monitor->displayRect.h = monitorInfo.rcMonitor.bottom - monitorInfo.rcMonitor.top; monitor->workArea.x = monitorInfo.rcWork.left; monitor->workArea.y = monitorInfo.rcWork.top; monitor->workArea.w = monitorInfo.rcWork.right - monitorInfo.rcWork.left; monitor->workArea.h = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top; return false; } return true; } static BOOL CALLBACK MonitorCheckProc(HMONITOR hMonitor, HDC, LPRECT, LPARAM userData) { MONITORINFOEX monitorInfo; monitorInfo.cbSize = sizeof(monitorInfo); ::GetMonitorInfoW(hMonitor, &monitorInfo); MonitorCheck* monitor = (MonitorCheck*)userData; if (monitor->first.toWstr() == monitorInfo.szDevice) { monitor->second = hMonitor; return false; } return true; } } namespace System { Array<Monitor> EnumerateActiveMonitors() { Array<Monitor> monitors; DISPLAY_DEVICE displayDevice; displayDevice.cb = sizeof(displayDevice); // デスクトップとして割り当てられている仮想ディスプレイを検索 for (int32 deviceIndex = 0; ::EnumDisplayDevicesW(0, deviceIndex, &displayDevice, 0); ++deviceIndex) { if (displayDevice.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) { DISPLAY_DEVICE monitor; ZeroMemory(&monitor, sizeof(monitor)); monitor.cb = sizeof(monitor); // デスクトップとして使われているモニターの一覧を取得 for (int32 monitorIndex = 0; ::EnumDisplayDevicesW(displayDevice.DeviceName, monitorIndex, &monitor, 0); ++monitorIndex) { if ((monitor.StateFlags & DISPLAY_DEVICE_ACTIVE) && !(monitor.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER)) { Monitor monitorInfo; monitorInfo.displayDeviceName = Unicode::FromWString(displayDevice.DeviceName); // モニターの配置とサイズを取得 ::EnumDisplayMonitors(nullptr, nullptr, detail::MonitorEnumProc, (LPARAM)&monitorInfo); // その他の情報を取得 monitorInfo.id = Unicode::FromWString(monitor.DeviceID); monitorInfo.name = Unicode::FromWString(monitor.DeviceString); monitorInfo.isPrimary = !!(displayDevice.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE); monitors.push_back(monitorInfo); } ZeroMemory(&monitor, sizeof(monitor)); monitor.cb = sizeof(monitor); } } ZeroMemory(&displayDevice, sizeof(displayDevice)); displayDevice.cb = sizeof(displayDevice); } return monitors; } size_t GetCurrentMonitorIndex() { const HMONITOR currentMonitor = ::MonitorFromWindow(Siv3DEngine::GetWindow()->getHandle(), MONITOR_DEFAULTTOPRIMARY); size_t index = 0; DISPLAY_DEVICE displayDevice; displayDevice.cb = sizeof(displayDevice); // デスクトップとして割り当てられている仮想デスクトップを検索 for (int32 deviceIndex = 0; ::EnumDisplayDevicesW(0, deviceIndex, &displayDevice, 0); ++deviceIndex) { if (displayDevice.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) { DISPLAY_DEVICE monitor; ZeroMemory(&monitor, sizeof(monitor)); monitor.cb = sizeof(monitor); // デスクトップとして使われているモニターの一覧を取得 for (int32 monitorIndex = 0; ::EnumDisplayDevicesW(displayDevice.DeviceName, monitorIndex, &monitor, 0); ++monitorIndex) { if ((monitor.StateFlags & DISPLAY_DEVICE_ACTIVE) && !(monitor.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER)) { detail::MonitorCheck desc = { Unicode::FromWString(displayDevice.DeviceName), nullptr }; // モニターのハンドルを取得 ::EnumDisplayMonitors(nullptr, nullptr, detail::MonitorCheckProc, (LPARAM)&desc); if (desc.second == currentMonitor) { return index; } ++index; } ZeroMemory(&monitor, sizeof(monitor)); monitor.cb = sizeof(monitor); } } ZeroMemory(&displayDevice, sizeof(displayDevice)); displayDevice.cb = sizeof(displayDevice); } return 0; } } } # elif defined(SIV3D_TARGET_MACOS) # include "../../ThirdParty/GLFW/include/GLFW/glfw3.h" # include <Siv3D/Window.hpp> namespace s3d { namespace System { Array<Monitor> EnumerateActiveMonitors() { Array<Monitor> results; int32 numMonitors; GLFWmonitor** monitors = ::glfwGetMonitors(&numMonitors); for (int32 i = 0; i < numMonitors; ++i) { GLFWmonitor* monitor = monitors[i]; Monitor result; result.name = Unicode::Widen(::glfwGetMonitorName(monitor)); uint32 displayID, unitNumber; int32 xPos, yPos, width, height; int32 wx, wy, ww, wh; glfwGetMonitorInfo_Siv3D(monitor, &displayID, &unitNumber, &xPos, &yPos, &width, &height, &wx, &wy, &ww, &wh); result.id = Format(displayID); result.displayDeviceName = Format(unitNumber); result.displayRect.x = xPos; result.displayRect.y = yPos; result.displayRect.w = width; result.displayRect.h = height; result.workArea.x = wx; result.workArea.y = wy; result.workArea.w = ww; result.workArea.h = wh; result.isPrimary = (i == 0); results.push_back(result); } return results; } size_t GetCurrentMonitorIndex() { const auto& state = Window::GetState(); const Point pos = state.pos; const Size size = state.windowSize; const auto monitors = EnumerateActiveMonitors(); int32 bestoverlap = 0; size_t bestIndex = 0; for (size_t i = 0; i < monitors.size(); ++i) { const auto& monitor = monitors[i]; const Point mPos = monitor.displayRect.pos; const Size mSize = monitor.displayRect.size; const int32 overlap = std::max(0, std::min(pos.x + size.x, mPos.x + mSize.x) - std::max(pos.x, mPos.x)) * std::max(0, std::min(pos.y + size.y, mPos.y + mSize.y) - std::max(pos.y, mPos.y)); if (bestoverlap < overlap) { bestoverlap = overlap; bestIndex = i; } } return bestIndex; } } } # elif defined(SIV3D_TARGET_LINUX) # include "../../ThirdParty/GLFW/include/GLFW/glfw3.h" # include <Siv3D/Window.hpp> namespace s3d { namespace System { Array<Monitor> EnumerateActiveMonitors() { Array<Monitor> results; int32 numMonitors; GLFWmonitor** monitors = ::glfwGetMonitors(&numMonitors); for (int32 i = 0; i < numMonitors; ++i) { GLFWmonitor* monitor = monitors[i]; Monitor result; result.name = Unicode::Widen(::glfwGetMonitorName(monitor)); uint32 displayID; int32 xPos, yPos, width, height; int32 wx, wy, ww, wh; char* name = nullptr; glfwGetMonitorInfo_Siv3D(monitor, &displayID, &name, &xPos, &yPos, &width, &height, &wx, &wy, &ww, &wh); result.id = Format(displayID); result.displayDeviceName = Unicode::Widen(name); result.displayRect.x = xPos; result.displayRect.y = yPos; result.displayRect.w = width; result.displayRect.h = height; result.workArea.x = wx; result.workArea.y = wy; result.workArea.w = ww; result.workArea.h = wh; result.isPrimary = (i == 0); results.push_back(result); ::free(name); // free monitor name buffer. } return results; } size_t GetCurrentMonitorIndex() { const auto& state = Window::GetState(); const Point pos = state.pos; const Size size = state.windowSize; const auto monitors = EnumerateActiveMonitors(); int32 bestoverlap = 0; size_t bestIndex = 0; for (size_t i = 0; i < monitors.size(); ++i) { const auto& monitor = monitors[i]; const Point mPos = monitor.displayRect.pos; const Size mSize = monitor.displayRect.size; const int32 overlap = std::max(0, std::min(pos.x + size.x, mPos.x + mSize.x) - std::max(pos.x, mPos.x)) * std::max(0, std::min(pos.y + size.y, mPos.y + mSize.y) - std::max(pos.y, mPos.y)); if (bestoverlap < overlap) { bestoverlap = overlap; bestIndex = i; } } return bestIndex; } } } # endif namespace s3d { void Formatter(FormatData& formatData, const Monitor& value) { String output; output += U"Name: " + value.name + U"\n"; output += U"ID: " + value.id + U"\n"; output += U"DisplayDeviceName: " + value.displayDeviceName + U"\n"; output += U"DisplayRect: " + Format(value.displayRect) + U"\n"; output += U"WorkArea: " + Format(value.workArea) + U"\n"; output += U"Primary: " + Format(value.isPrimary); formatData.string.append(output); } }
27.168605
125
0.656645
Fuyutsubaki
90daddb9d6e0c63b59a9202895e5b6f94dd48e7c
2,101
hpp
C++
cpp/visualmesh/network_structure.hpp
wongjoel/VisualMesh
98b973c6cd371aab51f2b631f75c9ac820d3b744
[ "MIT" ]
14
2018-06-22T19:46:34.000Z
2022-02-02T15:22:39.000Z
cpp/visualmesh/network_structure.hpp
wongjoel/VisualMesh
98b973c6cd371aab51f2b631f75c9ac820d3b744
[ "MIT" ]
2
2020-12-12T04:51:51.000Z
2021-06-28T01:14:42.000Z
cpp/visualmesh/network_structure.hpp
wongjoel/VisualMesh
98b973c6cd371aab51f2b631f75c9ac820d3b744
[ "MIT" ]
8
2018-06-11T14:54:45.000Z
2022-02-02T15:22:50.000Z
/* * Copyright (C) 2017-2020 Trent Houliston <[email protected]> * * 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 VISUALMESH_NETWORKSTRUCTURE_HPP #define VISUALMESH_NETWORKSTRUCTURE_HPP #include <vector> namespace visualmesh { /// Weights are a matrix (vector of vectors) template <typename Scalar> using Weights = std::vector<std::vector<Scalar>>; /// Biases are a vector template <typename Scalar> using Biases = std::vector<Scalar>; enum ActivationFunction { SELU, RELU, SOFTMAX, TANH, }; /// A layer is made up of weights biases and activation function template <typename Scalar> struct Layer { Weights<Scalar> weights; Biases<Scalar> biases; ActivationFunction activation; }; /// A convolutional layer is made up of a list of network layers template <typename Scalar> using ConvolutionalGroup = std::vector<Layer<Scalar>>; /// A network is a list of convolutional layers template <typename Scalar> using NetworkStructure = std::vector<ConvolutionalGroup<Scalar>>; } // namespace visualmesh #endif // VISUALMESH_NETWORKSTRUCTURE_HPP
36.859649
120
0.763922
wongjoel
90e69e6f340eeaf084901d09b18f28b3918e44a2
1,323
cpp
C++
chapter4_treesandGraphs/question2.cpp
kgajwan1/CTCI_practice
2e8e61f508777b4b7ad5d8c32dedd12ea5b27d39
[ "MIT" ]
null
null
null
chapter4_treesandGraphs/question2.cpp
kgajwan1/CTCI_practice
2e8e61f508777b4b7ad5d8c32dedd12ea5b27d39
[ "MIT" ]
null
null
null
chapter4_treesandGraphs/question2.cpp
kgajwan1/CTCI_practice
2e8e61f508777b4b7ad5d8c32dedd12ea5b27d39
[ "MIT" ]
null
null
null
//create a binary search tree from sorted array //make middle element root node, do recursion for left and right half #include<bits/stdc++.h> class node { public: int data; node *left, *right; }; //create a new node struct node *newNode(int item) { node *temp = new node; temp->data = item; temp->left = temp->right = NULL; return temp; } //utility to do preorder traversal void preOrderTraversal(node *n) { if(n == NULL) { return; } std::cout << n->data<<" "; preOrderTraversal(n->left); preOrderTraversal(n->right); } node *sortedArrtoBST(int arr[],int start,int end) { if (start>end) { // std::cout << "not possible\n"; return NULL; } //get middle elem and make it a root int mid = (start + end)/2; node *root = newNode(arr[mid]); root->left = sortedArrtoBST( arr, start,mid-1); root ->right = sortedArrtoBST( arr, mid+1,end); return root; } int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7}; int n = sizeof(arr) / sizeof(arr[0]); /* Convert List to BST */ node *root = sortedArrtoBST(arr, 0, n-1); std::cout << "PreOrder Traversal of constructed BST \n"; preOrderTraversal(root); return 0; }
23.210526
70
0.557067
kgajwan1
90e82c89d9a98a73c2c5a1dbb14b53e30be80f11
1,472
cpp
C++
904-fruit-into-baskets/solution.cpp
darxsys/leetcode
1174f0dbad56c6bfd8196bc4c14798b5f8cee418
[ "MIT" ]
null
null
null
904-fruit-into-baskets/solution.cpp
darxsys/leetcode
1174f0dbad56c6bfd8196bc4c14798b5f8cee418
[ "MIT" ]
null
null
null
904-fruit-into-baskets/solution.cpp
darxsys/leetcode
1174f0dbad56c6bfd8196bc4c14798b5f8cee418
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstring> #include <cstdlib> #include <cassert> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <map> #include <unordered_map> #include <algorithm> #include <unordered_set> using namespace std; class Solution { public: int totalFruit(vector<int>& tree) { if (tree.empty()) return 0; int sol = 1; int prev = -1; int cur = tree[0]; int seen = 1; int cur_len = 1; for (int i = 1; i < tree.size(); ++i) { int next = tree[i]; if (next == cur) { cur_len++; seen++; } else if (next == prev) { cur_len++; seen = 1; swap(cur, prev); } else { cur_len = seen + 1; seen = 1; prev = cur; cur = next; } sol = max(sol, cur_len); } return sol; } }; int main() { Solution s; vector<int> input({1, 2, 1}); assert(s.totalFruit(input) == 3); input = {0, 1, 2, 2}; assert(s.totalFruit(input) == 3); input = {1, 2, 3, 2, 2}; assert(s.totalFruit(input) == 4); input = {3,3,3,1,2,1,1,2,3,3,4}; assert(s.totalFruit(input) == 5); input = {0, 0, 0, 0, 0, 1}; assert(s.totalFruit(input) == 6); return 0; }
19.891892
45
0.443614
darxsys
90e913ad776a0343185c5d8aaae1d43df3d0020a
880
cpp
C++
PC_Clase7/max_val_k_array.cpp
Angelussz/ProgramacionCompetitiva
681c0aa21020d8e843108e77abcf2a62dd471dc5
[ "BSD-3-Clause" ]
null
null
null
PC_Clase7/max_val_k_array.cpp
Angelussz/ProgramacionCompetitiva
681c0aa21020d8e843108e77abcf2a62dd471dc5
[ "BSD-3-Clause" ]
null
null
null
PC_Clase7/max_val_k_array.cpp
Angelussz/ProgramacionCompetitiva
681c0aa21020d8e843108e77abcf2a62dd471dc5
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** Maximum sum of any contiguous subarray of size k *******************************************************************************/ #include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); vector<int> nums{2,3,4,1,5}; int k=3; int inic = 0; int sum = 0; int maxim = INT_MIN; for(int fin=0;fin < nums.size();fin++){ if(fin<k){ sum = sum+nums[fin]; maxim = sum; } else{ sum = sum-nums[inic]; sum = sum+nums[fin]; // cout<<sum<<"\n"; maxim = max(maxim,sum); inic++; } } if (maxim == 0){ cout<<0<<"\n"; } else{ cout<<maxim<<"\n"; } return 0; }
20.465116
80
0.359091
Angelussz
90e94d58c481a250c9ec78fd20e1c1b0fecb9ddd
14,546
cpp
C++
os/net/src/socket.cpp
rvedam/es-operating-system
32d3e4791c28a5623744800f108d029c40c745fc
[ "Apache-2.0" ]
2
2020-11-30T18:38:20.000Z
2021-06-07T07:44:03.000Z
os/net/src/socket.cpp
LambdaLord/es-operating-system
32d3e4791c28a5623744800f108d029c40c745fc
[ "Apache-2.0" ]
1
2019-01-14T03:09:45.000Z
2019-01-14T03:09:45.000Z
os/net/src/socket.cpp
LambdaLord/es-operating-system
32d3e4791c28a5623744800f108d029c40c745fc
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2008, 2009 Google Inc. * Copyright 2006, 2007 Nintendo Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <new> #include <stdlib.h> #include <string.h> #include <es/net/arp.h> #include "dix.h" #include "inet4address.h" #include "loopback.h" #include "socket.h" #include "visualizer.h" es::Resolver* Socket::resolver = 0; es::InternetConfig* Socket::config = 0; es::Context* Socket::interface = 0; AddressFamily::List Socket::addressFamilyList; NetworkInterface* Socket::interfaces[Socket::INTERFACE_MAX]; Timer* Socket::timer; LoopbackAccessor LoopbackInterface::loopbackAccessor; void Socket:: initialize() { DateTime seed = DateTime::getNow(); srand48(seed.getTicks()); timer = new Timer; } int Socket:: addInterface(es::NetworkInterface* networkInterface) { int n; for (n = 1; n < Socket::INTERFACE_MAX; ++n) { if (interfaces[n] == 0) { break; } } if (Socket::INTERFACE_MAX <= n) { return -1; } switch (networkInterface->getType()) { case es::NetworkInterface::Ethernet: { DIXInterface* dixInterface = new DIXInterface(networkInterface); dixInterface->setScopeID(n); interfaces[n] = dixInterface; // Connect address families to the loopback interface. AddressFamily* af; AddressFamily::List::Iterator iter = addressFamilyList.begin(); while ((af = iter.next())) { af->addInterface(dixInterface); } #if 0 { Visualizer v; dixInterface->getAdapter()->accept(&v); } #endif dixInterface->start(); break; } case es::NetworkInterface::Loopback: { LoopbackInterface* loopbackInterface = new LoopbackInterface(networkInterface); loopbackInterface->setScopeID(n); interfaces[n] = loopbackInterface; // Connect address families to the loopback interface. AddressFamily* af; AddressFamily::List::Iterator iter = addressFamilyList.begin(); while ((af = iter.next())) { af->addInterface(loopbackInterface); } #if 0 { Visualizer v; loopbackInterface->getAdapter()->accept(&v); } #endif loopbackInterface->start(); break; } default: return -1; } return n; } void Socket:: removeInterface(es::NetworkInterface* networkInterface) { for (int n = 1; n < Socket::INTERFACE_MAX; ++n) { NetworkInterface* i = interfaces[n]; if (i && i->networkInterface == networkInterface) { interfaces[n] = 0; delete i; break; } } } Socket:: Socket(int family, int type, int protocol) : family(family), type(type), protocol(protocol), adapter(0), af(0), recvBufferSize(8192), sendBufferSize(8192), errorCode(0), selector(0), blocking(true), recvFromAddress(0), recvFromPort(0) { af = getAddressFamily(family); } Socket:: ~Socket() { // Leave from multicast groups XXX if (adapter) { SocketUninstaller uninstaller(this); adapter->accept(&uninstaller); } } bool Socket:: input(InetMessenger* m, Conduit* c) { return true; } bool Socket:: output(InetMessenger* m, Conduit* c) { return true; } bool Socket:: error(InetMessenger* m, Conduit* c) { return true; } // // ISocket // bool Socket:: isBound() { return getLocalPort(); } bool Socket:: isClosed() { return isBound() && !getAdapter(); // bound and then uninstalled? } bool Socket:: sockAtMark() { if (!adapter) { errorCode = ENOTCONN; return -errorCode; } SocketMessenger m(this, &SocketReceiver::atMark); Visitor v(&m); adapter->accept(&v); int code = m.getErrorCode(); if (code) { if (code != EAGAIN) { errorCode = code; } return -errorCode; } return m.getFlag(); } bool Socket:: isUrgent() { if (!adapter) { errorCode = ENOTCONN; return -errorCode; } SocketMessenger m(this, &SocketReceiver::isUrgent); Visitor v(&m); adapter->accept(&v); int code = m.getErrorCode(); if (code) { if (code != EAGAIN) { errorCode = code; } return -errorCode; } return m.getFlag(); } bool Socket:: isConnected() { return getRemotePort(); } int Socket:: getHops() { } void Socket:: setHops(int limit) { } int Socket:: getReceiveBufferSize() { return recvBufferSize; } void Socket:: setReceiveBufferSize(int size) { if (!isBound()) { recvBufferSize = size; } } int Socket:: getSendBufferSize() { return sendBufferSize; } void Socket:: setSendBufferSize(int size) { if (!isBound()) { sendBufferSize = size; } } long long Socket:: getTimeout() { return timeout; } void Socket:: setTimeout(long long timeSpan) { timeout = timeSpan; } bool Socket:: getReuseAddress() { } void Socket:: setReuseAddress(bool on) { } void Socket:: bind(es::InternetAddress* addr, int port) { if (isBound()) { return; } if (port == 0) { port = af->selectEphemeralPort(this); if (port == 0) { return; } // XXX Reserve anon from others } Conduit* protocol = af->getProtocol(this); if (!protocol) { return; } setLocal(dynamic_cast<Address*>(addr)); // XXX setLocalPort(port); SocketInstaller installer(this); protocol->accept(&installer); } void Socket:: connect(es::InternetAddress* addr, int port) { if (isConnected() || addr == 0 || port == 0) { return; } Conduit* protocol = af->getProtocol(this); if (!protocol) { return; } int anon = 0; if (getLocalPort() == 0) { anon = af->selectEphemeralPort(this); if (anon == 0) { return; } // XXX Reserve anon from others } es::InternetAddress* src = 0; if (!getLocal()) // XXX any { src = af->selectSourceAddress(addr); if (!src) { return; } } if (isBound()) { SocketDisconnector disconnector(this); adapter->accept(&disconnector); if (anon) { setLocalPort(anon); } if (src) { setLocal(dynamic_cast<Address*>(src)); } setRemote(dynamic_cast<Address*>(addr)); // XXX setRemotePort(port); SocketConnector connector(this, disconnector.getProtocol()); protocol->accept(&connector); } else { if (anon) { setLocalPort(anon); } if (src) { setLocal(dynamic_cast<Address*>(src)); } setRemote(dynamic_cast<Address*>(addr)); // XXX setRemotePort(port); SocketInstaller installer(this); protocol->accept(&installer); } // Request connect SocketMessenger m(this, &SocketReceiver::connect); Visitor v(&m); adapter->accept(&v); int code = m.getErrorCode(); if (code != EINPROGRESS) { errorCode = code; } } es::Socket* Socket:: accept() { SocketMessenger m(this, &SocketReceiver::accept); Visitor v(&m); adapter->accept(&v); errorCode = m.getErrorCode(); int code = m.getErrorCode(); if (code != EAGAIN) { errorCode = code; } return m.getSocket(); } void Socket:: close() { if (!adapter) { return; } SocketMessenger m(this, &SocketReceiver::close); Visitor v(&m); adapter->accept(&v); int code = m.getErrorCode(); if (code != EAGAIN) { errorCode = code; } } void Socket:: listen(int backlog) { StreamReceiver* s = dynamic_cast<StreamReceiver*>(getReceiver()); if (s) { s->setState(StreamReceiver::stateListen); s->setBackLogCount(backlog); } } int Socket:: read(void* dst, int count) { if (!adapter) { errorCode = ENOTCONN; return -errorCode; } SocketMessenger m(this, &SocketReceiver::read, dst, count); Visitor v(&m); adapter->accept(&v); int code = m.getErrorCode(); if (code) { if (code != EAGAIN) { errorCode = code; } return -errorCode; } return m.getLength(); } int Socket:: recvFrom(void* dst, int count, int flags) { if (!adapter) { errorCode = ENOTCONN; return -errorCode; } SocketMessenger m(this, &SocketReceiver::read, dst, count); Visitor v(&m); adapter->accept(&v); int code = m.getErrorCode(); if (code) { if (code != EAGAIN) { errorCode = code; } return -errorCode; } if (recvFromAddress) { recvFromAddress->release(); } recvFromAddress = m.getRemote(); recvFromPort = m.getRemotePort(); return m.getLength(); } es::InternetAddress* Socket:: getRecvFromAddress() { es::InternetAddress* addr = recvFromAddress; recvFromAddress = 0; return addr; } int Socket:: getRecvFromPort() { int port = recvFromPort; recvFromPort = 0; return port; } int Socket:: sendTo(const void* src, int count, int flags, es::InternetAddress* addr, int port) { if (!adapter) { errorCode = ENOTCONN; return -errorCode; } SocketMessenger m(this, &SocketReceiver::write, const_cast<void*>(src), count); m.setRemote(dynamic_cast<Inet4Address*>(addr)); m.setRemotePort(port); m.setFlag(flags); Visitor v(&m); adapter->accept(&v); int code = m.getErrorCode(); if (code) { if (code != EAGAIN) { errorCode = code; } return -errorCode; } return m.getLength(); } void Socket:: shutdownInput() { if (!adapter) { return; } SocketMessenger m(this, &SocketReceiver::shutdownInput); Visitor v(&m); adapter->accept(&v); errorCode = m.getErrorCode(); } void Socket:: shutdownOutput() { if (!adapter) { return; } SocketMessenger m(this, &SocketReceiver::shutdownOutput); Visitor v(&m); adapter->accept(&v); errorCode = m.getErrorCode(); } int Socket:: write(const void* src, int count) { if (!adapter) { errorCode = ENOTCONN; return -errorCode; } SocketMessenger m(this, &SocketReceiver::write, const_cast<void*>(src), count); Visitor v(&m); adapter->accept(&v); int code = m.getErrorCode(); if (code) { if (code != EAGAIN) { errorCode = code; } return -errorCode; } return m.getLength(); } bool Socket:: isAcceptable() { if (!adapter) { return false; } SocketMessenger m(this, &SocketReceiver::isAcceptable); Visitor v(&m); adapter->accept(&v); return m.getErrorCode(); } bool Socket:: isConnectable() { if (!adapter) { return false; } SocketMessenger m(this, &SocketReceiver::isConnectable); Visitor v(&m); adapter->accept(&v); return m.getErrorCode(); } bool Socket:: isReadable() { if (!adapter) { return false; } SocketMessenger m(this, &SocketReceiver::isReadable); Visitor v(&m); adapter->accept(&v); return m.getErrorCode(); } bool Socket:: isWritable() { if (!adapter) { return false; } SocketMessenger m(this, &SocketReceiver::isWritable); Visitor v(&m); adapter->accept(&v); return m.getErrorCode(); } // // IMulticastSocket // bool Socket:: getLoopbackMode() { } void Socket:: setLoopbackMode(bool disable) { } void Socket:: joinGroup(es::InternetAddress* addr) { Address* address = static_cast<Address*>(addr); if (address->isMulticast()) { addresses.addLast(address); address->addSocket(this); } } void Socket:: leaveGroup(es::InternetAddress* addr) { Address* address = static_cast<Address*>(addr); if (addresses.contains(address)) { addresses.remove(address); address->removeSocket(this); } } void Socket:: notify() { if (!adapter) { return; } SocketMessenger m(this, &SocketReceiver::notify); Visitor v(&m); adapter->accept(&v); } int Socket:: add(es::Monitor* selector) { esReport("Socket::%s(%p) : %p\n", __func__, selector, this->selector); if (!selector || this->selector) { return -1; } selector->addRef(); this->selector = selector; return 1; } int Socket:: remove(es::Monitor* selector) { esReport("Socket::%s(%p) : %p\n", __func__, selector, this->selector); if (!selector || selector != this->selector) { return -1; } selector->release(); this->selector = 0; return 1; } // // IInterface // Object* Socket:: queryInterface(const char* riid) { Object* objectPtr; if (strcmp(riid, es::Socket::iid()) == 0) { objectPtr = static_cast<es::Socket*>(this); } else if (strcmp(riid, es::Selectable::iid()) == 0) { objectPtr = static_cast<es::Selectable*>(this); } else if (strcmp(riid, Object::iid()) == 0) { objectPtr = static_cast<es::Socket*>(this); } else if (strcmp(riid, es::MulticastSocket::iid()) == 0 && type == es::Socket::Datagram) { objectPtr = static_cast<es::Socket*>(this); } else { return NULL; } objectPtr->addRef(); return objectPtr; } unsigned int Socket:: addRef() { return ref.addRef(); } unsigned int Socket:: release() { unsigned int count = ref.release(); if (count == 0) { delete this; return 0; } return count; }
18.11457
91
0.571497
rvedam
90f32b95bb13f5a5f7953dcbf0df514c560f22e5
30,383
cpp
C++
snap/snap-core/centr.cpp
dkw-aau/trident-clone
18f896db2be05870069ae7b3aa6b4837c74fff0f
[ "Apache-2.0" ]
20
2018-10-17T21:39:40.000Z
2021-11-10T11:07:23.000Z
snap/snap-core/centr.cpp
dkw-aau/trident-clone
18f896db2be05870069ae7b3aa6b4837c74fff0f
[ "Apache-2.0" ]
5
2020-07-06T22:50:04.000Z
2022-03-17T10:34:15.000Z
snap/snap-core/centr.cpp
dkw-aau/trident-clone
18f896db2be05870069ae7b3aa6b4837c74fff0f
[ "Apache-2.0" ]
9
2018-09-18T11:37:35.000Z
2022-03-29T07:46:41.000Z
namespace TSnap { ///////////////////////////////////////////////// // Node centrality measures double GetDegreeCentr(const PUNGraph& Graph, const int& NId) { if (Graph->GetNodes() > 1) { return double(Graph->GetNI(NId).GetDeg())/double(Graph->GetNodes()-1); } else { return 0.0; } } void GetEigenVectorCentr(const PUNGraph& Graph, TIntFltH& NIdEigenH, const double& Eps, const int& MaxIter) { const int NNodes = Graph->GetNodes(); NIdEigenH.Gen(NNodes); // initialize vector values for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { NIdEigenH.AddDat(NI.GetId(), 1.0/NNodes); IAssert(NI.GetId() == NIdEigenH.GetKey(NIdEigenH.Len()-1)); } TFltV TmpV(NNodes); for (int iter = 0; iter < MaxIter; iter++) { int j = 0; // add neighbor values for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++, j++) { TmpV[j] = 0; for (int e = 0; e < NI.GetOutDeg(); e++) { TmpV[j] += NIdEigenH.GetDat(NI.GetOutNId(e)); } } // normalize double sum = 0; for (int i = 0; i < TmpV.Len(); i++) { sum += (TmpV[i]*TmpV[i]); } sum = sqrt(sum); for (int i = 0; i < TmpV.Len(); i++) { TmpV[i] /= sum; } // compute difference double diff = 0.0; j = 0; for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++, j++) { diff += fabs(NIdEigenH.GetDat(NI.GetId())-TmpV[j]); } // set new values j = 0; for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++, j++) { NIdEigenH.AddDat(NI.GetId(), TmpV[j]); } if (diff < Eps) { break; } } } // Group centrality measures double GetGroupDegreeCentr(const PUNGraph& Graph, const PUNGraph& Group) { int deg; TIntH NN; for (TUNGraph::TNodeI NI = Group->BegNI(); NI < Group->EndNI(); NI++) { deg = Graph->GetNI(NI.GetId()).GetDeg(); for (int i=0; i<deg; i++) { if (Group->IsNode(Graph->GetNI(NI.GetId()).GetNbrNId(i))==0) NN.AddDat(Graph->GetNI(NI.GetId()).GetNbrNId(i),NI.GetId()); } } return (double)NN.Len(); } double GetGroupDegreeCentr0(const PUNGraph& Graph, const TIntH& GroupNodes) { int deg; TIntH NN; for (int i = 0; i<GroupNodes.Len(); i++) { deg = Graph->GetNI(GroupNodes.GetDat(i)).GetDeg(); for (int j = 0; j < deg; j++) { if (GroupNodes.IsKey(Graph->GetNI(GroupNodes.GetDat(i)).GetNbrNId(j))==0) NN.AddDat(Graph->GetNI(GroupNodes.GetDat(i)).GetNbrNId(j),GroupNodes.GetDat(i)); } } return (double)NN.Len(); } double GetGroupDegreeCentr(const PUNGraph& Graph, const TIntH& GroupNodes) { int deg; TIntH NN; TIntH GroupNodes1; for (THashKeyDatI<TInt,TInt> NI = GroupNodes.BegI(); NI < GroupNodes.EndI(); NI++) GroupNodes1.AddDat(NI.GetDat(),NI.GetDat()); for (THashKeyDatI<TInt,TInt> NI = GroupNodes1.BegI(); NI < GroupNodes1.EndI(); NI++){ TUNGraph::TNodeI node = Graph->GetNI(NI.GetKey()); deg = node.GetDeg(); for (int j = 0; j < deg; j++){ if (GroupNodes1.IsKey(node.GetNbrNId(j))==0 && NN.IsKey(node.GetNbrNId(j))==0) NN.AddDat(node.GetNbrNId(j),NI.GetKey()); } } return (double)NN.Len(); } double GetGroupFarnessCentr(const PUNGraph& Graph, const TIntH& GroupNodes) { TIntH* NDistH = new TIntH[GroupNodes.Len()]; for (int i=0; i<GroupNodes.Len(); i++){ NDistH[i](Graph->GetNodes()); TSnap::GetShortPath<PUNGraph>(Graph, GroupNodes.GetDat(i), NDistH[i], true, TInt::Mx); } int min, dist, sum=0, len=0; for (PUNGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++){ if(NDistH[0].IsKey(NI.GetId())) min = NDistH[0].GetDat(NI.GetId()); else min = -1; for (int j=1; j<GroupNodes.Len(); j++){ if (NDistH[j].IsKey(NI.GetId())) dist = NDistH[j].GetDat(NI.GetId()); else dist = -1; if ((dist < min && dist != -1) || (dist > min && min == -1)) min = dist; } if (min>0){ sum += min; len++; } } if (len > 0) { return sum/double(len); } else { return 0.0; } } PUNGraph *AllGraphsWithNNodes(int n){ PUNGraph* g = new PUNGraph[(((n*n)-n)/2)+1]; PUNGraph g0; for(int i=0; i<n; i++) g0->AddNode(i); g[0] = g0; int br=1; for(int i=0; i<n; i++) for(int j=i; j<n; j++){ g0->AddEdge(i,j); g[br] = g0; br++; } return g; } TIntH *AllCombinationsMN(int m, int n){ float N = 1; for(int i=n; i>0; i--){ N *= (float)m/(float)n; m--; n--; } TIntH* C = new TIntH[(int)N]; return C; } double GetGroupClosenessCentr(const PUNGraph& Graph, const TIntH& GroupNodes) { const double Farness = GetGroupFarnessCentr(Graph, GroupNodes); if (Farness != 0.0) { return 1.0/Farness; } else { return 0.0; } } TIntH MaxCPGreedyBetter(const PUNGraph& Graph, const int k) { TIntH GroupNodes; // buildup cpntainer of group nodes TIntH NNodes; // container of neighbouring nodes TIntH Nodes; // nodes sorted by vd double gc = 0, gc0 = 0; int addId = 0, addIdPrev = 0; for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { Nodes.AddDat(NI.GetId(),NI.GetDeg()); } Nodes.SortByDat(false); int br = 0; while (br < k) { for (THashKeyDatI<TInt,TInt> NI = Nodes.BegI(); NI < Nodes.EndI(); NI++) { if ((NI.GetDat() <= (int)gc0)) break; gc = NI.GetDat()-Intersect(Graph->GetNI(NI.GetKey()),NNodes); if (gc>gc0) { gc0 = gc; addId = NI.GetKey(); } } if (addId != addIdPrev){ GroupNodes.AddDat(br,addId); br++; gc0=0; NNodes.AddDat(addId,0); for (int i=0; i<Graph->GetNI(addId).GetDeg(); i++) { NNodes.AddDat(Graph->GetNI(addId).GetNbrNId(i),0); } addIdPrev = addId; Nodes.DelKey(addId); } else { br = k; } printf("%i,",br); } // gcFinal = GetGroupDegreeCentr(Graph, GroupNodes); return GroupNodes; } // this is the variation of the first version that doesent stop after finding the optimal K TIntH MaxCPGreedyBetter1(const PUNGraph& Graph, const int k) { TIntH GroupNodes; TIntH NNodes; TIntH Nodes; double gc = 0, gc0 = 0; int addId = 0, addIdPrev = 0; // put nodes in the container and sort them by vertex degree for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++){ Nodes.AddDat(NI.GetId(),NI.GetDeg()); } Nodes.SortByDat(false); int br = 0; while (br < k) { for (THashKeyDatI<TInt,TInt> NI = Nodes.BegI(); NI < Nodes.EndI(); NI++){ if((NI.GetDat() < (int)gc0)) break; gc = NI.GetDat()-Intersect(Graph->GetNI(NI.GetKey()),NNodes); if (gc>gc0) { gc0 = gc; addId = NI.GetKey(); } } if (addId != addIdPrev){ GroupNodes.AddDat(br,addId); br++; gc0=-10000000; NNodes.AddDat(addId,0); for (int i=0; i<Graph->GetNI(addId).GetDeg(); i++) { NNodes.AddDat(Graph->GetNI(addId).GetNbrNId(i),0); } addIdPrev = addId; Nodes.DelKey(addId); } } // gcFinal = GetGroupDegreeCentr(Graph, GroupNodes); return GroupNodes; } // version with string type of container of group nodes - Fail (it is slower) TIntH MaxCPGreedyBetter2(const PUNGraph& Graph, const int k) { TIntH GroupNodes; // buildup cpntainer of group nodes TStr NNodes; // container of neighbouring nodes TIntH Nodes; // nodes sorted by vd double gc = 0, gc0 = 0; int addId = 0, addIdPrev=0; for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++){ Nodes.AddDat(NI.GetId(),NI.GetDeg()); } Nodes.SortByDat(false); int br=0; while (br < k) { for (THashKeyDatI<TInt,TInt> NI = Nodes.BegI(); NI < Nodes.EndI(); NI++){ if((NI.GetDat() <= (int)gc0)) break; gc = NI.GetDat()-Intersect(Graph->GetNI(NI.GetKey()),NNodes); if (gc>gc0) { gc0 = gc; addId = NI.GetKey(); } } if (addId != addIdPrev) { GroupNodes.AddDat(br,addId); br++; gc0=0; TInt digi = addId; TStr buf = digi.GetStr(); NNodes += " "+buf; for (int i=0; i<Graph->GetNI(addId).GetDeg(); i++) { TInt digi = Graph->GetNI(addId).GetNbrNId(i); TStr buf = digi.GetStr(); NNodes += " "+buf; } addIdPrev = addId; Nodes.DelKey(addId); } else { br = k; } printf("%i,",br); } // gcFinal = GetGroupDegreeCentr(Graph, GroupNodes); return GroupNodes; } // version with int array - the fastest TIntH MaxCPGreedyBetter3(const PUNGraph& Graph, const int k) { TIntH GroupNodes; // buildup cpntainer of group nodes const int n = Graph->GetNodes(); int *NNodes = new int[n]; // container of neighbouring nodes int NNodes_br = 0; TIntH Nodes; // nodes sorted by vd double gc = 0, gc0 = 0; int addId = 0, addIdPrev = 0; for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++){ Nodes.AddDat(NI.GetId(),NI.GetDeg()); } Nodes.SortByDat(false); int br = 0; while (br < k) { for (THashKeyDatI<TInt,TInt> NI = Nodes.BegI(); NI < Nodes.EndI(); NI++){ if((NI.GetDat() <= (int)gc0)) break; gc = NI.GetDat()-Intersect(Graph->GetNI(NI.GetKey()),NNodes,NNodes_br); if (gc>gc0){ gc0 = gc; addId = NI.GetKey(); } } if (addId != addIdPrev) { GroupNodes.AddDat(br,addId); br++; gc0=0; int nn = addId; bool nnnew = true; for (int j=0; j<NNodes_br; j++) if (NNodes[j] == nn){ nnnew = false; j = NNodes_br; } if (nnnew){ NNodes[NNodes_br] = nn; NNodes_br++; } for (int i=0; i<Graph->GetNI(addId).GetDeg(); i++) { int nn = Graph->GetNI(addId).GetNbrNId(i); bool nnnew = true; for (int j=0; j<NNodes_br; j++) { if (NNodes[j] == nn){ nnnew = false; j = NNodes_br; } } if (nnnew){ NNodes[NNodes_br] = nn; NNodes_br++; } } addIdPrev = addId; Nodes.DelKey(addId); } else { br = k; } printf("%i,",br); } delete[] NNodes; // gcFinal = GetGroupDegreeCentr(Graph, GroupNodes); return GroupNodes; } //Weighted PageRank int GetWeightedPageRank(const PNEANet Graph, TIntFltH& PRankH, const TStr& Attr, const double& C, const double& Eps, const int& MaxIter) { if (!Graph->IsFltAttrE(Attr)) return -1; TFltV Weights = Graph->GetFltAttrVecE(Attr); int mxid = Graph->GetMxNId(); TFltV OutWeights(mxid); Graph->GetWeightOutEdgesV(OutWeights, Weights); const int NNodes = Graph->GetNodes(); //const double OneOver = 1.0/double(NNodes); PRankH.Gen(NNodes); for (TNEANet::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { PRankH.AddDat(NI.GetId(), 1.0/NNodes); //IAssert(NI.GetId() == PRankH.GetKey(PRankH.Len()-1)); } TFltV TmpV(NNodes); for (int iter = 0; iter < MaxIter; iter++) { int j = 0; for (TNEANet::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++, j++) { TmpV[j] = 0; for (int e = 0; e < NI.GetInDeg(); e++) { const int InNId = NI.GetInNId(e); const TFlt OutWeight = OutWeights[InNId]; int EId = Graph->GetEId(InNId, NI.GetId()); const TFlt Weight = Weights[Graph->GetFltKeyIdE(EId)]; if (OutWeight > 0) { TmpV[j] += PRankH.GetDat(InNId) * Weight / OutWeight; } } TmpV[j] = C*TmpV[j]; // Berkhin (the correct way of doing it) //TmpV[j] = C*TmpV[j] + (1.0-C)*OneOver; // iGraph } double diff=0, sum=0, NewVal; for (int i = 0; i < TmpV.Len(); i++) { sum += TmpV[i]; } const double Leaked = (1.0-sum) / double(NNodes); for (int i = 0; i < PRankH.Len(); i++) { // re-instert leaked PageRank NewVal = TmpV[i] + Leaked; // Berkhin //NewVal = TmpV[i] / sum; // iGraph diff += fabs(NewVal-PRankH[i]); PRankH[i] = NewVal; } if (diff < Eps) { break; } } return 0; } #ifdef USE_OPENMP int GetWeightedPageRankMP(const PNEANet Graph, TIntFltH& PRankH, const TStr& Attr, const double& C, const double& Eps, const int& MaxIter) { if (!Graph->IsFltAttrE(Attr)) return -1; const int NNodes = Graph->GetNodes(); TVec<TNEANet::TNodeI> NV; //const double OneOver = 1.0/double(NNodes); PRankH.Gen(NNodes); int MxId = 0; for (TNEANet::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { NV.Add(NI); PRankH.AddDat(NI.GetId(), 1.0/NNodes); int Id = NI.GetId(); if (Id > MxId) { MxId = Id; } } TFltV PRankV(MxId+1); TFltV OutWeights(MxId+1); TFltV Weights = Graph->GetFltAttrVecE(Attr); #pragma omp parallel for schedule(dynamic,10000) for (int j = 0; j < NNodes; j++) { TNEANet::TNodeI NI = NV[j]; int Id = NI.GetId(); OutWeights[Id] = Graph->GetWeightOutEdges(NI, Attr); PRankV[Id] = 1/NNodes; } TFltV TmpV(NNodes); for (int iter = 0; iter < MaxIter; iter++) { #pragma omp parallel for schedule(dynamic,10000) for (int j = 0; j < NNodes; j++) { TNEANet::TNodeI NI = NV[j]; TFlt Tmp = 0; for (int e = 0; e < NI.GetInDeg(); e++) { const int InNId = NI.GetInNId(e); const TFlt OutWeight = OutWeights[InNId]; int EId = Graph->GetEId(InNId, NI.GetId()); const TFlt Weight = Weights[Graph->GetFltKeyIdE(EId)]; if (OutWeight > 0) { Tmp += PRankH.GetDat(InNId) * Weight / OutWeight; } } TmpV[j] = C*Tmp; // Berkhin (the correct way of doing it) //TmpV[j] = C*TmpV[j] + (1.0-C)*OneOver; // iGraph } double sum = 0; #pragma omp parallel for reduction(+:sum) schedule(dynamic,10000) for (int i = 0; i < TmpV.Len(); i++) { sum += TmpV[i]; } const double Leaked = (1.0-sum) / double(NNodes); double diff = 0; #pragma omp parallel for reduction(+:diff) schedule(dynamic,10000) for (int i = 0; i < NNodes; i++) { TNEANet::TNodeI NI = NV[i]; double NewVal = TmpV[i] + Leaked; // Berkhin //NewVal = TmpV[i] / sum; // iGraph int Id = NI.GetId(); diff += fabs(NewVal-PRankV[Id]); PRankV[Id] = NewVal; } if (diff < Eps) { break; } } #pragma omp parallel for schedule(dynamic,10000) for (int i = 0; i < NNodes; i++) { TNEANet::TNodeI NI = NV[i]; PRankH[i] = PRankV[NI.GetId()]; } return 0; } #endif // USE_OPENMP //Event importance TIntFltH EventImportance(const PNGraph& Graph, const int k) { TIntFltH NodeList; // values for nodese for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++){ NodeList.AddDat(NI.GetId(),NI.GetOutDeg()); } for (THashKeyDatI<TInt,TFlt> NI = NodeList.BegI(); NI < NodeList.EndI(); NI++){ int outdeg = Graph->GetNI(NI.GetKey()).GetOutDeg(); int indeg = Graph->GetNI(NI.GetKey()).GetInDeg(); if (outdeg>1 && indeg>0){ double val = (1-(1/(double)outdeg))/(double)indeg; for(int i=0; i<(outdeg+indeg);i++){ int NId = Graph->GetNI(NI.GetKey()).GetNbrNId(i); if (Graph->GetNI(NI.GetKey()).IsInNId(NId) == true){ NodeList.AddDat(NId,NodeList.GetDat(NId)+val); } } } } return NodeList; } //Event importance 1 TIntFltH EventImportance1 (const PNGraph& Graph, const int k) { TIntFltH NodeList; // values for nodese for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++){ NodeList.AddDat(NI.GetId(),NI.GetOutDeg()); } for (THashKeyDatI<TInt,TFlt> NI = NodeList.BegI(); NI < NodeList.EndI(); NI++){ int outdeg = Graph->GetNI(NI.GetKey()).GetOutDeg(); int indeg = Graph->GetNI(NI.GetKey()).GetInDeg(); if (outdeg>1 && indeg>0){ double val = (1-(1/(double)outdeg))/(double)indeg; for(int i=0; i<(outdeg+indeg);i++){ int NId = Graph->GetNI(NI.GetKey()).GetNbrNId(i); if (Graph->GetNI(NI.GetKey()).IsInNId(NId) == true){ NodeList.AddDat(NId,NodeList.GetDat(NId)+val); } } } } return NodeList; } int Intersect(TUNGraph::TNodeI Node, TIntH NNodes){ int br=0; for (int i=0; i<Node.GetDeg(); i++) { if (NNodes.IsKey(Node.GetNbrNId(i))) br++; } if (NNodes.IsKey(Node.GetId())) br++; return br; } int Intersect(TUNGraph::TNodeI Node, TStr NNodes){ int br=0; TInt digi = -1; TStr buf = ""; for (int i=0; i<Node.GetDeg(); i++) { digi = Node.GetNbrNId(i); TStr buf = digi.GetStr(); if (NNodes.IsStrIn(buf.CStr())) br++; } digi = Node.GetId(); buf = digi.GetStr(); if (NNodes.IsStrIn(buf.CStr())) br++; return br; } int Intersect(TUNGraph::TNodeI Node, int *NNodes, int NNodes_br){ int br = 0; int neig; for (int i=0; i<Node.GetDeg(); i++) { neig = Node.GetNbrNId(i); for (int j=0; j<NNodes_br; j++) { if (neig == NNodes[j]) { br++; j = NNodes_br; } } } neig = Node.GetId(); for (int j=0; j<NNodes_br; j++) { if (neig == NNodes[j]) { br++; j = NNodes_br; } } return br; } int Intersect1(TUNGraph::TNodeI Node, TStr NNodes){ int br=0; for (int i=0; i<Node.GetDeg(); i++) { TInt digi = Node.GetNbrNId(i); TStr buf = ""; buf = digi.GetStr(); if (NNodes.SearchStr(buf.CStr())!=-1) br++; } TInt digi = Node.GetId(); TStr buf = digi.GetStr(); if (NNodes.SearchStr(buf.CStr())!=-1) br++; return br; } TIntH LoadNodeList(TStr InFNmNodes){ TSsParser Ss(InFNmNodes, ssfWhiteSep, true, true, true); TIntIntH Nodes; int br = 0, NId; while (Ss.Next()) { if (Ss.GetInt(0, NId)) { Nodes.AddDat(br,NId); br++; } } return Nodes; } int findMinimum(TIntV& Frontier, TIntFltH& NIdDistH) { TFlt minimum = TInt::Mx; int min_index = 0; for (int i = 0; i < Frontier.Len(); i++) { int NId = Frontier.GetVal(i); if (NIdDistH[NId] < minimum) { minimum = NIdDistH[NId]; min_index = i; } } const int NId = Frontier.GetVal(min_index); Frontier.Del(min_index); return NId; } int GetWeightedShortestPath( const PNEANet Graph, const int& SrcNId, TIntFltH& NIdDistH, const TFltV& Attr) { TIntV frontier; NIdDistH.Clr(false); NIdDistH.AddDat(SrcNId, 0); frontier.Add(SrcNId); while (! frontier.Empty()) { const int NId = findMinimum(frontier, NIdDistH); const PNEANet::TObj::TNodeI NodeI = Graph->GetNI(NId); for (int v = 0; v < NodeI.GetOutDeg(); v++) { int DstNId = NodeI.GetOutNId(v); int EId = NodeI.GetOutEId(v); if (! NIdDistH.IsKey(DstNId)) { NIdDistH.AddDat(DstNId, NIdDistH.GetDat(NId) + Attr[EId]); frontier.Add(DstNId); } else { if (NIdDistH[DstNId] > NIdDistH.GetDat(NId) + Attr[EId]) { NIdDistH[DstNId] = NIdDistH.GetDat(NId) + Attr[EId]; } } } } return 0; } double GetWeightedFarnessCentr(const PNEANet Graph, const int& NId, const bool& IsDir, const TFltV& Attr, const bool& Normalized) { TIntFltH NDistH(Graph->GetNodes()); GetWeightedShortestPath(Graph, NId, NDistH, Attr); double sum = 0; for (TIntFltH::TIter I = NDistH.BegI(); I < NDistH.EndI(); I++) { sum += I->Dat(); } if (NDistH.Len() > 1) { double centr = sum/double(NDistH.Len()-1); if (Normalized) { centr *= (Graph->GetNodes() - 1)/double(NDistH.Len()-1); } return centr; } else { return 0.0; } } double GetWeightedClosenessCentr(const PNEANet Graph, const int& NId, const bool& IsDir, const TFltV& Attr, const bool& Normalized) { const double Farness = GetWeightedFarnessCentr(Graph, NId, IsDir, Attr, Normalized); if (Farness != 0.0) { return 1.0/Farness; } else { return 0.0; } return 0.0; } void GetWeightedBetweennessCentr(const PNEANet Graph, const TIntV& BtwNIdV, TIntFltH& NodeBtwH, const bool& IsDir, const bool& DoNodeCent, TIntPrFltH& EdgeBtwH, const bool& DoEdgeCent, const TFltV& Attr) { if (DoNodeCent) { NodeBtwH.Clr(); } if (DoEdgeCent) { EdgeBtwH.Clr(); } const int nodes = Graph->GetNodes(); TIntS S(nodes); TIntQ Q(nodes); TIntIntVH P(nodes); // one vector for every node TIntFltH delta(nodes); TIntFltH sigma(nodes), d(nodes); // init for (PNEANet::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { if (DoNodeCent) { NodeBtwH.AddDat(NI.GetId(), 0); } if (DoEdgeCent) { for (int e = 0; e < NI.GetOutDeg(); e++) { if (NI.GetId() < NI.GetOutNId(e)) { EdgeBtwH.AddDat(TIntPr(NI.GetId(), NI.GetOutNId(e)), 0); } } } sigma.AddDat(NI.GetId(), 0); d.AddDat(NI.GetId(), -1); P.AddDat(NI.GetId(), TIntV()); delta.AddDat(NI.GetId(), 0); } // calc betweeness for (int k=0; k < BtwNIdV.Len(); k++) { const PNEANet::TObj::TNodeI NI = Graph->GetNI(BtwNIdV[k]); // reset for (int i = 0; i < sigma.Len(); i++) { sigma[i]=0; d[i]=-1; delta[i]=0; P[i].Clr(false); } S.Clr(false); Q.Clr(false); sigma.AddDat(NI.GetId(), 1); d.AddDat(NI.GetId(), 0); Q.Push(NI.GetId()); while (! Q.Empty()) { const int v = Q.Top(); Q.Pop(); const PNEANet::TObj::TNodeI NI2 = Graph->GetNI(v); S.Push(v); const double VDat = d.GetDat(v); for (int e = 0; e < NI2.GetOutDeg(); e++) { const int w = NI2.GetOutNId(e); const int eid = NI2.GetOutEId(e); if (d.GetDat(w) < 0) { // find w for the first time Q.Push(w); d.AddDat(w, VDat+Attr[eid]); } //shortest path to w via v ? if (d.GetDat(w) == VDat+Attr[eid]) { sigma.AddDat(w) += sigma.GetDat(v); P.GetDat(w).Add(v); } } } while (! S.Empty()) { const int w = S.Top(); const double SigmaW = sigma.GetDat(w); const double DeltaW = delta.GetDat(w); const TIntV NIdV = P.GetDat(w); S.Pop(); for (int i = 0; i < NIdV.Len(); i++) { const int NId = NIdV[i]; const double c = (sigma.GetDat(NId)*1.0/SigmaW) * (1+DeltaW); delta.AddDat(NId) += c; if (DoEdgeCent) { EdgeBtwH.AddDat(TIntPr(TMath::Mn(NId, w), TMath::Mx(NId, w))) += c; } } double factor = (IsDir) ? 1.0 : 2.0; if (DoNodeCent && w != NI.GetId()) { NodeBtwH.AddDat(w) += delta.GetDat(w)/factor; } } } } void GetWeightedBetweennessCentr(const PNEANet Graph, TIntFltH& NodeBtwH, TIntPrFltH& EdgeBtwH, const TFltV& Attr, const bool& IsDir, const double& NodeFrac) { TIntV NIdV; Graph->GetNIdV(NIdV); if (NodeFrac < 1.0) { // calculate beetweenness centrality for a subset of nodes NIdV.Shuffle(TInt::Rnd); for (int i = int((1.0-NodeFrac)*NIdV.Len()); i > 0; i--) { NIdV.DelLast(); } } GetWeightedBetweennessCentr(Graph, NIdV, NodeBtwH, IsDir, true, EdgeBtwH, true, Attr ); } void GetWeightedBetweennessCentr(const PNEANet Graph, TIntFltH& NodeBtwH, const TFltV& Attr, const bool& IsDir, const double& NodeFrac) { TIntPrFltH EdgeBtwH; TIntV NIdV; Graph->GetNIdV(NIdV); if (NodeFrac < 1.0) { // calculate beetweenness centrality for a subset of nodes NIdV.Shuffle(TInt::Rnd); for (int i = int((1.0-NodeFrac)*NIdV.Len()); i > 0; i--) { NIdV.DelLast(); } } GetWeightedBetweennessCentr(Graph, NIdV, NodeBtwH, IsDir, true, EdgeBtwH, false, Attr); } void GetWeightedBetweennessCentr(const PNEANet Graph, TIntPrFltH& EdgeBtwH, const TFltV& Attr, const bool& IsDir, const double& NodeFrac) { TIntFltH NodeBtwH; TIntV NIdV; Graph->GetNIdV(NIdV); if (NodeFrac < 1.0) { // calculate beetweenness centrality for a subset of nodes NIdV.Shuffle(TInt::Rnd); for (int i = int((1.0-NodeFrac)*NIdV.Len()); i > 0; i--) { NIdV.DelLast(); } } GetWeightedBetweennessCentr(Graph, NIdV, NodeBtwH, IsDir, false, EdgeBtwH, true, Attr); } }; // namespace TSnap
35.165509
210
0.453313
dkw-aau
90f393f374347ea6a5f0ca26af15137e11c1348f
3,135
cpp
C++
modules/task_3/oganyan_r_global_search/main.cpp
orcyyy/pp_2020_autumn_engineer-1
14cb1248b8b765a02eaa4c73f06807c250545491
[ "BSD-3-Clause" ]
null
null
null
modules/task_3/oganyan_r_global_search/main.cpp
orcyyy/pp_2020_autumn_engineer-1
14cb1248b8b765a02eaa4c73f06807c250545491
[ "BSD-3-Clause" ]
1
2020-12-27T20:31:37.000Z
2020-12-27T20:31:37.000Z
modules/task_3/oganyan_r_global_search/main.cpp
schelyanskovan/pp_2020_autumn_engineer
2bacf7ccaf3c638044c41068565a693ac4fae828
[ "BSD-3-Clause" ]
1
2021-03-29T10:15:47.000Z
2021-03-29T10:15:47.000Z
// Copyright by Oganyan Robert 2020 #include <gtest/gtest.h> #include <gtest-mpi-listener.hpp> #include <iostream> #include "../../../modules/task_3/oganyan_r_global_search/functions.h" #include "../../../modules/task_3/oganyan_r_global_search/global_search.h" using std::cout; using std::endl; void CreateTest(int num_fun, double x_left, double x_right, double y_left, double y_right, double ans_minimum, dpair ans_pos, int repeat = 200) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); double time_start{MPI_Wtime()}; double res_par{ParallelGlobalSearch(num_fun, x_left, x_right, y_left, y_right)}; double time_par_end{MPI_Wtime()}; auto par_time{time_par_end - time_start}; cout << std::fixed << std::setprecision(10); if (rank == 0) { cout << " Test number: " << num_fun << endl; cout << "-#-#-#-#-#-# Parallel Time: " << par_time << " -#-#-#-#-#-#" << endl; cout << "-#-#-#-#-#-# Parallel Result: " << res_par << " -#-#-#-#-#-#" << endl; time_start = MPI_Wtime(); double res_seq{SequentialGlobalSearch(num_fun, x_left, x_right, y_left, y_right, repeat)}; const double time_end_s{MPI_Wtime()}; cout << "-#-#-#-#-#-# Sequential Time :" << time_end_s - time_start << " -#-#-#-#-#-#" << endl; cout << "-#-#-#-#-#-# Sequential Result :" << res_seq << " -#-#-#-#-#-#" << endl; ASSERT_EQ(1, abs(ans_minimum - res_par) <= 0.15); } } TEST(Parallel_Operations_MPI, Test_first_fun) { const std::function<double(dpair)> func{fun_first}; const std::function<dpair(dpair)> grad{grad_first}; CreateTest(1, -200.0, 200.0, -200.0, 200.0, 0.0, {0.0, 0.0}, 300); } TEST(Parallel_Operations_MPI, Test_second_fun) { const std::function<double(dpair)> func {fun_second}; const std::function<dpair(dpair)> grad { grad_second }; CreateTest(2, -300.0, 300.0, -200.0, 600.0, -2.0, {0.0, 1.0}, 100); } TEST(Parallel_Operations_MPI, Test_third_fun) { const std::function<double(dpair)> func {fun_third}; const std::function<dpair(dpair)> grad { grad_third }; double anss = -8.0 / (2.71828 * 2.71828); CreateTest(3, -10.0, 10.0, -10.0, 10.0, anss, {-4.0, 2.0}); } TEST(Parallel_Operations_MPI, Test_forth_fun) { const std::function<double(dpair)> func {fun_forth}; const std::function<dpair(dpair)> grad { grad_forth }; CreateTest(4, -200.0, 300.0, -200.0, 300.0, -0.125, {1.0, 0.5}, 100); } TEST(Parallel_Operations_MPI, Test_fifth_fun) { const std::function<double(dpair)> func {fun_fifth}; const std::function<dpair(dpair)> grad { grad_fifth }; CreateTest(5, -100.0, 100.0, -200.0, 300.0, 0.0, {3.0, 2.0}); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); MPI_Init(&argc, &argv); ::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment); ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); listeners.Release(listeners.default_result_printer()); listeners.Release(listeners.default_xml_generator()); listeners.Append(new GTestMPIListener::MPIMinimalistPrinter); return RUN_ALL_TESTS(); }
37.321429
99
0.652632
orcyyy
90f48bfbae987cbc20421d1ad70fed346527945d
37,683
cpp
C++
src/prod/src/Hosting2/FabricUpgradeImpl.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
1
2020-06-15T04:33:36.000Z
2020-06-15T04:33:36.000Z
src/prod/src/Hosting2/FabricUpgradeImpl.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
null
null
null
src/prod/src/Hosting2/FabricUpgradeImpl.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
null
null
null
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" #include "Common/FabricGlobals.h" using namespace std; using namespace Common; using namespace ServiceModel; using namespace Hosting2; using namespace Management; using namespace ImageModel; StringLiteral const TraceType("FabricUpgradeImpl"); class FabricUpgradeImpl::ValidateFabricUpgradeAsyncOperation : public AsyncOperation, protected TextTraceComponent<TraceTaskCodes::Hosting> { DENY_COPY(ValidateFabricUpgradeAsyncOperation) public: ValidateFabricUpgradeAsyncOperation( FabricUpgradeImpl & owner, FabricVersionInstance const & currentFabricVersionInstance, FabricUpgradeSpecification const & fabricUpgradeSpec, AsyncCallback const & callback, AsyncOperationSPtr const & parent) : AsyncOperation(callback, parent), owner_(owner), currentFabricVersionInstance_(currentFabricVersionInstance), fabricUpgradeSpec_(fabricUpgradeSpec), shouldRestartReplica_(false), fabricDeployerProcessWait_(), fabricDeployerProcessHandle_() { } virtual ~ValidateFabricUpgradeAsyncOperation() { } static ErrorCode End( __out bool & shouldRestartReplica, AsyncOperationSPtr const & operation) { auto thisPtr = AsyncOperation::End<ValidateFabricUpgradeAsyncOperation>(operation); shouldRestartReplica = thisPtr->shouldRestartReplica_; return thisPtr->Error; } protected: virtual void OnStart(AsyncOperationSPtr const & thisSPtr) { WriteNoise( TraceType, owner_.Root.TraceId, "ValidateAndAnalyzeFabricUpgradeImpl: CurrentVersion: {0}, TargetVersion: {1}", currentFabricVersionInstance_, FabricVersionInstance(fabricUpgradeSpec_.Version, fabricUpgradeSpec_.InstanceId)); if(currentFabricVersionInstance_.Version.CodeVersion != fabricUpgradeSpec_.Version.CodeVersion) { shouldRestartReplica_ = true; TryComplete(thisSPtr, ErrorCodeValue::Success); return; } if(currentFabricVersionInstance_.Version.ConfigVersion != fabricUpgradeSpec_.Version.ConfigVersion) { HandleUPtr fabricDeployerThreadHandle; wstring tempOutputFile = File::GetTempFileNameW(owner_.hosting_.NodeWorkFolder); wstring tempErrorFile = File::GetTempFileNameW(owner_.hosting_.NodeWorkFolder); wstring commandLineArguments = wformatString( Constants::FabricDeployer::ValidateAndAnalyzeArguments, owner_.fabricUpgradeRunLayout_.GetClusterManifestFile(fabricUpgradeSpec_.Version.ConfigVersion.ToString()), owner_.hosting_.NodeName, owner_.hosting_.NodeType, tempOutputFile, tempErrorFile); WriteInfo( TraceType, owner_.Root.TraceId, "ValidateAndAnalyzeFabricUpgradeImpl: FabricDeployerProcess called with {0}", commandLineArguments); wstring deployerPath = Path::Combine(Environment::GetExecutablePath(), Constants::FabricDeployer::ExeName); vector<wchar_t> envBlock(0); #if defined(PLATFORM_UNIX) // Environment map is only needed in linux since the environment is not // passed in by default in linux EnvironmentMap environmentMap; auto getEnvResult = Environment::GetEnvironmentMap(environmentMap); auto createEnvError = ProcessUtility::CreateDefaultEnvironmentBlock(envBlock); if (!createEnvError.IsSuccess()) { WriteWarning( TraceType, owner_.Root.TraceId, "Failed to create EnvironmentBlock for ValidateFabricUpgradeAsyncOperation due to {0}", createEnvError); TryComplete(thisSPtr, createEnvError); return; } #endif pid_t pid = 0; auto error = ProcessUtility::CreateProcessW( ProcessUtility::GetCommandLine(deployerPath, commandLineArguments), L"", envBlock, DETACHED_PROCESS /* Do not inherit console */, fabricDeployerProcessHandle_, fabricDeployerThreadHandle, pid); if (!error.IsSuccess()) { WriteWarning( TraceType, owner_.Root.TraceId, "ValidateAndAnalyzeFabricUpgradeImpl: Create FabricDeployerProcess failed with {0}", error); TryComplete(thisSPtr, error); return; } fabricDeployerProcessWait_ = ProcessWait::CreateAndStart( Handle(fabricDeployerProcessHandle_->Value, Handle::DUPLICATE()), pid, [this, thisSPtr, tempOutputFile, tempErrorFile](pid_t, ErrorCode const & waitResult, DWORD exitCode) { OnFabricDeployerProcessTerminated(thisSPtr, waitResult, exitCode, tempOutputFile, tempErrorFile); }); } else { TryComplete(thisSPtr, ErrorCodeValue::Success); return; } } void OnFabricDeployerProcessTerminated( AsyncOperationSPtr const & thisSPtr, Common::ErrorCode const & waitResult, DWORD fabricDeployerExitCode, wstring const & tempOutputFile, wstring const & tempErrorFile) { if(!waitResult.IsSuccess()) { TryComplete(thisSPtr, waitResult); return; } // Exit Code 1(256) and 2(512) is used by deployer currently to indicate whether restart is required or not // Exit Code 2 is restart not required and treated as success. On windows the exit code can go below 0 but // on linux it does not so basically anything other than 0, 1(256) or 2(512) is an error and we try to read the error file ErrorCode error; if (fabricDeployerExitCode != 0 && fabricDeployerExitCode != Constants::FabricDeployer::ExitCode_RestartRequired && fabricDeployerExitCode != Constants::FabricDeployer::ExitCode_RestartNotRequired) { wstring fileContent; error = owner_.ReadFabricDeployerTempFile(tempErrorFile, fileContent); if(error.IsSuccess()) { error = ErrorCode(ErrorCodeValue::FabricNotUpgrading, move(fileContent)); } else { WriteWarning( TraceType, owner_.Root.TraceId, "CheckIfRestartRequired: Could not read error file: {0}", tempErrorFile); } } WriteTrace( error.ToLogLevel(), TraceType, owner_.Root.TraceId, "ValidateAndAnalyzeFabricUpgradeImpl: FabricDeployer process terminated. CurrentVersion: {0}, TargetVersion: {1}. ExitCode:{2}. Error: {3}.", currentFabricVersionInstance_, FabricVersionInstance(fabricUpgradeSpec_.Version, fabricUpgradeSpec_.InstanceId), fabricDeployerExitCode, error); if(!error.IsSuccess()) { TryComplete(thisSPtr, error); return; } ASSERT_IF( Constants::FabricDeployer::ExitCode_RestartRequired == fabricDeployerExitCode && !File::Exists(tempOutputFile), "The output file should be generated by deployer when exit code is ExitCode_RestartRequired. File:{0}", tempOutputFile); bool staticParameterModified = false; if(Constants::FabricDeployer::ExitCode_RestartRequired == fabricDeployerExitCode) { error = CheckIfRestartRequired(tempOutputFile, staticParameterModified); WriteTrace( error.ToLogLevel(), TraceType, owner_.Root.TraceId, "CheckIfRestartRequired returned {0}. CurrentVersion: {1}, TargetVersion: {2}.", error, currentFabricVersionInstance_, FabricVersionInstance(fabricUpgradeSpec_.Version, fabricUpgradeSpec_.InstanceId)); if(!error.IsSuccess()) { TryComplete(thisSPtr, error); return; } } if(staticParameterModified || fabricUpgradeSpec_.UpgradeType == UpgradeType::Rolling_ForceRestart) { this->shouldRestartReplica_ = true; } TryComplete(thisSPtr, ErrorCodeValue::Success); } ErrorCode CheckIfRestartRequired(wstring const & validateOutputFileName, __out bool & staticParameterModified) { staticParameterModified = false; wstring fileContent; auto error = owner_.ReadFabricDeployerTempFile(validateOutputFileName, fileContent); if(!error.IsSuccess()) { WriteWarning( TraceType, owner_.Root.TraceId, "CheckIfRestartRequired: Could not read output file: {0}", validateOutputFileName); return error; } vector<wstring> tokens; #ifdef PLATFORM_UNIX StringUtility::SplitOnString<wstring>(StringUtility::ToWString(fileContent), tokens, L"\n", false); #else StringUtility::SplitOnString<wstring>(StringUtility::ToWString(fileContent), tokens, L"\r\n", false); #endif ASSERT_IF(tokens.size() == 0 || tokens.size() % 4 != 0, "The fileContent is invalid : {0}", fileContent); int index = 0; do { wstring section = tokens[index++]; wstring key = tokens[index++]; wstring value = tokens[index++]; bool isEncrypted = StringUtility::AreEqualCaseInsensitive(tokens[index++], L"true"); auto configStore = FabricGlobals::Get().GetConfigStore().Store; bool canUpgradeWithoutRestart = configStore->CheckUpdate( section, key, value, isEncrypted); WriteInfo( TraceType, owner_.Root.TraceId, "CheckIfRestartRequired: Section:{0}, Key:{1}, CanUpgradeWithoutRestart:{2}.", section, key, canUpgradeWithoutRestart); if(!canUpgradeWithoutRestart) { staticParameterModified = true; break; } } while(index < tokens.size()); return error; } virtual void OnCancel() { fabricDeployerProcessWait_->Cancel(); ErrorCode error; if(!::TerminateProcess(fabricDeployerProcessHandle_->Value, ProcessActivator::ProcessAbortExitCode)) { error = ErrorCode::FromWin32Error(); } WriteTrace( error.IsSuccess() ? LogLevel::Info : LogLevel::Warning, TraceType, owner_.Root.TraceId, "ValidateFabircUpgradeAsyncOperation OnCancel TerminateProcess: ErrorCode={0}", error); } private: FabricUpgradeImpl & owner_; FabricVersionInstance const currentFabricVersionInstance_; FabricUpgradeSpecification const fabricUpgradeSpec_; bool shouldRestartReplica_; ProcessWaitSPtr fabricDeployerProcessWait_; HandleUPtr fabricDeployerProcessHandle_; }; class FabricUpgradeImpl::FabricUpgradeAsyncOperation : public AsyncOperation, protected TextTraceComponent<TraceTaskCodes::Hosting> { DENY_COPY(FabricUpgradeAsyncOperation) public: FabricUpgradeAsyncOperation( FabricUpgradeImpl & owner, FabricVersionInstance const & currentFabricVersionInstance, FabricUpgradeSpecification const & fabricUpgradeSpec, AsyncCallback const & callback, AsyncOperationSPtr const & parent) : AsyncOperation(callback, parent), owner_(owner), currentFabricVersionInstance_(currentFabricVersionInstance), fabricUpgradeSpec_(fabricUpgradeSpec), timeoutHelper_(HostingConfig::GetConfig().FabricUpgradeTimeout) { } virtual ~FabricUpgradeAsyncOperation() { } static ErrorCode End(AsyncOperationSPtr const & operation) { auto thisPtr = AsyncOperation::End<FabricUpgradeAsyncOperation>(operation); return thisPtr->Error; } protected: virtual void OnStart(AsyncOperationSPtr const & thisSPtr) { bool hasCodeChanged = (currentFabricVersionInstance_.Version.CodeVersion != fabricUpgradeSpec_.Version.CodeVersion); bool hasConfigChanged = (currentFabricVersionInstance_.Version.ConfigVersion != fabricUpgradeSpec_.Version.ConfigVersion); bool hasInstanceIdChanged = (currentFabricVersionInstance_.InstanceId != fabricUpgradeSpec_.InstanceId); WriteInfo( TraceType, owner_.Root.TraceId, "FabricUpgradeImpl: CurrentVersion: {0}, TargetVersion: {1}", currentFabricVersionInstance_, FabricVersionInstance(fabricUpgradeSpec_.Version, fabricUpgradeSpec_.InstanceId)); if(hasCodeChanged) { this->CodeUpgrade(thisSPtr); } else if(hasConfigChanged) { this->ConfigUpgrade(thisSPtr, false /*instanceIdOnlyUpgrade*/); } else if(hasInstanceIdChanged) { this->ConfigUpgrade(thisSPtr, true /*instanceIdOnlyUpgrade*/); } else { TryComplete(thisSPtr, ErrorCodeValue::FabricAlreadyInTargetVersion); return; } } virtual void OnCancel() { AsyncOperation::Cancel(); } void CodeUpgrade(AsyncOperationSPtr const & thisSPtr) { wstring dataRoot, logRoot; auto error = FabricEnvironment::GetFabricDataRoot(dataRoot); if(!error.IsSuccess()) { WriteInfo( TraceType, owner_.Root.TraceId, "Error getting FabricDataRoot. Error:{0}", error); TryComplete(thisSPtr, error); return; } error = FabricEnvironment::GetFabricLogRoot(logRoot); if(!error.IsSuccess()) { WriteInfo( TraceType, owner_.Root.TraceId, "Error getting FabricLogRoot. Error:{0}", error); TryComplete(thisSPtr, error); return; } FabricDeploymentSpecification fabricDeploymentSpec(dataRoot, logRoot); // Write the installer script only if the target code package is a MSI or Cab File bool useFabricInstallerService = false; bool isCabFilePresent = false; wstring installerFilePath = owner_.fabricUpgradeRunLayout_.GetPatchFile(fabricUpgradeSpec_.Version.CodeVersion.ToString()); bool isInstallerFilePresent = File::Exists(installerFilePath); wstring downloadedFabricPackage(L""); if (isInstallerFilePresent) { #if defined(PLATFORM_UNIX) downloadedFabricPackage = move(installerFilePath); #else DWORD useFabricInstallerSvc; RegistryKey regKey(FabricConstants::FabricRegistryKeyPath, true, true); if (regKey.IsValid && regKey.GetValue(FabricConstants::UseFabricInstallerSvcKeyName, useFabricInstallerSvc) && useFabricInstallerSvc == 1UL) { downloadedFabricPackage = move(installerFilePath); useFabricInstallerService = true; WriteInfo( TraceType, owner_.Root.TraceId, "Hosting CodeUpgrade MSI path using FabricInstallerSvc. MSI: {0}", downloadedFabricPackage); } #endif } else { downloadedFabricPackage = move(owner_.fabricUpgradeRunLayout_.GetCabPatchFile(fabricUpgradeSpec_.Version.CodeVersion.ToString())); isCabFilePresent = File::Exists(downloadedFabricPackage); if (isCabFilePresent) { bool containsWUfile = false; int errorCode = CabOperations::ContainsFile(downloadedFabricPackage, *Constants::FabricUpgrade::FabricWindowsUpdateContainedFile, containsWUfile); if (errorCode != S_OK) { error = ErrorCode::FromWin32Error(errorCode); WriteTrace( error.ToLogLevel(), TraceType, owner_.Root.TraceId, "CabOperations::ContainsFile : Error:{0}", error); TryComplete(thisSPtr, error); return; } useFabricInstallerService = !containsWUfile; // WU file identifies package as incompatible with FabricInstallerSvc } else { // Directory package no longer supported WriteError(TraceType, "CodeUpgrade did not find CAB/MSI package for the given version."); TryComplete(thisSPtr, ErrorCode(ErrorCodeValue::InvalidArgument)); return; } } wstring installationScriptFilePath(L""); if (useFabricInstallerService) { // If Fabric installer service is running, wait till it stops //LINUXTODO #if !defined(PLATFORM_UNIX) ServiceController sc(Constants::FabricUpgrade::FabricInstallerServiceName); error = sc.WaitForServiceStop(timeoutHelper_.GetRemainingTime()); if (!error.IsSuccess() && !error.IsWin32Error(ERROR_SERVICE_DOES_NOT_EXIST)) { WriteWarning( TraceType, owner_.Root.TraceId, "Error {0} while waiting for Fabric installer service to stop", error); TryComplete(thisSPtr, error); return; } #endif } else { installationScriptFilePath = fabricDeploymentSpec.GetInstallerScriptFile(owner_.hosting_.NodeName); wstring installationLogFilePath = fabricDeploymentSpec.GetInstallerLogFile(owner_.hosting_.NodeName, fabricUpgradeSpec_.Version.CodeVersion.ToString()); error = WriteInstallationScriptFile(installationScriptFilePath, installationLogFilePath, isCabFilePresent); WriteTrace( error.ToLogLevel(), TraceType, owner_.Root.TraceId, "WriteInstallationScriptFile : Error:{0}", error); if (!error.IsSuccess()) { TryComplete(thisSPtr, error); return; } } wstring targetInformationFilePath = fabricDeploymentSpec.GetTargetInformationFile(); error = WriteTargetInformationFile(targetInformationFilePath, downloadedFabricPackage, useFabricInstallerService); WriteTrace( error.ToLogLevel(), TraceType, owner_.Root.TraceId, "WriteTargetInformationFile : Error:{0}", error); if (!error.IsSuccess()) { TryComplete(thisSPtr, error); return; } #if defined(PLATFORM_UNIX) wstring upgradeArgs = targetInformationFilePath;/* arguments */ #else wstring upgradeArgs = L"" /* arguments */; #endif if (!useFabricInstallerService) { WriteNoise( TraceType, owner_.Root.TraceId, "Begin(FabricActivatorClient FabricUpgrade): InstallationScript:{0}", installationScriptFilePath); } auto operation = owner_.hosting_.FabricActivatorClientObj->BeginFabricUpgrade( useFabricInstallerService, installationScriptFilePath, upgradeArgs /* arguments */, downloadedFabricPackage, [this, useFabricInstallerService](AsyncOperationSPtr const & operation) { this->FinishCodeUpgrade(operation, useFabricInstallerService, false); }, thisSPtr); FinishCodeUpgrade(operation, useFabricInstallerService, true); } void FinishCodeUpgrade(AsyncOperationSPtr const & operation, bool useFabricInstallerService, bool expectedCompletedSynhronously) { if (operation->CompletedSynchronously != expectedCompletedSynhronously) { return; } auto error = owner_.hosting_.FabricActivatorClientObj->EndFabricUpgrade(operation); // The assert is only valid if the upgrade was done using a MSI. if (!useFabricInstallerService) { ASSERT_IF(error.IsSuccess(), "The FabricUpgrade call for code should return only with failure. In case of success, the host will be killed."); } WriteTrace( error.ToLogLevel(), TraceType, owner_.Root.TraceId, "End(FabricActivatorClient FabricUpgrade): {0}", error); TryComplete(operation->Parent, error); } ErrorCode WriteTargetInformationFile(wstring const & targetInformationFilePath, wstring const & targetPackagePath, bool) { wstring currentInstallationElement(L""); wstring currentClusterManifestFile = move(owner_.fabricUpgradeRunLayout_.GetClusterManifestFile(currentFabricVersionInstance_.Version.ConfigVersion.ToString())); bool isCurrentMsi = false; bool isCurrentCab = false; bool isWindowsUpdate = false; // If the current version files are not provisioned Rollback will not be supported // Current Installation element is set only if both the cluster manifest and MSI/CodePackage are present if (File::Exists(currentClusterManifestFile)) { wstring currentCodeVersion = move(currentFabricVersionInstance_.Version.CodeVersion.ToString()); wstring currentMsiPackagePath = move(owner_.fabricUpgradeRunLayout_.GetPatchFile(currentCodeVersion)); wstring currentCabPackagePath = move(owner_.fabricUpgradeRunLayout_.GetCabPatchFile(currentCodeVersion)); wstring currentPackagePath(L""); if (File::Exists(currentMsiPackagePath)) { currentPackagePath = currentMsiPackagePath; isCurrentMsi = true; } else if (File::Exists(currentCabPackagePath)) { currentPackagePath = currentCabPackagePath; isCurrentCab = true; } // If !isCurrentCab && !isCurrentMsi then we skip writing CurrentInstallation for TargetInformationFile if (isCurrentCab) { int errorCode = CabOperations::ContainsFile(currentPackagePath, *Constants::FabricUpgrade::FabricWindowsUpdateContainedFile, isWindowsUpdate); if (errorCode != S_OK) { auto error = ErrorCode::FromWin32Error(errorCode); WriteTrace( error.ToLogLevel(), TraceType, owner_.Root.TraceId, "WriteTargetInformationFile CabOperations::ContainsFile : Error:{0}", error); return error; } if (!isWindowsUpdate) { // Current code package exists and is a XCOPY package currentInstallationElement = wformatString( Constants::FabricUpgrade::CurrentInstallationElementForXCopy, currentFabricVersionInstance_.InstanceId, currentFabricVersionInstance_.Version.CodeVersion.ToString(), currentClusterManifestFile, currentPackagePath, owner_.hosting_.NodeName, Constants::FabricSetup::ExeName, Constants::FabricSetup::UpgradeArguments, Constants::FabricSetup::ExeName, Constants::FabricSetup::UndoUpgradeArguments); } } if (isCurrentMsi || isWindowsUpdate) { currentInstallationElement = wformatString( Constants::FabricUpgrade::CurrentInstallationElement, currentFabricVersionInstance_.InstanceId, currentFabricVersionInstance_.Version.CodeVersion.ToString(), currentClusterManifestFile, currentPackagePath, owner_.hosting_.NodeName); } if (currentInstallationElement == L"") { WriteWarning(TraceType, "WriteTargetInformationFile did not find CAB/MSI package for the given version. Skip writing CurrentInstallation element."); } } wstring targetInstallationElement(L""); wstring targetCodeVersion = fabricUpgradeSpec_.Version.CodeVersion.ToString(); if (!isWindowsUpdate && Path::GetExtension(targetPackagePath) == L".cab") { // Target code package is a XCOPY package targetInstallationElement = wformatString( Constants::FabricUpgrade::TargetInstallationElementForXCopy, fabricUpgradeSpec_.InstanceId, fabricUpgradeSpec_.Version.CodeVersion.ToString(), owner_.fabricUpgradeRunLayout_.GetClusterManifestFile(fabricUpgradeSpec_.Version.ConfigVersion.ToString()), targetPackagePath, owner_.hosting_.NodeName, Constants::FabricSetup::ExeName, Constants::FabricSetup::UpgradeArguments, Constants::FabricSetup::ExeName, Constants::FabricSetup::UndoUpgradeArguments); } else { targetInstallationElement = wformatString( Constants::FabricUpgrade::TargetInstallationElement, fabricUpgradeSpec_.InstanceId, fabricUpgradeSpec_.Version.CodeVersion.ToString(), owner_.fabricUpgradeRunLayout_.GetClusterManifestFile(fabricUpgradeSpec_.Version.ConfigVersion.ToString()), targetPackagePath, owner_.hosting_.NodeName); } #if defined(PLATFORM_UNIX) wstring targetInformationContentUtf16 = wformatString( Constants::FabricUpgrade::TargetInformationXmlContent, currentInstallationElement, targetInstallationElement); string targetInformationContent = StringUtility::Utf16ToUtf8(targetInformationContentUtf16); #else wstring targetInformationContent = wformatString( Constants::FabricUpgrade::TargetInformationXmlContent, currentInstallationElement, targetInstallationElement); #endif FileWriter fileWriter; auto error = fileWriter.TryOpen(targetInformationFilePath); if(!error.IsSuccess()) { return error; } #if defined(PLATFORM_UNIX) fileWriter.WriteAsciiBuffer(targetInformationContent.c_str(), targetInformationContent.size()); #else fileWriter.WriteUnicodeBuffer(targetInformationContent.c_str(), targetInformationContent.size()); #endif fileWriter.Close(); return ErrorCodeValue::Success; } ErrorCode WriteInstallationScriptFile(wstring const & installationScriptFilePath, wstring const & installationLogFilePath, bool const & useCabFile) { if (File::Exists(installationScriptFilePath)) { File::Delete2(installationScriptFilePath).ReadValue(); } #if defined(PLATFORM_UNIX) wstring installerFile = Path::Combine(Environment::GetExecutablePath(), Constants::FabricUpgrade::LinuxPackageInstallerScriptFileName); return File::Copy(installerFile, installationScriptFilePath); #else FileWriter fileWriter; auto error = fileWriter.TryOpen(installationScriptFilePath); if(!error.IsSuccess()) { return error; } wstring installCommand = L""; wstring execCommand = L""; if (useCabFile) { wstring currentFabricCodeVersion = currentFabricVersionInstance_.Version.CodeVersion.ToString(); wstring upgradeCodeVersion = fabricUpgradeSpec_.Version.CodeVersion.ToString(); string stopFabricHostSvcAnsi; StringUtility::UnicodeToAnsi(*Constants::FabricUpgrade::StopFabricHostServiceCommand, stopFabricHostSvcAnsi); fileWriter.WriteLine(stopFabricHostSvcAnsi); if (currentFabricCodeVersion > upgradeCodeVersion) { installCommand = wformatString( Constants::FabricUpgrade::DISMExecUnInstallCommand, owner_.fabricUpgradeRunLayout_.GetCabPatchFile(currentFabricCodeVersion), installationLogFilePath); } else { installCommand = wformatString( Constants::FabricUpgrade::DISMExecCommand, owner_.fabricUpgradeRunLayout_.GetCabPatchFile(upgradeCodeVersion), installationLogFilePath); } } else { installCommand = wformatString( Constants::FabricUpgrade::MSIExecCommand, owner_.fabricUpgradeRunLayout_.GetPatchFile(fabricUpgradeSpec_.Version.CodeVersion.ToString()), installationLogFilePath); } string installCommandAnsi; StringUtility::UnicodeToAnsi(installCommand, installCommandAnsi); string startFabricHostSvcAnsi; StringUtility::UnicodeToAnsi(*Constants::FabricUpgrade::StartFabricHostServiceCommand, startFabricHostSvcAnsi); fileWriter.WriteLine(installCommandAnsi); fileWriter.WriteLine(startFabricHostSvcAnsi); fileWriter.Close(); return ErrorCodeValue::Success; #endif } void ConfigUpgrade(AsyncOperationSPtr const & thisSPtr, bool instanceIdOnlyUpgrade) { wstring tempErrorFile = File::GetTempFileNameW(owner_.hosting_.NodeWorkFolder); wstring pathToClusterManifest = owner_.fabricUpgradeRunLayout_.GetClusterManifestFile(fabricUpgradeSpec_.Version.ConfigVersion.ToString()); wstring upgradeArgument; if(instanceIdOnlyUpgrade) { upgradeArgument = wformatString( Constants::FabricDeployer::InstanceIdOnlyUpgradeArguments, fabricUpgradeSpec_.Version.CodeVersion.ToString(), fabricUpgradeSpec_.InstanceId, owner_.hosting_.NodeName, tempErrorFile); } else { upgradeArgument = wformatString( Constants::FabricDeployer::ConfigUpgradeArguments, pathToClusterManifest, fabricUpgradeSpec_.Version.CodeVersion.ToString(), fabricUpgradeSpec_.InstanceId, owner_.hosting_.NodeName, tempErrorFile); } wstring deployerPath = Path::Combine(Environment::GetExecutablePath(), Constants::FabricDeployer::ExeName); WriteInfo( TraceType, owner_.Root.TraceId, "Begin(FabricActivatorClient FabricUpgrade): Program:{0}, Arguments:{1}", deployerPath, upgradeArgument); auto operation = owner_.hosting_.FabricActivatorClientObj->BeginFabricUpgrade( false, deployerPath, upgradeArgument, L"", [this, tempErrorFile](AsyncOperationSPtr const & operation) { this->FinishConfigUpgrade(operation, false, tempErrorFile); }, thisSPtr); FinishConfigUpgrade(operation, true, tempErrorFile); } void FinishConfigUpgrade(AsyncOperationSPtr const & operation, bool expectedCompletedSynhronously, wstring const & tempErrorFile) { if (operation->CompletedSynchronously != expectedCompletedSynhronously) { return; } auto error = owner_.hosting_.FabricActivatorClientObj->EndFabricUpgrade(operation); if(!error.IsSuccess()) { wstring fileContent; auto fileReadError = owner_.ReadFabricDeployerTempFile(tempErrorFile, fileContent); if(fileReadError.IsSuccess()) { error = ErrorCode(error.ReadValue(), move(fileContent)); } else { WriteInfo(TraceType, owner_.Root.TraceId, "End(FabricActivatorClient FabricUpgrade): Could not read FabricDeployer error file."); } } WriteTrace( error.ToLogLevel(), TraceType, owner_.Root.TraceId, "End(FabricActivatorClient FabricUpgrade): {0}", error); TryComplete(operation->Parent, error); } private: FabricUpgradeImpl & owner_; FabricVersionInstance const currentFabricVersionInstance_; FabricUpgradeSpecification const fabricUpgradeSpec_; TimeoutHelper timeoutHelper_; }; FabricUpgradeImpl::FabricUpgradeImpl( ComponentRoot const & root, __in HostingSubsystem & hosting) : RootedObject(root), hosting_(hosting), fabricUpgradeRunLayout_(hosting.FabricUpgradeDeploymentFolder) { } FabricUpgradeImpl::~FabricUpgradeImpl() { } AsyncOperationSPtr FabricUpgradeImpl::BeginDownload( FabricVersion const & fabricVersion, AsyncCallback const & callback, AsyncOperationSPtr const & parent) { return this->hosting_.DownloadManagerObj->BeginDownloadFabricUpgradePackage( fabricVersion, callback, parent); } ErrorCode FabricUpgradeImpl::EndDownload( AsyncOperationSPtr const & operation) { return this->hosting_.DownloadManagerObj->EndDownloadFabricUpgradePackage(operation); } AsyncOperationSPtr FabricUpgradeImpl::BeginValidateAndAnalyze( FabricVersionInstance const & currentFabricVersionInstance, FabricUpgradeSpecification const & fabricUpgradeSpec, AsyncCallback const & callback, Common::AsyncOperationSPtr const & parent) { return AsyncOperation::CreateAndStart<ValidateFabricUpgradeAsyncOperation>( *this, currentFabricVersionInstance, fabricUpgradeSpec, callback, parent); } ErrorCode FabricUpgradeImpl::EndValidateAndAnalyze( __out bool & shouldCloseReplica, AsyncOperationSPtr const & operation) { return ValidateFabricUpgradeAsyncOperation::End(shouldCloseReplica, operation); } AsyncOperationSPtr FabricUpgradeImpl::BeginUpgrade( FabricVersionInstance const & currentFabricVersionInstance, FabricUpgradeSpecification const & fabricUpgradeSpec, AsyncCallback const & callback, AsyncOperationSPtr const & parent) { return AsyncOperation::CreateAndStart<FabricUpgradeAsyncOperation>( *this, currentFabricVersionInstance, fabricUpgradeSpec, callback, parent); } ErrorCode FabricUpgradeImpl::EndUpgrade( AsyncOperationSPtr const & operation) { return FabricUpgradeAsyncOperation::End(operation); } ErrorCode FabricUpgradeImpl::ReadFabricDeployerTempFile(std::wstring const & filePath, std::wstring & fileContent) { File file; auto error = file.TryOpen( filePath, FileMode::Open, FileAccess::Read, FileShare::Read); if (!error.IsSuccess()) { TraceWarning( TraceTaskCodes::Hosting, TraceType, Root.TraceId, "Failed to open file '{0}'. Error: {1}", filePath, error); return ErrorCode(error.ReadValue(), StringResource::Get(IDS_HOSTING_FabricDeployed_Output_Read_Failed)); } int bytesRead = 0; int fileSize = static_cast<int>(file.size()); vector<byte> buffer(fileSize); if((bytesRead = file.TryRead(reinterpret_cast<void*>(buffer.data()), fileSize)) > 0) { buffer.push_back(0); buffer.push_back(0); // skip byte-order mark fileContent = wstring(reinterpret_cast<wchar_t *>(&buffer[2])); error = ErrorCodeValue::Success; } else { TraceWarning( TraceTaskCodes::Hosting, TraceType, Root.TraceId, "Failed to read file '{0}'.", filePath); error = ErrorCode(ErrorCodeValue::OperationFailed, StringResource::Get(IDS_HOSTING_FabricDeployed_Output_Read_Failed)); } file.Close2(); File::Delete2(filePath, true /*deleteReadOnlyFiles*/); return error; }
38.256853
220
0.619616
vishnuk007
90f4baba0b86bb00ab5acbc2c492e5f808627a28
12,211
cpp
C++
test/dualtime/dualtimeExpDecayTest.cpp
MaxZZG/ExprLib
c35e361ef6af365e7cd6afca6548595693bd149a
[ "MIT" ]
null
null
null
test/dualtime/dualtimeExpDecayTest.cpp
MaxZZG/ExprLib
c35e361ef6af365e7cd6afca6548595693bd149a
[ "MIT" ]
null
null
null
test/dualtime/dualtimeExpDecayTest.cpp
MaxZZG/ExprLib
c35e361ef6af365e7cd6afca6548595693bd149a
[ "MIT" ]
null
null
null
#include <expression/dualtime/FixedPointBDFDualTimeIntegrator.h> #include <expression/dualtime/VariableImplicitBDFDualTimeIntegrator.h> #include <expression/dualtime/BlockImplicitBDFDualTimeIntegrator.h> #include <spatialops/structured/Grid.h> #include <spatialops/structured/FVStaggered.h> #include <spatialops/structured/FieldComparisons.h> #include <test/TestHelper.h> #include "ExpDecay.h" #include <expression/Functions.h> #include <expression/ExpressionTree.h> #include <expression/ExprPatch.h> #include <expression/matrix-assembly/SparseMatrix.h> #include <expression/matrix-assembly/ScaledIdentityMatrix.h> #include <boost/program_options.hpp> #include <iostream> #include <fstream> using std::cout; using std::endl; namespace po = boost::program_options; namespace so = SpatialOps; typedef so::SVolField FieldT; enum IntegratorType{ FIXED_POINT, VARIABLE_IMPLICIT, BLOCK_IMPLICIT }; #define ASSEMBLER(MatrixT, FieldT, name) \ boost::shared_ptr<MatrixT<FieldT> > name = boost::make_shared<MatrixT<FieldT> >(); bool test( const IntegratorType integratorType ) { /* --------------------------------------------------------------- * domain, operators, field managers, etc setup * --------------------------------------------------------------- */ Expr::ExprPatch patch(1); SpatialOps::OperatorDatabase sodb; Expr::FieldManagerList& fml = patch.field_manager_list(); /* --------------------------------------------------------------- * variable and rhs names, jacobian, preconditioner * --------------------------------------------------------------- */ std::string phiName = "phi"; const Expr::Tag phiTag ( phiName, Expr::STATE_NONE ); const Expr::Tag phiNTag ( phiName, Expr::STATE_N ); const Expr::Tag phiRHSTag( phiName + "_rhs", Expr::STATE_NONE ); /* --------------------------------------------------------------- * build integrator, set constant physical and dual time step * --------------------------------------------------------------- */ const unsigned bdfOrder = 1; boost::shared_ptr<Expr::DualTime::BDFDualTimeIntegrator> integrator; const Expr::Tag dtTag( "timestep" , Expr::STATE_NONE ); const Expr::Tag dsTag( "dual_timestep", Expr::STATE_NONE ); double ds; // dual time step size switch( integratorType ){ case FIXED_POINT:{ ds = 0.01; integrator = boost::make_shared<Expr::DualTime::FixedPointBDFDualTimeIntegrator<FieldT> >( 0, "Fixed Point BDF", dtTag, dsTag, bdfOrder ); break; } case VARIABLE_IMPLICIT:{ ds = 1e16; integrator = boost::make_shared<Expr::DualTime::VariableImplicitBDFDualTimeIntegrator<FieldT> >( 0, "Variable Implicit BDF", dtTag, dsTag, bdfOrder ); break; } case BLOCK_IMPLICIT:{ ds = 1e16; integrator = boost::make_shared<Expr::DualTime::BlockImplicitBDFDualTimeIntegrator<FieldT> >( 0, "Block Implicit BDF", dtTag, dsTag, bdfOrder ); break; } } const double dt = 0.01; typedef Expr::ConstantExpr<so::SingleValueField>::Builder ConstantSingleValueT; integrator->set_physical_time_step_expression( new ConstantSingleValueT( dtTag, dt ) ); integrator->set_dual_time_step_expression ( new ConstantSingleValueT( dsTag, ds ) ); /* --------------------------------------------------------------- * register variables and RHS at STATE_NONE to the integrator * --------------------------------------------------------------- */ Expr::ExpressionFactory& factory = integrator->factory(); const double rateConst = 1.3; factory.register_expression( new ExpDecayRHS<FieldT>::Builder( rateConst, phiRHSTag, phiTag ) ); integrator->add_variable<FieldT>( phiTag.name(), phiRHSTag ); if( integratorType == BLOCK_IMPLICIT ){ // because we have a generic integrator type, we need to cast to block implicit type to continue typedef Expr::DualTime::BlockImplicitBDFDualTimeIntegrator<FieldT> BIType; auto biPtr = boost::dynamic_pointer_cast<BIType>( integrator ); // need to call this before indices can be obtained biPtr->done_adding_variables(); // these are maps from tags to indices std::map<Expr::Tag,int> varIndices = biPtr->variable_tag_index_map(); std::map<Expr::Tag,int> rhsIndices = biPtr->rhs_tag_index_map(); const int phiVarIdx = varIndices[phiTag]; const int phiRhsIdx = rhsIndices[phiRHSTag]; // build an assembler to compute the Jacobian matrix of the rhs to the governed variable ASSEMBLER( Expr::matrix::DenseSubMatrix, FieldT, jacobian ) jacobian->element<FieldT>(phiRhsIdx,phiVarIdx) = Expr::matrix::sensitivity( phiRHSTag, phiTag ); jacobian->finalize(); // need to finalize before using // build an identity matrix preconditioner ASSEMBLER( Expr::matrix::ScaledIdentityMatrix, FieldT, preconditioner ) preconditioner->finalize(); // need to finalize before using // set the Jacobian and preconditioner assemblers biPtr->set_jacobian_and_preconditioner( jacobian, preconditioner ); } /* --------------------------------------------------------------- * final integrator prep, must happen before setting initial conditions, and tree output * --------------------------------------------------------------- */ integrator->prepare_for_integration( fml, sodb, patch.field_info() ); integrator->lock_field<FieldT>( phiNTag ); integrator->lock_all_execution_fields(); integrator->copy_from_initial_condition_to_execution<FieldT>( phiNTag.name() ); { std::ofstream f("dualtimeExpDecayTest-integrator-tree.dot"); integrator->get_tree().write_tree( f ); } /* --------------------------------------------------------------- * set initial conditions with STATE_N * --------------------------------------------------------------- */ Expr::ExpressionFactory icFactory; const double phi0 = 1.0; const Expr::ExpressionID id = icFactory.register_expression( new Expr::ConstantExpr<FieldT>::Builder( phiNTag, phi0 ) ); Expr::ExpressionTree icTree( id, icFactory, patch.id() ); icTree.register_fields( fml ); icTree.bind_fields( fml ); icTree.execute_tree(); /* --------------------------------------------------------------- * set iteration counts, prep solution history file * --------------------------------------------------------------- */ const unsigned maxIterPerStep = 100; unsigned totalIter = 0; unsigned stepCount = 0; unsigned dualIter = 0; bool converged = false; std::ofstream fout("dualtimeExpDecayTest-solution-history.txt"); fout << " t \t c-exact \t c\n"; /* --------------------------------------------------------------- * perform the integration * --------------------------------------------------------------- */ const double tend = 2.0; double t = 0; while( t<tend ){ dualIter = 0; integrator->begin_time_step(); do{ integrator->advance_dualtime( converged ); dualIter++; totalIter++; } while( !converged && dualIter <= maxIterPerStep ); integrator->end_time_step(); stepCount++; t += dt; FieldT& phiN = fml.field_ref<FieldT>(phiNTag); phiN.add_device(CPU_INDEX); fout << std::scientific << std::setprecision(10) << t << "\t" << phi0*exp(-rateConst*t) << "\t" << phiN[0] << std::endl; } fout.close(); /* --------------------------------------------------------------- * process the test * --------------------------------------------------------------- */ TestHelper status(false); if( integratorType != FIXED_POINT ){ status( integrator->get_tree().computes_field( sens_tag( phiRHSTag, phiTag ) ), "Computes d phi_rhs / d phi" ); status( integrator->get_tree().computes_field( sens_tag(phiTag,phiTag) ), "Computes d phi / d phi" ); } const FieldT& phiPredicted = fml.field_ref<FieldT>( phiNTag ); const double phiFromMatlabCode = 0.075528511873306; SpatialOps::SpatFldPtr<FieldT> tmp = SpatialOps::SpatialFieldStore::get<FieldT>( phiPredicted ); *tmp <<= phiFromMatlabCode; status( SpatialOps::field_equal_abs( phiPredicted, *tmp, 1e-6 ), "phi value-check" ); const double meanStepPerIter = ( (double) totalIter ) / ( (double) stepCount ); switch( integratorType ){ case FIXED_POINT:{ const double meanStepPerIterFromMatlabCode = 27; status( std::abs( meanStepPerIter - meanStepPerIterFromMatlabCode ) < 1e-8, "fixed-point convergence rate check" ); break; } case VARIABLE_IMPLICIT:{ const double meanStepPerIterFromMatlabCode = 2; status( std::abs( meanStepPerIter - meanStepPerIterFromMatlabCode ) < 1e-8, "variable-implicit convergence rate check" ); break; } case BLOCK_IMPLICIT:{ const double meanStepPerIterFromMatlabCode = 2; status( std::abs( meanStepPerIter - meanStepPerIterFromMatlabCode ) < 1e-8, "block-implicit convergence rate check" ); break; } } return status.ok(); } int main( int iarg, char* carg[] ) { /* --------------------------------------------------------------- * initialization from command line options * --------------------------------------------------------------- */ bool fixedPoint = false; bool variableImplicit = false; bool blockImplicit = false; { po::options_description desc("Supported Options"); desc.add_options() ( "help", "print help message" ) ( "fixed-point", "Use the fixed point dualtime integration scheme") ( "variable-implicit", "Use the variable implicit dualtime integration scheme") ( "block-implicit", "Use the block implicit dualtime integration scheme");; po::variables_map args; try{ po::store( po::parse_command_line(iarg,carg,desc), args ); po::notify(args); } catch( std::exception& err ){ cout << "\nError parsing command line options.\n\n" << err.what() << "\n\n" << desc << "\n"; return -1; } if( args.count("help") ){ cout << desc << "\n"; return 1; } fixedPoint = args.count("fixed-point"); variableImplicit = args.count("variable-implicit"); blockImplicit = args.count("block-implicit"); if( !fixedPoint && !variableImplicit && !blockImplicit ){ std::cout << "Error: no dualtime integration method selected.\n" << desc << std::endl; return -1; } } try{ TestHelper status( true ); if( fixedPoint ) status( test( FIXED_POINT ), "Fixed Point" ); if( variableImplicit ) status( test( VARIABLE_IMPLICIT ), "Variable Implicit" ); if( blockImplicit ) status( test( BLOCK_IMPLICIT ), "Block Implicit" ); if( status.ok() ){ std::cout << "PASS\n"; return 0; } } catch( std::exception& err ){ std::cout << err.what() << std::endl; } std::cout << "FAIL\n"; return -1; }
37.804954
127
0.534518
MaxZZG
90f55aecb8cea0f565a768b770147bdb8ebb289e
2,583
cpp
C++
dev/test/so_5/environment/reg_coop_after_stop/main.cpp
ZaMaZaN4iK/sobjectizer
afe9fc4d9fac6157860ec4459ac7a129223be87c
[ "BSD-3-Clause" ]
272
2019-05-16T11:45:54.000Z
2022-03-28T09:32:14.000Z
dev/test/so_5/environment/reg_coop_after_stop/main.cpp
ZaMaZaN4iK/sobjectizer
afe9fc4d9fac6157860ec4459ac7a129223be87c
[ "BSD-3-Clause" ]
40
2019-10-29T18:19:18.000Z
2022-03-30T09:02:49.000Z
dev/test/so_5/environment/reg_coop_after_stop/main.cpp
ZaMaZaN4iK/sobjectizer
afe9fc4d9fac6157860ec4459ac7a129223be87c
[ "BSD-3-Clause" ]
29
2019-05-16T12:05:32.000Z
2022-03-19T12:28:33.000Z
/* * A test for checking autoshutdown during execution of init function. */ #include <iostream> #include <map> #include <exception> #include <stdexcept> #include <cstdlib> #include <thread> #include <chrono> #include <sstream> #include <mutex> #include <so_5/all.hpp> #include <test/3rd_party/various_helpers/time_limited_execution.hpp> class log_t { public : void append( const std::string & what ) { std::lock_guard< std::mutex > l( m_lock ); m_value += what; } std::string get() { std::lock_guard< std::mutex > l( m_lock ); return m_value; } private : std::mutex m_lock; std::string m_value; }; class a_second_t : public so_5::agent_t { struct msg_timer : public so_5::signal_t {}; public : a_second_t( so_5::environment_t & env, log_t & log ) : so_5::agent_t( env ) , m_log( log ) {} virtual void so_evt_start() override { m_log.append( "s.start;" ); std::this_thread::sleep_for( std::chrono::milliseconds( 200 ) ); } virtual void so_evt_finish() override { m_log.append( "s.finish;" ); } private : log_t & m_log; }; class a_first_t : public so_5::agent_t { public : a_first_t( so_5::environment_t & env, log_t & log ) : so_5::agent_t( env ) , m_log( log ) {} virtual void so_evt_start() override { m_log.append( "f.start;" ); std::this_thread::sleep_for( std::chrono::milliseconds( 200 ) ); so_environment().stop(); m_log.append( "env.stop;" ); try { so_environment().register_agent_as_coop( so_environment().make_agent< a_second_t >( m_log ), so_5::disp::active_obj::make_dispatcher( so_environment() ).binder() ); } catch( const so_5::exception_t & x ) { std::ostringstream s; s << "exception(" << x.error_code() << ");"; m_log.append( s.str() ); } } virtual void so_evt_finish() override { m_log.append( "f.finish;" ); } private : log_t & m_log; }; int main() { try { log_t log; run_with_time_limit( [&log]() { so_5::launch( [&log]( so_5::environment_t & env ) { env.register_agent_as_coop( env.make_agent< a_first_t >( log ) ); } ); }, 20, "SO Environment reg_coop_after_stop test" ); const std::string expected = "f.start;env.stop;exception(28);f.finish;"; const std::string actual = log.get(); if( expected != actual ) throw std::runtime_error( expected + " != " + actual ); } catch( const std::exception & ex ) { std::cerr << "Error: " << ex.what() << std::endl; return 1; } return 0; }
17.22
74
0.612079
ZaMaZaN4iK
90fc34239f2ecedc10add0d63ee205a7f0900360
211
hpp
C++
SwapChain/Driver/OpenGL-DX/include/GL-DX/Win32/Surface.hpp
Gpinchon/OCRA
341bb07facc616f1f8a27350054d1e86f022d7c6
[ "Apache-2.0" ]
null
null
null
SwapChain/Driver/OpenGL-DX/include/GL-DX/Win32/Surface.hpp
Gpinchon/OCRA
341bb07facc616f1f8a27350054d1e86f022d7c6
[ "Apache-2.0" ]
null
null
null
SwapChain/Driver/OpenGL-DX/include/GL-DX/Win32/Surface.hpp
Gpinchon/OCRA
341bb07facc616f1f8a27350054d1e86f022d7c6
[ "Apache-2.0" ]
null
null
null
#pragma once #include <GL-DX/Surface.hpp> namespace OCRA::Surface::Win32 { struct Impl : Surface::Impl { Impl(const Instance::Handle& a_Instance, const Info& a_Info); ~Impl(); const void* hdc; }; }
16.230769
65
0.668246
Gpinchon
290028fc14d0d66e7b0b96d1caf2a91a9bcefa8e
52,764
cxx
C++
Rendering/RayTracing/vtkOSPRayPolyDataMapperNode.cxx
gabrielventosa/vtk
723711d79b0a23de6f07421a27e89539f9d500da
[ "BSD-3-Clause" ]
null
null
null
Rendering/RayTracing/vtkOSPRayPolyDataMapperNode.cxx
gabrielventosa/vtk
723711d79b0a23de6f07421a27e89539f9d500da
[ "BSD-3-Clause" ]
null
null
null
Rendering/RayTracing/vtkOSPRayPolyDataMapperNode.cxx
gabrielventosa/vtk
723711d79b0a23de6f07421a27e89539f9d500da
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: vtkOSPRayPolyDataMapperNode.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkOSPRayPolyDataMapperNode.h" #include "vtkActor.h" #include "vtkDataArray.h" #include "vtkFloatArray.h" #include "vtkImageData.h" #include "vtkImageExtractComponents.h" #include "vtkInformation.h" #include "vtkInformationDoubleKey.h" #include "vtkInformationObjectBaseKey.h" #include "vtkMapper.h" #include "vtkMatrix3x3.h" #include "vtkMatrix4x4.h" #include "vtkOSPRayActorNode.h" #include "vtkOSPRayMaterialHelpers.h" #include "vtkOSPRayRendererNode.h" #include "vtkObjectFactory.h" #include "vtkPiecewiseFunction.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRenderer.h" #include "vtkScalarsToColors.h" #include "vtkSmartPointer.h" #include "vtkTexture.h" #include "vtkUnsignedCharArray.h" #include "RTWrapper/RTWrapper.h" #include <map> //============================================================================ namespace vtkosp { void VToOPointNormals( vtkDataArray* vNormals, std::vector<osp::vec3f>& normals, vtkMatrix3x3* matrix) { int numNormals = vNormals->GetNumberOfTuples(); normals.resize(numNormals); for (int i = 0; i < numNormals; i++) { double vNormal[3]; double* vtmp = vNormals->GetTuple(i); matrix->MultiplyPoint(vtmp, vNormal); vtkMath::Normalize(vNormal); normals[i] = osp::vec3f{ static_cast<float>(vNormal[0]), static_cast<float>(vNormal[1]), static_cast<float>(vNormal[2]) }; } } //------------------------------------------------------------------------------ void MakeCellMaterials(vtkOSPRayRendererNode* orn, OSPRenderer oRenderer, vtkPolyData* poly, vtkMapper* mapper, vtkScalarsToColors* s2c, std::map<std::string, OSPMaterial> mats, std::vector<OSPMaterial>& ospMaterials, vtkUnsignedCharArray* vColors, float* specColor, float specPower, float opacity) { RTW::Backend* backend = orn->GetBackend(); if (backend == nullptr) return; vtkAbstractArray* scalars = nullptr; bool try_mats = s2c->GetIndexedLookup() && s2c->GetNumberOfAnnotatedValues() && !mats.empty(); if (try_mats) { int cflag2 = -1; scalars = mapper->GetAbstractScalars(poly, mapper->GetScalarMode(), mapper->GetArrayAccessMode(), mapper->GetArrayId(), mapper->GetArrayName(), cflag2); } int numColors = vColors->GetNumberOfTuples(); int width = vColors->GetNumberOfComponents(); for (int i = 0; i < numColors; i++) { bool found = false; if (scalars) { vtkVariant v = scalars->GetVariantValue(i); vtkIdType idx = s2c->GetAnnotatedValueIndex(v); if (idx > -1) { std::string name(s2c->GetAnnotation(idx)); if (mats.find(name) != mats.end()) { OSPMaterial oMaterial = mats[name]; ospCommit(oMaterial); ospMaterials.push_back(oMaterial); found = true; } } } if (!found) { double* color = vColors->GetTuple(i); OSPMaterial oMaterial; oMaterial = vtkOSPRayMaterialHelpers::NewMaterial(orn, oRenderer, "obj"); float diffusef[] = { static_cast<float>(color[0]) / (255.0f), static_cast<float>(color[1]) / (255.0f), static_cast<float>(color[2]) / (255.0f) }; float localOpacity = 1.f; if (width >= 4) { localOpacity = static_cast<float>(color[3]) / (255.0f); } ospSetVec3f(oMaterial, "kd", diffusef[0], diffusef[1], diffusef[2]); float specAdjust = 2.0f / (2.0f + specPower); float specularf[] = { specColor[0] * specAdjust, specColor[1] * specAdjust, specColor[2] * specAdjust }; ospSetVec3f(oMaterial, "ks", specularf[0], specularf[1], specularf[2]); ospSetFloat(oMaterial, "ns", specPower); ospSetFloat(oMaterial, "d", opacity * localOpacity); ospCommit(oMaterial); ospMaterials.push_back(oMaterial); } } } //------------------------------------------------------------------------------ float MapThroughPWF(double in, vtkPiecewiseFunction* scaleFunction) { double out = in; if (!scaleFunction) { out = in; } else { out = scaleFunction->GetValue(in); } return static_cast<float>(out); } //---------------------------------------------------------------------------- OSPGeometricModel RenderAsSpheres(osp::vec3f* vertices, std::vector<unsigned int>& indexArray, std::vector<unsigned int>& rIndexArray, double pointSize, vtkDataArray* scaleArray, vtkPiecewiseFunction* scaleFunction, bool useCustomMaterial, OSPMaterial actorMaterial, vtkImageData* vColorTextureMap, bool sRGB, int numTextureCoordinates, float* textureCoordinates, int numCellMaterials, std::vector<OSPMaterial>& CellMaterials, int numPointColors, osp::vec4f* PointColors, int numPointValueTextureCoords, float* pointValueTextureCoords, RTW::Backend* backend) { if (backend == nullptr) return OSPGeometry(); OSPGeometry ospMesh = ospNewGeometry("sphere"); OSPGeometricModel ospGeoModel = ospNewGeometricModel(ospMesh); ospRelease(ospMesh); size_t numSpheres = indexArray.size(); std::vector<osp::vec3f> vdata; std::vector<float> radii; vdata.reserve(indexArray.size()); if (scaleArray != nullptr) { radii.reserve(indexArray.size()); } for (size_t i = 0; i < indexArray.size(); i++) { vdata.emplace_back(vertices[indexArray[i]]); if (scaleArray != nullptr) { radii.emplace_back(MapThroughPWF(*scaleArray->GetTuple(indexArray[i]), scaleFunction)); } } OSPData positionData = ospNewCopyData1D(vdata.data(), OSP_VEC3F, vdata.size()); ospCommit(positionData); ospSetObject(ospMesh, "sphere.position", positionData); if (scaleArray != nullptr) { OSPData radiiData = ospNewCopyData1D(radii.data(), OSP_FLOAT, radii.size()); ospCommit(radiiData); ospSetObject(ospMesh, "sphere.radius", radiiData); } else { ospSetFloat(ospMesh, "radius", pointSize); } // send the texture map and texture coordinates over bool _hastm = false; if (numTextureCoordinates || numPointValueTextureCoords) { _hastm = true; if (numPointValueTextureCoords) { // using 1D texture for point value LUT std::vector<osp::vec2f> tc(indexArray.size()); for (size_t i = 0; i < indexArray.size(); i++) { float t1; int index1 = indexArray[i]; t1 = pointValueTextureCoords[index1 + 0]; tc[i] = osp::vec2f{ t1, 0 }; } OSPData tcs = ospNewCopyData1D(tc.data(), OSP_VEC2F, indexArray.size()); ospCommit(tcs); ospSetObject(ospMesh, "sphere.texcoord", tcs); } else if (numTextureCoordinates) { // 2d texture mapping float* itc = textureCoordinates; std::vector<osp::vec2f> tc(indexArray.size()); for (size_t i = 0; i < indexArray.size(); i++) { float t1, t2; int index1 = indexArray[i]; t1 = itc[index1 * 2 + 0]; t2 = itc[index1 * 2 + 1]; tc[i] = osp::vec2f{ t1, t2 }; } OSPData tcs = ospNewCopyData1D(tc.data(), OSP_VEC2F, indexArray.size()); ospCommit(tcs); ospSetObject(ospMesh, "sphere.texcoord", tcs); } } OSPData _cmats = nullptr; OSPData _PointColors = nullptr; bool perCellColor = false; bool perPointColor = false; if (!useCustomMaterial) { if (vColorTextureMap && _hastm) { OSPTexture t2d = vtkOSPRayMaterialHelpers::VTKToOSPTexture(backend, vColorTextureMap, sRGB); ospSetObject(actorMaterial, "map_kd", ((OSPTexture)(t2d))); ospRelease(t2d); ospCommit(actorMaterial); } else if (numCellMaterials) { // per cell color perCellColor = true; std::vector<OSPMaterial> perCellMats; for (size_t i = 0; i < numSpheres; i++) { perCellMats.push_back(CellMaterials[rIndexArray[i]]); } _cmats = ospNewCopyData1D(&perCellMats[0], OSP_MATERIAL, numSpheres); ospCommit(_cmats); ospSetObject(ospGeoModel, "material", _cmats); ospRelease(_cmats); } else if (numPointColors) { // per point color perPointColor = true; std::vector<osp::vec4f> perPointColors; for (size_t i = 0; i < numSpheres; i++) { perPointColors.push_back(PointColors[indexArray[i]]); } _PointColors = ospNewCopyData1D(&perPointColors[0], OSP_VEC4F, numSpheres); ospCommit(_PointColors); ospSetObject(ospGeoModel, "color", _PointColors); ospRelease(_PointColors); } } if (actorMaterial && !perCellColor && !perPointColor) { ospCommit(actorMaterial); ospSetObjectAsData(ospGeoModel, "material", OSP_MATERIAL, actorMaterial); } ospCommit(ospMesh); ospCommit(ospGeoModel); return ospGeoModel; } //---------------------------------------------------------------------------- OSPGeometricModel RenderAsCylinders(std::vector<osp::vec3f>& vertices, std::vector<unsigned int>& indexArray, std::vector<unsigned int>& rIndexArray, double lineWidth, vtkDataArray* scaleArray, vtkPiecewiseFunction* scaleFunction, bool useCustomMaterial, OSPMaterial actorMaterial, vtkImageData* vColorTextureMap, bool sRGB, int numTextureCoordinates, float* textureCoordinates, int numCellMaterials, std::vector<OSPMaterial>& CellMaterials, int numPointColors, osp::vec4f* PointColors, int numPointValueTextureCoords, float* pointValueTextureCoords, RTW::Backend* backend) { if (backend == nullptr) return OSPGeometry(); OSPGeometry ospMesh = ospNewGeometry("curve"); OSPGeometricModel ospGeoModel = ospNewGeometricModel(ospMesh); ospRelease(ospMesh); size_t numCylinders = indexArray.size() / 2; if (scaleArray != nullptr) { std::vector<osp::vec4f> mdata; mdata.reserve(indexArray.size() * 2); for (size_t i = 0; i < indexArray.size(); i++) { const double avg = (*scaleArray->GetTuple(indexArray[i]) + *scaleArray->GetTuple(indexArray[i])) * 0.5; const float r = static_cast<float>(MapThroughPWF(avg, scaleFunction)); const osp::vec3f& v = vertices[indexArray[i]]; // linear not supported for variable radii, must use curve type with // 4 instead of 2 control points mdata.emplace_back(osp::vec4f({ v.x, v.y, v.z, r })); mdata.emplace_back(osp::vec4f({ v.x, v.y, v.z, r })); } OSPData _mdata = ospNewCopyData1D(mdata.data(), OSP_VEC4F, mdata.size()); ospCommit(_mdata); ospSetObject(ospMesh, "vertex.position_radius", _mdata); ospRelease(_mdata); ospSetInt(ospMesh, "type", OSP_ROUND); ospSetInt(ospMesh, "basis", OSP_BEZIER); } else { std::vector<osp::vec3f> mdata; mdata.reserve(indexArray.size()); for (size_t i = 0; i < indexArray.size(); i++) { mdata.emplace_back(vertices[indexArray[i]]); } OSPData _mdata = ospNewCopyData1D(mdata.data(), OSP_VEC3F, mdata.size()); ospCommit(_mdata); ospSetObject(ospMesh, "vertex.position", _mdata); ospRelease(_mdata); ospSetFloat(ospMesh, "radius", lineWidth); ospSetInt(ospMesh, "type", OSP_ROUND); ospSetInt(ospMesh, "basis", OSP_LINEAR); } std::vector<unsigned int> indices; indices.reserve(indexArray.size() / 2); for (unsigned int i = 0; i < indexArray.size(); i += 2) { indices.push_back((scaleArray != nullptr ? i * 2 : i)); } OSPData _idata = ospNewCopyData1D(indices.data(), OSP_UINT, indices.size()); ospCommit(_idata); ospSetObject(ospMesh, "index", _idata); ospRelease(_idata); // send the texture map and texture coordinates over bool _hastm = false; if (numTextureCoordinates || numPointValueTextureCoords) { _hastm = true; if (numPointValueTextureCoords) { // using 1D texture for point value LUT std::vector<osp::vec2f> tc(indexArray.size()); for (size_t i = 0; i < indexArray.size(); i += 2) { float t1, t2; int index1 = indexArray[i + 0]; t1 = pointValueTextureCoords[index1 + 0]; tc[i] = osp::vec2f{ t1, 0 }; int index2 = indexArray[i + 1]; t2 = pointValueTextureCoords[index2 + 0]; tc[i + 1] = osp::vec2f{ t2, 0 }; } OSPData tcs = ospNewCopyData1D(tc.data(), OSP_VEC2F, indexArray.size()); ospCommit(tcs); ospSetObject(ospMesh, "vertex.texcoord", tcs); } else if (numTextureCoordinates) { // 2d texture mapping float* itc = textureCoordinates; std::vector<osp::vec2f> tc(indexArray.size()); for (size_t i = 0; i < indexArray.size(); i += 2) { float t1, t2; int index1 = indexArray[i + 0]; t1 = itc[index1 * 2 + 0]; t2 = itc[index1 * 2 + 1]; tc[i] = osp::vec2f{ t1, t2 }; int index2 = indexArray[i + 1]; t1 = itc[index2 * 2 + 0]; t2 = itc[index2 * 2 + 1]; tc[i + 1] = osp::vec2f{ t1, t2 }; } OSPData tcs = ospNewCopyData1D(tc.data(), OSP_VEC2F, indexArray.size()); ospCommit(tcs); ospSetObject(ospMesh, "vertex.texcoord", tcs); } } OSPData _cmats = nullptr; OSPData _PointColors = nullptr; bool perCellColor = false; if (!useCustomMaterial) { if (vColorTextureMap && _hastm) { OSPTexture t2d = vtkOSPRayMaterialHelpers::VTKToOSPTexture(backend, vColorTextureMap, sRGB); ospSetObject(actorMaterial, "map_kd", ((OSPTexture)(t2d))); ospRelease(t2d); ospCommit(actorMaterial); } else if (numCellMaterials) { // per cell color perCellColor = true; std::vector<OSPMaterial> perCellMats; for (size_t i = 0; i < numCylinders; i++) { perCellMats.push_back(CellMaterials[rIndexArray[i * 2 + 0]]); } _cmats = ospNewCopyData1D(&perCellMats[0], OSP_MATERIAL, numCylinders); ospCommit(_cmats); ospSetObject(ospGeoModel, "material", _cmats); ospRelease(_cmats); } else if (numPointColors) { // per point color std::vector<osp::vec4f> perPointColor; for (size_t i = 0; i < numCylinders; i++) { perPointColor.push_back(PointColors[indexArray[i * 2 + 0]]); } _PointColors = ospNewCopyData1D(&perPointColor[0], OSP_VEC4F, numCylinders); ospCommit(_PointColors); ospSetObject(ospGeoModel, "color", _PointColors); ospRelease(_PointColors); #if 0 //this should work, but it doesn't render whole mesh, I think ospray bug // per point color _PointColors = ospNewCopyData1D(&PointColors[0], OSP_VEC4F, numPointColors); ospCommit(_PointColors); ospSetObject(ospMesh, "vertex.color", _PointColors); ospRelease(_PointColors); #endif } } if (actorMaterial && !perCellColor) { ospCommit(actorMaterial); ospSetObjectAsData(ospGeoModel, "material", OSP_MATERIAL, actorMaterial); } ospCommit(ospMesh); ospCommit(ospGeoModel); return ospGeoModel; } //---------------------------------------------------------------------------- OSPGeometricModel RenderAsTriangles(OSPData vertices, std::vector<unsigned int>& indexArray, std::vector<unsigned int>& rIndexArray, bool useCustomMaterial, OSPMaterial actorMaterial, int numNormals, const std::vector<osp::vec3f>& normals, int interpolationType, vtkImageData* vColorTextureMap, bool sRGB, vtkImageData* vNormalTextureMap, vtkImageData* vMaterialTextureMap, vtkImageData* vAnisotropyTextureMap, vtkImageData* vCoatNormalTextureMap, int numTextureCoordinates, float* textureCoordinates, const osp::vec4f& textureTransform, int numCellMaterials, std::vector<OSPMaterial>& CellMaterials, int numPointColors, osp::vec4f* PointColors, int numPointValueTextureCoords, float* pointValueTextureCoords, RTW::Backend* backend) { if (backend == nullptr) return OSPGeometry(); OSPGeometry ospMesh = ospNewGeometry("mesh"); OSPGeometricModel ospGeoModel = ospNewGeometricModel(ospMesh); ospRelease(ospMesh); ospCommit(vertices); ospSetObject(ospMesh, "vertex.position", vertices); size_t numTriangles = indexArray.size() / 3; std::vector<osp::vec3ui> triangles(numTriangles); for (size_t i = 0, mi = 0; i < numTriangles; i++, mi += 3) { triangles[i] = osp::vec3ui{ static_cast<unsigned int>(indexArray[mi + 0]), static_cast<unsigned int>(indexArray[mi + 1]), static_cast<unsigned int>(indexArray[mi + 2]) }; } OSPData index = ospNewCopyData1D(triangles.data(), OSP_VEC3UI, numTriangles); ospCommit(index); ospSetObject(ospMesh, "index", index); ospRelease(index); OSPData _normals = nullptr; if (numNormals) { _normals = ospNewCopyData1D(normals.data(), OSP_VEC3F, numNormals); ospCommit(_normals); ospSetObject(ospMesh, "vertex.normal", _normals); ospRelease(_normals); } // send the texture map and texture coordinates over bool _hastm = false; OSPData tcs = nullptr; std::vector<osp::vec2f> tc; if (numTextureCoordinates || numPointValueTextureCoords) { _hastm = true; if (numPointValueTextureCoords) { // using 1D texture for point value LUT tc.resize(numPointValueTextureCoords); for (size_t i = 0; i < static_cast<size_t>(numPointValueTextureCoords); i++) { tc[i] = osp::vec2f{ pointValueTextureCoords[i], 0 }; } tcs = ospNewCopyData1D(tc.data(), OSP_VEC2F, numPointValueTextureCoords); ospCommit(tcs); ospSetObject(ospMesh, "vertex.texcoord", tcs); ospRelease(tcs); } else if (numTextureCoordinates) { // 2d texture mapping tc.resize(numTextureCoordinates / 2); float* itc = textureCoordinates; for (size_t i = 0; i < static_cast<size_t>(numTextureCoordinates); i += 2) { float t1, t2; t1 = *itc; itc++; t2 = *itc; itc++; tc[i / 2] = osp::vec2f{ t1, t2 }; } tcs = ospNewCopyData1D(tc.data(), OSP_VEC2F, numTextureCoordinates / 2); ospCommit(tcs); ospSetObject(ospMesh, "vertex.texcoord", tcs); ospRelease(tcs); } } // send over cell colors, point colors or whole actor color OSPData _cmats = nullptr; OSPData _PointColors = nullptr; bool perCellColor = false; if (!useCustomMaterial) { if (vNormalTextureMap && _hastm) { OSPTexture t2d = vtkOSPRayMaterialHelpers::VTKToOSPTexture(backend, vNormalTextureMap); if (interpolationType == VTK_PBR) { ospSetObject(actorMaterial, "map_normal", t2d); ospSetVec4f(actorMaterial, "map_normal.transform", textureTransform.x, textureTransform.y, textureTransform.z, textureTransform.w); } else { ospSetObject(actorMaterial, "map_Bump", t2d); ospSetVec4f(actorMaterial, "map_Bump.transform", textureTransform.x, textureTransform.y, textureTransform.z, textureTransform.w); } ospRelease(t2d); ospCommit(actorMaterial); } if (interpolationType == VTK_PBR && _hastm) { if (vMaterialTextureMap) { vtkNew<vtkImageExtractComponents> extractRoughness; extractRoughness->SetInputData(vMaterialTextureMap); extractRoughness->SetComponents(1); extractRoughness->Update(); vtkNew<vtkImageExtractComponents> extractMetallic; extractMetallic->SetInputData(vMaterialTextureMap); extractMetallic->SetComponents(2); extractMetallic->Update(); vtkImageData* vRoughnessTextureMap = extractRoughness->GetOutput(); vtkImageData* vMetallicTextureMap = extractMetallic->GetOutput(); OSPTexture t2dR = vtkOSPRayMaterialHelpers::VTKToOSPTexture(backend, vRoughnessTextureMap); ospSetObject(actorMaterial, "map_roughness", t2dR); ospSetVec4f(actorMaterial, "map_roughness.transform", textureTransform.x, textureTransform.y, textureTransform.z, textureTransform.w); ospRelease(t2dR); OSPTexture t2dM = vtkOSPRayMaterialHelpers::VTKToOSPTexture(backend, vMetallicTextureMap); ospSetObject(actorMaterial, "map_metallic", t2dM); ospSetVec4f(actorMaterial, "map_metallic.transform", textureTransform.x, textureTransform.y, textureTransform.z, textureTransform.w); ospRelease(t2dM); ospCommit(actorMaterial); } if (vAnisotropyTextureMap) { vtkNew<vtkImageExtractComponents> extractAnisotropyValue; extractAnisotropyValue->SetInputData(vAnisotropyTextureMap); extractAnisotropyValue->SetComponents(0); extractAnisotropyValue->Update(); vtkNew<vtkImageExtractComponents> extractAnisotropyRotation; extractAnisotropyRotation->SetInputData(vAnisotropyTextureMap); extractAnisotropyRotation->SetComponents(1); extractAnisotropyRotation->Update(); vtkImageData* vAnisotropyValueTextureMap = extractAnisotropyValue->GetOutput(); vtkImageData* vAnisotropyRotationTextureMap = extractAnisotropyRotation->GetOutput(); OSPTexture t2dA = vtkOSPRayMaterialHelpers::VTKToOSPTexture(backend, vAnisotropyValueTextureMap); ospSetObject(actorMaterial, "map_anisotropy", t2dA); ospSetVec4f(actorMaterial, "map_anisotropy.transform", textureTransform.x, textureTransform.y, textureTransform.z, textureTransform.w); ospRelease(t2dA); OSPTexture t2dR = vtkOSPRayMaterialHelpers::VTKToOSPTexture(backend, vAnisotropyRotationTextureMap); ospSetObject(actorMaterial, "map_rotation", t2dR); ospSetVec4f(actorMaterial, "map_rotation.transform", textureTransform.x, textureTransform.y, textureTransform.z, textureTransform.w); ospRelease(t2dR); ospCommit(actorMaterial); } if (vCoatNormalTextureMap) { OSPTexture t2d = vtkOSPRayMaterialHelpers::VTKToOSPTexture(backend, vCoatNormalTextureMap); ospSetObject(actorMaterial, "map_coatNormal", t2d); ospSetVec4f(actorMaterial, "map_coatNormal.transform", textureTransform.x, textureTransform.y, textureTransform.z, textureTransform.w); ospRelease(t2d); ospCommit(actorMaterial); } } if (vColorTextureMap && _hastm) { // Note: this will only have an affect on OBJMaterials OSPTexture t2d = vtkOSPRayMaterialHelpers::VTKToOSPTexture(backend, vColorTextureMap, sRGB); if (interpolationType == VTK_PBR) { ospSetObject(actorMaterial, "map_baseColor", ((OSPTexture)(t2d))); ospSetVec4f(actorMaterial, "map_baseColor.transform", textureTransform.x, textureTransform.y, textureTransform.z, textureTransform.w); } else { ospSetObject(actorMaterial, "map_kd", ((OSPTexture)(t2d))); ospSetVec4f(actorMaterial, "map_kd.transform", textureTransform.x, textureTransform.y, textureTransform.z, textureTransform.w); } ospRelease(t2d); ospCommit(actorMaterial); } else if (numCellMaterials) { perCellColor = true; std::vector<OSPMaterial> perCellMats; for (size_t i = 0; i < numTriangles; i++) { perCellMats.push_back(CellMaterials[rIndexArray[i * 3 + 0]]); } _cmats = ospNewCopyData1D(&perCellMats[0], OSP_MATERIAL, numTriangles); ospCommit(_cmats); ospSetObject(ospGeoModel, "material", _cmats); ospRelease(_cmats); } else if (numPointColors) { _PointColors = ospNewCopyData1D(&PointColors[0], OSP_VEC4F, numPointColors); ospCommit(_PointColors); ospSetObject(ospMesh, "vertex.color", _PointColors); ospRelease(_PointColors); } } if (actorMaterial && !perCellColor) { ospCommit(actorMaterial); ospSetObjectAsData(ospGeoModel, "material", OSP_MATERIAL, actorMaterial); } ospCommit(ospMesh); ospCommit(ospGeoModel); return ospGeoModel; } //------------------------------------------------------------------------------ OSPMaterial MakeActorMaterial(vtkOSPRayRendererNode* orn, OSPRenderer oRenderer, vtkProperty* property, double* ambientColor, double* diffuseColor, float* specularf, double opacity, bool pt_avail, bool& useCustomMaterial, std::map<std::string, OSPMaterial>& mats, const std::string& materialName) { RTW::Backend* backend = orn->GetBackend(); useCustomMaterial = false; if (backend == nullptr) { return OSPMaterial(); } float lum = static_cast<float>(vtkOSPRayActorNode::GetLuminosity(property)); float diffusef[] = { static_cast<float>(diffuseColor[0] * property->GetDiffuse()), static_cast<float>(diffuseColor[1] * property->GetDiffuse()), static_cast<float>(diffuseColor[2] * property->GetDiffuse()) }; if (lum > 0.0) { OSPMaterial oMaterial = vtkOSPRayMaterialHelpers::NewMaterial(orn, oRenderer, "luminous"); ospSetVec3f(oMaterial, "color", diffusef[0], diffusef[1], diffusef[2]); ospSetFloat(oMaterial, "intensity", lum); return oMaterial; } if (pt_avail && property->GetMaterialName()) { if (std::string("Value Indexed") == property->GetMaterialName()) { vtkOSPRayMaterialHelpers::MakeMaterials( orn, oRenderer, mats); // todo: do an mtime check to avoid doing this when unchanged std::string requested_mat_name = materialName; if (!requested_mat_name.empty() && requested_mat_name != "Value Indexed") { useCustomMaterial = true; return vtkOSPRayMaterialHelpers::MakeMaterial(orn, oRenderer, requested_mat_name.c_str()); } } else { useCustomMaterial = true; return vtkOSPRayMaterialHelpers::MakeMaterial(orn, oRenderer, property->GetMaterialName()); } } OSPMaterial oMaterial; if (pt_avail && property->GetInterpolation() == VTK_PBR) { oMaterial = vtkOSPRayMaterialHelpers::NewMaterial(orn, oRenderer, "principled"); ospSetVec3f(oMaterial, "baseColor", diffusef[0], diffusef[1], diffusef[2]); ospSetFloat(oMaterial, "metallic", static_cast<float>(property->GetMetallic())); ospSetFloat(oMaterial, "roughness", static_cast<float>(property->GetRoughness())); ospSetFloat(oMaterial, "opacity", static_cast<float>(opacity)); // As OSPRay seems to not recalculate the refractive index of the base layer // we need to recalculate, from the effective reflectance of the base layer (with the // coat), the ior of the base that will produce the same reflectance but with the air // with an ior of 1.0 double baseF0 = property->ComputeReflectanceOfBaseLayer(); const double exteriorIor = 1.0; double baseIor = vtkProperty::ComputeIORFromReflectance(baseF0, exteriorIor); ospSetFloat(oMaterial, "ior", static_cast<float>(baseIor)); float edgeColor[3] = { static_cast<float>(property->GetEdgeTint()[0]), static_cast<float>(property->GetEdgeTint()[1]), static_cast<float>(property->GetEdgeTint()[2]) }; ospSetVec3f(oMaterial, "edgeColor", edgeColor[0], edgeColor[1], edgeColor[2]); ospSetFloat(oMaterial, "anisotropy", static_cast<float>(property->GetAnisotropy())); ospSetFloat(oMaterial, "rotation", static_cast<float>(property->GetAnisotropyRotation())); ospSetFloat(oMaterial, "baseNormalScale", static_cast<float>(property->GetNormalScale())); ospSetFloat(oMaterial, "coat", static_cast<float>(property->GetCoatStrength())); ospSetFloat(oMaterial, "coatIor", static_cast<float>(property->GetCoatIOR())); ospSetFloat(oMaterial, "coatRoughness", static_cast<float>(property->GetCoatRoughness())); float coatColor[] = { static_cast<float>(property->GetCoatColor()[0]), static_cast<float>(property->GetCoatColor()[1]), static_cast<float>(property->GetCoatColor()[2]) }; ospSetVec3f(oMaterial, "coatColor", coatColor[0], coatColor[1], coatColor[2]); ospSetFloat(oMaterial, "coatNormal", static_cast<float>(property->GetCoatNormalScale())); } else { oMaterial = vtkOSPRayMaterialHelpers::NewMaterial(orn, oRenderer, "obj"); float ambientf[] = { static_cast<float>(ambientColor[0] * property->GetAmbient()), static_cast<float>(ambientColor[1] * property->GetAmbient()), static_cast<float>(ambientColor[2] * property->GetAmbient()) }; float specPower = static_cast<float>(property->GetSpecularPower()); float specAdjust = 2.0f / (2.0f + specPower); specularf[0] = static_cast<float>(property->GetSpecularColor()[0] * property->GetSpecular() * specAdjust); specularf[1] = static_cast<float>(property->GetSpecularColor()[1] * property->GetSpecular() * specAdjust); specularf[2] = static_cast<float>(property->GetSpecularColor()[2] * property->GetSpecular() * specAdjust); ospSetVec3f(oMaterial, "ka", ambientf[0], ambientf[1], ambientf[2]); if (property->GetDiffuse() == 0.0) { // a workaround for ParaView, remove when ospray supports Ka ospSetVec3f(oMaterial, "kd", ambientf[0], ambientf[1], ambientf[2]); } else { ospSetVec3f(oMaterial, "kd", diffusef[0], diffusef[1], diffusef[2]); } ospSetVec3f(oMaterial, "Ks", specularf[0], specularf[1], specularf[2]); ospSetFloat(oMaterial, "Ns", specPower); ospSetFloat(oMaterial, "d", static_cast<float>(opacity)); } return oMaterial; } //------------------------------------------------------------------------------ OSPMaterial MakeActorMaterial(vtkOSPRayRendererNode* orn, OSPRenderer oRenderer, vtkProperty* property, double* ambientColor, double* diffuseColor, float* specularf, double opacity) { bool dontcare1; std::map<std::string, OSPMaterial> dontcare2; return MakeActorMaterial(orn, oRenderer, property, ambientColor, diffuseColor, specularf, opacity, false, dontcare1, dontcare2, ""); }; } //============================================================================ vtkStandardNewMacro(vtkOSPRayPolyDataMapperNode); //------------------------------------------------------------------------------ vtkOSPRayPolyDataMapperNode::vtkOSPRayPolyDataMapperNode() {} //------------------------------------------------------------------------------ vtkOSPRayPolyDataMapperNode::~vtkOSPRayPolyDataMapperNode() {} //------------------------------------------------------------------------------ void vtkOSPRayPolyDataMapperNode::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //------------------------------------------------------------------------------ void vtkOSPRayPolyDataMapperNode::ORenderPoly(void* renderer, vtkOSPRayActorNode* aNode, vtkPolyData* poly, double* ambientColor, double* diffuseColor, double opacity, std::string materialName) { vtkOSPRayRendererNode* orn = static_cast<vtkOSPRayRendererNode*>(this->GetFirstAncestorOfType("vtkOSPRayRendererNode")); RTW::Backend* backend = orn->GetBackend(); if (backend == nullptr) return; OSPRenderer oRenderer = static_cast<OSPRenderer>(renderer); vtkActor* act = vtkActor::SafeDownCast(aNode->GetRenderable()); vtkProperty* property = act->GetProperty(); // get texture transform osp::vec4f texTransform{ 1.f, 0.f, 0.f, 1.f }; vtkInformation* info = act->GetPropertyKeys(); if (info && info->Has(vtkProp::GeneralTextureTransform())) { double* mat = info->Get(vtkProp::GeneralTextureTransform()); texTransform.x = mat[0]; texTransform.y = mat[1]; texTransform.z = mat[4]; texTransform.w = mat[5]; } // make geometry std::vector<double> _vertices; vtkPolyDataMapperNode::TransformPoints(act, poly, _vertices); size_t numPositions = _vertices.size() / 3; if (numPositions == 0) { return; } std::vector<osp::vec3f> vertices(numPositions); for (size_t i = 0; i < numPositions; i++) { vertices[i] = osp::vec3f{ static_cast<float>(_vertices[i * 3 + 0]), static_cast<float>(_vertices[i * 3 + 1]), static_cast<float>(_vertices[i * 3 + 2]) }; } OSPData position = ospNewCopyData1D(&vertices[0], OSP_VEC3F, numPositions); ospCommit(position); _vertices.clear(); // make connectivity vtkPolyDataMapperNode::vtkPDConnectivity conn; vtkPolyDataMapperNode::MakeConnectivity(poly, property->GetRepresentation(), conn); // choosing sphere and cylinder radii (for points and lines) that // approximate pointsize and linewidth vtkMapper* mapper = act->GetMapper(); double length = 1.0; if (mapper) { length = mapper->GetLength(); } int scalingMode = vtkOSPRayActorNode::GetEnableScaling(act); double pointSize = length / 1000.0 * property->GetPointSize(); double lineWidth = length / 1000.0 * property->GetLineWidth(); if (scalingMode == vtkOSPRayActorNode::ALL_EXACT) { pointSize = property->GetPointSize(); lineWidth = property->GetLineWidth(); } // finer control over sphere and cylinders sizes vtkDataArray* scaleArray = nullptr; vtkPiecewiseFunction* scaleFunction = nullptr; if (mapper && scalingMode > vtkOSPRayActorNode::ALL_APPROXIMATE) { vtkInformation* mapInfo = mapper->GetInformation(); char* scaleArrayName = (char*)mapInfo->Get(vtkOSPRayActorNode::SCALE_ARRAY_NAME()); scaleArray = poly->GetPointData()->GetArray(scaleArrayName); if (scalingMode != vtkOSPRayActorNode::EACH_EXACT) { scaleFunction = vtkPiecewiseFunction::SafeDownCast(mapInfo->Get(vtkOSPRayActorNode::SCALE_FUNCTION())); } } // now ask mapper to do most of the work and provide us with // colors per cell and colors or texture coordinates per point vtkUnsignedCharArray* vColors = nullptr; vtkFloatArray* vColorCoordinates = nullptr; vtkImageData* pColorTextureMap = nullptr; int cellFlag = -1; // mapper tells us which if (mapper) { mapper->MapScalars(poly, 1.0, cellFlag); vColors = mapper->GetColorMapColors(); vColorCoordinates = mapper->GetColorCoordinates(); pColorTextureMap = mapper->GetColorTextureMap(); } if (vColors || (vColorCoordinates && pColorTextureMap)) { // OSPRay scales the color mapping with the solid color but OpenGL backend does not do it. // set back to white to workaround this difference. std::fill(diffuseColor, diffuseColor + 3, 1.0); } // per actor material float specularf[3]; bool useCustomMaterial = false; std::map<std::string, OSPMaterial> mats; std::set<OSPMaterial> uniqueMats; const std::string rendererType = orn->GetRendererType(vtkRenderer::SafeDownCast(orn->GetRenderable())); bool pt_avail = rendererType == std::string("pathtracer") || rendererType == std::string("optix pathtracer"); OSPMaterial oMaterial = vtkosp::MakeActorMaterial(orn, oRenderer, property, ambientColor, diffuseColor, specularf, opacity, pt_avail, useCustomMaterial, mats, materialName); ospCommit(oMaterial); uniqueMats.insert(oMaterial); // texture int numTextureCoordinates = 0; std::vector<osp::vec2f> textureCoordinates; if (vtkDataArray* da = poly->GetPointData()->GetTCoords()) { numTextureCoordinates = da->GetNumberOfTuples(); textureCoordinates.resize(numTextureCoordinates); for (int i = 0; i < numTextureCoordinates; i++) { textureCoordinates[i] = osp::vec2f( { static_cast<float>(da->GetTuple(i)[0]), static_cast<float>(da->GetTuple(i)[1]) }); } numTextureCoordinates = numTextureCoordinates * 2; } vtkTexture* texture = nullptr; if (property->GetInterpolation() == VTK_PBR) { texture = property->GetTexture("albedoTex"); } else { texture = act->GetTexture(); } vtkImageData* vColorTextureMap = nullptr; vtkImageData* vNormalTextureMap = nullptr; vtkImageData* vMaterialTextureMap = nullptr; vtkImageData* vAnisotropyTextureMap = nullptr; vtkImageData* vCoatNormalTextureMap = nullptr; bool sRGB = false; if (texture) { sRGB = texture->GetUseSRGBColorSpace(); vColorTextureMap = texture->GetInput(); ospSetVec3f(oMaterial, "kd", 1.0f, 1.0f, 1.0f); ospCommit(oMaterial); } // colors from point and cell arrays int numCellMaterials = 0; std::vector<OSPMaterial> cellMaterials; int numPointColors = 0; std::vector<osp::vec4f> pointColors; int numPointValueTextureCoords = 0; std::vector<float> pointValueTextureCoords; if (vColors) { if (cellFlag == 2 && mapper->GetFieldDataTupleId() > -1) { // color comes from field data entry bool use_material = false; // check if the field data content says to use a material lookup vtkScalarsToColors* s2c = mapper->GetLookupTable(); bool try_mats = s2c->GetIndexedLookup() && s2c->GetNumberOfAnnotatedValues() && !mats.empty(); if (try_mats) { int cflag2 = -1; vtkAbstractArray* scalars = mapper->GetAbstractScalars(poly, mapper->GetScalarMode(), mapper->GetArrayAccessMode(), mapper->GetArrayId(), mapper->GetArrayName(), cflag2); vtkVariant v = scalars->GetVariantValue(mapper->GetFieldDataTupleId()); vtkIdType idx = s2c->GetAnnotatedValueIndex(v); if (idx > -1) { std::string name(s2c->GetAnnotation(idx)); if (mats.find(name) != mats.end()) { // yes it does! oMaterial = mats[name]; ospCommit(oMaterial); use_material = true; } } } if (!use_material) { // just use the color for the field data value int numComp = vColors->GetNumberOfComponents(); unsigned char* colorPtr = vColors->GetPointer(0); colorPtr = colorPtr + mapper->GetFieldDataTupleId() * numComp; // this setting (and all the other scalar colors) // really depends on mapper->ScalarMaterialMode // but I'm not sure Ka is working currently so leaving it on Kd float fdiffusef[] = { static_cast<float>(colorPtr[0] * property->GetDiffuse() / 255.0f), static_cast<float>(colorPtr[1] * property->GetDiffuse() / 255.0f), static_cast<float>(colorPtr[2] * property->GetDiffuse() / 255.0f) }; ospSetVec3f(oMaterial, "kd", fdiffusef[0], fdiffusef[1], fdiffusef[2]); ospCommit(oMaterial); } } else if (cellFlag == 1) { // color or material on cell vtkScalarsToColors* s2c = mapper->GetLookupTable(); vtkosp::MakeCellMaterials(orn, oRenderer, poly, mapper, s2c, mats, cellMaterials, vColors, specularf, float(property->GetSpecularPower()), opacity); numCellMaterials = static_cast<int>(cellMaterials.size()); for (OSPMaterial mat : cellMaterials) { uniqueMats.insert(mat); } } else if (cellFlag == 0) { // color on point interpolated RGB numPointColors = vColors->GetNumberOfTuples(); pointColors.resize(numPointColors); for (int i = 0; i < numPointColors; i++) { unsigned char* color = vColors->GetPointer(4 * i); pointColors[i] = osp::vec4f{ color[0] / 255.0f, color[1] / 255.0f, color[2] / 255.0f, (color[3] / 255.0f) * static_cast<float>(opacity) }; } ospSetVec3f(oMaterial, "kd", 1.0f, 1.0f, 1.0f); ospCommit(oMaterial); } } else { if (vColorCoordinates && pColorTextureMap) { // color on point interpolated values (subsequently colormapped via 1D LUT) numPointValueTextureCoords = vColorCoordinates->GetNumberOfTuples(); pointValueTextureCoords.resize(numPointValueTextureCoords); float* tc = vColorCoordinates->GetPointer(0); for (int i = 0; i < numPointValueTextureCoords; i++) { float v = *tc; v = ((v >= 1.0f) ? 0.99999f : ((v < 0.0f) ? 0.0f : v)); // clamp [0..1) pointValueTextureCoords[i] = v; tc += 2; } vColorTextureMap = pColorTextureMap; ospSetVec3f(oMaterial, "kd", 1.0f, 1.0f, 1.0f); ospCommit(oMaterial); } } // create an ospray mesh for the vertex cells if (!conn.vertex_index.empty()) { this->GeometricModels.emplace_back(vtkosp::RenderAsSpheres(vertices.data(), conn.vertex_index, conn.vertex_reverse, pointSize, scaleArray, scaleFunction, useCustomMaterial, oMaterial, vColorTextureMap, sRGB, numTextureCoordinates, (float*)textureCoordinates.data(), numCellMaterials, cellMaterials, numPointColors, pointColors.data(), numPointValueTextureCoords, (float*)pointValueTextureCoords.data(), backend)); } // create an ospray mesh for the line cells if (!conn.line_index.empty()) { // format depends on representation style if (property->GetRepresentation() == VTK_POINTS) { this->GeometricModels.emplace_back(vtkosp::RenderAsSpheres(vertices.data(), conn.line_index, conn.line_reverse, pointSize, scaleArray, scaleFunction, useCustomMaterial, oMaterial, vColorTextureMap, sRGB, numTextureCoordinates, (float*)textureCoordinates.data(), numCellMaterials, cellMaterials, numPointColors, pointColors.data(), numPointValueTextureCoords, (float*)pointValueTextureCoords.data(), backend)); } else { this->GeometricModels.emplace_back(vtkosp::RenderAsCylinders(vertices, conn.line_index, conn.line_reverse, lineWidth, scaleArray, scaleFunction, useCustomMaterial, oMaterial, vColorTextureMap, sRGB, numTextureCoordinates, (float*)textureCoordinates.data(), numCellMaterials, cellMaterials, numPointColors, pointColors.data(), numPointValueTextureCoords, (float*)pointValueTextureCoords.data(), backend)); } } // create an ospray mesh for the polygon cells if (!conn.triangle_index.empty()) { // format depends on representation style switch (property->GetRepresentation()) { case VTK_POINTS: { this->GeometricModels.emplace_back( vtkosp::RenderAsSpheres(vertices.data(), conn.triangle_index, conn.triangle_reverse, pointSize, scaleArray, scaleFunction, useCustomMaterial, oMaterial, vColorTextureMap, sRGB, numTextureCoordinates, (float*)textureCoordinates.data(), numCellMaterials, cellMaterials, numPointColors, pointColors.data(), numPointValueTextureCoords, (float*)pointValueTextureCoords.data(), backend)); break; } case VTK_WIREFRAME: { this->GeometricModels.emplace_back(vtkosp::RenderAsCylinders(vertices, conn.triangle_index, conn.triangle_reverse, lineWidth, scaleArray, scaleFunction, useCustomMaterial, oMaterial, vColorTextureMap, sRGB, numTextureCoordinates, (float*)textureCoordinates.data(), numCellMaterials, cellMaterials, numPointColors, pointColors.data(), numPointValueTextureCoords, (float*)pointValueTextureCoords.data(), backend)); break; } default: { if (property->GetEdgeVisibility()) { // edge mesh vtkPolyDataMapperNode::vtkPDConnectivity conn2; vtkPolyDataMapperNode::MakeConnectivity(poly, VTK_WIREFRAME, conn2); // edge material double* eColor = property->GetEdgeColor(); OSPMaterial oMaterial2 = vtkosp::MakeActorMaterial(orn, oRenderer, property, eColor, eColor, specularf, opacity); ospCommit(oMaterial2); this->GeometricModels.emplace_back( vtkosp::RenderAsCylinders(vertices, conn2.triangle_index, conn2.triangle_reverse, lineWidth, scaleArray, scaleFunction, false, oMaterial2, vColorTextureMap, sRGB, 0, (float*)textureCoordinates.data(), numCellMaterials, cellMaterials, numPointColors, pointColors.data(), 0, (float*)pointValueTextureCoords.data(), backend)); uniqueMats.insert(oMaterial2); } std::vector<osp::vec3f> normals; int numNormals = 0; if (property->GetInterpolation() != VTK_FLAT) { vtkDataArray* vNormals = poly->GetPointData()->GetNormals(); if (vNormals) { vtkSmartPointer<vtkMatrix4x4> m = vtkSmartPointer<vtkMatrix4x4>::New(); act->GetMatrix(m); vtkSmartPointer<vtkMatrix3x3> mat3 = vtkSmartPointer<vtkMatrix3x3>::New(); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { mat3->SetElement(i, j, m->GetElement(i, j)); } } mat3->Invert(); mat3->Transpose(); vtkosp::VToOPointNormals(vNormals, normals, mat3); numNormals = vNormals->GetNumberOfTuples(); } } texture = property->GetTexture("normalTex"); if (texture) { vNormalTextureMap = texture->GetInput(); } if (property->GetInterpolation() == VTK_PBR) { texture = property->GetTexture("materialTex"); if (texture) { vMaterialTextureMap = texture->GetInput(); } texture = property->GetTexture("anisotropyTex"); if (texture) { vAnisotropyTextureMap = texture->GetInput(); } texture = property->GetTexture("coatNormalTex"); if (texture) { vCoatNormalTextureMap = texture->GetInput(); } } this->GeometricModels.emplace_back( vtkosp::RenderAsTriangles(position, conn.triangle_index, conn.triangle_reverse, useCustomMaterial, oMaterial, numNormals, normals, property->GetInterpolation(), vColorTextureMap, sRGB, vNormalTextureMap, vMaterialTextureMap, vAnisotropyTextureMap, vCoatNormalTextureMap, numTextureCoordinates, (float*)textureCoordinates.data(), texTransform, numCellMaterials, cellMaterials, numPointColors, pointColors.data(), numPointValueTextureCoords, (float*)pointValueTextureCoords.data(), backend)); } } } if (!conn.strip_index.empty()) { switch (property->GetRepresentation()) { case VTK_POINTS: { this->GeometricModels.emplace_back( vtkosp::RenderAsSpheres(vertices.data(), conn.strip_index, conn.strip_reverse, pointSize, scaleArray, scaleFunction, useCustomMaterial, oMaterial, vColorTextureMap, sRGB, numTextureCoordinates, (float*)textureCoordinates.data(), numCellMaterials, cellMaterials, numPointColors, pointColors.data(), numPointValueTextureCoords, (float*)pointValueTextureCoords.data(), backend)); break; } case VTK_WIREFRAME: { this->GeometricModels.emplace_back(vtkosp::RenderAsCylinders(vertices, conn.strip_index, conn.strip_reverse, lineWidth, scaleArray, scaleFunction, useCustomMaterial, oMaterial, vColorTextureMap, sRGB, numTextureCoordinates, (float*)textureCoordinates.data(), numCellMaterials, cellMaterials, numPointColors, pointColors.data(), numPointValueTextureCoords, (float*)pointValueTextureCoords.data(), backend)); break; } default: { if (property->GetEdgeVisibility()) { // edge mesh vtkPolyDataMapperNode::vtkPDConnectivity conn2; vtkPolyDataMapperNode::MakeConnectivity(poly, VTK_WIREFRAME, conn2); // edge material double* eColor = property->GetEdgeColor(); OSPMaterial oMaterial2 = vtkosp::MakeActorMaterial(orn, oRenderer, property, eColor, eColor, specularf, opacity); ospCommit(oMaterial2); this->GeometricModels.emplace_back( vtkosp::RenderAsCylinders(vertices, conn2.strip_index, conn2.strip_reverse, lineWidth, scaleArray, scaleFunction, false, oMaterial2, vColorTextureMap, sRGB, 0, (float*)textureCoordinates.data(), numCellMaterials, cellMaterials, numPointColors, pointColors.data(), 0, (float*)pointValueTextureCoords.data(), backend)); uniqueMats.insert(oMaterial2); } std::vector<osp::vec3f> normals; int numNormals = 0; if (property->GetInterpolation() != VTK_FLAT) { vtkDataArray* vNormals = poly->GetPointData()->GetNormals(); if (vNormals) { vtkSmartPointer<vtkMatrix4x4> m = vtkSmartPointer<vtkMatrix4x4>::New(); act->GetMatrix(m); vtkSmartPointer<vtkMatrix3x3> mat3 = vtkSmartPointer<vtkMatrix3x3>::New(); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { mat3->SetElement(i, j, m->GetElement(i, j)); } } mat3->Invert(); mat3->Transpose(); vtkosp::VToOPointNormals(vNormals, normals, mat3); numNormals = vNormals->GetNumberOfTuples(); } } this->GeometricModels.emplace_back( vtkosp::RenderAsTriangles(position, conn.strip_index, conn.strip_reverse, useCustomMaterial, oMaterial, numNormals, normals, property->GetInterpolation(), vColorTextureMap, sRGB, vNormalTextureMap, vMaterialTextureMap, vAnisotropyTextureMap, vCoatNormalTextureMap, numTextureCoordinates, (float*)textureCoordinates.data(), texTransform, numCellMaterials, cellMaterials, numPointColors, pointColors.data(), numPointValueTextureCoords, (float*)pointValueTextureCoords.data(), backend)); } } } ospRelease(position); for (auto it : mats) { uniqueMats.insert(it.second); } for (OSPMaterial mat : uniqueMats) { ospRelease(mat); } for (auto g : this->GeometricModels) { OSPGroup group = ospNewGroup(); OSPInstance instance = ospNewInstance(group); // valgrind reports instance is lost ospCommit(instance); ospRelease(group); OSPData data = ospNewCopyData1D(&g, OSP_GEOMETRIC_MODEL, 1); ospRelease(&(*g)); ospCommit(data); ospSetObject(group, "geometry", data); ospCommit(group); ospRelease(data); this->Instances.emplace_back(instance); } this->GeometricModels.clear(); } //------------------------------------------------------------------------------ void vtkOSPRayPolyDataMapperNode::Invalidate(bool prepass) { if (prepass) { this->RenderTime = 0; } } //------------------------------------------------------------------------------ void vtkOSPRayPolyDataMapperNode::Render(bool prepass) { if (prepass) { // we use a lot of params from our parent vtkOSPRayActorNode* aNode = vtkOSPRayActorNode::SafeDownCast(this->Parent); vtkActor* act = vtkActor::SafeDownCast(aNode->GetRenderable()); if (act->GetVisibility() == false) { return; } vtkOSPRayRendererNode* orn = static_cast<vtkOSPRayRendererNode*>(this->GetFirstAncestorOfType("vtkOSPRayRendererNode")); // if there are no changes, just reuse last result vtkMTimeType inTime = aNode->GetMTime(); if (this->RenderTime >= inTime) { this->RenderGeometricModels(); return; } this->RenderTime = inTime; this->ClearGeometricModels(); vtkPolyData* poly = nullptr; vtkPolyDataMapper* mapper = vtkPolyDataMapper::SafeDownCast(act->GetMapper()); if (mapper && mapper->GetNumberOfInputPorts() > 0) { poly = mapper->GetInput(); } if (poly) { vtkProperty* property = act->GetProperty(); double ambient[3]; double diffuse[3]; property->GetAmbientColor(ambient); property->GetDiffuseColor(diffuse); this->ORenderPoly( orn->GetORenderer(), aNode, poly, ambient, diffuse, property->GetOpacity(), ""); } this->RenderGeometricModels(); } } //---------------------------------------------------------------------------- void vtkOSPRayPolyDataMapperNode::RenderGeometricModels() { vtkOSPRayRendererNode* orn = static_cast<vtkOSPRayRendererNode*>(this->GetFirstAncestorOfType("vtkOSPRayRendererNode")); for (auto instance : this->Instances) { orn->Instances.emplace_back(instance); } } //---------------------------------------------------------------------------- void vtkOSPRayPolyDataMapperNode::ClearGeometricModels() { vtkOSPRayRendererNode* orn = static_cast<vtkOSPRayRendererNode*>(this->GetFirstAncestorOfType("vtkOSPRayRendererNode")); RTW::Backend* backend = orn->GetBackend(); for (auto instance : this->Instances) ospRelease(&(*instance)); this->Instances.clear(); }
37.315417
100
0.652813
gabrielventosa
290236235d9c903a150cf047abbc35c1493025fa
11,083
cpp
C++
editor/DrawState.cpp
tay10r/libpx
0cdcaf959aed59907f68d08428e3808e69cfc8de
[ "MIT" ]
19
2020-06-16T01:43:26.000Z
2022-01-08T09:12:20.000Z
editor/DrawState.cpp
tay10r/libpx
0cdcaf959aed59907f68d08428e3808e69cfc8de
[ "MIT" ]
3
2020-06-16T10:27:14.000Z
2021-02-10T16:26:54.000Z
editor/DrawState.cpp
tay10r/libpx
0cdcaf959aed59907f68d08428e3808e69cfc8de
[ "MIT" ]
3
2020-10-24T09:26:28.000Z
2021-06-17T04:59:38.000Z
#include "DrawState.hpp" #include "App.hpp" #include "ColorEdit.hpp" #include "DrawPanel.hpp" #include "Input.hpp" #include "LayerPanel.hpp" #include "MenuBar.hpp" #include "Platform.hpp" #include "Renderer.hpp" #include "BucketTool.hpp" #include "ColorPickerTool.hpp" #include "EllipseTool.hpp" #include "EraserTool.hpp" #include "PenTool.hpp" #include "RectTool.hpp" #include "StrokeTool.hpp" #include <libpx.hpp> #include <imgui.h> #include <imgui_stdlib.h> #include <glm/glm.hpp> #include <glm/vec3.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/transform.hpp> #include <memory> #include <cstdio> namespace px { namespace { /// The panel that goes on the left side of the image. /// Shows drawing tools and document properties. class LeftPanel final { /// Whether or not the document size can be changed. bool sizeLock = true; /// Used for editing the background color. ColorEdit4 backgroundEdit; public: /// Renders the left panel. void operator() (App* app, DrawPanel::Observer* drawPanelObserver, DrawPanel& drawPanel) { ImGui::Begin("##left_panel", nullptr, windowFlags()); drawPanel.frame(drawPanelObserver); if (ImGui::CollapsingHeader("Document Properties")) { documentProperties(app); } ImGui::End(); } protected: /// Renders the document properties. void documentProperties(App* app) { documentName(app); documentBackground(app); documentSize(app); } /// Renders the document background setting. void documentBackground(App* app) { float bg[4] { 0, 0, 0, 0 }; getBackground(app->getDocument(), bg); if (backgroundEdit("Background Color", bg)) { setBackground(app->getDocument(), bg); } if (backgroundEdit.isJustStarted()) { app->snapshotDocument(); } if (backgroundEdit.isCommitted()) { app->stashDocument(); } } /// Renders the document name. void documentName(App* app) { auto docName = app->getDocumentName(); if (ImGui::InputText("Name", &docName)) { app->renameDocument(docName.c_str()); } } /// Renders the document size. void documentSize(App* app) { const auto* doc = app->getDocument(); auto w = int(getDocWidth(doc)); auto h = int(getDocHeight(doc)); auto wChanged = ImGui::InputInt("Width", &w); auto hChanged = ImGui::InputInt("Height", &h); if ((wChanged || hChanged) && !sizeLock) { app->snapshotDocument(); app->resizeDocument(w, h); app->stashDocument(); } ImGui::Checkbox("Size Lock", &sizeLock); } /// Gets the window flags used to create /// the left panel window. static constexpr ImGuiWindowFlags windowFlags() { return ImGuiWindowFlags_AlwaysAutoResize; } }; /// The panel that goes on the right side of the image. /// Contains the layers and eventually will also contain /// the navigation panel and the palette table. class RightPanel final { public: /// Renders the right panel. void operator () (App* app, LayerPanel& layerPanel) { ImGui::Begin("##right_panel", nullptr, windowFlags()); layerPanel.frame(app); ImGui::End(); } protected: /// Gets the window flags used to create /// the left panel window. static constexpr ImGuiWindowFlags windowFlags() { return ImGuiWindowFlags_AlwaysAutoResize; } }; /// Represents the application when it is being used /// for drawing the artwork. class DrawStateImpl final : public DrawState, public DrawPanel::Observer { /// Contains state information on /// the drawing tools. DrawPanel drawPanel; /// Shows all the layers from the document. LayerPanel layerPanel; /// The current draw tool. std::unique_ptr<DrawTool> currentTool; /// Contains draw tools, document properties, etc. LeftPanel leftPanel; /// Contains the layers in the document. RightPanel rightPanel; public: DrawStateImpl(App* app) : DrawState(app) { currentTool.reset(new PenTool(this)); } /// Renders the draw state windows. void frame() override { renderDocument(); leftPanel(getApp(), this, drawPanel); rightPanel(getApp(), layerPanel); } /// Handles a mouse button event. void mouseButton(const MouseButtonEvent& mouseButton) override { if (!currentTool) { return; } auto usable = (currentTool->isLeftClickTool() && mouseButton.isLeft()) || (currentTool->isRightClickTool() && mouseButton.isRight()); if (!usable) { return; } auto cursor = ImGui::GetIO().MousePos; auto docPos = windowToDoc(glm::vec2(cursor.x, cursor.y)); if (!currentTool->isActive() && mouseButton.isPressed()) { currentTool->begin(mouseButton, docPos.x, docPos.y); } else if (currentTool->isActive() && mouseButton.isReleased()) { currentTool->end(docPos.x, docPos.y); } } /// Handles mouse motion event. void mouseMotion(const MouseMotionEvent& motion) override { auto pos = windowToDoc(glm::vec2(motion.x, motion.y)); if (currentTool && currentTool->isActive()) { currentTool->drag(motion, pos.x, pos.y); } getPlatform()->getRenderer()->setCursor(pos.x, pos.y); } /// Gets a pointer to the draw panel. const DrawPanel* getDrawPanel() const noexcept override { return &drawPanel; } /// Gets a non-const pointer to the draw panel. DrawPanel* getDrawPanel() noexcept override { return &drawPanel; } /// Gets a pointer to the layer panel. /// /// @return A pointer to the layer panel. const LayerPanel* getLayerPanel() const noexcept override { return &layerPanel; } /// Requires that a layer be available for editing. /// This function will create a layer if it doesn't /// already exist. std::size_t requireCurrentLayer() override { std::size_t layerIndex = 0; if (layerPanel.getSelectedLayer(&layerIndex)) { return layerIndex; } auto* doc = getDocument(); if (!getLayerCount(doc)) { px::addLayer(doc); } return 0; } protected: /// Gets the current window size. glm::vec2 getWinSize() noexcept { std::size_t w = 0; std::size_t h = 0; getPlatform()->getWindowSize(&w, &h); return glm::vec2(float(w), float(h)); } /// Gets the size of the current document snapshot. glm::vec2 getDocSize() const noexcept { const auto* doc = getDocument(); return glm::vec2(float(getDocWidth(doc)), float(getDocHeight(doc))); } /// Calculates the transformation to be applied /// based on the editing position, zoom factor, /// and aspect ratios. glm::mat4 calculateTransform() noexcept { float zoom = getApp()->getZoom(); std::size_t fbW = 0; std::size_t fbH = 0; getPlatform()->getWindowSize(&fbW, &fbH); const auto* doc = getDocument(); std::size_t docW = getDocWidth(doc); std::size_t docH = getDocHeight(doc); float aspectA = float(fbW) / fbH; float aspectB = float(docW) / docH; float scaleX = zoom * (aspectB / aspectA); float scaleY = zoom; return glm::scale(glm::vec3(scaleX, scaleY, 1.0f)); } /// Gets a pointer to the platform interface. Platform* getPlatform() noexcept { return getApp()->getPlatform(); } /// Gets a pointer to the current document snapshot. Document* getDocument() noexcept { return getApp()->getDocument(); } /// Gets a pointer to the current document snapshot. const Document* getDocument() const noexcept { return getApp()->getDocument(); } /// Renders the document onto the window. void renderDocument() { auto* renderer = getPlatform()->getRenderer(); auto transform = calculateTransform(); renderer->setTransform(glm::value_ptr(transform)); auto* doc = getDocument(); auto* image = getApp()->getImage(); render(doc, image); auto* color = getColorBuffer(image); auto w = getImageWidth(image); auto h = getImageHeight(image); renderer->blit(color, w, h); } /// Observes an event from the draw panel. void observe(DrawPanel::Event event) override { switch (event) { case DrawPanel::Event::ChangedBlendMode: break; case DrawPanel::Event::ChangedPixelSize: break; case DrawPanel::Event::ChangedPrimaryColor: break; case DrawPanel::Event::ChangedTool: updateTool(); break; } } /// Changes the currently selected tool, /// based on what's indicating in the draw panel. void updateTool() { currentTool.reset(); switch (drawPanel.getCurrentTool()) { case DrawPanel::Tool::Bucket: currentTool.reset(new BucketTool(this)); break; case DrawPanel::Tool::ColorPicker: currentTool.reset(new ColorPickerTool(this)); break; case DrawPanel::Tool::Ellipse: currentTool.reset(new EllipseTool(this)); break; case DrawPanel::Tool::Eraser: currentTool.reset(new EraserTool(this)); break; case DrawPanel::Tool::Pen: currentTool.reset(new PenTool(this)); break; case DrawPanel::Tool::Rectangle: currentTool.reset(new RectTool(this)); break; case DrawPanel::Tool::Stroke: currentTool.reset(new StrokeTool(this)); break; } } /// Converts a position in window space to a position /// in document space. /// /// @param in The position in window space to convert. /// /// @return The resultant position in document space. glm::vec2 windowToDoc(const glm::vec2& in) noexcept { auto winSize = getWinSize(); auto transform = calculateTransform(); glm::vec4 scaledSize = transform * glm::vec4(winSize.x, winSize.y, 0, 1); auto offset = (winSize - glm::vec2(scaledSize.x, scaledSize.y)) * 0.5f; auto docSize = getDocSize(); auto pos = in - offset; pos = glm::vec2(pos.x * docSize.x / scaledSize.x, pos.y * docSize.y / scaledSize.y); return pos; } /// Converts NDC coordinates to document coordinates. /// /// @param in The NDC coordinates to convert. /// /// @return The NDC coordinates converted to document coordinates. glm::vec2 ndcToDocument(const glm::vec2& in) noexcept { auto w = getDocWidth(getDocument()); auto h = getDocHeight(getDocument()); return glm::vec2 { ((in[0] + 1) * 0.5) * w, ((1 - in[1]) * 0.5) * h }; } #if 0 glm::vec2 docToNDC(const glm::vec2& in) noexcept { } #endif /// Converts window coordinates to NDC coordinates. /// /// @param in The window coordinates to convert. /// /// @return The window coordinates as normalized coordinates. glm::vec2 windowToNDC(const glm::vec2& in) noexcept { std::size_t w = 0; std::size_t h = 0; getPlatform()->getWindowSize(&w, &h); glm::vec2 uv { in[0] / float(w), in[1] / float(h) }; return glm::vec2 { (2 * uv[0]) - 1, 1 - (2 * uv[1]) }; } }; } // namesapce DrawState* DrawState::init(App* app) { return new DrawStateImpl(app); } } // namespace px
24.961712
90
0.643689
tay10r
2906827781d0fba19b4c5e6adab1a47edcbcd851
6,739
cpp
C++
software/build-gui-Qt_5_12_8_qt5_temporary-Profile/app/controls_graphs_FlowGraph_qml.cpp
wajo10/Ventilator
ff6678d8c2b7037113f0947fb2d91b6b07fff7b9
[ "Apache-2.0" ]
null
null
null
software/build-gui-Qt_5_12_8_qt5_temporary-Profile/app/controls_graphs_FlowGraph_qml.cpp
wajo10/Ventilator
ff6678d8c2b7037113f0947fb2d91b6b07fff7b9
[ "Apache-2.0" ]
null
null
null
software/build-gui-Qt_5_12_8_qt5_temporary-Profile/app/controls_graphs_FlowGraph_qml.cpp
wajo10/Ventilator
ff6678d8c2b7037113f0947fb2d91b6b07fff7b9
[ "Apache-2.0" ]
null
null
null
// /controls/graphs/FlowGraph.qml namespace QmlCacheGeneratedCode { namespace _controls_graphs_FlowGraph_qml { extern const unsigned char qmlData alignas(16) [] = { 0x71,0x76,0x34,0x63,0x64,0x61,0x74,0x61, 0x20,0x0,0x0,0x0,0x8,0xc,0x5,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xdc,0x5,0x0,0x0,0x31,0x30,0x31,0x37, 0x39,0x39,0x66,0x38,0x61,0x63,0x64,0x62, 0x66,0x63,0x34,0x65,0x62,0x64,0x30,0x35, 0x66,0x33,0x37,0x61,0x37,0x63,0x30,0x39, 0x35,0x34,0x34,0x64,0x32,0x34,0x62,0x34, 0x31,0x61,0x66,0x31,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x23,0x0,0x0,0x0, 0x11,0x0,0x0,0x0,0x60,0x1,0x0,0x0, 0x1,0x0,0x0,0x0,0xf8,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0xfc,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0xfc,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0xfc,0x0,0x0,0x0, 0x2,0x0,0x0,0x0,0xfc,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x4,0x1,0x0,0x0, 0x2,0x0,0x0,0x0,0x10,0x1,0x0,0x0, 0x0,0x0,0x0,0x0,0x20,0x1,0x0,0x0, 0x0,0x0,0x0,0x0,0x20,0x1,0x0,0x0, 0x0,0x0,0x0,0x0,0x20,0x1,0x0,0x0, 0x0,0x0,0x0,0x0,0x20,0x1,0x0,0x0, 0x0,0x0,0x0,0x0,0x20,0x1,0x0,0x0, 0x0,0x0,0x0,0x0,0x20,0x1,0x0,0x0, 0x0,0x0,0x0,0x0,0x20,0x1,0x0,0x0, 0xff,0xff,0xff,0xff,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0xa8,0x4,0x0,0x0, 0x20,0x1,0x0,0x0,0xf3,0x0,0x0,0x0, 0x0,0x1,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0xb2,0x3f, 0x0,0x0,0x0,0x0,0x0,0x0,0xb2,0xbf, 0x38,0x0,0x0,0x0,0x7,0x0,0x0,0x0, 0xe,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x30,0x0,0x0,0x0,0x30,0x0,0x0,0x0, 0x0,0x0,0x1,0x0,0xff,0xff,0xff,0xff, 0x0,0x0,0x7,0x0,0x0,0x0,0x7,0x0, 0xd,0x0,0x50,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0xd,0x0,0x0,0x0, 0x2e,0x0,0x3a,0x1,0x18,0x6,0x2,0x0, 0xa8,0x1,0x0,0x0,0xc8,0x1,0x0,0x0, 0xf0,0x1,0x0,0x0,0x30,0x2,0x0,0x0, 0x58,0x2,0x0,0x0,0x78,0x2,0x0,0x0, 0xa8,0x2,0x0,0x0,0xd8,0x2,0x0,0x0, 0x0,0x3,0x0,0x0,0x28,0x3,0x0,0x0, 0x50,0x3,0x0,0x0,0x78,0x3,0x0,0x0, 0xa0,0x3,0x0,0x0,0xc8,0x3,0x0,0x0, 0xf0,0x3,0x0,0x0,0x38,0x4,0x0,0x0, 0x78,0x4,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x7,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x51,0x0,0x74,0x0,0x51,0x0,0x75,0x0, 0x69,0x0,0x63,0x0,0x6b,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x10,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x51,0x0,0x74,0x0,0x51,0x0,0x75,0x0, 0x69,0x0,0x63,0x0,0x6b,0x0,0x2e,0x0, 0x43,0x0,0x6f,0x0,0x6e,0x0,0x74,0x0, 0x72,0x0,0x6f,0x0,0x6c,0x0,0x73,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x7,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x52,0x0,0x65,0x0,0x73,0x0,0x70,0x0, 0x69,0x0,0x72,0x0,0x61,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x2,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x2e,0x0,0x2e,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x9,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x53,0x0,0x63,0x0,0x6f,0x0,0x70,0x0, 0x65,0x0,0x56,0x0,0x69,0x0,0x65,0x0, 0x77,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x8,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x66,0x0,0x6c,0x0,0x6f,0x0,0x77,0x0, 0x56,0x0,0x69,0x0,0x65,0x0,0x77,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x4,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x6e,0x0,0x61,0x0,0x6d,0x0,0x65,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x4,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x46,0x0,0x6c,0x0,0x6f,0x0,0x77,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x4,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x75,0x0,0x6e,0x0,0x69,0x0,0x74,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x5,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x4c,0x0,0x2f,0x0,0x6d,0x0,0x69,0x0, 0x6e,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x4,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x79,0x0,0x4d,0x0,0x69,0x0,0x6e,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x4,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x79,0x0,0x4d,0x0,0x61,0x0,0x78,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x7,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x64,0x0,0x61,0x0,0x74,0x0,0x61,0x0, 0x73,0x0,0x65,0x0,0x74,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x16,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x65,0x0,0x78,0x0,0x70,0x0,0x72,0x0, 0x65,0x0,0x73,0x0,0x73,0x0,0x69,0x0, 0x6f,0x0,0x6e,0x0,0x20,0x0,0x66,0x0, 0x6f,0x0,0x72,0x0,0x20,0x0,0x64,0x0, 0x61,0x0,0x74,0x0,0x61,0x0,0x73,0x0, 0x65,0x0,0x74,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x11,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x47,0x0,0x75,0x0,0x69,0x0,0x53,0x0, 0x74,0x0,0x61,0x0,0x74,0x0,0x65,0x0, 0x43,0x0,0x6f,0x0,0x6e,0x0,0x74,0x0, 0x61,0x0,0x69,0x0,0x6e,0x0,0x65,0x0, 0x72,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0xa,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x66,0x0,0x6c,0x0,0x6f,0x0,0x77,0x0, 0x53,0x0,0x65,0x0,0x72,0x0,0x69,0x0, 0x65,0x0,0x73,0x0,0x0,0x0,0x0,0x0, 0x4,0x0,0x0,0x0,0x10,0x0,0x0,0x0, 0x1,0x0,0x0,0x0,0x70,0x0,0x0,0x0, 0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0, 0xb,0x0,0x0,0x0,0x1,0x0,0x10,0x0, 0x1,0x0,0x0,0x0,0x2,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0, 0x4,0x0,0x0,0x0,0x2,0x0,0x10,0x0, 0x1,0x0,0x0,0x0,0x3,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x3,0x0,0x10,0x0, 0x2,0x0,0x0,0x0,0x4,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0x4,0x0,0x10,0x0, 0x74,0x0,0x0,0x0,0x5,0x0,0x0,0x0, 0x6,0x0,0x0,0x0,0x0,0x0,0xff,0xff, 0xff,0xff,0xff,0xff,0x0,0x0,0x0,0x0, 0x44,0x0,0x0,0x0,0x44,0x0,0x0,0x0, 0x44,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x44,0x0,0x0,0x0,0x44,0x0,0x0,0x0, 0x0,0x0,0x5,0x0,0x44,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0xbc,0x0,0x0,0x0, 0x6,0x0,0x10,0x0,0x7,0x0,0x50,0x0, 0xd,0x0,0x0,0x0,0x0,0x0,0x6,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xd,0x0,0x50,0x0,0xd,0x0,0xe0,0x0, 0xc,0x0,0x0,0x0,0x0,0x0,0x2,0x0, 0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xc,0x0,0x50,0x0,0xc,0x0,0xb0,0x0, 0xb,0x0,0x0,0x0,0x0,0x0,0x2,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xb,0x0,0x50,0x0,0xb,0x0,0xb0,0x0, 0x9,0x0,0x0,0x0,0x0,0x0,0x3,0x0, 0x0,0x0,0x0,0x0,0xa,0x0,0x0,0x0, 0x9,0x0,0x50,0x0,0x9,0x0,0xb0,0x0, 0x7,0x0,0x0,0x0,0x0,0x0,0x3,0x0, 0x0,0x0,0x0,0x0,0x8,0x0,0x0,0x0, 0x8,0x0,0x50,0x0,0x8,0x0,0xb0,0x0, 0x0,0x0,0x0,0x0 }; } }
34.208122
53
0.743879
wajo10
290701c5781bd90b45d89b9372e917a8b4dd3533
14,078
cpp
C++
DNPakCrypto/DNPakCrypto/ACT_DNT.cpp
alin1337/DNSkyProject
f2126e7ac547837156c5a192ba4b02755ae2c73b
[ "WTFPL", "Unlicense" ]
4
2017-02-14T16:22:37.000Z
2018-06-10T02:29:44.000Z
DNPakCrypto/DNPakCrypto/ACT_DNT.cpp
alin1337/DNSkyProject
f2126e7ac547837156c5a192ba4b02755ae2c73b
[ "WTFPL", "Unlicense" ]
2
2017-04-14T20:11:24.000Z
2018-07-01T10:57:36.000Z
DNPakCrypto/DNPakCrypto/ACT_DNT.cpp
alin1337/DNSkyProject
f2126e7ac547837156c5a192ba4b02755ae2c73b
[ "WTFPL", "Unlicense" ]
5
2018-02-24T03:03:20.000Z
2022-02-02T02:48:14.000Z
#include <Windows.h> #include <iostream> #include <fstream> #include <algorithm> #include <string> #include <dirent.h> #include <conio.h> #include <time.h> #include "..\\..\\DNSkyProject\\vlizer.h" #include "lzo.h" #include "Header.h" #include <random> #include <stdio.h> #include <VMProtectSDK.h> using namespace std; #include <vector> using namespace std; vector<unsigned char> intToBytes(DWORD paramInt) { vector<unsigned char> arrayOfByte(4); for (int i = 0; i < 4; i++) arrayOfByte[3 - i] = (paramInt >> (i * 8)); return arrayOfByte; } void encrypt_act(const string& s) { string outputF = "encrypted_act\\" + s; std::ifstream infile(s, std::ifstream::binary); if (infile.is_open()) { infile.seekg(0, ios::end); int size = infile.tellg(); BYTE *buffer = new BYTE[size]; infile.seekg(0, ios::beg); infile.read((char*)buffer, size); if (buffer[0x15] == 0xDA || buffer[0x15] == 0xDB) { printf("%s - > Already encrypted, skipping!\n", s.c_str()); return; } if (buffer[0x00] != 'E' && buffer[0x01] != 't') { printf("%s - > Invalid ACT file, skipping!\n", s.c_str()); return; } // ///start! DWORD TotalEncryptedBytes = 0x00; DWORD i = 0x20; int key_size = 0; BYTE key[9] = { 0 }; //generare potentiale chei. DWORD test[256] = { 0 }; for (int i = 0x20; i < size; i++) { if (buffer[i] != 0x00) { test[buffer[i]] += 1; } } VMProtectBeginVirtualization("ACT Encrypt"); //lista cheilor potentiale std::vector<BYTE> chei;// = new std::vector<BYTE>(); // printf("FILE : %s \n",s.c_str()); for (int i = 1; i <= 255;i++) { if (test[i] == 0x00) { // printf("%X = %X\n",i,test[i]); chei.push_back(i); key_size++; } } int MarimeChei = chei.size(); //stabilim dimensiunea fixa 9! if (key_size > 9) key_size = 9; if (key_size != 0 && chei.size() != 0) { //alegerea cheilor din lista //printf("Chei alese : "); for (int i = 0; i < key_size; i++) { /* std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<int> dist(0, chei.size()); */ key[i] = chei[(i*8)%chei.size()] & 0xFF; //hack for (int j = 0; j < chei.size(); j++) { if (chei[j] == key[i]) chei.erase(chei.begin()+j); } // printf("%X ",key[i]); } //printf("\n"); //criptare i = 0x20; //incepem de la 0x20 for (; i < size; i++) { if (buffer[i] != 0x00) { buffer[i] ^= key[i % key_size]; TotalEncryptedBytes++; if (buffer[i] == 0x00) { printf("ATTENTION, NULL HOLE!!! %X , cheie %X\n", i, key[i % key_size]); } } } //printf("%s - > Encrypted %d Bytes, Potential Keys: %d , Total Keys: %d!\n", s.c_str(), TotalEncryptedBytes, MarimeChei, key_size); //scriem header. buffer[0x15] = 0xDA; //este criptatt buffer[0x16] = key_size; //dimensiunea la chei for (int i = 0; i < key_size; i++) { buffer[i + 0x17] = key[i]; //cheile } // //encrypt key length buffer[0x16] ^= buffer[0x24]; }else{ // DWORD CryptoSize = buffer[0x24] * 10; //encrypt header for (DWORD j = 0x28; j < CryptoSize; j++) { buffer[j] ^= cheimagice[j % 512]; TotalEncryptedBytes++; } //encrypt data //encrypt data 8byte block! for (DWORD i = CryptoSize; i < size; i += CryptoSize) { for (DWORD j = 0; j < 8; j++) { buffer[i + j] ^= cheimagice[(j + 2) % 512]; } TotalEncryptedBytes += 8; } //criptare STATICA PHA! buffer[0x15] = 0xDB; //Criptate v2 //printf("%s - > Encrypted %d Bytes! Version 2\n", s.c_str(), TotalEncryptedBytes); } VMProtectEnd(); chei.clear(); ofstream outfile; outfile.open(outputF, ios::out | ios::binary); outfile.write((char*)buffer, size); outfile.close(); infile.close(); free(buffer); } return; } void decrypt_act(const string& s) { string outputF = "decrypted_act\\" + s; std::ifstream infile(s, std::ifstream::binary); if (infile.is_open()) { infile.seekg(0, ios::end); int size = infile.tellg(); BYTE *buffer = new BYTE[size]; infile.seekg(0, ios::beg); infile.read((char*)buffer, size); VMProtectBeginVirtualization("ACT DEcrypt"); if (buffer[0x15] == 0xDA) goto NEXT; if(buffer[0x15] == 0xDB) goto NEXT; printf("%s - > Not encrypted, skipping!\n", s.c_str()); return; NEXT: if (buffer[0x00] != 'E' && buffer[0x01] != 't') { printf("%s - > Invalid ACT file, skipping!\n", s.c_str()); return; } //globala DWORD TotalEncryptedBytes = 0x00; if (buffer[0x15] == 0xDA) { //decrypt key length buffer[0x16] ^= buffer[0x24]; //get keys BYTE key_size = buffer[0x16]; BYTE key[9] = { 0 }; for (BYTE i = 0; i < key_size; i++) { key[i] = buffer[i + 0x17]; } // ///start! DWORD i = 0x20; DWORD j = 0; for (; i < size; i++) { if (buffer[i] != 0x00) { buffer[i] ^= key[i % key_size]; TotalEncryptedBytes++; } } printf("%s - > DEcrypted %d Bytes!\n", s.c_str(), TotalEncryptedBytes); //HERE HEADER char *RaluKat_Stamp = "dRLKT13"; *RaluKat_Stamp = '\0'; i = 0; j = 0x15; for (; i < strlen(RaluKat_Stamp); i++) { buffer[j] = RaluKat_Stamp[i]; j++; } } else if(buffer[0x15] == 0xDB) { DWORD CryptoSize = buffer[0x24] * 10; //encrypt header for (DWORD j = 0x28; j < CryptoSize; j++) { buffer[j] ^= cheimagice[j % 512]; TotalEncryptedBytes++; } //encrypt data for (DWORD i = CryptoSize; i < size; i += CryptoSize) { buffer[i - 2] ^= cheimagice[(i + 2) % 512]; buffer[i - 1] ^= cheimagice[(i + 1) % 512]; buffer[i] ^= cheimagice[i % 512]; TotalEncryptedBytes += 3; } //criptare STATICA PHA! buffer[0x15] = 0x00; //Criptate v2 printf("%s - > DEcrypted %d Bytes!\n", s.c_str(), TotalEncryptedBytes); } VMProtectEnd(); ofstream outfile; outfile.open(outputF, ios::out | ios::binary); outfile.write((char*)buffer, size); outfile.close(); infile.close(); free(buffer); } return; } void encrypt_dnt(const string& s) { string outputF = "encrypted_dnt\\" + s; std::ifstream infile(s, std::ifstream::binary); if (infile.is_open()) { infile.seekg(0, ios::end); int size = infile.tellg(); BYTE *buffer = new BYTE[size]; infile.seekg(0, ios::beg); infile.read((char*)buffer, size); VMProtectBeginVirtualization("DNT Encrypt"); if (buffer[0x00] == 0xDA) { printf("%s - > Already encrypted, skipping!\n", s.c_str()); return; } // buffer[0x00] = 0xDA; DWORD CryptoSize = buffer[4]*10; //encrypt header for (DWORD j = 5; j < CryptoSize; j++) { buffer[j] ^= cheimagice[j % 512]; } //encrypt data 32byte block! for (DWORD i = CryptoSize; i < size; i += CryptoSize) { for (DWORD j = 0; j < 32; j++) { buffer[i + j] ^= cheimagice[(j + 2) % 512]; } } VMProtectEnd(); ofstream outfile; outfile.open(outputF, ios::out | ios::binary); outfile.write((char*)buffer, size); outfile.close(); infile.close(); free(buffer); } return; } void decrypt_dnt(const string& s) { string outputF = "decrypted_dnt\\" + s; std::ifstream infile(s, std::ifstream::binary); if (infile.is_open()) { infile.seekg(0, ios::end); int size = infile.tellg(); BYTE *buffer = new BYTE[size]; infile.seekg(0, ios::beg); infile.read((char*)buffer, size); if (buffer[0x00] != 0xDA) { printf("%s - > Not encrypted, skipping!\n", s.c_str()); return; } buffer[0] = 0x00; DWORD CryptoSize = buffer[4] * 10; VMProtectBeginVirtualization("DNT Decrypt"); //encrypt header for (DWORD j = 5; j < CryptoSize; j++) { buffer[j] ^= cheimagice[j % 512]; } //encrypt data for (DWORD i = CryptoSize; i < size; i += CryptoSize) { buffer[i - 2] ^= cheimagice[(i + 2) % 512]; buffer[i - 1] ^= cheimagice[(i + 1) % 512]; buffer[i] ^= cheimagice[i % 512]; } VMProtectEnd(); ofstream outfile; outfile.open(outputF, ios::out | ios::binary); outfile.write((char*)buffer, size); outfile.close(); infile.close(); free(buffer); } return; } void encryptTEST(const string& s) { string outputF = "encryptedACT-DNT-XML\\" + s; std::ifstream infile(s, std::ifstream::binary); bool isAct = false; if (infile.is_open()) { infile.seekg(0, ios::end); int size = infile.tellg(); BYTE *buffer = new BYTE[size]; BYTE *outBuffer = new BYTE[size*2]; infile.seekg(0, ios::beg); infile.read((char*)buffer, size); DWORD forSize = size+5; for (DWORD i = 0; i < forSize; i++) { outBuffer[i] = 0x00; } if (has_suffix(outputF, ".act")) { isAct = true; } DWORD NewSize = compress(buffer, size, outBuffer); BYTE bFileSize[4] = { 0 }; std::vector<BYTE> bytes = intToBytes(NewSize); for (int i = 0; i < bytes.size(); i++) bFileSize[i] = bytes[i]; if (isAct){ if (outBuffer[size - 1] == 0x00 && outBuffer[size - 2] == 0x00 && outBuffer[size - 3] == 0x00 && outBuffer[size - 4] == 0x00 && outBuffer[size - 5] == 0x00 && outBuffer[size - 6] == 0x00 && outBuffer[size - 7] == 0x00) { outBuffer[size - 1] = bFileSize[0]; outBuffer[size - 2] = bFileSize[1]; outBuffer[size - 3] = bFileSize[2]; outBuffer[size - 4] = bFileSize[3]; outBuffer[size - 5] = 0xDE; outBuffer[size - 7] ^= cheimagice[0]; outBuffer[size - 6] ^= cheimagice[1]; outBuffer[size - 4] ^= cheimagice[2]; outBuffer[size - 3] ^= cheimagice[3]; outBuffer[size - 2] ^= cheimagice[4]; outBuffer[size - 1] ^= cheimagice[5]; } else{ NewSize = 0; //.. } } // ofstream outfile; outfile.open(outputF, ios::out | ios::binary); if (NewSize == 0) { printf("%s NOT CRYPTED!!!!\n", s.c_str()); } else{ printf("%s OK!\n", s.c_str()); } if (NewSize == 0) { outfile.write((char*)buffer, size); //bagam un intreg pt original file size } else if(NewSize>0){ //scrie header! /*if (has_suffix(outputF, ".dnt")) { //outBuffer[3] = 0xDD; } else if (has_suffix(outputF, ".act")) { //outBuffer[0] = 0xDD; } else if (has_suffix(outputF, ".xml")) { //outBuffer[size-7] = 0xDD; }*/ if (!isAct) { outBuffer[size +4] = bFileSize[0]; outBuffer[size +3] = bFileSize[1]; outBuffer[size +2] = bFileSize[2]; outBuffer[size +1] = bFileSize[3]; outBuffer[size] = 0xDD; printf(" %.2X %.2X %.2X %.2X %.2X \n", outBuffer[size], outBuffer[size + 1], outBuffer[size + 2], outBuffer[size + 3], outBuffer[size + 4]); //Criptam footer. outBuffer[size -2] ^= cheimagice[0]; outBuffer[size -1] ^= cheimagice[1]; outBuffer[size +1] ^= cheimagice[2]; outBuffer[size +2] ^= cheimagice[3]; outBuffer[size +3] ^= cheimagice[4]; outBuffer[size +4] ^= cheimagice[5]; } //criptam header #if defined(RO) || defined(CHN) //decrypt header outBuffer[0] ^= cheimagice[10]; outBuffer[1] ^= cheimagice[11]; outBuffer[2] ^= cheimagice[12]; outBuffer[3] ^= cheimagice[13]; #endif if (isAct) { outfile.write((char*)outBuffer, size); //bagam un intreg pt original file size } else { outfile.write((char*)outBuffer, size + 5); //bagam un intreg pt original file size } //outfile.write((char*)bFileSize, sizeof(bFileSize)); //original file size } outfile.close(); infile.close(); free(outBuffer); free(buffer); } } void decryptTEST(const string &s) { string outputF = "decryptedACT-DNT-XML\\" + s; std::ifstream infile(s, std::ifstream::binary); bool isValid = TRUE; bool isAct = false; if (infile.is_open()) { infile.seekg(0, ios::end); int size = infile.tellg(); BYTE *buffer = new BYTE[size]; infile.seekg(0, ios::beg); infile.read((char*)buffer, size); //decriptam footer. if (has_suffix(outputF, ".act")) { if (buffer[size - 5] != 0xDE) { isValid = FALSE; } else if (buffer[size - 5] == 0xDE) { buffer[size - 5] = 0x00; } } if (has_suffix(outputF, ".dnt") || has_suffix(outputF, ".xml")) { if (buffer[size-5] != 0xDD) { isValid = FALSE; } else if (buffer[size - 5] == 0xDD) { buffer[size - 5] = 0x00; } } if (isValid) { #if defined(RO) || defined(CHN) //decrypt header buffer[0] ^= cheimagice[10]; buffer[1] ^= cheimagice[11]; buffer[2] ^= cheimagice[12]; buffer[3] ^= cheimagice[13]; #endif //decrypt footer buffer[size - 7] ^= cheimagice[0]; buffer[size - 6] ^= cheimagice[1]; buffer[size - 4] ^= cheimagice[2]; buffer[size - 3] ^= cheimagice[3]; buffer[size - 2] ^= cheimagice[4]; buffer[size - 1] ^= cheimagice[5]; //printf(" %.2X %.2X %.2X %.2X %.2X %.2X \n", buffer[size], buffer[size - 1], buffer[size - 2], buffer[size - 3], buffer[size - 4], buffer[size - 5]); /*buffer[size - 6] ^= cheimagice[0]; buffer[size - 5] ^= cheimagice[1]; buffer[size - 4] ^= cheimagice[2]; buffer[size - 3] ^= cheimagice[3]; buffer[size - 2] ^= cheimagice[4]; buffer[size - 1] ^= cheimagice[5];*/ } //printf("%x %x %x %x\n", buffer[size - 4], buffer[size - 3], buffer[size - 2], buffer[size-1]); DWORD OrigFileSize = (buffer[size - 1] << 24) | (buffer[size - 2] << 16) | (buffer[size - 3] << 8) | (buffer[size - 4]); //printf("Orig Size: %d\n",OrigFileSize); BYTE *outBuffer = new BYTE[size]; /* BYTE OrigSize[4] = { 0 }; std::vector<BYTE> bytes = intToBytes(size); for (int i = 0; i < bytes.size(); i++) OrigSize[i] = bytes[i]; */ DWORD NewSize = 0; if (isValid) NewSize = decompress(buffer, OrigFileSize, outBuffer); //scoatem int din size if (isValid == FALSE) { printf("%s NOT CRYPTED!!!!\n", s.c_str()); } else{ printf("%s OK!\n", s.c_str()); } ofstream outfile; outfile.open(outputF, ios::out | ios::binary); if (isValid) { outfile.write((char*)outBuffer, NewSize); }else{ outfile.write((char*)buffer, size); } outfile.close(); infile.close(); free(outBuffer); free(buffer); } }
19.912306
221
0.575437
alin1337
290e287b9485e49bf9303d3de19ceaf168fad9ef
2,312
hpp
C++
include/bounded/detail/underlying_type.hpp
davidstone/bounded-integer
d4f9a88a12174ca8382af60b00c5affd19aa8632
[ "BSL-1.0" ]
44
2020-10-03T21:37:52.000Z
2022-03-26T10:08:46.000Z
include/bounded/detail/underlying_type.hpp
davidstone/bounded-integer
d4f9a88a12174ca8382af60b00c5affd19aa8632
[ "BSL-1.0" ]
1
2021-01-01T23:22:39.000Z
2021-01-01T23:22:39.000Z
include/bounded/detail/underlying_type.hpp
davidstone/bounded-integer
d4f9a88a12174ca8382af60b00c5affd19aa8632
[ "BSL-1.0" ]
null
null
null
// Copyright David Stone 2017. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <bounded/detail/comparison.hpp> #include <bounded/detail/int128.hpp> #include <bounded/detail/overlapping_range.hpp> #include <bounded/detail/type.hpp> namespace bounded { namespace detail { template<typename T> constexpr auto range_fits_in_type(auto const minimum, auto const maximum) { return value_fits_in_type<T>(minimum) and value_fits_in_type<T>(maximum); } template<auto...> inline constexpr auto false_ = false; template<auto minimum, auto maximum> constexpr auto determine_type() { if constexpr (range_fits_in_type<unsigned char>(minimum, maximum)) { return types<unsigned char>{}; } else if constexpr (range_fits_in_type<signed char>(minimum, maximum)) { return types<signed char>{}; } else if constexpr (range_fits_in_type<unsigned short>(minimum, maximum)) { return types<unsigned short>{}; } else if constexpr (range_fits_in_type<signed short>(minimum, maximum)) { return types<signed short>{}; } else if constexpr (range_fits_in_type<unsigned int>(minimum, maximum)) { return types<unsigned int>{}; } else if constexpr (range_fits_in_type<signed int>(minimum, maximum)) { return types<signed int>{}; } else if constexpr (range_fits_in_type<unsigned long>(minimum, maximum)) { return types<unsigned long>{}; } else if constexpr (range_fits_in_type<signed long>(minimum, maximum)) { return types<signed long>{}; } else if constexpr (range_fits_in_type<unsigned long long>(minimum, maximum)) { return types<unsigned long long>{}; } else if constexpr (range_fits_in_type<signed long long>(minimum, maximum)) { return types<signed long long>{}; #if defined BOUNDED_DETAIL_HAS_128_BIT } else if constexpr (range_fits_in_type<uint128_t>(minimum, maximum)) { return types<uint128_t>{}; } else if constexpr (range_fits_in_type<int128_t>(minimum, maximum)) { return types<int128_t>{}; #endif } else { static_assert(false_<minimum, maximum>, "Bounds cannot fit in any type."); } } template<auto minimum, auto maximum> using underlying_type_t = typename decltype(determine_type<minimum, maximum>())::type; } // namespace detail } // namespace bounded
36.698413
86
0.754758
davidstone
290f0e43b3e843c5b55ae10774695af5f843ca99
591
cpp
C++
LCP.cpp
laxmena/CodeKata
6ae0b911f1a436f691dfac13a760a53beedf7405
[ "MIT" ]
null
null
null
LCP.cpp
laxmena/CodeKata
6ae0b911f1a436f691dfac13a760a53beedf7405
[ "MIT" ]
null
null
null
LCP.cpp
laxmena/CodeKata
6ae0b911f1a436f691dfac13a760a53beedf7405
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(){ vector<string> bucket; int n,minStr = INT_MAX; string temp; cout<<"enter number of strings: "; cin>>n; for(int i=0;i<n;i++){ cin>>temp; if(temp.size() < minStr) minStr = temp.size(); bucket.push_back(temp); } int prefixLen = 0; for(int i=0;i<minStr;i++){ for(int j=0;j<bucket.size()-1;j++){ if(bucket[j][i] != bucket[j+1][i]){ if(prefixLen == 0) cout<<"No Common Prefix found"; cout<<bucket[0].substr(0,prefixLen)<<endl; return 0; } } prefixLen++; } cout<<bucket[0]<<endl; return 0; }
18.46875
54
0.597293
laxmena
291655fe5de39ea765a8d9575aa61f7c3a8e220e
10,493
hpp
C++
samples/slam_or_pt_tutorial_1/cpp/pt/pt_module.hpp
bram4370/realsense_samples
69a1ca2c00765c76d524da56c6026e7abb95c1e3
[ "Apache-2.0" ]
36
2016-09-27T14:42:59.000Z
2021-09-22T09:45:41.000Z
samples/slam_or_pt_tutorial_1/cpp/pt/pt_module.hpp
bram4370/realsense_samples
69a1ca2c00765c76d524da56c6026e7abb95c1e3
[ "Apache-2.0" ]
12
2016-12-14T18:32:19.000Z
2017-12-19T13:46:04.000Z
samples/slam_or_pt_tutorial_1/cpp/pt/pt_module.hpp
bram4370/realsense_samples
69a1ca2c00765c76d524da56c6026e7abb95c1e3
[ "Apache-2.0" ]
22
2017-01-31T22:23:36.000Z
2022-02-18T11:59:28.000Z
// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2017 Intel Corporation. All Rights Reserved. #pragma once #include <sys/stat.h> #include <string> #include <iostream> #include <unistd.h> #include <thread> #include <mutex> #include <algorithm> #include <set> #include <iomanip> #include <librealsense/rs.hpp> #include <signal.h> #include "rs_sdk.h" #include "person_tracking_video_module_factory.h" namespace RS = Intel::RealSense; using namespace RS::PersonTracking; using namespace std; using namespace rs::core; class PT_module { public: PT_module(module_result_listener_interface* module_listener) : lastPersonCount(0), totalPersonIncrements(0), prevPeopleInFrame(-1), prevPeopleTotal(-1), id_set(nullptr), pt_initialized(false), pt_is_running(false), m_stopped(false), m_module_listener(module_listener) { dataDir = get_data_files_path(); // Create person tracker video module ptModule.reset(rs::person_tracking::person_tracking_video_module_factory:: create_person_tracking_video_module(dataDir.c_str())); m_sample_set = new rs::core::correlated_sample_set(); } int init_pt(rs::core::video_module_interface::supported_module_config& cfg, rs::device* device) { // Configure camera and get parameters for person tracking video module auto actualModuleConfig = ConfigureCamera(device, cfg); // Configure projection rs::core::intrinsics color_intrin = rs::utils::convert_intrinsics(device->get_stream_intrinsics(rs::stream::color)); rs::core::intrinsics depth_intrin = rs::utils::convert_intrinsics(device->get_stream_intrinsics(rs::stream::depth)); rs::core::extrinsics extrinsics = rs::utils::convert_extrinsics(device->get_extrinsics(rs::stream::depth, rs::stream::color)); actualModuleConfig.projection = rs::core::projection_interface::create_instance(&color_intrin, &depth_intrin, &extrinsics); // Enabling Person head pose and orientation ptModule->QueryConfiguration()->QueryTracking()->Enable(); ptModule->QueryConfiguration()->QueryTracking()->SetTrackingMode((Intel::RealSense::PersonTracking::PersonTrackingConfiguration::TrackingConfiguration::TrackingMode)0); // Set the enabled module configuration if(ptModule->set_module_config(actualModuleConfig) != rs::core::status_no_error) { cerr<<"error : failed to set the enabled module configuration" << endl; return -1; } pt_initialized = true; cout << "init_pt complete" << endl; return 0; } bool negotiate_supported_cfg( rs::core::video_module_interface::supported_module_config& slam_config) { slam_config.image_streams_configs[(int)rs::stream::color].size.width = 640; slam_config.image_streams_configs[(int)rs::stream::color].size.height = 480; slam_config[stream_type::color].is_enabled = true; slam_config[stream_type::color].frame_rate = 30.f; return true; } int query_supported_config(rs::device* device, video_module_interface::supported_module_config& supported_config) { supported_config.image_streams_configs[(int)rs::stream::color].size.width = 640; supported_config.image_streams_configs[(int)rs::stream::color].size.height = 480; supported_config[stream_type::color].is_enabled = true; supported_config[stream_type::color].frame_rate = 30.f; supported_config.image_streams_configs[(int)rs::stream::depth].size.width = 320; supported_config.image_streams_configs[(int)rs::stream::depth].size.height = 240; supported_config[stream_type::depth].is_enabled = true; supported_config[stream_type::depth].frame_rate = 30.f; return 0; } int process_pt(rs::core::correlated_sample_set& pt_sample_set) { std::unique_lock<std::mutex> mtx_lock(mtx); if(!pt_initialized || pt_is_running || m_stopped) { // Drop the frame mtx_lock.unlock(); return false; } pt_is_running = true; m_sample_set = &pt_sample_set; std::thread pt_work_thread(&PT_module::pt_worker, this); pt_work_thread.detach(); mtx_lock.unlock(); return 0; } void pt_worker() { // Process frame if (ptModule->process_sample_set(*m_sample_set) != rs::core::status_no_error) { cerr << "error : failed to process sample" << endl; return; } set<int>* new_ids = get_persion_ids(ptModule->QueryOutput()); int numPeopleInFrame = ptModule->QueryOutput()->QueryNumberOfPeople(); if (numPeopleInFrame > lastPersonCount) totalPersonIncrements += (numPeopleInFrame - lastPersonCount); else if(numPeopleInFrame == lastPersonCount && id_set != nullptr) { set<int> diff; set_difference(id_set->begin(), id_set->end(), new_ids->begin(), new_ids->end(), inserter(diff, diff.begin())); totalPersonIncrements += diff.size(); } if (id_set != nullptr) delete id_set; id_set = new_ids; bool people_changed =false; lastPersonCount = numPeopleInFrame; if (numPeopleInFrame != prevPeopleInFrame || totalPersonIncrements != prevPeopleTotal) { prevPeopleInFrame = numPeopleInFrame; prevPeopleTotal = totalPersonIncrements; people_changed = true; } m_module_listener->on_person_tracking_finished(*m_sample_set, numPeopleInFrame, totalPersonIncrements, people_changed); pt_is_running = false; } set<int>* get_persion_ids(PersonTrackingData* trackingData) { set<int>* id_set = new set<int>; for (int index = 0; index < trackingData->QueryNumberOfPeople(); ++index) { PersonTrackingData::Person* personData = trackingData->QueryPersonData( Intel::RealSense::PersonTracking::PersonTrackingData::ACCESS_ORDER_BY_INDEX, index); if (personData) { PersonTrackingData::PersonTracking* personTrackingData = personData->QueryTracking(); int id = personTrackingData->QueryId(); id_set->insert(id); } } return id_set; } wstring get_data_files_path() { struct stat stat_struct; if(stat(PERSON_TRACKING_DATA_FILES, &stat_struct) != 0) { cerr << "Failed to find person tracking data files at " << PERSON_TRACKING_DATA_FILES << endl; cerr << "Please check that you run sample from correct directory" << endl; exit(EXIT_FAILURE); } string person_tracking_data_files = PERSON_TRACKING_DATA_FILES; int size = person_tracking_data_files.length(); wchar_t wc_person_tracking_data_files[size + 1]; mbstowcs(wc_person_tracking_data_files, person_tracking_data_files.c_str(), size + 1); return wstring(wc_person_tracking_data_files); } rs::core::video_module_interface::actual_module_config ConfigureCamera ( rs::device* device, rs::core::video_module_interface::supported_module_config& cfg) { rs::core::video_module_interface::actual_module_config actualModuleConfig = {}; // Person tracking uses only color & depth vector<rs::core::stream_type> possible_streams = {rs::core::stream_type::depth, rs::core::stream_type::color }; for (auto &stream : possible_streams) { rs::stream librealsenseStream = rs::utils::convert_stream_type(stream); auto &supported_stream_config = cfg[stream]; int width = supported_stream_config.size.width; int height = supported_stream_config.size.height; int frame_rate = supported_stream_config.frame_rate; rs::core::video_module_interface::actual_image_stream_config &actualStreamConfig = actualModuleConfig[stream]; actualStreamConfig.size.width = width; actualStreamConfig.size.height = height; actualStreamConfig.frame_rate = frame_rate; actualStreamConfig.intrinsics = rs::utils::convert_intrinsics( device->get_stream_intrinsics(librealsenseStream)); actualStreamConfig.extrinsics = rs::utils::convert_extrinsics( device->get_extrinsics(rs::stream::depth, librealsenseStream)); actualStreamConfig.is_enabled = true; } return actualModuleConfig; } int8_t get_pixel_size(rs::format format) { switch(format) { case rs::format::any: return 0; case rs::format::z16: return 2; case rs::format::disparity16: return 2; case rs::format::xyz32f: return 4; case rs::format::yuyv: return 2; case rs::format::rgb8: return 3; case rs::format::bgr8: return 3; case rs::format::rgba8: return 4; case rs::format::bgra8: return 4; case rs::format::y8: return 1; case rs::format::y16: return 2; case rs::format::raw8: return 1; case rs::format::raw10: return 0;//not supported case rs::format::raw16: return 2; } } bool get_pt_running() { return pt_is_running; } bool get_pt_is_ready() { return pt_initialized && !pt_is_running && !m_stopped; } void stop() { m_stopped = true; } private: wstring dataDir; unique_ptr<rs::person_tracking::person_tracking_video_module_interface> ptModule; int lastPersonCount; int totalPersonIncrements; int prevPeopleInFrame; int prevPeopleTotal; set<int> *id_set; bool pt_initialized; bool pt_is_running; bool m_stopped; std::mutex mtx; rs::core::correlated_sample_set* m_sample_set; module_result_listener_interface* m_module_listener; };
34.976667
176
0.631755
bram4370
29180c6f6adc24d05286dceb2845501570ccbef1
5,028
cpp
C++
example/Mcached/McachedRequestHandler.cpp
fasShare/moxie-simple
9b21320f868ca1fe05ca5d39e70eb053d31155ee
[ "MIT" ]
1
2018-09-27T09:10:11.000Z
2018-09-27T09:10:11.000Z
example/Mcached/McachedRequestHandler.cpp
fasShare/moxie-simple
9b21320f868ca1fe05ca5d39e70eb053d31155ee
[ "MIT" ]
1
2018-09-16T07:17:29.000Z
2018-09-16T07:17:29.000Z
example/Mcached/McachedRequestHandler.cpp
fasShare/moxie-simple
9b21320f868ca1fe05ca5d39e70eb053d31155ee
[ "MIT" ]
null
null
null
#include <McachedRequestHandler.h> #include <mraft/floyd/include/floyd.h> extern floyd::Floyd *floyd_raft; moxie::McachedClientHandler::McachedClientHandler(const std::shared_ptr<PollerEvent>& client, const std::shared_ptr<moxie::NetAddress>& cad) : event_(client), peer_(cad), argc_(0), argv_() { } void moxie::McachedClientHandler::AfetrRead(const std::shared_ptr<PollerEvent>& event, EventLoop *loop) { if (ParseRedisRequest()) { DoMcachedCammand(); } if (writeBuf_.writableBytes()) { event_->EnableWrite(); loop->Modity(event); } } void moxie::McachedClientHandler::AfetrWrite(const std::shared_ptr<PollerEvent>& event, EventLoop *loop) { if (writeBuf_.readableBytes() > 0) { return; } event->DisableWrite(); loop->Modity(event); } bool moxie::McachedClientHandler::DoMcachedCammand() { ResetArgcArgv reset(argc_, argv_); assert(argc_ == argv_.size()); assert(argc_ > 0); assert(floyd_raft); //DebugArgcArgv(); slash::Status s; std::string res; s = floyd_raft->ExecMcached(argv_, res); if (s.ok()) { if (argv_[0] == "SET" || argv_[0] == "set") { res = "+OK\r\n"; ReplyString(res); } else if (argv_[0] == "get" || argv_[0] == "GET") { ReplyBulkString(res); } } else { if (argv_[0] == "SET" || argv_[0] == "set") { res = "-ERR write " + s.ToString() + " \r\n"; } else if (argv_[0] == "get" || argv_[0] == "GET") { res = "-ERR read " + s.ToString() + " \r\n"; } else { res = "-ERR request " + s.ToString() + " \r\n"; } ReplyString(res); } return true; } bool moxie::McachedClientHandler::ParseRedisRequest() { if (readBuf_.readableBytes() <= 0) { return false; } if (argc_ <= 0) { // parse buffer to get argc argv_.clear(); curArgvlen_ = -1; const char* crlf = readBuf_.findChars(Buffer::kCRLF, 2); if (crlf == nullptr) { return false; } std::string argc_str = readBuf_.retrieveAsString(crlf - readBuf_.peek()); if (argc_str[0] != '*') { ReplyString("-ERR Protocol error: invalid multibulk length\r\n"); return false; } argc_ = std::atoi(argc_str.c_str() + sizeof('*')); if (argc_ == 0) { ReplyString("-ERR Protocol error: invalid multibulk length\r\n"); return false; } // \r\n readBuf_.retrieve(2); //std::cout << "argc:" << argc_ << std::endl; } while (argv_.size() < argc_) { const char* crlf = readBuf_.findChars(Buffer::kCRLF, 2); if (crlf == nullptr) { return false; } if (curArgvlen_ < 0) { std::string argv_len = readBuf_.retrieveAsString(crlf - readBuf_.peek()); if (argv_len[0] != '$') { curArgvlen_ = -1; argc_ = 0; //std::cout << argv_len << " " << argv_len[0] << std::endl; ReplyString("-ERR Protocol error: invalid bulk length (argv_len)\r\n"); return false; } // remove $ curArgvlen_ = std::atoi(argv_len.c_str() + sizeof('$')); //std::cout << "curArgvlen_:" << curArgvlen_ << std::endl; // \r\n readBuf_.retrieve(2); } else { std::string argv_str = readBuf_.retrieveAsString(crlf - readBuf_.peek()); if (static_cast<ssize_t>(argv_str.size()) != curArgvlen_) { curArgvlen_ = -1; argc_ = 0; std::cout << argv_str << std::endl; ReplyString("-ERR Protocol error: invalid bulk length (argv_str)\r\n"); return false; } argv_.push_back(argv_str); //std::cout << "argv_str:" << argv_str << std::endl; // \r\n readBuf_.retrieve(2); curArgvlen_ = -1; // must do, to read next argv item } } // request can be solved if ((argc_ > 0) && (argv_.size() == argc_)) { return true; } return false; } void moxie::McachedClientHandler::DebugArgcArgv() const { std::cout << peer_->getIp() << ":" << peer_->getPort() << "->"; for (size_t index = 0; index < argc_; index++) { std::cout << argv_[index]; if (index != argc_ - 1) { std::cout << " "; } } std::cout << std::endl; } void moxie::McachedClientHandler::ReplyString(const std::string& error) { writeBuf_.append(error.c_str(), error.size()); } void moxie::McachedClientHandler::ReplyBulkString(const std::string& item) { writeBuf_.append("$", 1); std::string len = std::to_string(item.size()); writeBuf_.append(len.c_str(), len.size()); writeBuf_.append(Buffer::kCRLF, 2); writeBuf_.append(item.c_str(), item.size()); writeBuf_.append(Buffer::kCRLF, 2); }
31.425
143
0.532617
fasShare
291fd98f7c6b94875b3190bd3ced10dbdf31a604
344
cc
C++
util/env_win_detail/win_misc.cc
tamaskenez/leveldb
fa5614c35a7c58051e5f1d26f50f0c632a7f3e19
[ "BSD-3-Clause" ]
null
null
null
util/env_win_detail/win_misc.cc
tamaskenez/leveldb
fa5614c35a7c58051e5f1d26f50f0c632a7f3e19
[ "BSD-3-Clause" ]
null
null
null
util/env_win_detail/win_misc.cc
tamaskenez/leveldb
fa5614c35a7c58051e5f1d26f50f0c632a7f3e19
[ "BSD-3-Clause" ]
null
null
null
#include "win_misc.h" void usleep(int usec) { Sleep((usec + 999)/1000); } int getpagesize(void) { SYSTEM_INFO si; GetSystemInfo(&si); return si.dwPageSize; } bool ftruncate(const winapi::File& fd, int64_t length) { bool b = fd.setFilePointerEx(length, NULL, FILE_BEGIN); if ( !b ) return false; return fd.setEndOfFile(); }
15.636364
57
0.677326
tamaskenez
292c33e3752b32af894fab2470a5e26ae45f7175
11,507
cc
C++
Source/Plugins/GraphicsPlugins/BladeTerrain/source/TerrainBlock.cc
OscarGame/blade
6987708cb011813eb38e5c262c7a83888635f002
[ "MIT" ]
146
2018-12-03T08:08:17.000Z
2022-03-21T06:04:06.000Z
Source/Plugins/GraphicsPlugins/BladeTerrain/source/TerrainBlock.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
1
2019-01-18T03:35:49.000Z
2019-01-18T03:36:08.000Z
Source/Plugins/GraphicsPlugins/BladeTerrain/source/TerrainBlock.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
31
2018-12-03T10:32:43.000Z
2021-10-04T06:31:44.000Z
/******************************************************************** created: 2010/05/13 filename: TerrainBlock.cc author: Crazii purpose: *********************************************************************/ #include <BladePCH.h> #include <interface/IGraphicsSystem.h> #include <interface/IRenderQueue.h> #include "TerrainBufferManager.h" #include "TerrainBlock.h" #include "BlockQuery.h" namespace Blade { static const uint BLOCK_UPDATE_LOD = 0x01; static const uint BLOCK_UPDATE_INDICES = 0x02; ////////////////////////////////////////////////////////////////////////// TerrainBlock::TerrainBlock(index_t x,index_t z, ITerrainTile* parent) :mParent(parent) ,mFixedLOD(INVALID_FIXED_LOD) ,mLODLevel(0) ,mLODDiffIndex(LODDI_NONE) ,mMaterialLOD(0) { mUpdateFlags |= CUF_DEFAULT_VISIBLE | CUF_VISIBLE_UPDATE; mSpaceFlags = CSF_CONTENT | CSF_SHADOWCASTER; const TERRAIN_INFO& GTInfo = TerrainConfigManager::getSingleton().getTerrainInfo(); mBlockIndex.mX = (uint16)x; mBlockIndex.mZ = (uint16)z; mBlockIndex.mIndex = (uint32)( mBlockIndex.mX + mBlockIndex.mZ*GTInfo.mBlocksPerTileSide); const TILE_INFO& tileInfo = mParent->getTileInfo(); GraphicsGeometry& geometry = tileInfo.mRenderGeomBuffer[ this->getBlockIndex() ]; geometry.reset(); //setup render geometry geometry.useIndexBuffer(true); geometry.mIndexBuffer = NULL; geometry.mIndexCount = 0; geometry.mIndexStart = 0; geometry.mVertexSource = tileInfo.mVertexSource; geometry.mVertexDecl = TerrainConfigManager::getRenderType().getVertexDeclaration(); geometry.mVertexCount = (uint32)TerrainConfigManager::getSingleton().getTerrainBlockVertexCount(); geometry.mVertexStart = 0; geometry.mPrimitiveType = GraphicsGeometry::GPT_TRIANGLE_LIST; #if BLADE_DEBUG mQueued = 0; #endif if( IGraphicsSystem::getSingleton().getCurrentProfile() > BTString("2_0") ) tileInfo.mScene->getMaterialLODUpdater()->addForLODUpdate(this); } TerrainBlock::~TerrainBlock() { if(mParent->getTileInfo().mScene != NULL) mParent->getTileInfo().mScene->getMaterialLODUpdater()->removeFromLODUpdate(this); } /************************************************************************/ /* SpaceContent overrides */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// void TerrainBlock::updateRender(IRenderQueue* queue) { const TILE_INFO& tileInfo = mParent->getTileInfo(); assert(tileInfo.mMaterialLODCount == 0 || mMaterialLOD < tileInfo.mMaterialLODCount); if(tileInfo.mLODMaterials != NULL && mMaterialLOD < tileInfo.mMaterialLODCount) { TerrainConfigManager& tcm = static_cast<TerrainConfigManager&>(*mParent->getConfigManager()); ITerrainBatchCombiner* combiner = tcm.getBatchCombiner(); IRenderQueue* redirect = mParent->getTileInfo().mOutputBuffer; if (redirect != NULL && combiner->needCombine(queue) ) { #if BLADE_DEBUG //assert(mQueued == 0); mQueued = 1; #endif redirect->addRenderable(this); } else { this->updateIndexBuffer(); queue->addRenderable(this); } } } ////////////////////////////////////////////////////////////////////////// void TerrainBlock::visibleUpdateImpl(const Vector3& cameraPos) { uint8& updateMask = mParent->getTileInfo().mUpdatedMask[this->getBlockIndex()]; if (updateMask & BLOCK_UPDATE_LOD) //multiple camera update optimize. return; updateMask |= BLOCK_UPDATE_LOD; #define ADAPTIVE_FIXED_LOD 0 //TODO: use adaptive fixed LOD will need morph height for adapted level. #if !ADAPTIVE_FIXED_LOD if (mFixedLOD != INVALID_FIXED_LOD) mLODLevel = mFixedLOD; else #endif { //Vector3 CameraDir = cameraRotation*Vector3::NEGATIVE_UNIT_Z; //Vector3 Vec = mPostion - cameraPos; //scalar dist = Vec.dotProduct(CameraDir); //mLODLevel = TerrainConfigManager::getSingleton().getLODLevelByDistance(dist); //get LOD level only at horizontal dimension //to avoid LOD level gap, when height different is too large Vector3 position = mWorldAABB.getCenter(); Vector2 pos2(position.x, position.z); Vector2 camPos2(cameraPos.x, cameraPos.z); scalar SqrDist = pos2.getSquaredDistance(camPos2); mLODLevel = static_cast<TerrainConfigManager*>(mParent->getConfigManager())->getLODLevelBySquaredDistance(SqrDist); } #if ADAPTIVE_FIXED_LOD if (mFixedLOD != INVALID_FIXED_LOD) { if (mFixedLOD == TerrainConfigManager::getSingleton().getFlatLODLevel()) mLODLevel = std::max<uint8>(mFixedLOD, mLODLevel); else // mLODLevel = std::min<uint8>(mFixedLOD, mLODLevel); } #endif #if BLADE_DEBUG if(mLastLODLevel != mLODLevel) mLastLODLevel = mLODLevel; mQueued = 0; #endif } ////////////////////////////////////////////////////////////////////////// bool TerrainBlock::queryNearestPoint(SpaceQuery& query, scalar& distance) const { //transform ray to local space (actually it's tile's local space, not block's local space, because block's all vertices are in tile's space) StaticHandle<SpaceQuery> transformed = query.clone(this->getWorldTransform().getInverse()); const TERRAIN_POSITION_DATA_Y* vposition = mParent->getSoftHeightPositionData(); const TERRAIN_POSITION_DATA_XZ* hposition = TerrainBufferManager::getSingleton().getSoftHorizontalPositionBuffer(); const TerrainQueryIndexGroup* group = mParent->getQueryIndexBuffer(); size_t blockSize = TerrainConfigManager::getSingleton().getTerrainBlockSize(); BlockQuery blockQuery; blockQuery.initialize(vposition + mVertexStart, hposition + mVertexStart, group, mBlockIndex.mX*blockSize, mBlockIndex.mZ*blockSize); AABB localAABB = this->getWorldAABB(); localAABB.offset(-mParent->getStartPos()); blockQuery.setAABB(localAABB); BlockVolumeQuery q(this->getWorldTransform()[3], *transformed, mLODLevel, (LOD_DI)mLODDiffIndex); q.mDistance = distance; bool ret = blockQuery.raycastPoint(q); if (ret) { //skip scale since not scale for terrain blocks distance = q.mDistance; } return ret; } ////////////////////////////////////////////////////////////////////////// bool TerrainBlock::intersectTriangles(SpaceQuery& query, POS_VOL contentPos/* = PV_INTERSECTED*/) const { bool result = false; //transform the volume from world space to local space StaticHandle<SpaceQuery> transformed = query.clone( this->getWorldTransform().getInverse() ); const TERRAIN_POSITION_DATA_Y* vposition = mParent->getSoftHeightPositionData(); const TERRAIN_POSITION_DATA_XZ* hposition = TerrainBufferManager::getSingleton().getSoftHorizontalPositionBuffer(); const TerrainQueryIndexGroup* group = mParent->getQueryIndexBuffer(); size_t blockSize = TerrainConfigManager::getSingleton().getTerrainBlockSize(); BlockQuery blockQuery; blockQuery.initialize(vposition+mVertexStart, hposition+mVertexStart, group, mBlockIndex.mX*blockSize, mBlockIndex.mZ*blockSize); AABB localAABB = this->getWorldAABB(); localAABB.offset(-mParent->getStartPos()); blockQuery.setAABB(localAABB); BlockVolumeQuery q(this->getWorldTransform()[3], *transformed, mLODLevel, (LOD_DI)mLODDiffIndex); result = blockQuery.intersect(q, contentPos); return result; } /************************************************************************/ /* custom methods */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// void TerrainBlock::setVertexOffsetCount(index_t startVertex, size_t count) { mVertexStart = startVertex; mVertexCount = (uint16)count; } ////////////////////////////////////////////////////////////////////////// void TerrainBlock::updateIndexBuffer(bool force/* = false*/) { uint8& updateMask = mParent->getTileInfo().mUpdatedMask[this->getBlockIndex()]; if ((updateMask & BLOCK_UPDATE_INDICES) && !force) //multiple camera update optimize return; updateMask |= BLOCK_UPDATE_INDICES; TerrainConfigManager& tcm = static_cast<TerrainConfigManager&>(*mParent->getConfigManager()); ILODComparator* LODCmp = tcm.getIndexGenerator(); LODDiff diff; FixedLODDiff fixedDiff; TerrainBlock* up = mParent->getTerrainBlock((int)this->getBlockX(), (int)this->getBlockZ()-1); if (up != NULL && (fixedDiff.t=(int8)LODCmp->compareLOD(up->getCurrentLODLevel(), mLODLevel)) > 0 && !up->isFixedLOD()) diff.setUpDiff(); TerrainBlock* left = mParent->getTerrainBlock((int)this->getBlockX()-1, (int)this->getBlockZ()); if (left != NULL && (fixedDiff.l=(int8)LODCmp->compareLOD(left->getCurrentLODLevel(), mLODLevel)) > 0 && !left->isFixedLOD()) diff.setLeftDiff(); TerrainBlock* down = mParent->getTerrainBlock((int)this->getBlockX(), (int)this->getBlockZ()+1); if (down != NULL && (fixedDiff.b=(int8)LODCmp->compareLOD(down->getCurrentLODLevel(), mLODLevel)) > 0 && !down->isFixedLOD() ) diff.setDownDiff(); TerrainBlock* right = mParent->getTerrainBlock((int)this->getBlockX()+1, (int)this->getBlockZ()); if (right != NULL && (fixedDiff.r=(int8)LODCmp->compareLOD(right->getCurrentLODLevel(), mLODLevel)) > 0 && !right->isFixedLOD()) diff.setRightDiff(); GraphicsGeometry& geometry = mParent->getTileInfo().mRenderGeomBuffer[this->getBlockIndex()]; if (mFixedLOD != INVALID_FIXED_LOD && fixedDiff.isValid() && mLODLevel == tcm.getFlatLODLevel()) { //adaption only work for one side(flat or cliff), disable flat LOD adaption int8 specialDiff = (int8)LODCmp->compareLOD(tcm.getCliffLODLevel(), mLODLevel); if (std::abs(specialDiff) > 1) { assert(mLODLevel >= 1u); if (fixedDiff.l == specialDiff && left != NULL && left->isFixedLOD()) fixedDiff.l = 0; if (fixedDiff.t == specialDiff && up != NULL && up->isFixedLOD() ) fixedDiff.t = 0; if (fixedDiff.r == specialDiff && right != NULL && right->isFixedLOD()) fixedDiff.r = 0; if (fixedDiff.b == specialDiff && down != NULL && down->isFixedLOD()) fixedDiff.b = 0; } } if (mFixedLOD != INVALID_FIXED_LOD && mLODLevel == mFixedLOD && fixedDiff.isValid()) geometry.mIndexBuffer = mParent->getFixedIndexBuffer(mLODLevel, fixedDiff, this->getBlockIndex(), geometry.mIndexStart, geometry.mIndexCount); else { mLODDiffIndex = (uint8)LODDiff::generateDifferenceIndex(diff); #if BLADE_DEBUG if (mLastLODDiffIndex != mLODDiffIndex) mLastLODDiffIndex = mLODDiffIndex; #endif geometry.mIndexBuffer = mParent->getIndexBuffer(mLODLevel, (LOD_DI)mLODDiffIndex, this->getBlockIndex(), geometry.mIndexStart, geometry.mIndexCount); } geometry.mIndexCount = (uint32)geometry.mIndexBuffer->getIndexCount(); geometry.mVertexStart = (uint32)mVertexStart; geometry.mVertexCount = (uint32)mVertexCount; } ////////////////////////////////////////////////////////////////////////// void TerrainBlock::updateMaterial() { const TILE_INFO& tileInfo = mParent->getTileInfo(); assert(tileInfo.mMaterialLODCount > 0); if (mMaterialLOD >= tileInfo.mMaterialLODCount) mMaterialLOD = tileInfo.mMaterialLODCount - 1u; } ////////////////////////////////////////////////////////////////////////// void TerrainBlock::cacheOut() { assert(this->getSpace() == NULL); //mParent->getTileInfo().mScene->getMaterialLODUpdater()->removeFromLODUpdate(this); this->setElement(NULL); } }//namespace Blade
39.954861
152
0.656644
OscarGame
292d58375aa0a24f7cc246038919d9346209326d
2,449
hpp
C++
lib/runtime/public/atelier/hash.hpp
giranath/atelier
e1b9056b6f930979c03057bba306005943cf1b12
[ "MIT" ]
null
null
null
lib/runtime/public/atelier/hash.hpp
giranath/atelier
e1b9056b6f930979c03057bba306005943cf1b12
[ "MIT" ]
null
null
null
lib/runtime/public/atelier/hash.hpp
giranath/atelier
e1b9056b6f930979c03057bba306005943cf1b12
[ "MIT" ]
null
null
null
#ifndef ATELIER_RUNTIME_HASH_HPP #define ATELIER_RUNTIME_HASH_HPP #include "runtime_export.hpp" #include <cstdint> #include <iterator> #include <type_traits> #include <string_view> namespace at { // Current default Hash function is fnv1a inline namespace fnv1a { /** * Hash a range of bytes * @tparam It The iterator on the range of byte * @param begin The first iterator on the range * @param end The iterator after the last on the range * @return The hash value of the range * @note FNV-1a implementation */ template<typename It> [[nodiscard]] constexpr uint64_t hash(It begin, It end) noexcept { using iterator_value_type = typename std::iterator_traits<It>::value_type; static_assert(std::is_convertible_v<iterator_value_type, uint8_t>, "Iterator must be on bytes"); constexpr const uint64_t fnv_offset_basis = 0xcbf29ce484222325; constexpr const uint64_t fnv_prime = 0x00000100000001B3; uint64_t h = fnv_offset_basis; for (; begin != end; ++begin) { h ^= static_cast<uint8_t>(*begin); h *= fnv_prime; } return h; } /** * Hash a string * @param str The string to hash * @return The hash value of the string */ [[nodiscard]] constexpr uint64_t hash(std::string_view str) noexcept { return hash(str.begin(), str.end()); } /** * Hash a memory block * @param memory The memory block to hash * @param size The size of the memory block * @return The hash value for this memory block */ [[nodiscard]] ATELIER_RUNTIME_EXPORT uint64_t hash(const void* memory, std::size_t size) noexcept; } namespace literals { /** * String literals to create compile time hash * @param str The string to hash * @param length The length of the string to hash * @return The hashed value of the string */ [[nodiscard]] constexpr uint64_t operator ""_h(const char* str, std::size_t length) { return hash(std::string_view{str, length}); } } /** * Combine two hashes * @param h1 The first hash to combine with h2 * @param h2 The second hash to combine with h1 * @return A new hash constructed from two other hashes * @note The order used to combine hashes is important * Implementation based on this stack overflow answer: https://stackoverflow.com/a/27952689 */ [[nodiscard]] constexpr uint64_t hash_combine(uint64_t h1, uint64_t h2) noexcept { const uint64_t combined_hash = h1 ^ h2 + 0x9e3779b97f4a7c16 + (h1 << 6) + (h1 >> 2); return combined_hash; } } #endif
25.247423
100
0.716211
giranath
292ed96e6b0f49d1171d85f28473c10f4acfee32
658
cpp
C++
src/debug/stdmsg.cpp
mirpm/mirp-avr
ff2521b8ccd5314e7f7c357dd36982d9c954a30d
[ "Apache-2.0" ]
1
2017-04-12T20:00:00.000Z
2017-04-12T20:00:00.000Z
src/debug/stdmsg.cpp
mirpm/mirp-avr
ff2521b8ccd5314e7f7c357dd36982d9c954a30d
[ "Apache-2.0" ]
null
null
null
src/debug/stdmsg.cpp
mirpm/mirp-avr
ff2521b8ccd5314e7f7c357dd36982d9c954a30d
[ "Apache-2.0" ]
null
null
null
#include "stdmsg.h" /* * Initialises the standard messaging debug system */ bool StdMsg::Init() { UART::Init(); return true; } /* * Sends a warning via stdmsg and hex codes */ bool StdMsg::SendWarning(msg warning) { UART::PutChar(warning.type[0]); UART::PutChar(warning.type[1]); UART::PutChar(warning.eid); UART::PutChar(warning.msg); UART::PutChar('\n'); return true; } /* * Compares two commands, returns true if they are * the same and vice versa */ bool StdMsg::CommandCompare(command a, command b) { if(a.type[0] == b.type[0]) if(a.type[1] == b.type[1]) if(a.msg == a.msg) return true; return false; }
18.277778
51
0.636778
mirpm
292ede574b22b7ab5f41ac7c70ce1c9159eb3906
16,477
cpp
C++
src/v_pfx.cpp
351ELEC/lzdoom
2ee3ea91bc9c052b3143f44c96d85df22851426f
[ "RSA-MD" ]
2
2018-01-18T21:30:20.000Z
2018-01-19T02:24:46.000Z
src/v_pfx.cpp
351ELEC/lzdoom
2ee3ea91bc9c052b3143f44c96d85df22851426f
[ "RSA-MD" ]
4
2021-09-02T00:05:17.000Z
2021-09-07T14:56:12.000Z
src/v_pfx.cpp
351ELEC/lzdoom
2ee3ea91bc9c052b3143f44c96d85df22851426f
[ "RSA-MD" ]
1
2021-09-28T19:03:39.000Z
2021-09-28T19:03:39.000Z
/* ** v_pfx.cpp ** Pixel format conversion routines ** **--------------------------------------------------------------------------- ** Copyright 1998-2006 Randy Heit ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** 3. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **--------------------------------------------------------------------------- ** */ #include "doomtype.h" #include "i_system.h" #include "v_palette.h" #include "v_pfx.h" PfxUnion GPfxPal; PfxState GPfx; static bool AnalyzeMask (uint32_t mask, uint8_t *shift); static void Palette16Generic (const PalEntry *pal); static void Palette16R5G5B5 (const PalEntry *pal); static void Palette16R5G6B5 (const PalEntry *pal); static void Palette32Generic (const PalEntry *pal); static void Palette32RGB (const PalEntry *pal); static void Palette32BGR (const PalEntry *pal); static void Scale8 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac); static void Convert8 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac); static void Convert16 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac); static void Convert24 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac); static void Convert32 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac); void PfxState::SetFormat (int bits, uint32_t redMask, uint32_t greenMask, uint32_t blueMask) { switch (bits) { case -8: Convert = Scale8; SetPalette = NULL; break; case 8: Convert = Convert8; SetPalette = NULL; break; case 16: if (redMask == 0x7c00 && greenMask == 0x03e0 && blueMask == 0x001f) { SetPalette = Palette16R5G5B5; } else if (redMask == 0xf800 && greenMask == 0x07e0 && blueMask == 0x001f) { SetPalette = Palette16R5G6B5; } else { SetPalette = Palette16Generic; } Convert = Convert16; Masks.Bits16.Red = (uint16_t)redMask; Masks.Bits16.Green = (uint16_t)greenMask; Masks.Bits16.Blue = (uint16_t)blueMask; break; case 24: if (redMask == 0xff0000 && greenMask == 0x00ff00 && blueMask == 0x0000ff) { SetPalette = Palette32RGB; Convert = Convert24; } else if (redMask == 0x0000ff && greenMask == 0x00ff00 && blueMask == 0xff0000) { SetPalette = Palette32BGR; Convert = Convert24; } else { I_FatalError ("24-bit displays are only supported if they are RGB or BGR"); }; break; case 32: if (redMask == 0xff0000 && greenMask == 0x00ff00 && blueMask == 0x0000ff) { SetPalette = Palette32RGB; } else if (redMask == 0x0000ff && greenMask == 0x00ff00 && blueMask == 0xff0000) { SetPalette = Palette32BGR; } else { SetPalette = Palette32Generic; } Convert = Convert32; Masks.Bits32.Red = redMask; Masks.Bits32.Green = greenMask; Masks.Bits32.Blue = blueMask; break; default: I_FatalError ("Can't draw to %d-bit displays", bits); } if (bits != 8 && bits != -8) { RedLeft = AnalyzeMask (redMask, &RedShift); GreenLeft = AnalyzeMask (greenMask, &GreenShift); BlueLeft = AnalyzeMask (blueMask, &BlueShift); } } static bool AnalyzeMask (uint32_t mask, uint8_t *shiftout) { uint8_t shift = 0; if (mask >= 0xff) { while (mask > 0xff) { shift++; mask >>= 1; } *shiftout = shift; return true; } else { while (mask < 0xff) { shift++; mask <<= 1; } *shiftout = shift; return false; } } // Palette converters ------------------------------------------------------ static void Palette16Generic (const PalEntry *pal) { uint16_t *p16; int i; for (p16 = GPfxPal.Pal16, i = 256; i != 0; i--, pal++, p16++) { uint16_t rpart, gpart, bpart; if (GPfx.RedLeft) rpart = pal->r << GPfx.RedShift; else rpart = pal->r >> GPfx.RedShift; if (GPfx.GreenLeft) gpart = pal->g << GPfx.GreenShift; else gpart = pal->g >> GPfx.GreenShift; if (GPfx.BlueLeft) bpart = pal->b << GPfx.BlueShift; else bpart = pal->b >> GPfx.BlueShift; *p16 = (rpart & GPfx.Masks.Bits16.Red) | (gpart & GPfx.Masks.Bits16.Green) | (bpart & GPfx.Masks.Bits16.Blue); } } static void Palette16R5G5B5 (const PalEntry *pal) { uint16_t *p16; int i; for (p16 = GPfxPal.Pal16, i = 256; i != 0; i--, pal++, p16++) { *p16 = ((pal->r << 7) & 0x7c00) | ((pal->g << 2) & 0x03e0) | ((pal->b >> 3) & 0x001f); } } static void Palette16R5G6B5 (const PalEntry *pal) { uint16_t *p16; int i; for (p16 = GPfxPal.Pal16, i = 256; i != 0; i--, pal++, p16++) { *p16 = ((pal->r << 8) & 0xf800) | ((pal->g << 3) & 0x07e0) | ((pal->b >> 3) & 0x001f); } } static void Palette32Generic (const PalEntry *pal) { uint32_t *p32; int i; for (p32 = GPfxPal.Pal32, i = 256; i != 0; i--, pal++, p32++) { uint32_t rpart, gpart, bpart; if (GPfx.RedLeft) rpart = pal->r << GPfx.RedShift; else rpart = pal->r >> GPfx.RedShift; if (GPfx.GreenLeft) gpart = pal->g << GPfx.GreenShift; else gpart = pal->g >> GPfx.GreenShift; if (GPfx.BlueLeft) bpart = pal->b << GPfx.BlueShift; else bpart = pal->b >> GPfx.BlueShift; *p32 = (rpart & GPfx.Masks.Bits32.Red) | (gpart & GPfx.Masks.Bits32.Green) | (bpart & GPfx.Masks.Bits32.Blue); } } static void Palette32RGB (const PalEntry *pal) { memcpy (GPfxPal.Pal32, pal, 256*4); } static void Palette32BGR (const PalEntry *pal) { uint32_t *p32; int i; for (p32 = GPfxPal.Pal32, i = 256; i != 0; i--, pal++, p32++) { *p32 = (pal->r) | (pal->g << 8) | (pal->b << 16); } } // Bitmap converters ------------------------------------------------------- static void Scale8 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac) { if ((destwidth | destheight) == 0) { return; } int x, y, savedx; uint8_t *dest = (uint8_t *)destin; if (xstep == FRACUNIT && ystep == FRACUNIT) { for (y = destheight; y != 0; y--) { memcpy(dest, src, destwidth); dest += destpitch; src += srcpitch; } } else if (xstep == FRACUNIT/2 && ystep == FRACUNIT/2) { uint8_t *dest2 = dest + destpitch; destpitch = destpitch * 2 - destwidth; srcpitch -= destwidth / 2; for (y = destheight / 2; y != 0; --y) { for (x = destwidth / 2; x != 0; --x) { uint8_t foo = src[0]; dest[0] = foo; dest[1] = foo; dest2[0] = foo; dest2[1] = foo; dest += 2; dest2 += 2; src += 1; } dest += destpitch; dest2 += destpitch; src += srcpitch; } } else if (xstep == FRACUNIT/4 && ystep == FRACUNIT/4) { int gap = destpitch * 4 - destwidth; srcpitch -= destwidth / 4; for (y = destheight / 4; y != 0; --y) { for (uint8_t *end = dest + destpitch; dest != end; dest += 4) { uint8_t foo = src[0]; dest[0] = foo; dest[1] = foo; dest[2] = foo; dest[3] = foo; dest[0 + destpitch] = foo; dest[1 + destpitch] = foo; dest[2 + destpitch] = foo; dest[3 + destpitch] = foo; dest[0 + destpitch*2] = foo; dest[1 + destpitch*2] = foo; dest[2 + destpitch*2] = foo; dest[3 + destpitch*2] = foo; dest[0 + destpitch*3] = foo; dest[1 + destpitch*3] = foo; dest[2 + destpitch*3] = foo; dest[3 + destpitch*3] = foo; src += 1; } dest += gap; src += srcpitch; } } else { destpitch -= destwidth; for (y = destheight; y != 0; y--) { fixed_t xf = xfrac; x = destwidth; while (((size_t)dest & 3) && x != 0) { *dest++ = src[xf >> FRACBITS]; xf += xstep; x--; } for (savedx = x, x >>= 2; x != 0; x--) { uint32_t work; #ifdef __BIG_ENDIAN__ work = src[xf >> FRACBITS] << 24; xf += xstep; work |= src[xf >> FRACBITS] << 16; xf += xstep; work |= src[xf >> FRACBITS] << 8; xf += xstep; work |= src[xf >> FRACBITS]; xf += xstep; #else work = src[xf >> FRACBITS]; xf += xstep; work |= src[xf >> FRACBITS] << 8; xf += xstep; work |= src[xf >> FRACBITS] << 16; xf += xstep; work |= src[xf >> FRACBITS] << 24; xf += xstep; #endif *(uint32_t *)dest = work; dest += 4; } for (savedx &= 3; savedx != 0; savedx--, xf += xstep) { *dest++ = src[xf >> FRACBITS]; } yfrac += ystep; while (yfrac >= FRACUNIT) { yfrac -= FRACUNIT; src += srcpitch; } dest += destpitch; } } } static void Convert8 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac) { if ((destwidth | destheight) == 0) { return; } int x, y, savedx; uint8_t *dest = (uint8_t *)destin; destpitch -= destwidth; if (xstep == FRACUNIT && ystep == FRACUNIT) { srcpitch -= destwidth; for (y = destheight; y != 0; y--) { x = destwidth; while (((size_t)dest & 3) && x != 0) { *dest++ = GPfxPal.Pal8[*src++]; x--; } for (savedx = x, x >>= 2; x != 0; x--) { *(uint32_t *)dest = #ifdef __BIG_ENDIAN__ (GPfxPal.Pal8[src[0]] << 24) | (GPfxPal.Pal8[src[1]] << 16) | (GPfxPal.Pal8[src[2]] << 8) | (GPfxPal.Pal8[src[3]]); #else (GPfxPal.Pal8[src[0]]) | (GPfxPal.Pal8[src[1]] << 8) | (GPfxPal.Pal8[src[2]] << 16) | (GPfxPal.Pal8[src[3]] << 24); #endif dest += 4; src += 4; } for (savedx &= 3; savedx != 0; savedx--) { *dest++ = GPfxPal.Pal8[*src++]; } dest += destpitch; src += srcpitch; } } else { for (y = destheight; y != 0; y--) { fixed_t xf = xfrac; x = destwidth; while (((size_t)dest & 3) && x != 0) { *dest++ = GPfxPal.Pal8[src[xf >> FRACBITS]]; xf += xstep; x--; } for (savedx = x, x >>= 2; x != 0; x--) { uint32_t work; #ifdef __BIG_ENDIAN__ work = GPfxPal.Pal8[src[xf >> FRACBITS]] << 24; xf += xstep; work |= GPfxPal.Pal8[src[xf >> FRACBITS]] << 16; xf += xstep; work |= GPfxPal.Pal8[src[xf >> FRACBITS]] << 8; xf += xstep; work |= GPfxPal.Pal8[src[xf >> FRACBITS]]; xf += xstep; #else work = GPfxPal.Pal8[src[xf >> FRACBITS]]; xf += xstep; work |= GPfxPal.Pal8[src[xf >> FRACBITS]] << 8; xf += xstep; work |= GPfxPal.Pal8[src[xf >> FRACBITS]] << 16; xf += xstep; work |= GPfxPal.Pal8[src[xf >> FRACBITS]] << 24; xf += xstep; #endif *(uint32_t *)dest = work; dest += 4; } for (savedx &= 3; savedx != 0; savedx--, xf += xstep) { *dest++ = GPfxPal.Pal8[src[xf >> FRACBITS]]; } yfrac += ystep; while (yfrac >= FRACUNIT) { yfrac -= FRACUNIT; src += srcpitch; } dest += destpitch; } } } static void Convert16 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac) { if ((destwidth | destheight) == 0) { return; } int x, y, savedx; uint16_t *dest = (uint16_t *)destin; destpitch = (destpitch >> 1) - destwidth; if (xstep == FRACUNIT && ystep == FRACUNIT) { srcpitch -= destwidth; for (y = destheight; y != 0; y--) { x = destwidth; if ((size_t)dest & 1) { x--; *dest++ = GPfxPal.Pal16[*src++]; } for (savedx = x, x >>= 1; x != 0; x--) { *(uint32_t *)dest = #ifdef __BIG_ENDIAN__ (GPfxPal.Pal16[src[0]] << 16) | (GPfxPal.Pal16[src[1]]); #else (GPfxPal.Pal16[src[0]]) | (GPfxPal.Pal16[src[1]] << 16); #endif dest += 2; src += 2; } if (savedx & 1) { *dest++ = GPfxPal.Pal16[*src++]; } dest += destpitch; src += srcpitch; } } else { for (y = destheight; y != 0; y--) { fixed_t xf = xfrac; x = destwidth; if ((size_t)dest & 1) { *dest++ = GPfxPal.Pal16[src[xf >> FRACBITS]]; xf += xstep; x--; } for (savedx = x, x >>= 1; x != 0; x--) { uint32_t work; #ifdef __BIG_ENDIAN__ work = GPfxPal.Pal16[src[xf >> FRACBITS]] << 16; xf += xstep; work |= GPfxPal.Pal16[src[xf >> FRACBITS]]; xf += xstep; #else work = GPfxPal.Pal16[src[xf >> FRACBITS]]; xf += xstep; work |= GPfxPal.Pal16[src[xf >> FRACBITS]] << 16; xf += xstep; #endif *(uint32_t *)dest = work; dest += 2; } if (savedx & 1) { *dest++ = GPfxPal.Pal16[src[xf >> FRACBITS]]; } yfrac += ystep; while (yfrac >= FRACUNIT) { yfrac -= FRACUNIT; src += srcpitch; } dest += destpitch; } } } static void Convert24 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac) { if ((destwidth | destheight) == 0) { return; } int x, y; uint8_t *dest = (uint8_t *)destin; destpitch = destpitch - destwidth*3; if (xstep == FRACUNIT && ystep == FRACUNIT) { srcpitch -= destwidth; for (y = destheight; y != 0; y--) { for (x = destwidth; x != 0; x--) { uint8_t *pe = GPfxPal.Pal24[src[0]]; dest[0] = pe[0]; dest[1] = pe[1]; dest[2] = pe[2]; dest += 3; src++; } dest += destpitch; src += srcpitch; } } else { for (y = destheight; y != 0; y--) { fixed_t xf = xfrac; for (x = destwidth; x != 0; x--) { uint8_t *pe = GPfxPal.Pal24[src[xf >> FRACBITS]]; dest[0] = pe[0]; dest[1] = pe[1]; dest[2] = pe[2]; xf += xstep; dest += 2; } yfrac += ystep; while (yfrac >= FRACUNIT) { yfrac -= FRACUNIT; src += srcpitch; } dest += destpitch; } } } static void Convert32 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac) { if ((destwidth | destheight) == 0) { return; } int x, y, savedx; uint32_t *dest = (uint32_t *)destin; destpitch = (destpitch >> 2) - destwidth; if (xstep == FRACUNIT && ystep == FRACUNIT) { srcpitch -= destwidth; for (y = destheight; y != 0; y--) { for (savedx = x = destwidth, x >>= 3; x != 0; x--) { dest[0] = GPfxPal.Pal32[src[0]]; dest[1] = GPfxPal.Pal32[src[1]]; dest[2] = GPfxPal.Pal32[src[2]]; dest[3] = GPfxPal.Pal32[src[3]]; dest[4] = GPfxPal.Pal32[src[4]]; dest[5] = GPfxPal.Pal32[src[5]]; dest[6] = GPfxPal.Pal32[src[6]]; dest[7] = GPfxPal.Pal32[src[7]]; dest += 8; src += 8; } for (x = savedx & 7; x != 0; x--) { *dest++ = GPfxPal.Pal32[*src++]; } dest += destpitch; src += srcpitch; } } else { for (y = destheight; y != 0; y--) { fixed_t xf = xfrac; for (savedx = x = destwidth, x >>= 1; x != 0; x--) { dest[0] = GPfxPal.Pal32[src[xf >> FRACBITS]]; xf += xstep; dest[1] = GPfxPal.Pal32[src[xf >> FRACBITS]]; xf += xstep; dest += 2; } if (savedx & 1) { *dest++ = GPfxPal.Pal32[src[xf >> FRACBITS]]; } yfrac += ystep; while (yfrac >= FRACUNIT) { yfrac -= FRACUNIT; src += srcpitch; } dest += destpitch; } } }
23.914369
92
0.583237
351ELEC
a0955b149daa0b7e685e0bf3372985371779237d
5,012
cpp
C++
src/kernel/tengine/arm64/tengine_conv_2d_wino.cpp
mapnn/mapnn
fcd5ae04b9b9df809281882872842daaf5a35db0
[ "Apache-2.0" ]
2
2021-01-01T02:01:11.000Z
2022-02-15T02:50:44.000Z
src/kernel/tengine/arm64/tengine_conv_2d_wino.cpp
mapnn/mapnn
fcd5ae04b9b9df809281882872842daaf5a35db0
[ "Apache-2.0" ]
null
null
null
src/kernel/tengine/arm64/tengine_conv_2d_wino.cpp
mapnn/mapnn
fcd5ae04b9b9df809281882872842daaf5a35db0
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 The Mapnn Team. 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 "tengine_kernel.h" #include <executor/operator/arm64/conv/winograd/wino_trans_ker.h> #include <executor/operator/arm64/conv/winograd/wino_trans_inp.h> #include <executor/operator/arm64/conv/winograd/wino_sgemm.h> #include <executor/operator/arm64/conv/winograd/conv_2d_wino.h> #define TILE 4 namespace mapnn { void tengine_conv_2d_wino::init(const Tensors& ins, Tensor& out, Tensors& tmp, Operator& op) { Conv conv(op); L1CHW input(ins[0]); L1CHW output(out); L1VAB temp0(tmp[0]); L1VAB temp1(tmp[1]); const int extented_filter_h = conv.hdilation * (conv.hkernel - 1) + 1; const int extented_filter_w = conv.wdilation * (conv.wkernel - 1) + 1; const int output_xy = output.hw; const int kernel_size = input.c * conv.hkernel * conv.wkernel; output.c = conv.outch; output.h = (input.h - extented_filter_h) / conv.hstride + 1; output.w = (input.w - extented_filter_w) / conv.wstride + 1; int block_h = (output.h + TILE - 1) / TILE; int block_w = (output.w + TILE - 1) / TILE; int block_hw = block_h * block_w; int padded_inh = TILE * block_h + 2; int padded_inw = TILE * block_w + 2; int pad_inhw = padded_inh * padded_inw; int inp_padded_size = (input.c * pad_inhw + 2); temp0.u = 1; temp0.v = 1; temp0.a = inp_padded_size; temp1.u = 1; temp1.v = 1; temp1.a = ELEM_SIZE * input.c * block_hw + 32; } void tengine_conv_2d_wino::run(const Tensors& ins, Tensor& out, Tensors& tmp, Operator& op) { Conv conv(op); L1CHW output(out); L1CHW input(ins[0]); L1VAB weight(ins[1]); L111W biast(ins[2]); L1VAB temp0(tmp[0]); L1VAB temp1(tmp[1]); int pad_h0 = 0; int pad_w0 = 0; int cpu_type = TYPE_A53; int activation = -1; float* input_org = input.data; int input_c = input.c; int input_h = input.h; int input_w = input.w; int inp_chw = input_c * input_h * input_w; float* output_org = output.data; int output_h = output.h; int output_w = output.w; int output_c = output.c; int out_hw = output_h * output_w; int out_chw = out_hw * output_c; int output_n = 1; int block_h = (output_h + TILE - 1) / TILE; int block_w = (output_w + TILE - 1) / TILE; int block_hw = block_h * block_w; int padded_inh = TILE * block_h + 2; int padded_inw = TILE * block_w + 2; int pad_inhw = padded_inh * padded_inw; int nn_block = block_hw / BLOCK_HW_UNIT; int resi_block = nn_block * BLOCK_HW_UNIT; int resi_w = block_w * TILE - output_w; int resi_h = block_h * TILE - output_h; float* kernel_interleaved = weight.data; float* input_padded = temp0.data; float* trans_inp = temp1.data; float* bias = biast.data; int bias_term = biast.data != NULL; int block_4 = (block_hw+3)/4; int L2_CACHE_SIZE = (cpu_type == TYPE_A53) ? 512 * 1024 : 1024 * 1024; int L2_n = L2_CACHE_SIZE * 0.3 / (ELEM_SIZE * input_c * sizeof(float)); L2_n = L2_n > 16 ? (L2_n & -16) : 16; int cout_count16 = output_c/16; int cout_nn16 = cout_count16*16; for(int n = 0; n < output_n; n++) { float* input = input_org + n * inp_chw; float* output = output_org + n * out_chw; // pad_trans_interleave_inp pad_input1(input, input_padded, input_c, input_h, input_w, padded_inh, padded_inw, pad_h0, pad_w0); tran_input_4block(input_padded, trans_inp, input_c, 0, nn_block, block_w, pad_inhw, padded_inw); if(resi_block != block_hw) tran_input_resi_block(input_padded, trans_inp, input_c, nn_block, resi_block, block_hw, block_w, pad_inhw, padded_inw); wino_sgemm_4x16(kernel_interleaved, trans_inp, output, bias, bias_term, input_c, cpu_type, 0, cout_nn16, 0, block_hw, block_h, block_w, out_hw, output_w, resi_h, resi_w, activation); if(cout_nn16!=output_c) { wino_sgemm_4x4(kernel_interleaved, trans_inp, output, bias, bias_term, input_c, cpu_type, cout_nn16,output_c , 0, block_hw, block_h, block_w, out_hw, output_w, resi_h, resi_w, activation); } } } }
37.969697
125
0.627893
mapnn
a0985c4b23376a6bcf7e633ff0a6a998a3c5a33c
358
cpp
C++
SourceCode/Chapter 04/Pr4-3.cpp
aceiro/poo2019
0f93d22296f43a8b024a346f510c00314817d2cf
[ "MIT" ]
1
2019-04-09T18:29:38.000Z
2019-04-09T18:29:38.000Z
SourceCode/Chapter 04/Pr4-3.cpp
aceiro/poo2019
0f93d22296f43a8b024a346f510c00314817d2cf
[ "MIT" ]
null
null
null
SourceCode/Chapter 04/Pr4-3.cpp
aceiro/poo2019
0f93d22296f43a8b024a346f510c00314817d2cf
[ "MIT" ]
null
null
null
// This program demonstrates how a misplaced semicolon // prematurely terminates an if statement. #include <iostream> using namespace std; int main() { int x = 0, y = 10; cout << "x is " << x << " and y is " << y << endl; if (x > y); // Error! Misplaced semicolon cout << "x is greater than y\n"; //This is always executed. return 0; }
25.571429
65
0.611732
aceiro
a09a2b4f05ad623f8c253e4b604db59e5ec42fc4
290
cpp
C++
GeneticEvolution/main.cpp
nikluep/genetic-evo
c1556a9d5c7098b8a6b4392469b442cee718b6f3
[ "MIT" ]
null
null
null
GeneticEvolution/main.cpp
nikluep/genetic-evo
c1556a9d5c7098b8a6b4392469b442cee718b6f3
[ "MIT" ]
null
null
null
GeneticEvolution/main.cpp
nikluep/genetic-evo
c1556a9d5c7098b8a6b4392469b442cee718b6f3
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <SFML/Graphics.hpp> #include "Network.h" #include "Stage.h" int main() { Stage stage(3, 3000); sf::RenderWindow window(sf::VideoMode(1920, 1080), "Genetic Drone Evolution"); stage.init(window); stage.run(); return 0; }
16.111111
82
0.655172
nikluep
a0a497ab0c143d4db16f543dce6e56df6180c43b
2,476
cpp
C++
2021/20/a.cpp
kidonm/advent-of-code
b304d99d60dcdd9d67105964f2c6a6d8729ecfd6
[ "Apache-2.0" ]
null
null
null
2021/20/a.cpp
kidonm/advent-of-code
b304d99d60dcdd9d67105964f2c6a6d8729ecfd6
[ "Apache-2.0" ]
null
null
null
2021/20/a.cpp
kidonm/advent-of-code
b304d99d60dcdd9d67105964f2c6a6d8729ecfd6
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <iostream> #include <map> #include <queue> #include <set> #include <sstream> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; typedef unsigned long long ull; typedef pair<int, int> ipair; typedef vector<int> coord; void widen(deque<deque<char>> &img, int times, char c) { for (auto &row : img) { for (int i = 0; i < times; i++) { row.push_front(c); row.push_back(c); } } deque<char> r(img[0].size(), c); for (int i = 0; i < times; i++) { img.push_front(r); img.push_back(r); } }; void print(deque<deque<char>> &img) { for (auto row : img) { for (auto col : row) { printf("%c", col); } printf("\n"); } printf("\n"); } int index(int i, int j, deque<deque<char>> &src, char frame) { int ix = 0; int m = src.size(); int n = src[0].size(); for (int di : {-1, 0, 1}) { for (int dj : {-1, 0, 1}) { int bit = 0; if (i + di >= 0 && i + di < m && j + dj >= 0 && j + dj < n) { bit = src[i + di][j + dj] == '.' ? 0 : 1; } else { bit = frame == '.' ? 0 : 1; } // printf("%d", bit); ix += bit; // ix *= 2; if (dj == 1 && di == 1) continue; ix *= 2; } } // ix /= 2; return ix; // dst[i][j] = code[ix]; } int main() { int times = 2; string code; deque<deque<char>> img; getline(cin, code); string s; getline(cin, s); while (getline(cin, s)) { deque<char> tmp; for (char c : s) { tmp.push_back(c); } img.push_back(tmp); } // printf("index: %d", index(2, 2, img)); // return 0; // printf("%lu %lu\n", img.size(), img[0].size()); // return 0; char frame = '.'; widen(img, 2, frame); for (int t = 0; t < times; t++) { deque<deque<char>> next(img); // print(img); for (int i = 0; i < img.size(); i++) { for (int j = 0; j < img[0].size(); j++) { next[i][j] = code[index(i, j, img, frame)]; } } // char frame = t % 2 == 1 ? code[0] : code[code.size() - 1]; // if (code[0] == '.') frame = '.'; // printf("here\n"); img = next; frame = img[0][0]; // print(img); widen(img, 1, frame); } print(img); int sum = 0; for (int i = 0; i < img.size(); i++) { for (int j = 0; j < img[0].size(); j++) { if (img[i][j] == '#') sum++; } } printf("%lu %lu %d\n", img.size(), img[0].size(), sum); return 0; }
19.650794
67
0.477787
kidonm
a0a5ef886fba1e320663486b9c6a451dabd8a65e
10,427
cpp
C++
src/shogun/labels/MultilabelLabels.cpp
Arpit2601/shogun
e509f8c57f47dc74b3f791d450a70b770d11582a
[ "BSD-3-Clause" ]
1
2019-10-02T11:10:08.000Z
2019-10-02T11:10:08.000Z
src/shogun/labels/MultilabelLabels.cpp
Arpit2601/shogun
e509f8c57f47dc74b3f791d450a70b770d11582a
[ "BSD-3-Clause" ]
null
null
null
src/shogun/labels/MultilabelLabels.cpp
Arpit2601/shogun
e509f8c57f47dc74b3f791d450a70b770d11582a
[ "BSD-3-Clause" ]
1
2020-06-02T09:15:40.000Z
2020-06-02T09:15:40.000Z
/* * Copyright (C) 2013 Zuse-Institute-Berlin (ZIB) * Copyright (C) 2013-2014 Thoralf Klein * Written (W) 2013-2014 Thoralf Klein * 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the Shogun Development Team. */ #include <shogun/labels/MultilabelLabels.h> #include <shogun/io/SGIO.h> // for require, io::print, etc using namespace shogun; CMultilabelLabels::CMultilabelLabels() : CLabels() { init(0, 1); } CMultilabelLabels::CMultilabelLabels(int32_t num_classes) : CLabels() { init(0, num_classes); } CMultilabelLabels::CMultilabelLabels(int32_t num_labels, int32_t num_classes) : CLabels() { init(num_labels, num_classes); } CMultilabelLabels::~CMultilabelLabels() { delete[] m_labels; } void CMultilabelLabels::init(int32_t num_labels, int32_t num_classes) { require(num_labels >= 0, "num_labels={} should be >= 0", num_labels); require(num_classes > 0, "num_classes={} should be > 0", num_classes); // This one does consider the contained labels, so its simply BROKEN // Can be disabled as SG_ADD(&m_num_labels, "m_num_labels", "number of labels"); SG_ADD(&m_num_classes, "m_num_classes", "number of classes"); // SG_ADD((CSGObject**) &m_labels, "m_labels", "The labels"); // Can only be enabled after this issue has been solved: // https://github.com/shogun-toolbox/shogun/issues/1972 /* this->m_parameters->add(&m_num_labels, "m_num_labels", "Number of labels."); this->m_parameters->add(&m_num_classes, "m_num_classes", "Number of classes."); this->m_parameters->add_vector(&m_labels, &m_num_labels, "labels_array", "The label vectors for all (num_labels) outputs."); */ m_num_labels = num_labels; m_num_classes = num_classes; m_labels = new SGVector <int32_t>[m_num_labels]; } bool CMultilabelLabels::is_valid() const { for (int32_t label_j = 0; label_j < get_num_labels(); label_j++) { if (!CMath::is_sorted(m_labels[label_j])) return false; int32_t c_len = m_labels[label_j].vlen; if (c_len <= 0) { continue; } if (m_labels[label_j].vector[0] < 0) return false; if (m_labels[label_j].vector[c_len - 1] >= get_num_classes()) return false; } return true; } void CMultilabelLabels::ensure_valid(const char* context) { require( is_valid(), "Multilabel labels need to be sorted and in [0, num_classes-1]."); } int32_t CMultilabelLabels::get_num_labels() const { return m_num_labels; } int32_t CMultilabelLabels::get_num_classes() const { return m_num_classes; } void CMultilabelLabels::set_labels(SGVector <int32_t> * labels) { for (int32_t label_j = 0; label_j < m_num_labels; label_j++) { m_labels[label_j] = labels[label_j]; } ensure_valid("set_labels()"); } SGVector <int32_t> ** CMultilabelLabels::get_class_labels() const { SGVector <int32_t> ** labels_list = SG_MALLOC(SGVector <int32_t> *, get_num_classes()); int32_t * num_label_idx = SG_MALLOC(int32_t, get_num_classes()); for (int32_t class_i = 0; class_i < get_num_classes(); class_i++) { num_label_idx[class_i] = 0; } for (int32_t label_j = 0; label_j < get_num_labels(); label_j++) { for (int32_t c_pos = 0; c_pos < m_labels[label_j].vlen; c_pos++) { int32_t class_i = m_labels[label_j][c_pos]; require(class_i < get_num_classes(), "class_i exceeded number of classes"); num_label_idx[class_i]++; } } for (int32_t class_i = 0; class_i < get_num_classes(); class_i++) { labels_list[class_i] = new SGVector <int32_t> (num_label_idx[class_i]); } SG_FREE(num_label_idx); int32_t * next_label_idx = SG_MALLOC(int32_t, get_num_classes()); for (int32_t class_i = 0; class_i < get_num_classes(); class_i++) { next_label_idx[class_i] = 0; } for (int32_t label_j = 0; label_j < get_num_labels(); label_j++) { for (int32_t c_pos = 0; c_pos < m_labels[label_j].vlen; c_pos++) { // get class_i of current position int32_t class_i = m_labels[label_j][c_pos]; require(class_i < get_num_classes(), "class_i exceeded number of classes"); // next free element in m_classes[class_i]: int32_t l_pos = next_label_idx[class_i]; require(l_pos < labels_list[class_i]->size(), "l_pos exceeded length of label list"); next_label_idx[class_i]++; // finally, story label_j into class-column (*labels_list[class_i])[l_pos] = label_j; } } SG_FREE(next_label_idx); return labels_list; } SGMatrix<int32_t> CMultilabelLabels::get_labels() const { if (m_num_labels==0) return SGMatrix<int32_t>(); int32_t n_outputs = m_labels[0].vlen; SGMatrix<int32_t> labels(m_num_labels, n_outputs); for (int32_t i=0; i<m_num_labels; i++) { require(m_labels[i].vlen==n_outputs, "This function is valid only for multiclass multiple output lables."); for (int32_t j=0; j<n_outputs; j++) labels(i,j) = m_labels[i][j]; } return labels; } SGVector <int32_t> CMultilabelLabels::get_label(int32_t j) { require(j < get_num_labels(), "label index j={} should be within [{},{}[", j, 0, get_num_labels()); return m_labels[j]; } template <class S, class D> SGVector <D> CMultilabelLabels::to_dense (SGVector <S> * sparse, int32_t dense_len, D d_true, D d_false) { SGVector <D> dense(dense_len); dense.set_const(d_false); for (int32_t i = 0; i < sparse->vlen; i++) { S index = (*sparse)[i]; require(index < dense_len, "class index exceeded length of dense vector"); dense[index] = d_true; } return dense; } template SGVector <int32_t> CMultilabelLabels::to_dense <int32_t, int32_t> (SGVector <int32_t> *, int32_t, int32_t, int32_t); template SGVector <float64_t> CMultilabelLabels::to_dense <int32_t, float64_t> (SGVector <int32_t> *, int32_t, float64_t, float64_t); void CMultilabelLabels::set_label(int32_t j, SGVector <int32_t> label) { require(j < get_num_labels(), "label index j={} should be within [{},{}[", j, 0, get_num_labels()); m_labels[j] = label; } void CMultilabelLabels::set_class_labels(SGVector <int32_t> ** labels_list) { int32_t * num_class_idx = SG_MALLOC(int32_t , get_num_labels()); for (int32_t label_j = 0; label_j < get_num_labels(); label_j++) { num_class_idx[label_j] = 0; } for (int32_t class_i = 0; class_i < get_num_classes(); class_i++) { for (int32_t l_pos = 0; l_pos < labels_list[class_i]->vlen; l_pos++) { int32_t label_j = (*labels_list[class_i])[l_pos]; require(label_j < get_num_labels(), "class_i={}/{} :: label_j={}/{} (l_pos={})", class_i, get_num_classes(), label_j, get_num_labels(), l_pos); num_class_idx[label_j]++; } } for (int32_t label_j = 0; label_j < get_num_labels(); label_j++) { m_labels[label_j].resize_vector(num_class_idx[label_j]); } SG_FREE(num_class_idx); int32_t * next_class_idx = SG_MALLOC(int32_t , get_num_labels()); for (int32_t label_j = 0; label_j < get_num_labels(); label_j++) { next_class_idx[label_j] = 0; } for (int32_t class_i = 0; class_i < get_num_classes(); class_i++) { for (int32_t l_pos = 0; l_pos < labels_list[class_i]->vlen; l_pos++) { // get class_i of current position int32_t label_j = (*labels_list[class_i])[l_pos]; require(label_j < get_num_labels(), "class_i={}/{} :: label_j={}/{} (l_pos={})", class_i, get_num_classes(), label_j, get_num_labels(), l_pos); // next free element in m_labels[label_j]: int32_t c_pos = next_class_idx[label_j]; require(c_pos < m_labels[label_j].size(), "c_pos exceeded length of labels vector"); next_class_idx[label_j]++; // finally, story label_j into class-column m_labels[label_j][c_pos] = class_i; } } SG_FREE(next_class_idx); return; } void CMultilabelLabels::display() const { SGVector <int32_t> ** labels_list = get_class_labels(); io::print("printing {} binary label vectors for {} multilabels:\n", get_num_classes(), get_num_labels()); for (int32_t class_i = 0; class_i < get_num_classes(); class_i++) { io::print(" yC_{{class_i={}}}", class_i); SGVector <float64_t> dense = to_dense <int32_t, float64_t> (labels_list[class_i], get_num_labels(), +1, -1); dense.display_vector(""); delete labels_list[class_i]; } SG_FREE(labels_list); io::print("printing {} binary class vectors for {} labels:\n", get_num_labels(), get_num_classes()); for (int32_t j = 0; j < get_num_labels(); j++) { io::print(" y_{{j={}}}", j); SGVector <float64_t> dense = to_dense <int32_t , float64_t> (&m_labels[j], get_num_classes(), +1, -1); dense.display_vector(""); } return; }
28.803867
94
0.670279
Arpit2601
a0ade4bec71fb7f7fca99354d0ae7f796d1cc511
10,330
cpp
C++
test/TestParticleGPU.cpp
MaxZZG/RadProps
bd95421430fc266ee88d0480069f7d20be1414f6
[ "MIT" ]
null
null
null
test/TestParticleGPU.cpp
MaxZZG/RadProps
bd95421430fc266ee88d0480069f7d20be1414f6
[ "MIT" ]
null
null
null
test/TestParticleGPU.cpp
MaxZZG/RadProps
bd95421430fc266ee88d0480069f7d20be1414f6
[ "MIT" ]
null
null
null
/* * Copyright (c) 2014-2017 The University of Utah * * 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. */ /* Orion Sky Lawlor, [email protected], 9/23/2000 Computes so-called "Mie scattering" for a homogenous sphere of arbitrary size illuminated by coherent harmonic radiation. */ #include <radprops/Particles.h> #include <test/TestHelper.h> #include <iostream> #include <iomanip> #include <vector> #include <ctime> #include <string> #include "cuda.h" using namespace std; using namespace RadProps; bool cpu_gpu_compare(const double* gpuValues, const double* cpuValues, const size_t n, const double t_cpu, const double t_gpu) { double *hostValues; hostValues = (double*)malloc(sizeof(double) * n); cudaError_t err= cudaMemcpy( hostValues, gpuValues, sizeof(double) * n, cudaMemcpyDeviceToHost ); cudaThreadSynchronize(); for (int i=0; i<n; ++i) { if (std::abs((hostValues[i] - cpuValues[i]) / cpuValues[i]) > 1e-8) { std::cout << cpuValues[i] << " - " <<hostValues[i] << "\n"; return false; } } std::cout <<" npts = " << n << "\t" << "time CPU = " << t_cpu << ", GPU = " << t_gpu << " => CPU/GPU = " << t_cpu / t_gpu << std::endl; return true; } bool time_it2D(const ParticleRadCoeffs& pcoeff, const ParticleRadCoeffs3D& pcoeff3D, const size_t n) { TestHelper status(true); std::vector<double> wavelength, radius, temperature, iRreal; for (int i=0; i<n ; i++) { wavelength. push_back(double(rand())/double(RAND_MAX) * 1e-6); radius. push_back(double(rand())/double(RAND_MAX) * 1e-6); temperature.push_back(double(rand())/double(RAND_MAX) * 1000 + 300); iRreal. push_back(double(rand())/double(RAND_MAX)); } // GPU variables double *gpuWavelength, *gpuRadius, *gpuTemperature, *gpuiRreal; cudaMalloc((void**) &gpuWavelength, sizeof(double) * n); cudaMalloc((void**) &gpuRadius, sizeof(double) * n); cudaMalloc((void**) &gpuTemperature, sizeof(double) * n); cudaMalloc((void**) &gpuiRreal, sizeof(double) * n); cudaMemcpy(gpuWavelength , &wavelength[0], sizeof(double) * n, cudaMemcpyHostToDevice); cudaMemcpy(gpuRadius , &radius[0], sizeof(double) * n, cudaMemcpyHostToDevice); cudaMemcpy(gpuTemperature , &temperature[0],sizeof(double) * n, cudaMemcpyHostToDevice); cudaMemcpy(gpuiRreal , &gpuiRreal[0], sizeof(double) * n, cudaMemcpyHostToDevice); cudaThreadSynchronize(); double *gpuValues; cudaMalloc((void**) &gpuValues, sizeof(double) * n); std::clock_t start; double t_cpu, t_gpu; string modelname; modelname = "abs_spectral_coeff"; std::vector<double> cpuValues; cpuValues.clear(); // 2D // Run on CPU start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff.abs_spectral_coeff(wavelength[i], radius[i])); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff.gpu_abs_spectral_coeff(gpuValues, gpuWavelength, gpuRadius, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname); // 3D cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff3D.abs_spectral_coeff(wavelength[i], radius[i], iRreal[i])); t_cpu = std::clock() - start; start = std::clock(); pcoeff3D.gpu_abs_spectral_coeff(gpuValues, gpuWavelength, gpuRadius, gpuiRreal, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname + " 3D"); modelname = "scattering_spectral_coeff"; cpuValues.clear(); // 2D // Run on CPU start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues[i] = pcoeff.scattering_spectral_coeff(wavelength[i], radius[i]); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff.gpu_scattering_spectral_coeff(gpuValues, gpuWavelength, gpuRadius, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname); // 3D // Run on CPU cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues[i] = pcoeff3D.scattering_spectral_coeff(wavelength[i], radius[i], iRreal[i]); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff3D.gpu_scattering_spectral_coeff(gpuValues, gpuWavelength, gpuRadius, gpuiRreal, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname + " 3D"); // ----------- planck_abs_coeff // 2D // Run on CPU modelname = "planck_abs_coeff"; cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff.planck_abs_coeff(radius[i], temperature[i])); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff.gpu_planck_abs_coeff(gpuValues, gpuRadius, gpuTemperature, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname); // 3D // Run on CPU cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff3D.planck_abs_coeff(radius[i], temperature[i], iRreal[i])); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff3D.gpu_planck_abs_coeff(gpuValues, gpuRadius, gpuTemperature,gpuiRreal, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname + " 3D"); // ----------- planck_sca_coeff // Run on CPU modelname = "planck_sca_coeff"; cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff.planck_sca_coeff(radius[i], temperature[i])); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff.gpu_planck_sca_coeff(gpuValues, gpuRadius, gpuTemperature, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname); // 3D cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff3D.planck_sca_coeff(radius[i], temperature[i], iRreal[i])); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff3D.gpu_planck_sca_coeff(gpuValues, gpuRadius, gpuTemperature, gpuiRreal, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname + " 3D"); // ----------- ross_abs_coeff // 2D // Run on CPU modelname = "ross_abs_coeff"; cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff.ross_abs_coeff(radius[i], temperature[i])); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff.gpu_ross_abs_coeff(gpuValues, gpuRadius, gpuTemperature, n); t_gpu = std::clock() - start; // compare CPU and GPU results status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname); // 3D cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff3D.ross_abs_coeff(radius[i], temperature[i], iRreal[i])); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff3D.gpu_ross_abs_coeff(gpuValues, gpuRadius, gpuTemperature, gpuiRreal, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname + " 3D"); // ----------- ross_sca_coeff // Run on CPU modelname = "ross_sca_coeff"; cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff.ross_sca_coeff(radius[i], temperature[i])); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff.gpu_ross_sca_coeff(gpuValues, gpuRadius, gpuTemperature, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname); // 3D cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff3D.ross_sca_coeff(radius[i], temperature[i], iRreal[i])); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff3D.gpu_ross_sca_coeff(gpuValues, gpuRadius, gpuTemperature, gpuiRreal, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname + " 3D"); return status.ok(); cudaFree( gpuWavelength ); cudaFree( gpuRadius ); cudaFree( gpuTemperature ); cudaFree( gpuiRreal ); cudaFree( gpuValues ); } //============================================================================== int main( int argc, char* argv[] ) { TestHelper status(true); try{ complex<double> rCoal, rCoallo, rCoalhi; rCoal =complex<double>(2.0,-0.6); rCoallo =complex<double>(0,0); rCoalhi =complex<double>(1,1); ParticleRadCoeffs P2(rCoal,1e-7,1e-4,10,1); std::cout << " 2D table is made! \n"; ParticleRadCoeffs3D P3(rCoallo, rCoalhi,5,1e-7,1e-4,5,1); std::cout << " 3D table is made! \n"; status (time_it2D(P2, P3, 2), " Checking GPU versus CPU results "); if( status.ok() ){ cout << "PASS" << endl; return 0; } } catch( std::exception& err ){ cout << err.what() << endl; } cout << "FAIL" << endl; return -1; }
39.277567
144
0.664569
MaxZZG
a0b657ae7123fe48ac77fe7f4b2ad76c374283f9
27,674
cc
C++
src/SinCosOps.cc
oseikuffuor1/mgmol
5442962959a54c919a5e18c4e78db6ce41ee8f4e
[ "BSD-3-Clause-LBNL", "FSFAP" ]
null
null
null
src/SinCosOps.cc
oseikuffuor1/mgmol
5442962959a54c919a5e18c4e78db6ce41ee8f4e
[ "BSD-3-Clause-LBNL", "FSFAP" ]
null
null
null
src/SinCosOps.cc
oseikuffuor1/mgmol
5442962959a54c919a5e18c4e78db6ce41ee8f4e
[ "BSD-3-Clause-LBNL", "FSFAP" ]
null
null
null
// Copyright (c) 2017, Lawrence Livermore National Security, LLC and // UT-Battelle, LLC. // Produced at the Lawrence Livermore National Laboratory and the Oak Ridge // National Laboratory. // LLNL-CODE-743438 // All rights reserved. // This file is part of MGmol. For details, see https://github.com/llnl/mgmol. // Please also read this link https://github.com/llnl/mgmol/LICENSE #include "SinCosOps.h" #include "ExtendedGridOrbitals.h" #include "FunctionsPacking.h" #include "LocGridOrbitals.h" #include "MGmol_MPI.h" using namespace std; template <class T> void SinCosOps<T>::compute(const T& orbitals, vector<vector<double>>& a) { assert(a.size() == 6); compute_tm_.start(); const pb::Grid& grid(orbitals.grid_); const int numst = orbitals.numst(); const int dim0 = grid.dim(0); const int dim1 = grid.dim(1); const int dim2 = grid.dim(2); int n2 = numst * numst; int loc_length = dim0 / orbitals.subdivx_; assert(loc_length > 0); assert(loc_length <= dim0); int incx = dim1 * dim2; int incy = dim2; vector<double> sinx; vector<double> siny; vector<double> sinz; vector<double> cosx; vector<double> cosy; vector<double> cosz; grid.getSinCosFunctions(sinx, siny, sinz, cosx, cosy, cosz); const int size = orbitals.chromatic_number(); for (short iloc = 0; iloc < orbitals.subdivx_; iloc++) { for (int icolor = 0; icolor < size; icolor++) { const int i = orbitals.overlapping_gids_[iloc][icolor]; if (i != -1) { const ORBDTYPE* const ppsii = orbitals.psi(icolor); for (int jstate = 0; jstate <= icolor; jstate++) { const int j = orbitals.overlapping_gids_[iloc][jstate]; if (j != -1) { const ORBDTYPE* const ppsij = orbitals.psi(jstate); double atmp[6] = { 0., 0., 0., 0., 0., 0. }; const int ixend = loc_length * (iloc + 1); for (int ix = loc_length * iloc; ix < ixend; ix++) { const double cosix = cosx[ix]; const double sinix = sinx[ix]; const int offsetx = ix * incx; for (int iy = 0; iy < dim1; iy++) { const double cosiy = cosy[iy]; const double siniy = siny[iy]; const int offset = offsetx + iy * incy; for (int iz = 0; iz < dim2; iz++) { const int index = offset + iz; const double alpha = (double)ppsij[index] * (double)ppsii[index]; atmp[0] += alpha * cosix; atmp[1] += alpha * sinix; atmp[2] += alpha * cosiy; atmp[3] += alpha * siniy; atmp[4] += alpha * cosz[iz]; atmp[5] += alpha * sinz[iz]; } } } const int ji = j * numst + i; const int ij = i * numst + j; a[0][ji] = a[0][ij] += atmp[0]; a[1][ji] = a[1][ij] += atmp[1]; a[2][ji] = a[2][ij] += atmp[2]; a[3][ji] = a[3][ij] += atmp[3]; a[4][ji] = a[4][ij] += atmp[4]; a[5][ji] = a[5][ij] += atmp[5]; } } } } } MGmol_MPI& mmpi = *(MGmol_MPI::instance()); for (short i = 0; i < 6; i++) { mmpi.split_allreduce_sums_double(&a[i][0], n2); my_dscal(n2, grid.vel(), &a[i][0]); } compute_tm_.stop(); } template <class T> void SinCosOps<T>::computeSquare(const T& orbitals, vector<vector<double>>& a) { assert(a.size() == 6); for (short i = 0; i < 6; i++) assert(a[i].size() > 0); compute_tm_.start(); const pb::Grid& grid(orbitals.grid_); const int numst = orbitals.numst_; const int n2 = numst * numst; const int dim0 = grid.dim(0); const int dim1 = grid.dim(1); const int dim2 = grid.dim(2); int loc_length = dim0 / orbitals.subdivx_; assert(loc_length > 0); assert(loc_length <= dim0); const int xoff = grid.istart(0); const int yoff = grid.istart(1); const int zoff = grid.istart(2); const double hhx = 2. * M_PI / (double)grid.gdim(0); const double hhy = 2. * M_PI / (double)grid.gdim(1); const double hhz = 2. * M_PI / (double)grid.gdim(2); int incx = dim1 * dim2; int incy = dim2; const double inv_2pi = 0.5 * M_1_PI; const double alphax = grid.ll(0) * grid.ll(0) * inv_2pi * inv_2pi; const double alphay = grid.ll(1) * grid.ll(1) * inv_2pi * inv_2pi; const double alphaz = grid.ll(2) * grid.ll(2) * inv_2pi * inv_2pi; vector<double> sinx2, siny2, sinz2, cosx2, cosy2, cosz2; sinx2.resize(dim0); cosx2.resize(dim0); siny2.resize(dim1); cosy2.resize(dim1); sinz2.resize(dim2); cosz2.resize(dim2); for (int i = 0; i < dim0; i++) { const double tmp = sin((double)(xoff + i) * hhx); sinx2[i] = tmp * tmp * alphax; cosx2[i] = (1. - tmp * tmp) * alphax; } for (int i = 0; i < dim1; i++) { const double tmp = sin((double)(yoff + i) * hhy); siny2[i] = tmp * tmp * alphay; cosy2[i] = (1. - tmp * tmp) * alphay; } for (int i = 0; i < dim2; i++) { const double tmp = sin((double)(zoff + i) * hhz); sinz2[i] = tmp * tmp * alphaz; cosz2[i] = (1. - tmp * tmp) * alphaz; } const int size = orbitals.chromatic_number(); for (short iloc = 0; iloc < orbitals.subdivx_; iloc++) { for (int icolor = 0; icolor < size; icolor++) { int i = orbitals.overlapping_gids_[iloc][icolor]; if (i != -1) for (int jstate = 0; jstate <= icolor; jstate++) { int j = orbitals.overlapping_gids_[iloc][jstate]; if (j != -1) { double atmp[6] = { 0., 0., 0., 0., 0., 0. }; for (int ix = loc_length * iloc; ix < loc_length * (iloc + 1); ix++) for (int iy = 0; iy < dim1; iy++) for (int iz = 0; iz < dim2; iz++) { int index = ix * incx + iy * incy + iz; double alpha = orbitals.psi(jstate)[index] * orbitals.psi(icolor)[index]; atmp[0] += alpha * cosx2[ix]; atmp[1] += alpha * sinx2[ix]; atmp[2] += alpha * cosy2[iy]; atmp[3] += alpha * siny2[iy]; atmp[4] += alpha * cosz2[iz]; atmp[5] += alpha * sinz2[iz]; } int ji = j * numst + i; int ij = i * numst + j; a[0][ji] = a[0][ij] += atmp[0]; a[1][ji] = a[1][ij] += atmp[1]; a[2][ji] = a[2][ij] += atmp[2]; a[3][ji] = a[3][ij] += atmp[3]; a[4][ji] = a[4][ij] += atmp[4]; a[5][ji] = a[5][ij] += atmp[5]; } } } } MGmol_MPI& mmpi = *(MGmol_MPI::instance()); for (short i = 0; i < 6; i++) { mmpi.split_allreduce_sums_double(&a[i][0], n2); my_dscal(n2, grid.vel(), &a[i][0]); } compute_tm_.stop(); } template <class T> void SinCosOps<T>::computeSquare1D( const T& orbitals, vector<vector<double>>& a, const int dim_index) { assert(a.size() == 2); for (short i = 0; i < 2; i++) assert(a[i].size() > 0); compute_tm_.start(); const pb::Grid& grid(orbitals.grid_); const int numst = orbitals.numst_; const int dim = grid.dim(dim_index); const int dim0 = grid.dim(0); const int dim1 = grid.dim(1); const int dim2 = grid.dim(2); int n2 = numst * numst; int loc_length = dim0 / orbitals.subdivx_; assert(loc_length > 0); assert(loc_length <= dim0); const int off = grid.istart(dim_index); const double hh = 2. * M_PI / (double)grid.gdim(dim_index); int incx = dim1 * dim2; int incy = dim2; const double inv_2pi = 0.5 * M_1_PI; const double alphax = grid.ll(dim_index) * grid.ll(dim_index) * inv_2pi * inv_2pi; vector<double> sinx2(dim); vector<double> cosx2(dim); for (int i = 0; i < dim; i++) { const double tmp = sin((double)(off + i) * hh); sinx2[i] = tmp * tmp * alphax; cosx2[i] = (1. - tmp * tmp) * alphax; } const int size = orbitals.chromatic_number(); for (short iloc = 0; iloc < orbitals.subdivx_; iloc++) { for (int icolor = 0; icolor < size; icolor++) { int i = orbitals.overlapping_gids_[iloc][icolor]; if (i != -1) for (int jstate = 0; jstate <= icolor; jstate++) { int j = orbitals.overlapping_gids_[iloc][jstate]; if (j != -1) { double atmp[2] = { 0., 0. }; for (int ix = loc_length * iloc; ix < loc_length * (iloc + 1); ix++) for (int iy = 0; iy < dim1; iy++) for (int iz = 0; iz < dim2; iz++) { int dindex[3] = { ix, iy, iz }; int index = ix * incx + iy * incy + iz; double alpha = orbitals.psi(jstate)[index] * orbitals.psi(icolor)[index]; atmp[0] += alpha * cosx2[dindex[dim_index]]; atmp[1] += alpha * sinx2[dindex[dim_index]]; } int ji = j * numst + i; int ij = i * numst + j; a[0][ji] = a[0][ij] += atmp[0]; a[1][ji] = a[1][ij] += atmp[1]; } } } } MGmol_MPI& mmpi = *(MGmol_MPI::instance()); for (int i = 0; i < 2; i++) { mmpi.split_allreduce_sums_double(&a[i][0], n2); my_dscal(n2, grid.vel(), &a[i][0]); } compute_tm_.stop(); } template <class T> void SinCosOps<T>::compute1D( const T& orbitals, vector<vector<double>>& a, const int dim_index) { assert(a.size() == 2); for (short i = 0; i < 2; i++) assert(a[i].size() > 0); compute_tm_.start(); const pb::Grid& grid(orbitals.grid_); const int numst = orbitals.numst_; const int dim = grid.dim(dim_index); const int dim0 = grid.dim(0); const int dim1 = grid.dim(1); const int dim2 = grid.dim(2); int n2 = numst * numst; int loc_length = dim0 / orbitals.subdivx_; assert(loc_length > 0); assert(loc_length <= dim0); int incx = dim1 * dim2; int incy = dim2; const int off = grid.istart(dim_index); const double hh = 2. * M_PI / (double)grid.gdim(dim_index); const double inv_2pi = 0.5 * M_1_PI; const double alphax = grid.ll(dim_index) * inv_2pi; vector<double> sinx(dim); for (int i = 0; i < dim; i++) sinx[i] = sin(double(off + i) * hh) * alphax; vector<double> cosx(dim); for (int i = 0; i < dim; i++) cosx[i] = cos(double(off + i) * hh) * alphax; const int size = orbitals.chromatic_number(); for (short iloc = 0; iloc < orbitals.subdivx_; iloc++) { for (int icolor = 0; icolor < size; icolor++) { const int i = orbitals.overlapping_gids_[iloc][icolor]; if (i != -1) { const ORBDTYPE* const ppsii = orbitals.psi(icolor); for (int jstate = 0; jstate <= icolor; jstate++) { const int j = orbitals.overlapping_gids_[iloc][jstate]; if (j != -1) { const ORBDTYPE* const ppsij = orbitals.psi(jstate); double atmp[2] = { 0., 0. }; const int ixend = loc_length * (iloc + 1); for (int ix = loc_length * iloc; ix < ixend; ix++) for (int iy = 0; iy < dim1; iy++) for (int iz = 0; iz < dim2; iz++) { int dindex[3] = { ix, iy, iz }; const int index = ix * incx + iy * incy + iz; const double alpha = (double)ppsij[index] * (double)ppsii[index]; atmp[0] += alpha * cosx[dindex[dim_index]]; atmp[1] += alpha * sinx[dindex[dim_index]]; } const int ji = j * numst + i; const int ij = i * numst + j; a[0][ji] = a[0][ij] += atmp[0]; a[1][ji] = a[1][ij] += atmp[1]; } } } } } MGmol_MPI& mmpi = *(MGmol_MPI::instance()); for (short i = 0; i < 2; i++) { mmpi.split_allreduce_sums_double(&a[i][0], n2); my_dscal(n2, grid.vel(), &a[i][0]); } compute_tm_.stop(); } template <class T> void SinCosOps<T>::computeDiag2states( const T& orbitals, vector<vector<double>>& a, const int st1, const int st2) { assert(st1 >= 0); assert(st2 >= 0); assert(st1 != st2); compute_tm_.start(); const pb::Grid& grid(orbitals.grid_); const int st[2] = { st1, st2 }; const int dim0 = grid.dim(0); const int dim1 = grid.dim(1); const int dim2 = grid.dim(2); short color_st[2] = { -1, -1 }; for (short ic = 0; ic < 2; ++ic) { color_st[ic] = orbitals.getColor(st[ic]); } int loc_length = dim0 / orbitals.subdivx_; assert(loc_length > 0); assert(loc_length <= dim0); int incx = dim1 * dim2; int incy = dim2; vector<double> sinx; vector<double> siny; vector<double> sinz; vector<double> cosx; vector<double> cosy; vector<double> cosz; grid.getSinCosFunctions(sinx, siny, sinz, cosx, cosy, cosz); double norm2[2] = { 0., 0. }; for (short ic = 0; ic < 2; ic++) { const short mycolor = color_st[ic]; if (mycolor >= 0) for (short iloc = 0; iloc < orbitals.subdivx_; iloc++) { if (orbitals.overlapping_gids_[iloc][mycolor] == st[ic]) { const ORBDTYPE* const ppsii = orbitals.psi(mycolor); assert(ppsii != nullptr); double atmp[6] = { 0., 0., 0., 0., 0., 0. }; const int ixend = loc_length * (iloc + 1); for (int ix = loc_length * iloc; ix < ixend; ix++) for (int iy = 0; iy < dim1; iy++) for (int iz = 0; iz < dim2; iz++) { const int index = ix * incx + iy * incy + iz; const double alpha = (double)ppsii[index] * (double)ppsii[index]; atmp[0] += alpha * cosx[ix]; atmp[1] += alpha * sinx[ix]; atmp[2] += alpha * cosy[iy]; atmp[3] += alpha * siny[iy]; atmp[4] += alpha * cosz[iz]; atmp[5] += alpha * sinz[iz]; norm2[ic] += alpha; } a[0][ic] += atmp[0]; a[1][ic] += atmp[1]; a[2][ic] += atmp[2]; a[3][ic] += atmp[3]; a[4][ic] += atmp[4]; a[5][ic] += atmp[5]; } } } MGmol_MPI& mmpi = *(MGmol_MPI::instance()); for (short i = 0; i < 6; i++) { mmpi.split_allreduce_sums_double(&a[i][0], 2); my_dscal(2, grid.vel(), &a[i][0]); } compute_tm_.stop(); } template <class T> void SinCosOps<T>::compute2states( const T& orbitals, vector<vector<double>>& a, const int st1, const int st2) { assert(a.size() == 6); assert(st1 >= 0); assert(st2 >= 0); compute_tm_.start(); const pb::Grid& grid(orbitals.grid_); const int st[2] = { st1, st2 }; int color_st[2] = { -1, -1 }; for (short ic = 0; ic < 2; ++ic) { color_st[ic] = orbitals.getColor(st[ic]); } const int dim0 = grid.dim(0); const int dim1 = grid.dim(1); const int dim2 = grid.dim(2); int n2 = 4; int loc_length = dim0 / orbitals.subdivx_; assert(loc_length > 0); assert(loc_length <= dim0); int incx = dim1 * dim2; int incy = dim2; vector<double> sinx; vector<double> siny; vector<double> sinz; vector<double> cosx; vector<double> cosy; vector<double> cosz; grid.getSinCosFunctions(sinx, siny, sinz, cosx, cosy, cosz); for (int ic = 0; ic < 2; ic++) { const int mycolor = color_st[ic]; if (mycolor >= 0) for (short iloc = 0; iloc < orbitals.subdivx_; iloc++) { if (orbitals.overlapping_gids_[iloc][mycolor] == st[ic]) { const ORBDTYPE* const ppsii = orbitals.psi(mycolor); assert(ppsii != nullptr); for (int jc = 0; jc <= ic; jc++) if (color_st[jc] >= 0) { if (orbitals.overlapping_gids_[iloc][color_st[jc]] == st[jc]) { const ORBDTYPE* const ppsij = orbitals.psi(color_st[jc]); assert(ppsij != nullptr); double atmp[6] = { 0., 0., 0., 0., 0., 0. }; const int ixend = loc_length * (iloc + 1); for (int ix = loc_length * iloc; ix < ixend; ix++) for (int iy = 0; iy < dim1; iy++) for (int iz = 0; iz < dim2; iz++) { const int index = ix * incx + iy * incy + iz; const double alpha = (double)ppsij[index] * (double)ppsii[index]; atmp[0] += alpha * cosx[ix]; atmp[1] += alpha * sinx[ix]; atmp[2] += alpha * cosy[iy]; atmp[3] += alpha * siny[iy]; atmp[4] += alpha * cosz[iz]; atmp[5] += alpha * sinz[iz]; } const int ji = jc * 2 + ic; const int ij = ic * 2 + jc; a[0][ji] = a[0][ij] += atmp[0]; a[1][ji] = a[1][ij] += atmp[1]; a[2][ji] = a[2][ij] += atmp[2]; a[3][ji] = a[3][ij] += atmp[3]; a[4][ji] = a[4][ij] += atmp[4]; a[5][ji] = a[5][ij] += atmp[5]; } } } } } MGmol_MPI& mmpi = *(MGmol_MPI::instance()); for (short i = 0; i < 6; i++) { mmpi.split_allreduce_sums_double(&a[i][0], n2); my_dscal(n2, grid.vel(), &a[i][0]); } compute_tm_.stop(); } template <class T> void SinCosOps<T>::compute( const T& orbitals1, const T& orbitals2, vector<vector<double>>& a) { assert(a.size() == 6); compute_tm_.start(); const pb::Grid& grid(orbitals1.grid_); const int numst = orbitals1.numst_; int n2 = numst * numst; const int dim0 = grid.dim(0); const int dim1 = grid.dim(1); const int dim2 = grid.dim(2); int loc_length = dim0 / orbitals1.subdivx_; assert(loc_length > 0); assert(loc_length <= dim0); int incx = dim1 * dim2; int incy = dim2; vector<double> sinx; vector<double> siny; vector<double> sinz; vector<double> cosx; vector<double> cosy; vector<double> cosz; grid.getSinCosFunctions(sinx, siny, sinz, cosx, cosy, cosz); for (short iloc = 0; iloc < orbitals1.subdivx_; iloc++) { for (int color = 0; color < orbitals1.chromatic_number(); color++) { int i = orbitals1.overlapping_gids_[iloc][color]; if (i != -1) for (int jstate = 0; jstate < orbitals2.chromatic_number(); jstate++) { int j = orbitals2.overlapping_gids_[iloc][jstate]; if (j != -1) { double atmp[6] = { 0., 0., 0., 0., 0., 0. }; for (int ix = loc_length * iloc; ix < loc_length * (iloc + 1); ix++) for (int iy = 0; iy < dim1; iy++) for (int iz = 0; iz < dim2; iz++) { const int index = ix * incx + iy * incy + iz; const double alpha = (double)orbitals1.psi(color)[index] * (double)orbitals2.psi( jstate)[index]; atmp[0] += alpha * cosx[ix]; atmp[1] += alpha * sinx[ix]; atmp[2] += alpha * cosy[iy]; atmp[3] += alpha * siny[iy]; atmp[4] += alpha * cosz[iz]; atmp[5] += alpha * sinz[iz]; } int ij = j * numst + i; // row i, column j a[0][ij] += atmp[0]; a[1][ij] += atmp[1]; a[2][ij] += atmp[2]; a[3][ij] += atmp[3]; a[4][ij] += atmp[4]; a[5][ij] += atmp[5]; } } } } MGmol_MPI& mmpi = *(MGmol_MPI::instance()); for (short i = 0; i < 6; i++) { mmpi.split_allreduce_sums_double(&a[i][0], n2); my_dscal(n2, grid.vel(), &a[i][0]); } compute_tm_.stop(); } template <class T> void SinCosOps<T>::computeDiag(const T& orbitals, VariableSizeMatrix<sparserow>& mat, const bool normalized_functions) { compute_tm_.start(); const pb::Grid& grid(orbitals.grid_); const int dim0 = grid.dim(0); const int dim1 = grid.dim(1); const int dim2 = grid.dim(2); int loc_length = dim0 / orbitals.subdivx_; assert(loc_length > 0); assert(loc_length <= dim0); int incx = dim1 * dim2; int incy = dim2; vector<double> sinx; vector<double> siny; vector<double> sinz; vector<double> cosx; vector<double> cosy; vector<double> cosz; grid.getSinCosFunctions(sinx, siny, sinz, cosx, cosy, cosz); vector<vector<double>> inv_norms2; if (!normalized_functions) { orbitals.computeInvNorms2(inv_norms2); } // initialize sparse ordering of rows to match local overlap regions // This is necessary for computing correct moves in moveTo() mat.setupSparseRows(orbitals.getAllOverlappingGids()); const int size = orbitals.chromatic_number(); for (short iloc = 0; iloc < orbitals.subdivx_; iloc++) { for (short icolor = 0; icolor < size; icolor++) { int gid = orbitals.overlapping_gids_[iloc][icolor]; if (gid != -1) { const ORBDTYPE* const psii = orbitals.psi(icolor); double atmp[6] = { 0., 0., 0., 0., 0., 0. }; for (int ix = loc_length * iloc; ix < loc_length * (iloc + 1); ix++) for (int iy = 0; iy < dim1; iy++) for (int iz = 0; iz < dim2; iz++) { const int index = ix * incx + iy * incy + iz; const double alpha = (double)psii[index] * (double)psii[index]; atmp[0] += alpha * cosx[ix]; atmp[1] += alpha * sinx[ix]; atmp[2] += alpha * cosy[iy]; atmp[3] += alpha * siny[iy]; atmp[4] += alpha * cosz[iz]; atmp[5] += alpha * sinz[iz]; } if (!normalized_functions) { for (int col = 0; col < 6; col++) atmp[col] *= inv_norms2[iloc][icolor]; } for (int col = 0; col < 6; col++) mat.insertMatrixElement(gid, col, atmp[col], ADD, true); } } } /* scale data */ mat.scale(grid.vel()); /* gather data */ Mesh* mymesh = Mesh::instance(); const pb::Grid& mygrid = mymesh->grid(); const pb::PEenv& myPEenv = mymesh->peenv(); double domain[3] = { mygrid.ll(0), mygrid.ll(1), mygrid.ll(2) }; double maxr = orbitals.getMaxR(); DataDistribution distributor("Distributor4SinCos", maxr, myPEenv, domain); distributor.augmentLocalData(mat, true); compute_tm_.stop(); } template class SinCosOps<LocGridOrbitals>; template class SinCosOps<ExtendedGridOrbitals>;
34.292441
80
0.422346
oseikuffuor1
a0b6d49deda766258341b2b10a34eec487dc0f69
551
cpp
C++
Prim/PrimCheckLock.cpp
UltimateScript/FOG
edc96d916fc299f0a822f8c534a4e7487c0e3ea2
[ "BSD-3-Clause" ]
null
null
null
Prim/PrimCheckLock.cpp
UltimateScript/FOG
edc96d916fc299f0a822f8c534a4e7487c0e3ea2
[ "BSD-3-Clause" ]
2
2021-07-07T17:31:49.000Z
2021-07-16T11:40:38.000Z
Prim/PrimCheckLock.cpp
OuluLinux/FOG
edc96d916fc299f0a822f8c534a4e7487c0e3ea2
[ "BSD-3-Clause" ]
null
null
null
#include <Prim/PrimIncludeAll.h> #ifndef NO_PRIM_CHECKS int PrimCheckLock::_check_locks = 0; // Number of locks in force. #endif // // Return the debug checking control variable. // bool& PrimCheckLock::debug_check() { static PrimGetEnv<bool> debugCheck("PrimCheckLock::debug_check", debug_full_check()); return debugCheck; } // // Return the debug full check control variable. // bool& PrimCheckLock::debug_full_check() { static PrimGetEnv<bool> debugFullCheck("PrimCheckLock::debug_full_check", false); return debugFullCheck; }
21.192308
86
0.744102
UltimateScript
a0b7aa4bba66d43409216d479bc364403f3cdbcd
11,276
cpp
C++
pj_tflite_hand_mediapipe/ImageProcessor/HandLandmarkEngine.cpp
bjarkirafn/play_with_tflite
ab20bcfa79f1bbcf1cb5d8e2887df6253ef0a0c0
[ "Apache-2.0" ]
1
2021-01-13T00:52:14.000Z
2021-01-13T00:52:14.000Z
pj_tflite_hand_mediapipe/ImageProcessor/HandLandmarkEngine.cpp
bjarkirafn/play_with_tflite
ab20bcfa79f1bbcf1cb5d8e2887df6253ef0a0c0
[ "Apache-2.0" ]
null
null
null
pj_tflite_hand_mediapipe/ImageProcessor/HandLandmarkEngine.cpp
bjarkirafn/play_with_tflite
ab20bcfa79f1bbcf1cb5d8e2887df6253ef0a0c0
[ "Apache-2.0" ]
null
null
null
/*** Include ***/ /* for general */ #include <cstdint> #include <cstdlib> #define _USE_MATH_DEFINES #include <cmath> #include <cstring> #include <string> #include <vector> #include <array> #include <algorithm> #include <chrono> #include <fstream> /* for OpenCV */ #include <opencv2/opencv.hpp> /* for My modules */ #include "CommonHelper.h" #include "InferenceHelper.h" #include "HandLandmarkEngine.h" /*** Macro ***/ #define TAG "HandLandmarkEngine" #define PRINT(...) COMMON_HELPER_PRINT(TAG, __VA_ARGS__) #define PRINT_E(...) COMMON_HELPER_PRINT_E(TAG, __VA_ARGS__) /* Model parameters */ #define MODEL_NAME "hand_landmark.tflite" /*** Function ***/ int32_t HandLandmarkEngine::initialize(const std::string& workDir, const int32_t numThreads) { /* Set model information */ std::string modelFilename = workDir + "/model/" + MODEL_NAME; /* Set input tensor info */ m_inputTensorList.clear(); InputTensorInfo inputTensorInfo; inputTensorInfo.name = "input_1"; inputTensorInfo.tensorType = TensorInfo::TENSOR_TYPE_FP32; inputTensorInfo.tensorDims.batch = 1; inputTensorInfo.tensorDims.width = 256; inputTensorInfo.tensorDims.height = 256; inputTensorInfo.tensorDims.channel = 3; inputTensorInfo.dataType = InputTensorInfo::DATA_TYPE_IMAGE; inputTensorInfo.normalize.mean[0] = 0.0f; /* normalized to[0.f, 1.f] (hand_landmark_cpu.pbtxt) */ inputTensorInfo.normalize.mean[1] = 0.0f; inputTensorInfo.normalize.mean[2] = 0.0f; inputTensorInfo.normalize.norm[0] = 1.0f; inputTensorInfo.normalize.norm[1] = 1.0f; inputTensorInfo.normalize.norm[2] = 1.0f; m_inputTensorList.push_back(inputTensorInfo); /* Set output tensor info */ m_outputTensorList.clear(); OutputTensorInfo outputTensorInfo; outputTensorInfo.tensorType = TensorInfo::TENSOR_TYPE_FP32; outputTensorInfo.name = "ld_21_3d"; m_outputTensorList.push_back(outputTensorInfo); outputTensorInfo.name = "output_handflag"; m_outputTensorList.push_back(outputTensorInfo); outputTensorInfo.name = "output_handedness"; m_outputTensorList.push_back(outputTensorInfo); /* Create and Initialize Inference Helper */ //m_inferenceHelper.reset(InferenceHelper::create(InferenceHelper::OPEN_CV)); //m_inferenceHelper.reset(InferenceHelper::create(InferenceHelper::TENSOR_RT)); //m_inferenceHelper.reset(InferenceHelper::create(InferenceHelper::NCNN)); //m_inferenceHelper.reset(InferenceHelper::create(InferenceHelper::MNN)); m_inferenceHelper.reset(InferenceHelper::create(InferenceHelper::TENSORFLOW_LITE)); //m_inferenceHelper.reset(InferenceHelper::create(InferenceHelper::TENSORFLOW_LITE_EDGETPU)); //m_inferenceHelper.reset(InferenceHelper::create(InferenceHelper::TENSORFLOW_LITE_GPU)); //m_inferenceHelper.reset(InferenceHelper::create(InferenceHelper::TENSORFLOW_LITE_XNNPACK)); if (!m_inferenceHelper) { return RET_ERR; } if (m_inferenceHelper->setNumThread(numThreads) != InferenceHelper::RET_OK) { m_inferenceHelper.reset(); return RET_ERR; } if (m_inferenceHelper->initialize(modelFilename, m_inputTensorList, m_outputTensorList) != InferenceHelper::RET_OK) { m_inferenceHelper.reset(); return RET_ERR; } /* Check if input tensor info is set */ for (const auto& inputTensorInfo : m_inputTensorList) { if ((inputTensorInfo.tensorDims.width <= 0) || (inputTensorInfo.tensorDims.height <= 0) || inputTensorInfo.tensorType == TensorInfo::TENSOR_TYPE_NONE) { PRINT_E("Invalid tensor size\n"); m_inferenceHelper.reset(); return RET_ERR; } } return RET_OK; } int32_t HandLandmarkEngine::finalize() { if (!m_inferenceHelper) { PRINT_E("Inference helper is not created\n"); return RET_ERR; } m_inferenceHelper->finalize(); return RET_OK; } int32_t HandLandmarkEngine::invoke(const cv::Mat& originalMat, int32_t palmX, int32_t palmY, int32_t palmW, int32_t palmH, float palmRotation, RESULT& result) { if (!m_inferenceHelper) { PRINT_E("Inference helper is not created\n"); return RET_ERR; } /*** PreProcess ***/ const auto& tPreProcess0 = std::chrono::steady_clock::now(); InputTensorInfo& inputTensorInfo = m_inputTensorList[0]; /* Rotate palm image */ cv::Mat rotatedImage; cv::RotatedRect rect(cv::Point(palmX + palmW / 2, palmY + palmH / 2), cv::Size(palmW, palmH), palmRotation * 180.f / static_cast<float>(M_PI)); cv::Mat trans = cv::getRotationMatrix2D(rect.center, rect.angle, 1.0); cv::Mat srcRot; cv::warpAffine(originalMat, srcRot, trans, originalMat.size()); cv::getRectSubPix(srcRot, rect.size, rect.center, rotatedImage); //cv::imshow("rotatedImage", rotatedImage); /* Resize image */ cv::Mat imgSrc; cv::resize(rotatedImage, imgSrc, cv::Size(inputTensorInfo.tensorDims.width, inputTensorInfo.tensorDims.height)); #ifndef CV_COLOR_IS_RGB cv::cvtColor(imgSrc, imgSrc, cv::COLOR_BGR2RGB); #endif inputTensorInfo.data = imgSrc.data; inputTensorInfo.dataType = InputTensorInfo::DATA_TYPE_IMAGE; inputTensorInfo.imageInfo.width = imgSrc.cols; inputTensorInfo.imageInfo.height = imgSrc.rows; inputTensorInfo.imageInfo.channel = imgSrc.channels(); inputTensorInfo.imageInfo.cropX = 0; inputTensorInfo.imageInfo.cropY = 0; inputTensorInfo.imageInfo.cropWidth = imgSrc.cols; inputTensorInfo.imageInfo.cropHeight = imgSrc.rows; inputTensorInfo.imageInfo.isBGR = false; inputTensorInfo.imageInfo.swapColor = false; if (m_inferenceHelper->preProcess(m_inputTensorList) != InferenceHelper::RET_OK) { return RET_ERR; } const auto& tPreProcess1 = std::chrono::steady_clock::now(); /*** Inference ***/ const auto& tInference0 = std::chrono::steady_clock::now(); if (m_inferenceHelper->invoke(m_outputTensorList) != InferenceHelper::RET_OK) { return RET_ERR; } const auto& tInference1 = std::chrono::steady_clock::now(); /*** PostProcess ***/ const auto& tPostProcess0 = std::chrono::steady_clock::now(); /* Retrieve the result */ HAND_LANDMARK& handLandmark = result.handLandmark; handLandmark.handflag = m_outputTensorList[1].getDataAsFloat()[0]; handLandmark.handedness = m_outputTensorList[2].getDataAsFloat()[0]; const float *ld21 = m_outputTensorList[0].getDataAsFloat(); //printf("%f %f\n", m_outputTensorHandflag->getDataAsFloat()[0], m_outputTensorHandedness->getDataAsFloat()[0]); for (int32_t i = 0; i < 21; i++) { handLandmark.pos[i].x = ld21[i * 3 + 0] / inputTensorInfo.tensorDims.width; // 0.0 - 1.0 handLandmark.pos[i].y = ld21[i * 3 + 1] / inputTensorInfo.tensorDims.height; // 0.0 - 1.0 handLandmark.pos[i].z = ld21[i * 3 + 2] * 1; // Scale Z coordinate as X. (-100 - 100???) todo //printf("%f\n", m_outputTensorLd21->getDataAsFloat()[i]); //cv::circle(originalMat, cv::Point(m_outputTensorLd21->getDataAsFloat()[i * 3 + 0], m_outputTensorLd21->getDataAsFloat()[i * 3 + 1]), 5, cv::Scalar(255, 255, 0), 1); } /* Fix landmark rotation */ for (int32_t i = 0; i < 21; i++) { handLandmark.pos[i].x *= rotatedImage.cols; // coordinate on rotatedImage handLandmark.pos[i].y *= rotatedImage.rows; } rotateLandmark(handLandmark, palmRotation, rotatedImage.cols, rotatedImage.rows); // coordinate on thei nput image /* Calculate palm rectangle from Landmark */ transformLandmarkToRect(handLandmark); handLandmark.rect.rotation = calculateRotation(handLandmark); for (int32_t i = 0; i < 21; i++) { handLandmark.pos[i].x += palmX; handLandmark.pos[i].y += palmY; } handLandmark.rect.x += palmX; handLandmark.rect.y += palmY; const auto& tPostProcess1 = std::chrono::steady_clock::now(); /* Return the results */ result.timePreProcess = static_cast<std::chrono::duration<double>>(tPreProcess1 - tPreProcess0).count() * 1000.0; result.timeInference = static_cast<std::chrono::duration<double>>(tInference1 - tInference0).count() * 1000.0; result.timePostProcess = static_cast<std::chrono::duration<double>>(tPostProcess1 - tPostProcess0).count() * 1000.0;; return RET_OK; } void HandLandmarkEngine::rotateLandmark(HAND_LANDMARK& handLandmark, float rotationRad, int32_t imageWidth, int32_t imageHeight) { for (int32_t i = 0; i < 21; i++) { float x = handLandmark.pos[i].x - imageWidth / 2.f; float y = handLandmark.pos[i].y - imageHeight / 2.f; handLandmark.pos[i].x = x * std::cos(rotationRad) - y * std::sin(rotationRad) + imageWidth / 2.f; handLandmark.pos[i].y = x * std::sin(rotationRad) + y * std::cos(rotationRad) + imageHeight / 2.f; //handLandmark.pos[i].x = std::min(handLandmark.pos[i].x, 1.f); //handLandmark.pos[i].y = std::min(handLandmark.pos[i].y, 1.f); }; } float HandLandmarkEngine::calculateRotation(const HAND_LANDMARK& handLandmark) { // Reference: mediapipe\graphs\hand_tracking\calculators\hand_detections_to_rects_calculator.cc constexpr int32_t kWristJoint = 0; constexpr int32_t kMiddleFingerPIPJoint = 12; constexpr int32_t kIndexFingerPIPJoint = 8; constexpr int32_t kRingFingerPIPJoint = 16; constexpr float target_angle_ = static_cast<float>(M_PI) * 0.5f; const float x0 = handLandmark.pos[kWristJoint].x; const float y0 = handLandmark.pos[kWristJoint].y; float x1 = (handLandmark.pos[kMiddleFingerPIPJoint].x + handLandmark.pos[kMiddleFingerPIPJoint].x) / 2.f; float y1 = (handLandmark.pos[kMiddleFingerPIPJoint].y + handLandmark.pos[kMiddleFingerPIPJoint].y) / 2.f; x1 = (x1 + handLandmark.pos[kMiddleFingerPIPJoint].x) / 2.f; y1 = (y1 + handLandmark.pos[kMiddleFingerPIPJoint].y) / 2.f; float rotation; rotation = target_angle_ - std::atan2(-(y1 - y0), x1 - x0); rotation = rotation - 2 * static_cast<float>(M_PI) * std::floor((rotation - (-static_cast<float>(M_PI))) / (2 * static_cast<float>(M_PI))); return rotation; } void HandLandmarkEngine::transformLandmarkToRect(HAND_LANDMARK &handLandmark) { constexpr float shift_x = 0.0f; constexpr float shift_y = -0.0f; constexpr float scale_x = 1.8f; // tuned parameter by looking constexpr float scale_y = 1.8f; float width = 0; float height = 0; float x_center = 0; float y_center = 0; float xmin = handLandmark.pos[0].x; float xmax = handLandmark.pos[0].x; float ymin = handLandmark.pos[0].y; float ymax = handLandmark.pos[0].y; for (int32_t i = 0; i < 21; i++) { if (handLandmark.pos[i].x < xmin) xmin = handLandmark.pos[i].x; if (handLandmark.pos[i].x > xmax) xmax = handLandmark.pos[i].x; if (handLandmark.pos[i].y < ymin) ymin = handLandmark.pos[i].y; if (handLandmark.pos[i].y > ymax) ymax = handLandmark.pos[i].y; } width = xmax - xmin; height = ymax - ymin; x_center = (xmax + xmin) / 2.f; y_center = (ymax + ymin) / 2.f; width *= scale_x; height *= scale_y; float long_side = std::max(width, height); /* for hand is closed */ //float palmDistance = powf(handLandmark.pos[0].x - handLandmark.pos[9].x, 2) + powf(handLandmark.pos[0].y - handLandmark.pos[9].y, 2); //palmDistance = sqrtf(palmDistance); //long_side = std::max(long_side, palmDistance); handLandmark.rect.width = (long_side * 1); handLandmark.rect.height = (long_side * 1); handLandmark.rect.x = (x_center - handLandmark.rect.width / 2); handLandmark.rect.y = (y_center - handLandmark.rect.height / 2); }
39.426573
169
0.715945
bjarkirafn
a0ba8241d34a89a56e6b9642cda3a1bb4b9153b0
7,351
cpp
C++
src/internal/modbusTcpSlave.cpp
baggior/SmartHome_GATEWAY
14fd80e701d92ef79ee2289af40d8334fa48c154
[ "MIT" ]
1
2018-03-06T10:31:09.000Z
2018-03-06T10:31:09.000Z
src/internal/modbusTcpSlave.cpp
baggior/SmartHome_GATEWAY
14fd80e701d92ef79ee2289af40d8334fa48c154
[ "MIT" ]
4
2018-02-05T15:58:19.000Z
2018-11-05T10:11:50.000Z
src/internal/modbusTcpSlave.cpp
baggior/SmartHome_GATEWAY
14fd80e701d92ef79ee2289af40d8334fa48c154
[ "MIT" ]
null
null
null
#include "Arduino.h" #include "modbusTcpSlave.h" // WiFiServer mbServer(MODBUSIP_PORT); #define TCP_TIMEOUT_MS RTU_TIMEOUT * 2 ModbusTcpSlave::ModbusTcpSlave(_ApplicationLogger& logger, uint16_t port = MODBUSIP_PORT, bool _isDebug = false) : mbServer(port), mLogger(logger), isDebug(_isDebug) { mbServer.begin(); mbServer.setNoDelay(true); #ifdef ESP32 mbServer.setTimeout(TCP_TIMEOUT_MS / 1000); #endif for (uint8_t i = 0 ; i < FRAME_COUNT; i++) mbFrame[i].status = frameStatus::empty; for (uint8_t i = 0 ; i < CLIENT_NUM; i++) clientOnLine[i].onLine = false; } ModbusTcpSlave::~ModbusTcpSlave() { } void ModbusTcpSlave::waitNewClient(void) { // see if the old customers are alive if not alive then release them for (uint8_t i = 0 ; i < CLIENT_NUM; i++) { //find free/disconnected spot if (clientOnLine[i].onLine && !clientOnLine[i].client.connected()) { clientOnLine[i].client.stop(); // clientOnLine[i].onLine = false; this->mLogger.debug (("\tClient stopped: [%d]\n"), i); } // else clientOnLine[i].client.flush(); } if (mbServer.hasClient()) { bool clientAdded = false; for(uint8_t i = 0 ; i < CLIENT_NUM; i++) { if( !clientOnLine[i].onLine) { clientOnLine[i].client = mbServer.available(); clientOnLine[i].client.setNoDelay(true); //disable delay feature algorithm clientOnLine[i].onLine = true; clientAdded = true; if(this->isDebug) { this->mLogger.debug (("\tNew Client: [%d] remote Ip: %s\n"), i, clientOnLine[i].client.remoteIP().toString().c_str()); } break; } } if (!clientAdded) // If there was no place for a new client { //no free/disconnected spot so reject this->mLogger.error (("\tToo many Clients reject the new connection \n") ); mbServer.available().stop(); // clientOnLine[0].client.stop(); // clientOnLine[0].client = mbServer.available(); } } } void ModbusTcpSlave::readDataClient(void) { for(uint8_t i = 0; i < CLIENT_NUM; i++) { if(clientOnLine[i].onLine) { if(clientOnLine[i].client.available()) { this->readFrameClient(clientOnLine[i].client, i); } } } } void ModbusTcpSlave::readFrameClient(WiFiClient client, uint8_t nClient) { size_t available = client.available(); if ((available < TCP_BUFFER_SIZE) && (available > 11)) { size_t len = available; uint8_t buf[len]; size_t count = 0; while(client.available()) { buf[count] = client.read(); count++; } count =0; smbap mbap; mbapUnpack(&mbap, &buf[0]); if(this->isDebug) { this->mLogger.debug (("\tPaket in : len TCP data [%d] Len mbap pak [%d], UnitId [%d], TI [%d] \n"), len, mbap._len, mbap._ui, mbap._ti); } // checking for glued requests. (wizards are requested for 4 requests) while((count < len ) && ((len - count) <= (size_t) (mbap._len + TCP_MBAP_SIZE)) && (mbap._pi ==0)) { smbFrame * pmbFrame = this->getFreeBuffer(); if(pmbFrame == 0) break; // if there is no free buffer then we reduce the parsing pmbFrame->nClient = nClient; if(mbap._ui==0) { // UnitId = 0 => broadcast modbus message pmbFrame->status = frameStatus::readyToSendRtuNoReply; } else { pmbFrame->status = frameStatus::readyToSendRtu; } pmbFrame->len = mbap._len + TCP_MBAP_SIZE; pmbFrame->millis = millis(); for (uint16_t j = 0; j < (pmbFrame->len); j++) pmbFrame->buffer[j] = buf[j]; count += pmbFrame->len; mbapUnpack(&mbap, &buf[count]); } } else { this->mLogger.error (("\tTCP client [%d] data count invalid : %d\n"), nClient, available); // uint16_t tmp = client.available(); while(client.available()) client.read(); } } void ModbusTcpSlave::writeFrameClient(void) { smbFrame * pmbFrame = this->getReadyToSendTcpBuffer(); if(pmbFrame) { uint8_t cli = pmbFrame->nClient; size_t len = pmbFrame->len; if(! clientOnLine[cli].client.connected() ) { this->mLogger.warn (("\tERROR writeFrameClient: writing to a disconnected client: %d"), cli); return; } size_t written = clientOnLine[cli].client.write(&pmbFrame->buffer[0], len); // write to TCP client if(this->isDebug) { this->mLogger.debug (("\twritten data buffer to TCP client: %d, len=%d\n"), cli, len ); } if(written!= len) { this->mLogger.error (("\tERROR writeFrameClient: writing buffer [%d] to RTU client len_to_write=%d, written=%d\n"), cli, len, written); } // delay(1); // yield(); clientOnLine[cli].client.flush(); pmbFrame->status = frameStatus::empty; } } // void ModbusTcpSlave::task() // { // waitNewClient(); // yield(); // readDataClient(); // yield(); // writeFrameClient(); // yield(); // timeoutBufferCleanup(); // } void ModbusTcpSlave::timeoutBufferCleanup() { // Cleaning the buffers for(uint8_t i = 0; i < FRAME_COUNT; i++) { if(mbFrame[i].status != frameStatus::empty ) { if (millis() - mbFrame[i].millis > RTU_TIMEOUT) { mbFrame[i].status = frameStatus::empty; // this->mLogger.printf (("\tRTU_TIMEOUT -> Del pack.\n")); this->mLogger.error (("\tRTU_TIMEOUT -> Del pack.\n")); } } } } ModbusTcpSlave::smbFrame * ModbusTcpSlave::getFreeBuffer () { static uint8_t scanBuff = 0; while (mbFrame[scanBuff].status != frameStatus::empty) { scanBuff++; if(scanBuff >= FRAME_COUNT) { this->mLogger.error (("\tNo Free buffer\n")); scanBuff = 0; return 0; } } //init frame mbFrame[scanBuff].nClient=0; mbFrame[scanBuff].len=0; mbFrame[scanBuff].millis=0; mbFrame[scanBuff].guessedReponseLen=0; mbFrame[scanBuff].ascii_response_buffer=""; return &mbFrame[scanBuff]; } ModbusTcpSlave::smbFrame * ModbusTcpSlave::getReadyToSendRtuBuffer () { uint8_t pointer = 255; uint8_t pointerMillis = 0; for(uint8_t i = 0; i < FRAME_COUNT; i++) { if(mbFrame[i].status == frameStatus::readyToSendRtu || mbFrame[i].status == frameStatus::readyToSendRtuNoReply) { // check if current buffer is older if ( pointerMillis < (millis() - mbFrame[i].millis)) { pointerMillis = millis() - mbFrame[i].millis; pointer = i; } } } if (pointer != 255) return &mbFrame[pointer]; //returns the LEAST RECENTLY modified frame buffer else return NULL; } ModbusTcpSlave::smbFrame * ModbusTcpSlave::getWaitFromRtuBuffer () { for(uint8_t i = 0; i < FRAME_COUNT; i++) { if(mbFrame[i].status == frameStatus::waitFromRtu ) return &mbFrame[i]; } return NULL; } ModbusTcpSlave::smbFrame *ModbusTcpSlave::getReadyToSendTcpBuffer () { for(uint8_t i = 0; i < FRAME_COUNT; i++) { if(mbFrame[i].status == frameStatus::readyToSendTcp ) return &mbFrame[i]; } return NULL; } void ModbusTcpSlave::mbapUnpack(smbap* pmbap, uint8_t * buff ) { pmbap->_ti = *(buff + 0) << 8 | *(buff + 1); pmbap->_pi = *(buff + 2) << 8 | *(buff + 3); pmbap->_len = *(buff + 4) << 8 | *(buff + 5); pmbap->_ui = *(buff + 6); }
26.828467
141
0.604544
baggior
a0bdfd8f762fc66b4df84cdd9e62f37418311e2e
1,248
cpp
C++
Music Player/Using c++/Data sturcutre Project/Data sturcutre Project/Source.cpp
rafay99-epic/University-Projects
49cbd2c1e5e5879dd1dd2364301e35fd5c0bba81
[ "MIT" ]
null
null
null
Music Player/Using c++/Data sturcutre Project/Data sturcutre Project/Source.cpp
rafay99-epic/University-Projects
49cbd2c1e5e5879dd1dd2364301e35fd5c0bba81
[ "MIT" ]
null
null
null
Music Player/Using c++/Data sturcutre Project/Data sturcutre Project/Source.cpp
rafay99-epic/University-Projects
49cbd2c1e5e5879dd1dd2364301e35fd5c0bba81
[ "MIT" ]
null
null
null
#include "music.h" #include<iostream> #include<string> #include<fstream> using namespace std; int main() { Node n; int count{}; int choice; char yes; int const size = 3; int i = 0; music_data s; fstream data("music.txt", ios::out); ifstream take("music.txt"); take >> count; do { cout << endl << " " << "=====MENU=====" << endl; cout << endl << " " << "1.To Enter the data in to the File. " << endl; cout << endl << " " << "2.To display all of the data." << endl; cout << endl << " " << "Enter the choice: "; cin >> choice; switch (choice) { case 1: do { cout << endl << " " << "Enter the name of the song: "; cin.ignore(); getline(cin, s.name); cout << endl << " " << "Enter the name of movie: "; cin.ignore(); getline(cin, s.movie); cout << endl << " " << "Enter the name of the Singer: "; cin.ignore(); getline(cin, s.singer); data.write(reinterpret_cast<char*>(&s), sizeof(s)); cout << endl << " " << "Do you like to store the data again: "; cin >> yes; } while (yes == 'Y' && 1 < 3); for (int i = 0; i < count; i++) { take >> n.array[i]; } break; default: break; } } while (choice!=3); system("pause"); return 0; }
20.459016
73
0.525641
rafay99-epic
a0d1966a5f0f687659b75e2e06f569152b0a7a11
1,748
cpp
C++
leetcode99.cpp
SJTUGavinLiu/Leetcodes
99d4010bc34e78d22e3c8b6436e4489a7d1338da
[ "MIT" ]
null
null
null
leetcode99.cpp
SJTUGavinLiu/Leetcodes
99d4010bc34e78d22e3c8b6436e4489a7d1338da
[ "MIT" ]
null
null
null
leetcode99.cpp
SJTUGavinLiu/Leetcodes
99d4010bc34e78d22e3c8b6436e4489a7d1338da
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void recoverTree(TreeNode* root) { if(!root) return; stack<TreeNode*> st; vector<int> res; st.push(root); TreeNode* p = root; while(p->left) { st.push(p->left); p = p->left; } TreeNode* p1 = NULL; TreeNode* p2 = NULL; TreeNode* q; int flag = 0; int pre = 0; while(!st.empty()) { p = st.top(); st.pop(); q = p->right; while(q) { st.push(q); q = q->left; } if(!p1 && p->val > st.top()->val) { p1 = p; TreeNode* tmp = st.top(); st.pop(); q = tmp->right; while(q) { st.push(q); q = q->left; } if(st.empty() || st.top()->val > p1->val) { p2 = tmp; break; } flag = 1; pre = tmp->val; continue; } if(flag && !p2 && (st.empty() || p->val < pre)) { p2 = p; break; } pre = p->val; } int tmp = p1->val; p1->val = p2->val; p2->val = tmp; return ; } };
20.091954
59
0.306636
SJTUGavinLiu
a0d2c4eba9be4d74b5122054bc41d60203387dbe
573
cc
C++
ODWROTNO.cc
hkktr/POLSKI-SPOJ
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
[ "Unlicense" ]
1
2021-02-01T11:21:56.000Z
2021-02-01T11:21:56.000Z
ODWROTNO.cc
hkktr/POLSKI-SPOJ
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
[ "Unlicense" ]
null
null
null
ODWROTNO.cc
hkktr/POLSKI-SPOJ
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
[ "Unlicense" ]
1
2022-01-28T15:25:45.000Z
2022-01-28T15:25:45.000Z
// C++ (gcc 8.3) #include <iostream> #include <tuple> std::tuple<int, int, int> ExtendedGCD(int a, int b) { if (a == 0) return std::make_tuple(0, 1, b); int x, y, gcd; std::tie(x, y, gcd) = ExtendedGCD(b % a, a); return std::make_tuple(y - (b / a) * x, x, gcd); } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); int t; std::cin >> t; int p, n; while (--t >= 0) { std::cin >> p >> n; int y{std::get<1>(ExtendedGCD(p, n))}; if (y < 0) y -= ((y - p + 1) / p) * p; std::cout << y << "\n"; } return 0; }
18.483871
53
0.506108
hkktr
a0d4693a070316b4f3e9c3941bbe77b0c081a6b3
40,854
cpp
C++
export/windows/obj/src/lime/utils/Assets.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
null
null
null
export/windows/obj/src/lime/utils/Assets.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
null
null
null
export/windows/obj/src/lime/utils/Assets.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
1
2021-07-16T22:57:01.000Z
2021-07-16T22:57:01.000Z
// Generated by Haxe 4.0.0-rc.2+77068e10c #include <hxcpp.h> #ifndef INCLUDED_StringTools #include <StringTools.h> #endif #ifndef INCLUDED_haxe_IMap #include <haxe/IMap.h> #endif #ifndef INCLUDED_haxe_ds_StringMap #include <haxe/ds/StringMap.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_lime_app_Application #include <lime/app/Application.h> #endif #ifndef INCLUDED_lime_app_Future #include <lime/app/Future.h> #endif #ifndef INCLUDED_lime_app_IModule #include <lime/app/IModule.h> #endif #ifndef INCLUDED_lime_app_Module #include <lime/app/Module.h> #endif #ifndef INCLUDED_lime_app_Promise_lime_utils_AssetLibrary #include <lime/app/Promise_lime_utils_AssetLibrary.h> #endif #ifndef INCLUDED_lime_app__Event_Void_Void #include <lime/app/_Event_Void_Void.h> #endif #ifndef INCLUDED_lime_graphics_Image #include <lime/graphics/Image.h> #endif #ifndef INCLUDED_lime_graphics_ImageBuffer #include <lime/graphics/ImageBuffer.h> #endif #ifndef INCLUDED_lime_media_AudioBuffer #include <lime/media/AudioBuffer.h> #endif #ifndef INCLUDED_lime_text_Font #include <lime/text/Font.h> #endif #ifndef INCLUDED_lime_utils_AssetCache #include <lime/utils/AssetCache.h> #endif #ifndef INCLUDED_lime_utils_AssetLibrary #include <lime/utils/AssetLibrary.h> #endif #ifndef INCLUDED_lime_utils_AssetManifest #include <lime/utils/AssetManifest.h> #endif #ifndef INCLUDED_lime_utils_Assets #include <lime/utils/Assets.h> #endif #ifndef INCLUDED_lime_utils_Log #include <lime/utils/Log.h> #endif #ifndef INCLUDED_lime_utils_Preloader #include <lime/utils/Preloader.h> #endif HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_46_exists,"lime.utils.Assets","exists",0x1d422f71,"lime.utils.Assets.exists","lime/utils/Assets.hx",46,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_71_getAsset,"lime.utils.Assets","getAsset",0x8d49da4f,"lime.utils.Assets.getAsset","lime/utils/Assets.hx",71,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_157_getAudioBuffer,"lime.utils.Assets","getAudioBuffer",0x84c07015,"lime.utils.Assets.getAudioBuffer","lime/utils/Assets.hx",157,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_168_getBytes,"lime.utils.Assets","getBytes",0x24a878ca,"lime.utils.Assets.getBytes","lime/utils/Assets.hx",168,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_179_getFont,"lime.utils.Assets","getFont",0x6eb05e50,"lime.utils.Assets.getFont","lime/utils/Assets.hx",179,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_191_getImage,"lime.utils.Assets","getImage",0x24798fba,"lime.utils.Assets.getImage","lime/utils/Assets.hx",191,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_195_getLibrary,"lime.utils.Assets","getLibrary",0xdfc4ad1a,"lime.utils.Assets.getLibrary","lime/utils/Assets.hx",195,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_211_getPath,"lime.utils.Assets","getPath",0x7541e626,"lime.utils.Assets.getPath","lime/utils/Assets.hx",211,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_243_getText,"lime.utils.Assets","getText",0x77e9cd2e,"lime.utils.Assets.getText","lime/utils/Assets.hx",243,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_247_hasLibrary,"lime.utils.Assets","hasLibrary",0x1b170ed6,"lime.utils.Assets.hasLibrary","lime/utils/Assets.hx",247,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_257_isLocal,"lime.utils.Assets","isLocal",0x6de3bdec,"lime.utils.Assets.isLocal","lime/utils/Assets.hx",257,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_275_isValidAudio,"lime.utils.Assets","isValidAudio",0xfba1fa19,"lime.utils.Assets.isValidAudio","lime/utils/Assets.hx",275,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_282_isValidImage,"lime.utils.Assets","isValidImage",0x918aa09e,"lime.utils.Assets.isValidImage","lime/utils/Assets.hx",282,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_286_list,"lime.utils.Assets","list",0x96ec2eb3,"lime.utils.Assets.list","lime/utils/Assets.hx",286,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_303_loadAsset,"lime.utils.Assets","loadAsset",0x8c6c0f75,"lime.utils.Assets.loadAsset","lime/utils/Assets.hx",303,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_355_loadAsset,"lime.utils.Assets","loadAsset",0x8c6c0f75,"lime.utils.Assets.loadAsset","lime/utils/Assets.hx",355,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_376_loadAudioBuffer,"lime.utils.Assets","loadAudioBuffer",0xa72805bb,"lime.utils.Assets.loadAudioBuffer","lime/utils/Assets.hx",376,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_381_loadBytes,"lime.utils.Assets","loadBytes",0x23caadf0,"lime.utils.Assets.loadBytes","lime/utils/Assets.hx",381,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_386_loadFont,"lime.utils.Assets","loadFont",0xbb998fea,"lime.utils.Assets.loadFont","lime/utils/Assets.hx",386,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_391_loadImage,"lime.utils.Assets","loadImage",0x239bc4e0,"lime.utils.Assets.loadImage","lime/utils/Assets.hx",391,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_425_loadLibrary,"lime.utils.Assets","loadLibrary",0x93baf7c0,"lime.utils.Assets.loadLibrary","lime/utils/Assets.hx",425,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_446_loadLibrary,"lime.utils.Assets","loadLibrary",0x93baf7c0,"lime.utils.Assets.loadLibrary","lime/utils/Assets.hx",446,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_395_loadLibrary,"lime.utils.Assets","loadLibrary",0x93baf7c0,"lime.utils.Assets.loadLibrary","lime/utils/Assets.hx",395,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_455_loadText,"lime.utils.Assets","loadText",0xc4d2fec8,"lime.utils.Assets.loadText","lime/utils/Assets.hx",455,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_459_registerLibrary,"lime.utils.Assets","registerLibrary",0xb6301ea3,"lime.utils.Assets.registerLibrary","lime/utils/Assets.hx",459,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_481_unloadLibrary,"lime.utils.Assets","unloadLibrary",0xc816d6c7,"lime.utils.Assets.unloadLibrary","lime/utils/Assets.hx",481,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_512___cacheBreak,"lime.utils.Assets","__cacheBreak",0xe7faf592,"lime.utils.Assets.__cacheBreak","lime/utils/Assets.hx",512,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_516___libraryNotFound,"lime.utils.Assets","__libraryNotFound",0x7dfa37b5,"lime.utils.Assets.__libraryNotFound","lime/utils/Assets.hx",516,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_534_library_onChange,"lime.utils.Assets","library_onChange",0x3a89dec8,"lime.utils.Assets.library_onChange","lime/utils/Assets.hx",534,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_39_boot,"lime.utils.Assets","boot",0x90549687,"lime.utils.Assets.boot","lime/utils/Assets.hx",39,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_40_boot,"lime.utils.Assets","boot",0x90549687,"lime.utils.Assets.boot","lime/utils/Assets.hx",40,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_42_boot,"lime.utils.Assets","boot",0x90549687,"lime.utils.Assets.boot","lime/utils/Assets.hx",42,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_43_boot,"lime.utils.Assets","boot",0x90549687,"lime.utils.Assets.boot","lime/utils/Assets.hx",43,0x95055f23) namespace lime{ namespace utils{ void Assets_obj::__construct() { } Dynamic Assets_obj::__CreateEmpty() { return new Assets_obj; } void *Assets_obj::_hx_vtable = 0; Dynamic Assets_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< Assets_obj > _hx_result = new Assets_obj(); _hx_result->__construct(); return _hx_result; } bool Assets_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x2b49805f; } ::lime::utils::AssetCache Assets_obj::cache; ::lime::app::_Event_Void_Void Assets_obj::onChange; ::String Assets_obj::defaultRootPath; ::haxe::ds::StringMap Assets_obj::libraries; ::haxe::ds::StringMap Assets_obj::libraryPaths; bool Assets_obj::exists(::String id,::String type){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_46_exists) HXLINE( 48) if (hx::IsNull( type )) { HXLINE( 50) type = HX_("BINARY",01,68,8e,9f); } HXLINE( 53) ::String id1 = id; HXDLIN( 53) int colonIndex = id1.indexOf(HX_(":",3a,00,00,00),null()); HXDLIN( 53) ::String symbol_libraryName = id1.substring(0,colonIndex); HXDLIN( 53) ::String symbol_symbolName = id1.substring((colonIndex + 1),null()); HXDLIN( 53) ::lime::utils::AssetLibrary symbol_library = ::lime::utils::Assets_obj::getLibrary(symbol_libraryName); HXLINE( 55) if (hx::IsNotNull( symbol_library )) { HXLINE( 57) return symbol_library->exists(symbol_symbolName,type); } HXLINE( 61) return false; } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,exists,return ) ::Dynamic Assets_obj::getAsset(::String id,::String type,bool useCache){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_71_getAsset) HXLINE( 73) bool _hx_tmp; HXDLIN( 73) if (useCache) { HXLINE( 73) _hx_tmp = ::lime::utils::Assets_obj::cache->enabled; } else { HXLINE( 73) _hx_tmp = false; } HXDLIN( 73) if (_hx_tmp) { HXLINE( 75) ::String _hx_switch_0 = type; if ( (_hx_switch_0==HX_("BINARY",01,68,8e,9f)) || (_hx_switch_0==HX_("TEXT",ad,94,ba,37)) ){ HXLINE( 79) useCache = false; HXDLIN( 79) goto _hx_goto_1; } if ( (_hx_switch_0==HX_("FONT",cf,25,81,2e)) ){ HXLINE( 82) ::Dynamic font = ::lime::utils::Assets_obj::cache->font->get(id); HXLINE( 84) if (hx::IsNotNull( font )) { HXLINE( 86) return font; } HXLINE( 81) goto _hx_goto_1; } if ( (_hx_switch_0==HX_("IMAGE",3b,57,57,3b)) ){ HXLINE( 90) ::lime::graphics::Image image = ( ( ::lime::graphics::Image)(::lime::utils::Assets_obj::cache->image->get(id)) ); HXLINE( 92) if (::lime::utils::Assets_obj::isValidImage(image)) { HXLINE( 94) return image; } HXLINE( 89) goto _hx_goto_1; } if ( (_hx_switch_0==HX_("MUSIC",85,08,49,8e)) || (_hx_switch_0==HX_("SOUND",af,c4,ba,fe)) ){ HXLINE( 98) ::lime::media::AudioBuffer audio = ( ( ::lime::media::AudioBuffer)(::lime::utils::Assets_obj::cache->audio->get(id)) ); HXLINE( 100) if (::lime::utils::Assets_obj::isValidAudio(audio)) { HXLINE( 102) return audio; } HXLINE( 97) goto _hx_goto_1; } if ( (_hx_switch_0==HX_("TEMPLATE",3a,78,cd,05)) ){ HXLINE( 106) HX_STACK_DO_THROW((HX_("Not sure how to get template: ",a1,19,8c,ad) + id)); HXDLIN( 106) goto _hx_goto_1; } /* default */{ HXLINE( 109) return null(); } _hx_goto_1:; } HXLINE( 113) ::String id1 = id; HXDLIN( 113) int colonIndex = id1.indexOf(HX_(":",3a,00,00,00),null()); HXDLIN( 113) ::String symbol_libraryName = id1.substring(0,colonIndex); HXDLIN( 113) ::String symbol_symbolName = id1.substring((colonIndex + 1),null()); HXDLIN( 113) ::lime::utils::AssetLibrary symbol_library = ::lime::utils::Assets_obj::getLibrary(symbol_libraryName); HXLINE( 115) if (hx::IsNotNull( symbol_library )) { HXLINE( 117) if (symbol_library->exists(symbol_symbolName,type)) { HXLINE( 119) if (symbol_library->isLocal(symbol_symbolName,type)) { HXLINE( 121) ::Dynamic asset = symbol_library->getAsset(symbol_symbolName,type); HXLINE( 123) bool _hx_tmp1; HXDLIN( 123) if (useCache) { HXLINE( 123) _hx_tmp1 = ::lime::utils::Assets_obj::cache->enabled; } else { HXLINE( 123) _hx_tmp1 = false; } HXDLIN( 123) if (_hx_tmp1) { HXLINE( 125) ::lime::utils::Assets_obj::cache->set(id,type,asset); } HXLINE( 128) return asset; } else { HXLINE( 132) ::lime::utils::Log_obj::error((((type + HX_(" asset \"",d2,25,2a,5d)) + id) + HX_("\" exists, but only asynchronously",dc,ca,f2,dd)),hx::SourceInfo(HX_("lime/utils/Assets.hx",23,5f,05,95),132,HX_("lime.utils.Assets",39,6e,7e,b0),HX_("getAsset",7a,79,10,86))); } } else { HXLINE( 137) ::lime::utils::Log_obj::error(((((HX_("There is no ",e5,bb,ab,c5) + type) + HX_(" asset with an ID of \"",95,f2,3a,0d)) + id) + HX_("\"",22,00,00,00)),hx::SourceInfo(HX_("lime/utils/Assets.hx",23,5f,05,95),137,HX_("lime.utils.Assets",39,6e,7e,b0),HX_("getAsset",7a,79,10,86))); } } else { HXLINE( 142) ::String _hx_tmp2 = ::lime::utils::Assets_obj::_hx___libraryNotFound(symbol_libraryName); HXDLIN( 142) ::lime::utils::Log_obj::error(_hx_tmp2,hx::SourceInfo(HX_("lime/utils/Assets.hx",23,5f,05,95),142,HX_("lime.utils.Assets",39,6e,7e,b0),HX_("getAsset",7a,79,10,86))); } HXLINE( 146) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC3(Assets_obj,getAsset,return ) ::lime::media::AudioBuffer Assets_obj::getAudioBuffer(::String id,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACKFRAME(&_hx_pos_df5754140b017d9f_157_getAudioBuffer) HXDLIN( 157) return ( ( ::lime::media::AudioBuffer)(::lime::utils::Assets_obj::getAsset(id,HX_("SOUND",af,c4,ba,fe),useCache)) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,getAudioBuffer,return ) ::haxe::io::Bytes Assets_obj::getBytes(::String id){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_168_getBytes) HXDLIN( 168) return ( ( ::haxe::io::Bytes)(::lime::utils::Assets_obj::getAsset(id,HX_("BINARY",01,68,8e,9f),false)) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,getBytes,return ) ::lime::text::Font Assets_obj::getFont(::String id,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACKFRAME(&_hx_pos_df5754140b017d9f_179_getFont) HXDLIN( 179) return ( ( ::lime::text::Font)(::lime::utils::Assets_obj::getAsset(id,HX_("FONT",cf,25,81,2e),useCache)) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,getFont,return ) ::lime::graphics::Image Assets_obj::getImage(::String id,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACKFRAME(&_hx_pos_df5754140b017d9f_191_getImage) HXDLIN( 191) return ( ( ::lime::graphics::Image)(::lime::utils::Assets_obj::getAsset(id,HX_("IMAGE",3b,57,57,3b),useCache)) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,getImage,return ) ::lime::utils::AssetLibrary Assets_obj::getLibrary(::String name){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_195_getLibrary) HXLINE( 196) bool _hx_tmp; HXDLIN( 196) if (hx::IsNotNull( name )) { HXLINE( 196) _hx_tmp = (name == HX_("",00,00,00,00)); } else { HXLINE( 196) _hx_tmp = true; } HXDLIN( 196) if (_hx_tmp) { HXLINE( 198) name = HX_("default",c1,d8,c3,9b); } HXLINE( 201) return ( ( ::lime::utils::AssetLibrary)(::lime::utils::Assets_obj::libraries->get(name)) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,getLibrary,return ) ::String Assets_obj::getPath(::String id){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_211_getPath) HXLINE( 213) ::String id1 = id; HXDLIN( 213) int colonIndex = id1.indexOf(HX_(":",3a,00,00,00),null()); HXDLIN( 213) ::String symbol_libraryName = id1.substring(0,colonIndex); HXDLIN( 213) ::String symbol_symbolName = id1.substring((colonIndex + 1),null()); HXDLIN( 213) ::lime::utils::AssetLibrary symbol_library = ::lime::utils::Assets_obj::getLibrary(symbol_libraryName); HXLINE( 215) if (hx::IsNotNull( symbol_library )) { HXLINE( 217) if (symbol_library->exists(symbol_symbolName,null())) { HXLINE( 219) return symbol_library->getPath(symbol_symbolName); } else { HXLINE( 223) ::lime::utils::Log_obj::error(((HX_("There is no asset with an ID of \"",b0,92,42,96) + id) + HX_("\"",22,00,00,00)),hx::SourceInfo(HX_("lime/utils/Assets.hx",23,5f,05,95),223,HX_("lime.utils.Assets",39,6e,7e,b0),HX_("getPath",5b,95,d4,1c))); } } else { HXLINE( 228) ::String _hx_tmp = ::lime::utils::Assets_obj::_hx___libraryNotFound(symbol_libraryName); HXDLIN( 228) ::lime::utils::Log_obj::error(_hx_tmp,hx::SourceInfo(HX_("lime/utils/Assets.hx",23,5f,05,95),228,HX_("lime.utils.Assets",39,6e,7e,b0),HX_("getPath",5b,95,d4,1c))); } HXLINE( 232) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,getPath,return ) ::String Assets_obj::getText(::String id){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_243_getText) HXDLIN( 243) return ( (::String)(::lime::utils::Assets_obj::getAsset(id,HX_("TEXT",ad,94,ba,37),false)) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,getText,return ) bool Assets_obj::hasLibrary(::String name){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_247_hasLibrary) HXLINE( 248) bool _hx_tmp; HXDLIN( 248) if (hx::IsNotNull( name )) { HXLINE( 248) _hx_tmp = (name == HX_("",00,00,00,00)); } else { HXLINE( 248) _hx_tmp = true; } HXDLIN( 248) if (_hx_tmp) { HXLINE( 250) name = HX_("default",c1,d8,c3,9b); } HXLINE( 253) return ::lime::utils::Assets_obj::libraries->exists(name); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,hasLibrary,return ) bool Assets_obj::isLocal(::String id,::String type,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACKFRAME(&_hx_pos_df5754140b017d9f_257_isLocal) HXLINE( 259) bool _hx_tmp; HXDLIN( 259) if (useCache) { HXLINE( 259) _hx_tmp = ::lime::utils::Assets_obj::cache->enabled; } else { HXLINE( 259) _hx_tmp = false; } HXDLIN( 259) if (_hx_tmp) { HXLINE( 261) if (::lime::utils::Assets_obj::cache->exists(id,type)) { HXLINE( 261) return true; } } HXLINE( 264) ::String id1 = id; HXDLIN( 264) int colonIndex = id1.indexOf(HX_(":",3a,00,00,00),null()); HXDLIN( 264) ::String symbol_libraryName = id1.substring(0,colonIndex); HXDLIN( 264) ::String symbol_symbolName = id1.substring((colonIndex + 1),null()); HXDLIN( 264) ::lime::utils::AssetLibrary symbol_library = ::lime::utils::Assets_obj::getLibrary(symbol_libraryName); HXLINE( 265) if (hx::IsNotNull( symbol_library )) { HXLINE( 265) return symbol_library->isLocal(symbol_symbolName,type); } else { HXLINE( 265) return false; } HXDLIN( 265) return false; } STATIC_HX_DEFINE_DYNAMIC_FUNC3(Assets_obj,isLocal,return ) bool Assets_obj::isValidAudio( ::lime::media::AudioBuffer buffer){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_275_isValidAudio) HXDLIN( 275) return hx::IsNotNull( buffer ); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,isValidAudio,return ) bool Assets_obj::isValidImage( ::lime::graphics::Image image){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_282_isValidImage) HXDLIN( 282) if (hx::IsNotNull( image )) { HXDLIN( 282) return hx::IsNotNull( image->buffer ); } else { HXDLIN( 282) return false; } HXDLIN( 282) return false; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,isValidImage,return ) ::Array< ::String > Assets_obj::list(::String type){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_286_list) HXLINE( 287) ::Array< ::String > items = ::Array_obj< ::String >::__new(0); HXLINE( 289) { HXLINE( 289) ::Dynamic library = ::lime::utils::Assets_obj::libraries->iterator(); HXDLIN( 289) while(( (bool)(library->__Field(HX_("hasNext",6d,a5,46,18),hx::paccDynamic)()) )){ HXLINE( 289) ::lime::utils::AssetLibrary library1 = ( ( ::lime::utils::AssetLibrary)(library->__Field(HX_("next",f3,84,02,49),hx::paccDynamic)()) ); HXLINE( 291) ::Array< ::String > libraryItems = library1->list(type); HXLINE( 293) if (hx::IsNotNull( libraryItems )) { HXLINE( 295) items = items->concat(libraryItems); } } } HXLINE( 299) return items; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,list,return ) ::lime::app::Future Assets_obj::loadAsset(::String id,::String type,bool useCache){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_303_loadAsset) HXLINE( 305) bool _hx_tmp; HXDLIN( 305) if (useCache) { HXLINE( 305) _hx_tmp = ::lime::utils::Assets_obj::cache->enabled; } else { HXLINE( 305) _hx_tmp = false; } HXDLIN( 305) if (_hx_tmp) { HXLINE( 307) ::String _hx_switch_0 = type; if ( (_hx_switch_0==HX_("BINARY",01,68,8e,9f)) || (_hx_switch_0==HX_("TEXT",ad,94,ba,37)) ){ HXLINE( 311) useCache = false; HXDLIN( 311) goto _hx_goto_16; } if ( (_hx_switch_0==HX_("FONT",cf,25,81,2e)) ){ HXLINE( 314) ::Dynamic font = ::lime::utils::Assets_obj::cache->font->get(id); HXLINE( 316) if (hx::IsNotNull( font )) { HXLINE( 318) return ::lime::app::Future_obj::withValue(font); } HXLINE( 313) goto _hx_goto_16; } if ( (_hx_switch_0==HX_("IMAGE",3b,57,57,3b)) ){ HXLINE( 322) ::lime::graphics::Image image = ( ( ::lime::graphics::Image)(::lime::utils::Assets_obj::cache->image->get(id)) ); HXLINE( 324) if (::lime::utils::Assets_obj::isValidImage(image)) { HXLINE( 326) return ::lime::app::Future_obj::withValue(image); } HXLINE( 321) goto _hx_goto_16; } if ( (_hx_switch_0==HX_("MUSIC",85,08,49,8e)) || (_hx_switch_0==HX_("SOUND",af,c4,ba,fe)) ){ HXLINE( 330) ::lime::media::AudioBuffer audio = ( ( ::lime::media::AudioBuffer)(::lime::utils::Assets_obj::cache->audio->get(id)) ); HXLINE( 332) if (::lime::utils::Assets_obj::isValidAudio(audio)) { HXLINE( 334) return ::lime::app::Future_obj::withValue(audio); } HXLINE( 329) goto _hx_goto_16; } if ( (_hx_switch_0==HX_("TEMPLATE",3a,78,cd,05)) ){ HXLINE( 338) HX_STACK_DO_THROW((HX_("Not sure how to get template: ",a1,19,8c,ad) + id)); HXDLIN( 338) goto _hx_goto_16; } /* default */{ HXLINE( 341) return null(); } _hx_goto_16:; } HXLINE( 345) ::String id1 = id; HXDLIN( 345) int colonIndex = id1.indexOf(HX_(":",3a,00,00,00),null()); HXDLIN( 345) ::String symbol_libraryName = id1.substring(0,colonIndex); HXDLIN( 345) ::String symbol_symbolName = id1.substring((colonIndex + 1),null()); HXDLIN( 345) ::lime::utils::AssetLibrary symbol_library = ::lime::utils::Assets_obj::getLibrary(symbol_libraryName); HXLINE( 347) if (hx::IsNotNull( symbol_library )) { HXLINE( 349) if (symbol_library->exists(symbol_symbolName,type)) { HXLINE( 351) ::lime::app::Future future = symbol_library->loadAsset(symbol_symbolName,type); HXLINE( 353) bool _hx_tmp1; HXDLIN( 353) if (useCache) { HXLINE( 353) _hx_tmp1 = ::lime::utils::Assets_obj::cache->enabled; } else { HXLINE( 353) _hx_tmp1 = false; } HXDLIN( 353) if (_hx_tmp1) { HX_BEGIN_LOCAL_FUNC_S2(hx::LocalFunc,_hx_Closure_0,::String,id,::String,type) HXARGC(1) void _hx_run( ::Dynamic asset){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_355_loadAsset) HXLINE( 355) ::lime::utils::Assets_obj::cache->set(id,type,asset); } HX_END_LOCAL_FUNC1((void)) HXLINE( 355) future->onComplete( ::Dynamic(new _hx_Closure_0(id,type))); } HXLINE( 358) return future; } else { HXLINE( 362) return ::lime::app::Future_obj::withError(((((HX_("There is no ",e5,bb,ab,c5) + type) + HX_(" asset with an ID of \"",95,f2,3a,0d)) + id) + HX_("\"",22,00,00,00))); } } else { HXLINE( 367) return ::lime::app::Future_obj::withError(::lime::utils::Assets_obj::_hx___libraryNotFound(symbol_libraryName)); } HXLINE( 347) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC3(Assets_obj,loadAsset,return ) ::lime::app::Future Assets_obj::loadAudioBuffer(::String id,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACKFRAME(&_hx_pos_df5754140b017d9f_376_loadAudioBuffer) HXDLIN( 376) return ::lime::utils::Assets_obj::loadAsset(id,HX_("SOUND",af,c4,ba,fe),useCache); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,loadAudioBuffer,return ) ::lime::app::Future Assets_obj::loadBytes(::String id){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_381_loadBytes) HXDLIN( 381) return ::lime::utils::Assets_obj::loadAsset(id,HX_("BINARY",01,68,8e,9f),false); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,loadBytes,return ) ::lime::app::Future Assets_obj::loadFont(::String id,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACKFRAME(&_hx_pos_df5754140b017d9f_386_loadFont) HXDLIN( 386) return ::lime::utils::Assets_obj::loadAsset(id,HX_("FONT",cf,25,81,2e),useCache); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,loadFont,return ) ::lime::app::Future Assets_obj::loadImage(::String id,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACKFRAME(&_hx_pos_df5754140b017d9f_391_loadImage) HXDLIN( 391) return ::lime::utils::Assets_obj::loadAsset(id,HX_("IMAGE",3b,57,57,3b),useCache); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,loadImage,return ) ::lime::app::Future Assets_obj::loadLibrary(::String id){ HX_BEGIN_LOCAL_FUNC_S2(hx::LocalFunc,_hx_Closure_0,::String,id, ::lime::app::Promise_lime_utils_AssetLibrary,promise) HXARGC(1) void _hx_run( ::lime::utils::AssetManifest manifest){ HX_GC_STACKFRAME(&_hx_pos_df5754140b017d9f_425_loadLibrary) HXLINE( 426) if (hx::IsNull( manifest )) { HXLINE( 428) promise->error(((HX_("Cannot parse asset manifest for library \"",cf,1e,cc,48) + id) + HX_("\"",22,00,00,00))); HXLINE( 429) return; } HXLINE( 432) ::lime::utils::AssetLibrary library1 = ::lime::utils::AssetLibrary_obj::fromManifest(manifest); HXLINE( 434) if (hx::IsNull( library1 )) { HXLINE( 436) promise->error(((HX_("Cannot open library \"",44,cc,55,e7) + id) + HX_("\"",22,00,00,00))); } else { HXLINE( 440) ::lime::utils::Assets_obj::libraries->set(id,library1); HXLINE( 441) library1->onChange->add(::lime::utils::Assets_obj::onChange->dispatch_dyn(),null(),null()); HXLINE( 442) ::lime::app::Future _hx_tmp = library1->load(); HXDLIN( 442) promise->completeWith(_hx_tmp); } } HX_END_LOCAL_FUNC1((void)) HX_BEGIN_LOCAL_FUNC_S2(hx::LocalFunc,_hx_Closure_1,::String,id, ::lime::app::Promise_lime_utils_AssetLibrary,promise) HXARGC(1) void _hx_run( ::Dynamic _){ HX_GC_STACKFRAME(&_hx_pos_df5754140b017d9f_446_loadLibrary) HXLINE( 446) promise->error(((HX_("There is no asset library with an ID of \"",8b,06,e2,9a) + id) + HX_("\"",22,00,00,00))); } HX_END_LOCAL_FUNC1((void)) HX_GC_STACKFRAME(&_hx_pos_df5754140b017d9f_395_loadLibrary) HXLINE( 396) ::lime::app::Promise_lime_utils_AssetLibrary promise = ::lime::app::Promise_lime_utils_AssetLibrary_obj::__alloc( HX_CTX ); HXLINE( 399) ::lime::utils::AssetLibrary library = ::lime::utils::Assets_obj::getLibrary(id); HXLINE( 401) if (hx::IsNotNull( library )) { HXLINE( 403) return library->load(); } HXLINE( 406) ::String path = id; HXLINE( 407) ::String rootPath = null(); HXLINE( 409) if (::lime::utils::Assets_obj::libraryPaths->exists(id)) { HXLINE( 411) path = ::lime::utils::Assets_obj::libraryPaths->get_string(id); HXLINE( 412) rootPath = ::lime::utils::Assets_obj::defaultRootPath; } else { HXLINE( 416) if (::StringTools_obj::endsWith(path,HX_(".bundle",30,4a,b8,4e))) { HXLINE( 418) path = (path + HX_("/library.json",2a,a7,07,47)); } HXLINE( 421) path = ::lime::utils::Assets_obj::_hx___cacheBreak(path); } HXLINE( 424) ::lime::utils::AssetManifest_obj::loadFromFile(path,rootPath)->onComplete( ::Dynamic(new _hx_Closure_0(id,promise)))->onError( ::Dynamic(new _hx_Closure_1(id,promise))); HXLINE( 450) return promise->future; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,loadLibrary,return ) ::lime::app::Future Assets_obj::loadText(::String id){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_455_loadText) HXDLIN( 455) return ::lime::utils::Assets_obj::loadAsset(id,HX_("TEXT",ad,94,ba,37),false); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,loadText,return ) void Assets_obj::registerLibrary(::String name, ::lime::utils::AssetLibrary library){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_459_registerLibrary) HXLINE( 460) if (::lime::utils::Assets_obj::libraries->exists(name)) { HXLINE( 462) if (hx::IsEq( ::lime::utils::Assets_obj::libraries->get(name),library )) { HXLINE( 464) return; } else { HXLINE( 468) ::lime::utils::Assets_obj::unloadLibrary(name); } } HXLINE( 472) if (hx::IsNotNull( library )) { HXLINE( 474) library->onChange->add(::lime::utils::Assets_obj::library_onChange_dyn(),null(),null()); } HXLINE( 477) ::lime::utils::Assets_obj::libraries->set(name,library); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,registerLibrary,(void)) void Assets_obj::unloadLibrary(::String name){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_481_unloadLibrary) HXLINE( 483) ::lime::utils::AssetLibrary library = ( ( ::lime::utils::AssetLibrary)(::lime::utils::Assets_obj::libraries->get(name)) ); HXLINE( 485) if (hx::IsNotNull( library )) { HXLINE( 487) ::lime::utils::Assets_obj::cache->clear((name + HX_(":",3a,00,00,00))); HXLINE( 488) library->onChange->remove(::lime::utils::Assets_obj::library_onChange_dyn()); HXLINE( 489) library->unload(); } HXLINE( 492) ::lime::utils::Assets_obj::libraries->remove(name); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,unloadLibrary,(void)) ::String Assets_obj::_hx___cacheBreak(::String path){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_512___cacheBreak) HXDLIN( 512) return path; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,_hx___cacheBreak,return ) ::String Assets_obj::_hx___libraryNotFound(::String name){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_516___libraryNotFound) HXLINE( 517) bool _hx_tmp; HXDLIN( 517) if (hx::IsNotNull( name )) { HXLINE( 517) _hx_tmp = (name == HX_("",00,00,00,00)); } else { HXLINE( 517) _hx_tmp = true; } HXDLIN( 517) if (_hx_tmp) { HXLINE( 519) name = HX_("default",c1,d8,c3,9b); } HXLINE( 522) bool _hx_tmp1; HXDLIN( 522) bool _hx_tmp2; HXDLIN( 522) if (hx::IsNotNull( ::lime::app::Application_obj::current )) { HXLINE( 522) _hx_tmp2 = hx::IsNotNull( ::lime::app::Application_obj::current->_hx___preloader ); } else { HXLINE( 522) _hx_tmp2 = false; } HXDLIN( 522) if (_hx_tmp2) { HXLINE( 522) _hx_tmp1 = !(::lime::app::Application_obj::current->_hx___preloader->complete); } else { HXLINE( 522) _hx_tmp1 = false; } HXDLIN( 522) if (_hx_tmp1) { HXLINE( 524) return ((HX_("There is no asset library named \"",a1,83,5f,51) + name) + HX_("\", or it is not yet preloaded",db,ac,d4,2f)); } else { HXLINE( 528) return ((HX_("There is no asset library named \"",a1,83,5f,51) + name) + HX_("\"",22,00,00,00)); } HXLINE( 522) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,_hx___libraryNotFound,return ) void Assets_obj::library_onChange(){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_534_library_onChange) HXLINE( 535) ::lime::utils::Assets_obj::cache->clear(null()); HXLINE( 536) ::lime::utils::Assets_obj::onChange->dispatch(); } STATIC_HX_DEFINE_DYNAMIC_FUNC0(Assets_obj,library_onChange,(void)) Assets_obj::Assets_obj() { } bool Assets_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"list") ) { outValue = list_dyn(); return true; } break; case 5: if (HX_FIELD_EQ(inName,"cache") ) { outValue = ( cache ); return true; } break; case 6: if (HX_FIELD_EQ(inName,"exists") ) { outValue = exists_dyn(); return true; } break; case 7: if (HX_FIELD_EQ(inName,"getFont") ) { outValue = getFont_dyn(); return true; } if (HX_FIELD_EQ(inName,"getPath") ) { outValue = getPath_dyn(); return true; } if (HX_FIELD_EQ(inName,"getText") ) { outValue = getText_dyn(); return true; } if (HX_FIELD_EQ(inName,"isLocal") ) { outValue = isLocal_dyn(); return true; } break; case 8: if (HX_FIELD_EQ(inName,"onChange") ) { outValue = ( onChange ); return true; } if (HX_FIELD_EQ(inName,"getAsset") ) { outValue = getAsset_dyn(); return true; } if (HX_FIELD_EQ(inName,"getBytes") ) { outValue = getBytes_dyn(); return true; } if (HX_FIELD_EQ(inName,"getImage") ) { outValue = getImage_dyn(); return true; } if (HX_FIELD_EQ(inName,"loadFont") ) { outValue = loadFont_dyn(); return true; } if (HX_FIELD_EQ(inName,"loadText") ) { outValue = loadText_dyn(); return true; } break; case 9: if (HX_FIELD_EQ(inName,"libraries") ) { outValue = ( libraries ); return true; } if (HX_FIELD_EQ(inName,"loadAsset") ) { outValue = loadAsset_dyn(); return true; } if (HX_FIELD_EQ(inName,"loadBytes") ) { outValue = loadBytes_dyn(); return true; } if (HX_FIELD_EQ(inName,"loadImage") ) { outValue = loadImage_dyn(); return true; } break; case 10: if (HX_FIELD_EQ(inName,"getLibrary") ) { outValue = getLibrary_dyn(); return true; } if (HX_FIELD_EQ(inName,"hasLibrary") ) { outValue = hasLibrary_dyn(); return true; } break; case 11: if (HX_FIELD_EQ(inName,"loadLibrary") ) { outValue = loadLibrary_dyn(); return true; } break; case 12: if (HX_FIELD_EQ(inName,"libraryPaths") ) { outValue = ( libraryPaths ); return true; } if (HX_FIELD_EQ(inName,"isValidAudio") ) { outValue = isValidAudio_dyn(); return true; } if (HX_FIELD_EQ(inName,"isValidImage") ) { outValue = isValidImage_dyn(); return true; } if (HX_FIELD_EQ(inName,"__cacheBreak") ) { outValue = _hx___cacheBreak_dyn(); return true; } break; case 13: if (HX_FIELD_EQ(inName,"unloadLibrary") ) { outValue = unloadLibrary_dyn(); return true; } break; case 14: if (HX_FIELD_EQ(inName,"getAudioBuffer") ) { outValue = getAudioBuffer_dyn(); return true; } break; case 15: if (HX_FIELD_EQ(inName,"defaultRootPath") ) { outValue = ( defaultRootPath ); return true; } if (HX_FIELD_EQ(inName,"loadAudioBuffer") ) { outValue = loadAudioBuffer_dyn(); return true; } if (HX_FIELD_EQ(inName,"registerLibrary") ) { outValue = registerLibrary_dyn(); return true; } break; case 16: if (HX_FIELD_EQ(inName,"library_onChange") ) { outValue = library_onChange_dyn(); return true; } break; case 17: if (HX_FIELD_EQ(inName,"__libraryNotFound") ) { outValue = _hx___libraryNotFound_dyn(); return true; } } return false; } bool Assets_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"cache") ) { cache=ioValue.Cast< ::lime::utils::AssetCache >(); return true; } break; case 8: if (HX_FIELD_EQ(inName,"onChange") ) { onChange=ioValue.Cast< ::lime::app::_Event_Void_Void >(); return true; } break; case 9: if (HX_FIELD_EQ(inName,"libraries") ) { libraries=ioValue.Cast< ::haxe::ds::StringMap >(); return true; } break; case 12: if (HX_FIELD_EQ(inName,"libraryPaths") ) { libraryPaths=ioValue.Cast< ::haxe::ds::StringMap >(); return true; } break; case 15: if (HX_FIELD_EQ(inName,"defaultRootPath") ) { defaultRootPath=ioValue.Cast< ::String >(); return true; } } return false; } #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo *Assets_obj_sMemberStorageInfo = 0; static hx::StaticInfo Assets_obj_sStaticStorageInfo[] = { {hx::fsObject /* ::lime::utils::AssetCache */ ,(void *) &Assets_obj::cache,HX_("cache",42,9a,14,41)}, {hx::fsObject /* ::lime::app::_Event_Void_Void */ ,(void *) &Assets_obj::onChange,HX_("onChange",ef,87,1f,97)}, {hx::fsString,(void *) &Assets_obj::defaultRootPath,HX_("defaultRootPath",c8,76,96,0a)}, {hx::fsObject /* ::haxe::ds::StringMap */ ,(void *) &Assets_obj::libraries,HX_("libraries",19,50,f8,18)}, {hx::fsObject /* ::haxe::ds::StringMap */ ,(void *) &Assets_obj::libraryPaths,HX_("libraryPaths",33,26,5e,06)}, { hx::fsUnknown, 0, null()} }; #endif static void Assets_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(Assets_obj::cache,"cache"); HX_MARK_MEMBER_NAME(Assets_obj::onChange,"onChange"); HX_MARK_MEMBER_NAME(Assets_obj::defaultRootPath,"defaultRootPath"); HX_MARK_MEMBER_NAME(Assets_obj::libraries,"libraries"); HX_MARK_MEMBER_NAME(Assets_obj::libraryPaths,"libraryPaths"); }; #ifdef HXCPP_VISIT_ALLOCS static void Assets_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(Assets_obj::cache,"cache"); HX_VISIT_MEMBER_NAME(Assets_obj::onChange,"onChange"); HX_VISIT_MEMBER_NAME(Assets_obj::defaultRootPath,"defaultRootPath"); HX_VISIT_MEMBER_NAME(Assets_obj::libraries,"libraries"); HX_VISIT_MEMBER_NAME(Assets_obj::libraryPaths,"libraryPaths"); }; #endif hx::Class Assets_obj::__mClass; static ::String Assets_obj_sStaticFields[] = { HX_("cache",42,9a,14,41), HX_("onChange",ef,87,1f,97), HX_("defaultRootPath",c8,76,96,0a), HX_("libraries",19,50,f8,18), HX_("libraryPaths",33,26,5e,06), HX_("exists",dc,1d,e0,bf), HX_("getAsset",7a,79,10,86), HX_("getAudioBuffer",80,41,e3,26), HX_("getBytes",f5,17,6f,1d), HX_("getFont",85,0d,43,16), HX_("getImage",e5,2e,40,1d), HX_("getLibrary",05,ad,d1,8e), HX_("getPath",5b,95,d4,1c), HX_("getText",63,7c,7c,1f), HX_("hasLibrary",c1,0e,24,ca), HX_("isLocal",21,6d,76,15), HX_("isValidAudio",c4,0a,df,47), HX_("isValidImage",49,b1,c7,dd), HX_("list",5e,1c,b3,47), HX_("loadAsset",ea,b5,70,41), HX_("loadAudioBuffer",f0,71,7c,e3), HX_("loadBytes",65,54,cf,d8), HX_("loadFont",15,2f,60,b4), HX_("loadImage",55,6b,a0,d8), HX_("loadLibrary",75,e5,0d,10), HX_("loadText",f3,9d,99,bd), HX_("registerLibrary",d8,8a,84,f2), HX_("unloadLibrary",bc,5b,48,31), HX_("__cacheBreak",3d,06,38,34), HX_("__libraryNotFound",2a,db,69,c9), HX_("library_onChange",f3,20,14,c8), ::String(null()) }; void Assets_obj::__register() { Assets_obj _hx_dummy; Assets_obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("lime.utils.Assets",39,6e,7e,b0); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &Assets_obj::__GetStatic; __mClass->mSetStaticField = &Assets_obj::__SetStatic; __mClass->mMarkFunc = Assets_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(Assets_obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = hx::TCanCast< Assets_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = Assets_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = Assets_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = Assets_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } void Assets_obj::__boot() { { HX_GC_STACKFRAME(&_hx_pos_df5754140b017d9f_39_boot) HXDLIN( 39) cache = ::lime::utils::AssetCache_obj::__alloc( HX_CTX ); } { HX_GC_STACKFRAME(&_hx_pos_df5754140b017d9f_40_boot) HXDLIN( 40) onChange = ::lime::app::_Event_Void_Void_obj::__alloc( HX_CTX ); } { HX_GC_STACKFRAME(&_hx_pos_df5754140b017d9f_42_boot) HXDLIN( 42) libraries = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); } { HX_GC_STACKFRAME(&_hx_pos_df5754140b017d9f_43_boot) HXDLIN( 43) libraryPaths = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); } } } // end namespace lime } // end namespace utils
46.162712
293
0.683458
arturspon
a0d65a62bac666dc32545eb97211a79dfdb76e4e
120
cpp
C++
basic/assig_array.cpp
RohanKittu/CPP_practice_repo
4dd642cf2b3ba880f40f8dbd2cb5ae062fe6f089
[ "MIT" ]
null
null
null
basic/assig_array.cpp
RohanKittu/CPP_practice_repo
4dd642cf2b3ba880f40f8dbd2cb5ae062fe6f089
[ "MIT" ]
null
null
null
basic/assig_array.cpp
RohanKittu/CPP_practice_repo
4dd642cf2b3ba880f40f8dbd2cb5ae062fe6f089
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int arr[10] = {0}; cout<< arr[9]<<"\n"; return 0; }
10.909091
24
0.533333
RohanKittu
a0d77c396a1199ac137d1980f1a61e1ebec1f188
9,372
cxx
C++
STEER/ESD/AliESDMuonGlobalTrack.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
STEER/ESD/AliESDMuonGlobalTrack.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
STEER/ESD/AliESDMuonGlobalTrack.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //==================================================================================================================================================== // // ESD description of an ALICE muon forward track, combining the information of the Muon Spectrometer and the Muon Forward Tracker // // Contact author: [email protected] // //==================================================================================================================================================== #include "AliESDMuonGlobalTrack.h" #include "AliESDEvent.h" #include "TClonesArray.h" #include "TLorentzVector.h" #include "TMath.h" #include "TDatabasePDG.h" ClassImp(AliESDMuonGlobalTrack) //==================================================================================================================================================== AliESDMuonGlobalTrack::AliESDMuonGlobalTrack(): AliVParticle(), fCharge(0), fMatchTrigger(0), fNMFTClusters(0), fNWrongMFTClustersMC(-1), fMFTClusterPattern(0), fPx(0), fPy(0), fPz(0), fPt(0), fP(0), fEta(0), fRapidity(0), fFirstTrackingPointX(0), fFirstTrackingPointY(0), fFirstTrackingPointZ(0), fXAtVertex(0), fYAtVertex(0), fRAtAbsorberEnd(0), fCovariances(0), fChi2OverNdf(0), fChi2MatchTrigger(0), fLabel(-1), fMuonClusterMap(0), fHitsPatternInTrigCh(0), fHitsPatternInTrigChTrk(0), fLoCircuit(0), fIsConnected(kFALSE), fESDEvent(0) { // Default constructor fProdVertexXYZ[0]=0; fProdVertexXYZ[1]=0; fProdVertexXYZ[2]=0; } //==================================================================================================================================================== AliESDMuonGlobalTrack::AliESDMuonGlobalTrack(Double_t px, Double_t py, Double_t pz): AliVParticle(), fCharge(0), fMatchTrigger(0), fNMFTClusters(0), fNWrongMFTClustersMC(-1), fMFTClusterPattern(0), fPx(0), fPy(0), fPz(0), fPt(0), fP(0), fEta(0), fRapidity(0), fFirstTrackingPointX(0), fFirstTrackingPointY(0), fFirstTrackingPointZ(0), fXAtVertex(0), fYAtVertex(0), fRAtAbsorberEnd(0), fCovariances(0), fChi2OverNdf(0), fChi2MatchTrigger(0), fLabel(-1), fMuonClusterMap(0), fHitsPatternInTrigCh(0), fHitsPatternInTrigChTrk(0), fLoCircuit(0), fIsConnected(kFALSE), fESDEvent(0) { // Constructor with kinematics SetPxPyPz(px, py, pz); fProdVertexXYZ[0]=0; fProdVertexXYZ[1]=0; fProdVertexXYZ[2]=0; } //==================================================================================================================================================== AliESDMuonGlobalTrack::AliESDMuonGlobalTrack(const AliESDMuonGlobalTrack& muonTrack): AliVParticle(muonTrack), fCharge(muonTrack.fCharge), fMatchTrigger(muonTrack.fMatchTrigger), fNMFTClusters(muonTrack.fNMFTClusters), fNWrongMFTClustersMC(muonTrack.fNWrongMFTClustersMC), fMFTClusterPattern(muonTrack.fMFTClusterPattern), fPx(muonTrack.fPx), fPy(muonTrack.fPy), fPz(muonTrack.fPz), fPt(muonTrack.fPt), fP(muonTrack.fP), fEta(muonTrack.fEta), fRapidity(muonTrack.fRapidity), fFirstTrackingPointX(muonTrack.fFirstTrackingPointX), fFirstTrackingPointY(muonTrack.fFirstTrackingPointY), fFirstTrackingPointZ(muonTrack.fFirstTrackingPointZ), fXAtVertex(muonTrack.fXAtVertex), fYAtVertex(muonTrack.fYAtVertex), fRAtAbsorberEnd(muonTrack.fRAtAbsorberEnd), fCovariances(0), fChi2OverNdf(muonTrack.fChi2OverNdf), fChi2MatchTrigger(muonTrack.fChi2MatchTrigger), fLabel(muonTrack.fLabel), fMuonClusterMap(muonTrack.fMuonClusterMap), fHitsPatternInTrigCh(muonTrack.fHitsPatternInTrigCh), fHitsPatternInTrigChTrk(muonTrack.fHitsPatternInTrigChTrk), fLoCircuit(muonTrack.fLoCircuit), fIsConnected(muonTrack.fIsConnected), fESDEvent(muonTrack.fESDEvent) { // Copy constructor fProdVertexXYZ[0]=muonTrack.fProdVertexXYZ[0]; fProdVertexXYZ[1]=muonTrack.fProdVertexXYZ[1]; fProdVertexXYZ[2]=muonTrack.fProdVertexXYZ[2]; if (muonTrack.fCovariances) fCovariances = new TMatrixD(*(muonTrack.fCovariances)); } //==================================================================================================================================================== AliESDMuonGlobalTrack& AliESDMuonGlobalTrack::operator=(const AliESDMuonGlobalTrack& muonTrack) { // Assignment operator if (this == &muonTrack) return *this; // Base class assignement AliVParticle::operator=(muonTrack); fCharge = muonTrack.fCharge; fMatchTrigger = muonTrack.fMatchTrigger; fNMFTClusters = muonTrack.fNMFTClusters; fNWrongMFTClustersMC = muonTrack.fNWrongMFTClustersMC; fMFTClusterPattern = muonTrack.fMFTClusterPattern; fPx = muonTrack.fPx; fPy = muonTrack.fPy; fPz = muonTrack.fPz; fPt = muonTrack.fPt; fP = muonTrack.fP; fEta = muonTrack.fEta; fRapidity = muonTrack.fRapidity; fFirstTrackingPointX = muonTrack.fFirstTrackingPointX; fFirstTrackingPointY = muonTrack.fFirstTrackingPointY; fFirstTrackingPointZ = muonTrack.fFirstTrackingPointZ; fXAtVertex = muonTrack.fXAtVertex; fYAtVertex = muonTrack.fYAtVertex; fRAtAbsorberEnd = muonTrack.fRAtAbsorberEnd; fChi2OverNdf = muonTrack.fChi2OverNdf; fChi2MatchTrigger = muonTrack.fChi2MatchTrigger; fLabel = muonTrack.fLabel; fMuonClusterMap = muonTrack.fMuonClusterMap; fHitsPatternInTrigCh = muonTrack.fHitsPatternInTrigCh; fHitsPatternInTrigChTrk = muonTrack.fHitsPatternInTrigChTrk; fLoCircuit = muonTrack.fLoCircuit; fIsConnected = muonTrack.fIsConnected; fESDEvent = muonTrack.fESDEvent; fProdVertexXYZ[0]=muonTrack.fProdVertexXYZ[0]; fProdVertexXYZ[1]=muonTrack.fProdVertexXYZ[1]; fProdVertexXYZ[2]=muonTrack.fProdVertexXYZ[2]; if (muonTrack.fCovariances) { if (fCovariances) *fCovariances = *(muonTrack.fCovariances); else fCovariances = new TMatrixD(*(muonTrack.fCovariances)); } else { delete fCovariances; fCovariances = 0x0; } return *this; } //==================================================================================================================================================== void AliESDMuonGlobalTrack::Copy(TObject &obj) const { // This overwrites the virtual TObject::Copy() // to allow run time copying without casting // in AliESDEvent if (this==&obj) return; AliESDMuonGlobalTrack *robj = dynamic_cast<AliESDMuonGlobalTrack*>(&obj); if (!robj) return; // not an AliESDMuonGlobalTrack *robj = *this; } //==================================================================================================================================================== void AliESDMuonGlobalTrack::SetPxPyPz(Double_t px, Double_t py, Double_t pz) { Double_t mMu = TDatabasePDG::Instance()->GetParticle("mu-")->Mass(); Double_t eMu = TMath::Sqrt(mMu*mMu + px*px + py*py + pz*pz); TLorentzVector kinem(px, py, pz, eMu); fPx = kinem.Px(); fPy = kinem.Py(); fPz = kinem.Pz(); fP = kinem.P(); fPt = kinem.Pt(); fEta = kinem.Eta(); fRapidity = kinem.Rapidity(); } //==================================================================================================================================================== const TMatrixD& AliESDMuonGlobalTrack::GetCovariances() const { // Return the covariance matrix (create it before if needed) if (!fCovariances) { fCovariances = new TMatrixD(5,5); fCovariances->Zero(); } return *fCovariances; } //==================================================================================================================================================== void AliESDMuonGlobalTrack::SetCovariances(const TMatrixD& covariances) { // Set the covariance matrix if (fCovariances) *fCovariances = covariances; else fCovariances = new TMatrixD(covariances); } //====================================================================================================================================================
33.471429
150
0.55303
AllaMaevskaya
a0d8f38580b717c44c24b17cf5b2010a482272bb
2,267
cpp
C++
src/events/PusherEventListener.cpp
BlockChain-Station/enjin-cpp-sdk
3af1cd001d7e660787bbfb2e2414a96f5a95a228
[ "Apache-2.0" ]
12
2021-09-28T14:37:22.000Z
2022-03-04T17:54:11.000Z
src/events/PusherEventListener.cpp
BlockChain-Station/enjin-cpp-sdk
3af1cd001d7e660787bbfb2e2414a96f5a95a228
[ "Apache-2.0" ]
null
null
null
src/events/PusherEventListener.cpp
BlockChain-Station/enjin-cpp-sdk
3af1cd001d7e660787bbfb2e2414a96f5a95a228
[ "Apache-2.0" ]
8
2021-11-05T18:56:55.000Z
2022-01-10T11:14:24.000Z
/* Copyright 2021 Enjin Pte. Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "PusherEventListener.hpp" #include "EventTypeDef.hpp" #include <sstream> namespace enjin::sdk::events { PusherEventListener::PusherEventListener(PusherEventService* service) : service(service) { } void PusherEventListener::on_event(const pusher::PusherEvent& event) { const std::string& key = event.get_event_name().value_or(""); const std::string& channel = event.get_channel_name().value_or(""); const std::string& message = event.get_data().value_or(""); auto listeners = service->get_listeners(); auto logger = service->get_logger_provider(); // Log event received if (logger != nullptr) { std::stringstream ss; ss << "Received event " << key << " on channel " << channel << " with results " << message; logger->log(utils::LogLevel::INFO, ss.str()); } if (listeners.empty()) { if (logger != nullptr) { logger->log(utils::LogLevel::INFO, "No registered listener when event was received"); } return; } EventTypeDef def = EventTypeDef::get_from_key(key); if (def.get_type() == models::EventType::UNKNOWN) { if (logger != nullptr) { std::stringstream ss; ss << "Unknown event type for key " << def.get_key(); logger->log(utils::LogLevel::WARN, ss.str()); } return; } models::NotificationEvent notification_event(def.get_type(), channel, message); for (const auto& registration : listeners) { if (registration.get_matcher()(notification_event.get_type())) { registration.get_listener().notification_received(notification_event); } } } }
32.385714
99
0.659462
BlockChain-Station
a0da67996eacef201090cf59e4c6ac93ace5b7c4
7,297
cpp
C++
code/edmond_blossom.cpp
raynoldng/icpc_notebook
aef047bb441998411a1f89078634c93a6fa5b5c1
[ "MIT" ]
1
2021-08-10T15:08:35.000Z
2021-08-10T15:08:35.000Z
code/edmond_blossom.cpp
raynoldng/icpc_notebook
aef047bb441998411a1f89078634c93a6fa5b5c1
[ "MIT" ]
null
null
null
code/edmond_blossom.cpp
raynoldng/icpc_notebook
aef047bb441998411a1f89078634c93a6fa5b5c1
[ "MIT" ]
1
2020-10-29T01:38:59.000Z
2020-10-29T01:38:59.000Z
#include <algorithm> #include <iostream> #include <queue> #include <vector> class edmond_blossom { private: std::vector<std::vector<int>> adj_list; std::vector<int> match; std::vector<int> parent; std::vector<int> blossom_root; std::vector<bool> in_queue; std::vector<bool> in_blossom; std::queue<int> process_queue; int num_v; /// Find the lowest common ancestor between u and v. /// The specified root represents an upper bound. int get_lca(int root, int u, int v) { std::vector<bool> in_path(num_v, false); for (u = blossom_root[u]; ; u = blossom_root[parent[match[u]]]) { in_path[u] = true; if (u == root) { break; } } for (v = blossom_root[v]; ; v = blossom_root[parent[match[v]]]) { if (in_path[v]) { return v; } } } /// Mark the vertices between u and the specified lowest /// common ancestor for contraction where necessary. void mark_blossom(int lca, int u) { while (blossom_root[u] != lca) { int v = match[u]; in_blossom[blossom_root[u]] = true; in_blossom[blossom_root[v]] = true; u = parent[v]; if (blossom_root[u] != lca) { parent[u] = v; } } } /// Contract the blossom that is formed after processing /// the edge u-v. void contract_blossom(int source, int u, int v) { int lca = get_lca(source, u, v); std::fill(in_blossom.begin(), in_blossom.end(), false); mark_blossom(lca, u); mark_blossom(lca, v); if (blossom_root[u] != lca) { parent[u] = v; } if (blossom_root[v] != lca) { parent[v] = u; } for (int i = 0; i < num_v; ++i) { if (in_blossom[blossom_root[i]]) { blossom_root[i] = lca; if (!in_queue[i]) { process_queue.push(i); in_queue[i] = true; } } } } /// Return the vertex at the end of an augmenting path /// starting at the specified source, or -1 if none exist. int find_augmenting_path(int source) { for (int i = 0; i < num_v; ++i) { in_queue[i] = false; parent[i] = -1; blossom_root[i] = i; } // Empty the queue process_queue = std::queue<int>(); process_queue.push(source); in_queue[source] = true; while (!process_queue.empty()) { int u = process_queue.front(); process_queue.pop(); for (int v : adj_list[u]) { if (blossom_root[u] != blossom_root[v] && match[u] != v) { // Process if // + u-v is not an edge in the matching // && u and v are not in the same blossom (yet) if (v == source || (match[v] != -1 && parent[match[v]] != -1)) { // Contract a blossom if // + v is the source // || v is matched and v's match has a parent. // // The fact that parents are assigned to vertices // with odd distances from the source is used to // check if a cycle is odd or even. u is always an // even distance away from the source, so if v's // match is assigned a parent, you have an odd cycle. contract_blossom(source, u, v); } else if (parent[v] == -1) { parent[v] = u; if (match[v] == -1) { // v is unmatched; augmenting path found return v; } else { // Enqueue v's match. int w = match[v]; if (!in_queue[w]) { process_queue.push(w); in_queue[w] = true; } } } } } } return -1; } /// Augment the path that ends with the specified vertex /// using the parent and match fields. Returns the increase /// in the number of matchings. (i.e. 1 if the path is valid, /// 0 otherwise) int augment_path(int end) { int u = end; while (u != -1) { // Currently w===v----u int v = parent[u]; int w = match[v]; // Change to w---v===u match[v] = u; match[u] = v; u = w; } // Return 1 if the augmenting path is valid return end == -1 ? 0 : 1; } public: edmond_blossom(int v) : adj_list(v), match(v, -1), parent(v), blossom_root(v), in_queue(v), in_blossom(v), num_v(v) {} /// Add a bidirectional edge from u to v. void add_edge(int u, int v) { adj_list[u].push_back(v); adj_list[v].push_back(u); } /// Returns the maximum cardinality matching int get_max_matching() { int ans = 0; // Reset std::fill(match.begin(), match.end(), -1); for (int u = 0; u < num_v; ++u) { if (match[u] == -1) { int v = find_augmenting_path(u); if (v != -1) { // An augmenting path exists ans += augment_path(v); } } } return ans; } /// Constructs the maximum cardinality matching std::vector<std::pair<int, int>> construct_matching() { std::vector<std::pair<int, int>> output; std::vector<bool> is_processed(num_v, false); for (int u = 0; u < num_v; ++u) { if (!is_processed[u] && match[u] != -1) { output.emplace_back(u, match[u]); is_processed[u] = true; is_processed[match[u]] = true; } } return output; } }; int main() { /* 10 18 0 1 0 2 1 2 1 3 1 4 3 4 2 4 2 5 4 5 3 6 3 7 4 7 4 8 5 8 5 9 6 7 7 8 8 9 */ std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); int num_vertices; int num_edges; std::cin >> num_vertices >> num_edges; edmond_blossom eb(num_vertices); for (int i = 0; i < num_edges; ++i) { int u, v; std::cin >> u >> v; eb.add_edge(u, v); } std::cout << "Maximum Cardinality: " << eb.get_max_matching() << "\n"; std::vector<std::pair<int, int>> matching = eb.construct_matching(); for (auto& match : matching) { std::cout << match.first << " " << match.second << "\n"; } }
28.282946
85
0.438262
raynoldng
a0dbccc4e62ee5869886e15bc78814c6aa37882b
4,904
cpp
C++
editor/src/formula_editor_window.cpp
huangfeidian/formula_tree
fdb0db2c3e4503055630381e499934118d4a6036
[ "BSD-3-Clause" ]
5
2020-04-10T07:31:11.000Z
2021-11-19T04:41:58.000Z
editor/src/formula_editor_window.cpp
huangfeidian/formula_tree
fdb0db2c3e4503055630381e499934118d4a6036
[ "BSD-3-Clause" ]
null
null
null
editor/src/formula_editor_window.cpp
huangfeidian/formula_tree
fdb0db2c3e4503055630381e499934118d4a6036
[ "BSD-3-Clause" ]
null
null
null
#include <fstream> #include <streambuf> #include <qfiledialog.h> #include <tree_editor/common/dialogs/path_config_dialog.h> #include <tree_editor/common/choice_manager.h> #include <tree_editor/common/graph/tree_instance.h> #include <any_container/decode.h> #include "formula_editor_window.h" #include "formula_nodes.h" using namespace spiritsaway::tree_editor; using namespace spiritsaway::formula_tree::editor; using namespace std; std::string formula_editor_window::new_file_name() { std::string temp = fmt::format("new_formula_tree_{}.json", get_seq()); std::filesystem::path temp_path = data_folder / temp; while (already_open(temp) || std::filesystem::exists(temp_path)) { temp = fmt::format("new_formula_tree_{}.json", get_seq()); temp_path = data_folder / temp; } return temp; } bool formula_editor_window::load_config() { auto config_file_name = "formula_node_config.json"; std::string notify_info; std::string node_desc_path; std::string choice_desc_path; std::string save_path; if (!std::filesystem::exists(std::filesystem::path(config_file_name))) { path_req_desc node_req; node_req.name = "formula node types"; node_req.tips = "file to provide all formula nodes"; node_req.extension = ".json"; path_req_desc choice_req; choice_req.name = "formula named attr"; choice_req.tips = "file to provide named attr"; choice_req.extension = ".json"; path_req_desc save_path_req; save_path_req.name = "data save dir"; save_path_req.tips = "directory to save data files"; save_path_req.extension = ""; std::vector<path_req_desc> path_reqs; path_reqs.push_back(node_req); path_reqs.push_back(choice_req); path_reqs.push_back(save_path_req); auto cur_dialog = new path_config_dialog(path_reqs, config_file_name, this); auto temp_result = cur_dialog->run(); if (!cur_dialog->valid) { QMessageBox::about(this, QString("Error"), QString::fromStdString("invalid formula node config")); return false; } node_desc_path = temp_result[0]; choice_desc_path = temp_result[1]; save_path = temp_result[2]; } else { auto config_json_variant = load_json_file(config_file_name); if (std::holds_alternative<std::string>(config_json_variant)) { auto notify_info = "config file: " + std::get<std::string>(config_json_variant); QMessageBox::about(this, QString("Error"), QString::fromStdString(notify_info)); return false; } auto json_content = std::get<json::object_t>(config_json_variant); std::vector<std::string> temp_result; std::vector<std::string> path_keys = { "formula node types", "formula named attr" , "data save dir" }; for (auto one_key : path_keys) { auto cur_value_iter = json_content.find(one_key); if (cur_value_iter == json_content.end()) { notify_info = "config content should be should has key " + one_key; QMessageBox::about(this, QString("Error"), QString::fromStdString(notify_info)); return false; } if (!cur_value_iter->second.is_string()) { notify_info = "config content should for key " + one_key + " should be str"; QMessageBox::about(this, QString("Error"), QString::fromStdString(notify_info)); return false; } temp_result.push_back(cur_value_iter->second.get<std::string>()); } node_desc_path = temp_result[0]; choice_desc_path = temp_result[1]; save_path = temp_result[2]; } // choice first auto choice_json_variant = load_json_file(choice_desc_path); if (std::holds_alternative<std::string>(choice_json_variant)) { auto notify_info = "chocie file: " + std::get<std::string>(choice_json_variant); QMessageBox::about(this, QString("Error"), QString::fromStdString(notify_info)); return false; } else { choice_manager::instance().load_from_json(std::get<json::object_t>(choice_json_variant)); } //nodes depends on choice auto node_json_variant = load_json_file(node_desc_path); if (std::holds_alternative<std::string>(node_json_variant)) { auto notify_info = "nodes file: " + std::get<std::string>(node_json_variant); QMessageBox::about(this, QString("Error"), QString::fromStdString(notify_info)); return false; } else { node_config_repo::instance().load_config(std::get<json::object_t>(node_json_variant)); } data_folder = save_path; return true; } basic_node* formula_editor_window::create_node_from_desc(const basic_node_desc& cur_desc, basic_node* parent) { auto cur_config = node_config_repo::instance().get_config(cur_desc.type); if (!cur_config) { return nullptr; } auto cur_node = new formula_node(cur_config.value(), dynamic_cast<formula_node*>(parent), cur_desc.idx); if (parent) { parent->add_child(cur_node); } cur_node->color = cur_desc.color; cur_node->_is_collapsed = cur_desc.is_collpased; cur_node->comment = cur_desc.comment; cur_node->refresh_editable_items(); cur_node->set_extra(json(cur_desc.extra)); return cur_node; }
31.235669
109
0.734095
huangfeidian
a0dc0fd8aa4d9131132ebfc7d480bfa0d82fa5ac
2,802
hpp
C++
kernel/include/kernel/kallocators.hpp
F4doraOfDoom/juos
cdec685701c406defc9204dcadf154df9eefc879
[ "MIT" ]
3
2020-12-22T01:24:56.000Z
2021-01-06T11:44:50.000Z
kernel/include/kernel/kallocators.hpp
F4doraOfDoom/juos
cdec685701c406defc9204dcadf154df9eefc879
[ "MIT" ]
null
null
null
kernel/include/kernel/kallocators.hpp
F4doraOfDoom/juos
cdec685701c406defc9204dcadf154df9eefc879
[ "MIT" ]
null
null
null
#ifndef KERNEL_NEW_H_ #define KERNEL_NEW_H_ #include "kdef.h" #include "kuseful.h" #include "klog.h" #include <kernel/mem_operators.hpp> NAMESPACE_BEGIN(kernel) /** * @brief Custome memory allocator, that uses __primitive_heap * as an allocation space. Has no ability to deconstruct an object, * since you cannot deallocate on __primitive heap * More documentation inside of IAllocator (libstdcxx/allocator.hpp) * * @tparam Type - Allocator will alocate this type */ template <typename Type> struct PrimitiveAllocator { static constexpr uint32_t object_size = sizeof(Type); typedef Type value_type; typedef Type& reference; typedef const Type& const_reference; typedef Type* pointer; static pointer allocate(uint32_t n) { return (pointer)kernel::heap::Allocate(n * object_size); } static void construct(pointer p, const_reference v) { *p = Type(v); } static void destroy(pointer p) { p->~Type(); } }; /** * @brief Custome memory allocator, that uses __mapped_heap * as an allocation space. Has the ability to deallocate memory. * More documentation inside of IAllocator (libstdcxx/allocator.hpp) * * @tparam Type - Allocator will alocate this type */ template <typename Type> struct AdvancedAllocator { static constexpr uint32_t object_size = sizeof(Type); typedef Type value_type; typedef Type& reference; typedef const Type& const_reference; typedef Type* pointer; /** * @brief Allocate _n_ objects of size Type * * @param n * @return pointer */ static pointer allocate(uint32_t n) { return new Type[n]; } /** * @brief Deallocate a pointer pointing to _n_ objects of type Type * * @param p * @param n */ static void deallocate(pointer p, size_t n) { delete p; } /** * @brief construct an object of type Type in pointer _p_ with args _v_ * * @param p * @param v */ static void construct(pointer p, const_reference v) { *p = Type(v); } /** * @brief Destroy an object of type Type in pointer _p_ * * @param p */ static void destroy(pointer p) { p->~Type(); } }; NAMESPACE_END(kernel) #endif // KERNEL_NEW_H_
25.243243
79
0.534618
F4doraOfDoom
a0df361c8cca36d2629df1a6e850ae30f244b7b7
1,207
cpp
C++
Piscines/CPP/rush01/srcs/TimeModule.cpp
SpeedFireSho/42-1
5d7ce17910794a28ca44d937651b961feadcff11
[ "MIT" ]
84
2020-10-13T14:50:11.000Z
2022-01-11T11:19:36.000Z
Piscines/CPP/rush01/srcs/TimeModule.cpp
SpeedFireSho/42-1
5d7ce17910794a28ca44d937651b961feadcff11
[ "MIT" ]
null
null
null
Piscines/CPP/rush01/srcs/TimeModule.cpp
SpeedFireSho/42-1
5d7ce17910794a28ca44d937651b961feadcff11
[ "MIT" ]
43
2020-09-10T19:26:37.000Z
2021-12-28T13:53:55.000Z
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* TimeModule.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jaleman <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/07/15 18:52:47 by jaleman #+# #+# */ /* Updated: 2017/07/15 18:52:48 by jaleman ### ########.fr */ /* */ /* ************************************************************************** */ #include "TimeModule.hpp" TimeModule::TimeModule(void) { return ; } TimeModule::TimeModule(const TimeModule &src) { *this = src; return ; } TimeModule::~TimeModule(void) { return ; } TimeModule &TimeModule::operator= (const TimeModule &rhs) { static_cast <void> (rhs); return (*this); }
32.621622
80
0.256835
SpeedFireSho
a0e344ab6d420ded2e24d5db2a21d00614491eb0
124
cpp
C++
cmake/checks/test-cxx_memory_make_unique.cpp
moorwen91/plasma-potd-spotlight
c16417485fb62a1c8854935b8ce73b4cba9e24b4
[ "BSD-2-Clause" ]
104
2019-02-12T20:41:07.000Z
2022-03-07T16:58:47.000Z
cmake/checks/test-cxx_memory_make_unique.cpp
moorwen91/plasma-potd-spotlight
c16417485fb62a1c8854935b8ce73b4cba9e24b4
[ "BSD-2-Clause" ]
9
2019-08-24T03:23:21.000Z
2021-06-06T17:59:07.000Z
{{cookiecutter.project_slug}}/cmake/checks/test-cxx_memory_make_unique.cpp
Aetf/cc-modern-cmake
4421755acf85a30a42f3f48b6d2e1a5130fd3f46
[ "BSD-2-Clause" ]
18
2019-03-04T07:45:41.000Z
2021-09-15T22:13:07.000Z
#include <memory> int main() { std::unique_ptr<int> foo = std::make_unique<int>(42); return ((*foo) == 42) ? 0 : 1; }
13.777778
55
0.572581
moorwen91
a0e520d05a377d17ee332f8422515757b341ecf2
3,198
cpp
C++
src/caffe/layers/cross_perturbation_layer.cpp
chenbinghui1/Hybrid-Attention-based-Decoupled-Metric-Learning
7b1bda334efe0c98c6876548b35a728c3c35676d
[ "MIT" ]
44
2019-04-03T16:51:30.000Z
2022-02-02T15:19:48.000Z
src/caffe/layers/cross_perturbation_layer.cpp
chenbinghui1/Decoupled-Metric-Learning
7b1bda334efe0c98c6876548b35a728c3c35676d
[ "MIT" ]
1
2021-06-01T10:00:00.000Z
2021-06-23T01:46:43.000Z
src/caffe/layers/cross_perturbation_layer.cpp
chenbinghui1/Decoupled-Metric-Learning
7b1bda334efe0c98c6876548b35a728c3c35676d
[ "MIT" ]
8
2019-05-16T05:44:41.000Z
2020-08-19T17:16:28.000Z
//需要设置solver里面iter_size=2 ,第一次前向反向传播为正常输入和正常梯度,并记录反传回来的梯度,第二次前向为原输入+梯度干扰,输入list需要在第一次和第二次的时候保持一样。且根据ICLR18cross gradients 相应的loss也要做修改,此时只修改了BIER loss. #include <vector> #include "caffe/filler.hpp" #include "caffe/layers/cross_perturbation_layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> void CrossPerturbationLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { CHECK_EQ(bottom.size(), 2); CHECK_EQ(bottom[0]->count(), bottom[1]->count()); F_iter_size_ = 0; B_iter_size_ = 0; } template <typename Dtype> void CrossPerturbationLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { top[0]->ReshapeLike(*bottom[0]); top[1]->ReshapeLike(*bottom[1]); temp0_.ReshapeLike(*bottom[0]); temp1_.ReshapeLike(*bottom[1]); } template <typename Dtype> void CrossPerturbationLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { //load cross weights //static int iter_size = 0; vector<Dtype> ems; for(int i = 0; i < this->layer_param_.cross_perturbation_param().ems_size(); i++) { ems.push_back(this->layer_param_.cross_perturbation_param().ems(i)); } //forward propagation if(F_iter_size_ == 0) { for(int i = 0; i < bottom.size(); i++) caffe_copy(bottom[i]->count(), bottom[i]->cpu_data(), top[i]->mutable_cpu_data()); F_iter_size_ = 1; } else {//fi + ems[i]*gradient(fj) caffe_cpu_axpby(bottom[0]->count(), Dtype(1), bottom[0]->cpu_data(), Dtype(0), top[0]->mutable_cpu_data()); caffe_cpu_axpby(bottom[1]->count(), Dtype(ems[0]), temp1_.cpu_data(), Dtype(1), top[0]->mutable_cpu_data()); caffe_cpu_axpby(bottom[1]->count(), Dtype(1), bottom[1]->cpu_data(), Dtype(0), top[1]->mutable_cpu_data()); caffe_cpu_axpby(bottom[0]->count(), Dtype(ems[1]), temp0_.cpu_data(), Dtype(1), top[1]->mutable_cpu_data()); F_iter_size_ = 0; } } template <typename Dtype> void CrossPerturbationLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { //static int iter_size = 0; if(B_iter_size_ == 0) { for(int i = 0; i < bottom.size(); i++) { //propagate gradients caffe_copy(bottom[i]->count(), top[i]->cpu_diff(), bottom[i]->mutable_cpu_diff()); } //store gradients caffe_copy(bottom[0]->count(), top[0]->cpu_diff(), temp0_.mutable_cpu_data()); caffe_copy(bottom[1]->count(), top[1]->cpu_diff(), temp1_.mutable_cpu_data()); B_iter_size_ = 1; } else { for(int i = 0; i < bottom.size(); i++) { //propagate gradients caffe_set(bottom[i]->count(), Dtype(0), bottom[i]->mutable_cpu_diff()); } B_iter_size_ = 0; } } #ifdef CPU_ONLY STUB_GPU(CrossPerturbationLayer); #endif INSTANTIATE_CLASS(CrossPerturbationLayer); REGISTER_LAYER_CLASS(CrossPerturbation); } // namespace caffe
34.387097
151
0.636023
chenbinghui1
a0e8b87316eb686bb2997d40a1066a92e5746a5f
1,308
hpp
C++
libs/boost_1_72_0/boost/fusion/view/nview/detail/value_of_impl.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/fusion/view/nview/detail/value_of_impl.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/fusion/view/nview/detail/value_of_impl.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
/*============================================================================= Copyright (c) 2009 Hartmut Kaiser Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(BOOST_FUSION_VALUE_OF_PRIOR_IMPL_SEP_24_2009_0158PM) #define BOOST_FUSION_VALUE_OF_PRIOR_IMPL_SEP_24_2009_0158PM #include <boost/fusion/container/vector.hpp> #include <boost/fusion/iterator/deref.hpp> #include <boost/fusion/support/config.hpp> namespace boost { namespace fusion { struct nview_iterator_tag; template <typename Sequence, typename Pos> struct nview_iterator; namespace extension { template <typename Tag> struct value_of_impl; template <> struct value_of_impl<nview_iterator_tag> { template <typename Iterator> struct apply { typedef typename Iterator::first_type first_type; typedef typename Iterator::sequence_type sequence_type; typedef typename result_of::deref<first_type>::type index; typedef typename result_of::at<typename sequence_type::sequence_type, index>::type type; }; }; } // namespace extension } // namespace fusion } // namespace boost #endif
32.7
80
0.66896
henrywarhurst
a0f0c8e40c3982bdc323228e9603e3da357f8ad7
612
cpp
C++
ianlmk/cs161b/zybooks/11.4.3.cpp
ianlmk/cs161
7a50740d1642ca0111a6d0d076b600744552a066
[ "MIT" ]
null
null
null
ianlmk/cs161b/zybooks/11.4.3.cpp
ianlmk/cs161
7a50740d1642ca0111a6d0d076b600744552a066
[ "MIT" ]
1
2022-03-25T18:34:47.000Z
2022-03-25T18:35:23.000Z
ianlmk/cs161b/zybooks/11.4.3.cpp
ianlmk/cs161
7a50740d1642ca0111a6d0d076b600744552a066
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { const int SCORES_SIZE = 4; int bonusScores[SCORES_SIZE]; int i; for (i = 0; i < SCORES_SIZE; ++i) { cin >> bonusScores[i]; } // Set all indexed values to itself plus the next value except for the last element for (i = 0; i < SCORES_SIZE; ++i) { if (i == SCORES_SIZE - 1) { bonusScores[i] = bonusScores[i]; } else { bonusScores[i] = bonusScores[i] + bonusScores[i + 1]; } } for (i = 0; i < SCORES_SIZE; ++i) { cout << bonusScores[i] << " "; } cout << endl; return 0; }
20.4
88
0.545752
ianlmk
a0f12cf3aa1939bf73da706bf2ef14fdeb22c67e
411
cpp
C++
codeforces/gym/2018 IME Tryouts/b.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
4
2020-10-05T19:24:10.000Z
2021-07-15T00:45:43.000Z
codeforces/gym/2018 IME Tryouts/b.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
codeforces/gym/2018 IME Tryouts/b.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
#include <cpplib/stdinc.hpp> int32_t main(){ desync(); int acc = 0; char last = 0; string s; cin >> s; for(char c:s){ if(c != last) acc = 0; acc++; if(acc == 3){ cout << (c == 'C'? 'P' : 'T'); acc = 0; } else cout << (c == 'C'? 'B' : 'D'); last = c; } cout << endl; return 0; }
17.125
42
0.3382
tysm