id stringlengths 21 25 | content stringlengths 164 2.33k |
|---|---|
codereview_cpp_data_2929 | SpellStorage tmpSpells = spells;
std::sort( tmpSpells.begin(), tmpSpells.end() );
for ( int32_t i = 0; i < spellsPerPage; ++i ) {
- if ( spells.size() <= index + i )
return;
const int32_t ox = 84 + 81 * ( i & 1 );
Hi @undef21 Wouldn't it be logical to check `index + i` against `tmpSpells.size()` here instead of `spells.size()` if we later refer to the element of `tmpSpells`? I understand that now they are the same, but just in case.
SpellStorage tmpSpells = spells;
std::sort( tmpSpells.begin(), tmpSpells.end() );
for ( int32_t i = 0; i < spellsPerPage; ++i ) {
+ if ( tmpSpells.size() <= index + i )
return;
const int32_t ox = 84 + 81 * ( i & 1 ); |
codereview_cpp_data_2933 | priority.PopBack();
}
Assign( priority );
}
I think we need to break the loop if `JoinTroop` returns false: ``` if ( rightTroop && rightTroop->isValid() ) { if ( !JoinTroop( *rightTroop ) ) break; rightTroop->Reset(); } ```
priority.PopBack();
}
+ // assign stongest to army1, keep unit order
Assign( priority );
} |
codereview_cpp_data_2934 | }
}
-void GTabSetRemoveTabByPos(GGadget *g, int pos);
static void GTabSetChangeSel(GTabSet *gts, int sel,int sendevent) {
int i, width;
int oldsel = gts->sel;
Since this is in `ggadget.h` not sure why it's needed here.
}
}
static void GTabSetChangeSel(GTabSet *gts, int sel,int sendevent) {
int i, width;
int oldsel = gts->sel; |
codereview_cpp_data_2941 | }
/* validate a header value against https://tools.ietf.org/html/rfc7230#section-3.2 */
-static bool contains_invalid_field_value_char(const char *s, size_t len)
{
/* all printable chars + horizontal tab */
- static const bool valid_h2_field_value_char[] = {
0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0-31 */
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 32-63 */
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 64-95 */
Do we need to have this checked here? My understanding is that it is done in `h2o_hpack_parse_headers`.
}
/* validate a header value against https://tools.ietf.org/html/rfc7230#section-3.2 */
+static int contains_invalid_field_value_char(const char *s, size_t len)
{
/* all printable chars + horizontal tab */
+ static const char valid_h2_field_value_char[] = {
0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0-31 */
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 32-63 */
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 64-95 */ |
codereview_cpp_data_2944 | }
void PostgresQueryExecutorVisitor::setQueryHash(
- const shared_model::crypto::Hash &query_hash) {
query_hash_ = query_hash;
}
You can use shared_model::interface::types::HashType, so that you do not depend on cryptography directly
}
void PostgresQueryExecutorVisitor::setQueryHash(
+ const shared_model::interface::types::HashType &query_hash) {
query_hash_ = query_hash;
} |
codereview_cpp_data_2961 | if (predictor_ != nullptr) { delete predictor_; }
bool is_predict_leaf = false;
bool is_raw_score = false;
- if (predict_type == 2) {
is_predict_leaf = true;
- } else if (predict_type == 1) {
- is_raw_score = false;
- } else {
is_raw_score = true;
}
predictor_ = new Predictor(boosting_, is_raw_score, is_predict_leaf);
}
why not use enum?
if (predictor_ != nullptr) { delete predictor_; }
bool is_predict_leaf = false;
bool is_raw_score = false;
+ if (predict_type == C_API_PREDICT_LEAF_INDEX) {
is_predict_leaf = true;
+ } else if (predict_type == C_API_PREDICT_RAW_SCORE) {
is_raw_score = true;
+ } else {
+ is_raw_score = false;
}
predictor_ = new Predictor(boosting_, is_raw_score, is_predict_leaf);
} |
codereview_cpp_data_2962 | }
}
errno = 0;
- int = strtol(buf, &end, 0);
if (errno) return false;
if (end != buf+strlen(buf)) return false;
Build failed because of this with next error: ``` 1>..\lib\parse.cpp(658): error C2513: 'int' : no variable declared before '=' 1>..\lib\parse.cpp(666): error C2065: 'val' : undeclared identifier ```
}
}
errno = 0;
+ int val = strtol(buf, &end, 0);
if (errno) return false;
if (end != buf+strlen(buf)) return false; |
codereview_cpp_data_2966 | if ( buttonGift.isEnabled() && le.MouseClickLeft( buttonGift.area() ) ) {
Dialog::MakeGiftResource( kingdom );
- resourceTo = resourceFrom = Resource::UNKNOWN;
gui.ShowTradeArea( kingdom, resourceFrom, resourceTo, 0, 0, 0, 0, fromTradingPost, firstExchange );
cursorTo.hide();
Please use one operation per line: ```cpp resourceTo = Resource::UNKNOWN; resourceFrom = Resource::UNKNOWN; ```
if ( buttonGift.isEnabled() && le.MouseClickLeft( buttonGift.area() ) ) {
Dialog::MakeGiftResource( kingdom );
+ resourceTo = Resource::UNKNOWN;
+ resourceFrom = Resource::UNKNOWN;
gui.ShowTradeArea( kingdom, resourceFrom, resourceTo, 0, 0, 0, 0, fromTradingPost, firstExchange );
cursorTo.hide(); |
codereview_cpp_data_2969 | LocalEvent & le = LocalEvent::Get();
- while ( 1 ) {
if ( !le.HandleEvents( true, true ) ) {
break;
}
:warning: **modernize\-use\-bool\-literals** :warning: converting integer literal to bool, use bool literal instead ```suggestion while ( true ) { ```
LocalEvent & le = LocalEvent::Get();
+ while ( true ) {
if ( !le.HandleEvents( true, true ) ) {
break;
} |
codereview_cpp_data_2977 | int result = Dialog::CANCEL;
bool need_redraw = false;
- int alphaHero = 241;
fheroes2::Image surfaceHero( 552, 107 );
// dialog menu loop
It is unknown why we assign the value 241 to this variable. Shall we assign 255 instead?
int result = Dialog::CANCEL;
bool need_redraw = false;
+ int alphaHero = 255;
fheroes2::Image surfaceHero( 552, 107 );
// dialog menu loop |
codereview_cpp_data_2992 | void DotNode::renumberNodes(int &number)
{
- if (!m_renumbered)
- {
- m_renumbered = true;
- m_number = number++;
- }
for (const auto &cn : m_children)
{
if (!cn->isRenumbered())
I don't think this is correct in general. Now the code at line 808 will set `m_renumbered` to `true` and then `cn->renumberNodes()` will not do anything anymore even though no number has been assigned!
void DotNode::renumberNodes(int &number)
{
+ m_number = number++;
for (const auto &cn : m_children)
{
if (!cn->isRenumbered()) |
codereview_cpp_data_2996 | #include "vast/test/test.hpp"
-// CAF 0.17.2 added a test DSL macro named `inject`, which conflicts with
-// `range_map::inject`
-#undef inject
-
#include "vast/detail/range_map.hpp"
#include "vast/load.hpp"
#include "vast/save.hpp"
For a follow-up issue: maybe we should not include the DSL unconditionally in `vast/test/test.hpp` instead? Since it's not part of the core unit test suite, we may want to include only where we actually use the DSL.
#include "vast/test/test.hpp"
#include "vast/detail/range_map.hpp"
#include "vast/load.hpp"
#include "vast/save.hpp" |
codereview_cpp_data_2997 | free (value);
}
-int elektraIniSet(Plugin *handle ELEKTRA_UNUSED, KeySet *returned, Key *parentKey)
{
/* set all keys */
int errnosave = errno;
doing this when plugin is opened would reduce this code duplication
free (value);
}
+int elektraIniSet(Plugin *handle, KeySet *returned, Key *parentKey)
{
/* set all keys */
int errnosave = errno; |
codereview_cpp_data_3003 | if (line == "$continue" || line == "$quit" || line == "$exit")
break;
else if (line == "$help")
- std::cout << "Welcome to the Icinga 2 console/script debugger.\n"
"Usable commands:\n"
" $continue, $quit, $exit Quit the console\n"
" $help Print this help\n\n"
Please name it `debug console`, similar to the docs. Some users don't understand its purpose unless explicitly stated.
if (line == "$continue" || line == "$quit" || line == "$exit")
break;
else if (line == "$help")
+ std::cout << "Welcome to the Icinga 2 debug console.\n"
"Usable commands:\n"
" $continue, $quit, $exit Quit the console\n"
" $help Print this help\n\n" |
codereview_cpp_data_3017 | template <typename TensorDataType>
bool adam<TensorDataType>::load_from_checkpoint_shared(persist& p, std::string name_prefix) {
- load_from_shared_cereal_archive<adam<TensorDataType>>(*this, p, this->get_comm(), "adam.xml");
char l_name[512];
sprintf(l_name, "%s_optimizer_adam_moment1_%lldx%lld.bin", name_prefix.c_str(), m_moment1->Height(), m_moment2->Width());
```suggestion load_from_shared_cereal_archive(*this, p, this->get_comm(), "adam.xml"); ```
template <typename TensorDataType>
bool adam<TensorDataType>::load_from_checkpoint_shared(persist& p, std::string name_prefix) {
+ load_from_shared_cereal_archive(*this, p, this->get_comm(), "adam.xml");
char l_name[512];
sprintf(l_name, "%s_optimizer_adam_moment1_%lldx%lld.bin", name_prefix.c_str(), m_moment1->Height(), m_moment2->Width()); |
codereview_cpp_data_3029 | {
ResultRelInfo *resultRelInfo;
ResultRelInfo *saved_resultRelInfo = NULL;
- /* if copies are directed to a chunk that is compressed, we redirect
- * them to the internal compressed chunk. But we still
- * need to check triggers, constrainst etc. against the original
- * chunk (not the internal compressed chunk).
- * check_resultRelInfo saves that information
- */
- ResultRelInfo *check_resultRelInfo = NULL;
EState *estate = ccstate->estate; /* for ExecConstraints() */
ExprContext *econtext;
TupleTableSlot *singleslot;
Unclear what "check" means in this context. Is there a better name?
{
ResultRelInfo *resultRelInfo;
ResultRelInfo *saved_resultRelInfo = NULL;
EState *estate = ccstate->estate; /* for ExecConstraints() */
ExprContext *econtext;
TupleTableSlot *singleslot; |
codereview_cpp_data_3030 | assert( activeHumanColors <= 1 );
const Kingdom & myKingdom = world.GetKingdom( humanColors );
- const Settings & conf = Settings::Get();
if ( myKingdom.isControlHuman() ) {
if ( !continueAfterVictory && GameOver::COND_NONE != ( result = world.CheckKingdomWins( myKingdom ) ) ) {
DialogWins( result );
if ( conf.isCampaignGameType() ) {
res = fheroes2::GameMode::COMPLETE_CAMPAIGN_SCENARIO;
}
Could we please move this variable under if-body (`if ( !continueAfterVictory && GameOver::COND_NONE != ( result = world.CheckKingdomWins( myKingdom ) ) ) {`) to reduce the scope of it?
assert( activeHumanColors <= 1 );
const Kingdom & myKingdom = world.GetKingdom( humanColors );
if ( myKingdom.isControlHuman() ) {
if ( !continueAfterVictory && GameOver::COND_NONE != ( result = world.CheckKingdomWins( myKingdom ) ) ) {
DialogWins( result );
+ const Settings & conf = Settings::Get();
+
if ( conf.isCampaignGameType() ) {
res = fheroes2::GameMode::COMPLETE_CAMPAIGN_SCENARIO;
} |
codereview_cpp_data_3034 | using namespace sofa::defaulttype;
-#ifndef SOFA_FLOAT
-template class SOFA_RIGID_API JointSpring<defaulttype::Rigid3dTypes>;
-#endif
-#ifndef SOFA_DOUBLE
-template class SOFA_RIGID_API JointSpring<defaulttype::Rigid3fTypes>;
-#endif
} // namespace interactionforcefield
Nooooo ! The Sofa float are trying to re-enter in Sofa :)
using namespace sofa::defaulttype;
+template class SOFA_RIGID_API JointSpring<defaulttype::Rigid3Types>;
} // namespace interactionforcefield |
codereview_cpp_data_3035 | // node update
sc_updatenode();
#ifdef ENABLE_SYNC
- // run syncdown() before continuing
- applykeys();
- return false;
#endif
break;
We must control that the AP is not part of a cached fetchnodes. If so, do not return false (do not force any sync scan)
// node update
sc_updatenode();
#ifdef ENABLE_SYNC
+ if (!fetchingnodes)
+ {
+ // run syncdown() before continuing
+ applykeys();
+ return false;
+ }
#endif
break; |
codereview_cpp_data_3036 | return descriptions;
}
-void HeroesIndicator::SetHero( const Heroes & h )
{
- hero = &h;
}
void HeroesIndicator::SetPos( const Point & pt )
Hmm... passing a reference and taking a pointer from it is not a very good way to do. We should pass a pointer then.
return descriptions;
}
+void HeroesIndicator::SetHero( const Heroes * h )
{
+ hero = h;
}
void HeroesIndicator::SetPos( const Point & pt ) |
codereview_cpp_data_3042 | namespace
{
- const std::bitset<256> ObjMnts1ShadowBitset
= fheroes2::makeBitsetFromVector<256>( { 0, 5, 11, 17, 21, 26, 32, 38, 42, 45, 49, 52, 55, 59, 62, 65, 68, 71, 74, 75, 79, 80 } );
- const std::bitset<256> ObjMnts2ShadowBitset = fheroes2::makeBitsetFromVector<256>(
{ 0, 5, 11, 17, 21, 26, 32, 38, 42, 46, 47, 53, 57, 58, 62, 68, 72, 75, 79, 82, 85, 89, 92, 95, 98, 101, 104, 105, 109, 110 } );
}
/*
Please name all newly created variables from non-capital letter.
namespace
{
+ const std::bitset<256> objMnts1ShadowBitset
= fheroes2::makeBitsetFromVector<256>( { 0, 5, 11, 17, 21, 26, 32, 38, 42, 45, 49, 52, 55, 59, 62, 65, 68, 71, 74, 75, 79, 80 } );
+ const std::bitset<256> objMnts2ShadowBitset = fheroes2::makeBitsetFromVector<256>(
{ 0, 5, 11, 17, 21, 26, 32, 38, 42, 46, 47, 53, 57, 58, 62, 68, 72, 75, 79, 82, 85, 89, 92, 95, 98, 101, 104, 105, 109, 110 } );
}
/* |
codereview_cpp_data_3049 | u32 Heroes::GetVisionsDistance( void ) const
{
- uint32_t crystalBallCount = std::max( 1u, artifactCount( Artifact::CRYSTAL_BALL ) );
return 8 * crystalBallCount;
}
:warning: **readability\-uppercase\-literal\-suffix** :warning: integer literal has suffix `` u ``, which is not uppercase ```suggestion uint32_t crystalBallCount = std::max( 1U, artifactCount( Artifact::CRYSTAL_BALL ) ); ```
u32 Heroes::GetVisionsDistance( void ) const
{
+ uint32_t crystalBallCount = std::max( 1U, artifactCount( Artifact::CRYSTAL_BALL ) );
return 8 * crystalBallCount;
} |
codereview_cpp_data_3051 | {
LBANN_ASSERT_MSG_HAS_FIELD(proto_layer, gather);
using BuilderType = Builder<TensorDataType, Layout, Device>;
- auto axis = proto_layer.gather().axis().value();
return BuilderType::Build(axis);
}
What do we want to be the default value? Right now the default for `axis` is 0. We could alternatively do something like: ```suggestion const auto& params = proto_layer.gather(); int axis = -1; if (params.has_axis()) { axis = params.axis().value(); } ```
{
LBANN_ASSERT_MSG_HAS_FIELD(proto_layer, gather);
using BuilderType = Builder<TensorDataType, Layout, Device>;
+ const auto& params = proto_layer.gather();
+ int axis = -1;
+ if (params.has_axis()){
+ axis = params.axis().value();
+ }
return BuilderType::Build(axis);
} |
codereview_cpp_data_3052 | // Write conn log slices (as record batches) to the stream.
for (auto& slice : zeek_conn_log)
writer.write(slice);
- // Cause the writer to close its current Arrow writer by switching the layout.
- REQUIRE(writer.layout(::arrow::schema({})));
// Deserialize record batches, store them in arrow_table_slice objects, and
// compare to the original slices.
std::shared_ptr<arrow::Buffer> buf;
Have empty schemas been allowed for a while now? They used to be the main reasons for us disallowing empty record types. Maybe we need to reconsider that restriction (cc @tobim).
// Write conn log slices (as record batches) to the stream.
for (auto& slice : zeek_conn_log)
writer.write(slice);
+
+ // closing the stream so we can start reading back the data.
+ REQUIRE_OK(stream->Close());
+
// Deserialize record batches, store them in arrow_table_slice objects, and
// compare to the original slices.
std::shared_ptr<arrow::Buffer> buf; |
codereview_cpp_data_3057 | is_bn ? context.m_damping_bn_act : context.m_damping_act,
is_bn ? context.m_damping_bn_err : context.m_damping_err,
is_gru ? m_learning_rate_factor_gru : m_learning_rate_factor,
m_print_matrix, m_print_matrix_summary,
m_print_time);
prof_region_end(("kfac-inverse/" + block->get_name()).c_str(), prof_sync);
This will never run: ```suggestion ```
is_bn ? context.m_damping_bn_act : context.m_damping_act,
is_bn ? context.m_damping_bn_err : context.m_damping_err,
is_gru ? m_learning_rate_factor_gru : m_learning_rate_factor,
+ m_use_eigen_decomposition,
m_print_matrix, m_print_matrix_summary,
m_print_time);
prof_region_end(("kfac-inverse/" + block->get_name()).c_str(), prof_sync); |
codereview_cpp_data_3064 | }
catch (const std::exception& e) {
- std::cout << "Visualizer couldn't read "
<< attempts.back() << " because:\n"
<< e.what() << "\n";
return;
We should probably update the exception message that the file could not be found and opened since the mesh won't be read in until display time.
}
catch (const std::exception& e) {
+ std::cout << "Visualizer couldn't open "
<< attempts.back() << " because:\n"
<< e.what() << "\n";
return; |
codereview_cpp_data_3070 | SQLEXEC();
}
- SQLPREP("UPDATE `%1users` SET `pw`=?, `salt`=?, `kdfmeter`=? WHERE `server_id` = ? AND `user_id`=?");
query.addBindValue(pwHash);
query.addBindValue(saltHash);
query.addBindValue(Meta::mp.kdfIterations);
const QString &pw?
SQLEXEC();
}
+ SQLPREP("UPDATE `%1users` SET `pw`=?, `salt`=?, `kdfiterations`=? WHERE `server_id` = ? AND `user_id`=?");
query.addBindValue(pwHash);
query.addBindValue(saltHash);
query.addBindValue(Meta::mp.kdfIterations); |
codereview_cpp_data_3073 | return emitent.subscribe_on(rxcpp::observe_on_new_thread());
}
- GossipPropagationStrategy::~GossipPropagationStrategy() {}
-
bool GossipPropagationStrategy::initQueue() {
- return query_factory->createPeerQuery() | [](const auto &query) {
return query->getLedgerPeers();
} | [](auto &&data) -> boost::optional<PropagationData> {
if (data.size() == 0) {
Isn't it better write is as `=default` in hpp file?
return emitent.subscribe_on(rxcpp::observe_on_new_thread());
}
bool GossipPropagationStrategy::initQueue() {
+ return peer_factory->createPeerQuery() | [](const auto &query) {
return query->getLedgerPeers();
} | [](auto &&data) -> boost::optional<PropagationData> {
if (data.size() == 0) { |
codereview_cpp_data_3080 | void addFormNote(const String& text, const String& id)
{
addRowLabel_tr_id("", id);
- addHtmlDiv(F("note"), text);
}
// ********************************************************************************
Is that _Note:_ prefix no longer part of a note? I find it quite useful.
void addFormNote(const String& text, const String& id)
{
addRowLabel_tr_id("", id);
+ addHtmlDiv(F("note"), String(F("Note: ")) + text);
}
// ******************************************************************************** |
codereview_cpp_data_3085 | }
cvtsize = cvtindex;
- cvt = realloc(cvt, cvtsize * sizeof(uint8));
/* Try to implant the new cvt table */
gic->cvt_done = 0;
This is both not safe and does not match the `calloc` on line 695.
}
cvtsize = cvtindex;
+ cvt = realloc(cvt, cvtsize * 2 * sizeof(uint8));
/* Try to implant the new cvt table */
gic->cvt_done = 0; |
codereview_cpp_data_3090 | // Checks whether a component can be spawned at most once.
bool is_singleton(const std::string& component) {
- static detail::flat_set<std::string> singletons = {"archive", "index",
- "consensus"};
- return singletons.find(component) != singletons.end();
}
} // namespace <anonymous>
I would avoid bringing in such a big dependency here, how about: ``` c++ const char* singletons[] = {"archive", "index", "consensus"}; return std::any_of(std::begin(singletons), std::end(singletons), [&](const char* lhs) { return lhs == component; }); ```
// Checks whether a component can be spawned at most once.
bool is_singleton(const std::string& component) {
+ const char* singletons[] = {"archive", "index", "consensus"};
+ auto pred = [&](const char* lhs) { return lhs == component; };
+ return std::any_of(std::begin(singletons), std::end(singletons), pred);
}
} // namespace <anonymous> |
codereview_cpp_data_3097 | /* Load policy from / if SELinux is enabled, and we haven't already loaded
* a policy. This is mostly for the "compose tree" case.
*/
- if (selinux)
{
glnx_autofd int host_rootfs_dfd = -1;
/* Ensure that the imported packages are labeled with *a* policy if
Though... this now overwrites the explicit `set_sepolicy` we did before calling `setup` in the upgrader path, right? That means less potential sharing between the cache and the final commit. I.e. maybe just: ```diff -if (selinux) +if (selinux && !self->sepolicy) ``` ?
/* Load policy from / if SELinux is enabled, and we haven't already loaded
* a policy. This is mostly for the "compose tree" case.
*/
+ if (selinux && !self->sepolicy)
{
glnx_autofd int host_rootfs_dfd = -1;
/* Ensure that the imported packages are labeled with *a* policy if |
codereview_cpp_data_3105 | errno = 0;
if (env_ndevices_str != nullptr && env_rdevices_str != nullptr) {
Impl::throw_runtime_exception(
- "Error: cannot specify KOKKOS_NUM_DEVICES and KOKKOS_RAND_DEVICES. "
"Raised by Kokkos::initialize(int narg, char* argc[]).");
}
int rdevices = -1;
specify "both" X and Y
errno = 0;
if (env_ndevices_str != nullptr && env_rdevices_str != nullptr) {
Impl::throw_runtime_exception(
+ "Error: cannot specify both KOKKOS_NUM_DEVICES and "
+ "KOKKOS_RAND_DEVICES. "
"Raised by Kokkos::initialize(int narg, char* argc[]).");
}
int rdevices = -1; |
codereview_cpp_data_3116 | }
void FreeOrionNode::send_chat_message(godot::String text) {
- std::string text8 = std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t>{}.to_bytes(text.unicode_str());
m_app->Networking().SendMessage(PlayerChatMessage(text8, {}, false));
}
Does Godot use UTF-16 internally on all platforms?
}
void FreeOrionNode::send_chat_message(godot::String text) {
+ std::string text8 = text.utf8().get_data();
m_app->Networking().SendMessage(PlayerChatMessage(text8, {}, false));
} |
codereview_cpp_data_3117 | hasStatus = true;
if (_textStatus)
{
- writer.writeAttribute("v", QString("%1").arg(w->getStatus().toTextStatus()));
}
else
{
QString("%1") not needed - OR I'm going to feel really dumb when it turns out I'm wrong :)
hasStatus = true;
if (_textStatus)
{
+ writer.writeAttribute("v", w->getStatus().toTextStatus());
}
else
{ |
codereview_cpp_data_3125 | * @param aBody Pointer to body.
* @param rDirCos Orientation of the body with respect to the ground frame.
*/
-void SimbodyEngine::getDirectionCosines(const SimTK::State& s, const
- OpenSim::Body &aBody, double *rDirCos) const
{
Mat33::updAs(rDirCos) =
aBody.getMobilizedBody().getBodyRotation(s).asMat33();
line split, with a few more below
* @param aBody Pointer to body.
* @param rDirCos Orientation of the body with respect to the ground frame.
*/
+void SimbodyEngine::getDirectionCosines(const SimTK::State& s,
+ const OpenSim::Body& aBody, double *rDirCos) const
{
Mat33::updAs(rDirCos) =
aBody.getMobilizedBody().getBodyRotation(s).asMat33(); |
codereview_cpp_data_3126 | log_(logger::log("OrderingGate")) {}
void OrderingGateTransportGrpc::propagateTransaction(
- const std::shared_ptr<const shared_model::interface::Transaction>
- &transaction) {
log_->info("Propagate tx (on transport)");
auto call = new AsyncClientCall;
Why pass pointer by reference?
log_(logger::log("OrderingGate")) {}
void OrderingGateTransportGrpc::propagateTransaction(
+ std::shared_ptr<const shared_model::interface::Transaction> transaction) {
log_->info("Propagate tx (on transport)");
auto call = new AsyncClientCall; |
codereview_cpp_data_3128 | auto keysManager = iroha::KeysManagerImpl(FLAGS_name);
if (not keysManager.createKeys(FLAGS_pass_phrase)) {
logger->error("Keys already exist");
- return EXIT_FAILURE;
} else {
logger->info(
"Public and private key has been generated in current directory");
Execution should probably stop if such error occurs.
auto keysManager = iroha::KeysManagerImpl(FLAGS_name);
if (not keysManager.createKeys(FLAGS_pass_phrase)) {
logger->error("Keys already exist");
} else {
logger->info(
"Public and private key has been generated in current directory"); |
codereview_cpp_data_3136 | #define PROTO_DEVICE(T, Device) \
template class fully_connected_layer<T, data_layout::DATA_PARALLEL, Device>; \
- template class fully_connected_layer<T, data_layout::MODEL_PARALLEL, Device>;
#define LBANN_INSTANTIATE_CPU_HALF
#define LBANN_INSTANTIATE_GPU_HALF
```suggestion template class fully_connected_layer<T, data_layout::MODEL_PARALLEL, Device> ```
#define PROTO_DEVICE(T, Device) \
template class fully_connected_layer<T, data_layout::DATA_PARALLEL, Device>; \
+ template class fully_connected_layer<T, data_layout::MODEL_PARALLEL, Device>
#define LBANN_INSTANTIATE_CPU_HALF
#define LBANN_INSTANTIATE_GPU_HALF |
codereview_cpp_data_3144 | if ( hero.HasArtifact( Artifact::BALLISTA ) )
catShots += Artifact( Artifact::BALLISTA ).ExtraValue();
-
- const int maxCatShots = 3;
- if ( catShots > maxCatShots ) {
- catShots = maxCatShots;
- }
}
u32 Battle::Catapult::GetDamage() const
Hi @tau3 may be just change `extra` value for `Ballista of Quickness` in `resource/artifact.cpp` from 2 to 1? Hi @Branikolog I suppose this artifact should just give one extra shot?
if ( hero.HasArtifact( Artifact::BALLISTA ) )
catShots += Artifact( Artifact::BALLISTA ).ExtraValue();
}
u32 Battle::Catapult::GetDamage() const |
codereview_cpp_data_3153 | else
{
notRelevantChanges.add_sequence_number(seq_num, remoteReader);
- remoteReader->set_change_to_status(seq_num, UNDERWAY, false); //TODO(Ricardo) Review
}
};
- remoteReader->for_each_unsent_change(unsent_change_process);
}
if (m_pushMode)
I think we can remove this with the new implementation of ReaderProxy.
else
{
notRelevantChanges.add_sequence_number(seq_num, remoteReader);
}
};
+ remoteReader->for_each_unsent_change(max_sequence, unsent_change_process);
}
if (m_pushMode) |
codereview_cpp_data_3159 | *
* So, since the user is probably using this feature to test variable fonts,
* ask them if they even want FontForge to force compatibility. */
-bool InterpolationSanity(SplineSet* base, SplineSet *other, int order2) {
SplineSet *bss=NULL, *oss=NULL;
int bmcc = 0, omcc = 0;
if (base == NULL || other == NULL) return false;
Some glyphs may be viable to interpolate when they self-overlap but not when they don't. (Perhaps some ampersands may be in this category.) And not all formats prohibit overlap. `SplinePointListIsClockwise()` usually returns -1 for such contours, but may not always. However, it's unlikely to return the non-dominant value (e.g. false for a contour that would be clockwise if Remove Overlap were run on it). Therefore I think this section should allow a return value of -1 to be considered equal to any value.
*
* So, since the user is probably using this feature to test variable fonts,
* ask them if they even want FontForge to force compatibility. */
+bool InterpolationSanity(SplineSet* base, SplineSet *other, int order2, char* prefix) {
SplineSet *bss=NULL, *oss=NULL;
int bmcc = 0, omcc = 0;
+ bool ret = true;
if (base == NULL || other == NULL) return false; |
codereview_cpp_data_3164 | */
#ifdef _WIN32
# include <ws2tcpip.h>
-# ifndef AI_ADDRCONFIG
-# define AI_ADDRCONFIG 0
-# endif
-# ifndef AI_NUMERICSERV
-# define AI_NUMERICSERV 8
-# endif
#else
# include <arpa/inet.h>
# include <netdb.h>
Please move the includes and defines (e.g. `AI_ADDRCONFIG`) mandatory to use the functions provided by hostinfo.h to hostinfo.h, instead of repeating the definitions in each source file.
*/
#ifdef _WIN32
# include <ws2tcpip.h>
#else
# include <arpa/inet.h>
# include <netdb.h> |
codereview_cpp_data_3166 | }
key = pkidh.pkcs11_provider->load_private_key(certificate, file, password, exception);
-
- if ( nullptr == key )
- {
- exception = _SecurityException_(std::string("PKCS11 URIs require libp11 ") + file);
- }
}
else
{
Method `pkcs11_provider->load_private_key` is already filling out `exception` in case of error, so there is no need to change the exception message here. ```suggestion ```
}
key = pkidh.pkcs11_provider->load_private_key(certificate, file, password, exception);
}
else
{ |
codereview_cpp_data_3167 | client_ctx->websocket_timeout = NULL;
}
client_ctx->ssl_ctx = self->config.ssl_ctx;
- client_ctx->ssl_session_cache = h2o_cache_create(0, 4096, 86400 * 1000, h2o_socket_ssl_destroy_session_cache_entry);
h2o_context_set_handler_context(ctx, &self->super, client_ctx);
}
Don't we need to set `H2O_CACHE_FLAG_MULTITHREADED` here as well?
client_ctx->websocket_timeout = NULL;
}
client_ctx->ssl_ctx = self->config.ssl_ctx;
+ if (self->config.session_cache.capacity != 0 && self->config.session_cache.lifetime != 0) {
+ client_ctx->ssl_session_cache =
+ h2o_cache_create(0, self->config.session_cache.capacity, self->config.session_cache.lifetime * 1000,
+ h2o_socket_ssl_destroy_session_cache_entry);
+ } else {
+ client_ctx->ssl_session_cache = NULL;
+ }
h2o_context_set_handler_context(ctx, &self->super, client_ctx);
} |
codereview_cpp_data_3169 | MODULE_END;
-String ShaderGen::smCommonShaderPath(Con::getVariable("$Core::CommonShaderPath", "shaders/common"));
ShaderGen::ShaderGen()
{
This will always evaluate to "shaders/common" as console subsystem won't be initialized until way later, unless it segfaults. Keep in mind when you do object initialization like this at the source file scope it'll be executed before `int main(size_t argc, char *argv[])` is executed. Shouldn't call engine functions until after their respective subsystems are initialized.
MODULE_END;
+String ShaderGen::smCommonShaderPath("shaders/common");
ShaderGen::ShaderGen()
{ |
codereview_cpp_data_3171 | {
if (client->json.isnumeric())
{
- return client->app->resendverificationemail_result((error)client->json.getint());
}
else
{
client->json.storeobject();
- return client->app->resendverificationemail_result((error)API_EINTERNAL);
}
}
This method returns `void`. Actually, you can leave it fall through, and it will return anyway (as it is the code today).
{
if (client->json.isnumeric())
{
+ client->app->resendverificationemail_result((error)client->json.getint());
}
else
{
client->json.storeobject();
+ client->app->resendverificationemail_result((error)API_EINTERNAL);
}
} |
codereview_cpp_data_3173 | opt_group{custom_options_, "vast"}
.add<size_t>("table-slice-size",
"Maximum size for sources that generate table slices.");
- // Initialize factories.
- factory<synopsis>::initialize();
- factory<table_slice>::initialize();
- factory<table_slice_builder>::initialize();
- factory<value_index>::initialize();
}
caf::error configuration::parse(int argc, char** argv) {
I would like to see a little helper function for reducing the redundancy needed here. For example: ```c++ template <class... Ts> void initialize_factories() { (factory<Ts>::initialize(), ...); } ``` With that, the four lines boil down to: ```c++ initialize_factories<synopsis, table_slice, table_slice_builder, value_index>(). ```
opt_group{custom_options_, "vast"}
.add<size_t>("table-slice-size",
"Maximum size for sources that generate table slices.");
+
+ initialize_factories<synopsis, table_slice, table_slice_builder,
+ value_index>();
}
caf::error configuration::parse(int argc, char** argv) { |
codereview_cpp_data_3179 | void MainWindow::notifyUserAboutUpdate()
{
- QMessageBox::information(this, tr("Information"), tr("This server supports additional features that your client doesn't have.\nThis is most likely not a problem, but this message might mean there is a new version of Cockatrice available.\n\nTo update your client, go to Help → Update Cockatrice."));
}
void MainWindow::actOpenCustomFolder()
What about this: > This server supports additional features that your client doesn't have. > This is most likely not a problem, but there might be a new version of Cockatrice available for you. > To check for client updates go to "Help -> Update Cockatrice". Will cockatrice properly display the encoded "→" btw?
void MainWindow::notifyUserAboutUpdate()
{
+ QMessageBox::information(this, tr("Information"), tr("This server supports additional features that your client doesn't have.\nThis is most likely not a problem, but this message might mean there is a new version of Cockatrice available.\n\nTo update your client, go to Help -> Update Cockatrice."));
}
void MainWindow::actOpenCustomFolder() |
codereview_cpp_data_3182 | using namespace iroha::ametsuchi;
using PropagationData = GossipPropagationStrategy::PropagationData;
-const shared_model::interface::types::PubkeyType empty_pubkey(
- shared_model::crypto::Hash::fromHexString(""));
-
/**
* Generates peers with empty pub keys
* @param ids generated addresses of peers
Variable can be removed.
using namespace iroha::ametsuchi;
using PropagationData = GossipPropagationStrategy::PropagationData;
/**
* Generates peers with empty pub keys
* @param ids generated addresses of peers |
codereview_cpp_data_3186 | }
// Some times the interval could be negative if a writer expired during the call to this function
- // Once in this situation there is not much we can do but let asio timers expire inmediately
auto interval = timer_owner_->time - steady_clock::now();
timer_.update_interval_millisec((double)duration_cast<milliseconds>(interval).count());
timer_.restart_timer();
It's misspelled in remove_writer as well ```suggestion // Once in this situation there is not much we can do but let asio timers expire immediately ```
}
// Some times the interval could be negative if a writer expired during the call to this function
+ // Once in this situation there is not much we can do but let asio timers expire immediately
auto interval = timer_owner_->time - steady_clock::now();
timer_.update_interval_millisec((double)duration_cast<milliseconds>(interval).count());
timer_.restart_timer(); |
codereview_cpp_data_3190 | // hook up stderr to a specially-named file
//
if (freopen(STDERR_FILE, "a", stderr) == NULL) {
}
// lower our priority if needed
If this fails, then 'stderr' is not a valid file handler anymore, and then any further 'write' operations will fail. Maybe some handling of such situation should be added here?
// hook up stderr to a specially-named file
//
if (freopen(STDERR_FILE, "a", stderr) == NULL) {
+ _exit(errno);
}
// lower our priority if needed |
codereview_cpp_data_3196 | {
// Get the transform from the station's frame to the other frame
SimTK::Vec3 currentLocation = get_location();
- return getReferenceFrame().findLocationInAnotherFrame(s, currentLocation, getModel().getGround());
}
SimTK::Vec3 Station::findVelocityInGround(const SimTK::State& s) const
The flavor here should be something like `mb.findStationAccelerationInGround(s, getReferenceFrame().findLocationInAnotherFrame(s, currentLocation, getReferenceFrame().getBaseFrame()))`. Not ACTUALLY this, b/c this is messy, but this is the flavor. Other people more familiar with such methods might have an idea of how to do this more cleanly. Same for velocity.
{
// Get the transform from the station's frame to the other frame
SimTK::Vec3 currentLocation = get_location();
+
+ // Get station's physical frame
+ const PhysicalFrame& frame = getReferenceFrame();
+ // Get the frame's mobilized body
+ auto& mb = frame.getMobilizedBody();
+
+ // Use simbody method to get the velocity in ground
+ return mb.findStationLocationInGround(s,currentLocation);
+
}
SimTK::Vec3 Station::findVelocityInGround(const SimTK::State& s) const |
codereview_cpp_data_3201 | }
if (!chat->title.empty())
{
- char tstr[chat->title.size() * 4 / 3 + 4];
Base64::btoa((const byte *)chat->title.data(), chat->title.size(), tstr);
cout << "\tTitle: " << tstr << endl;
}
}
Local buffer of variable size. This probably won't compile on all platforms.
}
if (!chat->title.empty())
{
+ char *tstr = new char[chat->title.size() * 4 / 3 + 4];
Base64::btoa((const byte *)chat->title.data(), chat->title.size(), tstr);
cout << "\tTitle: " << tstr << endl;
+ delete [] tstr;
}
} |
codereview_cpp_data_3205 | const shared_model::interface::types::AccountIdType &account_id,
const shared_model::interface::types::AssetIdType &asset_id,
const std::string &amount,
- const int precision) {
std::string query = (boost::format(
// clang-format off
R"(
Pass by reference?
const shared_model::interface::types::AccountIdType &account_id,
const shared_model::interface::types::AssetIdType &asset_id,
const std::string &amount,
+ const shared_model::interface::types::PrecisionType precision) {
std::string query = (boost::format(
// clang-format off
R"( |
codereview_cpp_data_3217 | ifs.close();
} else {
// show message:
- std::cout << "Can't open file " << filepath << "Log will not be created." << std::endl;
return;
}
m_filesink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(filepath);
Should use the logger: `log_warn(...)`. We could add a function like `Logger::fileSinkExists()` or `Logger::hasFileSink()` that the GUI could invoke to determine if the GUI should log to some user data directory. I think it's also fine for there to be no logging file when using the GUI-the content is in the Messages window, anyway.
ifs.close();
} else {
// show message:
+ warn("Can't open file {} for writing. Log will not be created.",
+ filepath);
return;
}
m_filesink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(filepath); |
codereview_cpp_data_3236 | ERR_ENTRY(S2N_ERR_INVALID_X509_EXTENSION_TYPE, "Invalid X509 extension type") \
ERR_ENTRY(S2N_ERR_INSUFFICIENT_MEM_SIZE, "The provided buffer size is not large enough to contain the output data. Try increasing the allocation size.") \
ERR_ENTRY(S2N_ERR_KEYING_MATERIAL_EXPIRED, "The lifetime of the connection keying material has exceeded the limit. Perform a new full handshake.") \
- ERR_ENTRY(S2N_ERR_REJECTED_EARLY_DATA, "Unable to decrypt rejected early data") \
/* clang-format on */
Is the only scenario for using this error code when we fail to decrypt the early data? If so, we could be more precise in the error code. If we don't want to be precise, consider removing the `decrypt` from the description and say `Rejected early data`?
ERR_ENTRY(S2N_ERR_INVALID_X509_EXTENSION_TYPE, "Invalid X509 extension type") \
ERR_ENTRY(S2N_ERR_INSUFFICIENT_MEM_SIZE, "The provided buffer size is not large enough to contain the output data. Try increasing the allocation size.") \
ERR_ENTRY(S2N_ERR_KEYING_MATERIAL_EXPIRED, "The lifetime of the connection keying material has exceeded the limit. Perform a new full handshake.") \
+ ERR_ENTRY(S2N_ERR_EARLY_DATA_TRIAL_DECRYT, "Unable to decrypt rejected early data") \
/* clang-format on */ |
codereview_cpp_data_3257 | #define GJK_MAX_ITERATIONS 128
#ifdef BT_USE_DOUBLE_PRECISION
- #define GJK_ACCURARY ((btScalar)1e-12)
#define GJK_MIN_DISTANCE ((btScalar)1e-12)
#define GJK_DUPLICATED_EPS ((btScalar)1e-12)
#else
- #define GJK_ACCURARY ((btScalar)0.0001)
#define GJK_MIN_DISTANCE ((btScalar)0.0001)
#define GJK_DUPLICATED_EPS ((btScalar)0.0001)
#endif //BT_USE_DOUBLE_PRECISION
Would this be a good time to fix the spelling? `GJK_ACCURARY` -> `GJK_ACCURACY` ?
#define GJK_MAX_ITERATIONS 128
#ifdef BT_USE_DOUBLE_PRECISION
+ #define GJK_ACCURACY ((btScalar)1e-12)
#define GJK_MIN_DISTANCE ((btScalar)1e-12)
#define GJK_DUPLICATED_EPS ((btScalar)1e-12)
#else
+ #define GJK_ACCURACY ((btScalar)0.0001)
#define GJK_MIN_DISTANCE ((btScalar)0.0001)
#define GJK_DUPLICATED_EPS ((btScalar)0.0001)
#endif //BT_USE_DOUBLE_PRECISION |
codereview_cpp_data_3258 | {
error e = (error)client->json.getint();
MegaApp *app = client->app;
- if(!e || e == API_ESID)
{
if (client->sctable)
{
I think that API_ESID can't be received as a command-level response, only as a request-level response.
{
error e = (error)client->json.getint();
MegaApp *app = client->app;
+ if(!e)
{
if (client->sctable)
{ |
codereview_cpp_data_3266 | }
/* Copy the CLIENT_HELLO -> SERVER_FINISHED hash.
- * We'll need it later to calculate the application secrets. */
- if (s2n_conn_get_current_message_type(conn) == SERVER_FINISHED) {
GUARD(s2n_tls13_conn_copy_server_finished_hash(conn));
}
Does this need to be called in other TLS versions? Should we check `conn->actual_protocol_version >= S2N_TLS13`?
}
/* Copy the CLIENT_HELLO -> SERVER_FINISHED hash.
+ * TLS1.3 will need it later to calculate the application secrets. */
+ if (s2n_connection_get_protocol_version(conn) >= S2N_TLS13 &&
+ s2n_conn_get_current_message_type(conn) == SERVER_FINISHED) {
GUARD(s2n_tls13_conn_copy_server_finished_hash(conn));
} |
codereview_cpp_data_3277 | void wlr_scene_node_reparent(struct wlr_scene_node *node,
struct wlr_scene_node *new_parent) {
if (node->parent == new_parent) {
return;
}
Do we want to allow a node without any parent? I think I'd rather not.
void wlr_scene_node_reparent(struct wlr_scene_node *node,
struct wlr_scene_node *new_parent) {
+ assert(node->type != WLR_SCENE_NODE_ROOT && new_parent != NULL);
+
if (node->parent == new_parent) {
return;
} |
codereview_cpp_data_3293 | const struct s2n_ecc_named_curve s2n_ecc_supported_curves[2] = {
{.iana_id = TLS_EC_CURVE_SECP_256_R1, .libcrypto_nid = NID_X9_62_prime256v1, .name = "secp256r1"},
- {.iana_id = TLS_EC_CURVE_SECP_384_R1, .libcrypto_nid = NID_secp384r1, .name="secp384r1"},
};
static EC_KEY *s2n_ecc_generate_own_key(const struct s2n_ecc_named_curve *named_curve);
nit: missing spaces around the equals
const struct s2n_ecc_named_curve s2n_ecc_supported_curves[2] = {
{.iana_id = TLS_EC_CURVE_SECP_256_R1, .libcrypto_nid = NID_X9_62_prime256v1, .name = "secp256r1"},
+ {.iana_id = TLS_EC_CURVE_SECP_384_R1, .libcrypto_nid = NID_secp384r1, .name= "secp384r1"},
};
static EC_KEY *s2n_ecc_generate_own_key(const struct s2n_ecc_named_curve *named_curve); |
codereview_cpp_data_3300 | PYPKGCONFIG="$( cd "$PYLIBDIR/../../pkgconfig" && pwd )"
export PKG_CONFIG_PATH="$PKG_CONFIG_PATH:$PYPKGCONFIG"
echo "found python pkg_config information: $PYPKGCONFIG"
- export PYTHON="${HOMEBREW_PREFIX}/bin/python"
fi
AM_PATH_PYTHON([2.7])
Are you sure we want hard overrides for these variables rather than setting them if unset? I'm not particularly familiar with homebrew, but, when I'm building stuff from source, I often need to set non-standard environment variables, and this might make custom builds a bit more difficult.
PYPKGCONFIG="$( cd "$PYLIBDIR/../../pkgconfig" && pwd )"
export PKG_CONFIG_PATH="$PKG_CONFIG_PATH:$PYPKGCONFIG"
echo "found python pkg_config information: $PYPKGCONFIG"
+ if [ "y$PYTHON" = y ] ; then
+ export PYTHON="${HOMEBREW_PREFIX}/bin/python"
+ fi
fi
AM_PATH_PYTHON([2.7]) |
codereview_cpp_data_3301 | const TypeIdentifier *type_id_complete = objectFactory->get_type_identifier(dpst->getName(), true);
const TypeObject *type_obj_complete = objectFactory->get_type_object(dpst->getName(), true);
objectFactory->add_type_object(dpst->getName(), type_id_complete, type_obj_complete); // Add complete
}
}
}
Has this function always to return `false`?
const TypeIdentifier *type_id_complete = objectFactory->get_type_identifier(dpst->getName(), true);
const TypeObject *type_obj_complete = objectFactory->get_type_object(dpst->getName(), true);
objectFactory->add_type_object(dpst->getName(), type_id_complete, type_obj_complete); // Add complete
+ return true;
}
}
} |
codereview_cpp_data_3302 | #include "common/byteutils.hpp"
#include "cryptography/crypto_provider/crypto_defaults.hpp"
-#include "cryptography/ed25519_sha3_impl/internal/sha3_hash.hpp"
using iroha::operator|;
Remove that header as well plz. Hash function can be replaced with custom blob
#include "common/byteutils.hpp"
#include "cryptography/crypto_provider/crypto_defaults.hpp"
+
+using namespace shared_model::crypto;
using iroha::operator|; |
codereview_cpp_data_3310 | }
else
{
rtps_participant_->update_attributes(rtps_participant_->getRTPSParticipantAttributes());
}
}
```suggestion // Trigger update of network interfaces by calling update_attributes rtps_participant_->update_attributes(rtps_participant_->getRTPSParticipantAttributes()); ```
}
else
{
+ // Trigger update of network interfaces by calling update_attributes
rtps_participant_->update_attributes(rtps_participant_->getRTPSParticipantAttributes());
}
} |
codereview_cpp_data_3313 | _engine->updatePalette( StandardPaletteIndexes() );
}
-#if SDL_VERSION_ATLEAST( 2, 0, 0 ) && !defined( __WIN32__ )
- fheroes2::Size Display::getOutputSize() const
- {
- SDL_DisplayMode DM;
- SDL_GetCurrentDisplayMode( 0, &DM );
- return fheroes2::Size( DM.w, DM.h );
- }
-#endif
bool Cursor::isFocusActive() const
{
return engine().isMouseCursorActive();
We should cache this variable at the time of switching into fullscreen mode. `SDL_GetCurrentDisplayMode` call is not an instant while we're calling this method thousands of times per second.
_engine->updatePalette( StandardPaletteIndexes() );
}
+
bool Cursor::isFocusActive() const
{
return engine().isMouseCursorActive(); |
codereview_cpp_data_3315 | // List the device outputs we wish to display during the simulation.
std::vector<std::string> kneeDeviceOutputs{ "tension", "height" };
- std::vector<std::string> controllerOutputs{ "myo_control" };
// Add a ConsoleReporter to report deviceOutputs.
//addDeviceConsoleReporterToModel(assistedHopper, *kneeDevice,
[Tagging] This looks like good motivation for #1118
// List the device outputs we wish to display during the simulation.
std::vector<std::string> kneeDeviceOutputs{ "tension", "height" };
+ std::vector<std::string> deviceControllerOutputs{ "myo_control" };
// Add a ConsoleReporter to report deviceOutputs.
//addDeviceConsoleReporterToModel(assistedHopper, *kneeDevice, |
codereview_cpp_data_3323 | } // namespace gui
-} // namespace sofa
\ No newline at end of file
I think your editor remove empty line at end of file. I don't know if this is still an issue on linux?
} // namespace gui
\ No newline at end of file
+} // namespace sofa |
codereview_cpp_data_3327 | case HPDT_AUTOTRADE_VEND:
ret->HPDataSRCPtr = (void**)(&((struct autotrade_vending *)ptr)->hdata);
ret->hdatac = &((struct autotrade_vending *)ptr)->hdatac;
case HPDT_BGDATA:
ret->HPDataSRCPtr = (void**)(&((struct battleground_data *)ptr)->hdata);
ret->hdatac = &((struct battleground_data *)ptr)->hdatac;
Missing a `break;`!
case HPDT_AUTOTRADE_VEND:
ret->HPDataSRCPtr = (void**)(&((struct autotrade_vending *)ptr)->hdata);
ret->hdatac = &((struct autotrade_vending *)ptr)->hdatac;
+ break;
case HPDT_BGDATA:
ret->HPDataSRCPtr = (void**)(&((struct battleground_data *)ptr)->hdata);
ret->hdatac = &((struct battleground_data *)ptr)->hdatac; |
codereview_cpp_data_3333 | Steps for Matrix Expo
1. Create vector F1 : which is the copy of B.
-2. Create transpose matrix (Learn more abput it on the llernet)
3. Perform T^(n-1) [transpose matrix to the power n-1]
4. Multiply with F to get the last matrix of size (1xk).
The first element of this matrix is the required result.
about and Internet are both misspelled.
Steps for Matrix Expo
1. Create vector F1 : which is the copy of B.
+2. Create transpose matrix (Learn more about it on the internet)
3. Perform T^(n-1) [transpose matrix to the power n-1]
4. Multiply with F to get the last matrix of size (1xk).
The first element of this matrix is the required result. |
codereview_cpp_data_3341 | #ifdef ENABLE_SYNC
if (e.getErrorCode() == API_EBUSINESSPASTDUE)
{
- //Ideally, this piece of code should be in MegaClient, but that would entail handling it for every request
client->disableSyncs(BUSINESS_EXPIRED);
}
#endif
This block can be moved to the new `checkError()`, which is called upon response for every single API command. That way, for any command, if the error is `API_EBUSINESSPASTDUE`, it will be managed inside the SDK and not at the intermediate layer.
#ifdef ENABLE_SYNC
if (e.getErrorCode() == API_EBUSINESSPASTDUE)
{
+ //Ideally, this piece of code should be in MegaClient, but that would entail handling it for every request //TODO move to checkError after merging develop
client->disableSyncs(BUSINESS_EXPIRED);
}
#endif |
codereview_cpp_data_3349 | }
}
void test_tree() {
node *root = new node;
root->val = 4;
should perform self-check without manual intervention; something like below: ```cpp for(int i = 1; i < 8; i++) assert(root[i] == i); ```
}
}
+int arr[7] = { 0 };//for test tree use only
+int index = 0;//for test tree use only
+void testInOrderTraverse(node* n) {
+ if (n != NULL) {
+ testInOrderTraverse(n->left);
+ std::cout << n->val << " ";
+ arr[index++] = n->val;
+ testInOrderTraverse(n->right);
+ }
+}
+
void test_tree() {
node *root = new node;
root->val = 4; |
codereview_cpp_data_3350 | double *T = new double[vT->m_AvailableSteps * readsize[0] * readsize[1]];
// Create a 2D selection for the subset
- vT->SetSelection(offset_size_t, readsize_size_t);
vT->SetStepSelection(0, vT->m_AvailableSteps);
// Arrays are read by scheduling one or more of them
@JasonRuonanWang please follow @chuckatkins advice, the entire C++ (and C) API is based on size_t....For example, here the new operator expects a size_t input: new double[ size_t ] (same with malloc in C), but we we are casting from uint64_t.
double *T = new double[vT->m_AvailableSteps * readsize[0] * readsize[1]];
// Create a 2D selection for the subset
+ vT->SetSelection(offset, readsize);
vT->SetStepSelection(0, vT->m_AvailableSteps);
// Arrays are read by scheduling one or more of them |
codereview_cpp_data_3359 | //TODO add all the global variables to one object in the IDF
IdfObject idfObject(openstudio::IddObjectType::EnergyManagementSystem_GlobalVariable);
m_idfObjects.push_back(idfObject);
- m_map.insert(std::make_pair(modelObject.handle(), idfObject));
//AddErlVariable
s = modelObject.name();
Why are you doing this here? Isn't this done in translateAndMapModelObject?
//TODO add all the global variables to one object in the IDF
IdfObject idfObject(openstudio::IddObjectType::EnergyManagementSystem_GlobalVariable);
m_idfObjects.push_back(idfObject);
+ //m_map.insert(std::make_pair(modelObject.handle(), idfObject));
//AddErlVariable
s = modelObject.name(); |
codereview_cpp_data_3360 | const char * origTrueValue;
const char * origFalseValue;
- bool restoreAs = data->booleanRestore >= 0;
if (value[0] == '1' && value[1] == '\0')
{
- if (restoreAs)
{
keySetMeta (key, "origvalue", data->booleans[data->booleanRestore].trueValue);
}
Inconsistent naming: restoreAs on the left side, Restore on the right side.
const char * origTrueValue;
const char * origFalseValue;
+ bool restore = data->booleanRestore >= 0;
if (value[0] == '1' && value[1] == '\0')
{
+ if (restore)
{
keySetMeta (key, "origvalue", data->booleans[data->booleanRestore].trueValue);
} |
codereview_cpp_data_3366 | m_sbes_array[gindex + i1mindex + j] = m_sbes_array[gindex + i1mindex + j - 2] -
(2 * j - 1) / rb * m_sbes_array[gindex + i1mindex + j - 1];
- exts = m_sbes_array[gindex + (i - 1) * mindex + j - 2] -
(2 * j - 1) / rb * m_sbes_array[gindex + i1mindex + j - 1];
m_sbes_darray[gindex + i1mindex + 0] = sb;
Could replace (i-1)*mindex with m1index here too?
m_sbes_array[gindex + i1mindex + j] = m_sbes_array[gindex + i1mindex + j - 2] -
(2 * j - 1) / rb * m_sbes_array[gindex + i1mindex + j - 1];
+ exts = m_sbes_array[gindex + i1mindex + j - 2] -
(2 * j - 1) / rb * m_sbes_array[gindex + i1mindex + j - 1];
m_sbes_darray[gindex + i1mindex + 0] = sb; |
codereview_cpp_data_3371 | }
/*
- * flb_sds_snprintf_realloc is a wrapper of snprintf.
* The difference is that this function can increase the buffer of flb_sds_t.
*/
-int flb_sds_snprintf_realloc(flb_sds_t *str, size_t size, const char *fmt, ...)
{
va_list va;
flb_sds_t tmp;
I think this function is not necessary and we can simply rely on flb_sds_printf() functionality. flb_sds_t by default always reallocate if necessary, and calculating the final length can be done with flb_sds_len()
}
/*
+ * flb_sds_snprintf is a wrapper of snprintf.
* The difference is that this function can increase the buffer of flb_sds_t.
*/
+int flb_sds_snprintf(flb_sds_t *str, size_t size, const char *fmt, ...)
{
va_list va;
flb_sds_t tmp; |
codereview_cpp_data_3372 | #include "lbann/utils/lbann_library.hpp"
#include "lbann/callbacks/callback_checkpoint.hpp"
-#include "lbann/data_store/data_store_jag.hpp"
namespace lbann {
Why do you need to load a specific data reader in lbann_library?
#include "lbann/utils/lbann_library.hpp"
#include "lbann/callbacks/callback_checkpoint.hpp"
namespace lbann { |
codereview_cpp_data_3383 | #include "../Empire/EmpireManager.h"
#include "../Empire/Supply.h"
-#include <boost/algorithm/cxx11/all_of.hpp>
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/bind.hpp>
#include <boost/graph/adjacency_list.hpp>
why boost not std?
#include "../Empire/EmpireManager.h"
#include "../Empire/Supply.h"
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/bind.hpp>
#include <boost/graph/adjacency_list.hpp> |
codereview_cpp_data_3390 | "Number of bytes logged since service start");
METRIC_DEFINE_counter(tablet, log_wal_size, "Size of WAL Files",
- yb::MetricUnit::kUnits,
"Size of wal files");
METRIC_DEFINE_histogram(tablet, log_sync_latency, "Log Sync Latency",
Lets make the units kBytes.
"Number of bytes logged since service start");
METRIC_DEFINE_counter(tablet, log_wal_size, "Size of WAL Files",
+ yb::MetricUnit::kBytes,
"Size of wal files");
METRIC_DEFINE_histogram(tablet, log_sync_latency, "Log Sync Latency", |
codereview_cpp_data_3393 | * @returns 0 on exit
*/
int main() {
// the complete string
const std::string s = "applepenapple";
// the dictionary to be used
```suggestion test(); // call the test function :) // the complete string ```
* @returns 0 on exit
*/
int main() {
+ test(); // call the test function :)
+
// the complete string
const std::string s = "applepenapple";
// the dictionary to be used |
codereview_cpp_data_3396 | static string signupemail, signupname;
// true by default, to register a new account v2 (false means account v1)
-bool signupV2;
// signup code being confirmed
static string signupcode;
Maybe we want to initialize to true as default value. ```suggestion bool signupV2 = true; ```
static string signupemail, signupname;
// true by default, to register a new account v2 (false means account v1)
+bool signupV2 = true;
// signup code being confirmed
static string signupcode; |
codereview_cpp_data_3413 | skill->level_set_value(tmp_db.num, 1); // Default 1
/* Interrupt Cast */
- if (libconfig->setting_lookup_bool(conf, "InterruptCast", &tmp_db.castcancel) == CONFIG_FALSE)
- tmp_db.castcancel = 0;
/* Cast Defense Rate */
libconfig->setting_lookup_int(conf, "CastDefRate", &tmp_db.cast_def_rate);
Didn't we decide this defaults to true? `InterruptCast: Cast Interruption (bool, defaults to true)`
skill->level_set_value(tmp_db.num, 1); // Default 1
/* Interrupt Cast */
+ if (libconfig->setting_lookup_bool(conf, "InterruptCast", &tmp_db.castcancel) == 0)
+ tmp_db.castcancel = 1;
/* Cast Defense Rate */
libconfig->setting_lookup_int(conf, "CastDefRate", &tmp_db.cast_def_rate); |
codereview_cpp_data_3416 | DEV_TIMED_ABOVE("Stop worker", 100)
while (m_state != WorkerState::Stopped)
{
- m_state_notifier.wait_for(l, chrono::microseconds(5));
- this_thread::sleep_for(chrono::milliseconds(20));
}
}
}
I think this sleep_for is useless.
DEV_TIMED_ABOVE("Stop worker", 100)
while (m_state != WorkerState::Stopped)
{
+ m_state_notifier.wait(l);
}
}
} |
codereview_cpp_data_3422 | {
allocated = TO_TADDR(heap.alloc_allocated);
}
- if (taddrObj >= TO_TADDR(dacpSeg.mem) && taddrObj && taddrObj < allocated)
{
rngSeg.segAddr = (TADDR)dacpSeg.segmentAddr;
rngSeg.start = (TADDR)dacpSeg.mem;
can we change this to `if (taddrObj >= TO_TADDR(dacpSeg.mem) && taddrObj < allocated)` ?
{
allocated = TO_TADDR(heap.alloc_allocated);
}
+ if (taddrObj >= TO_TADDR(dacpSeg.mem) && taddrObj < allocated)
{
rngSeg.segAddr = (TADDR)dacpSeg.segmentAddr;
rngSeg.start = (TADDR)dacpSeg.mem; |
codereview_cpp_data_3429 | deleteNode = true;
}
- mThread = std::thread ([this, deleteNode, node]() {
LocalPath path;
if (transfer->getParentPath())
{
Mutual exclusion violated here.
deleteNode = true;
}
+ std::thread thread([this, deleteNode, node]() {
LocalPath path;
if (transfer->getParentPath())
{ |
codereview_cpp_data_3450 | for (const auto& [key, value] : r) {
auto us = duration_cast<microseconds>(value.duration).count();
auto rate = value.events * 1'000'000 / us;
- record(self, key+".events", value.events);
- record(self, key+".duration", us);
- record(self, key+".rate", rate);
}
},
[=](flush_atom) {
Binary operators, such as `+`, have spacing between their operands in our style guide.
for (const auto& [key, value] : r) {
auto us = duration_cast<microseconds>(value.duration).count();
auto rate = value.events * 1'000'000 / us;
+ record(self, key + ".events", value.events);
+ record(self, key + ".duration", us);
+ record(self, key + ".rate", rate);
}
},
[=](flush_atom) { |
codereview_cpp_data_3451 | #include "s2n_test.h"
#include "testlib/s2n_testlib.h"
-#include <fcntl.h>
-
static uint32_t write_pem_file_to_stuffer_as_chain(struct s2n_stuffer *chain_out_stuffer, const char *pem_data) {
struct s2n_stuffer chain_in_stuffer, cert_stuffer, temp_out_stuffer;
s2n_stuffer_alloc_ro_from_string(&chain_in_stuffer, pem_data);
The keyboard mash is fine, but if you're interested; I think that '\0' and "/" are formally invalid filenames that are forbidden to exist on POSIX systems. That said, they may not really test what you want, I'm not sure what error code they return.
#include "s2n_test.h"
#include "testlib/s2n_testlib.h"
static uint32_t write_pem_file_to_stuffer_as_chain(struct s2n_stuffer *chain_out_stuffer, const char *pem_data) {
struct s2n_stuffer chain_in_stuffer, cert_stuffer, temp_out_stuffer;
s2n_stuffer_alloc_ro_from_string(&chain_in_stuffer, pem_data); |
codereview_cpp_data_3452 | #include <stdlib.h>
#include <limits.h>
-#ifndef _MSC_VER
-#define MAY_HAVE_FTRUNCATE
-#include <unistd.h>
-#endif
-
#ifdef READTAGS_DSL
#define xMalloc(n,Type) (Type *)eMalloc((size_t)(n) * sizeof (Type))
#define xRealloc(p,n,Type) (Type *)eRealloc((p), (n) * sizeof (Type))
Isn't this line redundant? If `WIN32` isn't defined, `_MSC_VER` won't be defined.
#include <stdlib.h>
#include <limits.h>
#ifdef READTAGS_DSL
#define xMalloc(n,Type) (Type *)eMalloc((size_t)(n) * sizeof (Type))
#define xRealloc(p,n,Type) (Type *)eRealloc((p), (n) * sizeof (Type)) |
codereview_cpp_data_3481 | { 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2 },
{ 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2 }
};
- unsigned char urtoll[5] = { 6, 7, 8, 9, 10 };
- unsigned char ultolr[5] = { 6, 5, 4, 3, 2 };
- unsigned char lltour[5] = { 14, 13, 12, 11, 10 };
- unsigned char lrtoul[5] = { 14, 15, 0, 1, 2 };
int mx, my, md;
mx = abs(x2 - x1);
Use `BYTE` instead of `unsigned char`.
{ 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2 },
{ 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2 }
};
+ BYTE urtoll[5] = { 6, 7, 8, 9, 10 };
+ BYTE ultolr[5] = { 6, 5, 4, 3, 2 };
+ BYTE lltour[5] = { 14, 13, 12, 11, 10 };
+ BYTE lrtoul[5] = { 14, 15, 0, 1, 2 };
int mx, my, md;
mx = abs(x2 - x1); |
codereview_cpp_data_3502 | << "DefaultPipeline::doCollisionReset" ;
// clear all contacts
- if (contactManager!=nullptr)
{
const helper::vector<Contact::SPtr>& contacts = contactManager->getContacts();
for (const auto& contact : contacts)
Could you remember me how does the contact manager can return null contacts? Shouldn't be its job to make sure returned contacts are valid?
<< "DefaultPipeline::doCollisionReset" ;
// clear all contacts
+ if (contactManager != nullptr)
{
const helper::vector<Contact::SPtr>& contacts = contactManager->getContacts();
for (const auto& contact : contacts) |
codereview_cpp_data_3508 | const std::string DISCOVERY_QUESTION = "Yo, can I play Free-O here, dog?";
const std::string DISCOVERY_ANSWER = "Word!";
#ifdef FREEORION_OPENBSD
const int SOCKET_LINGER_TIME = 1 << (sizeof(unsigned short) * 4 - 1);
#else
const int SOCKET_LINGER_TIME = 1 << (sizeof(unsigned short) * 8 - 1);
What is the point of this condition? Why does OpenBSD need a different linger time?
const std::string DISCOVERY_QUESTION = "Yo, can I play Free-O here, dog?";
const std::string DISCOVERY_ANSWER = "Word!";
#ifdef FREEORION_OPENBSD
+ // Needs to set shorter linger time on OpenBSD to be able to start the session
const int SOCKET_LINGER_TIME = 1 << (sizeof(unsigned short) * 4 - 1);
#else
const int SOCKET_LINGER_TIME = 1 << (sizeof(unsigned short) * 8 - 1); |
codereview_cpp_data_3511 | POSIX_ENSURE_REF(conn);
POSIX_GUARD(s2n_connection_free_managed_send_io(conn));
conn->send_io_context = ctx;
- return 0;
}
int s2n_connection_set_recv_cb(struct s2n_connection *conn, s2n_recv_fn recv)
This is the only one you didn't update ;) ```suggestion conn->send_io_context = ctx; return S2N_SUCCESS; ```
POSIX_ENSURE_REF(conn);
POSIX_GUARD(s2n_connection_free_managed_send_io(conn));
conn->send_io_context = ctx;
+ return S2N_SUCCESS;
}
int s2n_connection_set_recv_cb(struct s2n_connection *conn, s2n_recv_fn recv) |
codereview_cpp_data_3512 | {
}
-//_____________________________________________________________________________
-/**
-* Copy constructor.
-*
-* @param aWrapDoubleCylinderObst WrapDoubleCylinderObst to be copied.
-*/
-WrapDoubleCylinderObst::WrapDoubleCylinderObst(const WrapDoubleCylinderObst& aWrapDoubleCylinderObst)
-{
- constructProperties();
-}
-
//=============================================================================
// CONSTRUCTION METHODS
This copy constructor should not be needed. Right now, it's doing the wrong thing because it's not copying any of the properties. It would be better to use the default copy constructor.
{
}
//=============================================================================
// CONSTRUCTION METHODS |
codereview_cpp_data_3534 | SP_ADD_CLASS_IN_FACTORY(TriangleSetTopologyModifier,sofa::component::topology::TriangleSetTopologyModifier)
/// Custom Exception
- const char* name = "Sofa.SofaException";
- const char* doc = "Base exception class for the SofaPython module." ;
PyObject* PyExc_SofaException = PyErr_NewExceptionWithDoc(
(char*) "Sofa.SofaException",
(char*) "Base exception class for the SofaPython module.",
Were those variables (name and doc) supposed to be use somewhere?
SP_ADD_CLASS_IN_FACTORY(TriangleSetTopologyModifier,sofa::component::topology::TriangleSetTopologyModifier)
/// Custom Exception
PyObject* PyExc_SofaException = PyErr_NewExceptionWithDoc(
(char*) "Sofa.SofaException",
(char*) "Base exception class for the SofaPython module.", |
codereview_cpp_data_3535 | public:
CommandExecutorTest() {
domain_id = "domain";
- account_id = "id@" + domain_id;
role_permissions.set(
shared_model::interface::permissions::Role::kAddMySignatory);
`"id"` repeats several times as well - maybe move it to named constant?
public:
CommandExecutorTest() {
domain_id = "domain";
+ name = "id";
+ account_id = name + "@" + domain_id;
role_permissions.set(
shared_model::interface::permissions::Role::kAddMySignatory); |
codereview_cpp_data_3539 | if ( System::IsFile( *it ) ) {
if ( conf.Read( *it ) ) {
isValidConfigurationFile = true;
- std::string sval;
- sval = conf.externalMusicCommand();
- if ( !sval.empty() )
- Music::SetExtCommand( sval );
break;
}
Please rename `sval` to something more valuable like `externalCommand` and make it const reference to avoid object copy.
if ( System::IsFile( *it ) ) {
if ( conf.Read( *it ) ) {
isValidConfigurationFile = true;
+ const std::string & externalCommand = conf.externalMusicCommand();
+ if ( !externalCommand.empty() )
+ Music::SetExtCommand( externalCommand );
break;
} |
codereview_cpp_data_3540 | }
query q;
q.cmd = query::erase{};
- auto rp = self->make_response_promise<atom::done>();
- return rp.delegate(self->state.store, q, all_ids);
},
[self](atom::status,
status_verbosity /*v*/) -> caf::config_value::dictionary {
Isn't this just `self->delegate`?
}
query q;
q.cmd = query::erase{};
+ return self->delegate(self->state.store, atom::erase_v,
+ std::move(all_ids));
},
[self](atom::status,
status_verbosity /*v*/) -> caf::config_value::dictionary { |
codereview_cpp_data_3548 | const Actions & plannedActions = _battlePlanner.planUnitTurn( arena, currentUnit );
actions.insert( actions.end(), plannedActions.begin(), plannedActions.end() );
// Do not end the turn if we only cast a spell
- if ( !( plannedActions.size() == 1 && plannedActions.front().isType( MSG_BATTLE_CAST ) ) )
actions.emplace_back( MSG_BATTLE_END_TURN, currentUnit.GetUID() );
}
}
Could you please apply opposite logic withon operator NOT as the operator might be easily missed during code reading: ``` if ( plannedActions.size() != 1 || !plannedActions.front().isType( MSG_BATTLE_CAST ) ) ```
const Actions & plannedActions = _battlePlanner.planUnitTurn( arena, currentUnit );
actions.insert( actions.end(), plannedActions.begin(), plannedActions.end() );
// Do not end the turn if we only cast a spell
+ if ( plannedActions.size() != 1 || !plannedActions.front().isType( MSG_BATTLE_CAST ) )
actions.emplace_back( MSG_BATTLE_END_TURN, currentUnit.GetUID() );
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.