hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
0adee71f3a849f120f6ededb76610168b8eb4c0c
767
cpp
C++
mcrouter/lib/RendezvousHashHelper.cpp
alynx282/mcrouter
b16af1a119eee775b051d323cb885b73fdf75757
[ "MIT" ]
null
null
null
mcrouter/lib/RendezvousHashHelper.cpp
alynx282/mcrouter
b16af1a119eee775b051d323cb885b73fdf75757
[ "MIT" ]
null
null
null
mcrouter/lib/RendezvousHashHelper.cpp
alynx282/mcrouter
b16af1a119eee775b051d323cb885b73fdf75757
[ "MIT" ]
null
null
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "mcrouter/lib/RendezvousHashHelper.h" #include "mcrouter/lib/fbi/hash.h" namespace facebook { namespace memcache { RendezvousIterator::RendezvousIterator(std::vector<ScoreAndIndex> scores) : queue_{std::less<ScoreAndIndex>(), std::move(scores)} {} RendezvousIterator& RendezvousIterator::operator++() { if (!queue_.empty()) { queue_.pop(); } return *this; } uint64_t RendezvousIterator::keyHash(folly::StringPiece key) { return murmur_hash_64A(key.data(), key.size(), kRendezvousExtraHashSeed); } } // namespace memcache } // namespace facebook
24.741935
75
0.728814
alynx282
0ae535e7b5ed38fa5e2a5df7a9d4e05934395ad7
3,612
cc
C++
mace/runtimes/runtime_registry.cc
gasgallo/mace
96b4089e2323d9af119f9f2eda51976ac19ae6c4
[ "Apache-2.0" ]
null
null
null
mace/runtimes/runtime_registry.cc
gasgallo/mace
96b4089e2323d9af119f9f2eda51976ac19ae6c4
[ "Apache-2.0" ]
null
null
null
mace/runtimes/runtime_registry.cc
gasgallo/mace
96b4089e2323d9af119f9f2eda51976ac19ae6c4
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The MACE Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "mace/core/runtime/runtime_registry.h" #ifdef MACE_ENABLE_OPENCL #include "mace/runtimes/opencl/core/opencl_executor.h" #endif // MACE_ENABLE_OPENCL #ifdef MACE_ENABLE_RPCMEM #include "mace/core/memory/rpcmem/rpcmem.h" #endif // MACE_ENABLE_RPCMEM namespace mace { extern void RegisterCpuRefRuntime(RuntimeRegistry *runtime_registry); #ifdef MACE_ENABLE_RPCMEM extern void RegisterCpuIonRuntime(RuntimeRegistry *runtime_registry); #endif // MACE_ENABLE_RPCMEM #ifdef MACE_ENABLE_OPENCL extern void RegisterOpenclRefRuntime(RuntimeRegistry *runtime_registry); #ifdef MACE_ENABLE_RPCMEM extern void RegisterOpenclQcIonRuntime(RuntimeRegistry *runtime_registry); #endif // MACE_ENABLE_RPCMEM #endif // MACE_ENABLE_OPENCL #ifdef MACE_ENABLE_HEXAGON extern void RegisterHexagonDspRuntime(RuntimeRegistry *runtime_registry); #endif // MACE_ENABLE_HEXAGON #ifdef MACE_ENABLE_HTA extern void RegisterHexagonHtaRuntime(RuntimeRegistry *runtime_registry); #ifdef MACE_ENABLE_OPENCL extern void RegisterHexagonHtaOpenclRuntime(RuntimeRegistry *runtime_registry); #endif // MACE_ENABLE_OPENCL #endif // MACE_ENABLE_HTA #ifdef MACE_ENABLE_APU extern void RegisterApuRuntime(RuntimeRegistry *runtime_registry); #endif // MACE_ENABLE_APU void RegisterAllRuntimes(RuntimeRegistry *runtime_registry) { RegisterCpuRefRuntime(runtime_registry); #ifdef MACE_ENABLE_RPCMEM RegisterCpuIonRuntime(runtime_registry); #endif // MACE_ENABLE_RPCMEM #ifdef MACE_ENABLE_OPENCL RegisterOpenclRefRuntime(runtime_registry); #ifdef MACE_ENABLE_RPCMEM RegisterOpenclQcIonRuntime(runtime_registry); #endif // MACE_ENABLE_RPCMEM #endif // MACE_ENABLE_OPENCL #ifdef MACE_ENABLE_HEXAGON RegisterHexagonDspRuntime(runtime_registry); #endif // MACE_ENABLE_HEXAGON #ifdef MACE_ENABLE_HTA RegisterHexagonHtaRuntime(runtime_registry); #ifdef MACE_ENABLE_OPENCL RegisterHexagonHtaOpenclRuntime(runtime_registry); #endif // MACE_ENABLE_OPENCL #endif // MACE_ENABLE_HTA #ifdef MACE_ENABLE_APU RegisterApuRuntime(runtime_registry); #endif // MACE_ENABLE_APU } std::unique_ptr<Runtime> SmartCreateRuntime(RuntimeRegistry *runtime_registry, const RuntimeType runtime_type, RuntimeContext *runtime_context) { RuntimeSubType sub_type = RuntimeSubType::RT_SUB_REF; #if defined(MACE_ENABLE_RPCMEM) && defined(MACE_ENABLE_OPENCL) if (Rpcmem::IsRpcmemSupported()) { if (runtime_type == RuntimeType::RT_OPENCL) { auto ion_type = OpenclExecutor::FindCurDeviceIonType(); if (ion_type == IONType::QUALCOMM_ION) { sub_type = RuntimeSubType::RT_SUB_QC_ION; } } else if (runtime_type == RuntimeType::RT_HTA) { sub_type = RuntimeSubType::RT_SUB_WITH_OPENCL; } } #endif // MACE_ENABLE_RPCMEM && MACE_ENABLE_OPENCL return runtime_registry->CreateRuntime(runtime_type, sub_type, runtime_context); } } // namespace mace
33.444444
79
0.772702
gasgallo
0aed11e435e20b217dc1286726ca4ebc3868c213
12,773
hpp
C++
includes/zab/descriptor_notifications.hpp
HungMingWu/zab
9e9fd78d192b4d037a6edbbd4c1474bd6e01feaf
[ "MIT" ]
null
null
null
includes/zab/descriptor_notifications.hpp
HungMingWu/zab
9e9fd78d192b4d037a6edbbd4c1474bd6e01feaf
[ "MIT" ]
null
null
null
includes/zab/descriptor_notifications.hpp
HungMingWu/zab
9e9fd78d192b4d037a6edbbd4c1474bd6e01feaf
[ "MIT" ]
null
null
null
/* * MMM"""AMV db `7MM"""Yp, * M' AMV ;MM: MM Yb * ' AMV ,V^MM. MM dP * AMV ,M `MM MM"""bg. * AMV , AbmmmqMA MM `Y * AMV ,M A' VML MM ,9 * AMVmmmmMM .AMA. .AMMA..JMMmmmd9 * * * MIT License * * Copyright (c) 2021 Donald-Rupin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. * * @file descriptor_notifications.hpp * */ #ifndef ZAB_DESCRIPTOR_NOTIFCATIONS_HPP_ #define ZAB_DESCRIPTOR_NOTIFCATIONS_HPP_ #include <algorithm> #include <deque> #include <iostream> #include <mutex> #include <optional> #include <sys/epoll.h> #include <thread> #include "zab/event.hpp" #include "zab/strong_types.hpp" namespace zab { class engine; /** * @brief This class implements an asynchronous `epoll` based descriptor notification * service. */ class descriptor_notification { /** * @brief This class is a for a descriptor, related information and the callback * information. */ class descriptor { friend class descriptor_notification; public: /** * @brief Construct in an empty state. */ descriptor(); /** * @brief Destroys the object. This is a non-owning object. */ ~descriptor() = default; /** * @brief Cannot be copied. * * @param[in] <unnamed> */ descriptor(const descriptor&) = delete; /** * @brief The flags set by the service. * * @return The flags. */ inline int return_flags() const noexcept { return return_flags_; } /** * @brief Sets the coroutine handle. * * @param[in] _handle The coroutine handle. */ void set_handle(std::coroutine_handle<> _handle) noexcept; /** * @brief Sets the timeout. * * @param[in] _timeout The timeout. */ inline void set_timeout(int32_t _timeout) noexcept { timeout_ = _timeout; } private: std::atomic<void*> awaiter_; int return_flags_ = 0; int32_t timeout_ = -1; thread_t thread_; std::atomic<bool> dead_; }; public: /** * @brief Constructs a new instance that will register to this engine. * * @param _engine The engine. * */ descriptor_notification(engine* _engine); /** * @brief Destroys the object and cleans up the resources. */ ~descriptor_notification(); /** * @brief Convince types for the epoll macro equivalent. */ enum NoticationType { kError = EPOLLERR, kRead = EPOLLIN, kWrite = EPOLLOUT, kException = EPOLLPRI, kClosed = EPOLLRDHUP, kDestruction, }; /** * @brief This class describes a descriptor waiter used of co_waiting descriptor * events. * */ class descriptor_waiter { public: /** * @brief Constructs a new instance in an empty state. */ descriptor_waiter(); /** * @brief Constructs a new instance registered to the * descriptor_notification service and subscribed to _fd.. * * @param _self The self * @param _desc The description * @param[in] _fd The file descriptor. */ descriptor_waiter(descriptor_notification* _self, descriptor* _desc, int _fd); /** * @brief Cannot copy this object. * * @param[in] _copy The copy */ descriptor_waiter(const descriptor_waiter& _copy) = delete; /** * @brief Constructs a new instance leave the old instance in an empty * state. * * @param _move The move */ descriptor_waiter(descriptor_waiter&& _move); /** * @brief Swap two descriptor_waiter's. * * @param _first The first * @param _second The second */ friend void swap(descriptor_waiter& _first, descriptor_waiter& _second) noexcept; /** * @brief Destroys the object and unsubscribes the file descriptor from the * notification service. */ ~descriptor_waiter(); /** * @brief Move assignment operator. * * @param _move The descriptor_waiter to move * * @return The result of the assignment */ descriptor_waiter& operator=(descriptor_waiter&& _move); /** * @brief The Awaitable Proxy used to co_await for events. */ struct await_proxy { /** * @brief Suspend an wait for the service to deliver an event. * * @param[in] _awaiter The coroutine handle. */ void await_suspend(std::coroutine_handle<> _awaiter) noexcept; /** * @brief Always suspend. * * @return false; */ bool await_ready() const noexcept { return false; } /** * @brief Return the return flags on resumption. * * @return The return flags. */ int await_resume() const noexcept { return this_->return_flags(); }; descriptor_waiter* this_; }; /** * @brief Sets the flags to watch for. * * @param[in] _flags The flags. */ inline void set_flags(int _flags) noexcept { flags_ = _flags; } /** * @brief Returns flags set by the service. * * @return The return flags. */ inline int return_flags() const noexcept { return desc_->return_flags(); } /** * @brief Gets the file descriptor. * * @return The file descriptor. */ inline int file_descriptor() const noexcept { return fd_; } /** * @brief Sets the timeout. * * @param[in] _timeout The timeout */ inline void set_timeout(int32_t _timeout) noexcept { timeout_ = _timeout; } /** * @brief Wakes any co_waiting instances that have finished suspending. */ void wake_up() noexcept; /** * @brief Co_await conversion operator. * * @return Returns an Await Proxy. */ await_proxy operator co_await() noexcept { return await_proxy{.this_ = this}; } private: friend struct await_proxy; descriptor_notification* self_; descriptor* desc_; int flags_; int fd_; int32_t timeout_ = -1; }; /** * @brief Subscribe to events on a given file descriptor. * * @details This function is not thread safe and can only be called once at a time. * Multiple concurrent call will most likely fail, but is dependent on the * epoll implementation. * * @param[in] _fd The file descriptor to subscribe to. * * @return A descriptor_waiter on success, otherwise nullopt. */ [[nodiscard]] std::optional<descriptor_waiter> subscribe(int _fd); /** * @brief Runs the internal service thread. */ void run(); /** * @brief Stops the internal service thread. */ void stop(); private: /** * @brief Notify a given descriptor with flags. * * @param _awaiting The awaiting descriptor. * @param[in] _flags The flags to set. */ void notify(descriptor* _awaiting, int _flags); std::jthread notification_loop_; std::unique_ptr<std::mutex> awaiting_mtx_; std::deque<std::unique_ptr<descriptor>> awaiting_; engine* engine_; int poll_descriptor_; int event_fd_; }; } // namespace zab #endif /* ZAB_DESCRIPTOR_NOTIFCATIONS_HPP_ */
34.152406
100
0.40429
HungMingWu
0aedc313682514aaa708a611709f23a9d83b4434
2,538
cpp
C++
src/Micro/Goals/AvoidNukeGoal.cpp
syhw/BroodwarBotQ
71053d943d1bfb4cbf5a687bb015362decd9428c
[ "BSD-3-Clause" ]
10
2015-12-14T16:55:22.000Z
2022-02-04T20:51:38.000Z
src/Micro/Goals/AvoidNukeGoal.cpp
SnippyHolloW/BroodwarBotQ
71053d943d1bfb4cbf5a687bb015362decd9428c
[ "BSD-3-Clause" ]
1
2019-10-22T04:52:28.000Z
2019-10-22T04:52:28.000Z
src/Micro/Goals/AvoidNukeGoal.cpp
SnippyHolloW/BroodwarBotQ
71053d943d1bfb4cbf5a687bb015362decd9428c
[ "BSD-3-Clause" ]
2
2017-06-21T17:24:00.000Z
2017-10-21T14:15:17.000Z
#include <PrecompiledHeader.h> #include "Micro/Goals/AvoidNukeGoal.h" #include "Regions/MapManager.h" using namespace BWAPI; using namespace std; /// Either we have detected the ghost(s) from the start and try and kill them /// Or we have not and we flee the nuke /// We assume that the detected ghost(s) around are responsible for the nuke /// /!\ This goal do not call _unitsGroup.update() /!\/ AvoidNukeGoal::AvoidNukeGoal(Position target) : Goal(100) // highest priority , _nukePos(target) , _detectedGhost(false) { for each (Unit* u in Broodwar->getUnitsInRadius(_nukePos, 12*32)) // 10 tiles for the Ghost upgraded vision... { if (u->getPlayer() == Broodwar->enemy() && u->getType() == UnitTypes::Terran_Ghost && u->isDetected()) _ghostsToKill.push_back(u); } _detectedGhost = !_ghostsToKill.empty(); // TODO change the following BWTA::BaseLocation* home = BWTA::getStartLocation(Broodwar->self()); _safePos = home->getPosition(); if (BWTA::getRegion(TilePosition(_safePos)) == home->getRegion()) { if (!home->getRegion()->getReachableRegions().empty()) _safePos = (*home->getRegion()->getReachableRegions().begin())->getCenter(); else // Island... Broodwar->printf("Nuke on a home island, non implemented"); } _status = GS_IN_PROGRESS; } void AvoidNukeGoal::fleeTheNuke() { _unitsGroup.switchMode(MODE_MOVE); _unitsGroup.move(_safePos); } void AvoidNukeGoal::achieve() { /// Check for the end of the Nuke if (Broodwar->getFrameCount() > 20*24 + _firstFrame) // 20 > 17 seconds for the nuke to fall { _status = GS_ACHIEVED; return; } /// Remove killed ghosts for (list<Unit*>::const_iterator it = _ghostsToKill.begin(); it != _ghostsToKill.end(); ) { if (!(*it)->exists()) // Assume we still detect it (TODO) _ghostsToKill.erase(it++); else ++it; } /// (We could also put potential damages in the damages map?) for each (Unit* u in Broodwar->getUnitsInRadius(_nukePos, 9*32)) // bid all units in 9 build tiles around bidOnUnit(u); if (_detectedGhost) { /// Kill the ghosts if (_ghostsToKill.empty()) { _status = GS_ACHIEVED; return; } else if (Broodwar->getFrameCount() > 12*24 + _firstFrame) { /// To late to try and kill the ghost (14 seconds to drop the Nuke) fleeTheNuke(); } else { for each (pBayesianUnit bu in _unitsGroup.units) bu->attackEnemyUnit(_ghostsToKill.front()); } } else { /// Flee the nuke fleeTheNuke(); } }
28.840909
112
0.661151
syhw
0aef5526f85265f5686d018b1aad5c86e08e5d0f
25,069
cpp
C++
pgadmin/schema/pgIndex.cpp
jcjc79/pgadmin3
be0f94786bf5b8138c9e6ec1b0b295308f8f89b6
[ "OLDAP-2.2.1" ]
5
2019-09-18T08:05:31.000Z
2021-04-26T03:05:52.000Z
pgadmin/schema/pgIndex.cpp
theory/pgadmin3
5eeee31f8c4f42907b1edf1a6984cdee7323ddaa
[ "PostgreSQL" ]
null
null
null
pgadmin/schema/pgIndex.cpp
theory/pgadmin3
5eeee31f8c4f42907b1edf1a6984cdee7323ddaa
[ "PostgreSQL" ]
4
2020-03-04T09:50:13.000Z
2021-02-02T03:28:04.000Z
////////////////////////////////////////////////////////////////////////// // // pgAdmin III - PostgreSQL Tools // // Copyright (C) 2002 - 2013, The pgAdmin Development Team // This software is released under the PostgreSQL Licence // // pgIndex.cpp - Index class // ////////////////////////////////////////////////////////////////////////// // wxWindows headers #include <wx/wx.h> // App headers #include "pgAdmin3.h" #include "frm/frmMain.h" #include "utils/misc.h" #include "utils/pgfeatures.h" #include "schema/pgIndex.h" #include "schema/pgConstraints.h" #include "schema/pgIndexConstraint.h" pgIndexBase::pgIndexBase(pgSchema *newSchema, pgaFactory &factory, const wxString &newName) : pgSchemaObject(newSchema, factory, newName) { showExtendedStatistics = false; } wxString pgIndexBase::GetTranslatedMessage(int kindOfMessage) const { wxString message = wxEmptyString; switch (kindOfMessage) { case RETRIEVINGDETAILS: message = _("Retrieving details on index"); message += wxT(" ") + GetName(); break; case REFRESHINGDETAILS: message = _("Refreshing index"); message += wxT(" ") + GetName(); break; case GRANTWIZARDTITLE: message = _("Privileges for index"); message += wxT(" ") + GetName(); break; case DROPINCLUDINGDEPS: message = wxString::Format(_("Are you sure you wish to drop index \"%s\" including all objects that depend on it?"), GetFullIdentifier().c_str()); break; case DROPEXCLUDINGDEPS: message = wxString::Format(_("Are you sure you wish to drop index \"%s\"?"), GetFullIdentifier().c_str()); break; case DROPCASCADETITLE: message = _("Drop index cascaded?"); break; case DROPTITLE: message = _("Drop index?"); break; case PROPERTIESREPORT: message = _("Index properties report"); message += wxT(" - ") + GetName(); break; case PROPERTIES: message = _("Index properties"); break; case DDLREPORT: message = _("Index DDL report"); message += wxT(" - ") + GetName(); break; case DDL: message = _("Index DDL"); break; case STATISTICSREPORT: message = _("Index statistics report"); message += wxT(" - ") + GetName(); break; case OBJSTATISTICS: message = _("Index statistics"); break; case DEPENDENCIESREPORT: message = _("Index dependencies report"); message += wxT(" - ") + GetName(); break; case DEPENDENCIES: message = _("Index dependencies"); break; case DEPENDENTSREPORT: message = _("Index dependents report"); message += wxT(" - ") + GetName(); break; case DEPENDENTS: message = _("Index dependents"); break; } return message; } bool pgIndexBase::DropObject(wxFrame *frame, ctlTree *browser, bool cascaded) { wxString sql = wxT("DROP INDEX ") + this->GetSchema()->GetQuotedIdentifier() + wxT(".") + this->GetQuotedIdentifier(); if (cascaded) sql += wxT(" CASCADE"); return GetDatabase()->ExecuteVoid(sql); } wxString pgIndexBase::GetCreate() { wxString str; // no functional indexes so far str = wxT("CREATE "); if (GetIsUnique()) str += wxT("UNIQUE "); str += wxT("INDEX "); str += qtIdent(GetName()) + wxT("\n ON ") + GetQuotedSchemaPrefix(GetIdxSchema()) + qtIdent(GetIdxTable()) + wxT("\n USING ") + GetIndexType() + wxT("\n ("); if (GetProcName().IsNull()) str += GetQuotedColumns(); else { str += GetQuotedSchemaPrefix(GetProcNamespace()) + qtIdent(GetProcName()) + wxT("(") + GetQuotedColumns() + wxT(")"); if (!this->GetOperatorClasses().IsNull()) str += wxT(" ") + GetOperatorClasses(); } str += wxT(")"); if (GetConnection()->BackendMinimumVersion(8, 2) && GetFillFactor().Length() > 0) str += wxT("\n WITH (FILLFACTOR=") + GetFillFactor() + wxT(")"); if (GetConnection()->BackendMinimumVersion(8, 0) && tablespace != GetDatabase()->GetDefaultTablespace()) str += wxT("\nTABLESPACE ") + qtIdent(tablespace); AppendIfFilled(str, wxT("\n WHERE "), GetConstraint()); str += wxT(";\n"); if (GetConnection()->BackendMinimumVersion(7, 5)) if (GetIsClustered()) str += wxT("ALTER TABLE ") + GetQuotedSchemaPrefix(GetIdxSchema()) + qtIdent(GetIdxTable()) + wxT(" CLUSTER ON ") + qtIdent(GetName()) + wxT(";\n"); return str; } wxString pgIndexBase::GetSql(ctlTree *browser) { if (sql.IsNull()) { sql = wxT("-- Index: ") + GetQuotedFullIdentifier() + wxT("\n\n") + wxT("-- DROP INDEX ") + GetQuotedFullIdentifier() + wxT(";\n\n") + GetCreate() + GetCommentSql(); } return sql; } void pgIndexBase::ReadColumnDetails() { if (!expandedKids) { expandedKids = true; bool indexconstraint = GetMetaType() == PGM_PRIMARYKEY || GetMetaType() == PGM_UNIQUE || GetMetaType() == PGM_EXCLUDE; // Allocate memory to store column def if (columnCount > 0) columnList.Alloc(columnCount); if (GetConnection()->BackendMinimumVersion(7, 4)) { long i; for (i = 1 ; i <= columnCount ; i++) { if (i > 1) { columns += wxT(", "); quotedColumns += wxT(", "); } wxString options, coldef, opcname; if (GetConnection()->BackendMinimumVersion(8, 3)) options = wxT(" i.indoption[") + NumToStr((long)(i - 1)) + wxT("] AS options,\n"); pgSet *res; wxString query; if (GetConnection()->BackendMinimumVersion(9, 0)) { query = wxT("SELECT\n") + options + wxT(" pg_get_indexdef(i.indexrelid, ") + NumToStr(i) + GetDatabase()->GetPrettyOption() + wxT(") AS coldef,\n") + wxT(" op.oprname,\n") + wxT(" CASE WHEN (o.opcdefault = FALSE) THEN o.opcname ELSE null END AS opcname\n"); if (GetConnection()->BackendMinimumVersion(9, 1)) query += wxT(",\n coll.collname, nspc.nspname as collnspname\n"); query += wxT("FROM pg_index i\n") wxT("JOIN pg_attribute a ON (a.attrelid = i.indexrelid AND attnum = ") + NumToStr(i) + wxT(")\n") + wxT("LEFT OUTER JOIN pg_opclass o ON (o.oid = i.indclass[") + NumToStr((long)(i - 1)) + wxT("])\n") + wxT("LEFT OUTER JOIN pg_constraint c ON (c.conindid = i.indexrelid) ") wxT("LEFT OUTER JOIN pg_operator op ON (op.oid = c.conexclop[") + NumToStr(i) + wxT("])\n"); if (GetConnection()->BackendMinimumVersion(9, 1)) query += wxT("LEFT OUTER JOIN pg_collation coll ON a.attcollation=coll.oid\n") wxT("LEFT OUTER JOIN pg_namespace nspc ON coll.collnamespace=nspc.oid\n"); query += wxT("WHERE i.indexrelid = ") + GetOidStr(); } else { query = wxT("SELECT\n") + options + wxT(" pg_get_indexdef(i.indexrelid, ") + NumToStr(i) + GetDatabase()->GetPrettyOption() + wxT(") AS coldef,\n") + wxT(" CASE WHEN (o.opcdefault = FALSE) THEN o.opcname ELSE null END AS opcname\n") + wxT("FROM pg_index i\n") + wxT("JOIN pg_attribute a ON (a.attrelid = i.indexrelid AND attnum = ") + NumToStr(i) + wxT(")\n") + wxT("LEFT OUTER JOIN pg_opclass o ON (o.oid = i.indclass[") + NumToStr((long)(i - 1)) + wxT("])\n") + wxT("WHERE i.indexrelid = ") + GetOidStr(); } res = ExecuteSet(query); if (res->NumRows() > 0) { coldef = res->GetVal(wxT("coldef")); if (GetConnection()->BackendMinimumVersion(9, 1) && !indexconstraint) { wxString collation = wxEmptyString; if (!res->GetVal(wxT("collname")).IsEmpty()) { collation = qtIdent(res->GetVal(wxT("collnspname"))) + wxT(".") + qtIdent(res->GetVal(wxT("collname"))); coldef += wxT(" COLLATE ") + collation; } collationsArray.Add(collation); } else { collationsArray.Add(wxEmptyString); } opcname = res->GetVal(wxT("opcname")); opclassesArray.Add(opcname); if (!opcname.IsEmpty()) coldef += wxT(" ") + opcname; // Get the column options if (GetConnection()->BackendMinimumVersion(8, 3)) { long opt = res->GetLong(wxT("options")); if (opt && (opt & 0x0001)) // Descending... { ordersArray.Add(wxT("DESC")); coldef += wxT(" DESC"); // NULLS FIRST is the default for descending if (!(opt && (opt & 0x0002))) { nullsArray.Add(wxT("NULLS LAST")); coldef += wxT(" NULLS LAST"); } else { nullsArray.Add(wxEmptyString); } } else // Ascending... { ordersArray.Add(wxT("ASC")); if ((opt && (opt & 0x0002))) { nullsArray.Add(wxT("NULLS FIRST")); coldef += wxT(" NULLS FIRST"); } else { nullsArray.Add(wxEmptyString); } } } else { ordersArray.Add(wxEmptyString); nullsArray.Add(wxEmptyString); } } if (isExclude) { coldef += wxT(" WITH ") + res->GetVal(wxT("oprname")); } columns += coldef; quotedColumns += coldef; columnList.Add(coldef); } } else { // its a 7.3 db // We cannot use SELECT IN (colNumbers) here because we couldn't be sure // about the read order wxStringTokenizer collist(GetColumnNumbers()); wxStringTokenizer args(procArgTypeList); wxString cn, ct; columnCount = 0; while (collist.HasMoreTokens()) { cn = collist.GetNextToken(); ct = args.GetNextToken(); pgSet *colSet = ExecuteSet( wxT("SELECT attname as conattname\n") wxT(" FROM pg_attribute\n") wxT(" WHERE attrelid=") + GetOidStr() + wxT(" AND attnum=") + cn); if (colSet) { if (columnCount) { columns += wxT(", "); quotedColumns += wxT(", "); } wxString colName = colSet->GetVal(0); columns += colName; columnList.Add(colName); ordersArray.Add(wxEmptyString); nullsArray.Add(wxEmptyString); opclassesArray.Add(wxEmptyString); collationsArray.Add(wxEmptyString); quotedColumns += qtIdent(colName); if (!ct.IsNull()) { pgSet *typeSet = ExecuteSet(wxT( "SELECT typname FROM pg_type where oid=") + ct); if (typeSet) { if (columnCount) { procArgs += wxT(", "); typedColumns += wxT(", "); quotedTypedColumns += wxT(", "); } wxString colType = typeSet->GetVal(0); procArgs += colType; typedColumns += colName + wxT("::") + colType; quotedTypedColumns += qtIdent(colName) + wxT("::") + colType; delete typeSet; } } delete colSet; } columnCount++; } } wxStringTokenizer ops(operatorClassList); wxString op; while (ops.HasMoreTokens()) { op = ops.GetNextToken(); pgSet *set = ExecuteSet(wxT( "SELECT opcname FROM pg_opclass WHERE oid=") + op); if (set) { if (!operatorClasses.IsNull()) operatorClasses += wxT(", "); operatorClasses += set->GetVal(0); delete set; } } } } void pgIndexBase::ShowTreeDetail(ctlTree *browser, frmMain *form, ctlListView *properties, ctlSQLBox *sqlPane) { ReadColumnDetails(); if (properties) { CreateListColumns(properties); properties->AppendItem(_("Name"), GetName()); properties->AppendItem(_("OID"), GetOid()); if (GetConnection()->BackendMinimumVersion(8, 0)) properties->AppendItem(_("Tablespace"), tablespace); if (!GetProcName().IsNull()) properties->AppendItem(_("Procedure "), GetSchemaPrefix(GetProcNamespace()) + GetProcName() + wxT("(") + GetTypedColumns() + wxT(")")); else properties->AppendItem(_("Columns"), GetColumns()); properties->AppendItem(_("Operator classes"), GetOperatorClasses()); properties->AppendYesNoItem(_("Unique?"), GetIsUnique()); properties->AppendYesNoItem(_("Primary?"), GetIsPrimary()); properties->AppendYesNoItem(_("Clustered?"), GetIsClustered()); properties->AppendYesNoItem(_("Valid?"), GetIsValid()); properties->AppendItem(_("Access method"), GetIndexType()); properties->AppendItem(_("Constraint"), GetConstraint()); properties->AppendYesNoItem(_("System index?"), GetSystemObject()); if (GetConnection()->BackendMinimumVersion(8, 2)) properties->AppendItem(_("Fill factor"), GetFillFactor()); properties->AppendItem(_("Comment"), firstLineOnly(GetComment())); } } void pgIndexBase::ShowStatistics(frmMain *form, ctlListView *statistics) { wxString sql = wxT("SELECT idx_scan AS ") + qtIdent(_("Index Scans")) + wxT(", idx_tup_read AS ") + qtIdent(_("Index Tuples Read")) + wxT(", idx_tup_fetch AS ") + qtIdent(_("Index Tuples Fetched")) + wxT(", idx_blks_read AS ") + qtIdent(_("Index Blocks Read")) + wxT(", idx_blks_hit AS ") + qtIdent(_("Index Blocks Hit")); if (GetConnection()->HasFeature(FEATURE_SIZE)) sql += wxT(", pg_size_pretty(pg_relation_size(") + GetOidStr() + wxT(")) AS ") + qtIdent(_("Index Size")); if (showExtendedStatistics) { sql += wxT(", version AS ") + qtIdent(_("Version")) + wxT(",\n") wxT(" tree_level AS ") + qtIdent(_("Tree Level")) + wxT(",\n") wxT(" pg_size_pretty(index_size) AS ") + qtIdent(_("Index Size")) + wxT(",\n") wxT(" root_block_no AS ") + qtIdent(_("Root Block No")) + wxT(",\n") wxT(" internal_pages AS ") + qtIdent(_("Internal Pages")) + wxT(",\n") wxT(" leaf_pages AS ") + qtIdent(_("Leaf Pages")) + wxT(",\n") wxT(" empty_pages AS ") + qtIdent(_("Empty Pages")) + wxT(",\n") wxT(" deleted_pages AS ") + qtIdent(_("Deleted Pages")) + wxT(",\n") wxT(" avg_leaf_density AS ") + qtIdent(_("Average Leaf Density")) + wxT(",\n") wxT(" leaf_fragmentation AS ") + qtIdent(_("Leaf Fragmentation")) + wxT("\n") wxT(" FROM pgstatindex('") + GetQuotedFullIdentifier() + wxT("'), pg_stat_all_indexes stat"); } else { sql += wxT("\n") wxT(" FROM pg_stat_all_indexes stat"); } sql += wxT("\n") wxT(" JOIN pg_statio_all_indexes statio ON stat.indexrelid = statio.indexrelid\n") wxT(" JOIN pg_class cl ON cl.oid=stat.indexrelid\n") wxT(" WHERE stat.indexrelid = ") + GetOidStr(); DisplayStatistics(statistics, sql); } pgObject *pgIndexBase::Refresh(ctlTree *browser, const wxTreeItemId item) { pgObject *index = 0; pgCollection *coll = browser->GetParentCollection(item); if (coll) index = indexFactory.CreateObjects(coll, 0, wxT("\n AND cls.oid=") + GetOidStr()); return index; } bool pgIndexBase::HasPgstatindex() { return GetConnection()->HasFeature(FEATURE_PGSTATINDEX); } executePgstatindexFactory::executePgstatindexFactory(menuFactoryList *list, wxMenu *mnu, ctlMenuToolbar *toolbar) : contextActionFactory(list) { mnu->Append(id, _("&Extended index statistics"), _("Get extended statistics via pgstatindex for the selected object."), wxITEM_CHECK); } wxWindow *executePgstatindexFactory::StartDialog(frmMain *form, pgObject *obj) { if (!((pgIndexBase *)obj)->GetShowExtendedStatistics()) { ((pgIndexBase *)obj)->iSetShowExtendedStatistics(true); wxTreeItemId item = form->GetBrowser()->GetSelection(); if (obj == form->GetBrowser()->GetObject(item)) form->SelectStatisticsTab(); } else ((pgIndexBase *)obj)->iSetShowExtendedStatistics(false); form->GetMenuFactories()->CheckMenu(obj, form->GetMenuBar(), (ctlMenuToolbar *)form->GetToolBar()); return 0; } bool executePgstatindexFactory::CheckEnable(pgObject *obj) { return obj && (obj->IsCreatedBy(indexFactory) || obj->IsCreatedBy(primaryKeyFactory) || obj->IsCreatedBy(uniqueFactory) || obj->IsCreatedBy(excludeFactory)) && ((pgIndexBase *)obj)->HasPgstatindex(); } bool executePgstatindexFactory::CheckChecked(pgObject *obj) { if (!obj) return false; if (obj->GetMetaType() == PGM_INDEX || obj->GetMetaType() == PGM_PRIMARYKEY || obj->GetMetaType() == PGM_UNIQUE || obj->GetMetaType() == PGM_EXCLUDE) return ((pgIndexBase *)obj)->GetShowExtendedStatistics(); return false; } pgIndex::pgIndex(pgSchema *newSchema, const wxString &newName) : pgIndexBase(newSchema, indexFactory, newName) { } pgObject *pgIndexBaseFactory::CreateObjects(pgCollection *coll, ctlTree *browser, const wxString &restriction) { pgSchemaObjCollection *collection = (pgSchemaObjCollection *)coll; pgIndexBase *index = 0; wxString query; wxString proname, projoin; if (collection->GetConnection()->BackendMinimumVersion(7, 4)) { proname = wxT("indnatts, "); if (collection->GetConnection()->BackendMinimumVersion(7, 5)) { proname += wxT("cls.reltablespace AS spcoid, spcname, "); projoin = wxT(" LEFT OUTER JOIN pg_tablespace ta on ta.oid=cls.reltablespace\n"); } } else { proname = wxT("proname, pn.nspname as pronspname, proargtypes, "); projoin = wxT(" LEFT OUTER JOIN pg_proc pr ON pr.oid=indproc\n") wxT(" LEFT OUTER JOIN pg_namespace pn ON pn.oid=pr.pronamespace\n"); } query = wxT("SELECT DISTINCT ON(cls.relname) cls.oid, cls.relname as idxname, indrelid, indkey, indisclustered, indisvalid, indisunique, indisprimary, n.nspname,\n") wxT(" ") + proname + wxT("tab.relname as tabname, indclass, con.oid AS conoid, CASE contype WHEN 'p' THEN desp.description WHEN 'u' THEN desp.description WHEN 'x' THEN desp.description ELSE des.description END AS description,\n") wxT(" pg_get_expr(indpred, indrelid") + collection->GetDatabase()->GetPrettyOption() + wxT(") as indconstraint, contype, condeferrable, condeferred, amname\n"); if (collection->GetConnection()->BackendMinimumVersion(8, 2)) query += wxT(", substring(array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor \n"); query += wxT(" FROM pg_index idx\n") wxT(" JOIN pg_class cls ON cls.oid=indexrelid\n") wxT(" JOIN pg_class tab ON tab.oid=indrelid\n") + projoin + wxT(" JOIN pg_namespace n ON n.oid=tab.relnamespace\n") wxT(" JOIN pg_am am ON am.oid=cls.relam\n") wxT(" LEFT JOIN pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_class WHERE relname='pg_constraint') AND dep.deptype='i')\n") wxT(" LEFT OUTER JOIN pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)\n") wxT(" LEFT OUTER JOIN pg_description des ON (des.objoid=cls.oid AND des.classoid='pg_class'::regclass)\n") wxT(" LEFT OUTER JOIN pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0 AND desp.classoid='pg_constraint'::regclass)\n") wxT(" WHERE indrelid = ") + collection->GetOidStr() + restriction + wxT("\n") wxT(" ORDER BY cls.relname"); pgSet *indexes = collection->GetDatabase()->ExecuteSet(query); if (indexes) { while (!indexes->Eof()) { switch (*(indexes->GetCharPtr(wxT("contype")))) { case 0: index = new pgIndex(collection->GetSchema()->GetSchema(), indexes->GetVal(wxT("idxname"))); break; case 'p': index = new pgPrimaryKey(collection->GetSchema()->GetSchema(), indexes->GetVal(wxT("idxname"))); ((pgPrimaryKey *)index)->iSetConstraintOid(indexes->GetOid(wxT("conoid"))); break; case 'u': index = new pgUnique(collection->GetSchema()->GetSchema(), indexes->GetVal(wxT("idxname"))); ((pgUnique *)index)->iSetConstraintOid(indexes->GetOid(wxT("conoid"))); break; case 'x': index = new pgExclude(collection->GetSchema()->GetSchema(), indexes->GetVal(wxT("idxname"))); ((pgExclude *)index)->iSetConstraintOid(indexes->GetOid(wxT("conoid"))); break; default: index = 0; break; } index->iSetOid(indexes->GetOid(wxT("oid"))); index->iSetIsClustered(indexes->GetBool(wxT("indisclustered"))); index->iSetIsValid(indexes->GetBool(wxT("indisvalid"))); index->iSetIsUnique(indexes->GetBool(wxT("indisunique"))); index->iSetIsPrimary(indexes->GetBool(wxT("indisprimary"))); index->iSetIsExclude(*(indexes->GetCharPtr(wxT("contype"))) == 'x'); index->iSetColumnNumbers(indexes->GetVal(wxT("indkey"))); index->iSetIdxSchema(indexes->GetVal(wxT("nspname"))); index->iSetComment(indexes->GetVal(wxT("description"))); index->iSetIdxTable(indexes->GetVal(wxT("tabname"))); index->iSetRelTableOid(indexes->GetOid(wxT("indrelid"))); if (collection->GetConnection()->BackendMinimumVersion(7, 4)) { index->iSetColumnCount(indexes->GetLong(wxT("indnatts"))); if (collection->GetConnection()->BackendMinimumVersion(8, 0)) { if (indexes->GetOid(wxT("spcoid")) == 0) index->iSetTablespaceOid(collection->GetDatabase()->GetTablespaceOid()); else index->iSetTablespaceOid(indexes->GetOid(wxT("spcoid"))); if (indexes->GetVal(wxT("spcname")) == wxEmptyString) index->iSetTablespace(collection->GetDatabase()->GetTablespace()); else index->iSetTablespace(indexes->GetVal(wxT("spcname"))); } } else { index->iSetColumnCount(0L); index->iSetProcNamespace(indexes->GetVal(wxT("pronspname"))); index->iSetProcName(indexes->GetVal(wxT("proname"))); index->iSetProcArgTypeList(indexes->GetVal(wxT("proargtypes"))); } index->iSetOperatorClassList(indexes->GetVal(wxT("indclass"))); index->iSetDeferrable(indexes->GetBool(wxT("condeferrable"))); index->iSetDeferred(indexes->GetBool(wxT("condeferred"))); index->iSetConstraint(indexes->GetVal(wxT("indconstraint"))); index->iSetIndexType(indexes->GetVal(wxT("amname"))); if (collection->GetConnection()->BackendMinimumVersion(8, 2)) index->iSetFillFactor(indexes->GetVal(wxT("fillfactor"))); if (browser) { browser->AppendObject(collection, index); indexes->MoveNext(); } else break; } delete indexes; } return index; } pgCollection *pgIndexBaseFactory::CreateCollection(pgObject *obj) { return new pgIndexBaseCollection(GetCollectionFactory(), (pgSchema *)obj); } pgObject *pgIndexFactory::CreateObjects(pgCollection *collection, ctlTree *browser, const wxString &restriction) { return pgIndexBaseFactory::CreateObjects(collection, browser, restriction + wxT("\n AND conname IS NULL")); } wxString pgIndexBaseCollection::GetTranslatedMessage(int kindOfMessage) const { wxString message = wxEmptyString; switch (kindOfMessage) { case RETRIEVINGDETAILS: message = _("Retrieving details on indexes"); break; case REFRESHINGDETAILS: message = _("Refreshing indexes"); break; case OBJECTSLISTREPORT: message = _("Indexes list report"); break; } return message; } ///////////////////////////// #include "images/index.pngc" #include "images/indexes.pngc" pgIndexFactory::pgIndexFactory() : pgIndexBaseFactory(__("Index"), __("New Index..."), __("Create a new Index."), index_png_img) { metaType = PGM_INDEX; } pgIndexFactory indexFactory; static pgaCollectionFactory cf(&indexFactory, __("Indexes"), indexes_png_img); pgIndexBaseCollection::pgIndexBaseCollection(pgaFactory *factory, pgSchema *sch) : pgSchemaObjCollection(factory, sch) { } void pgIndexBaseCollection::ShowStatistics(frmMain *form, ctlListView *statistics) { wxLogInfo(wxT("Displaying statistics for indexes on ") + GetSchema()->GetName()); bool hasSize = GetConnection()->HasFeature(FEATURE_SIZE); // Add the statistics view columns statistics->ClearAll(); statistics->AddColumn(_("Index Name")); statistics->AddColumn(_("Index Scans")); statistics->AddColumn(_("Index Tuples Read")); statistics->AddColumn(_("Index Tuples Fetched")); if (hasSize) statistics->AddColumn(_("Size")); wxString sql = wxT("SELECT indexrelname, ") wxT("idx_scan, idx_tup_read, idx_tup_fetch"); if (hasSize) sql += wxT(", pg_size_pretty(pg_relation_size(indexrelid)) AS ") + qtIdent(wxT("size")); sql += wxT("\n") wxT(" FROM pg_stat_all_indexes stat\n") wxT(" JOIN pg_class cls ON cls.oid=indexrelid\n") wxT(" LEFT JOIN pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_class WHERE relname='pg_constraint'))\n") wxT(" LEFT OUTER JOIN pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)\n") wxT(" WHERE schemaname = ") + qtDbString(GetSchema()->GetSchema()->GetName()) + wxT(" AND stat.relname = ") + qtDbString(GetSchema()->GetName()) + wxT(" AND con.contype IS NULL") + wxT("\n ORDER BY indexrelname"); pgSet *stats = GetDatabase()->ExecuteSet(sql); if (stats) { long pos = 0; while (!stats->Eof()) { statistics->InsertItem(pos, stats->GetVal(wxT("indexrelname")), PGICON_STATISTICS); statistics->SetItem(pos, 1, stats->GetVal(wxT("idx_scan"))); statistics->SetItem(pos, 2, stats->GetVal(wxT("idx_tup_read"))); statistics->SetItem(pos, 3, stats->GetVal(wxT("idx_tup_fetch"))); if (hasSize) statistics->SetItem(pos, 4, stats->GetVal(wxT("size"))); stats->MoveNext(); pos++; } delete stats; } }
33.292165
244
0.635566
jcjc79
0af0daa416bc000844b25227f8803f5fa24f8a94
42,415
cpp
C++
shell/ext/ratings/msrating/ratings.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
shell/ext/ratings/msrating/ratings.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
shell/ext/ratings/msrating/ratings.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/****************************************************************************\ * * RATINGS.CPP --Parses out the actual ratings from a site. * * Created: Ann McCurdy * \****************************************************************************/ /*Includes---------------------------------------------------------*/ #include "msrating.h" #include "mslubase.h" #include "debug.h" #include <ratings.h> #include <ratingsp.h> #include "parselbl.h" #include "picsrule.h" #include "pleasdlg.h" // CPleaseDialog #include <convtime.h> #include <contxids.h> #include <shlwapip.h> #include <wininet.h> #include <mluisupp.h> extern PICSRulesRatingSystem * g_pPRRS; extern array<PICSRulesRatingSystem*> g_arrpPRRS; extern PICSRulesRatingSystem * g_pApprovedPRRS; extern PICSRulesRatingSystem * g_pApprovedPRRSPreApply; extern array<PICSRulesRatingSystem*> g_arrpPICSRulesPRRSPreApply; extern BOOL g_fPICSRulesEnforced,g_fApprovedSitesEnforced; extern HMODULE g_hURLMON,g_hWININET; extern char g_szLastURL[INTERNET_MAX_URL_LENGTH]; extern HINSTANCE g_hInstance; HANDLE g_HandleGlobalCounter,g_ApprovedSitesHandleGlobalCounter; long g_lGlobalCounterValue,g_lApprovedSitesGlobalCounterValue; DWORD g_dwDataSource; BOOL g_fInvalid; PicsRatingSystemInfo *gPRSI = NULL; //7c9c1e2a-4dcd-11d2-b972-0060b0c4834d const GUID GUID_Ratings = { 0x7c9c1e2aL, 0x4dcd, 0x11d2, { 0xb9, 0x72, 0x00, 0x60, 0xb0, 0xc4, 0x83, 0x4d } }; //7c9c1e2b-4dcd-11d2-b972-0060b0c4834d const GUID GUID_ApprovedSites = { 0x7c9c1e2bL, 0x4dcd, 0x11d2, { 0xb9, 0x72, 0x00, 0x60, 0xb0, 0xc4, 0x83, 0x4d } }; extern CustomRatingHelper *g_pCustomRatingHelperList; BOOL g_fIsRunningUnderCustom = FALSE; void TerminateRatings(BOOL bProcessDetach); //+----------------------------------------------------------------------- // // Function: RatingsCustomInit // // Synopsis: Initialize the msrating dll for Custom // // Arguments: bInit (Default TRUE) - TRUE: change into Custom Mode // FALSE: change out of Custom Mode // // Returns: S_OK if properly initialized, E_OUTOFMEMORY otherwise // //------------------------------------------------------------------------ HRESULT WINAPI RatingCustomInit(BOOL bInit) { HRESULT hres = E_OUTOFMEMORY; ENTERCRITICAL; if (bInit) { if (NULL != gPRSI) { delete gPRSI; } gPRSI = new PicsRatingSystemInfo; if (gPRSI) { g_fIsRunningUnderCustom = TRUE; hres = S_OK; } } else { TerminateRatings(FALSE); RatingInit(); g_fIsRunningUnderCustom = FALSE; hres = S_OK; } LEAVECRITICAL; return hres; } //+----------------------------------------------------------------------- // // Function: RatingCustomAddRatingSystem // // Synopsis: Hand the description of a PICS rating system file to msrating. // The description is simply the contents of an RAT file. // // Arguments: pszRatingSystemBuffer : buffer containing the description // nBufferSize : the size of pszRatingSystemBuffer // // Returns: Success if rating system added // This function will not succeed if RatingCustomInit has // not been called. // //------------------------------------------------------------------------ STDAPI RatingCustomAddRatingSystem(LPSTR pszRatingSystemBuffer, UINT nBufferSize) { HRESULT hres = E_OUTOFMEMORY; if(!pszRatingSystemBuffer || nBufferSize == 0) { return E_INVALIDARG; } if (g_fIsRunningUnderCustom) { PicsRatingSystem* pPRS = new PicsRatingSystem; if (pPRS) { hres = pPRS->Parse(NULL, pszRatingSystemBuffer); if (SUCCEEDED(hres)) { pPRS->dwFlags |= PRS_ISVALID; } } if (SUCCEEDED(hres)) { ENTERCRITICAL; gPRSI->arrpPRS.Append(pPRS); gPRSI->fRatingInstalled = TRUE; LEAVECRITICAL; } else { if(pPRS) { delete pPRS; pPRS = NULL; } } } else { hres = E_FAIL; } return hres; } //+----------------------------------------------------------------------- // // Function: RatingCustomSetUserOptions // // Synopsis: Set the user options for the msrating dll for this process // // Arguments: pRSSetings : pointer to an array of rating system settings // cSettings : number of rating systems // // Returns: Success if user properly set // This function will not succeed if RatingCustomInit has // not been called. // //------------------------------------------------------------------------ HRESULT WINAPI RatingCustomSetUserOptions(RATINGSYSTEMSETTING* pRSSettings, UINT cSettings) { if (!pRSSettings || cSettings == 0) { return E_INVALIDARG; } ENTERCRITICAL; HRESULT hres = E_OUTOFMEMORY; UINT err, errTemp; if (g_fIsRunningUnderCustom) { if (gPRSI) { PicsUser* puser = new PicsUser; if (puser) { for (UINT i=0; i<cSettings; i++) { UserRatingSystem* pURS = new UserRatingSystem; if (!pURS) { err = ERROR_NOT_ENOUGH_MEMORY; break; } if (errTemp = pURS->QueryError()) { err = errTemp; break; } RATINGSYSTEMSETTING* parss = &pRSSettings[i]; pURS->SetName(parss->pszRatingSystemName); pURS->m_pPRS = FindInstalledRatingSystem(parss->pszRatingSystemName); for (UINT j=0; j<parss->cCategories; j++) { UserRating* pUR = new UserRating; if (pUR) { if (errTemp = pUR->QueryError()) { err = errTemp; } else { RATINGCATEGORYSETTING* parcs = &parss->paRCS[j]; pUR->SetName(parcs->pszValueName); pUR->m_nValue = parcs->nValue; if (pURS->m_pPRS) { pUR->m_pPC = FindInstalledCategory(pURS->m_pPRS->arrpPC, parcs->pszValueName); } err = pURS->AddRating(pUR); } } else { err = ERROR_NOT_ENOUGH_MEMORY; } if (ERROR_SUCCESS != err) { if (pUR) { delete pUR; pUR = NULL; } break; } } if (ERROR_SUCCESS == err) { err = puser->AddRatingSystem(pURS); } if (ERROR_SUCCESS != err) { if (pURS) { delete pURS; pURS = NULL; } break; } } if (ERROR_SUCCESS == err) { hres = NOERROR; gPRSI->fSettingsValid = TRUE; if (gPRSI->pUserObject) { delete gPRSI->pUserObject; } gPRSI->pUserObject = puser; } } } else { hres = E_UNEXPECTED; } } else { hres = E_FAIL; } LEAVECRITICAL; return hres; } //+----------------------------------------------------------------------- // // Function: RatingCustomAddRatingHelper // // Synopsis: Add a Custom ratings helper object // // Arguments: pszLibraryName : name of the library to load the helper from // clsid : CLSID of the rating helper // dwSort : Sort order or priority of the helper // // Returns: Success if rating helper added properly set // This function will not succeed if RatingCustomInit has // not been called. // //------------------------------------------------------------------------ HRESULT WINAPI RatingCustomAddRatingHelper(LPCSTR pszLibraryName, CLSID clsid, DWORD dwSort) { HRESULT hr = E_UNEXPECTED; if (g_fIsRunningUnderCustom) { CustomRatingHelper* pmrh = new CustomRatingHelper; if(NULL == pmrh) { hr = E_OUTOFMEMORY; } else { pmrh->hLibrary = LoadLibrary(pszLibraryName); if (pmrh->hLibrary) { pmrh->clsid = clsid; pmrh->dwSort = dwSort; ENTERCRITICAL; CustomRatingHelper* pmrhCurrent = g_pCustomRatingHelperList; CustomRatingHelper* pmrhPrev = NULL; while (pmrhCurrent && pmrhCurrent->dwSort < pmrh->dwSort) { pmrhPrev = pmrhCurrent; pmrhCurrent = pmrhCurrent->pNextHelper; } if (pmrhPrev) { ASSERT(pmrhPrev->pNextHelper == pmrhCurrent); pmrh->pNextHelper = pmrhCurrent; pmrhPrev->pNextHelper = pmrh; } else { ASSERT(pmrhCurrent == g_pCustomRatingHelperList); pmrh->pNextHelper = g_pCustomRatingHelperList; g_pCustomRatingHelperList = pmrh; } hr = S_OK; LEAVECRITICAL; } // if (pmrh->hLibrary) else { hr = E_FAIL; } } } else { hr = E_FAIL; } return hr; } //+----------------------------------------------------------------------- // // Function: RatingCustomRemoveRatingHelper // // Synopsis: Remove Custom rating helpers // // Arguments: CLSID : CLSID of the helper to remove // // Returns: S_OK if rating helper removed, S_FALSE if not found // E_UNEXPECTED if the global custom helper list is corrupted. // This function will not succeed if RatingCustomInit has // not been called and will return E_FAIL // //------------------------------------------------------------------------ HRESULT WINAPI RatingCustomRemoveRatingHelper(CLSID clsid) { CustomRatingHelper* pmrhCurrent = NULL; CustomRatingHelper* pmrhTemp = NULL; CustomRatingHelper* pmrhPrev = NULL; HRESULT hr = E_UNEXPECTED; if (g_fIsRunningUnderCustom) { if (NULL != g_pCustomRatingHelperList) { hr = S_FALSE; ENTERCRITICAL; pmrhCurrent = g_pCustomRatingHelperList; while (pmrhCurrent && pmrhCurrent->clsid != clsid) { pmrhPrev = pmrhCurrent; pmrhCurrent = pmrhCurrent->pNextHelper; } if (pmrhCurrent) { // // Snag copy of the node // pmrhTemp = pmrhCurrent; if (pmrhPrev) // Not on first node { // // Unlink the deleted node // pmrhPrev->pNextHelper = pmrhCurrent->pNextHelper; } else // First node -- adjust head pointer { ASSERT(pmrhCurrent == g_pCustomRatingHelperList); g_pCustomRatingHelperList = g_pCustomRatingHelperList->pNextHelper; } // // Wipe out the node // delete pmrhTemp; pmrhTemp = NULL; hr = S_OK; } LEAVECRITICAL; } } else { hr = E_FAIL; } return hr; } //+----------------------------------------------------------------------- // // Function: RatingCustomSetDefaultBureau // // Synopsis: Set the URL of the default rating bureau // // Arguments: pszRatingBureau - URL of the rating bureau // // Returns: S_OK if success, E_FAIL if RatingCustomInit has not been // called, E_OUTOFMEMORY if unable to allocate memory // E_INVALIDARG if pszRatingBureau is NULL // This function will not succeed if RatingCustomInit has // not been called and return E_FAIL. // //------------------------------------------------------------------------ HRESULT WINAPI RatingCustomSetDefaultBureau(LPCSTR pszRatingBureau) { HRESULT hr; if (pszRatingBureau) { if (g_fIsRunningUnderCustom) { LPSTR pszTemp = new char[strlenf(pszRatingBureau)+1]; if (pszTemp) { strcpy(pszTemp, pszRatingBureau); gPRSI->etstrRatingBureau.SetTo(pszTemp); hr = S_OK; } // if (pszTemp) else { hr = E_OUTOFMEMORY; } } // if(g_fIsRunningUnderCustom) else { hr = E_FAIL; } } else { hr = E_INVALIDARG; } return hr; } HRESULT WINAPI RatingInit() { DWORD dwNumSystems,dwCounter; HRESULT hRes; PICSRulesRatingSystem * pPRRS=NULL; g_hURLMON=LoadLibrary("URLMON.DLL"); if (g_hURLMON==NULL) { TraceMsg( TF_ERROR, "RatingInit() - Failed to Load URLMON!" ); g_pPRRS=NULL; //we couldn't load URLMON hRes=E_UNEXPECTED; } g_hWININET=LoadLibrary("WININET.DLL"); if (g_hWININET==NULL) { TraceMsg( TF_ERROR, "RatingInit() - Failed to Load WININET!" ); g_pPRRS=NULL; //we couldn't load WININET hRes=E_UNEXPECTED; } g_HandleGlobalCounter=SHGlobalCounterCreate(GUID_Ratings); g_lGlobalCounterValue=SHGlobalCounterGetValue(g_HandleGlobalCounter); g_ApprovedSitesHandleGlobalCounter=SHGlobalCounterCreate(GUID_ApprovedSites); g_lApprovedSitesGlobalCounterValue=SHGlobalCounterGetValue(g_ApprovedSitesHandleGlobalCounter); gPRSI = new PicsRatingSystemInfo; if(gPRSI == NULL) { TraceMsg( TF_ERROR, "RatingInit() - gPRSI is NULL!" ); return E_OUTOFMEMORY; } gPRSI->Init(); hRes=PICSRulesReadFromRegistry(PICSRULES_APPROVEDSITES,&g_pApprovedPRRS); if (FAILED(hRes)) { g_pApprovedPRRS=NULL; } hRes=PICSRulesGetNumSystems(&dwNumSystems); if (SUCCEEDED(hRes)) //we have PICSRules systems to inforce { for (dwCounter=PICSRULES_FIRSTSYSTEMINDEX; dwCounter<(dwNumSystems+PICSRULES_FIRSTSYSTEMINDEX); dwCounter++) { hRes=PICSRulesReadFromRegistry(dwCounter,&pPRRS); if (FAILED(hRes)) { char *lpszTitle,*lpszMessage; //we couldn't read in the systems, so don't inforce PICSRules, //and notify the user g_arrpPRRS.DeleteAll(); lpszTitle=(char *) GlobalAlloc(GPTR,MAX_PATH); lpszMessage=(char *) GlobalAlloc(GPTR,MAX_PATH); MLLoadString(IDS_PICSRULES_TAMPEREDREADTITLE,(LPTSTR) lpszTitle,MAX_PATH); MLLoadString(IDS_PICSRULES_TAMPEREDREADMSG,(LPTSTR) lpszMessage,MAX_PATH); MessageBox(NULL,(LPCTSTR) lpszMessage,(LPCTSTR) lpszTitle,MB_OK|MB_ICONERROR); GlobalFree(lpszTitle); lpszTitle = NULL; GlobalFree(lpszMessage); lpszMessage = NULL; break; } else { g_arrpPRRS.Append(pPRRS); pPRRS=NULL; } } } return NOERROR; } // YANGXU: 11/16/1999 // Actual rating term function that does the work // bProcessDetach: pass in as true if terminating during // ProcessDetach so libraries are not freed void TerminateRatings(BOOL bProcessDetach) { delete gPRSI; gPRSI = NULL; if (g_pApprovedPRRS != NULL) { delete g_pApprovedPRRS; g_pApprovedPRRS = NULL; } if (g_pApprovedPRRSPreApply != NULL) { delete g_pApprovedPRRSPreApply; g_pApprovedPRRSPreApply = NULL; } g_arrpPRRS.DeleteAll(); g_arrpPICSRulesPRRSPreApply.DeleteAll(); CloseHandle(g_HandleGlobalCounter); CloseHandle(g_ApprovedSitesHandleGlobalCounter); CustomRatingHelper *pTemp; while (g_pCustomRatingHelperList) { pTemp = g_pCustomRatingHelperList; if (bProcessDetach) { // TRICKY: Can't FreeLibrary() during DLL_PROCESS_DETACH, so leak the HMODULE... // (setting to NULL prevents the destructor from doing FreeLibrary()). // g_pCustomRatingHelperList->hLibrary = NULL; } g_pCustomRatingHelperList = g_pCustomRatingHelperList->pNextHelper; delete pTemp; pTemp = NULL; } if (bProcessDetach) { if ( g_hURLMON ) { FreeLibrary(g_hURLMON); g_hURLMON = NULL; } if ( g_hWININET ) { FreeLibrary(g_hWININET); g_hWININET = NULL; } } } void RatingTerm() { TerminateRatings(TRUE); } HRESULT WINAPI RatingEnabledQuery() { CheckGlobalInfoRev(); // $BUG - If the Settings are not valid should we return E_FAIL? if (gPRSI && !gPRSI->fSettingsValid) return S_OK; if (gPRSI && gPRSI->fRatingInstalled) { PicsUser *pUser = ::GetUserObject(); return (pUser && pUser->fEnabled) ? S_OK : S_FALSE; } else { return E_FAIL; } } // Store the Parsed Label List of Ratings Information to ppRatingDetails. void StoreRatingDetails( CParsedLabelList * pParsed, LPVOID * ppRatingDetails ) { if (ppRatingDetails != NULL) { *ppRatingDetails = pParsed; } else { if ( pParsed ) { FreeParsedLabelList(pParsed); pParsed = NULL; } } } HRESULT WINAPI RatingCheckUserAccess(LPCSTR pszUsername, LPCSTR pszURL, LPCSTR pszRatingInfo, LPBYTE pData, DWORD cbData, LPVOID *ppRatingDetails) { HRESULT hRes; BOOL fPassFail; g_fInvalid=FALSE; g_dwDataSource=cbData; g_fPICSRulesEnforced=FALSE; g_fApprovedSitesEnforced=FALSE; if (pszURL) lstrcpy(g_szLastURL,pszURL); CheckGlobalInfoRev(); if (ppRatingDetails != NULL) *ppRatingDetails = NULL; if (!gPRSI->fSettingsValid) return ResultFromScode(S_FALSE); if (!gPRSI->fRatingInstalled) return ResultFromScode(S_OK); PicsUser *pUser = GetUserObject(pszUsername); if (pUser == NULL) { return HRESULT_FROM_WIN32(ERROR_BAD_USERNAME); } if (!pUser->fEnabled) return ResultFromScode(S_OK); //check Approved Sites list hRes=PICSRulesCheckApprovedSitesAccess(pszURL,&fPassFail); if (SUCCEEDED(hRes)&&!g_fIsRunningUnderCustom) //the list made a determination, skip if Custom { g_fApprovedSitesEnforced=TRUE; if (fPassFail==PR_PASSFAIL_PASS) { return ResultFromScode(S_OK); } else { return ResultFromScode(S_FALSE); } } CParsedLabelList *pParsed=NULL; //check PICSRules systems hRes=PICSRulesCheckAccess(pszURL,pszRatingInfo,&fPassFail,&pParsed); if (SUCCEEDED(hRes)&&!g_fIsRunningUnderCustom) //the list made a determination, skip if Custom { g_fPICSRulesEnforced=TRUE; if (ppRatingDetails != NULL) *ppRatingDetails = pParsed; else FreeParsedLabelList(pParsed); if (fPassFail==PR_PASSFAIL_PASS) { return ResultFromScode(S_OK); } else { return ResultFromScode(S_FALSE); } } if (pszRatingInfo == NULL) { if (pUser->fAllowUnknowns) { hRes = ResultFromScode(S_OK); } else { hRes = ResultFromScode(S_FALSE); } //Site is unrated. Check if user can see unrated sites. /** Custom **/ // if notification interface exists, put in the URL if ( ( g_fIsRunningUnderCustom || ( hRes != S_OK ) ) && ( ppRatingDetails != NULL ) ) { if (!pParsed) { pParsed = new CParsedLabelList; } if (pParsed) { ASSERT(!pParsed->m_pszURL); pParsed->m_pszURL = new char[strlenf(pszURL) + 1]; if (pParsed->m_pszURL != NULL) { strcpyf(pParsed->m_pszURL, pszURL); } pParsed->m_fNoRating = TRUE; *ppRatingDetails = pParsed; } } return hRes; } else { if (pParsed!=NULL) { hRes = S_OK; } else { hRes = ParseLabelList(pszRatingInfo, &pParsed); } } if (SUCCEEDED(hRes)) { BOOL fRated = FALSE; BOOL fDenied = FALSE; ASSERT(pParsed != NULL); /** Custom **/ // if notification interface exists, put in the URL if (g_fIsRunningUnderCustom) { ASSERT(!pParsed->m_pszURL); pParsed->m_pszURL = new char[strlenf(pszURL) + 1]; if (pParsed->m_pszURL != NULL) { strcpyf(pParsed->m_pszURL, pszURL); } } DWORD timeCurrent = GetCurrentNetDate(); CParsedServiceInfo *psi = &pParsed->m_ServiceInfo; while (psi != NULL && !fDenied) { UserRatingSystem *pURS = pUser->FindRatingSystem(psi->m_pszServiceName); if (pURS != NULL && pURS->m_pPRS != NULL) { psi->m_fInstalled = TRUE; UINT cRatings = psi->aRatings.Length(); for (UINT i=0; i<cRatings; i++) { CParsedRating *pRating = &psi->aRatings[i]; // YANGXU: 11/17/1999 // Do not check the URL if under Custom mode // Checking the URL causes inaccuracies // when a label is returned for an URL on // a page whose server can have two different // DNS entries. We can't just not check because // passing in the URL is part of the published API if (!g_fIsRunningUnderCustom) { if (!pRating->pOptions->CheckURL(pszURL)) { pParsed->m_pszURL = new char[strlenf(pszURL) + 1]; if (pParsed->m_pszURL != NULL) { strcpyf(pParsed->m_pszURL, pszURL); } continue; /* this rating has expired or is for * another URL, ignore it */ } } if (!pRating->pOptions->CheckUntil(timeCurrent)) continue; UserRating *pUR = pURS->FindRating(pRating->pszTransmitName); if (pUR != NULL) { fRated = TRUE; pRating->fFound = TRUE; if ((*pUR).m_pPC!=NULL) { if ((pRating->nValue > (*((*pUR).m_pPC)).etnMax.Get())|| (pRating->nValue < (*((*pUR).m_pPC)).etnMin.Get())) { g_fInvalid = TRUE; fDenied = TRUE; pRating->fFailed = TRUE; } } if (pRating->nValue > pUR->m_nValue) { fDenied = TRUE; pRating->fFailed = TRUE; } else pRating->fFailed = FALSE; } else { g_fInvalid = TRUE; fDenied = TRUE; pRating->fFailed = TRUE; } } } else { psi->m_fInstalled = FALSE; } psi = psi->Next(); } if (!fRated) { pParsed->m_fRated = FALSE; hRes = E_RATING_NOT_FOUND; } else { pParsed->m_fRated = TRUE; if (fDenied) hRes = ResultFromScode(S_FALSE); } } else { TraceMsg( TF_WARNING, "RatingCheckUserAccess() - ParseLabelList() Failed with hres=0x%x!", hRes ); // Although the site has invalid PICS rules, the site should still be considered rated. hRes = ResultFromScode(S_FALSE); } StoreRatingDetails( pParsed, ppRatingDetails ); return hRes; } //+----------------------------------------------------------------------- // // Function: RatingCustomDeleteCrackedData // // Synopsis: frees the memory of structure returned by RatingCustomCrackData // // Arguments: prbInfo : pointer to RATINGBLOCKINGINFO to be deleted // // Returns: S_OK if delete successful, E_FAIL otherwise // //------------------------------------------------------------------------ HRESULT RatingCustomDeleteCrackedData(RATINGBLOCKINGINFO* prbInfo) { HRESULT hres = E_FAIL; RATINGBLOCKINGLABELLIST* prblTemp = NULL; if (NULL != prbInfo) { if (prbInfo->pwszDeniedURL) { delete [] prbInfo->pwszDeniedURL; prbInfo->pwszDeniedURL = NULL; } if (prbInfo->prbLabelList) { for (UINT j = 0; j < prbInfo->cLabels; j++) { prblTemp = &prbInfo->prbLabelList[j]; if (prblTemp->pwszRatingSystemName) { delete [] prblTemp->pwszRatingSystemName; prblTemp->pwszRatingSystemName = NULL; } if (prblTemp->paRBLS) { for (UINT i = 0; i < prblTemp->cBlockingLabels; i++) { if (prblTemp->paRBLS[i].pwszCategoryName) { delete [] prblTemp->paRBLS[i].pwszCategoryName; prblTemp->paRBLS[i].pwszCategoryName = NULL; } if (prblTemp->paRBLS[i].pwszTransmitName) { delete [] prblTemp->paRBLS[i].pwszTransmitName; prblTemp->paRBLS[i].pwszTransmitName = NULL; } if (prblTemp->paRBLS[i].pwszValueName) { delete [] prblTemp->paRBLS[i].pwszValueName; prblTemp->paRBLS[i].pwszValueName = NULL; } } delete [] prblTemp->paRBLS; prblTemp->paRBLS = NULL; } } delete [] prbInfo->prbLabelList; prbInfo->prbLabelList = NULL; } if (prbInfo->pwszRatingHelperName) { delete [] prbInfo->pwszRatingHelperName; prbInfo->pwszRatingHelperName = NULL; } hres = S_OK; if (prbInfo->pwszRatingHelperReason) { delete [] prbInfo->pwszRatingHelperReason; prbInfo->pwszRatingHelperReason = NULL; } delete prbInfo; prbInfo = NULL; } return hres; } HRESULT _CrackCategory(CParsedRating *pRating, RATINGBLOCKINGCATEGORY *pRBLS, UserRatingSystem* pURS) { UserRating *pUR = pURS->FindRating(pRating->pszTransmitName); if (pUR) { // // Mutated code from InitPleaseDialog, hope it works // PicsCategory* pPC = pUR->m_pPC; if (pPC) { pRBLS->nValue = pRating->nValue; Ansi2Unicode(&pRBLS->pwszTransmitName, pRating->pszTransmitName); LPCSTR pszCategory = NULL; if (pPC->etstrName.fIsInit()) { pszCategory = pPC->etstrName.Get(); } else if (pPC->etstrDesc.fIsInit()) { pszCategory = pPC->etstrDesc.Get(); } else { pszCategory = pRating->pszTransmitName; } Ansi2Unicode(&pRBLS->pwszCategoryName, pszCategory); UINT cValues = pPC->arrpPE.Length(); PicsEnum *pPE; for (UINT iValue=0; iValue < cValues; iValue++) { pPE = pPC->arrpPE[iValue]; if (pPE->etnValue.Get() == pRating->nValue) { break; } } LPCSTR pszValue = NULL; if (iValue < cValues) { if (pPE->etstrName.fIsInit()) { pszValue = pPE->etstrName.Get(); } else if (pPE->etstrDesc.fIsInit()) { pszValue = pPE->etstrDesc.Get(); } Ansi2Unicode(&pRBLS->pwszValueName, pszValue); } } } return S_OK; } //+----------------------------------------------------------------------- // // Function: RatingCustomCrackData // // Synopsis: packages the persistent, opaque data describing why a site // was denied into readable form // // Arguments: pszUsername : name of the user // pRatingDetails : pointer to the opaque data // pprbInfo : a RATINGBLOCKINGINFO representation of the data // // Returns: Success if data packaged // //------------------------------------------------------------------------ HRESULT RatingCustomCrackData(LPCSTR pszUsername, void* pvRatingDetails, RATINGBLOCKINGINFO** pprbInfo) { if(NULL != *pprbInfo) { return E_INVALIDARG; } RATINGBLOCKINGINFO* prbInfo = new RATINGBLOCKINGINFO; CParsedLabelList *pRatingDetails = (CParsedLabelList*)pvRatingDetails; if (!prbInfo) { return E_OUTOFMEMORY; } prbInfo->pwszDeniedURL = NULL; prbInfo->rbSource = RBS_ERROR; prbInfo->rbMethod = RBM_UNINIT; prbInfo->cLabels = 0; prbInfo->prbLabelList = NULL; prbInfo->pwszRatingHelperName = NULL; prbInfo->pwszRatingHelperReason = NULL; RATINGBLOCKINGLABELLIST* prblTemp = NULL; RATINGBLOCKINGLABELLIST* prblPrev = NULL; if (!g_fInvalid) { if (g_fIsRunningUnderCustom) { // pRatingDetails should not be NULL unless // we ran out of memory ASSERT(pRatingDetails); if (pRatingDetails->m_pszURL) { Ansi2Unicode(&prbInfo->pwszDeniedURL, pRatingDetails->m_pszURL); } if (pRatingDetails->m_fRated) { // The page can be rated or denied, but not both ASSERT(!pRatingDetails->m_fDenied); ASSERT(!pRatingDetails->m_fNoRating); prbInfo->rbMethod = RBM_LABEL; PicsUser* pPU = GetUserObject(pszUsername); if (pPU) { // first find out how many systems there are UINT cLabels = 0; CParsedServiceInfo *ppsi = &pRatingDetails->m_ServiceInfo; while (ppsi) { cLabels++; ppsi = ppsi->Next(); } // should have at least one label ASSERT(cLabels > 0); prbInfo->prbLabelList = new RATINGBLOCKINGLABELLIST[cLabels]; if (prbInfo->prbLabelList) { UINT iLabel = 0; for (ppsi = &pRatingDetails->m_ServiceInfo;ppsi;ppsi = ppsi->Next()) { if (!ppsi->m_fInstalled) { continue; } UserRatingSystem* pURS = pPU->FindRatingSystem(ppsi->m_pszServiceName); if (NULL == pURS || NULL == pURS->m_pPRS) { continue; } prblTemp = &(prbInfo->prbLabelList[iLabel]); Ansi2Unicode(&prblTemp->pwszRatingSystemName, pURS->m_pPRS->etstrName.Get()); UINT cRatings = ppsi->aRatings.Length(); prblTemp->paRBLS = new RATINGBLOCKINGCATEGORY[cRatings]; if (prblTemp->paRBLS == NULL) { RatingCustomDeleteCrackedData(prbInfo); return E_OUTOFMEMORY; } // if (prblTemp->paRBLS == NULL) prblTemp->cBlockingLabels = cRatings; for (UINT i=0; i < cRatings; i++) { CParsedRating *pRating = &ppsi->aRatings[i]; RATINGBLOCKINGCATEGORY* pRBLS = &prblTemp->paRBLS[i]; _CrackCategory(pRating, pRBLS, pURS); } // for (UINT i=0; i < cRatings; i++) // at this point, we should have valid ratings for // a system iLabel++; } // for (ppsi = &pRatingDetails->m_ServiceInfo;ppsi;ppsi = ppsi->Next()) prbInfo->cLabels = iLabel; } // if (prbInfo->prbLabelList) else { RatingCustomDeleteCrackedData(prbInfo); return E_OUTOFMEMORY; } if (!pRatingDetails->m_fIsHelper) { prbInfo->rbSource = RBS_PAGE; } else { if (pRatingDetails->m_fIsCustomHelper) { prbInfo->rbSource = RBS_CUSTOM_RATING_HELPER; if (pRatingDetails->m_pszRatingName) { Ansi2Unicode(&prbInfo->pwszRatingHelperName, pRatingDetails->m_pszRatingName); } if (pRatingDetails->m_pszRatingReason) { Ansi2Unicode(&prbInfo->pwszRatingHelperReason, pRatingDetails->m_pszRatingReason); } } else { prbInfo->rbSource = RBS_RATING_HELPER; } } } } // if (pRatingDetails->m_fRated) else { if (pRatingDetails->m_fDenied) { prbInfo->rbMethod = RBM_DENY; if (!pRatingDetails->m_fIsHelper) { prbInfo->rbSource = RBS_PAGE; } else { if (pRatingDetails->m_fIsCustomHelper) { prbInfo->rbSource = RBS_CUSTOM_RATING_HELPER; } else { prbInfo->rbSource = RBS_RATING_HELPER; } } } else { if (pRatingDetails->m_fNoRating) { prbInfo->rbSource = RBS_NO_RATINGS; } } } } // if (g_fIsRunningUnderCustom) else { prbInfo->rbMethod = RBM_ERROR_NOT_IN_CUSTOM_MODE; } } // (!g_fInvalid) *pprbInfo = prbInfo; return S_OK; } HRESULT WINAPI RatingAccessDeniedDialog(HWND hDlg, LPCSTR pszUsername, LPCSTR pszContentDescription, LPVOID pRatingDetails) { HRESULT hres; PleaseDlgData pdd; pdd.pszUsername = pszUsername; pdd.pPU = GetUserObject(pszUsername); if (pdd.pPU == NULL) { TraceMsg( TF_WARNING, "RatingAccessDeniedDialog() - Username is not valid!" ); return HRESULT_FROM_WIN32(ERROR_BAD_USERNAME); } pdd.pszContentDescription = pszContentDescription; pdd.pLabelList = (CParsedLabelList *)pRatingDetails; pdd.hwndEC = NULL; pdd.dwFlags = 0; pdd.hwndDlg = NULL; pdd.hwndOwner = hDlg; pdd.cLabels = 0; CPleaseDialog pleaseDialog( &pdd ); if ( pleaseDialog.DoModal( hDlg ) ) { hres = ResultFromScode(S_OK); } else { hres = ResultFromScode(S_FALSE); } for (UINT i=0; i<pdd.cLabels; i++) { delete pdd.apLabelStrings[i]; pdd.apLabelStrings[i] = NULL; } return hres; } HRESULT WINAPI RatingAccessDeniedDialog2(HWND hwndParent, LPCSTR pszUsername, LPVOID pRatingDetails) { PleaseDlgData *ppdd = (PleaseDlgData *)GetProp( hwndParent, szRatingsProp ); if (ppdd == NULL) { return RatingAccessDeniedDialog( hwndParent, pszUsername, NULL, pRatingDetails ); } HWND hwndDialog = ppdd->hwndDlg; ASSERT( hwndDialog ); ppdd->pLabelList = (CParsedLabelList *)pRatingDetails; SendMessage( hwndDialog, WM_NEWDIALOG, 0, (LPARAM)ppdd ); // The ppdd is only valid during the RatingAccessDeniedDialog() scope!! ppdd = NULL; // $REVIEW - Should we use a Windows Hook instead of looping to wait for the // modal dialog box to complete? // $CLEANUP - Use a CMessageLoop instead. // Property is removed once the modal dialog is toasted. while ( ::IsWindow( hwndParent ) && ::GetProp( hwndParent, szRatingsProp ) ) { MSG msg; if ( PeekMessage( &msg, NULL, 0, 0, PM_NOREMOVE ) ) { if ( GetMessage( &msg, NULL, 0, 0 ) > 0 ) // && !IsDialogMessage(ppdd->hwndDlg, &msg)) { { TranslateMessage(&msg); DispatchMessage(&msg); } } else { ::Sleep( 100 ); // Empty message queue means check again in 100 msecs } } DWORD dwFlags; dwFlags = ::IsWindow( hwndParent ) ? PtrToUlong( GetProp( hwndParent, szRatingsValue ) ) : PDD_DONE; TraceMsg( TF_ALWAYS, "RatingAccessDeniedDialog2() - Message Loop exited with dwFlags=%d", dwFlags ); return ( dwFlags & PDD_ALLOW ) ? S_OK : S_FALSE; } HRESULT WINAPI RatingFreeDetails(LPVOID pRatingDetails) { if (pRatingDetails) { FreeParsedLabelList((CParsedLabelList *)pRatingDetails); } return NOERROR; }
30.757796
124
0.461723
npocmaka
0af574fcf98b64c92bbf622f3aa34b2883023672
2,688
cc
C++
dds/src/model/DescribeReplicaSetRoleResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
dds/src/model/DescribeReplicaSetRoleResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
dds/src/model/DescribeReplicaSetRoleResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/dds/model/DescribeReplicaSetRoleResult.h> #include <json/json.h> using namespace AlibabaCloud::Dds; using namespace AlibabaCloud::Dds::Model; DescribeReplicaSetRoleResult::DescribeReplicaSetRoleResult() : ServiceResult() {} DescribeReplicaSetRoleResult::DescribeReplicaSetRoleResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeReplicaSetRoleResult::~DescribeReplicaSetRoleResult() {} void DescribeReplicaSetRoleResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allReplicaSetsNode = value["ReplicaSets"]["ReplicaSet"]; for (auto valueReplicaSetsReplicaSet : allReplicaSetsNode) { ReplicaSet replicaSetsObject; if(!valueReplicaSetsReplicaSet["ReplicaSetRole"].isNull()) replicaSetsObject.replicaSetRole = valueReplicaSetsReplicaSet["ReplicaSetRole"].asString(); if(!valueReplicaSetsReplicaSet["RoleId"].isNull()) replicaSetsObject.roleId = valueReplicaSetsReplicaSet["RoleId"].asString(); if(!valueReplicaSetsReplicaSet["ConnectionDomain"].isNull()) replicaSetsObject.connectionDomain = valueReplicaSetsReplicaSet["ConnectionDomain"].asString(); if(!valueReplicaSetsReplicaSet["ConnectionPort"].isNull()) replicaSetsObject.connectionPort = valueReplicaSetsReplicaSet["ConnectionPort"].asString(); if(!valueReplicaSetsReplicaSet["ExpiredTime"].isNull()) replicaSetsObject.expiredTime = valueReplicaSetsReplicaSet["ExpiredTime"].asString(); if(!valueReplicaSetsReplicaSet["NetworkType"].isNull()) replicaSetsObject.networkType = valueReplicaSetsReplicaSet["NetworkType"].asString(); replicaSets_.push_back(replicaSetsObject); } if(!value["DBInstanceId"].isNull()) dBInstanceId_ = value["DBInstanceId"].asString(); } std::string DescribeReplicaSetRoleResult::getDBInstanceId()const { return dBInstanceId_; } std::vector<DescribeReplicaSetRoleResult::ReplicaSet> DescribeReplicaSetRoleResult::getReplicaSets()const { return replicaSets_; }
35.84
105
0.78497
iamzken
0af8735a0ad57ef0863fa734864cb8860e5cb03e
650
cpp
C++
AudioSynthesis/synthetizerflowview.cpp
eliasrm87/AudioSynthesisQt
feb05c74d85494300d0fca868a37015042ec74c8
[ "Unlicense" ]
1
2021-09-03T11:06:45.000Z
2021-09-03T11:06:45.000Z
AudioSynthesis/synthetizerflowview.cpp
eliasrm87/AudioSynthesisQt
feb05c74d85494300d0fca868a37015042ec74c8
[ "Unlicense" ]
null
null
null
AudioSynthesis/synthetizerflowview.cpp
eliasrm87/AudioSynthesisQt
feb05c74d85494300d0fca868a37015042ec74c8
[ "Unlicense" ]
2
2021-09-03T11:06:53.000Z
2021-09-03T11:07:25.000Z
#include "synthetizerflowview.h" #include <AudioNodes/audionodes.h> SynthetizerFlowView::SynthetizerFlowView(QWidget *parent) : DataFlowView(parent) { } void SynthetizerFlowView::addNode(Node *node) { DataFlowView::addNode(node); } Node *SynthetizerFlowView::newNodeFromJson(const QJsonObject &obj) { QString nodeClass = obj.value("class").toString(); if (nodeClass == "Oscillator") { return new OscillatorNode(obj); } else if (nodeClass == "Output") { return new OutputNode(obj); } else if (nodeClass == "Loop") { return new LoopNode(obj); } return DataFlowView::newNodeFromJson(obj); }
22.413793
66
0.683077
eliasrm87
0afbb14b6809722653578e416d73682dd45a47ee
232,139
hpp
C++
Lib/Chip/Unknown/Atmel/ATSAMA5D35/DMAC0.hpp
operativeF/Kvasir
dfbcbdc9993d326ef8cc73d99129e78459c561fd
[ "Apache-2.0" ]
null
null
null
Lib/Chip/Unknown/Atmel/ATSAMA5D35/DMAC0.hpp
operativeF/Kvasir
dfbcbdc9993d326ef8cc73d99129e78459c561fd
[ "Apache-2.0" ]
null
null
null
Lib/Chip/Unknown/Atmel/ATSAMA5D35/DMAC0.hpp
operativeF/Kvasir
dfbcbdc9993d326ef8cc73d99129e78459c561fd
[ "Apache-2.0" ]
null
null
null
#pragma once #include <Register/Utility.hpp> namespace Kvasir { //DMA Controller 0 namespace Dmac0Gcfg{ ///<DMAC Global Configuration Register using Addr = Register::Address<0xffffe600,0xfffffeef,0x00000000,std::uint32_t>; ///Arbiter Configuration enum class ArbcfgVal { fixed=0x00000000, ///<Fixed priority arbiter. roundRobin=0x00000001, ///<Modified round robin arbiter. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,ArbcfgVal> arbCfg{}; namespace ArbcfgValC{ constexpr Register::FieldValue<decltype(arbCfg)::Type,ArbcfgVal::fixed> fixed{}; constexpr Register::FieldValue<decltype(arbCfg)::Type,ArbcfgVal::roundRobin> roundRobin{}; } ///Descriptor Integrity Check constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> dicen{}; } namespace Dmac0En{ ///<DMAC Enable Register using Addr = Register::Address<0xffffe604,0xfffffffe,0x00000000,std::uint32_t>; ///General Enable of DMA constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> enable{}; } namespace Dmac0Sreq{ ///<DMAC Software Single Request Register using Addr = Register::Address<0xffffe608,0xffff0000,0x00000000,std::uint32_t>; ///Source Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> ssreq0{}; ///Destination Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> dsreq0{}; ///Source Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> ssreq1{}; ///Destination Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> dsreq1{}; ///Source Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ssreq2{}; ///Destination Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> dsreq2{}; ///Source Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> ssreq3{}; ///Destination Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> dsreq3{}; ///Source Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> ssreq4{}; ///Destination Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> dsreq4{}; ///Source Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> ssreq5{}; ///Destination Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> dsreq5{}; ///Source Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> ssreq6{}; ///Destination Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> dsreq6{}; ///Source Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> ssreq7{}; ///Destination Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> dsreq7{}; } namespace Dmac0Creq{ ///<DMAC Software Chunk Transfer Request Register using Addr = Register::Address<0xffffe60c,0xffff0000,0x00000000,std::uint32_t>; ///Source Chunk Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> screq0{}; ///Destination Chunk Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> dcreq0{}; ///Source Chunk Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> screq1{}; ///Destination Chunk Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> dcreq1{}; ///Source Chunk Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> screq2{}; ///Destination Chunk Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> dcreq2{}; ///Source Chunk Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> screq3{}; ///Destination Chunk Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> dcreq3{}; ///Source Chunk Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> screq4{}; ///Destination Chunk Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> dcreq4{}; ///Source Chunk Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> screq5{}; ///Destination Chunk Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> dcreq5{}; ///Source Chunk Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> screq6{}; ///Destination Chunk Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> dcreq6{}; ///Source Chunk Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> screq7{}; ///Destination Chunk Request constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> dcreq7{}; } namespace Dmac0Last{ ///<DMAC Software Last Transfer Flag Register using Addr = Register::Address<0xffffe610,0xffff0000,0x00000000,std::uint32_t>; ///Source Last constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> slast0{}; ///Destination Last constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> dlast0{}; ///Source Last constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> slast1{}; ///Destination Last constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> dlast1{}; ///Source Last constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> slast2{}; ///Destination Last constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> dlast2{}; ///Source Last constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> slast3{}; ///Destination Last constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> dlast3{}; ///Source Last constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> slast4{}; ///Destination Last constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> dlast4{}; ///Source Last constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> slast5{}; ///Destination Last constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> dlast5{}; ///Source Last constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> slast6{}; ///Destination Last constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> dlast6{}; ///Source Last constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> slast7{}; ///Destination Last constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> dlast7{}; } namespace Dmac0Ebcier{ ///<DMAC Error, Chained Buffer Transfer Completed Interrupt and Buffer Transfer Completed Interrupt Enable register. using Addr = Register::Address<0xffffe618,0x00000000,0x00000000,std::uint32_t>; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc0{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc1{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc2{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc3{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc4{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc5{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc6{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc7{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc0{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc1{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc2{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc3{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc4{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc5{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc6{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc7{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err0{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err1{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err2{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err3{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err4{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err5{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err6{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err7{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr0{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr1{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr2{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr3{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr4{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr5{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr6{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr7{}; } namespace Dmac0Ebcidr{ ///<DMAC Error, Chained Buffer Transfer Completed Interrupt and Buffer Transfer Completed Interrupt Disable register. using Addr = Register::Address<0xffffe61c,0x00000000,0x00000000,std::uint32_t>; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc0{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc1{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc2{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc3{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc4{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc5{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc6{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc7{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc0{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc1{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc2{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc3{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc4{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc5{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc6{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc7{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err0{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err1{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err2{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err3{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err4{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err5{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err6{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err7{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr0{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr1{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr2{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr3{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr4{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr5{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr6{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr7{}; } namespace Dmac0Ebcimr{ ///<DMAC Error, Chained Buffer Transfer Completed Interrupt and Buffer transfer completed Mask Register. using Addr = Register::Address<0xffffe620,0x00000000,0x00000000,std::uint32_t>; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc0{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc1{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc2{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc3{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc4{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc5{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc6{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc7{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc0{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc1{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc2{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc3{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc4{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc5{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc6{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc7{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err0{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err1{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err2{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err3{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err4{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err5{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err6{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err7{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr0{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr1{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr2{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr3{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr4{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr5{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr6{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr7{}; } namespace Dmac0Ebcisr{ ///<DMAC Error, Chained Buffer Transfer Completed Interrupt and Buffer transfer completed Status Register. using Addr = Register::Address<0xffffe624,0x00000000,0x00000000,std::uint32_t>; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc0{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc1{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc2{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc3{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc4{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc5{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc6{}; ///Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btc7{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc0{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc1{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc2{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc3{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc4{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc5{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc6{}; ///Chained Buffer Transfer Completed [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> cbtc7{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err0{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err1{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err2{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err3{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err4{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err5{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err6{}; ///Access Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> err7{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr0{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr1{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr2{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr3{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr4{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr5{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr6{}; ///Descriptor Integrity Check Error [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dicerr7{}; } namespace Dmac0Cher{ ///<DMAC Channel Handler Enable Register using Addr = Register::Address<0xffffe628,0x00ff0000,0x00000000,std::uint32_t>; ///Enable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ena0{}; ///Enable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ena1{}; ///Enable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ena2{}; ///Enable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ena3{}; ///Enable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ena4{}; ///Enable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ena5{}; ///Enable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ena6{}; ///Enable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ena7{}; ///Suspend [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> susp0{}; ///Suspend [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> susp1{}; ///Suspend [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> susp2{}; ///Suspend [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> susp3{}; ///Suspend [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> susp4{}; ///Suspend [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> susp5{}; ///Suspend [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> susp6{}; ///Suspend [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> susp7{}; ///Keep on [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> keep0{}; ///Keep on [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> keep1{}; ///Keep on [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> keep2{}; ///Keep on [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> keep3{}; ///Keep on [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> keep4{}; ///Keep on [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> keep5{}; ///Keep on [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> keep6{}; ///Keep on [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> keep7{}; } namespace Dmac0Chdr{ ///<DMAC Channel Handler Disable Register using Addr = Register::Address<0xffffe62c,0xffff0000,0x00000000,std::uint32_t>; ///Disable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dis0{}; ///Disable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dis1{}; ///Disable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dis2{}; ///Disable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dis3{}; ///Disable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dis4{}; ///Disable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dis5{}; ///Disable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dis6{}; ///Disable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> dis7{}; ///Resume [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> res0{}; ///Resume [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> res1{}; ///Resume [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> res2{}; ///Resume [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> res3{}; ///Resume [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> res4{}; ///Resume [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> res5{}; ///Resume [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> res6{}; ///Resume [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> res7{}; } namespace Dmac0Chsr{ ///<DMAC Channel Handler Status Register using Addr = Register::Address<0xffffe630,0x00000000,0x00000000,std::uint32_t>; ///Enable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ena0{}; ///Enable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ena1{}; ///Enable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ena2{}; ///Enable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ena3{}; ///Enable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ena4{}; ///Enable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ena5{}; ///Enable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ena6{}; ///Enable [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ena7{}; ///Suspend [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> susp0{}; ///Suspend [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> susp1{}; ///Suspend [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> susp2{}; ///Suspend [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> susp3{}; ///Suspend [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> susp4{}; ///Suspend [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> susp5{}; ///Suspend [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> susp6{}; ///Suspend [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> susp7{}; ///Empty [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> empt0{}; ///Empty [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> empt1{}; ///Empty [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> empt2{}; ///Empty [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> empt3{}; ///Empty [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> empt4{}; ///Empty [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> empt5{}; ///Empty [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> empt6{}; ///Empty [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> empt7{}; ///Stalled [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> stal0{}; ///Stalled [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> stal1{}; ///Stalled [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> stal2{}; ///Stalled [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> stal3{}; ///Stalled [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> stal4{}; ///Stalled [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> stal5{}; ///Stalled [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> stal6{}; ///Stalled [7:0] constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> stal7{}; } namespace Dmac0Saddr0{ ///<DMAC Channel Source Address Register (ch_num = 0) using Addr = Register::Address<0xffffe63c,0x00000000,0x00000000,std::uint32_t>; ///Channel x Source Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> saddr{}; } namespace Dmac0Daddr0{ ///<DMAC Channel Destination Address Register (ch_num = 0) using Addr = Register::Address<0xffffe640,0x00000000,0x00000000,std::uint32_t>; ///Channel x Destination Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> daddr{}; } namespace Dmac0Dscr0{ ///<DMAC Channel Descriptor Address Register (ch_num = 0) using Addr = Register::Address<0xffffe644,0x00000000,0x00000000,std::uint32_t>; ///Descriptor Interface Selection enum class DscrifVal { ahbIf0=0x00000000, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 0 ahbIf1=0x00000001, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 1 ahbIf2=0x00000002, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,DscrifVal> dscrIf{}; namespace DscrifValC{ constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf2> ahbIf2{}; } ///Buffer Transfer Descriptor Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,2),Register::ReadWriteAccess,unsigned> dscr{}; } namespace Dmac0Ctrla0{ ///<DMAC Channel Control A Register (ch_num = 0) using Addr = Register::Address<0xffffe648,0x4c880000,0x00000000,std::uint32_t>; ///Buffer Transfer Size constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> btsize{}; ///Source Chunk Transfer Size. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,16),Register::ReadWriteAccess,unsigned> scsize{}; ///Destination Chunk Transfer Size constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,20),Register::ReadWriteAccess,unsigned> dcsize{}; ///Transfer Width for the Source enum class SrcwidthVal { byte=0x00000000, ///<the transfer size is set to 8-bit width halfWord=0x00000001, ///<the transfer size is set to 16-bit width word=0x00000002, ///<the transfer size is set to 32-bit width dword=0x00000003, ///<the transfer size is set to 64-bit width }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,SrcwidthVal> srcWidth{}; namespace SrcwidthValC{ constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::byte> byte{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::halfWord> halfWord{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::word> word{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::dword> dword{}; } ///Transfer Width for the Destination enum class DstwidthVal { byte=0x00000000, ///<the transfer size is set to 8-bit width halfWord=0x00000001, ///<the transfer size is set to 16-bit width word=0x00000002, ///<the transfer size is set to 32-bit width dword=0x00000003, ///<the transfer size is set to 64-bit width }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,DstwidthVal> dstWidth{}; namespace DstwidthValC{ constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::byte> byte{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::halfWord> halfWord{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::word> word{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::dword> dword{}; } ///Current Descriptor Stop Command and Transfer Completed Memory Indicator constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> done{}; } namespace Dmac0Ctrlb0{ ///<DMAC Channel Control B Register (ch_num = 0) using Addr = Register::Address<0xffffe64c,0x0c8eeecc,0x00000000,std::uint32_t>; ///Source Interface Selection Field enum class SifVal { ahbIf0=0x00000000, ///<The source transfer is done via AHB_Lite Interface 0 ahbIf1=0x00000001, ///<The source transfer is done via AHB_Lite Interface 1 ahbIf2=0x00000002, ///<The source transfer is done via AHB_Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,SifVal> sif{}; namespace SifValC{ constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf2> ahbIf2{}; } ///Destination Interface Selection Field enum class DifVal { ahbIf0=0x00000000, ///<The destination transfer is done via AHB_Lite Interface 0 ahbIf1=0x00000001, ///<The destination transfer is done via AHB_Lite Interface 1 ahbIf2=0x00000002, ///<The destination transfer is done via AHB_Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,DifVal> dif{}; namespace DifValC{ constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf2> ahbIf2{}; } ///Source Picture-in-Picture Mode enum class SrcpipVal { disable=0x00000000, ///<Picture-in-Picture mode is disabled. The source data area is contiguous. enable=0x00000001, ///<Picture-in-Picture mode is enabled. When the source PIP counter reaches the programmable boundary, the address is automatically incremented by a user defined amount. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SrcpipVal> srcPip{}; namespace SrcpipValC{ constexpr Register::FieldValue<decltype(srcPip)::Type,SrcpipVal::disable> disable{}; constexpr Register::FieldValue<decltype(srcPip)::Type,SrcpipVal::enable> enable{}; } ///Destination Picture-in-Picture Mode enum class DstpipVal { disable=0x00000000, ///<Picture-in-Picture mode is disabled. The Destination data area is contiguous. enable=0x00000001, ///<Picture-in-Picture mode is enabled. When the Destination PIP counter reaches the programmable boundary the address is automatically incremented by a user-defined amount. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,DstpipVal> dstPip{}; namespace DstpipValC{ constexpr Register::FieldValue<decltype(dstPip)::Type,DstpipVal::disable> disable{}; constexpr Register::FieldValue<decltype(dstPip)::Type,DstpipVal::enable> enable{}; } ///Source Address Descriptor enum class SrcdscrVal { fetchFromMem=0x00000000, ///<Source address is updated when the descriptor is fetched from the memory. fetchDisable=0x00000001, ///<Buffer Descriptor Fetch operation is disabled for the source. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,SrcdscrVal> srcDscr{}; namespace SrcdscrValC{ constexpr Register::FieldValue<decltype(srcDscr)::Type,SrcdscrVal::fetchFromMem> fetchFromMem{}; constexpr Register::FieldValue<decltype(srcDscr)::Type,SrcdscrVal::fetchDisable> fetchDisable{}; } ///Destination Address Descriptor enum class DstdscrVal { fetchFromMem=0x00000000, ///<Destination address is updated when the descriptor is fetched from the memory. fetchDisable=0x00000001, ///<Buffer Descriptor Fetch operation is disabled for the destination. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,DstdscrVal> dstDscr{}; namespace DstdscrValC{ constexpr Register::FieldValue<decltype(dstDscr)::Type,DstdscrVal::fetchFromMem> fetchFromMem{}; constexpr Register::FieldValue<decltype(dstDscr)::Type,DstdscrVal::fetchDisable> fetchDisable{}; } ///Flow Control enum class FcVal { mem2memDmaFc=0x00000000, ///<Memory-to-Memory Transfer DMAC is flow controller mem2perDmaFc=0x00000001, ///<Memory-to-Peripheral Transfer DMAC is flow controller per2memDmaFc=0x00000002, ///<Peripheral-to-Memory Transfer DMAC is flow controller per2perDmaFc=0x00000003, ///<Peripheral-to-Peripheral Transfer DMAC is flow controller }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,21),Register::ReadWriteAccess,FcVal> fc{}; namespace FcValC{ constexpr Register::FieldValue<decltype(fc)::Type,FcVal::mem2memDmaFc> mem2memDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::mem2perDmaFc> mem2perDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::per2memDmaFc> per2memDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::per2perDmaFc> per2perDmaFc{}; } ///Incrementing, Decrementing or Fixed Address for the Source enum class SrcincrVal { incrementing=0x00000000, ///<The source address is incremented decrementing=0x00000001, ///<The source address is decremented fixed=0x00000002, ///<The source address remains unchanged }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,SrcincrVal> srcIncr{}; namespace SrcincrValC{ constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::incrementing> incrementing{}; constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::decrementing> decrementing{}; constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::fixed> fixed{}; } ///Incrementing, Decrementing or Fixed Address for the Destination enum class DstincrVal { incrementing=0x00000000, ///<The destination address is incremented decrementing=0x00000001, ///<The destination address is decremented fixed=0x00000002, ///<The destination address remains unchanged }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,DstincrVal> dstIncr{}; namespace DstincrValC{ constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::incrementing> incrementing{}; constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::decrementing> decrementing{}; constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::fixed> fixed{}; } ///Interrupt Enable Not constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> ien{}; ///Automatic Multiple Buffer Transfer enum class Auto_Val { disable=0x00000000, ///<Automatic multiple buffer transfer is disabled. enable=0x00000001, ///<Automatic multiple buffer transfer is enabled. This bit enables replay mode or contiguous mode when several buffers are transferred. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,Auto_Val> auto_{}; namespace Auto_ValC{ constexpr Register::FieldValue<decltype(auto_)::Type,Auto_Val::disable> disable{}; constexpr Register::FieldValue<decltype(auto_)::Type,Auto_Val::enable> enable{}; } } namespace Dmac0Cfg0{ ///<DMAC Channel Configuration Register (ch_num = 0) using Addr = Register::Address<0xffffe650,0xc88e0000,0x00000000,std::uint32_t>; ///Source with Peripheral identifier constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> srcPer{}; ///Destination with Peripheral identifier constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,4),Register::ReadWriteAccess,unsigned> dstPer{}; ///Source Reloaded from Previous enum class SrcrepVal { contiguousAddr=0x00000000, ///<When automatic mode is activated, source address is contiguous between two buffers. reloadAddr=0x00000001, ///<When automatic mode is activated, the source address and the control register are reloaded from previous transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SrcrepVal> srcRep{}; namespace SrcrepValC{ constexpr Register::FieldValue<decltype(srcRep)::Type,SrcrepVal::contiguousAddr> contiguousAddr{}; constexpr Register::FieldValue<decltype(srcRep)::Type,SrcrepVal::reloadAddr> reloadAddr{}; } ///Software or Hardware Selection for the Source enum class Srch2selVal { sw=0x00000000, ///<Software handshaking interface is used to trigger a transfer request. hw=0x00000001, ///<Hardware handshaking interface is used to trigger a transfer request. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,Srch2selVal> srcH2sel{}; namespace Srch2selValC{ constexpr Register::FieldValue<decltype(srcH2sel)::Type,Srch2selVal::sw> sw{}; constexpr Register::FieldValue<decltype(srcH2sel)::Type,Srch2selVal::hw> hw{}; } ///SRC_PER Most Significant Bits constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,10),Register::ReadWriteAccess,unsigned> srcPerMsb{}; ///Destination Reloaded from Previous enum class DstrepVal { contiguousAddr=0x00000000, ///<When automatic mode is activated, destination address is contiguous between two buffers. reloadAddr=0x00000001, ///<When automatic mode is activated, the destination and the control register are reloaded from the pre-vious transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,DstrepVal> dstRep{}; namespace DstrepValC{ constexpr Register::FieldValue<decltype(dstRep)::Type,DstrepVal::contiguousAddr> contiguousAddr{}; constexpr Register::FieldValue<decltype(dstRep)::Type,DstrepVal::reloadAddr> reloadAddr{}; } ///Software or Hardware Selection for the Destination enum class Dsth2selVal { sw=0x00000000, ///<Software handshaking interface is used to trigger a transfer request. hw=0x00000001, ///<Hardware handshaking interface is used to trigger a transfer request. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,Dsth2selVal> dstH2sel{}; namespace Dsth2selValC{ constexpr Register::FieldValue<decltype(dstH2sel)::Type,Dsth2selVal::sw> sw{}; constexpr Register::FieldValue<decltype(dstH2sel)::Type,Dsth2selVal::hw> hw{}; } ///DST_PER Most Significant Bits constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,14),Register::ReadWriteAccess,unsigned> dstPerMsb{}; ///Stop On Done enum class SodVal { disable=0x00000000, ///<STOP ON DONE disabled, the descriptor fetch operation ignores DONE Field of CTRLA register. enable=0x00000001, ///<STOP ON DONE activated, the DMAC module is automatically disabled if DONE FIELD is set to 1. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,SodVal> sod{}; namespace SodValC{ constexpr Register::FieldValue<decltype(sod)::Type,SodVal::disable> disable{}; constexpr Register::FieldValue<decltype(sod)::Type,SodVal::enable> enable{}; } ///Interface Lock enum class LockifVal { disable=0x00000000, ///<Interface Lock capability is disabled enable=0x00000001, ///<Interface Lock capability is enabled }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,LockifVal> lockIf{}; namespace LockifValC{ constexpr Register::FieldValue<decltype(lockIf)::Type,LockifVal::disable> disable{}; constexpr Register::FieldValue<decltype(lockIf)::Type,LockifVal::enable> enable{}; } ///Bus Lock enum class LockbVal { disable=0x00000000, ///<AHB Bus Locking capability is disabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,LockbVal> lockB{}; namespace LockbValC{ constexpr Register::FieldValue<decltype(lockB)::Type,LockbVal::disable> disable{}; } ///Master Interface Arbiter Lock enum class LockiflVal { chunk=0x00000000, ///<The Master Interface Arbiter is locked by the channel x for a chunk transfer. buffer=0x00000001, ///<The Master Interface Arbiter is locked by the channel x for a buffer transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,LockiflVal> lockIfL{}; namespace LockiflValC{ constexpr Register::FieldValue<decltype(lockIfL)::Type,LockiflVal::chunk> chunk{}; constexpr Register::FieldValue<decltype(lockIfL)::Type,LockiflVal::buffer> buffer{}; } ///AHB Protection constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,24),Register::ReadWriteAccess,unsigned> ahbProt{}; ///FIFO Configuration enum class FifocfgVal { alapCfg=0x00000000, ///<The largest defined length AHB burst is performed on the destination AHB interface. halfCfg=0x00000001, ///<When half FIFO size is available/filled, a source/destination request is serviced. asapCfg=0x00000002, ///<When there is enough space/data available to perform a single AHB access, then the request is serviced. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,FifocfgVal> fifocfg{}; namespace FifocfgValC{ constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::alapCfg> alapCfg{}; constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::halfCfg> halfCfg{}; constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::asapCfg> asapCfg{}; } } namespace Dmac0Spip0{ ///<DMAC Channel Source Picture-in-Picture Configuration Register (ch_num = 0) using Addr = Register::Address<0xffffe654,0xfc000000,0x00000000,std::uint32_t>; ///Source Picture-in-Picture Hole constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> spipHole{}; ///Source Picture-in-Picture Boundary constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,16),Register::ReadWriteAccess,unsigned> spipBoundary{}; } namespace Dmac0Dpip0{ ///<DMAC Channel Destination Picture-in-Picture Configuration Register (ch_num = 0) using Addr = Register::Address<0xffffe658,0xfc000000,0x00000000,std::uint32_t>; ///Destination Picture-in-Picture Hole constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> dpipHole{}; ///Destination Picture-in-Picture Boundary constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,16),Register::ReadWriteAccess,unsigned> dpipBoundary{}; } namespace Dmac0Saddr1{ ///<DMAC Channel Source Address Register (ch_num = 1) using Addr = Register::Address<0xffffe664,0x00000000,0x00000000,std::uint32_t>; ///Channel x Source Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> saddr{}; } namespace Dmac0Daddr1{ ///<DMAC Channel Destination Address Register (ch_num = 1) using Addr = Register::Address<0xffffe668,0x00000000,0x00000000,std::uint32_t>; ///Channel x Destination Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> daddr{}; } namespace Dmac0Dscr1{ ///<DMAC Channel Descriptor Address Register (ch_num = 1) using Addr = Register::Address<0xffffe66c,0x00000000,0x00000000,std::uint32_t>; ///Descriptor Interface Selection enum class DscrifVal { ahbIf0=0x00000000, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 0 ahbIf1=0x00000001, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 1 ahbIf2=0x00000002, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,DscrifVal> dscrIf{}; namespace DscrifValC{ constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf2> ahbIf2{}; } ///Buffer Transfer Descriptor Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,2),Register::ReadWriteAccess,unsigned> dscr{}; } namespace Dmac0Ctrla1{ ///<DMAC Channel Control A Register (ch_num = 1) using Addr = Register::Address<0xffffe670,0x4c880000,0x00000000,std::uint32_t>; ///Buffer Transfer Size constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> btsize{}; ///Source Chunk Transfer Size. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,16),Register::ReadWriteAccess,unsigned> scsize{}; ///Destination Chunk Transfer Size constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,20),Register::ReadWriteAccess,unsigned> dcsize{}; ///Transfer Width for the Source enum class SrcwidthVal { byte=0x00000000, ///<the transfer size is set to 8-bit width halfWord=0x00000001, ///<the transfer size is set to 16-bit width word=0x00000002, ///<the transfer size is set to 32-bit width dword=0x00000003, ///<the transfer size is set to 64-bit width }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,SrcwidthVal> srcWidth{}; namespace SrcwidthValC{ constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::byte> byte{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::halfWord> halfWord{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::word> word{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::dword> dword{}; } ///Transfer Width for the Destination enum class DstwidthVal { byte=0x00000000, ///<the transfer size is set to 8-bit width halfWord=0x00000001, ///<the transfer size is set to 16-bit width word=0x00000002, ///<the transfer size is set to 32-bit width dword=0x00000003, ///<the transfer size is set to 64-bit width }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,DstwidthVal> dstWidth{}; namespace DstwidthValC{ constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::byte> byte{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::halfWord> halfWord{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::word> word{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::dword> dword{}; } ///Current Descriptor Stop Command and Transfer Completed Memory Indicator constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> done{}; } namespace Dmac0Ctrlb1{ ///<DMAC Channel Control B Register (ch_num = 1) using Addr = Register::Address<0xffffe674,0x0c8eeecc,0x00000000,std::uint32_t>; ///Source Interface Selection Field enum class SifVal { ahbIf0=0x00000000, ///<The source transfer is done via AHB_Lite Interface 0 ahbIf1=0x00000001, ///<The source transfer is done via AHB_Lite Interface 1 ahbIf2=0x00000002, ///<The source transfer is done via AHB_Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,SifVal> sif{}; namespace SifValC{ constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf2> ahbIf2{}; } ///Destination Interface Selection Field enum class DifVal { ahbIf0=0x00000000, ///<The destination transfer is done via AHB_Lite Interface 0 ahbIf1=0x00000001, ///<The destination transfer is done via AHB_Lite Interface 1 ahbIf2=0x00000002, ///<The destination transfer is done via AHB_Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,DifVal> dif{}; namespace DifValC{ constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf2> ahbIf2{}; } ///Source Picture-in-Picture Mode enum class SrcpipVal { disable=0x00000000, ///<Picture-in-Picture mode is disabled. The source data area is contiguous. enable=0x00000001, ///<Picture-in-Picture mode is enabled. When the source PIP counter reaches the programmable boundary, the address is automatically incremented by a user defined amount. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SrcpipVal> srcPip{}; namespace SrcpipValC{ constexpr Register::FieldValue<decltype(srcPip)::Type,SrcpipVal::disable> disable{}; constexpr Register::FieldValue<decltype(srcPip)::Type,SrcpipVal::enable> enable{}; } ///Destination Picture-in-Picture Mode enum class DstpipVal { disable=0x00000000, ///<Picture-in-Picture mode is disabled. The Destination data area is contiguous. enable=0x00000001, ///<Picture-in-Picture mode is enabled. When the Destination PIP counter reaches the programmable boundary the address is automatically incremented by a user-defined amount. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,DstpipVal> dstPip{}; namespace DstpipValC{ constexpr Register::FieldValue<decltype(dstPip)::Type,DstpipVal::disable> disable{}; constexpr Register::FieldValue<decltype(dstPip)::Type,DstpipVal::enable> enable{}; } ///Source Address Descriptor enum class SrcdscrVal { fetchFromMem=0x00000000, ///<Source address is updated when the descriptor is fetched from the memory. fetchDisable=0x00000001, ///<Buffer Descriptor Fetch operation is disabled for the source. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,SrcdscrVal> srcDscr{}; namespace SrcdscrValC{ constexpr Register::FieldValue<decltype(srcDscr)::Type,SrcdscrVal::fetchFromMem> fetchFromMem{}; constexpr Register::FieldValue<decltype(srcDscr)::Type,SrcdscrVal::fetchDisable> fetchDisable{}; } ///Destination Address Descriptor enum class DstdscrVal { fetchFromMem=0x00000000, ///<Destination address is updated when the descriptor is fetched from the memory. fetchDisable=0x00000001, ///<Buffer Descriptor Fetch operation is disabled for the destination. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,DstdscrVal> dstDscr{}; namespace DstdscrValC{ constexpr Register::FieldValue<decltype(dstDscr)::Type,DstdscrVal::fetchFromMem> fetchFromMem{}; constexpr Register::FieldValue<decltype(dstDscr)::Type,DstdscrVal::fetchDisable> fetchDisable{}; } ///Flow Control enum class FcVal { mem2memDmaFc=0x00000000, ///<Memory-to-Memory Transfer DMAC is flow controller mem2perDmaFc=0x00000001, ///<Memory-to-Peripheral Transfer DMAC is flow controller per2memDmaFc=0x00000002, ///<Peripheral-to-Memory Transfer DMAC is flow controller per2perDmaFc=0x00000003, ///<Peripheral-to-Peripheral Transfer DMAC is flow controller }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,21),Register::ReadWriteAccess,FcVal> fc{}; namespace FcValC{ constexpr Register::FieldValue<decltype(fc)::Type,FcVal::mem2memDmaFc> mem2memDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::mem2perDmaFc> mem2perDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::per2memDmaFc> per2memDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::per2perDmaFc> per2perDmaFc{}; } ///Incrementing, Decrementing or Fixed Address for the Source enum class SrcincrVal { incrementing=0x00000000, ///<The source address is incremented decrementing=0x00000001, ///<The source address is decremented fixed=0x00000002, ///<The source address remains unchanged }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,SrcincrVal> srcIncr{}; namespace SrcincrValC{ constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::incrementing> incrementing{}; constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::decrementing> decrementing{}; constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::fixed> fixed{}; } ///Incrementing, Decrementing or Fixed Address for the Destination enum class DstincrVal { incrementing=0x00000000, ///<The destination address is incremented decrementing=0x00000001, ///<The destination address is decremented fixed=0x00000002, ///<The destination address remains unchanged }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,DstincrVal> dstIncr{}; namespace DstincrValC{ constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::incrementing> incrementing{}; constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::decrementing> decrementing{}; constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::fixed> fixed{}; } ///Interrupt Enable Not constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> ien{}; ///Automatic Multiple Buffer Transfer enum class Auto_Val { disable=0x00000000, ///<Automatic multiple buffer transfer is disabled. enable=0x00000001, ///<Automatic multiple buffer transfer is enabled. This bit enables replay mode or contiguous mode when several buffers are transferred. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,Auto_Val> auto_{}; namespace Auto_ValC{ constexpr Register::FieldValue<decltype(auto_)::Type,Auto_Val::disable> disable{}; constexpr Register::FieldValue<decltype(auto_)::Type,Auto_Val::enable> enable{}; } } namespace Dmac0Cfg1{ ///<DMAC Channel Configuration Register (ch_num = 1) using Addr = Register::Address<0xffffe678,0xc88e0000,0x00000000,std::uint32_t>; ///Source with Peripheral identifier constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> srcPer{}; ///Destination with Peripheral identifier constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,4),Register::ReadWriteAccess,unsigned> dstPer{}; ///Source Reloaded from Previous enum class SrcrepVal { contiguousAddr=0x00000000, ///<When automatic mode is activated, source address is contiguous between two buffers. reloadAddr=0x00000001, ///<When automatic mode is activated, the source address and the control register are reloaded from previous transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SrcrepVal> srcRep{}; namespace SrcrepValC{ constexpr Register::FieldValue<decltype(srcRep)::Type,SrcrepVal::contiguousAddr> contiguousAddr{}; constexpr Register::FieldValue<decltype(srcRep)::Type,SrcrepVal::reloadAddr> reloadAddr{}; } ///Software or Hardware Selection for the Source enum class Srch2selVal { sw=0x00000000, ///<Software handshaking interface is used to trigger a transfer request. hw=0x00000001, ///<Hardware handshaking interface is used to trigger a transfer request. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,Srch2selVal> srcH2sel{}; namespace Srch2selValC{ constexpr Register::FieldValue<decltype(srcH2sel)::Type,Srch2selVal::sw> sw{}; constexpr Register::FieldValue<decltype(srcH2sel)::Type,Srch2selVal::hw> hw{}; } ///SRC_PER Most Significant Bits constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,10),Register::ReadWriteAccess,unsigned> srcPerMsb{}; ///Destination Reloaded from Previous enum class DstrepVal { contiguousAddr=0x00000000, ///<When automatic mode is activated, destination address is contiguous between two buffers. reloadAddr=0x00000001, ///<When automatic mode is activated, the destination and the control register are reloaded from the pre-vious transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,DstrepVal> dstRep{}; namespace DstrepValC{ constexpr Register::FieldValue<decltype(dstRep)::Type,DstrepVal::contiguousAddr> contiguousAddr{}; constexpr Register::FieldValue<decltype(dstRep)::Type,DstrepVal::reloadAddr> reloadAddr{}; } ///Software or Hardware Selection for the Destination enum class Dsth2selVal { sw=0x00000000, ///<Software handshaking interface is used to trigger a transfer request. hw=0x00000001, ///<Hardware handshaking interface is used to trigger a transfer request. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,Dsth2selVal> dstH2sel{}; namespace Dsth2selValC{ constexpr Register::FieldValue<decltype(dstH2sel)::Type,Dsth2selVal::sw> sw{}; constexpr Register::FieldValue<decltype(dstH2sel)::Type,Dsth2selVal::hw> hw{}; } ///DST_PER Most Significant Bits constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,14),Register::ReadWriteAccess,unsigned> dstPerMsb{}; ///Stop On Done enum class SodVal { disable=0x00000000, ///<STOP ON DONE disabled, the descriptor fetch operation ignores DONE Field of CTRLA register. enable=0x00000001, ///<STOP ON DONE activated, the DMAC module is automatically disabled if DONE FIELD is set to 1. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,SodVal> sod{}; namespace SodValC{ constexpr Register::FieldValue<decltype(sod)::Type,SodVal::disable> disable{}; constexpr Register::FieldValue<decltype(sod)::Type,SodVal::enable> enable{}; } ///Interface Lock enum class LockifVal { disable=0x00000000, ///<Interface Lock capability is disabled enable=0x00000001, ///<Interface Lock capability is enabled }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,LockifVal> lockIf{}; namespace LockifValC{ constexpr Register::FieldValue<decltype(lockIf)::Type,LockifVal::disable> disable{}; constexpr Register::FieldValue<decltype(lockIf)::Type,LockifVal::enable> enable{}; } ///Bus Lock enum class LockbVal { disable=0x00000000, ///<AHB Bus Locking capability is disabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,LockbVal> lockB{}; namespace LockbValC{ constexpr Register::FieldValue<decltype(lockB)::Type,LockbVal::disable> disable{}; } ///Master Interface Arbiter Lock enum class LockiflVal { chunk=0x00000000, ///<The Master Interface Arbiter is locked by the channel x for a chunk transfer. buffer=0x00000001, ///<The Master Interface Arbiter is locked by the channel x for a buffer transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,LockiflVal> lockIfL{}; namespace LockiflValC{ constexpr Register::FieldValue<decltype(lockIfL)::Type,LockiflVal::chunk> chunk{}; constexpr Register::FieldValue<decltype(lockIfL)::Type,LockiflVal::buffer> buffer{}; } ///AHB Protection constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,24),Register::ReadWriteAccess,unsigned> ahbProt{}; ///FIFO Configuration enum class FifocfgVal { alapCfg=0x00000000, ///<The largest defined length AHB burst is performed on the destination AHB interface. halfCfg=0x00000001, ///<When half FIFO size is available/filled, a source/destination request is serviced. asapCfg=0x00000002, ///<When there is enough space/data available to perform a single AHB access, then the request is serviced. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,FifocfgVal> fifocfg{}; namespace FifocfgValC{ constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::alapCfg> alapCfg{}; constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::halfCfg> halfCfg{}; constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::asapCfg> asapCfg{}; } } namespace Dmac0Spip1{ ///<DMAC Channel Source Picture-in-Picture Configuration Register (ch_num = 1) using Addr = Register::Address<0xffffe67c,0xfc000000,0x00000000,std::uint32_t>; ///Source Picture-in-Picture Hole constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> spipHole{}; ///Source Picture-in-Picture Boundary constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,16),Register::ReadWriteAccess,unsigned> spipBoundary{}; } namespace Dmac0Dpip1{ ///<DMAC Channel Destination Picture-in-Picture Configuration Register (ch_num = 1) using Addr = Register::Address<0xffffe680,0xfc000000,0x00000000,std::uint32_t>; ///Destination Picture-in-Picture Hole constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> dpipHole{}; ///Destination Picture-in-Picture Boundary constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,16),Register::ReadWriteAccess,unsigned> dpipBoundary{}; } namespace Dmac0Saddr2{ ///<DMAC Channel Source Address Register (ch_num = 2) using Addr = Register::Address<0xffffe68c,0x00000000,0x00000000,std::uint32_t>; ///Channel x Source Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> saddr{}; } namespace Dmac0Daddr2{ ///<DMAC Channel Destination Address Register (ch_num = 2) using Addr = Register::Address<0xffffe690,0x00000000,0x00000000,std::uint32_t>; ///Channel x Destination Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> daddr{}; } namespace Dmac0Dscr2{ ///<DMAC Channel Descriptor Address Register (ch_num = 2) using Addr = Register::Address<0xffffe694,0x00000000,0x00000000,std::uint32_t>; ///Descriptor Interface Selection enum class DscrifVal { ahbIf0=0x00000000, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 0 ahbIf1=0x00000001, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 1 ahbIf2=0x00000002, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,DscrifVal> dscrIf{}; namespace DscrifValC{ constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf2> ahbIf2{}; } ///Buffer Transfer Descriptor Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,2),Register::ReadWriteAccess,unsigned> dscr{}; } namespace Dmac0Ctrla2{ ///<DMAC Channel Control A Register (ch_num = 2) using Addr = Register::Address<0xffffe698,0x4c880000,0x00000000,std::uint32_t>; ///Buffer Transfer Size constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> btsize{}; ///Source Chunk Transfer Size. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,16),Register::ReadWriteAccess,unsigned> scsize{}; ///Destination Chunk Transfer Size constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,20),Register::ReadWriteAccess,unsigned> dcsize{}; ///Transfer Width for the Source enum class SrcwidthVal { byte=0x00000000, ///<the transfer size is set to 8-bit width halfWord=0x00000001, ///<the transfer size is set to 16-bit width word=0x00000002, ///<the transfer size is set to 32-bit width dword=0x00000003, ///<the transfer size is set to 64-bit width }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,SrcwidthVal> srcWidth{}; namespace SrcwidthValC{ constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::byte> byte{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::halfWord> halfWord{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::word> word{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::dword> dword{}; } ///Transfer Width for the Destination enum class DstwidthVal { byte=0x00000000, ///<the transfer size is set to 8-bit width halfWord=0x00000001, ///<the transfer size is set to 16-bit width word=0x00000002, ///<the transfer size is set to 32-bit width dword=0x00000003, ///<the transfer size is set to 64-bit width }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,DstwidthVal> dstWidth{}; namespace DstwidthValC{ constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::byte> byte{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::halfWord> halfWord{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::word> word{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::dword> dword{}; } ///Current Descriptor Stop Command and Transfer Completed Memory Indicator constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> done{}; } namespace Dmac0Ctrlb2{ ///<DMAC Channel Control B Register (ch_num = 2) using Addr = Register::Address<0xffffe69c,0x0c8eeecc,0x00000000,std::uint32_t>; ///Source Interface Selection Field enum class SifVal { ahbIf0=0x00000000, ///<The source transfer is done via AHB_Lite Interface 0 ahbIf1=0x00000001, ///<The source transfer is done via AHB_Lite Interface 1 ahbIf2=0x00000002, ///<The source transfer is done via AHB_Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,SifVal> sif{}; namespace SifValC{ constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf2> ahbIf2{}; } ///Destination Interface Selection Field enum class DifVal { ahbIf0=0x00000000, ///<The destination transfer is done via AHB_Lite Interface 0 ahbIf1=0x00000001, ///<The destination transfer is done via AHB_Lite Interface 1 ahbIf2=0x00000002, ///<The destination transfer is done via AHB_Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,DifVal> dif{}; namespace DifValC{ constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf2> ahbIf2{}; } ///Source Picture-in-Picture Mode enum class SrcpipVal { disable=0x00000000, ///<Picture-in-Picture mode is disabled. The source data area is contiguous. enable=0x00000001, ///<Picture-in-Picture mode is enabled. When the source PIP counter reaches the programmable boundary, the address is automatically incremented by a user defined amount. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SrcpipVal> srcPip{}; namespace SrcpipValC{ constexpr Register::FieldValue<decltype(srcPip)::Type,SrcpipVal::disable> disable{}; constexpr Register::FieldValue<decltype(srcPip)::Type,SrcpipVal::enable> enable{}; } ///Destination Picture-in-Picture Mode enum class DstpipVal { disable=0x00000000, ///<Picture-in-Picture mode is disabled. The Destination data area is contiguous. enable=0x00000001, ///<Picture-in-Picture mode is enabled. When the Destination PIP counter reaches the programmable boundary the address is automatically incremented by a user-defined amount. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,DstpipVal> dstPip{}; namespace DstpipValC{ constexpr Register::FieldValue<decltype(dstPip)::Type,DstpipVal::disable> disable{}; constexpr Register::FieldValue<decltype(dstPip)::Type,DstpipVal::enable> enable{}; } ///Source Address Descriptor enum class SrcdscrVal { fetchFromMem=0x00000000, ///<Source address is updated when the descriptor is fetched from the memory. fetchDisable=0x00000001, ///<Buffer Descriptor Fetch operation is disabled for the source. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,SrcdscrVal> srcDscr{}; namespace SrcdscrValC{ constexpr Register::FieldValue<decltype(srcDscr)::Type,SrcdscrVal::fetchFromMem> fetchFromMem{}; constexpr Register::FieldValue<decltype(srcDscr)::Type,SrcdscrVal::fetchDisable> fetchDisable{}; } ///Destination Address Descriptor enum class DstdscrVal { fetchFromMem=0x00000000, ///<Destination address is updated when the descriptor is fetched from the memory. fetchDisable=0x00000001, ///<Buffer Descriptor Fetch operation is disabled for the destination. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,DstdscrVal> dstDscr{}; namespace DstdscrValC{ constexpr Register::FieldValue<decltype(dstDscr)::Type,DstdscrVal::fetchFromMem> fetchFromMem{}; constexpr Register::FieldValue<decltype(dstDscr)::Type,DstdscrVal::fetchDisable> fetchDisable{}; } ///Flow Control enum class FcVal { mem2memDmaFc=0x00000000, ///<Memory-to-Memory Transfer DMAC is flow controller mem2perDmaFc=0x00000001, ///<Memory-to-Peripheral Transfer DMAC is flow controller per2memDmaFc=0x00000002, ///<Peripheral-to-Memory Transfer DMAC is flow controller per2perDmaFc=0x00000003, ///<Peripheral-to-Peripheral Transfer DMAC is flow controller }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,21),Register::ReadWriteAccess,FcVal> fc{}; namespace FcValC{ constexpr Register::FieldValue<decltype(fc)::Type,FcVal::mem2memDmaFc> mem2memDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::mem2perDmaFc> mem2perDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::per2memDmaFc> per2memDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::per2perDmaFc> per2perDmaFc{}; } ///Incrementing, Decrementing or Fixed Address for the Source enum class SrcincrVal { incrementing=0x00000000, ///<The source address is incremented decrementing=0x00000001, ///<The source address is decremented fixed=0x00000002, ///<The source address remains unchanged }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,SrcincrVal> srcIncr{}; namespace SrcincrValC{ constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::incrementing> incrementing{}; constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::decrementing> decrementing{}; constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::fixed> fixed{}; } ///Incrementing, Decrementing or Fixed Address for the Destination enum class DstincrVal { incrementing=0x00000000, ///<The destination address is incremented decrementing=0x00000001, ///<The destination address is decremented fixed=0x00000002, ///<The destination address remains unchanged }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,DstincrVal> dstIncr{}; namespace DstincrValC{ constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::incrementing> incrementing{}; constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::decrementing> decrementing{}; constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::fixed> fixed{}; } ///Interrupt Enable Not constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> ien{}; ///Automatic Multiple Buffer Transfer enum class Auto_Val { disable=0x00000000, ///<Automatic multiple buffer transfer is disabled. enable=0x00000001, ///<Automatic multiple buffer transfer is enabled. This bit enables replay mode or contiguous mode when several buffers are transferred. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,Auto_Val> auto_{}; namespace Auto_ValC{ constexpr Register::FieldValue<decltype(auto_)::Type,Auto_Val::disable> disable{}; constexpr Register::FieldValue<decltype(auto_)::Type,Auto_Val::enable> enable{}; } } namespace Dmac0Cfg2{ ///<DMAC Channel Configuration Register (ch_num = 2) using Addr = Register::Address<0xffffe6a0,0xc88e0000,0x00000000,std::uint32_t>; ///Source with Peripheral identifier constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> srcPer{}; ///Destination with Peripheral identifier constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,4),Register::ReadWriteAccess,unsigned> dstPer{}; ///Source Reloaded from Previous enum class SrcrepVal { contiguousAddr=0x00000000, ///<When automatic mode is activated, source address is contiguous between two buffers. reloadAddr=0x00000001, ///<When automatic mode is activated, the source address and the control register are reloaded from previous transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SrcrepVal> srcRep{}; namespace SrcrepValC{ constexpr Register::FieldValue<decltype(srcRep)::Type,SrcrepVal::contiguousAddr> contiguousAddr{}; constexpr Register::FieldValue<decltype(srcRep)::Type,SrcrepVal::reloadAddr> reloadAddr{}; } ///Software or Hardware Selection for the Source enum class Srch2selVal { sw=0x00000000, ///<Software handshaking interface is used to trigger a transfer request. hw=0x00000001, ///<Hardware handshaking interface is used to trigger a transfer request. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,Srch2selVal> srcH2sel{}; namespace Srch2selValC{ constexpr Register::FieldValue<decltype(srcH2sel)::Type,Srch2selVal::sw> sw{}; constexpr Register::FieldValue<decltype(srcH2sel)::Type,Srch2selVal::hw> hw{}; } ///SRC_PER Most Significant Bits constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,10),Register::ReadWriteAccess,unsigned> srcPerMsb{}; ///Destination Reloaded from Previous enum class DstrepVal { contiguousAddr=0x00000000, ///<When automatic mode is activated, destination address is contiguous between two buffers. reloadAddr=0x00000001, ///<When automatic mode is activated, the destination and the control register are reloaded from the pre-vious transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,DstrepVal> dstRep{}; namespace DstrepValC{ constexpr Register::FieldValue<decltype(dstRep)::Type,DstrepVal::contiguousAddr> contiguousAddr{}; constexpr Register::FieldValue<decltype(dstRep)::Type,DstrepVal::reloadAddr> reloadAddr{}; } ///Software or Hardware Selection for the Destination enum class Dsth2selVal { sw=0x00000000, ///<Software handshaking interface is used to trigger a transfer request. hw=0x00000001, ///<Hardware handshaking interface is used to trigger a transfer request. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,Dsth2selVal> dstH2sel{}; namespace Dsth2selValC{ constexpr Register::FieldValue<decltype(dstH2sel)::Type,Dsth2selVal::sw> sw{}; constexpr Register::FieldValue<decltype(dstH2sel)::Type,Dsth2selVal::hw> hw{}; } ///DST_PER Most Significant Bits constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,14),Register::ReadWriteAccess,unsigned> dstPerMsb{}; ///Stop On Done enum class SodVal { disable=0x00000000, ///<STOP ON DONE disabled, the descriptor fetch operation ignores DONE Field of CTRLA register. enable=0x00000001, ///<STOP ON DONE activated, the DMAC module is automatically disabled if DONE FIELD is set to 1. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,SodVal> sod{}; namespace SodValC{ constexpr Register::FieldValue<decltype(sod)::Type,SodVal::disable> disable{}; constexpr Register::FieldValue<decltype(sod)::Type,SodVal::enable> enable{}; } ///Interface Lock enum class LockifVal { disable=0x00000000, ///<Interface Lock capability is disabled enable=0x00000001, ///<Interface Lock capability is enabled }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,LockifVal> lockIf{}; namespace LockifValC{ constexpr Register::FieldValue<decltype(lockIf)::Type,LockifVal::disable> disable{}; constexpr Register::FieldValue<decltype(lockIf)::Type,LockifVal::enable> enable{}; } ///Bus Lock enum class LockbVal { disable=0x00000000, ///<AHB Bus Locking capability is disabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,LockbVal> lockB{}; namespace LockbValC{ constexpr Register::FieldValue<decltype(lockB)::Type,LockbVal::disable> disable{}; } ///Master Interface Arbiter Lock enum class LockiflVal { chunk=0x00000000, ///<The Master Interface Arbiter is locked by the channel x for a chunk transfer. buffer=0x00000001, ///<The Master Interface Arbiter is locked by the channel x for a buffer transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,LockiflVal> lockIfL{}; namespace LockiflValC{ constexpr Register::FieldValue<decltype(lockIfL)::Type,LockiflVal::chunk> chunk{}; constexpr Register::FieldValue<decltype(lockIfL)::Type,LockiflVal::buffer> buffer{}; } ///AHB Protection constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,24),Register::ReadWriteAccess,unsigned> ahbProt{}; ///FIFO Configuration enum class FifocfgVal { alapCfg=0x00000000, ///<The largest defined length AHB burst is performed on the destination AHB interface. halfCfg=0x00000001, ///<When half FIFO size is available/filled, a source/destination request is serviced. asapCfg=0x00000002, ///<When there is enough space/data available to perform a single AHB access, then the request is serviced. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,FifocfgVal> fifocfg{}; namespace FifocfgValC{ constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::alapCfg> alapCfg{}; constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::halfCfg> halfCfg{}; constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::asapCfg> asapCfg{}; } } namespace Dmac0Spip2{ ///<DMAC Channel Source Picture-in-Picture Configuration Register (ch_num = 2) using Addr = Register::Address<0xffffe6a4,0xfc000000,0x00000000,std::uint32_t>; ///Source Picture-in-Picture Hole constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> spipHole{}; ///Source Picture-in-Picture Boundary constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,16),Register::ReadWriteAccess,unsigned> spipBoundary{}; } namespace Dmac0Dpip2{ ///<DMAC Channel Destination Picture-in-Picture Configuration Register (ch_num = 2) using Addr = Register::Address<0xffffe6a8,0xfc000000,0x00000000,std::uint32_t>; ///Destination Picture-in-Picture Hole constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> dpipHole{}; ///Destination Picture-in-Picture Boundary constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,16),Register::ReadWriteAccess,unsigned> dpipBoundary{}; } namespace Dmac0Saddr3{ ///<DMAC Channel Source Address Register (ch_num = 3) using Addr = Register::Address<0xffffe6b4,0x00000000,0x00000000,std::uint32_t>; ///Channel x Source Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> saddr{}; } namespace Dmac0Daddr3{ ///<DMAC Channel Destination Address Register (ch_num = 3) using Addr = Register::Address<0xffffe6b8,0x00000000,0x00000000,std::uint32_t>; ///Channel x Destination Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> daddr{}; } namespace Dmac0Dscr3{ ///<DMAC Channel Descriptor Address Register (ch_num = 3) using Addr = Register::Address<0xffffe6bc,0x00000000,0x00000000,std::uint32_t>; ///Descriptor Interface Selection enum class DscrifVal { ahbIf0=0x00000000, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 0 ahbIf1=0x00000001, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 1 ahbIf2=0x00000002, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,DscrifVal> dscrIf{}; namespace DscrifValC{ constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf2> ahbIf2{}; } ///Buffer Transfer Descriptor Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,2),Register::ReadWriteAccess,unsigned> dscr{}; } namespace Dmac0Ctrla3{ ///<DMAC Channel Control A Register (ch_num = 3) using Addr = Register::Address<0xffffe6c0,0x4c880000,0x00000000,std::uint32_t>; ///Buffer Transfer Size constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> btsize{}; ///Source Chunk Transfer Size. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,16),Register::ReadWriteAccess,unsigned> scsize{}; ///Destination Chunk Transfer Size constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,20),Register::ReadWriteAccess,unsigned> dcsize{}; ///Transfer Width for the Source enum class SrcwidthVal { byte=0x00000000, ///<the transfer size is set to 8-bit width halfWord=0x00000001, ///<the transfer size is set to 16-bit width word=0x00000002, ///<the transfer size is set to 32-bit width dword=0x00000003, ///<the transfer size is set to 64-bit width }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,SrcwidthVal> srcWidth{}; namespace SrcwidthValC{ constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::byte> byte{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::halfWord> halfWord{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::word> word{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::dword> dword{}; } ///Transfer Width for the Destination enum class DstwidthVal { byte=0x00000000, ///<the transfer size is set to 8-bit width halfWord=0x00000001, ///<the transfer size is set to 16-bit width word=0x00000002, ///<the transfer size is set to 32-bit width dword=0x00000003, ///<the transfer size is set to 64-bit width }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,DstwidthVal> dstWidth{}; namespace DstwidthValC{ constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::byte> byte{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::halfWord> halfWord{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::word> word{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::dword> dword{}; } ///Current Descriptor Stop Command and Transfer Completed Memory Indicator constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> done{}; } namespace Dmac0Ctrlb3{ ///<DMAC Channel Control B Register (ch_num = 3) using Addr = Register::Address<0xffffe6c4,0x0c8eeecc,0x00000000,std::uint32_t>; ///Source Interface Selection Field enum class SifVal { ahbIf0=0x00000000, ///<The source transfer is done via AHB_Lite Interface 0 ahbIf1=0x00000001, ///<The source transfer is done via AHB_Lite Interface 1 ahbIf2=0x00000002, ///<The source transfer is done via AHB_Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,SifVal> sif{}; namespace SifValC{ constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf2> ahbIf2{}; } ///Destination Interface Selection Field enum class DifVal { ahbIf0=0x00000000, ///<The destination transfer is done via AHB_Lite Interface 0 ahbIf1=0x00000001, ///<The destination transfer is done via AHB_Lite Interface 1 ahbIf2=0x00000002, ///<The destination transfer is done via AHB_Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,DifVal> dif{}; namespace DifValC{ constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf2> ahbIf2{}; } ///Source Picture-in-Picture Mode enum class SrcpipVal { disable=0x00000000, ///<Picture-in-Picture mode is disabled. The source data area is contiguous. enable=0x00000001, ///<Picture-in-Picture mode is enabled. When the source PIP counter reaches the programmable boundary, the address is automatically incremented by a user defined amount. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SrcpipVal> srcPip{}; namespace SrcpipValC{ constexpr Register::FieldValue<decltype(srcPip)::Type,SrcpipVal::disable> disable{}; constexpr Register::FieldValue<decltype(srcPip)::Type,SrcpipVal::enable> enable{}; } ///Destination Picture-in-Picture Mode enum class DstpipVal { disable=0x00000000, ///<Picture-in-Picture mode is disabled. The Destination data area is contiguous. enable=0x00000001, ///<Picture-in-Picture mode is enabled. When the Destination PIP counter reaches the programmable boundary the address is automatically incremented by a user-defined amount. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,DstpipVal> dstPip{}; namespace DstpipValC{ constexpr Register::FieldValue<decltype(dstPip)::Type,DstpipVal::disable> disable{}; constexpr Register::FieldValue<decltype(dstPip)::Type,DstpipVal::enable> enable{}; } ///Source Address Descriptor enum class SrcdscrVal { fetchFromMem=0x00000000, ///<Source address is updated when the descriptor is fetched from the memory. fetchDisable=0x00000001, ///<Buffer Descriptor Fetch operation is disabled for the source. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,SrcdscrVal> srcDscr{}; namespace SrcdscrValC{ constexpr Register::FieldValue<decltype(srcDscr)::Type,SrcdscrVal::fetchFromMem> fetchFromMem{}; constexpr Register::FieldValue<decltype(srcDscr)::Type,SrcdscrVal::fetchDisable> fetchDisable{}; } ///Destination Address Descriptor enum class DstdscrVal { fetchFromMem=0x00000000, ///<Destination address is updated when the descriptor is fetched from the memory. fetchDisable=0x00000001, ///<Buffer Descriptor Fetch operation is disabled for the destination. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,DstdscrVal> dstDscr{}; namespace DstdscrValC{ constexpr Register::FieldValue<decltype(dstDscr)::Type,DstdscrVal::fetchFromMem> fetchFromMem{}; constexpr Register::FieldValue<decltype(dstDscr)::Type,DstdscrVal::fetchDisable> fetchDisable{}; } ///Flow Control enum class FcVal { mem2memDmaFc=0x00000000, ///<Memory-to-Memory Transfer DMAC is flow controller mem2perDmaFc=0x00000001, ///<Memory-to-Peripheral Transfer DMAC is flow controller per2memDmaFc=0x00000002, ///<Peripheral-to-Memory Transfer DMAC is flow controller per2perDmaFc=0x00000003, ///<Peripheral-to-Peripheral Transfer DMAC is flow controller }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,21),Register::ReadWriteAccess,FcVal> fc{}; namespace FcValC{ constexpr Register::FieldValue<decltype(fc)::Type,FcVal::mem2memDmaFc> mem2memDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::mem2perDmaFc> mem2perDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::per2memDmaFc> per2memDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::per2perDmaFc> per2perDmaFc{}; } ///Incrementing, Decrementing or Fixed Address for the Source enum class SrcincrVal { incrementing=0x00000000, ///<The source address is incremented decrementing=0x00000001, ///<The source address is decremented fixed=0x00000002, ///<The source address remains unchanged }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,SrcincrVal> srcIncr{}; namespace SrcincrValC{ constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::incrementing> incrementing{}; constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::decrementing> decrementing{}; constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::fixed> fixed{}; } ///Incrementing, Decrementing or Fixed Address for the Destination enum class DstincrVal { incrementing=0x00000000, ///<The destination address is incremented decrementing=0x00000001, ///<The destination address is decremented fixed=0x00000002, ///<The destination address remains unchanged }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,DstincrVal> dstIncr{}; namespace DstincrValC{ constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::incrementing> incrementing{}; constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::decrementing> decrementing{}; constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::fixed> fixed{}; } ///Interrupt Enable Not constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> ien{}; ///Automatic Multiple Buffer Transfer enum class Auto_Val { disable=0x00000000, ///<Automatic multiple buffer transfer is disabled. enable=0x00000001, ///<Automatic multiple buffer transfer is enabled. This bit enables replay mode or contiguous mode when several buffers are transferred. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,Auto_Val> auto_{}; namespace Auto_ValC{ constexpr Register::FieldValue<decltype(auto_)::Type,Auto_Val::disable> disable{}; constexpr Register::FieldValue<decltype(auto_)::Type,Auto_Val::enable> enable{}; } } namespace Dmac0Cfg3{ ///<DMAC Channel Configuration Register (ch_num = 3) using Addr = Register::Address<0xffffe6c8,0xc88e0000,0x00000000,std::uint32_t>; ///Source with Peripheral identifier constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> srcPer{}; ///Destination with Peripheral identifier constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,4),Register::ReadWriteAccess,unsigned> dstPer{}; ///Source Reloaded from Previous enum class SrcrepVal { contiguousAddr=0x00000000, ///<When automatic mode is activated, source address is contiguous between two buffers. reloadAddr=0x00000001, ///<When automatic mode is activated, the source address and the control register are reloaded from previous transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SrcrepVal> srcRep{}; namespace SrcrepValC{ constexpr Register::FieldValue<decltype(srcRep)::Type,SrcrepVal::contiguousAddr> contiguousAddr{}; constexpr Register::FieldValue<decltype(srcRep)::Type,SrcrepVal::reloadAddr> reloadAddr{}; } ///Software or Hardware Selection for the Source enum class Srch2selVal { sw=0x00000000, ///<Software handshaking interface is used to trigger a transfer request. hw=0x00000001, ///<Hardware handshaking interface is used to trigger a transfer request. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,Srch2selVal> srcH2sel{}; namespace Srch2selValC{ constexpr Register::FieldValue<decltype(srcH2sel)::Type,Srch2selVal::sw> sw{}; constexpr Register::FieldValue<decltype(srcH2sel)::Type,Srch2selVal::hw> hw{}; } ///SRC_PER Most Significant Bits constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,10),Register::ReadWriteAccess,unsigned> srcPerMsb{}; ///Destination Reloaded from Previous enum class DstrepVal { contiguousAddr=0x00000000, ///<When automatic mode is activated, destination address is contiguous between two buffers. reloadAddr=0x00000001, ///<When automatic mode is activated, the destination and the control register are reloaded from the pre-vious transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,DstrepVal> dstRep{}; namespace DstrepValC{ constexpr Register::FieldValue<decltype(dstRep)::Type,DstrepVal::contiguousAddr> contiguousAddr{}; constexpr Register::FieldValue<decltype(dstRep)::Type,DstrepVal::reloadAddr> reloadAddr{}; } ///Software or Hardware Selection for the Destination enum class Dsth2selVal { sw=0x00000000, ///<Software handshaking interface is used to trigger a transfer request. hw=0x00000001, ///<Hardware handshaking interface is used to trigger a transfer request. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,Dsth2selVal> dstH2sel{}; namespace Dsth2selValC{ constexpr Register::FieldValue<decltype(dstH2sel)::Type,Dsth2selVal::sw> sw{}; constexpr Register::FieldValue<decltype(dstH2sel)::Type,Dsth2selVal::hw> hw{}; } ///DST_PER Most Significant Bits constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,14),Register::ReadWriteAccess,unsigned> dstPerMsb{}; ///Stop On Done enum class SodVal { disable=0x00000000, ///<STOP ON DONE disabled, the descriptor fetch operation ignores DONE Field of CTRLA register. enable=0x00000001, ///<STOP ON DONE activated, the DMAC module is automatically disabled if DONE FIELD is set to 1. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,SodVal> sod{}; namespace SodValC{ constexpr Register::FieldValue<decltype(sod)::Type,SodVal::disable> disable{}; constexpr Register::FieldValue<decltype(sod)::Type,SodVal::enable> enable{}; } ///Interface Lock enum class LockifVal { disable=0x00000000, ///<Interface Lock capability is disabled enable=0x00000001, ///<Interface Lock capability is enabled }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,LockifVal> lockIf{}; namespace LockifValC{ constexpr Register::FieldValue<decltype(lockIf)::Type,LockifVal::disable> disable{}; constexpr Register::FieldValue<decltype(lockIf)::Type,LockifVal::enable> enable{}; } ///Bus Lock enum class LockbVal { disable=0x00000000, ///<AHB Bus Locking capability is disabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,LockbVal> lockB{}; namespace LockbValC{ constexpr Register::FieldValue<decltype(lockB)::Type,LockbVal::disable> disable{}; } ///Master Interface Arbiter Lock enum class LockiflVal { chunk=0x00000000, ///<The Master Interface Arbiter is locked by the channel x for a chunk transfer. buffer=0x00000001, ///<The Master Interface Arbiter is locked by the channel x for a buffer transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,LockiflVal> lockIfL{}; namespace LockiflValC{ constexpr Register::FieldValue<decltype(lockIfL)::Type,LockiflVal::chunk> chunk{}; constexpr Register::FieldValue<decltype(lockIfL)::Type,LockiflVal::buffer> buffer{}; } ///AHB Protection constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,24),Register::ReadWriteAccess,unsigned> ahbProt{}; ///FIFO Configuration enum class FifocfgVal { alapCfg=0x00000000, ///<The largest defined length AHB burst is performed on the destination AHB interface. halfCfg=0x00000001, ///<When half FIFO size is available/filled, a source/destination request is serviced. asapCfg=0x00000002, ///<When there is enough space/data available to perform a single AHB access, then the request is serviced. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,FifocfgVal> fifocfg{}; namespace FifocfgValC{ constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::alapCfg> alapCfg{}; constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::halfCfg> halfCfg{}; constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::asapCfg> asapCfg{}; } } namespace Dmac0Spip3{ ///<DMAC Channel Source Picture-in-Picture Configuration Register (ch_num = 3) using Addr = Register::Address<0xffffe6cc,0xfc000000,0x00000000,std::uint32_t>; ///Source Picture-in-Picture Hole constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> spipHole{}; ///Source Picture-in-Picture Boundary constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,16),Register::ReadWriteAccess,unsigned> spipBoundary{}; } namespace Dmac0Dpip3{ ///<DMAC Channel Destination Picture-in-Picture Configuration Register (ch_num = 3) using Addr = Register::Address<0xffffe6d0,0xfc000000,0x00000000,std::uint32_t>; ///Destination Picture-in-Picture Hole constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> dpipHole{}; ///Destination Picture-in-Picture Boundary constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,16),Register::ReadWriteAccess,unsigned> dpipBoundary{}; } namespace Dmac0Saddr4{ ///<DMAC Channel Source Address Register (ch_num = 4) using Addr = Register::Address<0xffffe6dc,0x00000000,0x00000000,std::uint32_t>; ///Channel x Source Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> saddr{}; } namespace Dmac0Daddr4{ ///<DMAC Channel Destination Address Register (ch_num = 4) using Addr = Register::Address<0xffffe6e0,0x00000000,0x00000000,std::uint32_t>; ///Channel x Destination Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> daddr{}; } namespace Dmac0Dscr4{ ///<DMAC Channel Descriptor Address Register (ch_num = 4) using Addr = Register::Address<0xffffe6e4,0x00000000,0x00000000,std::uint32_t>; ///Descriptor Interface Selection enum class DscrifVal { ahbIf0=0x00000000, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 0 ahbIf1=0x00000001, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 1 ahbIf2=0x00000002, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,DscrifVal> dscrIf{}; namespace DscrifValC{ constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf2> ahbIf2{}; } ///Buffer Transfer Descriptor Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,2),Register::ReadWriteAccess,unsigned> dscr{}; } namespace Dmac0Ctrla4{ ///<DMAC Channel Control A Register (ch_num = 4) using Addr = Register::Address<0xffffe6e8,0x4c880000,0x00000000,std::uint32_t>; ///Buffer Transfer Size constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> btsize{}; ///Source Chunk Transfer Size. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,16),Register::ReadWriteAccess,unsigned> scsize{}; ///Destination Chunk Transfer Size constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,20),Register::ReadWriteAccess,unsigned> dcsize{}; ///Transfer Width for the Source enum class SrcwidthVal { byte=0x00000000, ///<the transfer size is set to 8-bit width halfWord=0x00000001, ///<the transfer size is set to 16-bit width word=0x00000002, ///<the transfer size is set to 32-bit width dword=0x00000003, ///<the transfer size is set to 64-bit width }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,SrcwidthVal> srcWidth{}; namespace SrcwidthValC{ constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::byte> byte{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::halfWord> halfWord{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::word> word{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::dword> dword{}; } ///Transfer Width for the Destination enum class DstwidthVal { byte=0x00000000, ///<the transfer size is set to 8-bit width halfWord=0x00000001, ///<the transfer size is set to 16-bit width word=0x00000002, ///<the transfer size is set to 32-bit width dword=0x00000003, ///<the transfer size is set to 64-bit width }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,DstwidthVal> dstWidth{}; namespace DstwidthValC{ constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::byte> byte{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::halfWord> halfWord{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::word> word{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::dword> dword{}; } ///Current Descriptor Stop Command and Transfer Completed Memory Indicator constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> done{}; } namespace Dmac0Ctrlb4{ ///<DMAC Channel Control B Register (ch_num = 4) using Addr = Register::Address<0xffffe6ec,0x0c8eeecc,0x00000000,std::uint32_t>; ///Source Interface Selection Field enum class SifVal { ahbIf0=0x00000000, ///<The source transfer is done via AHB_Lite Interface 0 ahbIf1=0x00000001, ///<The source transfer is done via AHB_Lite Interface 1 ahbIf2=0x00000002, ///<The source transfer is done via AHB_Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,SifVal> sif{}; namespace SifValC{ constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf2> ahbIf2{}; } ///Destination Interface Selection Field enum class DifVal { ahbIf0=0x00000000, ///<The destination transfer is done via AHB_Lite Interface 0 ahbIf1=0x00000001, ///<The destination transfer is done via AHB_Lite Interface 1 ahbIf2=0x00000002, ///<The destination transfer is done via AHB_Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,DifVal> dif{}; namespace DifValC{ constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf2> ahbIf2{}; } ///Source Picture-in-Picture Mode enum class SrcpipVal { disable=0x00000000, ///<Picture-in-Picture mode is disabled. The source data area is contiguous. enable=0x00000001, ///<Picture-in-Picture mode is enabled. When the source PIP counter reaches the programmable boundary, the address is automatically incremented by a user defined amount. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SrcpipVal> srcPip{}; namespace SrcpipValC{ constexpr Register::FieldValue<decltype(srcPip)::Type,SrcpipVal::disable> disable{}; constexpr Register::FieldValue<decltype(srcPip)::Type,SrcpipVal::enable> enable{}; } ///Destination Picture-in-Picture Mode enum class DstpipVal { disable=0x00000000, ///<Picture-in-Picture mode is disabled. The Destination data area is contiguous. enable=0x00000001, ///<Picture-in-Picture mode is enabled. When the Destination PIP counter reaches the programmable boundary the address is automatically incremented by a user-defined amount. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,DstpipVal> dstPip{}; namespace DstpipValC{ constexpr Register::FieldValue<decltype(dstPip)::Type,DstpipVal::disable> disable{}; constexpr Register::FieldValue<decltype(dstPip)::Type,DstpipVal::enable> enable{}; } ///Source Address Descriptor enum class SrcdscrVal { fetchFromMem=0x00000000, ///<Source address is updated when the descriptor is fetched from the memory. fetchDisable=0x00000001, ///<Buffer Descriptor Fetch operation is disabled for the source. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,SrcdscrVal> srcDscr{}; namespace SrcdscrValC{ constexpr Register::FieldValue<decltype(srcDscr)::Type,SrcdscrVal::fetchFromMem> fetchFromMem{}; constexpr Register::FieldValue<decltype(srcDscr)::Type,SrcdscrVal::fetchDisable> fetchDisable{}; } ///Destination Address Descriptor enum class DstdscrVal { fetchFromMem=0x00000000, ///<Destination address is updated when the descriptor is fetched from the memory. fetchDisable=0x00000001, ///<Buffer Descriptor Fetch operation is disabled for the destination. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,DstdscrVal> dstDscr{}; namespace DstdscrValC{ constexpr Register::FieldValue<decltype(dstDscr)::Type,DstdscrVal::fetchFromMem> fetchFromMem{}; constexpr Register::FieldValue<decltype(dstDscr)::Type,DstdscrVal::fetchDisable> fetchDisable{}; } ///Flow Control enum class FcVal { mem2memDmaFc=0x00000000, ///<Memory-to-Memory Transfer DMAC is flow controller mem2perDmaFc=0x00000001, ///<Memory-to-Peripheral Transfer DMAC is flow controller per2memDmaFc=0x00000002, ///<Peripheral-to-Memory Transfer DMAC is flow controller per2perDmaFc=0x00000003, ///<Peripheral-to-Peripheral Transfer DMAC is flow controller }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,21),Register::ReadWriteAccess,FcVal> fc{}; namespace FcValC{ constexpr Register::FieldValue<decltype(fc)::Type,FcVal::mem2memDmaFc> mem2memDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::mem2perDmaFc> mem2perDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::per2memDmaFc> per2memDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::per2perDmaFc> per2perDmaFc{}; } ///Incrementing, Decrementing or Fixed Address for the Source enum class SrcincrVal { incrementing=0x00000000, ///<The source address is incremented decrementing=0x00000001, ///<The source address is decremented fixed=0x00000002, ///<The source address remains unchanged }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,SrcincrVal> srcIncr{}; namespace SrcincrValC{ constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::incrementing> incrementing{}; constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::decrementing> decrementing{}; constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::fixed> fixed{}; } ///Incrementing, Decrementing or Fixed Address for the Destination enum class DstincrVal { incrementing=0x00000000, ///<The destination address is incremented decrementing=0x00000001, ///<The destination address is decremented fixed=0x00000002, ///<The destination address remains unchanged }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,DstincrVal> dstIncr{}; namespace DstincrValC{ constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::incrementing> incrementing{}; constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::decrementing> decrementing{}; constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::fixed> fixed{}; } ///Interrupt Enable Not constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> ien{}; ///Automatic Multiple Buffer Transfer enum class Auto_Val { disable=0x00000000, ///<Automatic multiple buffer transfer is disabled. enable=0x00000001, ///<Automatic multiple buffer transfer is enabled. This bit enables replay mode or contiguous mode when several buffers are transferred. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,Auto_Val> auto_{}; namespace Auto_ValC{ constexpr Register::FieldValue<decltype(auto_)::Type,Auto_Val::disable> disable{}; constexpr Register::FieldValue<decltype(auto_)::Type,Auto_Val::enable> enable{}; } } namespace Dmac0Cfg4{ ///<DMAC Channel Configuration Register (ch_num = 4) using Addr = Register::Address<0xffffe6f0,0xc88e0000,0x00000000,std::uint32_t>; ///Source with Peripheral identifier constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> srcPer{}; ///Destination with Peripheral identifier constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,4),Register::ReadWriteAccess,unsigned> dstPer{}; ///Source Reloaded from Previous enum class SrcrepVal { contiguousAddr=0x00000000, ///<When automatic mode is activated, source address is contiguous between two buffers. reloadAddr=0x00000001, ///<When automatic mode is activated, the source address and the control register are reloaded from previous transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SrcrepVal> srcRep{}; namespace SrcrepValC{ constexpr Register::FieldValue<decltype(srcRep)::Type,SrcrepVal::contiguousAddr> contiguousAddr{}; constexpr Register::FieldValue<decltype(srcRep)::Type,SrcrepVal::reloadAddr> reloadAddr{}; } ///Software or Hardware Selection for the Source enum class Srch2selVal { sw=0x00000000, ///<Software handshaking interface is used to trigger a transfer request. hw=0x00000001, ///<Hardware handshaking interface is used to trigger a transfer request. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,Srch2selVal> srcH2sel{}; namespace Srch2selValC{ constexpr Register::FieldValue<decltype(srcH2sel)::Type,Srch2selVal::sw> sw{}; constexpr Register::FieldValue<decltype(srcH2sel)::Type,Srch2selVal::hw> hw{}; } ///SRC_PER Most Significant Bits constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,10),Register::ReadWriteAccess,unsigned> srcPerMsb{}; ///Destination Reloaded from Previous enum class DstrepVal { contiguousAddr=0x00000000, ///<When automatic mode is activated, destination address is contiguous between two buffers. reloadAddr=0x00000001, ///<When automatic mode is activated, the destination and the control register are reloaded from the pre-vious transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,DstrepVal> dstRep{}; namespace DstrepValC{ constexpr Register::FieldValue<decltype(dstRep)::Type,DstrepVal::contiguousAddr> contiguousAddr{}; constexpr Register::FieldValue<decltype(dstRep)::Type,DstrepVal::reloadAddr> reloadAddr{}; } ///Software or Hardware Selection for the Destination enum class Dsth2selVal { sw=0x00000000, ///<Software handshaking interface is used to trigger a transfer request. hw=0x00000001, ///<Hardware handshaking interface is used to trigger a transfer request. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,Dsth2selVal> dstH2sel{}; namespace Dsth2selValC{ constexpr Register::FieldValue<decltype(dstH2sel)::Type,Dsth2selVal::sw> sw{}; constexpr Register::FieldValue<decltype(dstH2sel)::Type,Dsth2selVal::hw> hw{}; } ///DST_PER Most Significant Bits constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,14),Register::ReadWriteAccess,unsigned> dstPerMsb{}; ///Stop On Done enum class SodVal { disable=0x00000000, ///<STOP ON DONE disabled, the descriptor fetch operation ignores DONE Field of CTRLA register. enable=0x00000001, ///<STOP ON DONE activated, the DMAC module is automatically disabled if DONE FIELD is set to 1. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,SodVal> sod{}; namespace SodValC{ constexpr Register::FieldValue<decltype(sod)::Type,SodVal::disable> disable{}; constexpr Register::FieldValue<decltype(sod)::Type,SodVal::enable> enable{}; } ///Interface Lock enum class LockifVal { disable=0x00000000, ///<Interface Lock capability is disabled enable=0x00000001, ///<Interface Lock capability is enabled }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,LockifVal> lockIf{}; namespace LockifValC{ constexpr Register::FieldValue<decltype(lockIf)::Type,LockifVal::disable> disable{}; constexpr Register::FieldValue<decltype(lockIf)::Type,LockifVal::enable> enable{}; } ///Bus Lock enum class LockbVal { disable=0x00000000, ///<AHB Bus Locking capability is disabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,LockbVal> lockB{}; namespace LockbValC{ constexpr Register::FieldValue<decltype(lockB)::Type,LockbVal::disable> disable{}; } ///Master Interface Arbiter Lock enum class LockiflVal { chunk=0x00000000, ///<The Master Interface Arbiter is locked by the channel x for a chunk transfer. buffer=0x00000001, ///<The Master Interface Arbiter is locked by the channel x for a buffer transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,LockiflVal> lockIfL{}; namespace LockiflValC{ constexpr Register::FieldValue<decltype(lockIfL)::Type,LockiflVal::chunk> chunk{}; constexpr Register::FieldValue<decltype(lockIfL)::Type,LockiflVal::buffer> buffer{}; } ///AHB Protection constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,24),Register::ReadWriteAccess,unsigned> ahbProt{}; ///FIFO Configuration enum class FifocfgVal { alapCfg=0x00000000, ///<The largest defined length AHB burst is performed on the destination AHB interface. halfCfg=0x00000001, ///<When half FIFO size is available/filled, a source/destination request is serviced. asapCfg=0x00000002, ///<When there is enough space/data available to perform a single AHB access, then the request is serviced. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,FifocfgVal> fifocfg{}; namespace FifocfgValC{ constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::alapCfg> alapCfg{}; constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::halfCfg> halfCfg{}; constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::asapCfg> asapCfg{}; } } namespace Dmac0Spip4{ ///<DMAC Channel Source Picture-in-Picture Configuration Register (ch_num = 4) using Addr = Register::Address<0xffffe6f4,0xfc000000,0x00000000,std::uint32_t>; ///Source Picture-in-Picture Hole constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> spipHole{}; ///Source Picture-in-Picture Boundary constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,16),Register::ReadWriteAccess,unsigned> spipBoundary{}; } namespace Dmac0Dpip4{ ///<DMAC Channel Destination Picture-in-Picture Configuration Register (ch_num = 4) using Addr = Register::Address<0xffffe6f8,0xfc000000,0x00000000,std::uint32_t>; ///Destination Picture-in-Picture Hole constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> dpipHole{}; ///Destination Picture-in-Picture Boundary constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,16),Register::ReadWriteAccess,unsigned> dpipBoundary{}; } namespace Dmac0Saddr5{ ///<DMAC Channel Source Address Register (ch_num = 5) using Addr = Register::Address<0xffffe704,0x00000000,0x00000000,std::uint32_t>; ///Channel x Source Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> saddr{}; } namespace Dmac0Daddr5{ ///<DMAC Channel Destination Address Register (ch_num = 5) using Addr = Register::Address<0xffffe708,0x00000000,0x00000000,std::uint32_t>; ///Channel x Destination Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> daddr{}; } namespace Dmac0Dscr5{ ///<DMAC Channel Descriptor Address Register (ch_num = 5) using Addr = Register::Address<0xffffe70c,0x00000000,0x00000000,std::uint32_t>; ///Descriptor Interface Selection enum class DscrifVal { ahbIf0=0x00000000, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 0 ahbIf1=0x00000001, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 1 ahbIf2=0x00000002, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,DscrifVal> dscrIf{}; namespace DscrifValC{ constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf2> ahbIf2{}; } ///Buffer Transfer Descriptor Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,2),Register::ReadWriteAccess,unsigned> dscr{}; } namespace Dmac0Ctrla5{ ///<DMAC Channel Control A Register (ch_num = 5) using Addr = Register::Address<0xffffe710,0x4c880000,0x00000000,std::uint32_t>; ///Buffer Transfer Size constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> btsize{}; ///Source Chunk Transfer Size. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,16),Register::ReadWriteAccess,unsigned> scsize{}; ///Destination Chunk Transfer Size constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,20),Register::ReadWriteAccess,unsigned> dcsize{}; ///Transfer Width for the Source enum class SrcwidthVal { byte=0x00000000, ///<the transfer size is set to 8-bit width halfWord=0x00000001, ///<the transfer size is set to 16-bit width word=0x00000002, ///<the transfer size is set to 32-bit width dword=0x00000003, ///<the transfer size is set to 64-bit width }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,SrcwidthVal> srcWidth{}; namespace SrcwidthValC{ constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::byte> byte{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::halfWord> halfWord{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::word> word{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::dword> dword{}; } ///Transfer Width for the Destination enum class DstwidthVal { byte=0x00000000, ///<the transfer size is set to 8-bit width halfWord=0x00000001, ///<the transfer size is set to 16-bit width word=0x00000002, ///<the transfer size is set to 32-bit width dword=0x00000003, ///<the transfer size is set to 64-bit width }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,DstwidthVal> dstWidth{}; namespace DstwidthValC{ constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::byte> byte{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::halfWord> halfWord{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::word> word{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::dword> dword{}; } ///Current Descriptor Stop Command and Transfer Completed Memory Indicator constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> done{}; } namespace Dmac0Ctrlb5{ ///<DMAC Channel Control B Register (ch_num = 5) using Addr = Register::Address<0xffffe714,0x0c8eeecc,0x00000000,std::uint32_t>; ///Source Interface Selection Field enum class SifVal { ahbIf0=0x00000000, ///<The source transfer is done via AHB_Lite Interface 0 ahbIf1=0x00000001, ///<The source transfer is done via AHB_Lite Interface 1 ahbIf2=0x00000002, ///<The source transfer is done via AHB_Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,SifVal> sif{}; namespace SifValC{ constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf2> ahbIf2{}; } ///Destination Interface Selection Field enum class DifVal { ahbIf0=0x00000000, ///<The destination transfer is done via AHB_Lite Interface 0 ahbIf1=0x00000001, ///<The destination transfer is done via AHB_Lite Interface 1 ahbIf2=0x00000002, ///<The destination transfer is done via AHB_Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,DifVal> dif{}; namespace DifValC{ constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf2> ahbIf2{}; } ///Source Picture-in-Picture Mode enum class SrcpipVal { disable=0x00000000, ///<Picture-in-Picture mode is disabled. The source data area is contiguous. enable=0x00000001, ///<Picture-in-Picture mode is enabled. When the source PIP counter reaches the programmable boundary, the address is automatically incremented by a user defined amount. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SrcpipVal> srcPip{}; namespace SrcpipValC{ constexpr Register::FieldValue<decltype(srcPip)::Type,SrcpipVal::disable> disable{}; constexpr Register::FieldValue<decltype(srcPip)::Type,SrcpipVal::enable> enable{}; } ///Destination Picture-in-Picture Mode enum class DstpipVal { disable=0x00000000, ///<Picture-in-Picture mode is disabled. The Destination data area is contiguous. enable=0x00000001, ///<Picture-in-Picture mode is enabled. When the Destination PIP counter reaches the programmable boundary the address is automatically incremented by a user-defined amount. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,DstpipVal> dstPip{}; namespace DstpipValC{ constexpr Register::FieldValue<decltype(dstPip)::Type,DstpipVal::disable> disable{}; constexpr Register::FieldValue<decltype(dstPip)::Type,DstpipVal::enable> enable{}; } ///Source Address Descriptor enum class SrcdscrVal { fetchFromMem=0x00000000, ///<Source address is updated when the descriptor is fetched from the memory. fetchDisable=0x00000001, ///<Buffer Descriptor Fetch operation is disabled for the source. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,SrcdscrVal> srcDscr{}; namespace SrcdscrValC{ constexpr Register::FieldValue<decltype(srcDscr)::Type,SrcdscrVal::fetchFromMem> fetchFromMem{}; constexpr Register::FieldValue<decltype(srcDscr)::Type,SrcdscrVal::fetchDisable> fetchDisable{}; } ///Destination Address Descriptor enum class DstdscrVal { fetchFromMem=0x00000000, ///<Destination address is updated when the descriptor is fetched from the memory. fetchDisable=0x00000001, ///<Buffer Descriptor Fetch operation is disabled for the destination. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,DstdscrVal> dstDscr{}; namespace DstdscrValC{ constexpr Register::FieldValue<decltype(dstDscr)::Type,DstdscrVal::fetchFromMem> fetchFromMem{}; constexpr Register::FieldValue<decltype(dstDscr)::Type,DstdscrVal::fetchDisable> fetchDisable{}; } ///Flow Control enum class FcVal { mem2memDmaFc=0x00000000, ///<Memory-to-Memory Transfer DMAC is flow controller mem2perDmaFc=0x00000001, ///<Memory-to-Peripheral Transfer DMAC is flow controller per2memDmaFc=0x00000002, ///<Peripheral-to-Memory Transfer DMAC is flow controller per2perDmaFc=0x00000003, ///<Peripheral-to-Peripheral Transfer DMAC is flow controller }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,21),Register::ReadWriteAccess,FcVal> fc{}; namespace FcValC{ constexpr Register::FieldValue<decltype(fc)::Type,FcVal::mem2memDmaFc> mem2memDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::mem2perDmaFc> mem2perDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::per2memDmaFc> per2memDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::per2perDmaFc> per2perDmaFc{}; } ///Incrementing, Decrementing or Fixed Address for the Source enum class SrcincrVal { incrementing=0x00000000, ///<The source address is incremented decrementing=0x00000001, ///<The source address is decremented fixed=0x00000002, ///<The source address remains unchanged }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,SrcincrVal> srcIncr{}; namespace SrcincrValC{ constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::incrementing> incrementing{}; constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::decrementing> decrementing{}; constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::fixed> fixed{}; } ///Incrementing, Decrementing or Fixed Address for the Destination enum class DstincrVal { incrementing=0x00000000, ///<The destination address is incremented decrementing=0x00000001, ///<The destination address is decremented fixed=0x00000002, ///<The destination address remains unchanged }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,DstincrVal> dstIncr{}; namespace DstincrValC{ constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::incrementing> incrementing{}; constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::decrementing> decrementing{}; constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::fixed> fixed{}; } ///Interrupt Enable Not constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> ien{}; ///Automatic Multiple Buffer Transfer enum class Auto_Val { disable=0x00000000, ///<Automatic multiple buffer transfer is disabled. enable=0x00000001, ///<Automatic multiple buffer transfer is enabled. This bit enables replay mode or contiguous mode when several buffers are transferred. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,Auto_Val> auto_{}; namespace Auto_ValC{ constexpr Register::FieldValue<decltype(auto_)::Type,Auto_Val::disable> disable{}; constexpr Register::FieldValue<decltype(auto_)::Type,Auto_Val::enable> enable{}; } } namespace Dmac0Cfg5{ ///<DMAC Channel Configuration Register (ch_num = 5) using Addr = Register::Address<0xffffe718,0xc88e0000,0x00000000,std::uint32_t>; ///Source with Peripheral identifier constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> srcPer{}; ///Destination with Peripheral identifier constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,4),Register::ReadWriteAccess,unsigned> dstPer{}; ///Source Reloaded from Previous enum class SrcrepVal { contiguousAddr=0x00000000, ///<When automatic mode is activated, source address is contiguous between two buffers. reloadAddr=0x00000001, ///<When automatic mode is activated, the source address and the control register are reloaded from previous transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SrcrepVal> srcRep{}; namespace SrcrepValC{ constexpr Register::FieldValue<decltype(srcRep)::Type,SrcrepVal::contiguousAddr> contiguousAddr{}; constexpr Register::FieldValue<decltype(srcRep)::Type,SrcrepVal::reloadAddr> reloadAddr{}; } ///Software or Hardware Selection for the Source enum class Srch2selVal { sw=0x00000000, ///<Software handshaking interface is used to trigger a transfer request. hw=0x00000001, ///<Hardware handshaking interface is used to trigger a transfer request. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,Srch2selVal> srcH2sel{}; namespace Srch2selValC{ constexpr Register::FieldValue<decltype(srcH2sel)::Type,Srch2selVal::sw> sw{}; constexpr Register::FieldValue<decltype(srcH2sel)::Type,Srch2selVal::hw> hw{}; } ///SRC_PER Most Significant Bits constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,10),Register::ReadWriteAccess,unsigned> srcPerMsb{}; ///Destination Reloaded from Previous enum class DstrepVal { contiguousAddr=0x00000000, ///<When automatic mode is activated, destination address is contiguous between two buffers. reloadAddr=0x00000001, ///<When automatic mode is activated, the destination and the control register are reloaded from the pre-vious transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,DstrepVal> dstRep{}; namespace DstrepValC{ constexpr Register::FieldValue<decltype(dstRep)::Type,DstrepVal::contiguousAddr> contiguousAddr{}; constexpr Register::FieldValue<decltype(dstRep)::Type,DstrepVal::reloadAddr> reloadAddr{}; } ///Software or Hardware Selection for the Destination enum class Dsth2selVal { sw=0x00000000, ///<Software handshaking interface is used to trigger a transfer request. hw=0x00000001, ///<Hardware handshaking interface is used to trigger a transfer request. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,Dsth2selVal> dstH2sel{}; namespace Dsth2selValC{ constexpr Register::FieldValue<decltype(dstH2sel)::Type,Dsth2selVal::sw> sw{}; constexpr Register::FieldValue<decltype(dstH2sel)::Type,Dsth2selVal::hw> hw{}; } ///DST_PER Most Significant Bits constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,14),Register::ReadWriteAccess,unsigned> dstPerMsb{}; ///Stop On Done enum class SodVal { disable=0x00000000, ///<STOP ON DONE disabled, the descriptor fetch operation ignores DONE Field of CTRLA register. enable=0x00000001, ///<STOP ON DONE activated, the DMAC module is automatically disabled if DONE FIELD is set to 1. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,SodVal> sod{}; namespace SodValC{ constexpr Register::FieldValue<decltype(sod)::Type,SodVal::disable> disable{}; constexpr Register::FieldValue<decltype(sod)::Type,SodVal::enable> enable{}; } ///Interface Lock enum class LockifVal { disable=0x00000000, ///<Interface Lock capability is disabled enable=0x00000001, ///<Interface Lock capability is enabled }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,LockifVal> lockIf{}; namespace LockifValC{ constexpr Register::FieldValue<decltype(lockIf)::Type,LockifVal::disable> disable{}; constexpr Register::FieldValue<decltype(lockIf)::Type,LockifVal::enable> enable{}; } ///Bus Lock enum class LockbVal { disable=0x00000000, ///<AHB Bus Locking capability is disabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,LockbVal> lockB{}; namespace LockbValC{ constexpr Register::FieldValue<decltype(lockB)::Type,LockbVal::disable> disable{}; } ///Master Interface Arbiter Lock enum class LockiflVal { chunk=0x00000000, ///<The Master Interface Arbiter is locked by the channel x for a chunk transfer. buffer=0x00000001, ///<The Master Interface Arbiter is locked by the channel x for a buffer transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,LockiflVal> lockIfL{}; namespace LockiflValC{ constexpr Register::FieldValue<decltype(lockIfL)::Type,LockiflVal::chunk> chunk{}; constexpr Register::FieldValue<decltype(lockIfL)::Type,LockiflVal::buffer> buffer{}; } ///AHB Protection constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,24),Register::ReadWriteAccess,unsigned> ahbProt{}; ///FIFO Configuration enum class FifocfgVal { alapCfg=0x00000000, ///<The largest defined length AHB burst is performed on the destination AHB interface. halfCfg=0x00000001, ///<When half FIFO size is available/filled, a source/destination request is serviced. asapCfg=0x00000002, ///<When there is enough space/data available to perform a single AHB access, then the request is serviced. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,FifocfgVal> fifocfg{}; namespace FifocfgValC{ constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::alapCfg> alapCfg{}; constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::halfCfg> halfCfg{}; constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::asapCfg> asapCfg{}; } } namespace Dmac0Spip5{ ///<DMAC Channel Source Picture-in-Picture Configuration Register (ch_num = 5) using Addr = Register::Address<0xffffe71c,0xfc000000,0x00000000,std::uint32_t>; ///Source Picture-in-Picture Hole constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> spipHole{}; ///Source Picture-in-Picture Boundary constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,16),Register::ReadWriteAccess,unsigned> spipBoundary{}; } namespace Dmac0Dpip5{ ///<DMAC Channel Destination Picture-in-Picture Configuration Register (ch_num = 5) using Addr = Register::Address<0xffffe720,0xfc000000,0x00000000,std::uint32_t>; ///Destination Picture-in-Picture Hole constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> dpipHole{}; ///Destination Picture-in-Picture Boundary constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,16),Register::ReadWriteAccess,unsigned> dpipBoundary{}; } namespace Dmac0Saddr6{ ///<DMAC Channel Source Address Register (ch_num = 6) using Addr = Register::Address<0xffffe72c,0x00000000,0x00000000,std::uint32_t>; ///Channel x Source Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> saddr{}; } namespace Dmac0Daddr6{ ///<DMAC Channel Destination Address Register (ch_num = 6) using Addr = Register::Address<0xffffe730,0x00000000,0x00000000,std::uint32_t>; ///Channel x Destination Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> daddr{}; } namespace Dmac0Dscr6{ ///<DMAC Channel Descriptor Address Register (ch_num = 6) using Addr = Register::Address<0xffffe734,0x00000000,0x00000000,std::uint32_t>; ///Descriptor Interface Selection enum class DscrifVal { ahbIf0=0x00000000, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 0 ahbIf1=0x00000001, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 1 ahbIf2=0x00000002, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,DscrifVal> dscrIf{}; namespace DscrifValC{ constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf2> ahbIf2{}; } ///Buffer Transfer Descriptor Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,2),Register::ReadWriteAccess,unsigned> dscr{}; } namespace Dmac0Ctrla6{ ///<DMAC Channel Control A Register (ch_num = 6) using Addr = Register::Address<0xffffe738,0x4c880000,0x00000000,std::uint32_t>; ///Buffer Transfer Size constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> btsize{}; ///Source Chunk Transfer Size. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,16),Register::ReadWriteAccess,unsigned> scsize{}; ///Destination Chunk Transfer Size constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,20),Register::ReadWriteAccess,unsigned> dcsize{}; ///Transfer Width for the Source enum class SrcwidthVal { byte=0x00000000, ///<the transfer size is set to 8-bit width halfWord=0x00000001, ///<the transfer size is set to 16-bit width word=0x00000002, ///<the transfer size is set to 32-bit width dword=0x00000003, ///<the transfer size is set to 64-bit width }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,SrcwidthVal> srcWidth{}; namespace SrcwidthValC{ constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::byte> byte{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::halfWord> halfWord{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::word> word{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::dword> dword{}; } ///Transfer Width for the Destination enum class DstwidthVal { byte=0x00000000, ///<the transfer size is set to 8-bit width halfWord=0x00000001, ///<the transfer size is set to 16-bit width word=0x00000002, ///<the transfer size is set to 32-bit width dword=0x00000003, ///<the transfer size is set to 64-bit width }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,DstwidthVal> dstWidth{}; namespace DstwidthValC{ constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::byte> byte{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::halfWord> halfWord{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::word> word{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::dword> dword{}; } ///Current Descriptor Stop Command and Transfer Completed Memory Indicator constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> done{}; } namespace Dmac0Ctrlb6{ ///<DMAC Channel Control B Register (ch_num = 6) using Addr = Register::Address<0xffffe73c,0x0c8eeecc,0x00000000,std::uint32_t>; ///Source Interface Selection Field enum class SifVal { ahbIf0=0x00000000, ///<The source transfer is done via AHB_Lite Interface 0 ahbIf1=0x00000001, ///<The source transfer is done via AHB_Lite Interface 1 ahbIf2=0x00000002, ///<The source transfer is done via AHB_Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,SifVal> sif{}; namespace SifValC{ constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf2> ahbIf2{}; } ///Destination Interface Selection Field enum class DifVal { ahbIf0=0x00000000, ///<The destination transfer is done via AHB_Lite Interface 0 ahbIf1=0x00000001, ///<The destination transfer is done via AHB_Lite Interface 1 ahbIf2=0x00000002, ///<The destination transfer is done via AHB_Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,DifVal> dif{}; namespace DifValC{ constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf2> ahbIf2{}; } ///Source Picture-in-Picture Mode enum class SrcpipVal { disable=0x00000000, ///<Picture-in-Picture mode is disabled. The source data area is contiguous. enable=0x00000001, ///<Picture-in-Picture mode is enabled. When the source PIP counter reaches the programmable boundary, the address is automatically incremented by a user defined amount. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SrcpipVal> srcPip{}; namespace SrcpipValC{ constexpr Register::FieldValue<decltype(srcPip)::Type,SrcpipVal::disable> disable{}; constexpr Register::FieldValue<decltype(srcPip)::Type,SrcpipVal::enable> enable{}; } ///Destination Picture-in-Picture Mode enum class DstpipVal { disable=0x00000000, ///<Picture-in-Picture mode is disabled. The Destination data area is contiguous. enable=0x00000001, ///<Picture-in-Picture mode is enabled. When the Destination PIP counter reaches the programmable boundary the address is automatically incremented by a user-defined amount. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,DstpipVal> dstPip{}; namespace DstpipValC{ constexpr Register::FieldValue<decltype(dstPip)::Type,DstpipVal::disable> disable{}; constexpr Register::FieldValue<decltype(dstPip)::Type,DstpipVal::enable> enable{}; } ///Source Address Descriptor enum class SrcdscrVal { fetchFromMem=0x00000000, ///<Source address is updated when the descriptor is fetched from the memory. fetchDisable=0x00000001, ///<Buffer Descriptor Fetch operation is disabled for the source. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,SrcdscrVal> srcDscr{}; namespace SrcdscrValC{ constexpr Register::FieldValue<decltype(srcDscr)::Type,SrcdscrVal::fetchFromMem> fetchFromMem{}; constexpr Register::FieldValue<decltype(srcDscr)::Type,SrcdscrVal::fetchDisable> fetchDisable{}; } ///Destination Address Descriptor enum class DstdscrVal { fetchFromMem=0x00000000, ///<Destination address is updated when the descriptor is fetched from the memory. fetchDisable=0x00000001, ///<Buffer Descriptor Fetch operation is disabled for the destination. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,DstdscrVal> dstDscr{}; namespace DstdscrValC{ constexpr Register::FieldValue<decltype(dstDscr)::Type,DstdscrVal::fetchFromMem> fetchFromMem{}; constexpr Register::FieldValue<decltype(dstDscr)::Type,DstdscrVal::fetchDisable> fetchDisable{}; } ///Flow Control enum class FcVal { mem2memDmaFc=0x00000000, ///<Memory-to-Memory Transfer DMAC is flow controller mem2perDmaFc=0x00000001, ///<Memory-to-Peripheral Transfer DMAC is flow controller per2memDmaFc=0x00000002, ///<Peripheral-to-Memory Transfer DMAC is flow controller per2perDmaFc=0x00000003, ///<Peripheral-to-Peripheral Transfer DMAC is flow controller }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,21),Register::ReadWriteAccess,FcVal> fc{}; namespace FcValC{ constexpr Register::FieldValue<decltype(fc)::Type,FcVal::mem2memDmaFc> mem2memDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::mem2perDmaFc> mem2perDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::per2memDmaFc> per2memDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::per2perDmaFc> per2perDmaFc{}; } ///Incrementing, Decrementing or Fixed Address for the Source enum class SrcincrVal { incrementing=0x00000000, ///<The source address is incremented decrementing=0x00000001, ///<The source address is decremented fixed=0x00000002, ///<The source address remains unchanged }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,SrcincrVal> srcIncr{}; namespace SrcincrValC{ constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::incrementing> incrementing{}; constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::decrementing> decrementing{}; constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::fixed> fixed{}; } ///Incrementing, Decrementing or Fixed Address for the Destination enum class DstincrVal { incrementing=0x00000000, ///<The destination address is incremented decrementing=0x00000001, ///<The destination address is decremented fixed=0x00000002, ///<The destination address remains unchanged }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,DstincrVal> dstIncr{}; namespace DstincrValC{ constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::incrementing> incrementing{}; constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::decrementing> decrementing{}; constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::fixed> fixed{}; } ///Interrupt Enable Not constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> ien{}; ///Automatic Multiple Buffer Transfer enum class Auto_Val { disable=0x00000000, ///<Automatic multiple buffer transfer is disabled. enable=0x00000001, ///<Automatic multiple buffer transfer is enabled. This bit enables replay mode or contiguous mode when several buffers are transferred. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,Auto_Val> auto_{}; namespace Auto_ValC{ constexpr Register::FieldValue<decltype(auto_)::Type,Auto_Val::disable> disable{}; constexpr Register::FieldValue<decltype(auto_)::Type,Auto_Val::enable> enable{}; } } namespace Dmac0Cfg6{ ///<DMAC Channel Configuration Register (ch_num = 6) using Addr = Register::Address<0xffffe740,0xc88e0000,0x00000000,std::uint32_t>; ///Source with Peripheral identifier constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> srcPer{}; ///Destination with Peripheral identifier constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,4),Register::ReadWriteAccess,unsigned> dstPer{}; ///Source Reloaded from Previous enum class SrcrepVal { contiguousAddr=0x00000000, ///<When automatic mode is activated, source address is contiguous between two buffers. reloadAddr=0x00000001, ///<When automatic mode is activated, the source address and the control register are reloaded from previous transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SrcrepVal> srcRep{}; namespace SrcrepValC{ constexpr Register::FieldValue<decltype(srcRep)::Type,SrcrepVal::contiguousAddr> contiguousAddr{}; constexpr Register::FieldValue<decltype(srcRep)::Type,SrcrepVal::reloadAddr> reloadAddr{}; } ///Software or Hardware Selection for the Source enum class Srch2selVal { sw=0x00000000, ///<Software handshaking interface is used to trigger a transfer request. hw=0x00000001, ///<Hardware handshaking interface is used to trigger a transfer request. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,Srch2selVal> srcH2sel{}; namespace Srch2selValC{ constexpr Register::FieldValue<decltype(srcH2sel)::Type,Srch2selVal::sw> sw{}; constexpr Register::FieldValue<decltype(srcH2sel)::Type,Srch2selVal::hw> hw{}; } ///SRC_PER Most Significant Bits constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,10),Register::ReadWriteAccess,unsigned> srcPerMsb{}; ///Destination Reloaded from Previous enum class DstrepVal { contiguousAddr=0x00000000, ///<When automatic mode is activated, destination address is contiguous between two buffers. reloadAddr=0x00000001, ///<When automatic mode is activated, the destination and the control register are reloaded from the pre-vious transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,DstrepVal> dstRep{}; namespace DstrepValC{ constexpr Register::FieldValue<decltype(dstRep)::Type,DstrepVal::contiguousAddr> contiguousAddr{}; constexpr Register::FieldValue<decltype(dstRep)::Type,DstrepVal::reloadAddr> reloadAddr{}; } ///Software or Hardware Selection for the Destination enum class Dsth2selVal { sw=0x00000000, ///<Software handshaking interface is used to trigger a transfer request. hw=0x00000001, ///<Hardware handshaking interface is used to trigger a transfer request. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,Dsth2selVal> dstH2sel{}; namespace Dsth2selValC{ constexpr Register::FieldValue<decltype(dstH2sel)::Type,Dsth2selVal::sw> sw{}; constexpr Register::FieldValue<decltype(dstH2sel)::Type,Dsth2selVal::hw> hw{}; } ///DST_PER Most Significant Bits constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,14),Register::ReadWriteAccess,unsigned> dstPerMsb{}; ///Stop On Done enum class SodVal { disable=0x00000000, ///<STOP ON DONE disabled, the descriptor fetch operation ignores DONE Field of CTRLA register. enable=0x00000001, ///<STOP ON DONE activated, the DMAC module is automatically disabled if DONE FIELD is set to 1. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,SodVal> sod{}; namespace SodValC{ constexpr Register::FieldValue<decltype(sod)::Type,SodVal::disable> disable{}; constexpr Register::FieldValue<decltype(sod)::Type,SodVal::enable> enable{}; } ///Interface Lock enum class LockifVal { disable=0x00000000, ///<Interface Lock capability is disabled enable=0x00000001, ///<Interface Lock capability is enabled }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,LockifVal> lockIf{}; namespace LockifValC{ constexpr Register::FieldValue<decltype(lockIf)::Type,LockifVal::disable> disable{}; constexpr Register::FieldValue<decltype(lockIf)::Type,LockifVal::enable> enable{}; } ///Bus Lock enum class LockbVal { disable=0x00000000, ///<AHB Bus Locking capability is disabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,LockbVal> lockB{}; namespace LockbValC{ constexpr Register::FieldValue<decltype(lockB)::Type,LockbVal::disable> disable{}; } ///Master Interface Arbiter Lock enum class LockiflVal { chunk=0x00000000, ///<The Master Interface Arbiter is locked by the channel x for a chunk transfer. buffer=0x00000001, ///<The Master Interface Arbiter is locked by the channel x for a buffer transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,LockiflVal> lockIfL{}; namespace LockiflValC{ constexpr Register::FieldValue<decltype(lockIfL)::Type,LockiflVal::chunk> chunk{}; constexpr Register::FieldValue<decltype(lockIfL)::Type,LockiflVal::buffer> buffer{}; } ///AHB Protection constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,24),Register::ReadWriteAccess,unsigned> ahbProt{}; ///FIFO Configuration enum class FifocfgVal { alapCfg=0x00000000, ///<The largest defined length AHB burst is performed on the destination AHB interface. halfCfg=0x00000001, ///<When half FIFO size is available/filled, a source/destination request is serviced. asapCfg=0x00000002, ///<When there is enough space/data available to perform a single AHB access, then the request is serviced. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,FifocfgVal> fifocfg{}; namespace FifocfgValC{ constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::alapCfg> alapCfg{}; constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::halfCfg> halfCfg{}; constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::asapCfg> asapCfg{}; } } namespace Dmac0Spip6{ ///<DMAC Channel Source Picture-in-Picture Configuration Register (ch_num = 6) using Addr = Register::Address<0xffffe744,0xfc000000,0x00000000,std::uint32_t>; ///Source Picture-in-Picture Hole constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> spipHole{}; ///Source Picture-in-Picture Boundary constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,16),Register::ReadWriteAccess,unsigned> spipBoundary{}; } namespace Dmac0Dpip6{ ///<DMAC Channel Destination Picture-in-Picture Configuration Register (ch_num = 6) using Addr = Register::Address<0xffffe748,0xfc000000,0x00000000,std::uint32_t>; ///Destination Picture-in-Picture Hole constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> dpipHole{}; ///Destination Picture-in-Picture Boundary constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,16),Register::ReadWriteAccess,unsigned> dpipBoundary{}; } namespace Dmac0Saddr7{ ///<DMAC Channel Source Address Register (ch_num = 7) using Addr = Register::Address<0xffffe754,0x00000000,0x00000000,std::uint32_t>; ///Channel x Source Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> saddr{}; } namespace Dmac0Daddr7{ ///<DMAC Channel Destination Address Register (ch_num = 7) using Addr = Register::Address<0xffffe758,0x00000000,0x00000000,std::uint32_t>; ///Channel x Destination Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> daddr{}; } namespace Dmac0Dscr7{ ///<DMAC Channel Descriptor Address Register (ch_num = 7) using Addr = Register::Address<0xffffe75c,0x00000000,0x00000000,std::uint32_t>; ///Descriptor Interface Selection enum class DscrifVal { ahbIf0=0x00000000, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 0 ahbIf1=0x00000001, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 1 ahbIf2=0x00000002, ///<The buffer transfer descriptor is fetched via AHB-Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,DscrifVal> dscrIf{}; namespace DscrifValC{ constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(dscrIf)::Type,DscrifVal::ahbIf2> ahbIf2{}; } ///Buffer Transfer Descriptor Address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,2),Register::ReadWriteAccess,unsigned> dscr{}; } namespace Dmac0Ctrla7{ ///<DMAC Channel Control A Register (ch_num = 7) using Addr = Register::Address<0xffffe760,0x4c880000,0x00000000,std::uint32_t>; ///Buffer Transfer Size constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> btsize{}; ///Source Chunk Transfer Size. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,16),Register::ReadWriteAccess,unsigned> scsize{}; ///Destination Chunk Transfer Size constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,20),Register::ReadWriteAccess,unsigned> dcsize{}; ///Transfer Width for the Source enum class SrcwidthVal { byte=0x00000000, ///<the transfer size is set to 8-bit width halfWord=0x00000001, ///<the transfer size is set to 16-bit width word=0x00000002, ///<the transfer size is set to 32-bit width dword=0x00000003, ///<the transfer size is set to 64-bit width }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,SrcwidthVal> srcWidth{}; namespace SrcwidthValC{ constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::byte> byte{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::halfWord> halfWord{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::word> word{}; constexpr Register::FieldValue<decltype(srcWidth)::Type,SrcwidthVal::dword> dword{}; } ///Transfer Width for the Destination enum class DstwidthVal { byte=0x00000000, ///<the transfer size is set to 8-bit width halfWord=0x00000001, ///<the transfer size is set to 16-bit width word=0x00000002, ///<the transfer size is set to 32-bit width dword=0x00000003, ///<the transfer size is set to 64-bit width }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,DstwidthVal> dstWidth{}; namespace DstwidthValC{ constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::byte> byte{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::halfWord> halfWord{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::word> word{}; constexpr Register::FieldValue<decltype(dstWidth)::Type,DstwidthVal::dword> dword{}; } ///Current Descriptor Stop Command and Transfer Completed Memory Indicator constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> done{}; } namespace Dmac0Ctrlb7{ ///<DMAC Channel Control B Register (ch_num = 7) using Addr = Register::Address<0xffffe764,0x0c8eeecc,0x00000000,std::uint32_t>; ///Source Interface Selection Field enum class SifVal { ahbIf0=0x00000000, ///<The source transfer is done via AHB_Lite Interface 0 ahbIf1=0x00000001, ///<The source transfer is done via AHB_Lite Interface 1 ahbIf2=0x00000002, ///<The source transfer is done via AHB_Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,SifVal> sif{}; namespace SifValC{ constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(sif)::Type,SifVal::ahbIf2> ahbIf2{}; } ///Destination Interface Selection Field enum class DifVal { ahbIf0=0x00000000, ///<The destination transfer is done via AHB_Lite Interface 0 ahbIf1=0x00000001, ///<The destination transfer is done via AHB_Lite Interface 1 ahbIf2=0x00000002, ///<The destination transfer is done via AHB_Lite Interface 2 }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,DifVal> dif{}; namespace DifValC{ constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf0> ahbIf0{}; constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf1> ahbIf1{}; constexpr Register::FieldValue<decltype(dif)::Type,DifVal::ahbIf2> ahbIf2{}; } ///Source Picture-in-Picture Mode enum class SrcpipVal { disable=0x00000000, ///<Picture-in-Picture mode is disabled. The source data area is contiguous. enable=0x00000001, ///<Picture-in-Picture mode is enabled. When the source PIP counter reaches the programmable boundary, the address is automatically incremented by a user defined amount. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SrcpipVal> srcPip{}; namespace SrcpipValC{ constexpr Register::FieldValue<decltype(srcPip)::Type,SrcpipVal::disable> disable{}; constexpr Register::FieldValue<decltype(srcPip)::Type,SrcpipVal::enable> enable{}; } ///Destination Picture-in-Picture Mode enum class DstpipVal { disable=0x00000000, ///<Picture-in-Picture mode is disabled. The Destination data area is contiguous. enable=0x00000001, ///<Picture-in-Picture mode is enabled. When the Destination PIP counter reaches the programmable boundary the address is automatically incremented by a user-defined amount. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,DstpipVal> dstPip{}; namespace DstpipValC{ constexpr Register::FieldValue<decltype(dstPip)::Type,DstpipVal::disable> disable{}; constexpr Register::FieldValue<decltype(dstPip)::Type,DstpipVal::enable> enable{}; } ///Source Address Descriptor enum class SrcdscrVal { fetchFromMem=0x00000000, ///<Source address is updated when the descriptor is fetched from the memory. fetchDisable=0x00000001, ///<Buffer Descriptor Fetch operation is disabled for the source. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,SrcdscrVal> srcDscr{}; namespace SrcdscrValC{ constexpr Register::FieldValue<decltype(srcDscr)::Type,SrcdscrVal::fetchFromMem> fetchFromMem{}; constexpr Register::FieldValue<decltype(srcDscr)::Type,SrcdscrVal::fetchDisable> fetchDisable{}; } ///Destination Address Descriptor enum class DstdscrVal { fetchFromMem=0x00000000, ///<Destination address is updated when the descriptor is fetched from the memory. fetchDisable=0x00000001, ///<Buffer Descriptor Fetch operation is disabled for the destination. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,DstdscrVal> dstDscr{}; namespace DstdscrValC{ constexpr Register::FieldValue<decltype(dstDscr)::Type,DstdscrVal::fetchFromMem> fetchFromMem{}; constexpr Register::FieldValue<decltype(dstDscr)::Type,DstdscrVal::fetchDisable> fetchDisable{}; } ///Flow Control enum class FcVal { mem2memDmaFc=0x00000000, ///<Memory-to-Memory Transfer DMAC is flow controller mem2perDmaFc=0x00000001, ///<Memory-to-Peripheral Transfer DMAC is flow controller per2memDmaFc=0x00000002, ///<Peripheral-to-Memory Transfer DMAC is flow controller per2perDmaFc=0x00000003, ///<Peripheral-to-Peripheral Transfer DMAC is flow controller }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,21),Register::ReadWriteAccess,FcVal> fc{}; namespace FcValC{ constexpr Register::FieldValue<decltype(fc)::Type,FcVal::mem2memDmaFc> mem2memDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::mem2perDmaFc> mem2perDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::per2memDmaFc> per2memDmaFc{}; constexpr Register::FieldValue<decltype(fc)::Type,FcVal::per2perDmaFc> per2perDmaFc{}; } ///Incrementing, Decrementing or Fixed Address for the Source enum class SrcincrVal { incrementing=0x00000000, ///<The source address is incremented decrementing=0x00000001, ///<The source address is decremented fixed=0x00000002, ///<The source address remains unchanged }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,SrcincrVal> srcIncr{}; namespace SrcincrValC{ constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::incrementing> incrementing{}; constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::decrementing> decrementing{}; constexpr Register::FieldValue<decltype(srcIncr)::Type,SrcincrVal::fixed> fixed{}; } ///Incrementing, Decrementing or Fixed Address for the Destination enum class DstincrVal { incrementing=0x00000000, ///<The destination address is incremented decrementing=0x00000001, ///<The destination address is decremented fixed=0x00000002, ///<The destination address remains unchanged }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,DstincrVal> dstIncr{}; namespace DstincrValC{ constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::incrementing> incrementing{}; constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::decrementing> decrementing{}; constexpr Register::FieldValue<decltype(dstIncr)::Type,DstincrVal::fixed> fixed{}; } ///Interrupt Enable Not constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> ien{}; ///Automatic Multiple Buffer Transfer enum class Auto_Val { disable=0x00000000, ///<Automatic multiple buffer transfer is disabled. enable=0x00000001, ///<Automatic multiple buffer transfer is enabled. This bit enables replay mode or contiguous mode when several buffers are transferred. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,Auto_Val> auto_{}; namespace Auto_ValC{ constexpr Register::FieldValue<decltype(auto_)::Type,Auto_Val::disable> disable{}; constexpr Register::FieldValue<decltype(auto_)::Type,Auto_Val::enable> enable{}; } } namespace Dmac0Cfg7{ ///<DMAC Channel Configuration Register (ch_num = 7) using Addr = Register::Address<0xffffe768,0xc88e0000,0x00000000,std::uint32_t>; ///Source with Peripheral identifier constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> srcPer{}; ///Destination with Peripheral identifier constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,4),Register::ReadWriteAccess,unsigned> dstPer{}; ///Source Reloaded from Previous enum class SrcrepVal { contiguousAddr=0x00000000, ///<When automatic mode is activated, source address is contiguous between two buffers. reloadAddr=0x00000001, ///<When automatic mode is activated, the source address and the control register are reloaded from previous transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SrcrepVal> srcRep{}; namespace SrcrepValC{ constexpr Register::FieldValue<decltype(srcRep)::Type,SrcrepVal::contiguousAddr> contiguousAddr{}; constexpr Register::FieldValue<decltype(srcRep)::Type,SrcrepVal::reloadAddr> reloadAddr{}; } ///Software or Hardware Selection for the Source enum class Srch2selVal { sw=0x00000000, ///<Software handshaking interface is used to trigger a transfer request. hw=0x00000001, ///<Hardware handshaking interface is used to trigger a transfer request. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,Srch2selVal> srcH2sel{}; namespace Srch2selValC{ constexpr Register::FieldValue<decltype(srcH2sel)::Type,Srch2selVal::sw> sw{}; constexpr Register::FieldValue<decltype(srcH2sel)::Type,Srch2selVal::hw> hw{}; } ///SRC_PER Most Significant Bits constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,10),Register::ReadWriteAccess,unsigned> srcPerMsb{}; ///Destination Reloaded from Previous enum class DstrepVal { contiguousAddr=0x00000000, ///<When automatic mode is activated, destination address is contiguous between two buffers. reloadAddr=0x00000001, ///<When automatic mode is activated, the destination and the control register are reloaded from the pre-vious transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,DstrepVal> dstRep{}; namespace DstrepValC{ constexpr Register::FieldValue<decltype(dstRep)::Type,DstrepVal::contiguousAddr> contiguousAddr{}; constexpr Register::FieldValue<decltype(dstRep)::Type,DstrepVal::reloadAddr> reloadAddr{}; } ///Software or Hardware Selection for the Destination enum class Dsth2selVal { sw=0x00000000, ///<Software handshaking interface is used to trigger a transfer request. hw=0x00000001, ///<Hardware handshaking interface is used to trigger a transfer request. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,Dsth2selVal> dstH2sel{}; namespace Dsth2selValC{ constexpr Register::FieldValue<decltype(dstH2sel)::Type,Dsth2selVal::sw> sw{}; constexpr Register::FieldValue<decltype(dstH2sel)::Type,Dsth2selVal::hw> hw{}; } ///DST_PER Most Significant Bits constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,14),Register::ReadWriteAccess,unsigned> dstPerMsb{}; ///Stop On Done enum class SodVal { disable=0x00000000, ///<STOP ON DONE disabled, the descriptor fetch operation ignores DONE Field of CTRLA register. enable=0x00000001, ///<STOP ON DONE activated, the DMAC module is automatically disabled if DONE FIELD is set to 1. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,SodVal> sod{}; namespace SodValC{ constexpr Register::FieldValue<decltype(sod)::Type,SodVal::disable> disable{}; constexpr Register::FieldValue<decltype(sod)::Type,SodVal::enable> enable{}; } ///Interface Lock enum class LockifVal { disable=0x00000000, ///<Interface Lock capability is disabled enable=0x00000001, ///<Interface Lock capability is enabled }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,LockifVal> lockIf{}; namespace LockifValC{ constexpr Register::FieldValue<decltype(lockIf)::Type,LockifVal::disable> disable{}; constexpr Register::FieldValue<decltype(lockIf)::Type,LockifVal::enable> enable{}; } ///Bus Lock enum class LockbVal { disable=0x00000000, ///<AHB Bus Locking capability is disabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,LockbVal> lockB{}; namespace LockbValC{ constexpr Register::FieldValue<decltype(lockB)::Type,LockbVal::disable> disable{}; } ///Master Interface Arbiter Lock enum class LockiflVal { chunk=0x00000000, ///<The Master Interface Arbiter is locked by the channel x for a chunk transfer. buffer=0x00000001, ///<The Master Interface Arbiter is locked by the channel x for a buffer transfer. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,LockiflVal> lockIfL{}; namespace LockiflValC{ constexpr Register::FieldValue<decltype(lockIfL)::Type,LockiflVal::chunk> chunk{}; constexpr Register::FieldValue<decltype(lockIfL)::Type,LockiflVal::buffer> buffer{}; } ///AHB Protection constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,24),Register::ReadWriteAccess,unsigned> ahbProt{}; ///FIFO Configuration enum class FifocfgVal { alapCfg=0x00000000, ///<The largest defined length AHB burst is performed on the destination AHB interface. halfCfg=0x00000001, ///<When half FIFO size is available/filled, a source/destination request is serviced. asapCfg=0x00000002, ///<When there is enough space/data available to perform a single AHB access, then the request is serviced. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,FifocfgVal> fifocfg{}; namespace FifocfgValC{ constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::alapCfg> alapCfg{}; constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::halfCfg> halfCfg{}; constexpr Register::FieldValue<decltype(fifocfg)::Type,FifocfgVal::asapCfg> asapCfg{}; } } namespace Dmac0Spip7{ ///<DMAC Channel Source Picture-in-Picture Configuration Register (ch_num = 7) using Addr = Register::Address<0xffffe76c,0xfc000000,0x00000000,std::uint32_t>; ///Source Picture-in-Picture Hole constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> spipHole{}; ///Source Picture-in-Picture Boundary constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,16),Register::ReadWriteAccess,unsigned> spipBoundary{}; } namespace Dmac0Dpip7{ ///<DMAC Channel Destination Picture-in-Picture Configuration Register (ch_num = 7) using Addr = Register::Address<0xffffe770,0xfc000000,0x00000000,std::uint32_t>; ///Destination Picture-in-Picture Hole constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> dpipHole{}; ///Destination Picture-in-Picture Boundary constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,16),Register::ReadWriteAccess,unsigned> dpipBoundary{}; } namespace Dmac0Wpmr{ ///<DMAC Write Protect Mode Register using Addr = Register::Address<0xffffe7e4,0x000000fe,0x00000000,std::uint32_t>; ///Write Protect Enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> wpen{}; ///Write Protect KEY constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> wpkey{}; } namespace Dmac0Wpsr{ ///<DMAC Write Protect Status Register using Addr = Register::Address<0xffffe7e8,0xff0000fe,0x00000000,std::uint32_t>; ///Write Protect Violation Status constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> wpvs{}; ///Write Protect Violation Source constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> wpvsrc{}; } }
78.266689
223
0.703402
operativeF
e403a28c865100513636fbe94a4eb975689e9dcb
2,600
cc
C++
srcs/apt-1.0.9.2/test/libapt/commandline_test.cc
Ziul/tcc1
97dc2b9afcd6736aa8158066b95a698301629543
[ "CC-BY-3.0" ]
null
null
null
srcs/apt-1.0.9.2/test/libapt/commandline_test.cc
Ziul/tcc1
97dc2b9afcd6736aa8158066b95a698301629543
[ "CC-BY-3.0" ]
2
2015-11-21T02:30:20.000Z
2015-11-21T02:30:35.000Z
srcs/apt-1.0.9.2/test/libapt/commandline_test.cc
Ziul/tcc1
97dc2b9afcd6736aa8158066b95a698301629543
[ "CC-BY-3.0" ]
null
null
null
#include <config.h> #include <apt-pkg/cmndline.h> #include <apt-pkg/configuration.h> #include <gtest/gtest.h> class CLT: public CommandLine { public: std::string static AsString(const char * const * const argv, unsigned int const argc) { std::string const static conf = "Commandline::AsString"; _config->Clear(conf); SaveInConfig(argc, argv); return _config->Find(conf); } }; #define EXPECT_CMD(x, ...) { const char * const argv[] = { __VA_ARGS__ }; EXPECT_EQ(x, CLT::AsString(argv, sizeof(argv)/sizeof(argv[0]))); } TEST(CommandLineTest,SaveInConfig) { EXPECT_CMD("apt-get install -sf", "apt-get", "install", "-sf"); EXPECT_CMD("apt-cache -s apt -so Debug::test=Test", "apt-cache", "-s", "apt", "-so", "Debug::test=Test"); EXPECT_CMD("apt-cache -s apt -so Debug::test=\"Das ist ein Test\"", "apt-cache", "-s", "apt", "-so", "Debug::test=Das ist ein Test"); EXPECT_CMD("apt-cache -s apt --hallo test=1.0", "apt-cache", "-s", "apt", "--hallo", "test=1.0"); } TEST(CommandLineTest,Parsing) { CommandLine::Args Args[] = { { 't', 0, "Test::Worked", 0 }, { 'z', "zero", "Test::Zero", 0 }, {0,0,0,0} }; ::Configuration c; CommandLine CmdL(Args, &c); char const * argv[] = { "test", "--zero", "-t" }; CmdL.Parse(3 , argv); EXPECT_TRUE(c.FindB("Test::Worked", false)); EXPECT_TRUE(c.FindB("Test::Zero", false)); c.Clear("Test"); EXPECT_FALSE(c.FindB("Test::Worked", false)); EXPECT_FALSE(c.FindB("Test::Zero", false)); c.Set("Test::Zero", true); EXPECT_TRUE(c.FindB("Test::Zero", false)); char const * argv2[] = { "test", "--no-zero", "-t" }; CmdL.Parse(3 , argv2); EXPECT_TRUE(c.FindB("Test::Worked", false)); EXPECT_FALSE(c.FindB("Test::Zero", false)); } TEST(CommandLineTest, BoolParsing) { CommandLine::Args Args[] = { { 't', 0, "Test::Worked", 0 }, {0,0,0,0} }; ::Configuration c; CommandLine CmdL(Args, &c); // the commandline parser used to use strtol() on the argument // to check if the argument is a boolean expression - that // stopped after the "0". this test ensures that we always check // that the entire string was consumed by strtol { char const * argv[] = { "show", "-t", "0ad" }; bool res = CmdL.Parse(sizeof(argv)/sizeof(char*), argv); EXPECT_TRUE(res); ASSERT_EQ(std::string(CmdL.FileList[0]), "0ad"); } { char const * argv[] = { "show", "-t", "0", "ad" }; bool res = CmdL.Parse(sizeof(argv)/sizeof(char*), argv); EXPECT_TRUE(res); ASSERT_EQ(std::string(CmdL.FileList[0]), "ad"); } }
29.545455
140
0.603462
Ziul
e4048547b62c2da8811f4c58f98a7261db617792
6,419
cpp
C++
libtumbler/examples/ledring2.cpp
FairyDevicesRD/tumbler
e847d9770e7b4d64f3eb936cfcd72e3588176138
[ "Apache-2.0" ]
12
2018-01-16T01:55:24.000Z
2021-10-05T21:59:05.000Z
libtumbler/examples/ledring2.cpp
FairyDevicesRD/tumbler
e847d9770e7b4d64f3eb936cfcd72e3588176138
[ "Apache-2.0" ]
2
2019-04-16T09:21:44.000Z
2019-07-04T06:57:48.000Z
libtumbler/examples/ledring2.cpp
FairyDevicesRD/tumbler
e847d9770e7b4d64f3eb936cfcd72e3588176138
[ "Apache-2.0" ]
4
2018-02-22T08:13:07.000Z
2019-03-13T16:53:21.000Z
/* * @file ledring.cpp * \~english * @brief Example program for controlling LED ring. * \~japanese * @brief LED リングの制御例 * \~ * @author Masato Fujino, created on: Apr 16, 2019 * @copyright Copyright 2019 Fairy Devices Inc. http://www.fairydevices.jp/ * @copyright Apache License, Version 2.0 * * Copyright 2019 Fairy Devices Inc. http://www.fairydevices.jp/ * * 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 <iostream> #include <unistd.h> #include "tumbler/tumbler.h" #include "tumbler/ledring.h" using namespace tumbler; /** * @class AzimuthFrame * @brief Tumbler 座標系における方位角(向かって右が 0 度、正面が 270 度)を指定した時、指定方位の LED を点灯させる機能を持つ。 * libtumbler が提供している Frame クラスを継承している。 * @details LED は 18 個しかないため、ちょうど 18 で割り切れる方位以外は、2 つの LED の明度のバランスを取ることで表現している */ class AzimuthFrame : public Frame { public: /** * @brief コンストラクタ * @param [in] 点灯させたい方向の方位角[0,360] * @param [in] foreground 点灯させたい方向の LED 色 * @param [in] background その他の LED 色 */ AzimuthFrame( const std::vector<int>& azimuths, const tumbler::LED& foreground, const tumbler::LED& background) : tumbler::Frame(background), azimuths_(azimuths.begin(), azimuths.end()), foreground_(foreground), background_(background) { // LED は 18 個あり、20 度ごとの角度で配置されている int node0Idx, node1Idx; // 反時計回りの始点と終点 float node0, node1; // 同明度 for(size_t i=0;i<azimuths_.size();++i){ // 値域対応 int caz = azimuths_[i]; if(360 <= caz){ caz = caz - 360; }else if(caz < 0){ caz = 360 + caz; } // 角度からセグメントを計算 if(caz < 10 || 350 <= caz){ // 端点処理 node0Idx = 17; node1Idx = 0; }else{ // 10 -> 349 // [10,29]->[20,39]=>1 // [30,49]->[40,59]=>2 // [330,349]->[340,359]=>17 int segment = (caz+10) / 20; node0Idx = segment-1; node1Idx = segment; } // 明度バランス // 角度 = 0 -> ida = 10 // 角度 = 5 -> ida = 15 // 角度 = 9 -> ida = 19 // 角度 = 10 -> ida = 0 // 角度 = 15 -> ida = 5 // 角度 = 17 -> ida = 7 // 角度 = 20 -> ida = 10 // .... int ida = (caz+10) % 20; CalcBrightnessPair(ida, node0, node1); setLED(V2PMap(node0Idx), tumbler::LED(foreground.r_*node0, foreground.g_*node0, foreground.b_*node0)); setLED(V2PMap(node1Idx), tumbler::LED(foreground.r_*node1, foreground.g_*node1, foreground.b_*node1)); } } private: /** * @brief 所与の内分角に対して 2 つの LED ペアの明るさバランスを計算する * @param [in] degree 内分角[0,19](度) * @param [out] node0 片側の明度(反時計回りの始点側) * @param [out] node1 片側の明度(反時計回りの終点側) */ void CalcBrightnessPair(int degree, float& node0, float& node1) { if(degree < 0 || 19 < degree){ // [0,19]度 throw std::runtime_error("CalcBrightnessPair(), degree out of range."); } node0 = 1.0 - degree*0.05; node1 = degree*0.05; } /** * @brief 基準座標系における仮想LEDIDと物理LED番号の対応 * @param [in] VID 仮想LEDID * @return 物理LEDID */ int V2PMap(int VID) { switch (VID){ case 0: return 4; case 1: return 3; case 2: return 2; case 3: return 1; case 4: return 0; case 5: return 17; case 6: return 16; case 7: return 15; case 8: return 14; case 9: return 13; case 10: return 12; case 11: return 11; case 12: return 10; case 13: return 9; case 14: return 8; case 15: return 7; case 16: return 6; case 17: return 5; default: return -1; } } std::vector<int> azimuths_; const tumbler::LED foreground_; const tumbler::LED background_; }; /** * @brief 角度計算 * @param [in] base 基準となる角度 * @param [in] diff 基準となる角度からの差 * @return 基準となる角度に対して、第二引数で指定した差を持つ角度 */ int calcDiffDegree(int base, int diff) { int d = base-diff; if(d < 0){ return d+360; }else if(360 < d){ return d-360; }else{ return d; } } /** * @brief デフォルトパターンを返す関数、典型的に利用される関数です。 * @details このパターンは Arduino Sketch にも内蔵されており、電源オフからオンへの切り替わり時点で OS が起動する前の時点で点灯されるパターン。reset 関数により消灯されるため、 * デフォルトパターンでの再点灯は、内部制御点灯により libtumbler 側から改めて命令する必要があります。内蔵されたパターンの定義は、以下にあります。 * @see https://github.com/FairyDevicesRD/tumbler/blob/be436908177daf22df32427c245034223300d102/arduino/sketch/LEDRing.h#L198 * @return フレーム */ Frame defaultPattern(){ Frame f; int r = 255; int g = 255; int b = 255; float a = 0.4; float c = 0.6; f.setLED(4, LED(r, g, b)); f.setLED(3, LED(r, g, b)); f.setLED(2, LED(r*a*a,g*a*a,b*c)); f.setLED(1, LED(r*a*a*a,g*a*a*a,b*c*c)); f.setLED(0, LED(r*a*a*a*a,g*a*a*a*a,b*c*c*c)); return f; } /** * @brief アニメーション定義の実装 * @param [in] degree LED を点灯させたい方位角 * @return アニメーションのためのフレーム群 * @note AzimuthFrame クラスは単一のフレームを返す。libmimixfe では AzimuthFrame クラスの直接利用による単一フレームを用いているが * 本サンプルプログラムでは、それらを複数用いてアニメーションの例を定義してみた。 */ std::vector<Frame> myAnimation(int degree) { LED foregroundColor(0,0,255); AzimuthFrame af2({calcDiffDegree(degree,70), calcDiffDegree(degree,-70)}, foregroundColor, LED(40,40,40)); AzimuthFrame af3({calcDiffDegree(degree,50), calcDiffDegree(degree,-50)}, foregroundColor, LED(30,30,30)); AzimuthFrame af4({calcDiffDegree(degree,20), calcDiffDegree(degree,-20)}, foregroundColor, LED(20,20,20)); AzimuthFrame af6({degree}, foregroundColor, LED(10,10,10)); return {af2,af3,af4,af6}; } int main(int argc, char** argv) { LEDRing& ring = LEDRing::getInstance(); ring.motion(false, 1, defaultPattern()); std::cout << "角度を入力すると、角度の方向がアニメーション付きで点灯します" << std::endl << std::endl; std::cout << "プログラムを終了するときは Ctrl+C で終了してください" << std::endl; ring.setFPS(30); std::string input; while(true){ std::cout << "角度を[0,359]の範囲で入力してください" << std::endl; std::getline(std::cin, input); int degree = std::atoi(input.c_str()); if(!(0 <= degree && degree < 360)){ std::cout << "角度は[0,359]の範囲で入力してください" << std::endl; continue; } ring.setFrames(myAnimation(degree)); ring.show(true); // 非同期で実行しています。このサンプルプログラムでは同期実行でも問題ありませんが、実際のプログラムでは、アニメーションの終了を待ちたくない場合があります。 std::cout << "リセットするために、もう一度リターンキーを押してください" << std::endl; std::cin.get(); ring.motion(false, 1, defaultPattern()); } }
27.431624
125
0.657891
FairyDevicesRD
e404c76322157c2229cf7b828409d4ecbcf6a16f
3,340
cpp
C++
Substream.cpp
malord/prime
f0e8be99b7dcd482708b9c928322bc07a3128506
[ "MIT" ]
null
null
null
Substream.cpp
malord/prime
f0e8be99b7dcd482708b9c928322bc07a3128506
[ "MIT" ]
null
null
null
Substream.cpp
malord/prime
f0e8be99b7dcd482708b9c928322bc07a3128506
[ "MIT" ]
null
null
null
// Copyright 2000-2021 Mark H. P. Lord #include "Substream.h" namespace Prime { PRIME_DEFINE_UID_CAST(Substream) Substream::Substream() { construct(); } void Substream::construct() { _discardWriteOverflow = false; _writeOverflowed = false; } Substream::Substream(Stream* stream, Offset baseOffset, bool seekToBaseOffset, Offset substreamSize, Log* log, bool seekable) { construct(); init(stream, baseOffset, seekToBaseOffset, substreamSize, log, seekable); } bool Substream::close(Log* log) { if (!_stream) { return true; } bool success = _stream->close(log); _stream.release(); return success; } bool Substream::init(Stream* stream, Offset baseOffset, bool seekToBaseOffset, Offset substreamSize, Log* log, bool seekable) { PRIME_ASSERT(!seekable || stream->isSeekable()); if (seekToBaseOffset) { PRIME_ASSERT(seekable); if (!stream->setOffset(baseOffset, log)) { return false; } } _stream = stream; _seekable = seekable; _base = baseOffset; _position = 0; _size = substreamSize; return true; } ptrdiff_t Substream::readSome(void* buffer, size_t maximumBytes, Log* log) { PRIME_ASSERT(_stream); Offset remaining = _size - _position; if ((Offset)maximumBytes > remaining) { maximumBytes = (size_t)remaining; } if (!maximumBytes) { return 0; } ptrdiff_t got = _stream->readSome(buffer, maximumBytes, log); if (got < 0) { return got; } _position += got; return got; } ptrdiff_t Substream::writeSome(const void* memory, size_t maximumBytes, Log* log) { PRIME_ASSERT(_stream); Offset remaining = _size - _position; size_t bytesToWrite = maximumBytes; if ((Offset)bytesToWrite > remaining) { _writeOverflowed = true; bytesToWrite = (size_t)remaining; } ptrdiff_t wrote = _stream->writeSome(memory, bytesToWrite, log); if (wrote < 0) { return wrote; } _position += wrote; if (_writeOverflowed && _discardWriteOverflow) { return maximumBytes; } return wrote; } Stream::Offset Substream::seek(Offset offset, SeekMode mode, Log* log) { PRIME_ASSERT(_stream); if (!_seekable) { log->error(PRIME_LOCALISE("seek() called on non-seekable Substream.")); return -1; } Offset newOffset = 0; switch (mode) { case SeekModeAbsolute: newOffset = offset; break; case SeekModeRelative: newOffset = _position + offset; break; case SeekModeRelativeToEnd: newOffset = _size + offset; break; default: PRIME_ASSERT(0); return -1; } if (newOffset < 0) { return -1; } if (newOffset > _size) { return -1; } _position = newOffset; Offset seekTo = _base + newOffset; if (!_stream->setOffset(seekTo, log)) { return -1; } return _position; } Stream::Offset Substream::getSize(Log*) { PRIME_ASSERT(_stream); return _seekable ? _size : -1; } bool Substream::setSize(Offset, Log* log) { log->error(PRIME_LOCALISE("Cannot set size of a Substream.")); return false; } bool Substream::flush(Log* log) { PRIME_ASSERT(_stream); return _stream->flush(log); } }
18.453039
125
0.626048
malord
e406732cfc3318c9cd19745391ac09cb209165e6
3,422
cpp
C++
src/DescentTest/src/DescentEngine/PhysicsTest.cpp
poseidn/KungFoo-legacy
9b79d65b596acc9dff4725ef5bfab8ecc4164afb
[ "MIT" ]
1
2017-11-24T03:01:31.000Z
2017-11-24T03:01:31.000Z
src/DescentTest/src/DescentEngine/PhysicsTest.cpp
poseidn/KungFoo-legacy
9b79d65b596acc9dff4725ef5bfab8ecc4164afb
[ "MIT" ]
null
null
null
src/DescentTest/src/DescentEngine/PhysicsTest.cpp
poseidn/KungFoo-legacy
9b79d65b596acc9dff4725ef5bfab8ecc4164afb
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> #include <gtest/gtest.h> #include "Support/TestEntity.h" #include <DescentEngine/src/EntityEngine/Entity.h> #include <DescentEngine/src/Physics/PhysicsEngine.h> TEST(Physics, startAndShutdown) { PhysicsEngine phyEg; } TEST(Physics, moveEntity) { PhysicsEngine phyEg; Vector2 initialPos(3.0f, 3.0f); Vector2 newPos(5.0f, 3.0f); Rectangle2 box(0.5f, 0.5f); auto ent = std::unique_ptr < TestEntity > (new TestEntity(initialPos, box)); ent->setCollisionGroup(2); // collide with the floor and other from our collision group ent->setCollisionMask(CollisionGroups::Ground | 2); ent->setCollisionType(CollisionType::CircleLike); phyEg.registerEntity(ent.get()); ent->setMoveIntent(newPos); // run for one second // dont make this time to big, as bullet can only subdivide in a certain part of substeps phyEg.step(0.1f); ASSERT_FLOAT_EQ(ent->getMoveIntent().x(), newPos.x()); ASSERT_FLOAT_EQ(ent->getMoveIntent().y(), newPos.y()); ASSERT_EQ(phyEg.getRegisteredEntitiesCount(), size_t(1)); } TEST(Physics, collideEntity) { PhysicsEngine phyEg; Vector2 initialPos(3.0f, 3.0f); Vector2 newPos(3.0f, 5.0f); Rectangle2 box(0.5f, 0.5f); auto ent = std::unique_ptr < TestEntity > (new TestEntity(initialPos, box)); ent->setCollisionGroup(2); // collide with the floor and other from our collision group ent->setCollisionMask(CollisionGroups::Ground | 2); ent->setCollisionType(CollisionType::CircleLike); phyEg.registerEntity(ent.get()); ent->setMoveIntent(newPos); // box in between Rectangle2 boxCollide(5.0f, 0.5f); Vector2 wallPos(3.0f, 4.0f); auto entWall = std::unique_ptr < TestEntity > (new TestEntity(wallPos, boxCollide)); entWall->setCollisionGroup(2); // collide with the floor and other from our collision group entWall->setCollisionMask(CollisionGroups::Ground | 2); entWall->setCollisionType(CollisionType::BoxLike); phyEg.registerEntity(entWall.get()); //entWall->setMoveIntent(newPos); // run for one second // dont make this time to big, as bullet can only subdivide in a certain part of substeps phyEg.step(0.1f); std::cout << "is at " << ent->getMoveIntent() << std::endl; ASSERT_TRUE(ent->getMoveIntent().y() < newPos.y()); } TEST(Physics, changeCollisionGroup) { PhysicsEngine phyEg; const Vector2 initialPos(3.0f, 3.0f); const Vector2 newPos(3.0f, 5.0f); Rectangle2 box(0.5f, 0.5f); auto ent = std::unique_ptr < TestEntity > (new TestEntity(initialPos, box)); ent->setCollisionGroup(2); // collide with the floor and other from our collision group ent->setCollisionMask(CollisionGroups::Ground | 2); ent->setCollisionType(CollisionType::CircleLike); phyEg.registerEntity(ent.get()); ent->setMoveIntent(newPos); // box in between Rectangle2 boxCollide(5.0f, 0.5f); Vector2 wallPos(3.0f, 4.0f); auto entWall = std::unique_ptr < TestEntity > (new TestEntity(wallPos, boxCollide)); entWall->setCollisionGroup(2); // collide with the floor and other from our collision group entWall->setCollisionMask(CollisionGroups::Ground | 2); entWall->setCollisionType(CollisionType::BoxLike); phyEg.registerEntity(entWall.get()); // the wall will be -invisible- entWall->setCollisionGroup(4); phyEg.step(0.1f); std::cout << "is at " << ent->getMoveIntent() << std::endl; EXPECT_NEAR(ent->getMoveIntent().x(), newPos.x(), 0.001); EXPECT_NEAR(ent->getMoveIntent().y(), newPos.y(), 0.001); }
29
90
0.72969
poseidn
e408a20910a8e799b4e5bd69b3cf20598cbd33d3
874
hpp
C++
include/SAMPCpp/Everything.hpp
PoetaKodu/samp-cpp
dbd5170efe0c799d1ec902e2b8a385596a5303a8
[ "MIT" ]
null
null
null
include/SAMPCpp/Everything.hpp
PoetaKodu/samp-cpp
dbd5170efe0c799d1ec902e2b8a385596a5303a8
[ "MIT" ]
null
null
null
include/SAMPCpp/Everything.hpp
PoetaKodu/samp-cpp
dbd5170efe0c799d1ec902e2b8a385596a5303a8
[ "MIT" ]
1
2021-06-10T22:59:53.000Z
2021-06-10T22:59:53.000Z
#pragma once #include SAMPCPP_PCH #include <SAMPCpp/SAMP/Player.hpp> #include <SAMPCpp/SAMP/Vehicle.hpp> #include <SAMPCpp/SAMP/Object.hpp> #include <SAMPCpp/SAMP/PlayerObject.hpp> #include <SAMPCpp/SAMP/Pickup.hpp> #include <SAMPCpp/SAMP/Menu.hpp> #include <SAMPCpp/SAMP/TextLabel3D.hpp> #include <SAMPCpp/SAMP/TextDraw.hpp> #include <SAMPCpp/SAMP/GangZone.hpp> #include <SAMPCpp/SAMP/Weapon.hpp> #include <SAMPCpp/SAMP/Http.hpp> #include <SAMPCpp/SAMP/Native.hpp> #include <SAMPCpp/SAMP/Timer.hpp> #include <SAMPCpp/SAMP/SAMP.hpp> #include <SAMPCpp/AMX/CallNative.hpp> #include <SAMPCpp/AMX/CallPublic.hpp> #include <SAMPCpp/AMX/NativeLoader.hpp> #include <SAMPCpp/AMX/SmartNative.hpp> #include <SAMPCpp/Core/Safety/Unique.hpp> #include <SAMPCpp/Core/Color.hpp> #include <SAMPCpp/Core/String.hpp> #include <SAMPCpp/Core/Formatting.hpp> #include <SAMPCpp/Core/Math.hpp>
30.137931
41
0.778032
PoetaKodu
e409a7f15a94d12dce75baca11196290f81e9c4a
2,606
cpp
C++
core/src/Documents/DocumentTypes.cpp
codesmithyide/codesmithy
9be7c2c45fa1f533aa7a7623b8f610737c720bca
[ "MIT" ]
6
2017-06-17T00:03:14.000Z
2019-02-03T03:17:39.000Z
core/src/Documents/DocumentTypes.cpp
codesmithyide/codesmithy
9be7c2c45fa1f533aa7a7623b8f610737c720bca
[ "MIT" ]
98
2016-08-31T12:49:09.000Z
2020-11-01T19:39:28.000Z
core/src/Documents/DocumentTypes.cpp
codesmithyide/codesmithy
9be7c2c45fa1f533aa7a7623b8f610737c720bca
[ "MIT" ]
1
2019-02-03T03:17:40.000Z
2019-02-03T03:17:40.000Z
/* Copyright (c) 2015-2016 Xavier Leclercq Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Documents/DocumentTypes.h" namespace CodeSmithy { DocumentTypes::DocumentTypes() { } DocumentTypes::~DocumentTypes() { } size_t DocumentTypes::size() const { return m_types.size(); } std::shared_ptr<const DocumentType> DocumentTypes::operator[](size_t index) const { return m_types[index]; } std::shared_ptr<DocumentType>& DocumentTypes::operator[](size_t index) { return m_types[index]; } void DocumentTypes::add(std::shared_ptr<DocumentType> type) { m_types.push_back(type); } std::shared_ptr<const DocumentType> DocumentTypes::find(const std::string& name) const { for (size_t i = 0; i < m_types.size(); ++i) { if (m_types[i]->name() == name) { return m_types[i]; } } return std::shared_ptr<const DocumentType>(); } std::shared_ptr<DocumentType> DocumentTypes::find(const std::string& name) { for (size_t i = 0; i < m_types.size(); ++i) { if (m_types[i]->name() == name) { return m_types[i]; } } return std::shared_ptr<DocumentType>(); } void DocumentTypes::getSuitableTypesForFileExtension(const boost::filesystem::path& extension, std::vector<std::shared_ptr<const DocumentType> >& types) const { for (size_t i = 0; i < m_types.size(); ++i) { if (m_types[i]->hasExtension(extension)) { types.push_back(m_types[i]); } } } }
28.021505
116
0.671527
codesmithyide
e40a092340e9a0cfe2289f9a93fecb4b2f9b0338
1,709
cpp
C++
Visual C++/QCMAide/QCMAideDoc.cpp
manimanis/Intranet
9cd4da01641212f18c710ae721bc48c8eadc4a28
[ "MIT" ]
null
null
null
Visual C++/QCMAide/QCMAideDoc.cpp
manimanis/Intranet
9cd4da01641212f18c710ae721bc48c8eadc4a28
[ "MIT" ]
null
null
null
Visual C++/QCMAide/QCMAideDoc.cpp
manimanis/Intranet
9cd4da01641212f18c710ae721bc48c8eadc4a28
[ "MIT" ]
null
null
null
// QCMAideDoc.cpp : implementation of the CQCMAideDoc class // #include "stdafx.h" #include "QCMAide.h" #include "QCMAideDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CQCMAideDoc IMPLEMENT_DYNCREATE(CQCMAideDoc, CDocument) BEGIN_MESSAGE_MAP(CQCMAideDoc, CDocument) //{{AFX_MSG_MAP(CQCMAideDoc) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CQCMAideDoc construction/destruction CQCMAideDoc::CQCMAideDoc() { // TODO: add one-time construction code here } CQCMAideDoc::~CQCMAideDoc() { } BOOL CQCMAideDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CQCMAideDoc serialization void CQCMAideDoc::Serialize(CArchive& ar) { if (ar.IsStoring()) { // TODO: add storing code here } else { // TODO: add loading code here } } ///////////////////////////////////////////////////////////////////////////// // CQCMAideDoc diagnostics #ifdef _DEBUG void CQCMAideDoc::AssertValid() const { CDocument::AssertValid(); } void CQCMAideDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CQCMAideDoc commands CString CQCMAideDoc::GetQCMFileName() { CFileDialog cfDlg(TRUE); cfDlg.DoModal(); return cfDlg.GetPathName(); }
18.78022
77
0.561732
manimanis
e40a21dbcd29828f3449e2c915b76171760fdd02
3,365
inl
C++
cpp/custrings/util.inl
williamBlazing/cudf
072785e24fd59b6f4eeaad3b54592a8c803ee96b
[ "Apache-2.0" ]
46
2019-03-11T19:44:23.000Z
2021-09-28T06:01:25.000Z
cpp/custrings/util.inl
CZZLEGEND/cudf
5d2465d6738d00628673fffdc1fac51fad7ef9a7
[ "Apache-2.0" ]
196
2019-03-11T18:31:28.000Z
2019-09-30T20:06:57.000Z
cpp/custrings/util.inl
CZZLEGEND/cudf
5d2465d6738d00628673fffdc1fac51fad7ef9a7
[ "Apache-2.0" ]
43
2019-03-11T18:15:02.000Z
2021-07-27T08:36:44.000Z
/* * Copyright (c) 2018-2019, NVIDIA CORPORATION. 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 <cstring> #include <rmm/rmm.h> // single unicode character to utf8 character // used only by translate method __host__ __device__ inline unsigned int u2u8( unsigned int unchr ) { unsigned int utf8 = 0; if( unchr < 0x00000080 ) utf8 = unchr; else if( unchr < 0x00000800 ) { utf8 = (unchr << 2) & 0x1F00; utf8 |= (unchr & 0x3F); utf8 |= 0x0000C080; } else if( unchr < 0x00010000 ) { utf8 = (unchr << 4) & 0x0F0000; // upper 4 bits utf8 |= (unchr << 2) & 0x003F00; // next 6 bits utf8 |= (unchr & 0x3F); // last 6 bits utf8 |= 0x00E08080; } else if( unchr < 0x00110000 ) // 3-byte unicode? { utf8 = (unchr << 6) & 0x07000000; // upper 3 bits utf8 |= (unchr << 4) & 0x003F0000; // next 6 bits utf8 |= (unchr << 2) & 0x00003F00; // next 6 bits utf8 |= (unchr & 0x3F); // last 6 bits utf8 |= (unsigned)0xF0808080; } return utf8; } __host__ __device__ inline unsigned int u82u( unsigned int utf8 ) { unsigned int unchr = 0; if( utf8 < 0x00000080 ) unchr = utf8; else if( utf8 < 0x0000E000 ) { unchr = (utf8 & 0x1F00) >> 2; unchr |= (utf8 & 0x003F); } else if( utf8 < 0x00F00000 ) { unchr = (utf8 & 0x0F0000) >> 4; unchr |= (utf8 & 0x003F00) >> 2; unchr |= (utf8 & 0x00003F); } else if( utf8 <= (unsigned)0xF8000000 ) { unchr = (utf8 & 0x03000000) >> 6; unchr |= (utf8 & 0x003F0000) >> 4; unchr |= (utf8 & 0x00003F00) >> 2; unchr |= (utf8 & 0x0000003F); } return unchr; } __device__ inline char* copy_and_incr( char*& dest, char* src, unsigned int bytes ) { memcpy(dest,src,bytes); dest += bytes; return dest; } __device__ inline char* copy_and_incr_both( char*& dest, char*& src, unsigned int bytes ) { memcpy(dest,src,bytes); dest += bytes; src += bytes; return dest; } template<typename T> T* device_alloc(size_t count, cudaStream_t sid) { T* buffer = nullptr; rmmError_t rerr = RMM_ALLOC(&buffer,count*sizeof(T),sid); if( rerr != RMM_SUCCESS ) { if( rerr==RMM_ERROR_OUT_OF_MEMORY ) { std::cerr.imbue(std::locale("")); std::cerr << "out of memory on alloc request of " << count << " elements of size " << sizeof(T) << " = " << (count*sizeof(T)) << " bytes\n"; } std::ostringstream message; message << "allocate error " << rerr; throw std::runtime_error(message.str()); } return buffer; }
30.590909
153
0.567013
williamBlazing
e40b071d375e6c34a6ba2f2c5cb143d94831c044
3,712
cpp
C++
src/compete/hackerrank/diagonal-queries.cpp
kinshuk4/algorithm-cpp
4cd81539399d1e745c55625a68b399248d25af66
[ "MIT" ]
null
null
null
src/compete/hackerrank/diagonal-queries.cpp
kinshuk4/algorithm-cpp
4cd81539399d1e745c55625a68b399248d25af66
[ "MIT" ]
null
null
null
src/compete/hackerrank/diagonal-queries.cpp
kinshuk4/algorithm-cpp
4cd81539399d1e745c55625a68b399248d25af66
[ "MIT" ]
null
null
null
//diagonal-queries.cpp //Diagonal Queries //Weekly Challenges - Week 15 //Author: derekhh //May 28, 2015 #include <cstdio> #include <string> #include <algorithm> using namespace std; const int MAX_NODES = 524288; const int MOD = 1000000007; struct Node { int left, right, lazyA, lazyD, sum; }; Node tree[MAX_NODES]; void inc(int& a, int b) { a = (a + b) % MOD; } int muldiv2(int a, int b) { return static_cast<long long>(a)* b % MOD * 500000004LL % MOD; } void build_tree(int node, int a, int b) { tree[node].lazyA = tree[node].lazyD = tree[node].sum = 0; tree[node].left = a; tree[node].right = b; if (a != b) { build_tree(node * 2, a, (a + b) / 2); build_tree(node * 2 + 1, (a + b) / 2 + 1, b); } } void lazyUpdate(int node) { if (tree[node].lazyA != 0 || tree[node].lazyD != 0) { int a0 = tree[node].lazyA, d = tree[node].lazyD, a = tree[node].left, b = tree[node].right; int sum1 = static_cast<long long>(a0)* (b - a + 1) % MOD; int sum2 = muldiv2(static_cast<long long>(b - a)*d % MOD, b - a + 1); int sum = (sum1 + sum2) % MOD; inc(tree[node].sum, sum); if (tree[node].left != tree[node].right) { inc(tree[node * 2].lazyA, tree[node].lazyA); inc(tree[node * 2].lazyD, tree[node].lazyD); int a0_rightChild = (tree[node].lazyA + static_cast<long long>(tree[node].lazyD) * (tree[node * 2 + 1].left - tree[node * 2].left) % MOD) % MOD; inc(tree[node * 2 + 1].lazyA, a0_rightChild); inc(tree[node * 2 + 1].lazyD, tree[node].lazyD); } tree[node].lazyA = 0; tree[node].lazyD = 0; } } void update_tree(int node, int i, int j, int a0, int d) { int a = tree[node].left, b = tree[node].right; if (a > j || b < i) return; lazyUpdate(node); if (a >= i && b <= j) { int newa0 = (a0 + static_cast<long long>(a - i) * d % MOD) % MOD; inc(tree[node].lazyA, newa0); inc(tree[node].lazyD, d); return; } update_tree(node * 2, i, j, a0, d); update_tree(node * 2 + 1, i, j, a0, d); int l = max(a, i), r = min(b, j); int newa0 = (a0 + static_cast<long long>(l - i) * d % MOD) % MOD; int sum1 = static_cast<long long>(newa0)* (r - l + 1) % MOD; int sum2 = muldiv2(static_cast<long long>(r - l)*d % MOD, r - l + 1); int sum = (sum1 + sum2) % MOD; inc(tree[node].sum, sum); } int query_tree(int node, int i, int j) { int a = tree[node].left, b = tree[node].right; if (a > j || b < i) return 0; lazyUpdate(node); if (a >= i && b <= j) return tree[node].sum; int sum1 = query_tree(node * 2, i, j); int sum2 = query_tree(node * 2 + 1, i, j); return (sum1 + sum2) % MOD; } int main() { int n, m, q; scanf("%d%d%d\n", &n, &m, &q); build_tree(1, 1, n + m - 1); char cmd[10]; while (q--) { scanf("%s", cmd); if (cmd[1] == 'c') { int c, d; scanf("%d%d\n", &c, &d); int newbase = static_cast<long long>(n)* d % MOD; update_tree(1, c, c + n - 1, newbase, MOD - d); } else if (cmd[1] == 'r') { int r, d; scanf("%d%d\n", &r, &d); update_tree(1, n - r + 1, n - r + m, d, d); } else if (cmd[1] == 's') { int x1, y1, x2, y2, d; scanf("%d%d%d%d%d\n", &x1, &y1, &x2, &y2, &d); int start = y1 + n - x2, end = y2 + n - x1; int width = min(x2 - x1, y2 - y1); int middle = end - start + 1 - width - width; if (width) { update_tree(1, start, start + width - 1, d, d); int newbase = static_cast<long long>(width)* d % MOD; update_tree(1, end - width + 1, end, newbase, MOD - d); } if (middle) { int newbase = static_cast<long long>(width + 1) * d % MOD; update_tree(1, start + width, end - width, newbase, 0); } } else if (cmd[1] == 'd') { int l, r; scanf("%d%d\n", &l, &r); printf("%d\n", query_tree(1, l, r)); } } return 0; }
22.634146
147
0.555765
kinshuk4
e40e060f6b4b9f522bd7851ac29d8d0972f9c3cf
1,362
cpp
C++
Input.cpp
mateoi/Threes
04619dc1b1c4995dad8d2f6703fc8473bee46d54
[ "MIT" ]
null
null
null
Input.cpp
mateoi/Threes
04619dc1b1c4995dad8d2f6703fc8473bee46d54
[ "MIT" ]
null
null
null
Input.cpp
mateoi/Threes
04619dc1b1c4995dad8d2f6703fc8473bee46d54
[ "MIT" ]
null
null
null
#include "Input.hpp" using namespace std; /** * Asks the user to input a number between min and max. */ int userInput(int min, int max) { int result = min - 1; string input; while (getline(cin, input)) { if (stringstream(input) >> result) { if (result >= min && result <= max) break; } cout << "Please enter a number between " << min << " and " << max << "." << endl; } return result; } vector<int>* userMultiInput(int min, int max) { vector<int>* result = new vector<int>(); string input; while (getline(cin, input)) { result->clear(); stringstream stream(input); string section; int item = min - 1; bool done = false; while (getline(stream, section, ' ')) { if (stringstream(section) >> item) { if (item >= min && item <= max) { result->push_back(item); done = true; continue; } } done = false; break; } if (done) { break; } else { cout << "Please enter numbers between " << min << " and " << max << "." << endl; } } return result; } /* Pause the program and wait for input */ void pauseProgram() { cin.get(); }
24.763636
92
0.473568
mateoi
e412c7e211a7760884952a94bb063390042529b2
857
cpp
C++
subjectplayer.cpp
Ashwin-Parivallal/2D-fighting-game-C-
484093edf9f1b178ecea321d9085431541007034
[ "MIT" ]
null
null
null
subjectplayer.cpp
Ashwin-Parivallal/2D-fighting-game-C-
484093edf9f1b178ecea321d9085431541007034
[ "MIT" ]
null
null
null
subjectplayer.cpp
Ashwin-Parivallal/2D-fighting-game-C-
484093edf9f1b178ecea321d9085431541007034
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include "subjectplayer.h" SubjectPlayer::~SubjectPlayer() { delete player2; } SubjectPlayer::SubjectPlayer( const std::string& name1, const std::string& name2) : Player(name1, true), player2(new SmartPlayer(name2, false)) { } void SubjectPlayer::update(Uint32 ticks) { Player::update(ticks); if(checkForCollisions(player2)){ AvoidCollision(player2->getCurrentFrame()); } static_cast<SmartPlayer* >(player2)->setUserPosition(Player::getPosition()); player2->update(ticks); if(player2->checkForCollisions(this)){ player2->AvoidCollision(getCurrentFrame()); } } void SubjectPlayer::draw() const { Player::draw(); player2->draw(); } void SubjectPlayer::handleKeyStroke(const Uint8 *keystate) { Player::handleKeyStroke(keystate); player2->handleKeyStroke(keystate); }
21.425
83
0.715286
Ashwin-Parivallal
e41423d5bb8b0e66617df8cd562109418da1c544
379
cpp
C++
Project Euler/015_Lattice_Paths.cpp
Togohogo1/pg
ee3c36acde47769c66ee13a227762ee677591375
[ "MIT" ]
null
null
null
Project Euler/015_Lattice_Paths.cpp
Togohogo1/pg
ee3c36acde47769c66ee13a227762ee677591375
[ "MIT" ]
1
2021-10-14T18:26:56.000Z
2021-10-14T18:26:56.000Z
Project Euler/015_Lattice_Paths.cpp
Togohogo1/pg
ee3c36acde47769c66ee13a227762ee677591375
[ "MIT" ]
1
2021-08-06T03:39:55.000Z
2021-08-06T03:39:55.000Z
#include <bits/stdc++.h> using namespace std; long arr[22][22]; int main() { ios_base::sync_with_stdio(0); cin.tie(0), cout.tie(0); arr[1][1] = 1; for (int i = 1; i < 22; i++) { for (int j = 1; j < 22; j++) { if (i != 1 || j != 1) arr[i][j] = arr[i-1][j] + arr[i][j-1]; } } cout << arr[21][21] << endl; }
17.227273
54
0.416887
Togohogo1
e414fdfaaba7a22fe82dad19ec31e33bf65e499e
395
cpp
C++
Chapter8/Calc/MainWindow.cpp
PacktPublishing/Cpp-Windows-Programming
9fa69bd9d7706ae205d0e6c2214c7f001c4533f3
[ "MIT" ]
34
2016-10-03T01:39:25.000Z
2022-03-01T03:21:41.000Z
Cpp Windows Programming/Calc/MainWindow.cpp
PacktPublishing/Cpp-Windows-Programming
9fa69bd9d7706ae205d0e6c2214c7f001c4533f3
[ "MIT" ]
null
null
null
Cpp Windows Programming/Calc/MainWindow.cpp
PacktPublishing/Cpp-Windows-Programming
9fa69bd9d7706ae205d0e6c2214c7f001c4533f3
[ "MIT" ]
31
2016-09-02T08:56:01.000Z
2022-03-12T20:15:21.000Z
#include "..\\SmallWindows\\SmallWindows.h" #include "Token.h" #include "Error.h" #include "Scanner.h" #include "TreeNode.h" #include "Parser.h" #include "Cell.h" #include "CalcDocument.h" void MainWindow(vector<String> /* argumentList */, WindowShow windowShow) { Application::ApplicationName() = TEXT("Calc"); Application::MainWindowPtr()= new CalcDocument(windowShow); }
26.333333
61
0.698734
PacktPublishing
e4166a9ec4dfbcd8e8eed76c7832273f1bd30425
11,968
cc
C++
src/pytheia/matching/matching.cc
urbste/TheiaSfM
a92fa27e90b6182e2a2511a46d24283afad1a995
[ "BSD-3-Clause" ]
3
2019-12-25T03:01:04.000Z
2021-08-04T08:08:45.000Z
src/pytheia/matching/matching.cc
urbste/TheiaSfM
a92fa27e90b6182e2a2511a46d24283afad1a995
[ "BSD-3-Clause" ]
null
null
null
src/pytheia/matching/matching.cc
urbste/TheiaSfM
a92fa27e90b6182e2a2511a46d24283afad1a995
[ "BSD-3-Clause" ]
2
2020-03-20T03:06:55.000Z
2021-08-04T08:08:52.000Z
#include "pytheia/matching/matching.h" #include <pybind11/eigen.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <Eigen/Core> #include <iostream> #include <pybind11/numpy.h> #include <vector> #include "theia/matching/brute_force_feature_matcher.h" #include "theia/matching/cascade_hasher.h" #include "theia/matching/cascade_hashing_feature_matcher.h" #include "theia/matching/feature_matcher.h" #include "theia/matching/feature_matcher_options.h" #include "theia/matching/features_and_matches_database.h" #include "theia/matching/fisher_vector_extractor.h" #include "theia/matching/global_descriptor_extractor.h" #include "theia/matching/indexed_feature_match.h" #include "theia/matching/keypoints_and_descriptors.h" #include "theia/sfm/feature.h" #include "theia/sfm/two_view_match_geometric_verification.h" //#include "theia/matching/rocksdb_features_and_matches_database.h" //#include "theia/matching/local_features_and_matches_database.h" #include "theia/matching/create_feature_matcher.h" #include "theia/matching/in_memory_features_and_matches_database.h" namespace py = pybind11; namespace pytheia { namespace matching { void pytheia_matching_classes(py::module& m) { // FeaturesAndMatchesDatabase py::class_<theia::FeaturesAndMatchesDatabase /*, theia::PyFeaturesAndMatchesDatabase */>(m, "FeaturesAndMatchesDatabase") //.def(py::init<>()) //.def("ContainsCameraIntrinsicsPrior", &theia::FeaturesAndMatchesDatabase::ContainsCameraIntrinsicsPrior) ; // RocksDbFeaturesAndMatchesDatabase // py::class_<theia::RocksDbFeaturesAndMatchesDatabase, // theia::FeaturesAndMatchesDatabase>(m, "RocksDbFeaturesAndMatchesDatabase") // .def(py::init<std::string>()) // .def("ContainsCameraIntrinsicsPrior", // &theia::RocksDbFeaturesAndMatchesDatabase::ContainsCameraIntrinsicsPrior) // .def("GetCameraIntrinsicsPrior", // &theia::RocksDbFeaturesAndMatchesDatabase::GetCameraIntrinsicsPrior) // .def("PutCameraIntrinsicsPrior", // &theia::RocksDbFeaturesAndMatchesDatabase::PutCameraIntrinsicsPrior) // .def("ImageNamesOfCameraIntrinsicsPriors", // &theia::RocksDbFeaturesAndMatchesDatabase::ImageNamesOfCameraIntrinsicsPriors) // .def("NumCameraIntrinsicsPrior", // &theia::RocksDbFeaturesAndMatchesDatabase::NumCameraIntrinsicsPrior) // .def("ContainsFeatures", // &theia::RocksDbFeaturesAndMatchesDatabase::ContainsFeatures) // .def("GetFeatures", // &theia::RocksDbFeaturesAndMatchesDatabase::GetFeatures) // .def("PutFeatures", // &theia::RocksDbFeaturesAndMatchesDatabase::PutFeatures) .def("NumImages", // &theia::RocksDbFeaturesAndMatchesDatabase::NumImages) // .def("GetImagePairMatch", // &theia::RocksDbFeaturesAndMatchesDatabase::GetImagePairMatch) // .def("PutImagePairMatch", // &theia::RocksDbFeaturesAndMatchesDatabase::PutImagePairMatch) // .def("ImageNamesOfMatches", // &theia::RocksDbFeaturesAndMatchesDatabase::ImageNamesOfMatches) // .def("NumMatches", &theia::RocksDbFeaturesAndMatchesDatabase::NumMatches) // .def("RemoveAllMatches", // &theia::RocksDbFeaturesAndMatchesDatabase::RemoveAllMatches) // .def("ImageNamesOfFeatures", // &theia::RocksDbFeaturesAndMatchesDatabase::ImageNamesOfFeatures) // ; // InMemoryFeaturesAndMatchesDatabase py::class_<theia::InMemoryFeaturesAndMatchesDatabase, theia::FeaturesAndMatchesDatabase>( m, "InMemoryFeaturesAndMatchesDatabase") .def(py::init<>()) .def("ContainsFeatures", &theia::InMemoryFeaturesAndMatchesDatabase::ContainsFeatures) .def("GetFeatures", &theia::InMemoryFeaturesAndMatchesDatabase::GetFeatures) .def("PutFeatures", &theia::InMemoryFeaturesAndMatchesDatabase::PutFeatures) .def("ImageNamesOfFeatures", &theia::InMemoryFeaturesAndMatchesDatabase::ImageNamesOfFeatures) .def("NumImages", &theia::InMemoryFeaturesAndMatchesDatabase::NumImages) .def("GetImagePairMatch", &theia::InMemoryFeaturesAndMatchesDatabase::GetImagePairMatch) .def("PutImagePairMatch", &theia::InMemoryFeaturesAndMatchesDatabase::PutImagePairMatch) .def("NumMatches", &theia::InMemoryFeaturesAndMatchesDatabase::NumMatches) .def("PutCameraIntrinsicsPrior", &theia::InMemoryFeaturesAndMatchesDatabase::PutCameraIntrinsicsPrior) .def("GetCameraIntrinsicsPrior", &theia::InMemoryFeaturesAndMatchesDatabase::GetCameraIntrinsicsPrior) .def("NumCameraIntrinsicsPrior", &theia::InMemoryFeaturesAndMatchesDatabase::NumCameraIntrinsicsPrior) .def("ImageNamesOfCameraIntrinsicsPriors", &theia::InMemoryFeaturesAndMatchesDatabase:: ImageNamesOfCameraIntrinsicsPriors) .def("ImageNamesOfMatches", &theia::InMemoryFeaturesAndMatchesDatabase::ImageNamesOfMatches) .def("ContainsCameraIntrinsicsPrior", &theia::InMemoryFeaturesAndMatchesDatabase:: ContainsCameraIntrinsicsPrior) ; py::class_<theia::ImagePairMatch>(m, "ImagePairMatch") .def(py::init<>()) .def_readwrite("image1", &theia::ImagePairMatch::image1) .def_readwrite("image2", &theia::ImagePairMatch::image2) .def_readwrite("twoview_info", &theia::ImagePairMatch::twoview_info) .def_readwrite("correspondences", &theia::ImagePairMatch::correspondences) ; /* //LocalFeaturesAndMatchesDatabase py::class_<theia::LocalFeaturesAndMatchesDatabase, theia::FeaturesAndMatchesDatabase>(m, "LocalFeaturesAndMatchesDatabase") .def(py::init<std::string>()) .def("ContainsFeatures", &theia::LocalFeaturesAndMatchesDatabase::ContainsFeatures) .def("GetFeatures", &theia::LocalFeaturesAndMatchesDatabase::GetFeatures) .def("PutFeatures", &theia::LocalFeaturesAndMatchesDatabase::PutFeatures) .def("ImageNamesOfFeatures", &theia::LocalFeaturesAndMatchesDatabase::ImageNamesOfFeatures) .def("NumImages", &theia::LocalFeaturesAndMatchesDatabase::NumImages) .def("GetImagePairMatch", &theia::LocalFeaturesAndMatchesDatabase::GetImagePairMatch) .def("PutImagePairMatch", &theia::LocalFeaturesAndMatchesDatabase::PutImagePairMatch) .def("NumMatches", &theia::LocalFeaturesAndMatchesDatabase::NumMatches) .def("SaveMatchesAndGeometry", &theia::LocalFeaturesAndMatchesDatabase::SaveMatchesAndGeometry) ; */ // FeatureMatcherOptions py::class_<theia::FeatureMatcherOptions>(m, "FeatureMatcherOptions") .def(py::init<>()) .def_readwrite("num_threads", &theia::FeatureMatcherOptions::num_threads) .def_readwrite("keep_only_symmetric_matches", &theia::FeatureMatcherOptions::keep_only_symmetric_matches) .def_readwrite("use_lowes_ratio", &theia::FeatureMatcherOptions::use_lowes_ratio) .def_readwrite("lowes_ratio", &theia::FeatureMatcherOptions::lowes_ratio) .def_readwrite( "perform_geometric_verification", &theia::FeatureMatcherOptions::perform_geometric_verification) .def_readwrite("min_num_feature_matches", &theia::FeatureMatcherOptions::min_num_feature_matches) .def_readwrite( "geometric_verification_options", &theia::FeatureMatcherOptions::geometric_verification_options) ; // KeypointsAndDescriptors py::class_<theia::KeypointsAndDescriptors>(m, "KeypointsAndDescriptors") .def(py::init<>()) .def_readwrite("image_name", &theia::KeypointsAndDescriptors::image_name) .def_readwrite("keypoints", &theia::KeypointsAndDescriptors::keypoints) .def_readwrite("descriptors", &theia::KeypointsAndDescriptors::descriptors); // IndexedFeatureMatch py::class_<theia::IndexedFeatureMatch>(m, "IndexedFeatureMatch") .def(py::init<>()) .def(py::init<int, int, float>()) .def_readwrite("feature1_ind", &theia::IndexedFeatureMatch::feature1_ind) .def_readwrite("feature2_ind", &theia::IndexedFeatureMatch::feature2_ind) .def_readwrite("distance", &theia::IndexedFeatureMatch::distance); py::class_<theia::FeatureCorrespondence>(m, "FeatureCorrespondence") .def(py::init<>()) .def(py::init<theia::Feature, theia::Feature>()) .def_readwrite("feature1", &theia::FeatureCorrespondence::feature1) .def_readwrite("feature2", &theia::FeatureCorrespondence::feature2) ; // GlobalDescriptorExtractor py::class_<theia::GlobalDescriptorExtractor>(m, "GlobalDescriptorExtractor") // abstract class in the constructor ; // FisherVectorExtractor Options py::class_<theia::FisherVectorExtractor::Options>( m, "FisherVectorExtractorOptions") .def(py::init<>()) .def_readwrite("num_threads", &theia::FisherVectorExtractor::Options::num_gmm_clusters) .def_readwrite( "keep_only_symmetric_matches", &theia::FisherVectorExtractor::Options::max_num_features_for_training) ; // FisherVectorExtractor py::class_<theia::FisherVectorExtractor, theia::GlobalDescriptorExtractor>( m, "FisherVectorExtractor") .def(py::init<theia::FisherVectorExtractor::Options>()) .def("AddFeaturesForTraining", &theia::FisherVectorExtractor::AddFeaturesForTraining) .def("Train", &theia::FisherVectorExtractor::Train) .def("ExtractGlobalDescriptor", &theia::FisherVectorExtractor::ExtractGlobalDescriptor) ; // FeatureMatcher py::class_<theia::FeatureMatcher>(m, "FeatureMatcher") // abstract class in the constructor //.def(py::init<theia::FeatureMatcherOptions, //&theia::FeaturesAndMatchesDatabase>()) .def("AddImages", (void (theia::FeatureMatcher::*)(const std::vector<std::string>&)) & theia::FeatureMatcher::AddImages, py::return_value_policy::reference_internal) .def("AddImage", (void (theia::FeatureMatcher::*)(const std::string&)) & theia::FeatureMatcher::AddImage, py::return_value_policy::reference_internal) .def("MatchImages", &theia::FeatureMatcher::MatchImages) .def("SetImagePairsToMatch", &theia::FeatureMatcher::SetImagePairsToMatch) ; // BruteForceFeatureMatcher py::class_<theia::BruteForceFeatureMatcher, theia::FeatureMatcher>( m, "BruteForceFeatureMatcher") .def(py::init<theia::FeatureMatcherOptions, theia::FeaturesAndMatchesDatabase*>()) // abstract class in the constructor //.def(py::init<theia::FeatureMatcherOptions, //theia::FeaturesAndMatchesDatabase>()) ; // CascadeHashingFeatureMatcher py::class_<theia::CascadeHashingFeatureMatcher, theia::FeatureMatcher>( m, "CascadeHashingFeatureMatcher") // abstract class in the constructor .def(py::init<theia::FeatureMatcherOptions, theia::FeaturesAndMatchesDatabase*>()) .def("AddImages", (void (theia::CascadeHashingFeatureMatcher::*)( const std::vector<std::string>&)) & theia::CascadeHashingFeatureMatcher::AddImages, py::return_value_policy::reference_internal) .def("AddImage", (void (theia::CascadeHashingFeatureMatcher::*)(const std::string&)) & theia::CascadeHashingFeatureMatcher::AddImage, py::return_value_policy::reference_internal) ; py::enum_<theia::MatchingStrategy>(m, "MatchingStrategy") .value("GLOBAL", theia::MatchingStrategy::BRUTE_FORCE) .value("INCREMENTAL", theia::MatchingStrategy::CASCADE_HASHING) .export_values(); } void pytheia_matching(py::module& m) { py::module m_submodule = m.def_submodule("matching"); pytheia_matching_classes(m_submodule); } } // namespace matching } // namespace pytheia
42.896057
123
0.715491
urbste
e41a8001986678f16aa11a3f8d7dc668ba153e1d
3,352
cpp
C++
project/src/common/ColorTransform.cpp
delahee/lime
c4bc1ff140fa27c12f580fa3b518721e2a8266f2
[ "MIT" ]
1
2022-01-19T13:06:26.000Z
2022-01-19T13:06:26.000Z
openfl_lime/src/common/ColorTransform.cpp
wannaphong/flappy
bc4630ca9120463c57c1d756c39c60a6dc509940
[ "MIT" ]
1
2020-11-17T00:58:59.000Z
2020-11-17T00:58:59.000Z
openfl_lime/src/common/ColorTransform.cpp
wannaphong/flappy
bc4630ca9120463c57c1d756c39c60a6dc509940
[ "MIT" ]
null
null
null
#include <Graphics.h> #include <map> namespace lime { static void CombineCol(double &outMultiplier, double &outOff, double inPMultiplier, double inPOff, double inCMultiplier, double inCOff) { outMultiplier = inPMultiplier * inCMultiplier; outOff = inPMultiplier * inCOff + inPOff; } void ColorTransform::Combine(const ColorTransform &inParent, const ColorTransform &inChild) { CombineCol(redMultiplier,redOffset, inParent.redMultiplier,inParent.redOffset, inChild.redMultiplier, inChild.redOffset); CombineCol(greenMultiplier,greenOffset, inParent.greenMultiplier,inParent.greenOffset, inChild.greenMultiplier, inChild.greenOffset); CombineCol(blueMultiplier,blueOffset, inParent.blueMultiplier,inParent.blueOffset, inChild.blueMultiplier, inChild.blueOffset); CombineCol(alphaMultiplier,alphaOffset, inParent.alphaMultiplier,inParent.alphaOffset, inChild.alphaMultiplier, inChild.alphaOffset); } inline uint32 ByteTrans(uint32 inVal, double inMultiplier, double inOffset, int inShift) { double val = ((inVal>>inShift) & 0xff) * inMultiplier + inOffset; if (val<0) return 0; if (val>255) return 0xff<<inShift; return ((int)val) << inShift; } uint32 ColorTransform::Transform(uint32 inVal) const { return ByteTrans(inVal,alphaMultiplier,alphaOffset,24) | ByteTrans(inVal,redMultiplier,redOffset,16) | ByteTrans(inVal,greenMultiplier,greenOffset,8) | ByteTrans(inVal,blueMultiplier,blueOffset,0); } static uint8 *sgIdentityLUT = 0; typedef std::pair<int,int> Trans; struct LUT { int mLastUsed; uint8 mLUT[256]; }; static int sgLUTID = 0; typedef std::map<Trans,LUT> LUTMap; static LUTMap sgLUTs; enum { LUT_CACHE = 256 }; void ColorTransform::TidyCache() { if (sgLUTID>(1<<30)) { sgLUTID = 1; sgLUTs.clear(); } } const uint8 *GetLUT(double inMultiplier, double inOffset) { if (inMultiplier==1 && inOffset==0) { if (sgIdentityLUT==0) { sgIdentityLUT = new uint8[256]; for(int i=0;i<256;i++) sgIdentityLUT[i] = i; } return sgIdentityLUT; } sgLUTID++; Trans t((int)(inMultiplier*128),(int)(inOffset/2)); LUTMap::iterator it = sgLUTs.find(t); if (it!=sgLUTs.end()) { it->second.mLastUsed = sgLUTID; return it->second.mLUT; } if (sgLUTs.size()>LUT_CACHE) { LUTMap::iterator where = sgLUTs.begin(); int oldest = where->second.mLastUsed; for(LUTMap::iterator i=sgLUTs.begin(); i!=sgLUTs.end();++i) { if (i->second.mLastUsed < oldest) { oldest = i->second.mLastUsed; where = i; } } sgLUTs.erase(where); } LUT &lut = sgLUTs[t]; lut.mLastUsed = sgLUTID; for(int i=0;i<256;i++) { double ival = i*inMultiplier + inOffset; lut.mLUT[i] = ival < 0 ? 0 : ival>255 ? 255 : (int)ival; } return lut.mLUT; } const uint8 *ColorTransform::GetAlphaLUT() const { return GetLUT(alphaMultiplier,alphaOffset); } const uint8 *ColorTransform::GetC0LUT() const { if (gC0IsRed) return GetLUT(redMultiplier,redOffset); else return GetLUT(blueMultiplier,blueOffset); } const uint8 *ColorTransform::GetC1LUT() const { return GetLUT(greenMultiplier,greenOffset); } const uint8 *ColorTransform::GetC2LUT() const { if (gC0IsRed) return GetLUT(blueMultiplier,blueOffset); else return GetLUT(redMultiplier,redOffset); } } // end namespace lime
22.198675
99
0.704952
delahee
e41af1e43d798f10575dfba9dc039248f02657be
5,281
cc
C++
check/distance.cc
nicuveo/MCL
ce717de6ebc873b9d18ac0e3d3a8e10e83eb2386
[ "MIT" ]
5
2015-03-25T12:10:08.000Z
2017-11-23T20:19:26.000Z
check/distance.cc
nicuveo/MCL
ce717de6ebc873b9d18ac0e3d3a8e10e83eb2386
[ "MIT" ]
null
null
null
check/distance.cc
nicuveo/MCL
ce717de6ebc873b9d18ac0e3d3a8e10e83eb2386
[ "MIT" ]
null
null
null
// // Copyright Antoine Leblanc 2010 - 2015 // Distributed under the MIT license. // // http://nauths.fr // http://github.com/nicuveo // mailto://antoine.jp.leblanc@gmail.com // //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH // Includes #include <cstdlib> #include <iostream> #include <boost/test/unit_test.hpp> #include "nauths/mcl/mcl.hh" //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH // Implementation BOOST_AUTO_TEST_SUITE(distance) BOOST_AUTO_TEST_CASE(distance_1976) { BOOST_CHECK_CLOSE(mcl::cie_1976(mcl::colors::red(), mcl::colors::yellow()), 114.030440, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1976(mcl::colors::red(), mcl::colors::lime()), 170.565250, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1976(mcl::colors::red(), mcl::colors::cyan()), 156.459940, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1976(mcl::colors::red(), mcl::colors::blue()), 176.313880, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1976(mcl::colors::red(), mcl::colors::magenta()), 129.500940, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1976(mcl::colors::yellow(), mcl::colors::lime()), 66.279822, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1976(mcl::colors::yellow(), mcl::colors::cyan()), 111.965680, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1976(mcl::colors::yellow(), mcl::colors::blue()), 235.146710, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1976(mcl::colors::yellow(), mcl::colors::magenta()), 199.558280, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1976(mcl::colors::lime(), mcl::colors::cyan()), 104.556160, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1976(mcl::colors::lime(), mcl::colors::blue()), 258.682530, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1976(mcl::colors::lime(), mcl::colors::magenta()), 235.580500, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1976(mcl::colors::cyan(), mcl::colors::blue()), 168.651590, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1976(mcl::colors::cyan(), mcl::colors::magenta()), 156.647160, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1976(mcl::colors::blue(), mcl::colors::magenta()), 57.970727, 0.001); } BOOST_AUTO_TEST_CASE(distance_1994) { BOOST_CHECK_CLOSE(mcl::cie_1994(mcl::colors::red(), mcl::colors::yellow()), 59.993149, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1994(mcl::colors::red(), mcl::colors::lime()), 73.430410, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1994(mcl::colors::red(), mcl::colors::cyan()), 67.601815, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1994(mcl::colors::red(), mcl::colors::blue()), 70.580406, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1994(mcl::colors::red(), mcl::colors::magenta()), 50.699880, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1994(mcl::colors::yellow(), mcl::colors::lime()), 27.107184, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1994(mcl::colors::yellow(), mcl::colors::cyan()), 42.723379, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1994(mcl::colors::yellow(), mcl::colors::blue()), 111.858130, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1994(mcl::colors::yellow(), mcl::colors::magenta()), 87.748199, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1994(mcl::colors::lime(), mcl::colors::cyan()), 30.102820, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1994(mcl::colors::lime(), mcl::colors::blue()), 105.904950, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1994(mcl::colors::lime(), mcl::colors::magenta()), 88.030095, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1994(mcl::colors::cyan(), mcl::colors::blue()), 99.896151, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1994(mcl::colors::cyan(), mcl::colors::magenta()), 87.431457, 0.001); BOOST_CHECK_CLOSE(mcl::cie_1994(mcl::colors::blue(), mcl::colors::magenta()), 32.251523, 0.001); } BOOST_AUTO_TEST_CASE(distance_2000) { BOOST_CHECK_CLOSE(mcl::cie_2000(mcl::colors::red(), mcl::colors::yellow()), 64.300859, 0.001); BOOST_CHECK_CLOSE(mcl::cie_2000(mcl::colors::red(), mcl::colors::lime()), 86.608245, 0.001); BOOST_CHECK_CLOSE(mcl::cie_2000(mcl::colors::red(), mcl::colors::cyan()), 70.959107, 0.001); BOOST_CHECK_CLOSE(mcl::cie_2000(mcl::colors::red(), mcl::colors::blue()), 52.881354, 0.001); BOOST_CHECK_CLOSE(mcl::cie_2000(mcl::colors::red(), mcl::colors::magenta()), 42.585671, 0.001); BOOST_CHECK_CLOSE(mcl::cie_2000(mcl::colors::yellow(), mcl::colors::lime()), 23.404276, 0.001); BOOST_CHECK_CLOSE(mcl::cie_2000(mcl::colors::yellow(), mcl::colors::cyan()), 41.973639, 0.001); BOOST_CHECK_CLOSE(mcl::cie_2000(mcl::colors::yellow(), mcl::colors::blue()), 103.426970, 0.001); BOOST_CHECK_CLOSE(mcl::cie_2000(mcl::colors::yellow(), mcl::colors::magenta()), 92.808516, 0.001); BOOST_CHECK_CLOSE(mcl::cie_2000(mcl::colors::lime(), mcl::colors::cyan()), 34.527363, 0.001); BOOST_CHECK_CLOSE(mcl::cie_2000(mcl::colors::lime(), mcl::colors::blue()), 83.185862, 0.001); BOOST_CHECK_CLOSE(mcl::cie_2000(mcl::colors::lime(), mcl::colors::magenta()), 111.414320, 0.001); BOOST_CHECK_CLOSE(mcl::cie_2000(mcl::colors::cyan(), mcl::colors::blue()), 66.466912, 0.001); BOOST_CHECK_CLOSE(mcl::cie_2000(mcl::colors::cyan(), mcl::colors::magenta()), 57.983482, 0.001); BOOST_CHECK_CLOSE(mcl::cie_2000(mcl::colors::blue(), mcl::colors::magenta()), 32.421232, 0.001); } BOOST_AUTO_TEST_SUITE_END()
62.129412
102
0.673736
nicuveo
e426ccdbb433cc5ea3826f64fa64d4efa34eb81a
2,340
cc
C++
include/insnet/operator/param.cc
ishine/N3LDG-plus
7fdfd79b75265487df9240176ca7a2b1adbaadab
[ "Apache-2.0" ]
27
2021-06-07T02:25:33.000Z
2022-03-16T20:41:14.000Z
include/insnet/operator/param.cc
ishine/N3LDG-plus
7fdfd79b75265487df9240176ca7a2b1adbaadab
[ "Apache-2.0" ]
null
null
null
include/insnet/operator/param.cc
ishine/N3LDG-plus
7fdfd79b75265487df9240176ca7a2b1adbaadab
[ "Apache-2.0" ]
3
2021-07-10T15:11:00.000Z
2022-03-06T03:10:30.000Z
#include "insnet/operator/param.h" #include "fmt/core.h" using namespace std; namespace insnet { class ParamNode : public Node, public Poolable<ParamNode> { public: ParamNode() : Node("paramNode") {} void setNodeDim(int dim) override { setDim(dim); } void connect(Graph &graph, BaseParam &param) { if (size() != param.val().size) { cerr << fmt::format("node size:{} param size:{}", size(), param.val().size) << endl; abort(); } param_ = &param; graph.addNode(this); } string typeSignature() const override { return Node::getNodeType() + "-" + addressToString(param_); } void compute() override { val().vec() = param_->val().vec(); } void backward() override { param_->initAndZeroGrad(); param_->grad().vec() += grad().vec(); } Executor* generate() override; protected: int forwardOnlyInputValSize() override { return 0; } bool isValForwardOnly() const override { return true; } private: BaseParam *param_; friend class ParamExecutor; }; Node* param(Graph &graph, BaseParam &param) { ParamNode *node = ParamNode::newNode(param.val().size); node->connect(graph, param); return node; } #if USE_GPU class ParamExecutor : public Executor { public: void forward () override { if (batch.size() > 1) { cerr << "The param op should only be used once in a computation graph. - batch size:" << batch.size() << endl; abort(); } ParamNode &node = dynamic_cast<ParamNode &>(*batch.front()); cuda::ParamForward(node.param_->val().value, node.size(), node.val().value); #if TEST_CUDA Executor::testForward(); #endif } void backward() override { ParamNode &node = dynamic_cast<ParamNode &>(*batch.front()); node.param_->initAndZeroGrad(); cuda::ParamBackward(node.grad().value, node.size(), node.param_->grad().value); #if TEST_CUDA Executor::backward(); node.param_->grad().verify("param backward"); #endif } }; #else class ParamExecutor : public Executor { public: int calculateFLOPs() override { return 0; } }; #endif Executor *ParamNode::generate() { return new ParamExecutor; } }
22.718447
97
0.59359
ishine
e42707a77bc2db612fc15c088c53993191ba5d4f
6,753
cpp
C++
assn2/Item.cpp
jrgoldfinemiddleton/cs162
dea72d9219e748e15a5796177a6b018bcab7816e
[ "BSD-2-Clause" ]
3
2016-11-04T20:18:46.000Z
2019-04-22T05:00:03.000Z
assn2/Item.cpp
jrgoldfinemiddleton/cs162
dea72d9219e748e15a5796177a6b018bcab7816e
[ "BSD-2-Clause" ]
1
2016-11-04T20:23:25.000Z
2016-11-04T20:23:45.000Z
assn2/Item.cpp
jrgoldfinemiddleton/cs162
dea72d9219e748e15a5796177a6b018bcab7816e
[ "BSD-2-Clause" ]
6
2015-12-25T16:14:46.000Z
2019-04-22T05:00:04.000Z
/********************************************************************* ** Program Filename: Item.cpp ** Author: Jason Goldfine-Middleton ** Date: 10/10/15 ** Description: Contains the Item class function declarations and ** a friend function to overload the << and == ** operators. ** Input: std::cin ** Output: std::cout *********************************************************************/ #include "Item.hpp" #include <iostream> // for input and output #include <iomanip> // for manipulating the output stream /********************************************************************* ** Function: Item::Item() ** Description: This constructor initializes an Item with a name, ** a unit type, a quantity, and a unit price. ** Parameters: name the name of the item ** unit the type of unit ** qty the quantity of the unit ** price the unit price ** Pre-Conditions: qty > 1 and price >= 0.00. ** Post-Conditions: An Item with the given information is initialized. *********************************************************************/ Item::Item(std::string name, std::string unit, int qty, double price) : item_name(name), unit(unit), quantity(qty), unit_price(price) { return; } /********************************************************************* ** Function: Item::get_item_name() ** Description: Returns this Item's name. ** Parameters: none ** Pre-Conditions: item_name has been initialized. ** Post-Conditions: Returns the name. This Item is not modified. *********************************************************************/ std::string Item::get_item_name() const { return this->item_name; } /********************************************************************* ** Function: Item::get_unit() ** Description: Returns this Item's unit type. ** Parameters: none ** Pre-Conditions: unit has been initialized. ** Post-Conditions: Returns the unit type. This Item is not ** modified. *********************************************************************/ std::string Item::get_unit() const { return this->unit; } /********************************************************************* ** Function: Item::get_quantity() ** Description: Returns this Item's quantity. ** Parameters: none ** Pre-Conditions: quantity has been initialized. ** Post-Conditions: Returns the quantity. This Item is not ** modified. *********************************************************************/ int Item::get_quantity() const { return this->quantity; } /********************************************************************* ** Function: Item::get_unit_price() ** Description: Returns this Item's unit price. ** Parameters: none ** Pre-Conditions: unit_price has been initialized. ** Post-Conditions: Returns the unit price. This Item is not ** modified. *********************************************************************/ double Item::get_unit_price() const { return this->unit_price; } /********************************************************************* ** Function: Item::get_total_price() ** Description: Returns this Item's total price, taking into accout ** its quantity and unit price. ** Parameters: none ** Pre-Conditions: quantity and unit_price have been initialized. ** Post-Conditions: Returns this Item's total price. This Item is not ** modified. *********************************************************************/ double Item::get_total_price() const { return this->quantity * this->unit_price; } /********************************************************************* ** Function: Item::set_quantity() ** Description: Updates the quantity of this Item to a new value. ** Parameters: qty the new quantity ** Pre-Conditions: qty > 0. ** Post-Conditions: quantity is updated to the value of qty. *********************************************************************/ void Item::set_quantity(const int qty) { this->quantity = qty; } /********************************************************************* ** Function: Item::set_unit_price() ** Description: Updates the unit price of this Item to a new value. ** Parameters: price the new unit price ** Pre-Conditions: price >= 0.00. ** Post-Conditions: unit_price is updated to the value of price. *********************************************************************/ void Item::set_unit_price(const double price) { this->unit_price = price; } /********************************************************************* ** Function: operator<<() ** Description: Allows the operator << to be used for sending a ** set of information about an Item to an object of type ** std::ostream. This operator may be chained. ** Parameters: out the output stream ** it the Item object ** Pre-Conditions: none ** Post-Conditions: A description of it is sent to outstream out. *********************************************************************/ std::ostream& operator<<(std::ostream &out, const Item& it) { // save original precision std::streamsize ss = std::cout.precision(); // add info to stream out << std::setw(50) << std::left << it.item_name << '\n' << '\t' << "unit: " << std::setw(10) << it.unit << " " << "quantity: " << std::setw(5) << it.quantity << " " << std::fixed << std::showpoint << std::setprecision(2) << "unit price: $" << it.unit_price << '\n' << '\t' << "total price: $" << it.get_total_price() << "\n\n" << std::noshowpoint; // restore original ios flags and precision std::resetiosflags(std::ios::fixed); out.precision(ss); return out; } /********************************************************************* ** Function: operator==() ** Description: Allows the operator == to be used for determining ** whether two Item objects are equivalent. Note that ** the quantity property of each Item is irrelevant. ** Parameters: it1 the left-hand Item ** it2 the right-hand Item ** Pre-Conditions: The properties of each Item are fully initialized. ** Post-Conditions: Returns true if the Items are equivalent and false ** otherwise. *********************************************************************/ bool operator==(const Item &it1, const Item &it2) { // true if all properties are the same except quantity return it1.item_name == it2.item_name && it1.unit == it2.unit && it1.unit_price == it2.unit_price; }
34.809278
71
0.48882
jrgoldfinemiddleton
e4273eb47f6be7f8babf73b0d8a6398443d6d9c0
270
hpp
C++
sprout/algorithm/random_swap.hpp
osyo-manga/Sprout
8885b115f739ef255530f772067475d3bc0dcef7
[ "BSL-1.0" ]
1
2020-02-04T05:16:01.000Z
2020-02-04T05:16:01.000Z
sprout/algorithm/random_swap.hpp
osyo-manga/Sprout
8885b115f739ef255530f772067475d3bc0dcef7
[ "BSL-1.0" ]
null
null
null
sprout/algorithm/random_swap.hpp
osyo-manga/Sprout
8885b115f739ef255530f772067475d3bc0dcef7
[ "BSL-1.0" ]
null
null
null
#ifndef SPROUT_ALGORITHM_RANDOM_SWAP_HPP #define SPROUT_ALGORITHM_RANDOM_SWAP_HPP #include <sprout/config.hpp> #include <sprout/algorithm/fixed/random_swap.hpp> #include <sprout/algorithm/fit/random_swap.hpp> #endif // #ifndef SPROUT_ALGORITHM_RANDOM_SWAP_HPP
30
51
0.818519
osyo-manga
e4293bf9205d515b1ff8a60449af538553d6a2fe
205
hpp
C++
Spiel/src/engine/collision/CoreSystemUniforms.hpp
Ipotrick/CPP-2D-Game-Engine
9cd87c369d813904d76668fe6153c7c4e8686023
[ "MIT" ]
null
null
null
Spiel/src/engine/collision/CoreSystemUniforms.hpp
Ipotrick/CPP-2D-Game-Engine
9cd87c369d813904d76668fe6153c7c4e8686023
[ "MIT" ]
null
null
null
Spiel/src/engine/collision/CoreSystemUniforms.hpp
Ipotrick/CPP-2D-Game-Engine
9cd87c369d813904d76668fe6153c7c4e8686023
[ "MIT" ]
null
null
null
#pragma once #include "../../engine/math/Vec2.hpp" struct PhysicsUniforms { float friction{ 0 }; Vec2 linearEffectDir{ 0, 0 }; float linearEffectAccel{ 0 }; float linearEffectForce{ 0 }; private: };
18.636364
37
0.697561
Ipotrick
e4295314b026a4b0dedd7510281a792208835205
753
cpp
C++
chapter-18/18.10.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
chapter-18/18.10.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
chapter-18/18.10.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
#include <iostream> #include "Sales_data.hpp" #include "Sales_data_exception.hpp" using std::cerr; using std::endl; using std::cin; int main() { Sales_data item1, item2, sum; while(cin >> item1 >> item2) sum = item1 + item2; // just like said in section 18.1.1 // for on throwed exception, if there is no matched catch expression // program calls std library function terminate to terminate program processing } // int main() // { // Sales_data item1, item2, sum; // while(cin >> item1 >> item2) // { // try // { // sum = item1 + item2; // } // catch(const isbn_mismatch &e) // { // cerr << e.what() << ": left isbn(" << e.left // << ") right isbn(" << e.right << ")" << endl; // } // } // }
20.916667
81
0.579017
zero4drift
e429fa09f0c9db13bdc07df1015b3a7300628c95
133
cpp
C++
UVA/level 2/1124 - Celebrity Jeopardy.cpp
lieahau/Online-Judge-Solution
26d81d1783cbdd9294455f00b77fb3dbaedd0c01
[ "MIT" ]
1
2020-04-13T11:12:19.000Z
2020-04-13T11:12:19.000Z
UVA/level 2/1124 - Celebrity Jeopardy.cpp
lieahau/Online-Judge-Solution
26d81d1783cbdd9294455f00b77fb3dbaedd0c01
[ "MIT" ]
null
null
null
UVA/level 2/1124 - Celebrity Jeopardy.cpp
lieahau/Online-Judge-Solution
26d81d1783cbdd9294455f00b77fb3dbaedd0c01
[ "MIT" ]
null
null
null
#include <stdio.h> int main() { char arr[100]; while(gets(arr)) { puts(arr); } return 0; }
10.230769
21
0.421053
lieahau
e42ad18b94fe05f9f5416be0d17f65fade18c723
6,685
cpp
C++
cmdstan/stan/src/test/unit/io/program_reader_test.cpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
1
2018-05-15T16:13:05.000Z
2018-05-15T16:13:05.000Z
cmdstan/stan/src/test/unit/io/program_reader_test.cpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/src/test/unit/io/program_reader_test.cpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
#include <stan/io/program_reader.hpp> #include <gtest/gtest.h> #include <iostream> #include <sstream> std::vector<std::string> create_search_path() { std::vector<std::string> search_path; search_path.push_back("foo"); search_path.push_back("src/test/test-models/included/"); search_path.push_back("bar/baz"); return search_path; } void expect_eq_traces(const std::vector<std::pair<std::string, int> >& e, const std::vector<std::pair<std::string, int> >& f) { EXPECT_EQ(e.size(), f.size()); for (size_t i = 0; i < e.size(); ++i) { EXPECT_EQ(e[i].first, f[i].first); EXPECT_EQ(e[i].second, f[i].second); } } void expect_trace(stan::io::program_reader& reader, int pos, const std::string& path1, int pos1) { using std::pair; using std::string; using std::vector; vector<pair<string, int> > expected; expected.push_back(pair<string, int>(path1, pos1)); vector<pair<string, int> > found = reader.trace(pos); expect_eq_traces(expected, found); } void expect_trace(stan::io::program_reader& reader, int pos, const std::string& path1, int pos1, const std::string& path2, int pos2) { using std::pair; using std::string; using std::vector; vector<pair<string, int> > expected; expected.push_back(pair<string, int>(path1, pos1)); expected.push_back(pair<string, int>(path2, pos2)); vector<pair<string, int> > found = reader.trace(pos); expect_eq_traces(expected, found); } void expect_trace(stan::io::program_reader& reader, int pos, const std::string& path1, int pos1, const std::string& path2, int pos2, const std::string& path3, int pos3) { using std::pair; using std::string; using std::vector; vector<pair<string, int> > expected; expected.push_back(pair<string, int>(path1, pos1)); expected.push_back(pair<string, int>(path2, pos2)); expected.push_back(pair<string, int>(path3, pos3)); vector<pair<string, int> > found = reader.trace(pos); expect_eq_traces(expected, found); } TEST(prog_reader, one) { using std::pair; using std::string; using stan::io::program_reader; std::stringstream ss; ss << "parameters {\n" // 1 << " real y;\n" // 2 << "}\n" // 3 << "model {\n" // 4 << " y ~ normal(0, 1);\n" // 5 << "}\n" // 6 << ""; // 7 (nothing on line) std::vector<std::string> search_path = create_search_path(); stan::io::program_reader reader(ss, "foo", search_path); EXPECT_EQ("parameters {\n" " real y;\n" "}\n" "model {\n" " y ~ normal(0, 1);\n" "}\n", reader.program()); for (int i = 1; i < 7; ++i) expect_trace(reader, i, "foo", i); EXPECT_THROW(reader.trace(0), std::runtime_error); EXPECT_THROW(reader.trace(7), std::runtime_error); } TEST(prog_reader, two) { using std::vector; using std::string; std::stringstream ss; ss << "functions {\n" << "#include incl_fun.stan\n" << "}\n" << "#include incl_params.stan\n" << "model {\n" << "}\n"; vector<string> search_path = create_search_path(); stan::io::program_reader reader(ss, "foo", search_path); EXPECT_EQ("functions {\n" " int foo() {\n" " return 1;\n" " }\n" "}\n" "parameters {\n" " real y;\n" "}\n" "model {\n" "}\n", reader.program()); expect_trace(reader, 1, "foo", 1); expect_trace(reader, 2, "foo", 2, "incl_fun.stan", 1); expect_trace(reader, 3, "foo", 2, "incl_fun.stan", 2); expect_trace(reader, 4, "foo", 2, "incl_fun.stan", 3); expect_trace(reader, 5, "foo", 3); expect_trace(reader, 6, "foo", 4, "incl_params.stan", 1); expect_trace(reader, 7, "foo", 4, "incl_params.stan", 2); expect_trace(reader, 8, "foo", 4, "incl_params.stan", 3); expect_trace(reader, 9, "foo", 5); expect_trace(reader, 10, "foo", 6); EXPECT_THROW(reader.trace(0), std::runtime_error); EXPECT_THROW(reader.trace(11), std::runtime_error); } TEST(prog_reader, three) { using std::vector; using std::string; std::stringstream ss; ss << "functions {\n" << "#include incl_rec.stan\n" << "}\n" << "model { }\n"; vector<string> search_path = create_search_path(); stan::io::program_reader reader(ss, "foo", search_path); EXPECT_EQ("functions {\n" "parameters {\n" "real y;\n" "real z;\n" "}\n" "transformed parameters {\n" " real w = y + z;\n" "}\n" "}\n" "model { }\n", reader.program()); expect_trace(reader, 1, "foo", 1); expect_trace(reader, 2, "foo", 2, "incl_rec.stan", 1); expect_trace(reader, 3, "foo", 2, "incl_rec.stan", 2, "incl_nested.stan", 1); expect_trace(reader, 4, "foo", 2, "incl_rec.stan", 2, "incl_nested.stan", 2); expect_trace(reader, 5, "foo", 2, "incl_rec.stan", 3); expect_trace(reader, 6, "foo", 2, "incl_rec.stan", 4); expect_trace(reader, 7, "foo", 2, "incl_rec.stan", 5); expect_trace(reader, 8, "foo", 2, "incl_rec.stan", 6); expect_trace(reader, 9, "foo", 3); expect_trace(reader, 10, "foo", 4); EXPECT_THROW(reader.trace(0), std::runtime_error); EXPECT_THROW(reader.trace(11), std::runtime_error); } TEST(prog_reader, ignoreRecursive) { using std::vector; using std::string; std::stringstream ss; ss << "functions {\n" << "#include badrecurse1.stan\n" << "}\n" << "model { }\n"; vector<string> search_path = create_search_path(); stan::io::program_reader reader(ss, "foo", search_path); EXPECT_EQ("functions {\n}\nmodel { }\n", reader.program()); } TEST(prog_reader, ignoreRecursive2) { using std::vector; using std::string; std::stringstream ss; ss << "functions {\n" << "#include badrecurse2.stan\n" << "}\n" << "model { }\n"; vector<string> search_path = create_search_path(); stan::io::program_reader reader(ss, "foo", search_path); EXPECT_EQ("functions {\n}\nmodel { }\n", reader.program()); } TEST(prog_reader, allowSequential) { using std::vector; using std::string; std::stringstream ss; ss << "functions {\n" << "#include simple1.stan\n" << "#include simple1.stan\n" << "}\n" << "model { }\n"; vector<string> search_path = create_search_path(); stan::io::program_reader reader(ss, "foo", search_path); EXPECT_EQ("functions {\n// foo\n// foo\n}\nmodel { }\n", reader.program()); }
30.949074
79
0.583994
yizhang-cae
e431af34e0549ec0308dafb190899697049eb25b
6,870
cpp
C++
resources/kate/flow/common.cpp
illia-zemlianytskyi/flow9
a300f2b0f0129c10079c10bad56b015e4a05885e
[ "MIT" ]
583
2019-04-26T11:52:35.000Z
2022-02-22T17:53:19.000Z
resources/kate/flow/common.cpp
illia-zemlianytskyi/flow9
a300f2b0f0129c10079c10bad56b015e4a05885e
[ "MIT" ]
279
2019-04-26T11:53:17.000Z
2022-02-21T13:35:08.000Z
resources/kate/flow/common.cpp
illia-zemlianytskyi/flow9
a300f2b0f0129c10079c10bad56b015e4a05885e
[ "MIT" ]
44
2019-04-29T18:09:19.000Z
2021-12-23T16:06:05.000Z
#include <stdexcept> #include <QFile> #include <QFileInfo> #include <QDateTime> #include <QDir> #include <QTextCursor> #include <KTextEditor/View> #include "common.hpp" namespace flow { QString curFile(KTextEditor::MainWindow* mainWindow) { return mainWindow->activeView()->document()->url().toLocalFile(); } QString curIdentifier(KTextEditor::View* activeView) { if (!activeView || !activeView->cursorPosition().isValid()) { return QString(); } const int line = activeView->cursorPosition().line(); const int col = activeView->cursorPosition().column(); QString linestr = activeView->document()->line(line); int startPos = qMax(qMin(col, linestr.length() - 1), 0); int endPos = startPos; while (startPos >= 0) { bool inId = linestr[startPos].isLetterOrNumber(); inId = inId || (linestr[startPos] == QLatin1Char('_')); inId = inId || (linestr[startPos] == QLatin1Char('-')); if (!inId) { break; } -- startPos; } while (endPos < linestr.length()) { bool inId = linestr[endPos].isLetterOrNumber(); inId = inId || (linestr[endPos] == QLatin1Char('_')); inId = inId || (linestr[endPos] == QLatin1Char('-')); if (!inId) { break; } ++ endPos; } if (startPos == endPos) { return QString(); } return linestr.mid(startPos + 1, endPos - startPos - 1); } QString stripQuotes(const QString& str) { if (str.isEmpty()) { return QString(); } else if (str.length() == 1) { return (str[0].toLatin1() == '"') ? QString() : str; } else { int beg = (str[0].toLatin1() == '"') ? 1 : 0; int len = ((str[str.length() - 1].toLatin1() == '"') ? str.length() - 1 : str.length()) - beg; return str.mid(beg, len); } } QTableWidgetItem* setNotEditable(QTableWidgetItem* item) { Qt::ItemFlags flags = item->flags(); item->setFlags(flags & ~Qt::ItemIsEditable); return item; } QString findConfig(const QString& file) { QFileInfo fileInfo(file); if (!fileInfo.exists()) { throw std::runtime_error("file '" + file.toStdString() + "' doesn't exist"); } QDir dir = fileInfo.dir(); while (true) { QFileInfoList conf = dir.entryInfoList(QStringList(QLatin1String("flow.config"))); if (!conf.isEmpty()) { return conf[0].absoluteFilePath(); } else if (dir.isRoot()) { break; } else { dir.cdUp(); } } return QString(); } ConfigFile parseConfig(const QString& confName) { if (!QFileInfo(confName).exists()) { throw std::runtime_error("file '" + confName.toStdString() + "' doesn't exist"); } QFile confFile(confName); QMap<QString, QString> ret; if (confFile.open(QIODevice::ReadOnly)) { QTextStream in(&confFile); while(!in.atEnd()) { QString line = in.readLine().trimmed(); if (!line.isEmpty() && !line.startsWith(QLatin1Char('#'))) { QStringList fields = line.split(QLatin1Char('=')); QString name = fields[0].toLower().trimmed(); QString value = fields[1].trimmed(); if (name == QLatin1String("include")) { value.replace(QLatin1Char(' '), QString()); } ret[name] = value; } } } return ret; } QString findFlowRoot(const QString& file) { QFileInfo fileInfo(file); QDir dir = fileInfo.dir(); QStringList flowStuff; flowStuff << QLatin1String("*.flow") << QLatin1String("flow.config"); while (true) { QFileInfoList conf = dir.entryInfoList(flowStuff); if (!conf.isEmpty()) { dir.cdUp(); } else { QFileInfoList siblings = dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot); int siblingsWithFlowStuff = 0; for (QFileInfo sibling : siblings) { if (sibling.isDir()) { QDir d(sibling.filePath() + QDir::separator()); if (d.entryInfoList(flowStuff).count() > 0) { ++siblingsWithFlowStuff; } } else if (sibling.isFile()) { if (sibling.suffix() == QLatin1String("flow")) { ++siblingsWithFlowStuff; } } } // A heuristic: siblings with flowfiles must be not less, then 1/3 of all siblings, // otherwise the previous dir is what we search for if (siblingsWithFlowStuff * 3 < siblings.count()) { break; } else { dir.cdUp(); } } } return dir.path(); } void progTimestamps(ProgTimestamps& map, const QString& name, const QStringList& includes) { if (map.contains(name)) { return; } map[name] = QFileInfo(name).lastModified(); QFile file(name); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return; } static QString importPrefix = QLatin1String("import"); static int importPrefixLen = importPrefix.length(); while (!file.atEnd()) { QString line = QString::fromLatin1(file.readLine()); if (line.startsWith(importPrefix)) { // remove prefix " import " line = line.trimmed().mid(importPrefixLen).trimmed(); // remove postfix ";" line = line.mid(0, line.indexOf(QLatin1Char(';'))); bool found = false; for (auto inc : includes) { if (!inc.endsWith(QLatin1Char('/'))) { inc += QLatin1Char('/'); } QString importPath = inc + line + QLatin1String(".flow"); QFileInfo import(importPath); if (import.isFile()) { progTimestamps(map, import.absoluteFilePath(), includes); found = true; break; } } if (!found) { QTextStream(stdout) << "file import: '" << line << "' is not found\n"; map[line] = QDateTime(); } } } } ProgTimestamps progTimestamps(const QString& file, const QString& dir, const QStringList& includes) { ProgTimestamps map; QDir current = QDir::current(); QDir::setCurrent(dir); progTimestamps(map, file, includes); QDir::setCurrent(current.path()); return map; } bool progTimestampsChanged(const ProgTimestamps& dep1, const ProgTimestamps& dep2) { if (dep1.count() != dep2.count()) { return true; } for (const auto& k : dep1.keys()) { if (dep1[k].toMSecsSinceEpoch() != dep2[k].toMSecsSinceEpoch()) { return true; } } return false; } QByteArray progTimestampsToBinary(const ProgTimestamps& timestamps) { QByteArray buffer; QDataStream out(&buffer, QIODevice::WriteOnly); out << timestamps; return buffer; } ProgTimestamps progTimestampsFromBinary(const QByteArray& buffer) { QDataStream in(buffer); ProgTimestamps timestamps; in >> timestamps; return timestamps; } void appendText(QPlainTextEdit* textEdit, const QString& text) { textEdit->moveCursor (QTextCursor::End); textEdit->insertPlainText(text); textEdit->moveCursor (QTextCursor::End); } QString locationNeighbourhood(const QString& str, int line, int col, int width) { for (int i = 0, l = 0, c = 0; i < str.size(); ++ i) { if (str[i] == QLatin1Char('\n')) { ++l; c = 0; } else { ++c; } if (l == line && c == col) { return str.mid(std::max(i - width, 0) / 2, std::min(width, str.size() - width)); } } return QString(); } }
27.926829
101
0.63246
illia-zemlianytskyi
e4374b836b2a6e1e4ceda604eef5dba640748804
10,512
cpp
C++
ProcessLib/HeatTransportBHE/HeatTransportBHEProcess.cpp
Bernie2019/ogs
80b66724d72d8ce01e02ddcd1fb6866c90b41c1d
[ "BSD-4-Clause" ]
null
null
null
ProcessLib/HeatTransportBHE/HeatTransportBHEProcess.cpp
Bernie2019/ogs
80b66724d72d8ce01e02ddcd1fb6866c90b41c1d
[ "BSD-4-Clause" ]
null
null
null
ProcessLib/HeatTransportBHE/HeatTransportBHEProcess.cpp
Bernie2019/ogs
80b66724d72d8ce01e02ddcd1fb6866c90b41c1d
[ "BSD-4-Clause" ]
2
2018-03-01T13:07:12.000Z
2018-03-01T13:16:22.000Z
/** * \file * \copyright * Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include "HeatTransportBHEProcess.h" #include <cassert> #include "ProcessLib/HeatTransportBHE/BHE/MeshUtils.h" #include "ProcessLib/HeatTransportBHE/LocalAssemblers/CreateLocalAssemblers.h" #include "ProcessLib/HeatTransportBHE/LocalAssemblers/HeatTransportBHELocalAssemblerBHE.h" #include "ProcessLib/HeatTransportBHE/LocalAssemblers/HeatTransportBHELocalAssemblerSoil.h" #include "BoundaryConditions/BHEBottomDirichletBoundaryCondition.h" #include "BoundaryConditions/BHEInflowDirichletBoundaryCondition.h" namespace ProcessLib { namespace HeatTransportBHE { HeatTransportBHEProcess::HeatTransportBHEProcess( std::string name, MeshLib::Mesh& mesh, std::unique_ptr<ProcessLib::AbstractJacobianAssembler>&& jacobian_assembler, std::vector<std::unique_ptr<ParameterLib::ParameterBase>> const& parameters, unsigned const integration_order, std::vector<std::vector<std::reference_wrapper<ProcessVariable>>>&& process_variables, HeatTransportBHEProcessData&& process_data, SecondaryVariableCollection&& secondary_variables, NumLib::NamedFunctionCaller&& named_function_caller) : Process(std::move(name), mesh, std::move(jacobian_assembler), parameters, integration_order, std::move(process_variables), std::move(secondary_variables), std::move(named_function_caller)), _process_data(std::move(process_data)), _bheMeshData(getBHEDataInMesh(mesh)) { if (_bheMeshData.BHE_mat_IDs.size() != _process_data._vec_BHE_property.size()) { OGS_FATAL( "The number of the given BHE properties (%d) are not consistent " "with the number of BHE groups in the mesh (%d).", _process_data._vec_BHE_property.size(), _bheMeshData.BHE_mat_IDs.size()); } auto material_ids = MeshLib::materialIDs(mesh); if (material_ids == nullptr) { OGS_FATAL("Not able to get material IDs! "); } _process_data._mesh_prop_materialIDs = material_ids; // create a map from a material ID to a BHE ID for (int i = 0; i < static_cast<int>(_bheMeshData.BHE_mat_IDs.size()); i++) { // fill in the map structure _process_data._map_materialID_to_BHE_ID[_bheMeshData.BHE_mat_IDs[i]] = i; } } void HeatTransportBHEProcess::constructDofTable() { // Create single component dof in every of the mesh's nodes. _mesh_subset_all_nodes = std::make_unique<MeshLib::MeshSubset>(_mesh, _mesh.getNodes()); // // Soil temperature variable defined on the whole mesh. // _mesh_subset_soil_nodes = std::make_unique<MeshLib::MeshSubset>(_mesh, _mesh.getNodes()); std::vector<MeshLib::MeshSubset> all_mesh_subsets{*_mesh_subset_soil_nodes}; std::vector<std::vector<MeshLib::Element*> const*> vec_var_elements; vec_var_elements.push_back(&(_mesh.getElements())); std::vector<int> vec_n_components{ 1}; // one component for the soil temperature variable. // // BHE nodes with BHE type dependend number of variables. // int const n_BHEs = _process_data._vec_BHE_property.size(); assert(n_BHEs == static_cast<int>(_bheMeshData.BHE_mat_IDs.size())); assert(n_BHEs == static_cast<int>(_bheMeshData.BHE_nodes.size())); assert(n_BHEs == static_cast<int>(_bheMeshData.BHE_elements.size())); // the BHE nodes need to be cherry-picked from the vector for (int i = 0; i < n_BHEs; i++) { auto const number_of_unknowns = visit([](auto const& bhe) { return bhe.number_of_unknowns; }, _process_data._vec_BHE_property[i]); auto const& bhe_nodes = _bheMeshData.BHE_nodes[i]; auto const& bhe_elements = _bheMeshData.BHE_elements[i]; // All the BHE nodes have additional variables. _mesh_subset_BHE_nodes.push_back( std::make_unique<MeshLib::MeshSubset const>(_mesh, bhe_nodes)); std::generate_n( std::back_inserter(all_mesh_subsets), // Here the number of components equals to the // number of unknowns on the BHE number_of_unknowns, [& ms = _mesh_subset_BHE_nodes.back()]() { return *ms; }); vec_n_components.push_back(number_of_unknowns); vec_var_elements.push_back(&bhe_elements); } _local_to_global_index_map = std::make_unique<NumLib::LocalToGlobalIndexMap>( std::move(all_mesh_subsets), vec_n_components, vec_var_elements, NumLib::ComponentOrder::BY_COMPONENT); // in case of debugging the dof table, activate the following line // std::cout << *_local_to_global_index_map << "\n"; } void HeatTransportBHEProcess::initializeConcreteProcess( NumLib::LocalToGlobalIndexMap const& dof_table, MeshLib::Mesh const& mesh, unsigned const integration_order) { // Quick access map to BHE's through element ids. std::unordered_map<std::size_t, BHE::BHETypes*> element_to_bhe_map; int const n_BHEs = _process_data._vec_BHE_property.size(); for (int i = 0; i < n_BHEs; i++) { auto const& bhe_elements = _bheMeshData.BHE_elements[i]; for (auto const& e : bhe_elements) { element_to_bhe_map[e->getID()] = &_process_data._vec_BHE_property[i]; } } assert(mesh.getDimension() == 3); ProcessLib::HeatTransportBHE::createLocalAssemblers< HeatTransportBHELocalAssemblerSoil, HeatTransportBHELocalAssemblerBHE>( mesh.getElements(), dof_table, _local_assemblers, element_to_bhe_map, mesh.isAxiallySymmetric(), integration_order, _process_data); // Create BHE boundary conditions for each of the BHEs createBHEBoundaryConditionTopBottom(_bheMeshData.BHE_nodes); } void HeatTransportBHEProcess::assembleConcreteProcess( const double t, double const dt, GlobalVector const& x, int const process_id, GlobalMatrix& M, GlobalMatrix& K, GlobalVector& b) { DBUG("Assemble HeatTransportBHE process."); ProcessLib::ProcessVariable const& pv = getProcessVariables(process_id)[0]; std::vector<std::reference_wrapper<NumLib::LocalToGlobalIndexMap>> dof_table = {std::ref(*_local_to_global_index_map)}; // Call global assembler for each local assembly item. GlobalExecutor::executeSelectedMemberDereferenced( _global_assembler, &VectorMatrixAssembler::assemble, _local_assemblers, pv.getActiveElementIDs(), dof_table, t, dt, x, process_id, M, K, b, _coupled_solutions); } void HeatTransportBHEProcess::assembleWithJacobianConcreteProcess( const double /*t*/, double const /*dt*/, GlobalVector const& /*x*/, GlobalVector const& /*xdot*/, const double /*dxdot_dx*/, const double /*dx_dx*/, int const /*process_id*/, GlobalMatrix& /*M*/, GlobalMatrix& /*K*/, GlobalVector& /*b*/, GlobalMatrix& /*Jac*/) { OGS_FATAL( "HeatTransportBHE: analytical Jacobian assembly is not implemented"); } void HeatTransportBHEProcess::computeSecondaryVariableConcrete( const double t, GlobalVector const& x, int const process_id) { DBUG("Compute heat flux for HeatTransportBHE process."); ProcessLib::ProcessVariable const& pv = getProcessVariables(process_id)[0]; GlobalExecutor::executeSelectedMemberOnDereferenced( &HeatTransportBHELocalAssemblerInterface::computeSecondaryVariable, _local_assemblers, pv.getActiveElementIDs(), getDOFTable(process_id), t, x, _coupled_solutions); } void HeatTransportBHEProcess::createBHEBoundaryConditionTopBottom( std::vector<std::vector<MeshLib::Node*>> const& all_bhe_nodes) { const int process_id = 0; auto& bcs = _boundary_conditions[process_id]; int const n_BHEs = static_cast<int>(_process_data._vec_BHE_property.size()); // for each BHE for (int bhe_i = 0; bhe_i < n_BHEs; bhe_i++) { auto const& bhe_nodes = all_bhe_nodes[bhe_i]; // find the variable ID // the soil temperature is 0-th variable // the BHE temperature is therefore bhe_i + 1 const int variable_id = bhe_i + 1; // Bottom and top nodes w.r.t. the z coordinate. auto const bottom_top_nodes = std::minmax_element( begin(bhe_nodes), end(bhe_nodes), [&](auto const& a, auto const& b) { return a->getCoords()[2] < b->getCoords()[2]; }); auto const bc_bottom_node_id = (*bottom_top_nodes.first)->getID(); auto const bc_top_node_id = (*bottom_top_nodes.second)->getID(); auto get_global_bhe_bc_indices = [&](std::size_t const node_id, std::pair<int, int> const& in_out_component_id) { return std::make_pair( _local_to_global_index_map->getGlobalIndex( {_mesh.getID(), MeshLib::MeshItemType::Node, node_id}, variable_id, in_out_component_id.first), _local_to_global_index_map->getGlobalIndex( {_mesh.getID(), MeshLib::MeshItemType::Node, node_id}, variable_id, in_out_component_id.second)); }; auto createBCs = [&](auto& bhe) { for (auto const& in_out_component_id : bhe.inflow_outflow_bc_component_ids) { // Top, inflow. bcs.addBoundaryCondition( createBHEInflowDirichletBoundaryCondition( get_global_bhe_bc_indices(bc_top_node_id, in_out_component_id), [&bhe](double const T, double const t) { return bhe.updateFlowRateAndTemperature(T, t); })); // Bottom, outflow. bcs.addBoundaryCondition( createBHEBottomDirichletBoundaryCondition( get_global_bhe_bc_indices(bc_bottom_node_id, in_out_component_id))); } }; visit(createBCs, _process_data._vec_BHE_property[bhe_i]); } } } // namespace HeatTransportBHE } // namespace ProcessLib
39.969582
91
0.664193
Bernie2019
e438d20e1e888d06fa6ce1b7c3d92985fe8765f1
12,123
cpp
C++
DeviceCode/pal/tinycrt/tinycrt.cpp
yangjunjiao/NetmfSTM32
62ddb8aa0362b83d2e73f3621a56593988e3620f
[ "Apache-2.0" ]
4
2019-01-21T11:47:53.000Z
2020-06-09T02:14:15.000Z
DeviceCode/pal/tinycrt/tinycrt.cpp
yisea123/NetmfSTM32
62ddb8aa0362b83d2e73f3621a56593988e3620f
[ "Apache-2.0" ]
null
null
null
DeviceCode/pal/tinycrt/tinycrt.cpp
yisea123/NetmfSTM32
62ddb8aa0362b83d2e73f3621a56593988e3620f
[ "Apache-2.0" ]
4
2019-01-21T11:48:00.000Z
2021-05-04T12:37:55.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <tinyhal.h> //--// /* ADS Specific functions to avoid the semihosting environment */ //--// #if defined(__arm) extern "C" { #if !defined(PLATFORM_ARM_OS_PORT) void __rt_div0() { NATIVE_PROFILE_PAL_CRT(); #if defined(BUILD_RTM) // failure, reset immediately CPU_Reset(); #else lcd_printf("\fERROR:\r\n__rt_div0\r\n"); debug_printf("ERROR: __rt_div0\r\n"); HARD_BREAKPOINT(); #endif } void __rt_exit (int /*returncode*/) {} void __rt_raise( int sig, int type ) { NATIVE_PROFILE_PAL_CRT(); #if defined(BUILD_RTM) // failure, reset immediately CPU_Reset(); #else lcd_printf("\fERROR:\r\n__rt_raise(%d, %d)\r\n", sig, type); debug_printf("ERROR: __rt_raise(%d, %d)\r\n", sig, type); HARD_BREAKPOINT(); #endif } #endif //!defined(PLATFORM_ARM_OS_PORT) } #endif //--// /* STDIO stubs */ //--// #if !defined(BUILD_RTM) static LOGGING_CALLBACK LoggingCallback; void hal_fprintf_SetLoggingCallback( LOGGING_CALLBACK fpn ) { NATIVE_PROFILE_PAL_CRT(); LoggingCallback = fpn; } #endif //--// int hal_printf( const char* format, ... ) { NATIVE_PROFILE_PAL_CRT(); va_list arg_ptr; va_start(arg_ptr, format); int chars = hal_vprintf( format, arg_ptr ); va_end( arg_ptr ); return chars; } int hal_vprintf( const char* format, va_list arg ) { NATIVE_PROFILE_PAL_CRT(); return hal_vfprintf( HalSystemConfig.stdio, format, arg ); } int hal_fprintf( COM_HANDLE stream, const char* format, ... ) { NATIVE_PROFILE_PAL_CRT(); va_list arg_ptr; int chars; va_start( arg_ptr, format ); chars = hal_vfprintf( stream, format, arg_ptr ); va_end( arg_ptr ); return chars; } int hal_vfprintf( COM_HANDLE stream, const char* format, va_list arg ) { NATIVE_PROFILE_PAL_CRT(); char buffer[512]; int chars = 0; chars = hal_vsnprintf( buffer, sizeof(buffer), format, arg ); switch(ExtractTransport(stream)) { case USART_TRANSPORT: case USB_TRANSPORT: case SOCKET_TRANSPORT: DebuggerPort_Write( stream, buffer, chars ); // skip null terminator break; #if !defined(BUILD_RTM) case FLASH_WRITE_TRANSPORT: if(LoggingCallback) { buffer[chars] = 0; LoggingCallback( buffer ); } break; #endif case LCD_TRANSPORT: { for(int i = 0; i < chars; i++) { LCD_WriteFormattedChar( buffer[i] ); } } break; } return chars; } #if !defined(PLATFORM_EMULATED_FLOATINGPOINT) int hal_snprintf_float( char* buffer, size_t len, const char* format, float f ) { NATIVE_PROFILE_PAL_CRT(); // GCC vsnprintf corrupts memory with floating point values #if defined(__GNUC__) INT64 i = (INT64)f; int pow=0; if((float)0x7FFFFFFFFFFFFFFFll < f || (float)(-0x7FFFFFFFFFFFFFFFll) > f) { while(f >= 10.0 || f <= -10.0) { f = f / 10.0; pow++; } float dec = f - (float)(INT64)f; if(dec < 0.0) dec = -dec; dec *= 1000000000ull; return hal_snprintf( buffer, len, "%d.%llue+%d", (int)f, (UINT64)dec, pow); } else if(f != 0.0 && (INT64)f == 0) { char zeros[32]; while(f < 1.0 && f > -1.0) { f = f * 10.0; pow--; } float dec = f - (float)(INT64)f; if(dec < 0.0) dec = -dec; //count the number of leading zeros double dec2 = dec; int num_zeros = 0; while(dec2 < 0.1 && dec2 > -0.1 && dec2 != 0 && num_zeros < ARRAYSIZE(zeros)-1) { dec2 *= 10; zeros[num_zeros++] = '0'; } //create a string containing the leading zeros zeros[num_zeros] = '\0'; dec *= 1000000000ull; return hal_snprintf( buffer, len, "%d.%s%llue%d", (int)f, zeros, (UINT64)dec, pow); } else { INT64 i = (INT64)f; f = f - (double)(INT64)f; if(f < 0) f = -f; f *= 1000000000ull; return hal_snprintf( buffer, len, "%lld.%09llu", i, (UINT64)f); } #else return hal_snprintf( buffer, len, format, f ); #endif } int hal_snprintf_double( char* buffer, size_t len, const char* format, double d ) { NATIVE_PROFILE_PAL_CRT(); // GCC vsnprintf corrupts memory with floating point values #if defined(__GNUC__) int pow=0; if((double)0x7FFFFFFFFFFFFFFFll < d || (double)(-0x7FFFFFFFFFFFFFFFll) > d) { while(d >= 10.0 || d <= -10.0) { d = d / 10.0; pow++; } double dec = d - (double)(INT64)d; if(dec < 0.0) dec = -dec; dec *= 100000000000000000ull; return hal_snprintf( buffer, len, "%d.%llue+%d", (int)d, (UINT64)dec, pow); } else if(d != 0.0 && (INT64)d == 0) { char zeros[32]; while(d < 1.0 && d > -1.0) { d = d * 10.0; pow--; } double dec = d - (double)(INT64)d; if(dec < 0.0) dec = -dec; //count the number of leading zeros double dec2 = dec; int num_zeros = 0; while(dec2 < 0.1 && dec2 > -0.1 && dec2 != 0 && num_zeros < ARRAYSIZE(zeros)-1) { dec2 *= 10; zeros[num_zeros++] = '0'; } //create a string containing the leading zeros zeros[num_zeros] = '\0'; dec *= 100000000000000000ull; return hal_snprintf( buffer, len, "%d.%s%llue%d", (int)d, zeros, (UINT64)dec, pow); } else { INT64 i = (INT64)d; d = d - (double)(INT64)d; if(d < 0) d = -d; d *= 100000000000000000ull; return hal_snprintf( buffer, len, "%lld.%017llu", i, (UINT64)d); } #else return hal_snprintf( buffer, len, format, d ); #endif } #else // no floating point, fixed point int hal_snprintf_float( char* buffer, size_t len, const char* format, INT32 f ) { NATIVE_PROFILE_PAL_CRT(); UINT32 i ; UINT32 dec; if ( f < 0 ) { // neagive number i = (UINT32) -f ; dec = i & (( 1<<HAL_FLOAT_SHIFT) -1 ); i = (i >>HAL_FLOAT_SHIFT); if (dec !=0) dec = (dec * (UINT32)HAL_FLOAT_PRECISION + (1<< (HAL_FLOAT_SHIFT-1))) >>HAL_FLOAT_SHIFT; return hal_snprintf( buffer, len, "-%d.%03u", i, (UINT32)dec); } else { // positive number i = (UINT32) f ; dec = f & (( 1<<HAL_FLOAT_SHIFT) -1 ); i =(UINT32)( i >>HAL_FLOAT_SHIFT); if (dec !=0) dec = (dec * (UINT32)HAL_FLOAT_PRECISION + (1<< (HAL_FLOAT_SHIFT-1))) >>HAL_FLOAT_SHIFT; return hal_snprintf( buffer, len, "%d.%03u", i, (UINT32)dec); } } int hal_snprintf_double( char* buffer, size_t len, const char* format, INT64& d ) { NATIVE_PROFILE_PAL_CRT(); UINT64 i; UINT32 dec; // 32 bit is enough for decimal part if ( d < 0 ) { // negative number i = (UINT64)-d; i += ((1 << (HAL_DOUBLE_SHIFT-1)) / HAL_DOUBLE_PRECISION); // add broad part of rounding increment before split dec = i & (( 1<<HAL_DOUBLE_SHIFT) -1 ); i = i >> HAL_DOUBLE_SHIFT ; if (dec !=0) dec = (dec * HAL_DOUBLE_PRECISION + ((1 << (HAL_DOUBLE_SHIFT-1)) % HAL_DOUBLE_PRECISION)) >> HAL_DOUBLE_SHIFT; return hal_snprintf( buffer, len, "-%lld.%04u", (INT64)i, (UINT32)dec); } else { // positive number i = (UINT64)d; i += ((1 << (HAL_DOUBLE_SHIFT-1)) / HAL_DOUBLE_PRECISION); // add broad part of rounding increment before split dec = i & (( 1<<HAL_DOUBLE_SHIFT) -1 ); i = i >> HAL_DOUBLE_SHIFT; if (dec !=0) dec = (dec * HAL_DOUBLE_PRECISION + ((1 << (HAL_DOUBLE_SHIFT-1)) % HAL_DOUBLE_PRECISION)) >> HAL_DOUBLE_SHIFT; return hal_snprintf( buffer, len, "%lld.%04u", (INT64)i, (UINT32)dec); } } #endif int hal_snprintf( char* buffer, size_t len, const char* format, ... ) { NATIVE_PROFILE_PAL_CRT(); va_list arg_ptr; int chars; va_start( arg_ptr, format ); chars = hal_vsnprintf( buffer, len, format, arg_ptr ); va_end( arg_ptr ); return chars; } #if defined(__GNUC__) // RealView and GCC signatures for hal_vsnprintf() are different. // This routine matches the RealView call, which defines va_list as int** // rather than void* for GNUC. // RealView calls to hal_vsnprintf() come here, then are converted to // the gcc call. int hal_vsnprintf( char* buffer, size_t len, const char* format, int* args ) { NATIVE_PROFILE_PAL_CRT(); hal_vsnprintf( buffer, len, format, (va_list) (args) ); // The GNU & RealView va_list actually differ only by a level of indirection } #endif #if defined(__RENESAS__) int hal_vsnprintf( char* buffer, size_t len, const char* format, va_list arg ) { NATIVE_PROFILE_PAL_CRT(); return vsprintf(buffer, format, arg); } #elif defined(__GNUC__) || defined(PLATFORM_BLACKFIN) int hal_vsnprintf( char* buffer, size_t len, const char* format, va_list arg ) { #undef vsnprintf return vsnprintf( buffer, len, format, arg ); #define vsnprintf DoNotUse_*printf [] } #elif defined(__arm) int hal_vsnprintf( char* buffer, size_t len, const char* format, va_list arg ) { NATIVE_PROFILE_PAL_CRT(); #if defined(HAL_REDUCESIZE) || defined(PLATFORM_EMULATED_FLOATINGPOINT) #undef _vsnprintf // _vsnprintf do not support floating point, vs vsnprintf supports floating point return _vsnprintf( buffer, len, format, arg ); #define _vsnprintf DoNotUse_*printf [] #else #undef vsnprintf return vsnprintf( buffer, len, format, arg ); #define vsnprintf DoNotUse_*printf [] #endif } #endif #if !defined(PLATFORM_BLACKFIN) int hal_strcpy_s ( char* strDst, size_t sizeInBytes, const char* strSrc ) { NATIVE_PROFILE_PAL_CRT(); #undef strcpy size_t len; if(strDst == NULL || strSrc == NULL || sizeInBytes == 0) {return 1;} len = hal_strlen_s(strSrc); if(sizeInBytes < len + 1) {return 1;} strcpy( strDst, strSrc ); return 0; #define strcpy DoNotUse_*strcpy [] } int hal_strncpy_s ( char* strDst, size_t sizeInBytes, const char* strSrc, size_t count ) { NATIVE_PROFILE_PAL_CRT(); #undef strncpy if(strDst == NULL || strSrc == NULL || sizeInBytes == 0) {return 1;} if (sizeInBytes < count + 1) { strDst[0] = 0; return 1; } strDst[count] = 0; strncpy( strDst, strSrc, count ); return 0; #define strncpy DoNotUse_*strncpy [] } size_t hal_strlen_s (const char * str) { NATIVE_PROFILE_PAL_CRT(); const char *eos = str; while( *eos++ ) ; return( eos - str - 1 ); } int hal_strncmp_s ( const char* str1, const char* str2, size_t num ) { NATIVE_PROFILE_PAL_CRT(); #undef strncmp if(str1 == NULL || str2 == NULL) {return 1;} return strncmp( str1, str2, num ); #define strncmp DoNotUse_*strncmp [] } #endif //!defined(PLATFORM_BLACKFIN) // Compares 2 ASCII strings case insensitive. Does not take locale into account. int hal_stricmp( const char * dst, const char * src ) { int f = 0, l = 0; do { if ( ((f = (unsigned char)(*(dst++))) >= 'A') && (f <= 'Z') ) { f -= 'A' - 'a'; } if ( ((l = (unsigned char)(*(src++))) >= 'A') && (l <= 'Z') ) { l -= 'A' - 'a'; } } while ( f && (f == l) ); return(f - l); }
22.916824
200
0.554978
yangjunjiao
e43972c8c29dcece927f451813ec0f4c06bfb901
21,364
cpp
C++
apps/mysql-5.1.65/storage/ndb/test/ndbapi/testMgm.cpp
vusec/firestarter
2048c1f731b8f3c5570a920757f9d7730d5f716a
[ "Apache-2.0" ]
3
2021-04-29T07:59:16.000Z
2021-12-10T02:23:05.000Z
apps/mysql-5.1.65/storage/ndb/test/ndbapi/testMgm.cpp
vusec/firestarter
2048c1f731b8f3c5570a920757f9d7730d5f716a
[ "Apache-2.0" ]
null
null
null
apps/mysql-5.1.65/storage/ndb/test/ndbapi/testMgm.cpp
vusec/firestarter
2048c1f731b8f3c5570a920757f9d7730d5f716a
[ "Apache-2.0" ]
null
null
null
/* Copyright (C) 2003 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <NDBT.hpp> #include <NDBT_Test.hpp> #include <HugoTransactions.hpp> #include <UtilTransactions.hpp> #include <NdbRestarter.hpp> #include <Vector.hpp> #include <random.h> #include <mgmapi.h> #include <mgmapi_debug.h> #include <ndb_logevent.h> #include <InputStream.hpp> #include <signaldata/EventReport.hpp> int runLoadTable(NDBT_Context* ctx, NDBT_Step* step){ int records = ctx->getNumRecords(); HugoTransactions hugoTrans(*ctx->getTab()); if (hugoTrans.loadTable(GETNDB(step), records) != 0){ return NDBT_FAILED; } return NDBT_OK; } int runClearTable(NDBT_Context* ctx, NDBT_Step* step){ int records = ctx->getNumRecords(); UtilTransactions utilTrans(*ctx->getTab()); if (utilTrans.clearTable2(GETNDB(step), records) != 0){ return NDBT_FAILED; } return NDBT_OK; } int create_index_on_pk(Ndb* pNdb, const char* tabName){ int result = NDBT_OK; const NdbDictionary::Table * tab = NDBT_Table::discoverTableFromDb(pNdb, tabName); // Create index const char* idxName = "IDX_ON_PK"; ndbout << "Create: " <<idxName << "( "; NdbDictionary::Index pIdx(idxName); pIdx.setTable(tabName); pIdx.setType(NdbDictionary::Index::UniqueHashIndex); for (int c = 0; c< tab->getNoOfPrimaryKeys(); c++){ pIdx.addIndexColumn(tab->getPrimaryKey(c)); ndbout << tab->getPrimaryKey(c)<<" "; } ndbout << ") "; if (pNdb->getDictionary()->createIndex(pIdx) != 0){ ndbout << "FAILED!" << endl; const NdbError err = pNdb->getDictionary()->getNdbError(); ERR(err); result = NDBT_FAILED; } else { ndbout << "OK!" << endl; } return result; } int drop_index_on_pk(Ndb* pNdb, const char* tabName){ int result = NDBT_OK; const char* idxName = "IDX_ON_PK"; ndbout << "Drop: " << idxName; if (pNdb->getDictionary()->dropIndex(idxName, tabName) != 0){ ndbout << "FAILED!" << endl; const NdbError err = pNdb->getDictionary()->getNdbError(); ERR(err); result = NDBT_FAILED; } else { ndbout << "OK!" << endl; } return result; } #define CHECK(b) if (!(b)) { \ g_err << "ERR: "<< step->getName() \ << " failed on line " << __LINE__ << endl; \ result = NDBT_FAILED; \ continue; } int runTestSingleUserMode(NDBT_Context* ctx, NDBT_Step* step){ int result = NDBT_OK; int loops = ctx->getNumLoops(); int records = ctx->getNumRecords(); Ndb* pNdb = GETNDB(step); NdbRestarter restarter; char tabName[255]; strncpy(tabName, ctx->getTab()->getName(), 255); ndbout << "tabName="<<tabName<<endl; int i = 0; int count; HugoTransactions hugoTrans(*ctx->getTab()); UtilTransactions utilTrans(*ctx->getTab()); while (i<loops && result == NDBT_OK) { g_info << i << ": "; int timeout = 120; // Test that the single user mode api can do everything CHECK(restarter.enterSingleUserMode(pNdb->getNodeId()) == 0); CHECK(restarter.waitClusterSingleUser(timeout) == 0); CHECK(hugoTrans.loadTable(pNdb, records, 128) == 0); CHECK(hugoTrans.pkReadRecords(pNdb, records) == 0); CHECK(hugoTrans.pkUpdateRecords(pNdb, records) == 0); CHECK(utilTrans.selectCount(pNdb, 64, &count) == 0); CHECK(count == records); CHECK(hugoTrans.pkDelRecords(pNdb, records/2) == 0); CHECK(hugoTrans.scanReadRecords(pNdb, records/2, 0, 64) == 0); CHECK(utilTrans.selectCount(pNdb, 64, &count) == 0); CHECK(count == (records/2)); CHECK(utilTrans.clearTable(pNdb, records/2) == 0); CHECK(restarter.exitSingleUserMode() == 0); CHECK(restarter.waitClusterStarted(timeout) == 0); // Test create index in single user mode CHECK(restarter.enterSingleUserMode(pNdb->getNodeId()) == 0); CHECK(restarter.waitClusterSingleUser(timeout) == 0); CHECK(create_index_on_pk(pNdb, tabName) == 0); CHECK(hugoTrans.loadTable(pNdb, records, 128) == 0); CHECK(hugoTrans.pkReadRecords(pNdb, records) == 0); CHECK(hugoTrans.pkUpdateRecords(pNdb, records) == 0); CHECK(utilTrans.selectCount(pNdb, 64, &count) == 0); CHECK(count == records); CHECK(hugoTrans.pkDelRecords(pNdb, records/2) == 0); CHECK(drop_index_on_pk(pNdb, tabName) == 0); CHECK(restarter.exitSingleUserMode() == 0); CHECK(restarter.waitClusterStarted(timeout) == 0); // Test recreate index in single user mode CHECK(create_index_on_pk(pNdb, tabName) == 0); CHECK(hugoTrans.loadTable(pNdb, records, 128) == 0); CHECK(utilTrans.selectCount(pNdb, 64, &count) == 0); CHECK(restarter.enterSingleUserMode(pNdb->getNodeId()) == 0); CHECK(restarter.waitClusterSingleUser(timeout) == 0); CHECK(drop_index_on_pk(pNdb, tabName) == 0); CHECK(utilTrans.selectCount(pNdb, 64, &count) == 0); CHECK(create_index_on_pk(pNdb, tabName) == 0); CHECK(restarter.exitSingleUserMode() == 0); CHECK(restarter.waitClusterStarted(timeout) == 0); CHECK(drop_index_on_pk(pNdb, tabName) == 0); CHECK(utilTrans.clearTable(GETNDB(step), records) == 0); ndbout << "Restarting cluster" << endl; CHECK(restarter.restartAll() == 0); CHECK(restarter.waitClusterStarted(timeout) == 0); CHECK(pNdb->waitUntilReady(timeout) == 0); i++; } return result; } int runTestApiSession(NDBT_Context* ctx, NDBT_Step* step) { char *mgm= ctx->getRemoteMgm(); Uint64 session_id= 0; NdbMgmHandle h; h= ndb_mgm_create_handle(); ndb_mgm_set_connectstring(h, mgm); ndb_mgm_connect(h,0,0,0); int s= ndb_mgm_get_fd(h); session_id= ndb_mgm_get_session_id(h); ndbout << "MGM Session id: " << session_id << endl; write(s,"get",3); ndb_mgm_disconnect(h); ndb_mgm_destroy_handle(&h); struct NdbMgmSession sess; int slen= sizeof(struct NdbMgmSession); h= ndb_mgm_create_handle(); ndb_mgm_set_connectstring(h, mgm); ndb_mgm_connect(h,0,0,0); NdbSleep_SecSleep(1); if(ndb_mgm_get_session(h,session_id,&sess,&slen)) { ndbout << "Failed, session still exists" << endl; ndb_mgm_disconnect(h); ndb_mgm_destroy_handle(&h); return NDBT_FAILED; } else { ndbout << "SUCCESS: session is gone" << endl; ndb_mgm_disconnect(h); ndb_mgm_destroy_handle(&h); return NDBT_OK; } } int runTestApiConnectTimeout(NDBT_Context* ctx, NDBT_Step* step) { char *mgm= ctx->getRemoteMgm(); int result= NDBT_FAILED; int cc= 0; int mgmd_nodeid= 0; ndb_mgm_reply reply; NdbMgmHandle h; h= ndb_mgm_create_handle(); ndb_mgm_set_connectstring(h, mgm); ndbout << "TEST connect timeout" << endl; ndb_mgm_set_timeout(h, 3000); struct timeval tstart, tend; int secs; timerclear(&tstart); timerclear(&tend); gettimeofday(&tstart,NULL); ndb_mgm_connect(h,0,0,0); gettimeofday(&tend,NULL); secs= tend.tv_sec - tstart.tv_sec; ndbout << "Took about: " << secs <<" seconds"<<endl; if(secs < 4) result= NDBT_OK; else goto done; ndb_mgm_set_connectstring(h, mgm); ndbout << "TEST connect timeout" << endl; ndb_mgm_destroy_handle(&h); h= ndb_mgm_create_handle(); ndb_mgm_set_connectstring(h, "1.1.1.1"); ndbout << "TEST connect timeout (invalid host)" << endl; ndb_mgm_set_timeout(h, 3000); timerclear(&tstart); timerclear(&tend); gettimeofday(&tstart,NULL); ndb_mgm_connect(h,0,0,0); gettimeofday(&tend,NULL); secs= tend.tv_sec - tstart.tv_sec; ndbout << "Took about: " << secs <<" seconds"<<endl; if(secs < 4) result= NDBT_OK; else result= NDBT_FAILED; done: ndb_mgm_disconnect(h); ndb_mgm_destroy_handle(&h); return result; } int runTestApiTimeoutBasic(NDBT_Context* ctx, NDBT_Step* step) { char *mgm= ctx->getRemoteMgm(); int result= NDBT_FAILED; int cc= 0; int mgmd_nodeid= 0; ndb_mgm_reply reply; NdbMgmHandle h; h= ndb_mgm_create_handle(); ndb_mgm_set_connectstring(h, mgm); ndbout << "TEST timout check_connection" << endl; int errs[] = { 1, 2, 3, -1}; for(int error_ins_no=0; errs[error_ins_no]!=-1; error_ins_no++) { int error_ins= errs[error_ins_no]; ndbout << "trying error " << error_ins << endl; ndb_mgm_connect(h,0,0,0); if(ndb_mgm_check_connection(h) < 0) { result= NDBT_FAILED; goto done; } mgmd_nodeid= ndb_mgm_get_mgmd_nodeid(h); if(mgmd_nodeid==0) { ndbout << "Failed to get mgmd node id to insert error" << endl; result= NDBT_FAILED; goto done; } reply.return_code= 0; if(ndb_mgm_insert_error(h, mgmd_nodeid, error_ins, &reply)< 0) { ndbout << "failed to insert error " << endl; result= NDBT_FAILED; goto done; } ndb_mgm_set_timeout(h,2500); cc= ndb_mgm_check_connection(h); if(cc < 0) result= NDBT_OK; else result= NDBT_FAILED; if(ndb_mgm_is_connected(h)) { ndbout << "FAILED: still connected" << endl; result= NDBT_FAILED; } } ndbout << "TEST get_mgmd_nodeid" << endl; ndb_mgm_connect(h,0,0,0); if(ndb_mgm_insert_error(h, mgmd_nodeid, 0, &reply)< 0) { ndbout << "failed to remove inserted error " << endl; result= NDBT_FAILED; goto done; } cc= ndb_mgm_get_mgmd_nodeid(h); ndbout << "got node id: " << cc << endl; if(cc==0) { ndbout << "FAILED: didn't get node id" << endl; result= NDBT_FAILED; } else result= NDBT_OK; ndbout << "TEST end_session" << endl; ndb_mgm_connect(h,0,0,0); if(ndb_mgm_insert_error(h, mgmd_nodeid, 4, &reply)< 0) { ndbout << "FAILED: insert error 1" << endl; result= NDBT_FAILED; goto done; } cc= ndb_mgm_end_session(h); if(cc==0) { ndbout << "FAILED: success in calling end_session" << endl; result= NDBT_FAILED; } else if(ndb_mgm_get_latest_error(h)!=ETIMEDOUT) { ndbout << "FAILED: Incorrect error code (" << ndb_mgm_get_latest_error(h) << " != expected " << ETIMEDOUT << ") desc: " << ndb_mgm_get_latest_error_desc(h) << " line: " << ndb_mgm_get_latest_error_line(h) << " msg: " << ndb_mgm_get_latest_error_msg(h) << endl; result= NDBT_FAILED; } else result= NDBT_OK; if(ndb_mgm_is_connected(h)) { ndbout << "FAILED: is still connected after error" << endl; result= NDBT_FAILED; } done: ndb_mgm_disconnect(h); ndb_mgm_destroy_handle(&h); return result; } int runTestApiGetStatusTimeout(NDBT_Context* ctx, NDBT_Step* step) { char *mgm= ctx->getRemoteMgm(); int result= NDBT_OK; int cc= 0; int mgmd_nodeid= 0; NdbMgmHandle h; h= ndb_mgm_create_handle(); ndb_mgm_set_connectstring(h, mgm); int errs[] = { 0, 5, 6, 7, 8, 9, -1 }; for(int error_ins_no=0; errs[error_ins_no]!=-1; error_ins_no++) { int error_ins= errs[error_ins_no]; ndb_mgm_connect(h,0,0,0); if(ndb_mgm_check_connection(h) < 0) { result= NDBT_FAILED; goto done; } mgmd_nodeid= ndb_mgm_get_mgmd_nodeid(h); if(mgmd_nodeid==0) { ndbout << "Failed to get mgmd node id to insert error" << endl; result= NDBT_FAILED; goto done; } ndb_mgm_reply reply; reply.return_code= 0; if(ndb_mgm_insert_error(h, mgmd_nodeid, error_ins, &reply)< 0) { ndbout << "failed to insert error " << error_ins << endl; result= NDBT_FAILED; } ndbout << "trying error: " << error_ins << endl; ndb_mgm_set_timeout(h,2500); struct ndb_mgm_cluster_state *cl= ndb_mgm_get_status(h); if(cl!=NULL) free(cl); /* * For whatever strange reason, * get_status is okay with not having the last enter there. * instead of "fixing" the api, let's have a special case * so we don't break any behaviour */ if(error_ins!=0 && error_ins!=9 && cl!=NULL) { ndbout << "FAILED: got a ndb_mgm_cluster_state back" << endl; result= NDBT_FAILED; } if(error_ins!=0 && error_ins!=9 && ndb_mgm_is_connected(h)) { ndbout << "FAILED: is still connected after error" << endl; result= NDBT_FAILED; } if(error_ins!=0 && error_ins!=9 && ndb_mgm_get_latest_error(h)!=ETIMEDOUT) { ndbout << "FAILED: Incorrect error code (" << ndb_mgm_get_latest_error(h) << " != expected " << ETIMEDOUT << ") desc: " << ndb_mgm_get_latest_error_desc(h) << " line: " << ndb_mgm_get_latest_error_line(h) << " msg: " << ndb_mgm_get_latest_error_msg(h) << endl; result= NDBT_FAILED; } } done: ndb_mgm_disconnect(h); ndb_mgm_destroy_handle(&h); return result; } int runTestMgmApiGetConfigTimeout(NDBT_Context* ctx, NDBT_Step* step) { char *mgm= ctx->getRemoteMgm(); int result= NDBT_OK; int mgmd_nodeid= 0; NdbMgmHandle h; h= ndb_mgm_create_handle(); ndb_mgm_set_connectstring(h, mgm); int errs[] = { 0, 1, 2, 3, -1 }; for(int error_ins_no=0; errs[error_ins_no]!=-1; error_ins_no++) { int error_ins= errs[error_ins_no]; ndb_mgm_connect(h,0,0,0); if(ndb_mgm_check_connection(h) < 0) { result= NDBT_FAILED; goto done; } mgmd_nodeid= ndb_mgm_get_mgmd_nodeid(h); if(mgmd_nodeid==0) { ndbout << "Failed to get mgmd node id to insert error" << endl; result= NDBT_FAILED; goto done; } ndb_mgm_reply reply; reply.return_code= 0; if(ndb_mgm_insert_error(h, mgmd_nodeid, error_ins, &reply)< 0) { ndbout << "failed to insert error " << error_ins << endl; result= NDBT_FAILED; } ndbout << "trying error: " << error_ins << endl; ndb_mgm_set_timeout(h,2500); struct ndb_mgm_configuration *c= ndb_mgm_get_configuration(h,0); if(c!=NULL) free(c); if(error_ins!=0 && c!=NULL) { ndbout << "FAILED: got a ndb_mgm_configuration back" << endl; result= NDBT_FAILED; } if(error_ins!=0 && ndb_mgm_is_connected(h)) { ndbout << "FAILED: is still connected after error" << endl; result= NDBT_FAILED; } if(error_ins!=0 && ndb_mgm_get_latest_error(h)!=ETIMEDOUT) { ndbout << "FAILED: Incorrect error code (" << ndb_mgm_get_latest_error(h) << " != expected " << ETIMEDOUT << ") desc: " << ndb_mgm_get_latest_error_desc(h) << " line: " << ndb_mgm_get_latest_error_line(h) << " msg: " << ndb_mgm_get_latest_error_msg(h) << endl; result= NDBT_FAILED; } } done: ndb_mgm_disconnect(h); ndb_mgm_destroy_handle(&h); return result; } int runTestMgmApiEventTimeout(NDBT_Context* ctx, NDBT_Step* step) { char *mgm= ctx->getRemoteMgm(); int result= NDBT_OK; int mgmd_nodeid= 0; NdbMgmHandle h; h= ndb_mgm_create_handle(); ndb_mgm_set_connectstring(h, mgm); int errs[] = { 10000, 0, -1 }; for(int error_ins_no=0; errs[error_ins_no]!=-1; error_ins_no++) { int error_ins= errs[error_ins_no]; ndb_mgm_connect(h,0,0,0); if(ndb_mgm_check_connection(h) < 0) { result= NDBT_FAILED; goto done; } mgmd_nodeid= ndb_mgm_get_mgmd_nodeid(h); if(mgmd_nodeid==0) { ndbout << "Failed to get mgmd node id to insert error" << endl; result= NDBT_FAILED; goto done; } ndb_mgm_reply reply; reply.return_code= 0; if(ndb_mgm_insert_error(h, mgmd_nodeid, error_ins, &reply)< 0) { ndbout << "failed to insert error " << error_ins << endl; result= NDBT_FAILED; } ndbout << "trying error: " << error_ins << endl; ndb_mgm_set_timeout(h,2500); int filter[] = { 15, NDB_MGM_EVENT_CATEGORY_BACKUP, 1, NDB_MGM_EVENT_CATEGORY_STARTUP, 0 }; int fd= ndb_mgm_listen_event(h, filter); if(fd==NDB_INVALID_SOCKET) { ndbout << "FAILED: could not listen to event" << endl; result= NDBT_FAILED; } Uint32 theData[25]; EventReport *fake_event = (EventReport*)theData; fake_event->setEventType(NDB_LE_NDBStopForced); fake_event->setNodeId(42); theData[2]= 0; theData[3]= 0; theData[4]= 0; theData[5]= 0; ndb_mgm_report_event(h, theData, 6); char *tmp= 0; char buf[512]; SocketInputStream in(fd,2000); for(int i=0; i<20; i++) { if((tmp = in.gets(buf, sizeof(buf)))) { // const char ping_token[]="<PING>"; // if(memcmp(ping_token,tmp,sizeof(ping_token)-1)) if(tmp && strlen(tmp)) ndbout << tmp; } else { if(in.timedout()) { ndbout << "TIMED OUT READING EVENT at iteration " << i << endl; break; } } } /* * events go through a *DIFFERENT* socket than the NdbMgmHandle * so we should still be connected (and be able to check_connection) * */ if(ndb_mgm_check_connection(h) && !ndb_mgm_is_connected(h)) { ndbout << "FAILED: is still connected after error" << endl; result= NDBT_FAILED; } ndb_mgm_disconnect(h); } done: ndb_mgm_disconnect(h); ndb_mgm_destroy_handle(&h); return result; } int runTestMgmApiStructEventTimeout(NDBT_Context* ctx, NDBT_Step* step) { char *mgm= ctx->getRemoteMgm(); int result= NDBT_OK; int mgmd_nodeid= 0; NdbMgmHandle h; h= ndb_mgm_create_handle(); ndb_mgm_set_connectstring(h, mgm); int errs[] = { 10000, 0, -1 }; for(int error_ins_no=0; errs[error_ins_no]!=-1; error_ins_no++) { int error_ins= errs[error_ins_no]; ndb_mgm_connect(h,0,0,0); if(ndb_mgm_check_connection(h) < 0) { result= NDBT_FAILED; goto done; } mgmd_nodeid= ndb_mgm_get_mgmd_nodeid(h); if(mgmd_nodeid==0) { ndbout << "Failed to get mgmd node id to insert error" << endl; result= NDBT_FAILED; goto done; } ndb_mgm_reply reply; reply.return_code= 0; if(ndb_mgm_insert_error(h, mgmd_nodeid, error_ins, &reply)< 0) { ndbout << "failed to insert error " << error_ins << endl; result= NDBT_FAILED; } ndbout << "trying error: " << error_ins << endl; ndb_mgm_set_timeout(h,2500); int filter[] = { 15, NDB_MGM_EVENT_CATEGORY_BACKUP, 1, NDB_MGM_EVENT_CATEGORY_STARTUP, 0 }; NdbLogEventHandle le_handle= ndb_mgm_create_logevent_handle(h, filter); struct ndb_logevent le; for(int i=0; i<20; i++) { if(error_ins==0 || (error_ins!=0 && i<5)) { Uint32 theData[25]; EventReport *fake_event = (EventReport*)theData; fake_event->setEventType(NDB_LE_NDBStopForced); fake_event->setNodeId(42); theData[2]= 0; theData[3]= 0; theData[4]= 0; theData[5]= 0; ndb_mgm_report_event(h, theData, 6); } int r= ndb_logevent_get_next(le_handle, &le, 2500); if(r>0) { ndbout << "Receieved event" << endl; } else if(r<0) { ndbout << "ERROR" << endl; } else // no event { ndbout << "TIMED OUT READING EVENT at iteration " << i << endl; if(error_ins==0) result= NDBT_FAILED; else result= NDBT_OK; break; } } /* * events go through a *DIFFERENT* socket than the NdbMgmHandle * so we should still be connected (and be able to check_connection) * */ if(ndb_mgm_check_connection(h) && !ndb_mgm_is_connected(h)) { ndbout << "FAILED: is still connected after error" << endl; result= NDBT_FAILED; } ndb_mgm_disconnect(h); } done: ndb_mgm_disconnect(h); ndb_mgm_destroy_handle(&h); return result; } NDBT_TESTSUITE(testMgm); TESTCASE("SingleUserMode", "Test single user mode"){ INITIALIZER(runTestSingleUserMode); FINALIZER(runClearTable); } TESTCASE("ApiSessionFailure", "Test failures in MGMAPI session"){ INITIALIZER(runTestApiSession); } TESTCASE("ApiConnectTimeout", "Connect timeout tests for MGMAPI"){ INITIALIZER(runTestApiConnectTimeout); } TESTCASE("ApiTimeoutBasic", "Basic timeout tests for MGMAPI"){ INITIALIZER(runTestApiTimeoutBasic); } TESTCASE("ApiGetStatusTimeout", "Test timeout for MGMAPI getStatus"){ INITIALIZER(runTestApiGetStatusTimeout); } TESTCASE("ApiGetConfigTimeout", "Test timeouts for mgmapi get_configuration"){ INITIALIZER(runTestMgmApiGetConfigTimeout); } TESTCASE("ApiMgmEventTimeout", "Test timeouts for mgmapi get_configuration"){ INITIALIZER(runTestMgmApiEventTimeout); } TESTCASE("ApiMgmStructEventTimeout", "Test timeouts for mgmapi get_configuration"){ INITIALIZER(runTestMgmApiStructEventTimeout); } NDBT_TESTSUITE_END(testMgm); int main(int argc, const char** argv){ ndb_init(); myRandom48Init(NdbTick_CurrentMillisecond()); return testMgm.execute(argc, argv); }
25.463647
79
0.641312
vusec
e43a079bc64f5a0fb30948cf7f7eae87fad85c77
623
cpp
C++
TestTicketSpinLock.cpp
zxylvlp/LockFree
ddc98968c8f944aac9f889d8eb8787a72fd87342
[ "Apache-2.0" ]
null
null
null
TestTicketSpinLock.cpp
zxylvlp/LockFree
ddc98968c8f944aac9f889d8eb8787a72fd87342
[ "Apache-2.0" ]
null
null
null
TestTicketSpinLock.cpp
zxylvlp/LockFree
ddc98968c8f944aac9f889d8eb8787a72fd87342
[ "Apache-2.0" ]
null
null
null
#include "TicketSpinLock.h" #include "vector" #include "thread" #include "iostream" int main(void) { TicketSpinLock ssl; std::vector<std::thread> threads; int num = 0; for (int i=0;i<10;i++) { std::thread t([i, &ssl, &num]{ num++; while (num!=10) { PAUSE(); } for (int j=0; j<1000000;j++) { ssl.lock(); std::cout << i << std::endl; ssl.unlock(); } }); threads.emplace_back(std::move(t)); } for (int i=0;i<10;i++) { threads[i].join(); } }
22.25
44
0.431782
zxylvlp
e43a25e0c0391947ded0d96977c706ecb4560455
2,031
cpp
C++
cpp/union_and_struct_test.cpp
ysoftman/test_code
4c71cc7c6a17d73cc84298e3a44051d3ab9d40f8
[ "MIT" ]
3
2017-12-07T04:29:36.000Z
2022-01-11T10:58:14.000Z
cpp/union_and_struct_test.cpp
ysoftman/test_code
4c71cc7c6a17d73cc84298e3a44051d3ab9d40f8
[ "MIT" ]
14
2018-07-17T05:16:42.000Z
2022-03-22T00:43:47.000Z
cpp/union_and_struct_test.cpp
ysoftman/test_code
4c71cc7c6a17d73cc84298e3a44051d3ab9d40f8
[ "MIT" ]
null
null
null
// ysoftman // union 과 struct 의 차이 #include <stdio.h> #include <string.h> struct ST { unsigned char ucChar; unsigned int unInt; }; union UI { unsigned char ucChar; unsigned int unInt; }; int main() { ST stInstance; memset(&stInstance, 0, sizeof(stInstance)); // 8 byte 출력 // 1바이트 char 형이 4바이트 int 형과 같은 4바이트 메모리를 차지하게 된다. // 멤버 변수를 추가하면 현재 구조체에 할당된 메모리 크기를 넘어가게 될 경우 // 가장 큰 멤버 변수의 타입의 크기 단위로 메모리를 할당하게 된다. // 4byte 를 넘어가면 -> 8byte 를 넘어가면 -> 12byte ... printf("stInstance size : %lu bytes\n", sizeof(stInstance)); UI uiInstance; memset(&uiInstance, 0, sizeof(uiInstance)); // 4 byte 출력 // 1바이트 char 형이 4바이트 int 형과 같은 4바이트 메모리를 차지하지만 하나의 하나의 4바이트 메모리공간을 공유한다. printf("uiInstance size : %lu bytes\n", sizeof(uiInstance)); printf("\n\n"); // struct 의 멤버는 각각의 독립적인 메모리 공간이 있어 각각 값을 유지한다. stInstance.ucChar = 255; stInstance.unInt = 65535; printf("stInstance.ucChar = %d stInstance.unInt = %d\n", stInstance.ucChar, stInstance.unInt); printf("stInstance.ucChar[0] = %x\n", stInstance.ucChar); // little/big endian 에 따라 byte order 가 다르게 나올 수 있다. printf("stInstance.unInt[0] = %x\n", (stInstance.unInt & 0x000000ff)); printf("stInstance.unInt[1] = %x\n", (stInstance.unInt & 0x0000ff00) >> 8); printf("stInstance.unInt[2] = %x\n", (stInstance.unInt & 0x00ff0000) >> 16); printf("stInstance.unInt[3] = %x\n", (stInstance.unInt & 0xff000000) >> 24); printf("\n"); // 가장 큰 메모리 공간을 공유함으로 각 바이트는 최근에 할당한 값이 유지된다. uiInstance.unInt = 65535; uiInstance.ucChar = 1; printf("uiInstance.ucChar = %d uiInstance.b = %d\n", uiInstance.ucChar, uiInstance.unInt); printf("uiInstance.ucChar[0] = %x\n", uiInstance.ucChar); // little/big endian 에 따라 byte order 가 다르게 나올 수 있다. printf("uiInstance.unInt[0] = %x\n", (uiInstance.unInt & 0x000000ff)); printf("uiInstance.unInt[1] = %x\n", (uiInstance.unInt & 0x0000ff00) >> 8); printf("uiInstance.unInt[2] = %x\n", (uiInstance.unInt & 0x00ff0000) >> 16); printf("uiInstance.unInt[3] = %x\n", (uiInstance.unInt & 0xff000000) >> 24); printf("\n"); return 0; }
32.758065
97
0.673067
ysoftman
e43b50b9abef0a0af5492404fd398da05e7ecaeb
13,514
hpp
C++
Project/include/lak/color.hpp
LAK132/OpenGL-Trash
9ddedf65792de78f642f47ad032b5027e4c390c1
[ "MIT" ]
null
null
null
Project/include/lak/color.hpp
LAK132/OpenGL-Trash
9ddedf65792de78f642f47ad032b5027e4c390c1
[ "MIT" ]
null
null
null
Project/include/lak/color.hpp
LAK132/OpenGL-Trash
9ddedf65792de78f642f47ad032b5027e4c390c1
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2018 Lucas Kleiss (LAK132) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <type_traits> #include <stdint.h> #include <GL/gl3w.h> #ifndef LAK_COLOR #define LAK_COLOR namespace lak { using std::conditional; struct null_t{}; template<GLenum gltype> struct gltct1 { typedef null_t type; }; template<> struct gltct1<GL_UNSIGNED_BYTE> { typedef uint8_t type; }; template<> struct gltct1<GL_BYTE> { typedef int8_t type; }; template<> struct gltct1<GL_UNSIGNED_SHORT> { typedef uint16_t type; }; template<> struct gltct1<GL_SHORT> { typedef int16_t type; }; template<> struct gltct1<GL_UNSIGNED_INT> { typedef uint32_t type; }; template<> struct gltct1<GL_INT> { typedef int32_t type; }; template<> struct gltct1<GL_FLOAT> { typedef float type; }; template<GLenum gltype> struct gltct2 { typedef null_t type; }; template<> struct gltct2<GL_UNSIGNED_BYTE_3_3_2> { typedef uint8_t type; }; template<> struct gltct2<GL_UNSIGNED_BYTE_2_3_3_REV> { typedef uint8_t type; }; template<> struct gltct2<GL_UNSIGNED_SHORT_5_6_5> { typedef uint16_t type; }; template<> struct gltct2<GL_UNSIGNED_SHORT_5_6_5_REV> { typedef uint16_t type; }; template<GLenum gltype> struct gltct3 { typedef null_t type; }; template<> struct gltct3<GL_UNSIGNED_SHORT_4_4_4_4> { typedef uint16_t type; }; template<> struct gltct3<GL_UNSIGNED_SHORT_4_4_4_4_REV> { typedef uint16_t type; }; template<> struct gltct3<GL_UNSIGNED_SHORT_5_5_5_1> { typedef uint16_t type; }; template<> struct gltct3<GL_UNSIGNED_SHORT_1_5_5_5_REV> { typedef uint16_t type; }; template<> struct gltct3<GL_UNSIGNED_INT_8_8_8_8> { typedef uint32_t type; }; template<> struct gltct3<GL_UNSIGNED_INT_8_8_8_8_REV> { typedef uint32_t type; }; template<> struct gltct3<GL_UNSIGNED_INT_10_10_10_2> { typedef uint32_t type; }; template<> struct gltct3<GL_UNSIGNED_INT_2_10_10_10_REV> { typedef uint32_t type; }; template<GLenum gltype, typename T> struct itgltct { enum { result = true }; }; template<GLenum gltype> struct itgltct<gltype, null_t> { enum { result = false }; }; template<GLenum gltype> struct gltct_t { typedef typename conditional<itgltct<gltype, typename gltct1<gltype>::type>::result, gltct1<gltype>, typename conditional<itgltct<gltype, typename gltct2<gltype>::type>::result, gltct2<gltype>, typename conditional<itgltct<gltype, typename gltct3<gltype>::type>::result, gltct3<gltype>, null_t>::type >::type >::type type; }; template<GLenum glformat, GLenum gltype, typename T> struct _color_t; // RX template<GLenum gltype> struct _color_t<GL_RED, gltype, gltct1<gltype>>{ typedef _color_t<GL_RED, gltype, gltct1<gltype>> ctype; typedef typename gltct1<gltype>::type type; type r = 0; _color_t(){} _color_t(type R){ r = R; } _color_t(ctype&& other) { *this = other; } _color_t(const ctype& other) { *this = other; } ctype& operator=(ctype&& other) { return *this = other; } ctype& operator=(const ctype& other) { r = other.r; return *this; } }; // RX GX template<GLenum gltype> struct _color_t<GL_RG, gltype, gltct1<gltype>>{ typedef _color_t<GL_RG, gltype, gltct1<gltype>> ctype; typedef typename gltct1<gltype>::type type; type r = 0; type g = 0; _color_t(){} _color_t(type R, type G){ r = R; g = G; } _color_t(ctype&& other) { *this = other; } _color_t(const ctype& other) { *this = other; } ctype& operator=(ctype&& other) { return *this = other; } ctype& operator=(const ctype& other) { r = other.r; g = other.g; return *this; } }; // RX GX BX template<GLenum gltype> struct _color_t<GL_RGB, gltype, gltct1<gltype>>{ typedef _color_t<GL_RGB, gltype, gltct1<gltype>> ctype; typedef typename gltct1<gltype>::type type; type r = 0; type g = 0; type b = 0; _color_t(){} _color_t(type R, type G, type B){ r = R; g = G; b = B; } _color_t(ctype&& other) { *this = other; } _color_t(const ctype& other) { *this = other; } ctype& operator=(ctype&& other) { return *this = other; } ctype& operator=(const ctype& other) { r = other.r; g = other.g; b = other.b; return *this; } }; // BX GX RX template<GLenum gltype> struct _color_t<GL_BGR, gltype, gltct1<gltype>>{ typedef _color_t<GL_BGR, gltype, gltct1<gltype>> ctype; typedef typename gltct1<gltype>::type type; type b = 0; type g = 0; type r = 0; _color_t(){} _color_t(type B, type G, type R){ r = R; g = G; b = B; } _color_t(ctype&& other) { *this = other; } _color_t(const ctype& other) { *this = other; } ctype& operator=(ctype&& other) { return *this = other; } ctype& operator=(const ctype& other) { r = other.r; g = other.g; b = other.b; return *this; } }; // RX GX BX AX template<GLenum gltype> struct _color_t<GL_RGBA, gltype, gltct1<gltype>>{ typedef _color_t<GL_RGBA, gltype, gltct1<gltype>> ctype; typedef typename gltct1<gltype>::type type; type r = 0; type g = 0; type b = 0; type a = 0; _color_t(){} _color_t(type R, type G, type B, type A){ r = R; g = G; b = B; a = A; } _color_t(ctype&& other) { *this = other; } _color_t(const ctype& other) { *this = other; } ctype& operator=(ctype&& other) { return *this = other; } ctype& operator=(const ctype& other) { r = other.r; g = other.g; b = other.b; a = other.a; return *this; } }; // BX GX RX AX template<GLenum gltype> struct _color_t<GL_BGRA, gltype, gltct1<gltype>>{ typedef _color_t<GL_BGRA, gltype, gltct1<gltype>> ctype; typedef typename gltct1<gltype>::type type; type b = 0; type g = 0; type r = 0; type a = 0; _color_t(){} _color_t(type B, type G, type R, type A){ r = R; g = G; b = B; a = A; } _color_t(ctype&& other) { *this = other; } _color_t(const ctype& other) { *this = other; } ctype& operator=(ctype&& other) { return *this = other; } ctype& operator=(const ctype& other) { r = other.r; g = other.g; b = other.b; a = other.a; return *this; } }; // R3 G3 B2 / B2 G3 R3 // R5 G6 B5 / B5 G6 R5 template<GLenum gltype> struct _color_t<GL_RGB, gltype, gltct2<gltype>>{ typedef _color_t<GL_RGB, gltype, gltct2<gltype>> ctype; typedef typename gltct1<gltype>::type type; type rgb; _color_t(){} _color_t(type RGB){ rgb = RGB; } _color_t(ctype&& other) { *this = other; } _color_t(const ctype& other) { *this = other; } ctype& operator=(ctype&& other) { return *this = other; } ctype& operator=(const ctype& other) { rgb = other.rgb; return *this; } }; // R4 G4 B4 A4 / A4 B4 G4 R4 // R5 G5 B5 A1 / A1 B5 G5 R5 // R8 G8 B8 A8 / A8 B8 G8 R8 // R10 G10 B10 A2 / B10 G10 R10 A2 template<GLenum gltype> struct _color_t<GL_RGBA, gltype, gltct3<gltype>>{ typedef _color_t<GL_RGBA, gltype, gltct3<gltype>> ctype; typedef typename gltct1<gltype>::type type; type rgba; _color_t(){} _color_t(type RGBA){ rgba = RGBA; } _color_t(ctype&& other) { *this = other; } _color_t(const ctype& other) { *this = other; } ctype& operator=(ctype&& other) { return *this = other; } ctype& operator=(const ctype& other) { rgba = other.rgba; return *this; } }; // B4 G4 R4 A4 / A4 R4 G4 B4 // B5 G5 R5 A1 / A1 R5 G5 B5 // B8 G8 R8 A8 / A8 R8 G8 B8 // B10 G10 R10 A2 / R10 G10 B10 A2 template<GLenum gltype> struct _color_t<GL_BGRA, gltype, gltct3<gltype>>{ typedef _color_t<GL_BGRA, gltype, gltct3<gltype>> ctype; typedef typename gltct1<gltype>::type type; type bgra; _color_t(){} _color_t(type BGRA){ bgra = BGRA; } _color_t(ctype&& other) { *this = other; } _color_t(const ctype& other) { *this = other; } ctype& operator=(ctype&& other) { return *this = other; } ctype& operator=(const ctype& other) { bgra = other.bgra; return *this; } }; template<GLenum glformat, GLenum gltype> using color_t = _color_t<glformat, gltype, typename gltct_t<gltype>::type>; typedef color_t<GL_RED, GL_UNSIGNED_BYTE> colorR8_t; typedef color_t<GL_RG, GL_UNSIGNED_BYTE> colorRG8_t; typedef color_t<GL_RGB, GL_UNSIGNED_BYTE> colorRGB8_t; typedef color_t<GL_RGBA, GL_UNSIGNED_BYTE> colorRGBA8_t; typedef color_t<GL_BGR, GL_UNSIGNED_BYTE> colorBGR8_t; typedef color_t<GL_BGRA, GL_UNSIGNED_BYTE> colorBGRA8_t; typedef color_t<GL_RED, GL_BYTE> colorRs8_t; typedef color_t<GL_RG, GL_BYTE> colorRGs8_t; typedef color_t<GL_RGB, GL_BYTE> colorRGBs8_t; typedef color_t<GL_RGBA, GL_BYTE> colorRGBAs8_t; typedef color_t<GL_BGR, GL_BYTE> colorBGRs8_t; typedef color_t<GL_BGRA, GL_BYTE> colorBGRAs8_t; typedef color_t<GL_RED, GL_UNSIGNED_SHORT> colorR16_t; typedef color_t<GL_RG, GL_UNSIGNED_SHORT> colorRG16_t; typedef color_t<GL_RGB, GL_UNSIGNED_SHORT> colorRGB16_t; typedef color_t<GL_RGBA, GL_UNSIGNED_SHORT> colorRGBA16_t; typedef color_t<GL_BGR, GL_UNSIGNED_SHORT> colorBGR16_t; typedef color_t<GL_BGRA, GL_UNSIGNED_SHORT> colorBGRA16_t; typedef color_t<GL_RED, GL_SHORT> colorRs16_t; typedef color_t<GL_RG, GL_SHORT> colorRGs16_t; typedef color_t<GL_RGB, GL_SHORT> colorRGBs16_t; typedef color_t<GL_RGBA, GL_SHORT> colorRGBAs16_t; typedef color_t<GL_BGR, GL_SHORT> colorBGRs16_t; typedef color_t<GL_BGRA, GL_SHORT> colorBGRAs16_t; typedef color_t<GL_RED, GL_UNSIGNED_INT> colorR32_t; typedef color_t<GL_RG, GL_UNSIGNED_INT> colorRG32_t; typedef color_t<GL_RGB, GL_UNSIGNED_INT> colorRGB32_t; typedef color_t<GL_RGBA, GL_UNSIGNED_INT> colorRGBA32_t; typedef color_t<GL_BGR, GL_UNSIGNED_INT> colorBGR32_t; typedef color_t<GL_BGRA, GL_UNSIGNED_INT> colorBGRA32_t; typedef color_t<GL_RED, GL_INT> colorRs32_t; typedef color_t<GL_RG, GL_INT> colorRGs32_t; typedef color_t<GL_RGB, GL_INT> colorRGBs32_t; typedef color_t<GL_RGBA, GL_INT> colorRGBAs32_t; typedef color_t<GL_BGR, GL_INT> colorBGRs32_t; typedef color_t<GL_BGRA, GL_INT> colorBGRAs32_t; typedef color_t<GL_RED, GL_FLOAT> colorRf_t; typedef color_t<GL_RG, GL_FLOAT> colorRGf_t; typedef color_t<GL_RGB, GL_FLOAT> colorRGBf_t; typedef color_t<GL_RGBA, GL_FLOAT> colorRGBAf_t; typedef color_t<GL_BGR, GL_FLOAT> colorBGRf_t; typedef color_t<GL_BGRA, GL_FLOAT> colorBGRAf_t; typedef color_t<GL_RGB, GL_UNSIGNED_BYTE_3_3_2> colorR3G3B2_t; typedef color_t<GL_RGB, GL_UNSIGNED_BYTE_2_3_3_REV> colorB2G3R3_t; typedef color_t<GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4> colorR4G4B4A4_t; typedef color_t<GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4_REV> colorA4B4G4R4_t; typedef color_t<GL_BGRA, GL_UNSIGNED_SHORT_4_4_4_4> colorB4G4R4A4_t; typedef color_t<GL_BGRA, GL_UNSIGNED_SHORT_4_4_4_4_REV> colorA4R4G4B4_t; typedef color_t<GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1> colorR5G5B5A1_t; typedef color_t<GL_RGBA, GL_UNSIGNED_SHORT_1_5_5_5_REV> colorA1B5G5R5_t; typedef color_t<GL_BGRA, GL_UNSIGNED_SHORT_5_5_5_1> colorB5G5R5A1_t; typedef color_t<GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV> colorA1R5G5B5_t; typedef color_t<GL_RGBA, GL_UNSIGNED_INT_8_8_8_8> colorR8G8B8A8_t; typedef color_t<GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV> colorA8B8G8R8_t; typedef color_t<GL_BGRA, GL_UNSIGNED_INT_8_8_8_8> colorB8G8R8A8_t; typedef color_t<GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV> colorA8R8G8B8_t; typedef color_t<GL_RGBA, GL_UNSIGNED_INT_10_10_10_2> colorR10G10B10A2_t; typedef color_t<GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV> colorA2B10G10R10_t; typedef color_t<GL_BGRA, GL_UNSIGNED_INT_10_10_10_2> colorB10G10R10A2_t; typedef color_t<GL_BGRA, GL_UNSIGNED_INT_2_10_10_10_REV> colorA2R10G10B10_t; } #endif // LAK_COLOR
43.876623
122
0.665532
LAK132
e4424540448117b94891a11d5ca81d35500952b1
2,809
hxx
C++
opencascade/Convert_TorusToBSplineSurface.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/Convert_TorusToBSplineSurface.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/Convert_TorusToBSplineSurface.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 1991-10-10 // Created by: Jean Claude VAUTHIER // Copyright (c) 1991-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Convert_TorusToBSplineSurface_HeaderFile #define _Convert_TorusToBSplineSurface_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Convert_ElementarySurfaceToBSplineSurface.hxx> #include <Standard_Real.hxx> #include <Standard_Boolean.hxx> class Standard_DomainError; class gp_Torus; //! This algorithm converts a bounded Torus into a rational //! B-spline surface. The torus is a Torus from package gp. //! The parametrization of the torus is : //! P (U, V) = //! Loc + MinorRadius * Sin(V) * Zdir + //! (MajorRadius+MinorRadius*Cos(V)) * (Cos(U)*Xdir + Sin(U)*Ydir) //! where Loc is the center of the torus, Xdir, Ydir and Zdir are the //! normalized directions of the local cartesian coordinate system of //! the Torus. The parametrization range is U [0, 2PI], V [0, 2PI]. //! KeyWords : //! Convert, Torus, BSplineSurface. class Convert_TorusToBSplineSurface : public Convert_ElementarySurfaceToBSplineSurface { public: DEFINE_STANDARD_ALLOC //! The equivalent B-spline surface as the same orientation as the //! torus in the U and V parametric directions. //! //! Raised if U1 = U2 or U1 = U2 + 2.0 * Pi //! Raised if V1 = V2 or V1 = V2 + 2.0 * Pi Standard_EXPORT Convert_TorusToBSplineSurface(const gp_Torus& T, const Standard_Real U1, const Standard_Real U2, const Standard_Real V1, const Standard_Real V2); //! The equivalent B-spline surface as the same orientation as the //! torus in the U and V parametric directions. //! //! Raised if Param1 = Param2 or Param1 = Param2 + 2.0 * Pi Standard_EXPORT Convert_TorusToBSplineSurface(const gp_Torus& T, const Standard_Real Param1, const Standard_Real Param2, const Standard_Boolean UTrim = Standard_True); //! The equivalent B-spline surface as the same orientation as the //! torus in the U and V parametric directions. Standard_EXPORT Convert_TorusToBSplineSurface(const gp_Torus& T); protected: private: }; #endif // _Convert_TorusToBSplineSurface_HeaderFile
29.882979
169
0.750089
valgur
e443c38fd2846d4b76e488e91b30eb703f45d8a9
4,839
cpp
C++
src/racer/libu/rbutton.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
null
null
null
src/racer/libu/rbutton.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
null
null
null
src/racer/libu/rbutton.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
1
2021-01-03T16:16:47.000Z
2021-01-03T16:16:47.000Z
/* * RButton - Racer GUI button * 04-11-01: Created! * NOTES: * - An attempt to get a 3D polygon-type button, instead of the regular * QLib buttons, but in the same framework to avoid coding a 2nd GUI. * (c) Dolphinity/RvG */ #include <raceru/button.h> #include <qlib/debug.h> #pragma hdrstop DEBUG_ENABLE RButton::RButton(QWindow *parent,QRect *pos,cstring text,DTexFont *_tfont) : QButton(parent,pos,text) { if(!_tfont) { qerr("RButton: can't pass empty font"); // Prepare to crash... } tfont=_tfont; tex=0; colNormal=new QColor(255,255,255,95); colHilite=new QColor(255,155,155,120); colEdge=new QColor(155,155,255,0); cv->SetMode(QCanvas::DOUBLEBUF); // Avoid Y flipping in the canvas cv->Enable(QCanvas::NO_FLIP); // Cancel offset installed by QWindow; we're drawing in 3D cv->SetOffset(0,0); aBackdrop=new RAnimTimer(pos->wid); aText=new RAnimTimer(strlen(text)); aHilite=new RAnimTimer(0); } RButton::~RButton() { //qdbg("RButton dtor\n"); QDELETE(colNormal); QDELETE(colHilite); QDELETE(colEdge); QDELETE(aBackdrop); QDELETE(aText); QDELETE(aHilite); } /********** * Attribs * **********/ void RButton::SetTexture(DTexture *_tex,QRect *_rDisarmed,QRect *_rArmed) // Define a texture to use instead of the default drawing. // If 'rDisarmed' is 0, then the whole texture is used. // Same for 'rArmed'. { QASSERT_V(_tex); tex=_tex; // Copy rectangles if(_rDisarmed==0) { // Use full texture rDisarmed.x=rDisarmed.y=0; rDisarmed.wid=tex->GetWidth(); rDisarmed.hgt=tex->GetHeight(); } else { // Explicit area rDisarmed.x=_rDisarmed->x; rDisarmed.y=_rDisarmed->y; rDisarmed.wid=_rDisarmed->wid; rDisarmed.hgt=_rDisarmed->hgt; } if(_rArmed==0) { // Use full texture rArmed.x=rArmed.y=0; rArmed.wid=tex->GetWidth(); rArmed.hgt=tex->GetHeight(); } else { // Explicit area rArmed.x=_rArmed->x; rArmed.y=_rArmed->y; rArmed.wid=_rArmed->wid; rArmed.hgt=_rArmed->hgt; } } static void Rect2TC(QRect *r,float *v,DTexture *tex) // Convert a rectangle to tex coordinates { v[0]=float(r->x)/float(tex->GetWidth()); v[1]=1.0-float(r->y)/float(tex->GetHeight()); v[2]=float(r->x+r->wid)/float(tex->GetWidth()); v[3]=1.0-float(r->y+r->hgt)/float(tex->GetHeight()); //qdbg("Rect2TC: in: %d,%d %dx%d, out %.2f,%.2f %.2f,%.2f\n", //r->x,r->y,r->wid,r->hgt,v[0],v[1],v[2],v[3]); } void RButton::Paint(QRect *rr) { QRect r; char buf[256]; unsigned int n; int tx,ty; // Text position float tc[4]; // Texture coordinates float w; GetPos(&r); cv->Map2Dto3D(&r.x,&r.y); if(tex) { // Use explicit texture instead of calculated button tex->Select(); if(state==ARMED)Rect2TC(&rArmed,tc,tex); else Rect2TC(&rDisarmed,tc,tex); //Rect2TC(&rArmed,tc,tex); //if(state==ARMED)qdbg("ARMED\n"); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glBegin(GL_QUADS); glTexCoord2f(tc[0],tc[1]); glVertex2f(r.x,r.y); glTexCoord2f(tc[2],tc[1]); glVertex2f(r.x+r.wid,r.y); glTexCoord2f(tc[2],tc[3]); glVertex2f(r.x+r.wid,r.y-r.hgt); glTexCoord2f(tc[0],tc[3]); glVertex2f(r.x,r.y-r.hgt); glEnd(); } else { // Hardcoded draw //qdbg("RButton:Paint() at %d,%d\n",r.x,r.y); w=r.wid; r.wid=aBackdrop->GetValue(); cv->Blend(TRUE); if(state==ARMED) cv->Rectfill(&r,colHilite,colEdge,colEdge,colHilite); else cv->Rectfill(&r,colNormal,colEdge,colEdge,colNormal); if(IsFocus()) cv->Rectfill(&r,colNormal,colNormal,colNormal,colNormal); // Outline r.wid=w; cv->SetColor(255,255,255); cv->Rectangle(r.x,r.y+1,r.wid,1); cv->Rectangle(r.x,r.y+0,1,r.hgt); cv->Rectangle(r.x,r.y-r.hgt+1,r.wid,1); cv->Rectangle(r.x+r.wid-1,r.y+0,1,r.hgt); // Text (a bit weird, as texts seem flipped wrt the rectfills) tx=r.x+(r.wid-tfont->GetWidth(text))/2; ty=r.y-tfont->GetHeight(text)-(r.hgt-tfont->GetHeight(text))/2; if(aText->IsFinished()) { tfont->Paint(text,tx,ty); } else { // Create left(text,n) string n=aText->GetValue(); if(n>sizeof(buf)-1) n=sizeof(buf)-1; strncpy(buf,text,n); buf[n]=0; tfont->Paint(buf,tx,ty); } } //qdbg("RButton:Paint() RET\n"); } /************ * Animation * ************/ void RButton::AnimIn(int t,int delay) // Make the button appear animated (no move) { QRect r; GetPos(&r); aBackdrop->Trigger(r.wid,t,delay); // Text a little later aText->Trigger(strlen(text),t,delay+t/2); } bool RButton::EvEnter() { qdbg("enter\n"); return TRUE; } bool RButton::EvExit() { qdbg("leave\n"); return TRUE; } bool RButton::EvMotionNotify(int x,int y) { //qdbg("motion %d,%d\n",x,y); return TRUE; }
23.15311
74
0.624303
3dhater
e449c0ecb937428e95bbf58132b7dac839f1d20d
20,979
cpp
C++
src/vlCore/Say.cpp
zpc930/visualizationlibrary
c81fa75c720a3d04d295b977a1f5dc4624428b53
[ "BSD-2-Clause" ]
null
null
null
src/vlCore/Say.cpp
zpc930/visualizationlibrary
c81fa75c720a3d04d295b977a1f5dc4624428b53
[ "BSD-2-Clause" ]
null
null
null
src/vlCore/Say.cpp
zpc930/visualizationlibrary
c81fa75c720a3d04d295b977a1f5dc4624428b53
[ "BSD-2-Clause" ]
null
null
null
/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.org */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without modification, */ /* are permitted provided that the following conditions are met: */ /* */ /* - Redistributions of source code must retain the above copyright notice, this */ /* list of conditions and the following disclaimer. */ /* */ /* - Redistributions in binary form must reproduce the above copyright notice, this */ /* list of conditions and the following disclaimer in the documentation and/or */ /* other materials provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */ /* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */ /* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */ /* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* */ /**************************************************************************************/ #include <vlCore/Say.hpp> #include <cmath> using namespace vl; SayArg::SayArg() { init(); } SayArg::SayArg(void* d) { init(); ulonglong = reinterpret_cast<unsigned long long>(d); type = ULONGLONG; } SayArg::SayArg(const std::string& d) { init(); str = d.c_str(); type = STRING; } SayArg::SayArg(const unsigned char* d) { init(); if (d) str = (const char*)d; type = STRING; } SayArg::SayArg(const char* d) { init(); if (d) str = d; type = STRING; } SayArg::SayArg(const String& d) { init(); str = d; type = STRING; } SayArg::SayArg(double d) { init(); float64 = d; type = FLOAT64; } SayArg::SayArg(float d) { init(); float64 = d; type = FLOAT64; } SayArg::SayArg(unsigned char d) { init(); ulonglong = d; type = ULONGLONG; } SayArg::SayArg(signed char d) { init(); slonglong = d; type = SLONGLONG; } SayArg::SayArg(unsigned short d) { init(); ulonglong = d; type = ULONGLONG; } SayArg::SayArg(signed short d) { init(); slonglong = d; type = SLONGLONG; } SayArg::SayArg(unsigned int d) { init(); ulonglong = d; type = ULONGLONG; } SayArg::SayArg(signed int d) { init(); slonglong = d; type = SLONGLONG; } SayArg::SayArg(unsigned long d) { init(); ulonglong = d; type = ULONGLONG; } SayArg::SayArg(signed long d) { init(); slonglong = d; type = SLONGLONG; } SayArg::SayArg(unsigned long long d) { init(); ulonglong = d; type = ULONGLONG; } SayArg::SayArg(signed long long d) { init(); slonglong = d; type = SLONGLONG; } void SayArg::init() { type = NO_TYPE; float64 = 0; ulonglong = 0; slonglong = 0; } String Say::parse( const Say& pset ) const { String out; String fmt = pset.format_string; int param_idx = 0; int eur = -1; int base = -1; int field = -1; int decimals = -1; int align = -1; int fill = -1; int plus = -1; int fmtstart = -1; // %H+014.5n bool fmtdata = false; for(int i=0; i<(int)fmt.length(); ++i) { int ch = (i<(int)fmt.length()) ? (int)fmt[i+0] : -1; int next_ch = (i<(int)fmt.length()-1) ? (int)fmt[i+1] : -1; int nnext_ch = (i<(int)fmt.length()-2) ? (int)fmt[i+2] : -1; if (!fmtdata) { if (ch == '%' && next_ch == '%') { out += '%'; ++i; } else if (ch == '%') { if (param_idx < (int)pset.size()) { fmtdata = true; fmtstart = i; } else { out += " !!!too few parameters: %"; } } else if (ch >= 0) { out += (unsigned short)ch; } } else { if(eur == -1) { if (ch == '$') { eur = 1; continue; } } if (base == -1) { switch(ch) { case 'b': base = 2; break; case 'o': base = 8; break; case 'd': base = 10; break; case 'h': base = 16; break; } if (base != -1) { if (eur == -1) eur = 0; continue; } } if (plus == -1) { switch(ch) { case '+': plus = 1; break; } if (plus != -1) { if (base == -1) base = 10; if (eur == -1) eur = 0; continue; } } if (fill == -1) { switch(ch) { case '0': fill = '0'; break; case ' ': fill = ' '; break; } if (fill != -1) { if (base == -1) base = 10; if (plus == -1) plus = 0; if (eur == -1) eur = 0; continue; } } if (field == -1) { if (ch >= '0' && ch <= '9') { field = ch - '0'; if (next_ch >= '0' && next_ch <= '9') { field = field*10 + next_ch - '0'; ++i; } } if (field != -1) { if (base == -1) base = 10; if (plus == -1) plus = 0; if (fill == -1) fill = ' '; if (eur == -1) eur = 0; continue; } } if (decimals == -1) { if(ch == '.') { if (next_ch >= '0' && next_ch <= '9') { decimals = next_ch - '0'; ++i; if (nnext_ch >= '0' && nnext_ch <= '9') { decimals = decimals*10 + nnext_ch - '0'; ++i; } } } if (decimals != -1) { if (base == -1) base = 10; if (plus == -1) plus = 0; if (fill == -1) fill = ' '; if (field == -1) field = 0; if (eur == -1) eur = 0; continue; } } if (align == -1) { if(ch == '=') align = 0; if(ch == '<') align = 1; if(ch == '>') align = 2; if (align != -1) { if (base == -1) base = 10; if (plus == -1) plus = 0; if (fill == -1) fill = ' '; if (field == -1) field = 0; if (eur == -1) eur = 0; if (decimals == -1) { switch(pset[param_idx].type) { case SayArg::FLOAT64: decimals = 6; break; default: decimals = 0; break; } } continue; } } // generate formatted string // output parameter const SayArg& p = pset[param_idx]; if (ch == 'c') { if (fmtstart != i-1) out += " !!! '%c' does not need arguments !!! "; switch(p.type) { case SayArg::FLOAT64: out += (char)p.float64; break; case SayArg::SLONGLONG: out += (char)p.slonglong; break; case SayArg::ULONGLONG: out += (char)p.ulonglong; break; default: out += " !!! wrong argument type for '%c' !!! "; break; } } else if (ch == 's') { if (fmtstart != i-1) out += " !!! '%s' does not need arguments !!! "; switch(p.type) { case SayArg::STRING: out += p.str; break; default: out += " !!! wrong argument type for '%s' !!! "; break; } } else if (ch == 'n' || ch == 'N' || ch == 'e' || ch == 'E') { if (param_idx<(int)pset.size()) { if (decimals == -1) { switch(p.type) { case SayArg::FLOAT64: decimals = 6; break; default: decimals = 0; break; } } if (base == -1) base = 10; if (field == -1) field = 0; if (decimals == -1) decimals = 0; if (fill == -1) fill = ' '; if (plus == -1) plus = 0; if (align == -1) align = 2; if (eur == -1) eur = 0; switch(p.type) { case SayArg::FLOAT64: out += format(p.float64, base, field, decimals, align, fill, plus, ch, eur); break; case SayArg::SLONGLONG: out += format(p.slonglong, base, field, decimals, align, fill, plus, ch, eur); break; case SayArg::ULONGLONG: out += format(p.ulonglong, base, field, decimals, align, fill, plus, ch, eur); break; default: out += " !!! wrong argument type for '%n' !!! "; break; } } else { out += " !!!missing parameter!!! "; if (ch != -1) i--; } } else { out += " !!!format error: unexpected '"; out += (char)ch; out += "' !!! "; } fmtdata = false; align = -1; base = -1; field = -1; decimals = -1; align = -1; fill = -1; plus = -1; eur = -1; param_idx++; } } if (fmtdata) { out += " !!!truncated format!!! "; param_idx++; } if (param_idx < (int)pset.size()) out += " !!!too many parameters!!! "; return out; // ... fare in modo che l'output venga generato anche quando non c'e' il carattere finale ... } String Say::euronotation(const String& str, int base) const { String tmp; int pos = (int)str.length(); if ( str.contains('.') ) { while(pos--) { if (str[pos] == '.') { tmp.insert(0, ','); break; } tmp.insert(0, str[pos]); } if (pos < 0) pos = (int)str.length(); } int count = 0; int wait = 3; if (base == 2) wait = 4; if (base == 16) wait = 2; while(pos--) { if (count && count % wait == 0) { tmp.insert(0, '.'); } tmp.insert(0, str[pos]); count ++; } return tmp; } String Say::format(unsigned long long n, int base, int field, int decimals, int align, int fill, int plus, int finalizer, int eur) const { if (field < 0) field = -field; if (field > 1024) field = 1024; if (decimals < 0) decimals = -decimals; if (decimals > 20) decimals = 20; if (align != 0 && align != 1 && align != 2) align = 0; if (base > 16) base = 16; if (base < 2) base = 2; String str; const char* hex = "0123456789abcdef"; // UNSIGNED INT ALGORITHM int k = base; do { int x = (int)(n % base); int c = x/(k/base); str.insert(0, hex[c]); n = n / base; } while(n); if (decimals) { str += '.'; int i = decimals; while(i--) str += '0'; } bool negative = false; return pipeline(str, base, field, decimals, finalizer, align, eur, fill, negative, plus); } String Say::format(signed long long nn, int base, int field, int decimals, int align, int fill, int plus, int finalizer, int eur) const { if (field < 0) field = -field; if (field > 1024) field = 1024; if (decimals < 0) decimals = -decimals; if (decimals > 20) decimals = 20; if (align != 0 && align != 1 && align != 2) align = 0; if (base > 16) base = 16; if (base < 2) base = 2; String str; const char* hex = "0123456789abcdef"; // SIGNED INT ALGORITHM bool negative = nn < 0; unsigned long long n; if (nn<0 && -nn<0) // overflow n = (unsigned long long)nn; else if (nn<0) n = - nn; else n = nn; //if (n < 0) // n = 0; int k = base; do { int x = (int)(n % base); int c = x/(k/base); str.insert(0, hex[c]); n = n / base; } while(n); if (decimals) { str += '.'; int i = decimals; while(i--) str += '0'; } return pipeline(str, base, field, decimals, finalizer, align, eur, fill, negative, plus); } String Say::format(double num, int base, int field, int decimals, int align, int fill, int plus, int finalizer, int eur) const { if (field < 0) field = -field; if (field > 1024) field = 1024; if (decimals < 0) decimals = -decimals; if (decimals > 20) decimals = 20; if (align != 0 && align != 1 && align != 2) align = 0; if (base > 16) base = 16; if (base < 2) base = 2; String str; const char* hex = "0123456789abcdef"; double f = num; // INDEFINITE = - 127 192 0 0 // -INFINITE = - 127 128 0 0 // +INFINITE = + 127 128 0 0 float tmp = (float)f; unsigned char *nan= (unsigned char*)&tmp; const char* sign = nan[3] >= 128 ? "-" : "+"; unsigned char exp = (nan[3] << 1) + (nan[2] >> 7); nan[2] &= 127; unsigned int frac = nan[0] + (nan[1] << 8) + (nan[2] << 16); bool negative = false; if (exp == 255 && frac == 0) { return String(sign) + "#INF"; } else if (exp == 255 && frac != 0) { return "#NAN"; } else { // ROUNDING FOR FRACTIONAL PART if (finalizer == 'n' || finalizer == 'N') { double fp = f - floor(f); double eps = base/2; int dec = decimals; do { if ( !(dec--) ) break; int c = (int)(fp * base); fp = fp * base - c; eps /= base; if (c<0 || c>15) { return "#ERR"; } if (dec == 0) // round only if all the decimals are here { // program rounded fp f += eps/base; break; } } while(fp>0); } if (f < 0) { f = -f; negative = true; } double n = floor(f); // INTEGER PART int count = 0; unsigned int base2 = base*base; unsigned int base3 = base*base*base; unsigned int base4 = base*base*base*base; unsigned int base5 = base*base*base*base*base; unsigned int base6 = base*base*base*base*base*base; unsigned int base7 = base*base*base*base*base*base*base; // maximum number in base 16 while (floor(n)) { if (n>=base7) { n /= base7; count+=7; } else if (n>=base6) { n /= base6; count+=6; } else if (n>=base5) { n /= base5; count+=5; } else if (n>=base4) { n /= base4; count+=4; } else if (n>=base3) { n /= base3; count+=3; } else if (n>=base2) { n /= base2; count+=2; } else { n = n / base; count++; } } // prevents rounding errors double eps = (base / 2.0) / base; for(int i=0; i<count; ++i) { eps /= base; } n+=eps; if (count) { do { int c = (int)(n * (double)base); n = n * (double)base - floor(n * (double)base); int next = (int)(n * base); if (c<0 || c>15 || next<0 || next>15) { return "#ERR"; } str += hex[c]; } while(--count); } else str += '0'; str += '.'; // FRACTIONAL PART double fp = f - floor(f); do { int c = (int)(fp * base); fp = fp * base - c; if (c<0 || c>15) { return "#ERR"; } str += hex[c]; } while(fp>0); // COMMON PIPELINE // (1) EXPONENTIAL SHIFT // (2) CLIP & FILL DECIMALS // (3) EXPONENTIAL DECORATIONS // (4) EURO NOTATION // (5) FIELD, ALIGN AND SIGN // (6) CASE TRANSFORM return pipeline(str, base, field, decimals, finalizer, align, eur, fill, negative, plus); } } String Say::pipeline(const String& in_str, int base, int field, int decimals, int finalizer, int align, int eur, int fill, int negative, int plus) const { String str = in_str; // EXPONENTIAL SHIFT int shift = 0; // exponential notation if (finalizer == 'e' || finalizer == 'E') { int ptpos = (int)str.length(); // point position int nzpos = -1; // non zero position for(int i=0; i<(int)str.length(); ++i) { if(str[i] != '0' && nzpos == -1 && str[i] != '.') nzpos = i; else if (str[i] == '.') ptpos = i; } if (nzpos == -1) shift = 0; else shift = ptpos - nzpos - ( (ptpos > nzpos) ? 1 : 0 ); // remove the point str.remove( ptpos, 1 ); // remove all the zeros on the left while( str.length() && str[0] == '0' ) str.remove(0); // reinsert the point at the 2-nd position // with up to 2 zero if needed. if (str.length() == 1) str += '0'; if (str.length() == 0) str = "00"; str.insert(1, '.'); } // CLIP AND FILL DECIMALS // position of the dot if ( !str.contains('.') ) str += ".0"; int pos = str.find('.'); // number of decimals int decs = (int)str.length() - pos -1; // trim decimals if (decs > decimals) { // remove also the dot int dot = decimals == 0 ? 1 : 0; str.resize(str.length() - (decs - decimals + dot)); } else { // add missing decimals int i = decimals - decs; while(i--) str += '0'; } // EXPONENTIAL DECORATION if (finalizer == 'e' || finalizer == 'E') { str += 'e'; str += format((signed long long)shift, base, 0, 0, 2, 0, 1, 0,0); } else // EURO NOTATION if (eur) str = euronotation(str, base); // FIELD, SIGN, ALIGN int right = (field - (int)str.length()) / 2; right = right < 0 ? 0 : right; int left = (field - (int)str.length()) - right; left = left < 0 ? 0 : left; if (align == 1) // left { right += left; left = 0; } else if (align == 2) // right { left += right; right = 0; } // fill left str.insert(0, (wchar_t)fill, left); // fill right str.append(fill, right); if (negative) { if (left) str.remove(0); else if (right) str.resize(str.length()-1); str.insert(0, '-'); } else if(plus) { if (left) str.remove(0); else if (right) str.resize(str.length()-1); str.insert(0, '+'); } // CASE TRANSFORM if (finalizer == 'N' || finalizer == 'E') { for(int i=0; i<(int)str.length(); ++i) if (str[i] >= 'a' && str[i] <= 'z') str[i] = str[i] - 'a' + 'A'; } return str; }
21.298477
153
0.417465
zpc930
e44ac373955864c632475809dae643c02f9d4be3
6,075
cpp
C++
source/message_bus/monitor/src/NodeViewModel.cpp
ford442/oglplu2
abf1e28d9bcd0d2348121e8640d9611a94112a83
[ "BSL-1.0" ]
103
2015-10-15T07:09:22.000Z
2022-03-20T03:39:32.000Z
source/app/monitor/src/NodeViewModel.cpp
matus-chochlik/eagine-msgbus
1672be9db227e918b17792e01d8a45ac58954181
[ "BSL-1.0" ]
11
2015-11-25T11:39:49.000Z
2021-06-18T08:06:06.000Z
source/message_bus/monitor/src/NodeViewModel.cpp
ford442/oglplu2
abf1e28d9bcd0d2348121e8640d9611a94112a83
[ "BSL-1.0" ]
10
2016-02-28T00:13:20.000Z
2021-09-06T05:21:38.000Z
/// /// Copyright Matus Chochlik. /// Distributed under the GNU GENERAL PUBLIC LICENSE version 3. /// See http://www.gnu.org/licenses/gpl-3.0.txt /// #include "NodeViewModel.hpp" #include "MonitorBackend.hpp" #include "TrackerModel.hpp" //------------------------------------------------------------------------------ NodeViewModel::NodeViewModel( MonitorBackend& backend, SelectedItemViewModel& selectedItemViewModel) : QObject{nullptr} , eagine::main_ctx_object{EAGINE_ID(NodeVM), backend} , _backend{backend} , _parameters{backend} { connect( &_backend, &MonitorBackend::trackerModelChanged, this, &NodeViewModel::onTrackerModelChanged); connect( &selectedItemViewModel, &SelectedItemViewModel::nodeChanged, this, &NodeViewModel::onNodeIdChanged); } //------------------------------------------------------------------------------ auto NodeViewModel::getItemKind() -> QString { if(_node.id()) { switch(_node.kind()) { case eagine::msgbus::node_kind::endpoint: return {"Endpoint"}; case eagine::msgbus::node_kind::router: return {"Router"}; case eagine::msgbus::node_kind::bridge: return {"Bridge"}; case eagine::msgbus::node_kind::unknown: break; } return {"UnknownNode"}; } return {"NoItem"}; } //------------------------------------------------------------------------------ auto NodeViewModel::getIdentifier() -> QVariant { if(_node) { return {QString::number(extract(_node.id()))}; } return {}; } //------------------------------------------------------------------------------ auto NodeViewModel::getDisplayName() -> QVariant { switch(_node.kind()) { case eagine::msgbus::node_kind::endpoint: if(auto optStr{_node.display_name()}) { return {c_str(extract(optStr))}; } break; case eagine::msgbus::node_kind::router: return {"routing node"}; case eagine::msgbus::node_kind::bridge: return {"bridge node"}; case eagine::msgbus::node_kind::unknown: return {"unknown node"}; } return {}; } //------------------------------------------------------------------------------ auto NodeViewModel::getDescription() -> QVariant { switch(_node.kind()) { case eagine::msgbus::node_kind::endpoint: if(auto optStr{_node.description()}) { return {c_str(extract(optStr))}; } break; case eagine::msgbus::node_kind::router: return {"message bus routing node"}; case eagine::msgbus::node_kind::bridge: return {"message bus bridge node"}; case eagine::msgbus::node_kind::unknown: return {"unknown message bus node"}; } return {}; } //------------------------------------------------------------------------------ auto NodeViewModel::getUptime() -> QVariant { if(const auto uptime{_node.uptime()}) { const std::chrono::seconds secs{extract(uptime)}; return {static_cast<qulonglong>(secs.count())}; } return {}; } //------------------------------------------------------------------------------ auto NodeViewModel::getSentMessages() -> QVariant { if(const auto count{_node.sent_messages()}) { return {static_cast<qulonglong>(extract(count))}; } return {}; } //------------------------------------------------------------------------------ auto NodeViewModel::getReceivedMessages() -> QVariant { if(const auto count{_node.received_messages()}) { return {static_cast<qulonglong>(extract(count))}; } return {}; } //------------------------------------------------------------------------------ auto NodeViewModel::getDroppedMessages() -> QVariant { if(const auto count{_node.dropped_messages()}) { return {static_cast<qulonglong>(extract(count))}; } return {}; } //------------------------------------------------------------------------------ auto NodeViewModel::getMessagesPerSecond() -> QVariant { if(auto optNum{_node.messages_per_second()}) { return {extract(optNum)}; } return {}; } //------------------------------------------------------------------------------ auto NodeViewModel::getPingSuccessRate() -> QVariant { if(auto optNum{_node.ping_success_rate()}) { return {extract(optNum)}; } return {}; } //------------------------------------------------------------------------------ auto NodeViewModel::getParameters() -> QAbstractItemModel* { return &_parameters; } //------------------------------------------------------------------------------ void NodeViewModel::onTrackerModelChanged() { if(auto trackerModel{_backend.trackerModel()}) { connect( trackerModel, &TrackerModel::nodeKindChanged, this, &NodeViewModel::onNodeInfoChanged); connect( trackerModel, &TrackerModel::nodeRelocated, this, &NodeViewModel::onNodeInfoChanged); connect( trackerModel, &TrackerModel::nodeInfoChanged, this, &NodeViewModel::onNodeInfoChanged); } } //------------------------------------------------------------------------------ void NodeViewModel::onNodeIdChanged(eagine::identifier_t nodeId) { if(nodeId) { if(auto trackerModel{_backend.trackerModel()}) { auto& tracker = trackerModel->tracker(); _node = tracker.get_node(nodeId); } } else { _node = {}; } emit infoChanged(); _parameters.setNodeId(nodeId); } //------------------------------------------------------------------------------ void NodeViewModel::onNodeInfoChanged(const remote_node& node) { if(node.id() == _node.id()) { emit infoChanged(); _parameters.notifyUpdated(); } } //------------------------------------------------------------------------------
34.714286
80
0.478519
ford442
e44d209461f833a0a5b7d53bb3448ed94fc4a6b0
8,625
cpp
C++
settings.cpp
sergrt/Gen61850Sv
ac4461ee0c755553e82be2513f635a6f92fb6f5d
[ "Apache-2.0" ]
6
2017-08-29T08:35:32.000Z
2021-07-10T07:56:56.000Z
settings.cpp
sergrt/Gen61850Sv
ac4461ee0c755553e82be2513f635a6f92fb6f5d
[ "Apache-2.0" ]
null
null
null
settings.cpp
sergrt/Gen61850Sv
ac4461ee0c755553e82be2513f635a6f92fb6f5d
[ "Apache-2.0" ]
4
2016-04-11T05:14:54.000Z
2022-01-20T16:16:30.000Z
#include "settings.h" const QString iniName = "settings.ini"; CSettings::CSettings() { signalShape = SGL_SHAPE_SIN; signalAmplitudeUa = signalAmplitudeUb = signalAmplitudeUc = signalAmplitudeUn = signalAmplitudeIa = signalAmplitudeIb = signalAmplitudeIc = signalAmplitudeIn = 100.0; signalFrequency = 50.0; signalPhaseUa = signalPhaseUb = signalPhaseUc = signalPhaseUn = signalPhaseIa = signalPhaseIb = signalPhaseIc = signalPhaseIn = 0.0; destinationMac = "FF:FF:FF:FF:FF:FF"; genStreamId = "sampleStream"; signalDiscrete = DISCRETE_80; captureMac = "FF:FF:FF:FF:FF:FF"; captureStreamId = "sampleStream"; langTranslation = LANG_TRANSLATE_RU; } void CSettings::load() { QSettings s(iniName, QSettings::IniFormat); s.beginGroup(getIniElementName(IF_GROUP_GENERATOR)); signalShape = static_cast<SGL_SHAPE>(s.value(getIniElementName(IF_SIGNAL_SHAPE)).toUInt()); signalAmplitudeUa = s.value(getIniElementName(IF_SIGNAL_AMPLITUDE_UA)).toDouble(); signalAmplitudeUb = s.value(getIniElementName(IF_SIGNAL_AMPLITUDE_UB)).toDouble(); signalAmplitudeUc = s.value(getIniElementName(IF_SIGNAL_AMPLITUDE_UC)).toDouble(); signalAmplitudeUn = s.value(getIniElementName(IF_SIGNAL_AMPLITUDE_UN)).toDouble(); signalAmplitudeIa = s.value(getIniElementName(IF_SIGNAL_AMPLITUDE_IA)).toDouble(); signalAmplitudeIb = s.value(getIniElementName(IF_SIGNAL_AMPLITUDE_IB)).toDouble(); signalAmplitudeIc = s.value(getIniElementName(IF_SIGNAL_AMPLITUDE_IC)).toDouble(); signalAmplitudeIn = s.value(getIniElementName(IF_SIGNAL_AMPLITUDE_IN)).toDouble(); signalFrequency = s.value(getIniElementName(IF_SIGNAL_FREQUENCY)).toDouble(); signalPhaseUa = s.value(getIniElementName(IF_SIGNAL_PHASE_UA)).toDouble(); signalPhaseUb = s.value(getIniElementName(IF_SIGNAL_PHASE_UB)).toDouble(); signalPhaseUc = s.value(getIniElementName(IF_SIGNAL_PHASE_UC)).toDouble(); signalPhaseUn = s.value(getIniElementName(IF_SIGNAL_PHASE_UN)).toDouble(); signalPhaseIa = s.value(getIniElementName(IF_SIGNAL_PHASE_IA)).toDouble(); signalPhaseIb = s.value(getIniElementName(IF_SIGNAL_PHASE_IB)).toDouble(); signalPhaseIc = s.value(getIniElementName(IF_SIGNAL_PHASE_IC)).toDouble(); signalPhaseIn = s.value(getIniElementName(IF_SIGNAL_PHASE_IN)).toDouble(); destinationMac = s.value(getIniElementName(IF_DESTINATION_MAC)).toString(); genStreamId = s.value(getIniElementName(IF_GEN_STREAM_ID)).toString(); signalDiscrete = static_cast<DISCRETE>(s.value(getIniElementName(IF_SIGNAL_DISCRETE)).toUInt()); genMac = s.value(getIniElementName(IF_GEN_MAC)).toString(); captureStreamId = s.value(getIniElementName(IF_CAPTURE_STREAM_ID)).toString(); captureMac = s.value(getIniElementName(IF_CAPTURE_MAC)).toString(); //signal1stHarmonicA = s.value(getIniElementName(IF_SIGNAL_1ST_HARMONIC_A)).toDouble(); //signal1stHarmonicPhi = s.value(getIniElementName(IF_SIGNAL_1ST_HARMONIC_PHI)).toDouble(); macFront = s.value(getIniElementName(IF_MAC_FRONT)).toString(); frontName = s.value(getIniElementName(IF_MAC_FRONT_NAME)).toString(); macRear = s.value(getIniElementName(IF_MAC_REAR)).toString(); rearName = s.value(getIniElementName(IF_MAC_REAR_NAME)).toString(); langTranslation = static_cast<LANG_TRANSLATE>(s.value(getIniElementName(IF_LANG_TRANSLATION)).toUInt()); s.endGroup(); } void CSettings::save() { QSettings s(iniName, QSettings::IniFormat); s.beginGroup(getIniElementName(IF_GROUP_GENERATOR)); s.setValue(getIniElementName(IF_SIGNAL_SHAPE), signalShape); s.setValue(getIniElementName(IF_SIGNAL_AMPLITUDE_UA), signalAmplitudeUa); s.setValue(getIniElementName(IF_SIGNAL_AMPLITUDE_UB), signalAmplitudeUb); s.setValue(getIniElementName(IF_SIGNAL_AMPLITUDE_UC), signalAmplitudeUc); s.setValue(getIniElementName(IF_SIGNAL_AMPLITUDE_UN), signalAmplitudeUn); s.setValue(getIniElementName(IF_SIGNAL_AMPLITUDE_IA), signalAmplitudeIa); s.setValue(getIniElementName(IF_SIGNAL_AMPLITUDE_IB), signalAmplitudeIb); s.setValue(getIniElementName(IF_SIGNAL_AMPLITUDE_IC), signalAmplitudeIc); s.setValue(getIniElementName(IF_SIGNAL_AMPLITUDE_IN), signalAmplitudeIn); s.setValue(getIniElementName(IF_SIGNAL_FREQUENCY), signalFrequency); s.setValue(getIniElementName(IF_SIGNAL_PHASE_UA), signalPhaseUa); s.setValue(getIniElementName(IF_SIGNAL_PHASE_UB), signalPhaseUb); s.setValue(getIniElementName(IF_SIGNAL_PHASE_UC), signalPhaseUc); s.setValue(getIniElementName(IF_SIGNAL_PHASE_UN), signalPhaseUn); s.setValue(getIniElementName(IF_SIGNAL_PHASE_IA), signalPhaseIa); s.setValue(getIniElementName(IF_SIGNAL_PHASE_IB), signalPhaseIb); s.setValue(getIniElementName(IF_SIGNAL_PHASE_IC), signalPhaseIc); s.setValue(getIniElementName(IF_SIGNAL_PHASE_IN), signalPhaseIn); s.setValue(getIniElementName(IF_DESTINATION_MAC), destinationMac); s.setValue(getIniElementName(IF_GEN_STREAM_ID), genStreamId); s.setValue(getIniElementName(IF_SIGNAL_DISCRETE), signalDiscrete); s.setValue(getIniElementName(IF_GEN_MAC), genMac); s.setValue(getIniElementName(IF_CAPTURE_STREAM_ID), captureStreamId); s.setValue(getIniElementName(IF_CAPTURE_MAC), captureMac); //s.setValue(getIniElementName(IF_SIGNAL_1ST_HARMONIC_A), signal1stHarmonicA); //s.setValue(getIniElementName(IF_SIGNAL_1ST_HARMONIC_PHI), signal1stHarmonicPhi); // Эти два не нужно сохранять из UI, они забиваются на заводе //s.setValue(getIniElementName(IF_MAC_FRONT), macFront); //s.setValue(getIniElementName(IF_MAC_REAR), macRear); s.endGroup(); } const QString CSettings::getIniElementName(const INI_ELEMENT element) { QString res; switch(element) { case IF_GROUP_GENERATOR: res = "generator"; break; case IF_SIGNAL_SHAPE: res = "signalShape"; break; case IF_SIGNAL_AMPLITUDE_UA: res = "signalAmplitudeUa"; break; case IF_SIGNAL_AMPLITUDE_UB: res = "signalAmplitudeUb"; break; case IF_SIGNAL_AMPLITUDE_UC: res = "signalAmplitudeUc"; break; case IF_SIGNAL_AMPLITUDE_UN: res = "signalAmplitudeUn"; break; case IF_SIGNAL_AMPLITUDE_IA: res = "signalAmplitudeIa"; break; case IF_SIGNAL_AMPLITUDE_IB: res = "signalAmplitudeIb"; break; case IF_SIGNAL_AMPLITUDE_IC: res = "signalAmplitudeIc"; break; case IF_SIGNAL_AMPLITUDE_IN: res = "signalAmplitudeIn"; break; case IF_SIGNAL_FREQUENCY: res = "signalFrequency"; break; case IF_SIGNAL_PHASE_UA: res = "signalPhaseUa"; break; case IF_SIGNAL_PHASE_UB: res = "signalPhaseUb"; break; case IF_SIGNAL_PHASE_UC: res = "signalPhaseUc"; break; case IF_SIGNAL_PHASE_UN: res = "signalPhaseUn"; break; case IF_SIGNAL_PHASE_IA: res = "signalPhaseIa"; break; case IF_SIGNAL_PHASE_IB: res = "signalPhaseIb"; break; case IF_SIGNAL_PHASE_IC: res = "signalPhaseIc"; break; case IF_SIGNAL_PHASE_IN: res = "signalPhaseIn"; break; case IF_DESTINATION_MAC: res = "destinationMac"; break; case IF_GEN_STREAM_ID: res = "genStreamId"; break; case IF_SIGNAL_DISCRETE: res = "signalDiscrete"; break; case IF_GEN_MAC: res = "genMac"; break; case IF_CAPTURE_STREAM_ID: res = "captureStreamId"; break; case IF_CAPTURE_MAC: res = "captureMac"; break; /* case IF_SIGNAL_1ST_HARMONIC_A: res = "signal1stHarmonicA"; break; case IF_SIGNAL_1ST_HARMONIC_PHI: res = "signal1stHarmonicPhi"; break; */ case IF_MAC_FRONT: res = "macFront"; break; case IF_MAC_REAR: res = "macRear"; break; case IF_MAC_FRONT_NAME: res = "frontName"; break; case IF_MAC_REAR_NAME: res = "rearName"; break; case IF_LANG_TRANSLATION: res = "langTranslation"; break; default: throw(""); break; } return res; }
39.56422
110
0.688696
sergrt
e44d9ca7e2b6057a6e02f6a01cf0b7b68e8f2560
2,997
cc
C++
src/FSISPH/computeFSISPHSumMassDensity.cc
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/FSISPH/computeFSISPHSumMassDensity.cc
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/FSISPH/computeFSISPHSumMassDensity.cc
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
#include "FSISPH/computeFSISPHSumMassDensity.hh" #include "Field/FieldList.hh" #include "Neighbor/ConnectivityMap.hh" #include "Kernel/TableKernel.hh" #include "NodeList/NodeList.hh" namespace Spheral{ template<typename Dimension> void computeFSISPHSumMassDensity(const ConnectivityMap<Dimension>& connectivityMap, const TableKernel<Dimension>& W, const std::vector<int>& sumDensityNodeLists, const FieldList<Dimension, typename Dimension::Vector>& position, const FieldList<Dimension, typename Dimension::Scalar>& mass, const FieldList<Dimension, typename Dimension::SymTensor>& H, FieldList<Dimension, typename Dimension::Scalar>& massDensity) { // Pre-conditions. const auto numNodeLists = massDensity.size(); REQUIRE(position.size() == numNodeLists); REQUIRE(mass.size() == numNodeLists); REQUIRE(H.size() == numNodeLists); // Some useful variables. const auto W0 = W.kernelValue(0.0, 1.0); // The set of interacting node pairs. const auto& pairs = connectivityMap.nodePairList(); const auto npairs = pairs.size(); for (auto nodeListi = 0u; nodeListi < numNodeLists; ++nodeListi) { const auto n = massDensity[nodeListi]->numInternalElements(); if (sumDensityNodeLists[nodeListi]==1){ #pragma omp parallel for for (auto i = 0u; i < n; ++i) { const auto mi = mass(nodeListi, i); const auto& Hi = H(nodeListi, i); const auto Hdeti = Hi.Determinant(); massDensity(nodeListi,i) = mi*Hdeti*W0; } } } // Now the pair contributions. #pragma omp parallel { int i, j, nodeListi, nodeListj; auto massDensity_thread = massDensity.threadCopy(); #pragma omp for for (auto k = 0u; k < npairs; ++k) { i = pairs[k].i_node; j = pairs[k].j_node; nodeListi = pairs[k].i_list; nodeListj = pairs[k].j_list; const auto mi = mass(nodeListi, i); const auto mj = mass(nodeListj, j); const auto& ri = position(nodeListi, i); const auto& rj = position(nodeListj, j); const auto rij = ri - rj; if(sumDensityNodeLists[nodeListi]==1){ const auto& Hi = H(nodeListi, i); const auto Hdeti = Hi.Determinant(); const auto etai = (Hi*rij).magnitude(); const auto Wi = W.kernelValue(etai, Hdeti); massDensity_thread(nodeListi, i) += (nodeListi == nodeListj ? mj : mi)*Wi; } if(sumDensityNodeLists[nodeListj]==1){ const auto& Hj = H(nodeListj, j); const auto Hdetj = Hj.Determinant(); const auto etaj = (Hj*rij).magnitude(); const auto Wj = W.kernelValue(etaj, Hdetj); massDensity_thread(nodeListj, j) += (nodeListi == nodeListj ? mi : mj)*Wj; } } #pragma omp critical { massDensity_thread.threadReduce(); } } } // function } //spheral namespace
31.547368
93
0.616617
jmikeowen
e44f27d17673edae597c8ce4e344fe9e57bbc5d3
1,555
cpp
C++
UVa Online Judge/10148. Advertisement.cpp
nicoelayda/competitive-programming
5b5452d8d2865a1a5f1e3d2fece011749722e8c4
[ "MIT" ]
null
null
null
UVa Online Judge/10148. Advertisement.cpp
nicoelayda/competitive-programming
5b5452d8d2865a1a5f1e3d2fece011749722e8c4
[ "MIT" ]
null
null
null
UVa Online Judge/10148. Advertisement.cpp
nicoelayda/competitive-programming
5b5452d8d2865a1a5f1e3d2fece011749722e8c4
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <map> #include <set> using namespace std; struct jogger { int a, b; jogger(int a, int b) { this->a = min(a, b); this->b = max(a, b); } bool operator< (const jogger &other) const { if (this->a == other.a) return this->b < other.b; return this->a > other.a; } }; int main() { int T; cin >> T; while (T-- != 0) { int k, n; cin >> k >> n; set<jogger> joggers; while (n-- != 0) { int a, b; cin >> a >> b; joggers.insert(jogger(a, b)); } set<int> ads; map<int, bool> has_ad; set<jogger>::iterator it_set; for (it_set = joggers.begin(); it_set != joggers.end(); it_set++) { int need = k; for (int i = it_set->a; i <= it_set->b && need > 0; i++) { if (has_ad[i]) need--; } for (int i = it_set->a; i <= it_set->b && need > 0; i++) { if (!has_ad[i]) { ads.insert(i); has_ad[i] = true; need--; } } } cout << ads.size() << endl; set<int>::iterator it_ads; for (it_ads = ads.begin(); it_ads != ads.end(); it_ads++) { cout << *it_ads << endl; } if (T != 0) cout << endl; } return 0; }
22.214286
76
0.379421
nicoelayda
e451fdb3e4971b53f3d2d077d768c3c28eb8a1c4
5,834
cc
C++
chromium/chrome/browser/ui/webui/media_router/query_result_manager.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/chrome/browser/ui/webui/media_router/query_result_manager.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/chrome/browser/ui/webui/media_router/query_result_manager.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/media_router/query_result_manager.h" #include "base/containers/hash_tables.h" #include "base/stl_util.h" #include "chrome/browser/media/router/media_router.h" #include "chrome/browser/media/router/media_sinks_observer.h" namespace media_router { // MediaSinkObserver that propagates results back to |result_manager|. // An instance of this class is associated with each registered MediaCastMode. class QueryResultManager::CastModeMediaSinksObserver : public MediaSinksObserver { public: CastModeMediaSinksObserver(MediaCastMode cast_mode, const MediaSource& source, MediaRouter* router, QueryResultManager* result_manager) : MediaSinksObserver(router, source), cast_mode_(cast_mode), result_manager_(result_manager) { DCHECK(result_manager); } ~CastModeMediaSinksObserver() override {} // MediaSinksObserver void OnSinksReceived(const std::vector<MediaSink>& result) override { latest_sink_ids_.clear(); for (const MediaSink& sink : result) { latest_sink_ids_.push_back(sink.id()); } result_manager_->UpdateWithSinksQueryResult(cast_mode_, result); result_manager_->NotifyOnResultsUpdated(); } // Returns the most recent sink IDs that were passed to |OnSinksReceived|. void GetLatestSinkIds(std::vector<MediaSink::Id>* sink_ids) const { DCHECK(sink_ids); *sink_ids = latest_sink_ids_; } MediaCastMode cast_mode() const { return cast_mode_; } private: MediaCastMode cast_mode_; std::vector<MediaSink::Id> latest_sink_ids_; QueryResultManager* result_manager_; }; QueryResultManager::QueryResultManager(MediaRouter* router) : router_(router) { DCHECK(router_); } QueryResultManager::~QueryResultManager() { DCHECK(thread_checker_.CalledOnValidThread()); } void QueryResultManager::AddObserver(Observer* observer) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(observer); observers_.AddObserver(observer); } void QueryResultManager::RemoveObserver(Observer* observer) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(observer); observers_.RemoveObserver(observer); } void QueryResultManager::StartSinksQuery(MediaCastMode cast_mode, const MediaSource& source) { DCHECK(thread_checker_.CalledOnValidThread()); if (source.Empty()) { LOG(WARNING) << "StartSinksQuery called with empty source for " << cast_mode; return; } SetSourceForCastMode(cast_mode, source); RemoveObserverForCastMode(cast_mode); UpdateWithSinksQueryResult(cast_mode, std::vector<MediaSink>()); scoped_ptr<CastModeMediaSinksObserver> observer( new CastModeMediaSinksObserver(cast_mode, source, router_, this)); observer->Init(); auto result = sinks_observers_.insert(std::make_pair(cast_mode, std::move(observer))); DCHECK(result.second); NotifyOnResultsUpdated(); } void QueryResultManager::StopSinksQuery(MediaCastMode cast_mode) { DCHECK(thread_checker_.CalledOnValidThread()); RemoveObserverForCastMode(cast_mode); SetSourceForCastMode(cast_mode, MediaSource()); UpdateWithSinksQueryResult(cast_mode, std::vector<MediaSink>()); NotifyOnResultsUpdated(); } void QueryResultManager::SetSourceForCastMode( MediaCastMode cast_mode, const MediaSource& source) { DCHECK(thread_checker_.CalledOnValidThread()); cast_mode_sources_[cast_mode] = source; } void QueryResultManager::RemoveObserverForCastMode(MediaCastMode cast_mode) { auto observers_it = sinks_observers_.find(cast_mode); if (observers_it != sinks_observers_.end()) sinks_observers_.erase(observers_it); } bool QueryResultManager::IsValid(const MediaSinkWithCastModes& entry) const { return !entry.cast_modes.empty(); } void QueryResultManager::UpdateWithSinksQueryResult( MediaCastMode cast_mode, const std::vector<MediaSink>& result) { base::hash_set<MediaSink::Id> result_sink_ids; for (const MediaSink& sink : result) result_sink_ids.insert(sink.id()); // (1) Iterate through current sink set, remove cast mode from those that // do not appear in latest result. for (auto it = all_sinks_.begin(); it != all_sinks_.end(); /*no-op*/) { if (!ContainsKey(result_sink_ids, it->first)) { it->second.cast_modes.erase(cast_mode); } if (!IsValid(it->second)) { all_sinks_.erase(it++); } else { ++it; } } // (2) Add / update sinks with latest result. for (const MediaSink& sink : result) { auto result = all_sinks_.insert(std::make_pair(sink.id(), MediaSinkWithCastModes(sink))); if (!result.second) result.first->second.sink = sink; result.first->second.cast_modes.insert(cast_mode); } } void QueryResultManager::GetSupportedCastModes(CastModeSet* cast_modes) const { DCHECK(cast_modes); cast_modes->clear(); for (const auto& observer_pair : sinks_observers_) { cast_modes->insert(observer_pair.first); } } MediaSource QueryResultManager::GetSourceForCastMode( MediaCastMode cast_mode) const { DCHECK(thread_checker_.CalledOnValidThread()); auto source_it = cast_mode_sources_.find(cast_mode); return source_it == cast_mode_sources_.end() ? MediaSource() : source_it->second; } void QueryResultManager::NotifyOnResultsUpdated() { std::vector<MediaSinkWithCastModes> sinks; for (const auto& sink_pair : all_sinks_) { sinks.push_back(sink_pair.second); } FOR_EACH_OBSERVER(QueryResultManager::Observer, observers_, OnResultsUpdated(sinks)); } } // namespace media_router
32.775281
79
0.728488
wedataintelligence
e452128ef04b0ab829fb3f018d7ec43399ea82b6
1,318
cpp
C++
mcc/src/FunctionAccess.cpp
petrufm/mcc
83d74c00a90971d5a1d5392878d8fd9351c3dfc6
[ "MIT" ]
2
2018-03-12T03:05:57.000Z
2019-04-17T10:19:59.000Z
mcc/src/FunctionAccess.cpp
petrufm/mcc
83d74c00a90971d5a1d5392878d8fd9351c3dfc6
[ "MIT" ]
null
null
null
mcc/src/FunctionAccess.cpp
petrufm/mcc
83d74c00a90971d5a1d5392878d8fd9351c3dfc6
[ "MIT" ]
null
null
null
#include "FunctionAccess.h" #include "MethodDeclaration.h" #include "ConcreteTableColumn.h" FunctionAccess::FunctionAccess(DataExtractor *next, ConcreteTableColumn *prototype, MethodDeclaration *condition):DataExtractor(next,prototype,condition) {}; TableColumn* FunctionAccess::handleExtraction(AbstractTree &tree) { TableColumn *column = prototype->clone(); std::string class_op = "class"; std::string class_decls_section = "class_decls_section"; std::string access_specifier = "access_specifier"; std::string class_kw = "class_kw"; std::string value; VTP_TreeP tmp_tree; tmp_tree = tree.tree; do { tmp_tree = VTP_TreeUp(tmp_tree); } while(class_decls_section != VTP_OP_NAME(VTP_TREE_OPERATOR(tmp_tree))); if(class_decls_section == VTP_OP_NAME(VTP_TREE_OPERATOR(tmp_tree)) && access_specifier == VTP_OP_NAME(VTP_TREE_OPERATOR(tmp_tree = VTP_TreeDown(tmp_tree,0)))) { value = VTP_NAME_STRING(VTP_TreeAtomValue(tmp_tree)); } else { do { tmp_tree = VTP_TreeUp(tmp_tree); } while(class_op != VTP_OP_NAME(VTP_TREE_OPERATOR(tmp_tree))); tmp_tree = VTP_TreeDown(VTP_TreeDown(tmp_tree,0),0); if(class_kw == VTP_OP_NAME(VTP_TREE_OPERATOR(tmp_tree))) { value = "private"; } else { value = "public"; } } column->init(value,false,1,TableColumn::MergeByCopy); return column; }
33.794872
157
0.752656
petrufm
e45222430b5572e5b5fe32f2f958fa0addfc8ba6
563
hpp
C++
Day03/ex03/ScavTrap.hpp
EnapsTer/StudyCPP
4bcf2a152fbefebab8ff68574e2b3bc198589f99
[ "MIT" ]
1
2021-09-08T12:16:13.000Z
2021-09-08T12:16:13.000Z
Day03/ex03/ScavTrap.hpp
EnapsTer/StudyCPP
4bcf2a152fbefebab8ff68574e2b3bc198589f99
[ "MIT" ]
null
null
null
Day03/ex03/ScavTrap.hpp
EnapsTer/StudyCPP
4bcf2a152fbefebab8ff68574e2b3bc198589f99
[ "MIT" ]
null
null
null
// // Created by Arborio Herlinda on 5/14/21. // #ifndef SCAVTRAP_HPP #define SCAVTRAP_HPP #define CHALLENGES_COUNT 5 #include <iostream> #include "ClapTrap.hpp" class ScavTrap : public ClapTrap { public: ScavTrap(std::string const &name); ScavTrap(ScavTrap const &other); ScavTrap &operator=(ScavTrap const &other); virtual ~ScavTrap(); void RangedAttack(std::string const &target); void MeleeAttack(std::string const &target); void TakeDamage(unsigned int amount); void BeRepaired(unsigned int amount); void ChallengeNewcomer(); }; #endif
22.52
47
0.738899
EnapsTer
e4586678f34783972c84f2ac8b74ffa31190568f
7,720
cpp
C++
src/iptv_utils_gst.cpp
karimdavoodi/iptv_out
ad1b3282456d42ec0ace4213e98a2014b648cfaf
[ "MIT" ]
3
2020-09-16T01:45:01.000Z
2021-11-02T14:34:45.000Z
src/iptv_utils_gst.cpp
karimdavoodi/iptv_out
ad1b3282456d42ec0ace4213e98a2014b648cfaf
[ "MIT" ]
null
null
null
src/iptv_utils_gst.cpp
karimdavoodi/iptv_out
ad1b3282456d42ec0ace4213e98a2014b648cfaf
[ "MIT" ]
null
null
null
/* * Copyright (c) 2020 Karim, karimdavoodi@gmail.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <string> #include <chrono> #include <boost/tokenizer.hpp> #include <boost/filesystem.hpp> #include <boost/log/trivial.hpp> #include <boost/log/core.hpp> #include "../third_party/json.hpp" #include "iptv_utils_gst.hpp" #include "utils.hpp" using namespace std; void SysUsage::calcCurrentUsage() { calcCurrentPartitions(); calcCurrentInterfaces(); calcCurrentCpu(); calcCurrentMem(); calcCurrentLoad(); calcCurrentContents(); } string SysUsage::getUsageJson(int systemId) { Data delta; priviuse = current; try{ calcCurrentUsage(); // CPU Usage float totald = current.cpuTotal - priviuse.cpuTotal; float idled = current.cpuIdle - priviuse.cpuIdle; delta.cpuUsage = (totald - idled) / totald; // Disk Usage for(const auto& [name, transfering] : current.partitions){ transfer d; d.read = transfering.read - priviuse.partitions[name].read; d.write = transfering.write - priviuse.partitions[name].write; delta.partitions[name] = d; } // Network Usage for(const auto& [name, transfering] : current.interfaces){ transfer d; d.read = transfering.read - priviuse.interfaces[name].read; d.write = transfering.write - priviuse.interfaces[name].write; delta.interfaces[name] = d; } // Total Disk Usage float diskUsage = 0; string percent = Util::shell_out("df /opt/sms/www/iptv/media/Video " "| tail -1 | awk '{print $5}' "); if(percent.find('%') != string::npos) diskUsage = stof(percent.substr(0,percent.find('%'))); else diskUsage = stof(percent); // Build JSON using nlohmann::json; json usage = json::object(); auto now = chrono::system_clock::now(); now.time_since_epoch().count(); usage["_id"] = now.time_since_epoch().count(); usage["time"] = now.time_since_epoch().count()/1000000000; usage["systemId"] = systemId; usage["sysLoad"] = current.sysLoad; usage["cpuUsage"] = delta.cpuUsage; usage["memUsage"] = (current.memTotal - current.memAvailable) / current.memTotal; usage["diskUsage"] = diskUsage / 100; usage["networkInterfaces"] = json::array(); for(const auto& interface : delta.interfaces){ json net = json::object(); net["name"] = interface.first; net["read"] = uint64_t(interface.second.read); net["write"] = uint64_t(interface.second.write); usage["networkInterfaces"].push_back(net); } usage["diskPartitions"] = json::array(); for(const auto& partition : delta.partitions){ json part = json::object(); part["name"] = partition.first; part["read"] = uint64_t(partition.second.read); part["write"] = uint64_t(partition.second.write); usage["diskPartitions"].push_back(part); } json contents = json::object(); for(const auto& content : current.contents){ contents[content.first] = content.second; } usage["contents"] = contents; return usage.dump(2); }catch(std::exception& e){ LOG(error) << e.what(); } return "{}"; } void SysUsage::calcCurrentPartitions() { string line; // 8 1 sda1 152 895 14335 2105 3 0 10 12 0 1704 2117 0 0 0 0 0 0 ifstream disk("/proc/diskstats"); while(disk.good()){ getline(disk, line); if(line.find(" sd") == string::npos) continue; vector<string> fields; boost::tokenizer<> tok(line); for(const auto& t : tok){ fields.push_back(t); } string name = fields[2]; current.partitions[name].read = 512*stof(fields[5]); current.partitions[name].write = 512*stof(fields[9]); } } void SysUsage::calcCurrentInterfaces() { for(const auto& dir : boost::filesystem::directory_iterator("/sys/class/net")){ string name = dir.path().filename().c_str(); string rx_file = "/sys/class/net/"+name+"/statistics/rx_bytes"; string tx_file = "/sys/class/net/"+name+"/statistics/tx_bytes"; auto read = Util::get_file_content(rx_file); if(read.size()){ current.interfaces[name].read = stof(read); } auto write = Util::get_file_content(tx_file); if(write.size()){ current.interfaces[name].write = stof(write); } } } void SysUsage::calcCurrentCpu() { string line; ifstream stat("/proc/stat"); if(!stat.is_open()) return; getline(stat, line); boost::tokenizer<> tok(line); auto it = tok.begin(); float user = stof(*(++it)); float nice = stof(*(++it)); float system = stof(*(++it)); float idle = stof(*(++it)); float iowait = stof(*(++it)); float irq = stof(*(++it)); float softirq = stof(*(++it)); float steal = stof(*(++it)); idle = idle + iowait; float nonIdle = user + nice + system + irq + softirq + steal; current.cpuIdle = idle; current.cpuTotal = idle + nonIdle; } void SysUsage::calcCurrentMem() { float total = 0; float available = 0; string line; ifstream mem("/proc/meminfo"); while(mem.good()){ getline(mem, line); if(line.find("MemTotal") != string::npos){ boost::tokenizer<> tok(line); auto it = tok.begin(); total = stof(*(++it)); } if(line.find("MemAvailable") != string::npos){ boost::tokenizer<> tok(line); auto it = tok.begin(); available = stof(*(++it)); break; } } current.memTotal = total; current.memAvailable = available; } void SysUsage::calcCurrentLoad() { string line; ifstream load("/proc/loadavg"); if(!load.is_open()) return; load >> current.sysLoad; } void SysUsage::calcCurrentContents() { long all_size = 1024 * stol(Util::shell_out( "df /opt/sms/www/iptv/media/Video | tail -1 | awk '{print $2}' ")) ; current.contents["All"] = all_size; for(const auto& content : contents_dir){ auto path = "/opt/sms/www/iptv/media/" + content; if(boost::filesystem::exists(path)){ current.contents[content] = stol(Util::shell_out( "du -sb " + path + "| tail -1 | awk '{print $1}' ")) ; }else{ current.contents[content] = 0; } } }
36.244131
89
0.6
karimdavoodi
e45980f6c9cf561f59a946e8b9c8b6c1ff42f6d2
15,818
hpp
C++
inference-engine/thirdparty/mkl-dnn/src/cpu/jit_uni_dw_convolution.hpp
fujunwei/dldt
09497b7724de4be92629f7799b8538b483d809a2
[ "Apache-2.0" ]
null
null
null
inference-engine/thirdparty/mkl-dnn/src/cpu/jit_uni_dw_convolution.hpp
fujunwei/dldt
09497b7724de4be92629f7799b8538b483d809a2
[ "Apache-2.0" ]
null
null
null
inference-engine/thirdparty/mkl-dnn/src/cpu/jit_uni_dw_convolution.hpp
fujunwei/dldt
09497b7724de4be92629f7799b8538b483d809a2
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef CPU_JIT_UNI_DW_CONVOLUTION_HPP #define CPU_JIT_UNI_DW_CONVOLUTION_HPP #include "c_types_map.hpp" #include "memory_tracking.hpp" #include "cpu_barrier.hpp" #include "cpu_convolution_pd.hpp" #include "cpu_reducer.hpp" #include "jit_uni_dw_conv_kernel_utils.hpp" namespace mkldnn { namespace impl { namespace cpu { template <cpu_isa_t isa, data_type_t src_type, data_type_t dst_type = src_type> struct _jit_uni_dw_convolution_fwd_t : public cpu_primitive_t { struct pd_t : public cpu_convolution_fwd_pd_t { pd_t(engine_t *engine, const convolution_desc_t *adesc, const primitive_attr_t *attr, const typename pd_t::base_class *hint_fwd_pd) : cpu_convolution_fwd_pd_t(engine, adesc, attr, hint_fwd_pd) , jcp_() {} DECLARE_COMMON_PD_T(JIT_IMPL_NAME_HELPER("jit_dw:", isa, ""), _jit_uni_dw_convolution_fwd_t<isa, src_type, dst_type>); virtual status_t init() override { using namespace prop_kind; assert(this->engine()->kind() == engine_kind::cpu); bool ok = true && this->set_default_params() == status::success && utils::one_of(this->desc()->prop_kind, forward_training, forward_inference) && utils::one_of(this->desc()->alg_kind, alg_kind::convolution_auto, alg_kind::convolution_direct) && !this->has_zero_dim_memory() && utils::everyone_is(src_type, this->desc()->src_desc.data_type, this->desc()->weights_desc.data_type) && this->desc()->dst_desc.data_type == dst_type && IMPLICATION(this->with_bias(), utils::one_of( this->desc()->bias_desc.data_type, data_type::f32, data_type::bf16)) && !this->attr()->has_asymmetric_quantization(); if (!ok) return status::unimplemented; status_t status = jit_uni_dw_conv_fwd_kernel<isa, src_type>::init_conf(jcp_, *this->desc(), this->src_pd_.desc(), *this->weights_pd_.desc(), *this->dst_pd_.desc(), *this->attr()); if (status != status::success) return status; auto scratchpad = scratchpad_registry().registrar(); jit_uni_dw_conv_fwd_kernel<isa, src_type>::init_scratchpad( scratchpad, jcp_); return status::success; } jit_conv_conf_t jcp_; protected: virtual status_t set_default_params() override { using namespace memory_format; auto desired_act_fmt = ndims() == 5 ? utils::one_of(isa, avx512_common, avx512_core) ? nCdhw16c : nCdhw8c : utils::one_of(isa, avx512_common, avx512_core) ? nChw16c : nChw8c; auto desired_wei_fmt = ndims() == 5 ? utils::one_of(isa, avx512_common, avx512_core) ? Goidhw16g : Goidhw8g : utils::one_of(isa, avx512_common, avx512_core) ? Goihw16g : Goihw8g; if (this->src_pd_.desc()->format == any) CHECK(this->src_pd_.set_format(desired_act_fmt)); if (this->dst_pd_.desc()->format == any) CHECK(this->dst_pd_.set_format(desired_act_fmt)); if (this->weights_pd_.desc()->format == any) CHECK(this->weights_pd_.set_format(desired_wei_fmt)); if (this->bias_pd_.desc()->format == any) CHECK(this->bias_pd_.set_format(x)); if (this->desc()->alg_kind == alg_kind::convolution_auto) CHECK(this->set_alg_kind(alg_kind::convolution_direct)); return status::success; } }; _jit_uni_dw_convolution_fwd_t(const pd_t *apd, const input_vector &inputs, const output_vector &outputs) : cpu_primitive_t(apd, inputs, outputs), kernel_(nullptr) { kernel_ = new jit_uni_dw_conv_fwd_kernel<isa, src_type>(pd()->jcp_, *pd()->attr()); } ~_jit_uni_dw_convolution_fwd_t() { delete kernel_; } typedef typename prec_traits<data_type::f32>::type f32_data_t; typedef typename prec_traits<data_type::bf16>::type bf16_data_t; typedef typename prec_traits<src_type>::type data_t; typedef typename prec_traits<dst_type>::type dst_data_t; virtual void execute(event_t *e) const { execute_forward(); e->set_state(event_t::ready); } private: void execute_forward() const; const pd_t *pd() const { return (const pd_t *)primitive_t::pd(); } jit_uni_dw_conv_fwd_kernel<isa, src_type> *kernel_; }; using jit_avx512_common_dw_convolution_fwd_t = _jit_uni_dw_convolution_fwd_t<avx512_common, data_type::f32>; using jit_avx2_dw_convolution_fwd_t = _jit_uni_dw_convolution_fwd_t<avx2, data_type::f32>; using jit_sse42_dw_convolution_fwd_t = _jit_uni_dw_convolution_fwd_t<sse42, data_type::f32>; template <cpu_isa_t isa, data_type_t diff_dst_type, data_type_t diff_src_type = diff_dst_type> struct _jit_uni_dw_convolution_bwd_data_t : public cpu_primitive_t { struct pd_t : public cpu_convolution_bwd_data_pd_t { pd_t(engine_t *engine, const convolution_desc_t *adesc, const primitive_attr_t *attr, const convolution_fwd_pd_t *hint_fwd_pd) : cpu_convolution_bwd_data_pd_t(engine, adesc, attr, hint_fwd_pd) , jcp_() {} DECLARE_COMMON_PD_T(JIT_IMPL_NAME_HELPER("jit_dw:", isa, ""), _jit_uni_dw_convolution_bwd_data_t<isa, diff_dst_type, diff_src_type>); virtual status_t init() override { using namespace prop_kind; assert(this->engine()->kind() == engine_kind::cpu); bool ok = true && this->set_default_params() == status::success && utils::one_of( this->desc()->prop_kind, backward, backward_data) && utils::one_of(this->desc()->alg_kind, alg_kind::convolution_auto, alg_kind::convolution_direct) && !this->has_zero_dim_memory() && utils::everyone_is(diff_dst_type, this->desc()->weights_desc.data_type, this->desc()->diff_dst_desc.data_type) && diff_src_type == this->desc()->diff_src_desc.data_type; if (!ok) return status::unimplemented; status_t status = jit_uni_dw_conv_bwd_data_kernel<isa, diff_dst_type>::init_conf(jcp_, *this->desc(), *this->diff_src_pd_.desc(), *this->weights_pd_.desc(), *this->diff_dst_pd_.desc(), *this->attr()); if (status != status::success) return status; auto scratchpad = scratchpad_registry().registrar(); jit_uni_dw_conv_bwd_data_kernel<isa, diff_dst_type>::init_scratchpad(scratchpad, jcp_); return status::success; } jit_conv_conf_t jcp_; protected: virtual status_t set_default_params() override { using namespace memory_format; auto desired_act_fmt = utils::one_of(isa, avx512_common, avx512_core) ? nChw16c : nChw8c; auto desired_wei_fmt = utils::one_of(isa, avx512_common, avx512_core) ? Goihw16g : Goihw8g; if (this->diff_src_pd_.desc()->format == any) CHECK(this->diff_src_pd_.set_format(desired_act_fmt)); if (this->diff_dst_pd_.desc()->format == any) CHECK(this->diff_dst_pd_.set_format(desired_act_fmt)); if (this->weights_pd_.desc()->format == any) CHECK(this->weights_pd_.set_format(desired_wei_fmt)); if (this->desc()->alg_kind == alg_kind::convolution_auto) CHECK(this->set_alg_kind(alg_kind::convolution_direct)); return status::success; } }; _jit_uni_dw_convolution_bwd_data_t(const pd_t *apd, const input_vector &inputs, const output_vector &outputs) : cpu_primitive_t(apd, inputs, outputs) { kernel_ = new jit_uni_dw_conv_bwd_data_kernel<isa, diff_dst_type>( pd()->jcp_, *pd()->attr()); } ~_jit_uni_dw_convolution_bwd_data_t() { delete kernel_; }; typedef typename prec_traits<diff_src_type>::type diff_src_data_t; typedef typename prec_traits<diff_dst_type>::type diff_dst_data_t; typedef typename prec_traits<diff_dst_type>::type diff_wei_data_t; virtual void execute(event_t *e) const { switch (pd()->desc()->prop_kind) { case prop_kind::backward_data: execute_backward_data(); break; default: assert(!"invalid prop_kind"); } e->set_state(event_t::ready); } private: void execute_backward_data() const; const pd_t *pd() const { return (const pd_t *)primitive_t::pd(); } jit_uni_dw_conv_bwd_data_kernel<isa, diff_dst_type> *kernel_; }; using jit_avx512_common_dw_convolution_bwd_data_t = _jit_uni_dw_convolution_bwd_data_t<avx512_common, data_type::f32>; using jit_avx2_dw_convolution_bwd_data_t = _jit_uni_dw_convolution_bwd_data_t<avx2, data_type::f32>; using jit_sse42_dw_convolution_bwd_data_t = _jit_uni_dw_convolution_bwd_data_t<sse42, data_type::f32>; template <cpu_isa_t isa, data_type_t src_type, data_type_t diff_weights_type = src_type> struct _jit_uni_dw_convolution_bwd_weights_t : public cpu_primitive_t { struct pd_t : public cpu_convolution_bwd_weights_pd_t { pd_t(engine_t *engine, const convolution_desc_t *adesc, const primitive_attr_t *attr, const convolution_fwd_pd_t *hint_fwd_pd) : cpu_convolution_bwd_weights_pd_t(engine, adesc, attr, hint_fwd_pd) , jcp_() {} DECLARE_COMMON_PD_T(JIT_IMPL_NAME_HELPER("jit_dw:", isa, ""), _jit_uni_dw_convolution_bwd_weights_t<isa, src_type, diff_weights_type>); virtual status_t init() override { using namespace prop_kind; assert(this->engine()->kind() == engine_kind::cpu); bool ok = true && this->set_default_params() == status::success && this->desc()->prop_kind == prop_kind::backward_weights && utils::one_of(this->desc()->alg_kind, alg_kind::convolution_auto, alg_kind::convolution_direct) && utils::everyone_is(src_type, this->desc()->src_desc.data_type, this->desc()->diff_dst_desc.data_type) && this->desc()->diff_weights_desc.data_type == diff_weights_type; if (!ok) return status::unimplemented; const int max_threads = mkldnn_in_parallel() ? 1 : mkldnn_get_max_threads(); status_t status = jit_uni_dw_conv_bwd_weights_kernel<isa, src_type>::init_conf(jcp_, *this->desc(), *this->src_pd_.desc(), *this->diff_weights_pd_.desc(), *this->diff_dst_pd_.desc(), max_threads); if (status != status::success) return status; auto scratchpad = scratchpad_registry().registrar(); jit_uni_dw_conv_bwd_weights_kernel<isa, src_type>::init_scratchpad( scratchpad, jcp_); return status::success; } jit_conv_conf_t jcp_; protected: virtual status_t set_default_params() override { using namespace memory_format; auto desired_act_fmt = utils::one_of(isa, avx512_common, avx512_core) ? nChw16c : nChw8c; auto desired_wei_fmt = utils::one_of(isa, avx512_common, avx512_core) ? Goihw16g : Goihw8g; if (this->src_pd_.desc()->format == any) CHECK(this->src_pd_.set_format(desired_act_fmt)); if (this->diff_dst_pd_.desc()->format == any) CHECK(this->diff_dst_pd_.set_format(desired_act_fmt)); if (this->diff_weights_pd_.desc()->format == any) CHECK(this->diff_weights_pd_.set_format(desired_wei_fmt)); if (this->diff_bias_pd_.desc()->format == any) CHECK(this->diff_bias_pd_.set_format(x)); if (this->desc()->alg_kind == alg_kind::convolution_auto) CHECK(this->set_alg_kind(alg_kind::convolution_direct)); return status::success; } }; _jit_uni_dw_convolution_bwd_weights_t(const pd_t *apd, const input_vector &inputs, const output_vector &outputs) : cpu_primitive_t(apd, inputs, outputs) , acc_ker_(nullptr) , kernel_(nullptr) { kernel_ = new jit_uni_dw_conv_bwd_weights_kernel<isa, src_type>( pd()->jcp_); if (pd()->jcp_.nthr_mb > 1 && isa != sse42) acc_ker_ = new cpu_accumulator_1d_t<data_type::f32>(); } ~_jit_uni_dw_convolution_bwd_weights_t() { delete acc_ker_; delete kernel_; }; typedef typename prec_traits<data_type::f32>::type f32_data_t; typedef typename prec_traits<data_type::bf16>::type bf16_data_t; typedef typename prec_traits<src_type>::type src_data_t; typedef typename prec_traits<src_type>::type diff_dst_data_t; typedef typename prec_traits<diff_weights_type>::type diff_weights_data_t; virtual void execute(event_t *e) const { execute_backward_weights(); execute_reduction(); e->set_state(event_t::ready); } private: void execute_backward_weights() const; void execute_reduction() const; const pd_t *pd() const { return (const pd_t *)primitive_t::pd(); } cpu_accumulator_1d_t<data_type::f32> *acc_ker_; jit_uni_dw_conv_bwd_weights_kernel<isa, src_type> *kernel_; }; using jit_avx512_common_dw_convolution_bwd_weights_t = _jit_uni_dw_convolution_bwd_weights_t<avx512_common, data_type::f32>; using jit_avx2_dw_convolution_bwd_weights_t = _jit_uni_dw_convolution_bwd_weights_t<avx2, data_type::f32>; using jit_sse42_dw_convolution_bwd_weights_t = _jit_uni_dw_convolution_bwd_weights_t<sse42, data_type::f32>; } } } #endif
42.867209
119
0.599886
fujunwei
e45a4370fc48147625ef2f9896c75782dcca1a2a
371
cpp
C++
algo1.cpp
zyfjeff/utils_code
034b1a0ff9ae4f7cebafdd7cfa464cc52119ab24
[ "Apache-2.0" ]
null
null
null
algo1.cpp
zyfjeff/utils_code
034b1a0ff9ae4f7cebafdd7cfa464cc52119ab24
[ "Apache-2.0" ]
null
null
null
algo1.cpp
zyfjeff/utils_code
034b1a0ff9ae4f7cebafdd7cfa464cc52119ab24
[ "Apache-2.0" ]
1
2020-02-21T17:16:50.000Z
2020-02-21T17:16:50.000Z
#include <cinttypes> #include <iostream> #include <vector> using namespace std; int main(int argc,char* argv[]) { using IntVector = vector<int32_t>; using IntVectorIterator = IntVector::iterator; IntVector myVector{0,1,2,3,4}; for(IntVectorIterator iter = myVector.begin();iter != myVector.end();++iter) { cout << "The value is: " << *iter << endl; } return 0; }
19.526316
76
0.690027
zyfjeff
e45c25b3028f8f9ed1d5be6c8e61476c739e3814
1,836
cpp
C++
Cpp/fost-crypto/nonce.cpp
KayEss/fost-base
05ac1b6a1fb672c61ba6502efea86f9c5207e28f
[ "BSL-1.0" ]
2
2016-05-25T22:17:38.000Z
2019-04-02T08:34:17.000Z
Cpp/fost-crypto/nonce.cpp
KayEss/fost-base
05ac1b6a1fb672c61ba6502efea86f9c5207e28f
[ "BSL-1.0" ]
5
2018-07-13T10:43:05.000Z
2019-09-02T14:54:42.000Z
Cpp/fost-crypto/nonce.cpp
KayEss/fost-base
05ac1b6a1fb672c61ba6502efea86f9c5207e28f
[ "BSL-1.0" ]
1
2020-10-22T20:44:24.000Z
2020-10-22T20:44:24.000Z
/** Copyright 2016-2019 Red Anchor Trading Co. Ltd. Distributed under the Boost Software License, Version 1.0. See <http://www.boost.org/LICENSE_1_0.txt> */ #include "fost-crypto.hpp" #include <fost/crypto.hpp> #include <fost/nonce.hpp> #include <chrono> namespace { template<std::size_t Size> fostlib::base64_string nonce() { const auto base64url = [](auto &&v) { fostlib::utf8_string b64u; for (const auto c : v) { if (c == '+') b64u += '-'; else if (c == '/') b64u += '_'; else if (c == '=') return b64u; else b64u += c; } return b64u; }; const auto bytes = fostlib::crypto_bytes<Size>(); const auto b64 = fostlib::coerce<fostlib::base64_string>( std::vector<unsigned char>(bytes.begin(), bytes.end())); return fostlib::ascii_string{base64url(b64)}; } template<std::size_t Size> fostlib::base64_string timed() { const auto time = std::chrono::system_clock::now(); const auto t_epoch = std::chrono::system_clock::to_time_t(time); // We assume POSIX return (std::to_string(t_epoch) + "-" + std::string(nonce<Size>())) .c_str(); } } fostlib::base64_string fostlib::nonce8b64u() { return nonce<8>(); } fostlib::base64_string fostlib::nonce24b64u() { return nonce<24>(); } fostlib::base64_string fostlib::nonce32b64u() { return nonce<32>(); } fostlib::base64_string fostlib::timestamp_nonce8b64u() { return timed<8>(); } fostlib::base64_string fostlib::timestamp_nonce24b64u() { return timed<24>(); } fostlib::base64_string fostlib::timestamp_nonce32b64u() { return timed<32>(); }
29.142857
79
0.568083
KayEss
e45d0bef946918cbf1fe4264d47efe1d203e082c
11,551
cc
C++
lib/lljvm-native/lljvm.cc
maropu/lljvm-translator
322fbe24a27976948c8e8081a9552152dda58b4b
[ "Apache-2.0" ]
70
2017-12-12T10:54:00.000Z
2022-03-22T07:45:19.000Z
lib/lljvm-native/lljvm.cc
maropu/lljvm-as
322fbe24a27976948c8e8081a9552152dda58b4b
[ "Apache-2.0" ]
14
2018-02-28T01:29:46.000Z
2019-12-10T01:42:22.000Z
lib/lljvm-native/lljvm.cc
maropu/lljvm-as
322fbe24a27976948c8e8081a9552152dda58b4b
[ "Apache-2.0" ]
4
2019-07-21T07:58:25.000Z
2021-02-01T09:46: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.io/github/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 "backend.h" #include "lljvm-internals.h" #include "io_github_maropu_lljvm_LLJVMNative.h" #include <llvm/ADT/DenseSet.h> #include <llvm/Bitcode/BitcodeReader.h> #include <llvm/CodeGen/Passes.h> #include <llvm/IR/LegacyPassManager.h> #include <llvm/IR/IRPrintingPasses.h> #include <llvm/IR/Verifier.h> #include <llvm/Transforms/IPO.h> #include <llvm/Transforms/IPO/AlwaysInliner.h> #include <llvm/Transforms/IPO/PassManagerBuilder.h> #include <llvm/Transforms/Scalar.h> #include <llvm/Transforms/Utils.h> #include <llvm/Target/TargetMachine.h> using namespace llvm; const std::string LLJVM_VERSION_NUMBER = "0.2.0-EXPERIMENTAL"; const std::string LLJVM_GENERATED_CLASSNAME_PREFIX = "GeneratedClass"; const std::string LLJVM_MAGIC_NUMBER = "20180731HMKjwzxmew"; static void throwException(JNIEnv *env, jobject& self, const std::string& err_msg) { jclass c = env->FindClass("io/github/maropu/lljvm/LLJVMNative"); assert(c != 0); jmethodID mth_throwex = env->GetMethodID(c, "throwException", "(Ljava/lang/String;)V"); assert(mth_throwex != 0); env->CallVoidMethod(self, mth_throwex, env->NewStringUTF(err_msg.c_str())); } static bool checkIfFieldExistInRuntime(JNIEnv *env, jobject& self, const std::string& fieldName) { jclass c = env->FindClass("io/github/maropu/lljvm/LLJVMNative"); assert(c != 0); jmethodID mth_exists = env->GetMethodID(c, "checkIfFieldExistInRuntime", "(Ljava/lang/String;)Z"); assert(mth_exists != 0); bool exists = (bool) env->CallIntMethod(self, mth_exists, env->NewStringUTF(fieldName.c_str())); return exists; } static bool checkIfFunctionExistInRuntime(JNIEnv *env, jobject& self, const std::string& methodSignature) { jclass c = env->FindClass("io/github/maropu/lljvm/LLJVMNative"); assert(c != 0); jmethodID mth_exists = env->GetMethodID(c, "checkIfFunctionExistInRuntime", "(Ljava/lang/String;)Z"); assert(mth_exists != 0); bool exists = (bool) env->CallIntMethod(self, mth_exists, env->NewStringUTF(methodSignature.c_str())); return exists; } // Adds optimization passes based on the selected optimization level. // This function was copied from `llvm/tools/opt/opt.cpp` and modified a little. static void addOptimizationPasses(legacy::PassManager& pm, int optLevel, int sizeLevel) { PassManagerBuilder pmBuilder; pmBuilder.OptLevel = optLevel; pmBuilder.SizeLevel = sizeLevel; if (optLevel > 1) { pmBuilder.Inliner = createFunctionInliningPass(optLevel, sizeLevel, false); } else { pmBuilder.Inliner = createAlwaysInlinerLegacyPass(); } pmBuilder.DisableUnitAtATime = false; pmBuilder.DisableUnrollLoops = false; // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize) if (!pmBuilder.LoopVectorize) { pmBuilder.LoopVectorize = optLevel > 1 && sizeLevel < 2; } // When #pragma vectorize is on for SLP, do the same as above pmBuilder.SLPVectorize = optLevel > 1 && sizeLevel < 2; pmBuilder.populateModulePassManager(pm); } static void initializePasses( LLVMContext& context, legacy::PassManager& pm, const char *bitcode, size_t size, int optLevel, int sizeLevel, unsigned debugLevel) { if (debugLevel > 0) { pm.add(createVerifierPass()); } if (optLevel >= 0 && sizeLevel >= 0) { // TODO: Add more optimization logics based on `llvm/tools/opt/opt.cpp` // Apply optimization passes into the given bitcode addOptimizationPasses(pm, optLevel, sizeLevel); // List up other optimization passes // TODO: fix switch generation so the following pass is not needed pm.add(createLowerSwitchPass()); pm.add(createCFGSimplificationPass()); pm.add(createGCLoweringPass()); // pm.add(createGCInfoDeleter()); } } const std::string toJVMAssemblyCode( JNIEnv *env, jobject *self, const char *bitcode, size_t size, int optLevel, int sizeLevel, unsigned debugLevel) { // Prepare an output pass for printing LLVM IR into the JVM assembly code const std::string clazz = LLJVM_GENERATED_CLASSNAME_PREFIX + LLJVM_MAGIC_NUMBER; std::string out; raw_string_ostream strbuf(out); DataLayout td( // Support 64bit platforms only "e-p:64:64:64" "-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64" "-f32:32:32-f64:64:64" ); LLVMContext context; legacy::PassManager pm; // Registers optimization passes in the given pass manager initializePasses(context, pm, bitcode, size, optLevel, sizeLevel, debugLevel); // Finally, add a pass for output JVMWriter *jvmWriter = new JVMWriter(&td, strbuf, clazz, debugLevel); pm.add(jvmWriter); auto buf = MemoryBuffer::getMemBuffer(StringRef((const char *)bitcode, size)); auto mod = parseBitcodeFile(buf.get()->getMemBufferRef(), context); // if(check if error happens) { // std::cerr << "Unable to parse bitcode file" << std::endl; // return 1; // } pm.run(*mod.get()); strbuf.flush(); // Checks if all the external functions exists in LLJVM runtime if (env != NULL && self != NULL) { const DenseSet<const Value*>& externRefs = jvmWriter->getExternRefs(); for (DenseSet<const Value*>::const_iterator i = externRefs.begin(), e = externRefs.end(); i != e; i++) { if (const Function *f = dyn_cast<Function>(*i)) { const std::string methodSignature = jvmWriter->getFunctionSignature(f); if (!checkIfFunctionExistInRuntime(env, *self, methodSignature)) { throwException(env, *self, "Can't find a function in LLJVM runtime: " + methodSignature); } } else { // Otherwise, this is an external reference to a field value const std::string& fieldName = (*i)->getName().str(); if (!checkIfFieldExistInRuntime(env, *self, fieldName)) { throwException(env, *self, "Can't find a field value in LLJVM runtime: " + fieldName); } } } } return out; } const std::string toJVMAssemblyCode( const char *bitcode, size_t size, int optLevel, int sizeLevel, unsigned debugLevel) { return toJVMAssemblyCode(NULL, NULL, bitcode, size, optLevel, sizeLevel, debugLevel); } const std::string toLLVMAssemblyCode( const char *bitcode, size_t size, int optLevel, int sizeLevel, unsigned debugLevel) { // Prepare an output pass for printing LLVM IR into the assembly code std::string out; raw_string_ostream strbuf(out); LLVMContext context; legacy::PassManager pm; // Registers optimization passes in the given pass manager initializePasses(context, pm, bitcode, size, optLevel, sizeLevel, debugLevel); // Finally, add a pass for output Pass *outputPass = createPrintModulePass(strbuf, "", false); pm.add(outputPass); auto buf = MemoryBuffer::getMemBuffer(StringRef((const char *)bitcode, size)); auto mod = parseBitcodeFile(buf.get()->getMemBufferRef(), context); // if(check if error happens) { // std::cerr << "Unable to parse bitcode file" << std::endl; // return 1; // } pm.run(*mod.get()); strbuf.flush(); return out; } // Visible for CPython const char *versionNumber() { return LLJVM_VERSION_NUMBER.c_str(); } void printAsLLVMAssemblyCode( const char *bitcode, size_t size, int optLevel, int sizeLevel, unsigned debugLevel) { const std::string llvmAsm = toLLVMAssemblyCode(bitcode, size, optLevel, sizeLevel, debugLevel); fprintf(stdout, "%s", llvmAsm.c_str()); } void printAsJVMAssemblyCode( const char *bitcode, size_t size, int optLevel, int sizeLevel, unsigned debugLevel) { const std::string jvmAsm = toJVMAssemblyCode(bitcode, size, optLevel, sizeLevel, debugLevel); fprintf(stdout, "%s", jvmAsm.c_str()); } JNIEXPORT jstring JNICALL Java_io_github_maropu_lljvm_LLJVMNative_versionNumber (JNIEnv *env, jobject self) { return env->NewStringUTF(LLJVM_VERSION_NUMBER.c_str()); } JNIEXPORT jstring JNICALL Java_io_github_maropu_lljvm_LLJVMNative_magicNumber (JNIEnv *env, jobject self) { return env->NewStringUTF(LLJVM_MAGIC_NUMBER.c_str()); } JNIEXPORT jlong JNICALL Java_io_github_maropu_lljvm_LLJVMNative_addressOf (JNIEnv *env, jobject self, jbyteArray ar) { void *ptr = env->GetPrimitiveArrayCritical(ar, 0); env->ReleasePrimitiveArrayCritical(ar, ptr, 0); return (jlong) ptr; } JNIEXPORT void JNICALL Java_io_github_maropu_lljvm_LLJVMNative_veryfyBitcode (JNIEnv *env, jobject self, jbyteArray bitcode) { jbyte *src = env->GetByteArrayElements(bitcode, NULL); size_t size = (size_t) env->GetArrayLength(bitcode); LLVMContext context; auto buf = MemoryBuffer::getMemBuffer(StringRef((char *)src, size)); auto mod = parseBitcodeFile(buf.get()->getMemBufferRef(), context); env->ReleaseByteArrayElements(bitcode, src, 0); // if(check if error happens) { // std::cerr << "Unable to parse bitcode file" << std::endl; // return 1; // } std::string out; raw_string_ostream strbuf(out); if (verifyModule(*mod.get(), &strbuf)) { throwException(env, self, out); } } JNIEXPORT jstring JNICALL Java_io_github_maropu_lljvm_LLJVMNative_asJVMAssemblyCode (JNIEnv *env, jobject self, jbyteArray bitcode, jint optLevel, jint sizeLevel, jint debugLevel) { jbyte *src = env->GetByteArrayElements(bitcode, NULL); size_t size = (size_t) env->GetArrayLength(bitcode); try { const std::string out = toJVMAssemblyCode(env, &self, (const char *)src, size, optLevel, sizeLevel, debugLevel); env->ReleaseByteArrayElements(bitcode, src, 0); return env->NewStringUTF(out.c_str()); } catch (const std::string& e) { env->ReleaseByteArrayElements(bitcode, src, 0); throwException(env, self, e); return env->NewStringUTF(""); } } JNIEXPORT jstring JNICALL Java_io_github_maropu_lljvm_LLJVMNative_asLLVMAssemblyCode (JNIEnv *env, jobject self, jbyteArray bitcode, jint optLevel, jint sizeLevel) { jbyte *src = env->GetByteArrayElements(bitcode, NULL); size_t size = (size_t) env->GetArrayLength(bitcode); try { const std::string out = toLLVMAssemblyCode((const char *)src, size, optLevel, sizeLevel, 0); env->ReleaseByteArrayElements(bitcode, src, 0); return env->NewStringUTF(out.c_str()); } catch (const std::string& e) { env->ReleaseByteArrayElements(bitcode, src, 0); throwException(env, self, e); return env->NewStringUTF(""); } } JNIEXPORT jboolean JNICALL Java_io_github_maropu_lljvm_LLJVMNative_verifyMemoryAddress (JNIEnv *env, jobject self, jlong base, jlong size) { // TODO: Needs more strict checks for memory accesses // try { // for (int i = 0; i < size; i++) { // *((unsigned char *) base + i); // } // } catch (std::exception& e) { // return false; // } // return true; return base > 0 && size > 0; }
34.583832
116
0.710415
maropu
e45d3f6dc0f14d49a21d3f179d461e3e18c462f3
864
cpp
C++
node/kagome_validating/main.cpp
FlorianFranzen/kagome
27ee11c78767e72f0ecd2c515c77bebc2ff5758d
[ "Apache-2.0" ]
null
null
null
node/kagome_validating/main.cpp
FlorianFranzen/kagome
27ee11c78767e72f0ecd2c515c77bebc2ff5758d
[ "Apache-2.0" ]
null
null
null
node/kagome_validating/main.cpp
FlorianFranzen/kagome
27ee11c78767e72f0ecd2c515c77bebc2ff5758d
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #include <iostream> #include <boost/program_options.hpp> #include "application/impl/app_config_impl.hpp" #include "application/impl/validating_node_application.hpp" #include "common/logger.hpp" #include "outcome/outcome.hpp" using kagome::application::AppConfiguration; using kagome::application::AppConfigurationImpl; int main(int argc, char **argv) { auto logger = kagome::common::createLogger("Kagome block producing node: "); auto configuration = std::make_shared<AppConfigurationImpl>(logger); configuration->initialize_from_args( AppConfiguration::LoadScheme::kValidating, argc, argv); auto &&app = std::make_shared<kagome::application::ValidatingNodeApplication>( std::move(configuration)); app->run(); return EXIT_SUCCESS; }
29.793103
80
0.756944
FlorianFranzen
e45ffe162c5eee956c99ba553ccf8c1fa2641efb
2,944
cxx
C++
test/test088.cxx
giupo/libpqxx
127f5682d3d2847d1b9a09b5670b89a07360d09f
[ "BSD-3-Clause" ]
1
2019-10-18T20:52:32.000Z
2019-10-18T20:52:32.000Z
test/test088.cxx
fineshift/pqxx
8e3cb37d6ddcb781fea5b03576f33b118f78c055
[ "BSD-3-Clause" ]
null
null
null
test/test088.cxx
fineshift/pqxx
8e3cb37d6ddcb781fea5b03576f33b118f78c055
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include "test_helpers.hxx" using namespace PGSTD; using namespace pqxx; // Test program for libpqxx. Attempt to perform nested transactions. namespace { void test_088(transaction_base &T0) { test::create_pqxxevents(T0); connection_base &C(T0.conn()); if (!C.supports(connection_base::cap_nested_transactions)) { cout << "Backend version does not support nested transactions. " "Skipping test." << endl; return; } // Trivial test: create subtransactions, and commit/abort cout << T0.exec("SELECT 'T0 starts'")[0][0].c_str() << endl; subtransaction T0a(static_cast<dbtransaction &>(T0), "T0a"); T0a.commit(); subtransaction T0b(static_cast<dbtransaction &>(T0), "T0b"); T0b.abort(); cout << T0.exec("SELECT 'T0 ends'")[0][0].c_str() << endl; T0.commit(); // Basic functionality: perform query in subtransaction; abort, continue work T1(C, "T1"); cout << T1.exec("SELECT 'T1 starts'")[0][0].c_str() << endl; subtransaction T1a(T1, "T1a"); cout << T1a.exec("SELECT ' a'")[0][0].c_str() << endl; T1a.commit(); subtransaction T1b(T1, "T1b"); cout << T1b.exec("SELECT ' b'")[0][0].c_str() << endl; T1b.abort(); subtransaction T1c(T1, "T1c"); cout << T1c.exec("SELECT ' c'")[0][0].c_str() << endl; T1c.commit(); cout << T1.exec("SELECT 'T1 ends'")[0][0].c_str() << endl; T1.commit(); // Commit/rollback functionality work T2(C, "T2"); const string Table = "test088"; T2.exec("CREATE TEMP TABLE " + Table + "(no INTEGER, text VARCHAR)"); T2.exec("INSERT INTO " + Table + " VALUES(1,'T2')"); subtransaction T2a(T2, "T2a"); T2a.exec("INSERT INTO "+Table+" VALUES(2,'T2a')"); T2a.commit(); subtransaction T2b(T2, "T2b"); T2b.exec("INSERT INTO "+Table+" VALUES(3,'T2b')"); T2b.abort(); subtransaction T2c(T2, "T2c"); T2c.exec("INSERT INTO "+Table+" VALUES(4,'T2c')"); T2c.commit(); const result R = T2.exec("SELECT * FROM " + Table + " ORDER BY no"); for (result::const_iterator i=R.begin(); i!=R.end(); ++i) cout << '\t' << i[0].c_str() << '\t' << i[1].c_str() << endl; PQXX_CHECK_EQUAL(R.size(), 3u, "Wrong number of results."); int expected[3] = { 1, 2, 4 }; for (result::size_type n=0; n<R.size(); ++n) PQXX_CHECK_EQUAL( R[n][0].as<int>(), expected[n], "Hit unexpected row number."); T2.abort(); // Auto-abort should only roll back the subtransaction. work T3(C, "T3"); subtransaction T3a(T3, "T3a"); PQXX_CHECK_THROWS( T3a.exec("SELECT * FROM nonexistent_table WHERE nonattribute=0"), sql_error, "Bogus query did not fail."); // Subtransaction can only be aborted now, because there was an error. T3a.abort(); // We're back in our top-level transaction. This did not abort. T3.exec("SELECT count(*) FROM pqxxevents"); // Make sure we can commit exactly one more level of transaction. T3.commit(); } } // namespace PQXX_REGISTER_TEST(test_088)
30.040816
74
0.634511
giupo
e462694df25e40a568f7d34cdad31882c4ca2320
255
hpp
C++
src/modules/osgUtil/generated_code/ReflectionMapGenerator.pypp.hpp
JaneliaSciComp/osgpyplusplus
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
[ "BSD-3-Clause" ]
17
2015-06-01T12:19:46.000Z
2022-02-12T02:37:48.000Z
src/modules/osgUtil/generated_code/ReflectionMapGenerator.pypp.hpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
7
2015-07-04T14:36:49.000Z
2015-07-23T18:09:49.000Z
src/modules/osgUtil/generated_code/ReflectionMapGenerator.pypp.hpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
7
2015-11-28T17:00:31.000Z
2020-01-08T07:00:59.000Z
// This file has been generated by Py++. #ifndef ReflectionMapGenerator_hpp__pyplusplus_wrapper #define ReflectionMapGenerator_hpp__pyplusplus_wrapper void register_ReflectionMapGenerator_class(); #endif//ReflectionMapGenerator_hpp__pyplusplus_wrapper
28.333333
54
0.878431
JaneliaSciComp
e4675dd670be7129964b04be13c42db10de6eb81
14,272
hpp
C++
src/Graphics/Vulkan/Image/Image.hpp
chrismile/sgl
03748cadbd1661285081c47775213091b665cb86
[ "MIT", "Unlicense", "Apache-2.0", "BSD-3-Clause" ]
8
2018-10-20T19:13:10.000Z
2021-08-17T01:45:10.000Z
src/Graphics/Vulkan/Image/Image.hpp
chrismile/sgl
03748cadbd1661285081c47775213091b665cb86
[ "MIT", "Unlicense", "Apache-2.0", "BSD-3-Clause" ]
3
2018-10-20T20:56:13.000Z
2022-03-28T20:32:46.000Z
src/Graphics/Vulkan/Image/Image.hpp
chrismile/sgl
03748cadbd1661285081c47775213091b665cb86
[ "MIT", "Unlicense", "Apache-2.0", "BSD-3-Clause" ]
3
2020-12-01T13:02:58.000Z
2021-08-24T06:39:46.000Z
/* * BSD 2-Clause License * * Copyright (c) 2021, Christoph Neuhauser * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SGL_IMAGE_HPP #define SGL_IMAGE_HPP #include <memory> #include <algorithm> #include <cmath> #include <glm/vec4.hpp> #include <Defs.hpp> #include "../libs/volk/volk.h" #include "../libs/VMA/vk_mem_alloc.h" #ifdef SUPPORT_OPENGL #include <GL/glew.h> #endif namespace sgl { namespace vk { class Device; class Buffer; typedef std::shared_ptr<Buffer> BufferPtr; class Image; typedef std::shared_ptr<Image> ImagePtr; class ImageView; typedef std::shared_ptr<ImageView> ImageViewPtr; class ImageSampler; typedef std::shared_ptr<ImageSampler> ImageSamplerPtr; class Texture; typedef std::shared_ptr<Texture> TexturePtr; struct DLL_OBJECT ImageSettings { ImageSettings() {} uint32_t width = 1; uint32_t height = 1; uint32_t depth = 1; VkImageType imageType = VK_IMAGE_TYPE_2D; uint32_t mipLevels = 1; uint32_t arrayLayers = 1; VkSampleCountFlagBits numSamples = VK_SAMPLE_COUNT_1_BIT; VkFormat format = VK_FORMAT_R8G8B8A8_UNORM; // VK_FORMAT_R8G8B8A8_SRGB VkImageTiling tiling = VK_IMAGE_TILING_OPTIMAL; // VK_IMAGE_TILING_OPTIMAL; VK_IMAGE_TILING_LINEAR -> row-major VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; VmaMemoryUsage memoryUsage = VMA_MEMORY_USAGE_GPU_ONLY; VkSharingMode sharingMode = VK_SHARING_MODE_EXCLUSIVE; bool exportMemory = false; // Whether to export the memory for external use, e.g., in OpenGL. }; inline bool hasStencilComponent(VkFormat format) { return format == VK_FORMAT_D32_SFLOAT_S8_UINT || format == VK_FORMAT_D24_UNORM_S8_UINT; } class DLL_OBJECT Image { friend class Renderer; public: Image(Device* device, const ImageSettings& imageSettings); Image(Device* device, const ImageSettings& imageSettings, VkImage image, bool takeImageOwnership = true); Image( Device* device, const ImageSettings& imageSettings, VkImage image, VmaAllocation imageAllocation, VmaAllocationInfo imageAllocationInfo); ~Image(); /** * Creates a copy of the buffer. * @param copyContent Whether to copy the content, too, or only create a buffer with the same settings. * @param aspectFlags The image aspect flags. * @return The new buffer. */ ImagePtr copy(bool copyContent, VkImageAspectFlags aspectFlags); // Computes the recommended number of mip levels for a 2D texture of the specified size. static uint32_t computeMipLevels(uint32_t width, uint32_t height) { return static_cast<uint32_t>(std::floor(std::log2(std::max(width, height)))) + 1; } inline VkImage getVkImage() { return image; } inline const ImageSettings& getImageSettings() { return imageSettings; } /** * Uploads the data to the GPU memory of the texture using a stating buffer. * @param sizeInBytes The size of the data to upload in bytes. * @param data A pointer to the data on the CPU. * @param generateMipmaps Whether to generate mipmaps (if imageSettings.mipLevels > 1). * NOTE: If generateMipmaps is true, VK_IMAGE_USAGE_TRANSFER_SRC_BIT must be specified in ImageSettings::usage. * Please also note that using this command only really makes sense if the texture was created with the mode * VMA_MEMORY_USAGE_GPU_ONLY. */ void uploadData(VkDeviceSize sizeInBytes, void* data, bool generateMipmaps = true); /** * Copies the content of a buffer to this image. * @param buffer The copy source. * @param commandBuffer The command buffer. If VK_NULL_HANDLE is specified, a transient command buffer is used and * the function will wait with vkQueueWaitIdle for the command to finish on the GPU. */ void copyFromBuffer(BufferPtr& buffer, VkCommandBuffer commandBuffer = VK_NULL_HANDLE); /** * Copies the content of the image to the specified buffer. * @param buffer The copy destination. * @param commandBuffer The command buffer. If VK_NULL_HANDLE is specified, a transient command buffer is used and * the function will wait with vkQueueWaitIdle for the command to finish on the GPU. */ void copyToBuffer(BufferPtr& buffer, VkCommandBuffer commandBuffer = VK_NULL_HANDLE); /** * Copies the content of the image to the specified image. * @param destImage The destination image. * @param aspectFlags The image aspect flags. * @param commandBuffer The command buffer. If VK_NULL_HANDLE is specified, a transient command buffer is used and * the function will wait with vkQueueWaitIdle for the command to finish on the GPU. * NOTE: This operation */ void copyToImage( ImagePtr& destImage, VkImageAspectFlags aspectFlags, VkCommandBuffer commandBuffer = VK_NULL_HANDLE); /** * Blits the content of this image to a destination image and performs format conversion if necessary. * @param destImage The destination image. * @param commandBuffer The command buffer. If VK_NULL_HANDLE is specified, a transient command buffer is used and * the function will wait with vkQueueWaitIdle for the command to finish on the GPU. */ void blit(ImagePtr& destImage, VkCommandBuffer commandBuffer = VK_NULL_HANDLE); void clearColor( const glm::vec4& clearColor = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f), VkCommandBuffer commandBuffer = VK_NULL_HANDLE); void clearDepthStencil( VkImageAspectFlags aspectFlags, float clearDepth = 1.0f, uint32_t clearStencil = 0, VkCommandBuffer commandBuffer = VK_NULL_HANDLE); /// Transitions the image layout from the current layout to the new layout. void transitionImageLayout(VkImageLayout newLayout); void transitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout); void transitionImageLayout(VkImageLayout newLayout, VkCommandBuffer commandBuffer); void transitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, VkCommandBuffer commandBuffer); void insertMemoryBarrier( VkCommandBuffer commandBuffer, VkImageLayout oldLayout, VkImageLayout newLayout, VkPipelineStageFlags srcStage, VkPipelineStageFlags dstStage, VkAccessFlags srcAccessMask, VkAccessFlags dstAccessMask); /// The subresource layout contains information necessary when accessing the image data on the CPU (e.g., stride). VkSubresourceLayout getSubresourceLayout( VkImageAspectFlags aspectFlags, uint32_t mipLevel = 0, uint32_t arrayLayer = 0) const; /// Transitions the image layout from the old layout to the new layout. inline VkImageLayout getVkImageLayout() const { return imageLayout; } /// For access from the framebuffer after a subpass has finished. inline void _updateLayout(VkImageLayout newLayout) { imageLayout = newLayout; } inline Device* getDevice() { return device; } void* mapMemory(); void unmapMemory(); #ifdef SUPPORT_OPENGL /** * Creates an OpenGL memory object from the external Vulkan memory. * NOTE: The image must have been created with exportMemory set to true. * @param memoryObjectGl The OpenGL memory object. * @return Whether the OpenGL memory object could be created successfully. */ bool createGlMemoryObject(GLuint& memoryObjectGl); #endif private: void _generateMipmaps(); Device* device = nullptr; bool hasImageOwnership = true; ImageSettings imageSettings; VkImage image = nullptr; VkImageLayout imageLayout = VK_IMAGE_LAYOUT_UNDEFINED; // Memory not exported, used only in Vulkan. VmaAllocation imageAllocation = nullptr; VmaAllocationInfo imageAllocationInfo = {}; // Exported memory for external use. VkDeviceMemory deviceMemory = VK_NULL_HANDLE; VkDeviceSize deviceMemorySizeInBytes = 0; }; class DLL_OBJECT ImageView { public: ImageView( const ImagePtr& image, VkImageViewType imageViewType, VkImageAspectFlags aspectFlags = VK_IMAGE_ASPECT_COLOR_BIT); explicit ImageView( const ImagePtr& image, VkImageAspectFlags aspectFlags = VK_IMAGE_ASPECT_COLOR_BIT); ImageView( const ImagePtr& image, VkImageView imageView, VkImageViewType imageViewType, VkImageAspectFlags aspectFlags = VK_IMAGE_ASPECT_COLOR_BIT); ~ImageView(); /** * Creates a copy of the image view. * @param copyImage Whether to create a deep copy (with the underlying image also being copied) or to create a * shallow copy that shares the image object with the original image view. * @param copyContent If copyImage is true: Whether to also copy the content of the underlying image. * @return The new image view. */ ImageViewPtr copy(bool copyImage, bool copyContent); void clearColor( const glm::vec4& clearColor = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f), VkCommandBuffer commandBuffer = VK_NULL_HANDLE); void clearDepthStencil( float clearDepth = 1.0f, uint32_t clearStencil = 0, VkCommandBuffer commandBuffer = VK_NULL_HANDLE); inline Device* getDevice() { return device; } inline ImagePtr& getImage() { return image; } inline VkImageView getVkImageView() { return imageView; } inline VkImageViewType getVkImageViewType() const { return imageViewType; } inline VkImageAspectFlags getVkImageAspectFlags() const { return aspectFlags; } private: Device* device = nullptr; ImagePtr image; VkImageView imageView = nullptr; VkImageViewType imageViewType; VkImageAspectFlags aspectFlags; }; struct DLL_OBJECT ImageSamplerSettings { ImageSamplerSettings() = default; /// Sets filter modes to NEAREST if an integer format is used. ImageSamplerSettings(const ImageSettings& imageSettings); VkFilter magFilter = VK_FILTER_LINEAR; VkFilter minFilter = VK_FILTER_LINEAR; VkSamplerMipmapMode mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; /* * VK_SAMPLER_ADDRESS_MODE_REPEAT, VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT, * VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE, * VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER */ VkSamplerAddressMode addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; VkSamplerAddressMode addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; VkSamplerAddressMode addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; float mipLodBias = 0.0f; VkBool32 anisotropyEnable = VK_FALSE; float maxAnisotropy = -1.0f; // Negative value means max. anisotropy. VkBool32 compareEnable = VK_FALSE; // VK_TRUE, e.g., for percentage-closer filtering VkCompareOp compareOp = VK_COMPARE_OP_ALWAYS; float minLod = 0.0f; float maxLod = VK_LOD_CLAMP_NONE; VkBorderColor borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK; // [0, 1) range vs. [0, size) range. VkBool32 unnormalizedCoordinates = VK_FALSE; }; /** * A texture sampler wrapper that lets images be used for sampling in a shader. */ class DLL_OBJECT ImageSampler { public: ImageSampler(Device* device, const ImageSamplerSettings& samplerSettings, float maxLodOverwrite = -1.0f); ImageSampler(Device* device, const ImageSamplerSettings& samplerSettings, ImagePtr image); ~ImageSampler(); inline const ImageSamplerSettings& getImageSamplerSettings() const { return imageSamplerSettings; } inline VkSampler getVkSampler() { return sampler; } private: Device* device = nullptr; ImageSamplerSettings imageSamplerSettings; VkSampler sampler = nullptr; }; class DLL_OBJECT Texture { public: Texture(const ImageViewPtr& imageView, const ImageSamplerPtr& imageSampler); Texture( Device* device, const ImageSettings& imageSettings, VkImageAspectFlags aspectFlags = VK_IMAGE_ASPECT_COLOR_BIT); Texture( Device* device, const ImageSettings& imageSettings, VkImageViewType imageViewType, VkImageAspectFlags aspectFlags = VK_IMAGE_ASPECT_COLOR_BIT); Texture(const ImageViewPtr& imageView); Texture( Device* device, const ImageSettings& imageSettings, const ImageSamplerSettings& samplerSettings, VkImageAspectFlags aspectFlags = VK_IMAGE_ASPECT_COLOR_BIT); Texture( Device* device, const ImageSettings& imageSettings, VkImageViewType imageViewType, const ImageSamplerSettings& samplerSettings, VkImageAspectFlags aspectFlags = VK_IMAGE_ASPECT_COLOR_BIT); Texture(const ImageViewPtr& imageView, const ImageSamplerSettings& samplerSettings); inline ImagePtr& getImage() { return imageView->getImage(); } inline ImageViewPtr& getImageView() { return imageView; } inline ImageSamplerPtr& getImageSampler() { return imageSampler; } private: ImageViewPtr imageView; ImageSamplerPtr imageSampler; }; }} #endif //SGL_IMAGE_HPP
42.730539
118
0.741172
chrismile
e46a4cd5763ed0c8e946ea444eb45497226a1430
528
cpp
C++
src/Controller/AI/detail/Message.cpp
MajorArkwolf/Project-Blue-Engine
e5fc6416d0a41a1251f1b369047e0ea1097775da
[ "MIT" ]
1
2021-04-18T09:49:38.000Z
2021-04-18T09:49:38.000Z
src/Controller/AI/detail/Message.cpp
MajorArkwolf/ICT397-Project-Blue
e5fc6416d0a41a1251f1b369047e0ea1097775da
[ "MIT" ]
null
null
null
src/Controller/AI/detail/Message.cpp
MajorArkwolf/ICT397-Project-Blue
e5fc6416d0a41a1251f1b369047e0ea1097775da
[ "MIT" ]
2
2020-06-13T15:24:01.000Z
2021-04-15T20:25:49.000Z
/// Declaration Include #include "Controller/AI/Message.hpp" Message::Message() { // Initialise the Message properties sender = 0u; type = Message_Type::Invalid; attachment = 0.0f; delay = 0u; } void Message::recipient_add(BlueEngine::ID identifier) { // Call the set's operation recipients.insert(identifier); } std::vector<BlueEngine::ID> Message::recipient_list() { // Copy and return the entire range of set elements into a new vector return std::vector<BlueEngine::ID>(recipients.begin(), recipients.end()); }
25.142857
74
0.729167
MajorArkwolf
e46b5398fb09a0d9e0701ddf53027c4015405ea4
3,760
cc
C++
pmem-mariadb/storage/tokudb/PerconaFT/src/tests/test_update_broadcast_with_empty_table.cc
wc222/pmdk-examples
64aadc3a70471c469ac8e214eb1e04ff47cf18ff
[ "BSD-3-Clause" ]
11
2017-10-28T08:41:08.000Z
2021-06-24T07:24:21.000Z
pmem-mariadb/storage/tokudb/PerconaFT/src/tests/test_update_broadcast_with_empty_table.cc
WSCWDA/pmdk-examples
c3d079e52cd18b0e14836ef42bad9a995336bf90
[ "BSD-3-Clause" ]
1
2021-02-24T05:26:44.000Z
2021-02-24T05:26:44.000Z
pmem-mariadb/storage/tokudb/PerconaFT/src/tests/test_update_broadcast_with_empty_table.cc
isabella232/pmdk-examples
be7a5a18ba7bb8931e512f6d552eadf820fa2235
[ "BSD-3-Clause" ]
4
2017-09-07T09:33:26.000Z
2021-02-19T07:45:08.000Z
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "$Id$" /*====== This file is part of PerconaFT. Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved. PerconaFT is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. PerconaFT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PerconaFT. If not, see <http://www.gnu.org/licenses/>. ---------------------------------------- PerconaFT is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. PerconaFT 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with PerconaFT. If not, see <http://www.gnu.org/licenses/>. ======= */ #ident "Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved." // test that update broadcast does nothing if the table is empty #include "test.h" const int envflags = DB_INIT_MPOOL|DB_CREATE|DB_THREAD |DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_TXN|DB_PRIVATE; DB_ENV *env; static int update_fun(DB *UU(db), const DBT *UU(key), const DBT *UU(old_val), const DBT *UU(extra), void UU((*set_val)(const DBT *new_val, void *set_extra)), void *UU(set_extra)) { assert(0); return 0; } static void setup (void) { toku_os_recursive_delete(TOKU_TEST_FILENAME); { int chk_r = toku_os_mkdir(TOKU_TEST_FILENAME, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(chk_r); } { int chk_r = db_env_create(&env, 0); CKERR(chk_r); } env->set_errfile(env, stderr); env->set_update(env, update_fun); { int chk_r = env->open(env, TOKU_TEST_FILENAME, envflags, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(chk_r); } } static void cleanup (void) { { int chk_r = env->close(env, 0); CKERR(chk_r); } } static int do_updates(DB_TXN *txn, DB *db, uint32_t flags) { DBT extra; DBT *extrap = dbt_init(&extra, NULL, 0); int r = db->update_broadcast(db, txn, extrap, flags); CKERR(r); return r; } static void run_test(bool is_resetting, bool prelock) { DB *db; uint32_t update_flags = is_resetting ? DB_IS_RESETTING_OP : 0; IN_TXN_COMMIT(env, NULL, txn_1, 0, { { int chk_r = db_create(&db, env, 0); CKERR(chk_r); } { int chk_r = db->open(db, txn_1, "foo.db", NULL, DB_BTREE, DB_CREATE, 0666); CKERR(chk_r); } }); if (prelock) { IN_TXN_COMMIT(env, NULL, txn_2, 0, { { int chk_r = db->pre_acquire_table_lock(db, txn_2); CKERR(chk_r); } }); } IN_TXN_COMMIT(env, NULL, txn_2, 0, { { int chk_r = do_updates(txn_2, db, update_flags); CKERR(chk_r); } }); { int chk_r = db->close(db, 0); CKERR(chk_r); } } int test_main(int argc, char * const argv[]) { parse_args(argc, argv); setup(); run_test(true,true); run_test(false,true); run_test(true,false); run_test(false,false); cleanup(); return 0; }
34.814815
105
0.645745
wc222
e46b89d391f97faca24e780858b9bf4074338255
7,536
hpp
C++
rmf_building_sim_common/include/rmf_building_sim_common/door_common.hpp
xiyuoh/rmf_simulation
e0ee7e66a7fa782897e68426411ccedfd5546422
[ "Apache-2.0" ]
3
2021-02-25T21:51:52.000Z
2022-03-24T01:47:49.000Z
rmf_building_sim_common/include/rmf_building_sim_common/door_common.hpp
xiyuoh/rmf_simulation
e0ee7e66a7fa782897e68426411ccedfd5546422
[ "Apache-2.0" ]
57
2021-04-05T01:36:03.000Z
2022-03-31T03:43:59.000Z
rmf_building_sim_common/include/rmf_building_sim_common/door_common.hpp
xiyuoh/rmf_simulation
e0ee7e66a7fa782897e68426411ccedfd5546422
[ "Apache-2.0" ]
5
2021-05-21T06:58:06.000Z
2021-09-28T19:59:04.000Z
/* * Copyright (C) 2020 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. * */ #ifndef RMF_BUILDING_SIM_COMMON__DOOR_COMMON_HPP #define RMF_BUILDING_SIM_COMMON__DOOR_COMMON_HPP #include <rclcpp/rclcpp.hpp> #include <rclcpp/logger.hpp> #include <rmf_door_msgs/msg/door_mode.hpp> #include <rmf_door_msgs/msg/door_state.hpp> #include <rmf_door_msgs/msg/door_request.hpp> #include "utils.hpp" #include <vector> #include <unordered_map> #include <unordered_set> namespace rmf_building_sim_common { using DoorMode = rmf_door_msgs::msg::DoorMode; using DoorState = rmf_door_msgs::msg::DoorState; using DoorRequest = rmf_door_msgs::msg::DoorRequest; //============================================================================== class DoorCommon { public: struct DoorUpdateRequest { std::string joint_name; double position; double velocity; }; struct DoorUpdateResult { std::string joint_name; double velocity; double fmax; }; template<typename SdfPtrT> static std::shared_ptr<DoorCommon> make( const std::string& door_name, rclcpp::Node::SharedPtr node, SdfPtrT& sdf); rclcpp::Logger logger() const; std::vector<std::string> joint_names() const; MotionParams& params(); std::vector<DoorUpdateResult> update(const double time, const std::vector<DoorUpdateRequest>& request); private: struct DoorElement { double closed_position; double open_position; double current_position; double current_velocity; DoorElement() {} DoorElement( const double lower_limit, const double upper_limit, const bool flip_direction = false) : current_position(0.0), current_velocity(0.0) { if (flip_direction) { closed_position = lower_limit; open_position = upper_limit; } else { closed_position = upper_limit; open_position = lower_limit; } } }; // Map joint name to its DoorElement using Doors = std::unordered_map<std::string, DoorElement>; DoorMode requested_mode() const; void publish_state(const uint32_t door_value, const rclcpp::Time& time); double calculate_target_velocity( const double target, const double current_position, const double current_velocity, const double dt); DoorCommon(const std::string& door_name, rclcpp::Node::SharedPtr node, const MotionParams& params, const Doors& doors); bool all_doors_open(); bool all_doors_closed(); rclcpp::Node::SharedPtr _ros_node; rclcpp::Publisher<DoorState>::SharedPtr _door_state_pub; rclcpp::Subscription<DoorRequest>::SharedPtr _door_request_sub; DoorState _state; DoorRequest _request; MotionParams _params; double _last_update_time = 0.0; // random start time offset to prevent state message crossfire double _last_pub_time = ((double) std::rand()) / ((double) (RAND_MAX)); bool _initialized = false; // Map of joint_name and corresponding DoorElement Doors _doors; }; template<typename SdfPtrT> std::shared_ptr<DoorCommon> DoorCommon::make( const std::string& door_name, rclcpp::Node::SharedPtr node, SdfPtrT& sdf) { // We work with a clone to avoid const correctness issues with // get_sdf_param functions in utils.hpp auto sdf_clone = sdf->Clone(); MotionParams params; get_sdf_param_if_available<double>(sdf_clone, "v_max_door", params.v_max); get_sdf_param_if_available<double>(sdf_clone, "a_max_door", params.a_max); get_sdf_param_if_available<double>(sdf_clone, "a_nom_door", params.a_nom); get_sdf_param_if_available<double>(sdf_clone, "dx_min_door", params.dx_min); get_sdf_param_if_available<double>(sdf_clone, "f_max_door", params.f_max); auto door_element = sdf_clone; std::string left_door_joint_name; std::string right_door_joint_name; std::string door_type; // Get the joint names and door type if (!get_element_required(sdf_clone, "door", door_element) || !get_sdf_attribute_required<std::string>( door_element, "left_joint_name", left_door_joint_name) || !get_sdf_attribute_required<std::string>( door_element, "right_joint_name", right_door_joint_name) || !get_sdf_attribute_required<std::string>( door_element, "type", door_type)) { RCLCPP_ERROR(node->get_logger(), " -- Missing required parameters for [%s] plugin", door_name.c_str()); return nullptr; } if ((left_door_joint_name == "empty_joint" && right_door_joint_name == "empty_joint") || (left_door_joint_name.empty() && right_door_joint_name.empty())) { RCLCPP_ERROR(node->get_logger(), " -- Both door joint names are missing for [%s] plugin, at least one" " is required", door_name.c_str()); return nullptr; } std::unordered_set<std::string> joint_names; if (!left_door_joint_name.empty() && left_door_joint_name != "empty_joint") joint_names.insert(left_door_joint_name); if (!right_door_joint_name.empty() && right_door_joint_name != "empty_joint") joint_names.insert(right_door_joint_name); Doors doors; auto extract_door = [&](SdfPtrT& joint_sdf) { auto joint_sdf_clone = joint_sdf->Clone(); std::string joint_name; get_sdf_attribute_required<std::string>( joint_sdf_clone, "name", joint_name); const auto it = joint_names.find(joint_name); if (it != joint_names.end()) { auto element = joint_sdf_clone; get_element_required(joint_sdf_clone, "axis", element); get_element_required(element, "limit", element); double lower_limit = -1.57; double upper_limit = 0.0; get_sdf_param_if_available<double>(element, "lower", lower_limit); get_sdf_param_if_available<double>(element, "upper", upper_limit); DoorCommon::DoorElement door_element; if (joint_name == right_door_joint_name) door_element = DoorCommon::DoorElement{lower_limit, upper_limit, true}; else if (joint_name == left_door_joint_name) door_element = DoorCommon::DoorElement{lower_limit, upper_limit}; doors.insert({joint_name, door_element}); } }; // Get the joint limits from parent sdf auto parent = sdf->GetParent(); if (!parent) { RCLCPP_ERROR(node->get_logger(), "Unable to access parent sdf to retrieve joint limits"); return nullptr; } auto joint_element = parent->GetElement("joint"); if (!joint_element) { RCLCPP_ERROR(node->get_logger(), "Parent sdf missing required joint element"); return nullptr; } extract_door(joint_element); // Find next joint element if present while (joint_element) { extract_door(joint_element); joint_element = joint_element->GetNextElement("joint"); } std::shared_ptr<DoorCommon> door_common(new DoorCommon( door_name, node, params, doors)); return door_common; } } // namespace rmf_building_sim_common #endif // RMF_BUILDING_SIM_COMMON__DOOR_COMMON_HPP
28.330827
80
0.701699
xiyuoh
e46d56de1178ee7684d736720c1e64b98ff6c718
1,547
cc
C++
Geometry/CaloEventSetup/plugins/CaloTopologyBuilder.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
1
2019-08-09T08:42:11.000Z
2019-08-09T08:42:11.000Z
Geometry/CaloEventSetup/plugins/CaloTopologyBuilder.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
null
null
null
Geometry/CaloEventSetup/plugins/CaloTopologyBuilder.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
1
2019-04-03T19:23:27.000Z
2019-04-03T19:23:27.000Z
#include "Geometry/CaloEventSetup/plugins/CaloTopologyBuilder.h" #include "Geometry/CaloTopology/interface/CaloSubdetectorTopology.h" #include "Geometry/CaloTopology/interface/EcalBarrelTopology.h" #include "Geometry/CaloTopology/interface/EcalEndcapTopology.h" #include "Geometry/CaloTopology/interface/EcalPreshowerTopology.h" #include "Geometry/CaloGeometry/interface/CaloGeometry.h" #include "DataFormats/EcalDetId/interface/EcalSubdetector.h" CaloTopologyBuilder::CaloTopologyBuilder( const edm::ParameterSet& /*iConfig*/ ) { //the following line is needed to tell the framework what // data is being produced // disable // setWhatProduced( this, &CaloTopologyBuilder::produceIdeal ); setWhatProduced( this, &CaloTopologyBuilder::produceCalo ); } CaloTopologyBuilder::~CaloTopologyBuilder() { } // // member functions // // ------------ method called to produce the data ------------ CaloTopologyBuilder::ReturnType CaloTopologyBuilder::produceCalo( const CaloTopologyRecord& iRecord ) { edm::ESHandle<CaloGeometry> theGeometry ; iRecord.getRecord<CaloGeometryRecord>().get( theGeometry ) ; ReturnType ct = std::make_unique<CaloTopology>(); //ECAL parts ct->setSubdetTopology( DetId::Ecal, EcalBarrel, new EcalBarrelTopology( theGeometry ) ) ; ct->setSubdetTopology( DetId::Ecal, EcalEndcap, new EcalEndcapTopology( theGeometry ) ) ; ct->setSubdetTopology( DetId::Ecal, EcalPreshower, new EcalPreshowerTopology(theGeometry)); return ct ; }
30.94
80
0.739496
bisnupriyasahu
e46e91755e9c3f595282f302fe23d69b48c16e96
697
hpp
C++
windows-build/include/ButtonList.hpp
CptSpookz/Roguelike
ae00014557b0025f0289bb5866d020a36c8bdb57
[ "MIT" ]
null
null
null
windows-build/include/ButtonList.hpp
CptSpookz/Roguelike
ae00014557b0025f0289bb5866d020a36c8bdb57
[ "MIT" ]
null
null
null
windows-build/include/ButtonList.hpp
CptSpookz/Roguelike
ae00014557b0025f0289bb5866d020a36c8bdb57
[ "MIT" ]
3
2017-08-07T05:27:20.000Z
2020-10-01T04:10:47.000Z
#ifndef BUTTONLIST_HPP #define BUTTONLIST_HPP // Roguelike #include <DataStructures.hpp> // SFML #include <SFML/Graphics.hpp> class ButtonList { public: ButtonList(); void setOutline(sf::Texture&); void addButton(sf::RenderWindow&, sf::Texture&); void setTextureIndex(int, sf::Texture&); void draw(sf::RenderWindow&); void toNext(); void toPrevious(); int getIndex(); protected: void centerHorizontal(sf::RenderWindow&); private: // lista de sprite dos botões LinkedList<sf::Sprite*> m_buttonSprites; // sprite do outline de seleção sf::Sprite m_outlineSprite; // indice do número atual int m_actualIndex; }; #endif
16.209302
52
0.672884
CptSpookz
e47183860ddd47113a13f88397488792572e3ff4
1,576
cpp
C++
src/common/time/test/DurationBenchmark.cpp
linkensphere201/nebula-common-personal
e31b7e88326195a08ac0460fd469326455df6417
[ "Apache-2.0" ]
28
2019-12-19T08:39:39.000Z
2022-01-30T01:56:01.000Z
src/common/time/test/DurationBenchmark.cpp
linkensphere201/nebula-common-personal
e31b7e88326195a08ac0460fd469326455df6417
[ "Apache-2.0" ]
156
2020-08-17T09:59:02.000Z
2021-09-27T02:22:57.000Z
src/common/time/test/DurationBenchmark.cpp
linkensphere201/nebula-common-personal
e31b7e88326195a08ac0460fd469326455df6417
[ "Apache-2.0" ]
48
2020-08-17T09:13:11.000Z
2021-12-06T08:10:09.000Z
/* Copyright (c) 2018 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "common/base/Base.h" #include <folly/Benchmark.h> #include "common/time/Duration.h" using nebula::time::Duration; using std::chrono::steady_clock; using std::chrono::duration_cast; using std::chrono::milliseconds; BENCHMARK(steady_clock_timer, iters) { for (uint32_t i = 0; i < iters; i++) { auto start = steady_clock::now(); auto end = steady_clock::now(); auto diffInMSec = (duration_cast<milliseconds>(end - start)).count(); folly::doNotOptimizeAway(diffInMSec); } } BENCHMARK_RELATIVE(duration_timer, iters) { for (uint32_t i = 0; i < iters; i++) { Duration d; auto diffInMSec = d.elapsedInMSec(); folly::doNotOptimizeAway(diffInMSec); } } int main(int argc, char** argv) { folly::init(&argc, &argv, true); folly::runBenchmarks(); return 0; } /* Tested on Intel(R) Xeon(R) CPU E5-2690 v2 @ 3.00GHz x 2 ============================================================================ DurationBenchmark.cpp relative time/iter iters/s ============================================================================ steady_clock_timer 44.45ns 22.50M duration_timer 170.50% 26.07ns 38.36M ============================================================================ */
29.185185
78
0.528553
linkensphere201
e4762e03d173e208a01d7ef61a139d9fae4a78bb
3,264
cpp
C++
examples/pframe/BitmapManager.cpp
bli19/stm32plus
fdf0b74bd8df95c4b0085e1e03b461ea5ca48d86
[ "BSD-3-Clause" ]
1
2015-10-31T09:01:16.000Z
2015-10-31T09:01:16.000Z
examples/pframe/BitmapManager.cpp
bli19/stm32plus
fdf0b74bd8df95c4b0085e1e03b461ea5ca48d86
[ "BSD-3-Clause" ]
null
null
null
examples/pframe/BitmapManager.cpp
bli19/stm32plus
fdf0b74bd8df95c4b0085e1e03b461ea5ca48d86
[ "BSD-3-Clause" ]
null
null
null
/* * This file is a part of the open source stm32plus library. * Copyright (c) 2011,2012,2013 Andy Brown <www.andybrown.me.uk> * Please see website for licensing terms. */ #include "stdafx.h" /* * Constructor */ BitmapManager::BitmapManager(LcdManager& lcdManager,FileSystemManager& fsManager) : Initialiser(lcdManager), _fsManager(fsManager) { } /* * Initialise the class */ bool BitmapManager::initialise() { // create the bitmap blocks on the sd card return createBitmapBlocks(); } /* * Create the contiguous blocks that hold the bitmaps for fast access */ bool BitmapManager::createBitmapBlocks() { countImages(); if(_fsManager.imagesAreCached()) return true; return readImages(); } /* * Count the images */ bool BitmapManager::countImages() { char buffer[30]; FileInformation *finfo; uint32_t length; FileSystem& fs=_fsManager.getFileSystem(); _lcdManager.getLcd().setForeground(ColourNames::WHITE); // status _term.writeString("Counting images"); // iterate over sequential *.262 images in /pframe/img // e.g. 0.262, 1.262, 2.262 etc. _imageCount=0; for(;;) { // check that the image exists strcpy(buffer,"/pframe/img/"); StringUtil::itoa(_imageCount,buffer+12,10); strcat(buffer,".262"); if(!fs.getFileInformation(buffer,finfo)) break; // verify that this is a bitmap by checking the size length=finfo->getLength(); delete finfo; if(length!=IMAGE_BYTE_SIZE) return error("Invalid image format"); _imageCount++; _term << '.'; } _term << '\n'; // check for no images if(_imageCount==0) return error("There are no images to play"); _term << "Found " << _imageCount << " images\n"; return true; } /* * Read the images */ bool BitmapManager::readImages() { char buffer[30]; uint8_t block[512]; uint32_t blockIndex,i,j,actuallyRead; FileSystem& fs=_fsManager.getFileSystem(); File *file; BlockDevice& sdcard=_fsManager.getSdCard(); // allocate enough blocks from the free space to hold the image data if(!_fsManager.allocateBlocks(_imageCount)) return false; // status _term << "Caching images.\n"; blockIndex=_fsManager.getFirstCacheBlock(); for(i=0;i<_imageCount;i++) { // read and cache the image strcpy(buffer,"/pframe/img/"); StringUtil::itoa(i,buffer+12,10); strcat(buffer,".262"); if(!fs.openFile(buffer,file)) return error("Failed to open file"); _term.clearLine(); _term << "Image: " << (i+1) << '/' << _imageCount; // 640 blocks/image (2 per row, 320 rows / image) // each block contains 1 scan line (240*4 bytes) for(j=0;j<640;j++) { if(!file->read(block,480,actuallyRead) || actuallyRead!=480) return error("IO error reading image"); if(!sdcard.writeBlock(block,blockIndex++)) return error("IO error writing to card"); } delete file; } _term << '\n'; return true; } /* * Open an image file */ bool BitmapManager::openImage(uint32_t imageIndex,File*& file) { char buffer[30]; strcpy(buffer,"/pframe/img/"); StringUtil::itoa(imageIndex,buffer+12,10); strcat(buffer,".262"); return _fsManager.getFileSystem().openFile(buffer,file); }
18.337079
81
0.65625
bli19
e47b547da11698f03ebc5cd751a47305d23f2958
2,039
cpp
C++
src/deferredreceiver.cpp
NotifAi/AMQP-CPP
197011074557230a9a312b9e591bdc7136dd5bce
[ "Apache-2.0" ]
null
null
null
src/deferredreceiver.cpp
NotifAi/AMQP-CPP
197011074557230a9a312b9e591bdc7136dd5bce
[ "Apache-2.0" ]
null
null
null
src/deferredreceiver.cpp
NotifAi/AMQP-CPP
197011074557230a9a312b9e591bdc7136dd5bce
[ "Apache-2.0" ]
null
null
null
/** * DeferredReceiver.cpp * * Implementation file for the DeferredReceiver class * * @copyright 2016 - 2018 Copernica B.V. */ /** * Dependencies */ #include "amqpcpp/deferredreceiver.h" #include "basicdeliverframe.h" #include "basicgetokframe.h" #include "basicheaderframe.h" #include "bodyframe.h" /** * Start namespace */ namespace AMQP { /** * Initialize the object: we are going to receive a message, next frames will be header and data * @param exchange * @param routingkey */ void DeferredReceiver::initialize(const std::string &exchange, const std::string &routingkey) { // anybody interested in the new message? if (_startCallback) { _startCallback(exchange, routingkey); } } /** * Process the message headers * * @param frame The frame to process */ void DeferredReceiver::process(BasicHeaderFrame &frame) { // make sure we stay in scope auto self = lock(); // store the body size _bodySize = frame.bodySize(); // is user interested in the size? if (_sizeCallback) { _sizeCallback(_bodySize); } // do we have a message? if (_message) { // store the body size and metadata _message->setBodySize(_bodySize); _message->set(frame.metaData()); } // anybody interested in the headers? if (_headerCallback) { _headerCallback(frame.metaData()); } // no body data expected? then we are now complete if (_bodySize == 0) { complete(); } } /** * Process the message data * * @param frame The frame to process */ void DeferredReceiver::process(BodyFrame &frame) { // make sure we stay in scope auto self = lock(); // update the bytes still to receive _bodySize -= frame.payloadSize(); // anybody interested in the data? if (_dataCallback) { _dataCallback(frame.payload(), frame.payloadSize()); } // do we have a message? then append the data if (_message) { _message->append(frame.payload(), frame.payloadSize()); } // if all bytes were received we are now complete if (_bodySize == 0) { complete(); } } /** * End namespace */ }
19.990196
98
0.682197
NotifAi
e47bd6ff4188a7e9ee71c2e2f049ab342c78a15d
3,568
cpp
C++
pieces/Knight.cpp
vtad4f/chess-ai
419656d4c16671465bd5536bc3f897c23f0dd8f7
[ "MIT" ]
null
null
null
pieces/Knight.cpp
vtad4f/chess-ai
419656d4c16671465bd5536bc3f897c23f0dd8f7
[ "MIT" ]
null
null
null
pieces/Knight.cpp
vtad4f/chess-ai
419656d4c16671465bd5536bc3f897c23f0dd8f7
[ "MIT" ]
1
2022-01-14T19:12:24.000Z
2022-01-14T19:12:24.000Z
#include "Knight.h" #include "board/BitBoard.h" #include "io/Error.h" //////////////////////////////////////////////////////////////////////////////// /// /// @brief Constructor /// //////////////////////////////////////////////////////////////////////////////// Knight::Knight(const uint8_t* bitBoard, bool black, int knight_i) : Piece(bitBoard, (black ? BLACK_START : WHITE_START) + (knight_i == 0 ? N1_INDEX : N2_INDEX)) { } //////////////////////////////////////////////////////////////////////////////// /// /// @brief Destructor /// //////////////////////////////////////////////////////////////////////////////// Knight::~Knight() { } //////////////////////////////////////////////////////////////////////////////// /// /// @brief Get the piece type as a string /// //////////////////////////////////////////////////////////////////////////////// std::string Knight::Type() const { return "Knight"; } //////////////////////////////////////////////////////////////////////////////// /// /// @brief Get the value for the knight /// //////////////////////////////////////////////////////////////////////////////// int Knight::Value() const { return Knight::VALUE; } //////////////////////////////////////////////////////////////////////////////// /// /// @brief Represent all the moves a knight can make as a bit mask /// //////////////////////////////////////////////////////////////////////////////// uint64_t Knight::MoveMask(const PlayerMasks& playerMasks, const MaskOptions& maskOptions) const { return Captured() ? 0 : __MoveMask(PosMask(), Row(), Col(), playerMasks, maskOptions); } //////////////////////////////////////////////////////////////////////////////// /// /// @brief Represent all the moves a knight can make as a bit mask /// //////////////////////////////////////////////////////////////////////////////// uint64_t Knight::__MoveMask(uint64_t posMask, int row, int col, const PlayerMasks& playerMasks, const MaskOptions& maskOptions) { if (maskOptions.blockableKingAttack) { return 0; } uint64_t moveMask = 0; bool not_top = row < TOP_ROW; bool not_top2 = row < TOP_ROW - 1; bool not_bottom = row > BOTTOM_ROW; bool not_bottom2 = row > BOTTOM_ROW + 1; bool not_left = col > LEFT_COL; bool not_left2 = col > LEFT_COL + 1; bool not_right = col < RIGHT_COL; bool not_right2 = col < RIGHT_COL - 1; if (not_left2) { if (not_top) { moveMask |= posMask >> ((8 * 2) - 1); // left 2, up 1 } if (not_bottom) { moveMask |= posMask >> ((8 * 2) + 1); // left 2, down 1 } } if (not_left) { if (not_top2) { moveMask |= posMask >> (8 - 2); // left 1, up 2 } if (not_bottom2) { moveMask |= posMask >> (8 + 2); // left 1, down 2 } } if (not_right) { if (not_top2) { moveMask |= posMask << (8 + 2); // right 1, up 2 } if (not_bottom2) { moveMask |= posMask << (8 - 2); // right 1, down 2 } } if (not_right2) { if (not_top) { moveMask |= posMask << ((8 * 2) + 1); // right 2, up 1 } if (not_bottom) { moveMask |= posMask << ((8 * 2) - 1); // right 2, down 1 } } // Exclude spaces already occupied by our pieces (unless told to include // the pieces we are guarding) if (!maskOptions.guard) { moveMask &= ~playerMasks.myPieces; } return moveMask; }
24.777778
127
0.399664
vtad4f
7cfd35a106f1619600805694013deb2fed36836d
1,292
cpp
C++
tools/EditorLayerInput/LayerManager.cpp
matcool/BetterEdit
aaf3f37b4c0d7b6d8298cd099d8bd2d9699cb68f
[ "MIT" ]
null
null
null
tools/EditorLayerInput/LayerManager.cpp
matcool/BetterEdit
aaf3f37b4c0d7b6d8298cd099d8bd2d9699cb68f
[ "MIT" ]
null
null
null
tools/EditorLayerInput/LayerManager.cpp
matcool/BetterEdit
aaf3f37b4c0d7b6d8298cd099d8bd2d9699cb68f
[ "MIT" ]
null
null
null
#include "LayerManager.hpp" LayerManager* g_manager; LayerManager::LevelName LayerManager::getLevelName() { if (!LevelEditorLayer::get()) { return ""; } return LevelEditorLayer::get()->m_pLevelSettings->m_pLevel->levelName; } LayerManager::Layer* LayerManager::getLayer(int number) { if (number < 0) return nullptr; if (number > static_cast<int>(max_layer_num)) return nullptr; auto lvl = this->getLevel(); if (!lvl) return nullptr; if (!lvl->m_mLayers[number]) lvl->m_mLayers[number] = new Layer(number); return lvl->m_mLayers[number]; } LayerManager::Level * LayerManager::getLevel() { auto lvl = this->getLevelName(); if (!lvl.size()) return nullptr; if (!m_mLevels.count(lvl)) m_mLevels.insert({ lvl, new Level() }); return m_mLevels[lvl]; } void LayerManager::dataLoaded(DS_Dictionary* data) {} void LayerManager::encodeDataTo(DS_Dictionary* data) {} bool LayerManager::init() { return true; } LayerManager* LayerManager::get() { return g_manager; } bool LayerManager::initGlobal() { g_manager = new LayerManager(); if (g_manager && g_manager->init()) { // g_manager->retain(); return true; } CC_SAFE_DELETE(g_manager); return false; }
20.83871
74
0.650155
matcool
7cff6aa673e91681e5a5ad026d3a5aaff0192cd8
42,484
cpp
C++
HopsanGUI/GUIObjects/AnimatedComponent.cpp
mjfwest/hopsan
77a0a1e69fd9588335b7e932f348972186cbdf6f
[ "Apache-2.0" ]
null
null
null
HopsanGUI/GUIObjects/AnimatedComponent.cpp
mjfwest/hopsan
77a0a1e69fd9588335b7e932f348972186cbdf6f
[ "Apache-2.0" ]
null
null
null
HopsanGUI/GUIObjects/AnimatedComponent.cpp
mjfwest/hopsan
77a0a1e69fd9588335b7e932f348972186cbdf6f
[ "Apache-2.0" ]
null
null
null
/*----------------------------------------------------------------------------- Copyright 2017 Hopsan Group This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. The full license is available in the file GPLv3. For details about the 'Hopsan Group' or information about Authors and Contributors see the HOPSANGROUP and AUTHORS files that are located in the Hopsan source code root directory. -----------------------------------------------------------------------------*/ //! //! @file AnimatedComponent.cpp //! @author Pratik Deschpande <pratik661@gmail.com> //! @author Robert Braun <robert.braun@liu.se> //! @date 2012-04-25 //! //! @brief Contains a class for animated components //! //$Id$ #include <qmath.h> #include <float.h> #include <QGraphicsColorizeEffect> #include "common.h" #include "global.h" #include "AnimatedComponent.h" #include "CoreAccess.h" #include "GraphicsView.h" #include "GUIModelObject.h" #include "GUIPort.h" #include "../HopsanCore/include/Port.h" #include "Dialogs/AnimatedIconPropertiesDialog.h" #include "GUIObjects/GUIContainerObject.h" #include "Utilities/GUIUtilities.h" #include "Widgets/AnimationWidget.h" #include "Widgets/ModelWidget.h" #include "PlotHandler.h" #include "PlotWindow.h" //! @brief Constructor for the animated component class AnimatedComponent::AnimatedComponent(ModelObject* unanimatedComponent, AnimationWidget *parent) : QObject(parent /*parent*/) { //Set member pointer variables mpAnimationWidget = parent; mpModelObject = unanimatedComponent; mpAnimationWidget = parent; mpData = new QList<QList<QVector<double> > >(); mpNodeDataPtrs = new QList<QList<double *> >(); //Store port positions for(int i=0; i<unanimatedComponent->getPortListPtrs().size(); ++i) { Port *pPort = unanimatedComponent->getPortListPtrs().at(i); mPortPositions.insert(pPort->getName(), pPort->getCenterPos()); } //Set the animation data object mpAnimationData = unanimatedComponent->getAppearanceData()->getAnimationDataPtr(); //Setup the base icon setupAnimationBase(mpAnimationData->baseIconPath); //Setup the movable icons if(!mpAnimationData->movables.isEmpty()) { for(int i=0; i<mpAnimationData->movables.size(); ++i) { setupAnimationMovable(i); //if(!mpAnimationData->movables[i].dataPorts.isEmpty()/* && unanimatedComponent->getPort(mpAnimationData->dataPorts.at(i).first())->isConnected()*/) //{ mpData->append(QList<QVector<double> >()); mpNodeDataPtrs->append(QList<double*>()); //! @todo generation info should be some kind of "property" for all of the animation code so that if you change it, it should change everywhere, to make it possible to animate different generations int generation = mpAnimationWidget->mpContainer->getLogDataHandler()->getCurrentGenerationNumber(); QString componentName = unanimatedComponent->getName(); for(int j=0; j<mpAnimationData->movables[i].dataPorts.size(); ++j) { QString portName = mpAnimationData->movables[i].dataPorts.at(j); QString dataName = mpAnimationData->movables[i].dataNames.at(j); if(!mpAnimationWidget->getPlotDataPtr()->isEmpty()) { QString tempComponentName = componentName; QString tempPortName = portName; if(mpModelObject->getPort(portName) && mpModelObject->getPort(portName)->getPortType().contains("Multiport")) { tempComponentName = mpModelObject->getPort(portName)->getConnectedPorts().first()->getParentModelObjectName(); tempPortName = mpModelObject->getPort(portName)->getConnectedPorts().first()->getName(); } mpData->last().append(mpAnimationWidget->getPlotDataPtr()->copyVariableDataVector(makeFullVariableName(mpModelObject->getParentSystemNameHieararchy(), tempComponentName, tempPortName, dataName),generation)); } mpNodeDataPtrs->last().append(mpAnimationWidget->mpContainer->getCoreSystemAccessPtr()->getNodeDataPtr(componentName, portName, dataName)); if(!mpNodeDataPtrs->last().last()) { mpNodeDataPtrs->last().last() = new double(0); } //qDebug() << "mpData = " << *mpData; } //} } } if(mpModelObject->getSubTypeName() == "XmasSky") { mpBase->setZValue(mpBase->zValue()-1); } if(mpModelObject->getSubTypeName() == "XmasSnow") { mpBase->setZValue(mpBase->zValue()+2); } if(mpModelObject->getSubTypeName() == "XmasSnowFlake") { mpBase->setZValue(mpBase->zValue()+1); } //Draw itself to the scene draw(); } //! @brief Draws the animated component to the scene of the parent animation widget void AnimatedComponent::draw() { //Add the base icon to the scene mpAnimationWidget->getGraphicsScene()->addItem(mpBase); //Add the movable icons to the scene if(mpMovables.size() > 0) { for(int m=0; m<mpMovables.size(); ++m) { mpAnimationWidget->getGraphicsScene()->addItem(mpMovables.at(m)); } } } //! @brief Updates the animation of the component void AnimatedComponent::updateAnimation() { int a=0; //Adjustables use a different indexing, because all movables are not adjustable if(mIsDisplay) { double textData; mpModelObject->getPort("in")->getLastNodeData("Value", textData); QString text = QString::number(textData,'g', 4); text = text.left(6); mpText->setPlainText(text); } //Loop through all movable icons for(int m=0; m<mpMovables.size(); ++m) { if(mpAnimationWidget->isRealTimeAnimation() && mpAnimationData->movables[m].isAdjustable) { double value = mpMovables.at(m)->x()*mpAnimationData->movables[m].adjustableGainX + mpMovables.at(m)->y()*mpAnimationData->movables[m].adjustableGainY; (*mpMovables.at(m)->mpAdjustableNodeDataPtr) = value; ++a; } else //Not adjustable, so let's move it { QList<double> data; if(mpAnimationWidget->isRealTimeAnimation() && !mpNodeDataPtrs->isEmpty()) //Real-time simulation, read from node vector directly { if(true/*mpModelObject->getPort(mpAnimationData->dataPorts.at(m).first())->isConnected()*/) { for(int i=0; i<mpNodeDataPtrs->at(m).size(); ++i) { data.append(*mpNodeDataPtrs->at(m).at(i)); } data.append(0); //mpAnimationWidget->mpContainer->getCoreSystemAccessPtr()->getLastNodeData(mpModelObject->getName(), mpAnimationData->dataPorts.at(m), mpAnimationData->dataNames.at(m), data); } else { data.append(0); } } else if(!mpData->isEmpty()) //Not real-time, so read from predefined data member object { for(int i=0; i<mpData->at(m).size(); ++i) { if(!mpData->at(m).at(i).isEmpty()) { data.append(mpData->at(m).at(i).at(mpAnimationWidget->getIndex())); } else { data.append(0); } } } if(data.isEmpty()) { continue; } //Set position and rotation double x = mpAnimationData->movables[m].startX; double y = mpAnimationData->movables[m].startY; double rot = mpAnimationData->movables[m].startTheta; foreach(const ModelObjectAnimationMovementData &movement, mpAnimationData->movables[m].movementData) { int idx = movement.dataIdx; x -= data[idx]*movement.x*movement.multiplierValue/movement.divisorValue; y -= data[idx]*movement.y*movement.multiplierValue/movement.divisorValue; rot -= data[idx]*movement.theta*movement.multiplierValue/movement.divisorValue; } //Apply parameter multipliers/divisors // if(mpAnimationData->movables[m].useMultipliers) //! @todo Multipliers and divisors currently only work for first data // { // x *= mpAnimationData->movables[m].multiplierValue; // y *= mpAnimationData->movables[m].multiplierValue; // rot *= mpAnimationData->movables[m].multiplierValue; // } // if(mpAnimationData->movables[m].useDivisors) // { // x /= mpAnimationData->movables[m].divisorValue; // y /= mpAnimationData->movables[m].divisorValue; // rot /= mpAnimationData->movables[m].divisorValue; // } //Apply new position mpMovables[m]->setPos(x, y); mpMovables[m]->setRotation(rot); //Set scale if(!mpAnimationData->movables[m].resizeData.isEmpty()) { double totalScaleX = 1; double totalScaleY = 1; bool xChanged = false; bool yChanged = false; foreach(const ModelObjectAnimationResizeData &resize, mpAnimationData->movables[m].resizeData) { int idx1 = resize.dataIdx1; int idx2 = resize.dataIdx2; double scaleData; if(idx1 != idx2 && idx2 > 0) { scaleData = data[idx1]+data[idx2]; } else { scaleData = data[idx1]; } if(resize.x != 0) { double scaleX = resize.x*scaleData; totalScaleX *= scaleX*resize.multiplierValue/resize.divisorValue; xChanged = true; } if(resize.y != 0) { double scaleY = resize.y*scaleData; totalScaleY *= scaleY*resize.multiplierValue/resize.divisorValue; yChanged = true; } } if(!xChanged) totalScaleX = 0; if(!yChanged) totalScaleY = 0; double initX = mpAnimationData->movables[m].initScaleX; double initY = mpAnimationData->movables[m].initScaleY; totalScaleX = initX - totalScaleX; totalScaleY = initY - totalScaleY; mpMovables[m]->resetTransform(); //mpMovables[m]->scale(initX-scaleX, initY-scaleY); mpMovables[m]->setTransform(QTransform::fromScale(totalScaleX, totalScaleY), true); } //Set color if(mpAnimationData->movables[m].colorData.r != 0.0 || mpAnimationData->movables[m].colorData.g != 0.0 || mpAnimationData->movables[m].colorData.b != 0.0 || mpAnimationData->movables[m].colorData.a != 0.0) { int idx = mpAnimationData->movables[m].colorData.dataIdx; double div = mpAnimationData->movables[m].colorData.divisorValue; double mul = mpAnimationData->movables[m].colorData.multiplierValue; int ir = mpAnimationData->movables[m].colorData.initR; int r=ir; if(mpAnimationData->movables[m].colorData.r != 0) { r = std::max(0, std::min(255, ir-int(mpAnimationData->movables[m].colorData.r*data[idx]*mul/div))); } int ig = mpAnimationData->movables[m].colorData.initG; int g = ig; if(mpAnimationData->movables[m].colorData.g != 0) { g = std::max(0, std::min(255, ig-int(mpAnimationData->movables[m].colorData.g*data[idx]*mul/div))); } int ib = mpAnimationData->movables[m].colorData.initB; int b = ib; if(mpAnimationData->movables[m].colorData.b != 0) { b = std::max(0, std::min(255, ib-int(mpAnimationData->movables[m].colorData.b*data[idx]*mul/div))); } int ia = mpAnimationData->movables[m].colorData.initA; if(ia == 0) { ia = 255; } int a = ia; if(mpAnimationData->movables[m].colorData.a != 0) { a = std::max(0, std::min(255, ia-int(mpAnimationData->movables[m].colorData.a*data[idx]*mul/div))); } QColor color(r,g,b,a); // qDebug() << "Color: " << r << " " << g << " " << b << " " << a; mpMovables[m]->mpEffect->setColor(color); mpMovables[m]->setGraphicsEffect(mpMovables[m]->mpEffect); mpMovables[m]->setOpacity(double(a)/255.0); } //Indicators if(mpAnimationData->movables[m].isIndicator) { double data = (*mpAnimationWidget->mpContainer->getCoreSystemAccessPtr()->getNodeDataPtr(mpModelObject->getName(), mpAnimationData->movables[m].indicatorPort, mpAnimationData->movables[m].indicatorDataName)); mpMovables[m]->setVisible(data > 0.5); } // mpMovables[m]->update(); //Update "port" positions, so that connectors will follow component for(int p=0; p<mpAnimationData->movables[m].movablePortNames.size(); ++p) { QString portName = mpAnimationData->movables[m].movablePortNames[p]; double portStartX = mpAnimationData->movables[m].movablePortStartX[p]; double portStartY = mpAnimationData->movables[m].movablePortStartY[p]; QPointF pos; //double mrot = mpMovables[m]->rotation(); //pos.setX((portStartX+x)*cos(mrot) - (portStartY+y)*sin(mrot)); //pos.setY((portStartY+y)*cos(mrot) + (portStartX+x)*sin(mrot)); //pos.setX(portStartX); //pos.setY(portStartY); pos = mpMovables[m]->mapToItem(mpBase, portStartX, portStartY); mPortPositions.insert(portName, pos); } } } if(mpModelObject->getTypeName() == HOPSANGUISCOPECOMPONENTTYPENAME) { LogDataHandler2 *pHandler = mpModelObject->getParentContainerObject()->getLogDataHandler(); QList<SharedVectorVariableT> vectors; SharedVectorVariableT pTimeVar = pHandler->getVectorVariable(mpModelObject->getName()+"_time",-1); if(!pTimeVar.isNull()) { pTimeVar->append(mpAnimationWidget->getLastAnimationTime()); vectors << pTimeVar; SharedVectorVariableT pVar; foreach(const Port *pPort, QVector<Port*>() << mpModelObject->getPort("in")->getConnectedPorts() << mpModelObject->getPort("in_right")->getConnectedPorts() << mpModelObject->getPort("in_bottom")) { //! @todo should pregenerate the names instead of doing it every update (getSystemHierarchy need to be regenerateed every time) QString fullName = makeFullVariableName(pPort->getParentModelObject()->getParentSystemNameHieararchy(), pPort->getParentModelObjectName(), pPort->getName(),"Value"); fullName.remove("#"); pVar = pHandler->getVectorVariable(fullName,-1); if(pVar.isNull()) { continue; } double data; pPort->getLastNodeData("Value", data); pVar->append(data); vectors << pVar; } double firstT = pTimeVar->first(); double lastT = pTimeVar->last(); while(lastT-firstT > 3) { for(int i=0; i<vectors.size(); ++i) { vectors[i]->chopAtBeginning(); } firstT = pTimeVar->first(); } } } } //! @brief Returns a pointer to the animation data object ModelObjectAnimationData *AnimatedComponent::getAnimationDataPtr() { return mpAnimationData; } //! @brief Returns the index of a movable icon //! @param [in] pMovable Pointer to movable icon int AnimatedComponent::indexOfMovable(AnimatedIcon *pMovable) { return mpMovables.indexOf(pMovable); } QPointF AnimatedComponent::getPortPos(QString portName) { return mPortPositions.find(portName).value(); } void AnimatedComponent::textEdited() { disconnect(mpText->document(), SIGNAL(contentsChanged()), this, SLOT(textEdited())); QTextCursor cursor = mpText->textCursor(); QString text = mpText->toPlainText(); text.remove("\n"); if(text.size() > 10) //Limit value to box size { text.chop(1); mpText->setPlainText(text); // QTextCursor cursor = mpText->textCursor(); // cursor.movePosition(QTextCursor::EndOfLine); // mpText->setTextCursor(cursor); } mpText->setPlainText(text); if(text.toDouble()) { qDebug() << "Double value: " << text.toDouble(); if(mpModelObject->getPort("out")) { mpModelObject->getParentContainerObject()->getCoreSystemAccessPtr()->writeNodeData(mpModelObject->getName(), "out", "Value", text.toDouble()); } } else { qDebug() << "Illegal value: " << text; } //cursor.movePosition(QTextCursor::EndOfLine); mpText->setTextCursor(cursor); connect(mpText->document(), SIGNAL(contentsChanged()), this, SLOT(textEdited())); } //! @brief Creates the animation base icon //! @param [in] basePath Path to the icon file void AnimatedComponent::setupAnimationBase(QString basePath) { ModelObjectAppearance *baseAppearance = new ModelObjectAppearance(); if(mpAnimationData->baseIconPath.isEmpty()) { mpAnimationData->baseIconPath = mpModelObject->getAppearanceData()->getIconPath(UserGraphics, Absolute); if(mpAnimationData->baseIconPath.isEmpty()) { mpAnimationData->baseIconPath = mpModelObject->getAppearanceData()->getIconPath(ISOGraphics, Absolute); } if(mpAnimationData->baseIconPath.isEmpty()) { mpAnimationData->baseIconPath = mpModelObject->getAppearanceData()->getDefaultMissingIconPath(); } baseAppearance->setIconPath(mpAnimationData->baseIconPath, UserGraphics, Absolute); } else { baseAppearance->setIconPath(basePath, UserGraphics, Relative); } mpBase = new AnimatedIcon(mpModelObject->pos(),0,baseAppearance,this,0,0); mpAnimationWidget->getGraphicsScene()->addItem(mpBase); if(mpModelObject->isFlipped()) { mpBase->flipHorizontal(); } mpBase->setRotation(mpModelObject->rotation()); mpBase->setCenterPos(mpModelObject->getCenterPos()); //Base icon shall never be movable mpBase->setFlag(QGraphicsItem::ItemIsMovable, false); // mpBase->refreshIconPosition(); mpText = new QGraphicsTextItem(mpBase); mpText->setPlainText("0"); mpText->setFont(QFont("Arial", 16)); mpText->setPos(7,0); mpText->hide(); mIsDisplay = (mpModelObject->getTypeName() == "SignalDisplay"); mIsNumericalInput = (mpModelObject->getTypeName() == "SignalNumericalInput"); if(mIsNumericalInput) { mpText->setTextInteractionFlags(Qt::TextEditorInteraction); mpText->show(); connect(mpText->document(), SIGNAL(contentsChanged()), this, SLOT(textEdited())); } if(mIsDisplay) { mpText->setDefaultTextColor(Qt::green); mpText->show(); } } //! @brief Creates a movable icon //! @param [in] m Index of icon to create void AnimatedComponent::setupAnimationMovable(int m) { ModelObjectAppearance* pAppearance = new ModelObjectAppearance(); pAppearance->setIconPath(mpAnimationData->movables[m].iconPath,UserGraphics, Relative); int idx = mpAnimationData->movables[m].idx; QGraphicsItem *pBase = mpBase; if(mpAnimationData->movables[m].movableRelative > -1) { for(int r=0; r<mpMovables.size(); ++r) { if(mpMovables[r]->mIdx == mpAnimationData->movables[m].movableRelative) { pBase = mpMovables[r]; } } } this->mpMovables.append(new AnimatedIcon(QPoint(0,0),0, pAppearance,this, 0, idx, pBase)); this->mpMovables.at(m)->setTransformOriginPoint(mpAnimationData->movables[m].transformOriginX,mpAnimationData->movables[m].transformOriginY); mpMovables.at(m)->setRotation(mpAnimationData->movables[m].startTheta); mpMovables.at(m)->setPos(mpAnimationData->movables[m].startX, mpAnimationData->movables[m].startY); //Set adjustables to non-adjustable if the port is connected if(mpAnimationData->movables[m].isAdjustable) { QString port = mpAnimationData->movables[m].adjustablePort; if(mpModelObject->getPort(port)->getPortType() != "WritePortType" && mpModelObject->getPort(port)->isConnected()) { mpAnimationData->movables[m].isAdjustable = false; } } //Set icon to be movable by mouse if it shall be adjustable mpMovables.at(m)->setFlag(QGraphicsItem::ItemIsMovable, mpAnimationData->movables[m].isAdjustable); if(mpAnimationData->movables[m].isSwitchable && mpAnimationData->movables[m].hideIconOnSwitch) { mpMovables.at(m)->hide(); } //Get parameter multipliers and divisors for movement data for(int i=0; i<mpAnimationData->movables[m].movementData.size(); ++i) { QString multStr = mpAnimationData->movables[m].movementData[i].multiplier; if(!multStr.isEmpty()) { QString parValue = mpModelObject->getParameterValue(multStr); if(!parValue.isEmpty() && parValue[0].isLetter()) //Starts with letter, to it must be a system parameter { parValue = mpModelObject->getParentContainerObject()->getParameterValue(parValue); } bool ok; double temp = parValue.toDouble(&ok); if(!ok) { temp = mpModelObject->getParentContainerObject()->getParameterValue(parValue).toDouble(&ok); } mpAnimationData->movables[m].movementData[i].multiplierValue = temp; } QString divStr = mpAnimationData->movables[m].movementData[i].divisor; if(!divStr.isEmpty()) { QString parValue = mpModelObject->getParameterValue(divStr); if(!parValue.isEmpty() && parValue[0].isLetter()) //Starts with letter, to it must be a system parameter { parValue = mpModelObject->getParentContainerObject()->getParameterValue(parValue); } bool ok; double temp = parValue.toDouble(&ok); if(!ok) { temp = mpModelObject->getParentContainerObject()->getParameterValue(parValue).toDouble(&ok); } mpAnimationData->movables[m].movementData[i].divisorValue = temp; } } //Get parameter multipliers and divisors for resize data for(int i=0; i<mpAnimationData->movables[m].resizeData.size(); ++i) { QString multStr = mpAnimationData->movables[m].resizeData[i].multiplier; if(!multStr.isEmpty()) { QString parValue = mpModelObject->getParameterValue(multStr); if(!parValue.isEmpty() && parValue[0].isLetter()) //Starts with letter, to it must be a system parameter { parValue = mpModelObject->getParentContainerObject()->getParameterValue(parValue); } bool ok; double temp = parValue.toDouble(&ok); if(!ok) { temp = mpModelObject->getParentContainerObject()->getParameterValue(parValue).toDouble(&ok); } mpAnimationData->movables[m].resizeData[i].multiplierValue = temp; } QString divStr = mpAnimationData->movables[m].resizeData[i].divisor; if(!divStr.isEmpty()) { QString parValue = mpModelObject->getParameterValue(divStr); if(!parValue.isEmpty() && parValue[0].isLetter()) //Starts with letter, to it must be a system parameter { parValue = mpModelObject->getParentContainerObject()->getParameterValue(parValue); } bool ok; double temp = parValue.toDouble(&ok); if(!ok) { temp = mpModelObject->getParentContainerObject()->getParameterValue(parValue).toDouble(&ok); } mpAnimationData->movables[m].resizeData[i].divisorValue = temp; } } //Get parameter multipliers and divisors for color data QString multStr = mpAnimationData->movables[m].colorData.multiplier; if(!multStr.isEmpty()) { QString parValue = mpModelObject->getParameterValue(multStr); if(!parValue.isEmpty() && parValue[0].isLetter()) //Starts with letter, to it must be a system parameter { parValue = mpModelObject->getParentContainerObject()->getParameterValue(parValue); } bool ok; double temp = parValue.toDouble(&ok); if(!ok) { temp = mpModelObject->getParentContainerObject()->getParameterValue(parValue).toDouble(&ok); } mpAnimationData->movables[m].colorData.multiplierValue = temp; } QString divStr = mpAnimationData->movables[m].colorData.divisor; if(!divStr.isEmpty()) { QString parValue = mpModelObject->getParameterValue(divStr); if(!parValue.isEmpty() && parValue[0].isLetter()) //Starts with letter, to it must be a system parameter { parValue = mpModelObject->getParentContainerObject()->getParameterValue(parValue); } bool ok; double temp = parValue.toDouble(&ok); if(!ok) { temp = mpModelObject->getParentContainerObject()->getParameterValue(parValue).toDouble(&ok); } mpAnimationData->movables[m].colorData.divisorValue = temp; } //Old code double multiplierValue = 1; for(int p=0; p<mpAnimationData->movables[m].multipliers.size(); ++p) { if(mpAnimationData->movables[m].multipliers[p].isEmpty()) continue; QString parValue = mpModelObject->getParameterValue(mpAnimationData->movables[m].multipliers[p]); if(!parValue.isEmpty() && parValue[0].isLetter()) //Starts with letter, to it must be a system parameter { parValue = mpModelObject->getParentContainerObject()->getParameterValue(parValue); } bool ok; double temp = parValue.toDouble(&ok); if(!ok) { temp = mpModelObject->getParentContainerObject()->getParameterValue(parValue).toDouble(&ok); } multiplierValue *= temp; } mpAnimationData->movables[m].multiplierValue = multiplierValue; mpAnimationData->movables[m].useMultipliers = !mpAnimationData->movables[m].multipliers.isEmpty(); //End old code //Old code double divisorValue = 1; for(int p=0; p<mpAnimationData->movables[m].divisors.size(); ++p) { if(mpAnimationData->movables[m].divisors[p].isEmpty()) continue; QString parValue = mpModelObject->getParameterValue(mpAnimationData->movables[m].divisors[p]); if(!parValue.isEmpty() && parValue[0].isLetter()) //Starts with letter, to it must be a system parameter { parValue = mpModelObject->getParentContainerObject()->getParameterValue(parValue); } bool ok; double temp = parValue.toDouble(&ok); if(!ok) { temp = mpModelObject->getParentContainerObject()->getParameterValue(parValue).toDouble(&ok); } divisorValue *= temp; } mpAnimationData->movables[m].divisorValue = divisorValue; mpAnimationData->movables[m].useDivisors = !mpAnimationData->movables[m].divisors.isEmpty(); //End old code } //! @brief Limits the position of movables that are adjustable (can be moved by mouse) void AnimatedComponent::limitMovables() { for(int m=0; m<mpMovables.size(); ++m) { if(mpAnimationData->movables[m].isAdjustable) { if(mpMovables.at(m)->x() > mpAnimationData->movables[m].adjustableMaxX) { mpMovables.at(m)->setX(mpAnimationData->movables[m].adjustableMaxX); } else if(mpMovables.at(m)->x() < mpAnimationData->movables[m].adjustableMinX) { mpMovables.at(m)->setX(mpAnimationData->movables[m].adjustableMinX); } else if(mpMovables.at(m)->y() > mpAnimationData->movables[m].adjustableMaxY) { mpMovables.at(m)->setY(mpAnimationData->movables[m].adjustableMaxY); } else if(mpMovables.at(m)->y() < mpAnimationData->movables[m].adjustableMinY) { mpMovables.at(m)->setY(mpAnimationData->movables[m].adjustableMinY); } } } } //! @brief Creator for the animated icon class //! @param [in] position Initial position of icon //! @param [in] rotation Initial rotation of icon //! @param [in] pAppearanceData Pointer to appearance data object //! @param [in] pAnimatedComponent Pointer to animated component icon belongs to //! @param [in] pParentContainer Pointer to container object animation is showing //! @param [in] pParent Parent object (QGraphicsItem), used for the coordinate system AnimatedIcon::AnimatedIcon(QPointF position, double rotation, const ModelObjectAppearance* pAppearanceData, AnimatedComponent *pAnimatedComponent, ContainerObject *pParentContainer, int idx, QGraphicsItem *pParent) : WorkspaceObject(position, rotation, Deselected, pParentContainer, pParent) { //Store original position mPreviousPos = position; //Initialize member pointer variables mpAnimatedComponent = pAnimatedComponent; //Make a local copy of the appearance data (that can safely be modified if needed) mModelObjectAppearance = *pAppearanceData; //Setup appearance QString iconPath = mModelObjectAppearance.getFullAvailableIconPath(mIconType); double iconScale = mModelObjectAppearance.getIconScale(mIconType); mIconType = UserGraphics; mpIcon = new QGraphicsSvgItem(iconPath, this); mpIcon->setFlags(QGraphicsItem::ItemStacksBehindParent); mpIcon->setScale(iconScale); this->prepareGeometryChange(); this->resize(mpIcon->boundingRect().width()*iconScale, mpIcon->boundingRect().height()*iconScale); //Resize modelobject mpSelectionBox->setSize(0.0, 0.0, mpIcon->boundingRect().width()*iconScale, mpIcon->boundingRect().height()*iconScale); //Resize selection box this->setCenterPos(position); this->setZValue(ModelobjectZValue); if(mpAnimatedComponent->mpModelObject->getSubTypeName() == "XmasSky") { this->setZValue(this->zValue()-1); } if(mpAnimatedComponent->mpModelObject->getSubTypeName() == "XmasSnow") { this->setZValue(this->zValue()+2); } if(mpAnimatedComponent->mpModelObject->getSubTypeName() == "XmasSnowFlake") { this->setZValue(this->zValue()+1); } mIdx = idx; this->setVisible(mpAnimatedComponent->mpModelObject->isVisible()); ModelObjectAnimationData *pData = mpAnimatedComponent->getAnimationDataPtr(); if(pParent != 0 && pData->movables[0].isAdjustable) { QString comp = mpAnimatedComponent->mpModelObject->getName(); QString port = pData->movables[0].adjustablePort; QString dataName = pData->movables[0].adjustableDataName; mpAdjustableNodeDataPtr = mpAnimatedComponent->mpAnimationWidget->mpContainer->getCoreSystemAccessPtr()->getNodeDataPtr(comp, port, dataName); } mpEffect = new QGraphicsColorizeEffect(); } void AnimatedIcon::loadFromDomElement(QDomElement domElement) { Q_UNUSED(domElement) // Nothing } void AnimatedIcon::saveToDomElement(QDomElement &rDomElement, SaveContentsEnumT contents) { Q_UNUSED(rDomElement) Q_UNUSED(contents) // Nothing } //! @brief Returns the type of the object (object, component, systemport, group etc) int AnimatedIcon::type() const { return Type; } QString AnimatedIcon::getHmfTagName() const { // These objects are not present in hmf files, so nothing return QString(); } void AnimatedIcon::deleteMe(UndoStatusEnumT undoSettings) { Q_UNUSED(undoSettings) // Does nothing } //! @brief Refresh icon position after flipping or rotating void AnimatedIcon::refreshIconPosition() { mpIcon->setPos( this->mapFromScene(this->getCenterPos() - mpIcon->boundingRect().center() )); } //! @brief Defines what happens when object position has changed (limits the position to maximum values) //! @param change Tells what it is that has changed QVariant AnimatedIcon::itemChange(GraphicsItemChange change, const QVariant &value) { if (change == QGraphicsItem::ItemPositionHasChanged && this->scene() != 0) { mpAnimatedComponent->limitMovables(); } return value; } //! @brief Defines what happens when icon is double clicked (open settings dialog) //! @param event Contains information about the event void AnimatedIcon::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) { if(mpAnimatedComponent->indexOfMovable(this) > -1) //Otherwise this is the base icon, which does not have parameters { AnimatedIconPropertiesDialog *pDialog = new AnimatedIconPropertiesDialog(mpAnimatedComponent, mpAnimatedComponent->indexOfMovable(this), gpMainWindowWidget); pDialog->exec(); delete(pDialog); } //Open plot window if double-clicking on scope component if(mpAnimatedComponent->mpModelObject->getTypeName() == HOPSANGUISCOPECOMPONENTTYPENAME) { LogDataHandler2 *pHandler = mpAnimatedComponent->mpModelObject->getParentContainerObject()->getLogDataHandler(); QString name = mpAnimatedComponent->mpModelObject->getName(); PlotWindow *pPlotWindow = mpAnimatedComponent->mpPlotWindow; QString timeName = name+"_time"; SharedVectorVariableT pTimeVar = pHandler->getVectorVariable(timeName, -1); if(pTimeVar.isNull()) { pTimeVar = pHandler->defineNewVectorVariable(timeName); } pTimeVar->assignFrom(QVector<double>() << 0); pPlotWindow = gpPlotHandler->createNewUniquePlotWindow(name); foreach(const Port* pPort, mpAnimatedComponent->mpModelObject->getPort("in")->getConnectedPorts()) { //! @todo should pregenerate the names instead of doing it every update (getSystemHierarchy need to be regenerateed every time) QString fullName = makeFullVariableName(pPort->getParentModelObject()->getParentSystemNameHieararchy(), pPort->getParentModelObjectName(), pPort->getName(),"Value"); fullName.remove("#"); SharedVectorVariableT pVar = pHandler->getVectorVariable(fullName, -1); if(pVar.isNull()) { pVar = pHandler->defineNewVectorVariable(fullName); } pVar->assignFrom(QVector<double>() << 0); pHandler->plotVariable(pPlotWindow, fullName, -1, QwtPlot::yLeft); } foreach(const Port* pPort, mpAnimatedComponent->mpModelObject->getPort("in_right")->getConnectedPorts()) { //! @todo should pregenerate the names instead of doing it every update (getSystemHierarchy need to be regenerateed every time) QString fullName = makeFullVariableName(pPort->getParentModelObject()->getParentSystemNameHieararchy(), pPort->getParentModelObjectName(), pPort->getName(),"Value"); fullName.remove("#"); SharedVectorVariableT pVar = pHandler->getVectorVariable(fullName, -1); if(pVar.isNull()) { pVar = pHandler->defineNewVectorVariable(fullName); } pVar->assignFrom(QVector<double>() << 0); pHandler->plotVariable(pPlotWindow, fullName, -1, QwtPlot::yLeft); } if(mpAnimatedComponent->mpModelObject->getPort("in_bottom")->isConnected()) { Port *pPort = mpAnimatedComponent->mpModelObject->getPort("in_bottom"); //! @todo should pregenerate the names instead of doing it every update (getSystemHierarchy need to be regenerateed every time) QString fullName = makeFullVariableName(pPort->getParentModelObject()->getParentSystemNameHieararchy(), pPort->getParentModelObjectName(), pPort->getName(),"Value"); fullName.remove("#"); SharedVectorVariableT pVar = pHandler->getVectorVariable(fullName, -1); if(pVar.isNull()) { pVar = pHandler->defineNewVectorVariable(fullName); } pVar->assignFrom(QVector<double>() << 0); gpPlotHandler->setPlotWindowXData(pPlotWindow, pVar, true); } else { gpPlotHandler->setPlotWindowXData(pPlotWindow, pTimeVar, true); } pPlotWindow->showNormal(); } QGraphicsWidget::mouseDoubleClickEvent(event); } void AnimatedIcon::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { int idx = mpAnimatedComponent->indexOfMovable(this); if(idx >= 0 && mpAnimatedComponent->getAnimationDataPtr()->movables[idx].isAdjustable) { mpSelectionBox->setHovered(); } QGraphicsWidget::hoverEnterEvent(event); } void AnimatedIcon::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { mpSelectionBox->setPassive(); QGraphicsWidget::hoverLeaveEvent(event); } //! @brief Handles mouse press events on animated icons, used for switchable movables void AnimatedIcon::mousePressEvent(QGraphicsSceneMouseEvent *event) { if(!mpAnimatedComponent->mpMovables.isEmpty()) { int idx = mIdx;//mpAnimatedComponent->indexOfMovable(this); if(idx < 0) { idx = 0; //Not good, we assume there is only one movable and that it is the switch } ModelObjectAnimationData *pData = mpAnimatedComponent->getAnimationDataPtr(); bool switchable = pData->movables[idx].isSwitchable; if(switchable) { //! @todo Don't do pointer lookup every time step! double *pNodeData = mpAnimatedComponent->mpAnimationWidget->mpContainer->getCoreSystemAccessPtr()->getNodeDataPtr(mpAnimatedComponent->mpModelObject->getName(), pData->movables[mIdx].switchablePort, pData->movables[mIdx].switchableDataName); double onValue = pData->movables[idx].switchableOnValue; double offValue = pData->movables[idx].switchableOffValue; if((*pNodeData) == onValue/*mpAnimatedComponent->mpMovables[idx]->isVisible()*/) { if(pData->movables[idx].hideIconOnSwitch) { mpAnimatedComponent->mpMovables[idx]->setVisible(false); } (*pNodeData) = offValue; } else { if(pData->movables[idx].hideIconOnSwitch) { mpAnimatedComponent->mpMovables[idx]->setVisible(true); } (*pNodeData) = onValue; } } } QGraphicsWidget::mousePressEvent(event); } //! @brief Slot that rotates the icon //! @param [in] angle Angle to rotate (degrees) void AnimatedIcon::rotate(double angle, UndoStatusEnumT undoSettings) { Q_UNUSED(undoSettings) if(mIsFlipped) { angle *= -1; } this->setRotation(normDeg360(this->rotation()+angle)); refreshIconPosition(); } //! @brief Slot that flips the object vertically //! @see flipHorizontal() void AnimatedIcon::flipVertical(UndoStatusEnumT undoSettings) { Q_UNUSED(undoSettings) this->flipHorizontal(); this->rotate(180); } //! @brief Slot that flips the object horizontally //! @see flipVertical() void AnimatedIcon::flipHorizontal(UndoStatusEnumT undoSettings) { Q_UNUSED(undoSettings) QTransform transf; transf.scale(-1.0, 1.0); //Remember center pos QPointF cpos = this->getCenterPos(); //Transform this->setTransform(transf,true); // transformation origin point seems to have no effect here for some reason //Reset to center pos (as transform origin point was ignored) this->setCenterPos(cpos); // If the icon is (not rotating) its position will be refreshed //refreshIconPosition(); // Toggle isFlipped bool if(mIsFlipped) { mIsFlipped = false; } else { mIsFlipped = true; } }
38.692168
253
0.611948
mjfwest
6b04573ccd3b7864ae5318de2befbfb009a186ea
831
cpp
C++
test/test_example.cpp
Expander/dilogarithm
ad86038206895ab5bff79a26294f4bb5c5634eb5
[ "MIT" ]
2
2017-05-04T14:47:41.000Z
2017-08-02T13:13:45.000Z
test/test_example.cpp
Expander/dilogarithm
ad86038206895ab5bff79a26294f4bb5c5634eb5
[ "MIT" ]
null
null
null
test/test_example.cpp
Expander/dilogarithm
ad86038206895ab5bff79a26294f4bb5c5634eb5
[ "MIT" ]
null
null
null
#include "Li.hpp" #include "Li2.hpp" #include "Li3.hpp" #include "Li4.hpp" #include "Li5.hpp" #include "Li6.hpp" #include <iostream> int main() { using namespace polylogarithm; const double x = 1.0; const std::complex<double> z(1.0, 1.0); // real polylogarithms for real arguments std::cout << "Li_2(" << x << ") = " << Li2(x) << '\n' << "Li_3(" << x << ") = " << Li3(x) << '\n' << "Li_4(" << x << ") = " << Li4(x) << '\n'; // complex polylogarithms for complex arguments std::cout << "Li_2(" << z << ") = " << Li2(z) << '\n' << "Li_3(" << z << ") = " << Li3(z) << '\n' << "Li_4(" << z << ") = " << Li4(z) << '\n' << "Li_5(" << z << ") = " << Li5(z) << '\n' << "Li_6(" << z << ") = " << Li6(z) << '\n' << "Li_10(" << z << ") = " << Li(10,z) << '\n'; }
27.7
53
0.416366
Expander
6b074f8393b6e887bc0cb634807c48d65e55bb93
1,398
hpp
C++
detail/core.hpp
JCYang/ya_uftp
b6a6dac7969371583c76ad90ef5ebf0c4ae66bdf
[ "BSL-1.0" ]
null
null
null
detail/core.hpp
JCYang/ya_uftp
b6a6dac7969371583c76ad90ef5ebf0c4ae66bdf
[ "BSL-1.0" ]
null
null
null
detail/core.hpp
JCYang/ya_uftp
b6a6dac7969371583c76ad90ef5ebf0c4ae66bdf
[ "BSL-1.0" ]
null
null
null
#pragma once #ifndef YA_UFTP_DETAIL_CORE_HPP_ #define YA_UFTP_DETAIL_CORE_HPP_ #include "api_binder.hpp" #include "boost/asio.hpp" namespace ya_uftp { namespace core { namespace detail { class execution_unit { boost::asio::io_context m_work_ctx; std::mutex m_guard_mutex; api::optional<boost::asio::executor_work_guard<boost::asio::io_context::executor_type>> m_work_guard; std::atomic<std::uint64_t> m_busy_count = 0u; std::thread m_work_thread; struct private_ctor_tag {}; static std::vector<std::unique_ptr<execution_unit>> m_net_exec_units; static std::vector<std::unique_ptr<execution_unit>> m_disk_exec_units; static std::unique_ptr<execution_unit> m_event_report_unit; static std::size_t m_max_thread_count; public: enum class type { disk_io, network_io }; execution_unit(private_ctor_tag tag); execution_unit(execution_unit&& from) = delete; execution_unit(const execution_unit& from) = delete; void start(); void stop(); boost::asio::io_context& context(); std::uint64_t busy_count() const; ~execution_unit(); bool running() const; static void set_max_thread_count(api::optional<std::size_t> count); static execution_unit& get_for_next_job(type t); static execution_unit& get_for_event_report(); }; } } } #endif
27.96
91
0.697425
JCYang
6b099adeeec69750bb2dae6c98cd80563828da23
1,957
cpp
C++
art-of-prog/02-str_contain/02-str_contain.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
art-of-prog/02-str_contain/02-str_contain.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
art-of-prog/02-str_contain/02-str_contain.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
#include <cwchar> #include <locale> #include <cstring> #include <iostream> using std::wcin; using std::wcout; using std::endl; #include <string> using std::wstring; using std::string; #include <algorithm> /**< 字符串包含判断 */ // http://taop.marchtea.com/01.02.html // 暴力查找 bool wstrCont1(wstring const& a, wstring const& b) { for (size_t i = 0u; i < b.length(); ++i) { size_t j; for (j = 0; j < a.length(); ++j) if (a[j] == b[i]) break; if (j >= a.length()) return false; } return true; } // 如果允许排序,可以对字符串进行轮询扫描 bool wstrCont2(wstring& a, wstring& b) { std::sort(a.begin(), a.end()); std::sort(b.begin(), b.end()); for (size_t pa = 0, pb = 0; pb < b.length();) { while ((pa < a.length()) && (a[pa] < b[pb])) ++pa; if ((pa >= a.length()) || a[pa] > b[pb]) return false; ++pb; // a[pa] == b[pb] } return true; } // 使用质数乘积,根据余数判断 // 只有理论意义,只能判断有限个字符 (26 个大写字母) bool strCont1(string &a, string &b) { const int p[26] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101 }; int f = 1; for (int i = 0; i < a.length(); ++i) { int x = p[a[i] - 'A']; if (f % x) f *= x; } for (int i = 0; i < b.length(); ++i) { int x = p[b[i] - 'A']; if (f % x) return false; } return true; } // 用异或运算当散列函数,用字符对应编码的整数表示签名 // 也只能测试有限个字符 (26 个大写字母,sizeof(unsigned int) = 32) bool strCont2(string const& a, string const& b) { unsigned int hash = 0u; for (int i = 0; i < a.length(); ++i) hash |= (1 << (a[i] - 'A')); for (int i = 0; i < b.length(); ++i) if ((hash & (1 << (b[i] - 'A'))) == 0) return false; return true; } int main() { wcout.imbue(std::locale("zh-CN")); wstring ws1(L"Test 你好 Hello"); wstring ws2(L"Hello 好"); wstring ws3(L"Test 你那"); wcout << ws1 << L" ->>- " << ws2 << L" => " << std::boolalpha << wstrCont1(ws1, ws2) << endl; wcout << ws1 << L" ->>- " << ws3 << L" => " << std::flush << std::boolalpha << wstrCont2(ws1, ws3) << endl; return 0; }
22.494253
123
0.544711
Ginkgo-Biloba
6b0bb5ff8108f224563b70cb470873c0a61a2d57
1,447
hpp
C++
Service/jni/boost/x86_64/include/boost-1_65_1/boost/detail/winapi/debugapi.hpp
Mattlk13/innoextract-android
5a69382ac9104d47383c1af0aaa0bc8a336c9744
[ "Apache-2.0" ]
16
2015-04-27T00:12:56.000Z
2022-01-05T01:52:56.000Z
Service/jni/boost/x86_64/include/boost-1_65_1/boost/detail/winapi/debugapi.hpp
Mattlk13/innoextract-android
5a69382ac9104d47383c1af0aaa0bc8a336c9744
[ "Apache-2.0" ]
1
2021-12-11T00:36:35.000Z
2022-01-11T15:39:01.000Z
Service/jni/boost/x86_64/include/boost-1_65_1/boost/detail/winapi/debugapi.hpp
Mattlk13/innoextract-android
5a69382ac9104d47383c1af0aaa0bc8a336c9744
[ "Apache-2.0" ]
7
2015-02-28T01:38:22.000Z
2019-07-13T13:36:36.000Z
// debugapi.hpp -------------------------------------------------------------- // // Copyright 2017 Vinnie Falco // // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt #ifndef BOOST_DETAIL_WINAPI_DEBUGAPI_HPP #define BOOST_DETAIL_WINAPI_DEBUGAPI_HPP #include <boost/detail/winapi/basic_types.hpp> #include <boost/detail/winapi/config.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif #if !defined( BOOST_USE_WINDOWS_H ) extern "C" { #if (BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_NT4) BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI IsDebuggerPresent( BOOST_DETAIL_WINAPI_VOID ); #endif BOOST_SYMBOL_IMPORT boost::detail::winapi::VOID_ WINAPI OutputDebugStringA( boost::detail::winapi::LPCSTR_ ); BOOST_SYMBOL_IMPORT boost::detail::winapi::VOID_ WINAPI OutputDebugStringW( boost::detail::winapi::LPCWSTR_ ); } #endif // extern "C" namespace boost { namespace detail { namespace winapi { #if (BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_NT4) using ::IsDebuggerPresent; #endif using ::OutputDebugStringA; using ::OutputDebugStringW; inline void output_debug_string(char const* s) { ::OutputDebugStringA(s); } inline void output_debug_string(wchar_t const* s) { ::OutputDebugStringW(s); } } } } #endif // BOOST_DETAIL_WINAPI_DEBUGAPI_HPP
18.0875
81
0.68763
Mattlk13
6b0c8743af79945acb608644d9e2d811334a171f
13,900
cc
C++
Lexical_Semantics/Repositories/UKB/ukb-3.1/src/kbGraph_v16.cc
MWTA/Text-Mining
d64250ed9f7d8f999bb925ec01c041062b1f4145
[ "MIT" ]
null
null
null
Lexical_Semantics/Repositories/UKB/ukb-3.1/src/kbGraph_v16.cc
MWTA/Text-Mining
d64250ed9f7d8f999bb925ec01c041062b1f4145
[ "MIT" ]
null
null
null
Lexical_Semantics/Repositories/UKB/ukb-3.1/src/kbGraph_v16.cc
MWTA/Text-Mining
d64250ed9f7d8f999bb925ec01c041062b1f4145
[ "MIT" ]
null
null
null
#include "kbGraph_v16.h" #include "common.h" #include "globalVars.h" #include "wdict.h" #include "prank.h" #include <string> #include <iostream> #include <fstream> #include <vector> #include <list> #include <string> #include <map> #include <iterator> #include <algorithm> #include <ostream> // Tokenizer #include <boost/tokenizer.hpp> #include <boost/lexical_cast.hpp> // Stuff for generating random numbers #include <boost/random/linear_congruential.hpp> #include <boost/random/uniform_int.hpp> #include <boost/random/variate_generator.hpp> // bfs #include <boost/graph/visitors.hpp> #include <boost/graph/breadth_first_search.hpp> #include <boost/pending/indirect_cmp.hpp> #if BOOST_VERSION > 104400 #include <boost/range/irange.hpp> #else #include <boost/pending/integer_range.hpp> #endif #include <boost/graph/graph_utility.hpp> // for boost::make_list // dijkstra #include <boost/graph/dijkstra_shortest_paths.hpp> // strong components #include <boost/graph/strong_components.hpp> namespace ukb { using namespace std; using namespace boost; static vector<string>::size_type get_reltype_idx(const string & rel, vector<string> & rtypes) { vector<string>::iterator it = rtypes.begin(); vector<string>::iterator end = rtypes.end(); vector<string>::size_type idx = 0; for(;it != end; ++it) { if (*it == rel) break; ++idx; } if (it == end) { // new relation type rtypes.push_back(rel); } if (idx > 31) { throw runtime_error("get_rtype_idx error: too many relation types !"); } return idx; } //////////////////////////////////////////////////////////////////////////////// // Class Kb //////////////////////////////////////////////////////////////////////////////// // Singleton stuff Kb16* Kb16::p_instance = 0; Kb16 *Kb16::create() { static Kb16 theKb; return &theKb; } Kb16 & Kb16::instance() { if (!p_instance) { throw runtime_error("KB not initialized"); } return *p_instance; } void Kb16::create_from_binfile(const std::string & fname) { if (p_instance) return; Kb16 *tenp = create(); ifstream fi(fname.c_str(), ifstream::binary|ifstream::in); if (!fi) { cerr << "Error: can't open " << fname << endl; exit(-1); } try { tenp->read_from_stream(fi); } catch(std::exception& e) { cerr << e.what() << "\n"; exit(-1); } p_instance = tenp; } //////////////////////////////////////////////////////////////////////////////// // strings <-> vertex_id pair<Kb16_vertex_t, bool> Kb16::get_vertex_by_name(const std::string & str, unsigned char flags) const { map<string, Kb16_vertex_t>::const_iterator it; if(flags & Kb16::is_concept) { it = synsetMap.find(str); if (it != synsetMap.end()) return make_pair(it->second, true); } // is it a word ? if(flags & Kb16::is_word) { it = wordMap.find(str); if (it != wordMap.end()) return make_pair(it->second, true); } return make_pair(Kb16_vertex_t(), false); } Kb16_vertex_t Kb16::InsertNode(const string & name, unsigned char flags) { coef_status = 0; // reset out degree coefficients if (static_ppv.size()) vector<float>().swap(static_ppv); // empty static rank vector Kb16_vertex_t u = add_vertex(g); put(vertex_name, g, u, name); put(vertex_flags, g, u, flags); return u; } Kb16_vertex_t Kb16::find_or_insert_synset(const string & str) { map<string, Kb16_vertex_t>::iterator it; bool insertedP; tie(it, insertedP) = synsetMap.insert(make_pair(str, Kb16_vertex_t())); if(insertedP) { // new vertex it->second = InsertNode(str, Kb16::is_concept); } return it->second; } Kb16_vertex_t Kb16::find_or_insert_word(const string & str) { map<string, Kb16_vertex_t>::iterator it; bool insertedP; tie(it, insertedP) = wordMap.insert(make_pair(str, Kb16_vertex_t())); if(insertedP) { // new vertex it->second = InsertNode(str, Kb16::is_word); } return it->second; } Kb16_edge_t Kb16::find_or_insert_edge(Kb16_vertex_t u, Kb16_vertex_t v, float w) { Kb16_edge_t e; bool existsP; if (u == v) throw runtime_error("Can't insert self loop !"); //if (w != 1.0) ++w; // minimum weight is 1 tie(e, existsP) = edge(u, v, g); if(!existsP) { coef_status = 0; // reset out degree coefficients if (static_ppv.size()) vector<float>().swap(static_ppv); // empty static rank vector e = add_edge(u, v, g).first; put(edge_weight, g, e, w); put(edge_rtype, g, e, static_cast<boost::uint32_t>(0)); } return e; } void Kb16::edge_add_reltype(Kb16_edge_t e, const string & rel) { boost::uint32_t m = get(edge_rtype, g, e); vector<string>::size_type idx = get_reltype_idx(rel, rtypes); m |= (1UL << idx); put(edge_rtype, g, e, m); } std::vector<std::string> Kb16::edge_reltypes(Kb16_edge_t e) const { vector<string> res; boost::uint32_t m = get(edge_rtype, g, e); vector<string>::size_type idx = 0; boost::uint32_t i = 1; while(idx < 32) { if (m & i) { res.push_back(rtypes[idx]); } idx++; i <<= 1; } return res; } //////////////////////////////////////////////////////////////////////////////// // Query and retrieval bool Kb16::vertex_is_synset(Kb16_vertex_t u) const { return !vertex_is_word(u); } bool Kb16::vertex_is_word(Kb16_vertex_t u) const { return (get(vertex_flags, g, u) & Kb16::is_word); } //////////////////////////////////////////////////////////////////////////////// // Streaming const size_t magic_id_v1 = 0x070201; const size_t magic_id = 0x080826; // read Kb16_vertex_t read_vertex_from_stream_v1(ifstream & is, Kb16Graph & g) { string name; read_atom_from_stream(is, name); Kb16_vertex_t v = add_vertex(g); put(vertex_name, g, v, name); put(vertex_flags, g, v, 0); return v; } Kb16_edge_t read_edge_from_stream_v1(ifstream & is, Kb16Graph & g) { size_t sIdx; size_t tIdx; float w = 0.0; //size_t source; bool insertedP; Kb16_edge_t e; read_atom_from_stream(is, sIdx); read_atom_from_stream(is, tIdx); read_atom_from_stream(is, w); //read_atom_from_stream(is, id); //read_atom_from_stream(is, source); tie(e, insertedP) = add_edge(sIdx, tIdx, g); assert(insertedP); put(edge_weight, g, e, w); //put(edge_source, g, e, source); return e; } Kb16_vertex_t read_vertex_from_stream(ifstream & is, Kb16Graph & g) { string name; string gloss; read_atom_from_stream(is, name); read_atom_from_stream(is, gloss); Kb16_vertex_t v = add_vertex(g); put(vertex_name, g, v, name); put(vertex_flags, g, v, static_cast<unsigned char>(Kb16::is_concept)); return v; } Kb16_edge_t read_edge_from_stream(ifstream & is, Kb16Graph & g) { size_t sIdx; size_t tIdx; float w = 0.0; boost::uint32_t rtype; bool insertedP; Kb16_edge_t e; read_atom_from_stream(is, sIdx); read_atom_from_stream(is, tIdx); read_atom_from_stream(is, w); read_atom_from_stream(is, rtype); //read_atom_from_stream(is, source); tie(e, insertedP) = add_edge(sIdx, tIdx, g); assert(insertedP); put(edge_weight, g, e, w); put(edge_rtype, g, e, rtype); return e; } void Kb16::read_from_stream (std::ifstream & is) { size_t vertex_n; size_t edge_n; size_t i; size_t id; std::map<std::string, int> relMap_aux; // Obsolete map from relation name to relation id try { coef_status = 0; vector<float>().swap(static_ppv); // empty static rank vector read_atom_from_stream(is, id); if (id == magic_id_v1) { // Backward compatibility with binary v1 format read_set_from_stream(is, relsSource); read_map_from_stream(is, relMap_aux); read_map_from_stream(is, synsetMap); read_map_from_stream(is, wordMap); //read_map_from_stream(is, sourceMap); read_atom_from_stream(is, id); if(id != magic_id_v1) { cerr << "Error: invalid id after reading maps" << endl; exit(-1); } read_atom_from_stream(is, vertex_n); for(i=0; i<vertex_n; ++i) { read_vertex_from_stream_v1(is, g); } read_atom_from_stream(is, id); if(id != magic_id_v1) { cerr << "Error: invalid id after reading vertices" << endl; exit(-1); } read_atom_from_stream(is, edge_n); for(i=0; i<edge_n; ++i) { read_edge_from_stream_v1(is, g); } read_atom_from_stream(is, id); if(id != magic_id_v1) { cerr << "Error: invalid id after reading edges" << endl; exit(-1); } read_vector_from_stream(is, notes); if(id != magic_id_v1) { cerr << "Error: invalid id (filename is a kbGraph?)" << endl; exit(-1); } } else { // Normal case read_set_from_stream(is, relsSource); read_vector_from_stream(is, rtypes); read_map_from_stream(is, synsetMap); read_map_from_stream(is, wordMap); read_atom_from_stream(is, id); if(id != magic_id) { cerr << "Error: invalid id after reading maps" << endl; exit(-1); } read_atom_from_stream(is, vertex_n); for(i=0; i<vertex_n; ++i) { read_vertex_from_stream(is, g); } read_atom_from_stream(is, id); if(id != magic_id) { cerr << "Error: invalid id after reading vertices" << endl; exit(-1); } read_atom_from_stream(is, edge_n); for(i=0; i<edge_n; ++i) { read_edge_from_stream(is, g); } read_atom_from_stream(is, id); if(id != magic_id) { cerr << "Error: invalid id after reading edges" << endl; exit(-1); } read_vector_from_stream(is, notes); if(id != magic_id) { cerr << "Error: invalid id (filename is a kbGraph?)" << endl; exit(-1); } } } catch (...) { throw runtime_error("Error when reading serialized graph (same platform used to compile the KB?)\n"); } map<string, Kb16_vertex_t>::iterator m_it(wordMap.begin()); map<string, Kb16_vertex_t>::iterator m_end(wordMap.end()); for(; m_it != m_end; ++m_it) { put(vertex_flags, g, m_it->second, get(vertex_flags, g, m_it->second) || Kb16::is_word); } } // write // // Auxiliary functions for removing isolated vertices // static size_t vdelta_isolated = numeric_limits<size_t>::max(); static size_t get_vdeltas(const Kb16Graph & g, vector<size_t> & vdeltas) { size_t d = 0; graph_traits<Kb16Graph>::vertex_iterator vit, vend; tie(vit, vend) = vertices(g); for(;vit != vend; ++vit) { if (out_degree(*vit, g) + in_degree(*vit, g) == 0) { // isolated vertex vdeltas[*vit] = vdelta_isolated; ++d; } else { vdeltas[*vit] = d; } } return d; } static void map_update(const vector<size_t> & vdelta, map<string, Kb16_vertex_t> & theMap) { map<string, Kb16_vertex_t>::iterator it = theMap.begin(); map<string, Kb16_vertex_t>::iterator end = theMap.end(); while(it != end) { if (vdelta[it->second] == vdelta_isolated) { // erase element theMap.erase(it++); } else { // update vertex id it->second -= vdelta[it->second]; ++it; } } } // write functions ofstream & write_vertex_to_stream(ofstream & o, const Kb16Graph & g, const vector<size_t> & vdelta, const Kb16_vertex_t & v) { string name; if (vdelta[v] != vdelta_isolated) { write_atom_to_stream(o, get(vertex_name, g, v)); write_atom_to_stream(o, get(vertex_gloss, g, v)); } return o; } ofstream & write_edge_to_stream(ofstream & o, const Kb16Graph & g, const vector<size_t> & vdelta, const Kb16_edge_t & e) { size_t uIdx = get(vertex_index, g, source(e,g)); uIdx -= vdelta[uIdx]; size_t vIdx = get(vertex_index, g, target(e,g)); vIdx -= vdelta[vIdx]; float w = get(edge_weight, g, e); boost::uint32_t rtype = get(edge_rtype, g, e); o.write(reinterpret_cast<const char *>(&uIdx), sizeof(uIdx)); o.write(reinterpret_cast<const char *>(&vIdx), sizeof(vIdx)); o.write(reinterpret_cast<const char *>(&w), sizeof(w)); o.write(reinterpret_cast<const char *>(&rtype), sizeof(rtype)); return o; } ofstream & Kb16::write_to_stream(ofstream & o) { // First remove isolated vertices and // - get delta vector // - remove from map // - get deltas vector<size_t> vdelta(num_vertices(g), 0); size_t visol_size = get_vdeltas(g, vdelta); // - update the maps if (visol_size) { map_update(vdelta, synsetMap); map_update(vdelta, wordMap); } // Write maps write_atom_to_stream(o, magic_id); write_vector_to_stream(o, relsSource); write_vector_to_stream(o, rtypes); write_map_to_stream(o, synsetMap); write_map_to_stream(o, wordMap); //write_map_to_stream(o, sourceMap); write_atom_to_stream(o, magic_id); size_t vertex_n = num_vertices(g) - visol_size; write_atom_to_stream(o, vertex_n); graph_traits<Kb16Graph>::vertex_iterator v_it, v_end; tie(v_it, v_end) = vertices(g); for(; v_it != v_end; ++v_it) { write_vertex_to_stream(o, g, vdelta, *v_it); } write_atom_to_stream(o, magic_id); size_t edge_n = num_edges(g); write_atom_to_stream(o, edge_n); graph_traits<Kb16Graph>::edge_iterator e_it, e_end; tie(e_it, e_end) = edges(g); for(; e_it != e_end; ++e_it) { write_edge_to_stream(o, g, vdelta, *e_it); } write_atom_to_stream(o, magic_id); if(notes.size()) write_vector_to_stream(o, notes); return o; } void Kb16::write_to_binfile (const string & fName) { ofstream fo(fName.c_str(), ofstream::binary|ofstream::out); if (!fo) { cerr << "Error: can't create" << fName << endl; exit(-1); } write_to_stream(fo); } // text write ofstream & write_to_textstream(const Kb16Graph & g, ofstream & o) { graph_traits<Kb16Graph>::edge_iterator e_it, e_end; tie(e_it, e_end) = edges(g); for(; e_it != e_end; ++e_it) { o << "u:" << get(vertex_name, g, source(*e_it, g)) << " "; o << "v:" << get(vertex_name, g, target(*e_it, g)) << " d:1\n"; } return o; } }
24.090121
104
0.632662
MWTA
6b0cd2b03d89de1764c8e62a2fbef37a93c48e2b
1,696
hxx
C++
base/efiutil/efilib/inc/fatdir.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
base/efiutil/efilib/inc/fatdir.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
base/efiutil/efilib/inc/fatdir.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1990 Microsoft Corporation Module Name: fatdir.hxx Abstract: This class is a virtual template for a FAT directory. It will be passed to functions who wish to query the directory entries from the directory without knowledge of how or where the directory is stored. The user of this class will not be able to read or write the directory to disk. --*/ #if !defined(FATDIR_DEFN) #define FATDIR_DEFN #if defined ( _AUTOCHECK_ ) || defined( _EFICHECK_ ) #define UFAT_EXPORT #elif defined ( _UFAT_MEMBER_ ) #define UFAT_EXPORT __declspec(dllexport) #else #define UFAT_EXPORT __declspec(dllimport) #endif DECLARE_CLASS( FATDIR ); DECLARE_CLASS( WSTRING ); DEFINE_POINTER_TYPES( PFATDIR ); CONST BytesPerDirent = 32; class FATDIR : public OBJECT { public: VIRTUAL PVOID GetDirEntry( IN LONG EntryNumber ) PURE; NONVIRTUAL UFAT_EXPORT PVOID SearchForDirEntry( IN PCWSTRING FileName ); NONVIRTUAL PVOID GetFreeDirEntry( ); VIRTUAL BOOLEAN Read( ) PURE; VIRTUAL BOOLEAN Write( ) PURE; VIRTUAL LONG QueryNumberOfEntries( ) PURE; NONVIRTUAL UFAT_EXPORT BOOLEAN QueryLongName( IN LONG EntryNumber, OUT PWSTRING LongName ); protected: DECLARE_CONSTRUCTOR( FATDIR ); }; #endif // FATDIR_DEFN
18.434783
73
0.556014
npocmaka
6b0dcd422f3a8302e92fb24017ab27c60ae42422
1,069
hpp
C++
source/utilities/linear_algebra.hpp
jgbarbosa/dgswemv2
b44fd05c4f461a301fc3695671898c91e3153d7b
[ "MIT" ]
5
2018-05-30T08:43:10.000Z
2021-12-14T18:33:10.000Z
source/utilities/linear_algebra.hpp
jgbarbosa/dgswemv2
b44fd05c4f461a301fc3695671898c91e3153d7b
[ "MIT" ]
57
2018-05-08T21:44:14.000Z
2019-11-07T17:13:30.000Z
source/utilities/linear_algebra.hpp
jgbarbosa/dgswemv2
b44fd05c4f461a301fc3695671898c91e3153d7b
[ "MIT" ]
7
2018-05-07T21:50:49.000Z
2021-04-30T14:02:02.000Z
#ifndef LINEAR_ALGEBRA_HPP #define LINEAR_ALGEBRA_HPP #ifdef USE_BLAZE #include "utilities/linear_algebra/use_blaze.hpp" #endif #ifdef USE_EIGEN #include "utilities/linear_algebra/use_eigen.hpp" #endif // Row major transform enum RowMajTrans2D : uchar { xx = 0, xy = 1, yx = 2, yy = 3 }; // The following are STL containers with aligned allocators. // These should be used whenever the template parameter is // a Static or Hybrid vector type or contains is a class // which contains Hybrid or Static vector types template <typename T> using AlignedVector = std::vector<T, AlignedAllocator<T>>; // On Macbook one can get error: // static assertion failed: std::map must have the same value_type as its allocator // static_assert(is_same<typename _Alloc::value_type, value_type>::value // A fix is adding const to Key in std::pair in AllignedAllocator // https://github.com/JakobEngel/dso/issues/111 template <typename Key, typename T, typename Compare = std::less<Key>> using AlignedMap = std::map<Key, T, Compare, AlignedAllocator<std::pair<const Key, T>>>; #endif
36.862069
88
0.76333
jgbarbosa
6b0ec23587e76e14f4f90d2d3ac332b056e87f66
3,410
cc
C++
examples/utils/tls_echo_server_demo.cc
NilFoundation/actor
b7602106c2ec254bc68592b41ccf4e5497206d43
[ "Apache-2.0" ]
1
2019-10-28T14:27:02.000Z
2019-10-28T14:27:02.000Z
examples/utils/tls_echo_server_demo.cc
NilFoundation/mtl
0beb96f4378cf10c4f6dfe55015c4b9b604529fe
[ "Apache-2.0" ]
7
2019-11-02T09:08:42.000Z
2020-03-22T14:20:49.000Z
examples/utils/tls_echo_server_demo.cc
NilFoundation/actor
b7602106c2ec254bc68592b41ccf4e5497206d43
[ "Apache-2.0" ]
1
2020-01-22T19:29:15.000Z
2020-01-22T19:29:15.000Z
//---------------------------------------------------------------------------// // Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation> // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //---------------------------------------------------------------------------// #include <cmath> #include <nil/actor/core/reactor.hh> #include <nil/actor/core/app-template.hh> #include <nil/actor/core/sleep.hh> #include <nil/actor/network/dns.hh> #include "tls_echo_server.hh" using namespace nil::actor; namespace bpo = boost::program_options; int main(int ac, char **av) { app_template app; app.add_options()("port", bpo::value<uint16_t>()->default_value(10000), "Server port")( "address", bpo::value<std::string>()->default_value("127.0.0.1"), "Server address")("cert,c", bpo::value<std::string>()->required(), "Server certificate file")("key,k", bpo::value<std::string>()->required(), "Certificate key")( "verbose,v", bpo::value<bool>()->default_value(false)->implicit_value(true), "Verbose"); return app.run_deprecated(ac, av, [&] { auto &&config = app.configuration(); uint16_t port = config["port"].as<uint16_t>(); auto crt = config["cert"].as<std::string>(); auto key = config["key"].as<std::string>(); auto addr = config["address"].as<std::string>(); auto verbose = config["verbose"].as<bool>(); std::cout << "Starting..." << std::endl; return net::dns::resolve_name(addr).then([=](net::inet_address a) { ipv4_addr ia(a, port); auto server = ::make_shared<nil::actor::sharded<echoserver>>(); return server->start(verbose) .then([=]() { return server->invoke_on_all(&echoserver::listen, socket_address(ia), sstring(crt), sstring(key), tls::client_auth::NONE); }) .handle_exception([=](auto e) { std::cerr << "Error: " << e << std::endl; engine().exit(1); }) .then([=] { std::cout << "TLS echo server running at " << addr << ":" << port << std::endl; engine().at_exit([server] { return server->stop().finally([server] {}); }); }); }); }); }
48.028169
120
0.586804
NilFoundation
6b121feeee857f871f14545a60c23eddf1a12281
2,126
cpp
C++
tests/cpp/unit/backend/dnnl/test_logical_tensor.cpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
tests/cpp/unit/backend/dnnl/test_logical_tensor.cpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
tests/cpp/unit/backend/dnnl/test_logical_tensor.cpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2020-2022 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <vector> #include <gtest/gtest.h> #include "cpp/unit/utils.hpp" #include "backend/dnnl/dnnl_backend.hpp" #include "interface/backend.hpp" #include "interface/logical_tensor.hpp" namespace impl = dnnl::graph::impl; namespace dnnl_impl = dnnl::graph::impl::dnnl_impl; namespace utils = dnnl::graph::tests::unit::utils; TEST(LogicalTensor, ImplicitEqualLayout) { using ltw = impl::logical_tensor_wrapper_t; using data_type = dnnl::memory::data_type; using format_tag = dnnl::memory::format_tag; dnnl::memory::desc md({1, 2, 3, 4}, data_type::f32, format_tag::nchw); auto layout_idx = dnnl_impl::dnnl_backend::get_singleton().set_mem_desc(md); ASSERT_TRUE(layout_idx.has_value()); auto backend_idx = dnnl_impl::dnnl_backend::get_singleton().get_id(); auto id = impl::backend_registry_t::get_singleton().encode_layout_id( layout_idx.value(), backend_idx); impl::logical_tensor_t lt1 = utils::logical_tensor_init( 0, {1, 2, 3, 4}, impl::data_type::f32, impl::layout_type::any); // set opaque layout id lt1.layout_type = impl::layout_type::opaque; lt1.layout.layout_id = id; // public layout impl::logical_tensor_t lt2 = utils::logical_tensor_init( 0, {1, 2, 3, 4}, impl::data_type::f32, impl::layout_type::strided); ASSERT_TRUE(ltw(lt1).has_same_layout_as(ltw(lt2))); }
39.37037
80
0.665099
wuxun-zhang
6b126ffee9a197a6f6fc189685efcd623cdffd09
55
cpp
C++
chapter_P/section_2/q_1.cpp
martindes01/learncpp
50c500b0cf03c9520eab0a6bdeb4556da7d13bbf
[ "MIT" ]
4
2020-08-03T15:00:00.000Z
2022-01-08T20:22:55.000Z
chapter_P/section_2/q_1.cpp
martindes01/learncpp
50c500b0cf03c9520eab0a6bdeb4556da7d13bbf
[ "MIT" ]
null
null
null
chapter_P/section_2/q_1.cpp
martindes01/learncpp
50c500b0cf03c9520eab0a6bdeb4556da7d13bbf
[ "MIT" ]
null
null
null
int main() { double highTemp[365]{ }; return 0; }
7.857143
26
0.563636
martindes01
6b13f59ca7c38d11dfaecf1b18c9610accaa090f
15,964
cc
C++
SimG4CMS/Forward/src/ZdcSD.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
SimG4CMS/Forward/src/ZdcSD.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
SimG4CMS/Forward/src/ZdcSD.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // File: ZdcSD.cc // Date: 03.01 // Description: Sensitive Detector class for Zdc // Modifications: /////////////////////////////////////////////////////////////////////////////// #include "SimG4CMS/Forward/interface/ZdcSD.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "SimG4Core/Notification/interface/TrackInformation.h" #include "G4SDManager.hh" #include "G4Step.hh" #include "G4Track.hh" #include "G4VProcess.hh" #include "G4ios.hh" #include "G4Cerenkov.hh" #include "G4ParticleTable.hh" #include "CLHEP/Units/GlobalSystemOfUnits.h" #include "CLHEP/Units/GlobalPhysicalConstants.h" #include "Randomize.hh" #include "G4Poisson.hh" ZdcSD::ZdcSD(G4String name, const DDCompactView & cpv, const SensitiveDetectorCatalog & clg, edm::ParameterSet const & p,const SimTrackManager* manager) : CaloSD(name, cpv, clg, p, manager), numberingScheme(0) { edm::ParameterSet m_ZdcSD = p.getParameter<edm::ParameterSet>("ZdcSD"); useShowerLibrary = m_ZdcSD.getParameter<bool>("UseShowerLibrary"); useShowerHits = m_ZdcSD.getParameter<bool>("UseShowerHits"); zdcHitEnergyCut = m_ZdcSD.getParameter<double>("ZdcHitEnergyCut")*GeV; verbosity = m_ZdcSD.getParameter<int>("Verbosity"); int verbn = verbosity/10; verbosity %= 10; ZdcNumberingScheme* scheme; scheme = new ZdcNumberingScheme(verbn); setNumberingScheme(scheme); edm::LogInfo("ForwardSim") << "***************************************************\n" << "* *\n" << "* Constructing a ZdcSD with name " << name <<" *\n" << "* *\n" << "***************************************************"; edm::LogInfo("ForwardSim") << "\nUse of shower library is set to " << useShowerLibrary << "\nUse of Shower hits method is set to " << useShowerHits; edm::LogInfo("ForwardSim") << "\nEnergy Threshold Cut set to " << zdcHitEnergyCut/GeV <<" (GeV)"; if(useShowerLibrary){ showerLibrary = new ZdcShowerLibrary(name, cpv, p); } } ZdcSD::~ZdcSD() { if(numberingScheme) delete numberingScheme; if(showerLibrary)delete showerLibrary; edm::LogInfo("ForwardSim") <<"end of ZdcSD\n"; } void ZdcSD::initRun(){ if(useShowerLibrary){ G4ParticleTable *theParticleTable = G4ParticleTable::GetParticleTable(); showerLibrary->initRun(theParticleTable); } hits.clear(); } bool ZdcSD::ProcessHits(G4Step * aStep, G4TouchableHistory * ) { NaNTrap( aStep ) ; if (aStep == NULL) { return true; } else { if(useShowerLibrary){ getFromLibrary(aStep); } if(useShowerHits){ if (getStepInfo(aStep)) { if (hitExists() == false && edepositEM+edepositHAD>0.) currentHit = CaloSD::createNewHit(); } } } return true; } void ZdcSD::getFromLibrary (G4Step* aStep) { bool ok = true; preStepPoint = aStep->GetPreStepPoint(); theTrack = aStep->GetTrack(); double etrack = preStepPoint->GetKineticEnergy(); int primaryID = setTrackID(aStep); hits.clear(); /* if (etrack >= zdcHitEnergyCut) { primaryID = theTrack->GetTrackID(); } else { primaryID = theTrack->GetParentID(); if (primaryID == 0) primaryID = theTrack->GetTrackID(); } */ // Reset entry point for new primary posGlobal = preStepPoint->GetPosition(); resetForNewPrimary(posGlobal, etrack); if (etrack >= zdcHitEnergyCut){ // create hits only if above threshold LogDebug("ForwardSim") //std::cout <<"----------------New track------------------------------\n" <<"Incident EnergyTrack: "<<etrack<< " MeV \n" <<"Zdc Cut Energy for Hits: "<<zdcHitEnergyCut<<" MeV \n" << "ZdcSD::getFromLibrary " <<hits.size() <<" hits for " << GetName() << " of " << primaryID << " with " << theTrack->GetDefinition()->GetParticleName() << " of " << preStepPoint->GetKineticEnergy()<< " MeV\n"; hits.swap(showerLibrary->getHits(aStep, ok)); } entrancePoint = preStepPoint->GetPosition(); for (unsigned int i=0; i<hits.size(); i++) { posGlobal = hits[i].position; entranceLocal = hits[i].entryLocal; double time = hits[i].time; unsigned int unitID = hits[i].detID; edepositHAD = hits[i].DeHad; edepositEM = hits[i].DeEM; currentID.setID(unitID, time, primaryID); // check if it is in the same unit and timeslice as the previous on if (currentID == previousID) { updateHit(currentHit); } else { currentHit = createNewHit(); } // currentHit->setPosition(hitPoint.x(),hitPoint.y(),hitPoint.z()); // currentHit->setEM(eEM); // currentHit->setHadr(eHAD); currentHit->setIncidentEnergy(etrack); // currentHit->setEntryLocal(hitEntry.x(),hitEntry.y(),hitEntry.z()); LogDebug("ForwardSim") << "ZdcSD: Final Hit number:"<<i<<"-->" <<"New HitID: "<<currentHit->getUnitID() <<" New Hit trackID: "<<currentHit->getTrackID() <<" New EM Energy: "<<currentHit->getEM()/GeV <<" New HAD Energy: "<<currentHit->getHadr()/GeV <<" New HitEntryPoint: "<<currentHit->getEntryLocal() <<" New IncidentEnergy: "<<currentHit->getIncidentEnergy()/GeV <<" New HitPosition: "<<posGlobal; } //Now kill the current track if (ok) { theTrack->SetTrackStatus(fStopAndKill); G4TrackVector tv = *(aStep->GetSecondary()); for (unsigned int kk=0; kk<tv.size(); kk++) { if (tv[kk]->GetVolume() == preStepPoint->GetPhysicalVolume()) tv[kk]->SetTrackStatus(fStopAndKill); } } } double ZdcSD::getEnergyDeposit(G4Step * aStep, edm::ParameterSet const & p ) { float NCherPhot = 0.; //std::cout<<"I go through here"<<std::endl; if (aStep == NULL) { LogDebug("ForwardSim") << "ZdcSD:: getEnergyDeposit: aStep is NULL!"; return 0; } else { // preStepPoint information G4SteppingControl stepControlFlag = aStep->GetControlFlag(); G4StepPoint* preStepPoint = aStep->GetPreStepPoint(); G4VPhysicalVolume* currentPV = preStepPoint->GetPhysicalVolume(); G4String nameVolume = currentPV->GetName(); G4ThreeVector hitPoint = preStepPoint->GetPosition(); G4ThreeVector hit_mom = preStepPoint->GetMomentumDirection(); G4double stepL = aStep->GetStepLength()/cm; G4double beta = preStepPoint->GetBeta(); G4double charge = preStepPoint->GetCharge(); // G4VProcess* curprocess = preStepPoint->GetProcessDefinedStep(); // G4String namePr = preStepPoint->GetProcessDefinedStep()->GetProcessName(); // G4LogicalVolume* lv = currentPV->GetLogicalVolume(); // G4Material* mat = lv->GetMaterial(); // G4double rad = mat->GetRadlen(); // postStepPoint information G4StepPoint* postStepPoint = aStep->GetPostStepPoint(); G4VPhysicalVolume* postPV = postStepPoint->GetPhysicalVolume(); G4String postnameVolume = postPV->GetName(); // theTrack information G4Track* theTrack = aStep->GetTrack(); G4String particleType = theTrack->GetDefinition()->GetParticleName(); G4int primaryID = theTrack->GetTrackID(); G4double entot = theTrack->GetTotalEnergy(); G4ThreeVector vert_mom = theTrack->GetVertexMomentumDirection(); G4ThreeVector localPoint = theTrack->GetTouchable()->GetHistory()->GetTopTransform().TransformPoint(hitPoint); // calculations float costheta = vert_mom.z()/sqrt(vert_mom.x()*vert_mom.x()+ vert_mom.y()*vert_mom.y()+ vert_mom.z()*vert_mom.z()); float theta = acos(std::min(std::max(costheta,float(-1.)),float(1.))); float eta = -log(tan(theta/2)); float phi = -100.; if (vert_mom.x() != 0) phi = atan2(vert_mom.y(),vert_mom.x()); if (phi < 0.) phi += twopi; // Get the total energy deposit double stepE = aStep->GetTotalEnergyDeposit(); LogDebug("ForwardSim") << "ZdcSD:: getEnergyDeposit: " <<"*****************HHHHHHHHHHHHHHHHHHHHHHHHHHLLLLLLLLLlllllllllll&&&&&&&&&&\n" << " preStepPoint: " << nameVolume << "," << stepL << "," << stepE << "," << beta << "," << charge << "\n" << " postStepPoint: " << postnameVolume << "," << costheta << "," << theta << "," << eta << "," << phi << "," << particleType << "," << primaryID; float bThreshold = 0.67; if ((beta > bThreshold) && (charge != 0) && (nameVolume == "ZDC_EMFiber" || nameVolume == "ZDC_HadFiber")) { LogDebug("ForwardSim") << "ZdcSD:: getEnergyDeposit: pass "; float nMedium = 1.4925; // float photEnSpectrDL = 10714.285714; // photEnSpectrDL = (1./400.nm-1./700.nm)*10000000.cm/nm; /* cm-1 */ float photEnSpectrDE = 1.24; // E = 2pi*(1./137.)*(eV*cm/370.)/lambda = 12.389184*(eV*cm)/lambda // Emax = 12.389184*(eV*cm)/400nm*10-7cm/nm = 3.01 eV // Emin = 12.389184*(eV*cm)/700nm*10-7cm/nm = 1.77 eV // delE = Emax - Emin = 1.24 eV float effPMTandTransport = 0.15; // Check these values float thFullRefl = 23.; float thFullReflRad = thFullRefl*pi/180.; edm::ParameterSet m_ZdcSD = p.getParameter<edm::ParameterSet>("ZdcSD"); thFibDir = m_ZdcSD.getParameter<double>("FiberDirection"); //float thFibDir = 90.; float thFibDirRad = thFibDir*pi/180.; // at which theta the point is located: // float th1 = hitPoint.theta(); // theta of charged particle in LabRF(hit momentum direction): float costh = hit_mom.z()/sqrt(hit_mom.x()*hit_mom.x()+ hit_mom.y()*hit_mom.y()+ hit_mom.z()*hit_mom.z()); float th = acos(std::min(std::max(costh,float(-1.)),float(1.))); // just in case (can do both standard ranges of phi): if (th < 0.) th += twopi; // theta of cone with Cherenkov photons w.r.t.direction of charged part.: float costhcher =1./(nMedium*beta); float thcher = acos(std::min(std::max(costhcher,float(-1.)),float(1.))); // diff thetas of charged part. and quartz direction in LabRF: float DelFibPart = fabs(th - thFibDirRad); // define real distances: float d = fabs(tan(th)-tan(thFibDirRad)); // float a = fabs(tan(thFibDirRad)-tan(thFibDirRad+thFullReflRad)); // float r = fabs(tan(th)-tan(th+thcher)); float a = tan(thFibDirRad)+tan(fabs(thFibDirRad-thFullReflRad)); float r = tan(th)+tan(fabs(th-thcher)); // std::cout.testOut << " d=|tan(" << th << ")-tan(" << thFibDirRad << ")| " // << "=|" << tan(th) << "-" << tan(thFibDirRad) << "| = " << d; // std::cout.testOut << " a=tan(" << thFibDirRad << ")=" << tan(thFibDirRad) // << " + tan(|" << thFibDirRad << " - " << thFullReflRad << "|)=" // << tan(fabs(thFibDirRad-thFullReflRad)) << " = " << a; // std::cout.testOut << " r=tan(" << th << ")=" << tan(th) << " + tan(|" << th // << " - " << thcher << "|)=" << tan(fabs(th-thcher)) << " = " << r; // define losses d_qz in cone of full reflection inside quartz direction float d_qz = -1; float variant = -1; // if (d > (r+a)) if (DelFibPart > (thFullReflRad + thcher) ) { variant = 0.; d_qz = 0.; } else { // if ((DelFibPart + thcher) < thFullReflRad ) [(d+r) < a] if ((th + thcher) < (thFibDirRad+thFullReflRad) && (th - thcher) > (thFibDirRad-thFullReflRad) ) { variant = 1.; d_qz = 1.; } else { // if ((thcher - DelFibPart ) > thFullReflRad ) [(r-d) > a] if ((thFibDirRad + thFullReflRad) < (th + thcher) && (thFibDirRad - thFullReflRad) > (th - thcher) ) { variant = 2.; d_qz = 0.; } else { // if ((thcher + DelFibPart ) > thFullReflRad && thcher < (DelFibPart+thFullReflRad) ) { [(r+d) > a && (r-d) < a)] variant = 3.; // d_qz is calculated below // use crossed length of circles(cone projection) - dC1/dC2 : float arg_arcos = 0.; float tan_arcos = 2.*a*d; if (tan_arcos != 0.) arg_arcos =(r*r-a*a-d*d)/tan_arcos; // std::cout.testOut << " d_qz: " << r << "," << a << "," << d << " " << tan_arcos << " " << arg_arcos; arg_arcos = fabs(arg_arcos); // std::cout.testOut << "," << arg_arcos; float th_arcos = acos(std::min(std::max(arg_arcos,float(-1.)),float(1.))); // std::cout.testOut << " " << th_arcos; d_qz = th_arcos/pi/2.; // std::cout.testOut << " " << d_qz; d_qz = fabs(d_qz); // std::cout.testOut << "," << d_qz; } } } // std::cout<< std::endl; double meanNCherPhot = 0.; G4int poissNCherPhot = 0; if (d_qz > 0) { meanNCherPhot = 370.*charge*charge*( 1. - 1./(nMedium*nMedium*beta*beta) ) * photEnSpectrDE * stepL; // dLamdX: meanNCherPhot = (2.*pi/137.)*charge*charge* // ( 1. - 1./(nMedium*nMedium*beta*beta) ) * photEnSpectrDL * stepL; poissNCherPhot = (G4int) G4Poisson(meanNCherPhot); if (poissNCherPhot < 0) poissNCherPhot = 0; // NCherPhot = meanNCherPhot; NCherPhot = poissNCherPhot * effPMTandTransport * d_qz; } LogDebug("ForwardSim") << "ZdcSD:: getEnergyDeposit: gED: " << stepE << "," << costh << "," << th << "," << costhcher << "," << thcher << "," << DelFibPart << "," << d << "," << a << "," << r << "," << hitPoint << "," << hit_mom << "," << stepControlFlag << "," << entot << "," << vert_mom << "," << localPoint << "," << charge << "," << beta << "," << stepL << "," << d_qz << "," << variant << "," << meanNCherPhot << "," << poissNCherPhot << "," << NCherPhot; // --constants----------------- // << "," << photEnSpectrDE // << "," << nMedium // << "," << bThreshold // << "," << thFibDirRad // << "," << thFullReflRad // << "," << effPMTandTransport // --other variables----------- // << "," << curprocess // << "," << nameProcess // << "," << name // << "," << rad // << "," << mat } else { // determine failure mode: beta, charge, and/or nameVolume if (beta <= bThreshold) LogDebug("ForwardSim") << "ZdcSD:: getEnergyDeposit: fail beta=" << beta; if (charge == 0) LogDebug("ForwardSim") << "ZdcSD:: getEnergyDeposit: fail charge=0"; if ( !(nameVolume == "ZDC_EMFiber" || nameVolume == "ZDC_HadFiber") ) LogDebug("ForwardSim") << "ZdcSD:: getEnergyDeposit: fail nv=" << nameVolume; } return NCherPhot; } } uint32_t ZdcSD::setDetUnitId(G4Step* aStep) { uint32_t returnNumber = 0; if(numberingScheme != 0)returnNumber = numberingScheme->getUnitID(aStep); // edm: return (numberingScheme == 0 ? 0 : numberingScheme->getUnitID(aStep)); return returnNumber; } void ZdcSD::setNumberingScheme(ZdcNumberingScheme* scheme) { if (scheme != 0) { edm::LogInfo("ForwardSim") << "ZdcSD: updates numbering scheme for " << GetName(); if (numberingScheme) delete numberingScheme; numberingScheme = scheme; } } int ZdcSD::setTrackID (G4Step* aStep) { theTrack = aStep->GetTrack(); double etrack = preStepPoint->GetKineticEnergy(); TrackInformation * trkInfo = (TrackInformation *)(theTrack->GetUserInformation()); int primaryID = trkInfo->getIDonCaloSurface(); if (primaryID == 0) { #ifdef DebugLog LogDebug("ZdcSD") << "ZdcSD: Problem with primaryID **** set by force " << "to TkID **** " << theTrack->GetTrackID(); #endif primaryID = theTrack->GetTrackID(); } if (primaryID != previousID.trackID()) resetForNewPrimary(preStepPoint->GetPosition(), etrack); return primaryID; }
36.036117
127
0.574668
pasmuss
6b19e9dd6ec86dfbf79807863c05988b5e783468
1,031
cpp
C++
src/ast/transform/Transformer.cpp
thomas-seed/souffle
2157ead5354a59979bf6b6adade47bb24a098f24
[ "UPL-1.0" ]
null
null
null
src/ast/transform/Transformer.cpp
thomas-seed/souffle
2157ead5354a59979bf6b6adade47bb24a098f24
[ "UPL-1.0" ]
null
null
null
src/ast/transform/Transformer.cpp
thomas-seed/souffle
2157ead5354a59979bf6b6adade47bb24a098f24
[ "UPL-1.0" ]
null
null
null
/* * Souffle - A Datalog Compiler * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved * Licensed under the Universal Permissive License v 1.0 as shown at: * - https://opensource.org/licenses/UPL * - <souffle root>/licenses/SOUFFLE-UPL.txt */ /************************************************************************ * * @file Transformer.cpp * * Defines the interface for AST transformation passes. * ***********************************************************************/ #include "ast/transform/Transformer.h" #include "ast/TranslationUnit.h" #include "reports/ErrorReport.h" namespace souffle { bool AstTransformer::apply(AstTranslationUnit& translationUnit) { // invoke the transformation bool changed = transform(translationUnit); if (changed) { translationUnit.invalidateAnalyses(); } /* Abort evaluation of the program if errors were encountered */ translationUnit.getErrorReport().exitIfErrors(); return changed; } } // end of namespace souffle
27.131579
73
0.616877
thomas-seed
6b1b1f5a8fb1402db3de809f1ada559382cf487c
1,374
cpp
C++
src/bkcommon/response_impl.cpp
titilima/blink
2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad
[ "MIT" ]
13
2020-04-21T13:14:00.000Z
2021-11-13T14:55:12.000Z
src/bkcommon/response_impl.cpp
titilima/blink
2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad
[ "MIT" ]
null
null
null
src/bkcommon/response_impl.cpp
titilima/blink
2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad
[ "MIT" ]
4
2020-04-21T13:15:43.000Z
2021-11-13T14:55:00.000Z
// ------------------------------------------------- // BlinKit - BkCommon Library // ------------------------------------------------- // File Name: response_impl.cpp // Description: Response Base Classes // Author: Ziming Li // Created: 2020-06-21 // ------------------------------------------------- // Copyright (C) 2020 MingYang Software Technology. // ------------------------------------------------- #include "response_impl.h" #include "bkcommon/buffer_impl.hpp" namespace BlinKit { ResponseBase::ResponseBase(const std::string &URL) : m_refCount(1), m_URL(URL) { } int ResponseBase::GetData(int data, BkBuffer *dst) const { switch (data) { case BK_RESPONSE_CURRENT_URL: case BK_RESPONSE_ORIGINAL_URL: BufferImpl::Set(dst, m_URL); break; case BK_RESPONSE_BODY: BufferImpl::Set(dst, m_body); break; default: NOTREACHED(); return BK_ERR_NOT_FOUND; } return BK_ERR_SUCCESS; } void ResponseBase::HijackBody(const void *newBody, size_t length) { m_body.resize(length); if (length > 0) memcpy(m_body.data(), newBody, length); } void ResponseBase::Release(void) { if (0 == --m_refCount) delete this; } ResponseImpl* ResponseBase::Retain(void) { ++m_refCount; return this; } } // namespace BlinKit
22.9
78
0.540757
titilima
6b1b2f6917787ee1ba5720ab2007f919be7719ef
2,521
cc
C++
src/words.cc
pgul/diskpoll
5512aba821fa432dcc2b0c5f3917b8353dd9546c
[ "Unlicense" ]
2
2018-01-14T03:08:09.000Z
2021-04-11T11:29:44.000Z
src/words.cc
huskyproject/diskpoll
0315ac783a759d60ae84092316ab4da67a1cd6d9
[ "Unlicense" ]
null
null
null
src/words.cc
huskyproject/diskpoll
0315ac783a759d60ae84092316ab4da67a1cd6d9
[ "Unlicense" ]
null
null
null
#ifdef INCS_NEED_DOT_H #include <ctype.h> #include <stdlib.h> /* NULL */ #else #include <ctype> #include <stdlib> /* NULL */ #endif #include "words.h" #include "cerror.h" TWords::TWords(char *cpWord) { char *cp; int i; if (cpWord==NULL) { nWords=0; } else { for (cp=cpWord;(*cp)&&(isspace(*cp));cp++); if (!(*cp)) { nWords=0; } else { nWords=1; for (;*cp;) { if (*(cp=getNextWord(cp))) { nWords++; cp++; } } } } if (nWords>0) { cpWords=new char*[nWords+1]; CheckPointer(cpWords,"TWords::TWords()"); for (cp=cpWord;(*cp)&&(isspace(*cp));cp++); for (i=0;*cp;i++,cp=getNextWord(cp+1)) { char *cp2; int len; for (cp2=cp,len=0;(*cp2)&&(!isspace(*cp2));cp2++,len++); cpWords[i]=new char[len+1]; CheckPointer(cpWords[i],"TWords::TWords()"); for (cp2=cp,len=0;(*cp2)&&(!isspace(*cp2));cp2++,len++) { cpWords[i][len]=*cp2; } cpWords[i][len]='\0'; } CheckCond(i==nWords,"TWords algorithm error"); } else cpWords=0; } TWords::~TWords() { int i; for (i=0;i<nWords;i++) delete[] cpWords[i]; if (cpWords) delete cpWords; } char *TWords::getWord(int nr) { if (nr<getNWords()) return cpWords[nr]; else return 0; } int TWords::getNWords(void) { return nWords; } char *TWords::getNextWord(char *cpWord) { char *cp=cpWord; for (;(*cp)&&(!isspace(*cp));cp++); for (;(*cp)&&(isspace(*cp));cp++); return cp; } TWords::TWords(const TWords&r) { int i; nWords=r.nWords; if (nWords) { cpWords=new char*[nWords+1]; CheckPointer(cpWords,"TWords::TWords()"); for (i=0;i<nWords;i++) { cpWords[i]=new char[strlen(r.cpWords[i])+1]; CheckPointer(cpWords[i],"TWords::TWords()"); strcpy(cpWords[i],r.cpWords[i]); } } else cpWords=0; } TWords& TWords::operator=(const TWords&r) { int i; for (i=0;i<nWords;i++) delete[] cpWords[i]; if (cpWords) delete cpWords; nWords=r.nWords; if (nWords) { cpWords=new char*[nWords+1]; CheckPointer(cpWords,"TWords::operator=()"); for (i=0;i<nWords;i++) { cpWords[i]=new char[strlen(r.cpWords[i])+1]; CheckPointer(cpWords[i],"TWords::operator=()"); strcpy(cpWords[i],r.cpWords[i]); } } else cpWords=0; return (*this); }
20.330645
64
0.513288
pgul
6b20ae02a93e5557b30c89e5a3bb43590117ea79
5,892
cpp
C++
src/AHZPapyrusMoreHud.cpp
AlexGreat007/moreHUDSE
b5eb07066ebcb3ab6e00931ac81a8005c1df7bad
[ "MIT" ]
1
2018-10-15T02:15:58.000Z
2018-10-15T02:15:58.000Z
src/AHZPapyrusMoreHud.cpp
AlexGreat007/moreHUDSE
b5eb07066ebcb3ab6e00931ac81a8005c1df7bad
[ "MIT" ]
3
2017-12-08T00:12:33.000Z
2022-03-31T02:32:23.000Z
src/AHZPapyrusMoreHud.cpp
AlexGreat007/moreHUDSE
b5eb07066ebcb3ab6e00931ac81a8005c1df7bad
[ "MIT" ]
4
2021-01-20T17:01:39.000Z
2021-12-11T07:03:19.000Z
#include "PCH.h" #include "AHZPapyrusMoreHud.h" #include "version.h" #include <mutex> using AhzIconItemCache = std::map<uint32_t, RE::BSFixedString>; using AhzIconFormListCache = std::map<std::string, RE::BGSListForm*>; static AhzIconItemCache s_ahzRegisteredIcons; static AhzIconFormListCache s_ahzRegisteredIconFormLists; static std::recursive_mutex mtx; auto PapyrusMoreHud::GetVersion([[maybe_unused]] RE::StaticFunctionTag* base) -> uint32_t { auto version = Version::ASINT; logger::trace("GetVersion: {}", version); return version; } void PapyrusMoreHud::RegisterIconFormList(RE::StaticFunctionTag* base, RE::BSFixedString iconName, RE::BGSListForm* list) { logger::trace("RegisterIconFormList"); std::lock_guard<std::recursive_mutex> lock(mtx); if (!list) return; if (!IsIconFormListRegistered(base, iconName)) { s_ahzRegisteredIconFormLists.insert(AhzIconFormListCache::value_type(iconName.c_str(), list)); } } void PapyrusMoreHud::UnRegisterIconFormList(RE::StaticFunctionTag* base, RE::BSFixedString iconName) { logger::trace("UnRegisterIconFormList"); std::lock_guard<std::recursive_mutex> lock(mtx); if (IsIconFormListRegistered(base, iconName)) { s_ahzRegisteredIconFormLists.erase(iconName.c_str()); } } auto PapyrusMoreHud::IsIconFormListRegistered_Internal(std::string iconName) -> bool { logger::trace("IsIconFormListRegistered_Internal"); std::lock_guard<std::recursive_mutex> lock(mtx); // Create an iterator of map AhzIconFormListCache::iterator it; if (s_ahzRegisteredIconFormLists.empty()) return false; // Find the element with key itemID it = s_ahzRegisteredIconFormLists.find(iconName); // Check if element exists in map or not return (it != s_ahzRegisteredIconFormLists.end()); } auto PapyrusMoreHud::IsIconFormListRegistered([[maybe_unused]] RE::StaticFunctionTag* base, RE::BSFixedString iconName) -> bool { return IsIconFormListRegistered_Internal(iconName.c_str()); } auto PapyrusMoreHud::HasForm(std::string iconName, uint32_t formId) -> bool { logger::trace("HasForm"); std::lock_guard<std::recursive_mutex> lock(mtx); if (IsIconFormListRegistered_Internal(iconName)) { auto formList = s_ahzRegisteredIconFormLists[iconName]; if (!formId) return false; auto formFromId = RE::TESForm::LookupByID(formId); if (!formFromId) return false; return formList->HasForm(formFromId); } return false; } auto PapyrusMoreHud::IsIconItemRegistered([[maybe_unused]] RE::StaticFunctionTag* base, uint32_t itemID) -> bool { logger::trace("IsIconItemRegistered"); std::lock_guard<std::recursive_mutex> lock(mtx); // Create an iterator of map AhzIconItemCache::iterator it; // Find the element with key itemID it = s_ahzRegisteredIcons.find(itemID); // Check if element exists in map or not return (it != s_ahzRegisteredIcons.end()); } void PapyrusMoreHud::AddIconItem(RE::StaticFunctionTag* base, uint32_t itemID, RE::BSFixedString iconName) { logger::trace("AddIconItem"); std::lock_guard<std::recursive_mutex> lock(mtx); if (!IsIconItemRegistered(base, itemID)) { s_ahzRegisteredIcons.insert(AhzIconItemCache::value_type(itemID, iconName)); } } void PapyrusMoreHud::RemoveIconItem(RE::StaticFunctionTag* base, uint32_t itemID) { logger::trace("RemoveIconItem"); std::lock_guard<std::recursive_mutex> lock(mtx); if (IsIconItemRegistered(base, itemID)) { s_ahzRegisteredIcons.erase(itemID); } } void PapyrusMoreHud::AddIconItems(RE::StaticFunctionTag* base, std::vector<uint32_t> itemIDs, std::vector<RE::BSFixedString> iconNames) { logger::trace("AddIconItems"); std::lock_guard<std::recursive_mutex> lock(mtx); if (itemIDs.size() != iconNames.size()) { return; } for (uint32_t i = 0; i < itemIDs.size(); i++) { uint32_t itemID; RE::BSFixedString iconName; itemID = itemIDs[i]; iconName = iconNames[i]; AddIconItem(base, itemID, iconName); } } void PapyrusMoreHud::RemoveIconItems(RE::StaticFunctionTag* base, std::vector<uint32_t> itemIDs) { logger::trace("RemoveIconItem"); std::lock_guard<std::recursive_mutex> lock(mtx); for (uint32_t i = 0; i < itemIDs.size(); i++) { uint32_t itemID; itemID = itemIDs[i]; if (itemID) { RemoveIconItem(base, itemID); } } } auto PapyrusMoreHud::GetIconName(uint32_t itemID) -> std::string { logger::trace("GetIconName"); std::string iconName(""); std::lock_guard<std::recursive_mutex> lock(mtx); if (IsIconItemRegistered(nullptr, itemID)) { iconName.append(s_ahzRegisteredIcons[itemID].c_str()); } return iconName; } auto PapyrusMoreHud::RegisterFunctions(RE::BSScript::IVirtualMachine* a_vm) -> bool { a_vm->RegisterFunction("GetVersion", "AhzMoreHud", GetVersion); a_vm->RegisterFunction("IsIconItemRegistered", "AhzMoreHud", IsIconItemRegistered); a_vm->RegisterFunction("AddIconItem", "AhzMoreHud", AddIconItem); a_vm->RegisterFunction("RemoveIconItem", "AhzMoreHud", RemoveIconItem); a_vm->RegisterFunction("AddIconItems", "AhzMoreHud", AddIconItems); a_vm->RegisterFunction("RemoveIconItems", "AhzMoreHud", RemoveIconItems); a_vm->RegisterFunction("RegisterIconFormList", "AhzMoreHud", RegisterIconFormList); a_vm->RegisterFunction("UnRegisterIconFormList", "AhzMoreHud", UnRegisterIconFormList); a_vm->RegisterFunction("IsIconFormListRegistered", "AhzMoreHud", IsIconFormListRegistered); return true; }
33.862069
136
0.684487
AlexGreat007
6b221aa38ce7f3b756f7b5ea2ec4ead3a9e76970
645
cpp
C++
Code/low_read.cpp
hewei-nju/TCP-IP-Network-Programming
0685f0cc60e3af49093d3aa5189c7eafda5af017
[ "MIT" ]
null
null
null
Code/low_read.cpp
hewei-nju/TCP-IP-Network-Programming
0685f0cc60e3af49093d3aa5189c7eafda5af017
[ "MIT" ]
null
null
null
Code/low_read.cpp
hewei-nju/TCP-IP-Network-Programming
0685f0cc60e3af49093d3aa5189c7eafda5af017
[ "MIT" ]
null
null
null
/** @author heweibright@gmail.com * @date 2021/8/28 11:20 * Copyright (c) All rights reserved. */ #include <iostream> #include <unistd.h> #include <fcntl.h> const int BUF_SIZE = 100; void error_handling(const char* msg) { std::cerr << msg << '\n'; std::terminate(); } int main() { int fd; char buf[BUF_SIZE]; fd = open("data.txt", O_RDONLY); if (fd == -1) error_handling("open() error!"); std::cout << "file descriptor: " << fd << '\n'; if (read(fd, buf, sizeof(buf)) == -1) error_handling("read() error!"); std::cout << "file data: " << buf << '\n'; close(fd); return 0; }
19.545455
51
0.555039
hewei-nju
6b29828ca93626ee89c5bc71a8f7205211d75a77
2,457
cpp
C++
src/CLIOR.cpp
CominLab/CLIOR
1c016f4bc48c59e3826ec1fbd7ef39c0b08c10e7
[ "MIT" ]
null
null
null
src/CLIOR.cpp
CominLab/CLIOR
1c016f4bc48c59e3826ec1fbd7ef39c0b08c10e7
[ "MIT" ]
null
null
null
src/CLIOR.cpp
CominLab/CLIOR
1c016f4bc48c59e3826ec1fbd7ef39c0b08c10e7
[ "MIT" ]
null
null
null
#include "Reassignment.h" using namespace std; int main(int argc, char* argv[]) { string empty = ""; string dir_output = "output/"; PairedEnd_G_C input; FilesScan scans; Mode_CLIOR m_clior; vector<string> grp_cls_files; vector<string> d_files; for(int i=1;i<argc;i++) { if(strcmp(argv[i], "-si") == 0) { grp_cls_files.push_back(argv[++i]); grp_cls_files.push_back(argv[++i]); input.init(grp_cls_files[0], grp_cls_files[1], empty, empty); if(!input.isCorrect()) { cerr<<"Please enter input files for single-end dataset: -si <AbsPathGroupsFile> <AbsPathClassificationFile>"<<endl<<flush; return 0; } } else if(strcmp(argv[i], "-pi") == 0) { grp_cls_files.push_back(argv[++i]); grp_cls_files.push_back(argv[++i]); grp_cls_files.push_back(argv[++i]); grp_cls_files.push_back(argv[++i]); input.init(grp_cls_files[0], grp_cls_files[1], grp_cls_files[2], grp_cls_files[3]); if(!input.isCorrect()) { cerr<<"Please enter input files for paired-end dataset: -pi <AbsPathGroupsFile_1> <AbsPathClassificationFile_1> <AbsPathGroupsFile_2> <AbsPathClassificationFile_2>"<<endl<<flush; return 0; } } else if(strcmp(argv[i], "-dirOutput") == 0) { dir_output.assign(argv[++i]); if(dir_output == "") { cerr<<"Please enter an output directory if you specify -dirOutput"<<endl<<flush; return 0; } } else if(strcmp(argv[i], "-mod_weight") == 0) { size_t val = atoi(argv[++i]); if(val >= Last_Weight) { cerr<<"Please enter a weight mode correct: from 0 to "<< Last_Weight-1 << "if you specify -mod_weight"<<endl<<flush; return 0; } m_clior.m_weight = Mode_Weight(val); } else if(strcmp(argv[i], "-mod_win") == 0) { size_t val = atoi(argv[++i]); if(val >= Last_Win) { cerr<<"Please enter a win mode correct: from 0 to "<< Last_Win-1 << "if you specify -mod_win"<<endl<<flush; return 0; } m_clior.m_win = Mode_Win(val); } else if(strcmp(argv[i], "-mod_assign") == 0) { size_t val = atoi(argv[++i]); if(val >= Last_Assign) { cerr<<"Please enter a assign mode correct: from 0 to "<< Last_Assign-1 << "if you specify -mod_assign"<<endl<<flush; return 0; } m_clior.m_assign = Mode_Assign(val); } } createDirAndSubDir(dir_output); if(input.isCorrect()) { Reassignment reass(input, dir_output); reass.compute_and_save_clior(m_clior); reass.save_info_reassignment(); } return 0; }
27.606742
182
0.648759
CominLab
6b2b8c5338c96c02fbea6db313810877e2a96fd7
18,126
cpp
C++
src/core/test/graph/partial_execution.cpp
kxz18/MegEngine
88c1eedbd716805244b35bdda57c3cea5efe734d
[ "Apache-2.0" ]
3
2021-08-08T12:55:53.000Z
2021-12-10T06:01:04.000Z
src/core/test/graph/partial_execution.cpp
kxz18/MegEngine
88c1eedbd716805244b35bdda57c3cea5efe734d
[ "Apache-2.0" ]
6
2020-04-24T08:52:06.000Z
2021-08-16T06:38:23.000Z
src/core/test/graph/partial_execution.cpp
kxz18/MegEngine
88c1eedbd716805244b35bdda57c3cea5efe734d
[ "Apache-2.0" ]
null
null
null
/** * \file src/core/test/graph/partial_execution.cpp * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include "megbrain/graph.h" #if MGB_ENABLE_PARTIAL_EXECUTION #include "megbrain/opr/basic_arith.h" #include "megbrain/opr/io.h" #include "megbrain/opr/tensor_manip.h" #include "megbrain/opr/utility.h" #include "megbrain/test/helper.h" #include "megbrain/utils/timer.h" using namespace mgb; namespace mgb { namespace cg { class ComputingGraphImpl { public: class MultiPartCompiler { public: static SmallVector<Typeinfo*> test_get_internal_opr_types(); }; }; } // namespace cg } // namespace mgb // declare some opr types so ASSERT_OPR could work namespace mgb { namespace opr { namespace { static const SmallVector<Typeinfo*>& internal_opr_types() { static SmallVector<Typeinfo*> ret = cg::ComputingGraphImpl:: MultiPartCompiler::test_get_internal_opr_types(); return ret; } #define DEF(name, idx) \ struct name { \ static Typeinfo* typeinfo() { return internal_opr_types().at(idx); } \ } DEF(ShapeProvider, 0); DEF(DeviceDataProvider, 1); DEF(EmptyExecuteOpr, 2); DEF(VarSinkOpr, 3); #undef DEF } // anonymous namespace } // namespace opr } // namespace mgb namespace { ThinHashMap<Typeinfo*, size_t> get_opr_types( const std::unique_ptr<cg::AsyncExecutable>& func) { ThinHashMap<Typeinfo*, size_t> ret; cg::DepOprIter opr_iter{ [&ret](cg::OperatorNodeBase* opr) { ++ret[opr->dyn_typeinfo()]; }}; auto on_opr = [&opr_iter](cg::OperatorNodeBase* opr) { opr_iter.add(opr); return true; }; func->iter_opr_seq(on_opr); return ret; } #define ASSERT_OPR(_set, _type, _num) \ ASSERT_EQ(_num##u, _set.at(opr::_type::typeinfo())) #define ASSERT_NO_OPR(_set, _type) \ ASSERT_EQ(0u, _set.count(opr::_type::typeinfo())) class TrackableDynamicMemAlloc final : public cg::DeviceMemoryAllocator { std::atomic_size_t m_nr_alive{0}; public: void alloc_dynamic(VarNode*, DeviceTensorStorage& dest, size_t size) override { auto ptr = dest.comp_node().alloc_device(size); ++m_nr_alive; auto del = [ this, cn = dest.comp_node() ](void* ptr) { cn.free_device(ptr); --m_nr_alive; }; dest.reset(dest.comp_node(), size, {static_cast<dt_byte*>(ptr), del}); } size_t nr_alive() const { return m_nr_alive; } ~TrackableDynamicMemAlloc() { EXPECT_EQ(0u, nr_alive()); } }; } // anonymous namespace TEST(TestPartialExecution, Simple) { auto graph = ComputingGraph::make(); HostTensorGenerator<> gen; auto host_x = gen({2, 3}), host_delta = gen({1}); int call0 = 0, call1 = 0; auto make_expect = [&host_x](float delta) { HostTensorND hv; auto ptr = hv.copy_from(*host_x).ptr<float>(); for (int i = 0; i < 6; ++i) ptr[i] += delta; return hv; }; auto cb0 = [&call0, &make_expect](DeviceTensorND& dv) { HostTensorND hv; hv.copy_from(dv).sync(); MGB_ASSERT_TENSOR_EQ(make_expect(0), hv); ++call0; }; auto cb1 = [&call1, &make_expect](DeviceTensorND& dv) { HostTensorND hv; hv.copy_from(dv).sync(); MGB_ASSERT_TENSOR_EQ(make_expect(1), hv); ++call1; }; host_delta->ptr<float>()[0] = -1; auto x = opr::Host2DeviceCopy::make(*graph, host_x), delta = opr::Host2DeviceCopy::make(*graph, host_delta), y0 = opr::CallbackInjector::make(x, cb0), y1 = opr::CallbackInjector::make(x + delta, cb1) + delta; // it should execute in part2 albeit with high priority set_priority(delta, -100); HostTensorND host_y1; auto funcs = graph->compile_multi_part( {{{y0, {}}}, {make_callback_copy(y1, host_y1)}}); ASSERT_EQ(2u, funcs.size()); for (int i = 0; i < 4; ++i) { *host_x = *gen({2, 3}); ASSERT_EQ(0, call0); funcs[0]->execute(); ASSERT_TRUE(host_y1.empty()); ASSERT_EQ(1, call0); ASSERT_EQ(0, call1); host_delta->ptr<float>()[0] = 1; funcs[1]->execute(); ASSERT_EQ(1, call0); ASSERT_EQ(1, call1); MGB_ASSERT_TENSOR_EQ(make_expect(2), host_y1); call0 = call1 = 0; host_y1.resize({}); } } TEST(TestPartialExecution, AddUpdate) { auto graph = ComputingGraph::make(); HostTensorGenerator<> gen; auto dv = std::make_shared<DeviceTensorND>(); auto hv = gen({2, 3}); dv->copy_from(*hv); auto make_expect = [&hv](float delta) { HostTensorND ret; auto ptr = ret.copy_from(*hv).ptr<float>(); for (int i = 0; i < 6; ++i) ptr[i] += delta; return ret; }; auto cur_dv = [&dv]() { return HostTensorND{}.copy_from(*dv).sync(); }; auto x = opr::SharedDeviceTensor::make(*graph, dv), y0 = x + 2.3f, y1 = opr::AddUpdate::make(x, x.make_scalar(-1.2f)) + 0.3f; HostTensorND host_y0, host_y1; auto funcs = graph->compile_multi_part({{make_callback_copy(y0, host_y0)}, {make_callback_copy(y1, host_y1)}}); funcs[0]->execute(); MGB_ASSERT_TENSOR_EQ(make_expect(2.3), host_y0); MGB_ASSERT_TENSOR_EQ(*hv, cur_dv()); funcs[1]->execute(); MGB_ASSERT_TENSOR_EQ(make_expect(-1.2f), cur_dv()); MGB_ASSERT_TENSOR_EQ(make_expect(-0.9f), host_y1); } TEST(TestPartialExecution, CompOrderDep) { constexpr float SLEEP_TIME = 0.3; auto graph = ComputingGraph::make(); graph->options().var_sanity_check_first_run = false; auto cns = load_multiple_xpus(2); HostTensorGenerator<> gen; auto dv = std::make_shared<DeviceTensorND>(); auto hv = gen({2, 3}, cns[0]), host_bias = gen({1}, cns[1]); dv->copy_from(*hv).sync(); auto make_expect = [&hv](float delta) { HostTensorND ret; auto ptr = ret.copy_from(*hv).ptr<float>(); for (int i = 0; i < 6; ++i) ptr[i] += delta; return ret; }; auto cur_dv = [&dv]() { return HostTensorND{}.copy_from(*dv).sync(); }; auto x = opr::SharedDeviceTensor::make(*graph, dv), bias = opr::Host2DeviceCopy::make(*graph, host_bias), y0 = opr::Copy::make(x, cns[1]) + opr::Sleep::make(bias, SLEEP_TIME), y1 = opr::AddUpdate::make(x, x.make_scalar(-1.2f)) + 0.3f; HostTensorND host_y0, host_y1; auto funcs = graph->compile_multi_part({{make_callback_copy(y0, host_y0, false)}, {make_callback_copy(y1, host_y1)}}); RealTimer timer; funcs[0]->execute(); // sleep kernel in cuda is easily affected by the frequency change of GPU, // so we just print warn log instead assert. more refer to // XPU-226 auto use_time = timer.get_secs(); if (use_time >= SLEEP_TIME / 2) { mgb_log_warn("expect time [%f < %f], got %f", use_time, SLEEP_TIME / 2, use_time); } MGB_ASSERT_TENSOR_EQ(*hv, cur_dv()); ASSERT_EQ(hv->shape(), host_y0.shape()); funcs[1]->execute(); // sleep kernel in cuda is easily affected by the frequency change of GPU, // so we just print warn log instead assert. more refer to // XPU-226 use_time = timer.get_secs(); if (use_time <= SLEEP_TIME) { mgb_log_warn("expect time [%f > %f], got %f", use_time, SLEEP_TIME, use_time); } MGB_ASSERT_TENSOR_EQ(make_expect(-1.2f), cur_dv()); MGB_ASSERT_TENSOR_EQ(make_expect(-0.9f), host_y1); host_y0.sync(); MGB_ASSERT_TENSOR_EQ(make_expect(host_bias->ptr<float>()[0]), host_y0); } TEST(TestPartialExecution, MultiDepType) { auto graph = ComputingGraph::make(); HostTensorGenerator<> gen; auto host_x = gen({2, 3}), host_y = gen({6}); auto p0_x = opr::Host2DeviceCopy::make(*graph, host_x).rename("x"), p0_y = opr::Host2DeviceCopy::make(*graph, host_y).rename("y"), p0_y_shp = p0_y.symshape(), p0_z = p0_x.reshape(p0_y_shp) + p0_y, // host value dep p1_z = opr::MarkDynamicVar::make(p0_x).reshape(p0_y_shp) + p0_y, // shape dep p2_z = p0_x.reshape(p0_z.symshape()) + p0_y; HostTensorND host_z0, host_z1, host_z2; auto funcs = graph->compile_multi_part({{make_callback_copy(p0_z, host_z0)}, {make_callback_copy(p1_z, host_z1)}, {make_callback_copy(p2_z, host_z2)}}); auto oprs_1 = get_opr_types(funcs[1]), oprs_2 = get_opr_types(funcs[2]); ASSERT_OPR(oprs_1, Host2DeviceCopy, 1); ASSERT_OPR(oprs_1, MarkDynamicVar, 1); ASSERT_OPR(oprs_1, DeviceDataProvider, 2); ASSERT_NO_OPR(oprs_1, ShapeProvider); ASSERT_NO_OPR(oprs_1, GetVarShape); ASSERT_NO_OPR(oprs_2, Host2DeviceCopy); ASSERT_OPR(oprs_2, GetVarShape, 1); ASSERT_OPR(oprs_2, DeviceDataProvider, 2); ASSERT_OPR(oprs_2, Reshape, 1); ASSERT_OPR(oprs_2, ShapeProvider, 1); for (size_t i = 0; i < 3; ++i) { funcs[0]->execute(); auto host_z0_cp = host_z0; host_z0.resize({}); ASSERT_TRUE(host_z1.empty()); funcs[1]->execute(); ASSERT_TRUE(host_z2.empty()); funcs[2]->execute(); ASSERT_TRUE(host_z0.empty()); MGB_ASSERT_TENSOR_EQ(host_z0_cp, host_z1); MGB_ASSERT_TENSOR_EQ(host_z0_cp, host_z2); host_z1.resize({}); host_z2.resize({}); *host_x = *gen({i + 5, 3}); *host_y = *gen({(i + 5) * 3}); } } TEST(TestPartialExecution, InternalValue) { auto graph = ComputingGraph::make(); HostTensorGenerator<> gen; auto host_x = gen({2, 3}); auto x = opr::Host2DeviceCopy::make(*graph, host_x), y = x + 1, z = x * 2; HostTensorND host_y0, host_y1, host_z; auto funcs = graph->compile_multi_part( {{make_callback_copy(y, host_y0)}, {make_callback_copy(y, host_y1), make_callback_copy(z, host_z)}}); funcs[0]->execute(); ASSERT_FALSE(host_y0.empty()); ASSERT_TRUE(host_y1.empty()); funcs[1]->execute(); ASSERT_FALSE(host_y1.empty()); auto oprs_0 = get_opr_types(funcs[0]), oprs_1 = get_opr_types(funcs[1]); ASSERT_OPR(oprs_0, Elemwise, 1); ASSERT_OPR(oprs_1, Elemwise, 1); ASSERT_OPR(oprs_1, DeviceDataProvider, 2); auto px = host_x->ptr<float>(), py0 = host_y0.ptr<float>(), py1 = host_y1.ptr<float>(), pz = host_z.ptr<float>(); for (size_t i = 0; i < 6; ++i) { auto xv = px[i]; ASSERT_EQ(xv + 1.f, py0[i]); ASSERT_EQ(xv + 1.f, py1[i]); ASSERT_EQ(xv * 2, pz[i]); } } TEST(TestPartialExecution, ValueReuse) { auto graph = ComputingGraph::make(); HostTensorGenerator<> gen; auto host_x = gen({2, 3}), host_y = gen({2, 3}); auto x = opr::Host2DeviceCopy::make(*graph, host_x), y = opr::Host2DeviceCopy::make(*graph, host_y); HostTensorND out0, out1, out2; auto funcs = graph->compile_multi_part({{make_callback_copy(x, out0)}, {make_callback_copy(x * y + 2, out1)}, {make_callback_copy(y, out2)}}); funcs[0]->execute(); MGB_ASSERT_TENSOR_EQ(*host_x, out0); funcs[1]->execute(); HostTensorND out1_expect; graph->compile({make_callback_copy(x * y + 2, out1_expect)})->execute(); MGB_ASSERT_TENSOR_EQ(out1_expect, out1); ASSERT_TRUE(out2.empty()); funcs[2]->execute(); MGB_ASSERT_TENSOR_EQ(*host_y, out2); } TEST(TestPartialExecution, MemoryManagement) { auto graph = ComputingGraph::make(); auto allocator = std::make_shared<TrackableDynamicMemAlloc>(); graph->set_device_memory_allocator(allocator); HostTensorGenerator<> gen; auto host_x = gen({2, 3}); auto cb0 = [&](DeviceTensorND&) { ASSERT_EQ(1u, allocator->nr_alive()); }; auto cb1 = [&](DeviceTensorND&) { ASSERT_EQ(0u, allocator->nr_alive()); }; auto x = opr::Host2DeviceCopy::make(*graph, host_x), y = x + 1, z = opr::CallbackInjector::make( opr::CallbackInjector::make(y, cb0) * 2, cb1); HostTensorND host_y, host_z; auto funcs = graph->compile_multi_part( {{make_callback_copy(y, host_y)}, {make_callback_copy(z, host_z)}}); for (size_t i = 0; i < 3; ++i) { funcs[0]->execute(); ASSERT_EQ(1u, allocator->nr_alive()); funcs[1]->execute(); ASSERT_EQ(0u, allocator->nr_alive()); auto px = host_x->ptr<float>(), py = host_y.ptr<float>(), pz = host_z.ptr<float>(); for (size_t i = 0, it = host_x->layout().total_nr_elems(); i < it; ++i) { ASSERT_EQ(px[i] + 1.f, py[i]); ASSERT_EQ((px[i] + 1.f) * 2.f, pz[i]); } *host_x = *gen({i / 2 + 4, 5}); } } TEST(TestPartialExecution, MemoryManagementAbort) { auto graph = ComputingGraph::make(); auto allocator = std::make_shared<TrackableDynamicMemAlloc>(); graph->set_device_memory_allocator(allocator); HostTensorGenerator<> gen; auto host_x = gen({2, 3}); auto x = opr::Host2DeviceCopy::make_no_fwd(*graph, host_x), y = x + 1; graph->options().graph_opt_level = 0; HostTensorND out0, out1, out2; auto funcs = graph->compile_multi_part({{make_callback_copy(x, out0)}, {make_callback_copy(y, out1)}, {make_callback_copy(y * 2, out2)}}); funcs[0]->execute(); ASSERT_EQ(1u, allocator->nr_alive()); funcs[1]->execute(); ASSERT_EQ(1u, allocator->nr_alive()); // memory should be reclaimed when execution aborts *host_x = *gen({4, 5}); funcs[0]->execute(); ASSERT_EQ(1u, allocator->nr_alive()); ASSERT_TRUE(out2.empty()); funcs[1]->execute(); ASSERT_EQ(1u, allocator->nr_alive()); funcs[2]->execute(); ASSERT_EQ(0u, allocator->nr_alive()); HostTensorND out1_expect, out2_expect; graph->compile({make_callback_copy(y, out1_expect), make_callback_copy(y * 2, out2_expect)}) ->execute(); MGB_ASSERT_TENSOR_EQ(*host_x, out0); MGB_ASSERT_TENSOR_EQ(out1_expect, out1); MGB_ASSERT_TENSOR_EQ(out2_expect, out2); } TEST(TestPartialExecution, Priority) { auto graph = ComputingGraph::make(); HostTensorGenerator<> gen; auto host_x = gen({2, 3}), host_y = gen({2, 3}); auto x = opr::Host2DeviceCopy::make_no_fwd(*graph, host_x), y = opr::Host2DeviceCopy::make_no_fwd(*graph, host_y), z = x + y; set_priority(x, 3); set_priority(y, -5); set_priority(z, -100); auto funcs = graph->compile_multi_part({{{x, {}}, {y, {}}}, {{z, {}}}}); SmallVector<opr::Host2DeviceCopy*> oprs_f0; funcs[0]->iter_opr_seq([&](cg::OperatorNodeBase* opr) { if (opr->same_type<opr::VarSinkOpr>()) { return true; } oprs_f0.emplace_back(&opr->cast_final_safe<opr::Host2DeviceCopy>()); return true; }); int nr_dev_data = 0; opr::Elemwise* opr_f1 = nullptr; funcs[1]->iter_opr_seq([&](cg::OperatorNodeBase* opr) { if (opr->same_type<opr::DeviceDataProvider>()) { ++nr_dev_data; return true; } EXPECT_EQ(nullptr, opr_f1); opr_f1 = &opr->cast_final_safe<opr::Elemwise>(); return true; }); ASSERT_EQ(2, nr_dev_data); ASSERT_EQ(2u, oprs_f0.size()); ASSERT_EQ(host_y.get(), oprs_f0[0]->host_data().get()); ASSERT_EQ(host_x.get(), oprs_f0[1]->host_data().get()); ASSERT_NE(nullptr, opr_f1); // priorities are remapped to consecutive integers ASSERT_EQ(-3, oprs_f0[0]->node_prop().attribute().priority); ASSERT_EQ(-2, oprs_f0[1]->node_prop().attribute().priority); ASSERT_EQ(-1, opr_f1->node_prop().attribute().priority); } TEST(TestPartialExecution, OrderCheck) { auto graph = ComputingGraph::make(); HostTensorGenerator<> gen; auto host_x = gen({2, 3}), host_y = gen({2, 3}); auto x = opr::Host2DeviceCopy::make(*graph, host_x), y = opr::Host2DeviceCopy::make(*graph, host_y); auto funcs = graph->compile_multi_part({{{x, {}}}, {{y, {}}}, {{x + y, {}}}}); funcs[0]->execute(); funcs[1]->execute(); funcs[2]->execute(); funcs[0]->execute(); funcs[1]->execute(); // cancel previous execution funcs[0]->execute(); funcs[1]->execute(); funcs[2]->execute(); // order violation ASSERT_THROW(funcs[1]->execute(), GraphError); funcs[0]->execute(); funcs[1]->execute(); // duplicated ASSERT_THROW(funcs[1]->execute(), GraphError); } #if MGB_ENABLE_EXCEPTION TEST(TestPartialExecution, AsyncError) { auto graph = ComputingGraph::make(); HostTensorGenerator<> gen; auto host_x = gen({2, 3}), host_y = gen({2, 3}); host_y->ptr<float>()[0] = host_x->ptr<float>()[0] + 1; auto x = opr::Host2DeviceCopy::make(*graph, host_x), y = opr::Host2DeviceCopy::make(*graph, host_y); for (int i = 0; i < 2; ++i) { auto funcs = graph->compile_multi_part( {{{x, {}}}, {{opr::AssertEqual::make(x, y), {}}}, {{y, {}}}}); funcs[0]->execute(); funcs[1]->execute(); funcs[2]->execute(); if (i == 0) { funcs[0]->wait(); funcs[2]->wait(); ASSERT_THROW(funcs[1]->wait(), MegBrainError); } else { // implicit wait ASSERT_THROW(funcs[0]->execute(), MegBrainError); } } } #endif // MGB_ENABLE_EXCEPTION #endif // MGB_ENABLE_PARTIAL_EXECUTION // vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}
34.394687
89
0.600629
kxz18
6b2cb450f7486fdea0c0902f83a93dd7d59464fe
128,573
cpp
C++
dev/Basic/medium/entities/conflux/Conflux.cpp
andrealho/simmobility-prod
041b91c9e36da452ca28014c305b9ae66a880277
[ "IJG" ]
2
2021-06-18T08:03:22.000Z
2021-06-18T08:03:28.000Z
dev/Basic/medium/entities/conflux/Conflux.cpp
ericchou0216/test
3c95a8d3b77016bf440499c4f7a6be68acd73cf5
[ "IJG" ]
null
null
null
dev/Basic/medium/entities/conflux/Conflux.cpp
ericchou0216/test
3c95a8d3b77016bf440499c4f7a6be68acd73cf5
[ "IJG" ]
null
null
null
//Copyright (c) 2013 Singapore-MIT Alliance for Research and Technology //Licensed under the terms of the MIT License, as described in the file: // license.txt (http://opensource.org/licenses/MIT) #include "Conflux.hpp" #include <algorithm> #include <cstdio> #include <cmath> #include <map> #include <stdexcept> #include <stdint.h> #include <string> #include <boost/algorithm/string.hpp> #include <sstream> #include <vector> #include <entities/roles/driver/OnCallDriverFacets.hpp> #include "conf/ConfigManager.hpp" #include "conf/ConfigParams.hpp" #include "config/MT_Config.hpp" #include "entities/BusStopAgent.hpp" #include "entities/TaxiStandAgent.hpp" #include "entities/conflux/SegmentStats.hpp" #include "entities/controllers/MobilityServiceControllerManager.hpp" #include "entities/Entity.hpp" #include "entities/misc/TripChain.hpp" #include "entities/roles/activityRole/ActivityPerformer.hpp" #include "entities/roles/driver/DriverVariantFacets.hpp" #include "entities/roles/driver/OnHailDriverFacets.hpp" #include "entities/roles/driver/TaxiDriverFacets.hpp" #include "entities/roles/driver/TaxiDriver.hpp" #include "entities/roles/driver/BusDriverFacets.hpp" #include "entities/roles/driver/DriverFacets.hpp" #include "entities/roles/passenger/PassengerFacets.hpp" #include "entities/roles/pedestrian/PedestrianFacets.hpp" #include "entities/roles/pedestrian/Pedestrian.hpp" #include "entities/roles/waitBusActivity/WaitBusActivityFacets.hpp" #include "entities/roles/waitTaxiActivity/WaitTaxiActivity.hpp" #include "entities/roles/waitTrainActivity/WaitTrainActivity.hpp" #include "entities/roles/driver/TrainDriverFacets.hpp" #include "entities/vehicle/VehicleBase.hpp" #include "entities/TrainController.hpp" #include "event/args/EventArgs.hpp" #include "event/EventPublisher.hpp" #include "event/SystemEvents.hpp" #include "geospatial/network/LaneConnector.hpp" #include "geospatial/network/Link.hpp" #include "geospatial/network/RoadNetwork.hpp" #include "geospatial/network/RoadSegment.hpp" #include "geospatial/streetdir/StreetDirectory.hpp" #include "logging/ControllerLog.hpp" #include "logging/Log.hpp" #include "message/MessageBus.hpp" #include "message/MobilityServiceControllerMessage.hpp" #include "metrics/Length.hpp" #include "path/PathSetManager.hpp" #include "util/Utils.hpp" #include "entities/roles/driver/TaxiDriver.hpp" #include "conf/ConfigManager.hpp" #include "conf/ConfigParams.hpp" #include "behavioral/ServiceController.hpp" //#include "DailyTime.cpp" using namespace boost; using namespace sim_mob; using namespace sim_mob::medium; using namespace sim_mob::messaging; using namespace std; typedef Entity::UpdateStatus UpdateStatus; namespace { const double INFINITESIMAL_DOUBLE = 0.000001; const double PASSENGER_CAR_UNIT = 400.0; //cm; 4 m. const double MAX_DOUBLE = std::numeric_limits<double>::max(); const double SHORT_SEGMENT_LENGTH_LIMIT = 5 * sim_mob::PASSENGER_CAR_UNIT; // 5 times a car's length const short EVADE_VQ_BOUNDS_THRESHOLD_TICKS = 24; //upper limit of number of ticks for which VQ size limit can reject a person from entering next link } void sim_mob::medium::sortPersonsDecreasingRemTime(std::deque<Person_MT*>& personList) { GreaterRemainingTimeThisTick greaterRemainingTimeThisTick; if (personList.size() > 1) { //ordering is required only if we have more than 1 person in the deque std::sort(personList.begin(), personList.end(), greaterRemainingTimeThisTick); } } unsigned Conflux::updateInterval = 0; int Conflux::currentframenumber =-1; boost::mutex Conflux::activeAgentsLock; std::unordered_map<const Node *,Conflux *> Conflux::nodeConfluxMap; Conflux::Conflux(Node* confluxNode, const MutexStrategy& mtxStrat, int id, bool isLoader) : Agent(mtxStrat, id), confluxNode(confluxNode), parentWorkerAssigned(false), currFrame(0, 0), isLoader(isLoader), numUpdatesThisTick(0), tickTimeInS(ConfigManager::GetInstance().FullConfig().baseGranSecond()), evadeVQ_Bounds(false), segStatsOutput(std::string()), lnkStatsOutput(std::string()) { nodeConfluxMap[confluxNode] = this; if (!isLoader) { multiUpdate = true; } } Conflux * Conflux::getConfluxFromNode(const Node * node) { std::unordered_map<const Node *,Conflux *>::const_iterator itr = nodeConfluxMap.find(node); return itr->second; } Conflux::~Conflux() { //delete all SegmentStats in this conflux for (UpstreamSegmentStatsMap::iterator upstreamIt = upstreamSegStatsMap.begin(); upstreamIt != upstreamSegStatsMap.end(); upstreamIt++) { const SegmentStatsList& linkSegments = upstreamIt->second; for (SegmentStatsList::const_iterator segIt = linkSegments.begin(); segIt != linkSegments.end(); segIt++) { safe_delete_item(*segIt); } } // clear person lists activityPerformers.clear(); pedestrianList.clear(); mrt.clear(); stashedPersons.clear(); } bool Conflux::isNonspatial() { return true; } void sim_mob::medium::Conflux::registerChild(Entity* child) { if(isLoader) { Person_MT* person = dynamic_cast<Person_MT*>(child); if(person) { loadingQueue.push_back(person); } else { throw std::runtime_error("Non-person entity cannot be loaded by loader conflux"); } } } void Conflux::initialize(const timeslice& now) { frame_init(now); //Register handlers for the bus stop agents for (UpstreamSegmentStatsMap::iterator upStrmSegMapIt = upstreamSegStatsMap.begin(); upStrmSegMapIt != upstreamSegStatsMap.end(); upStrmSegMapIt++) { for (std::vector<SegmentStats*>::const_iterator segStatsIt = upStrmSegMapIt->second.begin(); segStatsIt != upStrmSegMapIt->second.end(); segStatsIt++) { (*segStatsIt)->registerBusStopAgents(); } } setInitialized(true); } Conflux::PersonProps::PersonProps(const Person_MT* person, const Conflux* cnflx) { Role<Person_MT>* role = person->getRole(); isMoving = true; roleType = 0; if (role) { if (role->getResource()) { isMoving = role->getResource()->isMoving(); } roleType = role->roleType; VehicleBase* vehicle = role->getResource(); if (vehicle) { vehicleLength = vehicle->getLengthInM(); } else { vehicleLength = 0; } } lane = person->getCurrLane(); isQueuing = person->isQueuing; const SegmentStats* currSegStats = person->getCurrSegStats(); if (currSegStats) { segment = currSegStats->getRoadSegment(); conflux = currSegStats->getParentConflux(); segStats = conflux->findSegStats(segment, currSegStats->getStatsNumberInSegment()); //person->getCurrSegStats() cannot be used as it returns a const pointer } else { segment = nullptr; conflux = cnflx; segStats = nullptr; } if (roleType == Role<Person_MT>::RL_TRAVELPEDESTRIAN) { const medium::PedestrianMovement* pedestrianMvt = dynamic_cast<const medium::PedestrianMovement*>(role->Movement()); if (pedestrianMvt) { conflux = pedestrianMvt->getStartConflux(); } } distanceToSegEnd = person->distanceToEndOfSegment; } void Conflux::PersonProps::printProps(std::string personId, uint32_t frame, std::string prefix) const { char propbuf[1000]; if(roleType == 5) { sprintf(propbuf, "%s,%u,%s,cfx:%u,%p,activity\n", personId.c_str(), frame, prefix.c_str(), (conflux ? conflux->getConfluxNode()->getNodeId() : 0), (conflux ? conflux->currWorkerProvider : 0) ); } else { sprintf(propbuf, "%s,%u,%s,cfx:%u,%p,seg:%u-%u,ln:%u,rl:%u,q:%c,m:%c,d:%f\n", personId.c_str(), frame, prefix.c_str(), (conflux ? conflux->getConfluxNode()->getNodeId() : 0), (conflux ? conflux->currWorkerProvider : 0), (segment? segment->getRoadSegmentId() : 0), (segStats? segStats->getStatsNumberInSegment() : 0), (lane? lane->getLaneId() : 0), roleType, (isQueuing? 'T' : 'F' ), (isMoving? 'T' : 'F'), distanceToSegEnd ); } if(conflux) { conflux->log(std::string(propbuf)); } } bool Conflux::isStuck(Conflux::PersonProps& beforeUpdate, Conflux::PersonProps& afterUpdate) const { return ((beforeUpdate.roleType == Role<Person_MT>::RL_DRIVER || beforeUpdate.roleType == Role<Person_MT>::RL_BUSDRIVER || beforeUpdate.roleType == Role<Person_MT>::RL_BIKER || beforeUpdate.roleType == Role<Person_MT>::RL_TRUCKER_HGV || beforeUpdate.roleType == Role<Person_MT>::RL_TRUCKER_LGV) && beforeUpdate.lane && beforeUpdate.lane != beforeUpdate.segStats->laneInfinity && beforeUpdate.lane == afterUpdate.lane && beforeUpdate.segStats == afterUpdate.segStats && beforeUpdate.distanceToSegEnd == afterUpdate.distanceToSegEnd && beforeUpdate.roleType == afterUpdate.roleType); } void Conflux::addAgent(Person_MT* person) { if (isLoader) { loadingQueue.push_back(person); } else { Role<Person_MT>* role = person->getRole(); // at this point, we expect the role to have been initialized already if (!role) { safe_delete_item(person); return; } switch (role->roleType) { case Role<Person_MT>::RL_DRIVER: //fall through case Role<Person_MT>::RL_BUSDRIVER: case Role<Person_MT>::RL_BIKER: case Role<Person_MT>::RL_TRUCKER_LGV: case Role<Person_MT>::RL_TAXIDRIVER: case Role<Person_MT>::RL_TRUCKER_HGV: case Role<Person_MT>::RL_ON_HAIL_DRIVER: case Role<Person_MT>::RL_ON_CALL_DRIVER: { SegmentStats* rdSegStats = const_cast<SegmentStats*>(person->getCurrSegStats()); // person->currSegStats is set when frame_init of role is called person->setCurrLane(rdSegStats->laneInfinity); person->distanceToEndOfSegment = rdSegStats->getLength(); person->remainingTimeThisTick = tickTimeInS; rdSegStats->addAgent(rdSegStats->laneInfinity, person); break; } case Role<Person_MT>::RL_PEDESTRIAN: { assignPersonToPedestrianlist(person); break; } case Role<Person_MT>::RL_WAITBUSACTIVITY: { assignPersonToBusStopAgent(person); break; } case Role<Person_MT>::RL_WAITTRAINACTIVITY: { assignPersonToStationAgent(person); break; } case Role<Person_MT>::RL_TRAINPASSENGER: { assignPersonToMRT(person); break; } case Role<Person_MT>::RL_CARPASSENGER: case Role<Person_MT>::RL_PRIVATEBUSPASSENGER: { stashPerson(person); break; } case Role<Person_MT>::RL_ACTIVITY: { activityPerformers.push_back(person); //TODO: subscribe for time based event break; } case Role<Person_MT>::RL_PASSENGER: { throw std::runtime_error("person cannot start as a passenger"); break; } } } } void Conflux::acceptBrokenDriver(Person_MT* person) { brokenPersons.push_back(person); } void Conflux::removeBrokenDriver(Person_MT* person) { auto res = std::find(brokenPersons.begin(), brokenPersons.end(), person); if(res!=brokenPersons.end()) { brokenPersons.erase(res); } } Entity::UpdateStatus Conflux::frame_init(timeslice now) { messaging::MessageBus::RegisterHandler(this); for (UpstreamSegmentStatsMap::iterator upstreamIt = upstreamSegStatsMap.begin(); upstreamIt != upstreamSegStatsMap.end(); upstreamIt++) { const SegmentStatsList& linkSegments = upstreamIt->second; for (SegmentStatsList::const_iterator segIt = linkSegments.begin(); segIt != linkSegments.end(); segIt++) { (*segIt)->initializeBusStops(); } } for (std::vector<Agent *>::iterator it = stationAgents.begin(); it != stationAgents.end(); it++) { messaging::MessageBus::RegisterHandler((*it)); } /**************test code insert incident *********************/ /*************************************************************/ return Entity::UpdateStatus::Continue; } Entity::UpdateStatus sim_mob::medium::Conflux::frame_tick(timeslice now) { throw std::runtime_error("frame_tick() is not required and not implemented for Confluxes."); } void sim_mob::medium::Conflux::frame_output(timeslice now) { throw std::runtime_error("frame_output() is not required and not implemented for Confluxes."); } UpdateStatus Conflux::update(timeslice frameNumber) { if (!isInitialized()) { initialize(frameNumber); return UpdateStatus::ContinueIncomplete; } switch (numUpdatesThisTick) { case 0: { currFrame = frameNumber; if (isLoader) { loadPersons(); return UpdateStatus::Continue; } else { resetPositionOfLastUpdatedAgentOnLanes(); resetPersonRemTimes(); //reset the remaining times of persons in lane infinity and VQ if required. processAgents(frameNumber); //process all agents in this conflux for this tick if(segStatsOutput.length() > 0 || lnkStatsOutput.length() > 0) { writeOutputs(); //write outputs from previous update interval (if any) } setLastUpdatedFrame(frameNumber.frame()); numUpdatesThisTick = 1; return UpdateStatus::ContinueIncomplete; } } case 1: { processVirtualQueues(); numUpdatesThisTick = 2; return UpdateStatus::ContinueIncomplete; } case 2: { updateAndReportSupplyStats(currFrame); //reportLinkTravelTimes(currFrame); resetLinkTravelTimes(currFrame); numUpdatesThisTick = 0; return UpdateStatus::Continue; } default: { throw std::runtime_error("numUpdatesThisTick managed incorrectly"); } } } void Conflux::loadPersons() { unsigned int nextTickMS = (currFrame.frame() + MT_Config::getInstance().granPersonTicks) * ConfigManager::GetInstance().FullConfig().baseGranMS(); while (!loadingQueue.empty()) { Person_MT* person = loadingQueue.front(); person->currTick = currFrame; loadingQueue.pop_front(); Conflux* conflux = Conflux::findStartingConflux(person, nextTickMS); if (conflux) { messaging::MessageBus::PostMessage(conflux, MSG_PERSON_LOAD, messaging::MessageBus::MessagePtr(new PersonMessage(person))); } /*else { safe_delete_item(person); }*/ } } void Conflux::processAgents(timeslice frameNumber) { PersonList orderedPersons; getAllPersonsUsingTopCMerge(orderedPersons); //merge on-road agents of this conflux into a single list orderedPersons.insert(orderedPersons.end(), activityPerformers.begin(), activityPerformers.end()); // append activity performers orderedPersons.insert(orderedPersons.end(), travelingPersons.begin(), travelingPersons.end()); orderedPersons.insert(orderedPersons.end(), brokenPersons.begin(), brokenPersons.end()); for (PersonList::iterator personIt = orderedPersons.begin(); personIt != orderedPersons.end(); personIt++) //iterate and update all persons { (*personIt)->currTick = currFrame; updateAgent(*personIt); (*personIt)->latestUpdatedFrameTick = currFrame.frame(); } updateBusStopAgents(); //finally update bus stop agents in this conflux for(std::vector<Agent*>::iterator it=stationAgents.begin(); it!=stationAgents.end(); it++) { (*it)->currWorkerProvider = currWorkerProvider; (*it)->currTick = currFrame; (*it)->update(currFrame); } //Update the parking agents updateParkingAgents(); } void Conflux::processStartingAgents() { PersonList newPersons, tmpAgents; SegmentStats* segStats = nullptr; for(UpstreamSegmentStatsMap::iterator upStrmSegMapIt = upstreamSegStatsMap.begin(); upStrmSegMapIt!=upstreamSegStatsMap.end(); upStrmSegMapIt++) { const SegmentStatsList& upstreamSegments = upStrmSegMapIt->second; for(SegmentStatsList::const_iterator rdSegIt=upstreamSegments.begin(); rdSegIt!=upstreamSegments.end(); rdSegIt++) { segStats = (*rdSegIt); tmpAgents.clear(); segStats->getInfinityPersons(tmpAgents); newPersons.insert(newPersons.end(), tmpAgents.begin(), tmpAgents.end()); } } for (PersonList::iterator personIt = newPersons.begin(); personIt != newPersons.end(); personIt++) //iterate and update all persons { updateAgent(*personIt); } } void Conflux::updateQueuingTaxiDriverAgent(Person_MT *&person, timeslice now) { person->currTick = now; updateAgent(person); } void Conflux::updateParkedServiceDriver(Person_MT *&person, timeslice now) { person->currTick = now; updateAgent(person); } void Conflux::updateAgent(Person_MT* person) { if (person->getLastUpdatedFrame() < currFrame.frame()) { //if the person is being moved for the first time in this tick, reset person's remaining time to full tick size person->remainingTimeThisTick = tickTimeInS; } //let the person know which worker is (indirectly) managing him person->currWorkerProvider = currWorkerProvider; //capture person info before update PersonProps beforeUpdate(person, this); //let the person move UpdateStatus res = movePerson(currFrame, person); //kill person if he's DONE if (res.status == UpdateStatus::RS_DONE) { killAgent(person, beforeUpdate); return; } //capture person info after update PersonProps afterUpdate(person, this); //perform house keeping housekeep(beforeUpdate, afterUpdate, person); //update person's handler registration with MessageBus, if required updateAgentContext(beforeUpdate, afterUpdate, person); } bool Conflux::handleRoleChange(PersonProps& beforeUpdate, PersonProps& afterUpdate, Person_MT* person) { if(beforeUpdate.roleType == afterUpdate.roleType) { return false; //no role change took place; simply return } //there was a change of role in this tick //since we update only roles on roads and activity performers, the possible beforeUpdate switch(beforeUpdate.roleType) { case Role<Person_MT>::RL_ACTIVITY: { std::deque<Person_MT*>::iterator pIt = std::find(activityPerformers.begin(), activityPerformers.end(), person); if (pIt != activityPerformers.end()) { activityPerformers.erase(pIt); } break; } case Role<Person_MT>::RL_BUSDRIVER: { throw std::runtime_error("Bus drivers cannot change role"); break; } case Role<Person_MT>::RL_DRIVER: //fall through case Role<Person_MT>::RL_BIKER: case Role<Person_MT>::RL_TRUCKER_LGV: case Role<Person_MT>::RL_TRUCKER_HGV: { if(beforeUpdate.lane) //if person was not from VQ { beforeUpdate.segStats->dequeue(person, beforeUpdate.lane, beforeUpdate.isQueuing, beforeUpdate.vehicleLength); } break; } case Role<Person_MT>::RL_TRAVELPEDESTRIAN: { auto it = std::find(travelingPersons.begin(), travelingPersons.end(), person); if (it != travelingPersons.end()) { travelingPersons.erase(it); } break; } } switch(afterUpdate.roleType) { case Role<Person_MT>::RL_WAITBUSACTIVITY: //fall through case Role<Person_MT>::RL_TRAINPASSENGER: case Role<Person_MT>::RL_CARPASSENGER: case Role<Person_MT>::RL_PRIVATEBUSPASSENGER: case Role<Person_MT>::RL_PASSENGER: case Role<Person_MT>::RL_PEDESTRIAN: { break; //would have already been handled } case Role<Person_MT>::RL_ACTIVITY: { break; } case Role<Person_MT>::RL_BUSDRIVER: { throw std::runtime_error("Bus drivers are created and dispatched by bus controller. Cannot change role to Bus driver"); break; } case Role<Person_MT>::RL_WAITTAXIACTIVITY: { WaitTaxiActivity *activity = dynamic_cast<WaitTaxiActivity *>(person->getRole()); if (activity) { TaxiStandAgent *taxiStandAgent = TaxiStandAgent::getTaxiStandAgent(activity->getTaxiStand()); if (taxiStandAgent) { messaging::MessageBus::SendMessage(taxiStandAgent, MSG_WAITING_PERSON_ARRIVAL, messaging::MessageBus::MessagePtr(new ArrivalAtStopMessage(person))); } else { travelingPersons.push_back(person); } } break; } case Role<Person_MT>::RL_DRIVER: //fall through case Role<Person_MT>::RL_BIKER: case Role<Person_MT>::RL_TRUCKER_LGV: case Role<Person_MT>::RL_TRUCKER_HGV: { if (afterUpdate.lane) { if (afterUpdate.conflux == this) // if the next role is in the same conflux, we can safely add person to afterUpdate.segStats { afterUpdate.segStats->addAgent(afterUpdate.lane, person); // set the position of the last updated Person in his current lane (after update) if (afterUpdate.lane != afterUpdate.segStats->laneInfinity) { //if the person did not end up in a VQ and his lane is not lane infinity of segAfterUpdate double lengthToVehicleEnd = person->distanceToEndOfSegment + person->getRole()->getResource()->getLengthInM(); afterUpdate.segStats->setPositionOfLastUpdatedAgentInLane(lengthToVehicleEnd, afterUpdate.lane); } } else //post a message to the next conflux to handover this person for thread safety { sim_mob::messaging::MessageBus::PostMessage(afterUpdate.segStats->getParentConflux(), sim_mob::medium::MSG_PERSON_TRANSFER, sim_mob::messaging::MessageBus::MessagePtr(new PersonTransferMessage(person, afterUpdate.segStats, afterUpdate.lane))); } } else { //the person has changed role and wants to get into VQ right away person->distanceToEndOfSegment = afterUpdate.segStats->getLength(); afterUpdate.segStats->getParentConflux()->pushBackOntoVirtualQueue(afterUpdate.segment->getParentLink(), person); } break; } } return true; } void Conflux::housekeep(PersonProps& beforeUpdate, PersonProps& afterUpdate, Person_MT* person) { if(handleRoleChange(beforeUpdate, afterUpdate, person)) { return; //there was a change of role and it was handled } //person has not changed role in this tick if code path reaches here... //perform any specific role related handling first switch (afterUpdate.roleType) { case Role<Person_MT>::RL_ACTIVITY: case Role<Person_MT>::RL_TAXIPASSENGER: { // if the role was ActivityPerformer before the update as well, do nothing. // It is also possible that the person has changed from one activity to another. Do nothing even in this case. return; } case Role<Person_MT>::RL_TRAVELPEDESTRIAN: { if (beforeUpdate.conflux != afterUpdate.conflux) { auto it = std::find(travelingPersons.begin(), travelingPersons.end(), person); if (it != travelingPersons.end()) { travelingPersons.erase(it); } } return; } case Role<Person_MT>::RL_WAITTAXIACTIVITY: { return; } case Role<Person_MT>::RL_TAXIDRIVER: //fall through case Role<Person_MT>::RL_ON_HAIL_DRIVER: case Role<Person_MT>::RL_ON_CALL_DRIVER: case Role<Person_MT>::RL_BUSDRIVER: { if (beforeUpdate.isMoving && !afterUpdate.isMoving) { //if the vehicle stopped moving during the latest update (which //indicates that the bus has started serving a stop) we remove the bus from //segment stats //NOTE: the bus driver we remove here would have already been added //to the BusStopAgent corresponding to the stop currently served by //the bus driver. if (beforeUpdate.lane) { beforeUpdate.segStats->dequeue(person, beforeUpdate.lane, beforeUpdate.isQueuing, beforeUpdate.vehicleLength); } //if the bus driver started moving from a virtual queue, his beforeUpdate.lane will be null. //However, since he is already into a bus stop (afterUpdate.isMoving is false) we need not // add this bus driver to the new seg stats. So we must return from here in any case. return; } else if (!beforeUpdate.isMoving && afterUpdate.isMoving) { //if the vehicle has started moving during the latest update (which //indicates that the bus has finished serving a stop and is getting //back into the road network) we add the bus driver to the new segment //stats //NOTE: the bus driver we add here would have already been removed //from the BusStopAgent corresponding to the stop served by the //bus driver. if (afterUpdate.lane) { afterUpdate.segStats->addAgent(afterUpdate.lane, person); // set the position of the last updated Person in his current lane (after update) if (afterUpdate.lane != afterUpdate.segStats->laneInfinity) { //if the person did not end up in a VQ and his lane is not lane infinity of segAfterUpdate double lengthToVehicleEnd = person->distanceToEndOfSegment + person->getRole()->getResource()->getLengthInM(); afterUpdate.segStats->setPositionOfLastUpdatedAgentInLane(lengthToVehicleEnd, afterUpdate.lane); } } else { //the bus driver moved out of a stop and got added into a VQ. //we need to add the bus driver to the virtual queue here person->distanceToEndOfSegment = afterUpdate.segStats->getLength(); afterUpdate.segStats->getParentConflux()->pushBackOntoVirtualQueue(afterUpdate.segment->getParentLink(), person); } return; } else if (!beforeUpdate.isMoving && !afterUpdate.isMoving) { //There are two possibilities here. //1. The bus driver has been serving a stop through-out this tick //2. The bus driver has moved out of one stop and entered another within the same tick //In either case, there is nothing more for us to do here. //In case 2, we need not add the bus driver into the new segstats because he is already at the bus stop of that stats //we can simply return from here return; } break; } } //now we consider roles on the road //note: A person is in the virtual queue or performing and activity if beforeUpdate.lane is null if (!beforeUpdate.lane) { //if the person was in virtual queue or was performing an activity if (afterUpdate.lane) { //if the person has moved to another lane (possibly even to laneInfinity if he was performing activity) in some segment afterUpdate.segStats->addAgent(afterUpdate.lane, person); person->laneUpdated = true; } else { if (beforeUpdate.segStats != afterUpdate.segStats) { // the person must've have moved to another virtual queue - which is not possible if the virtual queues are processed // after all conflux updates std::stringstream debugMsgs; debugMsgs << "Error: Person has moved from one virtual queue to another. \n" << "Person " << person->getId() << "(" << person->getDatabaseId() << ")" << "|Frame: " << currFrame.frame() << "|Conflux: " << this->confluxNode->getNodeId() << "|segBeforeUpdate: " << beforeUpdate.segment->getRoadSegmentId() << "|segAfterUpdate: " << afterUpdate.segment->getRoadSegmentId(); throw std::runtime_error(debugMsgs.str()); } else { // this is typically the person who was not accepted by the next lane in the next segment. // we push this person back to the same virtual queue and let him update in the next tick. person->distanceToEndOfSegment = afterUpdate.segStats->getLength(); afterUpdate.segStats->getParentConflux()->pushBackOntoVirtualQueue(afterUpdate.segment->getParentLink(), person); } } } else if ((beforeUpdate.segStats != afterUpdate.segStats) /*if the person has moved to another segment*/ || (beforeUpdate.lane == beforeUpdate.segStats->laneInfinity && beforeUpdate.lane != afterUpdate.lane) /* or if the person has moved out of lane infinity*/ || !afterUpdate.lane /*some drivers have small loops in their path. Within 1 tick, it is possible for them to start from a proper lane of a segment in a link, eventually leave the segment and link, traverse the loop in their path and end up wanting to enter the same link from which they started. All of this could happen within the same tick. In this case, the segmentStats before and after update may be the same, but the lane after update will be NULL because the driver couldn't have got permission to enter the same link while its conflux is being processed. NOTE: This is a weird complication observed in the singapore network. There was a loop in the path of a driver near segment id 23881. This was the only segment in its link. The driver started from this segment, looped around and wanted to enter the same segment again. Permission was denied because the current conflux was still processing. I am attempting to handle this case by adding the third condition ~ Harish*/ ) { if (beforeUpdate.roleType != Role<Person_MT>::RL_ACTIVITY) { // the person could have been an activity performer in which case beforeUpdate.segStats would be null beforeUpdate.segStats->dequeue(person, beforeUpdate.lane, beforeUpdate.isQueuing, beforeUpdate.vehicleLength); person->laneUpdated = false; } if (afterUpdate.lane) { afterUpdate.segStats->addAgent(afterUpdate.lane, person); person->laneUpdated = true; person->updatedLane = afterUpdate.lane; } else { // we wouldn't know which lane the person has to go to if the person wants to enter a link which belongs to // a conflux that is not yet processed for this tick. We add this person to the virtual queue for that link here person->distanceToEndOfSegment = afterUpdate.segStats->getLength(); afterUpdate.segStats->getParentConflux()->pushBackOntoVirtualQueue(afterUpdate.segment->getParentLink(), person); } } else if (beforeUpdate.segStats == afterUpdate.segStats && afterUpdate.lane == afterUpdate.segStats->laneInfinity) { //it's possible for some persons to start a new trip on the same segment where they ended the previous trip. beforeUpdate.segStats->dequeue(person, beforeUpdate.lane, beforeUpdate.isQueuing, beforeUpdate.vehicleLength); //adding the person to lane infinity for the new trip person->laneUpdated = false; afterUpdate.segStats->addAgent(afterUpdate.lane, person); person->laneUpdated = true; person->updatedLane = afterUpdate.lane; } else if (beforeUpdate.isQueuing != afterUpdate.isQueuing) { //the person has joined the queuing part of the same segment stats afterUpdate.segStats->updateQueueStatus(afterUpdate.lane, person); person->laneUpdated = true; person->updatedLane = afterUpdate.lane; } // set the position of the last updated Person in his current lane (after update) if (afterUpdate.lane && afterUpdate.lane != afterUpdate.segStats->laneInfinity) { //if the person did not end up in a VQ and his lane is not lane infinity of segAfterUpdate double lengthToVehicleEnd = person->distanceToEndOfSegment + person->getRole()->getResource()->getLengthInM(); afterUpdate.segStats->setPositionOfLastUpdatedAgentInLane(lengthToVehicleEnd, afterUpdate.lane); person->laneUpdated = true; person->updatedLane = afterUpdate.lane; } /*if(isStuck(beforeUpdate, afterUpdate)) { // if the person was stuck at the same position in a segment in some lane person->numTicksStuck++; } else { person->numTicksStuck = 0; }*/ } void Conflux::updateAgentContext(PersonProps& beforeUpdate, PersonProps& afterUpdate, Person_MT* person) const { if (afterUpdate.conflux && beforeUpdate.conflux != afterUpdate.conflux) { MessageBus::ReRegisterHandler(person, afterUpdate.conflux->GetContext()); } } void Conflux::processVirtualQueues() { int counter = 0; { boost::unique_lock<boost::recursive_mutex> lock(mutexOfVirtualQueue); //sort the virtual queues before starting to move agents for this tick for (VirtualQueueMap::iterator i = virtualQueuesMap.begin(); i != virtualQueuesMap.end(); i++) { counter = i->second.size(); sortPersonsDecreasingRemTime(i->second); while (counter > 0) { Person_MT* p = i->second.front(); i->second.pop_front(); updateAgent(p); counter--; } } } } double Conflux::getSegmentSpeed(SegmentStats* segStats) const { return segStats->getSegSpeed(true); } /* * This function resets the remainingTime of persons who remain in lane infinity for more than 1 tick. * Note: This may include * 1. newly starting persons who (were supposed to, but) did not get added to the simulation * in the previous tick due to traffic congestion in their starting segment. * 2. Persons who got added to and remained virtual queue in the previous tick */ void Conflux::resetPersonRemTimes() { SegmentStats* segStats = nullptr; for (UpstreamSegmentStatsMap::iterator upStrmSegMapIt = upstreamSegStatsMap.begin(); upStrmSegMapIt != upstreamSegStatsMap.end(); upStrmSegMapIt++) { for (std::vector<SegmentStats*>::const_iterator segStatsIt = upStrmSegMapIt->second.begin(); segStatsIt != upStrmSegMapIt->second.end(); segStatsIt++) { segStats = *segStatsIt; PersonList& personsInLaneInfinity = segStats->getPersons(segStats->laneInfinity); for (PersonList::iterator personIt = personsInLaneInfinity.begin(); personIt != personsInLaneInfinity.end(); personIt++) { if ((*personIt)->getLastUpdatedFrame() < currFrame.frame()) { //if the person is going to be moved for the first time in this tick (*personIt)->remainingTimeThisTick = tickTimeInS; } } } } { boost::unique_lock<boost::recursive_mutex> lock(mutexOfVirtualQueue); for (VirtualQueueMap::iterator vqIt = virtualQueuesMap.begin(); vqIt != virtualQueuesMap.end(); vqIt++) { PersonList& personsInVQ = vqIt->second; for (PersonList::iterator pIt = personsInVQ.begin(); pIt != personsInVQ.end(); pIt++) { if ((*pIt)->getLastUpdatedFrame() < currFrame.frame()) { //if the person is going to be moved for the first time in this tick (*pIt)->remainingTimeThisTick = tickTimeInS; } } } } } unsigned int Conflux::resetOutputBounds() { boost::unique_lock<boost::recursive_mutex> lock(mutexOfVirtualQueue); unsigned int vqCount = 0; vqBounds.clear(); const Link* lnk = nullptr; SegmentStats* segStats = nullptr; int outputEstimate = 0; for (VirtualQueueMap::iterator i = virtualQueuesMap.begin(); i != virtualQueuesMap.end(); i++) { lnk = i->first; segStats = upstreamSegStatsMap.at(lnk).front(); outputEstimate = segStats->computeExpectedOutputPerTick(); // /** In DynaMIT, the upper bound to the space in virtual queue was set based on the number of empty spaces // the first segment of the downstream link (the one with the vq is attached to it) is going to create in this tick according to the outputFlowRate*tick_size. // This would ideally underestimate the space available in the next segment, as it doesn't account for the empty spaces the segment already has. // Therefore the virtual queues are most likely to be cleared by the end of that tick. // [1] But with short segments, we noticed that this over estimated the space and left a considerably large amount of vehicles remaining in vq. // Therefore, as per Yang Lu's suggestion, we are replacing computeExpectedOutputPerTick() calculation with existing number of empty spaces on the segment. // [2] Another reason for vehicles to remain in vq is that in mid-term, we currently process the new vehicles (i.e.trying to get added to the network from lane infinity), // before we process the virtual queues. Therefore the space that we computed to be for vehicles in virtual queues, would have been already occupied by the new vehicles // by the time the vehicles in virtual queues try to get added. // **/ // /** using ceil here, just to avoid short segments returning 0 as the total number of vehicles the road segment can hold i.e. when segment is shorter than a car**/ // int num_emptySpaces = std::ceil(segStats->getLength() * segStats->getNumVehicleLanes() / PASSENGER_CAR_UNIT) // - segStats->numMovingInSegment(true) - segStats->numQueuingInSegment(true); // outputEstimate = (num_emptySpaces >= 0) ? num_emptySpaces : 0; // /** we are decrementing the number of agents in lane infinity (of the first segment) to overcome problem [2] above**/ // outputEstimate = outputEstimate - segStats->numAgentsInLane(segStats->laneInfinity); // outputEstimate = (outputEstimate > 0 ? outputEstimate : 0); vqBounds.insert(std::make_pair(lnk, (unsigned int) outputEstimate)); vqCount += i->second.size(); } //loop if (vqBounds.empty() && !virtualQueuesMap.empty()) { Print() << boost::this_thread::get_id() << "," << this->confluxNode->getNodeId() << " vqBounds.empty()" << std::endl; } evadeVQ_Bounds = false; //reset to false at the end of everytick return vqCount; } bool Conflux::hasSpaceInVirtualQueue(const Link* lnk, short numTicksStuck) { // large value of numTicksStuck indicates that congestion is being built up because of VQ size limit. // we prevent deadlocks by returning true for 1 tick evadeVQ_Bounds = (numTicksStuck >= EVADE_VQ_BOUNDS_THRESHOLD_TICKS); if(evadeVQ_Bounds) { return true; } else { bool res = false; { boost::unique_lock<boost::recursive_mutex> lock(mutexOfVirtualQueue); try { res = (vqBounds.at(lnk) > virtualQueuesMap.at(lnk).size()); } catch (std::out_of_range& ex) { std::stringstream debugMsgs; debugMsgs << boost::this_thread::get_id() << " out_of_range exception occured in hasSpaceInVirtualQueue()" << "|Conflux: " << this->confluxNode->getNodeId() << "|lnk: " << lnk->getLinkId() << "|virtualQueuesMap.size():" << virtualQueuesMap.size() << "|elements:"; for (VirtualQueueMap::iterator i = virtualQueuesMap.begin(); i != virtualQueuesMap.end(); i++) { debugMsgs << " (" << lnk->getLinkId() << ":" << i->second.size() << "),"; } debugMsgs << "|\nvqBounds.size(): " << vqBounds.size() << std::endl; throw std::runtime_error(debugMsgs.str()); } } return res; } } void Conflux::pushBackOntoVirtualQueue(const Link* lnk, Person_MT* p) { boost::unique_lock<boost::recursive_mutex> lock(mutexOfVirtualQueue); virtualQueuesMap.at(lnk).push_back(p); } void Conflux::updateAndReportSupplyStats(timeslice frameNumber) { const ConfigManager& cfg = ConfigManager::GetInstance(); bool outputEnabled = cfg.CMakeConfig().OutputEnabled(); bool updateThisTick = ((frameNumber.frame() % updateInterval) == 0); for (UpstreamSegmentStatsMap::iterator upstreamIt = upstreamSegStatsMap.begin(); upstreamIt != upstreamSegStatsMap.end(); upstreamIt++) { const SegmentStatsList& linkSegments = upstreamIt->second; double lnkTotalVehicleLength = 0; for (SegmentStatsList::const_iterator segIt = linkSegments.begin(); segIt != linkSegments.end(); segIt++) { SegmentStats* segStats = (*segIt); if (updateThisTick && outputEnabled) { segStatsOutput.append(segStats->reportSegmentStats(frameNumber.frame() / updateInterval)); lnkTotalVehicleLength = lnkTotalVehicleLength + segStats->getTotalVehicleLength(); segStats->resetSegFlow(); } if(updateThisTick) { segStats->updateLaneParams(frameNumber); } } if(updateThisTick && outputEnabled) { LinkStats& lnkStats = (linkStatsMap.find(upstreamIt->first))->second; lnkStats.computeLinkDensity(lnkTotalVehicleLength); lnkStatsOutput.append(lnkStats.writeOutLinkStats(frameNumber.frame() / updateInterval)); } } if(updateThisTick && outputEnabled) { resetOutputBounds(); } } void Conflux::killAgent(Person_MT* person, PersonProps& beforeUpdate) { SegmentStats* prevSegStats = beforeUpdate.segStats; const Lane* prevLane = beforeUpdate.lane; bool wasQueuing = beforeUpdate.isQueuing; bool wasMoving = beforeUpdate.isMoving; double vehicleLength = beforeUpdate.vehicleLength; Role<Person_MT>::Type roleType = static_cast<Role<Person_MT>::Type>(beforeUpdate.roleType); switch(roleType) { case Role<Person_MT>::RL_ACTIVITY: { //In this case, the person will have a constructed role other than activity but the prevLane and prevSegStats will be NULL PersonList::iterator pIt = std::find(activityPerformers.begin(), activityPerformers.end(), person); if (pIt != activityPerformers.end()) { activityPerformers.erase(pIt); //Check if he was indeed an activity performer and erase him } break; } case Role<Person_MT>::RL_PEDESTRIAN: { PersonList::iterator pIt = std::find(pedestrianList.begin(), pedestrianList.end(), person); if (pIt != pedestrianList.end()) { pedestrianList.erase(pIt); } break; } case Role<Person_MT>::RL_PASSENGER: case Role<Person_MT>::RL_CARPASSENGER: case Role<Person_MT>::RL_PRIVATEBUSPASSENGER: { PersonList::iterator pIt = std::find(stashedPersons.begin(), stashedPersons.end(), person); if (pIt != stashedPersons.end()) { stashedPersons.erase(pIt); } break; } case Role<Person_MT>::RL_TRAINPASSENGER: { PersonList::iterator pIt = std::find(mrt.begin(), mrt.end(), person); if (pIt != mrt.end()) { mrt.erase(pIt); } break; } case Role<Person_MT>::RL_DRIVER: case Role<Person_MT>::RL_BIKER: case Role<Person_MT>::RL_TAXIDRIVER: case Role<Person_MT>::RL_TRUCKER_LGV: case Role<Person_MT>::RL_TRUCKER_HGV: { if (prevLane) { bool removed = prevSegStats->removeAgent(prevLane, person, wasQueuing, vehicleLength); if (!removed) { throw std::runtime_error("Conflux::killAgent(): Attempt to remove non-existent person in Lane"); } } break; } case Role<Person_MT>::RL_ON_HAIL_DRIVER: case Role<Person_MT>::RL_ON_CALL_DRIVER: { if (prevLane) { bool removed = prevSegStats->removeAgent(prevLane, person, wasQueuing, vehicleLength); //removed can be false in the case of On hail & on call drivers at the moment. //This is because an on hail driver could have been dequeued from prevLane in the previous tick and //be added to the taxi stand. When it has finished queuing there (time out), the driver is done. //He will be killed here. However, since he was already dequeued, we can't find him in prevLane now. //Similarly, an on call driver could have been dequeued from prevLane in the previous tick and //be added to the parking. The driver is done if its shift was completed there. //He will be killed here. However, since he was already dequeued, we can't find him in prevLane now. if (!removed && wasMoving) { throw std::runtime_error("Conflux::killAgent(): Attempt to remove non-existent person in Lane"); } } break; } case Role<Person_MT>::RL_BUSDRIVER: { if(person->parentEntity) { person->parentEntity->unregisterChild(person); //unregister bus driver from busController parent entity } if (prevLane) { bool removed = prevSegStats->removeAgent(prevLane, person, wasQueuing, vehicleLength); //removed can be false only in the case of BusDrivers at the moment. //This is because a BusDriver could have been dequeued from prevLane in the previous tick and be added to his //last bus stop. When he has finished serving the stop, the BusDriver is done. He will be killed here. However, //since he was already dequeued, we can't find him in prevLane now. //It is an error only if removed is false and the role is not BusDriver. if (!removed && wasMoving) { throw std::runtime_error("Conflux::killAgent(): Attempt to remove non-existent person in Lane"); } } break; } case Role<Person_MT>::RL_WAITBUSACTIVITY: { WaitBusActivity* waitBusRole = dynamic_cast<WaitBusActivity*>(person->getRole()); if(waitBusRole) { const BusStop* stop = waitBusRole->getStop(); BusStopAgent* busStopAgent = BusStopAgent::getBusStopAgentForStop(stop); busStopAgent->removeWaitingPerson(waitBusRole); } break; } default: { throw std::runtime_error("Person to be killed is not found."); } } person->currWorkerProvider = nullptr; if (person->getRole()->roleType==Role<Person_MT>::RL_ON_CALL_DRIVER && person->sureToBeDeletedPerson) { // Just Re Register the handler to avoid any mismatch between handler's context and Thread Context. messaging::MessageBus::ReRegisterHandler(person, GetContext()); } messaging::MessageBus::UnRegisterHandler(person); person->onWorkerExit(); Agent *ag=dynamic_cast<Agent*>(person); activeAgentsLock.lock(); std::vector<Entity*>::iterator itr=std::find(Agent::activeAgents.begin(),Agent::activeAgents.end(),ag); if(itr!=Agent::activeAgents.end()) { Agent::activeAgents.erase(itr); } activeAgentsLock.unlock(); ControllerLog()<<"killagent is called for Person " << person->getDatabaseId()<< " of Role " <<person->getRole()->getRoleName()<<" at time "<< person->currTick <<" is getting killed & be out of simulation ." << endl; safe_delete_item(person); } void Conflux::resetPositionOfLastUpdatedAgentOnLanes() { for (UpstreamSegmentStatsMap::iterator upstreamIt = upstreamSegStatsMap.begin(); upstreamIt != upstreamSegStatsMap.end(); upstreamIt++) { const SegmentStatsList& linkSegments = upstreamIt->second; for (SegmentStatsList::const_iterator segIt = linkSegments.begin(); segIt != linkSegments.end(); segIt++) { (*segIt)->resetPositionOfLastUpdatedAgentOnLanes(); } } } const std::vector<SegmentStats*>& sim_mob::medium::Conflux::findSegStats(const RoadSegment* rdSeg) const { return segmentAgents.find(rdSeg)->second; } LinkStats& Conflux::getLinkStats(const Link* lnk) { if(!lnk) { throw std::runtime_error("cannot find LinkStats for nullptr"); } LinkStatsMap::iterator lnkStatsIt = linkStatsMap.find(lnk); if(lnkStatsIt==linkStatsMap.end()) { throw std::runtime_error("link " + std::to_string(lnk->getLinkId()) + " does not belong to conflux " + std::to_string(confluxNode->getNodeId())); } return lnkStatsIt->second; } SegmentStats* Conflux::findSegStats(const RoadSegment* rdSeg, uint16_t statsNum) const { if (!rdSeg || statsNum == 0) { return nullptr; } const SegmentStatsList& statsList = segmentAgents.find(rdSeg)->second; if (statsList.size() < statsNum) { return nullptr; } SegmentStatsList::const_iterator statsIt = statsList.begin(); if (statsNum == 1) { return (*statsIt); } std::advance(statsIt, (statsNum - 1)); return (*statsIt); } void Conflux::setLinkTravelTimes(double travelTime, const Link* link) { std::map<const Link*, LinkTravelTimes>::iterator itTT = linkTravelTimesMap.find(link); if (itTT != linkTravelTimesMap.end()) { itTT->second.personCnt = itTT->second.personCnt + 1; itTT->second.linkTravelTime_ = itTT->second.linkTravelTime_ + travelTime; } else { LinkTravelTimes tTimes(travelTime, 1); linkTravelTimesMap.insert(std::make_pair(link, tTimes)); } } bool Conflux::callMovementFrameInit(timeslice now, Person_MT* person) { //register the person as a message handler if required if (!person->GetContext()) { messaging::MessageBus::RegisterHandler(person); } //Agents may be created with a null Role and a valid trip chain if (!person->getRole()) { //TODO: This UpdateStatus has a "prevParams" and "currParams" that should // (one would expect) be dealt with. Where does this happen? UpdateStatus res = person->checkTripChain(now.ms()); //Reset the start time (to the current time tick) so our dispatcher doesn't complain. person->setStartTime(now.ms()); //Nothing left to do? if (res.status == UpdateStatus::RS_DONE) { return false; } } #ifndef NDEBUG if (!person->getRole()) { std::stringstream debugMsgs; debugMsgs << "Person " << this->getId() << " has no Role."; throw std::runtime_error(debugMsgs.str()); } #endif //Get an UpdateParams instance. //TODO: This is quite unsafe, but it's a relic of how Person::update() used to work. // We should replace this eventually (but this will require a larger code cleanup). person->getRole()->make_frame_tick_params(now); //Now that the Role has been fully constructed, initialize it. if (person->getRole()) { person->getRole()->Movement()->frame_init(); if (person->isToBeRemoved()) { return false; } //if agent initialization fails, person is set to be removed } return true; } void Conflux::HandleMessage(messaging::Message::MessageType type, const messaging::Message& message) { switch (type) { case MSG_PERSON_TRANSFER: { const PersonTransferMessage& msg = MSG_CAST(PersonTransferMessage, message); msg.segStats->addAgent(msg.lane, msg.person); break; } case MSG_PEDESTRIAN_TRANSFER_REQUEST: { const PersonMessage& msg = MSG_CAST(PersonMessage, message); assignPersonToPedestrianlist(msg.person); break; } case MSG_TRAVELER_TRANSFER: { const PersonMessage& msg = MSG_CAST(PersonMessage, message); travelingPersons.push_back(msg.person); break; } case MSG_INSERT_INCIDENT: { //pathsetLogger << "Conflux received MSG_INSERT_INCIDENT" << std::endl; const InsertIncidentMessage& msg = MSG_CAST(InsertIncidentMessage, message); SegmentStatsList& statsList = segmentAgents.find(msg.affectedSegment)->second; //change the flow rate of the segment BOOST_FOREACH(SegmentStats* stat, statsList) { Conflux::insertIncident(stat, msg.newFlowRate); } break; } case MSG_WAKEUP_MRT_PAX: { const PersonMessage& msg = MSG_CAST(PersonMessage, message); PersonList::iterator pIt = std::find(mrt.begin(), mrt.end(), msg.person); if (pIt == mrt.end()) { throw std::runtime_error("Person not found in MRT list"); } mrt.erase(pIt); //switch to next trip chain item Entity::UpdateStatus retVal = switchTripChainItem(msg.person); if(retVal.status == UpdateStatus::RS_DONE) { safe_delete_item(msg.person); } break; } case MSG_WAKEUP_STASHED_PERSON: { const PersonMessage& msg = MSG_CAST(PersonMessage, message); PersonList::iterator pIt = std::find(stashedPersons.begin(), stashedPersons.end(), msg.person); if (pIt == stashedPersons.end()) { throw std::runtime_error("Person not found in Car list"); } stashedPersons.erase(pIt); //switch to next trip chain item Entity::UpdateStatus retVal = switchTripChainItem(msg.person); if(retVal.status == UpdateStatus::RS_DONE) { safe_delete_item(msg.person); } break; } case MSG_WAKEUP_PEDESTRIAN: { const PersonMessage& msg = MSG_CAST(PersonMessage, message); PersonList::iterator pIt = std::find(pedestrianList.begin(), pedestrianList.end(), msg.person); if (pIt == pedestrianList.end()) { throw std::runtime_error("Person not found in Car list"); } pedestrianList.erase(pIt); //switch to next trip chain item Entity::UpdateStatus retVal = switchTripChainItem(msg.person); if(retVal.status == UpdateStatus::RS_DONE) { safe_delete_item(msg.person); } break; } case MSG_PERSON_LOAD: { const PersonMessage& msg = MSG_CAST(PersonMessage, message); addAgent(msg.person); break; } case PASSENGER_LEAVE_FRM_PLATFORM: { const PersonMessage& msg = MSG_CAST(PersonMessage, message); switchTripChainItem(msg.person); if(!msg.person->isToBeRemoved() && msg.person->getRole()->roleType == Role<Person_MT>::RL_DRIVER) { SegmentStats* rdSegStats = const_cast<SegmentStats*>(msg.person->getCurrSegStats()); msg.person->setCurrLane(rdSegStats->laneInfinity); msg.person->distanceToEndOfSegment = rdSegStats->getLength(); msg.person->remainingTimeThisTick = tickTimeInS; rdSegStats->addAgent(rdSegStats->laneInfinity, msg.person); } break; } case MSG_WAKEUP_SHIFT_END: { const PersonMessage &msg = MSG_CAST(PersonMessage, message); MessageBus::PostMessage(msg.person, MSG_WAKEUP_SHIFT_END, MessageBus::MessagePtr(new PersonMessage(msg.person))); break; } default: break; } } void Conflux::collectTravelTime(Person_MT* person) { if (person && person->getRole()) { person->getRole()->collectTravelTime(); } } Entity::UpdateStatus Conflux::switchTripChainItem(Person_MT* person) { collectTravelTime(person); Entity::UpdateStatus retVal = person->checkTripChain(currFrame.ms()); if (retVal.status == UpdateStatus::RS_DONE) { return retVal; } Role<Person_MT>* personRole = person->getRole(); person->setStartTime(currFrame.ms()); //if person was a pedestrian previously, we need to remove him from the pedestrian list Role<Person_MT>* prevPersonRole = person->getPrevRole(); if(prevPersonRole && prevPersonRole->roleType == Role<Person_MT>::RL_PEDESTRIAN) { PersonList::iterator pIt = std::find(pedestrianList.begin(), pedestrianList.end(), person); if (pIt != pedestrianList.end()) { pedestrianList.erase(pIt); } } if ((*person->currTripChainItem)->itemType == TripChainItem::IT_ACTIVITY) { //IT_ACTIVITY as of now is just a matter of waiting for a period of time(between its start and end time) //since start time of the activity is usually later than what is configured initially, //we have to make adjustments so that it waits for exact amount of time Activity* acItem = dynamic_cast<Activity*>((*person->currTripChainItem)); ActivityPerformer<Person_MT> *ap = dynamic_cast<ActivityPerformer<Person_MT>*>(personRole); ap->setActivityStartTime(DailyTime(currFrame.ms() + ConfigManager::GetInstance().FullConfig().baseGranMS())); ap->setActivityEndTime( DailyTime(currFrame.ms() + ConfigManager::GetInstance().FullConfig().baseGranMS() + ((*person->currTripChainItem)->endTime.getValue() - (*person->currTripChainItem)->startTime.getValue()))); ap->setLocation(acItem->destination.node); messaging::MessageBus::ReRegisterHandler(person, GetContext()); } if (callMovementFrameInit(currFrame, person)) { person->setInitialized(true); } else { return UpdateStatus::Done; } if (personRole) { switch(personRole->roleType) { case Role<Person_MT>::RL_ACTIVITY: { activityPerformers.push_back(person); break; } case Role<Person_MT>::RL_WAITBUSACTIVITY: { assignPersonToBusStopAgent(person); break; } case Role<Person_MT>::RL_WAITTRAINACTIVITY: { assignPersonToStationAgent(person); return retVal; } case Role<Person_MT>::RL_TRAINPASSENGER: { assignPersonToMRT(person); break; } case Role<Person_MT>::RL_CARPASSENGER: case Role<Person_MT>::RL_PRIVATEBUSPASSENGER: { stashPerson(person); break; } case Role<Person_MT>::RL_PEDESTRIAN: { Conflux* destinationConflux = nullptr; const medium::PedestrianMovement* pedestrianMvt = dynamic_cast<const medium::PedestrianMovement*>(personRole->Movement()); if(pedestrianMvt) { destinationConflux = pedestrianMvt->getDestinationConflux(); } else { throw std::runtime_error("Pedestrian role facets not/incorrectly initialized"); } messaging::MessageBus::PostMessage(destinationConflux, MSG_PEDESTRIAN_TRANSFER_REQUEST, messaging::MessageBus::MessagePtr(new PersonMessage(person))); break; } } } return retVal; } Entity::UpdateStatus Conflux::callMovementFrameTick(timeslice now, Person_MT* person) { //const MT_Config& mtCfg = MT_Config::getInstance(); ConfigParams& config = ConfigManager::GetInstanceRW().FullConfig(); Role<Person_MT>* personRole = person->getRole(); if (person->isResetParamsRequired()) { personRole->make_frame_tick_params(now); person->setResetParamsRequired(false); } person->setLastUpdatedFrame(currFrame.frame()); Entity::UpdateStatus retVal = UpdateStatus::Continue; /* * The following loop guides the movement of the person by invoking the movement facet of the person's role one or more times * until the remainingTimeThisTick of the person is expired. * The frame tick of the movement facet returns when one of the following conditions are true. These are handled by case distinction. * * 1. Driver's frame_tick() has displaced the person to the maximum distance that the person can move in the full tick duration. * This case identified by checking if the remainingTimeThisTick of the person is 0. * If remainingTimeThisTick == 0 we break off from the while loop. * The person's location is updated in the conflux that it belongs to. If the person has to be removed from the simulation, he is. * * 2. The person has reached the end of a link. * This case is identified by checking requestedNextSegment which indicates that the role has requested permission to move to the next segment in a new link in its path. * The requested next segment will be assigned a segment by the mid-term driver iff the driver is moving into a new link. * The conflux immediately grants permission by setting canMoveToNextSegment to GRANTED. * If the next link is not processed for the current tick, the person is added to the virtual queue of the next conflux and the loop is broken. * If the next link is processed, the loop continues. The movement role facet (driver) checks canMoveToNextSegment flag before it advances in its frame_tick. * * 3. The person has reached the end of the current subtrip. The loop will catch this by checking person->isToBeRemoved() flag. * If the driver has reached the end of the current subtrip, the loop updates the current trip chain item of the person and change roles by calling person->checkTripChain(). * We also set the current segment, set the lane as lane infinity and call the movement facet of the person's role again. */ while (person->remainingTimeThisTick > 0.0) { //if person is Taxi Driver and has just entered into Taxi Stand then break this loop std::string id = person->getDatabaseId(); if (!person->isToBeRemoved()) { personRole->Movement()->frame_tick(); //Added to get Taxi Trajectory Output if((personRole->roleType == Role<Person_MT>::RL_ON_CALL_DRIVER && config.isOnCallTaxiTrajectoryEnabled()) ||(personRole->roleType == Role<Person_MT>::RL_ON_HAIL_DRIVER && config.isOnHailTaxiTrajectoryEnabled()) ||personRole->roleType == Role<Person_MT>::RL_TAXIDRIVER) { personRole->Movement()->frame_tick_output(); } if (personRole->roleType == Role<Person_MT>::RL_ACTIVITY) { person->setRemainingTimeThisTick(0.0); } } if (person->isToBeRemoved()) { retVal = switchTripChainItem(person); if (retVal.status == UpdateStatus::RS_DONE) { return retVal; } personRole = person->getRole(); } if (person->requestedNextSegStats) { const RoadSegment* nxtSegment = person->requestedNextSegStats->getRoadSegment(); Conflux* nxtConflux = person->requestedNextSegStats->getParentConflux(); // grant permission. But check whether the subsequent frame_tick can be called now. person->canMoveToNextSegment = Person_MT::GRANTED; long currentFrame = now.frame(); //frame will not be outside the range of long data type LaneParams* currLnParams = person->getCurrSegStats()->getLaneParams(person->getCurrLane()); if (currentFrame > nxtConflux->getLastUpdatedFrame()) { // nxtConflux is not processed for the current tick yet if (nxtConflux->hasSpaceInVirtualQueue(nxtSegment->getParentLink(), person->numTicksStuck) && currLnParams->getOutputCounter() > 0) { currLnParams->decrementOutputCounter(); person->setCurrSegStats(person->requestedNextSegStats); person->lastReqSegStats = person->requestedNextSegStats; person->setCurrLane(nullptr); // so that the updateAgent function will add this agent to the virtual queue person->requestedNextSegStats = nullptr; //if the person is trying to move to requestedNextSegStats from a bus stop in current segment, we need to //notify the corresponding bus stop agent and update moving status if (!personRole->getResource()->isMoving() && personRole->roleType == Role<Person_MT>::RL_BUSDRIVER) { BusDriverMovement* busDriverMovementFacet = dynamic_cast<BusDriverMovement*>(personRole->Movement()); busDriverMovementFacet->departFromCurrentStop(); } break; //break off from loop } else { person->canMoveToNextSegment = Person_MT::DENIED; person->requestedNextSegStats = nullptr; } } else if (currentFrame == nxtConflux->getLastUpdatedFrame()) { // nxtConflux is processed for the current tick. Can move to the next link. // already handled by setting person->canMoveToNextSegment = GRANTED if (currLnParams->getOutputCounter() > 0) { currLnParams->decrementOutputCounter(); } else { person->canMoveToNextSegment = Person_MT::DENIED; } person->requestedNextSegStats = nullptr; } else { throw std::runtime_error("lastUpdatedFrame of confluxes are managed incorrectly"); } } } return retVal; } void Conflux::callMovementFrameOutput(timeslice now, Person_MT* person) { //Save the output if (!isToBeRemoved()) { LogOut(person->currRole->Movement()->frame_tick_output()); } } void Conflux::reportLinkTravelTimes(timeslice frameNumber) { if (ConfigManager::GetInstance().CMakeConfig().OutputEnabled()) { std::map<const Link*, LinkTravelTimes>::const_iterator it = linkTravelTimesMap.begin(); for (; it != linkTravelTimesMap.end(); ++it) { LogOut( "(\"linkTravelTime\"" <<","<<frameNumber.frame() <<","<<it->first->getLinkId() <<",{" <<"\"travelTime\":\""<< (it->second.linkTravelTime_)/(it->second.personCnt) <<"\"})" <<std::endl); } } } void Conflux::resetLinkTravelTimes(timeslice frameNumber) { linkTravelTimesMap.clear(); } void Conflux::incrementSegmentFlow(const RoadSegment* rdSeg, uint16_t statsNum) { SegmentStats* segStats = findSegStats(rdSeg, statsNum); segStats->incrementSegFlow(); } void Conflux::updateBusStopAgents() { for (UpstreamSegmentStatsMap::iterator upStrmSegMapIt = upstreamSegStatsMap.begin();upStrmSegMapIt != upstreamSegStatsMap.end(); upStrmSegMapIt++) { for (std::vector<SegmentStats *>::const_iterator segStatsIt = upStrmSegMapIt->second.begin(); segStatsIt != upStrmSegMapIt->second.end(); segStatsIt++) { (*segStatsIt)->updateBusStopAgents(currFrame); } } } void Conflux::updateParkingAgents() { for(auto agent : parkingAgents) { agent->update(currFrame); } } void Conflux::assignPersonToStationAgent(Person_MT* person) { Role<Person_MT>* role = person->getRole(); if (role && role->roleType == Role<Person_MT>::RL_WAITTRAINACTIVITY) { const Platform* platform = nullptr; if (person->originNode.type == WayPoint::MRT_PLATFORM) { sim_mob::medium::WaitTrainActivity* curRole = dynamic_cast<sim_mob::medium::WaitTrainActivity*>(person->getRole()); if(curRole){ platform = person->originNode.platform; curRole->setStartPlatform(platform); curRole->setArrivalTime(currFrame.ms()+(ConfigManager::GetInstance().FullConfig().simStartTime()).getValue()); std::string stationNo = platform->getStationNo(); Agent* stationAgent = TrainController<Person_MT>::getAgentFromStation(stationNo); messaging::MessageBus::PostMessage(stationAgent,PASSENGER_ARRIVAL_AT_PLATFORM, messaging::MessageBus::MessagePtr(new PersonMessage(person))); } else { throw std::runtime_error("waiting train activity role don't exist."); } } } } void Conflux::assignPersonToBusStopAgent(Person_MT* person) { Role<Person_MT>* role = person->getRole(); if (role && role->roleType == Role<Person_MT>::RL_WAITBUSACTIVITY) { const BusStop* stop = nullptr; if (person->originNode.type == WayPoint::BUS_STOP) { stop = person->originNode.busStop; } if (!stop) { if (person->currSubTrip->origin.type == WayPoint::BUS_STOP) { stop = person->currSubTrip->origin.busStop; } } if (!stop) { return; } //always make sure we dispatch this person only to SOURCE_TERMINUS or NOT_A_TERMINUS stops if (stop->getTerminusType() == sim_mob::SINK_TERMINUS) { stop = stop->getTwinStop(); if (stop->getTerminusType() == sim_mob::SINK_TERMINUS) { throw std::runtime_error("both twin stops are SINKs"); } //sanity check } BusStopAgent* busStopAgent = BusStopAgent::getBusStopAgentForStop(stop); if (busStopAgent) { messaging::MessageBus::SendMessage(busStopAgent, MSG_WAITING_PERSON_ARRIVAL, messaging::MessageBus::MessagePtr(new ArrivalAtStopMessage(person))); } } } void Conflux::assignPersonToPedestrianlist(Person_MT* person) { Role<Person_MT>* role = person->getRole(); if(role && role->roleType == Role<Person_MT>::RL_PEDESTRIAN) { person->currWorkerProvider = currWorkerProvider; messaging::MessageBus::ReRegisterHandler(person, GetContext()); pedestrianList.push_back(person); uint32_t travelTime = role->getTravelTime(); unsigned int tick = ConfigManager::GetInstance().FullConfig().baseGranMS(); messaging::MessageBus::PostMessage(this, MSG_WAKEUP_PEDESTRIAN, messaging::MessageBus::MessagePtr(new PersonMessage(person)), false, travelTime / tick); } } void Conflux::dropOffTraveller(Person_MT *person) { if(person) { switchTripChainItem(person); } } Person_MT* Conflux::pickupTraveller(const std::string &personId) { Person_MT* personPickedUp = nullptr; if(!travelingPersons.empty()) { if (personId.empty()) { for (auto i = travelingPersons.begin(); i != travelingPersons.end();i++) { Pedestrian* pedestrian = dynamic_cast<Pedestrian*>((*i)->getRole()); if (pedestrian && !pedestrian->isOnDemandTraveller()) { personPickedUp = (*i); travelingPersons.erase(i); break; } } } else { for(auto i = travelingPersons.begin(); i!=travelingPersons.end(); i++) { if((*i)->getDatabaseId() == personId) { personPickedUp = (*i); travelingPersons.erase(i); break; } } } if(personPickedUp) { personPickedUp->currSubTrip->endLocationId = boost::lexical_cast<std::string>(this->getConfluxNode()->getNodeId()); personPickedUp->currSubTrip->endLocationType = "NODE"; personPickedUp->getRole()->collectTravelTime(); UpdateStatus status = personPickedUp->checkTripChain(currFrame.ms()); if((*(personPickedUp->currSubTrip)).origin.type == WayPoint::TAXI_STAND) { //Person was walking to taxi stand, where it would wait. //Switch role again status = personPickedUp->checkTripChain(currFrame.ms()); } if (status.status == UpdateStatus::RS_DONE) { return nullptr; } personPickedUp->currSubTrip->startLocationId = boost::lexical_cast<std::string>(this->getConfluxNode()->getNodeId()); personPickedUp->currSubTrip->startLocationType = "NODE"; personPickedUp->getRole()->setArrivalTime(currFrame.ms()+ConfigManager::GetInstance().FullConfig().simStartTime().getValue()); } } return personPickedUp; } void Conflux::assignPersonToMRT(Person_MT* person) { Role<Person_MT>* role = person->getRole(); if (role && role->roleType == Role<Person_MT>::RL_TRAINPASSENGER) { sim_mob::medium::Passenger* passengerRole = dynamic_cast<sim_mob::medium::Passenger*>(person->getRole()); person->currWorkerProvider = currWorkerProvider; messaging::MessageBus::ReRegisterHandler(person, GetContext()); mrt.push_back(person); uint32_t travelTime = person->currSubTrip->endTime.getValue(); //endTime was hacked to set the travel time for train passengers passengerRole->setTravelTime(travelTime); passengerRole->setStartPoint(person->currSubTrip->origin); passengerRole->setEndPoint(person->currSubTrip->destination); passengerRole->Movement()->startTravelTimeMetric(); unsigned int tick = ConfigManager::GetInstance().FullConfig().baseGranMS(); messaging::MessageBus::PostMessage(this, MSG_WAKEUP_MRT_PAX, messaging::MessageBus::MessagePtr(new PersonMessage(person)), false, travelTime / tick); } } void Conflux::stashPerson(Person_MT* person) { Role<Person_MT>* role = person->getRole(); if (role) { if(role->roleType == Role<Person_MT>::RL_CARPASSENGER || role->roleType == Role<Person_MT>::RL_PRIVATEBUSPASSENGER) { person->currWorkerProvider = currWorkerProvider; PersonList::iterator pIt = std::find(stashedPersons.begin(), stashedPersons.end(), person); if (pIt == stashedPersons.end()) { stashedPersons.push_back(person); } uint32_t travelTime = person->currSubTrip->endTime.getValue(); //endTime was hacked to set the travel time for car and private bus passengers person->setStartTime(currFrame.ms()); person->getRole()->setTravelTime(travelTime); unsigned int tick = ConfigManager::GetInstance().FullConfig().baseGranMS(); messaging::MessageBus::PostMessage(this, MSG_WAKEUP_STASHED_PERSON, messaging::MessageBus::MessagePtr(new PersonMessage(person)), false, travelTime / tick); } } } UpdateStatus Conflux::movePerson(timeslice now, Person_MT* person) { // We give the Agent the benefit of the doubt here and simply call frame_init(). // This allows them to override the start_time if it seems appropriate (e.g., if they // are swapping trip chains). If frame_init() returns false, immediately exit. if (!person->isInitialized()) { //Call frame_init() and exit early if required. if (!callMovementFrameInit(now, person)) { return UpdateStatus::Done; } //Set call_frame_init to false here; you can only reset frame_init() in frame_tick() person->setInitialized(true); //Only initialize once. } //Perform the main update tick UpdateStatus retVal = callMovementFrameTick(now, person); //This persons next movement will be in the next tick if (retVal.status != UpdateStatus::RS_DONE && person->remainingTimeThisTick <= 0) { //now is the right time to ask for resetting of updateParams person->setResetParamsRequired(true); } return retVal; } bool GreaterRemainingTimeThisTick::operator ()(const Person_MT* x, const Person_MT* y) const { if ((!x) || (!y)) { std::stringstream debugMsgs; debugMsgs << "cmp_person_remainingTimeThisTick: Comparison failed because at least one of the arguments is null" << "|x: " << (x ? x->getId() : 0) << "|y: " << (y ? y->getId() : 0); throw std::runtime_error(debugMsgs.str()); } //We want greater remaining time in this tick to translate into a higher priority. return (x->getRemainingTimeThisTick() > y->getRemainingTimeThisTick()); } std::deque<Person_MT*> Conflux::getAllPersons() { PersonList allPersonsInCfx, tmpAgents; SegmentStats* segStats = nullptr; for (UpstreamSegmentStatsMap::iterator upStrmSegMapIt = upstreamSegStatsMap.begin(); upStrmSegMapIt != upstreamSegStatsMap.end(); upStrmSegMapIt++) { const SegmentStatsList& upstreamSegments = upStrmSegMapIt->second; for (SegmentStatsList::const_iterator rdSegIt = upstreamSegments.begin(); rdSegIt != upstreamSegments.end(); rdSegIt++) { segStats = (*rdSegIt); segStats->getPersons(tmpAgents); allPersonsInCfx.insert(allPersonsInCfx.end(), tmpAgents.begin(), tmpAgents.end()); } } for (VirtualQueueMap::iterator vqMapIt = virtualQueuesMap.begin(); vqMapIt != virtualQueuesMap.end(); vqMapIt++) { tmpAgents = vqMapIt->second; allPersonsInCfx.insert(allPersonsInCfx.end(), tmpAgents.begin(), tmpAgents.end()); } allPersonsInCfx.insert(allPersonsInCfx.end(), activityPerformers.begin(), activityPerformers.end()); allPersonsInCfx.insert(allPersonsInCfx.end(), pedestrianList.begin(), pedestrianList.end()); return allPersonsInCfx; } PersonCount Conflux::countPersons() const { PersonCount count; count.activityPerformers = activityPerformers.size(); count.pedestrians = pedestrianList.size(); count.trainPassengers = mrt.size(); count.carSharers = stashedPersons.size(); PersonList onRoadPersons, tmpAgents; SegmentStats* segStats = nullptr; for (UpstreamSegmentStatsMap::const_iterator upStrmSegMapIt = upstreamSegStatsMap.begin(); upStrmSegMapIt != upstreamSegStatsMap.end(); upStrmSegMapIt++) { const SegmentStatsList& upstreamSegments = upStrmSegMapIt->second; for (SegmentStatsList::const_iterator rdSegIt = upstreamSegments.begin(); rdSegIt != upstreamSegments.end(); rdSegIt++) { segStats = (*rdSegIt); segStats->getPersons(tmpAgents); onRoadPersons.insert(onRoadPersons.end(), tmpAgents.begin(), tmpAgents.end()); count.busWaiters += segStats->getBusWaitersCount(); } } for (VirtualQueueMap::const_iterator vqMapIt = virtualQueuesMap.begin(); vqMapIt != virtualQueuesMap.end(); vqMapIt++) { tmpAgents = vqMapIt->second; onRoadPersons.insert(onRoadPersons.end(), tmpAgents.begin(), tmpAgents.end()); } for(PersonList::const_iterator onRoadPersonIt=onRoadPersons.begin(); onRoadPersonIt!=onRoadPersons.end(); onRoadPersonIt++) { const Role<Person_MT>* role = (*onRoadPersonIt)->getRole(); if(role) { switch(role->roleType) { case Role<Person_MT>::RL_DRIVER: { count.carDrivers++; break; } case Role<Person_MT>::RL_TAXIDRIVER: case Role<Person_MT>::RL_ON_HAIL_DRIVER: case Role<Person_MT>::RL_ON_CALL_DRIVER: { count.taxiDrivers++; break; } case Role<Person_MT>::RL_BIKER: { count.motorCyclists++; break; } case Role<Person_MT>::RL_TRUCKER_HGV: { count.truckerHGV++; break; } case Role<Person_MT>::RL_TRUCKER_LGV: { count.truckerLGV++; break; } case Role<Person_MT>::RL_BUSDRIVER: { count.busDrivers++; const BusDriver* busDriver = dynamic_cast<const BusDriver*>(role); if(busDriver) { count.busPassengers += busDriver->getPassengerCount(); } else { throw std::runtime_error("bus driver is NULL"); } break; } default: // not an on-road mode. Ideally an error, considering how we obtained onRoadPersons list { std::stringstream err; err << "Invalid mode on road. Role: " << role->roleType << "\n"; throw std::runtime_error(err.str()); } } } } return count; } void Conflux::getAllPersonsUsingTopCMerge(std::deque<Person_MT*>& mergedPersonDeque) { SegmentStats* segStats = nullptr; std::vector<PersonList> allPersonLists; int sumCapacity = 0; //need to calculate the time to intersection for each vehicle. //basic test-case shows that this calculation is kind of costly. for (UpstreamSegmentStatsMap::iterator upStrmSegMapIt = upstreamSegStatsMap.begin(); upStrmSegMapIt != upstreamSegStatsMap.end(); upStrmSegMapIt++) { const SegmentStatsList& upstreamSegments = upStrmSegMapIt->second; sumCapacity += (int) (ceil((*upstreamSegments.rbegin())->getCapacity())); double totalTimeToSegEnd = 0; std::deque<Person_MT*> oneDeque; for (SegmentStatsList::const_reverse_iterator rdSegIt = upstreamSegments.rbegin(); rdSegIt != upstreamSegments.rend(); rdSegIt++) { segStats = (*rdSegIt); double speed = segStats->getSegSpeed(true); //If speed is 0, treat it as a very small value if (speed < INFINITESIMAL_DOUBLE) { speed = INFINITESIMAL_DOUBLE; } segStats->updateLinkDrivingTimes(totalTimeToSegEnd); PersonList tmpAgents; segStats->topCMergeLanesInSegment(tmpAgents); totalTimeToSegEnd += segStats->getLength() / speed; oneDeque.insert(oneDeque.end(), tmpAgents.begin(), tmpAgents.end()); } allPersonLists.push_back(oneDeque); } topCMergeDifferentLinksInConflux(mergedPersonDeque, allPersonLists, sumCapacity); } void Conflux::topCMergeDifferentLinksInConflux(std::deque<Person_MT*>& mergedPersonDeque, std::vector<std::deque<Person_MT*> >& allPersonLists, int capacity) { std::vector<std::deque<Person_MT*>::iterator> iteratorLists; //init location size_t dequeSize = allPersonLists.size(); for (std::vector<std::deque<Person_MT*> >::iterator it = allPersonLists.begin(); it != allPersonLists.end(); ++it) { iteratorLists.push_back(((*it)).begin()); } //pick the Top C for (size_t c = 0; c < capacity; c++) { double minVal = MAX_DOUBLE; Person_MT* currPerson = nullptr; std::vector<std::pair<int, Person_MT*> > equiTimeList; for (size_t i = 0; i < dequeSize; i++) { if (iteratorLists[i] != (allPersonLists[i]).end()) { currPerson = (*(iteratorLists[i])); if (currPerson->drivingTimeToEndOfLink == minVal) { equiTimeList.push_back(std::make_pair(i, currPerson)); } else if (currPerson->drivingTimeToEndOfLink < minVal) { minVal = (*iteratorLists[i])->drivingTimeToEndOfLink; equiTimeList.clear(); equiTimeList.push_back(std::make_pair(i, currPerson)); } } } if (equiTimeList.empty()) { return; //no more vehicles } else { //we have to randomly choose from persons in equiDistantList size_t numElements = equiTimeList.size(); std::pair<int, Person_MT*> chosenPair; if (numElements == 1) { chosenPair = equiTimeList.front(); } else { int chosenIdx = rand() % numElements; chosenPair = equiTimeList[chosenIdx]; } iteratorLists.at(chosenPair.first)++; mergedPersonDeque.push_back(chosenPair.second); } } //After pick the Top C, there are still some vehicles left in the deque for (size_t i = 0; i < dequeSize; i++) { if (iteratorLists[i] != (allPersonLists[i]).end()) { mergedPersonDeque.insert(mergedPersonDeque.end(), iteratorLists[i], (allPersonLists[i]).end()); } } } // //void Conflux::addSegTT(Agent::RdSegTravelStat & stats, Person_MT* person) { // // TravelTimeManager::TR &timeRange = TravelTimeManager::getTimeInterval(stats.entryTime); // std::map<TravelTimeManager::TR,TravelTimeManager::TT>::iterator itTT = rdSegTravelTimesMap.find(timeRange); // TravelTimeManager::TT & travelTimeInfo = (itTT == rdSegTravelTimesMap.end() ? rdSegTravelTimesMap[timeRange] : itTT->second); // //initialization just in case // if(itTT == rdSegTravelTimesMap.end()){ // travelTimeInfo[stats.rs].first = 0.0; // travelTimeInfo[stats.rs].second = 0; // } // travelTimeInfo[stats.rs].first += stats.travelTime; //add to total travel time // rdSegTravelTimesMap[timeRange][stats.rs].second ++; //increment the total contribution //} // //void Conflux::resetRdSegTravelTimes() { // rdSegTravelTimesMap.clear(); //} // //void Conflux::reportRdSegTravelTimes(timeslice frameNumber) { // if (ConfigManager::GetInstance().CMakeConfig().OutputEnabled()) { // std::map<const RoadSegment*, RdSegTravelTimes>::const_iterator it = rdSegTravelTimesMap.begin(); // for( ; it != rdSegTravelTimesMap.end(); ++it ) { // LogOut("(\"rdSegTravelTime\"" // <<","<<frameNumber.frame() // <<","<<it->first // <<",{" // <<"\"travelTime\":\""<< (it->second.travelTimeSum)/(it->second.agCnt) // <<"\"})"<<std::endl); // } // } //// if (ConfigManager::GetInstance().FullConfig().PathSetMode()) { //// insertTravelTime2TmpTable(frameNumber, rdSegTravelTimesMap); //// } //} // //bool Conflux::insertTravelTime2TmpTable(timeslice frameNumber, std::map<const RoadSegment*, Conflux::RdSegTravelTimes>& rdSegTravelTimesMap) //{ //// bool res=false; //// //Link_travel_time& data //// std::map<const RoadSegment*, Conflux::RdSegTravelTimes>::const_iterator it = rdSegTravelTimesMap.begin(); //// for (; it != rdSegTravelTimesMap.end(); it++){ //// LinkTravelTime tt; //// const DailyTime &simStart = ConfigManager::GetInstance().FullConfig().simStartTime(); //// tt.linkId = (*it).first->getId(); //// tt.recordTime_DT = simStart + DailyTime(frameNumber.ms()); //// tt.travelTime = (*it).second.travelTimeSum/(*it).second.agCnt; //// PathSetManager::getInstance()->insertTravelTime2TmpTable(tt); //// } //// return res; //} unsigned int Conflux::getNumRemainingInLaneInfinity() { unsigned int count = 0; SegmentStats* segStats = nullptr; for (UpstreamSegmentStatsMap::iterator upStrmSegMapIt = upstreamSegStatsMap.begin(); upStrmSegMapIt != upstreamSegStatsMap.end(); upStrmSegMapIt++) { const SegmentStatsList& segStatsList = upStrmSegMapIt->second; for (SegmentStatsList::const_iterator statsIt = segStatsList.begin(); statsIt != segStatsList.end(); statsIt++) { segStats = (*statsIt); count += segStats->numAgentsInLane(segStats->laneInfinity); } } return count; } Conflux* Conflux::findStartingConflux(Person_MT* person, unsigned int now) { UpdateStatus res = person->checkTripChain(now); if (res.status == UpdateStatus::RS_DONE) { return nullptr; } //person without trip chain will be thrown out of the simulation person->setStartTime(now); Role<Person_MT>* personRole = person->getRole(); if (!personRole) { return nullptr; } if ((*person->currTripChainItem)->itemType == TripChainItem::IT_ACTIVITY) { //IT_ACTIVITY is just a matter of waiting for a period of time(between its start and end time) //since start time of the activity is usually later than what is configured initially, //we have to make adjustments so that it waits for exact amount of time ActivityPerformer<Person_MT>* ap = dynamic_cast<ActivityPerformer<Person_MT>*>(personRole); ap->setActivityStartTime(DailyTime(now + ConfigManager::GetInstance().FullConfig().baseGranMS())); ap->setActivityEndTime(DailyTime(now + ConfigManager::GetInstance().FullConfig().baseGranMS() + ((*person->currTripChainItem)->endTime.getValue() - (*person->currTripChainItem)->startTime.getValue()))); } //register the person as a message handler if required if (!person->GetContext()) { messaging::MessageBus::RegisterHandler(person); } //Now that the Role<Person_MT> has been fully constructed, initialize it. personRole->Movement()->frame_init(); if (person->isToBeRemoved()) { return nullptr; } //if agent initialization fails, person is set to be removed person->setInitialized(true); switch(personRole->roleType) { case Role<Person_MT>::RL_DRIVER: { const medium::DriverMovement *driverMvt = dynamic_cast<const medium::DriverMovement *>(personRole->Movement()); if (driverMvt) { return driverMvt->getStartingConflux(); } else { throw std::runtime_error("Driver role facets not/incorrectly initialized"); } break; } case Role<Person_MT>::RL_TRAINDRIVER: { const medium::TrainMovement *trainMvt = dynamic_cast<const medium::TrainMovement *>(personRole->Movement()); if (trainMvt) { trainMvt->arrivalAtStartPlaform(); } return nullptr; } case Role<Person_MT>::RL_TRUCKER_HGV: case Role<Person_MT>::RL_TRUCKER_LGV: { const medium::TruckerMovement *truckerMvt = dynamic_cast<const medium::TruckerMovement *>(personRole->Movement()); if (truckerMvt) { return truckerMvt->getStartingConflux(); } else { throw std::runtime_error("Driver role facets not/incorrectly initialized"); } break; } case Role<Person_MT>::RL_BIKER: { const medium::BikerMovement *bikerMvt = dynamic_cast<const medium::BikerMovement *>(personRole->Movement()); if (bikerMvt) { return bikerMvt->getStartingConflux(); } else { throw std::runtime_error("Biker role facets not/incorrectly initialized"); } break; } case Role<Person_MT>::RL_PEDESTRIAN: { const medium::PedestrianMovement *pedestrianMvt = dynamic_cast<const medium::PedestrianMovement *>(personRole->Movement()); if (pedestrianMvt) { return pedestrianMvt->getDestinationConflux(); } else { throw std::runtime_error("Pedestrian role facets not/incorrectly initialized"); } break; } case Role<Person_MT>::RL_TRAVELPEDESTRIAN: { const medium::PedestrianMovement *pedestrianMvt = dynamic_cast<const medium::PedestrianMovement *>(personRole->Movement()); if (pedestrianMvt) { return pedestrianMvt->getStartConflux(); } else { throw std::runtime_error("Pedestrian role facets not/incorrectly initialized"); } break; } case Role<Person_MT>::RL_BUSDRIVER: { const medium::BusDriverMovement *busDriverMvt = dynamic_cast<const medium::BusDriverMovement *>(personRole->Movement()); if (busDriverMvt) { return busDriverMvt->getStartingConflux(); } else { throw std::runtime_error("Bus-Driver role facets not/incorrectly initialized"); } break; } case Role<Person_MT>::RL_ON_HAIL_DRIVER: { auto *onHailDrvMvt = dynamic_cast<const medium::OnHailDriverMovement *>(personRole->Movement()); if (onHailDrvMvt) { return onHailDrvMvt->getStartingConflux(); } else { throw std::runtime_error("OnHailDriver role facets not/incorrectly initialized"); } break; } case Role<Person_MT>::RL_ON_CALL_DRIVER: { auto *onCallDrvMvt = dynamic_cast<const medium::OnCallDriverMovement *>(personRole->Movement()); if(onCallDrvMvt) { return onCallDrvMvt->getStartingConflux(); } else { throw std::runtime_error("OnCallDriver role facets not/incorrectly initialized"); } break; } case Role<Person_MT>::RL_TAXIDRIVER: { const medium::TaxiDriverMovement *taxiDriverMvt = dynamic_cast<const medium::TaxiDriverMovement *>(personRole->Movement()); if (taxiDriverMvt) { return taxiDriverMvt->getStartingConflux(); } else { throw std::runtime_error("Taxi-Driver role facets not/incorrectly initialized"); } break; } case Role<Person_MT>::RL_ACTIVITY: { ActivityPerformer<Person_MT> *ap = dynamic_cast<ActivityPerformer<Person_MT> *>(personRole); return MT_Config::getInstance().getConfluxForNode(ap->getLocation()); } case Role<Person_MT>::RL_PASSENGER: //Fall through case Role<Person_MT>::RL_TRAINPASSENGER: //Fall through case Role<Person_MT>::RL_CARPASSENGER: //Fall through case Role<Person_MT>::RL_PRIVATEBUSPASSENGER: //Fall through { const medium::PassengerMovement *passengerMvt = dynamic_cast<const medium::PassengerMovement *>(personRole->Movement()); if (passengerMvt) { return passengerMvt->getDestinationConflux(); } else { throw std::runtime_error("Passenger role facets not/incorrectly initialized"); } break; } case Role<Person_MT>::RL_WAITBUSACTIVITY: { const medium::WaitBusActivityMovement *waitBusMvt = dynamic_cast<const medium::WaitBusActivityMovement *>(personRole->Movement()); if (waitBusMvt) { return waitBusMvt->getStartingConflux(); } else { throw std::runtime_error("WaitBusActivity role facets not/incorrectly initialized"); } break; } case Role<Person_MT>::RL_WAITTRAINACTIVITY: { if (MT_Config::getInstance().getConfluxNodes().size() > 0) { return MT_Config::getInstance().getConfluxNodes().begin()->second; } } } } Conflux* sim_mob::medium::Conflux::getConflux(const RoadSegment* rdSeg) { return MT_Config::getInstance().getConfluxForNode(rdSeg->getParentLink()->getToNode()); } void sim_mob::medium::Conflux::writeOutputs() { if(segStatsOutput.length() > 0) { Log() << segStatsOutput; segStatsOutput = std::string(); } if(lnkStatsOutput.length() > 0) { Log() << lnkStatsOutput; lnkStatsOutput = std::string(); } } void Conflux::insertIncident(SegmentStats* segStats, double newFlowRate) { const std::vector<const Lane*>& lanes = segStats->getRoadSegment()->getLanes(); for (std::vector<const Lane*>::const_iterator it = lanes.begin(); it != lanes.end(); it++) { segStats->updateLaneParams((*it), newFlowRate); } } void Conflux::removeIncident(SegmentStats* segStats) { const std::vector<const Lane*>& lanes = segStats->getRoadSegment()->getLanes(); for (std::vector<const Lane*>::const_iterator it = lanes.begin(); it != lanes.end(); it++) { segStats->restoreLaneParams(*it); } } void Conflux::addStationAgent(Agent* stationAgent) { if(!stationAgent){ return; } stationAgent->currWorkerProvider = currWorkerProvider; stationAgents.push_back(stationAgent); } void Conflux::addParkingAgent(Agent *parkingAgent) { if(!parkingAgent) { return; } parkingAgent->currWorkerProvider = currWorkerProvider; parkingAgents.push_back(parkingAgent); } void Conflux::driverStatistics(timeslice now) { std::map<int, int> statSegs; std::map<int, int> statSegsInfinity; std::map<int, int> statLinks; std::map<int, string> statPersons; PersonList allPersonsInCfx, tmpAgents; SegmentStats* segStats = nullptr; std::string personIds; for(UpstreamSegmentStatsMap::iterator upStrmSegMapIt = upstreamSegStatsMap.begin(); upStrmSegMapIt!=upstreamSegStatsMap.end(); upStrmSegMapIt++) { const SegmentStatsList& upstreamSegments = upStrmSegMapIt->second; for(SegmentStatsList::const_iterator rdSegIt=upstreamSegments.begin(); rdSegIt!=upstreamSegments.end(); rdSegIt++) { tmpAgents.clear(); segStats = (*rdSegIt); segStats->getPersons(tmpAgents); int segId = segStats->getRoadSegment()->getRoadSegmentId(); if(statSegs.find(segId)!=statSegs.end()){ statSegs[segId] = statSegs[segId]+tmpAgents.size(); } else { statSegs[segId] = tmpAgents.size(); } statLinks[segId] = segStats->getRoadSegment()->getLinkId(); tmpAgents.clear(); personIds.clear(); segStats->getInfinityPersons(tmpAgents); statSegsInfinity[segId] = tmpAgents.size(); statPersons[segId] = personIds; } } for(VirtualQueueMap::iterator vqMapIt = virtualQueuesMap.begin(); vqMapIt != virtualQueuesMap.end(); vqMapIt++) { tmpAgents = vqMapIt->second; int segId = 0; if(vqMapIt->first && vqMapIt->first->getRoadSegments().size()>0){ segId = vqMapIt->first->getRoadSegments().back()->getRoadSegmentId(); } if(segId!=0){ segId = -segId; statSegs[segId] = tmpAgents.size(); statLinks[segId] = vqMapIt->first->getLinkId(); } } std::stringstream logout; std::string filename("driverstats.csv"); sim_mob::BasicLogger & movement = sim_mob::Logger::log(filename); std::map<int, int>::iterator it; for (it = statSegs.begin(); it != statSegs.end(); it++) { if (it->second > 0) { if (it->first > 0) { logout << it->first << "," << it->second << "," << statSegsInfinity[it->first] << "," << statLinks[it->first] << "," << DailyTime(now.ms()).getStrRepr() << std::endl; } else { logout << it->first << "," << it->second << "," << 0 << "," << statLinks[it->first] << "," << DailyTime(now.ms()).getStrRepr() << std::endl; } } } movement <<logout.str(); movement.flush(); } void Conflux::addConnectedConflux(Conflux* conflux) { if(!conflux) { throw std::runtime_error("invalid conflux passed for addition to connected Conflux set"); } connectedConfluxes.insert(conflux); } void Conflux::CreateSegmentStats(const RoadSegment* rdSeg, Conflux* conflux, std::list<SegmentStats*>& splitSegmentStats) { if (!rdSeg) { throw std::runtime_error("CreateSegmentStats(): NULL RoadSegment was passed"); } std::stringstream debugMsgs; const std::map<double, RoadItem*>& obstacles = rdSeg->getObstacles(); double lengthCoveredInSeg = 0; double segStatLength; double rdSegmentLength = rdSeg->getLength(); // NOTE: std::map implements strict weak ordering which defaults to less<key_type> // This is precisely the order in which we want to iterate the stops to create SegmentStats for (std::map<double, RoadItem*>::const_iterator obsIt = obstacles.begin(); obsIt != obstacles.end(); obsIt++) { const BusStop* busStop = dynamic_cast<const BusStop*>(obsIt->second); const TaxiStand* taxiStand = dynamic_cast<const TaxiStand*>(obsIt->second); if (busStop || taxiStand) { double stopOffset = obsIt->first; if (stopOffset <= 0) { SegmentStats* segStats = new SegmentStats(rdSeg, conflux, rdSegmentLength); if(busStop) { segStats->addBusStop(busStop); } if(taxiStand) { segStats->addTaxiStand(taxiStand); } //add the current stop and the remaining stops (if any) to the end of the segment as well while (++obsIt != obstacles.end()) { busStop = dynamic_cast<const BusStop*>(obsIt->second); if (busStop) { segStats->addBusStop(busStop); } taxiStand = dynamic_cast<const TaxiStand*>(obsIt->second); if(taxiStand) { segStats->addTaxiStand(taxiStand); } } splitSegmentStats.push_back(segStats); lengthCoveredInSeg = rdSegmentLength; break; } if (stopOffset < lengthCoveredInSeg) { debugMsgs << "bus stops are iterated in wrong order" << "|seg: " << rdSeg->getRoadSegmentId() << "|seg length: " << rdSegmentLength << "|curr busstop offset: " << obsIt->first << "|prev busstop offset: " << lengthCoveredInSeg << "|busstop: " << busStop->getStopCode() << std::endl; throw std::runtime_error(debugMsgs.str()); } if (stopOffset >= rdSegmentLength) { //this is probably due to error in data and needs manual fixing segStatLength = rdSegmentLength - lengthCoveredInSeg; lengthCoveredInSeg = rdSegmentLength; SegmentStats* segStats = new SegmentStats(rdSeg, conflux, segStatLength); if(busStop) { segStats->addBusStop(busStop); } if(taxiStand) { segStats->addTaxiStand(taxiStand); } //add the current stop and the remaining stops (if any) to the end of the segment as well while (++obsIt != obstacles.end()) { busStop = dynamic_cast<const BusStop*>(obsIt->second); if (busStop) { segStats->addBusStop(busStop); } taxiStand = dynamic_cast<const TaxiStand*>(obsIt->second); if(taxiStand) { segStats->addTaxiStand(taxiStand); } } splitSegmentStats.push_back(segStats); break; } //the relation (lengthCoveredInSeg < stopOffset < rdSegmentLength) holds here segStatLength = stopOffset - lengthCoveredInSeg; lengthCoveredInSeg = stopOffset; SegmentStats* segStats = new SegmentStats(rdSeg, conflux, segStatLength); if(busStop) { segStats->addBusStop(busStop); } if(taxiStand) { segStats->addTaxiStand(taxiStand); } splitSegmentStats.push_back(segStats); } } // manually adjust the position of the stops to avoid short segments if (!splitSegmentStats.empty()) { // if there are stops in the segment //another segment stats has to be created for the remaining length. //this segment stats does not contain a bus stop //adjust the length of the last segment stats if the remaining length is short double remainingSegmentLength = rdSegmentLength - lengthCoveredInSeg; if (remainingSegmentLength < 0) { debugMsgs << "Lengths of segment stats computed incorrectly\n"; debugMsgs << "segmentLength: " << rdSegmentLength << "|stat lengths: "; double totalStatsLength = 0; for (std::list<SegmentStats*>::iterator statsIt = splitSegmentStats.begin(); statsIt != splitSegmentStats.end(); statsIt++) { debugMsgs << (*statsIt)->getLength() << "|"; totalStatsLength = totalStatsLength + (*statsIt)->getLength(); } debugMsgs << "totalStatsLength: " << totalStatsLength << std::endl; throw std::runtime_error(debugMsgs.str()); } else if (remainingSegmentLength == 0) { // do nothing } else if (remainingSegmentLength < SHORT_SEGMENT_LENGTH_LIMIT) { // if the remaining length creates a short segment, // add this length to the last segment stats remainingSegmentLength = splitSegmentStats.back()->getLength() + remainingSegmentLength; splitSegmentStats.back()->length = remainingSegmentLength; } else { // if the remaining length is long enough create a new SegmentStats SegmentStats* segStats = new SegmentStats(rdSeg, conflux, remainingSegmentLength); splitSegmentStats.push_back(segStats); } // if there is atleast 1 bus stop in the segment and the length of the // created segment stats is short, we will try to adjust the lengths to // avoid short segments bool noMoreShortSegs = false; while (!noMoreShortSegs && splitSegmentStats.size() > 1) { noMoreShortSegs = true; //hopefully SegmentStats* lastStats = splitSegmentStats.back(); std::list<SegmentStats*>::iterator statsIt = splitSegmentStats.begin(); while ((*statsIt) != lastStats) { SegmentStats* currStats = *statsIt; std::list<SegmentStats*>::iterator nxtStatsIt = statsIt; nxtStatsIt++; //get a copy and increment for next SegmentStats* nextStats = *nxtStatsIt; if (currStats->getLength() < SHORT_SEGMENT_LENGTH_LIMIT) { noMoreShortSegs = false; //there is a short segment if (nextStats->getLength() >= SHORT_SEGMENT_LENGTH_LIMIT) { double lengthDiff = SHORT_SEGMENT_LENGTH_LIMIT - currStats->getLength(); currStats->length = SHORT_SEGMENT_LENGTH_LIMIT; nextStats->length = nextStats->getLength() - lengthDiff; } else { // we will merge i-th SegmentStats with i+1-th SegmentStats // and add both bus stops to the merged SegmentStats nextStats->length = currStats->getLength() + nextStats->getLength(); for (std::vector<const BusStop*>::iterator stopIt = currStats->busStops.begin(); stopIt != currStats->busStops.end(); stopIt++) { nextStats->addBusStop(*stopIt); } for(std::vector<const TaxiStand*>::iterator standIt = currStats->taxiStands.begin(); standIt != currStats->taxiStands.end(); standIt++) { nextStats->addTaxiStand(*standIt); } statsIt = splitSegmentStats.erase(statsIt); safe_delete_item(currStats); continue; } } statsIt++; } } if (splitSegmentStats.size() > 1) { // the last segment stat is handled separately std::list<SegmentStats*>::iterator statsIt = splitSegmentStats.end(); statsIt--; SegmentStats* lastSegStats = *(statsIt); statsIt--; SegmentStats* lastButOneSegStats = *(statsIt); if (lastSegStats->getLength() < SHORT_SEGMENT_LENGTH_LIMIT) { lastSegStats->length = lastButOneSegStats->getLength() + lastSegStats->getLength(); for (std::vector<const BusStop*>::iterator stopIt = lastButOneSegStats->busStops.begin(); stopIt != lastButOneSegStats->busStops.end(); stopIt++) { lastSegStats->addBusStop(*stopIt); } for (std::vector<const TaxiStand*>::iterator standIt = lastButOneSegStats->taxiStands.begin(); standIt != lastButOneSegStats->taxiStands.end(); standIt++) { lastSegStats->addTaxiStand(*standIt); } splitSegmentStats.erase(statsIt); safe_delete_item(lastButOneSegStats); } } } else { // if there are no stops in the segment, we create a single SegmentStats for this segment SegmentStats* segStats = new SegmentStats(rdSeg, conflux, rdSegmentLength); splitSegmentStats.push_back(segStats); } uint16_t statsNum = 1; std::set<SegmentStats*>& segmentStatsWithStops = MT_Config::getInstance().getSegmentStatsWithBusStops(); std::set<SegmentStats*>& segmentStatsWithStands = MT_Config::getInstance().getSegmentStatsWithTaxiStands(); for (std::list<SegmentStats*>::iterator statsIt = splitSegmentStats.begin(); statsIt != splitSegmentStats.end(); statsIt++) { SegmentStats* stats = *statsIt; //number the segment stats stats->statsNumberInSegment = statsNum; statsNum++; //add to segmentStatsWithStops if there is a bus stop in stats if (!(stats->getBusStops().empty())) { segmentStatsWithStops.insert(stats); } if(!(stats->getTaxiStand().empty())) { segmentStatsWithStands.insert(stats); } } } /* * iterates nodes and creates confluxes for all of them */ void Conflux::CreateConfluxes() { const RoadNetwork* rdnw = RoadNetwork::getInstance(); std::stringstream debugMsgs(std::stringstream::out); ConfigParams& cfg = ConfigManager::GetInstanceRW().FullConfig(); MT_Config& mtCfg = MT_Config::getInstance(); Conflux::updateInterval = mtCfg.getSupplyUpdateInterval(); const MutexStrategy& mtxStrat = cfg.mutexStategy(); std::set<Conflux*>& confluxes = mtCfg.getConfluxes(); std::map<const Node*, Conflux*>& nodeConfluxesMap = mtCfg.getConfluxNodes(); //Make a temporary map of <multi node, set of road-segments directly connected to the multinode> //TODO: This should be done automatically *before* it's needed. std::map<const Node*, std::set<const Link*> > linksAt; const std::map<unsigned int, Link*>& linkMap = rdnw->getMapOfIdVsLinks(); for (std::map<unsigned int, Link*>::const_iterator it=linkMap.begin(); it!=linkMap.end(); it++) { Link* lnk = it->second; linksAt[lnk->getToNode()].insert(lnk); } debugMsgs << "Nodes without upstream links: [ "; const std::map<unsigned int, Node*>& nodeMap= rdnw->getMapOfIdvsNodes(); for (std::map<unsigned int, Node*>::const_iterator i=nodeMap.begin(); i!=nodeMap.end(); i++) { Conflux* conflux = nullptr; std::map<const Node*, std::set<const Link*> >::const_iterator lnksAtNodeIt = linksAt.find(i->second); if (lnksAtNodeIt == linksAt.end()) { debugMsgs << (i->second)->getNodeId() << " "; continue; } const std::set<const Link*>& linksAtNode = lnksAtNodeIt->second; if (!linksAtNode.empty()) { // we create a conflux for each multinode conflux = new Conflux(i->second, mtxStrat); for (std::set<const Link*>::const_iterator lnkIt = linksAtNode.begin(); lnkIt != linksAtNode.end(); lnkIt++) { const Link* lnk = (*lnkIt); //lnk *ends* at the multinode of this conflux. //Therefore, lnk is upstream to the multinode and belongs to this conflux std::vector<SegmentStats*> upSegStatsList; const std::vector<RoadSegment*>& upSegs = lnk->getRoadSegments(); //set conflux pointer to the segments and create SegmentStats for the segment for (std::vector<RoadSegment*>::const_iterator segIt = upSegs.begin(); segIt != upSegs.end(); segIt++) { const RoadSegment* rdSeg = *segIt; double rdSegmentLength = rdSeg->getPolyLine()->getLength(); std::list<SegmentStats*> splitSegmentStats; CreateSegmentStats(rdSeg, conflux, splitSegmentStats); if (splitSegmentStats.empty()) { debugMsgs.str(std::string()); debugMsgs << "no segment stats created for segment." << "|segment: " << rdSeg->getRoadSegmentId() << "|conflux: " << conflux->getConfluxNode() << std::endl; throw std::runtime_error(debugMsgs.str()); } std::vector<SegmentStats*>& rdSegSatsList = conflux->segmentAgents[rdSeg]; rdSegSatsList.insert(rdSegSatsList.end(), splitSegmentStats.begin(), splitSegmentStats.end()); upSegStatsList.insert(upSegStatsList.end(), splitSegmentStats.begin(), splitSegmentStats.end()); } conflux->upstreamSegStatsMap.insert(std::make_pair(lnk, upSegStatsList)); conflux->virtualQueuesMap.insert(std::make_pair(lnk, std::deque<Person_MT*>())); conflux->linkStatsMap.insert(std::make_pair(lnk, LinkStats(lnk))); } // end for conflux->resetOutputBounds(); confluxes.insert(conflux); nodeConfluxesMap[i->second] = conflux; } //end if } // end for each multinode debugMsgs << "]\n"; #ifdef DEBUG Print() << debugMsgs.str(); #endif //now we go through each link again to tag confluxes with adjacent confluxes for (std::map<unsigned int, Link*>::const_iterator it=linkMap.begin(); it!=linkMap.end(); it++) { Link* lnk = it->second; std::map<const Node*, Conflux*>::const_iterator nodeConfluxIt = nodeConfluxesMap.find(lnk->getFromNode()); if(nodeConfluxIt != nodeConfluxesMap.end()) // link's start node need not necessarily have a conflux { Conflux* startConflux = nodeConfluxIt->second; Conflux* endConflux = nodeConfluxesMap.at(lnk->getToNode()); startConflux->addConnectedConflux(endConflux); //duplicates are naturally discarded by set container endConflux->addConnectedConflux(startConflux); //duplicates are naturally discarded by set container } } CreateLaneGroups(); } void Conflux::CreateLaneGroups() { const RoadNetwork* rdnw = RoadNetwork::getInstance(); std::set<Conflux*>& confluxes = MT_Config::getInstance().getConfluxes(); if (confluxes.empty()) { return; } typedef std::map<const Lane*, LaneStats*> LaneStatsMap; for (std::set<Conflux*>::const_iterator cfxIt = confluxes.begin(); cfxIt != confluxes.end(); cfxIt++) { UpstreamSegmentStatsMap& upSegsMap = (*cfxIt)->upstreamSegStatsMap; const Node* cfxNode = (*cfxIt)->getConfluxNode(); for (UpstreamSegmentStatsMap::const_iterator upSegsMapIt = upSegsMap.begin(); upSegsMapIt != upSegsMap.end(); upSegsMapIt++) { const Link* lnk = upSegsMapIt->first; const std::map<unsigned int, TurningGroup *>& turningGroupsFromLnk = cfxNode->getTurningGroups(lnk->getLinkId()); if(turningGroupsFromLnk.empty()) { continue; } const SegmentStatsList& segStatsList = upSegsMapIt->second; if (segStatsList.empty()) { throw std::runtime_error("No segment stats for link"); } //assign downstreamLinks to the last segment stats SegmentStats* lastStats = segStatsList.back(); for (std::map<unsigned int, TurningGroup*>::const_iterator tgIt = turningGroupsFromLnk.begin(); tgIt != turningGroupsFromLnk.end(); tgIt++) { const TurningGroup* turnGrp = tgIt->second; const Link* downStreamLink = rdnw->getById(rdnw->getMapOfIdVsLinks(), turnGrp->getToLinkId()); if(!downStreamLink) { throw std::runtime_error("to link of turn group is NULL"); } const std::map<unsigned int, std::map<unsigned int, TurningPath *> >& turnPaths = turnGrp->getTurningPaths(); for(std::map<unsigned int, std::map<unsigned int, TurningPath *> >::const_iterator tpOuterIt=turnPaths.begin(); tpOuterIt!=turnPaths.end(); tpOuterIt++) { for(std::map<unsigned int, TurningPath*>::const_iterator tpIt=tpOuterIt->second.begin(); tpIt!=tpOuterIt->second.end(); tpIt++) { const TurningPath* turnPath = tpIt->second; lastStats->laneStatsMap.at(turnPath->getFromLane())->addDownstreamLink(downStreamLink); //duplicates are eliminated by the std::set containing the downstream links } } } //construct inverse lookup for convenience for (LaneStatsMap::const_iterator lnStatsIt = lastStats->laneStatsMap.begin(); lnStatsIt != lastStats->laneStatsMap.end(); lnStatsIt++) { if (lnStatsIt->second->isLaneInfinity()) { continue; } LaneStats* lnStats = lnStatsIt->second; const std::set<const Link*>& downstreamLnks = lnStats->getDownstreamLinks(); if(downstreamLnks.empty()) { std::stringstream err; err << "no downstream links found for lane " << lnStatsIt->first->getLaneId() << " in last segment " << lnStatsIt->first->getParentSegment()->getRoadSegmentId() << " of link " << lnStatsIt->first->getParentSegment()->getParentLink()->getLinkId() << " \n"; throw std::runtime_error(err.str()); } for (std::set<const Link*>::const_iterator dnStrmIt = downstreamLnks.begin(); dnStrmIt != downstreamLnks.end(); dnStrmIt++) { lastStats->laneGroup[*dnStrmIt].push_back(lnStats); } } //extend the downstream links assignment to the segmentStats upstream to the last segmentStats SegmentStatsList::const_reverse_iterator upSegsRevIt = segStatsList.rbegin(); upSegsRevIt++; //lanestats of last segmentstats is already assigned with downstream links... so skip the last segmentstats const SegmentStats* downstreamSegStats = lastStats; for (; upSegsRevIt != segStatsList.rend(); upSegsRevIt++) { SegmentStats* currSegStats = (*upSegsRevIt); const RoadSegment* currSeg = currSegStats->getRoadSegment(); const std::vector<const Lane*>& currLanes = currSeg->getLanes(); if (currSeg == downstreamSegStats->getRoadSegment()) { //currSegStats and downstreamSegStats have the same parent segment //lanes of the two segstats are same for (std::vector<const Lane*>::const_iterator lnIt = currLanes.begin(); lnIt != currLanes.end(); lnIt++) { const Lane* ln = (*lnIt); if (ln->isPedestrianLane()) { continue; } const LaneStats* downStreamLnStats = downstreamSegStats->laneStatsMap.at(ln); LaneStats* currLnStats = currSegStats->laneStatsMap.at(ln); currLnStats->addDownstreamLinks(downStreamLnStats->getDownstreamLinks()); } } else { for (std::vector<const Lane*>::const_iterator lnIt = currLanes.begin(); lnIt != currLanes.end(); lnIt++) { const Lane* ln = (*lnIt); if (ln->isPedestrianLane()) { continue; } LaneStats* currLnStats = currSegStats->laneStatsMap.at(ln); const std::vector<LaneConnector*>& lnConnectors = ln->getLaneConnectors(); for(std::vector<LaneConnector*>::const_iterator lcIt=lnConnectors.begin(); lcIt!=lnConnectors.end(); lcIt++) { const LaneStats* downStreamLnStats = downstreamSegStats->laneStatsMap.at((*lcIt)->getToLane()); currLnStats->addDownstreamLinks(downStreamLnStats->getDownstreamLinks()); } } } //construct inverse lookup for convenience for (LaneStatsMap::const_iterator lnStatsIt = currSegStats->laneStatsMap.begin(); lnStatsIt != currSegStats->laneStatsMap.end(); lnStatsIt++) { if (lnStatsIt->second->isLaneInfinity()) { continue; } const std::set<const Link*>& downstreamLnks = lnStatsIt->second->getDownstreamLinks(); if(downstreamLnks.empty()) { std::stringstream err; err << "no downstream links found for lane " << lnStatsIt->first->getLaneId() << " in segment " << lnStatsIt->first->getParentSegment()->getRoadSegmentId() << " of link " << lnStatsIt->first->getParentSegment()->getParentLink()->getLinkId() << "\n"; throw std::runtime_error(err.str()); } for (std::set<const Link*>::const_iterator dnStrmIt = downstreamLnks.begin(); dnStrmIt != downstreamLnks.end(); dnStrmIt++) { currSegStats->laneGroup[*dnStrmIt].push_back(lnStatsIt->second); } } downstreamSegStats = currSegStats; } // *********** the commented for loop below is to print the lanes which do not have lane groups *** // for(SegmentStatsList::const_reverse_iterator statsRevIt=segStatsList.rbegin(); statsRevIt!=segStatsList.rend(); statsRevIt++) // { // const LaneStatsMap lnStatsMap = (*statsRevIt)->laneStatsMap; // unsigned int segId = (*statsRevIt)->getRoadSegment()->getSegmentAimsunId(); // uint16_t statsNum = (*statsRevIt)->statsNumberInSegment; // const std::vector<Lane*>& lanes = (*statsRevIt)->getRoadSegment()->getLanes(); // unsigned int numLanes = 0; // for(std::vector<Lane*>::const_iterator lnIt = lanes.begin(); lnIt!=lanes.end(); lnIt++) // { // if(!(*lnIt)->is_pedestrian_lane()) { numLanes++; } // } // for (LaneStatsMap::const_iterator lnStatsIt = lnStatsMap.begin(); lnStatsIt != lnStatsMap.end(); lnStatsIt++) // { // if(lnStatsIt->second->isLaneInfinity() || lnStatsIt->first->is_pedestrian_lane()) { continue; } // if(lnStatsIt->second->getDownstreamLinks().empty()) // { // Print() << "~~~ " << segId << "," << statsNum << "," << lnStatsIt->first->getLaneID() << "," << numLanes << std::endl; // } // } // } } } } void Conflux::log(std::string line) const { Log() << line; } PersonCount::PersonCount() : pedestrians(0), busPassengers(0), trainPassengers(0), carDrivers(0), motorCyclists(0), busDrivers(0), busWaiters(0), activityPerformers(0), carSharers(0), truckerLGV(0), truckerHGV(0) { } const PersonCount& PersonCount::operator+=(const PersonCount& personCount) { pedestrians += personCount.pedestrians; busPassengers += personCount.busPassengers; trainPassengers += personCount.trainPassengers; carDrivers += personCount.carDrivers; carSharers += personCount.carSharers; motorCyclists += personCount.motorCyclists; truckerLGV += personCount.truckerLGV; truckerHGV += personCount.truckerHGV; busDrivers += personCount.busDrivers; busWaiters += personCount.busWaiters; activityPerformers += personCount.activityPerformers; return *this; } unsigned int sim_mob::medium::PersonCount::getTotal() { return (pedestrians + busPassengers + trainPassengers + carDrivers + carSharers + motorCyclists + truckerLGV + truckerLGV + busDrivers + busWaiters + activityPerformers); } sim_mob::medium::PersonTransferMessage::PersonTransferMessage(Person_MT* person, SegmentStats* nextSegStats, const Lane* nextLane) : person(person), segStats(nextSegStats), lane(nextLane) { } sim_mob::medium::PersonTransferMessage::~PersonTransferMessage() { }
40.482683
220
0.614336
andrealho
6b30066df36fa2db5e3c24b1d938460d2b44de69
85
cpp
C++
tests/main.cpp
cbforks/sfl
21a28acc9fdbb578200e0289688610cdedb646d9
[ "BSD-2-Clause" ]
6
2015-04-14T19:04:15.000Z
2015-10-16T13:03:08.000Z
tests/main.cpp
zsszatmari/sfl
21a28acc9fdbb578200e0289688610cdedb646d9
[ "BSD-2-Clause" ]
null
null
null
tests/main.cpp
zsszatmari/sfl
21a28acc9fdbb578200e0289688610cdedb646d9
[ "BSD-2-Clause" ]
1
2015-10-16T13:03:11.000Z
2015-10-16T13:03:11.000Z
#include "stf.h" INIT_SFL int main(int argc, char *argv[]) { return runTests(); }
9.444444
32
0.647059
cbforks
6b359ed4f63f293852a8f7792ed36efeaf02ba1b
583
cpp
C++
tutoriat-poo-08/Seria CTI 26/model-01/JucarieElectronica.cpp
MaximTiberiu/Tutoriat-POO-2021-2022
73170623979ad3786007344c05e588f7f64f6435
[ "MIT" ]
null
null
null
tutoriat-poo-08/Seria CTI 26/model-01/JucarieElectronica.cpp
MaximTiberiu/Tutoriat-POO-2021-2022
73170623979ad3786007344c05e588f7f64f6435
[ "MIT" ]
null
null
null
tutoriat-poo-08/Seria CTI 26/model-01/JucarieElectronica.cpp
MaximTiberiu/Tutoriat-POO-2021-2022
73170623979ad3786007344c05e588f7f64f6435
[ "MIT" ]
null
null
null
#include "JucarieElectronica.h" JucarieElectronica::JucarieElectronica(const std::string &_denumire, float _dimensiune, const std::string &_tip, int _numarBaterii) : Jucarie(_denumire, _dimensiune, _tip) { this->numarBaterii = _numarBaterii; } void JucarieElectronica::read(std::istream &in) { Jucarie::read(in); std::cout << "Numar baterii: "; in >> numarBaterii; } void JucarieElectronica::print(std::ostream &out) const { Jucarie::print(out); out << "Numar baterii: " << numarBaterii << "\n"; }
30.684211
113
0.629503
MaximTiberiu
6b39ce2cf6249fa8d14f231883d6688c05bcc6ca
7,921
cpp
C++
kern/i686/mem/paging.cpp
greck2908/LudOS
db38455eb33dfc0dfc6d4be102e6bd54d852eee8
[ "MIT" ]
44
2018-01-28T20:07:48.000Z
2022-02-11T22:58:49.000Z
kern/i686/mem/paging.cpp
greck2908/LudOS
db38455eb33dfc0dfc6d4be102e6bd54d852eee8
[ "MIT" ]
2
2017-09-12T15:38:16.000Z
2017-11-05T12:19:01.000Z
kern/i686/mem/paging.cpp
greck2908/LudOS
db38455eb33dfc0dfc6d4be102e6bd54d852eee8
[ "MIT" ]
8
2018-08-17T13:30:57.000Z
2021-06-25T16:56:12.000Z
/* paging.cpp Copyright (c) 30 Yann BOUCHER (yann) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "paging.hpp" #include <stdint.h> #include "halt.hpp" #include "panic.hpp" #include "utils/logging.hpp" #include "utils/bitops.hpp" #include "i686/interrupts/isr.hpp" #include "i686/cpu/asmops.hpp" #include "physallocator.hpp" extern "C" int kernel_physical_end; static PagingInformation kernel_info; void Paging::init() { cli(); create_paging_info(kernel_info); isr::register_handler(isr::PageFault, page_fault_handler); uint32_t pd_addr { reinterpret_cast<uint32_t>(kernel_info.page_directory.data()) - KERNEL_VIRTUAL_BASE }; uint32_t cr4_var = cr4(); bit_clear(cr4_var, 4); // disable 4MB pages write_cr3(pd_addr); write_cr4(cr4_var); sti(); } void Paging::map_page(uintptr_t p_addr, void *v_addr, uint32_t flags) { auto entry = page_entry((uintptr_t)(v_addr)); assert(!entry->present); entry->phys_addr = p_addr >> 12; entry->write = !!(flags & Memory::Write); entry->cd = !!(flags & Memory::Uncached); entry->wt = !!(flags & Memory::WriteThrough); entry->user = !!(flags & Memory::User); entry->present = !(flags & Memory::Sentinel); entry->os_claimed = true; } void Paging::unmap_page(void *v_addr) { release_virtual_page(reinterpret_cast<uintptr_t>(v_addr)); } void Paging::identity_map(uintptr_t p_addr, size_t size, uint32_t flags) { size_t page_num = size/page_size + (size%page_size?1:0); for (size_t i { 0 }; i < page_num; ++i) { page_entry(p_addr + i * page_size)->os_claimed = true; map_page(p_addr + i * page_size, (uint8_t*)p_addr + i * page_size, flags); } } uintptr_t Paging::physical_address(const void *v_addr) { size_t offset = (uintptr_t)v_addr & 0xFFF; auto entry = page_entry(reinterpret_cast<uintptr_t>(v_addr)); if (!entry->present) return (uintptr_t)v_addr; return (entry->phys_addr << 12) + offset; } bool Paging::is_mapped(const void *v_addr) { return page_entry(reinterpret_cast<uintptr_t>(v_addr))->present; } bool Paging::check_user_ptr(const void *v_addr, size_t size) { size_t page_num = size/page_size + (size%page_size?1:0); auto entry = page_entry((uintptr_t)v_addr); for (size_t i { 0 }; i < page_num; ++i) { if (!entry[i].present || !entry[i].user) { return false; } } return true; } void Paging::unmap_user_space() { aligned_memsetl(page_entry(0), 0, (KERNEL_VIRTUAL_BASE >> 12)*sizeof(PTEntry)); // Reload the page tables write_cr3(cr3()); } void Paging::create_paging_info(PagingInformation &info) { log_serial("from %p to %p\n", info.page_directory.data(), info.page_directory.data() + info.page_directory.size()*sizeof(PDEntry)); auto get_addr = [](auto addr)->void* { return addr - KERNEL_VIRTUAL_BASE; //return (void*)Memory::physical_address((void*)addr); }; memset(info.page_directory.data(), 0, info.page_directory.size()*sizeof(PDEntry)); for (size_t i { 0 }; i < info.page_tables.size(); ++i) { memset(info.page_tables[i].data(), 0, info.page_tables[i].size()*sizeof(PTEntry)); info.page_directory[i].pt_addr = (reinterpret_cast<uintptr_t>(get_addr(info.page_tables[i].data())) - KERNEL_VIRTUAL_BASE) >> 12; info.page_directory[i].present = true; info.page_directory[i].os_claimed = true; info.page_directory[i].write = true; info.page_directory[i].user = true; } map_kernel(info); // map last dir entry to itself info.page_directory.back().pt_addr = (reinterpret_cast<uintptr_t>(get_addr(info.page_directory.data())) - KERNEL_VIRTUAL_BASE) >> 12; info.page_directory.back().write = true; info.page_directory.back().present = true; info.page_directory.back().os_claimed = true; info.page_directory.back().user = false; } uintptr_t Paging::alloc_virtual_page(size_t number, bool user) { assert(number != 0); constexpr size_t margin = 0; static size_t user_last_pos = USER_VIRTUAL_BASE >> 12; static size_t kernel_last_pos = KERNEL_VIRTUAL_BASE >> 12; const size_t base = (user ? USER_VIRTUAL_BASE : KERNEL_VIRTUAL_BASE) >> 12; size_t& last_pos = user ? user_last_pos : kernel_last_pos; PTEntry* entries = page_entry(0); uintptr_t addr { 0 }; size_t counter { 0 }; number += margin; loop: for (size_t i { last_pos }; i < (user ? (KERNEL_VIRTUAL_BASE >> 12) : ram_maxpage); ++i) { if (!entries[i].os_claimed) { assert(!entries[i].present); if (counter++ == 0) addr = i; } else { counter = 0; } if (counter == number) { last_pos = i; for (size_t j { addr }; j < addr + number + margin; ++j) { entries[j].os_claimed = true; // mark these entries as reclaimed so they cannot be claimed again while still not mapped } return addr * page_size + (margin/2*page_size); } } // Reloop if (last_pos != base) { log_serial("virtual reloop, size %d\n", number); last_pos = base; goto loop; } panic("no more virtual addresses available"); return 0; } bool Paging::release_virtual_page(uintptr_t v_addr, size_t number, ReleaseFlags flags) { #if 1 auto entry = page_entry(v_addr); for (size_t i { 0 }; i < number; ++i) { //assert(entry[i].present); assert(entry[i].os_claimed); assert(flags == FreePage); entry[i].present = false; entry[i].os_claimed = false; invlpg(v_addr + i*page_size); } #else // FIXME auto base = page_entry(v_addr); memset(base, 0, number*sizeof(PTEntry)); for (size_t i { 0 }; i < number; ++i) { asm volatile ("invlpg (%0)"::"r"(reinterpret_cast<uint8_t*>(v_addr) + i*page_size) : "memory"); } #endif return true; } void Paging::map_kernel(PagingInformation& info) { uint32_t pdindex = KERNEL_VIRTUAL_BASE >> 22; uint32_t ptindex = KERNEL_VIRTUAL_BASE >> 12 & 0x03FF; PageTable * pt = reinterpret_cast<PageTable*>((info.page_directory[pdindex].pt_addr << 12) + KERNEL_VIRTUAL_BASE); PTEntry* entry = &(*pt)[ptindex]; for (uint32_t addr { 0 }; addr <= reinterpret_cast<uint32_t>(&kernel_physical_end) + page_size; addr+=page_size, ++entry) { entry->phys_addr = addr >> 12; entry->present = true; entry->os_claimed = true; entry->write = true; entry->user = true; } } PTEntry *Paging::page_entry(uintptr_t addr) { uint32_t pdindex = addr >> 22; uint32_t ptindex = addr >> 12 & 0x03FF; PageTable * pt = reinterpret_cast<PageTable*>(((kernel_info.page_directory)[pdindex].pt_addr << 12) + KERNEL_VIRTUAL_BASE); return &(*pt)[ptindex]; }
28.908759
137
0.656862
greck2908
6b3d4042e2c5b07b7a2f29c4e13b98a60b1b73e3
5,253
hpp
C++
OptFrame/ExtendedMultiObjSearch.hpp
vncoelho/optmarket
dcfa8d909da98d89a464eda2420c38b0526f900c
[ "MIT" ]
null
null
null
OptFrame/ExtendedMultiObjSearch.hpp
vncoelho/optmarket
dcfa8d909da98d89a464eda2420c38b0526f900c
[ "MIT" ]
null
null
null
OptFrame/ExtendedMultiObjSearch.hpp
vncoelho/optmarket
dcfa8d909da98d89a464eda2420c38b0526f900c
[ "MIT" ]
null
null
null
// OptFrame - Optimization Framework // Copyright (C) 2009-2015 // http://optframe.sourceforge.net/ // // This file is part of the OptFrame optimization framework. This framework // is free software; you can redistribute it and/or modify it under the // terms of the GNU Lesser General Public License v3 as published by the // Free Software Foundation. // This framework 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 v3 for more details. // You should have received a copy of the GNU Lesser General Public License v3 // along with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. #ifndef OPTFRAME_EXTENDED_MULTI_OBJ_SEARCH_HPP_ #define OPTFRAME_EXTENDED_MULTI_OBJ_SEARCH_HPP_ #include <iostream> #include <vector> using namespace std; #include "Solution.hpp" #include "Population.hpp" #include "Evaluation.hpp" #include "MultiEvaluator.hpp" #include "Component.hpp" #include "ComponentBuilder.h" #include "MultiObjSearch.hpp" namespace optframe { template<class R, class X, class ADS = OPTFRAME_DEFAULT_ADS> class ExtendedPareto { private: vector<Solution<R>*> paretoSet; vector<vector<MultiEvaluation*> > paretoFront; vector<Population<X, ADS>*> decodedSolutions; public: ExtendedPareto() { } virtual ~ExtendedPareto() { for(unsigned i = 0; i < paretoSet.size(); i++) delete paretoSet[i]; paretoSet.clear(); for(unsigned i = 0; i < paretoFront.size(); i++) { for(unsigned j = 0; j < paretoFront[i].size(); j++) delete paretoFront[i][j]; paretoFront[i].clear(); } paretoFront.clear(); for(unsigned i = 0; i < decodedSolutions.size(); i++) delete decodedSolutions[i]; decodedSolutions.clear(); } Pareto<X>* getPareto() { return NULL; } void push_back(Solution<R>* s, vector<MultiEvaluation*>& v_e, Population<X, ADS>* v_x) { paretoSet.push_back(s); paretoFront.push_back(v_e); decodedSolutions.push_back(v_x); } void push_back(const Solution<R, ADS>& s, const vector<MultiEvaluation*>& v_e, const Population<X, ADS>& v_x) { paretoSet.push_back(&s->clone()); vector<MultiEvaluation*> ve; for(unsigned mev = 0; mev < v_e.size(); mev++) ve.push_back(&v_e[mev]->clone()); paretoFront.push_back(ve); decodedSolutions.push_back(&v_x.clone()); } unsigned size() { return paretoSet.size(); } pair<Solution<R>*, pair<vector<MultiEvaluation*>, vector<Population<X, ADS>*> > > erase(unsigned index) { vector<MultiEvaluation*> vme = paretoFront.at(index); Population<X, ADS>* pop = decodedSolutions.at(index); pair<vector<MultiEvaluation*>, Population<X, ADS>*> p1 = make_pair(vme, pop); pair<Solution<R>*, pair<vector<MultiEvaluation*>, Population<X, ADS>*> > p; p = make_pair(paretoSet.at(index), p1); paretoSet.erase(paretoSet.begin() + index); paretoSet.erase(paretoFront.begin() + index); decodedSolutions.erase(decodedSolutions.begin() + index); return p; } pair<Solution<R>*, pair<vector<MultiEvaluation*>, Population<X, ADS>*> > at(unsigned index) { vector<MultiEvaluation*> vme = paretoFront.at(index); Population<X, ADS>* pop = decodedSolutions.at(index); pair<vector<MultiEvaluation*>, Population<X, ADS>*> p1 = make_pair(vme, pop); return make_pair(paretoSet.at(index), p1); } vector<Solution<R, ADS>*> getParetoSet() { return paretoSet; } vector<vector<Evaluation*> > getParetoFront() { return paretoFront; } void print() const { cout << "ExtendedPareto size=" << paretoFront.size(); cout << endl; } }; template<class R, class X, class ADS = OPTFRAME_DEFAULT_ADS> class ExtendedMultiObjSearch: public Component { public: ExtendedMultiObjSearch() { } virtual ~ExtendedMultiObjSearch() { } virtual ExtendedPareto<R, X, ADS>* search(double timelimit = 100000000, double target_f = 0, ExtendedPareto<R, X, ADS>* _pf = NULL) = 0; virtual string log() { return "Empty heuristic log."; } virtual bool compatible(string s) { return (s == idComponent()) || (Component::compatible(s)); } static string idComponent() { stringstream ss; ss << Component::idComponent() << "ExtendedMultiObjSearch:"; return ss.str(); } virtual string id() const { return idComponent(); } }; template<class R, class X, class ADS = OPTFRAME_DEFAULT_ADS> class ExtendedMultiObjSearchBuilder: public ComponentBuilder<R, ADS> { public: virtual ~ExtendedMultiObjSearchBuilder() { } virtual ExtendedMultiObjSearch<R, X, ADS>* build(Scanner& scanner, HeuristicFactory<R, ADS>& hf, string family = "") = 0; virtual Component* buildComponent(Scanner& scanner, HeuristicFactory<R, ADS>& hf, string family = "") { return build(scanner, hf, family); } virtual vector<pair<string, string> > parameters() = 0; virtual bool canBuild(string) = 0; static string idComponent() { stringstream ss; ss << ComponentBuilder<R, ADS>::idComponent() << "ExtendedMultiObjSearch:"; return ss.str(); } virtual string id() const { return idComponent(); } }; } #endif /* OPTFRAME_EXTENDED_MULTI_OBJ_SEARCH_HPP_ */
24.207373
137
0.708738
vncoelho
6b3d6a259aef74060a38f16d03f74b78618f52ae
16,673
cc
C++
mysql-server/storage/perfschema/pfs_data_lock.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/storage/perfschema/pfs_data_lock.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/storage/perfschema/pfs_data_lock.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** @file storage/perfschema/pfs_data_lock.cc The performance schema implementation for data locks. */ #include "storage/perfschema/pfs_data_lock.h" #include <stddef.h> #include "my_dbug.h" /* clang-format off */ /** @page PAGE_PFS_DATA_LOCKS Performance schema data locks @section SERVER_ENGINE_INTERFACE Server / Storage engine interface @subsection SE_INTERFACE_REGISTRATION Registration @startuml title Registration participant server as "MySQL server" participant pfs as "Performance schema" participant se as "Storage Engine" participant se_inspector as "Storage Engine\nData Lock Inspector" == plugin init == server -> se : plugin_init() se -> pfs : register_data_lock() == SELECT * FROM performance_schema.data_locks == server -> pfs : table_data_locks::rnd_next() pfs -> se_inspector : (multiple calls) == plugin deinit == server -> se : plugin_deinit() se -> pfs : unregister_data_lock() @enduml To expose DATA_LOCKS to the performance schema, a storage engine needs to: - implement a sub class of #PSI_engine_data_lock_inspector - register it with the performance schema on init - unregister it with the performance schema on deinit While the storage engine is in use (between init and deinit), the performance schema keeps a reference to the data lock inspector given, and use it to inspect the storage engine data locks. @subsection SE_INTERFACE_SCAN_1 Iteration for each storage engine @startuml title Iteration for each storage engine participant server as "MySQL server" participant pfs as "Performance schema\nTable data_locks" participant pfs_container as "Performance schema\nData Lock container" participant se_inspector as "Storage Engine\nData Lock Inspector" participant se_iterator as "Storage Engine\nData Lock Iterator" == SELECT init == server -> pfs : rnd_init() activate pfs_container pfs -> pfs_container : create() == For each storage engine == pfs -> se_inspector : create_iterator() activate se_iterator se_inspector -> se_iterator : create() pfs -> se_iterator : (multiple calls) pfs -> se_iterator : destroy() deactivate se_iterator == SELECT end == server -> pfs : rnd_end() pfs -> pfs_container : destroy() deactivate pfs_container @enduml When the server performs a SELECT * from performance_schema.data_locks, the performance schema creates a #PSI_server_data_lock_container for the duration of the table scan. Then, the scan loops for each storage engine capable of exposing data locks (that is, engines that registered a data lock inspector). For each engine, the inspector is called to create an iterator, dedicated for this SELECT scan. @subsection SE_INTERFACE_SCAN_2 Iteration inside a storage engine @startuml title Iteration inside a storage engine participant server as "MySQL server" participant pfs as "Performance schema\nTable data_locks" participant pfs_container as "Performance schema\nData Lock container" participant se_iterator as "Storage Engine\nData Lock Iterator" loop until the storage engine iterator is done == SELECT scan == server -> pfs : rnd_next() == First scan, fetch N rows at once from the storage engine == pfs -> se_iterator : scan() se_iterator -> pfs_container : add_row() // 1 se_iterator -> pfs_container : add_row() // 2 se_iterator -> pfs_container : ... se_iterator -> pfs_container : add_row() // N pfs -> pfs_container : get_row(1) pfs -> server : result set row 1 == Subsequent scans, return the rows collected == server -> pfs : rnd_next() pfs -> pfs_container : get_row(2) pfs -> server : result set row 2 server -> pfs : rnd_next() pfs -> pfs_container : get_row(...) pfs -> server : result set row ... server -> pfs : rnd_next() pfs -> pfs_container : get_row(N) pfs -> server : result set row N end @enduml When table_data_locks::rnd_next() is first called, the performance schema calls the storage engine iterator, which adds N rows in the data container. Upon subsequent calls to table_data_locks::rnd_next(), data present in the container is returned. This process loops until the storage engine iterator finally reports that it reached the end of the scan. Note that the storage engine iterator has freedom to implement: - either a full table scan, returning all rows in a single call, - or a restartable scan, returning only a few rows in each call. The major benefit of this interface is that the engine iterator can stop and restart a scan at natural boundaries within the storage engine (say, return all the locks for one transaction per call), which simplifies a lot the storage engine implementation. */ /* clang-format on */ PFS_data_cache::PFS_data_cache() {} PFS_data_cache::~PFS_data_cache() {} const char *PFS_data_cache::cache_data(const char *ptr, size_t length) { /* std::string is just a sequence of bytes, which actually can contain a 0 byte ... Never use strlen() on the binary data. */ std::string key(ptr, length); std::pair<set_type::iterator, bool> ret; ret = m_set.insert(key); return (*ret.first).data(); } void PFS_data_cache::clear() { m_set.clear(); } PFS_data_lock_container::PFS_data_lock_container() : m_logical_row_index(0), m_filter(nullptr) {} PFS_data_lock_container::~PFS_data_lock_container() {} const char *PFS_data_lock_container::cache_string(const char *string) { return m_cache.cache_data(string, strlen(string)); } const char *PFS_data_lock_container::cache_data(const char *ptr, size_t length) { return m_cache.cache_data(ptr, length); } bool PFS_data_lock_container::accept_engine(const char *engine, size_t engine_length) { if (m_filter != nullptr) { return m_filter->match_engine(engine, engine_length); } return true; } bool PFS_data_lock_container::accept_lock_id(const char *engine_lock_id, size_t engine_lock_id_length) { if (m_filter != nullptr) { return m_filter->match_lock_id(engine_lock_id, engine_lock_id_length); } return true; } bool PFS_data_lock_container::accept_transaction_id(ulonglong transaction_id) { if (m_filter != nullptr) { return m_filter->match_transaction_id(transaction_id); } return true; } bool PFS_data_lock_container::accept_thread_id_event_id(ulonglong thread_id, ulonglong event_id) { if (m_filter != nullptr) { return m_filter->match_thread_id_event_id(thread_id, event_id); } return true; } bool PFS_data_lock_container::accept_object( const char *table_schema, size_t table_schema_length, const char *table_name, size_t table_name_length, const char *partition_name, size_t partition_name_length, const char *sub_partition_name, size_t sub_partition_name_length) { if (m_filter != nullptr) { return m_filter->match_object(table_schema, table_schema_length, table_name, table_name_length, partition_name, partition_name_length, sub_partition_name, sub_partition_name_length); } return true; } void PFS_data_lock_container::add_lock_row( const char *engine, size_t engine_length MY_ATTRIBUTE((unused)), const char *engine_lock_id, size_t engine_lock_id_length, ulonglong transaction_id, ulonglong thread_id, ulonglong event_id, const char *table_schema, size_t table_schema_length, const char *table_name, size_t table_name_length, const char *partition_name, size_t partition_name_length, const char *sub_partition_name, size_t sub_partition_name_length, const char *index_name, size_t index_name_length, const void *identity, const char *lock_mode, const char *lock_type, const char *lock_status, const char *lock_data) { row_data_lock row; row.m_engine = engine; if (engine_lock_id != nullptr) { size_t len = engine_lock_id_length; if (len > sizeof(row.m_hidden_pk.m_engine_lock_id)) { DBUG_ASSERT(false); len = sizeof(row.m_hidden_pk.m_engine_lock_id); } if (len > 0) { memcpy(row.m_hidden_pk.m_engine_lock_id, engine_lock_id, len); } row.m_hidden_pk.m_engine_lock_id_length = len; } else { row.m_hidden_pk.m_engine_lock_id_length = 0; } row.m_transaction_id = transaction_id; row.m_thread_id = thread_id; row.m_event_id = event_id; row.m_index_row.m_object_row.m_object_type = OBJECT_TYPE_TABLE; if (table_schema_length > 0) { memcpy(row.m_index_row.m_object_row.m_schema_name, table_schema, table_schema_length); } row.m_index_row.m_object_row.m_schema_name_length = table_schema_length; if (table_name_length > 0) { memcpy(row.m_index_row.m_object_row.m_object_name, table_name, table_name_length); } row.m_index_row.m_object_row.m_object_name_length = table_name_length; row.m_partition_name = partition_name; row.m_partition_name_length = partition_name_length; row.m_sub_partition_name = sub_partition_name; row.m_sub_partition_name_length = sub_partition_name_length; if (index_name_length > 0) { memcpy(row.m_index_row.m_index_name, index_name, index_name_length); } row.m_index_row.m_index_name_length = index_name_length; row.m_identity = identity; row.m_lock_mode = lock_mode; row.m_lock_type = lock_type; row.m_lock_status = lock_status; row.m_lock_data = lock_data; m_rows.push_back(row); } void PFS_data_lock_container::clear() { m_logical_row_index = 0; m_rows.clear(); m_cache.clear(); } void PFS_data_lock_container::shrink() { /* Keep rows numbering. */ m_logical_row_index += m_rows.size(); /* Discard existing data. */ m_rows.clear(); m_cache.clear(); } row_data_lock *PFS_data_lock_container::get_row(size_t index) { if (index < m_logical_row_index) { /* This row existed, before a call to ::shrink(). The caller should not ask for it again. */ DBUG_ASSERT(false); return nullptr; } size_t physical_index = index - m_logical_row_index; if (physical_index < m_rows.size()) { return &m_rows[physical_index]; } return nullptr; } PFS_data_lock_wait_container::PFS_data_lock_wait_container() : m_logical_row_index(0), m_filter(nullptr) {} PFS_data_lock_wait_container::~PFS_data_lock_wait_container() {} const char *PFS_data_lock_wait_container::cache_string(const char *string) { return m_cache.cache_data(string, strlen(string)); } const char *PFS_data_lock_wait_container::cache_data(const char *ptr, size_t length) { return m_cache.cache_data(ptr, length); } bool PFS_data_lock_wait_container::accept_engine(const char *engine, size_t engine_length) { if (m_filter != nullptr) { return m_filter->match_engine(engine, engine_length); } return true; } bool PFS_data_lock_wait_container::accept_requesting_lock_id( const char *engine_lock_id, size_t engine_lock_id_length) { if (m_filter != nullptr) { return m_filter->match_requesting_lock_id(engine_lock_id, engine_lock_id_length); } return true; } bool PFS_data_lock_wait_container::accept_blocking_lock_id( const char *engine_lock_id, size_t engine_lock_id_length) { if (m_filter != nullptr) { return m_filter->match_blocking_lock_id(engine_lock_id, engine_lock_id_length); } return true; } bool PFS_data_lock_wait_container::accept_requesting_transaction_id( ulonglong transaction_id) { if (m_filter != nullptr) { return m_filter->match_requesting_transaction_id(transaction_id); } return true; } bool PFS_data_lock_wait_container::accept_blocking_transaction_id( ulonglong transaction_id) { if (m_filter != nullptr) { return m_filter->match_blocking_transaction_id(transaction_id); } return true; } bool PFS_data_lock_wait_container::accept_requesting_thread_id_event_id( ulonglong thread_id, ulonglong event_id) { if (m_filter != nullptr) { return m_filter->match_requesting_thread_id_event_id(thread_id, event_id); } return true; } bool PFS_data_lock_wait_container::accept_blocking_thread_id_event_id( ulonglong thread_id, ulonglong event_id) { if (m_filter != nullptr) { return m_filter->match_blocking_thread_id_event_id(thread_id, event_id); } return true; } void PFS_data_lock_wait_container::add_lock_wait_row( const char *engine, size_t engine_length MY_ATTRIBUTE((unused)), const char *requesting_engine_lock_id, size_t requesting_engine_lock_id_length, ulonglong requesting_transaction_id, ulonglong requesting_thread_id, ulonglong requesting_event_id, const void *requesting_identity, const char *blocking_engine_lock_id, size_t blocking_engine_lock_id_length, ulonglong blocking_transaction_id, ulonglong blocking_thread_id, ulonglong blocking_event_id, const void *blocking_identity) { row_data_lock_wait row; row.m_engine = engine; if (requesting_engine_lock_id != nullptr) { size_t len = requesting_engine_lock_id_length; if (len > sizeof(row.m_hidden_pk.m_requesting_engine_lock_id)) { DBUG_ASSERT(false); len = sizeof(row.m_hidden_pk.m_requesting_engine_lock_id); } if (len > 0) { memcpy(row.m_hidden_pk.m_requesting_engine_lock_id, requesting_engine_lock_id, len); } row.m_hidden_pk.m_requesting_engine_lock_id_length = len; } else { row.m_hidden_pk.m_requesting_engine_lock_id_length = 0; } row.m_requesting_transaction_id = requesting_transaction_id; row.m_requesting_thread_id = requesting_thread_id; row.m_requesting_event_id = requesting_event_id; row.m_requesting_identity = requesting_identity; if (blocking_engine_lock_id != nullptr) { size_t len = blocking_engine_lock_id_length; if (len > sizeof(row.m_hidden_pk.m_blocking_engine_lock_id)) { DBUG_ASSERT(false); len = sizeof(row.m_hidden_pk.m_blocking_engine_lock_id); } if (len > 0) { memcpy(row.m_hidden_pk.m_blocking_engine_lock_id, blocking_engine_lock_id, len); } row.m_hidden_pk.m_blocking_engine_lock_id_length = len; } else { row.m_hidden_pk.m_blocking_engine_lock_id_length = 0; } row.m_blocking_transaction_id = blocking_transaction_id; row.m_blocking_thread_id = blocking_thread_id; row.m_blocking_event_id = blocking_event_id; row.m_blocking_identity = blocking_identity; m_rows.push_back(row); } void PFS_data_lock_wait_container::clear() { m_logical_row_index = 0; m_rows.clear(); m_cache.clear(); } void PFS_data_lock_wait_container::shrink() { /* Keep rows numbering. */ m_logical_row_index += m_rows.size(); /* Discard existing data. */ m_rows.clear(); m_cache.clear(); } row_data_lock_wait *PFS_data_lock_wait_container::get_row(size_t index) { if (index < m_logical_row_index) { /* This row existed, before a call to ::shrink(). The caller should not ask for it again. */ DBUG_ASSERT(false); return nullptr; } size_t physical_index = index - m_logical_row_index; if (physical_index < m_rows.size()) { return &m_rows[physical_index]; } return nullptr; }
31.940613
80
0.727164
silenc3502
6b3fd6236942fff87335aeb6ac752992043ee248
63
cpp
C++
Source/FSD/Private/DorrettaHead.cpp
Dr-Turtle/DRG_ModPresetManager
abd7ff98a820969504491a1fe68cf2f9302410dc
[ "MIT" ]
8
2021-07-10T20:06:05.000Z
2022-03-04T19:03:50.000Z
Source/FSD/Private/DorrettaHead.cpp
Dr-Turtle/DRG_ModPresetManager
abd7ff98a820969504491a1fe68cf2f9302410dc
[ "MIT" ]
9
2022-01-13T20:49:44.000Z
2022-03-27T22:56:48.000Z
Source/FSD/Private/DorrettaHead.cpp
Dr-Turtle/DRG_ModPresetManager
abd7ff98a820969504491a1fe68cf2f9302410dc
[ "MIT" ]
2
2021-07-10T20:05:42.000Z
2022-03-14T17:05:35.000Z
#include "DorrettaHead.h" ADorrettaHead::ADorrettaHead() { }
10.5
32
0.730159
Dr-Turtle
6b3fda02bbb70da932461a55eb2907a5d6604f46
4,856
cc
C++
projects/MatlabTranslation/src/typeInference/SSAForm.cc
ouankou/rose
76f2a004bd6d8036bc24be2c566a14e33ba4f825
[ "BSD-3-Clause" ]
488
2015-01-09T08:54:48.000Z
2022-03-30T07:15:46.000Z
projects/MatlabTranslation/src/typeInference/SSAForm.cc
ouankou/rose
76f2a004bd6d8036bc24be2c566a14e33ba4f825
[ "BSD-3-Clause" ]
174
2015-01-28T18:41:32.000Z
2022-03-31T16:51:05.000Z
projects/MatlabTranslation/src/typeInference/SSAForm.cc
ouankou/rose
76f2a004bd6d8036bc24be2c566a14e33ba4f825
[ "BSD-3-Clause" ]
146
2015-04-27T02:48:34.000Z
2022-03-04T07:32:53.000Z
#include <set> #include <vector> #include <map> #include <algorithm> #include <iostream> // TODO: delete later #include "SSAForm.h" #include "rose.h" #include "sageGeneric.h" //~ #include "utility/utils.h" //~ #include "FastNumericsRoseSupport.h" //~ #include "TypeAttribute.h" namespace si = SageInterface; namespace sb = SageBuilder; namespace sg = SageGeneric; struct SSAContext { typedef std::vector<std::pair<SgExpression*, int> > node_updates; typedef std::map<SgName, size_t> symbol_state; SSAContext() : lvalue_candidate(false), updates(), symbols(NULL) {} static SSAContext create() { return SSAContext(node_updates(), new symbol_state); } static void destroy(SSAContext& ctx) { delete ctx.symbols; } void setLValue(bool lval) { lvalue = lval; } bool isLValue() const { return lvalue; } private: SSAContext(node_updates nodes, symbol_state* symbols) : updates(), symbols(symbols) {} bool lvalue; node_updates updates; symbol_state* symbols; }; struct SSAResult { std::set<SgName> updated_symbols; }; struct SSAConverter : AstTopDownBottomUpProcessing<SSAContext, SSAResult> { typedef AstTopDownBottomUpProcessing<InheritedAttr, SynthesizedAttr> base; typedef SSAContext inherited_type; typedef SSAResult synthesized_type; typedef base::SynthesizedAttributesList synthesized_attributes; inherited_type evaluateInheritedAttribute(SgNode* n, inherited_type inh) override; synthesized_type evaluateSynthesizedAttribute(SgNode* n, inherited_type inh, synthesized_attributes syn) override; }; struct LValueCandidateSetter : sg::DispatchHandler<SSAContext> { LValueCandidateSetter() = delete; LValueCandidateSetter(SSAContext ssactx, SgExpression& node) : base(ssactx), expr(n) {} void handle(SgNode&) { ROSE_ASSERT(false); } void handle(SgAssignOp& n) { // set lvalue, if this expr is on the left hand side of an assignment // expr = 1872; res.setLValueCand(n.get_lhs_operand() == &expr); } void handle(SgArrayRefExp& n) { // clear lvalue, if this expr is on the right hand side of an array index // e.g., arr[expr] = 1234; if (!res.isLValueCand() || (n.get_rhs_operand() != &expr)) return; res.setLValueCand(false); } // operator SSAContext() { return res; } private: SgExpression& expr; }; struct SSAInheritedEval : sg::DispatchHandler<SSAContext> { typedef sg::DispatchHandler<SSAContext> base; SSAInheritedEval() = delete; explicit SSAInheritedEval(SSAContext ssactx) : base(ssactx), ssaContext(ssactx) {} void handle(SgNode&) { ROSE_ASSERT(false); } void setLValueInfo(SgExpression& e) { res = sg::dispatch( LValueCandidateSetter(e, res), sg::deref(e.get_parent() ); } void handle(SgStatement&) {} void handle(SgExpression& e) { setLValueInfo(e); } void handle(SgVarRefExp& n) { setLValueInfo(e); } void handle(SgFunctionDefinition&) { // context is created here and will be destroyed // by the bottom up evaluator. res = SSAContext::create(); } private: SSAContext ssactx; }; struct SSASynthesizedEval : sg::DispatchHandler<SSAResult> { typedef sg::DispatchHandler<SSAContext> base; SSASynthesizedEval() = delete; SSASynthesizedEval(SSAContext ssactx, SSAConverter::synthesized_attributes lst) : base(), ctx(ssactx), attr(lst) {} void handle(SgNode&) { ROSE_ASSERT(false); } void handle(SgStatement&) {} void handle(SgExpression& n) { } void handle(SgVarRefExp& n) { if (ctx.isLValue()) { updateLValueName(n, ctx); } else { updateRValueName(n, ctx); } } void handle(SgFunctionDefinition&) { SSAContext::destroy(ctx); } private: SSAContext ctx; SSAConverter::synthesized_attributes attr; }; SSAConverter::inherited_type evaluateInheritedAttribute(SgNode* n, inherited_type inh) { return sg::dispatch(SSAInheritedEval(inh), sg::deref(n)); } SSAConverter::synthesized_type evaluateSynthesizedAttribute(SgNode* n, inherited_type inh, synthesized_attributes syn) { return sg::dispatch(SSASynthesizedEval(inh, syn), sg::deref(n)); } /// converts a function to SSA form void convertToSSA (SgFunctionDefinition* def) { } void convertToSSA(SgProject* proj) { } /// converts a function from SSA to normal form void convertFromSSA(SgFunctionDefinition* def) {} void convertFromSSA(SgProject* proj) {}
21.39207
116
0.646829
ouankou
6b4085bf11b4a679e0c0b5dad56a0732b690b450
3,566
hpp
C++
cpp/src/binaryop/jit/util.hpp
BenikaHall/cudf
d3f5add210293a4832dafb85f04cbb73149b9d54
[ "Apache-2.0" ]
null
null
null
cpp/src/binaryop/jit/util.hpp
BenikaHall/cudf
d3f5add210293a4832dafb85f04cbb73149b9d54
[ "Apache-2.0" ]
1
2021-02-23T18:05:36.000Z
2021-02-23T18:05:36.000Z
cpp/src/binaryop/jit/util.hpp
BenikaHall/cudf
d3f5add210293a4832dafb85f04cbb73149b9d54
[ "Apache-2.0" ]
1
2020-11-10T03:19:16.000Z
2020-11-10T03:19:16.000Z
/* * Copyright (c) 2019, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cudf/binaryop.hpp> #include <string> namespace cudf { namespace binops { namespace jit { /** * @brief Orientation of lhs and rhs in operator */ enum class OperatorType { Direct, ///< Orientation of operands is op(lhs, rhs) Reverse ///< Orientation of operands is op(rhs, lhs) }; /** * @brief Get the Operator Name * * @param op The binary operator as enum of type cudf::binary_operator * @param type @see OperatorType * @return std::string The name of the operator as string */ std::string inline get_operator_name(binary_operator op, OperatorType type) { std::string const operator_name = [op] { // clang-format off switch (op) { case binary_operator::ADD: return "Add"; case binary_operator::SUB: return "Sub"; case binary_operator::MUL: return "Mul"; case binary_operator::DIV: return "Div"; case binary_operator::TRUE_DIV: return "TrueDiv"; case binary_operator::FLOOR_DIV: return "FloorDiv"; case binary_operator::MOD: return "Mod"; case binary_operator::PYMOD: return "PyMod"; case binary_operator::POW: return "Pow"; case binary_operator::EQUAL: return "Equal"; case binary_operator::NOT_EQUAL: return "NotEqual"; case binary_operator::LESS: return "Less"; case binary_operator::GREATER: return "Greater"; case binary_operator::LESS_EQUAL: return "LessEqual"; case binary_operator::GREATER_EQUAL: return "GreaterEqual"; case binary_operator::BITWISE_AND: return "BitwiseAnd"; case binary_operator::BITWISE_OR: return "BitwiseOr"; case binary_operator::BITWISE_XOR: return "BitwiseXor"; case binary_operator::LOGICAL_AND: return "LogicalAnd"; case binary_operator::LOGICAL_OR: return "LogicalOr"; case binary_operator::GENERIC_BINARY: return "UserDefinedOp"; case binary_operator::SHIFT_LEFT: return "ShiftLeft"; case binary_operator::SHIFT_RIGHT: return "ShiftRight"; case binary_operator::SHIFT_RIGHT_UNSIGNED: return "ShiftRightUnsigned"; case binary_operator::LOG_BASE: return "LogBase"; case binary_operator::ATAN2: return "ATan2"; case binary_operator::PMOD: return "PMod"; case binary_operator::NULL_EQUALS: return "NullEquals"; case binary_operator::NULL_MAX: return "NullMax"; case binary_operator::NULL_MIN: return "NullMin"; default: return "None"; } // clang-format on }(); return type == OperatorType::Direct ? operator_name : 'R' + operator_name; } } // namespace jit } // namespace binops } // namespace cudf
41.952941
78
0.63152
BenikaHall
6b4507a4a754dc25b3895b663be5da6fbefd1b40
264
cpp
C++
opencl/source/os_interface/linux/driver_info.cpp
Rajpratik71/compute-runtime
fe2ac18dac6f573496351ad83f4356bea3af4a97
[ "MIT" ]
null
null
null
opencl/source/os_interface/linux/driver_info.cpp
Rajpratik71/compute-runtime
fe2ac18dac6f573496351ad83f4356bea3af4a97
[ "MIT" ]
null
null
null
opencl/source/os_interface/linux/driver_info.cpp
Rajpratik71/compute-runtime
fe2ac18dac6f573496351ad83f4356bea3af4a97
[ "MIT" ]
null
null
null
/* * Copyright (C) 2017-2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "opencl/source/device/driver_info.h" namespace NEO { DriverInfo *DriverInfo::create(OSInterface *osInterface) { return new DriverInfo(); }; } // namespace NEO
17.6
58
0.704545
Rajpratik71
6b4560b56f41190326b18835669de11a7881b7c3
9,308
cpp
C++
src/Pegasus/Config/LogPropertyOwner.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
null
null
null
src/Pegasus/Config/LogPropertyOwner.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
null
null
null
src/Pegasus/Config/LogPropertyOwner.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
1
2022-03-07T22:54:02.000Z
2022-03-07T22:54:02.000Z
//%2005//////////////////////////////////////////////////////////////////////// // // Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development // Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems. // Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.; // IBM Corp.; EMC Corporation, The Open Group. // Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.; // IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group. // Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.; // EMC Corporation; VERITAS Software Corporation; The Open Group. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE SHALL BE INCLUDED IN // ALL COPIES OR SUBSTANTIAL PORTIONS OF THE SOFTWARE. THE SOFTWARE IS PROVIDED // "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // //============================================================================== // // Author: Nag Boranna (nagaraja_boranna@hp.com) // // Modified By: Yi Zhou (yi_zhou@hp.com) // Dave Rosckes (rosckes@us.ibm.com) // Aruran, IBM (ashanmug@in.ibm.com) for Bug# 3614 // Vijay Eli, IBM, (vijayeli@in.ibm.com) for Bug# 3613 // Aruran, IBM (ashanmug@in.ibm.com) for Bug# 3613 // //%///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // // This file has implementation for the log property owner class. // /////////////////////////////////////////////////////////////////////////////// #include "LogPropertyOwner.h" #include <Pegasus/Common/Logger.h> PEGASUS_USING_STD; PEGASUS_NAMESPACE_BEGIN /////////////////////////////////////////////////////////////////////////////// // LogPropertyOwner /////////////////////////////////////////////////////////////////////////////// static struct ConfigPropertyRow properties[] = { #if defined(PEGASUS_USE_RELEASE_CONFIG_OPTIONS) && !defined(PEGASUS_OS_OS400) #if !defined(PEGASUS_USE_SYSLOGS) {"logdir", "./logs", IS_DYNAMIC, 0, 0, IS_HIDDEN}, #endif {"logLevel", "SEVERE", IS_DYNAMIC, 0, 0, IS_HIDDEN} #else #if !defined(PEGASUS_USE_SYSLOGS) {"logdir", "./logs", IS_DYNAMIC, 0, 0, IS_VISIBLE}, #endif {"logLevel", "INFORMATION", IS_DYNAMIC, 0, 0, IS_VISIBLE} #endif }; const Uint32 NUM_PROPERTIES = sizeof(properties) / sizeof(properties[0]); /** Constructors */ LogPropertyOwner::LogPropertyOwner() { #if !defined(PEGASUS_USE_SYSLOGS) _logdir.reset(new ConfigProperty); #endif _logLevel.reset(new ConfigProperty); } /** Initialize the config properties. */ void LogPropertyOwner::initialize() { for (Uint32 i = 0; i < NUM_PROPERTIES; i++) { // // Initialize the properties with default values // #if !defined (PEGASUS_USE_SYSLOGS) if (String::equalNoCase(properties[i].propertyName, "logdir")) { _logdir->propertyName = properties[i].propertyName; _logdir->defaultValue = properties[i].defaultValue; _logdir->currentValue = properties[i].defaultValue; _logdir->plannedValue = properties[i].defaultValue; _logdir->dynamic = properties[i].dynamic; _logdir->domain = properties[i].domain; _logdir->domainSize = properties[i].domainSize; _logdir->externallyVisible = properties[i].externallyVisible; } else #endif if (String::equalNoCase(properties[i].propertyName, "logLevel")) { _logLevel->propertyName = properties[i].propertyName; _logLevel->defaultValue = properties[i].defaultValue; _logLevel->currentValue = properties[i].defaultValue; _logLevel->plannedValue = properties[i].defaultValue; _logLevel->dynamic = properties[i].dynamic; _logLevel->domain = properties[i].domain; _logLevel->domainSize = properties[i].domainSize; _logLevel->externallyVisible = properties[i].externallyVisible; Logger::setlogLevelMask(_logLevel->currentValue); } } } struct ConfigProperty* LogPropertyOwner::_lookupConfigProperty( const String& name) const { #if !defined(PEGASUS_USE_SYSLOGS) if (String::equalNoCase(_logdir->propertyName, name)) { return _logdir.get(); } else #endif if (String::equalNoCase(_logLevel->propertyName, name)) { return _logLevel.get(); } else { throw UnrecognizedConfigProperty(name); } } /** Get information about the specified property. */ void LogPropertyOwner::getPropertyInfo( const String& name, Array<String>& propertyInfo) const { propertyInfo.clear(); struct ConfigProperty* configProperty = _lookupConfigProperty(name); propertyInfo.append(configProperty->propertyName); propertyInfo.append(configProperty->defaultValue); propertyInfo.append(configProperty->currentValue); propertyInfo.append(configProperty->plannedValue); if (configProperty->dynamic) { propertyInfo.append(STRING_TRUE); } else { propertyInfo.append(STRING_FALSE); } if (configProperty->externallyVisible) { propertyInfo.append(STRING_TRUE); } else { propertyInfo.append(STRING_FALSE); } } /** Get default value of the specified property. */ String LogPropertyOwner::getDefaultValue(const String& name) const { struct ConfigProperty* configProperty = _lookupConfigProperty(name); return configProperty->defaultValue; } /** Get current value of the specified property. */ String LogPropertyOwner::getCurrentValue(const String& name) const { struct ConfigProperty* configProperty = _lookupConfigProperty(name); return configProperty->currentValue; } /** Get planned value of the specified property. */ String LogPropertyOwner::getPlannedValue(const String& name) const { struct ConfigProperty* configProperty = _lookupConfigProperty(name); return configProperty->plannedValue; } /** Init current value of the specified property to the specified value. */ void LogPropertyOwner::initCurrentValue( const String& name, const String& value) { if(String::equalNoCase(_logLevel->propertyName,name)) { _logLevel->currentValue = value; Logger::setlogLevelMask(_logLevel->currentValue); } else { struct ConfigProperty* configProperty = _lookupConfigProperty(name); configProperty->currentValue = value; } } /** Init planned value of the specified property to the specified value. */ void LogPropertyOwner::initPlannedValue( const String& name, const String& value) { struct ConfigProperty* configProperty = _lookupConfigProperty(name); configProperty->plannedValue = value; } /** Update current value of the specified property to the specified value. */ void LogPropertyOwner::updateCurrentValue( const String& name, const String& value) { // // make sure the property is dynamic before updating the value. // if (!isDynamic(name)) { throw NonDynamicConfigProperty(name); } // // Since the validations done in initCurrrentValue are sufficient and // no additional validations required for update, we will call // initCurrrentValue. // initCurrentValue(name, value); } /** Update planned value of the specified property to the specified value. */ void LogPropertyOwner::updatePlannedValue( const String& name, const String& value) { // // Since the validations done in initPlannedValue are sufficient and // no additional validations required for update, we will call // initPlannedValue. // initPlannedValue(name, value); } /** Checks to see if the given value is valid or not. */ Boolean LogPropertyOwner::isValid(const String& name, const String& value) const { if (String::equalNoCase(_logLevel->propertyName, name)) { // // Check if the logLevel is valid // if (!Logger::isValidlogLevel(value)) { throw InvalidPropertyValue(name, value); } } return(true); } /** Checks to see if the specified property is dynamic or not. */ Boolean LogPropertyOwner::isDynamic(const String& name) const { struct ConfigProperty* configProperty = _lookupConfigProperty(name); return (configProperty->dynamic == IS_DYNAMIC); } PEGASUS_NAMESPACE_END
29.738019
80
0.656639
ncultra
6b4734d6aa5676f26cbf6e868459db49e77f0bf2
708
hh
C++
elements/grid/setgridchecksum.hh
BorisPis/asplos22-nicmem-fastclick
ab4df08ee056ed48a4c534ec5f8536a958f756b5
[ "BSD-3-Clause-Clear" ]
129
2015-10-08T14:38:35.000Z
2022-03-06T14:54:44.000Z
elements/grid/setgridchecksum.hh
BorisPis/asplos22-nicmem-fastclick
ab4df08ee056ed48a4c534ec5f8536a958f756b5
[ "BSD-3-Clause-Clear" ]
241
2016-02-17T16:17:58.000Z
2022-03-15T09:08:33.000Z
elements/grid/setgridchecksum.hh
BorisPis/asplos22-nicmem-fastclick
ab4df08ee056ed48a4c534ec5f8536a958f756b5
[ "BSD-3-Clause-Clear" ]
61
2015-12-17T01:46:58.000Z
2022-02-07T22:25:19.000Z
#ifndef SETGRIDCHECKSUM_HH #define SETGRIDCHECKSUM_HH /* * =c * SetGridChecksum() * =s Grid * =d * Expects a Grid MAC packet as input. * Calculates the Grid header's checksum and sets the version and checksum header fields. * * =a * CheckGridHeader */ #include <click/element.hh> #include <click/glue.hh> CLICK_DECLS class SetGridChecksum : public Element { public: SetGridChecksum() CLICK_COLD; ~SetGridChecksum() CLICK_COLD; const char *class_name() const override { return "SetGridChecksum"; } const char *port_count() const override { return PORTS_1_1; } const char *processing() const override { return AGNOSTIC; } Packet *simple_action(Packet *); }; CLICK_ENDDECLS #endif
21.454545
89
0.727401
BorisPis
6b4867a57967cdc52a21ef108c55822fb56bfa44
2,320
cpp
C++
Decrypt/main.cpp
nwy140/HackAccess
e3c353067b45eae2eed327a7fb98a1f6fda0de18
[ "Apache-2.0" ]
1
2018-03-31T15:43:33.000Z
2018-03-31T15:43:33.000Z
Decrypt/main.cpp
nwy140/HackAccess
e3c353067b45eae2eed327a7fb98a1f6fda0de18
[ "Apache-2.0" ]
null
null
null
Decrypt/main.cpp
nwy140/HackAccess
e3c353067b45eae2eed327a7fb98a1f6fda0de18
[ "Apache-2.0" ]
1
2018-03-31T15:43:34.000Z
2018-03-31T15:43:34.000Z
#include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; const std::string &BASE64_CODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const std::string &SALT1 = "LM::TB::BB"; const std::string &SALT2 = "__:/__77"; const std::string &SALT3 = "line=wowC++"; string DecryptB64(string s); string base64_decode(const std::string &s); int main( int argc , char *argv[]) { if (argc !=3) // number of arguements on command return cout << "Program needs TWO arguement , input and output!" <<endl ,2; string in (argv[1]) , out (argv[2]); // arguement parameter 1 ifstream fi (in); if (!fi) return cout<< "Cannot read input file'" << in <<"'" <<endl ,3 ; //return 3 after print string data ; fi >> data ; // input into data if (!fi) // if input is still empty return cout << "Input file '" << in <<"' corrupted!" <<endl, 4; data = DecryptB64 (data); ofstream fo (out); // output to file if (!fo) return cout << "Cannot write output file '" << out << "'" <<endl , 5 ; fo << data; // output data to file cout << "Decoding was succesful" << endl; return 0; } string DecryptB64 (string s) { s = s.erase (7, 1); s = s.erase (1, 1); s = base64_decode (s); s = s.substr (SALT2.length() + SALT3.length()); s = s.substr (0, s.length() - SALT1.length()); s = base64_decode (s); s = s.substr (0, s.length() - SALT1.length()); s = s.erase (7, SALT3.length()); s = base64_decode (s); s = s.substr (SALT1.length()); s = s.substr (0, s.length() - SALT2.length() - SALT3.length()); return s; } string base64_decode(const std::string &s) { string ret; vector<int> vec(256, -1); for (int i = 0; i < 64; i++) vec [BASE64_CODES[i]] = i; int val = 0, bits = -8; for (const auto &c : s) { if (vec[c] == -1) break; val = (val << 6) + vec[c]; bits += 6; if (bits >= 0) { ret.push_back(char((val >> bits) & 0xFF)); bits -= 8; } } return ret; }
28.641975
101
0.510776
nwy140