id
stringlengths
21
25
content
stringlengths
164
2.33k
codereview_cpp_data_5081
if(node) { // After speculative instant completion removal, this is not needed (always sent via actionpacket code) - client->syncs.forEachRunningSync([&](Sync* s) { - if (s->localroot->node && - node->isbelow(s->localroot->node)) - { - client->app->syncupdate_remote_rename(s, node, pa.c_str()); - } }); } } We might want to refactor this: forEachSyncContainingNode(node, [&](Sync *s){....} if(node) { // After speculative instant completion removal, this is not needed (always sent via actionpacket code) + client->syncs.forEachRunningSyncContainingNode(node, [&](Sync* s) { + client->app->syncupdate_remote_rename(s, node, pa.c_str()); }); } }
codereview_cpp_data_5097
// Keep this CUIWnd entirely inside the application window. available_size = GG::Pt(app->AppWidth(), app->AppHeight()); } else { - available_size = GG::Pt( GG::X(HumanClientApp::MaximumPossibleWidth()), - GG::Y(HumanClientApp::MaximumPossibleHeight())); ErrorLogger() << "CUIWnd::SizeMove() could not get app instance!"; } no space before GG::X // Keep this CUIWnd entirely inside the application window. available_size = GG::Pt(app->AppWidth(), app->AppHeight()); } else { + available_size = GG::Pt(GG::X(HumanClientApp::MaximumPossibleWidth()), + GG::Y(HumanClientApp::MaximumPossibleHeight())); ErrorLogger() << "CUIWnd::SizeMove() could not get app instance!"; }
codereview_cpp_data_5115
QPixmap UserLevelPixmapGenerator::generatePixmap(int height, UserLevelFlags userLevel, bool isBuddy, QString privLevel) { - int privkeysize = privLevel.size(); - if (privLevel.size() == 0) - privkeysize = 1; - int key = height * 10000 + (int)userLevel + (int)isBuddy + privkeysize; if (pmCache.contains(key)) return pmCache.value(key); This can easily collide as userLevel, isBuddy, and privkeysize are all single numbers... Try changing to something like `int key = height * 10000 + (int)userLevel*88 + (int)isBuddy*54 + privkeysize*31;` QPixmap UserLevelPixmapGenerator::generatePixmap(int height, UserLevelFlags userLevel, bool isBuddy, QString privLevel) { + QString key = QString::number(height * 10000 + (int)userLevel + (int)isBuddy) + privLevel; if (pmCache.contains(key)) return pmCache.value(key);
codereview_cpp_data_5119
#include <iostream> #include <climits> -#include<vector> int maxSubArraySum(std::vector <int> a) { int max_so_far = INT_MIN, max_ending_here = 0; ```suggestion #include <vector> ``` #include <iostream> #include <climits> +#include <vector> int maxSubArraySum(std::vector <int> a) { int max_so_far = INT_MIN, max_ending_here = 0;
codereview_cpp_data_5122
int TryAddRawGroupKern(struct splinefont *sf, int isv, struct glif_name_index *class_name_pair_hash, int *current_groupkern_index_p, struct ff_rawoffsets **current_groupkern_p, const char *left, const char *right, int offset) { char *pairtext; int success = 0; - if (left && right && ((pairtext = smprintf("%s %s", left, right)) != NULL) && pairtext) { if (!glif_name_search_glif_name(class_name_pair_hash, pairtext)) { glif_name_track_new(class_name_pair_hash, (*current_groupkern_index_p)++, pairtext); struct ff_rawoffsets *tmp_groupkern = calloc(1, sizeof(struct ff_rawoffsets)); Double `pairtext` check here. int TryAddRawGroupKern(struct splinefont *sf, int isv, struct glif_name_index *class_name_pair_hash, int *current_groupkern_index_p, struct ff_rawoffsets **current_groupkern_p, const char *left, const char *right, int offset) { char *pairtext; int success = 0; + if (left && right && ((pairtext = smprintf("%s %s", left, right)) != NULL)) { if (!glif_name_search_glif_name(class_name_pair_hash, pairtext)) { glif_name_track_new(class_name_pair_hash, (*current_groupkern_index_p)++, pairtext); struct ff_rawoffsets *tmp_groupkern = calloc(1, sizeof(struct ff_rawoffsets));
codereview_cpp_data_5125
idfObject.setName(*s); } - idfObject.setString(EnergyManagementSystem_MeteredOutputVariableFields::EMSVariableName, modelObject.eMSVariableName()); idfObject.setString(EnergyManagementSystem_MeteredOutputVariableFields::UpdateFrequency, modelObject.updateFrequency()); - s = modelObject.eMSProgramorSubroutineName(); if (s.is_initialized()) { idfObject.setString(EnergyManagementSystem_MeteredOutputVariableFields::EMSProgramorSubroutineName, s.get()); } Why store the name? Usually this would be a pointer to the object. Is this because you don't have a base class for Program/Subroutine and have two distinct objects for the same thing? It seems like you sometimes store UUIDs and other times the Name in various objects. idfObject.setName(*s); } + idfObject.setString(EnergyManagementSystem_MeteredOutputVariableFields::EMSVariableName, modelObject.emsVariableName()); idfObject.setString(EnergyManagementSystem_MeteredOutputVariableFields::UpdateFrequency, modelObject.updateFrequency()); + s = modelObject.emsProgramOrSubroutineName(); if (s.is_initialized()) { idfObject.setString(EnergyManagementSystem_MeteredOutputVariableFields::EMSProgramorSubroutineName, s.get()); }
codereview_cpp_data_5129
const char *NetworkAddress::GetHostname() { if (StrEmpty(this->hostname) && this->address.ss_family != AF_UNSPEC) { - /* Use real address struct size because Emscripten fails when given sockaddr_storage size. */ - int size = this->address.ss_family == AF_INET6 ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in); - getnameinfo((struct sockaddr *)&this->address, size, this->hostname, sizeof(this->hostname), nullptr, 0, NI_NUMERICHOST); } return this->hostname; } why this change? seems like it should be explained sufficiently and split into its own commit (and this->address_length removed?) const char *NetworkAddress::GetHostname() { if (StrEmpty(this->hostname) && this->address.ss_family != AF_UNSPEC) { + assert(this->address_length != 0); + getnameinfo((struct sockaddr *)&this->address, this->address_length, this->hostname, sizeof(this->hostname), nullptr, 0, NI_NUMERICHOST); } return this->hostname; }
codereview_cpp_data_5131
} break; - case MAKENAMEID4('s', 'm', 's', 'v'): - if (!client->json.storeobject(&smsv)) - { - return client->app->userdata_result(NULL, NULL, NULL, jid, API_EINTERNAL); - } - break; - case EOO: if (v) { Why are we parsing this parameter?? it's used nowhere. Does `smsv` value represent the phone-number configured by the user for SMS verification? I don't know. However, the API command `smsv` is used to verify a received code, so it's strange to me to see it in the `CommandGetUserData` } break; case EOO: if (v) {
codereview_cpp_data_5134
return conn->session_id_len; } -int s2n_connection_get_session_id(struct s2n_connection *conn, uint8_t *session_id) -{ - notnull_check(conn); - notnull_check(session_id); - - uint32_t session_id_len = s2n_connection_get_session_id_length(conn); - memcpy_check(session_id, conn->session_id, session_id_len); - - return session_id_len; -} - int s2n_connection_set_blinding(struct s2n_connection *conn, s2n_blinding blinding) { conn->blinding = blinding; Most s2n APIs provide max_length in arguments to avoid buffer overrun. return conn->session_id_len; } int s2n_connection_set_blinding(struct s2n_connection *conn, s2n_blinding blinding) { conn->blinding = blinding;
codereview_cpp_data_5140
void PictureLoaderWorker::picDownloadFailed() { if (cardBeingDownloaded.nextUrl() || cardBeingDownloaded.nextSet()) { mutex.lock(); loadQueue.prepend(cardBeingDownloaded); Note to future myself: this works because the || operator is short-circuiting: if the first operand is true, the second operand is not evaluated. void PictureLoaderWorker::picDownloadFailed() { + /* Take advantage of short circuiting here to call the nextUrl until one + is not available. Only once nextUrl evaluates to false will this move + on to nextSet. If the Urls for a particular card are empty, this will + effectively go through the sets for that card. */ if (cardBeingDownloaded.nextUrl() || cardBeingDownloaded.nextSet()) { mutex.lock(); loadQueue.prepend(cardBeingDownloaded);
codereview_cpp_data_5144
{ int p1, p2; - object[i]._oDoorFlag = 1; if (ot == 1) { p1 = dPiece[x][y]; p2 = dPiece[x][y - 1]; This should be changed to BOOL { int p1, p2; + object[i]._oDoorFlag = TRUE; if (ot == 1) { p1 = dPiece[x][y]; p2 = dPiece[x][y - 1];
codereview_cpp_data_5165
{ // The original CDRMessage buffer (msg) now points to the proprietary temporary CDRMessage buffer (crypto_msg_). // This way the already decoded proprietary buffer is processed while it is being modified. - *msg = CDRMessage_t(crypto_msg_); } #endif // if HAVE_SECURITY This is creating a copy of the buffer, allocating and copying it. I would add a method to `CDRMessage_t` ``` void wrap_from( const CDRMessage_t& other) { buffer = other.buffer; pos = other.pos; max_size = other.max_size; reserved_size = other.reserved_size; length = other.length; msg_endian = other.msg_endian; wraps = true; } ``` And then call here: ```suggestion msg->wrap_from(*auxiliary_buffer); ``` { // The original CDRMessage buffer (msg) now points to the proprietary temporary CDRMessage buffer (crypto_msg_). // This way the already decoded proprietary buffer is processed while it is being modified. + msg = auxiliary_buffer; + auxiliary_buffer = &crypto_submsg_; } #endif // if HAVE_SECURITY
codereview_cpp_data_5166
psb->m_cfg.kDF = .1; psb->m_cfg.collisions = btSoftBody::fCollision::SDF_RD; getDeformableDynamicsWorld()->addSoftBody(psb); - getDeformableDynamicsWorld()->addForce(psb, new btDeformableMassSpringForce(2, 0.01, false)); - getDeformableDynamicsWorld()->addForce(psb, new btDeformableGravityForce(gravity)); } m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld); those forces are never deleted. please do so in exitPhysics psb->m_cfg.kDF = .1; psb->m_cfg.collisions = btSoftBody::fCollision::SDF_RD; getDeformableDynamicsWorld()->addSoftBody(psb); + + btDeformableMassSpringForce* mass_spring = new btDeformableMassSpringForce(2, 0.01, false); + getDeformableDynamicsWorld()->addForce(psb, mass_spring); + forces.push_back(mass_spring); + + btDeformableGravityForce* gravity_force = new btDeformableGravityForce(gravity); + getDeformableDynamicsWorld()->addForce(psb, gravity_force); + forces.push_back(gravity_force); } m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld);
codereview_cpp_data_5170
static int s2n_conn_update_handshake_hashes(struct s2n_connection *conn, struct s2n_blob *data) { GUARD(s2n_hash_update(&conn->handshake.md5, data->data, data->size)); if (s2n_hash_is_available(S2N_HASH_MD5_SHA1)) { Why was this check removed? static int s2n_conn_update_handshake_hashes(struct s2n_connection *conn, struct s2n_blob *data) { + /* The handshake MD5 hash state will fail the s2n_hash_is_available() check + * since MD5 is not permitted in FIPS mode. This check will not be used as + * the handshake MD5 hash state is specifically used by the TLS 1.0 and TLS 1.1 + * PRF, which is required to comply with the TLS 1.0 and 1.1 RFCs and is approved + * as per NIST Special Publication 800-52 Revision 1. + */ GUARD(s2n_hash_update(&conn->handshake.md5, data->data, data->size)); if (s2n_hash_is_available(S2N_HASH_MD5_SHA1)) {
codereview_cpp_data_5181
PROJECT* p = projects[i]; if (p->possibly_backed_off && now > p->min_rpc_time) { p->possibly_backed_off = false; - char buf[256]; - snprintf(buf, sizeof(buf), "Backoff ended for %.128s", p->get_project_name()); request_work_fetch(buf); } } I'd better increase `buf` length to MAXPATHLEN and not cut p->get_project_name() output twice PROJECT* p = projects[i]; if (p->possibly_backed_off && now > p->min_rpc_time) { p->possibly_backed_off = false; + char buf[1024]; + snprintf(buf, sizeof(buf), "Backoff ended for %s", p->get_project_name()); request_work_fetch(buf); } }
codereview_cpp_data_5214
ERR_ENTRY(S2N_ERR_ARRAY_INDEX_OOB, "Array index out of bounds") \ ERR_ENTRY(S2N_ERR_FREE_STATIC_BLOB, "Cannot free a static blob") \ ERR_ENTRY(S2N_ERR_RESIZE_STATIC_BLOB, "Cannot resize a static blob") \ - ERR_ENTRY(S2N_ERR_LIBCRYPTO_NOT_SUPPORTED, "Cannot use this LibCrypto for the requested operation") \ ERR_ENTRY(S2N_ERR_NO_ALERT, "No Alert present") \ ERR_ENTRY(S2N_ERR_CLIENT_MODE, "operation not allowed in client mode") \ ERR_ENTRY(S2N_ERR_CLIENT_MODE_DISABLED, "client connections not allowed") \ We should be extra clear about whether this is s2n being incompatible with a specific LibCrypto, or a specific LibCrypto that doesn't support an operation that other LibCrypto's do support. Also, if it's the latter, the error could be clearer as well `S2N_ERR_NO_AVAILABLE_{BORINGSSL/LIBRESSL/OPENSSL}_API` ERR_ENTRY(S2N_ERR_ARRAY_INDEX_OOB, "Array index out of bounds") \ ERR_ENTRY(S2N_ERR_FREE_STATIC_BLOB, "Cannot free a static blob") \ ERR_ENTRY(S2N_ERR_RESIZE_STATIC_BLOB, "Cannot resize a static blob") \ + ERR_ENTRY(S2N_ERR_NO_AVAILABLE_BORINGSSL_API, "BoringSSL does not support this API") \ ERR_ENTRY(S2N_ERR_NO_ALERT, "No Alert present") \ ERR_ENTRY(S2N_ERR_CLIENT_MODE, "operation not allowed in client mode") \ ERR_ENTRY(S2N_ERR_CLIENT_MODE_DISABLED, "client connections not allowed") \
codereview_cpp_data_5222
const struct s2n_cipher_preferences *preferences; GUARD(s2n_find_cipher_pref_from_version(version, &preferences)); for (int i = 0; i < preferences->count; ++i) { - if (0 == strcmp(preferences->suites[i]->name, conn->secure.cipher_suite->name) && - /* make sure we dont use a tls version lower than that configured by the version */ - s2n_connection_get_actual_protocol_version(conn) >= preferences->suites[i]->minimum_required_tls_version) { return 1; } } Same problem: `preferences->suites[i]->minimum_required_tls_version` is not cipher preference restriction. you need to use `preference->minimum_protocol_version` . You can even move it out of the loop: ```c if (s2n_connection_get_actual_protocol_version(conn) < preference->minimum_protocol_version) { return 0; } ``` const struct s2n_cipher_preferences *preferences; GUARD(s2n_find_cipher_pref_from_version(version, &preferences)); + /* make sure we dont use a tls version lower than that configured by the version */ + if (s2n_connection_get_actual_protocol_version(conn) < preferences->minimum_protocol_version) { + return 0; + } + for (int i = 0; i < preferences->count; ++i) { + if (0 == strcmp(preferences->suites[i]->name, conn->secure.cipher_suite->name)) { return 1; } }
codereview_cpp_data_5224
virtual bool isMouseCursorActive() const override { -#ifdef VITA - // required for edge of screen scrolling - return true; -#else return ( SDL_GetAppState() & SDL_APPMOUSEFOCUS ) == SDL_APPMOUSEFOCUS; -#endif } private: I think the best way would be to derive a child class from this one and override needed functions so the code will look much cleaner. virtual bool isMouseCursorActive() const override { return ( SDL_GetAppState() & SDL_APPMOUSEFOCUS ) == SDL_APPMOUSEFOCUS; } private:
codereview_cpp_data_5229
return Direction::LEFT; } assert( 0 ); } } :warning: **clang\-diagnostic\-return\-type** :warning: non\-void function does not return a value in all control paths return Direction::LEFT; } assert( 0 ); + return Direction::UNKNOWN; } }
codereview_cpp_data_5246
const int numWorkers() const { return m_threadSupportInterface->getNumWorkerThreads(); } void runTask(int threadIdx, btThreadSupportInterface::ThreadFunc func, void *arg) { - FunctionContext ctx = m_functionContexts[threadIdx]; ctx.func = func; ctx.arg = arg; m_threadSupportInterface->runTask(threadIdx, (void *)&ctx); ctx is a local copy of the m_functionContexts[.], and this local variable goes out-of-scope while the threads are using it. Please use a reference instead: ~~~~~~~~~~~~ FunctionContext& ctx = m_functionContexts[threadIdx]; ~~~~~~~~~~~~ const int numWorkers() const { return m_threadSupportInterface->getNumWorkerThreads(); } void runTask(int threadIdx, btThreadSupportInterface::ThreadFunc func, void *arg) { + FunctionContext& ctx = m_functionContexts[threadIdx]; ctx.func = func; ctx.arg = arg; m_threadSupportInterface->runTask(threadIdx, (void *)&ctx);
codereview_cpp_data_5260
void pre_initialize_internal(const InitArguments& args) { if (args.disable_warnings) g_show_warnings = false; - if (args.tune_kokkos_internals) g_tune_internals = false; } void post_initialize_internal(const InitArguments& args) { I'd expect that would set to `true` void pre_initialize_internal(const InitArguments& args) { if (args.disable_warnings) g_show_warnings = false; + if (args.tune_kokkos_internals) g_tune_internals = true; } void post_initialize_internal(const InitArguments& args) {
codereview_cpp_data_5269
{ if(db->hasDetectedFirstRun()) { - QMessageBox::information(this, tr("Welcome"), tr("Hi! Its seems like it's the first time you run this version of Cockatrice.<br/>All the sets in the card database have been enabled; if you want to hide a set from the deck editor, disable it in the \"Edit Sets\" window.")); actEditSets(); } } \ No newline at end of file Use `\n` over `<br>`? At least that's what I've seen around in the client so far. It gets recognized better by Transifex as well! Will this message dialog shows up directly after the first app launch? Right before the `Edit sets...` pops up? Not sure about the last part of the last sentence... If you add detailed instructions/notes/information about how disabling+sorting sets effect the app in the `Edit sets...` dialog, that might be enough: `"(...)\n All the sets in the card database have been enabled. Read more about changing the set order or disabling specific sets in the the \"Edit Sets\" window."` or `... More information about how and why to change the set order or disable specific sets can be found...` or `... You can read/you find more information about how and why to change the set order or disable specific sets in...` { if(db->hasDetectedFirstRun()) { + QMessageBox::information(this, tr("Welcome"), tr("Hi! Its seems like it's the first time you run this version of Cockatrice.\nAll the sets in the card database have been enabled.\nRead more about changing the set order or disabling specific sets in the the \"Edit Sets\" window.")); actEditSets(); } } \ No newline at end of file
codereview_cpp_data_5273
EXPECT_CALL(*wsv_queries, getSignatories(account_id)) .WillRepeatedly(Return(signatories)); - auto wrapper = make_test_subscriber<CallExact>(qpi.blocksQueryNotifier(), blockNumber); wrapper.subscribe([](auto response) { ASSERT_NO_THROW({ boost::apply_visitor( gwt docs are missing EXPECT_CALL(*wsv_queries, getSignatories(account_id)) .WillRepeatedly(Return(signatories)); + auto wrapper = make_test_subscriber<CallExact>( + qpi.blocksQueryHandle(std::make_shared<shared_model::proto::BlocksQuery>( + blockQuery.getTransport())), + blockNumber); wrapper.subscribe([](auto response) { ASSERT_NO_THROW({ boost::apply_visitor(
codereview_cpp_data_5275
uint8_t protocol_version = 0; uint16_t fragment_length = 0; - /* First two bytes to parse are the fragment length */ uint8_t header_bytes[] = { 0x00, 0x00, 0x00, 0x00, 0x00 }; EXPECT_SUCCESS(s2n_stuffer_write_bytes(&conn->header_in, header_bytes, sizeof(header_bytes))); EXPECT_FAILURE_WITH_ERRNO(s2n_sslv2_record_header_parse(conn, &record_type, &protocol_version, &fragment_length), S2N_ERR_SAFETY); } EXPECT_SUCCESS(s2n_hmac_free(&check_mac)); Since safety errors are pretty common, you could add another layer of verification that this is the safety error you added by checking that we only read the first two bytes of head_in. uint8_t protocol_version = 0; uint16_t fragment_length = 0; + /* First two bytes are the fragment length */ uint8_t header_bytes[] = { 0x00, 0x00, 0x00, 0x00, 0x00 }; EXPECT_SUCCESS(s2n_stuffer_write_bytes(&conn->header_in, header_bytes, sizeof(header_bytes))); EXPECT_FAILURE_WITH_ERRNO(s2n_sslv2_record_header_parse(conn, &record_type, &protocol_version, &fragment_length), S2N_ERR_SAFETY); + + /* Check the rest of the stuffer has not been read yet */ + EXPECT_EQUAL(s2n_stuffer_data_available(&conn->header_in), 3); } EXPECT_SUCCESS(s2n_hmac_free(&check_mac));
codereview_cpp_data_5308
CardInfo *card = addCard(set->getShortName(), cardName, false, cardId, cardCost, cmc, cardType, cardPT, cardLoyalty, cardText, colors, relatedCards, upsideDown); if (!set->contains(card)) { - - if(cardName=="Mountain") - { - qDebug() << cardName << " " << set->getShortName(); - } - card->addToSet(set); cards++; } Is this check used for anything or just left over from troubleshooting? CardInfo *card = addCard(set->getShortName(), cardName, false, cardId, cardCost, cmc, cardType, cardPT, cardLoyalty, cardText, colors, relatedCards, upsideDown); if (!set->contains(card)) { card->addToSet(set); cards++; }
codereview_cpp_data_5323
} catch (Exception& e) { - ENCDB_LOG(ERROR) << "[Put] Encrypt ERROR! [k/v]: " << _key.ToString() << "/ " - << _value.ToString() << endl; BOOST_THROW_EXCEPTION( EncryptedLevelDBEncryptFailed() << errinfo_comment("EncryptedLevelDB encrypt error")); } This log hasn't been modified. } catch (Exception& e) { + ENCDB_LOG(ERROR) << LOG_BADGE("Put") << LOG_DESC(" Encrypt ERROR!") + << LOG_KV(_key.ToString(), _value.ToString()); BOOST_THROW_EXCEPTION( EncryptedLevelDBEncryptFailed() << errinfo_comment("EncryptedLevelDB encrypt error")); }
codereview_cpp_data_5330
ValueTokenizer values(arg[iarg],":"); start = values.next_tagint(); if (utils::strmatch(arg[iarg],"^\\d+$")) { - start = stop; } else if (utils::strmatch(arg[iarg],"^\\d+:\\d+$")) { stop = values.next_tagint(); } else if (utils::strmatch(arg[iarg],"^\\d+:\\d+:\\d+$")) { @akohlmey Instead of double-parsing with `strmatch` here you could instead store `values.count()` as `ncount` and then do: ``` if (ncount == 1) { ... } else if (ncount == 2) { ... } else if (ncount == 3) { ... } ``` or use a `switch` statement. The `next_tagint()` functions will already throw a `TokenizerException` if the value isn't an integer. ValueTokenizer values(arg[iarg],":"); start = values.next_tagint(); if (utils::strmatch(arg[iarg],"^\\d+$")) { + stop = start; } else if (utils::strmatch(arg[iarg],"^\\d+:\\d+$")) { stop = values.next_tagint(); } else if (utils::strmatch(arg[iarg],"^\\d+:\\d+:\\d+$")) {
codereview_cpp_data_5338
{ IdfObject idfObject( openstudio::IddObjectType::Schedule_File ); - m_idfObjects.push_back(idfObject); - idfObject.setName(modelObject.name().get()); boost::optional<ScheduleTypeLimits> scheduleTypeLimits = modelObject.scheduleTypeLimits(); The way I read the IDD, externalFile().name() would be 'ExternalFile 1' and externalFile().fileName() would be the actual file path right? { IdfObject idfObject( openstudio::IddObjectType::Schedule_File ); idfObject.setName(modelObject.name().get()); boost::optional<ScheduleTypeLimits> scheduleTypeLimits = modelObject.scheduleTypeLimits();
codereview_cpp_data_5340
try { Model model("arm26.osim"); - // all subcomponents are now accounted for. ASSERT(model.countNumComponents() > 0); // model must be up-to-date with its properties Consider adding a note that this is because `finalizeFromProperties()` is called in the constructor. try { Model model("arm26.osim"); + // all subcomponents are accounted for since Model constructor invokes + // finalizeFromProperties(). ASSERT(model.countNumComponents() > 0); // model must be up-to-date with its properties
codereview_cpp_data_5341
// goto main menu int rs = ( test ? Game::TESTING : Game::MAINMENU ); - Video::ShowVideo( Settings::GetLastFile( "data", "H2XINTRO.SMK" ), false ); while ( rs != Game::QUITGAME ) { switch ( rs ) { Hi @undef21 , why do we need this change? Which version of Homm2 are you using? // goto main menu int rs = ( test ? Game::TESTING : Game::MAINMENU ); + Video::ShowVideo( Settings::GetLastFile( System::ConcatePath( "heroes2", "anim" ), "H2XINTRO.SMK" ), false ); while ( rs != Game::QUITGAME ) { switch ( rs ) {
codereview_cpp_data_5348
char time_formatted[255]; struct tm tm; struct flb_time tms; - flb_sds_t severity = flb_sds_create_size(10); msgpack_object *obj; msgpack_unpacked result; msgpack_sbuffer mp_sbuf; do not allocate memory if you don't need it. If ctx->severity_key is NULL or not set, why to allocate and deallocate everytime ?, make the allocation conditional few lines below char time_formatted[255]; struct tm tm; struct flb_time tms; + severity_t severity; msgpack_object *obj; msgpack_unpacked result; msgpack_sbuffer mp_sbuf;
codereview_cpp_data_5366
transfer->setFolderTransferTag(folderTransferTag); } - transfer->setForceNewUpload(forceNewUpload); transferQueue.push(transfer); waiter->notify(); Better to reuse `setStreamingTransfer()` for this purpose, so we don't need a new member with setter/getter, etc. transfer->setFolderTransferTag(folderTransferTag); } + transfer->setStreamingTransfer(forceNewUpload); transferQueue.push(transfer); waiter->notify();
codereview_cpp_data_5375
auto tserver = tablet_map->find(desc->permanent_uuid()); bool no_tablets = tserver == tablet_map->end(); - if (viewType == kTServersClocksView) { // Render physical time. const Timestamp p_ts(desc->physical_time()); *output << " <td>" << p_ts.ToFormattedString() << "</td>"; I don't think that we need `+0000` in each entry. Also not sure that the logical component is useful since it changes quite frequently. auto tserver = tablet_map->find(desc->permanent_uuid()); bool no_tablets = tserver == tablet_map->end(); + if (viewType == TServersViewType::kTServersClocksView) { // Render physical time. const Timestamp p_ts(desc->physical_time()); *output << " <td>" << p_ts.ToFormattedString() << "</td>";
codereview_cpp_data_5385
g->base = NULL; while ( gw->parent!=NULL && !gw->is_toplevel ) gw = gw->parent; - if (gw->is_dying) return; td = (GTopLevelD *) (gw->widget_data); if ( td->gdef == g ) td->gdef = NULL; if ( td->gcancel == g ) td->gcancel = NULL; if ( td->gfocus == g ) td->gfocus = NULL; So what happens in 'normal' window managers, is gw->widget_data not null but it is dying? g->base = NULL; while ( gw->parent!=NULL && !gw->is_toplevel ) gw = gw->parent; td = (GTopLevelD *) (gw->widget_data); + if ( td == NULL ) return; /* dying, prevents tiling WM crash */ if ( td->gdef == g ) td->gdef = NULL; if ( td->gcancel == g ) td->gcancel = NULL; if ( td->gfocus == g ) td->gfocus = NULL;
codereview_cpp_data_5387
const uint8_t **src, const uint8_t *src_end, unsigned prefix_bits, const char **err_desc) { - assert(base_index >= 0); int64_t off; if (decode_int(&off, src, src_end, prefix_bits) != 0 || off >= base_index) { Maybe we do not need this, assuming that we add the assertion to `parse_decode_context` as you did in this PR? const uint8_t **src, const uint8_t *src_end, unsigned prefix_bits, const char **err_desc) { int64_t off; if (decode_int(&off, src, src_end, prefix_bits) != 0 || off >= base_index) {
codereview_cpp_data_5399
// Walkers: move closer to the castle walls during siege if ( _attackingCastle && target.cell == -1 ) { - uint32_t shortestDist = 65535; for ( const int wallIndex : underWallsIndicies ) { if ( !arena.hexIsPassable( wallIndex ) ) { (optional) We can use either `UINT32_MAX` from `<cstdint>` or `std::numeric_limits<uint32_t>::max` from `<limits>` here and in other similar places. // Walkers: move closer to the castle walls during siege if ( _attackingCastle && target.cell == -1 ) { + uint32_t shortestDist = UINT32_MAX; for ( const int wallIndex : underWallsIndicies ) { if ( !arena.hexIsPassable( wallIndex ) ) {
codereview_cpp_data_5400
auto result = temp_wsv->apply(tx); ASSERT_FALSE(framework::expected::err(result)); - storage->prepareBlock(*temp_wsv); - temp_wsv.reset(); // balance remains unchanged validateAccountAsset( It looks like `tx`, `other_tx` can be moved to fixture and reused in test cases, and some shortcut for `block` can be created - a method which only takes a vector of transactions, for example. auto result = temp_wsv->apply(tx); ASSERT_FALSE(framework::expected::err(result)); + storage->prepareBlock(std::move(temp_wsv)); // balance remains unchanged validateAccountAsset(
codereview_cpp_data_5408
dbname, [](auto &) {}, false, - std::chrono::milliseconds(20000), - std::chrono::milliseconds(20000), path) .setInitialState(kAdminKeypair) .sendTx(tx) Maybe move waiting parameters after the block store path, so we can omit them here? dbname, [](auto &) {}, false, path) .setInitialState(kAdminKeypair) .sendTx(tx)
codereview_cpp_data_5411
} } - // update fm_kspace if long-range - // remove short-range comp. of fm_kspace - - if (long_spin_flag) { - - } - // update half s for all atoms if (sector_flag) { // sectoring seq. update This if statement is empty. Either something needs to be added inside the curly braces or the whole block can be removed. } } // update half s for all atoms if (sector_flag) { // sectoring seq. update
codereview_cpp_data_5415
} } - if ((wd.flag & BF_WEAPON && sc != NULL && sc->data[SC_FALLINGSTAR] != NULL && rand() % 100 < sc->data[SC_FALLINGSTAR]->val2)) { if (sd != NULL) sd->auto_cast_current.type = AUTOCAST_TEMP; if (status->charge(src, 0, skill->get_sp(SJ_FALLINGSTAR_ATK, sc->data[SC_FALLINGSTAR]->val1))) missing space and parentheses near ``&`` should be one of this: ``if ((wd.flag & BF_WEAPON) && ...)`` or ``if ((wd.flag & BF_WEAPON && ...))`` also missing space near ``%`` } } + if (wd.flag&BF_WEAPON && sc != NULL && sc->data[SC_FALLINGSTAR] != NULL && rand()%100 < sc->data[SC_FALLINGSTAR]->val2) { if (sd != NULL) sd->auto_cast_current.type = AUTOCAST_TEMP; if (status->charge(src, 0, skill->get_sp(SJ_FALLINGSTAR_ATK, sc->data[SC_FALLINGSTAR]->val1)))
codereview_cpp_data_5417
" --blacklist=filename - blacklist directory or file.\n" " --build - build a whitelisted profile for the application.\n" " --build=filename - build a whitelisted profile for the application.\n" - " -c - login shell compatibility option (has no effect).\n" " --caps - enable default Linux capabilities filter.\n" " --caps.drop=all - drop all capabilities.\n" " --caps.drop=capability,capability - blacklist capabilities filter.\n" if it's not meant to be run by the user and has no effect, I wouldn't even show it in the usage list. " --blacklist=filename - blacklist directory or file.\n" " --build - build a whitelisted profile for the application.\n" " --build=filename - build a whitelisted profile for the application.\n" " --caps - enable default Linux capabilities filter.\n" " --caps.drop=all - drop all capabilities.\n" " --caps.drop=capability,capability - blacklist capabilities filter.\n"
codereview_cpp_data_5421
// switch (priority) { case MSG_INTERNAL_ERROR: - snprintf(event_msg, sizeof(event_msg), "[error] %.512s", message); break; case MSG_SCHEDULER_ALERT: - snprintf(event_msg, sizeof(event_msg), "%.64s: %.512s", _("Message from server"), message ); break; `event_msg` has the same size (1024) as a `message`. Maybe should be increased to 2048 instead? Then this `"[error] %.512s", message` could be changed to this: `"[error] %.*s", sizeof(message), message` // switch (priority) { case MSG_INTERNAL_ERROR: + snprintf(event_msg, sizeof(event_msg), "[error] %s", message); break; case MSG_SCHEDULER_ALERT: + snprintf(event_msg, sizeof(event_msg), "%.64s: %s", _("Message from server"), message ); break;
codereview_cpp_data_5422
} }; -TEST_F(BaseContext_test , DISABLED_testGetObjects ) { this->testGetObjects(); } ```suggestion // TODO: hTalbot 2021-08-18: This test should be reactivated as soon as the identified problem has been fixed ``` } }; +TEST_F(BaseContext_test , testGetObjects ) { this->testGetObjects(); }
codereview_cpp_data_5424
break; case ELEMENT_TYPE_ENV_VAR: /* %{..}e */ { h2o_iovec_t *env_var = h2o_req_getenv(req, element->data.name.base, element->data.name.len, 0); - if (env_var == NULL || env_var->len < 1) goto EmitNull; RESERVE(env_var->len * unsafe_factor); pos = append_safe_string(pos, env_var->base, env_var->len); Shouldn't we emit an zero-length string if `len` is zero? Some applications may use the existence of the environment variable as a sign of something, and in such case it is desirable to be able to distinguish between NULL and a zero-length string. break; case ELEMENT_TYPE_ENV_VAR: /* %{..}e */ { h2o_iovec_t *env_var = h2o_req_getenv(req, element->data.name.base, element->data.name.len, 0); + if (env_var == NULL || env_var->len < 0) goto EmitNull; RESERVE(env_var->len * unsafe_factor); pos = append_safe_string(pos, env_var->base, env_var->len);
codereview_cpp_data_5440
#if defined(_WIN32) bool read, write; - if (info.checkEvent(read, write)) { curl_multi_socket_action(curlm[d], info.fd, (read ? CURL_CSELECT_IN : 0) Same as above. init booleans #if defined(_WIN32) bool read, write; + if (info.checkEvent(read, write)) // if checkEvent returns true, both `read` and `write` have been set. { curl_multi_socket_action(curlm[d], info.fd, (read ? CURL_CSELECT_IN : 0)
codereview_cpp_data_5443
} } result = transcodeCharacterStringToUTF8(result); - if (result.right(1) != "\n") result += "\n"; //fprintf(stderr,"readCodeFragement(%d-%d)=%s\n",startLine,endLine,result.data()); return found; } `result.right(1)` is pretty inefficient for lange strings. Better use something like `!result.isEmpty() && result.at(result.length()-1)!='\n'` } } result = transcodeCharacterStringToUTF8(result); + if (!result.isEmpty() && result.at(result.length()-1)!='\n') result += "\n"; //fprintf(stderr,"readCodeFragement(%d-%d)=%s\n",startLine,endLine,result.data()); return found; }
codereview_cpp_data_5446
/** * @file - * @brief This program aims at calculating nCr modulo p. To know more about it, - * visit https://cp-algorithms.com/combinatorics/binomial-coefficients.html * @details nCr is defined as n! / (r! * (n-r)!) where n! represents factorial * of n. In many cases, the value of nCr is too large to fit in a 64 bit * integer. Hence, in competitive programming, there are many problems or ```suggestion std::vector<uint64_t> fac{}; /// stores precomputed factorial(i) % p value uint64_t p = 0; /// the p from (nCr % p) ``` /** * @file + * @brief This program aims at calculating [nCr modulo + * p](https://cp-algorithms.com/combinatorics/binomial-coefficients.html). * @details nCr is defined as n! / (r! * (n-r)!) where n! represents factorial * of n. In many cases, the value of nCr is too large to fit in a 64 bit * integer. Hence, in competitive programming, there are many problems or
codereview_cpp_data_5448
void GenericConstraintCorrection::rebuildSystem(double massFactor, double forceFactor) { - for (auto & m_linearSolver : m_linearSolvers) - m_linearSolver->rebuildSystem(massFactor, forceFactor); } void GenericConstraintCorrection::addComplianceInConstraintSpace(const ConstraintParams *cparams, BaseMatrix* W) ```suggestion for (auto & linearSolver : m_linearSolvers) linearSolver->rebuildSystem(massFactor, forceFactor); ``` void GenericConstraintCorrection::rebuildSystem(double massFactor, double forceFactor) { + for (auto & linearSolver : m_linearSolvers) + linearSolver->rebuildSystem(massFactor, forceFactor); } void GenericConstraintCorrection::addComplianceInConstraintSpace(const ConstraintParams *cparams, BaseMatrix* W)
codereview_cpp_data_5463
fullOutputFilename); if (get_report_errors()) { STOFileAdapter_<double>::write(*modelOrientationErrors, - getName() + "_orientationErrors.sto"); } } else - log_info("IMUInverseKinematicsTool: No output files are written."); // Results written to file, clear in case we run again ikReporter->clearTable(); } Should this case actually just throw an Exception instead of logging that no files were written? I think this will also be called if both `results_dir` and `output_motion_file` are used? It may be useful to have a separate message for this. If there's a use case for this (e.g., running this without outputting files) I'd just add one more statement here to give the user a reason why files were written so that they can fix it if it's a problem. Perhaps "Either the results directory or output_file_name must be specified to write to file." fullOutputFilename); if (get_report_errors()) { STOFileAdapter_<double>::write(*modelOrientationErrors, + outName + "_orientationErrors.sto"); } } else + log_info("IMUInverseKinematicsTool: No output files were generated, " + "set output_motion_file to generate output files."); // Results written to file, clear in case we run again ikReporter->clearTable(); }
codereview_cpp_data_5465
constructProperty_ProbeSet(probeSet); } -//_____________________________________________________________________________ -/* - * Connect old style properties to local references. - */ -void Model::setupProperties() -{ -} //------------------------------------------------------------------------------ // BUILD SYSTEM Can this be removed? constructProperty_ProbeSet(probeSet); } //------------------------------------------------------------------------------ // BUILD SYSTEM
codereview_cpp_data_5487
{ "default", &cipher_preferences_20150202 }, { "20140601", &cipher_preferences_20140601 }, { "20141001", &cipher_preferences_20141001 }, - { "20150202", &cipher_preferences_20150202 } }; struct s2n_config s2n_default_config = { you could terminate this with a { NULL, NULL } pair, then when enumerating, simply do: for (int i = 0; selection[i].version; i++) { ... } but i don't feel strongly about that. { "default", &cipher_preferences_20150202 }, { "20140601", &cipher_preferences_20140601 }, { "20141001", &cipher_preferences_20141001 }, + { "20150202", &cipher_preferences_20150202 }, + { NULL, NULL } }; struct s2n_config s2n_default_config = {
codereview_cpp_data_5490
return -ENOMEM; st = iio_priv(indio_dev); - spi_set_drvdata(spi, indio_dev); st->spi = spi; st->regmap = regmap; since we are here, I do not think this is needed since `spi_set_drvdata()` seems not to be called anywhere... return -ENOMEM; st = iio_priv(indio_dev); st->spi = spi; st->regmap = regmap;
codereview_cpp_data_5503
} else if ((option == "-ReadX") || (option == "-RX")) { if (argc < 4) { - cout << "Both directory of data files and setup file are needed to read Xsens data. Please fix and retry." << endl; PrintUsage(argv[0], cout); exit(-1); } `"Both the directory containing Xsens data files and the reader settings file are necessary to read Xsens data. Please retry with these inputs."` Also try to fit in 80cols. } else if ((option == "-ReadX") || (option == "-RX")) { if (argc < 4) { + cout << "Both the directory containing Xsens data files and the reader settings file are necessary to read Xsens data. Please retry with these inputs." << endl; PrintUsage(argv[0], cout); exit(-1); }
codereview_cpp_data_5512
} else if ((option == "-AddIMUs") || (option == "-A")) { if (argc < 4) { - cout << "Both model file (.osim) and markers file are needed for this option. Please fix and retry." << endl; PrintUsage(argv[0], cout); exit(-1); } `Both a model (.osim) file and marker data (e.g. .trc) file are necessary to add IMU frames to the model based-on marker data.` } else if ((option == "-AddIMUs") || (option == "-A")) { if (argc < 4) { + cout << "Both a model (.osim) file and marker data (e.g. .trc) file are necessary to add IMU frames to the model based-on marker data." << endl; PrintUsage(argv[0], cout); exit(-1); }
codereview_cpp_data_5518
{ logInfo(RTPS_EDP,"Adding SEDP Pub Writer to my Pub Reader"); temp_writer_proxy_data_.guid().entityId = c_EntityId_SEDPPubWriter; - temp_writer_proxy_data_.persistence_guid().entityId = temp_writer_proxy_data_.persistence_guid().guidPrefix != c_GuidPrefix_Unknown ? c_EntityId_SEDPPubWriter : c_EntityId_Unknown; publications_reader_.first->matched_writer_add(temp_writer_proxy_data_); } auxendp = endp; This comparison is repeated several times. We may add a set_persistence_entity_id method that performs the ternary operation of this line. { logInfo(RTPS_EDP,"Adding SEDP Pub Writer to my Pub Reader"); temp_writer_proxy_data_.guid().entityId = c_EntityId_SEDPPubWriter; + temp_writer_proxy_data_.set_persistence_entity_id(c_EntityId_SEDPPubWriter); publications_reader_.first->matched_writer_add(temp_writer_proxy_data_); } auxendp = endp;
codereview_cpp_data_5523
bool TxPool::insert(Transaction const& _tx) { h256 tx_hash = _tx.sha3(); TransactionQueue::iterator p_tx = m_txsQueue.emplace(_tx).first; m_txsHash[tx_hash] = p_tx; return true; We need to check before insert bool TxPool::insert(Transaction const& _tx) { h256 tx_hash = _tx.sha3(); + if (m_txsHash.find(tx_hash) != m_txsHash.end()) + { + return true; + } TransactionQueue::iterator p_tx = m_txsQueue.emplace(_tx).first; m_txsHash[tx_hash] = p_tx; return true;
codereview_cpp_data_5532
token_id parent_id = ast_id(parent); if (parent_id == TK_VAR || parent_id == TK_LET) { - ast_error_frame(frame, parent, "the previous value of '%s' is used because you are trying to use the return value of this %s declaration", ast_print_type(ast), ast_print_type(parent)); } } ```suggestion ast_error_frame(frame, parent, "the previous value of '%s' is used because you are trying to use the resulting value of this %s declaration", ast_print_type(ast), ast_print_type(parent)); ``` token_id parent_id = ast_id(parent); if (parent_id == TK_VAR || parent_id == TK_LET) { + ast_error_frame(frame, parent, "the previous value of '%s' is used because you are trying to use the resulting value of this %s declaration", ast_print_type(ast), ast_print_type(parent)); } }
codereview_cpp_data_5535
std::string topic_name = TEST_TOPIC_NAME; for (uint32_t len : array_lengths) { - topic_name += "_"; test_big_message_corner_case(topic_name, len); } } I suppose some more specific information related with this loop was intended here and it was forgotten at the last minute. std::string topic_name = TEST_TOPIC_NAME; for (uint32_t len : array_lengths) { test_big_message_corner_case(topic_name, len); } }
codereview_cpp_data_5536
namespace { void handleEvents(rxcpp::composite_subscription &subscription, - rxcpp::schedulers::run_loop &run_loop, - bool &stream_failed) { - while ((subscription.is_subscribed() or not run_loop.empty()) - and not stream_failed) { run_loop.dispatch(); } } Please refactor without passing additional variables to this loop. namespace { void handleEvents(rxcpp::composite_subscription &subscription, + rxcpp::schedulers::run_loop &run_loop) { + while (subscription.is_subscribed() or not run_loop.empty()) { run_loop.dispatch(); } }
codereview_cpp_data_5554
in.close(); } -void data_store_image::exchange_data_two_sided() { - if (m_master) std::cerr << "starting exchange_data_two_sided\n"; std::stringstream err; //build map: proc -> global indices that proc needs for this epoch, and Perhaps, it may look cleaner to create a function exchange_data_one_sided() to contain the most of the body of this function and make this function only to choose between the two. In addition, it would probably safer to make the decision static, i.e., by defining m_use_two_sided_comms a constant member variable which would not change once initialized. in.close(); } +void data_store_image::exchange_data() { + if (m_master) std::cerr << "starting exchange_data\n"; std::stringstream err; //build map: proc -> global indices that proc needs for this epoch, and
codereview_cpp_data_5557
mst_processor_->onPreparedBatches().subscribe([this](auto &&batch) { log_->info("MST batch prepared"); - // TODO: 07/08/2018 @muratovv rework interface of pcs::propagate batch - // and mst::propagate batch IR-1584 this->pcs_->propagate_batch(batch); }); mst_processor_->onExpiredBatches().subscribe([this](auto &&batch) { Isn't the TODO above about the task you did in this PR? If that's the case, you should remove it mst_processor_->onPreparedBatches().subscribe([this](auto &&batch) { log_->info("MST batch prepared"); this->pcs_->propagate_batch(batch); }); mst_processor_->onExpiredBatches().subscribe([this](auto &&batch) {
codereview_cpp_data_5558
nHashType |= SIGHASH_ANYONECANPAY; else if (boost::iequals(s, "FORKID")) nHashType |= SIGHASH_FORKID; else { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param"); I would like to keep the ability to sign a bitcoin-style transaction using signrawtransaction. This may be useful by some people for cross-chain stuff. But default should be FORKID (not either depending on forked status) as you have implemented in this PR. nHashType |= SIGHASH_ANYONECANPAY; else if (boost::iequals(s, "FORKID")) nHashType |= SIGHASH_FORKID; + else if (boost::iequals(s, "NOFORKID")) + { + // Still support signing legacy chain transactions + fForkId = false; + nHashType &= ~SIGHASH_FORKID; + } else { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
codereview_cpp_data_5579
#include "vast/detail/assert.hpp" #include "vast/detail/string.hpp" #include "vast/expression.hpp" -#include "vast/expression_visitors.hpp" #include "vast/type.hpp" namespace vast { The expander doesn't really belong in `expression_visitor.hpp`. Can you move it to this file, remove the include, and rename it to something more specific like `value_predicate_expander`? #include "vast/detail/assert.hpp" #include "vast/detail/string.hpp" #include "vast/expression.hpp" #include "vast/type.hpp" namespace vast {
codereview_cpp_data_5586
} bool has_required_version(const plugin_version& version) noexcept { - return !std::strcmp(plugin::version.libvast_version, version.libvast_version) - && !std::strcmp(plugin::version.libvast_build_tree_hash, - version.libvast_build_tree_hash) - && plugin::version.major == version.major && std::tie(plugin::version.minor, plugin::version.patch, plugin::version.tweak) <= std::tie(version.minor, version.patch, version.tweak); Do we still need to compare major/minor/patch/tweak version? I thought we were going to use these as the user-facing plugin version. } bool has_required_version(const plugin_version& version) noexcept { + return plugin::version.major == version.major && std::tie(plugin::version.minor, plugin::version.patch, plugin::version.tweak) <= std::tie(version.minor, version.patch, version.tweak);
codereview_cpp_data_5598
return BuildIfAvailable( castle, BUILD_WELL ); } - const bool islandCastle = world.getRegion( world.GetTiles( castle.GetIndex() ).GetRegion() ).getNeighbours().size() < 2; - if ( islandCastle && BuildIfEnoughResources( castle, BUILD_SHIPYARD, 2 ) ) { return true; } `island Castle` or `is Land Castle`? return BuildIfAvailable( castle, BUILD_WELL ); } + const bool castleOnIsland = world.getRegion( world.GetTiles( castle.GetIndex() ).GetRegion() ).getNeighbours().size() < 2; + if ( castleOnIsland && BuildIfEnoughResources( castle, BUILD_SHIPYARD, 2 ) ) { return true; }
codereview_cpp_data_5602
#include <model/Schedule.hpp> #include <model/Schedule_Impl.hpp> -// Delete? #include <model/ScheduleTypeLimits.hpp> -// Delete? #include <model/ScheduleTypeRegistry.hpp> #include <utilities/idd/IddFactory.hxx> #include <utilities/idd/OS_Fan_ZoneExhaust_FieldEnums.hxx> @kbenne Will this throw a runtime error? I honestly don't know. It obviously compiles fine. #include <model/Schedule.hpp> #include <model/Schedule_Impl.hpp> #include <utilities/idd/IddFactory.hxx> #include <utilities/idd/OS_Fan_ZoneExhaust_FieldEnums.hxx>
codereview_cpp_data_5616
/* Write the extensions */ GUARD(s2n_client_extensions_send(conn, out)); - /* Default our signature digest algorithms */ conn->secure.signature_digest_alg = S2N_HASH_MD5_SHA1; if (conn->actual_protocol_version == S2N_TLS12) { conn->secure.signature_digest_alg = S2N_HASH_SHA1; Should the client end be setting the defaults here? Aren't we dependent on parsing the {hash,sign} algorithm used by the server in ServerKeyExchange? /* Write the extensions */ GUARD(s2n_client_extensions_send(conn, out)); + /* Default our signature digest algorithm to SHA1. Will be used when verifying a client certificate. */ conn->secure.signature_digest_alg = S2N_HASH_MD5_SHA1; if (conn->actual_protocol_version == S2N_TLS12) { conn->secure.signature_digest_alg = S2N_HASH_SHA1;
codereview_cpp_data_5634
H2O_PROBE_CONN(RECEIVE_REQUEST_HEADERS, &conn->super, conn->_req_index, &conn->req.input.method, &conn->req.input.authority, &conn->req.input.path, conn->req.version, conn->req.headers.entries, conn->req.headers.size); - H2O_PROBE(RECEIVE_REQUEST_HEADERS, &conn->super, conn->_req_index, &conn->req.input.method, &conn->req.input.authority, - &conn->req.input.path, conn->req.version, conn->req.headers.entries, conn->req.headers.size); - if (entity_body_header_index != -1) { conn->req.timestamps.request_body_begin_at = h2o_gettimeofday(conn->super.ctx->loop); if (expect.base != NULL) { Seems like we are calling the probe twice? H2O_PROBE_CONN(RECEIVE_REQUEST_HEADERS, &conn->super, conn->_req_index, &conn->req.input.method, &conn->req.input.authority, &conn->req.input.path, conn->req.version, conn->req.headers.entries, conn->req.headers.size); if (entity_body_header_index != -1) { conn->req.timestamps.request_body_begin_at = h2o_gettimeofday(conn->super.ctx->loop); if (expect.base != NULL) {
codereview_cpp_data_5635
{ g_autoptr(GOptionContext) context = g_option_context_new (""); glnx_unref_object RPMOSTreeSysroot *sysroot_proxy = NULL; - g_autofree char *transaction_address = NULL; _cleanup_peer_ GPid peer_pid = 0; if (!rpmostree_option_context_parse (context, We can just do this just once, no? E.g.: 1. register for transaction path changes 2. check that the path we're listening on still the same 3. enter main loop and wait until done ? { g_autoptr(GOptionContext) context = g_option_context_new (""); glnx_unref_object RPMOSTreeSysroot *sysroot_proxy = NULL; _cleanup_peer_ GPid peer_pid = 0; if (!rpmostree_option_context_parse (context,
codereview_cpp_data_5645
/****************************************************************************** * * Project: PROJ - * Purpose: Test pj_phi2.c * Author: Kurt Schwehr <schwehr@google.com> * ****************************************************************************** - * Copyright (c) 2018, Google Inc * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), I think this should read "Test pj_phi2 function". /****************************************************************************** * * Project: PROJ + * Purpose: Test pj_phi2 function. * Author: Kurt Schwehr <schwehr@google.com> * ****************************************************************************** + * Copyright (c) 2018, Google Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"),
codereview_cpp_data_5646
ASSERT_EQUAL(0.5, context->getValue(dr_elbow_flexNew), 0.000001); // Exercise Editing workflow OpenSim::Body& bdy = model->updBodySet().get("r_humerus"); AbstractProperty& massProp = bdy.updPropertyByName("mass"); double oldValue = PropertyHelper::getValueDouble(massProp); Is there a reason for using the property interface here instead `body.setMass(body.getMass()+1.0)`? Seems harder to read. But is this is actually what the GUI executes when an edit is made, it makes sense to leave it as is. Can you make a note of that, if that's the case? ASSERT_EQUAL(0.5, context->getValue(dr_elbow_flexNew), 0.000001); // Exercise Editing workflow + // These are the same calls done from GUI code base through Property edits OpenSim::Body& bdy = model->updBodySet().get("r_humerus"); AbstractProperty& massProp = bdy.updPropertyByName("mass"); double oldValue = PropertyHelper::getValueDouble(massProp);
codereview_cpp_data_5659
} // timestamp - change->sourceTimestamp = Time_t(sqlite3_column_double(load_writer_stmt_, 5)); changes.insert(changes.begin(), change); } Using `double` to store the sourcetimestap sure there will be loss of precision. I recomend to store the values of `rtps::Time_t`: seconds and nanoseconds. } // timestamp + change->sourceTimestamp.from_ns(sqlite3_column_int64(load_writer_stmt_, 5)); changes.insert(changes.begin(), change); }
codereview_cpp_data_5661
hipFunction_t* kds = reinterpret_cast<hipFunction_t*>(malloc(sizeof(hipFunction_t) * numDevices)); if (kds == nullptr) { - return hipLogStatus(hipErrorNotInitialized); } // prepare all kernel descriptors for each device as all streams will be locked in the next loop Should be ```ihipLogStatus```. hipFunction_t* kds = reinterpret_cast<hipFunction_t*>(malloc(sizeof(hipFunction_t) * numDevices)); if (kds == nullptr) { + return ihipLogStatus(hipErrorNotInitialized); } // prepare all kernel descriptors for each device as all streams will be locked in the next loop
codereview_cpp_data_5681
return fheroes2::AGG::GetICN( -1, 0 ); } -void Captain::PortraitRedraw( s32 _px, s32 py, PortraitType type, fheroes2::Image & dstsf ) const { if ( !isValid() ) return; :warning: **clang-diagnostic-unused-parameter** :warning: unused parameter '_px' return fheroes2::AGG::GetICN( -1, 0 ); } +void Captain::PortraitRedraw( s32 _px, s32 _py, PortraitType type, fheroes2::Image & dstsf ) const { if ( !isValid() ) return;
codereview_cpp_data_5683
{ memcpy(original_change_cit->getChange()->serializedPayload.data + original_offset, incoming_change->serializedPayload.data + incoming_offset, - original_change_cit->getChange()->serializedPayload.length - - (size_t(count) * original_change_cit->getChange()->getFragmentSize())); } original_change_cit->getChange()->getDataFragments()->at(count) = ChangeFragmentStatus_t::PRESENT; Can the last argument be replaced with `original_change_cit->getChange()->serializedPayload.length - original_offset`? { memcpy(original_change_cit->getChange()->serializedPayload.data + original_offset, incoming_change->serializedPayload.data + incoming_offset, + original_change_cit->getChange()->serializedPayload.length - original_offset); } original_change_cit->getChange()->getDataFragments()->at(count) = ChangeFragmentStatus_t::PRESENT;
codereview_cpp_data_5685
missile[i]._miVar2 = plr[id]._pHPBase; if (missile[i]._mirange == 0) { missile[i]._miDelFlag = TRUE; -#ifdef HELLFIRE - NetSendCmd(1u, 0x61u); //TODO: apply enum -#else NetSendCmd(TRUE, CMD_ENDSHIELD); -#endif } } PutMissile(i); ```suggestion NetSendCmd(TRUE, CMD_ENDSHIELD); ``` This line doesn't need an ifdef missile[i]._miVar2 = plr[id]._pHPBase; if (missile[i]._mirange == 0) { missile[i]._miDelFlag = TRUE; NetSendCmd(TRUE, CMD_ENDSHIELD); } } PutMissile(i);
codereview_cpp_data_5697
bool EDPServer2::createSEDPEndpoints() { // Assert that there is PDP SERVER - assert(mp_PDP); bool created = true; // Return code I think the idea was to assert that the `mp_PDP` is in fact pointing to a `PDPServer2*` ```suggestion assert(dynamic_cast<PDPServer2*>(mp_PDP)); ``` bool EDPServer2::createSEDPEndpoints() { // Assert that there is PDP SERVER + assert(dynamic_cast<PDPServer2*>(mp_PDP)); bool created = true; // Return code
codereview_cpp_data_5701
else { std::vector<fastrtps::rtps::GUID_t> readers_in_topic = {reader_guid}; - auto retu = readers_by_topic_.insert( std::pair<std::string, std::vector<fastrtps::rtps::GUID_t>>(topic_name, readers_in_topic)); - if (!retu.second) { logError(DISCOVERY_DATABASE, "Could not insert reader " << reader_guid << " in topic " << topic_name); } ```suggestion auto reader_by_topic = readers_by_topic_.insert( std::pair<std::string, std::vector<fastrtps::rtps::GUID_t>>(topic_name, readers_in_topic)); if (!reader_by_topic.second) ``` else { std::vector<fastrtps::rtps::GUID_t> readers_in_topic = {reader_guid}; + auto topic_iterator = readers_by_topic_.insert( std::pair<std::string, std::vector<fastrtps::rtps::GUID_t>>(topic_name, readers_in_topic)); + if (!topic_iterator.second) { logError(DISCOVERY_DATABASE, "Could not insert reader " << reader_guid << " in topic " << topic_name); }
codereview_cpp_data_5705
#include "error/s2n_errno.h" #include "utils/s2n_safety.h" -#define s2n_parsed_extension_is_valid(parsed_extension) ((parsed_extension)->extension.data != NULL) static const s2n_parsed_extension empty_parsed_extensions[S2N_PARSED_EXTENSIONS_COUNT] = { 0 }; this was renamed to `s2n_parsed_extension_is_empty`, right? #include "error/s2n_errno.h" #include "utils/s2n_safety.h" +#define s2n_parsed_extension_is_empty(parsed_extension) ((parsed_extension)->extension.data == NULL) static const s2n_parsed_extension empty_parsed_extensions[S2N_PARSED_EXTENSIONS_COUNT] = { 0 };
codereview_cpp_data_5737
std::for_each(internal_state_.cbegin(), internal_state_.cend(), visitor); } void MstState::iterateTransactions( std::function< void(const std::shared_ptr<shared_model::interface::Transaction> &)> std::function is not considered as a good solution for non-tests code due to its performance drawbacks. std::for_each(internal_state_.cbegin(), internal_state_.cend(), visitor); } + /* void MstState::iterateTransactions( std::function< void(const std::shared_ptr<shared_model::interface::Transaction> &)>
codereview_cpp_data_5739
if (al.volatileSpecifier()) result+=" volatile"; if (al.refQualifier()==RefQualifierLValue) result+=" &"; else if (al.refQualifier()==RefQualifierRValue) result+=" &&"; - if (!al.trailingReturnType().isEmpty()) result+=" -> "+al.trailingReturnType(); if (al.pureSpecifier()) result+=" =0"; return removeRedundantWhiteSpace(result); } I don't think this fix is not a fix but an undo of #8013 and should not be present (It certainly has nothing tho do with hyphenation). if (al.volatileSpecifier()) result+=" volatile"; if (al.refQualifier()==RefQualifierLValue) result+=" &"; else if (al.refQualifier()==RefQualifierRValue) result+=" &&"; + if (!al.trailingReturnType().isEmpty()) result+=al.trailingReturnType(); if (al.pureSpecifier()) result+=" =0"; return removeRedundantWhiteSpace(result); }
codereview_cpp_data_5744
} std::shared_ptr<const UniverseObject> Empire::Source() const { - // Make it safe to use with a null this pointer. - // This generates a compiler warning, but it enables the natural line of code of - // "GetEmpire(id)->Source()" without requiring an intervening null check - if (!this || m_eliminated) return nullptr; // Use the current source if valid Just have a GetSourceForEmpire(int id) function that can return nullptr. Not having a check that GetEmpire(id) didn't return nullptr is weird / misleading. } std::shared_ptr<const UniverseObject> Empire::Source() const { + if (m_eliminated) return nullptr; // Use the current source if valid
codereview_cpp_data_5745
void CalculateBoundsVisitor::visit(const shared_ptr<const Element>& e) { // TRICKY: We will be in trouble if our element is NOT a node - const Node * pNode = dynamic_cast<const Node *>(e.get()); - //const shared_ptr<const Node> n(e.get()); - // Note: OGREnvelope takes care of initializing & merging logic _envelope.Merge(pNode->getX(), pNode->getY()); } Should we throw a specific exception stating only node type is valid here? void CalculateBoundsVisitor::visit(const shared_ptr<const Element>& e) { // TRICKY: We will be in trouble if our element is NOT a node + if (e->getElementType() != ElementType::Node) + { + throw HootException("CalculateBoundsVisitor attempted to visit " + "element that is not a node!"); + } + // Merge node. OGREnvelope takes care of initializing & merging logic + const Node * pNode = dynamic_cast<const Node *>(e.get()); _envelope.Merge(pNode->getX(), pNode->getY()); }
codereview_cpp_data_5751
const char *kPeerFindFail = "Failed to find requested peer"; struct TimerWrapper : public val::FieldValidator { - TimerWrapper(iroha::ts64_t t) : FieldValidator(val::FieldValidator::kDefaultFutureGap, [=] { return t; }) {} }; Codacy asks to make the constructor `explicit` and I agree with it. const char *kPeerFindFail = "Failed to find requested peer"; struct TimerWrapper : public val::FieldValidator { + explicit TimerWrapper(iroha::ts64_t t) : FieldValidator(val::FieldValidator::kDefaultFutureGap, [=] { return t; }) {} };
codereview_cpp_data_5756
using namespace Battle; -namespace AI { - const double ANTIMAGIC_LOW_LIMIT = 200.0; double ReduceEffectivenessByDistance( const Unit & unit ) { // Reduce spell effectiveness if unit already crossed the battlefield Please use camelCase code style for variable naming. using namespace Battle; +namespace { + const double antimagicLowLimit = 200.0; +} +namespace AI +{ double ReduceEffectivenessByDistance( const Unit & unit ) { // Reduce spell effectiveness if unit already crossed the battlefield
codereview_cpp_data_5763
aClearSearch = new QAction(QString(), this); aClearSearch->setIcon(QIcon(":/resources/icon_clearsearch.svg")); connect(aClearSearch, SIGNAL(triggered()), this, SLOT(actClearSearch())); - searchEdit = new SearchLineEdit; searchEdit->addAction(QIcon(":/resources/icon_search_black.svg"), QLineEdit::LeadingPosition); searchEdit->setObjectName("searchEdit"); - searchEdit->setStyleSheet("#searchEdit{background:#DFE0E5;border-radius:13px;padding:5px 0px;}#searchEdit:focus{background:#EBEBEB;}"); setFocusProxy(searchEdit); setFocusPolicy(Qt::ClickFocus); I'd avoid to hardcode a style in the binary; it may look good in your box, but could appear incoherent under other os/desktop managers. Typically qt makes a good work at faking an os-integrated appearance, it could be nice to create external skin files (who remembers mIRC scripts with custom themes?) aClearSearch = new QAction(QString(), this); aClearSearch->setIcon(QIcon(":/resources/icon_clearsearch.svg")); connect(aClearSearch, SIGNAL(triggered()), this, SLOT(actClearSearch())); searchEdit = new SearchLineEdit; searchEdit->addAction(QIcon(":/resources/icon_search_black.svg"), QLineEdit::LeadingPosition); searchEdit->setObjectName("searchEdit"); + setFocusProxy(searchEdit); setFocusPolicy(Qt::ClickFocus);
codereview_cpp_data_5792
DebugLogger(combat) << "Attacker: " << attacker->Name(); // Set launching carrier as at least basically visible to other empires. - if (launches_event) { for (auto detector_empire_id : combat_info.empire_ids) { Visibility initial_vis = combat_info.empire_object_visibility[detector_empire_id][attacker_id]; TraceLogger(combat) << "Pre-attack visibility of launching carrier id: " << attacker_id does this test do anything? DebugLogger(combat) << "Attacker: " << attacker->Name(); // Set launching carrier as at least basically visible to other empires. + if (!launches_event->AreSubEventsEmpty(ALL_EMPIRES)) { for (auto detector_empire_id : combat_info.empire_ids) { Visibility initial_vis = combat_info.empire_object_visibility[detector_empire_id][attacker_id]; TraceLogger(combat) << "Pre-attack visibility of launching carrier id: " << attacker_id
codereview_cpp_data_5810
TermMsg("Invalid monster %d getting hit by monster", mid); } - if ( !monster[mid].MType ) { TermMsg("Monster %d \"%s\" getting hit by monster: MType NULL", mid, monster[mid].mName); } Pointer check ```suggestion if ( monster[mid].MType == NULL ) { ``` TermMsg("Invalid monster %d getting hit by monster", mid); } + if ( monster[mid].MType = NULL ) { TermMsg("Monster %d \"%s\" getting hit by monster: MType NULL", mid, monster[mid].mName); }
codereview_cpp_data_5813
void ServerApp::Run() { DebugLogger() << "FreeOrion server waiting for network events"; while (1) { if (m_io_service.run_one()) m_networking.HandleNextEvent(); Why? With this line, there is some indication of what's happening if the server process is run from command line. void ServerApp::Run() { DebugLogger() << "FreeOrion server waiting for network events"; + std::cout << "FreeOrion server waiting for network events" << std::endl; while (1) { if (m_io_service.run_one()) m_networking.HandleNextEvent();
codereview_cpp_data_5814
QPixmap UserLevelPixmapGenerator::generatePixmap(int height, UserLevelFlags userLevel, bool isBuddy, QString privLevel) { - int privkeysize = privLevel.size(); - if (privLevel.size() == 0) - privkeysize = 1; - int key = height * 10000 + (int)userLevel * 88 + (int)isBuddy * 54 + privkeysize * 31; if (pmCache.contains(key)) return pmCache.value(key); These magic numbers are quite hard to understand; also, using the length of `privLevel` as a key will cause collisions if in the future we'll add new levels. Maybe a better idea is to change the `pmCache` map to use string keys: ```cpp QMap<QString, QPixmap> UserLevelPixmapGenerator::pmCache; ``` and then generate the key like this: ```cpp QString key = QString::number(height * 10000 + (int) userLevel + (int) isBuddy) + privLevel; ``` QPixmap UserLevelPixmapGenerator::generatePixmap(int height, UserLevelFlags userLevel, bool isBuddy, QString privLevel) { + QString key = QString::number(height * 10000 + (int)userLevel + (int)isBuddy) + privLevel; if (pmCache.contains(key)) return pmCache.value(key);
codereview_cpp_data_5830
Text::Text( const Text & t ) { assert( t.message != nullptr ); - message = new TextAscii( static_cast<TextAscii &>( *t.message ) ); gw = t.gw; gh = t.gh; :warning: **cppcoreguidelines-pro-type-static-cast-downcast** :warning: do not use static_cast to downcast from a base to a derived class; use dynamic_cast instead ```suggestion message = new TextAscii( dynamic_cast<TextAscii &>( *t.message ) ); ``` Text::Text( const Text & t ) { assert( t.message != nullptr ); + message = new TextAscii( dynamic_cast<TextAscii &>( *t.message ) ); gw = t.gw; gh = t.gh;
codereview_cpp_data_5835
for ( i=1; i<argc; ++i ) { char *pt = argv[i]; - if ( strcmp(pt,"-SkipPythonInitFiles")==0 ) { run_python_init_files = false; - } else if ( strcmp(pt,"-SkipPythonPlugins")==0 ) { import_python_plugins = false; } } Wow, this is so inconsistent from the rest of the cmdline arguments (lower case). Although looking at the blame on `SkipPythonInitFiles` I can see why... fwiw neither your new flag or the old are in the help text. for ( i=1; i<argc; ++i ) { char *pt = argv[i]; + if ( strcmp(pt,"-SkipPythonInitFiles")==0 || strcmp(pt,"-skippyfile")==0 ) { run_python_init_files = false; + } else if ( strcmp(pt,"-skippyplug")==0 ) { import_python_plugins = false; } }
codereview_cpp_data_5836
#include "reaxc_ffield.h" #include "reaxc_tool_box.h" -#include "lammps.h" -#include "error.h" char Read_Force_Field( FILE *fp, reax_interaction *reax, control_params *control ) it should be sufficient to include only "error.h" here. #include "reaxc_ffield.h" #include "reaxc_tool_box.h" char Read_Force_Field( FILE *fp, reax_interaction *reax, control_params *control )
codereview_cpp_data_5837
#define STR(var) #var #define MAKE_VERSION_STRING(maj,min,build) STR(maj.min.build) #define MAKE_COPYRIGHT_STRING(y,a) \ - "Copyright (c) 2005-2016 Stanford University, " STR(a) #define MAKE_STRING(a) STR(a) #define GET_VERSION_STRING \ What was the reason for changing this? #define STR(var) #var #define MAKE_VERSION_STRING(maj,min,build) STR(maj.min.build) #define MAKE_COPYRIGHT_STRING(y,a) \ + "Copyright (c) " STR(y) " Stanford University, " STR(a) #define MAKE_STRING(a) STR(a) #define GET_VERSION_STRING \
codereview_cpp_data_5844
const auto& vals = m_weights[i]->get_values(); if (vals.Participating() && vals.GetLocalDevice() == El::Device::GPU - && vals.RedundantRank() == i % vals.RedundantSize()) { - if (vals.LocalWidth() < 1 || vals.LocalHeight() < 1) { - } else if (vals.LocalWidth() == 1 - || vals.LDim() == vals.LocalHeight()) { cublas::dot(handle, vals.LocalHeight() * vals.LocalWidth(), vals.LockedBuffer(), 1, Might be more clear to just have one if statement? const auto& vals = m_weights[i]->get_values(); if (vals.Participating() && vals.GetLocalDevice() == El::Device::GPU + && vals.RedundantRank() == i % vals.RedundantSize() + && vals.LocalWidth() > 0 && vals.LocalHeight() > 0) { + if (vals.LocalWidth() == 1 || vals.LDim() == vals.LocalHeight()) { cublas::dot(handle, vals.LocalHeight() * vals.LocalWidth(), vals.LockedBuffer(), 1,
codereview_cpp_data_5846
RTPSDomain::t_p_RTPSParticipant& participant) { // The destructor of RTPSParticipantImpl already deletes the associated RTPSParticipant and sets - // its pointter to the RTPSParticipant to nullptr, so there is no need to do it here manually. delete(participant.second); } ```suggestion // its pointer to the RTPSParticipant to nullptr, so there is no need to do it here manually. ``` RTPSDomain::t_p_RTPSParticipant& participant) { // The destructor of RTPSParticipantImpl already deletes the associated RTPSParticipant and sets + // its pointer to the RTPSParticipant to nullptr, so there is no need to do it here manually. delete(participant.second); }
codereview_cpp_data_5849
const Heroes * from_hero = Interface::GetFocusHeroes(); const Heroes * guardian = castle.GetHeroes().Guard(); - const int thievesGuildCount = world.GetKingdom( conf.GetPlayers().current_color ).GetCountThievesGuild(); // draw guardian portrait if ( guardian && // my colors - ( castle.isFriends( conf.CurrentColor() ) || // show guardians (scouting: advanced) ( from_hero && Skill::Level::ADVANCED <= from_hero->GetSecondaryValues( Skill::Secondary::SCOUTING ) ) ) ) { // heroes name Instead of `conf.GetPlayers().current_color` please use `castle.GetColor()`. const Heroes * from_hero = Interface::GetFocusHeroes(); const Heroes * guardian = castle.GetHeroes().Guard(); + const int currentColor = castle.GetColor(); + const int thievesGuildCount = world.GetKingdom( currentColor ).GetCountThievesGuild(); // draw guardian portrait if ( guardian && // my colors + ( castle.isFriends( currentColor ) || // show guardians (scouting: advanced) ( from_hero && Skill::Level::ADVANCED <= from_hero->GetSecondaryValues( Skill::Secondary::SCOUTING ) ) ) ) { // heroes name
codereview_cpp_data_5852
if ( distance == 0 ) return value; // scale non-linearly (more value lost as distance increases) - return value - ( 1.5 * distance * std::log10( distance ) ); } double Normal::getObjectValue( const Heroes & hero, int index, int objectID, double valueToIgnore ) const This can potentially break a lot of other logic since AI heroes will focus on objects close to them (e.g. picking up resource instead of capturing a mine). if ( distance == 0 ) return value; // scale non-linearly (more value lost as distance increases) + return value - ( distance * std::log10( distance ) ); } double Normal::getObjectValue( const Heroes & hero, int index, int objectID, double valueToIgnore ) const
codereview_cpp_data_5853
int iseed = 451; Real mass = 10.0; - MyParticleContainer::ParticleInitData pdata = {mass, AMREX_D_DECL(1.0, 2.0, 3.0), {}, {}, {}}; myPC.InitRandom(num_particles, iseed, pdata, serialize); myPC.AssignCellDensitySingleLevel(0, partMF, 0, 4, 0); ```suggestion MyParticleContainer::ParticleInitData pdata = {{mass, AMREX_D_DECL(1.0, 2.0, 3.0)}, {}, {}, {}}; ``` Thanks for fixing these warnings. With clang, it also complains unless we insert these extra brackets around the real struct data part. int iseed = 451; Real mass = 10.0; + MyParticleContainer::ParticleInitData pdata = {{mass, AMREX_D_DECL(1.0, 2.0, 3.0)}, {}, {}, {}}; myPC.InitRandom(num_particles, iseed, pdata, serialize); myPC.AssignCellDensitySingleLevel(0, partMF, 0, 4, 0);
codereview_cpp_data_5859
////////////////////////// // PERFORM A SIMULATION // ///////////////////////// - - osimModel.setUseVisualizer(true); // Initialize the system and get the default state SimTK::State& si = osimModel.initSystem(); Next, use the environment variable in the code here. ////////////////////////// // PERFORM A SIMULATION // ///////////////////////// + const char* env_p = std::getenv("OPENSIM_USE_VISUALIZER"); + // if environment variable OPENSIM_USE_VISUALIZER is unset or not 0 + // then turn on visualization + if (!env_p || *env_p!='0') + osimModel.setUseVisualizer(true); // Initialize the system and get the default state SimTK::State& si = osimModel.initSystem();