id
stringlengths
21
25
content
stringlengths
164
2.33k
codereview_cpp_data_3549
* SPDX-License-Identifier: Apache-2.0 */ -#include <endpoint.pb.h> #include <gtest/gtest.h> #include "builders/protobuf/block.hpp" #include "builders/protobuf/block_variant_transport_builder.hpp" #include "builders/protobuf/empty_block.hpp" Please use "" instead of <> * SPDX-License-Identifier: Apache-2.0 */ #include <gtest/gtest.h> +#include "endpoint.pb.h" #include "builders/protobuf/block.hpp" #include "builders/protobuf/block_variant_transport_builder.hpp" #include "builders/protobuf/empty_block.hpp"
codereview_cpp_data_3556
void IO::FlushAll() { m_IO.FlushAll(); } -void IO::LockDefinitions() -{ - m_IO.LockDefinitions(); -} std::map<std::string, Params> IO::AvailableVariables() noexcept { missing noexcept: `void IO::LockDefinitions() noexcept` void IO::FlushAll() { m_IO.FlushAll(); } +void IO::LockDefinitions() noexcept { m_IO.LockDefinitions(); } std::map<std::string, Params> IO::AvailableVariables() noexcept {
codereview_cpp_data_3558
if (cipher_preferences == NULL) { return false; } - for (int j = 0; j < cipher_preferences->count; j++) { - if (s2n_cipher_suite_requires_ecc_extension(cipher_preferences->suites[j])) { return true; } } Any reason you use `j` instead of `i` here and below? if (cipher_preferences == NULL) { return false; } + for (uint8_t i = 0; i < cipher_preferences->count; i++) { + if (s2n_cipher_suite_requires_ecc_extension(cipher_preferences->suites[i])) { return true; } }
codereview_cpp_data_3561
template bool lbann::write_distmat<T>( \ int fd, const char *name, DistMatDT<T> *M, uint64_t *bytes); \ template bool lbann::read_distmat<T>( \ - int fd, const char *name, DistMatDT<T> *M, uint64_t *bytes); #define LBANN_INSTANTIATE_CPU_HALF #include "lbann/macros/instantiate.hpp" ```suggestion int fd, const char *name, DistMatDT<T> *M, uint64_t *bytes) ``` template bool lbann::write_distmat<T>( \ int fd, const char *name, DistMatDT<T> *M, uint64_t *bytes); \ template bool lbann::read_distmat<T>( \ + int fd, const char *name, DistMatDT<T> *M, uint64_t *bytes) #define LBANN_INSTANTIATE_CPU_HALF #include "lbann/macros/instantiate.hpp"
codereview_cpp_data_3567
// MessageBox blocks and can allow other events to transit<> to a new state // which makes this transit fatal. boost::statechart::result retval = fatal ? transit<IntroMenu>() : discard_event(); - ClientUI::MessageBox(UserString(problem), true); if (fatal) { Client().EndGame(true); Client().Remove(Client().GetClientUI()->GetMapWnd()); Client().GetClientUI()->GetMapWnd()->RemoveWindows(); Client().Networking().SetHostPlayerID(Networking::INVALID_PLAYER_ID); I renamed the AI script directory, then started freeorion, then quickstarted. I got a crash around here, though I'm now unable to reproduce it. // MessageBox blocks and can allow other events to transit<> to a new state // which makes this transit fatal. boost::statechart::result retval = fatal ? transit<IntroMenu>() : discard_event(); + ClientUI::MessageBox(UserString(problem), false); if (fatal) { Client().EndGame(true); + Client().GetClientUI()->GetMessageWnd()->Hide(); + Client().GetClientUI()->GetPlayerListWnd()->Hide(); Client().Remove(Client().GetClientUI()->GetMapWnd()); Client().GetClientUI()->GetMapWnd()->RemoveWindows(); Client().Networking().SetHostPlayerID(Networking::INVALID_PLAYER_ID);
codereview_cpp_data_3572
cancellable, error)) return FALSE; } } OstreeRepoTransactionStats stats = { 0, }; OstreeRepoTransactionStats *statsp = NULL; Hmm, I think this slightly changes the semantics of `--write-commitid-to` though. Before it would override `ref`, but now we're doing both. That's likely to cause issues in e.g. pungi, which does the ref update as a separate step. cancellable, error)) return FALSE; } + g_print ("%s => %s\n", self->ref, new_revision); + g_variant_builder_add (&composemeta_builder, "{sv}", "ref", g_variant_new_string (self->ref)); } + else + g_print ("Wrote commit: %s\n", new_revision); OstreeRepoTransactionStats stats = { 0, }; OstreeRepoTransactionStats *statsp = NULL;
codereview_cpp_data_3574
read-only ${HOME}/.local/bin read-only ${HOME}/.cargo/bin # Write-protection for desktop entries read-only ${HOME}/.config/menus read-only ${HOME}/.local/share/applications why not just make all of cargo readonly? read-only ${HOME}/.local/bin read-only ${HOME}/.cargo/bin +# cargo +read-only ${HOME}/.cargo/env +blacklist ${HOME}/.cargo/registry +blacklist ${HOME}/.cargo/config + # Write-protection for desktop entries read-only ${HOME}/.config/menus read-only ${HOME}/.local/share/applications
codereview_cpp_data_3599
// if the disconnected player wasn't in the lobby, don't need to do anything more. // if player is in lobby, need to remove it int id = player_connection->PlayerID(); - // if player was not etablished disconnect him as AI also have player_id is Networking::INVALID_PLAYER_ID if (id == Networking::INVALID_PLAYER_ID) { DebugLogger(FSM) << "MPLobby.Disconnection : Disconnecting player (" << id << ") was not established"; return discard_event(); What this means isn't clear. Please elaborate. // if the disconnected player wasn't in the lobby, don't need to do anything more. // if player is in lobby, need to remove it int id = player_connection->PlayerID(); + // Non-established player shouldn't be processed because it wasn't in lobby and AI entries have same id (INVALID_PLAYER_ID). if (id == Networking::INVALID_PLAYER_ID) { DebugLogger(FSM) << "MPLobby.Disconnection : Disconnecting player (" << id << ") was not established"; return discard_event();
codereview_cpp_data_3600
crypto::Keypair ModelCrypto::fromPrivateKey( const std::string &private_key) { - if (private_key.length() != 64) { throw std::invalid_argument("input string has incorrect length " + std::to_string(private_key.length())); } Add please a todo for crypto magics removal with reference to IR-977 crypto::Keypair ModelCrypto::fromPrivateKey( const std::string &private_key) { + // TODO 07/06/18 Akvinikym: remove magic number (64) IR-977 + if (private_key.size() != 64) { throw std::invalid_argument("input string has incorrect length " + std::to_string(private_key.length())); }
codereview_cpp_data_3611
switch (element->getElementType().getEnum()) { case ElementType::Node: - changeElement.reset(new Node(*dynamic_pointer_cast<const Node>(element))); break; case ElementType::Way: - changeElement.reset(new Way(*dynamic_pointer_cast<const Way>(element))); break; case ElementType::Relation: - changeElement.reset(new Relation(*dynamic_pointer_cast<const Relation>(element))); break; default: throw HootException("Unknown element type"); Could we use this to avoid updating the api db id sequence and instead assign negative ids starting at -1 to all new features? switch (element->getElementType().getEnum()) { case ElementType::Node: + changeElement.reset(new Node(*boost::dynamic_pointer_cast<const Node>(element))); break; case ElementType::Way: + changeElement.reset(new Way(*boost::dynamic_pointer_cast<const Way>(element))); break; case ElementType::Relation: + changeElement.reset(new Relation(*boost::dynamic_pointer_cast<const Relation>(element))); break; default: throw HootException("Unknown element type");
codereview_cpp_data_3630
return true; } if ((conn->mode == S2N_CLIENT) && !s2n_is_tls13_fully_supported()) { /* There are some TLS Servers in the wild that will always choose RSA PSS if the client claims to support TLS 1.3 * even if the client does not advertise support for RSA PSS in the SignatureScheme extension. In order to work Have we considered mutual auth? return true; } + s2n_cert_auth_type client_auth_status = S2N_CERT_AUTH_NONE; + s2n_connection_get_client_auth_type(conn, &client_auth_status); + + if ((conn->mode == S2N_SERVER) + && (client_auth_status != S2N_CERT_AUTH_NONE) + && !s2n_is_tls13_fully_supported()) { + /* If we're a Server that is going to request a client certificate, and we don't support RSA PSS, then + * downgrade to TLS 1.2 in case the client attempts to send an RSA PSS Certificate. */ + return true; + } + if ((conn->mode == S2N_CLIENT) && !s2n_is_tls13_fully_supported()) { /* There are some TLS Servers in the wild that will always choose RSA PSS if the client claims to support TLS 1.3 * even if the client does not advertise support for RSA PSS in the SignatureScheme extension. In order to work
codereview_cpp_data_3634
sol_raii.resize(namrlevs); for (int alev = 0; alev < namrlevs; ++alev) { - if (a_sol[alev]->nGrow() >= 1) { sol[alev] = a_sol[alev]; } Let's not change the current behavior. sol_raii.resize(namrlevs); for (int alev = 0; alev < namrlevs; ++alev) { + if (cf_strategy == CFStrategy::ghostnodes) + { + sol[alev] = a_sol[alev]; + } + else if (a_sol[alev]->nGrow() == 1) { sol[alev] = a_sol[alev]; }
codereview_cpp_data_3635
bool PosixFileSystemAccess::mkdirlocal(LocalPath& name, bool) { mode_t mode = umask(0); - bool r = !mkdir(adjustBasePath(name).c_str(), defaultfolderpermissions); umask(mode); if (!r) using a variable will speed things up for ios bool PosixFileSystemAccess::mkdirlocal(LocalPath& name, bool) { +#ifdef USE_IOS + const string nameStr = adjustBasePath(name); +#else + // use the existing string if it's not iOS, no need for a copy + const string& nameStr = adjustBasePath(name); +#endif + mode_t mode = umask(0); + bool r = !mkdir(nameStr.c_str(), defaultfolderpermissions); umask(mode); if (!r)
codereview_cpp_data_3645
g_autoptr(GVariant) metadata = g_variant_get_child_value (commit, 0); g_autoptr(GVariantDict) metadata_dict = g_variant_dict_new (metadata); const char *current_cacheid = NULL; - g_variant_dict_lookup (metadata_dict, "rpmostree.jigdo_cacheid", "s", &current_cacheid); if (g_strcmp0 (current_cacheid, cacheid)) { if (!ostree_repo_set_ref_immediate (pkgcache_repo, NULL, jigdo_branch, NULL, This should be `&s`, right? g_autoptr(GVariant) metadata = g_variant_get_child_value (commit, 0); g_autoptr(GVariantDict) metadata_dict = g_variant_dict_new (metadata); const char *current_cacheid = NULL; + g_variant_dict_lookup (metadata_dict, "rpmostree.jigdo_cacheid", "&s", &current_cacheid); if (g_strcmp0 (current_cacheid, cacheid)) { if (!ostree_repo_set_ref_immediate (pkgcache_repo, NULL, jigdo_branch, NULL,
codereview_cpp_data_3654
); if (!rp->avp) { msg_printf(project, MSG_INTERNAL_ERROR, - "No application found for task %s: platform %s version %d plan class%s; discarding", rp->wup->name, rp->platform, rp->version_num, rp->plan_class ); delete rp; Needs space after "plan class". ); if (!rp->avp) { msg_printf(project, MSG_INTERNAL_ERROR, + "No application found for task %s: platform %s version %d plan class %s; discarding", rp->wup->name, rp->platform, rp->version_num, rp->plan_class ); delete rp;
codereview_cpp_data_3659
static gboolean opt_all; static char *opt_arch; static char *opt_app_runtime; -static const char **opt_cols; static GOptionEntry options[] = { { "show-details", 'd', 0, G_OPTION_ARG_NONE, &opt_show_details, N_("Show extra information"), NULL }, This is duplicated from ps, can we put it in app/flatpak-builtins-utils.c instead? static gboolean opt_all; static char *opt_arch; static char *opt_app_runtime; static GOptionEntry options[] = { { "show-details", 'd', 0, G_OPTION_ARG_NONE, &opt_show_details, N_("Show extra information"), NULL },
codereview_cpp_data_3675
AttachChild(m_icon); m_link_text = new LinkText(GG::X0, GG::Y0, GG::X1, m_sitrep_entry.GetText() + " ", - ClientUI::GetFont(1.0*ClientUI::Pts()), GG::FORMAT_LEFT | GG::FORMAT_VCENTER | GG::FORMAT_WORDBREAK, ClientUI::TextColor()); m_link_text->SetDecorator(VarText::EMPIRE_ID_TAG, new ColorEmpire()); AttachChild(m_link_text); no need for 1.0\* or any parameter to GetFont... the no-parameter version defaults to the same thing. AttachChild(m_icon); m_link_text = new LinkText(GG::X0, GG::Y0, GG::X1, m_sitrep_entry.GetText() + " ", + ClientUI::GetFont(ClientUI::Pts()), GG::FORMAT_LEFT | GG::FORMAT_VCENTER | GG::FORMAT_WORDBREAK, ClientUI::TextColor()); m_link_text->SetDecorator(VarText::EMPIRE_ID_TAG, new ColorEmpire()); AttachChild(m_link_text);
codereview_cpp_data_3682
return nodeToIndex(cardNode); } -QModelIndex DeckListModel::addCard(const QString &cardName, const QString &zoneName, bool anAddAnyway) { CardInfo *info = db->getCard(cardName); if (info == nullptr) { - if (anAddAnyway) { // We need to keep this card added no matter what // This is usually called from tab_deck_editor what's the `an` in `anAddAnyway`? Maybe rename to `addIfMissingFromDb`? return nodeToIndex(cardNode); } +QModelIndex DeckListModel::addCard(const QString &cardName, const QString &zoneName, bool abAddAnyway) { CardInfo *info = db->getCard(cardName); if (info == nullptr) { + if (abAddAnyway) { // We need to keep this card added no matter what // This is usually called from tab_deck_editor
codereview_cpp_data_3687
m_filterCallback(NULL) { b3Clock clock; - srand(clock.getTimeMilliseconds()); // Set random milliseconds based on system time clock.reset(true); // Reset clock to zero to get new random seed } virtual ~NN3DWalkersExample() you may want to call this reset before calling 'getTimeMilliseconds', otherwise you still get the relative time since the clock was created. m_filterCallback(NULL) { b3Clock clock; clock.reset(true); // Reset clock to zero to get new random seed + srand(clock.getTimeMilliseconds()); // Set random milliseconds based on system time } virtual ~NN3DWalkersExample()
codereview_cpp_data_3689
connect(soundPathClearButton, SIGNAL(clicked()), this, SLOT(soundPathClearButtonClicked())); QPushButton *soundPathButton = new QPushButton("..."); connect(soundPathButton, SIGNAL(clicked()), this, SLOT(soundPathButtonClicked())); - QPushButton *soundTestButton = new QPushButton(QString("Play test sound")); connect(soundTestButton, SIGNAL(clicked()), soundEngine, SLOT(cuckoo())); QGridLayout *soundGrid = new QGridLayout; Button text needs a `tr`. I think better wording might be "Test system sound engine" connect(soundPathClearButton, SIGNAL(clicked()), this, SLOT(soundPathClearButtonClicked())); QPushButton *soundPathButton = new QPushButton("..."); connect(soundPathButton, SIGNAL(clicked()), this, SLOT(soundPathButtonClicked())); + soundTestButton = new QPushButton(); connect(soundTestButton, SIGNAL(clicked()), soundEngine, SLOT(cuckoo())); QGridLayout *soundGrid = new QGridLayout;
codereview_cpp_data_3700
assert(self == &conn->_ostr_final); /* count bytes_sent if other ostreams haven't counted */ - if (inbufcnt > 0 && req->bytes_sent == 0) { - self->count_bytes_sent = 1; - } - if (self->count_bytes_sent) { for (i = 0; i != inbufcnt; ++i) { req->bytes_sent += inbufs[i].len; } I can understand the fact that you wanted to keep modifications within http1.c, but isn't this a bit complicated? How about adding a flag to `h2o_req_t` that tells if the bytes are counted outside of the protocol handler (and set the flag in chunked.c)? We already have HTTP/1 specific flag in `h2o_req_t` (as `http1_is_persistent`). I think we can add another. assert(self == &conn->_ostr_final); /* count bytes_sent if other ostreams haven't counted */ + if (req->bytes_counted_by_ostream == 0) { for (i = 0; i != inbufcnt; ++i) { req->bytes_sent += inbufs[i].len; }
codereview_cpp_data_3701
&header, RecordBase::m_alloc_ptr, sizeof(SharedAllocationHeader)); Kokkos::fence( "SharedAllocationRecord<Kokkos::CudaSpace, " - "void>::~SharedAllocationRecord(): fence after obtaining label"); label = header.label(); } auto alloc_size = SharedAllocationRecord<void, void>::m_alloc_size; after copying header &header, RecordBase::m_alloc_ptr, sizeof(SharedAllocationHeader)); Kokkos::fence( "SharedAllocationRecord<Kokkos::CudaSpace, " + "void>::~SharedAllocationRecord(): fence after copying header"); label = header.label(); } auto alloc_size = SharedAllocationRecord<void, void>::m_alloc_size;
codereview_cpp_data_3707
QueryString name_editbox; ///< Client name editbox. QueryString filter_editbox; ///< Editbox for filter on servers GUITimer requery_timer; ///< Timer for network requery - bool searched_internet; ///< Did we ever press "Search Internet" button? int lock_offset; ///< Left offset for lock icon. int blot_offset; ///< Left offset for green/yellow/red compatibility icon. This could be named better. Suggesting `query_owner` although that's a bit long. Really maybe `ShowQueryString` should be changed to take a std::function instead of an object. QueryString name_editbox; ///< Client name editbox. QueryString filter_editbox; ///< Editbox for filter on servers GUITimer requery_timer; ///< Timer for network requery int lock_offset; ///< Left offset for lock icon. int blot_offset; ///< Left offset for green/yellow/red compatibility icon.
codereview_cpp_data_3717
*/ #include <gmock/gmock.h> -#include <builders/protobuf/transaction.hpp> #include "framework/batch_helper.hpp" #include "framework/result_fixture.hpp" #include "interfaces/iroha_internal/transaction_batch.hpp" Use quotes instead of angle brackets for project-local includes. */ #include <gmock/gmock.h> + +#include "builders/protobuf/transaction.hpp" #include "framework/batch_helper.hpp" #include "framework/result_fixture.hpp" #include "interfaces/iroha_internal/transaction_batch.hpp"
codereview_cpp_data_3720
auto start_time = std::chrono::steady_clock::now(); // Now generate new data structure feature4, and copy data to the device int nthreads = std::min(omp_get_max_threads(), (int)dense_feature_map_.size() / dword_features_); std::vector<Feature4*> host4_vecs(nthreads); std::vector<boost::compute::buffer> host4_bufs(nthreads); std::vector<Feature4*> host4_ptrs(nthreads); It seems you call ```RawGet``` many times. I think a better solution is use a function like ```CopyTo(buffer)``` to get these bin data by only one function call. auto start_time = std::chrono::steady_clock::now(); // Now generate new data structure feature4, and copy data to the device int nthreads = std::min(omp_get_max_threads(), (int)dense_feature_map_.size() / dword_features_); + nthreads = std::max(nthreads, 1); std::vector<Feature4*> host4_vecs(nthreads); std::vector<boost::compute::buffer> host4_bufs(nthreads); std::vector<Feature4*> host4_ptrs(nthreads);
codereview_cpp_data_3722
const KeyTimeList::value_type timeA = std::get<0>(kfl)->at( id0 ); const KeyTimeList::value_type timeB = std::get<0>(kfl)->at( id1 ); - // do the actual interpolation in double-precision arithmetics - // because it is a bit sensitive to rounding errors. - const double factor = timeB == timeA ? 0. : static_cast<double>( ( time - timeA ) ) / ( timeB - timeA ); const ai_real interpValue = static_cast<ai_real>( valueA + ( valueB - valueA ) * factor ); result[ std::get<2>(kfl) ] = interpValue; Could you please change double to ai_real? const KeyTimeList::value_type timeA = std::get<0>(kfl)->at( id0 ); const KeyTimeList::value_type timeB = std::get<0>(kfl)->at( id1 ); + const ai_real factor = timeB == timeA ? 0. : static_cast<ai_real>( ( time - timeA ) ) / ( timeB - timeA ); const ai_real interpValue = static_cast<ai_real>( valueA + ( valueB - valueA ) * factor ); result[ std::get<2>(kfl) ] = interpValue;
codereview_cpp_data_3727
aOStream << "-ReadX, -RX directory settings.xml Parse Xsens exported files from directory using settingsFile.xml.\n"; aOStream << "-ReadA, -RA datafile.csv settings.xml Parse single csv file provided by APDM using specified settingsFile.xml.\n"; aOStream << "-Calibrate, -C IMUPlacer_setup.xml Place IMUs on the model that is specified in the IMUPlacer_setup.xml file.\n"; - aOStream << " The model is positioned in its default pose, IMUs are then registered to the model according to\n "; aOStream << " their orientations in the first frame of the quaternions file that is specified in IMUPlacer_setup.xml.\n"; aOStream << " The orientations of the IMUs in the quaternions file are assumed to be in the IMU world frame.\n"; aOStream << " The resultant model with IMU frames registered is written to file if output_model_file is specified\n"; There should be a period after "The model is positioned in its default pose" rather than a comma. Otherwise the content looks good to me. aOStream << "-ReadX, -RX directory settings.xml Parse Xsens exported files from directory using settingsFile.xml.\n"; aOStream << "-ReadA, -RA datafile.csv settings.xml Parse single csv file provided by APDM using specified settingsFile.xml.\n"; aOStream << "-Calibrate, -C IMUPlacer_setup.xml Place IMUs on the model that is specified in the IMUPlacer_setup.xml file.\n"; + aOStream << " The model is positioned in its default pose. IMUs are then registered to the model according to\n "; aOStream << " their orientations in the first frame of the quaternions file that is specified in IMUPlacer_setup.xml.\n"; aOStream << " The orientations of the IMUs in the quaternions file are assumed to be in the IMU world frame.\n"; aOStream << " The resultant model with IMU frames registered is written to file if output_model_file is specified\n";
codereview_cpp_data_3739
/ std::accumulate(num_samples_list.begin(), num_samples_list.end(), 0)); - std::cout << "World average " << m->get_name() << " " << mode_string << " " << "objective function : " << avg_obj_fn << std::endl; } I think it's more readable if the output string looks like: ``` Model "gen" (global) training objective function: 12.345 ``` / std::accumulate(num_samples_list.begin(), num_samples_list.end(), 0)); + std::cout << m->get_name() << " global average " << mode_string << " " << "objective function : " << avg_obj_fn << std::endl; }
codereview_cpp_data_3748
std::ostringstream pt; pt << "LatencyTest_"; if (hostname) - { pt << asio::ip::host_name() << "_"; - } pt << pid << "_PUB2SUB"; PubDataparam.topic.topicName = pt.str(); PubDataparam.times.heartbeatPeriod.seconds = 0; Why this new configuration? std::ostringstream pt; pt << "LatencyTest_"; if (hostname) pt << asio::ip::host_name() << "_"; pt << pid << "_PUB2SUB"; PubDataparam.topic.topicName = pt.str(); PubDataparam.times.heartbeatPeriod.seconds = 0;
codereview_cpp_data_3754
ScrollingLines.Line[j].LastWidth = PixLengthLineOut; // while page scrolling this line is right aligned } - if ((PixLengthLineIn > getDisplaySizeSettings(disp_resolution).Width) && (fScrollTime > 0.0f)) { // width of the line > display width -> scroll line ScrollingLines.Line[j].LineContent = ScrollingPages.LineIn[j]; Comparing floats like this is dangerous. Also where `fScrollTime` is used is in a divide, so if it is like 0.0000001, then the value of `dPix` may be just any value as it is only an `unit8_t` So even a value of 0 is possible then. ScrollingLines.Line[j].LastWidth = PixLengthLineOut; // while page scrolling this line is right aligned } + if ((PixLengthLineIn > getDisplaySizeSettings(disp_resolution).Width) && (iScrollTime >= 0)) { // width of the line > display width -> scroll line ScrollingLines.Line[j].LineContent = ScrollingPages.LineIn[j];
codereview_cpp_data_3759
void createDefaultAccount() { CHECK_SUCCESSFUL_RESULT( execute(*mock_command_factory->constructCreateAccount( - "id", domain_id, *pubkey), true)); } Also, I think, they should be renamed to `default_{domain, account}_id` void createDefaultAccount() { CHECK_SUCCESSFUL_RESULT( execute(*mock_command_factory->constructCreateAccount( + name, domain_id, *pubkey), true)); }
codereview_cpp_data_3764
return compressible_types; } -h2o_iovec_t h2o_build_destination(h2o_req_t *req, const char *prefix, size_t prefix_len, int escape) { h2o_iovec_t parts[4]; size_t num_parts = 0; How about renaming `escape` to `use_path_normalized` or something to better indicate that it is a selection between `path` and `path_normalized`? return compressible_types; } +h2o_iovec_t h2o_build_destination(h2o_req_t *req, const char *prefix, size_t prefix_len, int use_path_normalized) { h2o_iovec_t parts[4]; size_t num_parts = 0;
codereview_cpp_data_3768
/* append suffix path and query */ - if (escape || req->res_is_delegated) { /* When proxying, we don't want to modify the input URL, unless the url has been rewritten already */ parts[num_parts++] = h2o_uri_escape(&req->pool, req->path_normalized.base + req->pathconf->path.len, How about using `req->path` instead of `req->input.path` and also removing the check of `req->res_is_delegated` in the if statement above? That way, I assume we can use the unnormalized path for both before and after delegation (note: I believe the proxy handler should use the unnormalized path independent to how the URL is given (e.g. via an HTTP request or via a X-Reproxy-URL header)). /* append suffix path and query */ + if (use_path_normalized) { /* When proxying, we don't want to modify the input URL, unless the url has been rewritten already */ parts[num_parts++] = h2o_uri_escape(&req->pool, req->path_normalized.base + req->pathconf->path.len,
codereview_cpp_data_3775
if (e == API_EOVERQUOTA) { - assert(type != PUT || !timeleft); //only expected overstorage overquota for uploads if (!slot) { bt.backoff(timeleft ? timeleft : NEVER); I think we can check both PUT and GET cases here - some code relies on testing only timeleft, so these two have to match: `assert((type == PUT && !timeleft) || (type == GET && timeleft)); ` if (e == API_EOVERQUOTA) { + assert((type == PUT && !timeleft) || (type == GET && timeleft)); // overstorage only possible for uploads, overbandwidth for downloads if (!slot) { bt.backoff(timeleft ? timeleft : NEVER);
codereview_cpp_data_3790
"Kokkos::Experimental::SYCL::fence: Unnamed Instance Fence"); } void SYCL::impl_static_fence(const std::string& name) { - // guard accessing all_queues Kokkos::Tools::Experimental::Impl::profile_fence_event< Kokkos::Experimental::SYCL>( name, Kokkos::Tools::Experimental::SpecialSynchronizationCases:: GlobalDeviceSynchronization, [&]() { std::lock_guard<std::mutex> lock(Impl::SYCLInternal::mutex); for (auto& queue : Impl::SYCLInternal::all_queues) Impl::SYCLInternal::fence(**queue); ```suggestion [&]() { // guard accessing all_queues std::lock_guard<std::mutex> lock(Impl::SYCLInternal::mutex); ``` and delete above. "Kokkos::Experimental::SYCL::fence: Unnamed Instance Fence"); } void SYCL::impl_static_fence(const std::string& name) { Kokkos::Tools::Experimental::Impl::profile_fence_event< Kokkos::Experimental::SYCL>( name, Kokkos::Tools::Experimental::SpecialSynchronizationCases:: GlobalDeviceSynchronization, [&]() { + // guard accessing all_queues std::lock_guard<std::mutex> lock(Impl::SYCLInternal::mutex); for (auto& queue : Impl::SYCLInternal::all_queues) Impl::SYCLInternal::fence(**queue);
codereview_cpp_data_3791
* @return if number is a factorial, returns true, else false. */ -bool is_factorial(int n) { if (n <= 0) { return false; } - for (int i = 1;; i++) { if (n % i != 0) { break; } wouldn't it be better to use the fixed number type as below? ```suggestion bool is_factorial(uint64_t n) { ``` similarly, the variable `i` on line 20 could probably be `uint32_t`? * @return if number is a factorial, returns true, else false. */ +bool is_factorial(uint64_t n) { if (n <= 0) { return false; } + for (uint32_t i = 1;; i++) { if (n % i != 0) { break; }
codereview_cpp_data_3796
/* Settle for a cipher with a higher required proto version, if it was set */ if (higher_vers_match) { conn->secure.cipher_suite = higher_vers_match; - conn->handshake_params.our_chain_and_key = s2n_get_compatible_cert_chain_and_key(conn, higher_vers_match); return 0; } Is this necessary? Trying to follow the logic, but it looks like `our_chain_and_key` is set with `match` and then `higher_vers_match` is set to `match` so wouldn't `our_chain_and_key` already have a cert set for `higher_vers_match`? /* Settle for a cipher with a higher required proto version, if it was set */ if (higher_vers_match) { conn->secure.cipher_suite = higher_vers_match; + conn->handshake_params.our_chain_and_key = higher_vers_cert; return 0; }
codereview_cpp_data_3810
const auto& stencil = m_stencil[amrlev][cmglev-1]; bool regular_coarsening = true; int idir = 2; - if (amrlev == 0 and cmglev > 0) { regular_coarsening = mg_coarsen_ratio_vec[cmglev-1] == mg_coarsen_ratio; - IntVect ratio = (amrlev > 0) ? IntVect(2) : mg_coarsen_ratio_vec[cmglev-1]; if (ratio[1] == 1) { idir = 1; } else if (ratio[0] == 1) { This is inside `if (amrlev == 0 and ..)` so it's not possible `amrlev > 0`. const auto& stencil = m_stencil[amrlev][cmglev-1]; bool regular_coarsening = true; int idir = 2; + if (cmglev > 0) { regular_coarsening = mg_coarsen_ratio_vec[cmglev-1] == mg_coarsen_ratio; + IntVect ratio = mg_coarsen_ratio_vec[cmglev-1]; if (ratio[1] == 1) { idir = 1; } else if (ratio[0] == 1) {
codereview_cpp_data_3848
case MegaRequest::TYPE_GET_ATTR_NODE: if (mApi[apiIndex].lastError == API_OK) { - mMegaFavNodeList = request->getMegaNodeList()->copy(); } break; } You are accumulating a memory leak here, every time you make a copy, the previous allocated memory is leaked. case MegaRequest::TYPE_GET_ATTR_NODE: if (mApi[apiIndex].lastError == API_OK) { + mMegaFavNodeList.reset(request->getMegaHandleList()->copy()); } break; }
codereview_cpp_data_3853
#include "utils/s2n_random.h" #include "utils/s2n_safety.h" -int s2n_parse_client_hello(struct s2n_connection *conn); - struct s2n_client_hello *s2n_connection_get_client_hello(struct s2n_connection *conn) { if (conn->client_hello.parsed != 1) { return NULL; Let's keep this function static. #include "utils/s2n_random.h" #include "utils/s2n_safety.h" struct s2n_client_hello *s2n_connection_get_client_hello(struct s2n_connection *conn) { if (conn->client_hello.parsed != 1) { return NULL;
codereview_cpp_data_3856
struct wlr_color_config *wlr_color_config_load(const char *icc_profile_path) { assert(icc_profile_path); - if(0 == strlen(icc_profile_path)) { - return NULL; - } - bool can_access = access(icc_profile_path, F_OK) != -1; if (!can_access) { wlr_log(WLR_ERROR, "Unable to access color profile '%s'", icc_profile_path); You're comparing a struct containing a pointer to another struct containing a pointer. This won't ever work. You should compare either the ICC profile bytes, the ICC profile parameters (better) or the colorspace (if provided). struct wlr_color_config *wlr_color_config_load(const char *icc_profile_path) { assert(icc_profile_path); bool can_access = access(icc_profile_path, F_OK) != -1; if (!can_access) { wlr_log(WLR_ERROR, "Unable to access color profile '%s'", icc_profile_path);
codereview_cpp_data_3869
CHECK(printers::json<policy::oneline>(line, json{o})); CHECK_EQUAL(line, "{\"baz\": 4.2}"); MESSAGE("tree policy"); - o = {{"baz", json{4.2}}, - {"x", json{a}}, - {"inner", json{json::object{ - {"a", json{false}}, {"c", json{a}}, {"b", json{42}}}}}}; auto json_tree = R"json({ "baz": 4.2, "x": [ Formatting it like "actual" JSON looks a bit nicer: ``` o = { {"baz", json{4.2}}, {"x", json{a}}, {"inner", json{json::object{ {"a", json{false}}, {"c", json{a}}, {"b", json{42}} ... ``` CHECK(printers::json<policy::oneline>(line, json{o})); CHECK_EQUAL(line, "{\"baz\": 4.2}"); MESSAGE("tree policy"); + o = { + {"baz", json{4.2}}, + {"x", json{a}}, + {"inner", json{json::object{ + {"a", json{false}}, + {"c", json{a}}, + {"b", json{42}}}}}}; auto json_tree = R"json({ "baz": 4.2, "x": [
codereview_cpp_data_3874
{ std::string path = str; - for ( const char sep : { '/', '\\' } ) { - std::replace( path.begin(), path.end(), sep, SEPARATOR ); - } return GetBasename( path ); } Here we're doing double loop while we could run only once: ``` const char sep = ( SEPARATOR == '/' ) ? '\\' : '/'; std::replace( path.begin(), path.end(), sep, SEPARATOR ); ``` because we have to replace only separators which are different from the curent system. { std::string path = str; + std::replace( path.begin(), path.end(), ( SEPARATOR == '/' ) ? '\\' : '/', SEPARATOR ); return GetBasename( path ); }
codereview_cpp_data_3884
finalize_statement(update_writer_last_seq_num_stmt_); int res = sqlite3_close(db_); - if(res != SQLITE_OK) // (0) SQLITE_OK { - logWarning(RTPS_PERSISTENCE, "Database could not be closed. sqlite3_close code: " << res); } db_ = NULL; } I'd make this an ERROR log, as we suspect it is the cause of the issues we are experiencing, and we already saw it may affect the user. finalize_statement(update_writer_last_seq_num_stmt_); int res = sqlite3_close(db_); + if (res != SQLITE_OK) // (0) SQLITE_OK { + logError(RTPS_PERSISTENCE, "Database could not be closed. sqlite3_close code: " << res); } db_ = NULL; }
codereview_cpp_data_3892
.append("page_size", std::to_string(pageSize())); auto first_tx_hash = firstTxHash(); if (first_tx_hash) { - pretty_builder = std::move( - pretty_builder.append("first_tx_hash", first_tx_hash->toString())); } return pretty_builder.finalize(); } String builder is mutable, so there is no need to reassign it. `append` should be enough. .append("page_size", std::to_string(pageSize())); auto first_tx_hash = firstTxHash(); if (first_tx_hash) { + pretty_builder.append("first_tx_hash", first_tx_hash->toString()); } return pretty_builder.finalize(); }
codereview_cpp_data_3897
std::unique_ptr<callback_base> build_print_model_description_callback_from_pbuf( - const google::protobuf::Message& proto_msg, const std::shared_ptr<lbann_summary>&) { return make_unique<print_model_description>(); } `proto_msg` is unused. ```suggestion const google::protobuf::Message&, const std::shared_ptr<lbann_summary>&) { ``` std::unique_ptr<callback_base> build_print_model_description_callback_from_pbuf( + const google::protobuf::Message&, const std::shared_ptr<lbann_summary>&) { return make_unique<print_model_description>(); }
codereview_cpp_data_3907
ListSnapshotRestorationsResponsePB rest_resp; RETURN_NOT_OK(master_backup_proxy_->ListSnapshotRestorations(rest_req, &rest_resp, &rpc)); - if (!rest_resp.restorations_size()) { cout << "No snapshot restorations" << endl; } else if (!show_restored) { cout << "Not show fully RESTORED entries" << endl; Here I think it's better to write `if (rest_resp.restorations_size() == 0) {` (just for better readability) ListSnapshotRestorationsResponsePB rest_resp; RETURN_NOT_OK(master_backup_proxy_->ListSnapshotRestorations(rest_req, &rest_resp, &rpc)); + if (rest_resp.restorations_size() == 0) { cout << "No snapshot restorations" << endl; } else if (!show_restored) { cout << "Not show fully RESTORED entries" << endl;
codereview_cpp_data_3909
shared_model::interface::permissions::Grantable permission) { const auto perm_str = shared_model::interface::GrantablePermissionSet({permission}) - .to_string(); auto query = (boost::format( "INSERT INTO account_has_grantable_permissions as " "has_perm(permittee_account_id, account_id, permission) VALUES " "(%1%, %2%, %3%) ON CONFLICT (permittee_account_id, account_id) " "DO UPDATE SET permission=(SELECT has_perm.permission | %3% " - "WHERE has_perm.permission & %3% <> %3%);") % transaction_.quote(permittee_account_id) % transaction_.quote(account_id) % transaction_.quote(perm_str)) .str(); Better to add parenthesis so order of operations is not confusing shared_model::interface::permissions::Grantable permission) { const auto perm_str = shared_model::interface::GrantablePermissionSet({permission}) + .toBitstring(); auto query = (boost::format( "INSERT INTO account_has_grantable_permissions as " "has_perm(permittee_account_id, account_id, permission) VALUES " "(%1%, %2%, %3%) ON CONFLICT (permittee_account_id, account_id) " + // SELECT will end up with a error, if the permission exists "DO UPDATE SET permission=(SELECT has_perm.permission | %3% " + "WHERE (has_perm.permission & %3%) <> %3%);") % transaction_.quote(permittee_account_id) % transaction_.quote(account_id) % transaction_.quote(perm_str)) .str();
codereview_cpp_data_3913
if (nvirial) { vptr = new double*[nvirial]; nvirial = 0; - if (hybridpairflag && force->pair) { PairHybrid *ph = (PairHybrid *) force->pair; ph->no_virial_fdotr_compute = 1; - vptr[nvirial++] = hybridpair->virial; } if (pairflag && force->pair) vptr[nvirial++] = force->pair->virial; if (bondflag && force->bond) vptr[nvirial++] = force->bond->virial; this seems problematic, what if this compute goes away (uncompute), then the setting in PH will not be un-done better way to do this might be, PH in its init_style() sets this no_virial flag in its usual way (currently in flags()), but also loops over computes looking to see if any (like this one) sets a flag that tells it to override the setting it would normally make if (nvirial) { vptr = new double*[nvirial]; nvirial = 0; + if (pairhybridflag && force->pair) { PairHybrid *ph = (PairHybrid *) force->pair; ph->no_virial_fdotr_compute = 1; + vptr[nvirial++] = pairhybrid->virial; } if (pairflag && force->pair) vptr[nvirial++] = force->pair->virial; if (bondflag && force->bond) vptr[nvirial++] = force->bond->virial;
codereview_cpp_data_3918
Node *n = client->nodebyhandle(h); if (n) { - n->setpubliclink(ph, 0, ets, false); n->changed.publiclink = true; client->notifynode(n); } We should set a valid creation timestamp at completion of this command. Use `time(nullptr)` instead of `0`. The small offset between the reception of the response and the actual creation ts is negligible and the user will not notice (we don't even show the seconds). ```suggestion n->setpubliclink(ph, time(nullptr), ets, false); ``` Node *n = client->nodebyhandle(h); if (n) { + n->setpubliclink(ph, time(nullptr), ets, false); n->changed.publiclink = true; client->notifynode(n); }
codereview_cpp_data_3923
return 0; } -static int validate_file(Plugin *handle, Key *parentKey) { iconv_t conv = iconv_open(getFrom(handle), getFrom(handle)); if(conv == (iconv_t)(-1)) please use camelCase return 0; } +static int validateFile(Plugin *handle, Key *parentKey) { iconv_t conv = iconv_open(getFrom(handle), getFrom(handle)); if(conv == (iconv_t)(-1))
codereview_cpp_data_3927
bool almostEqual = true; for(int i = 0; i < AMREX_SPACEDIM && almostEqual; ++i) { - almostEqual = almostEqual && std::abs(box1.lo(i) - box2.lo(i)) < eps; - almostEqual = almostEqual && std::abs(box1.hi(i) - box2.hi(i)) < eps; } return almostEqual; } Should it be `<=` instead of `<`? bool almostEqual = true; for(int i = 0; i < AMREX_SPACEDIM && almostEqual; ++i) { + almostEqual = almostEqual && std::abs(box1.lo(i) - box2.lo(i)) <= eps; + almostEqual = almostEqual && std::abs(box1.hi(i) - box2.hi(i)) <= eps; } return almostEqual; }
codereview_cpp_data_3929
if(sc->data[SC_DEFENDER] && #ifdef RENEWAL ((flag&(BF_LONG|BF_WEAPON)) == (BF_LONG|BF_WEAPON) || skill_id == CR_ACIDDEMONSTRATION)) - damage = damage * ( 100 - sc->data[SC_DEFENDER]->val2 ) / 100; #else (flag&(BF_LONG|BF_WEAPON)) == (BF_LONG|BF_WEAPON)) // In pre-re Defender doesn't reduce damage from Acid Demonstration damage = damage * ( 100 - sc->data[SC_DEFENDER]->val2 ) / 100; -#endif - #ifndef RENEWAL if(sc->data[SC_GS_ADJUSTMENT] && (flag&(BF_LONG|BF_WEAPON)) == (BF_LONG|BF_WEAPON)) why not make this common, and only include condition part in #ifdef ? if(sc->data[SC_DEFENDER] && #ifdef RENEWAL ((flag&(BF_LONG|BF_WEAPON)) == (BF_LONG|BF_WEAPON) || skill_id == CR_ACIDDEMONSTRATION)) #else (flag&(BF_LONG|BF_WEAPON)) == (BF_LONG|BF_WEAPON)) // In pre-re Defender doesn't reduce damage from Acid Demonstration +#endif damage = damage * ( 100 - sc->data[SC_DEFENDER]->val2 ) / 100; + #ifndef RENEWAL if(sc->data[SC_GS_ADJUSTMENT] && (flag&(BF_LONG|BF_WEAPON)) == (BF_LONG|BF_WEAPON))
codereview_cpp_data_3957
#include <OpenSim/Common/Storage.h> #include "ControlSet.h" #include "ControlLinear.h" -// TODO #include <OpenSim/Simulation/SimbodyEngine/Constraint.h> Go ahead and remove this. I cannot imagine why the `ControlSet` needs to know about `Constraints`. #include <OpenSim/Common/Storage.h> #include "ControlSet.h" #include "ControlLinear.h"
codereview_cpp_data_3959
void SceneCheckAPIChange::installDefaultChangeSets() { addHookInChangeSet("17.06", [](Base* o){ - if(o->getClassName() == "RestShapeSpringsForceField" && o->findLink("external_rest_shape")->getSize() != 0) - msg_warning(o) << "RestShapeSpringsForceField have changed since 17.06. The parameter 'external_rest_shape' is now a Link. To fix your scene you need to add and '@' in front of the provided path. See PR#315" ; }) ; addHookInChangeSet("17.06", [](Base* o){ This is messing with my brain again >< What happens if there is no `external_rest_shape` parameter in my RestShapeSpringsForceField? void SceneCheckAPIChange::installDefaultChangeSets() { addHookInChangeSet("17.06", [](Base* o){ + if(o->getClassName() == "RestShapeSpringsForceField" && o->findLink("external_rest_shape") ) + { + if( o->findLink("external_rest_shape")->getSize() != 0) + msg_warning(o) << "RestShapeSpringsForceField have changed since 17.06. The parameter 'external_rest_shape' is now a Link. To fix your scene you need to add and '@' in front of the provided path. See PR#315" ; + } }) ; addHookInChangeSet("17.06", [](Base* o){
codereview_cpp_data_3990
delete [] set; if (group) { - std::string cmd = fmt::format("{} delete",master_group); - group->assign(cmd); if (stabilization_flag == 1) { - cmd = fmt::format("{} delete",exclude_group); - group->assign(cmd); delete [] exclude_group; } } This could be just one line: `group->assign(fmt::format("{} delete",master_group));` and the same for `group->assign(fmt::format("{} delete",exclude_group));` An alternate way to do the same - and perhaps more readable since it retains the order of arguments - would be: `group->assign(std::string(master_group) + " delete");` and `group->assign(std::string(exclude_group) + " delete");` delete [] set; if (group) { + group->assign(std::string(master_group) + " delete"); if (stabilization_flag == 1) { + group->assign(std::string(exclude_group) + " delete"); delete [] exclude_group; } }
codereview_cpp_data_4005
} } - LOG_INFO( "Bounded query read " << (boundedNodeCount + boundedWayCount + boundedRelationCount) << " total elements."); LOG_VARD(boundedNodeCount); Still want this at INFO level? } } + LOG_DEBUG( "Bounded query read " << (boundedNodeCount + boundedWayCount + boundedRelationCount) << " total elements."); LOG_VARD(boundedNodeCount);
codereview_cpp_data_4009
return ihipLogStatus(hipErrorLaunchFailure); } - uint impCoopArg = 1; void* impCoopParams[1]; impCoopParams[0] = &impCoopArg; The pointer value itself is supposed to be 1 for the single grid case, not a pointer to 1. return ihipLogStatus(hipErrorLaunchFailure); } + size_t impCoopArg = 1; void* impCoopParams[1]; impCoopParams[0] = &impCoopArg;
codereview_cpp_data_4018
return false; } -bool SecondarySkillsBar::ActionBarCursor( const fheroes2::Point &, Skill::Secondary & skill, const fheroes2::Rect & ) { if ( skill.isValid() ) { msg = _( "View %{skill} Info" ); :warning: **readability\-named\-parameter** :warning: all parameters should be named in a function ```suggestion bool SecondarySkillsBar::ActionBarCursor( const fheroes2::Point & /*unused*/, Skill::Secondary & skill, const fheroes2::Rect & /*unused*/) ``` return false; } +bool SecondarySkillsBar::ActionBarCursor( const fheroes2::Point & /*unused*/, Skill::Secondary & skill, const fheroes2::Rect & /*unused*/) { if ( skill.isValid() ) { msg = _( "View %{skill} Info" );
codereview_cpp_data_4027
return NULL; self = binding_func->self; -#if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) - Py_INCREF(self); -#endif Py_INCREF(self); PyTuple_SET_ITEM(new_args, 0, self); - -#if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) - Py_XDECREF(self); self = NULL; -#endif for (i = 0; i < argc; i++) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS This seems redundant. Just remove the first incref above. return NULL; self = binding_func->self; + Py_INCREF(self); PyTuple_SET_ITEM(new_args, 0, self); self = NULL; for (i = 0; i < argc; i++) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS
codereview_cpp_data_4029
os_constructed (GObject *object) { RpmostreedOS *self = RPMOSTREED_OS (object); - GError *error = NULL; self->authority = polkit_authority_get_sync (NULL, &error); if (self->authority == NULL) { - g_error ("Can't get polkit authority: %s", error->message); } self->signal_id = g_signal_connect (rpmostreed_sysroot_get (), "updated", I tend to avoid `g_error()` in general because few conditions where one typically finds it necessitate dumping core. That's true here; if we fail to talk to polkitd, it's highly unlikely that a core dump from rpm-ostreed is going to be useful to operators. Hence I'd prefer `errx()` in this case. (And in cases where we *do* want a core dump, that's `g_assert()`) os_constructed (GObject *object) { RpmostreedOS *self = RPMOSTREED_OS (object); + g_autoptr(GError) error = NULL; self->authority = polkit_authority_get_sync (NULL, &error); if (self->authority == NULL) { + errx (1, "Can't get polkit authority: %s", error->message); } self->signal_id = g_signal_connect (rpmostreed_sysroot_get (), "updated",
codereview_cpp_data_4030
std::vector<std::string> response_header_filters; int c; pid_t h2o_pid = -1; - while ((c = getopt(argc, argv, "hdp:qt:s:w:")) != -1) { switch (c) { case 'p': h2o_pid = atoi(optarg); The `q` seems not to be used. A typo? std::vector<std::string> response_header_filters; int c; pid_t h2o_pid = -1; + while ((c = getopt(argc, argv, "hdp:t:s:w:")) != -1) { switch (c) { case 'p': h2o_pid = atoi(optarg);
codereview_cpp_data_4032
, backsf( sz.w, sz.h ) { for ( u32 dw = DWELLING_MONSTER1; dw <= DWELLING_MONSTER6; dw <<= 1 ) - content.emplace_back( DwellingItem( castle, dw ) ); SetContent( content ); This applies to every `emplace_back` occurence: please try to remove the name of the class from the call making `emplace_back` to have arguments for its constructor. For example, `content.emplace_back( castle, dw );`. In this case the object will be constructed directly within a container. , backsf( sz.w, sz.h ) { for ( u32 dw = DWELLING_MONSTER1; dw <= DWELLING_MONSTER6; dw <<= 1 ) + content.emplace_back( castle, dw ); SetContent( content );
codereview_cpp_data_4034
cursor.Show(); } - ListFiles list1; - list1.ReadDir( Settings::GetSaveDir(), ".sav", false ); - // mainmenu loop while ( le.HandleEvents() ) { for ( u32 i = 0; i < ARRAY_COUNT( buttons ); i++ ) { I'm suggesting to put this code right in else if condition because files could be moved/added. No hard to this as it doesn't affect the performance visibly. cursor.Show(); } // mainmenu loop while ( le.HandleEvents() ) { for ( u32 i = 0; i < ARRAY_COUNT( buttons ); i++ ) {
codereview_cpp_data_4052
return false; } - enable(); - mp_sync = new DSClientEvent(this, TimeConv::Duration_t2MilliSecondsDouble(m_discovery.discovery_config.discoveryServer_client_syncperiod)); mp_sync->restart_timer(); Shouldn't this be done after initialization of WLP? return false; } mp_sync = new DSClientEvent(this, TimeConv::Duration_t2MilliSecondsDouble(m_discovery.discovery_config.discoveryServer_client_syncperiod)); mp_sync->restart_timer();
codereview_cpp_data_4070
}; assert(graph::isBipartite(graph_not_bipartite) == false); /// check whether the above defined graph is indeed bipartite } /** * @brief Main function ```suggestion assert(graph::isBipartite(graph_not_bipartite) == false); /// check whether the above defined graph is indeed bipartite std::cout << "All tests have successfully passed!\n"; ``` }; assert(graph::isBipartite(graph_not_bipartite) == false); /// check whether the above defined graph is indeed bipartite + std::cout << "All tests have successfully passed!\n"; } /** * @brief Main function
codereview_cpp_data_4079
<h1>Error 503 Backend is unhealthy</h1> <p>Backend is unhealthy</p> <h3>Guru Mediation:</h3> - <p>Details: cache-sea4470-SEA 1645537672 2783367812</p> <hr> <p>Varnish cache server</p> </body> At some point I would like to detach this somewhat from the backend as well, but for now it's fine. <h1>Error 503 Backend is unhealthy</h1> <p>Backend is unhealthy</p> <h3>Guru Mediation:</h3> + <p>Details: cache-sea4455-SEA 1645537672 2776811606</p> <hr> <p>Varnish cache server</p> </body>
codereview_cpp_data_4080
fd, host, port); /* - * Prepare a timeout using select(2): we could use our own * event loop mechanism for this, but it will require an - * extra file descriptor, the select(2) call is straightforward * for this use case. */ FD_ZERO(&wait_set); we will need an approach for other OSes... (Windows and potentially MacOS) fd, host, port); /* + * Prepare a timeout using poll(2): we could use our own * event loop mechanism for this, but it will require an + * extra file descriptor, the poll(2) call is straightforward * for this use case. */ FD_ZERO(&wait_set);
codereview_cpp_data_4082
double value = castle->getBuildingValue() * 150.0 + 3000; // If the castle is defenseless if ( castle->GetActualArmy().GetStrength() <= 0 ) - value += 5; return value; } } I'd say that this value is too small. Why don't we add some percentage instead? For example, 50%. double value = castle->getBuildingValue() * 150.0 + 3000; // If the castle is defenseless if ( castle->GetActualArmy().GetStrength() <= 0 ) + value *= 1.25; return value; } }
codereview_cpp_data_4084
return comp; } -int MegaApiImpl::nodeNaturalComparatorASC(Node *i, Node *j) { int r = naturalsorting_compare(i->displayname(), j->displayname()); if (r < 0 || (!r && i < j)) We should be able to still return `bool`, shouldn't we? return comp; } +bool MegaApiImpl::nodeNaturalComparatorASC(Node *i, Node *j) { int r = naturalsorting_compare(i->displayname(), j->displayname()); if (r < 0 || (!r && i < j))
codereview_cpp_data_4103
return uniq; } -// Get Tile metadata field #1 (used for things like monster count of resource amount) int Maps::Tiles::GetQuantity1( void ) const { return quantity1; Please replace word **of** by **or**. return uniq; } +// Get Tile metadata field #1 (used for things like monster count or resource amount) int Maps::Tiles::GetQuantity1( void ) const { return quantity1;
codereview_cpp_data_4105
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; } It's unsigned, no need in that fix std::cout << "Wrong format for amount" << std::endl; return nullptr; } + if (precision.value() > 255) { std::cout << "Too big precision (should be between 0 and 256)" << std::endl; return nullptr; }
codereview_cpp_data_4122
std::vector<std::string> badFactors; - unsigned long cutOffIdx = topFactors.size() - (unsigned int)((double)topFactors.size() * retrain); std::multimap<double, std::string> sortedFactors; std::multimap<double, std::string>::iterator mMapItr; Again the variable's data type is correct, the result of the calculation needs to be cast to `unsigned int` instead of being an `unsigned long`. std::vector<std::string> badFactors; + unsigned int cutOffIdx = topFactors.size() - (unsigned int)((double)topFactors.size() * retrain); std::multimap<double, std::string> sortedFactors; std::multimap<double, std::string>::iterator mMapItr;
codereview_cpp_data_4127
#include "mega/filesystem.h" #include <iomanip> -#include <locale> -#include <codecvt> -#include <string> #if defined(_WIN32) && defined(_MSC_VER) #include <sys/timeb.h> These should not be needed by the new code changes. #include "mega/filesystem.h" #include <iomanip> #if defined(_WIN32) && defined(_MSC_VER) #include <sys/timeb.h>
codereview_cpp_data_4128
{ uint8_t renegotiation_info_scsv[S2N_TLS_CIPHER_SUITE_LEN] = { TLS_EMPTY_RENEGOTIATION_INFO_SCSV }; struct s2n_cipher_suite *higher_vers_match = NULL; /* RFC 7507 - If client is attempting to negotiate a TLS Version that is lower than the highest supported server * version, and the client cipher list contains TLS_FALLBACK_SCSV, then the server must abort the connection since nitpick: this function is setting the cipher and the cert. Is there a better name that could indicate we're doing both? It makes the code in s2n_process_client_hello a little more readable { uint8_t renegotiation_info_scsv[S2N_TLS_CIPHER_SUITE_LEN] = { TLS_EMPTY_RENEGOTIATION_INFO_SCSV }; struct s2n_cipher_suite *higher_vers_match = NULL; + struct s2n_cert_chain_and_key *higher_vers_cert = NULL; /* RFC 7507 - If client is attempting to negotiate a TLS Version that is lower than the highest supported server * version, and the client cipher list contains TLS_FALLBACK_SCSV, then the server must abort the connection since
codereview_cpp_data_4133
statecacheadd(l); if (isnetwork && l->type == FILENODE) { LOG_debug << "Queueing extra fs notification for modified file"; I think we should replace this with `fa.reset()` to ensure fa is deleted before calling `notify` statecacheadd(l); + fa.reset(); + if (isnetwork && l->type == FILENODE) { LOG_debug << "Queueing extra fs notification for modified file";
codereview_cpp_data_4156
cout << out2.getName() <<"|"<< out2.getTypeName() <<"|"<< out2.getValueAsString(s) << endl; cout << out3.getName() <<"|"<< out3.getTypeName() <<"|"<< out3.getValueAsString(s) << endl; - bar.realizeAcceleration(s); cout << out4.getName() <<"|"<< out4.getTypeName() <<"|"<< out4.getValueAsString(s) << endl; cout << out5.getName() <<"|"<< out5.getTypeName() <<"|"<< out5.getValueAsString(s) << endl; //viz.report(s); - foo.realizeReport(s); cout << "foo.input1 = " << foo.getInputValue<double>(s, "input1") << endl; } Better the way it was: `system.realize(s, Stage::Acceleration);`. cout << out2.getName() <<"|"<< out2.getTypeName() <<"|"<< out2.getValueAsString(s) << endl; cout << out3.getName() <<"|"<< out3.getTypeName() <<"|"<< out3.getValueAsString(s) << endl; + system.realize(s, Stage::Acceleration); cout << out4.getName() <<"|"<< out4.getTypeName() <<"|"<< out4.getValueAsString(s) << endl; cout << out5.getName() <<"|"<< out5.getTypeName() <<"|"<< out5.getValueAsString(s) << endl; //viz.report(s); + system.realize(s, Stage::Report); cout << "foo.input1 = " << foo.getInputValue<double>(s, "input1") << endl; }
codereview_cpp_data_4159
namespace lbann { namespace callback { -void replace_weights::setup(model *m, const std::string& trainer_name) { auto const layers = m->get_layers(); m_src_layers = select_things_by_name(layers, m_src_layer_names); m_dst_layers = select_things_by_name(layers, m_dst_layer_names); ```suggestion void replace_weights::setup(model *m, const std::string&) { ``` namespace lbann { namespace callback { +void replace_weights::setup(model *m, const std::string&) { auto const layers = m->get_layers(); m_src_layers = select_things_by_name(layers, m_src_layer_names); m_dst_layers = select_things_by_name(layers, m_dst_layer_names);
codereview_cpp_data_4161
} //_____________________________________________________________________________ /** - * Get the stress of the force (using the actuation signal). - * * @return Stress. */ double CoordinateActuator::getStress( const SimTK::State& s) const Could we change this to `This is the force or torque provided by this actuator divided by its optimal force.` Actuation `signal` can get confusing with Controller's, which send control signals. So I think we might should avoid using `actuation` with `signal`. } //_____________________________________________________________________________ /** + * Get the stress of the force. This would be the force or torque provided by + * this actuator divided by its optimal force. * @return Stress. */ double CoordinateActuator::getStress( const SimTK::State& s) const
codereview_cpp_data_4181
} CaffeNet(string param_file, string pretrained_param_file) { - CheckFile(param_file); CheckFile(pretrained_param_file); - net_.reset(new Net<float>(param_file)); net_->CopyTrainedLayersFrom(pretrained_param_file); } Is this right? This looks like part of a previous commit being accidentally reverted. } CaffeNet(string param_file, string pretrained_param_file) { + Init(param_file); CheckFile(pretrained_param_file); net_->CopyTrainedLayersFrom(pretrained_param_file); }
codereview_cpp_data_4182
if ( interface ) { interface->RedrawActionSpellCastPart1( spell, dst, current_commander, targets ); - std::for_each( resistTargets.begin(), resistTargets.end(), - [&playResistSound, this]( TargetInfo & target ) { interface->RedrawActionResistSpell( *target.defender, playResistSound ); } ); } TargetsApplySpell( current_commander, spell, targets ); We could write without iterators and labda function: ``` for ( const TargetInfo & target : resistTargets ) { interface->RedrawActionResistSpell( *target.defender, playResistSound ); } ``` if ( interface ) { interface->RedrawActionSpellCastPart1( spell, dst, current_commander, targets ); + for ( const TargetInfo & target : resistTargets ) { + interface->RedrawActionResistSpell( *target.defender, playResistSound ); + } } TargetsApplySpell( current_commander, spell, targets );
codereview_cpp_data_4183
#include <set> #ifdef VITA -#include <SDL.h> #endif namespace Why do we need this change? #include <set> #ifdef VITA +#include <vita2d.h> #endif namespace
codereview_cpp_data_4193
{ // Create a committer and recursively delete all the associated LocalNodes, and their associated transfer and file objects. DBTableTransactionCommitter committer(client->tctable); localroot.reset(); } ```suggestion // Create a committer and recursively delete all the associated LocalNodes, and their associated transfer and file objects. // If any have transactions in progress, the committer will ensure we update the transfer database in an efficient single commit. ``` { // Create a committer and recursively delete all the associated LocalNodes, and their associated transfer and file objects. + // If any have transactions in progress, the committer will ensure we update the transfer database in an efficient single commit. DBTableTransactionCommitter committer(client->tctable); localroot.reset(); }
codereview_cpp_data_4212
#ifdef ENABLE_SYNC p->Add(exec_sync, sequence(text("sync"), opt(either(sequence(localFSPath(), remoteFSPath(client, &cwd, "dst")), param("cancelslot"))))); p->Add(exec_syncconfig, sequence(text("syncconfig"), opt(sequence(param("type (TWOWAY/UP/DOWN)"), opt(sequence(param("syncDeletions (ON/OFF)"), param("forceOverwrite (ON/OFF)"))))))); - p->Add(exec_backupcentre, sequence(text("backupcentre"))); #endif p->Add(exec_export, sequence(text("export"), remoteFSPath(client, &cwd), opt(either(flag("-writable"), param("expiretime"), text("del"))))); p->Add(exec_share, sequence(text("share"), opt(sequence(remoteFSPath(client, &cwd), opt(sequence(contactEmail(client), opt(either(text("r"), text("rw"), text("full"))), opt(param("origemail")))))))); Perhaps, and just for testing, it would be good to implement the `backupcenter -del <backup_id>` that calls the `CommandBackupRemove` :thinking: In my case, I already have a testing account with 15 backups registered, which I don't have locally configured anymore. Also, in the future, both the API and the user will be able to remove orphaned ids (not soon, but considered for phase 2, probably with some strong checks beforehand, to avoid removing live backups). #ifdef ENABLE_SYNC p->Add(exec_sync, sequence(text("sync"), opt(either(sequence(localFSPath(), remoteFSPath(client, &cwd, "dst")), param("cancelslot"))))); p->Add(exec_syncconfig, sequence(text("syncconfig"), opt(sequence(param("type (TWOWAY/UP/DOWN)"), opt(sequence(param("syncDeletions (ON/OFF)"), param("forceOverwrite (ON/OFF)"))))))); + p->Add(exec_backupcentre, sequence(text("backupcentre"), opt(sequence(flag("-del"), param("backup_id"))))); #endif p->Add(exec_export, sequence(text("export"), remoteFSPath(client, &cwd), opt(either(flag("-writable"), param("expiretime"), text("del"))))); p->Add(exec_share, sequence(text("share"), opt(sequence(remoteFSPath(client, &cwd), opt(sequence(contactEmail(client), opt(either(text("r"), text("rw"), text("full"))), opt(param("origemail"))))))));
codereview_cpp_data_4218
{ if (force->bond == NULL) error->all(FLERR,"No bond style is defined for compute bond/local"); - if (comm->ghost_velocity == 0) - error->all(FLERR,"Compute bond/local requires ghost atoms store velocity"); // do initial memory allocation so that memory_usage() is correct @efremdan1 This test should only be made, if the user requested a property requiring ghost velocities. For just potential energy or force, ghost velocities are not needed. { if (force->bond == NULL) error->all(FLERR,"No bond style is defined for compute bond/local"); // do initial memory allocation so that memory_usage() is correct
codereview_cpp_data_4224
} } - // Set environment file - SystemInfo::set_environment_file(); - // Create the server int return_value = 0; Participant* pServer = Domain::createParticipant(*att, nullptr); Perhaps we should move this inside `Domain::createParticipant` } } // Create the server int return_value = 0; Participant* pServer = Domain::createParticipant(*att, nullptr);
codereview_cpp_data_4226
void MegaApiImpl::setUserAlias(MegaHandle uh, const char *alias, MegaRequestListener *listener) { MegaRequestPrivate *request = new MegaRequestPrivate(MegaRequest::TYPE_SET_ATTR_USER, listener); - unique_ptr<MegaStringMap> stringMap(new MegaStringMapPrivate()); - stringMap->set(Base64Str<MegaClient::USERHANDLE>(uh), alias ? alias : ""); - request->setMegaStringMap(stringMap.get()); request->setParamType(MegaApi::USER_ATTR_ALIAS); request->setNodeHandle(uh); request->setText(alias); Good catch! Actually, the old declaration of the `stringMap` variable should result in a compilation error. We should define an default ctor as protected, to avoid this kind of issues. Please, add it to every public object that provides a `createInstance()` method, since those are the risky ones (for the other types, it's always the SDK who creates the private object and provides it to the app via a pointer to the public object). However, in this case, the best would be to declare the variable in the stack, avoiding more heap activity: ```suggestion MegaStringMapPrivate stringMap; ``` void MegaApiImpl::setUserAlias(MegaHandle uh, const char *alias, MegaRequestListener *listener) { MegaRequestPrivate *request = new MegaRequestPrivate(MegaRequest::TYPE_SET_ATTR_USER, listener); + MegaStringMapPrivate stringMap; + stringMap.set(Base64Str<MegaClient::USERHANDLE>(uh), alias ? alias : ""); + request->setMegaStringMap(&stringMap); request->setParamType(MegaApi::USER_ATTR_ALIAS); request->setNodeHandle(uh); request->setText(alias);
codereview_cpp_data_4242
exit(EXIT_FAILURE); } - if (*my_args.argv == NULL) { ERROR("A command to execute in the new namespace is required"); exit(EXIT_FAILURE); } Should be `if (!*my_args.argv)` :) exit(EXIT_FAILURE); } + if (!*my_args.argv) { ERROR("A command to execute in the new namespace is required"); exit(EXIT_FAILURE); }
codereview_cpp_data_4244
BUILDIN_DEF(npcshopattach,"s?"), BUILDIN_DEF(equip,"i"), BUILDIN_DEF(autoequip,"ii"), - BUILDIN_DEF(equip2,"iiiiiii?"), BUILDIN_DEF(setbattleflag,"si"), BUILDIN_DEF(getbattleflag,"s"), BUILDIN_DEF(setitemscript,"is?"), //Set NEW item bonus script. Lupus There's a leftover `?` here, you forgot it when removing the account id parameter. Once this is removed, I believe the PR is ready to be merged :3 BUILDIN_DEF(npcshopattach,"s?"), BUILDIN_DEF(equip,"i"), BUILDIN_DEF(autoequip,"ii"), + BUILDIN_DEF(equip2,"iiiiiii"), BUILDIN_DEF(setbattleflag,"si"), BUILDIN_DEF(getbattleflag,"s"), BUILDIN_DEF(setitemscript,"is?"), //Set NEW item bonus script. Lupus
codereview_cpp_data_4252
}; output->win = xcb_generate_id(x11->xcb_conn); xcb_create_window(x11->xcb_conn, XCB_COPY_FROM_PARENT, output->win, - x11->screen->root, wlr_output->width, wlr_output->height, 1024, 768, 1, XCB_WINDOW_CLASS_INPUT_OUTPUT, x11->screen->root_visual, mask, values); output->surf = wlr_egl_create_surface(&x11->egl, &output->win); The two values that were previously `0, 0` are x and y, I think those should remain 0. The two values that are `1024, 768` are the window size, which should be set to `wlr_output->{width,height}`. }; output->win = xcb_generate_id(x11->xcb_conn); xcb_create_window(x11->xcb_conn, XCB_COPY_FROM_PARENT, output->win, + x11->screen->root, 0, 0, wlr_output->width, wlr_output->height, 1, XCB_WINDOW_CLASS_INPUT_OUTPUT, x11->screen->root_visual, mask, values); output->surf = wlr_egl_create_surface(&x11->egl, &output->win);
codereview_cpp_data_4253
Point heroAnimationOffset; int heroAnimationSpriteId = 0; - bool isCursorOverButtons = le.MouseCursor( buttonsArea.GetRect() ); // startgame loop while ( Game::CANCEL == res ) { Please assign this variable to false. There is no way to have a case when we start a game with pressed buttons. Point heroAnimationOffset; int heroAnimationSpriteId = 0; + bool isCursorOverButtons = false; // startgame loop while ( Game::CANCEL == res ) {
codereview_cpp_data_4257
* Unit tests * @rerturns none */ -void tests() { /** * _ 3 _ * / | \ Let us make the test functions static. Otherwise, it seems that the doxygen is considering them global functions and hence leading to conflicts. ```suggestion static void tests() { ``` * Unit tests * @rerturns none */ +static void tests() { /** * _ 3 _ * / | \
codereview_cpp_data_4260
#include "random_mars.h" #include "respa.h" #include "update.h" -#include "compute.h" -#include "group.h" using namespace LAMMPS_NS; using namespace FixConst; I don't see where compute.h would need to be included here. #include "random_mars.h" #include "respa.h" #include "update.h" using namespace LAMMPS_NS; using namespace FixConst;
codereview_cpp_data_4268
void PairQUIP::settings(int narg, char **arg) { if (narg != 0) error->all(FLERR,"Illegal pair_style command"); - if (strncmp(force->pair->style,"hybrid",6) == 0) - error->all(FLERR,"Pair style quip is not compatible with hybrid styles"); } /* ---------------------------------------------------------------------- Is there a specific reason for this? I've been using quip potentials as part of a `hybrid/overlay` pair style without any apparent problems. void PairQUIP::settings(int narg, char **arg) { if (narg != 0) error->all(FLERR,"Illegal pair_style command"); + if (strcmp(force->pair_style,"hybrid") == 0) + error->all(FLERR,"Pair style quip is only compatible with hybrid/overlay"); + + // check if linked to the correct QUIP library API version + // as of 2017-07-19 this is API_VERSION 1 + if (quip_lammps_api_version() != 1) + error->all(FLERR,"QUIP LAMMPS wrapper API version is not compatible " + "with this version of LAMMPS"); } /* ----------------------------------------------------------------------
codereview_cpp_data_4281
template <typename Dtype> void PoolingLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { - PoolingParameter pool_param = this->layer_param_.pooling_param(); const Dtype* bottom_data = bottom[0]->cpu_data(); Dtype* top_data = top[0]->mutable_cpu_data(); const int top_count = top[0]->count(); How about, instead of reading the param every time, just add a class member variable to hold the value of the flag, and just set it once during `LayerSetUp`? template <typename Dtype> void PoolingLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->cpu_data(); Dtype* top_data = top[0]->mutable_cpu_data(); const int top_count = top[0]->count();
codereview_cpp_data_4283
XS(XS_Client_GetAAEXPModifier) { dXSARGS; if (items != 2) - Perl_croak(aTHX_ "Usage: Client::GetAAEXPModifier(THIS, [uint32 zone_id])"); { Client* THIS; double aa_modifier = 1.0f; Unneeded brackets around `[uint32 zone_id]` in the croak message XS(XS_Client_GetAAEXPModifier) { dXSARGS; if (items != 2) + Perl_croak(aTHX_ "Usage: Client::GetAAEXPModifier(THIS, uint32 zone_id)"); { Client* THIS; double aa_modifier = 1.0f;
codereview_cpp_data_4307
io_thread_pool->launch_pinned_threads(1, 1); std::set<std::string> active_data_fields = {"samples"}; - active_data_fields.insert(GENERATE("labels", "responses")); auto s = GENERATE(range(1, 11)); El::Int num_samples = s; std::vector<int> dims = {s,s};; ```suggestion active_data_fields.insert(GENERATE(std::string("labels"), std::string("responses"))); ``` Apple clang was whining about this one... io_thread_pool->launch_pinned_threads(1, 1); std::set<std::string> active_data_fields = {"samples"}; + active_data_fields.insert(GENERATE(std::string("labels"), + std::string("responses"))); auto s = GENERATE(range(1, 11)); El::Int num_samples = s; std::vector<int> dims = {s,s};;
codereview_cpp_data_4319
// Count number of lines in the buffer. There is one line per each log message output to that buffer std::string out_string_out = out_stream_out.str(); - uint32_t lines_out = std::count(out_string_out.begin(), out_string_out.end(), '\n'); // If CMAKE_BUILD_TYPE is Debug, the INTERNAL_DEBUG flag was set, and the logInfo messages were not deactivated, // then there should be 3 messages in the out buffer, one for the logError, one for the logWarning, and another one Should this also check that nothing is sent to `std::cerr` ? // Count number of lines in the buffer. There is one line per each log message output to that buffer std::string out_string_out = out_stream_out.str(); + std::string::difference_type lines_out = std::count(out_string_out.begin(), out_string_out.end(), '\n'); // If CMAKE_BUILD_TYPE is Debug, the INTERNAL_DEBUG flag was set, and the logInfo messages were not deactivated, // then there should be 3 messages in the out buffer, one for the logError, one for the logWarning, and another one
codereview_cpp_data_4322
template <typename T> void ihipMemsetKernel(hipStream_t stream, T* ptr, T val, size_t sizeBytes) { - if(sizeof(T) == sizeof(uint32_t)){ // for all sizeof(uint32_t) use the fast path using hsa specialization - hsa_amd_memory_fill(ptr, reinterpret_cast<const std::uint32_t&>(val), sizeBytes); return; } Failure is in one of the memset tests. I need to check the hsa spec, but I think the ```sizeBytes``` probably needs to be divided by ```sizeof(uint32_t)```. template <typename T> void ihipMemsetKernel(hipStream_t stream, T* ptr, T val, size_t sizeBytes) { + if(sizeof(T) == sizeof(uint32_t) && (sizeBytes % sizeof(uint32_t) == 0)){ // for all sizeof(uint32_t) use the fast path using hsa specialization + hsa_amd_memory_fill(ptr, reinterpret_cast<const std::uint32_t&>(val), sizeBytes/sizeof(uint32_t)); return; }
codereview_cpp_data_4324
static const char *get_ext(h2o_configurator_command_t *cmd, yoml_t *node) { if (strcmp(node->data.scalar, "default") == 0) { - return node->data.scalar; } else if (assert_is_extension(cmd, node) == 0) { return node->data.scalar + 1; } else { The function seems to either return "default" or return the extension stripping the preceding dot. Does the fact mean that we can no longer register `.default` as an extension? static const char *get_ext(h2o_configurator_command_t *cmd, yoml_t *node) { if (strcmp(node->data.scalar, "default") == 0) { + /* empty string means default */ + return ""; } else if (assert_is_extension(cmd, node) == 0) { return node->data.scalar + 1; } else {