id
stringlengths
21
25
content
stringlengths
164
2.33k
codereview_cpp_data_9370
char **jx_match_string(struct jx *j, char **v) { if (jx_istype(j, JX_STRING)) { if (v) { - *v = strdup(j->u.string_value); } return &j->u.string_value; } else { Here, as per our discussion, I think if the strdup fails we should return NULL. That way if the match is successful we know that v is also usable if requested. This can be bypassed by setting v to NULL as a parameter in the case were you just want a point. char **jx_match_string(struct jx *j, char **v) { if (jx_istype(j, JX_STRING)) { if (v) { + if (!(*v = strdup(j->u.string_value))) return NULL; } return &j->u.string_value; } else {
codereview_cpp_data_9395
if (node->data.scalar[0] == '\0') { self->vars->mruby_handler_path = h2o_iovec_init(NULL, 0); } else { - self->vars->mruby_handler_path = h2o_strdup(NULL, node->data.scalar, - strlen(node->data.scalar)); h2o_mruby_register(ctx->pathconf, self->vars); } return 0; You do not need to duplicate the string here, since it is guaranteed that the data in `yoml_t` will not be freed until the configuration completes. I suggest to stop calling `h2o_strdup` here (since if you do so you would need to free it somewhere else, which does not seem to be done), and instead do the duplication within `h2o_mruby_register`. if (node->data.scalar[0] == '\0') { self->vars->mruby_handler_path = h2o_iovec_init(NULL, 0); } else { + self->vars->mruby_handler_path = h2o_iovec_init(node->data.scalar, strlen(node->data.scalar)); h2o_mruby_register(ctx->pathconf, self->vars); } return 0;
codereview_cpp_data_9409
/** - * @file kadane.cpp * @brief Implementation of [Kadane * Algorithm] (https://en.wikipedia.org/wiki/Kadane%27s_algorithm) * ```suggestion } } // namespace dynamic_programming ``` /** + * @file * @brief Implementation of [Kadane * Algorithm] (https://en.wikipedia.org/wiki/Kadane%27s_algorithm) *
codereview_cpp_data_9411
{ struct s2n_config *config = s2n_config_new(); - struct s2n_connection *conn = s2n_connection_new(S2N_SERVER); s2n_connection_set_config(conn, config); const struct s2n_security_policy *security_policy = NULL; Why is this changing? { struct s2n_config *config = s2n_config_new(); + struct s2n_connection *conn = s2n_connection_new(S2N_CLIENT); s2n_connection_set_config(conn, config); const struct s2n_security_policy *security_policy = NULL;
codereview_cpp_data_9415
} } -int Component::constructOutputForStateVariable(const std::string& name) { return constructOutput<double>(name, std::bind(&Component::getStateVariableValue, Should we settle now to use `SimTK_DEFINE_UNIQUE_INDEX_TYPE()`? instead of an int? With the potential of having many indices I like using the unique index to thwart accidentally mixing indices up. } } +Component::OutputIndex +Component::constructOutputForStateVariable(const std::string& name) { return constructOutput<double>(name, std::bind(&Component::getStateVariableValue,
codereview_cpp_data_9419
auto storage = static_cast<MutableStorageImpl *>(mutable_storage.get()); storage->block_storage_->forEach( - [this](auto, const auto &block) { this->storeBlock(*block); }); try { *(storage->sql_) << "COMMIT"; storage->committed = true; This line looks a bit unclear, could you explain please why it's necessary? auto storage = static_cast<MutableStorageImpl *>(mutable_storage.get()); storage->block_storage_->forEach( + [this](const auto &block) { this->storeBlock(*block); }); try { *(storage->sql_) << "COMMIT"; storage->committed = true;
codereview_cpp_data_9421
void AddTown(int mi, int sx, int sy, int dx, int dy, int midir, char mienemy, int id, int dam) { int i, j, k, mx, tx, ty; - -#ifndef HELLFIRE int CrawlNum[6] = { 0, 3, 12, 45, 94, 159 }; -#endif tx = dx; if (currlevel) { Seems you got more in your commit than you expected ;) We don't need AddTown here void AddTown(int mi, int sx, int sy, int dx, int dy, int midir, char mienemy, int id, int dam) { int i, j, k, mx, tx, ty; int CrawlNum[6] = { 0, 3, 12, 45, 94, 159 }; tx = dx; if (currlevel) {
codereview_cpp_data_9426
{ if (listener_ == listener) { - return ReturnCode_t::RETCODE_ERROR; } listener_ = listener; return ReturnCode_t::RETCODE_OK; This behavior isn't standard. Should we change it and return always `RETCODE_OK` even if wasn't modified? { if (listener_ == listener) { + return ReturnCode_t::RETCODE_OK; } listener_ = listener; return ReturnCode_t::RETCODE_OK;
codereview_cpp_data_9431
diff = 0; } - if (real_diff != 0) { - flb_debug("[input chunk] update output instances with new chunk size diff=%d", - real_diff); - flb_input_chunk_update_output_instances(ic, real_diff); - } - /* Lock buffers where size > 2MB */ if (size > FLB_INPUT_CHUNK_FS_MAX_SIZE) { cio_chunk_lock(ic->chunk); Could you add the chunk name to the debug message? If the similar issue happened in the future, we could have some `audit` logs on the change to the chunk size update. diff = 0; } /* Lock buffers where size > 2MB */ if (size > FLB_INPUT_CHUNK_FS_MAX_SIZE) { cio_chunk_lock(ic->chunk);
codereview_cpp_data_9436
SimTK_TEST(table.getNumColumns() == numColumns); SimTK_TEST(table.getNumRows() == states.getSize()); - const auto& colNames = table.getDependentsMetaData() - .getValueArrayForKey("labels"); // Test that the data table has exactly the same numbers. for (int itime = 0; itime < states.getSize(); ++itime) { This is ugly too. You can now use `table.getColumnLabels()` you suggested I add to DataTable. SimTK_TEST(table.getNumColumns() == numColumns); SimTK_TEST(table.getNumRows() == states.getSize()); + const auto& colNames = table.getColumnLabels(); // Test that the data table has exactly the same numbers. for (int itime = 0; itime < states.getSize(); ++itime) {
codereview_cpp_data_9440
void MessageLogWidget::logAlwaysLookAtTopCard(Player *player, CardZone *zone, bool reveal) { - appendHtmlServerMessage((reveal ? tr("%1 is now looking at top card of their deck at any time.") - : tr("%1 is no longer looking at top card of their deck at any time.")) .arg(sanitizeHtml(player->getName())) .arg(zone->getTranslatedName(true, CaseTopCardsOfZone))); } in the interest of keeping the log messages short I think something like can now look at the top of their library at any time is better here. also note that %2 is replaced with the name of the zone, in this case the library. void MessageLogWidget::logAlwaysLookAtTopCard(Player *player, CardZone *zone, bool reveal) { + appendHtmlServerMessage((reveal ? tr("%1 can now look at top card %2 at any time.") + : tr("%1 no longer can look at top card %2 at any time.")) .arg(sanitizeHtml(player->getName())) .arg(zone->getTranslatedName(true, CaseTopCardsOfZone))); }
codereview_cpp_data_9443
shared_ptr<const Element> e1 = map->getElement(it->first); shared_ptr<const Element> e2 = map->getElement(it->second); //LOG_INFO(e1->getTags()["note"] << " <=> " << e2->getTags()["note"]); - CPPUNIT_ASSERT_EQUAL(e1->getTags()["note"].toStdString(), e2->getTags()["note"].toStdString()); } } You can use HOOT_STR_EQUALS to avoid the .toStdString() call. Handy for other comparisons too. shared_ptr<const Element> e1 = map->getElement(it->first); shared_ptr<const Element> e2 = map->getElement(it->second); //LOG_INFO(e1->getTags()["note"] << " <=> " << e2->getTags()["note"]); + HOOT_STR_EQUALS(e1->getTags()["note"], e2->getTags()["note"]) } }
codereview_cpp_data_9444
return false; if (! ServerDB::serverExists(srvnum)) return false; - if (! ServerDB::getConf(srvnum, "autostart",Meta::mp.bAutoStart).toBool()) - return false; Server *s = new Server(srvnum, this); if (! s->bValid) { delete s; I don't think it's a good idea to handle it this way. When this function is called, the server should start. Instead I think this setting should be checked inside `Meta:bootAll()` - maybe even extend the function's signature to be `void bootAll(bool respectAutostartConfig)` and only check the config if `respectAutostartConfig` is `true` return false; if (! ServerDB::serverExists(srvnum)) return false; Server *s = new Server(srvnum, this); if (! s->bValid) { delete s;
codereview_cpp_data_9451
* it's never accessed anywhere else without a check for it being * NULL first */ - if(metaLenUncompressed == (uint32_t)0xffffffff) { LogError(_("WOFF uncompressed metadata section too large.\n")); sf->woffMetadata = NULL; return( sf ); } - if(metaLenCompressed == (uint32_t)0xffffffff) { LogError(_("WOFF compressed metadata section too large.\n")); sf->woffMetadata = NULL; return( sf ); Actually, we might want to do `0xffffffffLU` here (still with the cast) just to be safe. @jtanx? * it's never accessed anywhere else without a check for it being * NULL first */ + if(metaLenUncompressed == (uint32_t)0xffffffffLU) { LogError(_("WOFF uncompressed metadata section too large.\n")); sf->woffMetadata = NULL; return( sf ); } + if(metaLenCompressed == (uint32_t)0xffffffffLU) { LogError(_("WOFF compressed metadata section too large.\n")); sf->woffMetadata = NULL; return( sf );
codereview_cpp_data_9455
{ if((*rit)->matched_writer_remove(writer_guid)) { - GUID_t reader_guid = (*rit)->getGuid(); #if HAVE_SECURITY mp_RTPSParticipant->security_manager().remove_writer(reader_guid, participant_guid, writer_guid); ```suggestion const GUID_t& reader_guid = (*rit)->getGuid(); ``` { if((*rit)->matched_writer_remove(writer_guid)) { + const GUID_t& reader_guid = (*rit)->getGuid(); #if HAVE_SECURITY mp_RTPSParticipant->security_manager().remove_writer(reader_guid, participant_guid, writer_guid);
codereview_cpp_data_9462
}; /** - * @given initialized storage with 4 peers, second block with add peer - * command, third block signed by new peer, blocks are signed by supermajority - * of ledger peers - * @when chain with second and third blocks is validated * @then result is successful */ TEST_F(ChainValidatorStorageTest, PeerAdded) { Telling honestly, I understood nothing from the raw description of test without looking to the code. Can you please reformulate it a bit, for example, by reflecting blocks states as elements of list? }; /** + * @given initialized storage + * block 1 - initial block with 4 peers + * block 2 - new peer added. signed by supermajority of ledger peers + * block 3 - signed by supermajority of ledger peers, contains signature of + * new peer + * @when blocks 2 and 3 are validated * @then result is successful */ TEST_F(ChainValidatorStorageTest, PeerAdded) {
codereview_cpp_data_9474
// download (our chain will now not sync until the next block announcement is received). Therefore, if the // best invalid chain work is still greater than our chaintip then we have to keep looking for more blocks // to download. - if (!IsChainSyncd() || (pindexBestInvalid.load() && chainActive.Tip() && - pindexBestInvalid.load()->nChainWork > chainActive.Tip()->nChainWork)) { TRY_LOCK(cs_main, locked); if (locked) you need to store pindexBestInvalid.load() and chainActive.Tip() in temporaries since they could be nullified between the 2 calls. // download (our chain will now not sync until the next block announcement is received). Therefore, if the // best invalid chain work is still greater than our chaintip then we have to keep looking for more blocks // to download. + // + // Use temporaries for the chain tip and best invalid because they are both atomics and either could + // be nullified between the two calls. + CBlockIndex *pTip = chainActive.Tip(); + CBlockIndex *pBestInvalid = pindexBestInvalid.load(); + if (!IsChainSyncd() || (pBestInvalid && pTip && pBestInvalid->nChainWork > pTip->nChainWork)) { TRY_LOCK(cs_main, locked); if (locked)
codereview_cpp_data_9475
wl_signal_emit(&view->events.destroy, view); free(view); } destroy event normally goes first before all the extra cleanup is done. wl_signal_emit(&view->events.destroy, view); + if (view->destroy) { + view->destroy(view); + } + free(view); }
codereview_cpp_data_9477
args.push_back("\"" + AI_CLIENT_EXE + "\""); args.push_back("place_holder"); size_t player_pos = args.size()-1; - std::stringstream maxAggrStr; - maxAggrStr << max_aggression; - args.push_back(maxAggrStr.str()); args.push_back("--resource-dir"); args.push_back("\"" + GetOptionsDB().Get<std::string>("resource-dir") + "\""); args.push_back("--log-level"); not original to this PR, but should be renamed `max_aggr_str` args.push_back("\"" + AI_CLIENT_EXE + "\""); args.push_back("place_holder"); size_t player_pos = args.size()-1; + std::stringstream max_aggr_str; + max_aggr_str << max_aggression; + args.push_back(max_aggr_str.str()); args.push_back("--resource-dir"); args.push_back("\"" + GetOptionsDB().Get<std::string>("resource-dir") + "\""); args.push_back("--log-level");
codereview_cpp_data_9486
} if (available_fighters > 0 && !part_fighter_launch_capacities.empty()) { - for (std::multimap<std::string, int>::iterator launch_it = part_fighter_launch_capacities.begin(); launch_it != part_fighter_launch_capacities.end(); ++launch_it) { int to_launch = std::min(launch_it->second, available_fighters); Gives a compiler error (MSVC 2010, Win7). Fixed by changing to `std::map::iterator`. If multimap is indeed intended, need to switch the type of `part_fighter_launch_capacities`... } if (available_fighters > 0 && !part_fighter_launch_capacities.empty()) { + for (std::map<std::string, int>::iterator launch_it = part_fighter_launch_capacities.begin(); launch_it != part_fighter_launch_capacities.end(); ++launch_it) { int to_launch = std::min(launch_it->second, available_fighters);
codereview_cpp_data_9489
mparams.setKFactor(kFact); if (matrix != NULL) { - //std::cout << "MechanicalAddMBK_ToMatrixVisitor "<< mFact << " " << bFact << " " << kFact << " " << offset << std::endl; - executeVisitor( MechanicalAddMBK_ToMatrixVisitor(&mparams /* PARAMS FIRST */, matrix) ); - executeVisitor( MechanicalAddProjectiveConstraint_ToMatrixVisitor(&mparams /* PARAMS FIRST */, matrix) ); } } STRONGLY disagree about always applying the projection matrix in the addMBK visitor. It completely depends on the numerical solver you are using. After projection MBK is no longer positive definite. + mappings can also add geometric stiffness that would not be projected. Did you make modifications in numerical solvers by considering the MBK matrix as always projected? mparams.setKFactor(kFact); if (matrix != NULL) { + executeVisitor( MechanicalAddMBK_ToMatrixVisitor(&mparams, matrix) ); + executeVisitor( MechanicalAddProjectiveConstraint_ToMatrixVisitor(&mparams, matrix) ); } }
codereview_cpp_data_9508
#ifdef ENABLE_LOG_PERFORMANCE -#ifdef WIN32 //thread_local std::array<char, LOGGER_CHUNKS_SIZE> SimpleLogger::mBuffer; #else __thread std::array<char, LOGGER_CHUNKS_SIZE> SimpleLogger::mBuffer; ```suggestion #ifdef _WIN64 thread_local std::array<char, LOGGER_CHUNKS_SIZE> SimpleLogger::mBuffer; // Keep this as a normal class member on WIN32 until we abandon XP (Qt fonts appear with strikethrough on XP otherwise) #endif ``` #ifdef ENABLE_LOG_PERFORMANCE +#ifdef WIN64 +thread_local std::array<char, LOGGER_CHUNKS_SIZE> SimpleLogger::mBuffer; +#elif WIN32 //thread_local std::array<char, LOGGER_CHUNKS_SIZE> SimpleLogger::mBuffer; #else __thread std::array<char, LOGGER_CHUNKS_SIZE> SimpleLogger::mBuffer;
codereview_cpp_data_9513
return ihipLogStatus(hip_status); } -hipError_t ihipBindTextureToArrayImpl(TlsData *tls, int dim, enum hipTextureReadMode readMode, hipArray_const_t array, const struct hipChannelFormatDesc& desc, textureReference* tex) { hipError_t hip_status = hipSuccess; enum hipTextureAddressMode addressMode = tex->addressMode[0]; enum hipTextureFilterMode filterMode = tex->filterMode; ```ihipBindTextureToArrayImpl``` is used by the cplusplus variants of ```hipBindTextureToArrray``` defined in include/hip/hcc_detail/hip_runtime_api.h. Hence this change breaks the unit test directed_test/texture/hipTextureRef2D. return ihipLogStatus(hip_status); } +hipError_t ihipBindTextureToArrayImpl(TlsData *tls_, int dim, enum hipTextureReadMode readMode, hipArray_const_t array, const struct hipChannelFormatDesc& desc, textureReference* tex) { + TlsData *tls = (tls_ == nullptr) ? tls_get_ptr() : tls_; hipError_t hip_status = hipSuccess; enum hipTextureAddressMode addressMode = tex->addressMode[0]; enum hipTextureFilterMode filterMode = tex->filterMode;
codereview_cpp_data_9516
{ } -static void engineThrowUp(const std::string &engineType, const std::string &func) { throw std::invalid_argument( Use `UpperCamelCase` for function names { } +static void EngineThrowUp(const std::string &engineType, const std::string &func) { throw std::invalid_argument(
codereview_cpp_data_9520
input[1] = Flip( input[1], true, false ); input[3] = Flip( input[3], true, false ); - Sprite out = ExtractCommonPattern( input ); // Here are 2 pixels which should be removed. if ( out.width() == width && out.height() == height ) { :warning: **cppcoreguidelines\-slicing** :warning: slicing object from type `` Sprite `` to `` Image `` discards 11 bytes of state input[1] = Flip( input[1], true, false ); input[3] = Flip( input[3], true, false ); + Image out = ExtractCommonPattern( input ); // Here are 2 pixels which should be removed. if ( out.width() == width && out.height() == height ) {
codereview_cpp_data_9524
this->ResetEngine(); try { this->engine->LoadScript(filename); - } catch (Script_FatalError e) { DEBUG(script, 0, "Fatal error '%s' when trying to load the script '%s'.", e.GetErrorMessage(), filename); return false; } The general recommendation is to catch exceptions by reference to avoid copy constructors being run during exception handling. this->ResetEngine(); try { this->engine->LoadScript(filename); + } catch (Script_FatalError &e) { DEBUG(script, 0, "Fatal error '%s' when trying to load the script '%s'.", e.GetErrorMessage(), filename); return false; }
codereview_cpp_data_9527
connect(settingsCache, SIGNAL(horizontalHandChanged()), this, SLOT(rearrangeZones())); connect(settingsCache, SIGNAL(handJustificationChanged()), this, SLOT(rearrangeZones())); - zoneId = 0; - playerArea = new PlayerArea(this); playerTarget = new PlayerTarget(this, playerArea, game); initialize this together with the rest 5 lines up please connect(settingsCache, SIGNAL(horizontalHandChanged()), this, SLOT(rearrangeZones())); connect(settingsCache, SIGNAL(handJustificationChanged()), this, SLOT(rearrangeZones())); playerArea = new PlayerArea(this); playerTarget = new PlayerTarget(this, playerArea, game);
codereview_cpp_data_9530
Impl::SYCLInternal::singleton().initialize(d.get_device()); } -std::ostream& SYCL::info(std::ostream& os, const sycl::device& device) { using namespace sycl::info; return os << "Name: " << device.get_info<device::name>() << "\nDriver Version: " << device.get_info<device::driver_version>() How about naming this impl_sycl_info. I am not insisting on it, but it took me a while to recognize this is a private function and thus its fine to have it as something which isn't part of the execution space concept. Since its private I am not against it, we may actually jsut want to discuss in the next meeting naming practices for private functions - if we want one or not. Impl::SYCLInternal::singleton().initialize(d.get_device()); } +std::ostream& SYCL::impl_sycl_info(std::ostream& os, + const sycl::device& device) { using namespace sycl::info; return os << "Name: " << device.get_info<device::name>() << "\nDriver Version: " << device.get_info<device::driver_version>()
codereview_cpp_data_9542
if(change_size) { hash_table_firstkey(d->files); - while(hash_table_nextkey(d->files, &name, (void **) &f) && dag_file_exists(f)) { - stat(name, &st); - average += ((double) st.st_size) / ((double) d->completed_files); } } This stat may fail, right? I think dag_file_exists does not actually check the file is there. if(change_size) { hash_table_firstkey(d->files); + while(hash_table_nextkey(d->files, &name, (void **) &f) && dag_file_should_exist(f)) { + if(stat(name,&st)==0) { + average += ((double) st.st_size) / ((double) d->completed_files); + } } }
codereview_cpp_data_9548
SFXSource* source = NULL; if( track ) { - if( x == "" ) { source = SFX->playOnce( track ); } This one `if (dStrcmp(x, "") == 0)` 'ified too. SFXSource* source = NULL; if( track ) { + if (dStrcmp(x, "") == 0) { source = SFX->playOnce( track ); }
codereview_cpp_data_9571
int s2n_server_extensions_send(struct s2n_connection *conn, struct s2n_stuffer *out) { - if (conn->secure.cipher_suite->key_exchange_alg == NULL) { - return 0; - } - uint16_t total_size = 0; const uint8_t application_protocol_len = strlen(conn->application_protocol); hmm, so you don't want to send any extensions when this is NULL? that seems like overkill. perhaps you simply mean to change line 100: ``` if (conn->secure.cipher_suite->key_exchange_alg) { GUARD(s2n_kex_write_server_extension(conn->secure.cipher_suite->key_exchange_alg, conn, out)); } ``` int s2n_server_extensions_send(struct s2n_connection *conn, struct s2n_stuffer *out) { uint16_t total_size = 0; const uint8_t application_protocol_len = strlen(conn->application_protocol);
codereview_cpp_data_9577
if (_database.getDB().isOpen()) { throw HootException( - "Database already open. Close the existing database connection before opening a new one."); } // Make sure we're not already open and the URL is valid could you say: ```if (!_unresolvedRefs.unresolvedRelationRefs)``` here, instead of the comparison with an empty shared ptr? if (_database.getDB().isOpen()) { throw HootException( + QString("Database already open. Close the existing database connection before opening ") + + QString("a new one. URL: ") + url); } // Make sure we're not already open and the URL is valid
codereview_cpp_data_9582
const int64_t padding = shmem_size * 10 / 100; // Padding per team. // FIXME_OPENMPTARGET - Total amount of scratch memory allocated is depenedent // on the maximum number of teams possible. Currently the maximum number of - // teams possible is calculated based on NVIDIA's Volta GPU and assuming that - // the number of threads per threadblock will not exceed 1024 threads. In // future this value should be based on the chosen architecture for the // OpenMPTarget backend. - int64_t total_size = (shmem_size + 16 + padding) * ((1024 * 80) / team_size); if (total_size > m_scratch_size) { space.deallocate(m_scratch_ptr, m_scratch_size); we probably need to build our own list for this, how fun ... const int64_t padding = shmem_size * 10 / 100; // Padding per team. // FIXME_OPENMPTARGET - Total amount of scratch memory allocated is depenedent // on the maximum number of teams possible. Currently the maximum number of + // teams possible is calculated based on NVIDIA's Volta GPU. In // future this value should be based on the chosen architecture for the // OpenMPTarget backend. + int64_t total_size = (shmem_size + 16 + padding) * ((2048 * 80) / team_size); if (total_size > m_scratch_size) { space.deallocate(m_scratch_ptr, m_scratch_size);
codereview_cpp_data_9586
} /* exactly like s2n_choose_sig_scheme() without matching client's preference */ -static int s2n_preferred_sig_scheme(struct s2n_connection *conn, struct s2n_signature_scheme *chosen_scheme_out) { notnull_check(conn); const struct s2n_signature_preferences *signature_preferences = NULL; How about modifying the `s2n_choose_sig_scheme` to fallback to top preferred if no match with client list is made? } /* exactly like s2n_choose_sig_scheme() without matching client's preference */ +static int s2n_tls13_preferred_sig_scheme(struct s2n_connection *conn, struct s2n_signature_scheme *chosen_scheme_out) { notnull_check(conn); const struct s2n_signature_preferences *signature_preferences = NULL;
codereview_cpp_data_9587
cmd("spt"); arg("p", deviceType); arg("t", token); - notself(client); tag = client->reqtag; } Is it needed a `notself` here? I mean, does this command generate an any action packet? cmd("spt"); arg("p", deviceType); arg("t", token); + tag = client->reqtag; }
codereview_cpp_data_9592
return request_reject_round == reject_round or (request_reject_round >= 2 and reject_round >= 2); }); - // add log } std::for_each(unprocessed_batches.begin(), unprocessed_batches.end(), please add log return request_reject_round == reject_round or (request_reject_round >= 2 and reject_round >= 2); }); + log_->info( + "Using round [{}, {}]", it->first.block_round, it->first.reject_round); } std::for_each(unprocessed_batches.begin(), unprocessed_batches.end(),
codereview_cpp_data_9600
return val >= _timeRange[0] && val <= _timeRange[1]; }); - auto avgRow = staticPoseTable.averageRow(_timeRange[0], _timeRange[1]); for(int r = staticPoseTable.getNumRows() - 1; r >= 0; --r) { if(staticPoseTable.getIndependentColumn()[r] >= _timeRange[0] && staticPoseTable.getIndependentColumn()[r] <= _timeRange[1]) { if using the `staticPoseTable` below to create the `MarkersReference` why not remove `staticPose` now since it seems to be unused? return val >= _timeRange[0] && val <= _timeRange[1]; }); + const auto avgRow = staticPoseTable.averageRow(_timeRange[0], + _timeRange[1]); for(int r = staticPoseTable.getNumRows() - 1; r >= 0; --r) { if(staticPoseTable.getIndependentColumn()[r] >= _timeRange[0] && staticPoseTable.getIndependentColumn()[r] <= _timeRange[1]) {
codereview_cpp_data_9608
request = new MegaRequestPrivate(MegaRequest::TYPE_FETCH_NODES); } -#ifdef ENABLE_SYNC - const bool resumeSyncs = request->getFlag(); - // resetting to default in case it was set by fetchNodes() - request->setFlag(false); -#endif - if (e == API_OK) { // check if we fetched a folder link and the key is invalid Rather than overwrite an input param, as suggested above, use a different field in the `MegaRequest` to store the new input flag. That way, you can avoid some mistakes when the fetchnodes sets the flag to true :) request = new MegaRequestPrivate(MegaRequest::TYPE_FETCH_NODES); } if (e == API_OK) { // check if we fetched a folder link and the key is invalid
codereview_cpp_data_9618
#define ERR_STR_CASE(ERR, str) case ERR: return str; #define ERR_NAME_CASE(ERR, str) case ERR: return #ERR; void s2n_clear_error() { s2n_errno = S2N_ERR_T_OK; Does this need to be annotated with `S2N_API`? Are users allowed to call it? #define ERR_STR_CASE(ERR, str) case ERR: return str; #define ERR_NAME_CASE(ERR, str) case ERR: return #ERR; +S2N_API void s2n_clear_error() { s2n_errno = S2N_ERR_T_OK;
codereview_cpp_data_9619
"Cannot cast uninferred numeric literal"); ast_error_continue(opt->check.errors, expr, "To give a numeric literal a specific type, " - "use constructor of primitive"); return AST_ERROR; default: break; Good error message! But I think we can be a little more clear here to give the user a little extra help - I worry that `primitive` may be confusing because the user may not be thinking of the numeric types as primitives (they are primitives, but that's a bit of a detail we might not expect them to know) So, instead of "use constructor of primitive", I'd say "use the constructor of that numeric type". "Cannot cast uninferred numeric literal"); ast_error_continue(opt->check.errors, expr, "To give a numeric literal a specific type, " + "use the constructor of that numeric type"); return AST_ERROR; default: break;
codereview_cpp_data_9641
break; case LONG_OPT_SHARED_FS: assert(shared_fs); - s = string_combine(xxstrdup(optarg), "/"); - t = realpath(s, NULL); - free(s); - if (!t) fatal("can't access shared filesystem %s: %s", optarg, strerror(errno)); - list_push_head(shared_fs, string_combine(t, "/")); break; case LONG_OPT_DOCKER: if(!wrapper) wrapper = makeflow_wrapper_create(); @trshaffer It looks like you might be appending the trailing slash twice (here and 1543)? Changing 1547 to this makes my makeflow script work: ``` list_push_head(shared_fs, t); ``` break; case LONG_OPT_SHARED_FS: assert(shared_fs); + list_push_head(shared_fs, xxstrdup(optarg)); break; case LONG_OPT_DOCKER: if(!wrapper) wrapper = makeflow_wrapper_create();
codereview_cpp_data_9660
xwayland_surface->width = event->width; xwayland_surface->height = event->height; - roots_surface->view->x = (double) event->x; - roots_surface->view->y = (double) event->y; wlr_xwayland_surface_configure(roots_surface->view->desktop->xwayland, xwayland_surface); Drop the spaces after `(double)` xwayland_surface->width = event->width; xwayland_surface->height = event->height; + roots_surface->view->x = (double)event->x; + roots_surface->view->y = (double)event->y; wlr_xwayland_surface_configure(roots_surface->view->desktop->xwayland, xwayland_surface);
codereview_cpp_data_9672
namespace lbann { template <typename TensorDataType> -void buffered_data_coordinator<TensorDataType>::register_active_data_field(data_field_type const data_field) { data_coordinator::register_active_data_field(data_field); for (const auto& buf_map : m_data_buffers) { const data_buffer_map_t& buffer_map = buf_map; In principle this check shouldn't be necessary. I could imagine cases where you run a model without the data coordinator ever fetching data (e.g. testing). Do we expect to run into weirdness if we remove it, like in batch size calculation? namespace lbann { template <typename TensorDataType> +void buffered_data_coordinator<TensorDataType>::register_active_data_field( + data_field_type const data_field) +{ data_coordinator::register_active_data_field(data_field); for (const auto& buf_map : m_data_buffers) { const data_buffer_map_t& buffer_map = buf_map;
codereview_cpp_data_9684
auto current_time = std::chrono::steady_clock::now(); if (current_time > next_trigger) { - next_trigger = current_time += std::chrono::microseconds(10); } cv_.wait_until(lock, next_trigger); As `current_time` is not used after this line, it makes no sense to use `+=` ```suggestion next_trigger = current_time + std::chrono::microseconds(10); ``` auto current_time = std::chrono::steady_clock::now(); if (current_time > next_trigger) { + next_trigger = current_time + std::chrono::microseconds(10); } cv_.wait_until(lock, next_trigger);
codereview_cpp_data_9691
case P128_modetype::Wipe: return F("wipe"); case P128_modetype::Dualwipe: return F("dualwipe"); case P128_modetype::FakeTV: return F("faketv"); - - // case P128_modetype::SimpleClock: return F("simpleclock"); } return F("*unknown*"); } We do have functions to wrap some string in characters and also for json like elements. case P128_modetype::Wipe: return F("wipe"); case P128_modetype::Dualwipe: return F("dualwipe"); case P128_modetype::FakeTV: return F("faketv"); + case P128_modetype::SimpleClock: return F("simpleclock"); } return F("*unknown*"); }
codereview_cpp_data_9699
REJECT_INVALID, "bad-txns-nonfinal"); } - if (fStrictPayToScriptHash) - { - // Add in sigops done by pay-to-script-hash inputs; - // this is to prevent a "rogue miner" from creating - // an incredibly-expensive-to-validate block. - nSigOps += GetP2SHSigOpCount(txref, view, flags); - if (nSigOps > GetMaxBlockSigOpsCount(block.GetBlockSize())) - return state.DoS( - 100, error("ConnectBlock(): too many sigops"), REJECT_INVALID, "bad-blk-sigops"); - } - nFees += view.GetValueIn(tx) - tx.GetValueOut(); uint256 hash = tx.GetHash(); let's combine this check and the one above by putting them both outside the "if (!tx.IsCoinBase())" block (and for DTOR as well). REJECT_INVALID, "bad-txns-nonfinal"); } nFees += view.GetValueIn(tx) - tx.GetValueOut(); uint256 hash = tx.GetHash();
codereview_cpp_data_9712
void Castle::setName( const std::set<std::string> & usedNames ) { - assert( name.empty() && !usedNames.empty() ); std::vector<const char *> shuffledCastleNames( defaultCastleNames.begin(), defaultCastleNames.end() ); What if all the castles on the map don't have names? In this case `usedNames` will be empty and this assertion will fail. void Castle::setName( const std::set<std::string> & usedNames ) { + assert( name.empty() ); std::vector<const char *> shuffledCastleNames( defaultCastleNames.begin(), defaultCastleNames.end() );
codereview_cpp_data_9715
wlr_matrix_transpose(transposition, matrix); float converted[4]; - color_convert(NULL, wlr_renderer->color, color, converted); PUSH_GLES2_DEBUG; glUseProgram(renderer->shaders.quad.program); Of course this won't even do anything without a protocol to provide a client profile or colorspace. Which is why this _really_ needs a protocol before it can be merged. Otherwise people who currently care about color and let clients apply the profile themselves will be broken as they'll have a profile applied twice before display. wlr_matrix_transpose(transposition, matrix); float converted[4]; + color_convert(NULL, renderer->color, color, converted); PUSH_GLES2_DEBUG; glUseProgram(renderer->shaders.quad.program);
codereview_cpp_data_9731
{ if (logWarnCount < Log::getWarnMessageLimit()) { - LOG_WARN("Truncateing the " << it.key() << " attribute (" << vba.length() << " characters) to the output field width (" << fieldWidth << " characters)."); } else if (logWarnCount == Log::getWarnMessageLimit()) { `Truncating` is misspelled. { if (logWarnCount < Log::getWarnMessageLimit()) { + LOG_WARN("Truncating the " << it.key() << " attribute (" << vba.length() << " characters) to the output field width (" << fieldWidth << " characters)."); } else if (logWarnCount == Log::getWarnMessageLimit()) {
codereview_cpp_data_9747
cout<<"\n5. Size"; cout<<"\n0. Exit"; cout<<"\n\nEnter you choice : "; - cin>>choice; switch (choice) { case 1 : cout<<"\nEnter the element to be inserted : "; - cin>>x;; insert(x); break; case 2 : cout<<"\nEnter the element to be removed : "; cin>>x; suppose there is only 1 node in the Linked list, ``temp->next->val`` will cause error because ``temp->next`` will be ``NULL`` cout<<"\n5. Size"; cout<<"\n0. Exit"; cout<<"\n\nEnter you choice : "; + cin>>choice; switch (choice) { case 1 : cout<<"\nEnter the element to be inserted : "; + cin>>x; insert(x); break; case 2 : cout<<"\nEnter the element to be removed : "; cin>>x;
codereview_cpp_data_9752
} tinyxml2::XMLDocument xmlDoc; - tinyxml2::XMLError load_error = xmlDoc.LoadFile(filename.c_str()); - if (tinyxml2::XMLError::XML_SUCCESS != load_error) { logError(XMLPARSER, "Error opening '" << filename << "'"); return XMLP_ret::XML_ERROR; Can we combine the two lines above into a single one? } tinyxml2::XMLDocument xmlDoc; + if (tinyxml2::XMLError::XML_SUCCESS != xmlDoc.LoadFile(filename.c_str())) { logError(XMLPARSER, "Error opening '" << filename << "'"); return XMLP_ret::XML_ERROR;
codereview_cpp_data_9758
/* adjust speed for broken vehicles */ if (v->vehstatus & VS_AIRCRAFT_BROKEN) { speed_limit = min(speed_limit, SPEED_LIMIT_BROKEN); - hard_limit = false; } if (v->vcache.cached_max_speed < speed_limit) { This needs a similar condition as "(v->vcache.cached_max_speed < speed_limit)" in the case below. hard_limit should only be set to false, if the new speed limit is the actual speed limit. If the speed limit was already smaller than SPEED_LIMIT_BROKEN, then it continues to be a hard limit. /* adjust speed for broken vehicles */ if (v->vehstatus & VS_AIRCRAFT_BROKEN) { + if (speed_limit > SPEED_LIMIT_BROKEN) hard_limit = false; speed_limit = min(speed_limit, SPEED_LIMIT_BROKEN); } if (v->vcache.cached_max_speed < speed_limit) {
codereview_cpp_data_9762
G_CALLBACK (on_hifstate_percentage_changed), NULL); g_auto(RpmOstreeProgress) progress = { 0, }; - rpmostree_output_progress_percent_begin (&progress, "Importing rpm-md metadata"); /* This will check the metadata again, but it *should* hit the cache; down * the line we should really improve the libdnf API around all of this. The "md" there stands for metadata though...a bit like "ATM machine" here (which, I totally understand why people say that, I do it myself sometimes). How about "Importing rpm repo metadata"? G_CALLBACK (on_hifstate_percentage_changed), NULL); g_auto(RpmOstreeProgress) progress = { 0, }; + rpmostree_output_progress_percent_begin (&progress, "Importing rpm-md"); /* This will check the metadata again, but it *should* hit the cache; down * the line we should really improve the libdnf API around all of this.
codereview_cpp_data_9767
{ if (!key || !strcmp(keyName(key), "")) return handle->defaultBackend; - if (!handle) return NULL; // TODO: what is the best way to handle this - Backend *ret = elektraTrieLookup(handle->trie, key); if (!ret) return handle->defaultBackend; return ret; Does this happen? Can you post the stack strace? Basically, there should be a docu that handle must be valid and an assertion that this won't happen. { if (!key || !strcmp(keyName(key), "")) return handle->defaultBackend; Backend *ret = elektraTrieLookup(handle->trie, key); if (!ret) return handle->defaultBackend; return ret;
codereview_cpp_data_9769
delete[] buf; } -void MegaClient::makeattr(SymmCipher* key, std::unique_ptr<string> const & attrstring, const char* json, int l) const { makeattr(key, attrstring.get(), json, l); } we normally put the `const` before the type: `const std::unique_ptr<string>&` delete[] buf; } +void MegaClient::makeattr(SymmCipher* key, const std::unique_ptr<string>& attrstring, const char* json, int l) const { makeattr(key, attrstring.get(), json, l); }
codereview_cpp_data_9773
} const char *query = "SELECT `account_id`, `class`, `guild_id` FROM `%s` WHERE `char_id`=?"; - int account_id; - int class; - int guild_id; /** Abort changing gender if there was an error while loading the data. **/ if (SQL_ERROR == SQL->StmtPrepare(stmt, query, char_db) probably better left 0 for initial value of vars. it will prevent errors if code bellow will use this vars without checking. } const char *query = "SELECT `account_id`, `class`, `guild_id` FROM `%s` WHERE `char_id`=?"; + int account_id = 0; + int class = 0; + int guild_id = 0; /** Abort changing gender if there was an error while loading the data. **/ if (SQL_ERROR == SQL->StmtPrepare(stmt, query, char_db)
codereview_cpp_data_9775
* Part of SELinux in Fedora >= 24: https://bugzilla.redhat.com/show_bug.cgi?id=1290659 */ gboolean -rpmostree_rootfs_prepare_selinux (int rootfs_dfd, - GCancellable *cancellable, - GError **error) { const char *semanage_path = "usr/etc/selinux/semanage.conf"; Can we name this something more explicit, e.g. `rpmostree_set_selinux_etc_store_root` ? Or maybe `rpmostree_move_selinux_store` ? * Part of SELinux in Fedora >= 24: https://bugzilla.redhat.com/show_bug.cgi?id=1290659 */ gboolean +rpmostree_rootfs_fixup_selinux_store_root (int rootfs_dfd, + GCancellable *cancellable, + GError **error) { const char *semanage_path = "usr/etc/selinux/semanage.conf";
codereview_cpp_data_9792
if (total_data_recv > 0) { fprintf(stdout, "Early Data received: "); - for (size_t i = 0; i < (ssize_t)total_data_recv; i++) { fprintf(stdout, "%c", early_data_received[i]); } fprintf(stdout, "\n"); `i` can be a `ssize_t` here as well. if (total_data_recv > 0) { fprintf(stdout, "Early Data received: "); + for (ssize_t i = 0; i < total_data_recv; i++) { fprintf(stdout, "%c", early_data_received[i]); } fprintf(stdout, "\n");
codereview_cpp_data_9793
return m_state.getNonce(_addr); } -h256 MPTState::rootHash(bool _needCal) const { - (void)_needCal; return m_state.rootHash(); } What about? ```cpp h256 MPTState::rootHash(bool) const { return m_state.rootHash(); } ``` return m_state.getNonce(_addr); } +h256 MPTState::rootHash(bool) const { return m_state.rootHash(); }
codereview_cpp_data_9797
fheroes2::Blit( fheroes2::AGG::GetICN( ICN::CSLMARKER, 0 ), dstsf, pos.x + pos.width - 10, pos.y + 4 ); } -bool DwellingsBar::ActionBarLeftMouseSingleClick( const fheroes2::Point &, DwellingItem & dwl, const fheroes2::Rect & ) { if ( castle.isBuild( dwl.type ) ) { castle.RecruitMonster( Dialog::RecruitMonster( dwl.mons, castle.getMonstersInDwelling( dwl.type ), true ) ); :warning: **readability\-named\-parameter** :warning: all parameters should be named in a function ```suggestion bool DwellingsBar::ActionBarLeftMouseSingleClick( const fheroes2::Point & /*unused*/, DwellingItem & dwl, const fheroes2::Rect & /*unused*/) ``` fheroes2::Blit( fheroes2::AGG::GetICN( ICN::CSLMARKER, 0 ), dstsf, pos.x + pos.width - 10, pos.y + 4 ); } +bool DwellingsBar::ActionBarLeftMouseSingleClick( const fheroes2::Point & /*unused*/, DwellingItem & dwl, const fheroes2::Rect & /*unused*/) { if ( castle.isBuild( dwl.type ) ) { castle.RecruitMonster( Dialog::RecruitMonster( dwl.mons, castle.getMonstersInDwelling( dwl.type ), true ) );
codereview_cpp_data_9799
cout << "t = " << s.getTime() << " | fiber_length = " << fl << " : default_fiber_length = " << muscle.get_default_fiber_length() << endl; - SimTK_ASSERT_ALWAYS(fl >= muscle.getMinimumFiberLengthAlongTendon(), "Equilibrium failed to compute valid fiber length."); if (isCoordinatesOnly) { Since L182 is getting the fiber length, seems like it would be more consistent to test `fl >= muscle.getMinimumFiberLength()` here. cout << "t = " << s.getTime() << " | fiber_length = " << fl << " : default_fiber_length = " << muscle.get_default_fiber_length() << endl; + SimTK_ASSERT_ALWAYS(fl >= muscle.getMinimumFiberLength(), "Equilibrium failed to compute valid fiber length."); if (isCoordinatesOnly) {
codereview_cpp_data_9809
if(unguaranteedPhase) { evt->process(this); - if (evt->getRefCount() == 0) - evt->incRef(); evt->decRef(); if(mErrorBuffer.isNotEmpty()) return; I think this is the one thing I want to investigate closer, since it seems to be patching some underlying issue. if(unguaranteedPhase) { evt->process(this); evt->decRef(); if(mErrorBuffer.isNotEmpty()) return;
codereview_cpp_data_9811
} bool OSArgument::modelDependent() const { - return m_required; } bool OSArgument::hasValue() const { @macumber A bug ... can't see it without letting you know. Cheers! } bool OSArgument::modelDependent() const { + return m_modelDependent; } bool OSArgument::hasValue() const {
codereview_cpp_data_9835
fseek(ttf,td->cff_start+td->private_offset+td->subrsoff,SEEK_SET); readcffsubrs(ttf,td,&td->local_subrs, 1, name ); } - if (name != NULL && *name != "<Nameless>") free(name); } static struct topdicts **readcfftopdicts(FILE *ttf, char **fontnames, int cff_start) { this makes no sense, `name` is a `char*`, and you're dereferencing it to compare against a const string? fseek(ttf,td->cff_start+td->private_offset+td->subrsoff,SEEK_SET); readcffsubrs(ttf,td,&td->local_subrs, 1, name ); } + if (name != NULL && *name != *nameless_str) free(name); } static struct topdicts **readcfftopdicts(FILE *ttf, char **fontnames, int cff_start) {
codereview_cpp_data_9840
#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W') for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) { - if (i < src_len - 2 && src[i] == '%' && isxdigit(* (const unsigned char *) (src + i + 1)) && isxdigit(* (const unsigned char *) (src + i + 2))) { a = tolower(* (const unsigned char *) (src + i + 1)); This is also a question of style. src[i] will always be valid because of check if 'for' statement #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W') for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) { + if (src[i] == '%' && i < src_len - 2 && isxdigit(* (const unsigned char *) (src + i + 1)) && isxdigit(* (const unsigned char *) (src + i + 2))) { a = tolower(* (const unsigned char *) (src + i + 1));
codereview_cpp_data_9843
{ LOG(Debug, "Creating a UserScriptJob"); - try { - FileInfo sql = t_files.getLastByFilename("eplusout.sql"); - // addParam("lastSqlFilePath", sql.fullPath); // Jason how do I do this? - } catch (const std::runtime_error &) { - } - LOG(Debug, "UserScriptJob Created"); } Do you still need Jason to answer this question? { LOG(Debug, "Creating a UserScriptJob"); LOG(Debug, "UserScriptJob Created"); }
codereview_cpp_data_9854
bool GameFiltersSettings::isShowOnlyIfSpectatorsCanWatch() { QVariant previous = getValue("show_only_if_spectators_can_watch", "filter_games"); - return previous == QVariant() ? true : previous.toBool(); } void GameFiltersSettings::setShowSpectatorPasswordProtected(bool show) I think this default is a bit harsh, people most likely still want to join games even if they don't allow spectators. bool GameFiltersSettings::isShowOnlyIfSpectatorsCanWatch() { QVariant previous = getValue("show_only_if_spectators_can_watch", "filter_games"); + return previous == QVariant() ? false : previous.toBool(); } void GameFiltersSettings::setShowSpectatorPasswordProtected(bool show)
codereview_cpp_data_9859
placement_zone_ = std::move(zone); } -bool CheckSpaces(std::string str) { - if (str.empty()) return false; - size_t start = 0; - size_t end = str.size() - 1; - if (isspace(str[start]) != 0 || isspace(str[end]) != 0) { - return true; - } - //Eliminate compile warnings - return false; -} - } // namespace server } // namespace yb Nit format: if (x) { // do something } placement_zone_ = std::move(zone); } } // namespace server } // namespace yb
codereview_cpp_data_9861
//Write Edges if (d_writeEdges.getValue()) { - for (Size i=0 ; i<m_inputtopology->getNbEdges() ; i++) { outfile << 'l'; sofa::core::topology::BaseMeshTopology::Edge t = m_inputtopology->getEdge(i); Isn't it a duplication of : sofa-src\modules\SofaExporter\src\SofaExporter\OBJExporter.cpp which already use #include <sofa/simulation/ExportOBJVisitor.h> which call void VisualModelImpl::exportOBJ on each visulaModel... .... ok so the answer to my question is not exactly the same... but... what a mess! //Write Edges if (d_writeEdges.getValue()) { + for (Index i=0 ; i<m_inputtopology->getNbEdges() ; i++) { outfile << 'l'; sofa::core::topology::BaseMeshTopology::Edge t = m_inputtopology->getEdge(i);
codereview_cpp_data_9863
h2o_multithread_receiver_t receiver; }; -struct status_ctx { int active; void *ctx; }; Please surround the struct with `st_XXX_t`. h2o_multithread_receiver_t receiver; }; +struct st_status_ctx_t { int active; void *ctx; };
codereview_cpp_data_9870
&& uh != me && !fetchingnodes) { - // Invalidate attrs to ensure that are re-fetched for users - // with group chats previous to establish contact relationship - u->invalidateattr(ATTR_FIRSTNAME); - u->invalidateattr(ATTR_LASTNAME); - // new user --> fetch keys fetchContactKeys(u); } I think we shouldn't flag these attributes in the SDK, since they do not exist yet. Hence, the `changed.first/lastname` are being set to true, but no previous value existed. It would be better to manage the invalidation at the app's cache, in case it has that value cached. && uh != me && !fetchingnodes) { // new user --> fetch keys fetchContactKeys(u); }
codereview_cpp_data_9872
// Filter out MWS edition symbols and basic land extras QRegExp rx("\\[.*\\]\\s?"); line.remove(rx); - rx.setPattern("\\\\s?(.*\\)"); line.remove(rx); // Filter out post card name editions This looks not correct. >I am adding `\\s?` at the start of the regex. You had the right thought, but it should look a bit different. Did you try `rx.setPattern("\\s?\\(.*\\)");`? // Filter out MWS edition symbols and basic land extras QRegExp rx("\\[.*\\]\\s?"); line.remove(rx); + rx.setPattern("\\s?\\(.*\\)"); line.remove(rx); // Filter out post card name editions
codereview_cpp_data_9876
auto type_registry = caf::actor_cast<type_registry_actor>( self->state.registry.find_by_label("type-registry")); if (!type_registry) - return caf::make_message(make_error(ec::missing_component, "type-" - "registry")); caf::error request_error = caf::none; auto rp = self->make_response_promise(); // The overload for 'request(...)' taking a 'std::chrono::duration' does not Can you manually reformat this to enforce that "type-registry" remains a single string? auto type_registry = caf::actor_cast<type_registry_actor>( self->state.registry.find_by_label("type-registry")); if (!type_registry) + return caf::make_message(make_error(ec::missing_component, // + "type-registry")); caf::error request_error = caf::none; auto rp = self->make_response_promise(); // The overload for 'request(...)' taking a 'std::chrono::duration' does not
codereview_cpp_data_9884
m_num_files_in_cur_spill_dir = m_max_files_per_directory; if (opts->has_string("data_store_spill")) { m_spill_dir_base = options::get()->get_string("data_store_spill"); } else { m_spill_dir_base = options::get()->get_string("data_store_test_checkpoint"); } make_dir_if_it_doesnt_exist(m_spill_dir_base); m_comm->trainer_barrier(); Should we increment `m_num_files_in_cur_spill_dir` here? If I'm following the code correctly, it's initialized to `m_max_files_per_directory` in `setup_spill`, set to 0 the first time `spill_conduit_node` is called, and stays there forever. m_num_files_in_cur_spill_dir = m_max_files_per_directory; if (opts->has_string("data_store_spill")) { m_spill_dir_base = options::get()->get_string("data_store_spill"); + if (m_spill_dir_base == "" || m_spill_dir_base == "1") { + LBANN_ERROR("--data_store_spill=1; you probably forgot to specify the spill directory; instead of the flag --data_store_spill you must use --data_store_spill=<string>"); + } } else { m_spill_dir_base = options::get()->get_string("data_store_test_checkpoint"); } + if (m_world_master) std::cout << "setup_spill; spilling to: " << m_spill_dir_base << std::endl; make_dir_if_it_doesnt_exist(m_spill_dir_base); m_comm->trainer_barrier();
codereview_cpp_data_9886
template <typename TensorDataType> bool adam<TensorDataType>::save_to_checkpoint_distributed(persist& p, std::string name_prefix) { - write_cereal_archive<adam<TensorDataType>>(*this, p, "adam.xml"); char l_name[512]; sprintf(l_name, "%s_optimizer_adam_moment1_%lldx%lld", name_prefix.c_str(), m_moment1->Height(), m_moment2->Width()); ```suggestion write_cereal_archive(*this, p, "adam.xml"); ``` template <typename TensorDataType> bool adam<TensorDataType>::save_to_checkpoint_distributed(persist& p, std::string name_prefix) { + write_cereal_archive(*this, p, "adam.xml"); char l_name[512]; sprintf(l_name, "%s_optimizer_adam_moment1_%lldx%lld", name_prefix.c_str(), m_moment1->Height(), m_moment2->Width());
codereview_cpp_data_9889
if (name.base == NULL) return 0; - if ((token = h2o_lookup_token(name.base, name.len)) != NULL) { - value = h2o_strdup(&req->pool, value.base, value.len); - h2o_add_header(&req->pool, &req->headers, token, NULL, value.base, value.len); - } else { - value = h2o_strdup(&req->pool, value.base, value.len); - h2o_add_header_by_str(&req->pool, &req->headers, name.base, name.len, 0, NULL, value.base, value.len); - } return 0; } Instead of doing "if...is_token...else", you can simply rely on `h2o_add_header_by_str` with its `maybe_token` argument set to 1? if (name.base == NULL) return 0; + value = h2o_strdup(&req->pool, value.base, value.len); + h2o_add_header_by_str(&req->pool, &req->headers, name.base, name.len, 1, NULL, value.base, value.len); return 0; }
codereview_cpp_data_9897
FILE *file; unichar_t *pt; - GEvent e; - e.type = et_save; - e.w = gt->g.base; - GDrawPostEvent(&e); - if ( _ggadget_use_gettext ) { char *temp = GWidgetOpenFile8(_("Save"),NULL,"*.txt",NULL,NULL); ret = utf82u_copy(temp); Move this to the very end of the function. Also look at how `GTextFieldChanged` implements the send, and copy that (making et_save a subtype of et_controlevent) FILE *file; unichar_t *pt; if ( _ggadget_use_gettext ) { char *temp = GWidgetOpenFile8(_("Save"),NULL,"*.txt",NULL,NULL); ret = utf82u_copy(temp);
codereview_cpp_data_9910
#ifdef ENABLE_SYNC if (!(*it)->isSyncable()) { - mUnsyncableNodes.insert((*it)->nodehandle); - auto nodehandle = std::to_string((*it)->nodehandle); - if (!(complete = mUnsyncableNodesTable->put((*it)->dbid, &nodehandle))) { break; } Can we be sure the dbid has been assigned at this point, since it's for a different table? I think it would be better to keep them independent, eg. in case of total node tree reload? #ifdef ENABLE_SYNC if (!(*it)->isSyncable()) { + if (!(complete = unsyncables->addNode((*it)->nodehandle))) { break; }
codereview_cpp_data_9916
namespace caffe { -using std::map; -using std::string; - bool NetNeedsUpgrade(const NetParameter& net_param) { for (int i = 0; i < net_param.layers_size(); ++i) { if (net_param.layers(i).has_layer()) { rm these 2 usings? namespace caffe { bool NetNeedsUpgrade(const NetParameter& net_param) { for (int i = 0; i < net_param.layers_size(); ++i) { if (net_param.layers(i).has_layer()) {
codereview_cpp_data_9923
/* * Check that setting FASTDDS_ENVIRONMENT_FILE to an unexisting file issues 1 logWarning */ -TEST_P(PubSubBasic, EnvFileWarningWrongFile) { env_file_warning("unexisting_file", 1); } Do we really need these tests to be `TEST_P`? I think we could use just `TEST` /* * Check that setting FASTDDS_ENVIRONMENT_FILE to an unexisting file issues 1 logWarning */ +TEST(PubSubBasic, EnvFileWarningWrongFile) { env_file_warning("unexisting_file", 1); }
codereview_cpp_data_9929
.setRepresentation(SimTK::DecorativeGeometry::DrawSurface) .setTransform(Vec3({-.01, -.03, .03}))); Transform cylTransform; cylTransform.updR().setRotationFromAngleAboutX(SimTK_PI / 2); stdPrimitives.push_back( DecorativeCylinder(.025, .05).setBodyId(0).setColor(SimTK::Cyan) Should the rotations be (a) about all three axes, and (b) by amounts that are not multiples of 90 to ensure the geometry isn't accidentally getting flipped or reflected somehow? A few things can still be wrong even if a pi/2 rotation lands the cylinder in the right place. .setRepresentation(SimTK::DecorativeGeometry::DrawSurface) .setTransform(Vec3({-.01, -.03, .03}))); Transform cylTransform; + // This transform parallels the code in generateDecorations to reflect + // that DecorativeCylinder is Y aligned while WrapCylinder is Z aligned cylTransform.updR().setRotationFromAngleAboutX(SimTK_PI / 2); stdPrimitives.push_back( DecorativeCylinder(.025, .05).setBodyId(0).setColor(SimTK::Cyan)
codereview_cpp_data_9930
return true; } -static void GGDK_ChangeRestrictCount(GGDKDisplay *gdisp, int c) { gdisp->restrict_count += c; } I don't see much benefit in making this a function Also prefixes for static unexported functions in this file is `_GGDKDraw`, not `GGDK` return true; } +static void _GGDKDraw_ChangeRestrictCount(GGDKDisplay *gdisp, int c) { gdisp->restrict_count += c; }
codereview_cpp_data_9940
} src; pthread_mutex_t mutex; size_t num_remaining_threads; - h2o_globalconf_t *gconf; H2O_VECTOR(struct status_ctx) status_ctx; }; I believe you do not need to retain a pointer to h2o_globalconf_t. It can be reached by accessing `h2o_context_t::globalconf`. } src; pthread_mutex_t mutex; size_t num_remaining_threads; H2O_VECTOR(struct status_ctx) status_ctx; };
codereview_cpp_data_9944
DacpModuleData ModuleData; if (FAILED(ModuleData.Request(g_sos, ModuleAddr))) { - ExtDbgOut("Failed to request module data from assembly for %p\n", ModuleAddr); continue; } Given that it's an address: ```suggestion ExtDbgOut("Failed to request module data from assembly at %p\n", ModuleAddr); ``` DacpModuleData ModuleData; if (FAILED(ModuleData.Request(g_sos, ModuleAddr))) { + ExtDbgOut("Failed to request module data from assembly at %p\n", ModuleAddr); continue; }
codereview_cpp_data_9951
BLACKBOXTEST(BlackBox, ReqRepVolatileHelloworldRequesterCheckWriteParams) { ReqRepAsReliableHelloWorldRequester requester; - ReqRepAsReliableHelloWorldReplier replier; requester.durability_kind(eprosima::fastrtps::VOLATILE_DURABILITY_QOS).init(); ASSERT_TRUE(requester.isInitialized()); - replier.init(); - - ASSERT_TRUE(replier.isInitialized()); - requester.send(1); } I think the replier should also be set to volatile for this test to work BLACKBOXTEST(BlackBox, ReqRepVolatileHelloworldRequesterCheckWriteParams) { ReqRepAsReliableHelloWorldRequester requester; requester.durability_kind(eprosima::fastrtps::VOLATILE_DURABILITY_QOS).init(); ASSERT_TRUE(requester.isInitialized()); requester.send(1); }
codereview_cpp_data_9964
if (sqlInterface->validateTableColumnStringData("{prefix}_users", "email", QString::fromStdString(cmd.user_name()), QString::fromStdString(cmd.email()))) { if (servatrice->getEnableForgotPasswordAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET_CHALLANGE", "Correctly answered email challange question", true); if (sqlInterface->addForgotPassword(QString::fromStdString(cmd.user_name()))) return Response::RespOk; } else { if (servatrice->getEnableForgotPasswordAudit()) - sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET_CHALLANGE", "Failed to answere email challange question", false); } return Response::RespFunctionNotAllowed; Typos: answere, challange if (sqlInterface->validateTableColumnStringData("{prefix}_users", "email", QString::fromStdString(cmd.user_name()), QString::fromStdString(cmd.email()))) { if (servatrice->getEnableForgotPasswordAudit()) + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET_CHALLANGE", "", true); if (sqlInterface->addForgotPassword(QString::fromStdString(cmd.user_name()))) return Response::RespOk; } else { if (servatrice->getEnableForgotPasswordAudit()) + sqlInterface->addAuditRecord(QString::fromStdString(cmd.user_name()).simplified(), this->getAddress(), QString::fromStdString(cmd.clientid()).simplified(), "PASSWORD_RESET_CHALLANGE", "Failed to answer email challenge question", false); } return Response::RespFunctionNotAllowed;
codereview_cpp_data_9965
foreach (QString v, values) { QStringList newList = conf().getList(kvl[0]); - if( !newList.contains(v)) { throw HootException("Unknown default value: (" + v + ")"); } just formatting: `if (!newList.contains(v))` foreach (QString v, values) { QStringList newList = conf().getList(kvl[0]); + if (!newList.contains(v)) { throw HootException("Unknown default value: (" + v + ")"); }
codereview_cpp_data_9979
buf.seek( offset2 ); std::vector<std::string> tags = StringSplit( buf.toString( length2 ), "\n" ); - for ( auto it = tags.begin(); it != tags.end(); ++it ) { if ( encoding.empty() ) encoding = get_tag( *it, tag1, sep1 ); :warning: **modernize\-loop\-convert** :warning: use range\-based for loop instead ```suggestion for (auto & tag : tags) { tagtag ``` buf.seek( offset2 ); std::vector<std::string> tags = StringSplit( buf.toString( length2 ), "\n" ); + for (auto & tag : tags) { +tagtag if ( encoding.empty() ) encoding = get_tag( *it, tag1, sep1 );
codereview_cpp_data_9985
} sprintf(command, "/kick %s (%d)", status->get_name(target), status->get_class(target)); logs->atcommand(sd, command); - if(pc_has_permission(sd,PC_PERM_DISABLE_DROPS)) - status_kill(target); - else - status_percent_damage(&sd->bl, target, 100, 0, true); // can invalidate 'target' } break; Umm, are you sure about this one? It doesn't really seem to match the description, this only affects /kick (and even so, I'm not sure this would be the right way, since you're just removing the src parameter from the status_percent_change call, which most likely has have some side-effects). And what about the monsters killed by this player by normal means? I don't think I see code that disables those drops? } sprintf(command, "/kick %s (%d)", status->get_name(target), status->get_class(target)); logs->atcommand(sd, command); + status_percent_damage(&sd->bl, target, 100, 0, true); // can invalidate 'target' } break;
codereview_cpp_data_9986
detailed_description += "\n"; } - if (planet->Size() < SZ_ASTEROIDS) { detailed_description += UserString("ENC_SUITABILITY_REPORT_WHEEL_INTRO") + "<img src=\"encyclopedia/EP_wheel.png\"></img>"; } The correct semantic would be to check against `Type`, not `Size` as this check also covers `SZ_NOWORLD`. Also this needs to exclude `INVALID_PLANET_TYPE`. detailed_description += "\n"; } + if (planet->Type() < PT_ASTEROIDS && planet->Type() > INVALID_PLANET_TYPE) { detailed_description += UserString("ENC_SUITABILITY_REPORT_WHEEL_INTRO") + "<img src=\"encyclopedia/EP_wheel.png\"></img>"; }
codereview_cpp_data_9992
constrained_height); if (serial > 0) { roots_surface->pending_move_resize_configure_serial = serial; - } else if(roots_surface->pending_move_resize_configure_serial == 0) { view->x = x; view->y = y; } Style error, put a space between `if` and `(` constrained_height); if (serial > 0) { roots_surface->pending_move_resize_configure_serial = serial; + } else if (roots_surface->pending_move_resize_configure_serial == 0) { view->x = x; view->y = y; }
codereview_cpp_data_9994
bool clFree(void* virtualPtr) { - LOG(INFO)<<"calling clFree()"; - if ( ! gpu->isValidPtr(virtualPtr) ) { LOG(ERROR) << gpu->name() << "> not a valid memory pointer @ " << virtualPtr; return false; Delete this printf please. Creates a big mess. bool clFree(void* virtualPtr) { if ( ! gpu->isValidPtr(virtualPtr) ) { LOG(ERROR) << gpu->name() << "> not a valid memory pointer @ " << virtualPtr; return false;
codereview_cpp_data_10014
nc = subnodeCounts(); gotnc = true; - // nodes moving from cloud drive to rubbish for example. Nodes should not move between inshares and owned nodes client->nodecounters[oah] -= nc; } Should they be copied&deleted instead of moved? (I don't know by heart) nc = subnodeCounts(); gotnc = true; + // nodes moving from cloud drive to rubbish for example, or between inshares from the same user. client->nodecounters[oah] -= nc; }
codereview_cpp_data_10019
delete chat->userpriv; // discard any existing `userpriv` chat->userpriv = this->chatPeers; chat->group = group; chat->setTag(tag ? tag : -1); client->notifychat(chat); I think that this check and other similar ones in this pull request could be removed because the tag `0` shouldn't be used (except for commands generated internally by the SDK without any interest for client apps and libraries), but I understand that they ensure that `isOwnChange()` never returns `0` for own changes, even if a wrong tag is set. delete chat->userpriv; // discard any existing `userpriv` chat->userpriv = this->chatPeers; chat->group = group; + chat->ts = (ts != -1) ? ts : 0; chat->setTag(tag ? tag : -1); client->notifychat(chat);
codereview_cpp_data_10064
GUARD_PTR(s2n_alloc(&allocator, sizeof(struct s2n_config))); new_config = (struct s2n_config *)(void *)allocator.data; - if (s2n_config_init(new_config)) { s2n_free(&allocator); return NULL; } Can you make this an explicit comparison to `!= S2N_SUCCESS`, instead? Makes it a bit easier to read. GUARD_PTR(s2n_alloc(&allocator, sizeof(struct s2n_config))); new_config = (struct s2n_config *)(void *)allocator.data; + if (s2n_config_init(new_config) != S2N_SUCCESS) { s2n_free(&allocator); return NULL; }
codereview_cpp_data_10068
case HEROFL04: case HEROFL05: case HEROFL06: - return ticket % 6; case TWNBDOCK: case TWNKDOCK: Hi @shprotru , this case is incorrect. `case HEROFL06:` is a correct change but **ticket % 6;** is not as each of **HEROFL00.. HEROFL06** contains only 5 frames. Please correct this place. case HEROFL04: case HEROFL05: case HEROFL06: + return ticket % 5; case TWNBDOCK: case TWNKDOCK:
codereview_cpp_data_10076
ordering_gate_fixture.rounds_.get_subscriber().on_next(std::move(result.value)); }, [](const iroha::expected::Error<std::string> &error) { - ordering_gate_fixture.rounds_.get_subscriber().on_next(OnDemandOrderingGate::EmptyEvent()); }); } Is there a reason to send empty events each time a block creation failed? Should not we just ignore such data? ordering_gate_fixture.rounds_.get_subscriber().on_next(std::move(result.value)); }, [](const iroha::expected::Error<std::string> &error) { + // just ignore a bad case }); }
codereview_cpp_data_10077
} template <typename TensorDataType> auto data_type_layer<TensorDataType>::get_error_signals(const Layer& parent) const -> const BaseDistMat& { - const int parent_index = std::distance(m_parent_layers.begin(), - std::find(m_parent_layers.begin(), - m_parent_layers.end(), - &parent)); if (parent_index >= get_num_parents()) { std::stringstream err; err << "attempted to get error signal tensor of " If we have a method for computing the child's index, we should have the same for the parent's index. } template <typename TensorDataType> auto data_type_layer<TensorDataType>::get_error_signals(const Layer& parent) const -> const BaseDistMat& { + const int parent_index = find_parent_layer_index(&parent); if (parent_index >= get_num_parents()) { std::stringstream err; err << "attempted to get error signal tensor of "
codereview_cpp_data_10078
if (o-> pargc == 0 && o->fargc > 0) { /* Assume we got a auth:code combination */ std::string input(o->fargv[0]); - int n = input.find(":"); if (n > 0) { std::string auth = input.substr(0,n); std::string code = input.substr(n+1, input.length()); There are a few operation names that include ':' in them. See ``` $ echo "SELECT * FROM coordinate_operation_view WHERE name LIKE '%:%';" | sqlite3 data/proj.db other_transformation|PROJ|CRS84_TO_EPSG_4326|OGC:CRS84 to WGS 84||EPSG|9843|Axis Order Reversal (2D)|OGC|CRS84|EPSG|4326|0.0|0 other_transformation|PROJ|CRS27_TO_EPSG_4267|OGC:CRS27 to NAD27||EPSG|9843|Axis Order Reversal (2D)|OGC|CRS27|EPSG|4267|0.0|0 other_transformation|PROJ|CRS83_TO_EPSG_4269|OGC:CRS83 to NAD83||EPSG|9843|Axis Order Reversal (2D)|OGC|CRS83|EPSG|4269|0.0|0 concatenated_operation|PROJ|KKJ_TO_ETRS89|KKJ to ETRS89 (using PROJ:YKJ_TO_ETRS35FIN)|Transformation based on a triangulated irregular network||||EPSG|4123|EPSG|4258||0 ``` So it would be prudent to do ```suggestion } if( P == nullptr ) { ``` if (o-> pargc == 0 && o->fargc > 0) { /* Assume we got a auth:code combination */ std::string input(o->fargv[0]); + auto n = input.find(":"); if (n > 0) { std::string auth = input.substr(0,n); std::string code = input.substr(n+1, input.length());
codereview_cpp_data_10080
JointHasNoCoordinates); OPENSIM_THROW_IF(numCoordinates() > 1, InvalidCall, - "Coordinate set has more than one coordinate. Use " - "getCoordinate method defined in the concrete class " - "instead."); return get_coordinates(0); } Maybe good to say "_Joint_ ~~Coordinates set~~ has more than one coordinate. ......". JointHasNoCoordinates); OPENSIM_THROW_IF(numCoordinates() > 1, InvalidCall, + "Joint has more than one coordinate. Use the getCoordinate " + "method defined in the concrete class instead."); return get_coordinates(0); }