id
stringlengths
21
25
content
stringlengths
164
2.33k
codereview_cpp_data_5871
ModelCalibrator::ModelCalibrator() { constructProperties(); } Could we return the angularDifference from OpenSenseUtilities::computeHeadingCorrection and make a get() method from the model calibrator? When debugging the orientations, it is helpful to know what the angular difference is but it is printed to the console above all of the imu frame orientations so you have to scroll up and try and find it. It would be nice if the value could be gettable (.getAngluarDifference() ) or printable (.printAngluarDifferenceToConsol() ). ModelCalibrator::ModelCalibrator() { constructProperties(); + _calibrated = false; }
codereview_cpp_data_5877
shared_model::crypto::Hash(model_hash)); // if load is successful if (block) { - subscriber.on_next(*block); // update the cache with block consensus voted for consensus_result_cache_->insert( std::make_shared<ConsensusResult>(*block)); } subscriber.on_completed(); }); This may throw, so it is better to put it before on_next call shared_model::crypto::Hash(model_hash)); // if load is successful if (block) { // update the cache with block consensus voted for consensus_result_cache_->insert( std::make_shared<ConsensusResult>(*block)); + subscriber.on_next(*block); } subscriber.on_completed(); });
codereview_cpp_data_5885
int Dialog::ArmySplitTroop( const uint32_t freeSlots, const uint32_t redistributeMax, const bool savelastTroop, uint32_t & redistributeCount, bool & useFastSplit ) { fheroes2::Display & display = fheroes2::Display::instance(); // cursor Could we please check add an assert to check that the number of freeSlots is always bigger than 0 otherwise the code below will stuck forever: `freeSlots - 1`? int Dialog::ArmySplitTroop( const uint32_t freeSlots, const uint32_t redistributeMax, const bool savelastTroop, uint32_t & redistributeCount, bool & useFastSplit ) { + assert( freeSlots > 0 ); + fheroes2::Display & display = fheroes2::Display::instance(); // cursor
codereview_cpp_data_5899
} else g_print ("State: idle\n"); - g_print ("\n"); if (booted_deployment) g_assert (g_variant_lookup (booted_deployment, "id", "&s", &booted_id)); This is an interesting idea, and I like it. A `Deployments:` header might be nice as well to make the overall output more cohesive, e.g.: ``` State: idle Deployments: fedora-atomic:fedora-atomic/f23/x86_64/docker-host Version: 23.137 (2016-06-14 21:40:52) Commit: 0e686e114410cbc7e04713970c417338efc0d657779b428bff23ad571bfbc927 OSName: fedora-atomic GPGSignature: (unsigned) * fedora-atomic:fedora-atomic/f23/x86_64/docker-host Version: 23.131 (2016-06-07 01:00:21) Commit: aadcfe51acd85e8cf2554b6a3c952d8335a934d219bbb537fec10ce0fde7dc06 OSName: fedora-atomic GPGSignature: (unsigned) Unlocked: development ``` WDYT? } else g_print ("State: idle\n"); + g_print ("Deployments:\n"); if (booted_deployment) g_assert (g_variant_lookup (booted_deployment, "id", "&s", &booted_id));
codereview_cpp_data_5903
static int cache_mode = 1; -static int json_input = 0; -static int jx_input = 0; -static char *jx_context = NULL; - static container_mode_t container_mode = CONTAINER_MODE_NONE; static char *container_image = NULL; static char *container_image_tar = NULL; If these variables are only used in main function, move these to the beginning of that function. If there is a foreseeable reason to have them as global statics just let me know. static int cache_mode = 1; static container_mode_t container_mode = CONTAINER_MODE_NONE; static char *container_image = NULL; static char *container_image_tar = NULL;
codereview_cpp_data_5905
account.account_id = "b@domain"; auto creator = "a@domain"; - EXPECT_CALL(*storage, getWsvQuery()).WillRepeatedly(Return(wsv_query)); - EXPECT_CALL(*storage, getBlockQuery()).WillRepeatedly(Return(block_query)); // TODO: refactor this to use stateful validation mocks EXPECT_CALL( *wsv_query, Same as before, since there are no tests that return `nullptr` for `WsvQuery` or `BlockQuery`, this can be moved to `SetUp`. account.account_id = "b@domain"; auto creator = "a@domain"; // TODO: refactor this to use stateful validation mocks EXPECT_CALL( *wsv_query,
codereview_cpp_data_5937
std::chrono::milliseconds delay_milliseconds, std::shared_ptr<ametsuchi::OSPersistentStateFactory> persistent_state, - std::shared_ptr<ametsuchi::BlockQueryFactory> block_query_factory) { auto query = peer_query_factory->createPeerQuery(); - if (not query) { log_->error("Cannot get the peer query"); } auto ledger_peers = query.get()->getLedgerPeers(); Isn't it potential exception on dereferencing empty optional, if you could not create `query`? std::chrono::milliseconds delay_milliseconds, std::shared_ptr<ametsuchi::OSPersistentStateFactory> persistent_state, + std::shared_ptr<ametsuchi::BlockQueryFactory> block_query_factory, + std::shared_ptr<network::AsyncGrpcClient<google::protobuf::Empty>> + async_call) { auto query = peer_query_factory->createPeerQuery(); + if (not query or not query.get()) { log_->error("Cannot get the peer query"); } auto ledger_peers = query.get()->getLedgerPeers();
codereview_cpp_data_5941
}); Real* hp = da.copyToHost(); ParallelDescriptor::ReduceRealSum(hp[0]); - amrex::Print().SetPrecision(17) << "1-nrom: " << hp[0] << "\n"; } { ```suggestion amrex::Print().SetPrecision(17) << "1-norm: " << hp[0] << "\n"; ``` }); Real* hp = da.copyToHost(); ParallelDescriptor::ReduceRealSum(hp[0]); + amrex::Print().SetPrecision(17) << "1-norm: " << hp[0] << "\n"; } {
codereview_cpp_data_5958
/* GT: English (possibly translating it in parentheses). I believe there */ /* GT: are legal reasons for this. */ /* GT: So "Añadir SIL Open Font License (licencia de fuentes libres)" */ - tnlabel[5].text = (unichar_t *) S_("Automatically add OFL licensing"); tnlabel[5].image_precedes = false; tnlabel[5].image = &OFL_logo; tnlabel[5].text_is_1byte = true; I guess the full text was "Add SIL OFL", represented by the "Add SIL" string followed by the OFL logo &ndash; this was significantly more concise imo. Most importantly the word "Automatically" does not seem to serve any purpose here: if there is a button to add it it seems obvious that it's to be done for you. /* GT: English (possibly translating it in parentheses). I believe there */ /* GT: are legal reasons for this. */ /* GT: So "Añadir SIL Open Font License (licencia de fuentes libres)" */ + tnlabel[5].text = (unichar_t *) S_("Add OFL"); tnlabel[5].image_precedes = false; tnlabel[5].image = &OFL_logo; tnlabel[5].text_is_1byte = true;
codereview_cpp_data_5964
// This class may be shared amongst many megaclients, so thread safety is needed typedef map<string, m_time_t> Map; Map recentFails; - std::mutex m; string server(const string& url) { Can we rename `m` to something sensible? // This class may be shared amongst many megaclients, so thread safety is needed typedef map<string, m_time_t> Map; Map recentFails; + std::mutex m_mutex; string server(const string& url) {
codereview_cpp_data_5968
} using receiver_type = caf::typed_actor< caf::reacts_to<table_slice_ptr>>; - auto dst = caf::actor_cast<receiver_type>(self->current_sender()); auto session = self->state.store->extract(xs); while (true) { auto slice = session->next(); I find `dst` for "destination" a bit generic. How about calling this variable `client` or `requester` for added semantics? } using receiver_type = caf::typed_actor< caf::reacts_to<table_slice_ptr>>; + auto requester = caf::actor_cast<receiver_type>( + self->current_sender()); auto session = self->state.store->extract(xs); while (true) { auto slice = session->next();
codereview_cpp_data_5971
} } template<typename Dtype> void DataTransformer<Dtype>::Transform(const vector<cv::Mat> & mat_vector, Blob<Dtype>* transformed_blob) { This code should be surrounded by `#ifndef OSX` } } +#ifndef OSX template<typename Dtype> void DataTransformer<Dtype>::Transform(const vector<cv::Mat> & mat_vector, Blob<Dtype>* transformed_blob) {
codereview_cpp_data_5973
if (auto res = mkdir(abs_dir); !res) return make_error(ec::filesystem_error, "unable to create db-directory:", abs_dir.str()); - if (::access(abs_dir.str().c_str(), W_OK) != 0) return make_error(ec::filesystem_error, "unable to write to db-directory:", abs_dir.str()); VAST_DEBUG_ANON(__func__, "spawns local node:", id); It might make sense to bundle the fs-specific functions in the existing `filesystem.hpp`, and e.g. add a `path::is_writable()` or `vast::writable()` function. if (auto res = mkdir(abs_dir); !res) return make_error(ec::filesystem_error, "unable to create db-directory:", abs_dir.str()); + if (!abs_dir.is_writable()) return make_error(ec::filesystem_error, "unable to write to db-directory:", abs_dir.str()); VAST_DEBUG_ANON(__func__, "spawns local node:", id);
codereview_cpp_data_5983
<< LOG_KV("nodeID", nodeID.substr(0, 4)); return false; } if (!preverified) { return false; this is unnecessary, what about delete it? << LOG_KV("nodeID", nodeID.substr(0, 4)); return false; } + /// return early when the certificate is invalid if (!preverified) { return false;
codereview_cpp_data_5990
{ GVariantDict dict; g_variant_dict_init (&dict, NULL); /* let's take care of install_pkgs first since it can fail */ if (install_pkgs) { g_autoptr(GPtrArray) repo_pkgs = NULL; g_autoptr(GVariant) fd_idxs = NULL; - /* NB: after this, it's a guaranteed TRUE, so we - * just pass the out_ var directly here */ - if (!rpmostree_sort_pkgs_strv (install_pkgs, &repo_pkgs, out_fd_list, &fd_idxs, error)) return FALSE; I'm OK with this, but it is a code refactoring hazard. { GVariantDict dict; g_variant_dict_init (&dict, NULL); + glnx_unref_object GUnixFDList *fd_list = NULL; /* let's take care of install_pkgs first since it can fail */ if (install_pkgs) { g_autoptr(GPtrArray) repo_pkgs = NULL; g_autoptr(GVariant) fd_idxs = NULL; + if (!rpmostree_sort_pkgs_strv (install_pkgs, &repo_pkgs, &fd_list, &fd_idxs, error)) return FALSE;
codereview_cpp_data_5992
EXPECT_NOT_NULL(client_config = s2n_config_new()); EXPECT_NOT_NULL(client_conn = s2n_connection_new(S2N_CLIENT)); - //EXPECT_SUCCESS(s2n_config_set_cipher_preferences(client_config, "test_all")); EXPECT_SUCCESS(s2n_connection_set_config(client_conn, client_config)); /* The client will request TLS1.3 */ Delete this line EXPECT_NOT_NULL(client_config = s2n_config_new()); EXPECT_NOT_NULL(client_conn = s2n_connection_new(S2N_CLIENT)); EXPECT_SUCCESS(s2n_connection_set_config(client_conn, client_config)); /* The client will request TLS1.3 */
codereview_cpp_data_6001
/** * @brief Function with test cases for Horspool's algorithm */ static void test(){ assert(strings::horspool::horspool("Hello World","World") == true); ```suggestion * @brief Function with test cases for Horspool's algorithm * @returns void ``` /** * @brief Function with test cases for Horspool's algorithm + * @returns void */ static void test(){ assert(strings::horspool::horspool("Hello World","World") == true);
codereview_cpp_data_6011
blacklist ${PATH}/ssh blacklist /usr/lib/openssh blacklist /usr/lib/ssh -blacklist /usr/libexec/openssh/ssh-keysign blacklist ${PATH}/passwd blacklist /usr/lib/xorg/Xorg.wrap blacklist /usr/lib/policykit-1/polkit-agent-helper-1 `/usr/lib/openssh/ssh-keysign` is the path in Debian. Please keep it. :-) blacklist ${PATH}/ssh blacklist /usr/lib/openssh blacklist /usr/lib/ssh +blacklist /usr/libexec/openssh blacklist ${PATH}/passwd blacklist /usr/lib/xorg/Xorg.wrap blacklist /usr/lib/policykit-1/polkit-agent-helper-1
codereview_cpp_data_6018
if (items > 5) { unk20 = (uint32) SvUV(ST(5)); } if (items > 6) { perm_effect = (bool) SvTRUE(ST(6)); } if (items > 7) { - if (sv_derived_from(ST(3), "Client")) { IV tmp = SvIV((SV *)SvRV(ST(7))); client = INT2PTR(Client *, tmp); } Why is this 3 here? if (items > 5) { unk20 = (uint32) SvUV(ST(5)); } if (items > 6) { perm_effect = (bool) SvTRUE(ST(6)); } if (items > 7) { + if (sv_derived_from(ST(7), "Client")) { IV tmp = SvIV((SV *)SvRV(ST(7))); client = INT2PTR(Client *, tmp); }
codereview_cpp_data_6023
max_proposal_size_(max_proposal_size), proposal_delay_(proposal_delay), vote_delay_(vote_delay), - is_mst_supported_(opt_mst_gossip_params), - opt_mst_gossip_params_(opt_mst_gossip_params), keypair(keypair) { log_ = logger::log("IROHAD"); log_->info("created"); Is that field is still required? max_proposal_size_(max_proposal_size), proposal_delay_(proposal_delay), vote_delay_(vote_delay), + is_mst_supported_(is_mst_supported), + mst_gossip_emitting_period_( + mst_gossip_emitting_period.value_or(kDefGossipEmittingPeriod)), + mst_gossip_amount_per_once_( + mst_gossip_amount_per_once.value_or(kDefGossipAmountPerOnce)), keypair(keypair) { log_ = logger::log("IROHAD"); log_->info("created");
codereview_cpp_data_6060
if ( hero ) { Interface::RedrawHeroesIcon( *hero, dstx + 82, dsty + 19 ); - char skillValues[64]; - sprintf( skillValues, "%d-%d-%d-%d", hero->GetAttack(), hero->GetDefense(), hero->GetPower(), hero->GetKnowledge() ); - text.Set( skillValues ); text.Blit( dstx + 104 - text.w() / 2, dsty + 43 ); } else { This is incorrect way of populating a string. Please do not use `sprintf` for such purposes but a normal string concatenation. if ( hero ) { Interface::RedrawHeroesIcon( *hero, dstx + 82, dsty + 19 ); + text.Set( GetString( hero->GetAttack() ) + sep + GetString( hero->GetDefense() ) + sep + GetString( hero->GetPower() ) + sep + GetString( hero->GetKnowledge() ) ); text.Blit( dstx + 104 - text.w() / 2, dsty + 43 ); } else {
codereview_cpp_data_6066
fastrtps::rtps::RTPSWriter* /*writer*/, const fastrtps::LivelinessLostStatus& status) { - fastdds::dds::LivelinessLostStatus dds_status; - dds_status.total_count = status.total_count; - dds_status.total_count_change = status.total_count_change; if (data_writer_->listener_ != nullptr) { - data_writer_->listener_->on_liveliness_lost(data_writer_->user_datawriter_, dds_status); } - data_writer_->publisher_->publisher_listener_.on_liveliness_lost(data_writer_->user_datawriter_, dds_status); } bool DataWriterImpl::wait_for_acknowledgments( `fastrtps::LivelinessLostStatus` should be another alias for `fasdds::dds::LivelinessLostStatus`, and thus, we can avoid the copy and code duplication. fastrtps::rtps::RTPSWriter* /*writer*/, const fastrtps::LivelinessLostStatus& status) { if (data_writer_->listener_ != nullptr) { + data_writer_->listener_->on_liveliness_lost(data_writer_->user_datawriter_, status); } + data_writer_->publisher_->publisher_listener_.on_liveliness_lost(data_writer_->user_datawriter_, status); } bool DataWriterImpl::wait_for_acknowledgments(
codereview_cpp_data_6070
{ struct s2n_hash_state signature_hash; struct s2n_stuffer *in = &conn->handshake.io; - struct s2n_blob serverECDHparams, signature; uint16_t signature_length; - /* Read server ECDH params */ - GUARD(s2n_ecc_read_ecc_params(&conn->pending.server_ecc_params, in, &serverECDHparams)); if (conn->actual_protocol_version == S2N_TLS12) { uint8_t hash_algorithm; I think we have definitions for the signature and hash algorithm here already, in s2n_tls_parameters.h { struct s2n_hash_state signature_hash; struct s2n_stuffer *in = &conn->handshake.io; + struct s2n_blob signature; uint16_t signature_length; + GUARD(s2n_hash_init(&signature_hash, conn->pending.signature_digest_alg)); + + /* Read server ECDH params and calculate their hash */ + GUARD(s2n_ecc_read_ecc_params(&conn->pending.server_ecc_params, in, &signature_hash)); if (conn->actual_protocol_version == S2N_TLS12) { uint8_t hash_algorithm;
codereview_cpp_data_6080
Query("DELETE FROM " + GetTablePrefix() + table + " WHERE session_token <> " + Convert::ToString(m_SessionToken)); } -void IdoMysqlConnection::ClearConfiglTable(const String& table) { Query("DELETE FROM " + GetTablePrefix() + table + " WHERE instance_id = " + Convert::ToString(static_cast<long>(m_InstanceID))); } This seems odd, intended change? Query("DELETE FROM " + GetTablePrefix() + table + " WHERE session_token <> " + Convert::ToString(m_SessionToken)); } +void IdoMysqlConnection::ClearConfigTable(const String& table) { Query("DELETE FROM " + GetTablePrefix() + table + " WHERE instance_id = " + Convert::ToString(static_cast<long>(m_InstanceID))); }
codereview_cpp_data_6083
sm2Group = EC_GROUP_new_by_curve_name(NID_sm2); if (!sm2Group) { - CRYPTO_LOG(ERROR) << "[#CRYPTO::SM2::genKey] Error Of Gain SM2 Group Object"; - ERROR_OUTPUT << "[#CRYPTO::SM2::genKey] Error Of Gain SM2 Group Object" << std::endl; goto err; } CRYPTO_LOG(ERROR) << "[genKey] Error Of Gain SM2 Group Object"; maybe better without "#". sm2Group = EC_GROUP_new_by_curve_name(NID_sm2); if (!sm2Group) { + CRYPTO_LOG(ERROR) << "[SM2::genKey] Error Of Gain SM2 Group Object"; + ERROR_OUTPUT << "[SM2::genKey] Error Of Gain SM2 Group Object" << std::endl; goto err; }
codereview_cpp_data_6087
// fail the tx auto cmd_name = "CommandName"; size_t cmd_index = 2; - uint32_t error_code = 2; auto verified_proposal = std::make_shared<shared_model::proto::Proposal>( TestProposalBuilder().height(0).createdTime(iroha::time::now()).build()); verified_prop_notifier.get_subscriber().on_next( Set please that value different from the `cmd_index` one Test is a bit more precise in that case // fail the tx auto cmd_name = "CommandName"; size_t cmd_index = 2; + uint32_t error_code = 3; auto verified_proposal = std::make_shared<shared_model::proto::Proposal>( TestProposalBuilder().height(0).createdTime(iroha::time::now()).build()); verified_prop_notifier.get_subscriber().on_next(
codereview_cpp_data_6089
wl_container_of(listener, roots_xdg_surface, commit); struct roots_view *view = roots_xdg_surface->view; - bool centered = view_center(view); - if (centered) { - wl_list_remove(&listener->link); } } Why remove the link if the view is off-screen? Also, won't this center it every time the view configures itself? Like when it's resizing? wl_container_of(listener, roots_xdg_surface, commit); struct roots_view *view = roots_xdg_surface->view; + if (!roots_xdg_surface->initialized) { + bool centered = view_center(view); + if (centered) { + roots_xdg_surface->initialized = true; + } } }
codereview_cpp_data_6091
EXPECT_SUCCESS(s2n_config_free(client_config)); } - /* Stop here if RSA PSS signing is unsupported */ - if (!s2n_is_rsa_pss_supported()) { - END_TEST(); - } - /* Test: RSA cert with RSA PSS signatures */ { const struct s2n_signature_scheme* const rsa_pss_rsae_sig_schemes[] = { /* RSA PSS */ Since each of these checks applies to one test, can we wrap the individual tests in these "is_supported" checks instead, rather than calling "END_TEST" at multiple places in the file? We're already wrapping them in { } :) EXPECT_SUCCESS(s2n_config_free(client_config)); } /* Test: RSA cert with RSA PSS signatures */ + if (s2n_is_rsa_pss_signing_supported()) { const struct s2n_signature_scheme* const rsa_pss_rsae_sig_schemes[] = { /* RSA PSS */
codereview_cpp_data_6094
#include <iostream> #include <string> -#include "./priority_queue.h" /** * @brief Main function This shall fix `clang-tidy` warning. ```suggestion #include "./priority_queue.hpp" ``` #include <iostream> #include <string> +#include "./priority_queue.hpp" /** * @brief Main function
codereview_cpp_data_6099
EXPECT_EQ(pool_backup_a1.use_count(), 1); EXPECT_EQ(pool_backup_a3.use_count(), 1); EXPECT_EQ(pool_backup_b1.use_count(), 1); } If we check for the reference counting, we are considering that releasing the last reference of a pool also releases all resources assigned to that pool. I'm OK with that, but in that case I would also like to test that getting pools for the same topic and config again will provide new objects, not old copies. Something like: ``` auto pool_a1 = TopicPayloadPoolRegistry::get("topic_a", cfg); EXPECT_NE(pool_backup_a1, pool_a1); ``` EXPECT_EQ(pool_backup_a1.use_count(), 1); EXPECT_EQ(pool_backup_a3.use_count(), 1); EXPECT_EQ(pool_backup_b1.use_count(), 1); + + // Repeat allocations and check a different pointer is returned + cfg.memory_policy = PREALLOCATED_MEMORY_MODE; + pool_a1 = TopicPayloadPoolRegistry::get("topic_a", cfg); + EXPECT_NE(pool_a1, pool_backup_a1); + pool_b1 = TopicPayloadPoolRegistry::get("topic_b", cfg); + EXPECT_NE(pool_b1, pool_backup_b1); + cfg.memory_policy = DYNAMIC_RESERVE_MEMORY_MODE; + pool_a3 = TopicPayloadPoolRegistry::get("topic_a", cfg); + EXPECT_NE(pool_a3, pool_backup_a3); }
codereview_cpp_data_6102
common_objects_factory_ = std::make_shared<shared_model::proto::ProtoCommonObjectsFactory< shared_model::validation::FieldValidator>>(); - auto perm_converter_ = std::make_shared<shared_model::proto::ProtoPermissionToString>(); auto block_converter = std::make_shared<shared_model::proto::ProtoBlockJsonConverter>(); Underscore should be removed in variable's name common_objects_factory_ = std::make_shared<shared_model::proto::ProtoCommonObjectsFactory< shared_model::validation::FieldValidator>>(); + auto perm_converter = std::make_shared<shared_model::proto::ProtoPermissionToString>(); auto block_converter = std::make_shared<shared_model::proto::ProtoBlockJsonConverter>();
codereview_cpp_data_6113
msg->hdr.dwTime = GetTickCount() + 500; msg->hdr.bLen = bLen; memcpy(msg->body, pbMsg, bLen); - for (tail = &sgpTimedMsgHead; *tail; tail = &(*tail)->hdr.pNext) ; *tail = msg; } this looks odd msg->hdr.dwTime = GetTickCount() + 500; msg->hdr.bLen = bLen; memcpy(msg->body, pbMsg, bLen); + for (tail = &sgpTimedMsgHead; *tail; tail = &(*tail)->hdr.pNext) { ; + } *tail = msg; }
codereview_cpp_data_6138
{ logWarning(RTPS_MSG_IN, IDSTRING "Problem copying CacheChange, received data is: " << change->serializedPayload.length << " bytes and max size in reader " - << m_guid << " is " << fixed_payload_size_); change_pool_->release_cache(change_to_add); return false; } Seeing that the max size is '0' may freak a customer ```suggestion logWarning(RTPS_MSG_IN, IDSTRING "Problem copying CacheChange, received data is: " << change->serializedPayload.length << " bytes and max size in reader " << m_guid << " is " << (fixed_payload_size_ > 0 ? fixed_payload_size_ : std::numeric_limits<uint32_t>::max()); ``` { logWarning(RTPS_MSG_IN, IDSTRING "Problem copying CacheChange, received data is: " << change->serializedPayload.length << " bytes and max size in reader " + << m_guid << " is " + << (fixed_payload_size_ > 0) ? fixed_payload_size_ : std::numeric_limits<uint32_t>::max()); change_pool_->release_cache(change_to_add); return false; }
codereview_cpp_data_6141
goto Exit; } - /* calls H2O.after_generate_handler hook */ - mrb_funcall_argv(mrb, h2o_mruby_eval_expr(mrb, "H2O"), mrb_intern_lit(mrb, "after_generate_handler"), 1, &result); if (mrb->exc != NULL) { mrb_value obj = mrb_funcall(mrb, mrb_obj_value(mrb->exc), "inspect", 0); struct RString *error = mrb_str_ptr(obj); generalize validation as `after_generate_handler` hook, and it came to do finalization too goto Exit; } + /* call post_handler_generation hooks */ + mrb_funcall_argv(mrb, h2o_mruby_eval_expr(mrb, "H2O::ConfigurationContext.instance"), mrb_intern_lit(mrb, "post_handler_generation"), 1, &result); if (mrb->exc != NULL) { mrb_value obj = mrb_funcall(mrb, mrb_obj_value(mrb->exc), "inspect", 0); struct RString *error = mrb_str_ptr(obj);
codereview_cpp_data_6143
} else { #ifdef HELLFIRE if (2 * curlv < AllItemsList[i].iMinMLvl) - okflag = FALSE; #else if (2 * currlevel < AllItemsList[i].iMinMLvl) - okflag = FALSE; #endif } if (AllItemsList[i].itype == ITYPE_MISC) okflag = FALSE; The other `ifdef` in this function only contain the the if-statment and not the body } else { #ifdef HELLFIRE if (2 * curlv < AllItemsList[i].iMinMLvl) #else if (2 * currlevel < AllItemsList[i].iMinMLvl) #endif + okflag = FALSE; } if (AllItemsList[i].itype == ITYPE_MISC) okflag = FALSE;
codereview_cpp_data_6152
} else { flb_warn("[in_syslog] error parsing log message " - "(input_plugin_alias_name='%s' parser_name='%s')", - ctx->i_ins->alias, ctx->parser->name); - flb_debug("[in_syslog] unparsed log message: %s", out_buf); return -1; } same feedback as above. } else { flb_warn("[in_syslog] error parsing log message " + "on \"%s\" with parser '%s')", + flb_input_name(ctx->i_ins), ctx->parser->name); + flb_debug("[in_syslog] unparsed log message: %.*s", size, buf); return -1; }
codereview_cpp_data_6156
peer_socket_ctx = (struct s2n_socket_read_io_context *)(void *)ctx_mem.data; peer_socket_ctx->fd = rfd; - s2n_connection_set_recv_cb(conn, s2n_socket_read); POSIX_GUARD(s2n_connection_set_recv_ctx(conn, peer_socket_ctx)); - conn->managed_recv_io = 1; /* This is only needed if the user is using corked io. * Take the snapshot in case optimized io is enabled after setting the fd. These calls to set the callback should also probably be guarded! Let's fix that peer_socket_ctx = (struct s2n_socket_read_io_context *)(void *)ctx_mem.data; peer_socket_ctx->fd = rfd; + POSIX_GUARD(s2n_connection_set_recv_cb(conn, s2n_socket_read)); POSIX_GUARD(s2n_connection_set_recv_ctx(conn, peer_socket_ctx)); + conn->managed_recv_io = true; /* This is only needed if the user is using corked io. * Take the snapshot in case optimized io is enabled after setting the fd.
codereview_cpp_data_6163
FD_SET(this->sock, &write_fd); tv.tv_sec = tv.tv_usec = 0; // don't block at all. - -#ifndef __EMSCRIPTEN__ - int nfds = FD_SETSIZE; -#else /* !__EMSCRIPTEN__ */ - /* Emscripten select supports only 64 nfds (Emscripten #1711) */ - int nfds = 64; -#endif /* __EMSCRIPTEN__ */ - if (select(nfds, &read_fd, &write_fd, nullptr, &tv) < 0) return false; this->writable = !!FD_ISSET(this->sock, &write_fd); return FD_ISSET(this->sock, &read_fd) != 0; again, if this is because EMSCRIPTEN doesn't define `FD_SETSIZE`, it should be set separately, instead of creating an extra variable FD_SET(this->sock, &write_fd); tv.tv_sec = tv.tv_usec = 0; // don't block at all. + if (select(FD_SETSIZE, &read_fd, &write_fd, nullptr, &tv) < 0) return false; this->writable = !!FD_ISSET(this->sock, &write_fd); return FD_ISSET(this->sock, &read_fd) != 0;
codereview_cpp_data_6169
{ union { - struct {unsigned char b,g,r,a;} _data; char _array[4]; }; }; Don't start identifiers with underscore, some of those are reserved for implementation only. { union { + struct {unsigned char b,g,r,a;} data; char _array[4]; }; };
codereview_cpp_data_6182
// hoot #include <hoot/core/TestUtils.h> #include <hoot/core/io/OsmApiWriter.h> #include <hoot/core/util/Log.h> // Qt Again all of the changes in this file are mine from another PR and need to be restored. // hoot #include <hoot/core/TestUtils.h> #include <hoot/core/io/OsmApiWriter.h> +#include <hoot/core/util/ConfigOptions.h> #include <hoot/core/util/Log.h> // Qt
codereview_cpp_data_6184
if (!ostree_sysroot_simple_write_deployment (self->sysroot, self->osname, new_deployment, self->merge_deployment, - 0, cancellable, error)) goto out; - /* regenerate the baselayer refs in case we just kicked out an ancient layered - * deployment whose base layer is not needed anymore */ - if (!generate_baselayer_refs (self, repo, cancellable, error)) - goto out; - if (!sysroot_upgrader_cleanup (self, repo, cancellable, error)) goto out; We do this already in `sysroot_upgrader_cleanup()` right? if (!ostree_sysroot_simple_write_deployment (self->sysroot, self->osname, new_deployment, self->merge_deployment, + OSTREE_SYSROOT_SIMPLE_WRITE_DEPLOYMENT_FLAGS_NO_CLEAN, cancellable, error)) goto out; if (!sysroot_upgrader_cleanup (self, repo, cancellable, error)) goto out;
codereview_cpp_data_6185
castles.resize( size, nullptr ); - for ( Castle * castle : castles ) { msg >> index; castle = ( index < 0 ? nullptr : world.getCastleEntrance( Maps::GetPoint( index ) ) ); assert( castle != nullptr ); We're assigning to a temporary variable instead of element of an array. castles.resize( size, nullptr ); + for ( Castle *& castle : castles ) { msg >> index; castle = ( index < 0 ? nullptr : world.getCastleEntrance( Maps::GetPoint( index ) ) ); assert( castle != nullptr );
codereview_cpp_data_6196
static RpmOstreeCommand override_subcommands[] = { { "replace", RPM_OSTREE_BUILTIN_FLAG_SUPPORTS_PKG_INSTALLS, - "Remove packages from the base layer", rpmostree_override_builtin_replace }, { "remove", RPM_OSTREE_BUILTIN_FLAG_SUPPORTS_PKG_INSTALLS, "Remove packages from the base layer", `"Replace packages in the base layer"` static RpmOstreeCommand override_subcommands[] = { { "replace", RPM_OSTREE_BUILTIN_FLAG_SUPPORTS_PKG_INSTALLS, + "Replace packages in the base layer", rpmostree_override_builtin_replace }, { "remove", RPM_OSTREE_BUILTIN_FLAG_SUPPORTS_PKG_INSTALLS, "Remove packages from the base layer",
codereview_cpp_data_6200
if (syncxfer && (!badfp.isvalid || !(badfp == fingerprint))) { badfp = fingerprint; chunkmacs.clear(); client->fsaccess->unlinklocal(&localfilename); - fa.reset(); return failed(API_EWRITE); } else Let's move this back to before `chunkmacs.clear()`? if (syncxfer && (!badfp.isvalid || !(badfp == fingerprint))) { badfp = fingerprint; + fa.reset(); chunkmacs.clear(); client->fsaccess->unlinklocal(&localfilename); return failed(API_EWRITE); } else
codereview_cpp_data_6207
//============================================================================= // EXCEPTIONS //============================================================================= -class CannotUsePhysicalOffsetFrame : public OpenSim::Exception { public: - CannotUsePhysicalOffsetFrame(const std::string& file, size_t line, const std::string& func, const Object& obj) : Seems ambiguous. Perhaps `PhysicalOffsetFrameIsInvalidArgument` or `InvalidArgumentToSimbodyEngine`? //============================================================================= // EXCEPTIONS //============================================================================= +class PhysicalOffsetFrameIsInvalidArgument : public OpenSim::Exception { public: + PhysicalOffsetFrameIsInvalidArgument(const std::string& file, size_t line, const std::string& func, const Object& obj) :
codereview_cpp_data_6211
void TxPool::verifyAndSetSenderForBlock(dev::eth::Block& block) { ReadGuard l(m_lock); - for (size_t i = 0; i < block.getTransactionSize(); i++) { /// force sender for the transaction auto p_tx = m_txsHash.find(block.transactions()[i].sha3()); Can not call getSize for every time coming the loop void TxPool::verifyAndSetSenderForBlock(dev::eth::Block& block) { + auto trans_num = block.getTransactionSize(); ReadGuard l(m_lock); + for (size_t i = 0; i < trans_num; i++) { /// force sender for the transaction auto p_tx = m_txsHash.find(block.transactions()[i].sha3());
codereview_cpp_data_6218
std::string responseUsed = getContactResponse(model1, model2); - // To be removed at v22.06 - std::map<std::string,std::string>::iterator it; - for(it=renamingResponseMethod.begin(); it!=renamingResponseMethod.end(); ++it) - { - if(responseUsed == it->first) - { - msg_warning() << "Options for data \"response\" changed since #2522: please use "<< it->second << " instead of " << it->first; - } - } - // We can create rules in order to not respond to specific collisions if (!responseUsed.compare("nullptr")) { ```suggestion const auto it = renamingResponseMethod.find(responseUsed); msg_warning_when(it != renamingResponseMethod.end()) << "Options for data \"response\" changed since #2522: please use "<< it->second << " instead of " << it->first; ``` std::string responseUsed = getContactResponse(model1, model2); // We can create rules in order to not respond to specific collisions if (!responseUsed.compare("nullptr")) {
codereview_cpp_data_6229
for(WriterProxyData* wdatait : (*pit)->m_writers) { bool valid = validMatching(&rdata, wdatait); - GUID_t reader_guid = R->getGuid(); - GUID_t writer_guid = wdatait->guid(); if(valid) { Use const ref to avoid copies. for(WriterProxyData* wdatait : (*pit)->m_writers) { bool valid = validMatching(&rdata, wdatait); + const GUID_t& reader_guid = R->getGuid(); + const GUID_t& writer_guid = wdatait->guid(); if(valid) {
codereview_cpp_data_6235
return S2N_SUCCESS; } -int client_hello_noop_cb(struct s2n_connection *conn, void *ctx) { return S2N_SUCCESS; } should probably make this static / add the s2n_ prefix return S2N_SUCCESS; } +int static s2n_client_hello_no_op_cb(struct s2n_connection *conn, void *ctx) { return S2N_SUCCESS; }
codereview_cpp_data_6236
int s2n_hmac_hash_alg(s2n_hmac_algorithm hmac_alg, s2n_hash_algorithm *out) { switch(hmac_alg) { case S2N_HMAC_NONE: *out = S2N_HASH_NONE; break; case S2N_HMAC_MD5: *out = S2N_HASH_MD5; break; as above on the out param int s2n_hmac_hash_alg(s2n_hmac_algorithm hmac_alg, s2n_hash_algorithm *out) { + notnull_check(out); switch(hmac_alg) { case S2N_HMAC_NONE: *out = S2N_HASH_NONE; break; case S2N_HMAC_MD5: *out = S2N_HASH_MD5; break;
codereview_cpp_data_6261
#include "../../utilities/idf/WorkspaceExtensibleGroup.hpp" -#include <utilities/idd/ZoneProperty_UserViewFactors_BySurfaceName_FieldEnums.hxx> #include "../../utilities/idd/IddEnums.hpp" #include <utilities/idd/IddEnums.hxx> This works on Windows, but it doesn't on Unix as case matters. Since E+ uses **by** and not **By** it has to be the correct casing here: ``` #include <utilities/idd/ZoneProperty_UserViewFactors_bySurfaceName_FieldEnums.hxx> ``` #include "../../utilities/idf/WorkspaceExtensibleGroup.hpp" +#include <utilities/idd/ZoneProperty_UserViewFactors_bySurfaceName_FieldEnums.hxx> #include "../../utilities/idd/IddEnums.hpp" #include <utilities/idd/IddEnums.hxx>
codereview_cpp_data_6274
<< " m_file_sizes.size(): " << m_file_sizes.size(); throw lbann_exception(err.str()); } - count += m_file_sizes[idx]; } } return count; Is this correct.. because m_num_img_srcs is 1? << " m_file_sizes.size(): " << m_file_sizes.size(); throw lbann_exception(err.str()); } + count += m_file_sizes[index]; } } return count;
codereview_cpp_data_6282
query.tx_hashes.end(), std::back_inserter(hashes), [](const auto &h) { return shared_model::crypto::Hash(h.to_string()); }); - auto txs = _blockQuery->getTransactions(hashes).map([](auto &tx) { - return boost::optional<model::Transaction>( - *std::unique_ptr<iroha::model::Transaction>((*tx)->makeOldModel())); - }); std::vector<iroha::model::Transaction> transactions; txs.subscribe([&transactions](auto const &tx_opt) { if (tx_opt) { Can we safely use *operator here? tx has optional type and just obtaining the value might result in sigsegv if tx is empty query.tx_hashes.end(), std::back_inserter(hashes), [](const auto &h) { return shared_model::crypto::Hash(h.to_string()); }); + auto txs = _blockQuery->getTransactions(hashes) + .filter([](auto &tx) { return tx; }) + .map([](auto &tx) { + return boost::optional<model::Transaction>( + *std::unique_ptr<iroha::model::Transaction>( + (*tx)->makeOldModel())); + }); std::vector<iroha::model::Transaction> transactions; txs.subscribe([&transactions](auto const &tx_opt) { if (tx_opt) {
codereview_cpp_data_6302
#include <stdlib.h> #include <errno.h> -#define CHAR_SIZE_MAX 4 static inline const char* getFrom(Plugin *handle) { Why only iconv with size of 4? #include <stdlib.h> #include <errno.h> +#define CHAR_SIZE_MAX 4 //biggest character encoding, let the OS deal with the buffering static inline const char* getFrom(Plugin *handle) {
codereview_cpp_data_6304
path = g_strdup_printf ("%s/%s.rpm", self->metadata_dir_path, nevra); pkg = dnf_sack_add_cmdline_package (sack, path); if (!pkg) - glnx_throw (error, "Failed to add local pkg %s to sack", nevra); hy_goal_install (goal, pkg); } Missing a `return` here? path = g_strdup_printf ("%s/%s.rpm", self->metadata_dir_path, nevra); pkg = dnf_sack_add_cmdline_package (sack, path); if (!pkg) + return glnx_throw (error, "Failed to add local pkg %s to sack", nevra); hy_goal_install (goal, pkg); }
codereview_cpp_data_6310
void CarvingManager::handleEvent(sofa::core::objectmodel::Event* event) { - if (m_carvingReady == false) return; if (sofa::core::objectmodel::KeypressedEvent* ev = dynamic_cast<sofa::core::objectmodel::KeypressedEvent*>(event)) why not as in line 140 ? void CarvingManager::handleEvent(sofa::core::objectmodel::Event* event) { + if (!m_carvingReady) return; if (sofa::core::objectmodel::KeypressedEvent* ev = dynamic_cast<sofa::core::objectmodel::KeypressedEvent*>(event))
codereview_cpp_data_6328
#include <cassert> /// for assert #include <iostream> /// for IO operations #include <vector> /// for std::vector -#include <string> /// for string #include <cstring> /// for string /** What's the difference between these two? Why not only use one? #include <cassert> /// for assert #include <iostream> /// for IO operations #include <vector> /// for std::vector #include <cstring> /// for string /**
codereview_cpp_data_6330
/* Clone the stuffers */ /* ignore gcc 4.7 address warnings because dest is allocated on the stack */ /* pragma gcc diagnostic was added in gcc 4.6 */ -#if GCC_VERSION >= 40600 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Waddress" #endif I think this needs to be nested in an ``` #if defined(__GNUC__) ``` guard also. Otherwise if the compiler doesn't define **GNUC** et al, and is also intolerant of bad syntax in the if, the condition will end up expanding to: ``` #if ( * 10000 + 100 + ) >= 40600 ``` and afaict the C standard says that can be considered an error :( /* Clone the stuffers */ /* ignore gcc 4.7 address warnings because dest is allocated on the stack */ /* pragma gcc diagnostic was added in gcc 4.6 */ +#if defined(__GNUC__) && GCC_VERSION >= 40600 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Waddress" #endif
codereview_cpp_data_6337
#define PROTO(T) \ template class glorot_initializer<T>; \ template class he_initializer<T>; \ - template class lecun_initializer<T>; #define LBANN_INSTANTIATE_CPU_HALF #include "lbann/macros/instantiate.hpp" ```suggestion template class lecun_initializer<T> ``` #define PROTO(T) \ template class glorot_initializer<T>; \ template class he_initializer<T>; \ + template class lecun_initializer<T> #define LBANN_INSTANTIATE_CPU_HALF #include "lbann/macros/instantiate.hpp"
codereview_cpp_data_6339
interface::types::HashType reduced_hash_{ shared_model::crypto::Sha3_256::makeHash(reduced_payload_blob_)}; - std::vector<proto::Command> commands_{[this] { - return std::vector<proto::Command>( - reduced_payload_.mutable_commands()->begin(), - reduced_payload_.mutable_commands()->end()); - }()}; boost::optional<std::shared_ptr<interface::BatchMeta>> meta_{ [this]() -> boost::optional<std::shared_ptr<interface::BatchMeta>> { Please remove this lambda interface::types::HashType reduced_hash_{ shared_model::crypto::Sha3_256::makeHash(reduced_payload_blob_)}; + std::vector<proto::Command> commands_{ + reduced_payload_.mutable_commands()->begin(), + reduced_payload_.mutable_commands()->end()}; boost::optional<std::shared_ptr<interface::BatchMeta>> meta_{ [this]() -> boost::optional<std::shared_ptr<interface::BatchMeta>> {
codereview_cpp_data_6342
// Extract FLAGS bool bScriptHash = false; - if (vStrInputParts.size() == 3) { std::string flags = vStrInputParts.back(); bScriptHash = (flags.find("S") != std::string::npos); If the string has 4 parts this code will ignore the flags. To maintain compatibility with the previous behavior, we would ignore additional sections. so this should be: if (vStrInputParts.size() > 2) // Extract FLAGS bool bScriptHash = false; + if (vStrInputParts.size() > 2) { std::string flags = vStrInputParts.back(); bScriptHash = (flags.find("S") != std::string::npos);
codereview_cpp_data_6343
else if (strCommand == NetMsgType::XPEDITEDBLK) { // ignore the expedited message unless we are at the chain tip... - if (!fImporting && !fReindex && !IsInitialBlockDownload() && IsThinBlocksEnabled()) { if (!HandleExpeditedBlock(vRecv, pfrom)) { The ThinBlocksEnabled check is now handle by HandleExpeditedBlock after ptschip's recent PR that went in. else if (strCommand == NetMsgType::XPEDITEDBLK) { // ignore the expedited message unless we are at the chain tip... + if (!fImporting && !fReindex && !IsInitialBlockDownload()) { if (!HandleExpeditedBlock(vRecv, pfrom)) {
codereview_cpp_data_6359
bool Server_Room::userMayJoin(const ServerInfo_User & userInfo) { - qDebug() << "USERPRIV: " << QString::fromStdString(userInfo.privlevel()); - ServerInfo_Room roomInfo; - qDebug() << "ROOMPERM: " << permissionLevel.toLower(); - qDebug() << "ROOMPRIV: " << privilegeLevel.toLower(); - if (permissionLevel.toLower() == "administrator" || permissionLevel.toLower() == "moderator") return false; You create a roomInfo object, but never use it in the function, nor call getRoomPermissionDisplay() bool Server_Room::userMayJoin(const ServerInfo_User & userInfo) { + ServerInfo_Room roomInfo; if (permissionLevel.toLower() == "administrator" || permissionLevel.toLower() == "moderator") return false;
codereview_cpp_data_6372
case WID_M_TRACK_NAME: { Dimension d = GetStringBoundingBox(STR_MUSIC_TITLE_NONE); - for (auto &song : _music.music_set) { SetDParamStr(0, song.songname); d = maxdim(d, GetStringBoundingBox(STR_MUSIC_TITLE_NAME)); } i think the generally accepted way of doing these for loops is `const auto &foo` for that const-correctness goodness case WID_M_TRACK_NAME: { Dimension d = GetStringBoundingBox(STR_MUSIC_TITLE_NONE); + for (const auto &song : _music.music_set) { SetDParamStr(0, song.songname); d = maxdim(d, GetStringBoundingBox(STR_MUSIC_TITLE_NAME)); }
codereview_cpp_data_6377
#include "LinearMath/btSerializer.h" #include "BulletDynamics/Featherstone/btMultiBodyLinkCollider.h" #include "BulletDynamics/Featherstone/btMultiBodyConstraint.h" -#include <iostream> // btSoftBody::btSoftBody(btSoftBodyWorldInfo* worldInfo, int node_count, const btVector3* x, const btScalar* m) : m_softBodySolver(0), m_worldInfo(worldInfo) remove, not needed? #include "LinearMath/btSerializer.h" #include "BulletDynamics/Featherstone/btMultiBodyLinkCollider.h" #include "BulletDynamics/Featherstone/btMultiBodyConstraint.h" // btSoftBody::btSoftBody(btSoftBodyWorldInfo* worldInfo, int node_count, const btVector3* x, const btScalar* m) : m_softBodySolver(0), m_worldInfo(worldInfo)
codereview_cpp_data_6378
if (std::all_of(std::begin(temp), std::end(temp), [](auto b) { return b; })) { - return query_response_factory_->createErrorQueryResponse( QueryErrorType::kStatefulFailed, err_response(), - this->query_hash_); } auto query_range = range | boost::adaptors::transformed([](auto &t) { Replication of strings. Also you seem to log some errors, but not others. Is this intentional? If you want to log all errors you can wrap logging and error construction in a function to reduce code duplication. if (std::all_of(std::begin(temp), std::end(temp), [](auto b) { return b; })) { + return logAndReturnErrorResponse( QueryErrorType::kStatefulFailed, err_response(), + this->query_hash_, + query_response_factory_, + log_); } auto query_range = range | boost::adaptors::transformed([](auto &t) {
codereview_cpp_data_6382
addComponent(comp); } // Top level connection method for all encompassing Component - void connect() { initComponentTreeTraversal(*this); - Super::connect(*this); } void buildUpSystem(MultibodySystem& system) { addToSystem(system); } Does this go against the policy that `Super::` calls should be the first in a method? addComponent(comp); } + // Top level connection method for all encompassing Component + void buildComponentTreeAndConnect() { initComponentTreeTraversal(*this); + connect(*this); } void buildUpSystem(MultibodySystem& system) { addToSystem(system); }
codereview_cpp_data_6387
stopEvent->attachToCompletionFuture(&cf, hStream, hipEventTypeStopCommand); } - ihipPostLaunchKernel(f->_name.c_str(), hStream, lp); -#if (__hcc_workweek__ >= 19213) - if (lockHSAQueue) { - lp.av->release_locked_hsa_queue(); - } -#endif } I think this should happen after all the kernels have been enqueued. Otherwise there is no guarantee of atomicity. stopEvent->attachToCompletionFuture(&cf, hStream, hipEventTypeStopCommand); } + ihipPostLaunchKernel(f->_name.c_str(), hStream, lp, isStreamLocked); }
codereview_cpp_data_6388
#include "vast/type.hpp" #include <arrow/api.h> -#include <arrow/util/config.h> #include <caf/none.hpp> #if ARROW_VERSION_MAJOR < 5 Is this include still required with the removed #ifdef below? #include "vast/type.hpp" #include <arrow/api.h> #include <caf/none.hpp> #if ARROW_VERSION_MAJOR < 5
codereview_cpp_data_6397
struct s2n_stuffer old_stuffer = *stuffer; struct store_byte_from_buffer old_byte; save_byte_from_blob(&stuffer->blob, &old_byte); - uint32_t n; - assert (s2n_stuffer_reread(stuffer) == S2N_SUCCESS); assert(stuffer->read_cursor == 0); /* These assertions should always hold, regardless of whether the test succeeded */ Does this n have a purpose? I missed the CBMC workshop so I'm just trying to reverse engineer all of this myself :) struct s2n_stuffer old_stuffer = *stuffer; struct store_byte_from_buffer old_byte; save_byte_from_blob(&stuffer->blob, &old_byte); + assert(s2n_stuffer_reread(stuffer) == S2N_SUCCESS); assert(stuffer->read_cursor == 0); /* These assertions should always hold, regardless of whether the test succeeded */
codereview_cpp_data_6412
//TODO: Provide the absolute path names of the PhysicalOffsetFrames defined on // the hopper for attaching the assistive device. See buildHopperModel.cpp -// and Component::printSubcomponentInfo() in helperMethods.h. // [Step 3, Task A] static const std::string thighAttachment{"/Dennis/?????"}; //fill this in static const std::string shankAttachment{"/Dennis/?????"}; //fill this in helperMethods.h does not contain `Component::printSubcomponentInfo()`. //TODO: Provide the absolute path names of the PhysicalOffsetFrames defined on // the hopper for attaching the assistive device. See buildHopperModel.cpp +// and Component::printSubcomponentInfo(). // [Step 3, Task A] static const std::string thighAttachment{"/Dennis/?????"}; //fill this in static const std::string shankAttachment{"/Dennis/?????"}; //fill this in
codereview_cpp_data_6414
DefineConsoleMethod( GuiMissionAreaEditorCtrl, setSelectedMissionArea, void, (const char * missionAreaName), (""), "" ) { - if ( missionAreaName == "" ) object->setSelectedMissionArea(NULL); else { Uh oh, need to go with either `dStrlen(missionAreaName) == 0` or `dStrcmp(missionAreaName, "") == 0` like it is used elsewhere. Not sure which one is faster though. DefineConsoleMethod( GuiMissionAreaEditorCtrl, setSelectedMissionArea, void, (const char * missionAreaName), (""), "" ) { + if ( dStrcmp( missionAreaName, "" )==0 ) object->setSelectedMissionArea(NULL); else {
codereview_cpp_data_6421
*/ #if !defined(LIBRESSL_VERSION_NUMBER) && !defined(OPENSSL_IS_BORINGSSL) /* Symbols for AES-SHA1-CBC composite ciphers were added in Openssl 1.0.1: - * See https://www.openssl.org/news/cl101.txt. */ #if S2N_OPENSSL_VERSION_AT_LEAST(1,0,1) #define S2N_AES_SHA1_COMPOSITE_AVAILABLE This link doesn't work, and I don't see a way to link to the relevant entry in the openssl changelog that does exist. You might want to just delete this line instead of moving it. */ #if !defined(LIBRESSL_VERSION_NUMBER) && !defined(OPENSSL_IS_BORINGSSL) /* Symbols for AES-SHA1-CBC composite ciphers were added in Openssl 1.0.1: */ #if S2N_OPENSSL_VERSION_AT_LEAST(1,0,1) #define S2N_AES_SHA1_COMPOSITE_AVAILABLE
codereview_cpp_data_6423
namespace vast { void factory_traits<table_slice_builder>::initialize() { - using F = factory<table_slice_builder>; - F::add<default_table_slice_builder>(default_table_slice::class_id); } } // namespace vast So far we only use upper-case names for template parameters. I think we should not make an exception here. namespace vast { void factory_traits<table_slice_builder>::initialize() { + using f = factory<table_slice_builder>; + f::add<default_table_slice_builder>(default_table_slice::class_id); } } // namespace vast
codereview_cpp_data_6440
return players.current_color; } -/* return fontname */ -const std::string & Settings::FontsNormal() const -{ - return font_normal; -} -const std::string & Settings::FontsSmall() const -{ - return font_small; -} - const std::string & Settings::ForceLang() const { return force_lang; :warning: **cppcoreguidelines-pro-bounds-array-to-pointer-decay** :warning: do not implicitly decay an array into a pointer; consider using gsl::array_view or an explicit cast instead return players.current_color; } const std::string & Settings::ForceLang() const { return force_lang;
codereview_cpp_data_6455
} if (_timeStepper) { - std::string msg = "Cannot set a new integrator on this Manager"; msg += "after Manager::integrate() has been called at least once."; OPENSIM_THROW(Exception, msg); } This may be confusing to users as they did not try to set a new integrator. Perhaps the message could be "Cannot set a different model ..." } if (_timeStepper) { + std::string msg = "Cannot set a new Model on this Manager"; msg += "after Manager::integrate() has been called at least once."; OPENSIM_THROW(Exception, msg); }
codereview_cpp_data_6456
ihipStreamCallback_t* cb = static_cast<ihipStreamCallback_t*> (cbArgs); // Call registered callback function cb->_callback(cb->_stream, e, cb->_userData); Where `hipError_t e` is handled? Should the function unconditionally return `false`? ihipStreamCallback_t* cb = static_cast<ihipStreamCallback_t*> (cbArgs); + if(cb->comFuture.valid()) + cb->comFuture.wait(); + // Call registered callback function cb->_callback(cb->_stream, e, cb->_userData);
codereview_cpp_data_6458
{ if (!client->fsaccess->mkdirlocal(&localpath)) { LOG_err << "Unable to create folder: " << *path; recursive--; Replace with da.reset()? { if (!client->fsaccess->mkdirlocal(&localpath)) { + da.reset(); LOG_err << "Unable to create folder: " << *path; recursive--;
codereview_cpp_data_6462
ReasonsGroupType reason; reason.first = "Transaction list"; for (const auto &tx : transactions) { - auto answer = ParentType::transaction_validator_.validate(tx); if (answer.hasErrors()) { auto message = (boost::format("Tx %s : %s") % tx.hash().hex() % answer.reason()) As I've seen everywhere throughout the code, library includes are always in the beginning of all others, so shouldn't it be moved upwards? ReasonsGroupType reason; reason.first = "Transaction list"; for (const auto &tx : transactions) { + auto answer = + SignedTransactionsCollectionValidator::transaction_validator_ + .validate(tx); if (answer.hasErrors()) { auto message = (boost::format("Tx %s : %s") % tx.hash().hex() % answer.reason())
codereview_cpp_data_6468
num_data_ = train_data_->num_data(); // create buffer for gradients and Hessians - size_t total_size = static_cast<size_t>(num_data_) * num_tree_per_iteration_; if (objective_function_ != nullptr) { gradients_.resize(total_size); hessians_.resize(total_size); - } else { - // use customized objective function, only for GOSS - gradients_.resize(total_size, 0.0f); - hessians_.resize(total_size, 0.0f); } // get max feature index max_feature_idx_ = train_data_->num_total_features() - 1; Please consider moving this into the GOSS Sample strategy. For example, we can do this in `ResetConfig`. num_data_ = train_data_->num_data(); // create buffer for gradients and Hessians if (objective_function_ != nullptr) { + const size_t total_size = static_cast<size_t>(num_data_) * num_tree_per_iteration_; gradients_.resize(total_size); hessians_.resize(total_size); } // get max feature index max_feature_idx_ = train_data_->num_total_features() - 1;
codereview_cpp_data_6473
// commit transactions commits.subscribe( // on next - [this](auto model_block) { - for (const auto &tx : model_block->transactions()) { const auto &hash = tx.hash(); log_->debug("Committed transaction: {}", hash.hex()); this->publishStatus(TxStatusType::kCommitted, hash); } for (const auto &rejected_tx_hash : - model_block->rejected_transactions_hashes()) { log_->debug("Rejected transaction: {}", rejected_tx_hash.hex()); this->publishStatus(TxStatusType::kRejected, rejected_tx_hash); } ```suggestion [this](auto block) { ``` // commit transactions commits.subscribe( // on next + [this](auto block) { + for (const auto &tx : block->transactions()) { const auto &hash = tx.hash(); log_->debug("Committed transaction: {}", hash.hex()); this->publishStatus(TxStatusType::kCommitted, hash); } for (const auto &rejected_tx_hash : + block->rejected_transactions_hashes()) { log_->debug("Rejected transaction: {}", rejected_tx_hash.hex()); this->publishStatus(TxStatusType::kRejected, rejected_tx_hash); }
codereview_cpp_data_6478
h2o_req_fill_mime_attributes(req); if (!req->res.mime_attr->is_compressible) goto Next; - /* 100 is a rough estimate */ - if (req->res.content_length <= self->args.min_size) goto Next; /* skip if failed to gather the list of compressible types */ if ((compressible_types = h2o_get_compressible_types(&req->headers)) == 0) Should we better change the operator to `<` since the variable defines the minimum size that gets compressed? h2o_req_fill_mime_attributes(req); if (!req->res.mime_attr->is_compressible) goto Next; + if (req->res.content_length < self->args.min_size) goto Next; /* skip if failed to gather the list of compressible types */ if ((compressible_types = h2o_get_compressible_types(&req->headers)) == 0)
codereview_cpp_data_6480
// https://www.gnu.org/software/libc/manual/html_node/Mathematical-Constants.html EXPECT_DOUBLE_EQ(-0.95445818456292697, pj_phi2(ctx, M_PI, 0.0)); - EXPECT_TRUE(isnan(pj_phi2(ctx, 0.0, M_PI))); EXPECT_DOUBLE_EQ(4.0960508381527205, pj_phi2(ctx, -M_PI, 0.0)); - EXPECT_TRUE(isnan(pj_phi2(ctx, 0.0, -M_PI))); - EXPECT_TRUE(isnan(pj_phi2(ctx, M_PI, M_PI))); - EXPECT_TRUE(isnan(pj_phi2(ctx, -M_PI, -M_PI))); } should be std::isnan() to please x86_64-w64-mingw32 // https://www.gnu.org/software/libc/manual/html_node/Mathematical-Constants.html EXPECT_DOUBLE_EQ(-0.95445818456292697, pj_phi2(ctx, M_PI, 0.0)); + EXPECT_TRUE(std::isnan(pj_phi2(ctx, 0.0, M_PI))); EXPECT_DOUBLE_EQ(4.0960508381527205, pj_phi2(ctx, -M_PI, 0.0)); + EXPECT_TRUE(std::isnan(pj_phi2(ctx, 0.0, -M_PI))); + EXPECT_TRUE(std::isnan(pj_phi2(ctx, M_PI, M_PI))); + EXPECT_TRUE(std::isnan(pj_phi2(ctx, -M_PI, -M_PI))); }
codereview_cpp_data_6490
#include <errno.h> #include <s2n.h> -#define PSK_SECRET_SIZE_MAX 2048 char *load_file_to_cstring(const char *path) { FILE *pem_file = fopen(path, "rb"); Why do we need a limit on secret size? Are we advertising it somewhere? #include <errno.h> #include <s2n.h> char *load_file_to_cstring(const char *path) { FILE *pem_file = fopen(path, "rb");
codereview_cpp_data_6502
AccountAssetResponse::AccountAssetResponse( QueryResponseType &&queryResponse) : CopyableProto(std::forward<QueryResponseType>(queryResponse)), - accountAssetResponse_{proto_->account_assets_response()}, - accountAssets_{std::vector<proto::AccountAsset>{ - accountAssetResponse_.account_assets().begin(), - accountAssetResponse_.account_assets().end()}} {} template AccountAssetResponse::AccountAssetResponse( AccountAssetResponse::TransportType &); please remove std::vector constructor since its redundant AccountAssetResponse::AccountAssetResponse( QueryResponseType &&queryResponse) : CopyableProto(std::forward<QueryResponseType>(queryResponse)), + account_asset_response_{proto_->account_assets_response()}, + account_assets_{account_asset_response_.account_assets().begin(), + account_asset_response_.account_assets().end()} {} template AccountAssetResponse::AccountAssetResponse( AccountAssetResponse::TransportType &);
codereview_cpp_data_6505
CHECK_EQUAL(y->num_slices(), 1u); CHECK(std::equal(x->chunk()->begin(), x->chunk()->end(), y->chunk()->begin(), y->chunk()->end())); - /* MESSAGE("load segment from chunk"); auto z = segment::make(chunk::make(std::move(buf))); REQUIRE(z); CHECK(std::equal(x->chunk()->begin(), x->chunk()->end(), z->chunk()->begin(), z->chunk()->end())); - */ } FIXTURE_SCOPE_END() Is there still some `TODO` before we can reenable this check? CHECK_EQUAL(y->num_slices(), 1u); CHECK(std::equal(x->chunk()->begin(), x->chunk()->end(), y->chunk()->begin(), y->chunk()->end())); MESSAGE("load segment from chunk"); auto z = segment::make(chunk::make(std::move(buf))); REQUIRE(z); CHECK(std::equal(x->chunk()->begin(), x->chunk()->end(), z->chunk()->begin(), z->chunk()->end())); } FIXTURE_SCOPE_END()
codereview_cpp_data_6526
{ notifyAboutUpdates = _notifyaboutupdate; settings->setValue("personal/updatenotification", notifyAboutUpdates); -} - -QString SettingsCache::getSrvClientID(const QString _hostname) -{ - QString srvClientID = getClientID(); - srvClientID += _hostname; - QString uniqueServerClientID = QCryptographicHash::hash(srvClientID.toUtf8(), QCryptographicHash::Sha1).toHex().right(15); - return uniqueServerClientID; } \ No newline at end of file Why do we take the `right` like this? { notifyAboutUpdates = _notifyaboutupdate; settings->setValue("personal/updatenotification", notifyAboutUpdates); } \ No newline at end of file
codereview_cpp_data_6529
bool MegaClient::loggedIntoWritableFolder() const { - return !ISUNDEF(publichandle) && !publichandleWriteAuth.empty(); } void MegaClient::userfeedbackstore(const char *message) What about: ```suggestion cpp return loggedIntoFolder() && !publichandleWriteAuth.empty(); ``` bool MegaClient::loggedIntoWritableFolder() const { + return loggedIntoFolder() && !publichandleWriteAuth.empty(); } void MegaClient::userfeedbackstore(const char *message)
codereview_cpp_data_6532
} bool TransactionsPageResponse::operator==(const ModelType &rhs) const { - return transactions() == rhs.transactions(); } } // namespace interface Why is it not required to also compare nextTxHash and allTransactionsSize? } bool TransactionsPageResponse::operator==(const ModelType &rhs) const { + return transactions() == rhs.transactions() + and nextTxHash() == rhs.nextTxHash() + and allTransactionsSize() == rhs.allTransactionsSize(); } } // namespace interface
codereview_cpp_data_6536
stop = true; } else if (msg.source == src) { VAST_DEBUG("received DOWN from source"); - if (caf::get_or(options, "blocking", false)) { self->send(importer, subscribe_atom::value, flush_atom::value, self); - } else { stop = true; - } } }, [&](flush_atom) { Style: superfluous curly braces. stop = true; } else if (msg.source == src) { VAST_DEBUG("received DOWN from source"); + if (caf::get_or(options, "blocking", false)) self->send(importer, subscribe_atom::value, flush_atom::value, self); + else stop = true; } }, [&](flush_atom) {
codereview_cpp_data_6538
RESULT_GUARD(s2n_pkey_size(pkey, &maximum_signature_length)); RESULT_GUARD_POSIX(s2n_alloc(&sign->signature, maximum_signature_length)); - /* If signature validation mode is S2N_ASYNC_PKEY_VALIDATION_STRICT * then use local hash copy to sign the signature */ - if (op->conn->config->async_pkey_validation_mode == S2N_ASYNC_PKEY_VALIDATION_STRICT) { DEFER_CLEANUP(struct s2n_hash_state hash_state_copy, s2n_hash_free); RESULT_GUARD_POSIX(s2n_hash_new(&hash_state_copy)); RESULT_GUARD_POSIX(s2n_hash_copy(&hash_state_copy, &sign->digest)); Actually this may lead to concurrency issues. `s2n_async_pkey_sign_perform` usually is called inside the thread, while some other operations are performed on `op->connection` in a different thread (like freeing that connection), so you can't really access anything out of `op->conn` in `perform` call. If you want to avoid redundant copy when validation mode is not strict, you can put some flag into `op` struct. RESULT_GUARD(s2n_pkey_size(pkey, &maximum_signature_length)); RESULT_GUARD_POSIX(s2n_alloc(&sign->signature, maximum_signature_length)); + /* If validation mode is S2N_ASYNC_PKEY_VALIDATION_STRICT * then use local hash copy to sign the signature */ + if (op->validation_mode == S2N_ASYNC_PKEY_VALIDATION_STRICT) { DEFER_CLEANUP(struct s2n_hash_state hash_state_copy, s2n_hash_free); RESULT_GUARD_POSIX(s2n_hash_new(&hash_state_copy)); RESULT_GUARD_POSIX(s2n_hash_copy(&hash_state_copy, &sign->digest));
codereview_cpp_data_6553
} memset(&listener->ssl, 0, sizeof(listener->ssl)); memset(&listener->quic, 0, sizeof(listener->quic)); - -#if defined(__linux__) - listener->timestamping = timestamping; -#else /* !defined(__linux__) */ - listener->timestamping = 0; -#endif /* defined(__linux__) */ - listener->quic.qpack = (h2o_http3_qpack_context_t){.encoder_table_capacity = 4096 /* our default */}; listener->proxy_protocol = proxy_protocol; listener->tcp_congestion_controller = h2o_iovec_init(NULL, 0); ```suggestion listener->timestamping = timestamping; ``` I think we'd want to be principled if the concept of timestamping is platform-agnostic or not. If it is going to be platform-specific, not only these lines but everything (incl. `listener_config_t::timestamping`, `timestamping` argument passed to `add_listener`) have to be covered by `#if defined(__linux__)`. If we are to consider timestamping as a platform-agnostic concept that happens to be supported only on some platforms at the moment, I think we'd not want to change the flag silently at the middle between where the flag is set (i.e. config knob) and where the flag is used. } memset(&listener->ssl, 0, sizeof(listener->ssl)); memset(&listener->quic, 0, sizeof(listener->quic)); +listener->timestamping = timestamping; listener->quic.qpack = (h2o_http3_qpack_context_t){.encoder_table_capacity = 4096 /* our default */}; listener->proxy_protocol = proxy_protocol; listener->tcp_congestion_controller = h2o_iovec_init(NULL, 0);
codereview_cpp_data_6555
void UpdatePreferredDownload(CNode *node, CNodeState *state) { - LOCK(cs_main); - nPreferredDownload -= state->fPreferredDownload; // Whether this node should be marked as a preferred download node. state->fPreferredDownload = !node->fOneShot && !node->fClient; should we atomic nPreferredDownload so it doesn't require cs_main? void UpdatePreferredDownload(CNode *node, CNodeState *state) { + nPreferredDownload.fetch_sub(state->fPreferredDownload); // Whether this node should be marked as a preferred download node. state->fPreferredDownload = !node->fOneShot && !node->fClient;
codereview_cpp_data_6560
return glnx_throw (error, "Checksum mismatch for package %s", nevra); } - g_autoptr(GVariant) header = NULL; - if (!get_header_variant (pkgcache, cache_branch, &header, cancellable, error)) - return FALSE; - - *out_header = g_steal_pointer (&header); - return TRUE; } static gboolean This could be just `return get_header_variant (..., out_header)` return glnx_throw (error, "Checksum mismatch for package %s", nevra); } + return get_header_variant (pkgcache, cache_branch, out_header, cancellable, error); } static gboolean
codereview_cpp_data_6579
} #ifdef ENABLE_CHAT -CommandChatCreate::CommandChatCreate(MegaClient *client, bool group, userpriv_vector *upl) { this->client = client; - this->chatPeers = upl; cmd("mcc"); arg("g", (group) ? 1 : 0); It seems that there is a missing `delete chat;` here. } #ifdef ENABLE_CHAT +CommandChatCreate::CommandChatCreate(MegaClient *client, bool group, const userpriv_vector *upl) { this->client = client; + this->chatPeers = new userpriv_vector(*upl); cmd("mcc"); arg("g", (group) ? 1 : 0);
codereview_cpp_data_6585
ASSERT_FALSE(manager.loadKeys()); } -TEST_F(KeyManager, CreateInaccessiblePubkey) { - KeysManagerImpl manager = KeysManagerImpl(inexistent); - ASSERT_FALSE(manager.createKeys(passphrase)); -} - -TEST_F(KeyManager, CreateInaccessiblePrikey) { - KeysManagerImpl manager = KeysManagerImpl(inexistent); ASSERT_FALSE(manager.createKeys(passphrase)); } Doesn't conform with the test name ASSERT_FALSE(manager.loadKeys()); } +TEST_F(KeyManager, CreateKeypairInNonexistentDir) { + KeysManagerImpl manager = KeysManagerImpl(nonexistent); ASSERT_FALSE(manager.createKeys(passphrase)); }
codereview_cpp_data_6603
/* Initialize context */ ctx = flb_calloc(1, sizeof(struct winevtlog_config)); - if (!ctx) { flb_errno(); return -1; } Could you change this to explicitly compare against NULL? (same goes for other occurrences but I won't spam the diffs with this) /* Initialize context */ ctx = flb_calloc(1, sizeof(struct winevtlog_config)); + if (ctx == NULL) { flb_errno(); return -1; }
codereview_cpp_data_6605
template <typename TensorDataType> bool rmsprop<TensorDataType>::save_to_checkpoint_distributed(persist& p, std::string name_prefix) { - write_cereal_archive<rmsprop<TensorDataType>>(*this, p, "rmsprop.xml"); char l_name[512]; sprintf(l_name, "%s_optimizer_cache_%lldx%lld", name_prefix.c_str(), m_cache->Height(), m_cache->Width()); ```suggestion write_cereal_archive(*this, p, "rmsprop.xml"); ``` template <typename TensorDataType> bool rmsprop<TensorDataType>::save_to_checkpoint_distributed(persist& p, std::string name_prefix) { + write_cereal_archive(*this, p, "rmsprop.xml"); char l_name[512]; sprintf(l_name, "%s_optimizer_cache_%lldx%lld", name_prefix.c_str(), m_cache->Height(), m_cache->Width());
codereview_cpp_data_6626
#include <set> #include <map> #define _THROW_LBANN_EXCEPTION_(_CLASS_NAME_,_MSG_) { \ std::stringstream err; \ err << __FILE__ << ' ' << __LINE__ << " :: " \ I like these macros and would like to see them generalized to all of lbann. Only problem is the "data_reader_jag_conduit" #include <set> #include <map> +// This macro may be moved to a global scope #define _THROW_LBANN_EXCEPTION_(_CLASS_NAME_,_MSG_) { \ std::stringstream err; \ err << __FILE__ << ' ' << __LINE__ << " :: " \
codereview_cpp_data_6636
annotateTokensCheckBox.setText(tr("Annotate card text on tokens")); animationGroupBox->setTitle(tr("Animation settings")); tapAnimationCheckBox.setText(tr("&Tap/untap animation")); - idleClientTimeOutCheckBox.setText(tr("Disconnect from server if sitting idle for an extended periods of time")); } 'sitting' may be redundant / incorrect annotateTokensCheckBox.setText(tr("Annotate card text on tokens")); animationGroupBox->setTitle(tr("Animation settings")); tapAnimationCheckBox.setText(tr("&Tap/untap animation")); + idleClientTimeOutCheckBox.setText(tr("Disconnect from server if idle for 1 hour")); }