id
stringlengths
21
25
content
stringlengths
164
2.33k
codereview_cpp_data_764
} ViewingLayerPtr Layer::get_parent_layer_pointer(size_t index) const { - if (index >= m_child_layers.size()) { LBANN_ERROR( "attempted to get pointer to parent ",index," of ", get_type()," layer \"",get_name(),"\", ", @timmoon10 this should be m_parent_layers.size() } ViewingLayerPtr Layer::get_parent_layer_pointer(size_t index) const { + if (index >= m_parent_layers.size()) { LBANN_ERROR( "attempted to get pointer to parent ",index," of ", get_type()," layer \"",get_name(),"\", ",
codereview_cpp_data_767
if (s2n_stuffer_space_remaining(stuffer) < n) { if (stuffer->growable) { /* Always grow a stuffer by at least 1k */ - uint32_t growth = MIN(n, 1024); GUARD(s2n_stuffer_resize(stuffer, stuffer->blob.size + growth)); } else { I think this should be MAX if (s2n_stuffer_space_remaining(stuffer) < n) { if (stuffer->growable) { /* Always grow a stuffer by at least 1k */ + uint32_t growth = MAX(n, 1024); GUARD(s2n_stuffer_resize(stuffer, stuffer->blob.size + growth)); } else {
codereview_cpp_data_772
return CommitResult::ERROR_PARENT_HASH; } - block.header().setGasLimit(m_gasLimit); - block.header().setGasUsed(block.gasUsed()); - try { { gassed should be stetted when finish the execution of block return CommitResult::ERROR_PARENT_HASH; } try { {
codereview_cpp_data_774
if (it != m_fields.end()) { - m_capacity -= (key.size() + it->second.size()); it->second = value; - m_capacity += (key.size() + value.size()); } else { m_fields.insert(std::make_pair(key, value)); - m_capacity += (key.size() + value.size()); } m_dirty = true; Is there a possibility of out of range ? if (it != m_fields.end()) { + // m_capacity -= (key.size() + it->second.size()); it->second = value; + // m_capacity += (key.size() + value.size()); } else { m_fields.insert(std::make_pair(key, value)); + // m_capacity += (key.size() + value.size()); } m_dirty = true;
codereview_cpp_data_776
, qos_(&qos == &TOPIC_QOS_DEFAULT ? participant_->get_default_topic_qos() : qos) , listener_(listen) , user_topic_(nullptr) - , handle_() , num_refs_(0u) { } This is not necessary. Topic inherits from DomainEntity which already has instance_handle_ , qos_(&qos == &TOPIC_QOS_DEFAULT ? participant_->get_default_topic_qos() : qos) , listener_(listen) , user_topic_(nullptr) , num_refs_(0u) { }
codereview_cpp_data_779
c, "paths", H2O_CONFIGURATOR_FLAG_HOST | H2O_CONFIGURATOR_FLAG_EXPECT_MAPPING | H2O_CONFIGURATOR_FLAG_DEFERRED, on_config_paths); h2o_configurator_define_command( - c, "strict-match", H2O_CONFIGURATOR_FLAG_HOST | H2O_CONFIGURATOR_FLAG_EXPECT_SCALAR | H2O_CONFIGURATOR_FLAG_DEFERRED, on_config_strict_match); }; ```suggestion c, "strict-match", H2O_CONFIGURATOR_FLAG_HOST | H2O_CONFIGURATOR_FLAG_EXPECT_SCALAR, ``` I do not think this directive has to be merged deferred, as it does not depend on other directives used at global- or host-level? c, "paths", H2O_CONFIGURATOR_FLAG_HOST | H2O_CONFIGURATOR_FLAG_EXPECT_MAPPING | H2O_CONFIGURATOR_FLAG_DEFERRED, on_config_paths); h2o_configurator_define_command( + c, "strict-match", H2O_CONFIGURATOR_FLAG_HOST | H2O_CONFIGURATOR_FLAG_EXPECT_SCALAR, on_config_strict_match); };
codereview_cpp_data_803
leaf_value_[0] = 0.0f; leaf_weight_[0] = 0.0f; leaf_parent_[0] = -1; - internal_parent_[0] = -1; shrinkage_ = 1.0f; num_cat_ = 0; cat_boundaries_.push_back(0); how do the changes here and in `tree.h` relate to the R package? leaf_value_[0] = 0.0f; leaf_weight_[0] = 0.0f; leaf_parent_[0] = -1; shrinkage_ = 1.0f; num_cat_ = 0; cat_boundaries_.push_back(0);
codereview_cpp_data_804
struct flb_dns_lookup_context *lookup_context; lookup_context = (struct flb_dns_lookup_context *) event; - if (0 == lookup_context->finished) { event->handler(event); - if (1 == lookup_context->finished) { mk_list_add(&lookup_context->_head, &lookup_context_cleanup_queue); } } for boolean kind check let's use: ```c if (!lookup_context->finished) { } ``` struct flb_dns_lookup_context *lookup_context; lookup_context = (struct flb_dns_lookup_context *) event; + if (!lookup_context->finished) { event->handler(event); + if (lookup_context->finished) { mk_list_add(&lookup_context->_head, &lookup_context_cleanup_queue); } }
codereview_cpp_data_808
#include "backend/protobuf/proto_block_factory.hpp" using namespace shared_model::proto; ProtoBlockFactory::ProtoBlockFactory( Capturing `block_payload`, which is a pointer, by reference? Is it good? #include "backend/protobuf/proto_block_factory.hpp" +#include "backend/protobuf/block.hpp" +#include "backend/protobuf/empty_block.hpp" + using namespace shared_model::proto; ProtoBlockFactory::ProtoBlockFactory(
codereview_cpp_data_817
case TYPE_PUBLIC_LINK_INFORMATION: return "PUBLIC_LINK_INFORMATION"; case TYPE_GET_BACKGROUND_UPLOAD_URL: return "GET_BACKGROUND_UPLOAD_URL"; case TYPE_COMPLETE_BACKGROUND_UPLOAD: return "COMPLETE_BACKGROUND_UPLOAD"; - case TYPE_GET_CLOUDSTORAGEUSED: return "TYPE_GET_CLOUDSTORAGEUSED"; } return "UNKNOWN"; } ```suggestion case TYPE_GET_CLOUDSTORAGEUSED: return "GET_CLOUDSTORAGEUSED"; ``` case TYPE_PUBLIC_LINK_INFORMATION: return "PUBLIC_LINK_INFORMATION"; case TYPE_GET_BACKGROUND_UPLOAD_URL: return "GET_BACKGROUND_UPLOAD_URL"; case TYPE_COMPLETE_BACKGROUND_UPLOAD: return "COMPLETE_BACKGROUND_UPLOAD"; + case TYPE_GET_CLOUDSTORAGEUSED: return "GET_CLOUDSTORAGEUSED"; } return "UNKNOWN"; }
codereview_cpp_data_834
EXPECT_NO_THROW(TopicPayloadPoolRegistry::release(pool_b2)); EXPECT_FALSE(pool_b2); - // Repeat allocations and check a different pointer is returned - cfg.memory_policy = DYNAMIC_RESERVE_MEMORY_MODE; - pool_a3 = TopicPayloadPoolRegistry::get("topic_a", cfg); - EXPECT_NE(pool_a3.get(), pool_backup_a3); - cfg.memory_policy = PREALLOCATED_MEMORY_MODE; - pool_a1 = TopicPayloadPoolRegistry::get("topic_a", cfg); - EXPECT_NE(pool_a1.get(), pool_backup_a1); - pool_b1 = TopicPayloadPoolRegistry::get("topic_b", cfg); - EXPECT_NE(pool_b1.get(), pool_backup_b1); } This test doesn't make sense because relies on CRT dependent behavior: 1- The pools were allocated in the first part of the test from heap in chunks of equal size from C++ heap. 2- References to this original chunks are keept in the pool_backup_xx references. 3- The pools are freed and return to the free storage in the C++ heap. 4- The pools are allocated again **but C++ heap may decide to reuse the step 3 freed memory blocks**. Thus we cannot assure that a different pointer is returned. Note the chunks are allocated in the heap in the call: ```c++ std::shared_ptr<TopicPayloadPoolProxy> do_get( std::shared_ptr<TopicPayloadPoolProxy>& ptr, const std::string& topic_name, const BasicPoolConfig& config) { if (!ptr) { ptr = std::make_shared<TopicPayloadPoolProxy>(topic_name, config); } return ptr; } ``` EXPECT_NO_THROW(TopicPayloadPoolRegistry::release(pool_b2)); EXPECT_FALSE(pool_b2); + // Destructor should have been called a certain number of times + EXPECT_EQ(detail::TopicPayloadPoolProxy::DestructorHelper::instance().get(), 3u); }
codereview_cpp_data_841
m_Socket = zmq_socket(m_Context, ZMQ_REQ); const std::string fullIP("tcp://" + m_IPAddress + ":" + m_Port); int err = zmq_connect(m_Socket, fullIP.c_str()); if (m_Profiler.IsActive) { Does err need to be checked? What happens if zmq_connect fails? m_Socket = zmq_socket(m_Context, ZMQ_REQ); const std::string fullIP("tcp://" + m_IPAddress + ":" + m_Port); int err = zmq_connect(m_Socket, fullIP.c_str()); + if (err) + { + throw std::runtime_error("ERROR: zmq_connect() failed with " + + std::to_string(err)); + } if (m_Profiler.IsActive) {
codereview_cpp_data_847
// --------------------------------------------------------------------------- -TEST_F(CApi, use_proj4_init_rules__from_global_context) { int initial_rules = proj_context_get_use_proj4_init_rules(nullptr, true); proj_context_use_proj4_init_rules(nullptr, true); ```suggestion TEST_F(CApi, use_proj4_init_rules_from_global_context) { ``` // --------------------------------------------------------------------------- +TEST_F(CApi, use_proj4_init_rules_from_global_context) { int initial_rules = proj_context_get_use_proj4_init_rules(nullptr, true); proj_context_use_proj4_init_rules(nullptr, true);
codereview_cpp_data_850
/* First Count the number of digits in the given number */ while(temp != 0) { - rem = temp%10; temp /= 10; count++; } Looks like the variable's value is never used here. ```suggestion ``` /* First Count the number of digits in the given number */ while(temp != 0) { temp /= 10; count++; }
codereview_cpp_data_853
if(priceTagSource1->isChecked()) source=1; - QMetaObject::invokeMethod( settingsCache, "setPriceTagSource", Qt::QueuedConnection, Q_ARG(int, source)); } MessagesSettingsPage::MessagesSettingsPage() Is this different than using the slots mechanism? if(priceTagSource1->isChecked()) source=1; + emit priceTagSourceChanged(source); } MessagesSettingsPage::MessagesSettingsPage()
codereview_cpp_data_855
} void TSDescriptor::UpdateHeartbeat(const TSHeartbeatRequestPB* req) { - std::lock_guard<decltype(lock_)> l(lock_); - last_heartbeat_ = MonoTime::Now(); - DCHECK_GE(req->num_live_tablets(), 0); DCHECK_GE(req->leader_count(), 0); num_live_replicas_ = req->num_live_tablets(); leader_count_ = req->leader_count(); physical_time_ = req->ts_physical_time(); It seems these two checks can be lifted ahead of taking the lock } void TSDescriptor::UpdateHeartbeat(const TSHeartbeatRequestPB* req) { DCHECK_GE(req->num_live_tablets(), 0); DCHECK_GE(req->leader_count(), 0); + std::lock_guard<decltype(lock_)> l(lock_); + last_heartbeat_ = MonoTime::Now(); num_live_replicas_ = req->num_live_tablets(); leader_count_ = req->leader_count(); physical_time_ = req->ts_physical_time();
codereview_cpp_data_857
// if conversion failed, check for the "//" separator used in split cards if (!convertSuccess) { int cmcSum = 0; - foreach (QString cmc, info->getCmc().split("//")) { cmcInt = cmc.toInt(); cmcSum += cmcInt; if (relationCheck(cmcInt)) { can you change this to `for (QString cmc : info->getCMC().split("//")) {` ? I'm trying to remove the foreach from the codebase as it's not proper C++ // if conversion failed, check for the "//" separator used in split cards if (!convertSuccess) { int cmcSum = 0; + for (QString cmc : info->getCmc().split("//")) { cmcInt = cmc.toInt(); cmcSum += cmcInt; if (relationCheck(cmcInt)) {
codereview_cpp_data_860
POSIX_ENSURE_REF(security_policy->signature_preferences); POSIX_ENSURE_REF(security_policy->ecc_preferences); - /* If the Security Policies Minimum version is higher than what libcrypto supports, return an error. */ POSIX_ENSURE((security_policy->minimum_protocol_version <= s2n_get_highest_fully_supported_tls_version()), S2N_ERR_PROTOCOL_VERSION_UNSUPPORTED); conn->security_policy_override = security_policy; (Also on line 858) ```suggestion /* If the security policy's minimum version is higher than what libcrypto supports, return an error. */ ``` POSIX_ENSURE_REF(security_policy->signature_preferences); POSIX_ENSURE_REF(security_policy->ecc_preferences); + /* If the security policy's minimum version is higher than what libcrypto supports, return an error. */ POSIX_ENSURE((security_policy->minimum_protocol_version <= s2n_get_highest_fully_supported_tls_version()), S2N_ERR_PROTOCOL_VERSION_UNSUPPORTED); conn->security_policy_override = security_policy;
codereview_cpp_data_871
conn->actual_protocol_version = S2N_TLS13; EXPECT_SUCCESS(s2n_connection_set_config(conn, config)); - /* Check that s2n_is_pss_certs_supported() is a superset of s2n_is_rsa_pss_supported() */ - { - if (s2n_is_pss_certs_supported()) { - EXPECT_TRUE(s2n_is_rsa_pss_supported()); - } - } - /* Do not offer PSS signatures schemes if unsupported: * s2n_send_supported_sig_scheme_list + PSS */ { I don't think this test belongs in this file. Can you put it with other tests specifically for rsa_pss? conn->actual_protocol_version = S2N_TLS13; EXPECT_SUCCESS(s2n_connection_set_config(conn, config)); /* Do not offer PSS signatures schemes if unsupported: * s2n_send_supported_sig_scheme_list + PSS */ {
codereview_cpp_data_875
//Insert the new char entry to the database if( SQL_ERROR == SQL->Query(inter->sql_handle, "INSERT INTO `%s` (`account_id`, `char_num`, `name`, `class`, `zeny`, `str`, `agi`, `vit`, `int`, `dex`, `luk`, `max_hp`, `hp`," "`max_sp`, `sp`, `hair`, `hair_color`, `last_map`, `last_x`, `last_y`, `save_map`, `save_x`, `save_y`) VALUES (" - "'%d', '%d', '%s', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d','%d', '%d','%d', '%d', '%s', '%d', '%d', '%s', '%d', '%d')", char_db, sd->account_id , slot, esc_name, starting_job, start_zeny, str, agi, vit, int_, dex, luk, (40 * (100 + vit)/100) , (40 * (100 + vit)/100 ), (11 * (100 + int_)/100), (11 * (100 + int_)/100), hair_style, hair_color, mapindex_id2name(start_point.map), start_point.x, start_point.y, mapindex_id2name(start_point.map), start_point.x, start_point.y) ) Missing the format string placeholder, as above //Insert the new char entry to the database if( SQL_ERROR == SQL->Query(inter->sql_handle, "INSERT INTO `%s` (`account_id`, `char_num`, `name`, `class`, `zeny`, `str`, `agi`, `vit`, `int`, `dex`, `luk`, `max_hp`, `hp`," "`max_sp`, `sp`, `hair`, `hair_color`, `last_map`, `last_x`, `last_y`, `save_map`, `save_x`, `save_y`) VALUES (" + "'%d', '%d', '%s', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d','%d', '%d','%d', '%d', '%s', '%d', '%d', '%s', '%d', '%d')", char_db, sd->account_id , slot, esc_name, starting_job, start_zeny, str, agi, vit, int_, dex, luk, (40 * (100 + vit)/100) , (40 * (100 + vit)/100 ), (11 * (100 + int_)/100), (11 * (100 + int_)/100), hair_style, hair_color, mapindex_id2name(start_point.map), start_point.x, start_point.y, mapindex_id2name(start_point.map), start_point.x, start_point.y) )
codereview_cpp_data_879
}, [=](caf::error err) { VAST_ERROR(self, "failed to load partition:", render(err)); self->quit(std::move(err)); }); return { Let's double-check if we need to `deliver()` the outstanding evalutions here }, [=](caf::error err) { VAST_ERROR(self, "failed to load partition:", render(err)); + // Deliver the error for all deferred evaluations. + for (auto&& [expr, rp] : + std::exchange(self->state.deferred_evaluations, {})) { + // Because of a deficiency in the typed_response_promise API, we must + // access the underlying response_promise to deliver the error. + caf::response_promise& untyped_rp = rp; + untyped_rp.deliver(static_cast<partition_actor>(self), err); + } + // Quit the partition. self->quit(std::move(err)); }); return {
codereview_cpp_data_884
{ bool ret; - if (!strncmp(snapname, "ALL", strlen(snapname))) ret = c->snapshot_destroy_all(c); else ret = c->snapshot_destroy(c, snapname); `== 0` syntax, please { bool ret; + if (strncmp(snapname, "ALL", strlen(snapname)) == 0) ret = c->snapshot_destroy_all(c); else ret = c->snapshot_destroy(c, snapname);
codereview_cpp_data_892
.build(); } -template <typename Builder> -auto createValidQuery(Builder builder, - const shared_model::crypto::Keypair &keypair) { - return builder.signAndAddSignature(keypair).finish(); -} - template <typename Query> auto createInvalidQuery(Query query, const shared_model::crypto::Keypair &keypair) { This test should be split into two ones: for valid query and invalid one, otherwise two different cases are tested at once. Also naming suggests that this is test for only failed case whereas it is not .build(); } template <typename Query> auto createInvalidQuery(Query query, const shared_model::crypto::Keypair &keypair) {
codereview_cpp_data_909
// bultin transport, and instead use a lossy shim layer variant. auto testTransport = std::make_shared<test_UDPv4TransportDescriptor>(); testTransport->sendBufferSize = 1024; testTransport->receiveBufferSize = 65536; // We drop 20% of all data frags testTransport->dropDataFragMessagesPercentage = 20; To reduce fragment size, `max_message_size` should be decreased instead of `sendBufferSize`. // bultin transport, and instead use a lossy shim layer variant. auto testTransport = std::make_shared<test_UDPv4TransportDescriptor>(); testTransport->sendBufferSize = 1024; + testTransport->maxMessageSize = 1024; testTransport->receiveBufferSize = 65536; // We drop 20% of all data frags testTransport->dropDataFragMessagesPercentage = 20;
codereview_cpp_data_921
log_->info("check proposal"); // fetch first proposal from proposal queue ProposalType proposal; - log_->info("fetching from queue"); fetchFromQueue( proposal_queue_, proposal, proposal_waiting, "missed proposal"); - log_->info("validating proposal"); validation(proposal); return *this; } I believe this logs were added when debugging, maybe remove them? log_->info("check proposal"); // fetch first proposal from proposal queue ProposalType proposal; fetchFromQueue( proposal_queue_, proposal, proposal_waiting, "missed proposal"); validation(proposal); return *this; }
codereview_cpp_data_928
btnGroup.createButton( area.x + 5, area.y + 222, okayButtonIcn, 0, 1, Dialog::OK ); btnGroup.createButton( area.x + 187, area.y + 222, cancelButtonIcn, 0, 1, Dialog::CANCEL ); - drawButtonWithShadow( fheroes2::AGG::GetICN( okayButtonIcn, 1 ), display, btnGroup.button( 0 ).area() ); - drawButtonWithShadow( fheroes2::AGG::GetICN( cancelButtonIcn, 1 ), display, btnGroup.button( 1 ).area() ); - btnGroup.draw(); display.render(); By doing this we essentially rendering each button twice. We shouldn't do this. btnGroup.createButton( area.x + 5, area.y + 222, okayButtonIcn, 0, 1, Dialog::OK ); btnGroup.createButton( area.x + 187, area.y + 222, cancelButtonIcn, 0, 1, Dialog::CANCEL ); + btnGroup.drawShadows(); btnGroup.draw(); display.render();
codereview_cpp_data_933
* an undirected graph can be represented simply by storing each each as * two directed edges in both directions. */ -typedef std::vector<std::vector<int> > adjacency_list; /** * \brief ```suggestion using adjacency_list = std::vector<std::vector<int>>; ``` * an undirected graph can be represented simply by storing each each as * two directed edges in both directions. */ +using adjacency_list = std::vector<std::vector<int>>; /** * \brief
codereview_cpp_data_948
} fflush(output_model_file); } - fprintf(output_model_file, "feature importances=%s\n", FeatureImportance(models_.size()).c_str()); - fflush(output_model_file); fclose(output_model_file); } I think it is better to put "feature importances=%s\n" into FeatureImportance function. } fflush(output_model_file); } + FeatureImportance(models_.size()); fclose(output_model_file); }
codereview_cpp_data_957
}; static struct s2n_cipher_suite *s2n_tls13_null_key_exchange_alg_cipher_suites[] = { - &s2n_tls13_aes_256_gcm_sha384, /* 0x13,0x02 */ &s2n_tls13_aes_128_gcm_sha256, /* 0x13,0x01 */ &s2n_tls13_chacha20_poly1305_sha256, /* 0x13,0x03 */ }; nit: reorder these. }; static struct s2n_cipher_suite *s2n_tls13_null_key_exchange_alg_cipher_suites[] = { &s2n_tls13_aes_128_gcm_sha256, /* 0x13,0x01 */ + &s2n_tls13_aes_256_gcm_sha384, /* 0x13,0x02 */ &s2n_tls13_chacha20_poly1305_sha256, /* 0x13,0x03 */ };
codereview_cpp_data_966
if (!checkSql()) return true; - if (!usernameIsValid(user)) return true; QSqlQuery *passwordQuery = prepareQuery("select password_sha512 from {prefix}_users where name = :name"); Is the query deleted by some other function? Will this leak? if (!checkSql()) return true; + QString error; + if (!usernameIsValid(user, error)) return true; QSqlQuery *passwordQuery = prepareQuery("select password_sha512 from {prefix}_users where name = :name");
codereview_cpp_data_969
* */ -int partition(int *arr, int low, int high) { int pivot = arr[high]; // taking the last element as pivot int i = (low - 1); // Index of smaller element Would be better to use `std::vector` or `std::array` instead of C-style arrays. * */ +int partition(vector<int> arr, int low, int high) { int pivot = arr[high]; // taking the last element as pivot int i = (low - 1); // Index of smaller element
codereview_cpp_data_971
return str1 > str2; } -bool Army::isFootsloggingArmy() const { double meleeInfantry = 0; double other = 0; This method name is a bit confusing. Maybe we could rename it into isMeleeDominantArmy()? What do you think? return str1 > str2; } +bool Army::isMeleeDominantArmy() const { double meleeInfantry = 0; double other = 0;
codereview_cpp_data_972
ySize = p->srcPtr.ysize; dstPitch = p->dstPtr.pitch; } - hc::completion_future marker; try { if((widthInBytes == dstPitch) && (widthInBytes == srcPitch)) { Think it is better to keep it here. ySize = p->srcPtr.ysize; dstPitch = p->dstPtr.pitch; } + hipStream_t stream = ihipSyncAndResolveStream(stream); hc::completion_future marker; try { if((widthInBytes == dstPitch) && (widthInBytes == srcPitch)) {
codereview_cpp_data_976
wlr_log(L_DEBUG, "got shell surface toplevel"); struct wlr_wl_shell_surface *surface = wl_resource_get_user_data(resource); - if (surface->transient_state != NULL) { return; } - surface->toplevel = true; - wl_signal_emit(&surface->events.set_toplevel, surface); } static void shell_surface_set_transient(struct wl_client *client, Reminder that you should have the rootston side of things listen to this and attach the view to the cursor. wlr_log(L_DEBUG, "got shell surface toplevel"); struct wlr_wl_shell_surface *surface = wl_resource_get_user_data(resource); + if (surface->role != WLR_WL_SHELL_SURFACE_ROLE_NONE) { return; } + surface->role = WLR_WL_SHELL_SURFACE_ROLE_TOPLEVEL; + wl_signal_emit(&surface->events.set_role, surface); } static void shell_surface_set_transient(struct wl_client *client,
codereview_cpp_data_979
UniValue generate(const UniValue &params, bool fHelp) { - if (fHelp || params.size() < 1 || params.size() > 3) - throw runtime_error("generate numblocks ( maxtries ) (genmode)\n" "\nMine up to numblocks blocks immediately (before the RPC call returns)\n" "\nArguments:\n" "1. numblocks (numeric, required) How many blocks are generated immediately.\n" "2. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n" - "3. genmode (string, optional) Generation mode for weak and strong blocks (default = " - "strong-only) Can be one of strong-only, weak-and-strong, weak-only" "\nResult\n" "[ blockhashes ] (array) hashes of blocks generated\n" "\nExamples:\n" do you want to convert this to a bool before passing in? UniValue generate(const UniValue &params, bool fHelp) { + if (fHelp || params.size() < 1 || params.size() > 2) + throw runtime_error("generate numblocks ( maxtries )\n" "\nMine up to numblocks blocks immediately (before the RPC call returns)\n" "\nArguments:\n" "1. numblocks (numeric, required) How many blocks are generated immediately.\n" "2. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n" "\nResult\n" "[ blockhashes ] (array) hashes of blocks generated\n" "\nExamples:\n"
codereview_cpp_data_981
if(0){ // WIP(leveldb don't active) Send transaction data separated block to new peer. logger::debug("peer-service") << "send all transaction infomation"; auto transactions = repository::transaction::findAll(); - int block_size = 500; for (std::size_t i = 0; i < transactions.size(); i += block_size) { auto txResponse = Api::TransactionResponse(); txResponse.set_message("Midstream send Transactions"); `std::size_t block_size` as well if(0){ // WIP(leveldb don't active) Send transaction data separated block to new peer. logger::debug("peer-service") << "send all transaction infomation"; auto transactions = repository::transaction::findAll(); + std::size_t block_size = 500; for (std::size_t i = 0; i < transactions.size(); i += block_size) { auto txResponse = Api::TransactionResponse(); txResponse.set_message("Midstream send Transactions");
codereview_cpp_data_983
EXPECT_SUCCESS(s2n_connection_set_io_pair(server_conn, &io_pair)); EXPECT_SUCCESS(try_handshake(server_conn, client_conn, async_handler_sign_with_different_pkey_and_apply)); - EXPECT_EQUAL(async_handler_called, 1); - - /* Reset counter */ - async_handler_called = 0; /* Free the data */ EXPECT_SUCCESS(s2n_connection_free(server_conn)); Do you need to reset the counter here, or before you call try_handshake? EXPECT_SUCCESS(s2n_connection_set_io_pair(server_conn, &io_pair)); EXPECT_SUCCESS(try_handshake(server_conn, client_conn, async_handler_sign_with_different_pkey_and_apply)); /* Free the data */ EXPECT_SUCCESS(s2n_connection_free(server_conn));
codereview_cpp_data_987
std::sort(childrenNodes.begin(), childrenNodes.end(), comparatorFunction); } } - return new MegaNodeListPrivate(childrenNodes.data(), int(childrenNodes.size()));; } MegaNodeList *MegaApiImpl::getVersions(MegaNode *node) We could take this chance to apply the same improvements to the other analog methods: - `MegaApiImpl::getFileFolderChildren()` - `MegaApiImpl::getIndex()` The other public methods allowing to specify the order for the results, they already use `ORDER_NONE` by default (ie. `search()` ) :) std::sort(childrenNodes.begin(), childrenNodes.end(), comparatorFunction); } } + return new MegaNodeListPrivate(childrenNodes.data(), int(childrenNodes.size())); } MegaNodeList *MegaApiImpl::getVersions(MegaNode *node)
codereview_cpp_data_1000
{"swift-module-search-paths", OptionValue::eTypeFileSpecList, false, 0, nullptr, nullptr, "List of directories to be searched when locating modules for Swift."}, - {"swift-create-module-contexts-in-parallel", OptionValue::eTypeBoolean, false, true, - nullptr, nullptr, "Create modules AST context in parallel."}, {"auto-import-clang-modules", OptionValue::eTypeBoolean, false, true, nullptr, nullptr, "Automatically load Clang modules referred to by the program."}, `Create the per-module Swift AST contexts in parallel.` ? {"swift-module-search-paths", OptionValue::eTypeFileSpecList, false, 0, nullptr, nullptr, "List of directories to be searched when locating modules for Swift."}, {"auto-import-clang-modules", OptionValue::eTypeBoolean, false, true, nullptr, nullptr, "Automatically load Clang modules referred to by the program."},
codereview_cpp_data_1007
std::string classname = arg->getAttribute( "type", ""); std::string templatename = arg->getAttribute( "template", ""); templatename = sofa::defaulttype::TemplateAliases::resolveAlias(templatename); // Resolve template aliases ClassEntryMap::iterator it = registry.find(classname); if (it == registry.end()) The modifs in the object factory need explanations to clearly get what the consequences are. std::string classname = arg->getAttribute( "type", ""); std::string templatename = arg->getAttribute( "template", ""); templatename = sofa::defaulttype::TemplateAliases::resolveAlias(templatename); // Resolve template aliases + ClassEntry::SPtr entry ; ClassEntryMap::iterator it = registry.find(classname); if (it == registry.end())
codereview_cpp_data_1011
&& (0xBF == mio_getc (mio))) r = true; - if (r && skipIfFound) mio_rewind (mio); return r; } Is this condition correct? Shouldn't be `! (r && skipIfFound)`? && (0xBF == mio_getc (mio))) r = true; + if (! (r && skipIfFound)) mio_rewind (mio); return r; }
codereview_cpp_data_1012
parser::parseValue<boost::multiprecision::uint256_t>(params[2]); auto precision = parser::parseValue<uint32_t>(params[3]); if (not val_int or not precision) { - std::cout << "Wrong format for amount or precision should be greater than 0" << std::endl; return nullptr; } - if (precision.value() > 255) { - std::cout << "Too big precision (should be less than 256)" << std::endl; return nullptr; } std::cout << val_int.value() << " " << precision.value() << std::endl; These are 2 separate cases, so I suggest having two separate checks with different messages, one for amount and one for precision. Also, that line is too long, our guideline is 80 characters per line. We use clang-format to keep code style consistent. parser::parseValue<boost::multiprecision::uint256_t>(params[2]); auto precision = parser::parseValue<uint32_t>(params[3]); if (not val_int or not precision) { + std::cout << "Wrong format for amount" << std::endl; return nullptr; } + if (precision.value() > 255 || precision.value() < 0) { + std::cout << "Too big precision (should be between 0 and 256)" << std::endl; return nullptr; } std::cout << val_int.value() << " " << precision.value() << std::endl;
codereview_cpp_data_1021
return false; }, [this](const auto &status) { - log_->warn( - "Received already processed batch. Duplicate transaction: {}", - status.hash.hex()); return true; }); }); From the log it will be unclear, where messages about one batch end and another starts. I propose to add some splitters to the messages, so it would be: Batch 1: Received already processed batch. Duplicate transaction 395gjfr8g49 Received already processed batch. Duplicate transaction fc409mir43k Batch 42: Received already processed batch. Duplicate transaction fk4590owfje Of course, the information can be extracted from tx hashes, but for usability it will be better, if it were understood from the first glance return false; }, [this](const auto &status) { + log_->warn("Duplicate transaction: {}", status.hash.hex()); return true; }); });
codereview_cpp_data_1022
*/ void WrapTorus::constructProperties() { - constructProperty_inner_radius(1.0); - constructProperty_outer_radius(1.0); } void WrapTorus::extendScale(const SimTK::State& s, const ScaleSet& scaleSet) Consider using more reasonable defaults (inner radius of 0.05 cm, outer radius of 0.01 cm). */ void WrapTorus::constructProperties() { + constructProperty_inner_radius(0.01); + constructProperty_outer_radius(0.05); } void WrapTorus::extendScale(const SimTK::State& s, const ScaleSet& scaleSet)
codereview_cpp_data_1023
ametsuchi_factory_(std::move(factory)), block_queries_(std::move(blockQuery)), crypto_signer_(std::move(crypto_signer)), - block_factory_(std::move(block_factory)) { - log_ = logger::log("Simulator"); ordering_gate->on_proposal().subscribe( proposal_subscription_, [this](std::shared_ptr<shared_model::interface::Proposal> proposal) { To ctor initialisation, please ametsuchi_factory_(std::move(factory)), block_queries_(std::move(blockQuery)), crypto_signer_(std::move(crypto_signer)), + block_factory_(std::move(block_factory)), + log_(logger::log("Simulator")){ ordering_gate->on_proposal().subscribe( proposal_subscription_, [this](std::shared_ptr<shared_model::interface::Proposal> proposal) {
codereview_cpp_data_1024
return false; } if (last_tx_status_received) { // force stream to end because no more tx statuses will arrive. // it is thread safe because of synchronization on current_thread return false; } - - log_->debug("status written, {}", client_id); return true; }) .subscribe(subscription, I get the following order in a minimal example: ``` a next a complete a finally b next take while complete ``` where `a` is status bus, and `b` is consensus events observable. It means that it will execute `take_while` after `finally`, and this log `status written` should be moved before `last_tx_status_received` conditional. return false; } + log_->debug("status written, {}", client_id); if (last_tx_status_received) { // force stream to end because no more tx statuses will arrive. // it is thread safe because of synchronization on current_thread return false; } return true; }) .subscribe(subscription,
codereview_cpp_data_1026
} auto const* comma = std::strchr(resource_str, ','); - if (!comma || strncmp(resource_str, "id:", 3) != 0) { std::ostringstream ss; ss << "Error: invalid value of " << ctest_resource_group_id_name << ": '" << resource_str << "'. Raised by Kokkos::Impl::get_ctest_gpu()."; maybe extra paren around `strncmp(...) != 0` } auto const* comma = std::strchr(resource_str, ','); + if (!comma || (strncmp(resource_str, "id:", 3) != 0)) { std::ostringstream ss; ss << "Error: invalid value of " << ctest_resource_group_id_name << ": '" << resource_str << "'. Raised by Kokkos::Impl::get_ctest_gpu().";
codereview_cpp_data_1030
} } -CommandQueryBandwidthQuota::CommandQueryBandwidthQuota(MegaClient* client, m_off_t size) { cmd("qbq"); arg("s", size); Shouldn't we return `API_EINTERNAL` in this case?? } } +CommandQueryTransferQuota::CommandQueryTransferQuota(MegaClient* client, m_off_t size) { cmd("qbq"); arg("s", size);
codereview_cpp_data_1043
# include "../../_Plugin_Helper.h" # include "../Helpers/ESPEasyStatistics.h" # include "../Static/WebStaticData.h" -//HELPERS_ESPEASY_MATH_H //clumsy-stefan: what's this for? #ifdef WEBSERVER_METRICS #ifdef ESP32 # include <esp_partition.h> #endif // ifdef ESP32 No idea why it ended up in the code. You can remove the entire line. # include "../../_Plugin_Helper.h" # include "../Helpers/ESPEasyStatistics.h" # include "../Static/WebStaticData.h" #ifdef WEBSERVER_METRICS + #ifdef ESP32 # include <esp_partition.h> #endif // ifdef ESP32
codereview_cpp_data_1048
HifPackage *pkg = k; /* Set noscripts since we already validated them above */ - if (!add_to_transaction (rpmdb_ts, pkg, tmp_metadata_dfd, TRUE, - self->ignore_scripts, cancellable, error)) goto out; } Change to `NULL` to not give false illusions? HifPackage *pkg = k; /* Set noscripts since we already validated them above */ + if (!add_to_transaction (rpmdb_ts, pkg, tmp_metadata_dfd, TRUE, NULL, cancellable, error)) goto out; }
codereview_cpp_data_1049
printf(" %-30s Add node id symbol tags in the makeflow log. (default is false)\n", " --log-verbose"); printf(" %-30s Run each task with a container based on this docker image.\n", "--docker=<image>"); printf(" %-30s Load docker image from the tar file.\n", "--docker-tar=<tar file>"); - printf(" %-30s Indicate user trusts inputs exist.\n", "--skip-file-check"); printf(" %-30s Indicate preferred master connection. Choose one of by_ip or by_hostname. (default is by_ip)\n", "--work-queue-preferred-connection"); printf("\n*Monitor Options:\n\n"); "Do not check whether inputs exit (Useful for very large workflows on shared filesystems.)" Also, add to man page. printf(" %-30s Add node id symbol tags in the makeflow log. (default is false)\n", " --log-verbose"); printf(" %-30s Run each task with a container based on this docker image.\n", "--docker=<image>"); printf(" %-30s Load docker image from the tar file.\n", "--docker-tar=<tar file>"); + printf(" %-30s Do not check whether inputs exist. (Useful for very large workflows on shared filesystems.)\n", "--skip-file-check"); printf(" %-30s Indicate preferred master connection. Choose one of by_ip or by_hostname. (default is by_ip)\n", "--work-queue-preferred-connection"); printf("\n*Monitor Options:\n\n");
codereview_cpp_data_1056
*/ #include <utils/s2n_socket.h> void s2n_socket_read_snapshot_harness() { - struct s2n_socket_read_io_context *cbmc_allocate_s2n_socket_read_io_context(); /* Non-deterministic inputs. */ struct s2n_connection *s2n_connection = malloc(sizeof(*s2n_connection)); if (s2n_connection != NULL) { (Nitpick - same for other harnesses) It should be ```c /* Non-deterministic inputs. */ struct s2n_socket_read_io_context *cbmc_allocate_s2n_socket_read_io_context(); struct s2n_connection *s2n_connection = malloc(sizeof(*s2n_connection)); if (s2n_connection != NULL) { s2n_connection->recv_io_context = cbmc_allocate_s2n_socket_read_io_context(); } ``` */ #include <utils/s2n_socket.h> +#include <cbmc_proof/make_common_datastructures.h> void s2n_socket_read_snapshot_harness() { /* Non-deterministic inputs. */ struct s2n_connection *s2n_connection = malloc(sizeof(*s2n_connection)); if (s2n_connection != NULL) {
codereview_cpp_data_1058
std::move(cache), std::move(proposal_factory), std::move(tx_cache), - initial_round, max_number_of_transactions, ordering_log_manager->getChild("Gate")->getLogger()); } Header has to be fixed as well. std::move(cache), std::move(proposal_factory), std::move(tx_cache), max_number_of_transactions, ordering_log_manager->getChild("Gate")->getLogger()); }
codereview_cpp_data_1061
argv[argc - 1] = NULL; // check that the gpg binary exists and that it is executable - if (isExecutable (argv[0], errorKey) < 0) { elektraFree (argv[0]); return -1; // error set by isExecutable() Why not free `argv[0]`? argv[argc - 1] = NULL; // check that the gpg binary exists and that it is executable + if (isExecutable (argv[0], errorKey) != 1) { elektraFree (argv[0]); return -1; // error set by isExecutable()
codereview_cpp_data_1068
TEST(StatusConditionImplTests, notify_trigger) { - ConditionNotifier notifier; StatusConditionImpl uut(&notifier); StatusMask mask_all = StatusMask::all(); Use StrictMock to fail if undesired mock calls are made. Specifically, we do not want calls to `notifier.notify` to occur when not expected. ```suggestion using ::testing::StrictMock; StrictMock<ConditionNotifier> notifier; ``` TEST(StatusConditionImplTests, notify_trigger) { + ::testing::StrictMock<ConditionNotifier> notifier; StatusConditionImpl uut(&notifier); StatusMask mask_all = StatusMask::all();
codereview_cpp_data_1073
} // Only the first time, initialize environment file watch if the corresponding environment variable is set - if (m_RTPSParticipantIDs.empty()) { if (!SystemInfo::get_environment_file().empty()) { What if we create a participant, remove it, and create another one? Could we base this check on the value of `RTPSDomainImpl::file_watch_handle_`? Or perhaps we could add a boolean flag to `RTPSDomainImpl` } // Only the first time, initialize environment file watch if the corresponding environment variable is set + if (!RTPSDomainImpl::file_watch_handle_) { if (!SystemInfo::get_environment_file().empty()) {
codereview_cpp_data_1081
* OLD: This routine inverts this relation using the iterative scheme given * by Snyder (1987), Eqs. (7-9) - (7-11). * - * NEW: This routine writes converts t = exp(-psi) to * * tau' = sinh(psi) = (1/t - t)/2 * ```suggestion * NEW: This routine converts t = exp(-psi) to ``` * OLD: This routine inverts this relation using the iterative scheme given * by Snyder (1987), Eqs. (7-9) - (7-11). * + * NEW: This routine converts t = exp(-psi) to * * tau' = sinh(psi) = (1/t - t)/2 *
codereview_cpp_data_1084
while(*c && isspacetab(*c)) c++; - if(*c && (*c != ',')) { paramBegin[iParamCount] = c; c++; Hum, won't this add one parameter too many, as it'll be entered by the closing `)`? while(*c && isspacetab(*c)) c++; + if(*c && (*c != ',') && (*c != ')')) { paramBegin[iParamCount] = c; c++;
codereview_cpp_data_1086
boost::optional<std::unique_ptr<FlatFile>> FlatFile::create( const std::string &path) { - auto log_ = logger::log("KeyValueStorage::create()"); boost::system::error_code err; if (not boost::filesystem::is_directory(path, err) `FlatFile` seemed more appropriate, because this method is not called from `KeyValueStorage`. boost::optional<std::unique_ptr<FlatFile>> FlatFile::create( const std::string &path) { + auto log_ = logger::log("FlatFile::create()"); boost::system::error_code err; if (not boost::filesystem::is_directory(path, err)
codereview_cpp_data_1097
stream << QString("%1 %2\n").arg( card->getNumber() ).arg( - card->getName().replace("//", "/").replace("Who / What / When / Where / Why", "Who/What/When/Where/Why") ); } } Instead of hardcoding a specific card name, what about doing `.replace("//", "/").replace(" / ", "/")`? Would that work? stream << QString("%1 %2\n").arg( card->getNumber() ).arg( + card->getName().replace("//", "/") ); } }
codereview_cpp_data_1102
lbann_data::LbannPB& p, std::vector<int>& root_random_seeds, std::vector<int>& random_seeds, - std::vector<int>& data_seq_random_seeds, - int procs_per_trainer) { if (!comm.am_world_master()) { return; Can we get `procs_per_trainer` by interrogating `comm`? lbann_data::LbannPB& p, std::vector<int>& root_random_seeds, std::vector<int>& random_seeds, + std::vector<int>& data_seq_random_seeds) { if (!comm.am_world_master()) { return;
codereview_cpp_data_1104
* 1) create a global script for running docker container * 2) add this script to the global wrapper list */ - makeflow_create_docker_sh(); - //makeflow_wrapper_add_input_file(CONTAINER_SH); - char global_cmd[64]; - sprintf(global_cmd, "./%s", CONTAINER_SH); makeflow_wrapper_add_command(global_cmd); } Why use sprintf here? Just pass CONTAINER_SH as the argument. * 1) create a global script for running docker container * 2) add this script to the global wrapper list */ + makeflow_create_docker_sh(); + char *global_cmd = string_format("sh %s", CONTAINER_SH); makeflow_wrapper_add_command(global_cmd); }
codereview_cpp_data_1106
} } } - } - for (handledrn_map::iterator it = hdrns.begin(); it != hdrns.end();) - { - (it++)->second->retry(API_OK); } } Should the loop over `hdrns` (the direct read nodes) be included in this check for EPAYWALL? If we are disallowing downloads, direct read should probably be paused/prevented during that state also? thanks } } } + for (handledrn_map::iterator it = hdrns.begin(); it != hdrns.end();) + { + (it++)->second->retry(API_OK); + } } }
codereview_cpp_data_1112
QSqlQuery *query = servatriceDatabaseInterface->prepareQuery( "insert into {prefix}_uptime (id_server, timest, uptime, users_count, mods_count, mods_list, games_count, " - "tx_bytes, " - "rx_bytes) " - "values(:id, NOW(), :uptime, :users_count, :mods_count, :mods_list, :games_count, :tx, :rx)"); query->bindValue(":id", serverId); query->bindValue(":uptime", uptime); query->bindValue(":users_count", uc); line splitting looks ugly, is this due to clang-format? QSqlQuery *query = servatriceDatabaseInterface->prepareQuery( "insert into {prefix}_uptime (id_server, timest, uptime, users_count, mods_count, mods_list, games_count, " + "tx_bytes, rx_bytes) values(:id, NOW(), :uptime, :users_count, :mods_count, :mods_list, :games_count, :tx, " + ":rx)"); query->bindValue(":id", serverId); query->bindValue(":uptime", uptime); query->bindValue(":users_count", uc);
codereview_cpp_data_1119
// ...then pass those pairs one at a time through the merger, since it only merges pairs NodeMap nodes = map->getNodeMap(); OsmMapPtr mergedMap(map); - const ElementId firstId = ElementId::node(((nodes.begin()->second))->getId()); //LOG_DEBUG("First ID: " << firstId.getId()); - int count = 0; for (NodeMap::const_iterator it = nodes.begin(); it != nodes.end(); ++it) { - if (count > 0) { const boost::shared_ptr<const Node>& n = it->second; std::set< std::pair< ElementId, ElementId> > matches; @mingjiesu This is the section that will be reworked to support the swapped node issue that Brian was describing. I'm hoping we can address the elements based on ID here rather than looping through them. // ...then pass those pairs one at a time through the merger, since it only merges pairs NodeMap nodes = map->getNodeMap(); OsmMapPtr mergedMap(map); + + const ElementId firstId = ElementId::node(elementId); //LOG_DEBUG("First ID: " << firstId.getId()); for (NodeMap::const_iterator it = nodes.begin(); it != nodes.end(); ++it) { + if (it->second->getId() != elementId) { const boost::shared_ptr<const Node>& n = it->second; std::set< std::pair< ElementId, ElementId> > matches;
codereview_cpp_data_1120
m_httpResponse = client .request(web::http::methods::GET, builder.to_string()) .then([](web::http::http_response resp) { return resp.extract_utf8string(); }) - .then([this](std::string xml) { auto remoteQueryResponse = processReply(xml); if (remoteQueryResponse) { @axelstudios does this client use wstring on all platforms? m_httpResponse = client .request(web::http::methods::GET, builder.to_string()) .then([](web::http::http_response resp) { return resp.extract_utf8string(); }) + .then([this](const std::string& xml) { auto remoteQueryResponse = processReply(xml); if (remoteQueryResponse) {
codereview_cpp_data_1126
if ( !Parent::preload( server, errorBuffer ) ) return false; - if( server ) return true; - // If we don't have a physics plugin active then // we have to fail completely. if ( !PHYSICSMGR ) This needs to be removed, it stops the TSShape and PhysicsCollisionRef from been created server side. if ( !Parent::preload( server, errorBuffer ) ) return false; // If we don't have a physics plugin active then // we have to fail completely. if ( !PHYSICSMGR )
codereview_cpp_data_1130
EXPECT_SUCCESS(s2n_client_hello_send(client_conn)); EXPECT_SUCCESS(s2n_stuffer_copy(&client_conn->handshake.io, &server_conn->handshake.io, s2n_stuffer_data_available(&client_conn->handshake.io))); - if (s2n_is_tls_12_self_downgrade_required(client_conn)) { - EXPECT_FAILURE_WITH_ERRNO(s2n_client_hello_recv(server_conn), S2N_ERR_PROTOCOL_VERSION_UNSUPPORTED); - } else { - EXPECT_SUCCESS(s2n_client_hello_recv(server_conn)); - } s2n_connection_free(client_conn); s2n_connection_free(server_conn); This test isn't interested in fallback behavior. TLS1.2 + QUIC always fails, but we're not testing that here. Probably worth restricting it to TLS1.3 only. Same for the next one. EXPECT_SUCCESS(s2n_client_hello_send(client_conn)); EXPECT_SUCCESS(s2n_stuffer_copy(&client_conn->handshake.io, &server_conn->handshake.io, s2n_stuffer_data_available(&client_conn->handshake.io))); + + EXPECT_SUCCESS(s2n_client_hello_recv(server_conn)); + s2n_connection_free(client_conn); s2n_connection_free(server_conn);
codereview_cpp_data_1131
server->clientsLock.lockForRead(); while (allUsersIterator.hasNext()) { Server_AbstractUserInterface *userHandler = server->findUser(allUsersIterator.next()); - if (userHandler) - if (server->getStoreReplaysEnabled()) userHandler->sendProtocolItem(*sessionEvent); } server->clientsLock.unlock(); Maybe just put these into a single `if (userHandler && server->getStoreReplaysEnabled())`? server->clientsLock.lockForRead(); while (allUsersIterator.hasNext()) { Server_AbstractUserInterface *userHandler = server->findUser(allUsersIterator.next()); + if (userHandler && server->getStoreReplaysEnabled()) userHandler->sendProtocolItem(*sessionEvent); } server->clientsLock.unlock();
codereview_cpp_data_1146
namespace config { namespace detail { -std::string appendSlashIfNeeded(const std::string& str) { if (str.empty()) { return std::string("/"); } why camelCase name? (and below also) namespace config { namespace detail { +std::string append_slash_if_needed(const std::string& str) { if (str.empty()) { return std::string("/"); }
codereview_cpp_data_1153
{ const char *cmd = argv[0], *opt_config_file = H2O_TO_STR(H2O_CONFIG_PATH); int n, error_log_fd = -1; - size_t num_threads = h2o_numproc(); - h2o_vector_reserve(NULL, &conf.thread_map, num_threads); - for (n = 0; n < num_threads; n++) conf.thread_map.entries[conf.thread_map.size++] = -1; conf.tfo_queues = H2O_DEFAULT_LENGTH_TCP_FASTOPEN_QUEUE; conf.launch_time = time(NULL); Nitpick, but we might want to name the variable `num_procs`, because it indicates the number of CPU cores, not the number of threads in any particular way. { const char *cmd = argv[0], *opt_config_file = H2O_TO_STR(H2O_CONFIG_PATH); int n, error_log_fd = -1; + size_t num_procs = h2o_numproc(); + h2o_vector_reserve(NULL, &conf.thread_map, num_procs); + for (n = 0; n < num_procs; n++) conf.thread_map.entries[conf.thread_map.size++] = -1; conf.tfo_queues = H2O_DEFAULT_LENGTH_TCP_FASTOPEN_QUEUE; conf.launch_time = time(NULL);
codereview_cpp_data_1165
cb = proceed_handshake; break; default: cb = on_handshake_fail_complete; break; } lgtm, thank you. suppose `PTLS_ERROR_STATELESS_RETRY` is OK to be handled here. cb = proceed_handshake; break; default: + assert(ret != PTLS_ERROR_STATELESS_RETRY && "stateless retry is never turned on by us for TCP"); cb = on_handshake_fail_complete; break; }
codereview_cpp_data_1168
} auto sql = std::make_unique<soci::session>(*connection_); if (block_is_prepared) { rollbackPrepared(*sql); } Please add a note here that it is safely rolled back because `createMutableStorage` is not called before `commitPrepared` in good case. Otherwise it is a bit confusing that `createMutableStorage` is usually called before any operations, and it looks like prepared block is always rolled back. } auto sql = std::make_unique<soci::session>(*connection_); + // if we create mutable storage, then we intend to mutate wsv + // this means that any state prepared before that moment is not needed + // and must be removed to preventy locking if (block_is_prepared) { rollbackPrepared(*sql); }
codereview_cpp_data_1181
if (!nodebyhandle(config.getRemoteNode())) { // remote node gone - syncConfigs->remove(config.getLocalPath()); continue; } const auto e = addsync(config, DEBRISFOLDER, nullptr); The sync should not be removed in this case. It would change the current behavior in MEGAsync (just try to remove the node relative to a synced folder and you will see the SyncConfig stays there, but disabled). Removing is not an option here. Please, disable the sync instead of remove. if (!nodebyhandle(config.getRemoteNode())) { // remote node gone + config.setResumable(false); + syncConfigs->insert(config); continue; } const auto e = addsync(config, DEBRISFOLDER, nullptr);
codereview_cpp_data_1183
// assumptions between DecorativeCylinder aligned with y and // WrapCylinder aligned with z ztoy.updR().setRotationFromAngleAboutX(SimTK_PI / 2); - // B: base Frame (Body or Ground) - // F: PhysicalFrame that this ContactGeometry is connected to - // P: the frame defined (relative to F) by the location and orientation - // properties. - const SimTK::Transform& X_BF = getFrame().findTransformInBaseFrame(); - const auto& X_FP = getTransform(); - const auto X_BP = X_BF * X_FP; SimTK::Transform X_BP_ztoy = X_BP*ztoy; appendToThis.push_back( SimTK::DecorativeCylinder(get_radius(), ContactGeometry -> WrapGeometry. // assumptions between DecorativeCylinder aligned with y and // WrapCylinder aligned with z ztoy.updR().setRotationFromAngleAboutX(SimTK_PI / 2); + + const auto X_BP = getWrapGeometryTransformInBody(); SimTK::Transform X_BP_ztoy = X_BP*ztoy; appendToThis.push_back( SimTK::DecorativeCylinder(get_radius(),
codereview_cpp_data_1184
} // what is the port chosen for the server? - char addr[LINK_ADDRESS_MAX]; - int local = link_address_local(server_link, &addr, &server_port); if(!local){ printf("could not get local address: %s\n", strerror(errno)); return 1; The name of an array is the address of its first element. So just pass `addr` not `&addr` } // what is the port chosen for the server? + char *addr; + addr = (char *)malloc(LINK_ADDRESS_MAX); + int local = link_address_local(server_link, addr, &server_port); if(!local){ printf("could not get local address: %s\n", strerror(errno)); return 1;
codereview_cpp_data_1192
#ifdef AMREX_USE_HYPRE if (init_hypre) { HYPRE_Init(); -#ifdef AMREX_USE_CUDA hypre_HandleDefaultExecPolicy(hypre_handle()) = HYPRE_EXEC_DEVICE; hypre_HandleSpgemmUseCusparse(hypre_handle()) = 0; #endif ```suggestion #if defined(AMREX_USE_HYPRE) && defined(HYPRE_USING_CUDA) if (init_hypre) { HYPRE_Init(); hypre_HandleDefaultExecPolicy(hypre_handle()) = HYPRE_EXEC_DEVICE; hypre_HandleSpgemmUseCusparse(hypre_handle()) = 0; } #endif ``` @WeiqunZhang We should probably account for the fact that the user might attempt to link to a hypre that is not compiled for CUDA. I had used something like the one above to handle situations where hypre and AMReX were built differently. Do you have any thoughts on that? #ifdef AMREX_USE_HYPRE if (init_hypre) { HYPRE_Init(); +#ifdef HYPRE_USING_CUDA hypre_HandleDefaultExecPolicy(hypre_handle()) = HYPRE_EXEC_DEVICE; hypre_HandleSpgemmUseCusparse(hypre_handle()) = 0; #endif
codereview_cpp_data_1203
}); PostgresOrderingServicePersistentState::create(pg_conn_).match( - [&](expected::Value<std::shared_ptr<ametsuchi::PostgresOrderingServicePersistentState>> &_storage) { - ordering_service_storage_ = _storage.value; - }, [](expected::Error<std::string> &error) { throw std::runtime_error(error.error); }); wow. throwing exceptions from business logic code is forbidden without serious reasons. Better to rework it with explicit behavior. }); PostgresOrderingServicePersistentState::create(pg_conn_).match( + [&](expected::Value< + std::shared_ptr<ametsuchi::PostgresOrderingServicePersistentState>> + &_storage) { ordering_service_storage_ = _storage.value; }, [](expected::Error<std::string> &error) { throw std::runtime_error(error.error); });
codereview_cpp_data_1207
const char *policy = rpmostree_sysroot_get_automatic_update_policy (sysroot_proxy); g_print ("State: %s\n", txn_proxy ? "busy" : "idle"); - g_print ("Automatic Updates: "); if (g_str_equal (policy, "none")) g_print ("disabled\n"); else Minor/bikeshed: lowercase `updates` to make consistent with "Available update"? Alternatively, convert both this one and "Available update" to systemd/golang naming like `AutomaticUpdates` and `AvailableUpdate`? const char *policy = rpmostree_sysroot_get_automatic_update_policy (sysroot_proxy); g_print ("State: %s\n", txn_proxy ? "busy" : "idle"); + g_print ("AutomaticUpdates: "); if (g_str_equal (policy, "none")) g_print ("disabled\n"); else
codereview_cpp_data_1218
} else { - ELEKTRA_SET_ERROR(97, parentKey, "Encountered a multiline value but multiline support is not enabled"); ret = -1; } } Usability maybe not ideal here, please give a hint the user should read "kdb info ini" } else { + ELEKTRA_SET_ERROR(97, parentKey, "Encountered a multiline value but multiline support is not enabled\n " + "Have a look at kdb info ini for more details"); ret = -1; } }
codereview_cpp_data_1221
if (owner && owner->IsClient()) { if (!(owner->CastToClient()->ClientVersionBit() & EQ::versions::maskUFAndLater)) { if ((typeofpet != petFamiliar && typeofpet != petAnimation) || - GetAA(aaAnimationEmpathy) >= 3) { taunting=true; } } We should check aabonuses.PetCommands array instead. if (owner && owner->IsClient()) { if (!(owner->CastToClient()->ClientVersionBit() & EQ::versions::maskUFAndLater)) { if ((typeofpet != petFamiliar && typeofpet != petAnimation) || + aabonuses.PetCommands[PET_TAUNT]) { taunting=true; } }
codereview_cpp_data_1222
* SPDX-License-Identifier: Apache-2.0 */ -#include <validators/protobuf/proto_transaction_validator.hpp> #include "model/sha3_hash.hpp" #include "module/irohad/ametsuchi/ametsuchi_mocks.hpp" #include "module/irohad/multi_sig_transactions/mst_mocks.hpp" change to <> -> "" * SPDX-License-Identifier: Apache-2.0 */ #include "model/sha3_hash.hpp" #include "module/irohad/ametsuchi/ametsuchi_mocks.hpp" #include "module/irohad/multi_sig_transactions/mst_mocks.hpp"
codereview_cpp_data_1227
// front(), which will cause iterating over the *entire* trajectory. To // prevent this, we have to detect if front().getTime() > endTime. if (m_states.empty() || front().getTime() > endTime) { - return makeIteratorRange(end(), end()); } // Must add one to the last iterator since it's supposed to point past // the end. - return makeIteratorRange(getIteratorAfter(startTime, tolerance), getIteratorBefore(endTime, tolerance) + 1); } Should this be NaN or model's default for this state value? NaN may be better so that the value is not blindly used as though it were read in - when in fact it did not exist. A StateTrajectoryBuilder could read in a StateTrajectory and produce a new with NaNs resolved based on convenient rules, like use default values and solver for equilibrium, etc ... is that what you are thinking? // front(), which will cause iterating over the *entire* trajectory. To // prevent this, we have to detect if front().getTime() > endTime. if (m_states.empty() || front().getTime() > endTime) { + return SimTK::makeIteratorRange(end(), end()); } // Must add one to the last iterator since it's supposed to point past // the end. + return SimTK::makeIteratorRange(getIteratorAfter(startTime, tolerance), getIteratorBefore(endTime, tolerance) + 1); }
codereview_cpp_data_1252
writer_two{write_two}; writer_one.join(); reader.join(); } Why you removed that joins? writer_two{write_two}; writer_one.join(); reader.join(); + releaser.join(); }
codereview_cpp_data_1260
// diagonal move costs 50% extra if ( direction & ( Direction::TOP_RIGHT | Direction::BOTTOM_RIGHT | Direction::BOTTOM_LEFT | Direction::TOP_LEFT ) ) - penalty *= 1.5; return penalty; } Let's avoid type conversion here and use `penalty = penalty * 3 / 2;`. We really want to reduce the number of compilation warnings :( // diagonal move costs 50% extra if ( direction & ( Direction::TOP_RIGHT | Direction::BOTTOM_RIGHT | Direction::BOTTOM_LEFT | Direction::TOP_LEFT ) ) + penalty = penalty * 3 / 2; return penalty; }
codereview_cpp_data_1266
ASSERT_TRUE(account_asset); ASSERT_EQ((*account_asset)->accountId(), account); ASSERT_EQ((*account_asset)->assetId(), asset); - ASSERT_EQ((*account_asset)->balance().toString(), amount.toString()); } /** ```suggestion ASSERT_EQ((*account_asset)->balance(), amount); ``` ASSERT_TRUE(account_asset); ASSERT_EQ((*account_asset)->accountId(), account); ASSERT_EQ((*account_asset)->assetId(), asset); + ASSERT_EQ((*account_asset)->balance(), amount); } /**
codereview_cpp_data_1279
emit muteDeafStateChanged(); } -void ClientUser::setLocalVolume(float volume) { - fLocalVolume = volume; - emit muteDeafStateChanged(); -} - void ClientUser::setDeaf(bool deaf) { bDeaf = deaf; if (bDeaf) Why do you need this? If this is not needed, I think you should just simply assign to fLocalVolume like I do in my change. emit muteDeafStateChanged(); } void ClientUser::setDeaf(bool deaf) { bDeaf = deaf; if (bDeaf)
codereview_cpp_data_1282
int max = security_policy->signature_preferences->signature_schemes[i]->maximum_protocol_version; s2n_signature_algorithm sig_alg = security_policy->signature_preferences->signature_schemes[i]->sig_alg; - if (min >= S2N_TLS13 || max <= S2N_TLS13) { has_tls_13_sig_alg = 1; } Not sure how checking for `max <= S2N_TLS13` helps here, are we interested only in the minimum version? int max = security_policy->signature_preferences->signature_schemes[i]->maximum_protocol_version; s2n_signature_algorithm sig_alg = security_policy->signature_preferences->signature_schemes[i]->sig_alg; + if (min == S2N_TLS13 || max >= S2N_TLS13) { has_tls_13_sig_alg = 1; }
codereview_cpp_data_1283
EXPECT_SUCCESS(s2n_tls13_keys_init(&secrets, S2N_HMAC_SHA256)); - struct s2n_psk *psk = NULL; /* Derive Early Secrets */ - EXPECT_SUCCESS(s2n_tls13_derive_early_secrets(&secrets, psk)); S2N_BLOB_EXPECT_EQUAL(secrets.extract_secret, expected_early_secret); S2N_BLOB_EXPECT_EQUAL(secrets.derive_secret, expect_derived_handshake_secret); Might be cleaner as just `EXPECT_SUCCESS(s2n_tls13_derive_early_secrets(&secrets, NULL));` EXPECT_SUCCESS(s2n_tls13_keys_init(&secrets, S2N_HMAC_SHA256)); /* Derive Early Secrets */ + EXPECT_SUCCESS(s2n_tls13_derive_early_secrets(&secrets, NULL)); S2N_BLOB_EXPECT_EQUAL(secrets.extract_secret, expected_early_secret); S2N_BLOB_EXPECT_EQUAL(secrets.derive_secret, expect_derived_handshake_secret);
codereview_cpp_data_1289
nmax = 0; rho = NULL; fp = NULL; - count_embed = NULL; map = NULL; type2frho = NULL; looks good - except let's call this numforce[], similar to numneigh[], since it is the number of atoms within the force cutoff nmax = 0; rho = NULL; fp = NULL; + numforce = NULL; map = NULL; type2frho = NULL;
codereview_cpp_data_1290
}; } __attribute__((aligned(4))); __device__ unsigned int __byte_perm(unsigned int x, unsigned int y, unsigned int s) { struct uchar2Holder cHoldVal; struct ucharHolder cHoldKey; This struct is used by ```__byte_perm``` device function. So we cannot remove it. }; } __attribute__((aligned(4))); +struct uchar2Holder { + union { + unsigned int ui[2]; + unsigned char c[8]; + }; +} __attribute__((aligned(8))); + __device__ unsigned int __byte_perm(unsigned int x, unsigned int y, unsigned int s) { struct uchar2Holder cHoldVal; struct ucharHolder cHoldKey;
codereview_cpp_data_1297
RedistributeArmy( selectedTroop, destTroop, _army ); return true; } - else if ( destTroop.isValid() ) { Army::SwapTroops( selectedTroop, destTroop ); return true; } :warning: **readability\-else\-after\-return** :warning: do not use `` else `` after `` return `` ```suggestion if ( destTroop.isValid() ) { Army::SwapTroops( selectedTroop, destTroop ); return true; } ``` RedistributeArmy( selectedTroop, destTroop, _army ); return true; } + + if ( destTroop.isValid() ) { Army::SwapTroops( selectedTroop, destTroop ); return true; }
codereview_cpp_data_1307
} else if (lhs.attr == system::type_atom::value) { result_type result; for (auto& [part_id, part_syn] : partition_synopses_) - for (auto& pair : part_syn) { - VAST_INFO(this, "checking", pair.first.name()); if (evaluate(pair.first.name(), x.op, d)) { result.push_back(part_id); break; } - } return result; } VAST_WARNING(this, "cannot process attribute extractor:", lhs.attr); Debugging output (and braces). } else if (lhs.attr == system::type_atom::value) { result_type result; for (auto& [part_id, part_syn] : partition_synopses_) + for (auto& pair : part_syn) if (evaluate(pair.first.name(), x.op, d)) { result.push_back(part_id); break; } return result; } VAST_WARNING(this, "cannot process attribute extractor:", lhs.attr);
codereview_cpp_data_1313
for (int i = 0; i < user_data_entries.size(); ++i) { const std::string key = user_data_entries.getKeyAtIndex(i).m_string1; const std::string* value = user_data_entries.getAtIndex(i); - addUserData(bodyUniqueId, linkIndex, visualShapeIndex, key.c_str(), value->c_str(), - value->size()+1, USER_DATA_VALUE_TYPE_STRING); } } best to add a check if value is valid, to avoid crash when using the pointer. for (int i = 0; i < user_data_entries.size(); ++i) { const std::string key = user_data_entries.getKeyAtIndex(i).m_string1; const std::string* value = user_data_entries.getAtIndex(i); + if (value) { + addUserData(bodyUniqueId, linkIndex, visualShapeIndex, key.c_str(), value->c_str(), + value->size()+1, USER_DATA_VALUE_TYPE_STRING); + } } }
codereview_cpp_data_1316
zero_vert_normal_bulk = zero_vert_normal_bulk_SSE; #endif } - else if(Platform::SystemInfo.processor.properties & CPU_PROP_ALTIVEC) - { - #if defined(TORQUE_CPU_PPC) - zero_vert_normal_bulk = zero_vert_normal_bulk_gccvec; - #endif - } } MODULE_END; can get rid of PPC as well. Torque doesn't support powerpc architecture / altivec zero_vert_normal_bulk = zero_vert_normal_bulk_SSE; #endif } } MODULE_END;
codereview_cpp_data_1325
int ret; if (is_encrypt) { - /* encrypt given data, witch the QUIC tag appended if necessary */ uint8_t srcbuf[src.len + sizeof(self->quic_tag)]; if (self->is_quic) { memcpy(srcbuf, src.base, src.len); This line has no effect? Did you mean `memcpy`? int ret; if (is_encrypt) { + /* encrypt given data, with the QUIC tag appended if necessary */ uint8_t srcbuf[src.len + sizeof(self->quic_tag)]; if (self->is_quic) { memcpy(srcbuf, src.base, src.len);
codereview_cpp_data_1330
void Rpc::checkRequest(int _groupID) { - auto _nodeList = service()->getNodeListByGroupID(_groupID); - if (_nodeList.size() == 0) { BOOST_THROW_EXCEPTION( JsonRpcException(RPCExceptionType::GroupID, RPCMsg[RPCExceptionType::GroupID])); } auto it = std::find(_nodeList.begin(), _nodeList.end(), service()->id()); if (it == _nodeList.end()) { getNodeListByGroupID for every coming request is cost too heavy, do you think about using cache ? void Rpc::checkRequest(int _groupID) { + auto blockchain = ledgerManager()->blockChain(_groupID); + if (!blockchain) { BOOST_THROW_EXCEPTION( JsonRpcException(RPCExceptionType::GroupID, RPCMsg[RPCExceptionType::GroupID])); } + auto _nodeList = blockchain->minerList() + blockchain->observerList(); auto it = std::find(_nodeList.begin(), _nodeList.end(), service()->id()); if (it == _nodeList.end()) {
codereview_cpp_data_1333
const char* localname = ptr; ptr += localnamelen; - bool syncable = true; if (hasExtensionBytes) { - syncable = MemAccess::get<bool>(ptr); - ptr += sizeof(syncable); for (int i = 7; i--;) { this function would benefit a lot from using CacheableReader/CacheableWriter too const char* localname = ptr; ptr += localnamelen; + int8_t syncableInt = 1; if (hasExtensionBytes) { + syncableInt = MemAccess::get<int8_t>(ptr); + ptr += 1; for (int i = 7; i--;) {
codereview_cpp_data_1339
for (size_t i = 0; i < num_partitions; ++i) { auto name = i % 2 == 0 ? "foo"s : "foobar"s; auto& part = mock_partitions.emplace_back(std::move(name), ids[i], i); - auto ps = make_partition_synopsis(part.slice, {}); meta_idx.merge(part.id, std::move(ps)); } MESSAGE("verify generated timestamps"); You can also remove the second argument, this is a helper function just for this unit test. for (size_t i = 0; i < num_partitions; ++i) { auto name = i % 2 == 0 ? "foo"s : "foobar"s; auto& part = mock_partitions.emplace_back(std::move(name), ids[i], i); + auto ps = make_partition_synopsis(part.slice); meta_idx.merge(part.id, std::move(ps)); } MESSAGE("verify generated timestamps");
codereview_cpp_data_1343
b->yy_bs_column = 0; } - b->yy_is_interactive = file ? (isatty( _fileno(file) ) > 0) : 0; - errno = oerrno; } I assume you're getting a warning only in Visual Studio about this as _fileno() doesn't exist anywhere else except in VC++'s headers. This change isn't acceptable. Define `_CRT_SECURE_NO_WARNINGS` in your compiler's preprocessor settings to disable that non-sense. b->yy_bs_column = 0; } +#ifdef _MSC_VER + const int fe = _fileno( file ); +#else + const int fe = fileno( file ); +#endif + b->yy_is_interactive = file ? (isatty( fe ) > 0) : 0; + errno = oerrno; }