id
stringlengths
21
25
content
stringlengths
164
2.33k
codereview_cpp_data_7371
switch ( direction ) { case Direction::TOP_LEFT: { assert( index >= mapWidth + 1 ); - - const bool isLeftTileWater = GetTiles( index - 1 ).isWater(); - const bool isTopTileWater = GetTiles( index - mapWidth ).isWater(); - const bool isTopLeftTileWater = GetTiles( index - mapWidth - 1 ).isWater(); - - if ( isTopLeftTileWater != isLeftTileWater || isTopLeftTileWater != isTopTileWater ) { return false; } Check if this condition is correct. Function will return false you try to land diagonally and on of the adjacent tiles is water (i.e. not in the corner but on straight piece of land). switch ( direction ) { case Direction::TOP_LEFT: { assert( index >= mapWidth + 1 ); + if ( GetTiles( index - mapWidth - 1 ).isWater() && ( !GetTiles( index - 1 ).isWater() || !GetTiles( index - mapWidth ).isWater() ) ) { + // Cannot sail through the corner of land. return false; }
codereview_cpp_data_7378
& BOOST_SERIALIZATION_NVP(m_offset_to_empire_id); } else { auto temp_empire_id = empire_id; - ar & boost::serialization::make_nvp("m_empire_id", temp_empire_id); // Filter the map for empires so they only have their own actual next id and no // information about other clients. is `temp_empire_id` needed? & BOOST_SERIALIZATION_NVP(m_offset_to_empire_id); } else { auto temp_empire_id = empire_id; + ar & boost::serialization::make_nvp(BOOST_PP_STRINGIZE(m_empire_id), temp_empire_id); // Filter the map for empires so they only have their own actual next id and no // information about other clients.
codereview_cpp_data_7385
conn->server_protocol_version = server_version; - return 0; } static int s2n_server_supported_versions_recv(struct s2n_connection *conn, struct s2n_stuffer *in) /nit Replace 6 with a constant value conn->server_protocol_version = server_version; + return S2N_SUCCESS; } static int s2n_server_supported_versions_recv(struct s2n_connection *conn, struct s2n_stuffer *in)
codereview_cpp_data_7390
} /** - * Returns whether *this not allows sending a notification of type type right now. * - * @param type The type of notification to send (or not to send). * - * @return Whether not to send the notification. */ bool Checkable::NotificationReasonSuppressed(NotificationType type) { ```suggestion /** * Checks if notifications of a given type should be suppressed for this Checkable at the moment. * * @param type The notification type for which to query the suppression status. * * @return true if no notification of this type should be sent. */ ``` } /** + * Checks if notifications of a given type should be suppressed for this Checkable at the moment. * + * @param type The notification type for which to query the suppression status. * + * @return true if no notification of this type should be sent. */ bool Checkable::NotificationReasonSuppressed(NotificationType type) {
codereview_cpp_data_7391
// request proposal for the current round auto proposal = network_client_->onRequestProposal(current_round_); - auto final_proposal = this->processProposalRequest(proposal); // vote for the object received from the network proposal_notifier_.get_subscriber().on_next(std::move(final_proposal)); })), Maybe use `std::move(proposal)` instead? Because `proposal` should not be used after processing it // request proposal for the current round auto proposal = network_client_->onRequestProposal(current_round_); + auto final_proposal = this->processProposalRequest(std::move(proposal)); // vote for the object received from the network proposal_notifier_.get_subscriber().on_next(std::move(final_proposal)); })),
codereview_cpp_data_7393
object[i]._oMissFlag = AllObjects[ot].oMissFlag; object[i]._oLight = AllObjects[ot].oLightFlag; object[i]._oBreak = AllObjects[ot].oBreak; - object[i]._oDelFlag = 0; object[i]._oSelFlag = AllObjects[ot].oSelFlag; object[i]._oPreFlag = FALSE; object[i]._oTrapFlag = FALSE; `_oDelFlag` should be chaned to BOOL object[i]._oMissFlag = AllObjects[ot].oMissFlag; object[i]._oLight = AllObjects[ot].oLightFlag; object[i]._oBreak = AllObjects[ot].oBreak; + object[i]._oDelFlag = FALSE; object[i]._oSelFlag = AllObjects[ot].oSelFlag; object[i]._oPreFlag = FALSE; object[i]._oTrapFlag = FALSE;
codereview_cpp_data_7402
data.special_flag[2] = special_flag[2]; data.special_flag[3] = special_flag[3]; - if(list->d_neighbors.dimension_0()<nall) { // Can this EVER be true??? - TIM 20170215 - list->d_neighbors = typename ArrayTypes<DeviceType>::t_neighbors_2d("neighbors", nall*1.1, list->maxneighs); - list->d_numneigh = typename ArrayTypes<DeviceType>::t_int_1d("numneigh", nall*1.1); - data.neigh_list.d_neighbors = list->d_neighbors; - data.neigh_list.d_numneigh = list->d_numneigh; - } data.h_resize()=1; while(data.h_resize()) { data.h_new_maxneighs() = list->maxneighs; I don't remember why I asked this question, but I guess it still stands... Can (list->d_neighbors.dimension_0()<nall) ever be true at this point in the code? data.special_flag[2] = special_flag[2]; data.special_flag[3] = special_flag[3]; data.h_resize()=1; while(data.h_resize()) { data.h_new_maxneighs() = list->maxneighs;
codereview_cpp_data_7405
c->di_unit = LLVMDIBuilderCreateCompileUnit(c->di, LLVMDWARFSourceLanguageC_plus_plus, fileRef, version, strlen(version), opt->release, - opt->all_args, strlen(opt->all_args), 0, "", 0, - LLVMDWARFEmissionFull, 0, false, false, "", 0, "", 0); # else c->di_unit = LLVMDIBuilderCreateCompileUnit(c->di, we should talk about if we want to delete code for older versions of LLVM. Given that we don't support using other LLVMs, I would be in favor of deleting and only having currently supported version. I remember us saying we would discuss this eventually. Maybe now is a good to have that "eventually" discussion. If we did however, I'd want to do that removal as a separate PR. c->di_unit = LLVMDIBuilderCreateCompileUnit(c->di, LLVMDWARFSourceLanguageC_plus_plus, fileRef, version, strlen(version), opt->release, + opt->all_args ? opt->all_args : "", + opt->all_args ? strlen(opt->all_args) : 0, + 0, "", 0, LLVMDWARFEmissionFull, 0, false, false, "", 0, "", 0); # else c->di_unit = LLVMDIBuilderCreateCompileUnit(c->di,
codereview_cpp_data_7410
result.push_back(std::move(slice)); return caf::none; }; - // TODO: Figure out why we cannot iteratore over `*segment->ids()` directly. auto intervals = std::vector(segment->ids()->begin(), segment->ids()->end()); auto flat_slices = std::vector(segment->slices()->begin(), segment->slices()->end()); The Flatbuffers::Vector<Offset<T>> iterator dereferences to a temporary pointer, this works for normal iteration, but the `zip` adapter tries to take the address of that pointer, which can't work. Alternatively, we could change `select_with` to iterate over 2 ranges in lockstep. result.push_back(std::move(slice)); return caf::none; }; + // TODO: We cannot iterate over `*segment->ids()` and `*segment->slices()` + // directly here, because the `flatbuffers::Vector<Offset<T>>` iterator + // dereferences to a temporary pointer. This works for normal iteration, but + // the `detail::zip` adapter tries to take the address of the pointer, which + // cannot work. We could improve this by adding a `select_with` overload that + // iterates over multiple ranges in lockstep. auto intervals = std::vector(segment->ids()->begin(), segment->ids()->end()); auto flat_slices = std::vector(segment->slices()->begin(), segment->slices()->end());
codereview_cpp_data_7411
Timer::~Timer() { - delete _timer; } bool Timer::valid() const :warning: **clang\-diagnostic\-delete\-incomplete** :warning: cannot delete expression with pointer\-to\-`` void `` type `` void * `` Timer::~Timer() { + delete static_cast<TimerImp *>( _timer ); } bool Timer::valid() const
codereview_cpp_data_7417
for (auto & sync : client->syncs) { - if (sync->localroot->ts == TREESTATE_SYNCING) { return true; } Not sure, but you might want to consider the abnormal state `TREESTATE_PENDING` here too, since it's also syncing, but waiting for stable `mtime`/`size` or waiting for the upload to complete and put the node. It all depends on the planned usage for this new function. for (auto & sync : client->syncs) { + if (sync->localroot->ts == TREESTATE_SYNCING || sync->localroot->ts == TREESTATE_PENDING) { return true; }
codereview_cpp_data_7418
_icnId = icnId; _releasedIndex = releasedIndex; _pressedIndex = pressedIndex; - _releasedDisabled.reset(); } const Sprite & Button::_getPressed() const We should not expose this class member to child classes. Please move it to private section. The correct way to invalidate this unique pointer is to remember a pointer to the original image and compare it every time. within `void ButtonBase::draw( Image & area )` method. _icnId = icnId; _releasedIndex = releasedIndex; _pressedIndex = pressedIndex; } const Sprite & Button::_getPressed() const
codereview_cpp_data_7424
} else { - if( x == "" ) source = SFX->playOnce( tempProfile ); else { `if (dStrcmp(x, "") == 0)` too. } else { + if (dStrcmp(x, "") == 0) source = SFX->playOnce( tempProfile ); else {
codereview_cpp_data_7426
if (values.count() != 4) error->one(FLERR,"Invalid Coords section in molecule file"); int iatom = values.next_int() - 1; - if (iatom >= natoms) error->one(FLERR,"Invalid Coords section in molecule file"); x[iatom][0] = values.next_double(); x[iatom][1] = values.next_double(); x[iatom][2] = values.next_double(); There should be range check for `iatom < 0` too. if (values.count() != 4) error->one(FLERR,"Invalid Coords section in molecule file"); int iatom = values.next_int() - 1; + if (iatom < 0 || iatom >= natoms) error->one(FLERR,"Invalid Coords section in molecule file"); x[iatom][0] = values.next_double(); x[iatom][1] = values.next_double(); x[iatom][2] = values.next_double();
codereview_cpp_data_7431
using namespace interface::types; struct Proposal::Impl { - Impl(TransportType &&ref) : proto_(std::move(ref)) {} - Impl(const TransportType &ref) : proto_(ref) {} TransportType proto_; Please use explicit for these two constructors as suggested by codacy. using namespace interface::types; struct Proposal::Impl { + explicit Impl(TransportType &&ref) : proto_(std::move(ref)) {} + explicit Impl(const TransportType &ref) : proto_(ref) {} TransportType proto_;
codereview_cpp_data_7441
const int id = spell.GetID(); const uint32_t spellCost = spell.SpellPoint(); - const uint32_t casts = spellCost ? std::min( 10u, currentSpellPoints / spellCost ) : 0; // use quadratic formula to diminish returns from subsequent spell casts, (up to x5 when spell has 10 uses) const double amountModifier = ( casts == 1 ) ? 1 : casts - ( 0.05 * casts * casts ); :warning: **readability\-uppercase\-literal\-suffix** :warning: integer literal has suffix `` u ``, which is not uppercase ```suggestion const uint32_t casts = spellCost ? std::min( 10U, currentSpellPoints / spellCost ) : 0; ``` const int id = spell.GetID(); const uint32_t spellCost = spell.SpellPoint(); + const uint32_t casts = spellCost ? std::min( 10U, currentSpellPoints / spellCost ) : 0; // use quadratic formula to diminish returns from subsequent spell casts, (up to x5 when spell has 10 uses) const double amountModifier = ( casts == 1 ) ? 1 : casts - ( 0.05 * casts * casts );
codereview_cpp_data_7446
wl_list_remove(&roots_xdg_surface->surface_commit.link); wl_list_remove(&roots_xdg_surface->destroy.link); wl_list_remove(&roots_xdg_surface->new_popup.link); wl_list_remove(&roots_xdg_surface->request_move.link); wl_list_remove(&roots_xdg_surface->request_resize.link); wl_list_remove(&roots_xdg_surface->request_maximize.link); Would it fit better if we added a `destroy()` method to the view interface which is called by `view_destroy()`? That seems to be how all the other interfaces work. wl_list_remove(&roots_xdg_surface->surface_commit.link); wl_list_remove(&roots_xdg_surface->destroy.link); wl_list_remove(&roots_xdg_surface->new_popup.link); + wl_list_remove(&roots_xdg_surface->map.link); + wl_list_remove(&roots_xdg_surface->unmap.link); wl_list_remove(&roots_xdg_surface->request_move.link); wl_list_remove(&roots_xdg_surface->request_resize.link); wl_list_remove(&roots_xdg_surface->request_maximize.link);
codereview_cpp_data_7457
, _isHiddenWindow( false ) , _isMusicPaused( false ) , _isSoundPaused( false ) - , _volume( 0 ) {} #if SDL_VERSION_ATLEAST( 2, 0, 0 ) Could we please be more explicit and define where this volume belongs to: sound or music? , _isHiddenWindow( false ) , _isMusicPaused( false ) , _isSoundPaused( false ) + , _musicVolume( 0 ) {} #if SDL_VERSION_ATLEAST( 2, 0, 0 )
codereview_cpp_data_7468
// DLM: not sure how to do this right, think I only need this for static builds #include <QtPlugin> -Q_IMPORT_PLUGIN(qwindows) #include "qwinwidget.h" my understanding was that the only difference between static plugin vs dynamic in qt 5.6 was that with static you needed to link the .lib plugin like you are doing here for qwindows.lib. I don't think there are more or less requirements for what you do in the code. qsqlite seems to work without special attention. // DLM: not sure how to do this right, think I only need this for static builds #include <QtPlugin> +Q_IMPORT_PLUGIN(AccessibleFactory) +Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin) #include "qwinwidget.h"
codereview_cpp_data_7476
* Check wiped instead of s2n_stuffer_data_available to differentiate between the initial call * to s2n_handshake_write_io and a repeated call after an EWOULDBLOCK. */ - int handshake_io_wiped = s2n_stuffer_is_wiped(&conn->handshake.io); if (handshake_io_wiped && record_type == TLS_HANDSHAKE) { GUARD(s2n_handshake_write_header(&conn->handshake.io, ACTIVE_STATE(conn).message_type)); } Can this be `const`? * Check wiped instead of s2n_stuffer_data_available to differentiate between the initial call * to s2n_handshake_write_io and a repeated call after an EWOULDBLOCK. */ + const bool handshake_io_wiped = s2n_stuffer_is_wiped(&conn->handshake.io); if (handshake_io_wiped && record_type == TLS_HANDSHAKE) { GUARD(s2n_handshake_write_header(&conn->handshake.io, ACTIVE_STATE(conn).message_type)); }
codereview_cpp_data_7479
double activation = getActivation(s); //Tolerance, in Newtons, of the desired equilibrium - double tol = 1e-8*getMaxIsometricForce(); //Should this be user settable? - if (tol < SimTK::SignificantReal * 10) { - tol = SimTK::SignificantReal * 10; - } int maxIter = 20; //Should this be user settable? std::pair<StatusFromInitMuscleState, ValuesFromInitMuscleState> result; L317-320 should be `const double tol = std::max( SimTK::SignificantReal * 10, getMaxIsometricForce() * 1e-8 );`. double activation = getActivation(s); //Tolerance, in Newtons, of the desired equilibrium + const double tol = max( 1e-8*getMaxIsometricForce(), + SimTK::SignificantReal * 10 ); + int maxIter = 20; //Should this be user settable? std::pair<StatusFromInitMuscleState, ValuesFromInitMuscleState> result;
codereview_cpp_data_7483
{ return false; } - return state.DoS(100, error("ConnectBlockDTOR(): %s inputs missing/spent in tx %d %s", block.GetHash().ToString(), i, tx.GetHash().ToString()), REJECT_INVALID, "bad-txns-inputs-missingorspent"); } As you are at it, maybe add the word `block` here as well, so that it reads `block %s inputs missing/spent ...` ? Minor nit though. { return false; } + return state.DoS(100, error("ConnectBlockDTOR(): block %s inputs missing/spent in tx %d %s", block.GetHash().ToString(), i, tx.GetHash().ToString()), REJECT_INVALID, "bad-txns-inputs-missingorspent"); }
codereview_cpp_data_7490
} } -void OpenSim::updateConnecteesBySearch(Model& model) { for (auto& comp : model.updComponentList()) { const auto socketNames = comp.getSocketNames(); for (int i = 0; i < socketNames.size(); ++i) { else, report that this Socket needs updating but couldn't be done automatically? } } +void OpenSim::updateSocketConnecteesBySearch(Model& model) { + int numSocketsUpdated = 0; for (auto& comp : model.updComponentList()) { const auto socketNames = comp.getSocketNames(); for (int i = 0; i < socketNames.size(); ++i) {
codereview_cpp_data_7497
QString allowedPunctuation = settingsCache->value("users/allowedpunctuation", "_").toString(); QStringList disallowedWords = settingsCache->value("users/disallowedwords", "").toString().split(",", QString::SkipEmptyParts); disallowedWords.removeDuplicates(); - QStringList disallowedRegExp = settingsCache->value("users/disallowedregexp", "").toString().split(",", QString::SkipEmptyParts); - disallowedRegExp.removeDuplicates(); - error = QString("%1|%2|%3|%4|%5|%6|%7|%8|%9").arg(minNameLength).arg(maxNameLength).arg(allowLowercase).arg(allowUppercase).arg(allowNumerics).arg(allowPunctuationPrefix).arg(allowedPunctuation).arg(disallowedWords.join(",")).arg(disallowedRegExp.join(",")); if (user.length() < minNameLength || user.length() > maxNameLength) return false; If we were going to keep the regex support in, we should store compiled regex objects rather than strings. You'd also want to log invalid-regex failures. It's a moot point though since we should take it out QString allowedPunctuation = settingsCache->value("users/allowedpunctuation", "_").toString(); QStringList disallowedWords = settingsCache->value("users/disallowedwords", "").toString().split(",", QString::SkipEmptyParts); disallowedWords.removeDuplicates(); + error = QString("%1|%2|%3|%4|%5|%6|%7|%8|%9").arg(minNameLength).arg(maxNameLength).arg(allowLowercase).arg(allowUppercase).arg(allowNumerics).arg(allowPunctuationPrefix).arg(allowedPunctuation).arg(settingsCache->value("users/disallowedwords", "").toString()).arg(settingsCache->value("users/disallowedregexp", "").toString()); if (user.length() < minNameLength || user.length() > maxNameLength) return false;
codereview_cpp_data_7500
* (0-1 property) * * ### Algorithm - * ............ * * @author [Anmol](https://github.com/Anmol3299) * @author [Pardeep](https://github.com/Pardeep009) this stub lines 16 and 17 can be removed * (0-1 property) * * ### Algorithm + * The idea is to consider all subsets of items and calculate the total weight + * and value of all subsets. Consider the only subsets whose total weight is + * smaller than W. From all such subsets, pick the maximum value subset. * * @author [Anmol](https://github.com/Anmol3299) * @author [Pardeep](https://github.com/Pardeep009)
codereview_cpp_data_7501
merge_settings_impl(caf::get<caf::settings>(value), dst[key].as_dictionary(), policy, depth + 1); } else { - if constexpr (std::is_same_v<Policy, policy::deep_tag>) { if (caf::holds_alternative<caf::config_value::list>(value)) { const auto& src_list = caf::get<caf::config_value::list>(value); if (caf::holds_alternative<caf::config_value::list>(dst[key])) { Not sure this will work correctly: ```suggestion if constexpr (std::is_same_v<Policy, policy::deep_tag>) { if (caf::holds_alternative<caf::config_value::list>(value) && caf::holds_alternative<caf::config_value::list>(dst[key])) { const auto& src_list = caf::get<caf::config_value::list>(value); auto& dst_list = dst[key].as_list(); dst_list.insert(dst_list.end(), src_list.begin(), src_list.end()); } else { dst.insert_or_assign(key, value); } ``` merge_settings_impl(caf::get<caf::settings>(value), dst[key].as_dictionary(), policy, depth + 1); } else { + if constexpr (std::is_same_v<Policy, policy::merge_lists_tag>) { if (caf::holds_alternative<caf::config_value::list>(value)) { const auto& src_list = caf::get<caf::config_value::list>(value); if (caf::holds_alternative<caf::config_value::list>(dst[key])) {
codereview_cpp_data_7505
#include <assert.h> void s2n_is_base64_char_harness() { - char c; - int result = s2n_is_base64_char(c); - assert(result == 0 || result == 1); } What exactly are we proving here? I read this as: > `s2n_is_base64_char` takes any `char` value and returns `true` or `false`. But, that's already proven to be true by the type system. (speaking of, can you change the return value to `bool`, rather than `int`?) #include <assert.h> void s2n_is_base64_char_harness() { + unsigned char c; + bool is_base_64 = ('A' <= c && c <= 'Z') || + ('a' <= c && c <= 'z') || + ('0' <= c && c <= '9') || + c == '+' || c == '/' || c == '='; + assert(is_base_64 == s2n_is_base64_char(c)); }
codereview_cpp_data_7506
const protocol::RemoveSignatory &pb_remove_signatory) { model::RemoveSignatory remove_signatory; remove_signatory.account_id = pb_remove_signatory.account_id(); - iroha::hexstringToArray<pubkey_t::size()>( - pb_remove_signatory.public_key()) - | [&remove_signatory](const auto &blob) { - remove_signatory.pubkey = blob; - }; return remove_signatory; } // set account quorum I would suggest creating a local static function like this: ```c++ static void trySetHexKey(auto &dest, const std::string &src) { auto opt_blob = iroha::hexstringToArray<pubkey_t::size()>(src); if (opt_blob) { dest = *opt_blob; } } ``` It would remove the need for many similar lambdas and make the code more clear, like that (instead of 5 lines): ```suggestion trySetHexKey(add_signatory.pubkey, pb_add_signatory.public_key()); ``` const protocol::RemoveSignatory &pb_remove_signatory) { model::RemoveSignatory remove_signatory; remove_signatory.account_id = pb_remove_signatory.account_id(); + trySetHexKey(remove_signatory.pubkey, pb_remove_signatory.public_key()); return remove_signatory; } // set account quorum
codereview_cpp_data_7508
entity_list.RemoveFromAutoXTargets(this); - if (killer->GetUltimateOwner()->IsClient()) { killer->GetUltimateOwner()->CastToClient()->ProcessXTargetAutoHaters(); } uint16 emoteid = this->GetEmoteID(); We should check for valid pointer before accessing it eg ```cpp killer->GetUltimateOwner() && killer->GetUltimateOwner()->IsClient() ``` entity_list.RemoveFromAutoXTargets(this); + if (killer->GetUltimateOwner() && killer->GetUltimateOwner()->IsClient()) { killer->GetUltimateOwner()->CastToClient()->ProcessXTargetAutoHaters(); } uint16 emoteid = this->GetEmoteID();
codereview_cpp_data_7522
return S2N_SUCCESS; } -int print_connection_data(struct s2n_connection *conn, bool session_resumed) { int client_hello_version; int client_protocol_version; I see the duplicate call to `s2n_connection_is_session_resumed` passing in `session_resumed` avoids. But from an API design I slightly prefer just passing in the `s2n_connection` and letting print pull out whatever it needs to print. return S2N_SUCCESS; } +int print_connection_data(struct s2n_connection *conn) { int client_hello_version; int client_protocol_version;
codereview_cpp_data_7524
/* Load the static pose marker file, and average all the * frames in the user-specified time range. */ - MarkerData* staticPose = new MarkerData(aPathToSubject + _markerFileName); if (_timeRange.getSize()<2) throw Exception("MarkerPlacer::processModel, time_range is unspecified."); IMO It's slightly better to use a unique_ptr and then release it when you pass this pointer onto the `MarkersReference`. The reason is that the memory is still leaked if an exception is thrown before you construct the `MarkersReference` (for example, 2 lines down, there's an exception). ``` cpp std::unique_ptr<MarkerData> staticPose(new MarkerData(...)); ... MarkersReference markersReference(staticPose.release(), &markerWeightSet); ``` /* Load the static pose marker file, and average all the * frames in the user-specified time range. */ + std::unique_ptr<MarkerData> staticPose( + new MarkerData(aPathToSubject + _markerFileName) ); if (_timeRange.getSize()<2) throw Exception("MarkerPlacer::processModel, time_range is unspecified.");
codereview_cpp_data_7539
EXPECT_SUCCESS(s2n_stuffer_wipe(&conn->in)); EXPECT_SUCCESS(s2n_stuffer_reread(&conn->out)); EXPECT_SUCCESS(s2n_stuffer_copy(&conn->out, &conn->in, s2n_stuffer_data_available(&conn->out))); - EXPECT_FAILURE(conn->secure.cipher_suite->record_alg->record_parse(conn)); /* Restore the original sequence number */ memcpy(conn->server->client_sequence_number, original_seq_num, 8); There's a lot of these identical changes. Would it make sense to just make s2n_record_parse() a macro that expands to conn->secure.cipher_suite->record_alg->record_parse EXPECT_SUCCESS(s2n_stuffer_wipe(&conn->in)); EXPECT_SUCCESS(s2n_stuffer_reread(&conn->out)); EXPECT_SUCCESS(s2n_stuffer_copy(&conn->out, &conn->in, s2n_stuffer_data_available(&conn->out))); + EXPECT_FAILURE(s2n_record_parse(conn)); /* Restore the original sequence number */ memcpy(conn->server->client_sequence_number, original_seq_num, 8);
codereview_cpp_data_7541
pD = &sgLevels[currlevel].item[i]; if (pD->bCmd == 0xFF) { pD->bCmd = CMD_STAND; - sgbDeltaChanged = 1; pD->x = item[ii]._ix; pD->y = item[ii]._iy; pD->wIndx = item[ii].IDidx; Is `sgbDeltaChanged` a boolean? pD = &sgLevels[currlevel].item[i]; if (pD->bCmd == 0xFF) { pD->bCmd = CMD_STAND; + sgbDeltaChanged = TRUE; pD->x = item[ii]._ix; pD->y = item[ii]._iy; pD->wIndx = item[ii].IDidx;
codereview_cpp_data_7545
} while (eof == 0 && done == 0) { int blank = strspn(line," \t\n\r"); - if ((blank == strlen(line)) || (line[blank] == '#')) { if (fgets(line,MAXLINE,fp) == NULL) eof = 1; } else done = 1; } please don't undo changes in the LAMMPS code, that have no relevance to your change. } while (eof == 0 && done == 0) { int blank = strspn(line," \t\n\r"); + if ((blank == (int)strlen(line)) || (line[blank] == '#')) { if (fgets(line,MAXLINE,fp) == NULL) eof = 1; } else done = 1; }
codereview_cpp_data_7548
for (auto& c : *concepts) { auto concept_ = caf::get_if<std::string>(&c); if (!concept_) - return make_error(ec::convert_error, "concept is not a string:", c); dest.concepts.push_back(*concept_); } } else { - return make_error(ec::convert_error, - "concepts is not a list:", cs->second); } } auto desc = c->find("description"); This warning message does not follow our usual log message style, e.g., "<noun> encountered conflicting descriptions...". Also, there's still a space between `*name` and `:`. for (auto& c : *concepts) { auto concept_ = caf::get_if<std::string>(&c); if (!concept_) + return make_error(ec::convert_error, "concept in", *name, + "is not a string:", c); dest.concepts.push_back(*concept_); } } else { + return make_error(ec::convert_error, "concepts in", *name, + "is not a list:", cs->second); } } auto desc = c->find("description");
codereview_cpp_data_7555
ReasonsGroupType reason; reason.first = "Transaction list"; for (const auto &tx : transactions) { - auto answer = ParentType::transaction_validator_.validate(tx); if (answer.hasErrors()) { auto message = (boost::format("Tx %s : %s") % tx.hash().hex() % answer.reason()) The same with library include at the top of the file ReasonsGroupType reason; reason.first = "Transaction list"; for (const auto &tx : transactions) { + auto answer = + UnsignedTransactionsCollectionValidator::transaction_validator_ + .validate(tx); if (answer.hasErrors()) { auto message = (boost::format("Tx %s : %s") % tx.hash().hex() % answer.reason())
codereview_cpp_data_7562
local_parent_kind = parent_kind; } - /* Scan for parametric type constructor */ - skipWhitespace(lexer, false); - if (lexer->cur_c == '{') - { - scanCurlyBlock(lexer); - skipWhitespace(lexer, false); - } - name = vStringNewCopy(lexer->token_str); arg_list = vStringNew(); line = lexer->line; I'm sorry that I accepted this style of change. I should not. This is nothing to do with the original issue you wanted to fix. Could you make a separate commit for the change of style? In that case, I would like to use "Julia,cosmetic" or "Julia,style" as the prefix for the header of the commit log. INSTEAD, I would like to invite you to to this project. So you can control your parser especially when we get a pull request for your parser. We can avoid the mistake I took. local_parent_kind = parent_kind; } name = vStringNewCopy(lexer->token_str); arg_list = vStringNew(); line = lexer->line;
codereview_cpp_data_7568
proposal.transactions() | boost::adaptors::transformed([](const auto &polymorphic_tx) { return static_cast<const shared_model::proto::Transaction &>( - *polymorphic_tx.operator->()); }); auto block = std::make_shared<shared_model::proto::Block>( shared_model::proto::UnsignedBlockBuilder() Better to add operator * for poly wrapper proposal.transactions() | boost::adaptors::transformed([](const auto &polymorphic_tx) { return static_cast<const shared_model::proto::Transaction &>( + *polymorphic_tx); }); auto block = std::make_shared<shared_model::proto::Block>( shared_model::proto::UnsignedBlockBuilder()
codereview_cpp_data_7570
rxcpp::observable<Commit> SynchronizerImpl::on_commit_chain() { return notifier_.get_observable(); } - - void SynchronizerImpl::shutdown() { - subscription_.unsubscribe(); - } } // namespace synchronizer } // namespace iroha Same as above, it seems that it can be moved to destructor. rxcpp::observable<Commit> SynchronizerImpl::on_commit_chain() { return notifier_.get_observable(); } } // namespace synchronizer } // namespace iroha
codereview_cpp_data_7574
/* json parser */ fuzz_config = flb_config_init(); - fuzz_parser = flb_parser_create("fuzzer", "json", NULL, NULL, NULL, NULL, MK_FALSE, NULL, - NULL, NULL, MK_FALSE, NULL, 0, NULL, fuzz_config); flb_parser_do(fuzz_parser, (char*)data, size, &out_buf, &out_size, &out_time); Probably this line is an edit error. This function call does not match the parameter definition of the callee and causes a compilation failure. /* json parser */ fuzz_config = flb_config_init(); + fuzz_parser = flb_parser_create("fuzzer", "json", NULL, NULL, NULL, NULL, MK_FALSE, NULL, 0, NULL, fuzz_config); flb_parser_do(fuzz_parser, (char*)data, size, &out_buf, &out_size, &out_time);
codereview_cpp_data_7581
//check that the cleanup functions are called on each loop exit for (int i = 0; i < 10; ++i) { - DEFER_CLEANUP(struct foo x = {0}, foo_free); S2N_UNUSED(x); EXPECT_EQUAL(foo_cleanup_calls, expected_cleanup_count); expected_cleanup_count++; What was the purpose of this change? //check that the cleanup functions are called on each loop exit for (int i = 0; i < 10; ++i) { + DEFER_CLEANUP(struct foo x = {i}, foo_free); S2N_UNUSED(x); EXPECT_EQUAL(foo_cleanup_calls, expected_cleanup_count); expected_cleanup_count++;
codereview_cpp_data_7594
// go through all the IDs in the in data set. foreach (QString id, _expectedIdToEid.keys()) { QSet<QString> actualMatchSet = *_actualMatchGroups[id]; QSet<QString> expectedMatchSet = *_expectedMatchGroups[id]; QSet<QString> actualReviewSet = *_actualReviews.getCluster(id); Will this visitor ever need to be called in other places in the future in the Multiary Conflation routines? If so I suggest extracting it out to a separate set of files. If not then this is as good a place as any. (Same with the other one below) // go through all the IDs in the in data set. foreach (QString id, _expectedIdToEid.keys()) { +// LOG_VAR(id); + assert(_actualMatchGroups.contains(id)); + assert(_expectedMatchGroups.contains(id)); + QSet<QString> actualMatchSet = *_actualMatchGroups[id]; QSet<QString> expectedMatchSet = *_expectedMatchGroups[id]; QSet<QString> actualReviewSet = *_actualReviews.getCluster(id);
codereview_cpp_data_7597
case TX_MULTISIG: scriptSigRet << OP_0; // workaround CHECKMULTISIG bug return (SignN(vSolutions, creator, scriptPubKey, scriptSigRet)); - case TX_LABELPUBLIC: // These are OP_RETURN unspendable outputs so they should never be an input that needs signing - return false; } return false; I would just move this up to line 80...then there's no need for another "return false" case TX_MULTISIG: scriptSigRet << OP_0; // workaround CHECKMULTISIG bug return (SignN(vSolutions, creator, scriptPubKey, scriptSigRet)); } return false;
codereview_cpp_data_7602
Client().GetClientUI().GetPlayerListWnd()->Refresh(); context<HumanClientFSM>().process_event(DoneLoading()); } why does this function generate the `DoneLoading` event and not the caller? It and `ProcessData` and `ProcessUI` don't seem to be used elsewhere. Client().GetClientUI().GetPlayerListWnd()->Refresh(); + // HumanClientFSM isn't being processed right now so we can't use transit<PlayingTurn>() and need an event for the FSM to react + // ideally HumanClientFSM would have it's own processing thread, but right now it is processed by the GUI thread in response to network messages + // post_event(DoneLoading()) would delay the event until the next network message is processed, so we use process_event(DoneLoading()) to get immediate results context<HumanClientFSM>().process_event(DoneLoading()); }
codereview_cpp_data_7610
GossipPropagationStrategy::GossipPropagationStrategy( PeerProviderFactory peer_factory, std::chrono::milliseconds period, uint32_t amount) : peer_factory(peer_factory), non_visited({}), - emit_worker(rxcpp::observe_on_new_thread()), emitent(rxcpp::observable<>::interval(steady_clock::now(), period) .map([this, amount](int) { PropagationData vec; Now it looks like a dependency of gossip propagation strategy. I think better to explicitly initialize it. GossipPropagationStrategy::GossipPropagationStrategy( PeerProviderFactory peer_factory, + rxcpp::observe_on_one_worker emit_worker, std::chrono::milliseconds period, uint32_t amount) : peer_factory(peer_factory), non_visited({}), + emit_worker(emit_worker), emitent(rxcpp::observable<>::interval(steady_clock::now(), period) .map([this, amount](int) { PropagationData vec;
codereview_cpp_data_7620
static int __Pyx_TraceSetupAndCall(PyCodeObject** code, PyFrameObject** frame, PyThreadState* tstate, const char *funcname, const char *srcfile, int firstlineno); /*proto*/ #if !CYTHON_USE_MODULE_STATE -static PyObject *__pyx_dummy_tracer = NULL; #endif static PyObject *__Pyx_dummy_tracer(PyObject *self, PyObject *args); ```suggestion static PyObject *$dummy_tracer = NULL; ``` The "subsitute: naming" option (which I believe is above) lets you get the name out of the `Naming` module rather than writing it explicitly in the utility code. There's a few more places in this PR with `__pyx_dummy_trace` which could be replaced with `$dummy_tracer` static int __Pyx_TraceSetupAndCall(PyCodeObject** code, PyFrameObject** frame, PyThreadState* tstate, const char *funcname, const char *srcfile, int firstlineno); /*proto*/ #if !CYTHON_USE_MODULE_STATE +static PyObject *$dummy_tracer_cname = NULL; #endif static PyObject *__Pyx_dummy_tracer(PyObject *self, PyObject *args);
codereview_cpp_data_7622
bp::with_custodian_and_ward<1, 2, bp::with_custodian_and_ward<1, 3> >()) .def("save", &Net_Save) .def("save_hdf5", &Net_SaveHDF5) - .def("load_hdf5", &Net_LoadHDF5) - .def("before_forward", &Net_before_forward) - .def("after_forward", &Net_after_forward) - .def("before_backward", &Net_before_backward) - .def("after_backward", &Net_after_backward) - .def("after_backward", &Net_add_nccl); BP_REGISTER_SHARED_PTR_TO_PYTHON(Net<Dtype>); bp::class_<Blob<Dtype>, shared_ptr<Blob<Dtype> >, boost::noncopyable>( Many of the members exposed in these changes don't seem specific to this PR. Could they be pulled out on their own? bp::with_custodian_and_ward<1, 2, bp::with_custodian_and_ward<1, 3> >()) .def("save", &Net_Save) .def("save_hdf5", &Net_SaveHDF5) + .def("load_hdf5", &Net_LoadHDF5); BP_REGISTER_SHARED_PTR_TO_PYTHON(Net<Dtype>); bp::class_<Blob<Dtype>, shared_ptr<Blob<Dtype> >, boost::noncopyable>(
codereview_cpp_data_7627
return false; } -bool PrimarySkillsBar::ActionBarCursor( const fheroes2::Point &, int & skill, const fheroes2::Rect & ) { if ( Skill::Primary::UNKNOWN != skill ) { msg = _( "View %{skill} Info" ); :warning: **readability\-named\-parameter** :warning: all parameters should be named in a function ```suggestion bool PrimarySkillsBar::ActionBarCursor( const fheroes2::Point & /*unused*/, int & skill, const fheroes2::Rect & /*unused*/) ``` return false; } +bool PrimarySkillsBar::ActionBarCursor( const fheroes2::Point & /*unused*/, int & skill, const fheroes2::Rect & /*unused*/) { if ( Skill::Primary::UNKNOWN != skill ) { msg = _( "View %{skill} Info" );
codereview_cpp_data_7629
highlightCells.emplace( attackerCell ); if ( _currentUnit->GetTailIndex() != -1 ) { - if ( _currentUnit->isReflect() ) { - highlightCells.emplace( Board::GetCell( attackerCell->GetIndex(), RIGHT ) ); - } - else { - highlightCells.emplace( Board::GetCell( attackerCell->GetIndex(), LEFT ) ); - } } } else { I'd add an assertion here as well - just in case. Something like this: ``` const Cell * attackerTailCell = Board::GetCell( attackerCell->GetIndex(), _currentUnit->isReflect() ? RIGHT : LEFT ); assert( attackerTailCell != nullptr ); highlightCells.emplace( attackerTailCell ); ``` highlightCells.emplace( attackerCell ); if ( _currentUnit->GetTailIndex() != -1 ) { + const int tailDirection = _currentUnit->isReflect() ? RIGHT : LEFT; + const Cell * tailAttackerCell = Board::GetCell( attackerCell->GetIndex(), tailDirection ); + assert( tailAttackerCell != nullptr ); + + highlightCells.emplace( tailAttackerCell ); } } else {
codereview_cpp_data_7634
#include <iostream> -#include <string.h> using namespace std; int max(int a, int b) { return (a > b) ? a : b; } ```suggestion #include <cstring> ``` #include <iostream> +#include <cstring> using namespace std; int max(int a, int b) { return (a > b) ? a : b; }
codereview_cpp_data_7637
void AbstractCardItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { if ((event->modifiers() & Qt::ControlModifier)) { - setSelected(isSelected() ? false : true); } else if (!isSelected()) { scene()->clearSelection(); Why not `!isSelected` instead of the ternary? void AbstractCardItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { if ((event->modifiers() & Qt::ControlModifier)) { + setSelected(!isSelected()); } else if (!isSelected()) { scene()->clearSelection();
codereview_cpp_data_7638
cvt_tab = chunkalloc(sizeof(struct ttf_table)); cvt_tab->tag = CHR('c','v','t',' '); cvt_tab->maxlen = 200; - cvt_tab->data = malloc(100*sizeof(uint8)); cvt_tab->next = sf->ttf_tables; sf->ttf_tables = cvt_tab; } This isn't safe. `ttf_table.data` is probably a generic data pointer used in different ways. Regardless, a typical short is twice the size of a uint8. To make this change you would need to confirm that only half the memory is needed. cvt_tab = chunkalloc(sizeof(struct ttf_table)); cvt_tab->tag = CHR('c','v','t',' '); cvt_tab->maxlen = 200; + cvt_tab->data = malloc(100*sizeof(short)); cvt_tab->next = sf->ttf_tables; sf->ttf_tables = cvt_tab; }
codereview_cpp_data_7639
break; case YOML_TYPE_MAPPING: { yoml_t **capacity_node, **lifetime_node; - if (h2o_configurator_parse_mapping(cmd, node, "capacity,lifetime", NULL, &capacity_node, &lifetime_node) != 0) return -1; if (h2o_configurator_scanf(cmd, *capacity_node, "%zu", &capacity) != 0) return -1; Actually both of `capacity` and `lifetime` must be scalars? break; case YOML_TYPE_MAPPING: { yoml_t **capacity_node, **lifetime_node; + if (h2o_configurator_parse_mapping(cmd, node, "capacity:*,lifetime:*", NULL, &capacity_node, &lifetime_node) != 0) return -1; if (h2o_configurator_scanf(cmd, *capacity_node, "%zu", &capacity) != 0) return -1;
codereview_cpp_data_7645
FIXTURE_SCOPE(command_tests, fixture) -TEST(option map handling) { auto num = 42; opts.add("true", true); opts.add("false", false); "handling" is a very generic term that doesn't explain what's getting tested here. FIXTURE_SCOPE(command_tests, fixture) +TEST(retrieving data) { auto num = 42; opts.add("true", true); opts.add("false", false);
codereview_cpp_data_7652
.num_channels = 5, .has_oversampling = true, }, - [ID_AD7606B] = { - .channels = ad7606_channels, - .num_channels = 9, - .has_oversampling = true, - .sw_mode_config = ad7606B_sw_mode_config, - }, }; static int ad7606_request_gpios(struct ad7606_state *st) i think `has_registers` could be removed entirely right now; checking if `sw_mode_config` is non-NULL looks sufficient; unless there are future use-cases that I am not foreseeing .num_channels = 5, .has_oversampling = true, }, }; static int ad7606_request_gpios(struct ad7606_state *st)
codereview_cpp_data_7653
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************************************************************/ #include "QJson.hpp" #include "Assert.hpp" @jmarrec we will eventually replace QVariant with std::variant (on update_depends because requires c++17). What happens to this file then? Should it just stay in Json.hpp? * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************************************************************/ +// TODO: QT-Separation-Move #include "QJson.hpp" #include "Assert.hpp"
codereview_cpp_data_7656
std::stringstream error_message; error_message << "Requested GPU with id " << id << " but only " << gpu_devices.size() << " GPU(s) available!\n"; - Kokkos::abort(error_message.str().c_str()); } m_device = gpu_devices[id]; } Throw an exception instead std::stringstream error_message; error_message << "Requested GPU with id " << id << " but only " << gpu_devices.size() << " GPU(s) available!\n"; + Kokkos::Impl::throw_runtime_exception(error_message.str()); } m_device = gpu_devices[id]; }
codereview_cpp_data_7670
size_t j = 0; UA_ByteString buf = UA_BYTESTRING_NULL; for(size_t i = 0; i < layer->mappingsSize && j < (size_t)resultsize; i++) { - if(UA_fd_isset(layer->mappings[i].sockfd, &errset)) {} - else if(!UA_fd_isset(layer->mappings[i].sockfd, &fdset)) { continue; } UA_StatusCode retval = socket_recv(layer->mappings[i].connection, &buf, 0); @NetoLe Can you explain line 430? If the errset is set for the socket, we want to continue (and close the socket)? I would fold line 430 and line 431 into a single if. The empty brackets can be overseen. size_t j = 0; UA_ByteString buf = UA_BYTESTRING_NULL; for(size_t i = 0; i < layer->mappingsSize && j < (size_t)resultsize; i++) { + if(!UA_fd_isset(layer->mappings[i].sockfd, &errset) && !UA_fd_isset(layer->mappings[i].sockfd, &fdset)) { continue; } UA_StatusCode retval = socket_recv(layer->mappings[i].connection, &buf, 0);
codereview_cpp_data_7675
} else { - if (KDB_DB_SPEC[0] == '~') { const char * oldPath = p->path; char * path = elektraMalloc (filenameSize); - strcpy (path, KDB_DB_SPEC); strcat (path, "/"); strcat (path, p->path); p->path = path; Did you already consider discussion at #691? ~ would not be on the first position. } else { + if (KDB_DB_SPEC_REAL[0] == '~') { const char * oldPath = p->path; char * path = elektraMalloc (filenameSize); + strcpy (path, KDB_DB_SPEC_REAL); strcat (path, "/"); strcat (path, p->path); p->path = path;
codereview_cpp_data_7678
// Parametrized XML const char* xml_p = "\ - <reader>\ <userId>%d</userId>\ <entityID>%d</entityID>\ <livelinessQos kind=\"%s\" leaseDuration_ms=\"%s\"/>\ - </reader>\ "; char xml[500]; ```suggestion <writer>\ ``` Fix this error along `loadXMLWriterEndpoint` function // Parametrized XML const char* xml_p = "\ + <writer>\ <userId>%d</userId>\ <entityID>%d</entityID>\ <livelinessQos kind=\"%s\" leaseDuration_ms=\"%s\"/>\ + </writer>\ "; char xml[500];
codereview_cpp_data_7690
/* The socket has opened. Signal it to the application. The callback can * switch out the context. So put it into a temp variable. */ - void *fdctx_address = NULL; - UA_EventLoop_getFDContext(cm->eventSource.eventLoop, fd, &fdctx_address); - cm->connectionCallback(cm, (uintptr_t)fd, (void **) fdctx_address, UA_STATUSCODE_GOOD, UA_BYTESTRING_NULL); void *ctx = cm->initialConnectionContext; I don't get the change. This is about initializing the context of the new connection. Why do you want to forward the context of the parent fd? The pointer to the cm and the initialContext should be enough. At any rate, you want to forward a "true" double-pointer. So that `connectionCallback` can switch out the pointer to something else if it wants to. /* The socket has opened. Signal it to the application. The callback can * switch out the context. So put it into a temp variable. */ + cm->connectionCallback(cm, (uintptr_t)fd, fdcontext, UA_STATUSCODE_GOOD, UA_BYTESTRING_NULL); void *ctx = cm->initialConnectionContext;
codereview_cpp_data_7703
* @author [TsungHan Ho](https://github.com/dalaoqi) */ #include <iostream> #include <vector> Test implementations use `assert` (requires the `cassert` library) to verify the code works as expected. * @author [TsungHan Ho](https://github.com/dalaoqi) */ +#include <algorithm> +#include <cassert> #include <iostream> #include <vector>
codereview_cpp_data_7707
// text recruit monster std::string str = _( "Recruit %{name}" ); StringReplace( str, "%{name}", monster.GetMultiName() ); - TextBox recruitMonsterText( str, Font::YELLOW_BIG, BOXAREA_WIDTH ); - dst_pt.x = pos.x + ( pos.width - recruitMonsterText.w() ) / 2; dst_pt.y = pos.y + 25; - recruitMonsterText.Blit( dst_pt.x, dst_pt.y ); // sprite monster const fheroes2::Sprite & smon = fheroes2::AGG::GetICN( monster.ICNMonh(), 0 ); Let's please put all changes which are not present in the original game into separate pull request as we did not discussed them properly. // text recruit monster std::string str = _( "Recruit %{name}" ); StringReplace( str, "%{name}", monster.GetMultiName() ); + text.Set( str, Font::BIG ); + dst_pt.x = pos.x + ( pos.width - text.w() ) / 2; dst_pt.y = pos.y + 25; + text.Blit( dst_pt.x, dst_pt.y ); // sprite monster const fheroes2::Sprite & smon = fheroes2::AGG::GetICN( monster.ICNMonh(), 0 );
codereview_cpp_data_7717
if (mapMultiArgs.count("-rpcauth") > 0) { // Search for multi-user login/pass "rpcauth" from config - for (std::string strRPCAuth : mapMultiArgs["-rpcauth"]) { std::vector<std::string> vFields; boost::split(vFields, strRPCAuth, boost::is_any_of(":$")); minor, but couldn't we do - for (std::string strPRCAuth... +for (std::string &strRPCAuth... if (mapMultiArgs.count("-rpcauth") > 0) { // Search for multi-user login/pass "rpcauth" from config + for (std::string &strRPCAuth : mapMultiArgs["-rpcauth"]) { std::vector<std::string> vFields; boost::split(vFields, strRPCAuth, boost::is_any_of(":$"));
codereview_cpp_data_7733
int backupType = static_cast<int>(request->getTotalBytes()); if (backupType < MegaApi::BACKUP_TYPE_CAMERA_UPLOADS || backupType > MegaApi::BACKUP_TYPE_MEDIA_UPLOADS) { - e = API_EARGS; - break; } BackupType bType = static_cast<BackupType>(backupType); backupType can be MegaApi::BACKUP_TYPE_INVALID in case of update request. This condition will be satisfied and will prematurely break with API_EARGS without giving a chance to update. int backupType = static_cast<int>(request->getTotalBytes()); if (backupType < MegaApi::BACKUP_TYPE_CAMERA_UPLOADS || backupType > MegaApi::BACKUP_TYPE_MEDIA_UPLOADS) { + if (isNew || (!isNew && backupType != MegaApi::BACKUP_TYPE_INVALID)) + { + e = API_EARGS; + break; + } } BackupType bType = static_cast<BackupType>(backupType);
codereview_cpp_data_7741
// Currently only works on DataTypes. // Need to decide how to handle uint8_t matrices. auto& mat = data.template get<DataType>(); // Don't use El::Scale because it spawns OpenMP threads. DataType* __restrict__ buf = mat.Buffer(); const El::Int size = mat.Height() * mat.Width(); Couldn't this be done with a matrix scale operation rather than per entry? // Currently only works on DataTypes. // Need to decide how to handle uint8_t matrices. auto& mat = data.template get<DataType>(); + if (mat.Height() != mat.LDim()) { + LBANN_ERROR("Scaling non-contiguous matrix not supported."); + } // Don't use El::Scale because it spawns OpenMP threads. DataType* __restrict__ buf = mat.Buffer(); const El::Int size = mat.Height() * mat.Width();
codereview_cpp_data_7750
} } - - -// Get/Set for Discrete Variables - -/* Get the value of a discrete variable allocated by this Component by name. - * - * param state the State from which to get the value - * param name the name of the state variable */ double Component:: getDiscreteVariable(const SimTK::State& s, const std::string& name) const { `state` is not the name of the parameter in the declaration; it is `s`. } } +// Get the value of a discrete variable allocated by this Component by name. double Component:: getDiscreteVariable(const SimTK::State& s, const std::string& name) const {
codereview_cpp_data_7777
shared_model::interface::TransactionBatch>> &value) { auto cache_presence = tx_presence_cache_->check(*value.value); if (not cache_presence) { - // TODO handle return; } auto is_replay = std::any_of( Pls, add task with todo description shared_model::interface::TransactionBatch>> &value) { auto cache_presence = tx_presence_cache_->check(*value.value); if (not cache_presence) { + // TODO andrei 30.11.18 IR-51 Handle database error + async_call_->log_->warn( + "Check tx presence database error. Batch: {}", + value.value->toString()); return; } auto is_replay = std::any_of(
codereview_cpp_data_7782
for (int i = 0; i < top_size; ++i) { (*top)[i]->Reshape(batch_size, hdf_blobs_[i]->channels(), hdf_blobs_[i]->height(), hdf_blobs_[i]->width()); - LOG(INFO) << "output '" << this->layer_param_.top(i) << "' size: " - << (*top)[i]->num() << "," << (*top)[i]->channels() - << "," << (*top)[i]->height() << "," - << (*top)[i]->width(); } } let's just remove this LOG message -- Net::Init will already print the size of all the top blobs for (int i = 0; i < top_size; ++i) { (*top)[i]->Reshape(batch_size, hdf_blobs_[i]->channels(), hdf_blobs_[i]->height(), hdf_blobs_[i]->width()); } }
codereview_cpp_data_7787
rpmostreed_transaction_force_close (RpmostreedTransaction *transaction) { RpmostreedTransactionPrivate *priv = rpmostreed_transaction_get_private (transaction); g_dbus_server_stop (priv->server); g_hash_table_foreach_remove (priv->peer_connections, foreach_close_peer, NULL); } Should we sanity check here that `active == FALSE`? (And `g_debug` or something if that's not the case?) rpmostreed_transaction_force_close (RpmostreedTransaction *transaction) { RpmostreedTransactionPrivate *priv = rpmostreed_transaction_get_private (transaction); + g_assert (!priv->executed); g_dbus_server_stop (priv->server); g_hash_table_foreach_remove (priv->peer_connections, foreach_close_peer, NULL); }
codereview_cpp_data_7804
void MegaClient::unlinkifexists(LocalNode *l, FileAccess *fa, std::string *path) { - // sdisable = true for this call. In the case where we are doing a full scan due to fs notificaions failing, and a file was renamed but retains the same shortname, we would check the presence of the wrong file. // Also shortnames are slowly being deprecated by Microsoft, so using full names is now the normal case anyway. l->getlocalpath(path, true); ```suggestion // sdisable = true for this call. In the case where we are doing a full scan due to fs notifications failing, // and a file was renamed but retains the same shortname, we would check the presence of the wrong file. // Also shortnames are slowly being deprecated by Microsoft, so using full names is now the normal case anyway. ``` void MegaClient::unlinkifexists(LocalNode *l, FileAccess *fa, std::string *path) { + // sdisable = true for this call. In the case where we are doing a full scan due to fs notifications failing, + // and a file was renamed but retains the same shortname, we would check the presence of the wrong file. // Also shortnames are slowly being deprecated by Microsoft, so using full names is now the normal case anyway. l->getlocalpath(path, true);
codereview_cpp_data_7813
exit(EXIT_FAILURE); } wl_display_init_shm(compositor.display); - wlr_compositor_init(&state.compositor, compositor.display, state.renderer); state.wl_shell = wlr_wl_shell_create(compositor.display); state.xdg_shell = wlr_xdg_shell_v6_create(compositor.display); state.data_device_manager = wlr_data_device_manager_create(compositor.display); This should probably be converted to a create exit(EXIT_FAILURE); } wl_display_init_shm(compositor.display); + state.wlr_compositor = wlr_compositor_create(compositor.display, state.renderer); state.wl_shell = wlr_wl_shell_create(compositor.display); state.xdg_shell = wlr_xdg_shell_v6_create(compositor.display); state.data_device_manager = wlr_data_device_manager_create(compositor.display);
codereview_cpp_data_7815
if ((matchCreators.size() == 0 || mergerCreators.size() == 0)) { - throw HootException( - "Empty match/merger creators only allowed when conflate.enable.old.roads is enabled."); } //fix matchers/mergers - https://github.com/ngageoint/hootenanny-ui/issues/972 I suggest you throw a different message in this exception. Or maybe if they are empty, we could grab the defaults from `ConfigOptions::getMatchCreatorsDefaultValue()` and `ConfigOptions::getMergerCreatorsDefaultValue()` since this function is about fixing defaults. if ((matchCreators.size() == 0 || mergerCreators.size() == 0)) { + LOG_WARN("Match or merger creators empty. Setting to defaults."); + matchCreators = ConfigOptions::getMatchCreatorsDefaultValue(); + mergerCreators = ConfigOptions::getMergerCreatorsDefaultValue(); } //fix matchers/mergers - https://github.com/ngageoint/hootenanny-ui/issues/972
codereview_cpp_data_7816
strcpy(xml_signature, ""); bool found_data = false; while (fgets(buf, 256, in)) { - // intentionally set higher than debug as it may produce lots of output - if (config.fuh_debug_level > MSG_DEBUG) { - log_messages.printf(MSG_DEBUG, "got:%s\n", buf); - } if (match_tag(buf, "<file_info>")) continue; if (match_tag(buf, "</file_info>")) continue; if (match_tag(buf, "<signed_xml>")) continue; Why do this instead of just set log_messages.printf(MSG_DETAIL, "got:%s\n", buf); MSG_DETAIL is lower than MSG_DEBUG Isn't the check for config.fuh_debug_level redundant since the log utility will exclude messages of a lower level? strcpy(xml_signature, ""); bool found_data = false; while (fgets(buf, 256, in)) { + log_messages.printf(MSG_DETAIL, "got:%s\n", buf); if (match_tag(buf, "<file_info>")) continue; if (match_tag(buf, "</file_info>")) continue; if (match_tag(buf, "<signed_xml>")) continue;
codereview_cpp_data_7821
#include <SofaConstraint/ConstraintStoreLambdaVisitor.h> #include <algorithm> #include <sofa/core/behavior/MultiVec.h> -#include <sofa/simulation/Node.h> #include <thread> #include <functional> Hi, thank you very much for this kind of contribution @EulalieCoevoet ! It is funny because yesterday I was thinking of reworking the Gauss Seidel code to parallelize it. Back to your PR I think the clean approach would be to enable the multi-thread plugin from SOFA which give access to a MT api where you "just" need to create a runner and give him some work. I will be happy to help you on that and test your changes. Could you describe which scene you used to test and how did you log it. #include <SofaConstraint/ConstraintStoreLambdaVisitor.h> #include <algorithm> #include <sofa/core/behavior/MultiVec.h> #include <thread> #include <functional>
codereview_cpp_data_7831
int s2n_extension_supported_iana_value_to_id(const uint16_t iana_value, s2n_extension_type_id *internal_id) { *internal_id = s2n_extension_iana_value_to_id(iana_value); S2N_ERROR_IF(*internal_id == s2n_unsupported_extension, S2N_ERR_UNRECOGNIZED_EXTENSION); return S2N_SUCCESS; Do we `notnull_check` output pointers? int s2n_extension_supported_iana_value_to_id(const uint16_t iana_value, s2n_extension_type_id *internal_id) { + notnull_check(internal_id); + *internal_id = s2n_extension_iana_value_to_id(iana_value); S2N_ERROR_IF(*internal_id == s2n_unsupported_extension, S2N_ERR_UNRECOGNIZED_EXTENSION); return S2N_SUCCESS;
codereview_cpp_data_7834
entity_list.RemoveFromAutoXTargets(this); - if (killer && killer != 0 && killer->GetUltimateOwner() && killer->GetUltimateOwner()->IsClient()) { killer->GetUltimateOwner()->CastToClient()->ProcessXTargetAutoHaters(); } uint16 emoteid = this->GetEmoteID(); Should be just `killer != nullptr` (yes I know the rest of the code is gross) entity_list.RemoveFromAutoXTargets(this); + if (killer && killer != nullptr && killer != 0 && killer->GetUltimateOwner() && killer->GetUltimateOwner()->IsClient()) { killer->GetUltimateOwner()->CastToClient()->ProcessXTargetAutoHaters(); } uint16 emoteid = this->GetEmoteID();
codereview_cpp_data_7835
if (otherPlayerId != -1) cmd.set_player_id(otherPlayerId); cmd.set_zone_name("grave"); - cmd.set_card_id(-2); sendGameCommand(cmd); } Note to self: server code in `Server_Player::cmdRevealCards()` considers the card id value of `-2` as "choose a random card from the zone" if (otherPlayerId != -1) cmd.set_player_id(otherPlayerId); cmd.set_zone_name("grave"); + cmd.set_card_id(RANDOM_CARD_FROM_ZONE); sendGameCommand(cmd); }
codereview_cpp_data_7837
if ( sw > 1 ) { fheroes2::Fill( display, dstx, dsty, sw, sw, fillColor ); } - // We can use fheroes2::SetPixel function but calling it so many times is much slower than doing the same logic here. - else if ( dstx < display.width() && dsty < display.height() && dstx >= 0 && dsty >= 0 ) { - const int32_t displayOffset = dsty * display.width() + dstx; - *( display.image() + displayOffset ) = fillColor; - *( display.transform() + displayOffset ) = 0; } } } Hi @ihhub May be just move implementation of `SetPixel()` into the header (in this case you will also need to mark it as `inline` since namespace-scoped functions IIRC do not become `inline` automatically, only class members are)? I bet the compiler will inline them in this case and there will be no need in code duplication. if ( sw > 1 ) { fheroes2::Fill( display, dstx, dsty, sw, sw, fillColor ); } + else { + fheroes2::SetPixel( display, dstx, dsty, fillColor ); } } }
codereview_cpp_data_7843
.add<std::string>("aging-query", "query for aging out obsolete data") .add<std::string>("shutdown-grace-period", "time to wait until component shutdown " - "finishes cleanly"); return std::make_unique<command>(path, "", documentation::vast, add_index_opts(std::move(ob))); } I'm fine with this as is, but I also wouldn't mind making clear that the second shutdown mode starts after this period. ```suggestion "timeout for graceful shutdowns; after this period, the server forces a shutdown"); ``` Modulo formatting. .add<std::string>("aging-query", "query for aging out obsolete data") .add<std::string>("shutdown-grace-period", "time to wait until component shutdown " + "finishes cleanly before inducing a hard kill"); return std::make_unique<command>(path, "", documentation::vast, add_index_opts(std::move(ob))); }
codereview_cpp_data_7844
<h1>Error 503 Backend is unhealthy</h1> <p>Backend is unhealthy</p> <h3>Guru Mediation:</h3> - <p>Details: cache-sea4469-SEA 1645537672 1103802737</p> <hr> <p>Varnish cache server</p> </body> Is EGL applicable to other backends? <h1>Error 503 Backend is unhealthy</h1> <p>Backend is unhealthy</p> <h3>Guru Mediation:</h3> + <p>Details: cache-sea4478-SEA 1645537672 57516320</p> <hr> <p>Varnish cache server</p> </body>
codereview_cpp_data_7850
//make sure we don't call this before onAdd(); if( !mProfile ) return; - if (txt && txt != mText) dStrncpy(mText, (UTF8*)txt, MAX_STRING_LENGTH); mText[MAX_STRING_LENGTH] = '\0'; Is that pointer comparison? Surely neither of these are `StringTableEntry`s so wouldn't a string comparison be more appropriate? And if so, it begs the question whether it's worth doing a comparison to avoid a copy :P. //make sure we don't call this before onAdd(); if( !mProfile ) return; + + // The txt pointer is sometimes the same as the mText pointer, so make sure + // we don't call strncpy with overlapping src and dest. if (txt && txt != mText) dStrncpy(mText, (UTF8*)txt, MAX_STRING_LENGTH); mText[MAX_STRING_LENGTH] = '\0';
codereview_cpp_data_7856
npc_faction_id ).c_str() ); - c->Message(Chat::White, "Use: #setfaction [Faction ID] - Set an NPC's Primary Faction ID"); } } } Not sure of the need for #setfaction message here npc_faction_id ).c_str() ); } } }
codereview_cpp_data_7860
} else { - if (e->getTags().keys().contains(_k) && _appendToExistingValue) { e->getTags()[_k] = e->getTags()[_k] + "," + _v; } Possibly swap the order of the conditions here - so that if we are not appending, we don't have to search for _k } else { + if (_appendToExistingValue && e->getTags().keys().contains(_k)) { e->getTags()[_k] = e->getTags()[_k] + "," + _v; }
codereview_cpp_data_7875
} } - if (lxc_config_define_load(&defines, c->lxc_conf)) exit(EXIT_FAILURE); if (my_args.uid) c->lxc_conf->init_uid = my_args.uid; This misses a `lxc_container_put(c);` :) So this should be: ``` ret = lxc_config_define_load(&defines, c->lxc_conf); if (ret) { lxc_container_put(c); exit(EXIT_FAILURE); } ``` } } + ret = lxc_config_define_load(&defines, c->lxc_conf); + if (ret) { + lxc_container_put(c); exit(EXIT_FAILURE); + } if (my_args.uid) c->lxc_conf->init_uid = my_args.uid;
codereview_cpp_data_7884
gboolean thrift_ssl_socket_close (ThriftTransport *transport, GError **error) { - /* gboolean retval = FALSE; */ ThriftSSLSocket *ssl_socket = THRIFT_SSL_SOCKET(transport); if(ssl_socket!=NULL && ssl_socket->ssl) { - int rc = SSL_shutdown(ssl_socket->ssl); - (void)rc; -/* if (rc < 0) { - int errno_copy = THRIFT_SSL_SOCKET_ERROR_SSL; - }*/ SSL_free(ssl_socket->ssl); ssl_socket->ssl = NULL; ERR_remove_state(0); Better to remove it entirely if it's unused. I did this in #1830 but still waiting on approval. cc @Jens-G gboolean thrift_ssl_socket_close (ThriftTransport *transport, GError **error) { ThriftSSLSocket *ssl_socket = THRIFT_SSL_SOCKET(transport); if(ssl_socket!=NULL && ssl_socket->ssl) { + SSL_shutdown(ssl_socket->ssl); SSL_free(ssl_socket->ssl); ssl_socket->ssl = NULL; ERR_remove_state(0);
codereview_cpp_data_7890
#ifdef UA_ENABLE_MULTITHREADING pthread_cond_destroy(&server->dispatchQueue_condition); #endif UA_free(server); } I don't think we need that additional blocks. Maybe they are indicators for functionality that can be separated off in a small static function. That's considered good style. #ifdef UA_ENABLE_MULTITHREADING pthread_cond_destroy(&server->dispatchQueue_condition); + pthread_mutex_destroy(&server->dispatchQueue_mutex); #endif UA_free(server); }
codereview_cpp_data_7901
*/ #include <grpc++/grpc++.h> #include <gtest/gtest.h> -#include <iostream> #include "framework/test_subscriber.hpp" This include should not be required now. */ #include <grpc++/grpc++.h> #include <gtest/gtest.h> #include "framework/test_subscriber.hpp"
codereview_cpp_data_7902
buts[2] = _("_No"); buts[3] = NULL; ret = gwwv_ask( _("Unsaved script"),(const char **) buts,0,2,_("You have an unsaved script in the «Execute Script» dialog. Do you intend to discard it?")); - if (ret == 1) warn_script_unsaved = false; SavePrefs(true); return( ret ); } Don't put this all on one line and put this in brackets, you're otherwise always saving preferences buts[2] = _("_No"); buts[3] = NULL; ret = gwwv_ask( _("Unsaved script"),(const char **) buts,0,2,_("You have an unsaved script in the «Execute Script» dialog. Do you intend to discard it?")); + if (ret == 1) { + warn_script_unsaved = false; + SavePrefs(true); + } return( ret ); }
codereview_cpp_data_7903
template <typename TensorDataType> bool rmsprop<TensorDataType>::load_from_checkpoint_shared(persist& p, std::string name_prefix) { - load_from_shared_cereal_archive<rmsprop<TensorDataType>>(*this, p, this->get_comm(), "rmsprop.xml"); char l_name[512]; sprintf(l_name, "%s_optimizer_cache_%lldx%lld.bin", name_prefix.c_str(), m_cache->Height(), m_cache->Width()); ```suggestion load_from_shared_cereal_archive(*this, p, this->get_comm(), "rmsprop.xml"); ``` template <typename TensorDataType> bool rmsprop<TensorDataType>::load_from_checkpoint_shared(persist& p, std::string name_prefix) { + load_from_shared_cereal_archive(*this, p, this->get_comm(), "rmsprop.xml"); char l_name[512]; sprintf(l_name, "%s_optimizer_cache_%lldx%lld.bin", name_prefix.c_str(), m_cache->Height(), m_cache->Width());
codereview_cpp_data_7905
m_network_Factory.RegisterTransport(&descriptor); } - /// Creation of metatraffic locator and receiver resources - uint32_t metatraffic_multicast_port = m_att.port.getMulticastPort(m_att.builtin.domainId); - uint32_t metatraffic_unicast_port = m_att.port.getUnicastPort(m_att.builtin.domainId, - static_cast<uint32_t>(m_att.participantID)); - // Workaround TCP discovery issues when register switch (PParam.builtin.discoveryProtocol) { After the explanation of why these changes were done, I think the user is responsible for configuring participants that use TCP transport. m_network_Factory.RegisterTransport(&descriptor); } // Workaround TCP discovery issues when register switch (PParam.builtin.discoveryProtocol) {
codereview_cpp_data_7911
} else { - // TODO: actually delete file? syncs.removeSelectedSyncs([](SyncConfig&, Sync* s) { return s != nullptr; }); syncs.truncate(); } `if (!keepSyncsConfigFile)`, then yes, we should actually delete the file. } else { syncs.removeSelectedSyncs([](SyncConfig&, Sync* s) { return s != nullptr; }); syncs.truncate(); }
codereview_cpp_data_7927
um_map::iterator mit = umindex.find(nuid); if (mit != umindex.end() && mit->second != hit->second) { assert(!users[mit->second].sharing.size()); users.erase(mit->second); } Node::copystring(&u->email, email); umindex[nuid] = hit->second; I think that the new approach doesn't take into account email changes and wouldn't remove the element related to the previous email from `umindex`. um_map::iterator mit = umindex.find(nuid); if (mit != umindex.end() && mit->second != hit->second) { + // duplicated user: one by email, one by handle assert(!users[mit->second].sharing.size()); users.erase(mit->second); } + // if mapping a different email, remove old index + if (strcmp(u->email, email)) + { + umindex.erase(u->email); + } Node::copystring(&u->email, email); umindex[nuid] = hit->second;
codereview_cpp_data_7936
{ return std::cerr; } - else - { - return std::cout; - } } } // Namespace dds ```suggestion // If Log::Kind is stderr_threshold_ or more severe, then use STDERR, else use STDOUT if (entry.kind <= stderr_threshold_) { return std::cerr; } return std::cout; ``` { return std::cerr; } + return std::cout; } } // Namespace dds
codereview_cpp_data_7946
if (mode_listen) { int fd, reuseaddr_flag = 1; - if ( -#ifdef __linux__ - (fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)) == -1 || -#else - (fd = socket(AF_INET, SOCK_STREAM, 0)) == -1 || -#endif setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr_flag, sizeof(reuseaddr_flag)) != 0 || bind(fd, res->ai_addr, res->ai_addrlen) != 0 || listen(fd, SOMAXCONN) != 0) { fprintf(stderr, "failed to listen to %s:%s:%s\n", host, port, strerror(errno)); I would appreciate it if you could revert the change to minimize the maintenance cost of the code. Considering that a HTTP/2 connection is typically long-running and that latency optimization issues many syscalls than when set to off, I do not think we need to complicate things here. if (mode_listen) { int fd, reuseaddr_flag = 1; + if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1 || setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr_flag, sizeof(reuseaddr_flag)) != 0 || bind(fd, res->ai_addr, res->ai_addrlen) != 0 || listen(fd, SOMAXCONN) != 0) { fprintf(stderr, "failed to listen to %s:%s:%s\n", host, port, strerror(errno));
codereview_cpp_data_7948
: transferQueue; // transfer queue of class MegaApiImpl // if we are processing a custom queue, we need to process in one shot - bool timeout = !queue; while(MegaTransferPrivate *transfer = auxQueue.pop()) { It is not a timeout only, but also the amount of transfers processed. Better to name it differently. Maybe `canSplit` or alike : transferQueue; // transfer queue of class MegaApiImpl // if we are processing a custom queue, we need to process in one shot + bool canSplit = !queue; while(MegaTransferPrivate *transfer = auxQueue.pop()) {
codereview_cpp_data_7955
void testStateChangesBetweenIntegration() { using SimTK::Vec3; Model model; Changing the state without an explicit realize to at least velocity doesn't seem right. I would always realize after changing the state. Does that make a difference? void testStateChangesBetweenIntegration() { + cout << "Running testStateChangesBetweenIntegration" << endl; + using SimTK::Vec3; Model model;
codereview_cpp_data_7961
template <typename TensorDataType> bool sgd<TensorDataType>::save_to_checkpoint_shared(persist& p, std::string name_prefix) { if (this->get_comm().am_trainer_master()) { - write_cereal_archive<sgd<TensorDataType>>(*this, p, "sgd.xml"); } char l_name[512]; ```suggestion write_cereal_archive(*this, p, "sgd.xml"); ``` template <typename TensorDataType> bool sgd<TensorDataType>::save_to_checkpoint_shared(persist& p, std::string name_prefix) { if (this->get_comm().am_trainer_master()) { + write_cereal_archive(*this, p, "sgd.xml"); } char l_name[512];
codereview_cpp_data_7962
if (fd == -1) { LOG_debug << "Unable to open path using fseventspath."; - this->fsEventsPath = *crootpath; } else { New class members should be named with a `m` prefix. Please, refactor `fsEventsPath` to `mFsEventsPath` or alike (and you should skip also the usage of `this->` to access the member (we avoid clashes with other variables thanks to the prefix). if (fd == -1) { LOG_debug << "Unable to open path using fseventspath."; + mFsEventsPath = *crootpath; } else {
codereview_cpp_data_7966
GUARD_PTR(s2n_blob_zero(&mem)); struct s2n_offered_psk *psk = (struct s2n_offered_psk*)(void*) mem.data; - *psk = (struct s2n_offered_psk){ 0 }; ZERO_TO_DISABLE_DEFER_CLEANUP(mem); return psk; You don't need to do "*psk = (struct s2n_offered_psk){ 0 };" anymore. You've already zeroed the memory. GUARD_PTR(s2n_blob_zero(&mem)); struct s2n_offered_psk *psk = (struct s2n_offered_psk*)(void*) mem.data; ZERO_TO_DISABLE_DEFER_CLEANUP(mem); return psk;