id
stringlengths
27
29
content
stringlengths
226
3.24k
codereview_new_cpp_data_10558
bool SharedTaskManager::HandleCompletedActivities(SharedTask* s) std::array<bool, MAXACTIVITIESPERTASK> completed_steps; completed_steps.fill(true); auto activity_states = s->GetActivityState(); std::sort(activity_states.begin(), activity_states.end(), [](const auto& lhs, const auto& rhs) { return lhs.step < rhs.step; }); Would be good to add simple comments to new viewers why some of these steps are happening. Why are we sorting here for example (I'm sure there's plenty good reason, but good to know) bool SharedTaskManager::HandleCompletedActivities(SharedTask* s) std::array<bool, MAXACTIVITIESPERTASK> completed_steps; completed_steps.fill(true); + // multiple activity ids may share a step, sort so previous step completions can be checked auto activity_states = s->GetActivityState(); std::sort(activity_states.begin(), activity_states.end(), [](const auto& lhs, const auto& rhs) { return lhs.step < rhs.step; });
codereview_new_cpp_data_10559
void Client::CompleteConnect() if (GetGMInvul()) { state.emplace_back("invulnerable to all damage"); } - if (flymode == 1) { state.emplace_back("flying"); } - else if (flymode == 2) { state.emplace_back("levitating"); } if (tellsoff) { Can use `GravityBehavior::Flying` here maybe? void Client::CompleteConnect() if (GetGMInvul()) { state.emplace_back("invulnerable to all damage"); } + if (flymode == GravityBehavior::Flying) { state.emplace_back("flying"); } + else if (flymode == GravityBehavior::Levitating) { state.emplace_back("levitating"); } if (tellsoff) {
codereview_new_cpp_data_10560
void Client::CompleteConnect() if (GetGMInvul()) { state.emplace_back("invulnerable to all damage"); } - if (flymode == 1) { state.emplace_back("flying"); } - else if (flymode == 2) { state.emplace_back("levitating"); } if (tellsoff) { Can use `GravityBehavior::Levitating` here maybe? void Client::CompleteConnect() if (GetGMInvul()) { state.emplace_back("invulnerable to all damage"); } + if (flymode == GravityBehavior::Flying) { state.emplace_back("flying"); } + else if (flymode == GravityBehavior::Levitating) { state.emplace_back("levitating"); } if (tellsoff) {
codereview_new_cpp_data_10561
bool SharedDatabase::SetGMFlymode(uint32 account_id, uint8 flymode) { auto a = AccountRepository::FindOne(*this, account_id); if (a.id > 0) { - a.flymode = flymode ? 1 : 0; AccountRepository::UpdateOne(*this, a); } Does this allow flymodes other than just Fly Mode 0 (Ground) and Fly Mode 1 (Flying)? There's 4 other types as well. bool SharedDatabase::SetGMFlymode(uint32 account_id, uint8 flymode) { auto a = AccountRepository::FindOne(*this, account_id); if (a.id > 0) { + a.flymode = flymode; AccountRepository::UpdateOne(*this, a); }
codereview_new_cpp_data_10562
void ConsoleGuildSay( } auto from = args[0]; - auto guild_id = std::stoul(args[1]); auto join_args = args; join_args.erase(join_args.begin(), join_args.begin() + 2); Since `stoul` can throw you might want to just use `strtoul` here and abort if 0 to avoid crashing world with a bad input void ConsoleGuildSay( } auto from = args[0]; + auto guild_id = StringIsNumber(args[1]) ? std::stoul(args[1]) : 0; + if (!guild_id) { + return; + } auto join_args = args; join_args.erase(join_args.begin(), join_args.begin() + 2);
codereview_new_cpp_data_10563
void command_reload(Client *c, const Seperator *sep) return; } - ServerPacket* pack; if (is_aa) { c->Message(Chat::White, "Attempting to reload Alternate Advancement Data globally."); Initialize this with `= nullptr` since it might contain a non-null garbage value void command_reload(Client *c, const Seperator *sep) return; } + ServerPacket* pack = nullptr; if (is_aa) { c->Message(Chat::White, "Attempting to reload Alternate Advancement Data globally.");
codereview_new_cpp_data_10564
void Object::HandleAutoCombine(Client* user, const RecipeAutoCombine_Struct* rac } // Character does not have the required skill. - if(spec.skill_needed > 0 && user->GetSkill(spec.tradeskill) < spec.skill_needed ) { // Notify client. user->Message(Chat::Red, "You are not skilled enough."); user->QueuePacket(outapp); Space before `) {` here. void Object::HandleAutoCombine(Client* user, const RecipeAutoCombine_Struct* rac } // Character does not have the required skill. + if (spec.skill_needed > 0 && user->GetSkill(spec.tradeskill) < spec.skill_needed) { // Notify client. user->Message(Chat::Red, "You are not skilled enough."); user->QueuePacket(outapp);
codereview_new_cpp_data_10565
void Object::HandleAutoCombine(Client* user, const RecipeAutoCombine_Struct* rac } // Character does not have the required skill. - if(spec.skill_needed > 0 && user->GetSkill(spec.tradeskill) < spec.skill_needed ) { // Notify client. user->Message(Chat::Red, "You are not skilled enough."); user->QueuePacket(outapp); Is there no string ID for this? void Object::HandleAutoCombine(Client* user, const RecipeAutoCombine_Struct* rac } // Character does not have the required skill. + if (spec.skill_needed > 0 && user->GetSkill(spec.tradeskill) < spec.skill_needed) { // Notify client. user->Message(Chat::Red, "You are not skilled enough."); user->QueuePacket(outapp);
codereview_new_cpp_data_10588
OSIMMOCO_API void RegisterTypes_osimMoco() { Object::registerType(MocoMarkerTrackingGoal()); Object::registerType(MocoMarkerFinalGoal()); Object::registerType(MocoContactTrackingGoal()); - Object::registerType(MocoContactTrackingGoalGroup()); - Object::registerType(MocoContactImpulseTrackingGoal()); - Object::registerType(MocoContactImpulseTrackingGoalGroup()); Object::registerType(MocoControlGoal()); Object::registerType(MocoSumSquaredStateGoal()); Object::registerType(MocoControlTrackingGoal()); These three lines shouldn't be indented. OSIMMOCO_API void RegisterTypes_osimMoco() { Object::registerType(MocoMarkerTrackingGoal()); Object::registerType(MocoMarkerFinalGoal()); Object::registerType(MocoContactTrackingGoal()); + Object::registerType(MocoContactTrackingGoalGroup()); + Object::registerType(MocoContactImpulseTrackingGoal()); + Object::registerType(MocoContactImpulseTrackingGoalGroup()); Object::registerType(MocoControlGoal()); Object::registerType(MocoSumSquaredStateGoal()); Object::registerType(MocoControlTrackingGoal());
codereview_new_cpp_data_11561
bool SecurityManager::discovered_participant( restore_discovered_participant_info(participant_data.m_guid, remote_participant_info); return returnedValue; } I think we should add the following code here: ``` if (notify_part_authorized) { notify_participant_authorized(participant_data); } ``` bool SecurityManager::discovered_participant( restore_discovered_participant_info(participant_data.m_guid, remote_participant_info); + if (notify_part_authorized) + { + notify_participant_authorized(participant_data); + } + return returnedValue; }
codereview_new_cpp_data_11562
void PDPSimple::announceParticipantState( { auto endpoints = static_cast<fastdds::rtps::SimplePDPEndpoints*>(builtin_endpoints_.get()); StatelessWriter& writer = *(endpoints->writer.writer_); - WriterHistory& history = *endpoints->writer.history_; PDP::announceParticipantState(writer, history, new_change, dispose, wp); ```suggestion StatelessWriter& writer = *(endpoints->writer.writer_); WriterHistory& history = *(endpoints->writer.history_); ``` NIT: Just for uniformity sake void PDPSimple::announceParticipantState( { auto endpoints = static_cast<fastdds::rtps::SimplePDPEndpoints*>(builtin_endpoints_.get()); StatelessWriter& writer = *(endpoints->writer.writer_); + WriterHistory& history = *(endpoints->writer.history_); PDP::announceParticipantState(writer, history, new_change, dispose, wp);
codereview_new_cpp_data_11563
#include <statistics/rtps/StatisticsBase.hpp> #include <fastdds/rtps/reader/RTPSReader.h> - -#include "../../types/types.h" using namespace eprosima::fastdds::statistics; Maybe this could point to <statistics/types/types.h> instead of a relative path #include <statistics/rtps/StatisticsBase.hpp> #include <fastdds/rtps/reader/RTPSReader.h> +#include <statistics/types/types.h> using namespace eprosima::fastdds::statistics;
codereview_new_cpp_data_11564
#include "LogMacros.hpp" #include <gtest/gtest.h> -// Check that logInfo logWarning and logError and its private ones does not exist. TEST_F(LogMacrosTests, check_old_not_compiled) { ```suggestion // Check that logInfo, logWarning and logError and its private definitions does not exist. ``` #include "LogMacros.hpp" #include <gtest/gtest.h> +// Check that logInfo logWarning and logError and its private definitions does not exist. TEST_F(LogMacrosTests, check_old_not_compiled) {
codereview_new_cpp_data_11565
XMLP_ret XMLParser::parseXMLEnumDynamicType( XMLP_ret ret = XMLP_ret::XML_OK; const char* enumName = p_root->Attribute(NAME); - if(enumName == nullptr) { logError(XMLPARSER, "Error parsing 'enum' type. No name attribute given."); return XMLP_ret::XML_ERROR; Uncrustify fails here: ```suggestion if (enumName == nullptr) ``` XMLP_ret XMLParser::parseXMLEnumDynamicType( XMLP_ret ret = XMLP_ret::XML_OK; const char* enumName = p_root->Attribute(NAME); + if (enumName == nullptr) { logError(XMLPARSER, "Error parsing 'enum' type. No name attribute given."); return XMLP_ret::XML_ERROR;
codereview_new_cpp_data_11566
void DynamicDataHelper::print_complex_element( MemberId id, const std::string& tabs) { -<<<<<<< HEAD - const TypeDescriptor* desc = data->type_->get_type_descriptor(); - switch(desc->get_kind()) -======= DynamicData* st_data = data->loan_value(id); const TypeDescriptor* desc = st_data->type_->get_type_descriptor(); switch (desc->get_kind()) ->>>>>>> 78473a0de (Fix complex member printing for DynamicDataHelper (#2957)) { case TK_STRUCTURE: case TK_BITSET: ```suggestion DynamicData* st_data = data->loan_value(id); const TypeDescriptor* desc = st_data->type_->get_type_descriptor(); switch (desc->get_kind()) ``` void DynamicDataHelper::print_complex_element( MemberId id, const std::string& tabs) { DynamicData* st_data = data->loan_value(id); const TypeDescriptor* desc = st_data->type_->get_type_descriptor(); switch (desc->get_kind()) { case TK_STRUCTURE: case TK_BITSET:
codereview_new_cpp_data_11567
struct Arg : public option::Arg bool msg) { char* endptr = 0; - if ( option.arg != nullptr) { strtol(option.arg, &endptr, 10); if (endptr != option.arg && *endptr == 0) ```suggestion if ( option.arg != nullptr ) ``` struct Arg : public option::Arg bool msg) { char* endptr = 0; + if ( option.arg != nullptr ) { strtol(option.arg, &endptr, 10); if (endptr != option.arg && *endptr == 0)
codereview_new_cpp_data_11568
void set_attributes_from_qos( attr.multicastLocatorList = qos.endpoint().multicast_locator_list; attr.remoteLocatorList = qos.endpoint().remote_locator_list; attr.historyMemoryPolicy = qos.endpoint().history_memory_policy; - attr.setUserDefinedID((uint8_t)qos.endpoint().user_defined_id); - attr.setEntityID((uint8_t)qos.endpoint().entity_id); attr.times = qos.reliable_writer_qos().times; attr.qos.m_disablePositiveACKs = qos.reliable_writer_qos().disable_positive_acks; attr.qos.m_durability = qos.durability(); Instead of using the C casting format we usually try to comply with the C++ format: ```suggestion attr.setUserDefinedID(static_cast<uint8_t>(qos.endpoint().user_defined_id)); ``` void set_attributes_from_qos( attr.multicastLocatorList = qos.endpoint().multicast_locator_list; attr.remoteLocatorList = qos.endpoint().remote_locator_list; attr.historyMemoryPolicy = qos.endpoint().history_memory_policy; + attr.setUserDefinedID(static_cast<uint8_t>(qos.endpoint().user_defined_id)); + attr.setEntityID(static_cast<uint8_t>(qos.endpoint().entity_id)); attr.times = qos.reliable_writer_qos().times; attr.qos.m_disablePositiveACKs = qos.reliable_writer_qos().disable_positive_acks; attr.qos.m_durability = qos.durability();
codereview_new_cpp_data_11569
RTPSWriter* RTPSDomain::createRTPSWriter( WriterHistory* hist, WriterListener* listen) { - RTPSParticipantImpl* impl = RTPSDomainImpl::find_local_participant(p->getGuid()); - if (impl) - { - RTPSWriter* ret_val = nullptr; - if (impl->create_writer(&ret_val, watt, payload_pool, change_pool, hist, listen, entity_id)) - { - return ret_val; - } - } - - return nullptr; } RTPSWriter* RTPSDomain::createRTPSWriter( ```suggestion return RTPSDomainImpl::create_rtps_writer(p, entity_id, watt, payload_pool, change_pool, hist, listen); ``` RTPSWriter* RTPSDomain::createRTPSWriter( WriterHistory* hist, WriterListener* listen) { + return RTPSDomainImpl::create_rtps_writer(p, entity_id, watt, payload_pool, change_pool, hist, listen); } RTPSWriter* RTPSDomain::createRTPSWriter(
codereview_new_cpp_data_11570
ReturnCode_t DataWriterImpl::check_qos( logError(RTPS_QOS_CHECK, "DATA_SHARING cannot be used with memory policies other than PREALLOCATED."); return ReturnCode_t::RETCODE_INCONSISTENT_POLICY; } - if (qos.resource_limits().max_samples < - (qos.resource_limits().max_instances * qos.resource_limits().max_samples_per_instance)) { logError(DDS_QOS_CHECK, "max_samples should be greater than max_instances * max_samples_per_instance"); return ReturnCode_t::RETCODE_INCONSISTENT_POLICY; } - if ((qos.resource_limits().max_instances == 0 || qos.resource_limits().max_samples_per_instance == 0) && - (qos.resource_limits().max_samples != 0)) { logError(DDS_QOS_CHECK, "max_samples should be greater than max_instances * max_samples_per_instance"); return ReturnCode_t::RETCODE_INCONSISTENT_POLICY; ```suggestion logError(DDS_QOS_CHECK, "max_samples should be infinite when max_instances or max_samples_per_instance are infinite"); ``` ReturnCode_t DataWriterImpl::check_qos( logError(RTPS_QOS_CHECK, "DATA_SHARING cannot be used with memory policies other than PREALLOCATED."); return ReturnCode_t::RETCODE_INCONSISTENT_POLICY; } + if ((qos.resource_limits().max_samples > 0) && + (qos.resource_limits().max_samples <= + (qos.resource_limits().max_instances * qos.resource_limits().max_samples_per_instance))) { logError(DDS_QOS_CHECK, "max_samples should be greater than max_instances * max_samples_per_instance"); return ReturnCode_t::RETCODE_INCONSISTENT_POLICY; } + if ((qos.resource_limits().max_instances <= 0 || qos.resource_limits().max_samples_per_instance <= 0) && + (qos.resource_limits().max_samples > 0)) { logError(DDS_QOS_CHECK, "max_samples should be greater than max_instances * max_samples_per_instance"); return ReturnCode_t::RETCODE_INCONSISTENT_POLICY;
codereview_new_cpp_data_11571
ReturnCode_t TopicImpl::check_qos( return ReturnCode_t::RETCODE_INCONSISTENT_POLICY; } } - if (qos.resource_limits().max_samples < - (qos.resource_limits().max_instances * qos.resource_limits().max_samples_per_instance)) { logError(DDS_QOS_CHECK, "max_samples should be greater than max_instances * max_samples_per_instance"); return ReturnCode_t::RETCODE_INCONSISTENT_POLICY; } - if ((qos.resource_limits().max_instances == 0 || qos.resource_limits().max_samples_per_instance == 0) && - (qos.resource_limits().max_samples != 0)) { logError(DDS_QOS_CHECK, "max_samples should be greater than max_instances * max_samples_per_instance"); return ReturnCode_t::RETCODE_INCONSISTENT_POLICY; ```suggestion logError(DDS_QOS_CHECK, "max_samples should be infinite when max_instances or max_samples_per_instance are infinite"); ``` ReturnCode_t TopicImpl::check_qos( return ReturnCode_t::RETCODE_INCONSISTENT_POLICY; } } + if ((qos.resource_limits().max_samples > 0) && + (qos.resource_limits().max_samples <= + (qos.resource_limits().max_instances * qos.resource_limits().max_samples_per_instance))) { logError(DDS_QOS_CHECK, "max_samples should be greater than max_instances * max_samples_per_instance"); return ReturnCode_t::RETCODE_INCONSISTENT_POLICY; } + if ((qos.resource_limits().max_instances <= 0 || qos.resource_limits().max_samples_per_instance <= 0) && + (qos.resource_limits().max_samples > 0)) { logError(DDS_QOS_CHECK, "max_samples should be greater than max_instances * max_samples_per_instance"); return ReturnCode_t::RETCODE_INCONSISTENT_POLICY;
codereview_new_cpp_data_11572
ReturnCode_t TopicImpl::check_qos_including_resource_limits( const TopicQos& qos, const TypeSupport& type) { - ReturnCode_t check_qos_return; - check_qos_return = check_qos(qos); - if (!check_qos_return) - { - return check_qos_return; - } - if (type->m_isGetKeyDefined) { check_qos_return = check_allocation_consistency(qos); - if (!check_qos_return) - { - return check_qos_return; - } } - return ReturnCode_t::RETCODE_OK; } ReturnCode_t TopicImpl::check_qos( ```suggestion ReturnCode_t check_qos_return = check_qos(qos); if (ReturnCode_t::RETCODE_OK == check_qos_return && type->m_isGetKeyDefined) { check_qos_return = check_allocation_consistency(qos); } return check_qos_return; ``` ReturnCode_t TopicImpl::check_qos_including_resource_limits( const TopicQos& qos, const TypeSupport& type) { + ReturnCode_t check_qos_return = check_qos(qos); + if (ReturnCode_t::RETCODE_OK == check_qos_return && + type->m_isGetKeyDefined) { check_qos_return = check_allocation_consistency(qos); } + return check_qos_return; } ReturnCode_t TopicImpl::check_qos(
codereview_new_cpp_data_11617
TreeLearner* TreeLearner::CreateTreeLearner(const std::string& learner_type, con if (config->num_gpu == 1) { return new CUDASingleGPUTreeLearner(config, boosting_on_cuda); } else { - Log::Fatal("cuda only supports training on a single GPU."); } } else { - Log::Fatal("cuda only supports training on a single machine."); } } return nullptr; ```suggestion Log::Fatal("Currently cuda version only supports training on a single GPU."); ``` TreeLearner* TreeLearner::CreateTreeLearner(const std::string& learner_type, con if (config->num_gpu == 1) { return new CUDASingleGPUTreeLearner(config, boosting_on_cuda); } else { + Log::Fatal("Currently cuda version only supports training on a single GPU."); } } else { + Log::Fatal("Currently cuda version only supports training on a single machine."); } } return nullptr;
codereview_new_cpp_data_11620
ObjectiveFunction* ObjectiveFunction::CreateObjectiveFunction(const std::string& } else if (type == std::string("binary")) { return new CUDABinaryLogloss(config); } else if (type == std::string("lambdarank")) { - Log::Warning("Objective lambdarank is not implemented in cuda_exp version. Fall back to boosting on CPU."); return new CUDALambdarankNDCG(config); } else if (type == std::string("rank_xendcg")) { Log::Warning("Objective rank_xendcg is not implemented in cuda_exp version. Fall back to boosting on CPU."); remove this warning? ObjectiveFunction* ObjectiveFunction::CreateObjectiveFunction(const std::string& } else if (type == std::string("binary")) { return new CUDABinaryLogloss(config); } else if (type == std::string("lambdarank")) { return new CUDALambdarankNDCG(config); } else if (type == std::string("rank_xendcg")) { Log::Warning("Objective rank_xendcg is not implemented in cuda_exp version. Fall back to boosting on CPU.");
codereview_new_cpp_data_11630
void Metadata::Init(data_size_t num_data, int32_t has_weights, int32_t has_init_ num_data_ = num_data; label_ = std::vector<label_t>(num_data_); if (has_weights) { - weights_ = std::vector<label_t>(num_data_, 0.0f); num_weights_ = num_data_; weight_load_from_file_ = false; } if (has_init_scores) { num_init_score_ = static_cast<int64_t>(num_data) * nclasses; - init_score_ = std::vector<double>(num_init_score_, 0); } if (has_queries) { - if (!query_weights_.empty()) { query_weights_.clear(); } - queries_ = std::vector<data_size_t>(num_data_, 0); query_load_from_file_ = false; } } A better way to do this should be clear and resize `queries_` directly, to avoid unnecessary memory allocation and reallocation? void Metadata::Init(data_size_t num_data, int32_t has_weights, int32_t has_init_ num_data_ = num_data; label_ = std::vector<label_t>(num_data_); if (has_weights) { + if (!weights_.empty()) { + Log::Fatal("Calling Init() on Metadata weights that have already been initialized"); + } + weights_.resize(num_data_, 0.0f); num_weights_ = num_data_; weight_load_from_file_ = false; } if (has_init_scores) { + if (!init_score_.empty()) { + Log::Fatal("Calling Init() on Metadata initial scores that have already been initialized"); + } num_init_score_ = static_cast<int64_t>(num_data) * nclasses; + init_score_.resize(num_init_score_, 0); } if (has_queries) { + if (!query_weights_.empty()) { + Log::Fatal("Calling Init() on Metadata queries that have already been initialized"); + } + queries_.resize(num_data_, 0); query_load_from_file_ = false; } }
codereview_new_cpp_data_11663
auto PythonServer::FillListPlayers(std::vector<PlayerSetupData>& players) const const py::extract<py::list> py_players(r); if (py_players.check()) { py::stl_input_iterator<PlayerSetupData> players_begin(py_players), players_end; - players.reserve(std::distance(players_begin, players_end)); players.insert(players.end(), players_begin, players_end); } else { DebugLogger() << "Wrong players list data: check returns " regardless of the rest, why remove the `reserve`? unless that is consuming the input data destructively so that the insert later fails? then just remove that, not the `insert`. auto PythonServer::FillListPlayers(std::vector<PlayerSetupData>& players) const const py::extract<py::list> py_players(r); if (py_players.check()) { py::stl_input_iterator<PlayerSetupData> players_begin(py_players), players_end; + players.reserve(py::len(py_players)); players.insert(players.end(), players_begin, players_end); } else { DebugLogger() << "Wrong players list data: check returns "
codereview_new_cpp_data_11664
auto PythonServer::FillListPlayers(std::vector<PlayerSetupData>& players) const const py::extract<py::list> py_players(r); if (py_players.check()) { py::stl_input_iterator<PlayerSetupData> players_begin(py_players), players_end; - players.reserve(std::distance(players_begin, players_end)); players.insert(players.end(), players_begin, players_end); } else { DebugLogger() << "Wrong players list data: check returns " no `&` I think. the iterator is not a reference. But I don't see why this makes a difference. Should be doing the same thing, unless it's the `std::distance(...)` call consuming the input. auto PythonServer::FillListPlayers(std::vector<PlayerSetupData>& players) const const py::extract<py::list> py_players(r); if (py_players.check()) { py::stl_input_iterator<PlayerSetupData> players_begin(py_players), players_end; + players.reserve(py::len(py_players)); players.insert(players.end(), players_begin, players_end); } else { DebugLogger() << "Wrong players list data: check returns "
codereview_new_cpp_data_11666
#include "../util/i18n.h" namespace ValueRef { - const std::string& MeterToName(const MeterType& meter); } UniverseObject::UniverseObject(UniverseObjectType type, std::string name, `MeterType` is an enum so is better passed by value in cases like this #include "../util/i18n.h" namespace ValueRef { + const std::string& MeterToName(const MeterType meter); } UniverseObject::UniverseObject(UniverseObjectType type, std::string name,
codereview_new_cpp_data_11667
MeterType NameToMeter(const std::string_view name) { return MeterType::INVALID_METER_TYPE; } -const std::string_view MeterToName(const MeterType meter) { return NAME_BY_METER[static_cast<std::underlying_type_t<MeterType>>(meter) + 1]; } I'd add a comment here noting that the lowest value for `meter` should be `INVALID_METER_TYPE = -1` and the highest less than `NUM_METER_TYPES` MeterType NameToMeter(const std::string_view name) { return MeterType::INVALID_METER_TYPE; } +std::string_view MeterToName(const MeterType meter) { return NAME_BY_METER[static_cast<std::underlying_type_t<MeterType>>(meter) + 1]; }
codereview_new_cpp_data_11668
double Variable<double>::Eval(const ScriptingContext& context) const { IF_CURRENT_VALUE(double) - const std::string property_name = m_property_name.empty() ? "" : m_property_name.back(); if (m_ref_type == ReferenceType::NON_OBJECT_REFERENCE) { if ((property_name == "UniverseCentreX") || why this change? double Variable<double>::Eval(const ScriptingContext& context) const { IF_CURRENT_VALUE(double) + const std::string& property_name = m_property_name.empty() ? "" : m_property_name.back(); if (m_ref_type == ReferenceType::NON_OBJECT_REFERENCE) { if ((property_name == "UniverseCentreX") ||
codereview_new_cpp_data_11669
namespace { // shouldn't be possible to instantiate with this block enabled, but if so, // try to generate some useful compiler error messages to indicate what // type MappedObjectType is - // TODO: Unused alias? using GenerateCompileError = typename MappedObjectType::not_a_member_zi23tg; return false; } Technically unused anywhere in the code base, but comment above indicates it's still needed? namespace { // shouldn't be possible to instantiate with this block enabled, but if so, // try to generate some useful compiler error messages to indicate what // type MappedObjectType is using GenerateCompileError = typename MappedObjectType::not_a_member_zi23tg; return false; }
codereview_new_cpp_data_11670
unsigned int ValueTest::GetCheckSum() const { std::unique_ptr<Condition> ValueTest::Clone() const { return std::make_unique<ValueTest>(*this); } /////////////////////////////////////////////////////////// // Location // /////////////////////////////////////////////////////////// I think these could be defined in the header where declared unsigned int ValueTest::GetCheckSum() const { std::unique_ptr<Condition> ValueTest::Clone() const { return std::make_unique<ValueTest>(*this); } + /////////////////////////////////////////////////////////// // Location // ///////////////////////////////////////////////////////////
codereview_new_cpp_data_11677
int s2n_config_set_status_request_type(struct s2n_config *config, s2n_status_req S2N_ERROR_IF(type == S2N_STATUS_REQUEST_OCSP && !s2n_x509_ocsp_stapling_supported(), S2N_ERR_OCSP_NOT_SUPPORTED); POSIX_ENSURE_REF(config); - config->ocsp_status_requested_by_user = type == S2N_STATUS_REQUEST_OCSP; return 0; } Nit: I generally think this is clearer with parentheses. I worry the mix of "="s will confuse people :) ```suggestion config->ocsp_status_requested_by_user = (type == S2N_STATUS_REQUEST_OCSP); ``` int s2n_config_set_status_request_type(struct s2n_config *config, s2n_status_req S2N_ERROR_IF(type == S2N_STATUS_REQUEST_OCSP && !s2n_x509_ocsp_stapling_supported(), S2N_ERR_OCSP_NOT_SUPPORTED); POSIX_ENSURE_REF(config); + config->ocsp_status_requested_by_user = (type == S2N_STATUS_REQUEST_OCSP); return 0; }
codereview_new_cpp_data_11678
int s2n_connection_set_config(struct s2n_connection *conn, struct s2n_config *co conn->multirecord_send = true; } - /* Users can enable OCSP status requests via s2n_config_set_status_request_type. - * To ensure backwards compatibility, s2n_config_set_verification_ca_location can - * also enable OCSP status requests if called on a client. This behavior can be - * avoided if s2n_config_set_verification_ca_location is called on a server, since - * s2n-tls did not initially support sending an OCSP status request from a server. */ conn->request_ocsp_status = config->ocsp_status_requested_by_user; if (config->ocsp_status_requested_by_s2n && conn->mode == S2N_CLIENT) { I still don't think this is clear enough about the "why" for future developers. But maybe we need another opinion from someone unfamiliar with this strange behavior. How about: "Historically, calling s2n_config_set_verification_ca_location enabled OCSP stapling regardless of the value set by an application calling s2n_config_set_status_request_type. We maintain this behavior for backwards compatibility. However, the s2n_config_set_verification_ca_location behavior predates client auth / mutual auth support for OCSP stapling, so could only affect whether clients requested OCSP stapling. We therefore only have to maintain the legacy behavior for clients, not servers." Do we also need to update the USAGE guide at all? int s2n_connection_set_config(struct s2n_connection *conn, struct s2n_config *co conn->multirecord_send = true; } + /* Historically, calling s2n_config_set_verification_ca_location enabled OCSP stapling + * regardless of the value set by an application calling s2n_config_set_status_request_type. + * We maintain this behavior for backwards compatibility. + * + * However, the s2n_config_set_verification_ca_location behavior predates client authentication + * support for OCSP stapling, so could only affect whether clients requested OCSP stapling. We + * therefore only have to maintain the legacy behavior for clients, not servers. */ conn->request_ocsp_status = config->ocsp_status_requested_by_user; if (config->ocsp_status_requested_by_s2n && conn->mode == S2N_CLIENT) {
codereview_new_cpp_data_11679
int s2n_connection_get_session(struct s2n_connection *conn, uint8_t *session, si POSIX_ENSURE_REF(session); const int len = s2n_connection_get_session_length(conn); const size_t size = len; - if (len == 0) { return 0; } - POSIX_ENSURE(size < max_length, S2N_ERR_SERIALIZED_SESSION_STATE_TOO_LONG); struct s2n_blob serialized_data = { 0 }; POSIX_GUARD(s2n_blob_init(&serialized_data, session, len)); ```suggestion POSIX_ENSURE(size <= max_length, S2N_ERR_SERIALIZED_SESSION_STATE_TOO_LONG); ``` int s2n_connection_get_session(struct s2n_connection *conn, uint8_t *session, si POSIX_ENSURE_REF(session); const int len = s2n_connection_get_session_length(conn); + POSIX_GUARD(len); const size_t size = len; + if (size == 0) { return 0; } + POSIX_ENSURE(size <= max_length, S2N_ERR_SERIALIZED_SESSION_STATE_TOO_LONG); struct s2n_blob serialized_data = { 0 }; POSIX_GUARD(s2n_blob_init(&serialized_data, session, len));
codereview_new_cpp_data_11680
S2N_RESULT s2n_early_data_record_bytes(struct s2n_connection *conn, ssize_t data if (data_len < 0 || !s2n_is_early_data_io(conn)) { return S2N_RESULT_OK; } - /* Check to ensure data_len is non-negative */ - RESULT_ENSURE_GTE(data_len, 0); /* Ensure the bytes read are within the bounds of what we can actually record. */ if ((size_t) data_len > (UINT64_MAX - conn->early_data_bytes)) { `data_len` is already being checked to see if it's negative above this, so this additional check seems unnecessary. S2N_RESULT s2n_early_data_record_bytes(struct s2n_connection *conn, ssize_t data if (data_len < 0 || !s2n_is_early_data_io(conn)) { return S2N_RESULT_OK; } /* Ensure the bytes read are within the bounds of what we can actually record. */ if ((size_t) data_len > (UINT64_MAX - conn->early_data_bytes)) {
codereview_new_cpp_data_11681
static int s2n_utf8_string_from_extension_data(const uint8_t *extension_data, ui int len = ASN1_STRING_length(asn1_str); if (out_data != NULL) { - POSIX_ENSURE(*out_len >= (uint32_t) len, S2N_ERR_INSUFFICIENT_MEM_SIZE); /* ASN1_STRING_data() returns an internal pointer to the data. * Since this is an internal pointer it should not be freed or modified in any way. * Ref: https://www.openssl.org/docs/man1.0.2/man3/ASN1_STRING_data.html. We should _probably_ check to make sure `len` is non-negative before casting it to an unsigned value. ```suggestion POSIX_ENSURE(len >= 0, S2N_ERR_SAFETY); POSIX_ENSURE(*out_len >= (uint32_t) len, S2N_ERR_INSUFFICIENT_MEM_SIZE); ``` static int s2n_utf8_string_from_extension_data(const uint8_t *extension_data, ui int len = ASN1_STRING_length(asn1_str); if (out_data != NULL) { + POSIX_ENSURE((int64_t) *out_len >= (int64_t) len, S2N_ERR_INSUFFICIENT_MEM_SIZE); /* ASN1_STRING_data() returns an internal pointer to the data. * Since this is an internal pointer it should not be freed or modified in any way. * Ref: https://www.openssl.org/docs/man1.0.2/man3/ASN1_STRING_data.html.
codereview_new_cpp_data_11682
static int s2n_rsa_decrypt(const struct s2n_pkey *priv, struct s2n_blob *in, str /* Safety: RSA_private_decrypt does not mutate the key */ int r = RSA_private_decrypt(in->size, (unsigned char *) in->data, intermediate, s2n_unsafe_rsa_get_non_const(priv_key), RSA_NO_PADDING); - POSIX_ENSURE((int64_t) r == expected_size, S2N_ERR_SIZE_MISMATCH); s2n_constant_time_pkcs1_unpad_or_dont(out->data, intermediate, r, out->size); Same problem here I think. expected_size is unsigned. static int s2n_rsa_decrypt(const struct s2n_pkey *priv, struct s2n_blob *in, str /* Safety: RSA_private_decrypt does not mutate the key */ int r = RSA_private_decrypt(in->size, (unsigned char *) in->data, intermediate, s2n_unsafe_rsa_get_non_const(priv_key), RSA_NO_PADDING); + POSIX_ENSURE((int64_t) r == (int64_t) expected_size, S2N_ERR_SIZE_MISMATCH); s2n_constant_time_pkcs1_unpad_or_dont(out->data, intermediate, r, out->size);
codereview_new_cpp_data_11683
int s2n_kem_client_key_send(struct s2n_connection *conn, struct s2n_blob *shared POSIX_ENSURE_REF(shared_key); S2N_ERROR_IF(shared_key != &(conn->kex_params.kem_params.shared_secret), S2N_ERR_SAFETY); - const struct s2n_kem_preferences *kem_pref = NULL; - POSIX_GUARD(s2n_connection_get_kem_preferences(conn, &kem_pref)); conn->kex_params.kem_params.len_prefixed = true; /* PQ TLS 1.2 is always length prefixed */ POSIX_GUARD(s2n_kem_send_ciphertext(&(conn->handshake.io), &(conn->kex_params.kem_params))); What are you doing with kem_pref? int s2n_kem_client_key_send(struct s2n_connection *conn, struct s2n_blob *shared POSIX_ENSURE_REF(shared_key); S2N_ERROR_IF(shared_key != &(conn->kex_params.kem_params.shared_secret), S2N_ERR_SAFETY); conn->kex_params.kem_params.len_prefixed = true; /* PQ TLS 1.2 is always length prefixed */ POSIX_GUARD(s2n_kem_send_ciphertext(&(conn->handshake.io), &(conn->kex_params.kem_params)));
codereview_new_cpp_data_11684
bool s2n_kem_preferences_includes_tls13_kem_group(const struct s2n_kem_preferenc return false; } -/* Whether the client should include the length prefix in the PQ TLS 1.3 KEM KeyShares that it sends. Earlier drafts of - * the PQ TLS 1.3 standard required length prefixing, and later drafts removed this length prefix. To not break * backwards compatibility, we check what revision of the draft standard is configured to determine whether to send it. */ -bool s2n_tls13_client_prefers_hybrid_kem_length_prefix(const struct s2n_kem_preferences *kem_pref) { return kem_pref && (kem_pref->tls13_pq_hybrid_draft_revision == 0); } (Overly pedantic) nit: it's not really that the client `prefers` the length prefixes, because that suggest that while they prefer prefixing, they would still be OK if the server sent back a non-prefixed key share. Maybe better to name this something like `s2n_tls13_client_sent_hybrid_kem_length_prefixes()`. bool s2n_kem_preferences_includes_tls13_kem_group(const struct s2n_kem_preferenc return false; } +/* Whether the client must include the length prefix in the PQ TLS 1.3 KEM KeyShares that it sends. Draft 0 of + * the PQ TLS 1.3 standard required length prefixing, and drafts 1-5 removed this length prefix. To not break * backwards compatibility, we check what revision of the draft standard is configured to determine whether to send it. */ +bool s2n_tls13_client_must_use_hybrid_kem_length_prefix(const struct s2n_kem_preferences *kem_pref) { return kem_pref && (kem_pref->tls13_pq_hybrid_draft_revision == 0); }
codereview_new_cpp_data_11685
const struct s2n_kem_group *ALL_SUPPORTED_KEM_GROUPS[S2N_SUPPORTED_KEM_GROUPS_CO * The old format is used by draft 0 of the Hybrid PQ TLS 1.3 specification, and all revisions of the Hybrid PQ TLS 1.2 * draft specification. Only draft revisions 1-5 of the Hybrid PQ TLS 1.3 specification use the new format. */ -int s2n_is_tls13_hybrid_kem_length_prefixed(uint16_t actual_hybrid_share_size, const struct s2n_kem_group *kem_group, bool *is_length_prefixed) { - POSIX_ENSURE_REF(kem_group); - POSIX_ENSURE_REF(kem_group->curve); - POSIX_ENSURE_REF(kem_group->kem); - POSIX_ENSURE_REF(is_length_prefixed); uint16_t unprefixed_hybrid_share_size = kem_group->curve->share_size + kem_group->kem->public_key_length; uint16_t prefixed_hybrid_share_size = (2 * S2N_SIZE_OF_KEY_SHARE_SIZE) + unprefixed_hybrid_share_size; - POSIX_ENSURE((actual_hybrid_share_size == unprefixed_hybrid_share_size) || (actual_hybrid_share_size == prefixed_hybrid_share_size), S2N_ERR_BAD_KEY_SHARE); - if (actual_hybrid_share_size == prefixed_hybrid_share_size) { - *is_length_prefixed = true; - } else { - *is_length_prefixed = false; - } - return S2N_SUCCESS; } S2N_RESULT s2n_kem_generate_keypair(struct s2n_kem_params *kem_params) Nit: Was this for readability? If/else that return true/false always seem odd to me. ```suggestion *is_length_prefixed = (actual_hybrid_share_size == prefixed_hybrid_share_size); ``` const struct s2n_kem_group *ALL_SUPPORTED_KEM_GROUPS[S2N_SUPPORTED_KEM_GROUPS_CO * The old format is used by draft 0 of the Hybrid PQ TLS 1.3 specification, and all revisions of the Hybrid PQ TLS 1.2 * draft specification. Only draft revisions 1-5 of the Hybrid PQ TLS 1.3 specification use the new format. */ +S2N_RESULT s2n_is_tls13_hybrid_kem_length_prefixed(uint16_t actual_hybrid_share_size, const struct s2n_kem_group *kem_group, bool *is_length_prefixed) { + RESULT_ENSURE_REF(kem_group); + RESULT_ENSURE_REF(kem_group->curve); + RESULT_ENSURE_REF(kem_group->kem); + RESULT_ENSURE_REF(is_length_prefixed); uint16_t unprefixed_hybrid_share_size = kem_group->curve->share_size + kem_group->kem->public_key_length; uint16_t prefixed_hybrid_share_size = (2 * S2N_SIZE_OF_KEY_SHARE_SIZE) + unprefixed_hybrid_share_size; + RESULT_ENSURE((actual_hybrid_share_size == unprefixed_hybrid_share_size) || (actual_hybrid_share_size == prefixed_hybrid_share_size), S2N_ERR_BAD_KEY_SHARE); + *is_length_prefixed = (actual_hybrid_share_size == prefixed_hybrid_share_size); + return S2N_RESULT_OK; } S2N_RESULT s2n_kem_generate_keypair(struct s2n_kem_params *kem_params)
codereview_new_cpp_data_11686
static int s2n_client_key_share_recv_pq_hybrid(struct s2n_connection *conn, stru bool is_hybrid_share_length_prefixed = 0; uint16_t actual_hybrid_share_size = key_share->blob.size; - /* The length of the hybrid key share must be one of two possible lengths. It's internal values are either length * prefixed, or they are not. If actual_hybrid_share_size is not one of these two lengths, then * s2n_is_tls13_hybrid_kem_length_prefixed() will return an error. */ - POSIX_GUARD_RESULT(s2n_is_tls13_hybrid_kem_length_prefixed(actual_hybrid_share_size, kem_group, &is_hybrid_share_length_prefixed)); if (is_hybrid_share_length_prefixed) { /* Ignore KEM groups with unexpected ECC share sizes */ Nit ```suggestion /* The length of the hybrid key share must be one of two possible lengths. Its internal values are either length * prefixed, or they are not. If actual_hybrid_share_size is not one of these two lengths, then ``` static int s2n_client_key_share_recv_pq_hybrid(struct s2n_connection *conn, stru bool is_hybrid_share_length_prefixed = 0; uint16_t actual_hybrid_share_size = key_share->blob.size; + /* The length of the hybrid key share must be one of two possible lengths. Its internal values are either length * prefixed, or they are not. If actual_hybrid_share_size is not one of these two lengths, then * s2n_is_tls13_hybrid_kem_length_prefixed() will return an error. */ + s2n_result result = s2n_is_tls13_hybrid_kem_length_prefixed(actual_hybrid_share_size, kem_group, &is_hybrid_share_length_prefixed); + + /* Ignore KEM groups with unexpected overall total share sizes */ + if (s2n_result_is_error(result)) { + return S2N_SUCCESS; + } if (is_hybrid_share_length_prefixed) { /* Ignore KEM groups with unexpected ECC share sizes */
codereview_new_cpp_data_11687
int s2n_config_set_ktls_mode(struct s2n_config *config, s2n_ktls_mode ktls_mode) config->ktls_send_requested = true; break; case S2N_KTLS_MODE_SEND: config->ktls_send_requested = true; break; case S2N_KTLS_MODE_RECV: config->ktls_recv_requested = true; break; case S2N_KTLS_MODE_DISABLED: config->ktls_recv_requested = false; No new functions should return bools. This should be an "out parameter". int s2n_config_set_ktls_mode(struct s2n_config *config, s2n_ktls_mode ktls_mode) config->ktls_send_requested = true; break; case S2N_KTLS_MODE_SEND: + config->ktls_recv_requested = false; config->ktls_send_requested = true; break; case S2N_KTLS_MODE_RECV: config->ktls_recv_requested = true; + config->ktls_send_requested = false; break; case S2N_KTLS_MODE_DISABLED: config->ktls_recv_requested = false;
codereview_new_cpp_data_11688
static int s2n_server_cert_status_request_send(struct s2n_connection *conn, stru static bool s2n_server_cert_status_request_should_send(struct s2n_connection *conn) { - return conn->config->status_request_type != S2N_STATUS_REQUEST_NONE; } Why not == S2N_STATUS_REQUEST_OCSP? static int s2n_server_cert_status_request_send(struct s2n_connection *conn, stru static bool s2n_server_cert_status_request_should_send(struct s2n_connection *conn) { + return conn->config->status_request_type == S2N_STATUS_REQUEST_OCSP; }
codereview_new_cpp_data_11689
int wait_for_shutdown(struct s2n_connection *conn, int fd) } /* Otherwise, IO errors are fatal and should be investigated */ fprintf(stderr, "Unexpected IO error during shutdown: %s\n", strerror(errno_val)); - exit(1); default: - fprintf(stderr, "Unexpected error during shutdown: %s\n", s2n_strerror(s2n_errno, NULL)); - exit(1); } } return S2N_SUCCESS; This isn't the PR for it, but should we make GUARD_EXIT work with format strings? int wait_for_shutdown(struct s2n_connection *conn, int fd) } /* Otherwise, IO errors are fatal and should be investigated */ fprintf(stderr, "Unexpected IO error during shutdown: %s\n", strerror(errno_val)); + return S2N_FAILURE; default: + return S2N_FAILURE; } } return S2N_SUCCESS;
codereview_new_cpp_data_11690
int s2n_server_status_request_recv(struct s2n_connection *conn, struct s2n_stuff /* Old-style extension functions -- remove after extensions refactor is complete */ -/* used in fuzz test */ int s2n_recv_server_status_request(struct s2n_connection *conn, struct s2n_stuffer *extension) { return s2n_extension_recv(&s2n_server_status_request_extension, conn, extension); Are these comments necessary? Searching for occurrences of the method should return the fuzz tests just like the unit tests. What if we remove the fuzz test reference, but don't clean up this comment? int s2n_server_status_request_recv(struct s2n_connection *conn, struct s2n_stuff /* Old-style extension functions -- remove after extensions refactor is complete */ int s2n_recv_server_status_request(struct s2n_connection *conn, struct s2n_stuffer *extension) { return s2n_extension_recv(&s2n_server_status_request_extension, conn, extension);
codereview_new_cpp_data_11691
struct s2n_cipher_suite *cipher_suites_cloudfront_tls_1_2_2017[] = { &s2n_ecdhe_rsa_with_aes_256_cbc_sha384, &s2n_ecdhe_ecdsa_with_aes_256_cbc_sha, &s2n_ecdhe_rsa_with_aes_256_cbc_sha, &s2n_ecdhe_rsa_with_aes_128_cbc_sha, &s2n_rsa_with_aes_128_gcm_sha256, &s2n_rsa_with_aes_256_gcm_sha384, also esdsa variant for completeness? struct s2n_cipher_suite *cipher_suites_cloudfront_tls_1_2_2017[] = { &s2n_ecdhe_rsa_with_aes_256_cbc_sha384, &s2n_ecdhe_ecdsa_with_aes_256_cbc_sha, &s2n_ecdhe_rsa_with_aes_256_cbc_sha, + &s2n_ecdhe_ecdsa_with_aes_128_cbc_sha, &s2n_ecdhe_rsa_with_aes_128_cbc_sha, &s2n_rsa_with_aes_128_gcm_sha256, &s2n_rsa_with_aes_256_gcm_sha384,
codereview_new_cpp_data_11692
static int s2n_signature_scheme_valid_to_accept(struct s2n_connection *conn, con POSIX_ENSURE_LTE(conn->actual_protocol_version, scheme->maximum_protocol_version); } - if (conn->actual_protocol_version >= S2N_TLS13 - || conn->actual_protocol_version == S2N_UNKNOWN_PROTOCOL_VERSION) { POSIX_ENSURE_NE(scheme->hash_alg, S2N_HASH_SHA1); POSIX_ENSURE_NE(scheme->sig_alg, S2N_SIGNATURE_RSA); - if (scheme->sig_alg == S2N_SIGNATURE_ECDSA) { - POSIX_ENSURE_REF(scheme->signature_curve); - } } if (conn->actual_protocol_version < S2N_TLS13) { - POSIX_ENSURE_EQ(scheme->signature_curve, NULL); POSIX_ENSURE_NE(scheme->sig_alg, S2N_SIGNATURE_RSA_PSS_PSS); } Why consider S2N_UNKNOWN_PROTOCOL_VERSION? Is it just for the unit tests? static int s2n_signature_scheme_valid_to_accept(struct s2n_connection *conn, con POSIX_ENSURE_LTE(conn->actual_protocol_version, scheme->maximum_protocol_version); } + POSIX_ENSURE_NE(conn->actual_protocol_version, S2N_UNKNOWN_PROTOCOL_VERSION); + + if (conn->actual_protocol_version >= S2N_TLS13) { POSIX_ENSURE_NE(scheme->hash_alg, S2N_HASH_SHA1); POSIX_ENSURE_NE(scheme->sig_alg, S2N_SIGNATURE_RSA); } if (conn->actual_protocol_version < S2N_TLS13) { POSIX_ENSURE_NE(scheme->sig_alg, S2N_SIGNATURE_RSA_PSS_PSS); }
codereview_new_cpp_data_11693
static int s2n_signature_scheme_valid_to_accept(struct s2n_connection *conn, con if (conn->actual_protocol_version >= S2N_TLS13) { POSIX_ENSURE_NE(scheme->hash_alg, S2N_HASH_SHA1); POSIX_ENSURE_NE(scheme->sig_alg, S2N_SIGNATURE_RSA); - } - - if (conn->actual_protocol_version < S2N_TLS13) { POSIX_ENSURE_NE(scheme->sig_alg, S2N_SIGNATURE_RSA_PSS_PSS); } Per your comment in the PR description, I wonder if these checks make more sense in `s2n_signature_scheme_valid_to_offer`? `s2n_signature_scheme_valid_to_accept` calls `s2n_signature_scheme_valid_to_offer`, so the checks would be triggered in both functions. If the goal is to eventually replace the signature min/max versions, it seems like you might ultimately want the check in `s2n_signature_scheme_valid_to_offer`? Not sure. static int s2n_signature_scheme_valid_to_accept(struct s2n_connection *conn, con if (conn->actual_protocol_version >= S2N_TLS13) { POSIX_ENSURE_NE(scheme->hash_alg, S2N_HASH_SHA1); POSIX_ENSURE_NE(scheme->sig_alg, S2N_SIGNATURE_RSA); + } else { POSIX_ENSURE_NE(scheme->sig_alg, S2N_SIGNATURE_RSA_PSS_PSS); }
codereview_new_cpp_data_11694
#include "tls/extensions/s2n_extension_type.h" #include "tls/s2n_cipher_suites.h" #include "tls/s2n_security_policies.h" -#include "tls/s2n_signature_algorithms.h" #include "tls/s2n_tls13_secrets.h" #include "utils/s2n_mem.h" #include "utils/s2n_random.h" Is this include needed? #include "tls/extensions/s2n_extension_type.h" #include "tls/s2n_cipher_suites.h" #include "tls/s2n_security_policies.h" #include "tls/s2n_tls13_secrets.h" #include "utils/s2n_mem.h" #include "utils/s2n_random.h"
codereview_new_cpp_data_11774
void handle_controllers_ControllerSettingsPage(controllerIndex_t controllerindex const protocolIndex_t ProtocolIndex = getProtocolIndex_from_ControllerIndex(controllerindex); addRTDControllerButton(Protocol[ProtocolIndex].Number); if (Settings.Protocol[controllerindex]) { Please do not include this in minimal OTA builds void handle_controllers_ControllerSettingsPage(controllerIndex_t controllerindex const protocolIndex_t ProtocolIndex = getProtocolIndex_from_ControllerIndex(controllerindex); + # ifndef LIMIT_BUILD_SIZE addRTDControllerButton(Protocol[ProtocolIndex].Number); + # endif // ifndef LIMIT_BUILD_SIZE if (Settings.Protocol[controllerindex]) {
codereview_new_cpp_data_11775
bool CPlugin_014(CPlugin::Function function, struct EventStruct *event, String& cmd = F("GPIO,"); cmd += valueName.substring(gpio_value_tag_length).toInt(); // get the GPIO - if ((equals(event->String2, F("true"))) || (equals(event->String2, F("1")))) { cmd += F(",1"); } else { cmd += F(",0"); } validTopic = true; } else if (valueName.equals(F(CPLUGIN_014_CMD_VALUE))) // msg to send a command `F("1")` can be replaced by `'1'` bool CPlugin_014(CPlugin::Function function, struct EventStruct *event, String& cmd = F("GPIO,"); cmd += valueName.substring(gpio_value_tag_length).toInt(); // get the GPIO + if ((equals(event->String2, F("true"))) || (equals(event->String2, '1'))) { cmd += F(",1"); } else { cmd += F(",0"); } validTopic = true; } else if (valueName.equals(F(CPLUGIN_014_CMD_VALUE))) // msg to send a command
codereview_new_cpp_data_11776
void handle_dumpcache() { if (isWrappedWithQuotes(sep)) { removeChar(sep, sep[0]); } - separator = sep[0]; - } - if (hasArg(F("jointimestamp"))) { - joinTimestamp = true; } if (hasArg(F("jointimestamp"))) { This seems to be duplicated? Or has GH messed something up? void handle_dumpcache() { if (isWrappedWithQuotes(sep)) { removeChar(sep, sep[0]); } + if (sep.equalsIgnoreCase(F("Tab"))) { separator = '\t'; } + else if (sep.equalsIgnoreCase(F("Comma"))) { separator = ','; } + else if (sep.equalsIgnoreCase(F("Semicolon"))) { separator = ';'; } } if (hasArg(F("jointimestamp"))) {
codereview_new_cpp_data_11777
bool CPlugin_006(CPlugin::Function function, struct EventStruct *event, String& String name = topicSplit[4]; - if (name.equals(Settings.getUnitname())) { String cmd = topicSplit[5]; cmd += ','; This may break existing setups. bool CPlugin_006(CPlugin::Function function, struct EventStruct *event, String& String name = topicSplit[4]; + if (name.equals(Settings.getName())) { String cmd = topicSplit[5]; cmd += ',';
codereview_new_cpp_data_11778
void html_add_script(bool defer) { if (defer) { addHtml(F(" defer")); } - addHtml(F(">")); } void html_add_script_end() { After your change, the "text" has been reduced to a single char. So it is better to use `addHtml('>');` which is of type `char` instead of a FlashString. A char is much smaller and uses less resources. void html_add_script(bool defer) { if (defer) { addHtml(F(" defer")); } + addHtml(F('>')); } void html_add_script_end() {
codereview_new_cpp_data_11779
#include "../Helpers/StringConverter.h" -#include "..//Globals/Settings.h" // ******************************************************************************** // HTML string re-use to keep the executable smaller Double slash used, typo? #include "../Helpers/StringConverter.h" +#include "../Globals/Settings.h" // ******************************************************************************** // HTML string re-use to keep the executable smaller
codereview_new_cpp_data_11780
void handle_notifications() { } else { - //MFD: we display the GPIO - if (NotificationSettings.Pin1>=0){ - addHtml(F("GPIO-")); - addHtmlInt(NotificationSettings.Pin1); - } if (NotificationSettings.Pin2>=0) { html_BR(); - addHtml(F("GPIO-")); - addHtmlInt(NotificationSettings.Pin2); } html_TD(3); } Please use the function `addHtml` here instead of adding to the TXBuffer. void handle_notifications() { } else { + //MFD: we display the GPIO + addGpioHtml(NotificationSettings.Pin1); + if (NotificationSettings.Pin2>=0) { html_BR(); + addGpioHtml(NotificationSettings.Pin2); } html_TD(3); }
codereview_new_cpp_data_11781
void handle_notifications() { } else { - //MFD: we display the GPIO - if (NotificationSettings.Pin1>=0){ - addHtml(F("GPIO-")); - addHtmlInt(NotificationSettings.Pin1); - } if (NotificationSettings.Pin2>=0) { html_BR(); - addHtml(F("GPIO-")); - addHtmlInt(NotificationSettings.Pin2); } html_TD(3); } I was just reading through this PR code and just realized I had (a long time ago) made functions to generate these descriptions. So I searched through the code and I think the best function to use here is `GpioToHtml` as it is also used on the DevicesPage to format generic pins. Then you don't even need to check for -1. Only thing is, you may still need to to not include the BR if the first one is not set. void handle_notifications() { } else { + //MFD: we display the GPIO + addGpioHtml(NotificationSettings.Pin1); + if (NotificationSettings.Pin2>=0) { html_BR(); + addGpioHtml(NotificationSettings.Pin2); } html_TD(3); }
codereview_new_cpp_data_11783
void ControllerSettingsStruct::reset() { MinimalTimeBetweenMessages = CONTROLLER_DELAY_QUEUE_DELAY_DFLT; MaxQueueDepth = CONTROLLER_DELAY_QUEUE_DEPTH_DFLT; MaxRetry = CONTROLLER_DELAY_QUEUE_RETRY_DFLT; - DeleteOldest = DEFAULT_MQTT_DELETE_OLDEST; ClientTimeout = CONTROLLER_CLIENTTIMEOUT_DFLT; MustCheckReply = DEFAULT_CONTROLLER_MUST_CHECK_REPLY ; SampleSetInitiator = INVALID_TASK_INDEX; Please rename those defaults to `DEFAULT_CONTROLLER_xxx` as it has to do with controller settings. Only when controller settings are specifically meant for MQTT, like the retain setting, then using `MQTT` is appropriate. Thus `DEFAULT_CONTROLLER_MUST_CHECK_REPLY` and `DEFAULT_CONTROLLER_PORT` and `DEFAULT_CONTROLLER_USE_DNS` void ControllerSettingsStruct::reset() { MinimalTimeBetweenMessages = CONTROLLER_DELAY_QUEUE_DELAY_DFLT; MaxQueueDepth = CONTROLLER_DELAY_QUEUE_DEPTH_DFLT; MaxRetry = CONTROLLER_DELAY_QUEUE_RETRY_DFLT; + DeleteOldest = DEFAULT_CONTROLLER_DELETE_OLDEST; ClientTimeout = CONTROLLER_CLIENTTIMEOUT_DFLT; MustCheckReply = DEFAULT_CONTROLLER_MUST_CHECK_REPLY ; SampleSetInitiator = INVALID_TASK_INDEX;
codereview_new_cpp_data_11787
uint64_t OsmXmlWriter::getPos() return _fp->pos(); } -void OsmXmlWriter::flush() -{ - //if (_fp && _fp->isOpen()) - // _fp-> -} - void OsmXmlWriter::write(const ConstOsmMapPtr& map, const QString& path) { open(path); Is the flushing code not necessary or just not implemented yet? uint64_t OsmXmlWriter::getPos() return _fp->pos(); } void OsmXmlWriter::write(const ConstOsmMapPtr& map, const QString& path) { open(path);
codereview_new_cpp_data_11789
static bool lclif_send_server_list(struct login_session_data *sd) packet->packet_id = HEADER_AC_ACCEPT_LOGIN; #else packet->packet_id = HEADER_AC_ACCEPT_LOGIN2; #endif packet->packet_len = length; packet->auth_code = sd->login_id1; Is this needed? You can use postHook and create a method in the plugin itself. static bool lclif_send_server_list(struct login_session_data *sd) packet->packet_id = HEADER_AC_ACCEPT_LOGIN; #else packet->packet_id = HEADER_AC_ACCEPT_LOGIN2; + login->generate_token(sd, packet->auth_token); #endif packet->packet_len = length; packet->auth_code = sd->login_id1;
codereview_new_cpp_data_11790
#include "flatbuffers/code_generators.h" #include "flatbuffers/flatbuffers.h" -#include "flatbuffers/flatc.h" #include "flatbuffers/idl.h" #include "flatbuffers/util.h" is this necessary? #include "flatbuffers/code_generators.h" #include "flatbuffers/flatbuffers.h" #include "flatbuffers/idl.h" #include "flatbuffers/util.h"
codereview_new_cpp_data_11851
void FlagTreeItem::showUnknownTokenMessage(const std::map<std::string, bool, Fla } std::stringstream tmp; - tmp << "Unknown token '" << token << "'" << ". The closest existing flags are:" << msgendl; for(auto& [name, score] : sofa::helper::getClosestMatch(token, allFlagNames, 2, 0.6)) { tmp << "\t" << "- " << name << " ("+ std::to_string((int)(100*score))+"% match)" << msgendl; "token" sound like programmer's slang. ```suggestion tmp << "Unknown flag '" << token << "'" << ". The closest existing ones:" << msgendl; ``` void FlagTreeItem::showUnknownTokenMessage(const std::map<std::string, bool, Fla } std::stringstream tmp; + tmp << "Unknown flag '" << token << "'" << ". The closest existing ones:" << msgendl; for(auto& [name, score] : sofa::helper::getClosestMatch(token, allFlagNames, 2, 0.6)) { tmp << "\t" << "- " << name << " ("+ std::to_string((int)(100*score))+"% match)" << msgendl;
codereview_new_cpp_data_11852
bool TopologicalMapping::checkTopologyInputTypes() { if (m_inputType == TopologyElementType::UNKNOWN) { - dmsg_error() << "The input TopologyElementType has not be set. Define 'm_inputType' to the correct TopologyElementType in the constructor."; return false; } if (m_outputType == TopologyElementType::UNKNOWN) { - dmsg_error() << "The output TopologyElementType has not be set. Define 'm_outputType' to the correct TopologyElementType in the constructor."; return false; } ```suggestion dmsg_error() << "The output TopologyElementType has not been set. Define 'm_outputType' to the correct TopologyElementType in the constructor."; ``` bool TopologicalMapping::checkTopologyInputTypes() { if (m_inputType == TopologyElementType::UNKNOWN) { + dmsg_error() << "The input TopologyElementType has not been set. Define 'm_inputType' to the correct TopologyElementType in the constructor."; return false; } if (m_outputType == TopologyElementType::UNKNOWN) { + dmsg_error() << "The output TopologyElementType has not been set. Define 'm_outputType' to the correct TopologyElementType in the constructor."; return false; }
codereview_new_cpp_data_11853
Edge2QuadTopologicalMapping::Edge2QuadTopologicalMapping() , d_nbPointsOnEachCircle( initData(&d_nbPointsOnEachCircle, "nbPointsOnEachCircle", "Discretization of created circles")) , d_radius( initData(&d_radius, 1_sreal, "radius", "Radius of created circles in yz plan")) , d_radiusFocal( initData(&d_radiusFocal, 0_sreal, "radiusFocal", "If greater than 0., radius in focal axis of created ellipses")) - , d_focalAxis( initData(&d_focalAxis, Vec3(0,0,1), "focalAxis", "In case of ellipses")) , d_edgeList(initData(&d_edgeList, "edgeList", "list of input edges for the topological mapping: by default, all considered")) , d_flipNormals(initData(&d_flipNormals, bool(false), "flipNormals", "Flip Normal ? (Inverse point order when creating quad)")) { ```suggestion , d_focalAxis( initData(&d_focalAxis, Vec3(0_sreal, 0_sreal, 1_sreal), "focalAxis", "In case of ellipses")) ``` Edge2QuadTopologicalMapping::Edge2QuadTopologicalMapping() , d_nbPointsOnEachCircle( initData(&d_nbPointsOnEachCircle, "nbPointsOnEachCircle", "Discretization of created circles")) , d_radius( initData(&d_radius, 1_sreal, "radius", "Radius of created circles in yz plan")) , d_radiusFocal( initData(&d_radiusFocal, 0_sreal, "radiusFocal", "If greater than 0., radius in focal axis of created ellipses")) + , d_focalAxis( initData(&d_focalAxis, Vec3(0_sreal, 0_sreal, 1_sreal), "focalAxis", "In case of ellipses")) , d_edgeList(initData(&d_edgeList, "edgeList", "list of input edges for the topological mapping: by default, all considered")) , d_flipNormals(initData(&d_flipNormals, bool(false), "flipNormals", "Flip Normal ? (Inverse point order when creating quad)")) {
codereview_new_cpp_data_11854
objectmodel::BaseObject::SPtr ObjectFactory::createObject(objectmodel::BaseConte { msg_error(object.get()) << "Requested template '" << usertemplatename << "' " << "cannot be found in the list of available templates [" << ss.str() << "]. " - << "Falling back to default template: '" << object->getTemplateName() << "'."; } } I am not sure it's necessarily the default template. To be checked objectmodel::BaseObject::SPtr ObjectFactory::createObject(objectmodel::BaseConte { msg_error(object.get()) << "Requested template '" << usertemplatename << "' " << "cannot be found in the list of available templates [" << ss.str() << "]. " + << "Falling back to the first compatible template: '" << object->getTemplateName() << "'."; } }
codereview_new_cpp_data_11855
void init() const char* getModuleComponentList() { /// string containing the names of the classes provided by the plugin - static std::string classes = core::ObjectFactory::getInstance()->listClassesFromTarget(sofa_tostring(SOFA_TARGET)); return classes.c_str(); } } // namespace sofa::component::animationloop I think the constexpr var `MODULE_NAME` (which is defined for each module normally, and in its own namespace) would be better than to use the SOFA_TARGET preproc macro void init() const char* getModuleComponentList() { /// string containing the names of the classes provided by the plugin + static std::string classes = core::ObjectFactory::getInstance()->listClassesFromTarget(sofa_tostring(MODULE_NAME)); return classes.c_str(); } } // namespace sofa::component::animationloop
codereview_new_cpp_data_11856
void init() const char* getModuleComponentList() { /// string containing the names of the classes provided by the plugin - static std::string classes = core::ObjectFactory::getInstance()->listClassesFromTarget(sofa_tostring(MODULE_NAME)); return classes.c_str(); } } // namespace sofa::component::animationloop I dont think `sofa_tostring` is still required ? void init() const char* getModuleComponentList() { /// string containing the names of the classes provided by the plugin + static std::string classes = core::ObjectFactory::getInstance()->listClassesFromTarget(MODULE_NAME); return classes.c_str(); } } // namespace sofa::component::animationloop
codereview_new_cpp_data_11857
void CarvingManager::init() if (d_surfaceModelPath.getValue().empty()) { // We look for a CollisionModel identified with the CarvingSurface Tag. - std::vector<core::CollisionModel*> models; - getContext()->get<core::CollisionModel>(&models, core::objectmodel::Tag("CarvingSurface"), core::objectmodel::BaseContext::SearchRoot); - for (size_t i=0;i<models.size();++i) - { - core::CollisionModel* m = models[i]; - m_surfaceCollisionModels.push_back(m); - } } else { ```suggestion getContext()->get<core::CollisionModel>(&m_surfaceCollisionModels, core::objectmodel::Tag("CarvingSurface"), core::objectmodel::BaseContext::SearchRoot); ``` void CarvingManager::init() if (d_surfaceModelPath.getValue().empty()) { // We look for a CollisionModel identified with the CarvingSurface Tag. + getContext()->get<core::CollisionModel>(&m_surfaceCollisionModels, core::objectmodel::Tag("CarvingSurface"), core::objectmodel::BaseContext::SearchRoot); } else {
codereview_new_cpp_data_11858
void FixedConstraint<Rigid3Types>::draw(const core::visual::VisualParams* vparam std::vector< Vector3 > points; - if (d_fixAll.getValue() == true) { for (unsigned i = 0; i < x.size(); i++) points.push_back(x[i].getCenter()); ```suggestion if (d_fixAll.getValue()) ``` void FixedConstraint<Rigid3Types>::draw(const core::visual::VisualParams* vparam std::vector< Vector3 > points; + if (d_fixAll.getValue()) { for (unsigned i = 0; i < x.size(); i++) points.push_back(x[i].getCenter());
codereview_new_cpp_data_11859
std::string PluginManager::getDefaultSuffix() #endif } -auto PluginManager::loadPluginByPath(const std::string& pluginPath, std::ostream* errlog) -> PluginLoadStatus { if (pluginIsLoaded(pluginPath)) { not sure you want to print an error for already loaded plugins. There will be a lot of print at each new start no? std::string PluginManager::getDefaultSuffix() #endif } +PluginManager::PluginLoadStatus PluginManager::loadPluginByPath(const std::string& pluginPath, std::ostream* errlog) { if (pluginIsLoaded(pluginPath)) {
codereview_new_cpp_data_11860
bool Base::parseField( const std::string& attribute, const std::string& value) if (dataVec.empty() && linkVec.empty()) { std::vector<std::string> possibleNames; for(auto& data : m_vecData) possibleNames.emplace_back(data->getName()); for(auto& link : m_vecLink) ```suggestion std::vector<std::string> possibleNames; possibleNames.reserve(m_vecData.size() + m_vecLink.size()); ``` bool Base::parseField( const std::string& attribute, const std::string& value) if (dataVec.empty() && linkVec.empty()) { std::vector<std::string> possibleNames; + possibleNames.reserve(m_vecData.size() + m_vecLink.size()); for(auto& data : m_vecData) possibleNames.emplace_back(data->getName()); for(auto& link : m_vecLink)
codereview_new_cpp_data_11863
std::string BPBase::ReadBPString(const std::vector<char> &buffer, // static members const std::set<std::string> BPBase::m_TransformTypes = { {"unknown", "none", "identity", "bzip2", "sz", "zfp", "mgard", "png", - "blosc", "blosc2", "sirius", "mgardplus", "plugin"}}; const std::map<int, std::string> BPBase::m_TransformTypesToNames = { - {transform_unknown, "unknown"}, {transform_none, "none"}, - {transform_identity, "identity"}, {transform_sz, "sz"}, - {transform_zfp, "zfp"}, {transform_mgard, "mgard"}, - {transform_png, "png"}, {transform_bzip2, "bzip2"}, - {transform_blosc, "blosc"}, {transform_blosc2, "blosc2"}, - {transform_sirius, "sirius"}, {transform_mgardplus, "mgardplus"}, {transform_plugin, "plugin"}}; BPBase::TransformTypes Same question, I feel we need to be consistent with what we are keeping (if `blosc2` the naming should reflect this). Maybe I am misunderstanding this std::string BPBase::ReadBPString(const std::vector<char> &buffer, // static members const std::set<std::string> BPBase::m_TransformTypes = { {"unknown", "none", "identity", "bzip2", "sz", "zfp", "mgard", "png", + "blosc", "sirius", "mgardplus", "plugin"}}; const std::map<int, std::string> BPBase::m_TransformTypesToNames = { + {transform_unknown, "unknown"}, + {transform_none, "none"}, + {transform_identity, "identity"}, + {transform_sz, "sz"}, + {transform_zfp, "zfp"}, + {transform_mgard, "mgard"}, + {transform_png, "png"}, + {transform_bzip2, "bzip2"}, + {transform_blosc, "blosc"}, + {transform_sirius, "sirius"}, + {transform_mgardplus, "mgardplus"}, {transform_plugin, "plugin"}}; BPBase::TransformTypes
codereview_new_cpp_data_11936
void ImproperAmoeba::init_style() // check if PairAmoeba disabled improper terms Pair *pair = nullptr; - pair = force->pair_match("amoeba",1,0); - if (!pair) pair = force->pair_match("amoeba/gpu",1,0); - if (!pair) pair = force->pair_match("hippo",1,0); - if (!pair) pair = force->pair_match("hippo/gpu",1,0); if (!pair) error->all(FLERR,"Improper amoeba could not find pair amoeba/hippo"); int tmp; Please see my previous comment on using `Force::pair_match()`. void ImproperAmoeba::init_style() // check if PairAmoeba disabled improper terms Pair *pair = nullptr; + pair = force->pair_match("^amoeba",0,0); + if (!pair) pair = force->pair_match("^hippo",0,0); + if (!pair) error->all(FLERR,"Improper amoeba could not find pair amoeba/hippo"); int tmp;
codereview_new_cpp_data_11937
void PairAmoeba::init_style() // request standard neighbor list - -// int irequest = neighbor->request(this,instance_me); - - // for DEBUGGING with GPU - //neighbor->requests[irequest]->half = 0; - //neighbor->requests[irequest]->full = 1; - neighbor->add_request(this); } More debug comments. The commented out code would not even work anymore if uncommented. void PairAmoeba::init_style() // request standard neighbor list neighbor->add_request(this); }
codereview_new_cpp_data_11938
MLIAPModelPython::MLIAPModelPython(LAMMPS *lmp, char *coefffilename, bool is_chi MLIAPModelPython::~MLIAPModelPython() { - if (model_loaded) MLIAPPY_unload_model(this); - model_loaded=false; } /* ---------------------------------------------------------------------- model_loaded is an integer variable not a boolean. MLIAPModelPython::MLIAPModelPython(LAMMPS *lmp, char *coefffilename, bool is_chi MLIAPModelPython::~MLIAPModelPython() { + if (model_loaded!=0) MLIAPPY_unload_model(this); + model_loaded=0; } /* ----------------------------------------------------------------------
codereview_new_cpp_data_11939
FixWallReflect::FixWallReflect(LAMMPS *lmp, int narg, char **arg) : for (int m = 0; m < nwall; m++) { if ((wallwhich[m] == XLO || wallwhich[m] == XHI) && domain->xperiodic) - error->all(FLERR,"Cannot use fix wall/reflect in xperiodic dimension"); if ((wallwhich[m] == YLO || wallwhich[m] == YHI) && domain->yperiodic) - error->all(FLERR,"Cannot use fix wall/reflect in yperiodic dimension"); if ((wallwhich[m] == ZLO || wallwhich[m] == ZHI) && domain->zperiodic) - error->all(FLERR,"Cannot use fix wall/reflect in zperiodic dimension"); } for (int m = 0; m < nwall; m++) ```suggestion error->all(FLERR,"Cannot use fix wall/reflect in periodic dimension x"); ``` and equivalent below. FixWallReflect::FixWallReflect(LAMMPS *lmp, int narg, char **arg) : for (int m = 0; m < nwall; m++) { if ((wallwhich[m] == XLO || wallwhich[m] == XHI) && domain->xperiodic) + error->all(FLERR,"Cannot use fix wall/reflect in periodic dimension x"); if ((wallwhich[m] == YLO || wallwhich[m] == YHI) && domain->yperiodic) + error->all(FLERR,"Cannot use fix wall/reflect in periodic dimension y"); if ((wallwhich[m] == ZLO || wallwhich[m] == ZHI) && domain->zperiodic) + error->all(FLERR,"Cannot use fix wall/reflect in periodic dimension z"); } for (int m = 0; m < nwall; m++)
codereview_new_cpp_data_11964
void flb_ml_parser_destroy_all(struct mk_list *list) struct mk_list *head; struct flb_ml_parser *parser; - /* Ensure list is initialized */ - if (list->next == NULL) { - return; - } - mk_list_foreach_safe(head, tmp, list) { parser = mk_list_entry(head, struct flb_ml_parser, _head); flb_ml_parser_destroy(parser); I think the check should not be here, if there is a mk_list_init() in place the check should not be needed. void flb_ml_parser_destroy_all(struct mk_list *list) struct mk_list *head; struct flb_ml_parser *parser; mk_list_foreach_safe(head, tmp, list) { parser = mk_list_entry(head, struct flb_ml_parser, _head); flb_ml_parser_destroy(parser);
codereview_new_cpp_data_11965
static flb_sds_t add_aws_signature(struct flb_http_client *c, struct flb_bigquer signature = flb_signv4_do(c, FLB_TRUE, FLB_TRUE, time(NULL), ctx->aws_region, "sts", - 0, ctx->aws_provider); if (!signature) { flb_plg_error(ctx->ins, "Could not sign the request with AWS SigV4"); return NULL; @matthewfala Do you know why we have AWS Auth in the bigquery output here?? Isn't that a google only product?? static flb_sds_t add_aws_signature(struct flb_http_client *c, struct flb_bigquer signature = flb_signv4_do(c, FLB_TRUE, FLB_TRUE, time(NULL), ctx->aws_region, "sts", + 0, NULL, ctx->aws_provider); if (!signature) { flb_plg_error(ctx->ins, "Could not sign the request with AWS SigV4"); return NULL;
codereview_new_cpp_data_11966
static struct flb_config_map config_map[] = { "Set the parser" }, { - FLB_CONFIG_MAP_SIZE, "buffer_rcv_size", (char *)NULL, - 0, FLB_TRUE, offsetof(struct flb_syslog, buffer_rcv_size), "Set the socket receiving buffer size" }, /* EOF */ please rename it to `receive_buffer_size` (and adjust all other name references. static struct flb_config_map config_map[] = { "Set the parser" }, { + FLB_CONFIG_MAP_SIZE, "receive_buffer_size", (char *)NULL, + 0, FLB_TRUE, offsetof(struct flb_syslog, receive_buffer_size), "Set the socket receiving buffer size" }, /* EOF */
codereview_new_cpp_data_11967
static int get_mode(unsigned int attr) static int64_t filetime_to_epoch(FILETIME ft) { - int64_t ldap; /* * The LDAP timestamp represents the number of * 100-nanosecond intervals since Jan 1, 1601 UTC. */ - ldap = UINT64(ft.dwHighDateTime, ft.dwLowDateTime); - return (ldap / LDAP_TO_SECONDS_DIVISOR) - LDAP_TO_EPOCH_DIFF_SECONDS; } static int is_symlink(const char *path) Please use a [ULARGE_INTEGER](https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-ularge_integer-r1) to store the QWORD instead of that custom cast. static int get_mode(unsigned int attr) static int64_t filetime_to_epoch(FILETIME ft) { + ULARGE_INTEGER ldap; /* * The LDAP timestamp represents the number of * 100-nanosecond intervals since Jan 1, 1601 UTC. */ + ldap.HighPart = ft.dwHighDateTime; + ldap.LowPart = ft.dwLowDateTime; + + return ((int64_t) ldap.QuadPart / LDAP_TO_SECONDS_DIVISOR) - LDAP_TO_EPOCH_DIFF_SECONDS; } static int is_symlink(const char *path)
codereview_new_cpp_data_11968
int api_v1_registration(struct flb_hs *hs) api_v1_metrics(hs); api_v1_plugins(hs); -#ifdef FLB_TRACE api_v1_trace(hs); -#endif // FLB_TRACE if (hs->config->health_check == FLB_TRUE) { api_v1_health(hs); wrong macro name int api_v1_registration(struct flb_hs *hs) api_v1_metrics(hs); api_v1_plugins(hs); +#ifdef FLB_HAVE_CHUNK_TRACE api_v1_trace(hs); +#endif /* FLB_HAVE_CHUNK_TRACE */ if (hs->config->health_check == FLB_TRUE) { api_v1_health(hs);
codereview_new_cpp_data_11980
bool OpenMP::in_parallel(OpenMP const &exec_space) noexcept { int OpenMP::impl_thread_pool_size() const noexcept { #ifdef KOKKOS_ENABLE_DEPRECATED_CODE_3 - return OpenMP::in_parallel() ? omp_get_num_threads() : (Impl::t_openmp_instance ? Impl::t_openmp_instance->m_pool_size : impl_internal_space_instance()->m_pool_size); #else - return OpenMP::in_parallel() ? omp_get_num_threads() - : impl_internal_space_instance()->m_pool_size; #endif } ```suggestion return in_parallel(*this) ``` bool OpenMP::in_parallel(OpenMP const &exec_space) noexcept { int OpenMP::impl_thread_pool_size() const noexcept { #ifdef KOKKOS_ENABLE_DEPRECATED_CODE_3 + return OpenMP::in_parallel(*this) ? omp_get_num_threads() : (Impl::t_openmp_instance ? Impl::t_openmp_instance->m_pool_size : impl_internal_space_instance()->m_pool_size); #else + return OpenMP::in_parallel(*this) + ? omp_get_num_threads() + : impl_internal_space_instance()->m_pool_size; #endif }
codereview_new_cpp_data_11981
TEST(hpx, independent_instances_delayed_execution) { KOKKOS_LAMBDA(int) { ran() = true; }); #if defined(KOKKOS_ENABLE_HPX_ASYNC_DISPATCH) - ASSERT_TRUE(!ran()); #else ASSERT_TRUE(ran()); #endif ```suggestion ASSERT_FALSE(ran()); ``` TEST(hpx, independent_instances_delayed_execution) { KOKKOS_LAMBDA(int) { ran() = true; }); #if defined(KOKKOS_ENABLE_HPX_ASYNC_DISPATCH) + ASSERT_FALSE(ran()); #else ASSERT_TRUE(ran()); #endif
codereview_new_cpp_data_11982
void hpx_thread_buffer::resize(const std::size_t num_threads, } void *hpx_thread_buffer::get(std::size_t thread_num) const noexcept { - KOKKOS_ASSERT(thread_num < m_num_threads); if (m_data == nullptr) { return nullptr; } return &m_data[thread_num * m_size_per_thread]; } void *hpx_thread_buffer::get_extra_space() const noexcept { - KOKKOS_ASSERT(m_extra_space > 0); if (m_data == nullptr) { return nullptr; } This is fine but just pointing out there is also a `KOKKOS_EXPECTS` that was meant for checking preconditions void hpx_thread_buffer::resize(const std::size_t num_threads, } void *hpx_thread_buffer::get(std::size_t thread_num) const noexcept { + KOKKOS_EXPECTS(thread_num < m_num_threads); if (m_data == nullptr) { return nullptr; } return &m_data[thread_num * m_size_per_thread]; } void *hpx_thread_buffer::get_extra_space() const noexcept { + KOKKOS_EXPECTS(m_extra_space > 0); if (m_data == nullptr) { return nullptr; }
codereview_new_cpp_data_11983
void hpx_thread_buffer::resize(const std::size_t num_threads, m_num_threads * m_size_per_thread + m_extra_space; if (m_size_total < size_total_new) { - delete[] m_data; - m_data = new char[size_total_new]; m_size_total = size_total_new; } } void *hpx_thread_buffer::get(std::size_t thread_num) const noexcept { KOKKOS_EXPECTS(thread_num < m_num_threads); - if (m_data == nullptr) { return nullptr; } return &m_data[thread_num * m_size_per_thread]; } void *hpx_thread_buffer::get_extra_space() const noexcept { KOKKOS_EXPECTS(m_extra_space > 0); - if (m_data == nullptr) { return nullptr; } return &m_data[m_num_threads * m_size_per_thread]; Is there a good reason not to use a smart pointer like `std::unique_ptr` or `std::shared_ptr` for `m_data`? void hpx_thread_buffer::resize(const std::size_t num_threads, m_num_threads * m_size_per_thread + m_extra_space; if (m_size_total < size_total_new) { + m_data = std::make_unique<char[]>(size_total_new); m_size_total = size_total_new; } } void *hpx_thread_buffer::get(std::size_t thread_num) const noexcept { KOKKOS_EXPECTS(thread_num < m_num_threads); + if (!m_data) { return nullptr; } return &m_data[thread_num * m_size_per_thread]; } void *hpx_thread_buffer::get_extra_space() const noexcept { KOKKOS_EXPECTS(m_extra_space > 0); + if (!m_data) { return nullptr; } return &m_data[m_num_threads * m_size_per_thread];
codereview_new_cpp_data_11984
int get_device_count() { return acc_get_num_devices( Kokkos::Experimental::Impl::OpenACC_Traits::dev_type); #elif defined(KOKKOS_ENABLE_OPENMPTARGET) - return Kokkos::Experimental::OpenMPTarget::detect_device_count(); #else Kokkos::abort("implementation bug"); return -1; ```suggestion #elif defined(KOKKOS_ENABLE_OPENMPTARGET) return omp_get_num_devices(); ``` int get_device_count() { return acc_get_num_devices( Kokkos::Experimental::Impl::OpenACC_Traits::dev_type); #elif defined(KOKKOS_ENABLE_OPENMPTARGET) + return omp_get_num_devices(); #else Kokkos::abort("implementation bug"); return -1;
codereview_new_cpp_data_11994
namespace model { OS_ASSERT(getImpl<detail::ZoneAirHeatBalanceAlgorithm_Impl>()); setAlgorithm("ThirdOrderBackwardDifference"); - setDoSpaceHeatBalanceforSizing("No"); - setDoSpaceHeatBalanceforSimulation("No"); } /// @endcond Well see, why would we have a Default and yet still force them here? namespace model { OS_ASSERT(getImpl<detail::ZoneAirHeatBalanceAlgorithm_Impl>()); setAlgorithm("ThirdOrderBackwardDifference"); + setDoSpaceHeatBalanceforSizing(false); + setDoSpaceHeatBalanceforSimulation(false); } /// @endcond
codereview_new_cpp_data_11995
namespace model { OS_ASSERT(ok); ok = setOutdoorUnitEvaporatorRatedBypassFactor(0.4); OS_ASSERT(ok); - ok = ok = setOutdoorUnitCondenserRatedBypassFactor(0.2); OS_ASSERT(ok); ok = setDifferencebetweenOutdoorUnitEvaporatingTemperatureandOutdoorAirTemperatureinHeatRecoveryMode(5); OS_ASSERT(ok); ```suggestion ok = setOutdoorUnitCondenserRatedBypassFactor(0.2); ``` namespace model { OS_ASSERT(ok); ok = setOutdoorUnitEvaporatorRatedBypassFactor(0.4); OS_ASSERT(ok); + ok = setOutdoorUnitCondenserRatedBypassFactor(0.2); OS_ASSERT(ok); ok = setDifferencebetweenOutdoorUnitEvaporatingTemperatureandOutdoorAirTemperatureinHeatRecoveryMode(5); OS_ASSERT(ok);
codereview_new_cpp_data_11996
namespace model { bool ok = true; ok = setCompressorSpeed(compressorSpeed); OS_ASSERT(ok); - ok = setEvaporativeCapacityMultiplierFunctionofTemperatureCurve(evaporativeCapacityMultiplierFunctionofTemperatureCurve); - OS_ASSERT(ok); - ok = setCompressorPowerMultiplierFunctionofTemperatureCurve(compressorPowerMultiplierFunctionofTemperatureCurve); - OS_ASSERT(ok); } IddObjectType LoadingIndex::iddObjectType() { probably want to do this, as it's not unlikely the curve wouldn't match. ``` bool ok = setEvaporativeCapacityMultiplierFunctionofTemperatureCurve(evaporativeCapacityMultiplierFunctionofTemperatureCurve); if (!ok) { remove(); LOG_AND_THROW("Unable to set " << briefDescription() << "'s Evaporative Capacity Multiplier Function of Temperature Curve Coil to " << evaporativeCapacityMultiplierFunctionofTemperatureCurve.briefDescription() << "."); } ``` namespace model { bool ok = true; ok = setCompressorSpeed(compressorSpeed); OS_ASSERT(ok); + bool ok = setEvaporativeCapacityMultiplierFunctionofTemperatureCurve(evaporativeCapacityMultiplierFunctionofTemperatureCurve); + if (!ok) { + remove(); + LOG_AND_THROW("Unable to set " << briefDescription() << "'s Evaporative Capacity Multiplier Function of Temperature Curve to " << evaporativeCapacityMultiplierFunctionofTemperatureCurve.briefDescription() << "."); + } + bool ok = setCompressorPowerMultiplierFunctionofTemperatureCurve(compressorPowerMultiplierFunctionofTemperatureCurve); + if (!ok) { + remove(); + LOG_AND_THROW("Unable to set " << briefDescription() << "'s Compressor Power Multiplier Function of Temperature Curve to " << compressorPowerMultiplierFunctionofTemperatureCurve.briefDescription() << "."); + } } IddObjectType LoadingIndex::iddObjectType() {
codereview_new_cpp_data_11997
TEST_F(ModelFixture, AirConditionerVariableRefrigerantFlow_addToNode) { TEST_F(ModelFixture, AirConditionerVariableRefrigerantFlow_Remove) { Model model; auto size = model.modelObjects().size(); AirConditionerVariableRefrigerantFlow vrf(model); EXPECT_EQ(0u, model.getObjectsByType(CurveQuadratic::iddObjectType()).size()); EXPECT_EQ(9u, model.getObjectsByType(CurveBiquadratic::iddObjectType()).size()); EXPECT_EQ(11u, model.getObjectsByType(CurveCubic::iddObjectType()).size()); - ZoneHVACTerminalUnitVariableRefrigerantFlow term(model); - EXPECT_EQ(1u, model.getObjectsByType(ZoneHVACTerminalUnitVariableRefrigerantFlow::iddObjectType()).size()); - vrf.addTerminal(term); - EXPECT_EQ(1u, vrf.terminals().size()); EXPECT_FALSE(vrf.remove().empty()); EXPECT_EQ(0u, model.getObjectsByType(CurveQuadratic::iddObjectType()).size()); EXPECT_EQ(0u, model.getObjectsByType(CurveBiquadratic::iddObjectType()).size()); EXPECT_EQ(0u, model.getObjectsByType(CurveCubic::iddObjectType()).size()); - EXPECT_EQ(0u, model.getObjectsByType(ZoneHVACTerminalUnitVariableRefrigerantFlow::iddObjectType()).size()); EXPECT_EQ(size + 2, model.modelObjects().size()); // Always On Discrete, OnOff } this is C++, use the templated one, and since this is a concrete class: ```suggestion EXPECT_EQ(1u, model.getConcreteModelObjects<ZoneHVACTerminalUnitVariableRefrigerantFlow>().size()); ``` TEST_F(ModelFixture, AirConditionerVariableRefrigerantFlow_addToNode) { TEST_F(ModelFixture, AirConditionerVariableRefrigerantFlow_Remove) { Model model; + + EXPECT_EQ(0u, model.getObjectsByType(CurveQuadratic::iddObjectType()).size()); + EXPECT_EQ(0u, model.getObjectsByType(CurveBiquadratic::iddObjectType()).size()); + EXPECT_EQ(0u, model.getObjectsByType(CurveCubic::iddObjectType()).size()); + EXPECT_EQ(0u, model.getObjectsByType(ZoneHVACTerminalUnitVariableRefrigerantFlow::iddObjectType()).size()); + EXPECT_EQ(0u, model.getObjectsByType(ModelObjectList::iddObjectType()).size()); + auto size = model.modelObjects().size(); AirConditionerVariableRefrigerantFlow vrf(model); + ZoneHVACTerminalUnitVariableRefrigerantFlow term(model); + vrf.addTerminal(term); + EXPECT_EQ(1u, vrf.terminals().size()); + EXPECT_EQ(0u, model.getObjectsByType(CurveQuadratic::iddObjectType()).size()); EXPECT_EQ(9u, model.getObjectsByType(CurveBiquadratic::iddObjectType()).size()); EXPECT_EQ(11u, model.getObjectsByType(CurveCubic::iddObjectType()).size()); + EXPECT_EQ(1u, model.getConcreteModelObjects<ZoneHVACTerminalUnitVariableRefrigerantFlow>().size()); + EXPECT_FALSE(vrf.remove().empty()); EXPECT_EQ(0u, model.getObjectsByType(CurveQuadratic::iddObjectType()).size()); EXPECT_EQ(0u, model.getObjectsByType(CurveBiquadratic::iddObjectType()).size()); EXPECT_EQ(0u, model.getObjectsByType(CurveCubic::iddObjectType()).size()); + EXPECT_EQ(0u, model.getConcreteModelObjects<ZoneHVACTerminalUnitVariableRefrigerantFlow>().size()); EXPECT_EQ(size + 2, model.modelObjects().size()); // Always On Discrete, OnOff }
codereview_new_cpp_data_11998
TEST_F(ModelFixture, AirConditionerVariableRefrigerantFlow_addToNode) { TEST_F(ModelFixture, AirConditionerVariableRefrigerantFlow_Remove) { Model model; auto size = model.modelObjects().size(); AirConditionerVariableRefrigerantFlow vrf(model); EXPECT_EQ(0u, model.getObjectsByType(CurveQuadratic::iddObjectType()).size()); EXPECT_EQ(9u, model.getObjectsByType(CurveBiquadratic::iddObjectType()).size()); EXPECT_EQ(11u, model.getObjectsByType(CurveCubic::iddObjectType()).size()); - ZoneHVACTerminalUnitVariableRefrigerantFlow term(model); - EXPECT_EQ(1u, model.getObjectsByType(ZoneHVACTerminalUnitVariableRefrigerantFlow::iddObjectType()).size()); - vrf.addTerminal(term); - EXPECT_EQ(1u, vrf.terminals().size()); EXPECT_FALSE(vrf.remove().empty()); EXPECT_EQ(0u, model.getObjectsByType(CurveQuadratic::iddObjectType()).size()); EXPECT_EQ(0u, model.getObjectsByType(CurveBiquadratic::iddObjectType()).size()); EXPECT_EQ(0u, model.getObjectsByType(CurveCubic::iddObjectType()).size()); - EXPECT_EQ(0u, model.getObjectsByType(ZoneHVACTerminalUnitVariableRefrigerantFlow::iddObjectType()).size()); EXPECT_EQ(size + 2, model.modelObjects().size()); // Always On Discrete, OnOff } add this to make sure ``` EXPECT_EQ(0, model.getConcreteModelObjects<AirConditionerVariableRefrigerantFlow>().size()); ``` TEST_F(ModelFixture, AirConditionerVariableRefrigerantFlow_addToNode) { TEST_F(ModelFixture, AirConditionerVariableRefrigerantFlow_Remove) { Model model; + + EXPECT_EQ(0u, model.getObjectsByType(CurveQuadratic::iddObjectType()).size()); + EXPECT_EQ(0u, model.getObjectsByType(CurveBiquadratic::iddObjectType()).size()); + EXPECT_EQ(0u, model.getObjectsByType(CurveCubic::iddObjectType()).size()); + EXPECT_EQ(0u, model.getObjectsByType(ZoneHVACTerminalUnitVariableRefrigerantFlow::iddObjectType()).size()); + EXPECT_EQ(0u, model.getObjectsByType(ModelObjectList::iddObjectType()).size()); + auto size = model.modelObjects().size(); AirConditionerVariableRefrigerantFlow vrf(model); + ZoneHVACTerminalUnitVariableRefrigerantFlow term(model); + vrf.addTerminal(term); + EXPECT_EQ(1u, vrf.terminals().size()); + EXPECT_EQ(0u, model.getObjectsByType(CurveQuadratic::iddObjectType()).size()); EXPECT_EQ(9u, model.getObjectsByType(CurveBiquadratic::iddObjectType()).size()); EXPECT_EQ(11u, model.getObjectsByType(CurveCubic::iddObjectType()).size()); + EXPECT_EQ(1u, model.getConcreteModelObjects<ZoneHVACTerminalUnitVariableRefrigerantFlow>().size()); + EXPECT_FALSE(vrf.remove().empty()); EXPECT_EQ(0u, model.getObjectsByType(CurveQuadratic::iddObjectType()).size()); EXPECT_EQ(0u, model.getObjectsByType(CurveBiquadratic::iddObjectType()).size()); EXPECT_EQ(0u, model.getObjectsByType(CurveCubic::iddObjectType()).size()); + EXPECT_EQ(0u, model.getConcreteModelObjects<ZoneHVACTerminalUnitVariableRefrigerantFlow>().size()); EXPECT_EQ(size + 2, model.modelObjects().size()); // Always On Discrete, OnOff }
codereview_new_cpp_data_11999
namespace energyplus { std::vector<AirConditionerVariableRefrigerantFlowFluidTemperatureControl> vrfftcs = model.getConcreteModelObjects<AirConditionerVariableRefrigerantFlowFluidTemperatureControl>(); std::sort(vrfftcs.begin(), vrfftcs.end(), WorkspaceObjectNameLess()); - for (AirConditionerVariableRefrigerantFlowFluidTemperatureControl vrfftc : vrfftcs) { translateAndMapModelObject(vrfftc); } // get AirConditionerVariableRefrigerantFlowFluidTemperatureControlHR objects in sorted order std::vector<AirConditionerVariableRefrigerantFlowFluidTemperatureControlHR> vrfftchrs = model.getConcreteModelObjects<AirConditionerVariableRefrigerantFlowFluidTemperatureControlHR>(); std::sort(vrfftchrs.begin(), vrfftchrs.end(), WorkspaceObjectNameLess()); - for (AirConditionerVariableRefrigerantFlowFluidTemperatureControlHR vrfftchr : vrfftchrs) { translateAndMapModelObject(vrfftchr); } I know you're copying above, but to avoid having to do another pass ocne #4532 is merged, please take a reference here ```suggestion for (auto& vrfftc : vrfftcs) { ``` namespace energyplus { std::vector<AirConditionerVariableRefrigerantFlowFluidTemperatureControl> vrfftcs = model.getConcreteModelObjects<AirConditionerVariableRefrigerantFlowFluidTemperatureControl>(); std::sort(vrfftcs.begin(), vrfftcs.end(), WorkspaceObjectNameLess()); + for (auto& vrfftc : vrfftcs) { translateAndMapModelObject(vrfftc); } // get AirConditionerVariableRefrigerantFlowFluidTemperatureControlHR objects in sorted order std::vector<AirConditionerVariableRefrigerantFlowFluidTemperatureControlHR> vrfftchrs = model.getConcreteModelObjects<AirConditionerVariableRefrigerantFlowFluidTemperatureControlHR>(); std::sort(vrfftchrs.begin(), vrfftchrs.end(), WorkspaceObjectNameLess()); + for (auto& vrfftchr : vrfftchrs) { translateAndMapModelObject(vrfftchr); }
codereview_new_cpp_data_12000
std::ostream& operator<<(std::ostream& os, const BoostMultiPolygon& boostPolygon return os; } -// Scale factor for parameters passed to boost -double scaleBy = 1000.0; // Cleans a polygon by shrinking and expanding. Can return multiple polygons std::vector<BoostPolygon> removeSpikesEx(const BoostPolygon& polygon) { Never use a global variable like this. ```suggestion // Scale factor for parameters when converting between openstudio and boost data formats to improve the numerical accuracy of the boolean operations. // Idea came from this comment in the boostorg/geometry repo: https://github.com/boostorg/geometry/issues/1034#issuecomment-1284180101 // where the author indicates that scaling the values by 10 improved the result and talks about rounding to an integer grid, // so by increasing the range of values we pass to boost we should be improving the resolution of the integer rounding static constexpr double scaleBy = 1000.0; ``` std::ostream& operator<<(std::ostream& os, const BoostMultiPolygon& boostPolygon return os; } +// Scale factor for parameters when converting between openstudio and boost data formats to improve the numerical accuracy of the boolean operations. +// Idea came from this comment in the boostorg/geometry repo: https://github.com/boostorg/geometry/issues/1034#issuecomment-1284180101 +// where the author indicates that scaling the values by 10 improved the result and talks about rounding to an integer grid, +// so by increasing the range of values we pass to boost we should be improving the resolution of the integer rounding +static constexpr double scaleBy = 1000.0; // Cleans a polygon by shrinking and expanding. Can return multiple polygons std::vector<BoostPolygon> removeSpikesEx(const BoostPolygon& polygon) {
codereview_new_cpp_data_12001
namespace osversion { IdfObject newObject(iddObject.get()); for (size_t i = 0; i < object.numFields(); ++i) { - auto value = object.getString(i); - if (value) { if (i < 3) { newObject.setString(i, value.get()); } else { ```suggestion if ((value = object.getString(i))) { ``` namespace osversion { IdfObject newObject(iddObject.get()); for (size_t i = 0; i < object.numFields(); ++i) { + if ((value = object.getString(i))) { if (i < 3) { newObject.setString(i, value.get()); } else {
codereview_new_cpp_data_12002
namespace energyplus { // for CeilingHeight, Volume, FloorArea: only FT if hard set (same logic as for ThermalZone) // CeilingHeight - if (modelObject.getDouble(OS_SpaceFields::CeilingHeight)) { - idfObject.setDouble(SpaceFields::CeilingHeight, modelObject.getDouble(SpaceFields::CeilingHeight).get()); } // Volume - if (modelObject.getDouble(OS_SpaceFields::Volume)) { - idfObject.setDouble(SpaceFields::Volume, modelObject.getDouble(OS_SpaceFields::Volume).get()); } // FloorArea - if (modelObject.getDouble(OS_SpaceFields::FloorArea)) { - idfObject.setDouble(SpaceFields::FloorArea, modelObject.getDouble(OS_SpaceFields::FloorArea).get()); } // SpaceType ```suggestion if (!modelObject.isVolumeDefaulted()) { idfObject.setDouble(SpaceFields::Volume, modelObject.volume()); } ``` namespace energyplus { // for CeilingHeight, Volume, FloorArea: only FT if hard set (same logic as for ThermalZone) // CeilingHeight + if (!modelObject.isCeilingHeightDefaulted()) { + idfObject.setDouble(SpaceFields::CeilingHeight, modelObject.ceilingHeight()); } // Volume + if (!modelObject.isVolumeDefaulted()) { + idfObject.setDouble(SpaceFields::Volume, modelObject.volume()); } // FloorArea + if (!modelObject.isFloorAreaDefaulted()) { + idfObject.setDouble(SpaceFields::FloorArea, modelObject.floorArea()); } // SpaceType
codereview_new_cpp_data_12003
namespace energyplus { // for CeilingHeight, Volume, FloorArea: only FT if hard set (same logic as for ThermalZone) // CeilingHeight - if (modelObject.getDouble(OS_SpaceFields::CeilingHeight)) { - idfObject.setDouble(SpaceFields::CeilingHeight, modelObject.getDouble(SpaceFields::CeilingHeight).get()); } // Volume - if (modelObject.getDouble(OS_SpaceFields::Volume)) { - idfObject.setDouble(SpaceFields::Volume, modelObject.getDouble(OS_SpaceFields::Volume).get()); } // FloorArea - if (modelObject.getDouble(OS_SpaceFields::FloorArea)) { - idfObject.setDouble(SpaceFields::FloorArea, modelObject.getDouble(OS_SpaceFields::FloorArea).get()); } // SpaceType ```suggestion if (!modelObject.isCeilingHeightDefaulted()) { idfObject.setDouble(SpaceFields::CeilingHeight, modelObject.ceilingHeight()); } ``` namespace energyplus { // for CeilingHeight, Volume, FloorArea: only FT if hard set (same logic as for ThermalZone) // CeilingHeight + if (!modelObject.isCeilingHeightDefaulted()) { + idfObject.setDouble(SpaceFields::CeilingHeight, modelObject.ceilingHeight()); } // Volume + if (!modelObject.isVolumeDefaulted()) { + idfObject.setDouble(SpaceFields::Volume, modelObject.volume()); } // FloorArea + if (!modelObject.isFloorAreaDefaulted()) { + idfObject.setDouble(SpaceFields::FloorArea, modelObject.floorArea()); } // SpaceType
codereview_new_cpp_data_12004
namespace energyplus { // for CeilingHeight, Volume, FloorArea: only FT if hard set (same logic as for ThermalZone) // CeilingHeight - if (modelObject.getDouble(OS_SpaceFields::CeilingHeight)) { - idfObject.setDouble(SpaceFields::CeilingHeight, modelObject.getDouble(SpaceFields::CeilingHeight).get()); } // Volume - if (modelObject.getDouble(OS_SpaceFields::Volume)) { - idfObject.setDouble(SpaceFields::Volume, modelObject.getDouble(OS_SpaceFields::Volume).get()); } // FloorArea - if (modelObject.getDouble(OS_SpaceFields::FloorArea)) { - idfObject.setDouble(SpaceFields::FloorArea, modelObject.getDouble(OS_SpaceFields::FloorArea).get()); } // SpaceType ```suggestion if (!modelObject.isFloorAreaDefaulted()) { idfObject.setDouble(SpaceFields::FloorArea, modelObject.floorArea()); } ``` namespace energyplus { // for CeilingHeight, Volume, FloorArea: only FT if hard set (same logic as for ThermalZone) // CeilingHeight + if (!modelObject.isCeilingHeightDefaulted()) { + idfObject.setDouble(SpaceFields::CeilingHeight, modelObject.ceilingHeight()); } // Volume + if (!modelObject.isVolumeDefaulted()) { + idfObject.setDouble(SpaceFields::Volume, modelObject.volume()); } // FloorArea + if (!modelObject.isFloorAreaDefaulted()) { + idfObject.setDouble(SpaceFields::FloorArea, modelObject.floorArea()); } // SpaceType
codereview_new_cpp_data_12005
namespace energyplus { boost::optional<IdfObject> ForwardTranslator::translateOutputConstructions(OutputConstructions& modelObject) { // If nothing to write, don't - bool constructions = modelObject.constructions(); - bool materials = modelObject.materials(); - if (!constructions && !materials) { return boost::none; } IdfObject idfObject = createAndRegisterIdfObject(openstudio::IddObjectType::Output_Constructions, modelObject); - if (modelObject.constructions()) { idfObject.setString(Output_ConstructionsFields::DetailsType1, "Constructions"); - } - - if (modelObject.materials()) { - idfObject.setString(Output_ConstructionsFields::DetailsType2, "Materials"); } return idfObject; Have you tested whether this works when you have Constructions = No and Materials = yes? This leads to this IDF object: ``` Output:Constructions, , !- Details Type 1 Materials; !- Details Type 2 ``` namespace energyplus { boost::optional<IdfObject> ForwardTranslator::translateOutputConstructions(OutputConstructions& modelObject) { // If nothing to write, don't + bool reportForConstructions = modelObject.constructions(); + bool reportForMaterials = modelObject.materials(); + if (!reportForConstructions && !reportForMaterials) { return boost::none; } IdfObject idfObject = createAndRegisterIdfObject(openstudio::IddObjectType::Output_Constructions, modelObject); + if (reportForConstructions) { idfObject.setString(Output_ConstructionsFields::DetailsType1, "Constructions"); + if (reportForMaterials) { + idfObject.setString(Output_ConstructionsFields::DetailsType2, "Materials"); + } + } else if (reportForMaterials) { + idfObject.setString(Output_ConstructionsFields::DetailsType1, "Materials"); } return idfObject;
codereview_new_cpp_data_12006
namespace energyplus { boost::optional<IdfObject> ForwardTranslator::translateOutputConstructions(OutputConstructions& modelObject) { // If nothing to write, don't - bool constructions = modelObject.constructions(); - bool materials = modelObject.materials(); - if (!constructions && !materials) { return boost::none; } IdfObject idfObject = createAndRegisterIdfObject(openstudio::IddObjectType::Output_Constructions, modelObject); - if (modelObject.constructions()) { idfObject.setString(Output_ConstructionsFields::DetailsType1, "Constructions"); - } - - if (modelObject.materials()) { - idfObject.setString(Output_ConstructionsFields::DetailsType2, "Materials"); } return idfObject; I assume E+ is unhappy if you end up with a blank object? namespace energyplus { boost::optional<IdfObject> ForwardTranslator::translateOutputConstructions(OutputConstructions& modelObject) { // If nothing to write, don't + bool reportForConstructions = modelObject.constructions(); + bool reportForMaterials = modelObject.materials(); + if (!reportForConstructions && !reportForMaterials) { return boost::none; } IdfObject idfObject = createAndRegisterIdfObject(openstudio::IddObjectType::Output_Constructions, modelObject); + if (reportForConstructions) { idfObject.setString(Output_ConstructionsFields::DetailsType1, "Constructions"); + if (reportForMaterials) { + idfObject.setString(Output_ConstructionsFields::DetailsType2, "Materials"); + } + } else if (reportForMaterials) { + idfObject.setString(Output_ConstructionsFields::DetailsType1, "Materials"); } return idfObject;
codereview_new_cpp_data_12007
TEST_F(ModelFixture, 4678_SurfaceGlassUFactorSqlError) { ASSERT_TRUE(surface->uFactor()); double uFactor = surface->uFactor().get(); - EXPECT_TRUE(openstudio::equal(0.310, uFactor, 1.0E-3)); ASSERT_TRUE(surface->thermalConductance()); double thermalConductance = surface->thermalConductance().get(); - EXPECT_TRUE(openstudio::equal(0.325, thermalConductance, 1.0E-3)); } `EXPECT_DOUBLE_EQ(val1, val2)` is meant for this, and will report a nicer output in case it fails. > Verifies that the two double values val1 and val2 are approximately equal, to within 4 ULPs from each other. If you need a specific tolerance (I don't think you do), then use `EXPECT_NEAR(val1, val2, abs_error)` TEST_F(ModelFixture, 4678_SurfaceGlassUFactorSqlError) { ASSERT_TRUE(surface->uFactor()); double uFactor = surface->uFactor().get(); + EXPECT_NEAR(0.310, uFactor, 1E-03); ASSERT_TRUE(surface->thermalConductance()); double thermalConductance = surface->thermalConductance().get(); + EXPECT_NEAR(0.325, thermalConductance, 1E-03); }