text
stringlengths
1
2.12k
source
dict
c++, performance, strings, c++20 // free memory, set values to zero void reset () { if(!siz) return; free(src); len = 0; siz = 0; } // destructor ~xstring () { reset(); } }; } // xstring class functions, i will write long functions here to arrange the file and keep it beautiful namespace x { /** * @brief set value of xstring object */ bool xstring::set (const char *ref, size_t rlen = 0) { if(!rlen) rlen = strlen(ref); // [increase performance] If the length is known, there is no need to recalculate it if(siz == 0) // alloc space in heap memory to store value { siz = rlen + _xs_extra_space_; // [increase performance] extra 25 bytes space to avoid realloc in next times if space is enough if(siz >= xnpos - 25) { siz -= rlen + _xs_extra_space_; return false; } // check if size > max size src = (char*) calloc(siz, sizeof(char)); // allocate space if(src == nullptr) return false; // check if space is allocated } else if(siz <= rlen) // realloc more space to contains the new value { siz = rlen + _xs_extra_space_; if(siz >= xnpos - 25) { siz -= rlen + _xs_extra_space_; return false; } src = (char*) realloc(src, siz * sizeof(char)); if(src == nullptr) return false; } memcpy(src, ref, rlen+1); // copy value from ref len = rlen; // update length src[len] = '\0'; // terminate the array return true; }
{ "domain": "codereview.stackexchange", "id": 43210, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++20", "url": null }
c++, performance, strings, c++20 /** * @brief add value to begin of xstring object */ bool xstring::append (const char *ref, size_t rlen = 0) { if(siz == 0) return set(ref,rlen); // if space is null, call set() if(!rlen) rlen = strlen(ref); if(siz <= (len + rlen)) { siz += rlen + _xs_extra_space_; if(siz >= xnpos - 25) { siz -= rlen + _xs_extra_space_; return false; } src = (char*) realloc(src, siz * sizeof(char)); if(src == nullptr) return false; } memcpy(src + len, ref, rlen+1); len += rlen; src[len] = '\0'; return true; } /** * @brief add value to end of xstring object */ bool xstring::prepend (const char *ref, size_t rlen = 0) { if(siz == 0) return set(ref,rlen); if(!rlen) rlen = strlen(ref); if(siz <= (len + rlen)) { siz += rlen + _xs_extra_space_; if(siz >= xnpos - 25) { siz -= rlen + _xs_extra_space_; return false; } src = (char*) realloc(src, siz * sizeof(char)); if(src == nullptr) return false; } memmove(src + rlen, src, len); // move data to rlen pos size_t i = 0; while(i < rlen) // loop in copy ref to begin of src { src[i] = ref[i]; ++i; } len += rlen; src[len] = '\0'; return true; } /** * @brief add value to position of xstring object */ bool xstring::insert (size_t pos, const char *ref, size_t rlen = 0) { if(siz == 0) return set(ref,rlen); if(pos > len) return false; if(!rlen) rlen = strlen(ref);
{ "domain": "codereview.stackexchange", "id": 43210, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++20", "url": null }
c++, performance, strings, c++20 if(siz <= (len + rlen)) { siz += rlen + _xs_extra_space_; if(siz >= xnpos - 25) { siz -= rlen + _xs_extra_space_; return false; } src = (char*) realloc(src, siz * sizeof(char)); if(src == nullptr) return false; } memmove(src + rlen, src, len); size_t i = 0; while(true) { size_t target = pos == 0 ? (0 + i) : (pos+i); src[target] = ref[i]; if(++i >= rlen) break;; } len += rlen; src[len] = '\0'; return true; } } #endif test.cpp #include "xstring.h" #include <chrono> #include <string> #include <iostream> #include <iomanip> #include <limits.h> #include <float.h> using namespace x; using namespace std; void TEST_PRNT (const char*f, const char*t, const char*r, const char*n, bool row = false) { char sep = row ? '+' : '|'; std::cout << std::left << sep << std::setw(25) << f << sep << std::setw(8) << t << sep << std::setw(6) << r << sep << std::setw(30) << n << sep << std::endl; } #define TEST_STUP std::chrono::steady_clock::time_point test_begin; std::chrono::steady_clock::time_point test_end; char test_result[75]; TEST_PRNT("-------------------------", "--------", "------", "------------------------------",true);TEST_PRNT("METHOD", "CLASS", "TIME", "NOTES");TEST_PRNT("-------------------------", "--------", "------", "------------------------------",true); #define TEST_STRT test_begin = std::chrono::steady_clock::now(); for(int i = 0; i < 1000000; ++i) { #define TEST_STOP } test_end = std::chrono::steady_clock::now(); sprintf(test_result,"%-6ld",(std::chrono::duration_cast<std::chrono::microseconds>(test_end - test_begin).count()) / 1000); #define TEST_LINE TEST_PRNT("-------------------------", "--------", "------", "------------------------------", true); using namespace x;
{ "domain": "codereview.stackexchange", "id": 43210, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++20", "url": null }
c++, performance, strings, c++20 using namespace x; int main() { std::cout << "----------------------------------------" << std::endl; std::cout << "USE: g++ --std c++20 -g test.cpp -o test" << std::endl; std::cout << "----------------------------------------" << std::endl; TEST_STUP // create empty TEST_STRT xstring x; TEST_STOP TEST_PRNT("create empty","xstring" ,test_result,""); TEST_STRT string x; TEST_STOP TEST_PRNT(" ","string" ,test_result,""); TEST_LINE // create by string TEST_STRT xstring x = "value"; TEST_STOP TEST_PRNT("create by string","xstring" ,test_result,""); TEST_STRT string x = "value"; TEST_STOP TEST_PRNT(" ","string" ,test_result,""); TEST_LINE // create by character TEST_STRT xstring x = 'c'; TEST_STOP TEST_PRNT("create by character","xstring" ,test_result,""); TEST_STRT string x = to_string('c'); TEST_STOP TEST_PRNT(" ","string" ,test_result,"Unavailable, used to_string()"); TEST_LINE // create by bool TEST_STRT xstring x = true; TEST_STOP TEST_PRNT("create by bool","xstring" ,test_result,""); TEST_STRT string x = to_string(true); TEST_STOP TEST_PRNT(" ","string" ,test_result,"Unavailable, used to_string()"); TEST_LINE // create by integer TEST_STRT xstring x = 1; TEST_STOP TEST_PRNT("create by integer","xstring" ,test_result,""); TEST_STRT string x = to_string(1); TEST_STOP TEST_PRNT(" ","string" ,test_result,"Unavailable, used to_string()"); TEST_LINE // create by decimal TEST_STRT xstring x = 123.456; TEST_STOP TEST_PRNT("create by decimal","xstring" ,test_result,""); TEST_STRT string x = to_string(123.456); TEST_STOP TEST_PRNT(" ","string" ,test_result,"Unavailable, used to_string()"); TEST_LINE
{ "domain": "codereview.stackexchange", "id": 43210, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++20", "url": null }
c++, performance, strings, c++20 // create by same object TEST_STRT xstring y = "val"; xstring x = y; TEST_STOP TEST_PRNT("create by same object","xstring" ,test_result,""); TEST_STRT string y = "val"; string x = y; TEST_STOP TEST_PRNT(" ","string" ,test_result,""); TEST_LINE // create by multiple TEST_STRT xstring x = {"Hello"," ","World","!"}; TEST_STOP TEST_PRNT("create by multiple","xstring" ,test_result,""); TEST_PRNT(" ","string" ,"--" ,"Unavailable"); TEST_LINE // append TEST_STRT xstring x = "Hello"; x += "World"; TEST_STOP TEST_PRNT("append","xstring" ,test_result,""); TEST_STRT string x = "Hello"; x += "World"; TEST_STOP TEST_PRNT(" ","string" ,test_result,""); TEST_LINE // prepend TEST_STRT xstring x = "Hello"; x |= "Hello"; TEST_STOP TEST_PRNT("prepend","xstring" ,test_result,""); TEST_STRT string x = "World"; x.insert(0,"Hello"); TEST_STOP TEST_PRNT(" ","string" ,test_result,"Unavailable, used insert(0,)"); TEST_LINE // insert TEST_STRT xstring x = "Hello"; x.insert(3,"Hello"); TEST_STOP TEST_PRNT("insert","xstring" ,test_result,""); TEST_STRT string x = "World"; x.insert(3,"Hello"); TEST_STOP TEST_PRNT(" ","string" ,test_result,""); TEST_LINE // compare TEST_STRT xstring x = "Hello", y = "World"; x.compare(y); TEST_STOP TEST_PRNT("compare" ,"xstring" ,test_result,""); TEST_STRT string x = "Hello", y = "World"; x.compare(y); TEST_STOP TEST_PRNT(" ","string" ,test_result,""); TEST_LINE // swap TEST_STRT xstring x = "Hello", y = "World"; x.swap(y); TEST_STOP TEST_PRNT("swap" ,"xstring" ,test_result,""); TEST_STRT string x = "Hello", y = "World"; x.swap(y); TEST_STOP TEST_PRNT(" ","string" ,test_result,""); TEST_LINE
{ "domain": "codereview.stackexchange", "id": 43210, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++20", "url": null }
c++, performance, strings, c++20 // to lower TEST_STRT xstring x = "Hello"; x.to_lower(); TEST_STOP TEST_PRNT("to lower" ,"xstring" ,test_result,""); TEST_PRNT(" ","string" ,"--","Unavailable"); TEST_LINE // to upper TEST_STRT xstring x = "Hello"; x.to_upper(); TEST_STOP TEST_PRNT("to upper" ,"xstring" ,test_result,""); TEST_PRNT(" ","string" ,"--","Unavailable"); TEST_LINE // select by index TEST_STRT xstring x = "Hello"; x[0] = 'x'; TEST_STOP TEST_PRNT("select by index","xstring" ,test_result,""); TEST_STRT string x = "Hello"; x[0] = 'x'; TEST_STOP TEST_PRNT(" ","string" ,test_result,""); TEST_LINE // select char TEST_STRT xstring x = "Hello"; x.getIndex('l',1); TEST_STOP TEST_PRNT("select by char and pos","xstring" ,test_result,""); TEST_STRT string x = "Hello"; x.find('l',1); TEST_STOP TEST_PRNT(" ","string" ,test_result,""); TEST_LINE // select last TEST_STRT xstring x = "Hello"; x.getLast(); TEST_STOP TEST_PRNT("select last","xstring" ,test_result,""); TEST_STRT string x = "Hello"; x.back(); TEST_STOP TEST_PRNT(" ","string" ,test_result,""); TEST_LINE // pop last TEST_STRT xstring x = "Hello"; x.pop_last(); TEST_STOP TEST_PRNT("pop last","xstring" ,test_result,""); TEST_STRT string x = "Hello"; x.pop_back(); TEST_STOP TEST_PRNT(" ","string" ,test_result,""); TEST_LINE // pop by index TEST_STRT xstring x = "Hello"; x.pop(2,1); TEST_STOP TEST_PRNT("pop by index","xstring" ,test_result,""); TEST_STRT string x = "Hello"; x.erase(2,1); TEST_STOP TEST_PRNT(" ","string" ,test_result,""); TEST_LINE
{ "domain": "codereview.stackexchange", "id": 43210, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++20", "url": null }
c++, performance, strings, c++20 // reverse TEST_STRT xstring x = "Hello"; x.reverse(); TEST_STOP TEST_PRNT("reverse","xstring" ,test_result,""); TEST_PRNT(" ","string" ,"--","Unavailable"); TEST_LINE // find first of TEST_STRT xstring x = "Hello"; x.first_of('l'); TEST_STOP TEST_PRNT("find first of","xstring" ,test_result,""); TEST_STRT string x = "Hello"; x.find_first_of('l'); TEST_STOP TEST_PRNT(" ","string" ,test_result,""); TEST_LINE // find last of TEST_STRT xstring x = "Hello"; x.last_of('l'); TEST_STOP TEST_PRNT("find last of","xstring" ,test_result,""); TEST_STRT string x = "Hello"; x.find_last_of('l'); TEST_STOP TEST_PRNT(" ","string" ,test_result,""); TEST_LINE // sub string TEST_STRT xstring x = "Hello",y; x.sub(y, 0,3); TEST_STOP TEST_PRNT("sub string","xstring" ,test_result,""); TEST_STRT string x = "Hello",y; y = x.substr(0,3); TEST_STOP TEST_PRNT(" ","string" ,test_result,""); TEST_LINE // is empty TEST_STRT xstring x = "Hello"; if(x.empty()){} TEST_STOP TEST_PRNT("is empty","xstring" ,test_result,""); TEST_STRT string x = "Hello"; if(x.empty()){} TEST_STOP TEST_PRNT(" ","string" ,test_result,""); TEST_LINE }
{ "domain": "codereview.stackexchange", "id": 43210, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++20", "url": null }
c++, performance, strings, c++20 } Final Note: I only started learning C++ a couple of months ago, so I don't have much experience, I wasn't aware of the optimization options, so it seems like I was too quick to judge my project and my abilities! I will learn more and re-work on the same project to fix my mistakes not to do something faster! I will be glad for your suggestions, and please tell me how to improve the code, what should I do? What do I learn? The Second Final Note :D I will stop working for a while, I will try to develop my skills and increase my knowledge of the language and the compiler. I will not delete the code now, my mistake does not mean my end, on the contrary, I will learn from this mistake and will come back soon with something strong.
{ "domain": "codereview.stackexchange", "id": 43210, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++20", "url": null }
c++, performance, strings, c++20 Answer: Unfortunately, your implementation is slower (sometimes substantially slower) than std::string according to your own benchmarks in every test but "create by decimal": +-------------------------+--------+------+------------------------------+ |METHOD |CLASS |TIME |NOTES | +-------------------------+--------+------+------------------------------+ |create empty |xstring |0 | | | |string |0 | | +-------------------------+--------+------+------------------------------+ |create by string |xstring |56 | | | |string |0 | | +-------------------------+--------+------+------------------------------+ |create by character |xstring |58 | | | |string |7 |Unavailable, used to_string() | +-------------------------+--------+------+------------------------------+ |create by bool |xstring |45 | | | |string |4 |Unavailable, used to_string() | +-------------------------+--------+------+------------------------------+ |create by integer |xstring |67 | | | |string |5 |Unavailable, used to_string() | +-------------------------+--------+------+------------------------------+ |create by decimal |xstring |133 | | | |string |1164 |Unavailable, used to_string() | +-------------------------+--------+------+------------------------------+ |create by same object |xstring |555 | | | |string |18 | | +-------------------------+--------+------+------------------------------+
{ "domain": "codereview.stackexchange", "id": 43210, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++20", "url": null }
c++, performance, strings, c++20 +-------------------------+--------+------+------------------------------+ |create by multiple |xstring |147 | | | |string |-- |Unavailable | +-------------------------+--------+------+------------------------------+ |append |xstring |97 | | | |string |11 | | +-------------------------+--------+------+------------------------------+ |prepend |xstring |106 | | | |string |27 |Unavailable, used insert(0,) | +-------------------------+--------+------+------------------------------+ |insert |xstring |105 | | | |string |27 | | +-------------------------+--------+------+------------------------------+ |compare |xstring |154 | | | |string |0 | | +-------------------------+--------+------+------------------------------+ |swap |xstring |419 | | | |string |34 | | +-------------------------+--------+------+------------------------------+ |to lower |xstring |110 | | | |string |-- |Unavailable | +-------------------------+--------+------+------------------------------+ |to upper |xstring |100 | | | |string |-- |Unavailable | +-------------------------+--------+------+------------------------------+ |select by index |xstring |62 | |
{ "domain": "codereview.stackexchange", "id": 43210, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++20", "url": null }
c++, performance, strings, c++20 |select by index |xstring |62 | | | |string |0 | | +-------------------------+--------+------+------------------------------+ |select by char and pos |xstring |64 | | | |string |10 | | +-------------------------+--------+------+------------------------------+ |select last |xstring |66 | | | |string |0 | | +-------------------------+--------+------+------------------------------+ |pop last |xstring |52 | | | |string |5 | | +-------------------------+--------+------+------------------------------+ |pop by index |xstring |370 | | | |string |18 | | +-------------------------+--------+------+------------------------------+ |reverse |xstring |89 | | | |string |-- |Unavailable | +-------------------------+--------+------+------------------------------+ |find first of |xstring |54 | | | |string |10 | | +-------------------------+--------+------+------------------------------+ |find last of |xstring |54 | | | |string |5 | | +-------------------------+--------+------+------------------------------+ |sub string |xstring |139 | | | |string |0 | |
{ "domain": "codereview.stackexchange", "id": 43210, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++20", "url": null }
c++, performance, strings, c++20 | |string |0 | | +-------------------------+--------+------+------------------------------+ |is empty |xstring |53 | | | |string |0 | | +-------------------------+--------+------+------------------------------+
{ "domain": "codereview.stackexchange", "id": 43210, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++20", "url": null }
c++, performance, strings, c++20 See for yourself Now, I've compiled it with full optimizations enabled (-O2), rather than without optimizations enabled, which is what your "USE" suggestion shows. But it makes no sense to compare the performance of code when not compiling with optimizations enabled. To me, these test results are a deal-breaker. There's no reason to review this code any further. It doesn't matter how well-written your code is, how nice your comments are, how nicely things are aligned into columns, how well thought-out your interface is, or any of that. The code fails to meet its primary design goal, which is to be faster than the built-in string class. Unless it's faster than the built-in string class, or can achieve things that the built-in string class cannot, then there's no reason for this code to even exist. Writing it, testing it, learning its interface, and everything else is merely a waste of time, for both the author and the consumers. If string formatting (which is apparently the function that the "create" tests are measuring) is slow, and you want to improve that, then you can improve just that, without any need to introduce another incompatible string class. … But, before you embark on that project, check out C++20's std::format.
{ "domain": "codereview.stackexchange", "id": 43210, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++20", "url": null }
java, algorithm, graph, genetic-algorithm, traveling-salesman Title: Much more efficient trisexual genetic algorithm for TSP in Java Question: (The entire project lives there.) This time, I have made the previous version of the GA for TSP run faster by around the factor of 6+. The idea is to cache the tour costs with the actual tour objects and cache the hash codes of each tour. GeneticTSPSolverV2.java: package com.github.coderodde.tsp.impl; import com.github.coderodde.tsp.AllPairsShortestPathData; import com.github.coderodde.tsp.Node; import com.github.coderodde.tsp.Utils; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Random; import java.util.Set; import com.github.coderodde.tsp.TSPSolver;
{ "domain": "codereview.stackexchange", "id": 43211, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, graph, genetic-algorithm, traveling-salesman", "url": null }
java, algorithm, graph, genetic-algorithm, traveling-salesman /** * This class implements the genetic (optimized) TSP solver. * * @author Rodion "rodde" Efremov * @version 1.6 (Apr 8, 2022) * @since 1.6 (Apr 8, 2022) */ public final class GeneticTSPSolverV2 implements TSPSolver { private static final class Tour { final List<Node> nodes; final double cost; private final int hashCode; Tour(List<Node> nodes, double cost) { this.nodes = nodes; this.cost = cost; this.hashCode = nodes.hashCode(); } @Override public int hashCode() { return hashCode; } @Override public boolean equals(Object o) { if (!(o instanceof Tour)) { return false; } Tour other = (Tour) o; return nodes.equals(other.nodes); } } // The number of parents of each individual (tour). This is trisexual. private static final int NUMBER_OF_PARENTS = 3; // The minimum number of generations. If 1 is passed, only a randomly // (initial) generation will be returned. private static final int MINIMUM_NUMBER_OF_GENERATIONS = 1; // The minimum population size. private static final int MINIMUM_POPULATION_SIZE = 5; // The minimum number of vertices in the input graph. We need this in order // to make sure that we have sufficient amount of individuals in each // generation. private static final int MINIMUM_GRAPH_SIZE = 4; private static final int DEFAULT_NUMBER_OF_GENERATIONS = 10; private static final int DEFAULT_POPULATION_SIZE = 10; private final int numberOfGenerations; private final int populationSize; /** * Constructs a genetic solver with given parameters. * * @param numberOfGenerations the number of generations. * @param populationSize the population size at each generation. */
{ "domain": "codereview.stackexchange", "id": 43211, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, graph, genetic-algorithm, traveling-salesman", "url": null }
java, algorithm, graph, genetic-algorithm, traveling-salesman * @param populationSize the population size at each generation. */ public GeneticTSPSolverV2(int numberOfGenerations, int populationSize) { checkNumberOfGenerations(numberOfGenerations); checkPopulationSize(populationSize); this.numberOfGenerations = numberOfGenerations; this.populationSize = populationSize; } public GeneticTSPSolverV2() { this(DEFAULT_NUMBER_OF_GENERATIONS, DEFAULT_POPULATION_SIZE); } /** * Returns an (approximate) solution to the TSP problem via genetic * algorithm. * * @param seedNode the seed node of the graph. * @return an approximate solution to the TSP problem instance. */ public TSPSolver.Solution findTSPSolution(Node seedNode) { Objects.requireNonNull(seedNode, "The seed node is null."); List<Node> reachableNodes = GraphExpander.computeReachableNodesFrom(seedNode); checkGraphSize(reachableNodes.size()); Random random = new Random(); AllPairsShortestPathData allPairsData = AllPairsShortestPathSolver.solve(reachableNodes); List<Tour> population = computeInitialGeneration(reachableNodes, populationSize, random); for (int generationNumber = 1; generationNumber < numberOfGenerations; generationNumber++) { List<Tour> nextPopulation = evolvePopulation(population, allPairsData, random); population = nextPopulation; } Tour fittestTour = getFittestTour(population, allPairsData); return new TSPSolver.Solution(fittestTour.nodes, allPairsData); } private static Tour getFittestTour(List<Tour> population,
{ "domain": "codereview.stackexchange", "id": 43211, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, graph, genetic-algorithm, traveling-salesman", "url": null }
java, algorithm, graph, genetic-algorithm, traveling-salesman } private static Tour getFittestTour(List<Tour> population, AllPairsShortestPathData data) { Tour fittestTour = null; double fittestTourCost = Double.MAX_VALUE; for (Tour tour : population) { double tourCost = tour.cost; if (fittestTourCost > tourCost) { fittestTourCost = tourCost; fittestTour = tour; } } return fittestTour; } private static List<Tour> evolvePopulation(List<Tour> population, AllPairsShortestPathData data, Random random) { List<Tour> nextPopulation = new ArrayList<>(population.size()); while (nextPopulation.size() < population.size()) { Tour[] parents = getParents(population, data, random); nextPopulation.add(breedTour(parents, random, data)); } return nextPopulation; } private static Tour breedTour(Tour[] parents, Random random, AllPairsShortestPathData data) { int tourLength = parents[0].nodes.size(); int totalGeneLength = tourLength / NUMBER_OF_PARENTS; int gene1Length = totalGeneLength; int gene2Length = totalGeneLength; int gene3Length = tourLength - gene1Length - gene2Length; List<Node> tour = new ArrayList<>(totalGeneLength); List<Node> genes1 = new ArrayList<>(gene1Length); List<Node> genes2 = new ArrayList<>(gene2Length); List<Node> genes3 = new ArrayList<>(gene3Length); Set<Node> nodeSet = new HashSet<>(); for (int i = 0; i < gene1Length; ++i) { Node node = parents[0].nodes.get(i); nodeSet.add(node); genes1.add(node); } int index = 0;
{ "domain": "codereview.stackexchange", "id": 43211, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, graph, genetic-algorithm, traveling-salesman", "url": null }
java, algorithm, graph, genetic-algorithm, traveling-salesman genes1.add(node); } int index = 0; while (genes2.size() < gene2Length) { Node node = parents[1].nodes.get(index++); if (!nodeSet.contains(node)) { nodeSet.add(node); genes2.add(node); } } index = 0; while (genes3.size() < gene3Length) { Node node = parents[2].nodes.get(index++); if (!nodeSet.contains(node)) { nodeSet.add(node); genes3.add(node); } } List<List<Node>> genes = new ArrayList<>(NUMBER_OF_PARENTS); genes.add(genes1); genes.add(genes2); genes.add(genes3); Collections.<List<Node>>shuffle(genes, random); tour.addAll(genes.get(0)); tour.addAll(genes.get(1)); tour.addAll(genes.get(2)); return new Tour(tour, Utils.getTourCost(tour, data)); } private static double getMaximumTourCost(List<Tour> population, AllPairsShortestPathData data) { double fittestTourCost = -1.0; for (Tour tour : population) { fittestTourCost = Math.max(fittestTourCost, tour.cost); } return fittestTourCost; } private static Tour[] getParents(List<Tour> population, AllPairsShortestPathData data, Random random) { ProbabilityDistribution<Tour> distribution = new ProbabilityDistribution<>(random); double maximumTourCost = getMaximumTourCost(population, data); for (Tour tour : population) { double tourWeight = 1.2 * maximumTourCost - tour.cost; distribution.addElement(tour, tourWeight); }
{ "domain": "codereview.stackexchange", "id": 43211, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, graph, genetic-algorithm, traveling-salesman", "url": null }
java, algorithm, graph, genetic-algorithm, traveling-salesman distribution.addElement(tour, tourWeight); } Tour[] parents = new Tour[NUMBER_OF_PARENTS]; Set<Tour> parentFilter = new HashSet<>(); int index = 0; while (parentFilter.size() < NUMBER_OF_PARENTS) { Tour parent = distribution.sampleElement(); if (!parentFilter.contains(parent)) { parentFilter.add(parent); distribution.removeElement(parent); parents[index++] = parent; } } return parents; } private static List<Tour> computeInitialGeneration(List<Node> reachableNodes, int populationSize, Random random) { List<Tour> initialGeneration = new ArrayList<>(populationSize); for (int i = 0; i < populationSize; ++i) { List<Node> nodes = new ArrayList<>(reachableNodes); Collections.shuffle(nodes, random); Tour tour = new Tour(nodes, 0.0); initialGeneration.add(tour); } return initialGeneration; } protected static void checkNumberOfGenerations(int numberOfGenerations) { if (numberOfGenerations < MINIMUM_NUMBER_OF_GENERATIONS) { throw new IllegalArgumentException( "Number of generations is too small: " + numberOfGenerations + ". Must be at least " + MINIMUM_NUMBER_OF_GENERATIONS + "."); } } protected static void checkPopulationSize(int populationSize) { if (populationSize < MINIMUM_POPULATION_SIZE) { throw new IllegalArgumentException( "Population size is too small: " + populationSize
{ "domain": "codereview.stackexchange", "id": 43211, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, graph, genetic-algorithm, traveling-salesman", "url": null }
java, algorithm, graph, genetic-algorithm, traveling-salesman "Population size is too small: " + populationSize + ". Must be at least " + MINIMUM_POPULATION_SIZE + "."); } } protected static void checkGraphSize(int graphSize) { if (graphSize < MINIMUM_GRAPH_SIZE) { throw new IllegalArgumentException( "The graph size is " + graphSize + ". Minimum allowed size is " + MINIMUM_GRAPH_SIZE + "." ); } } }
{ "domain": "codereview.stackexchange", "id": 43211, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, graph, genetic-algorithm, traveling-salesman", "url": null }
java, algorithm, graph, genetic-algorithm, traveling-salesman Typical output On my PC, I get the following output: GA duration: 712 ms. Brute-force duration: 8127 ms. --- GA cost: 1298.5923370671355 Brute-force cost: 1187.226303336163 Cost ratio: 1.093803543113919 Critique request As always, I would like to hear any comments on how to improve my code. Answer: List<Tour> nextPopulation = evolvePopulation(population, allPairsData, random); population = nextPopulation; The nextPopulation variable doesn't serve a purpose. This is the same: population = evolvePopulation(population, allPairsData, random); In: private static Tour getFittestTour(List<Tour> population, AllPairsShortestPathData data) { Parameter data is unused. Consider using streams. E.g. your ParallelGeneticTSPSolver class has: Tour getMinimalTour(List<Tour> population) { Tour minimalTour = null; double minimalTourCost = Double.POSITIVE_INFINITY; for (Tour tour : population) { double tentativeTourCost = tour.cost; if (minimalTourCost > tentativeTourCost) { minimalTourCost = tentativeTourCost; minimalTour = tour; } } return minimalTour; } It appears to be the same as getFittestTour You only need this once, and it can be rewritten using the Stream API in a much more concise way: Tour getMinimalTour(List<Tour> population) { return population.stream() .min((a, b) -> Double.compare(a.cost, b.cost)) .get(); } ParallelGeneticTSPSolver also has: private double getMaximumTourCost(List<Tour> population, AllPairsShortestPathData data) { double fittestTourCost = -1.0;
{ "domain": "codereview.stackexchange", "id": 43211, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, graph, genetic-algorithm, traveling-salesman", "url": null }
java, algorithm, graph, genetic-algorithm, traveling-salesman for (Tour tour : population) { fittestTourCost = Math.max(fittestTourCost, tour.cost); } return fittestTourCost; } which also has an unused parameter data and could be simplified greatly using the stream APIs: private double getMaximumTourCost(List<Tour> population) { return population.stream().mapToDouble(t -> t.cost).max().getAsDouble(); } This code: for (int i = 0; i < gene1Length; ++i) { Node node = parents[0].nodes.get(i); nodeSet.add(node); genes1.add(node); } int index = 0; while (genes2.size() < gene2Length) { Node node = parents[1].nodes.get(index++); if (!nodeSet.contains(node)) { nodeSet.add(node); genes2.add(node); } } index = 0; while (genes3.size() < gene3Length) { Node node = parents[2].nodes.get(index++); if (!nodeSet.contains(node)) { nodeSet.add(node); genes3.add(node); } } is a little awkward. You could decrement the gene[2/3]Length variable when you add nodes and break when it is zero, instead of calling the size() method every iteration. (This way you only need the comparison for iterations that actually change the size.): for (;;) { Node node = parents[2].nodes.get(index++); if (!nodeSet.contains(node)) { nodeSet.add(node); genes3.add(node); if (--gene3Length == 0) break; } }
{ "domain": "codereview.stackexchange", "id": 43211, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, graph, genetic-algorithm, traveling-salesman", "url": null }
java, algorithm, graph, genetic-algorithm, traveling-salesman I assume something in the algorithm assures that index won't go out of bounds. If you are trying to tune this to get the very best performance, I suggest making a benchmark with JMH before you start tweaking. Some other things to try for speed ups, since now we break the loop differently, we can use for-each (no need to dereference parents array inside the loop, no need for index variable at all) for(Node node : parent[2].nodes) { if (!nodeSet.contains(node)) { nodeSet.add(node); genes3.add(node); if (--gene3Length == 0) break; } } Here again the stream APIs would make this easier to read. Is this not equivalent (I'm assuming that the nodes list for each parent never has duplicate nodes, so nodeSet doesn't need to be updated on-the-fly): List<Node> genes1 = new ArrayList<>(parents[0].nodes.subList(0, gene1Length)); nodeSet.addAll(genes1); List<Node> genes2 = parents[1].nodes.stream() .filter(n -> !nodeSet.contains(n)) .limit(gene2Length).toList(); nodeSet.addAll(genes2); List<Node> genes3 = parents[2].nodes.stream() .filter(n -> !nodeSet.contains(n)) .limit(gene3Length).toList(); nodeSet.addAll(genes3);
{ "domain": "codereview.stackexchange", "id": 43211, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, graph, genetic-algorithm, traveling-salesman", "url": null }
c#, asp.net, locking Title: C# lock on string value Question: Our codebase is full of locks such as: lock("Something." + var) { .... } This causes issues due to strings not meant to be used in locks in this way. We have a need to lock on dynamic strings, so this is the replacement based on the implementation of the lock object specified here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/statements/lock public class StringLock : IDisposable { private static readonly ConcurrentDictionary<string, object> LockObjects = new (); private string Key { get; } private object LockObject { get; } private readonly bool _lockWasTaken; public StringLock(string key) { Key = key; LockObject = LockObjects.GetOrAdd(Key, new object()); _lockWasTaken = false; System.Threading.Monitor.Enter(LockObject, ref _lockWasTaken); } public void Dispose() { if (_lockWasTaken) System.Threading.Monitor.Exit(LockObject); LockObjects.TryRemove(Key, out _); } } Usage: using (new StringLock("test")) { // Locked }
{ "domain": "codereview.stackexchange", "id": 43212, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, asp.net, locking", "url": null }
c#, asp.net, locking Usage: using (new StringLock("test")) { // Locked } Answer: Thread 1 and Thread 2 call into StringLock("test"). One of them wins, lets say Thread 1. Thread 1 goes into Monitor.Enter. Thread 2 waits. Thread 1 exits and removes the lock object from ConcurrentDictionary. Thread 2 enters the Monitor.Enter. Thread 3 calls into StringLock("test") and gets a new lock object, because not in the ConcurrentDictionary anymore, and can proceed while Thread 2 is still in the "lock". The hard part here is knowing when it's safe to remove from LockObjects. Could make a more complex lock object instead of object that contains a counter. Something like the WaitingWriteCount of the ReaderWriterLockSlim class. Then instead of using GetOrAdd on concurrent dictionary use AddOrUpdate to increment a count if object exist. Still could need grab the object again before releasing the lock and decrement the counter. Another option could be the ConditionalWeakTable but strings could be a bad option for the key and would still need to have some mapping object between strings and the key. Update You could use the AddOrUpdate method to know when it's safe to remove the lockobject. public class StringLock : IDisposable { private static readonly ConcurrentDictionary<string, Tuple<object, object>> LockObjects = new ConcurrentDictionary<string, Tuple<object, object>>(); private readonly Tuple<object, object> _lockTuple; private readonly string _key; private bool _lockTaken = false; public StringLock(string key) { _key = key; // Add a new tuple or if updating just replace the "holder" part of the tuple so all locks share common object but each call has own object for the call _lockTuple = LockObjects.AddOrUpdate(key, _ => Tuple.Create(new object(), new object()), (_, x) => Tuple.Create(x.Item1, new object())); Monitor.Enter(LockObject, ref _lockTaken); } private object LockObject => _lockTuple.Item1;
{ "domain": "codereview.stackexchange", "id": 43212, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, asp.net, locking", "url": null }
c#, asp.net, locking private object LockObject => _lockTuple.Item1; public void Dispose() { if (_lockTaken) { Monitor.Exit(LockObject); } // Cast to IDictionary to do Atomic remove if the "Value" hasn't changed from the update statement // gist taken from https://devblogs.microsoft.com/pfxteam/little-known-gems-atomic-conditional-removals-from-concurrentdictionary/ var dict = (IDictionary<string, Tuple<object, object>>)LockObjects; dict.Remove(new KeyValuePair<string, Tuple<object, object>>(_key, _lockTuple)); } public override string ToString() { return _key; } } Here we are using a tuple's item1 to hold the object that is to be locked on with all threads. The tuple's item2 is just a unique object for each call. We use AddOrUpdate to change Item2 to a new object if the key exists in the ConcurrentDictionary. Then we can cast the ConcurrentDictionary to IDictionary and use the Atomic remove where it will only remove if both the key and value are the same and haven't been changed.
{ "domain": "codereview.stackexchange", "id": 43212, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, asp.net, locking", "url": null }
c++, memory-management, pointers, weak-references Title: Improvement suggestions to my shared_ptr and weak_ptr implementations Question: Below is the entire code. I appreciate if, someone with more C++ experience can suggest if this can be improved further and if you notice any issues. controlblock.hpp template<class T> struct ControlBlock { int _ref_count; int _weak_count; void inc_ref() noexcept { ++_ref_count; } void inc_wref() noexcept { ++_weak_count; } void dec_ref() noexcept { --_ref_count; } void dec_wref() noexcept { if (--_weak_count == 0) delete this; } int use_count() const noexcept { return _ref_count; } ControlBlock() : _ref_count{ 0 }, _weak_count{ 0 } {} ~ControlBlock() { _ref_count = 0; _weak_count = 0; } }; shared_ptr.hpp #pragma once #include <algorithm> #include <iterator> #include <compare> #include <cassert> #include <memory> #include "controlblock.hpp" #include "weak_ptr.hpp" template<class T> class SharedPtr { #define CHECK assert(Invariant()); template<class Y> friend class WeakPtr; private: T* _ptr; ControlBlock<T>* _ctrl_block; void __increment_reference() { if (_ptr != nullptr && _ctrl_block != nullptr) _ctrl_block->inc_ref(); } void __remove_reference() { if (_ctrl_block && _ctrl_block->_ref_count > 0) { --_ctrl_block->_ref_count; if(_ctrl_block && _ctrl_block->_ref_count == 0){ delete _ptr; } if(_ctrl_block->_ref_count + _ctrl_block->_weak_count == 0) { delete _ctrl_block; } _ptr = nullptr; _ctrl_block = nullptr; } }
{ "domain": "codereview.stackexchange", "id": 43213, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, pointers, weak-references", "url": null }
c++, memory-management, pointers, weak-references public: constexpr SharedPtr() : _ptr{ nullptr }, _ctrl_block{ nullptr } { } explicit SharedPtr(T* other) : _ptr{ other }, _ctrl_block{new ControlBlock<T>} { __increment_reference(); CHECK } constexpr SharedPtr(const std::nullptr_t) noexcept : _ptr{ nullptr }, _ctrl_block{ nullptr } { CHECK } explicit SharedPtr(WeakPtr<T>& other) : _ptr{other._ptr}, _ctrl_block{other._ctrl_block} { if (other.expired()) throw std::bad_weak_ptr(); _ctrl_block->inc_wref(); CHECK } SharedPtr(const SharedPtr& other) noexcept : _ptr{other._ptr}, _ctrl_block{other._ctrl_block} { __increment_reference(); CHECK } SharedPtr(SharedPtr&& other) noexcept : _ptr{ std::exchange(other._ptr, nullptr) }, _ctrl_block{std::exchange(other._ctrl_block, nullptr)} { CHECK } ~SharedPtr() { __remove_reference(); CHECK }; SharedPtr& operator=(const SharedPtr& other) noexcept { if (this == &other) return *this; __remove_reference(); _ptr = other._ptr; _ctrl_block = other._ctrl_block; __increment_reference(); CHECK return *this; } SharedPtr& operator=(SharedPtr&& other) noexcept { if (this == &other) return *this; __remove_reference(); _ptr = std::exchange(other._ptr, nullptr); _ctrl_block = std::exchange(other._ctrl_block, nullptr); CHECK return *this; } SharedPtr& operator=(std::nullptr_t) { if (_ptr == nullptr && _ctrl_block == nullptr) return *this; __remove_reference(); return *this; }
{ "domain": "codereview.stackexchange", "id": 43213, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, pointers, weak-references", "url": null }
c++, memory-management, pointers, weak-references __remove_reference(); return *this; } T* get() const noexcept { return _ptr; } T& operator*() const noexcept { return *_ptr; } T* operator->() const noexcept { return _ptr; } operator bool() const noexcept { return _ptr != nullptr && _ctrl_block != nullptr; } size_t use_count() const noexcept { return (_ctrl_block) ? _ctrl_block->use_count() : 0; } void reset() noexcept { this->__remove_reference(); } bool Invariant() const noexcept; template<class T> friend void swap(SharedPtr<T>& lhs, SharedPtr<T>& rhs) noexcept; friend auto operator<=>(const SharedPtr& lhs, const SharedPtr& rhs) = default; friend auto operator==(const SharedPtr& lhs, const SharedPtr& rhs) { if (lhs.get() != rhs.get()) return false; return (lhs.get() <=> rhs.get()) == 0; } }; template<class T> inline bool SharedPtr<T>::Invariant() const noexcept { if (_ptr == nullptr && _ctrl_block == nullptr) return true; else if (_ptr != nullptr || _ctrl_block != nullptr && _ctrl_block->_ref_count > 0 || _ctrl_block->_weak_count > 0) return true; return false; } template<class T> void swap(SharedPtr<T>& lhs, SharedPtr<T>& rhs) noexcept { std::swap(lhs, rhs); } template<class T, class ...Args> SharedPtr<T> MakeShared(Args && ...args) { return SharedPtr<T>(new T(std::forward<Args>(args)...)); } weak_ptr.hpp #pragma once #include "controlblock.hpp" #include "shared_ptr.hpp" template<class T> class WeakPtr { #define CHECK assert(Invariant()); template<class Y> friend class SharedPtr; private: T* _ptr; ControlBlock<T>* _ctrl_block; public: WeakPtr() { CHECK } WeakPtr(T* other) : _ptr{other}, _ctrl_block{new ControlBlock<T>()} { __increment_weakptr(); CHECK } WeakPtr(const WeakPtr& other) noexcept : _ptr{other._ptr}, _ctrl_block{other._ctrl_block} { __increment_weakptr(); CHECK }
{ "domain": "codereview.stackexchange", "id": 43213, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, pointers, weak-references", "url": null }
c++, memory-management, pointers, weak-references WeakPtr(const SharedPtr<T>& other) noexcept : _ptr{other._ptr}, _ctrl_block{other._ctrl_block} { if(_ptr != nullptr && _ctrl_block != nullptr) _ctrl_block->inc_wref(); CHECK } ~WeakPtr() { __decrement_weakptr(); CHECK } void reset() noexcept { this->__decrement_weakptr(); } bool expired() noexcept { if (_ctrl_block == nullptr) return true; if (_ctrl_block->_ref_count == 0) --_ctrl_block->_weak_count; if (_ctrl_block->_ref_count + _ctrl_block->_weak_count == 0) { delete _ctrl_block; _ptr = nullptr; _ctrl_block = nullptr; } return !_ctrl_block || _ctrl_block->_weak_count == 0; } auto lock() { return expired() ? SharedPtr<T>() : SharedPtr<T>(*this); } bool Invariant() const noexcept { if (_ptr == nullptr) return true; return _ctrl_block->_weak_count > 0; } template<class T> friend void swap(WeakPtr<T>& lhs, WeakPtr <T>& rhs) noexcept; WeakPtr& operator=(const WeakPtr& other) { if (this != &other) { __decrement_weakptr(); _ptr = other._ptr; _ctrl_block = other._ctrl_block; __increment_weakptr(); } CHECK return *this; } WeakPtr& operator=(const SharedPtr<T>& other) { _ptr = other._ptr; _ctrl_block = other._ctrl_block; if(_ptr != nullptr && _ctrl_block != nullptr) _ctrl_block->inc_wref(); CHECK return *this; } private: void __increment_weakptr() { if (_ctrl_block != nullptr) { _ctrl_block->inc_wref(); } }
{ "domain": "codereview.stackexchange", "id": 43213, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, pointers, weak-references", "url": null }
c++, memory-management, pointers, weak-references void __decrement_weakptr() { if (_ctrl_block != nullptr && _ptr != nullptr) { if (--_ctrl_block->_weak_count == 0 && _ctrl_block->_ref_count == 0) { delete _ctrl_block; delete _ptr; } } _ptr = nullptr; _ctrl_block = nullptr; } }; template<class T> inline void swap(WeakPtr<T>& lhs, WeakPtr<T>& rhs) noexcept { std::swap(lhs, rhs); } Answer: General Overall very good. The double underscore is reserved for the implementation. You should not be using it in your code. Also the rules for leading underscore are non-trivial enough that most people either don't know the rules or get them wrong. Even though you don't it still not a good idea as others will get things wrong, and it will become an issue. What are the rules about using an underscore in a C++ identifier? The trailing underscore is perfectly fine, so a minor modification, and you can get the same pattern to help you identify your member variables (though I don't personally think this is a good idea as it tends to lead to sloppy variable naming that makes cut-and-paste mistakes easier). Bugs I believe you have a bug in the shared_ptr constructor that takes a weak_ptr. explicit SharedPtr(WeakPtr<T>& other) : _ptr{other._ptr}, _ctrl_block{other._ctrl_block} { if (other.expired()) throw std::bad_weak_ptr(); // Why are you increneting the weak_pointer count? // You just created a shared pointer. _ctrl_block->inc_wref(); CHECK } This does not make sense. WeakPtr(T* other) : _ptr{other}, _ctrl_block{new ControlBlock<T>()} { __increment_weakptr(); CHECK }
{ "domain": "codereview.stackexchange", "id": 43213, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, pointers, weak-references", "url": null }
c++, memory-management, pointers, weak-references You can never get a shared pointer to that object (as there has to exist at least one shared pointer before a weak pointer can be converted to a shared pointer as otherwise the pointed at object will have been deleted. I suspect that you are also leaking the other pointer as a result. This looks wrong. Is this not a const method that simply checks the state of what the weak pointer is pointing at? bool expired() noexcept { if (_ctrl_block == nullptr) return true; // Not sure why you are decrementing the reference count here. // You are only checking if the current weak pointer is valid // Which simply requries you to check if there still exists a // a shared pointer. if (_ctrl_block->_ref_count == 0) --_ctrl_block->_weak_count; // This is doubly wrong. if (_ctrl_block->_ref_count + _ctrl_block->_weak_count == 0) { delete _ctrl_block; _ptr = nullptr; _ctrl_block = nullptr; } return !_ctrl_block || _ctrl_block->_weak_count == 0; } I would simply write it like this: bool expired() const noexcept { return _ctrl_block == nullptr || _ctrl_block->_ref_count == 0; } You have not defined the member values here WeakPtr() { CHECK } Thus they are currently indeterminate. Likely to cause some undefined behaviour if you use an object created like this. This bug may not even be caught by check. As debug code will generally initialize the memory with all zeros (to help in debuggin) and in production the assert() will be disabled. Corner Case Issues You should declare the operator bool() as explicit. operator bool() const noexcept { return _ptr != nullptr && _ctrl_block != nullptr; }
{ "domain": "codereview.stackexchange", "id": 43213, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, pointers, weak-references", "url": null }
c++, memory-management, pointers, weak-references This prevents certain corner cases. Check out here This version of operator bool will convert your shared object to bool in a few other instances. For example: SharedPtr<int> value1(new int(8)); SharedPtr<int> value2(new int(9)); if (value1 == value2) { // unfortunately, this will print "They match". // Because both values are converted to bool (in this case true). // Then the test is done. std::cout << "They match\n"; } To prevent this:: explicit operator bool() const noexcept { return _ptr != nullptr && _ctrl_block != nullptr; } // ^^^^^^^^ Compiler Warnings: Does this not give you a compiler warning. You have two definitions of CHECK. The compiler should tell you that you are redefining CHECK as you include both header files that include a definition. #define CHECK assert(Invariant()); Why is this a macro? #define CHECK assert(Invariant()); I don't think you gain any advantage over this being a macro over an inline function. That fact that it can be redefined or have another definition may be a good reason that this should not be a macro, but rather an inline function. Actual Compiler Warnings generated by gcc > g++ -std=c++20 -Wall -Wextra -Werror -pedantic <file>.cpp error: declaration of 'T' shadows template parameter template<class T> friend void swap(SharedPtr<T>& lhs, SharedPtr<T>& rhs) noexcept; warning: '&&' within '||' else if (_ptr != nullptr || _ctrl_block != nullptr && ~~ ~~~~~~~~~~~~~~~~~~~~~~~^~ Code Review This is very old school: template<class T> This imlies that T can only be a class. So more modern approach is to use typename. template<typename T> Not sure why this is a template! template<class T> struct ControlBlock { int _ref_count; int _weak_count; void inc_ref() noexcept { ++_ref_count; } void inc_wref() noexcept { ++_weak_count; } void dec_ref() noexcept { --_ref_count; }
{ "domain": "codereview.stackexchange", "id": 43213, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, pointers, weak-references", "url": null }
c++, memory-management, pointers, weak-references // Skeptical over this delete. // Though I don't see it being misuesed in the code below // A call to `delete **this**` is very much an antipattern. // This is likely to cause errors down the road. void dec_wref() noexcept { if (--_weak_count == 0) delete this; } int use_count() const noexcept { return _ref_count; } ControlBlock() : _ref_count{ 0 }, _weak_count{ 0 } {} ~ControlBlock() { _ref_count = 0; _weak_count = 0; } }; There is no reference to T in the class. Why the check on _ptr here. void __increment_reference() { if (_ptr != nullptr && _ctrl_block != nullptr) _ctrl_block->inc_ref(); } If the _ptr is nullptr then should _ctrl_block not already be nullptr. Seems like a wasted check. And in the next section, __remove_reference() you don't check the _ptr. I would note that this is one time you don't use '{}` around the conditional code. I would always use the braces (even for simple one liner), and for consistency you should use the same style as everywhere else. void __remove_reference() { if (_ctrl_block && _ctrl_block->_ref_count > 0) { --_ctrl_block->_ref_count; // You have already established that _ctrl_block is not nullptr // You don't need to check again. if(_ctrl_block && _ctrl_block->_ref_count == 0){ delete _ptr; } Please initialize one variable per line. constexpr SharedPtr() : _ptr{ nullptr }, _ctrl_block{ nullptr } { } explicit SharedPtr(T* other) : _ptr{ other }, _ctrl_block{new ControlBlock<T>} Just like in normal code where it is standard to only initialize one variable per line. It is a nice to only initialize one variable per line in the initializer list. Remember this is being read by humans not machines. Be nice to your fellow human.
{ "domain": "codereview.stackexchange", "id": 43213, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, pointers, weak-references", "url": null }
c++, memory-management, pointers, weak-references Congrats on getting the nullptr case. Most people miss this. constexpr SharedPtr(const std::nullptr_t) noexcept : _ptr{ nullptr }, _ctrl_block{ nullptr } { CHECK } Good use of std::exchange(). I am still getting used to using that. SharedPtr(SharedPtr&& other) noexcept : _ptr{ std::exchange(other._ptr, nullptr) }, _ctrl_block{std::exchange(other._ctrl_block, nullptr)} Normally I am against the assignment to self test, because it is better handled by the copy and swap idiom. But I think in this case we can argue that it is useful. SharedPtr& operator=(const SharedPtr& other) noexcept { if (this == &other) return *this; BUT. I think a better test is simply to test if they are both using the same control block. If they are then we don't need to change anything, and it covers the assignment to self at the same time. So I would change the above to: if (_ctrl_block == other._ctrl_block) return *this; SharedPtr& operator=(std::nullptr_t) { // Like `__remove_reference()`, I think the check on // `_ptr` is not required. if (_ptr == nullptr && _ctrl_block == nullptr) return *this; OK. This works. But the point of writing your own swap() is to have a more efficient one than the standard implementation. If you are simply going to use the standard version, then there is no point in writing your own. template<class T> void swap(SharedPtr<T>& lhs, SharedPtr<T>& rhs) noexcept { std::swap(lhs, rhs); } Normally, I implement the swap function in terms of a swap method. template<class T> void swap(SharedPtr<T>& lhs, SharedPtr<T>& rhs) { lhs.swap(rhs); } void SharedPtr::swap(SharedPtr& other) noexcept { using std:swap; swap(ptr, other.ptr); swap(ctrl, other.ctrl); }
{ "domain": "codereview.stackexchange", "id": 43213, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, pointers, weak-references", "url": null }
c++, memory-management, pointers, weak-references In this constructor, you call __increment_weakptr(). WeakPtr(const WeakPtr& other) noexcept : _ptr{other._ptr}, _ctrl_block{other._ctrl_block} { __increment_weakptr(); CHECK } But in the very next one, you call inc_wref() on the control block directly. WeakPtr(const SharedPtr<T>& other) noexcept : _ptr{other._ptr}, _ctrl_block{other._ctrl_block} { if(_ptr != nullptr && _ctrl_block != nullptr) _ctrl_block->inc_wref(); CHECK } Self Plug: Please also have a read of the article I wrote about writting smart pointers: https://lokiastari.com/series/
{ "domain": "codereview.stackexchange", "id": 43213, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, pointers, weak-references", "url": null }
c, interpreter, brainfuck, c11 Title: Brainfuck interpreter in C, looking for improvements on the looping functionality Question: I've just started to get into PL design and made a simple Brainfuck interpreter. Although it is functional, I don't feel too confident on the execution, particularly the implementation for loops, I read some other bf interpreters and they generally used stacks for looping, but I didn't knew how to implement one ._. Anyway, I', beyond open to constructive criticism on how to improve this code. Also note the the macros COL_RED_BLK and COL_END are ansii escape code sequences to add to flare to the error messages and that I'm using C11 as the standard, since it's the one that I prefer the most. int interpret(char * tape, size_t size); char * loadTape(const char filename[], size_t * tape_size); int main(int argc, char * argv[]) { if (argc != 2) { fprintf(stderr, "%s: <file> \n" "Input File required \n", argv[0]); return EXIT_FAILURE; } size_t tape_sz = 0; char * tape = loadTape(argv[1], &tape_sz); // load the input file into a string if (!tape) { fprintf(stderr, "%sError:%s loading the file to the tape.\n", COL_RED_BLK, COL_END); } interpret(tape, tape_sz); free(tape); return EXIT_SUCCESS; }
{ "domain": "codereview.stackexchange", "id": 43214, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, interpreter, brainfuck, c11", "url": null }
c, interpreter, brainfuck, c11 int interpret(char * tape, size_t size) { size_t cond = 0, loop_s = 0, et_pos = 0; char et[size]; memset(&et, 0, size); // executable tape for (size_t i = 0; i < size; ++i) { switch (tape[i]) { case (OP_ADD): ++et[et_pos]; break; case (OP_SUB): --et[et_pos]; break; case (MV_INC): if (et_pos + 1 < size) { ++et_pos; } else { fprintf(stderr, "%sError:%s tape overrun in instruction %zu\n", COL_RED_BLK, COL_END, i+1); return 1; } break; case (MV_DEC): if (et_pos != 0) { --et_pos; } else { fprintf(stderr, "%sError:%s tape underrun in instrunction %zu\n", COL_RED_BLK, COL_END, i+1); return 1; } break; case (LOOP_S): cond = et_pos; loop_s = i; break; case (LOOP_E): if (et[cond]) { et_pos = cond; i = loop_s; } break; case (IO_INP): et[et_pos] = getchar(); break; case (IO_OUT): putchar(et[et_pos]); break; default: break; // brainfuck comment or empty space } } return 0; } An example program is of course Hello World -[------->+<]>-. -[->+++++<]>++. +++++++.. +++. [--->+<]>-----. ---[->+++<]>. -[--->+<]>---. +++. ------. --------. hello world Answer: Issues You don't support nested loops. As you point out in the description, you need a stack to support nested loops. The easiest way to get one is to move to C++ as a language and use a std::stack. The rest of the code would be very similar. But lets say you want to stick with C. Here is the most trivial of stack implementations. size_t stack[255]; size_t stackP = 0;
{ "domain": "codereview.stackexchange", "id": 43214, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, interpreter, brainfuck, c11", "url": null }
c, interpreter, brainfuck, c11 void push(size_t s) {stack[stackP++] = s;} size_t top() {return stack[stackP - 1];} void pop() {--stackP;} No error checking or anything. But it will serve your purpose for a version 1. Don't be lazy: size_t cond = 0, loop_s = 0, et_pos = 0; You are making the reader work harder to understand the types. One variable per line with its type. size_t cond = 0; size_t loop_s = 0; size_t et_pos = 0; char et[size]; memset(&et, 0, size); You can achieve the same like this: char et[size] = {0}; You have this test: if (et_pos + 1 < size) { And this test: if (et_pos != 0) { Why not make them the same form to ease reading: if (et_pos != size) { // STUFF if (et_pos != 0) { TO support nested loops. You need a stack. case (LOOP_S): cond = et_pos; loop_s = i; break; Here you would simply push the value on to the stack: case (LOOP_S): push(i); // Note. Restore this location as the position. // The for loop increment will automatically // take it to the first instruction in the loop. break; Also I think it is a bug to restore the place on the tape. So saving the tape location is not useful. cond = et_pos; Conversely to support the end of loop: case (LOOP_E): if (et[cond]) { et_pos = cond; i = loop_s; } break; Should look more like this: case (LOOP_E): if (et[cond]) { i = top(); // Jump to the saved loop location } else { pop(); // Remove the loop position. } break;
{ "domain": "codereview.stackexchange", "id": 43214, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, interpreter, brainfuck, c11", "url": null }
javascript, performance, algorithm, programming-challenge, balanced-delimiters Title: Leetcode problem: minimum removal to make valid parentheses Question: I was working on this problem on leetcode Question Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string. Formally, a parentheses string is valid if and only if: It is the empty string, contains only lowercase characters, or It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string. Example 1: Input: s = "lee(t(c)o)de)" Output: "lee(t(c)o)de" Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted. Example 2: Input: s = "))((" Output: "" Explanation: An empty string is also valid. My Solution var minRemoveToMakeValid = function(s) { let myStack = []; let myObj = {}; // for storing index having invalid parentheses to be removed let out = ''; // O(n)?? for(let i = 0; i < s.length; i++){ let val = s[i] if(["(", ")"].includes(val)){ if(val == ')' && myStack[myStack.length -1]?.char == "("){ const rem = myStack.pop() delete myObj[rem.index] } else { myStack.push({ char: val, index: i }) myObj[i] = true } } } // O(n) for(let i = 0; i < s.length; i++){ if(!myObj[i]){ out += s[i] } } return out }; Isn't the above solution in O(N) time complexity? It seems so to me however the results show that it is not (the solution runtime is in bottom 8% percentile) Why is this having such bad runtime even it seems like O(N)? or is it not so?
{ "domain": "codereview.stackexchange", "id": 43215, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, performance, algorithm, programming-challenge, balanced-delimiters", "url": null }
javascript, performance, algorithm, programming-challenge, balanced-delimiters Answer: Performance Your function is not O(n), because of the out += s[i] when constructing the result. Since JavaScript strings are immutable, every time you perform such a concatenation, it must construct a new string, which involves copying the out that it has constructed so far. When you do that in a loop, it becomes O(n2). Instead, you want to work on an array, then use join() to build the resulting string all at once. Data structures myObj is the least informative name you could possibly pick for a variable. A better name might be isInvalidPos. myStack is also not a wonderful name, but it does have the advantage of stating your intention to use the array as a stack. You use it to store all occurrences of ( and ), but really, you only care about storing (, since the only place where you inspect the contents is myStack[myStack.length -1]?.char == "(". So, in my suggested solution below, I've turned it into openParenPosStack. Instead of building myObj, then writing a second loop that uses it to build out (the loop with the performance problem), why not build the output in the main loop? Suggested solution
{ "domain": "codereview.stackexchange", "id": 43215, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, performance, algorithm, programming-challenge, balanced-delimiters", "url": null }
javascript, performance, algorithm, programming-challenge, balanced-delimiters var minRemoveToMakeValid = function(s) { let openParenPosStack = []; // indexes of outstanding open parens let out = new Array(s.length); // array of valid characters in output for (let i = 0; i < s.length; i++) { switch (s[i]) { case '(': openParenPosStack.push(i); break; // assume invalid, until a close paren is encountered case ')': if (!openParenPosStack.length) { break; // close without matching open is invalid } out[openParenPosStack.pop()] = '('; // retroactively make the open paren valid // fall through default: out[i] = s[i]; // valid close paren, or misc character } } return out.join(''); }; console.log(minRemoveToMakeValid("lee(t(c)o)de)")); console.log(minRemoveToMakeValid("))(("));
{ "domain": "codereview.stackexchange", "id": 43215, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, performance, algorithm, programming-challenge, balanced-delimiters", "url": null }
java, array Title: Java - Breaking a large 1-D array into a 2-D array Question: Java's largest array length is 2^31 – 8 = 2,147,483,639, which is an int consisting of 32-bits. In the case where we want to store more elements, we are better off creating multiple 1-D arrays or use a 2-D array which is an array of arrays. A program is coded to accept a length (typically larger than 2^31 – 8) to create a 2-D array with the appropriate number of cells. It has the methods get(long index) and set(long index, byte value) to get and set a specific index, respectively. Here, the type long is used which is a 64-bit whole number. Given the number of elements as size, create the correct number of 1-D arrays containing exactly size number of cells in total Given some element at index, find the appropriate 1-D array containing that element as well as find it in that array Since we are creating arrays taking Gigabytes of RAM, the type byte, which is an 8-bit number, is used For testing, the sequence 0, 1, ..., 126, 127, 0, 1, ... is stored in the large array A for loop is then executed to loop through each cell and ensure the sequence follows though The program has been tested for days without encountering any bugs There are two tests: The first to ensure the lengths of the 1-D arrays are created correctly The data structure used is a 1-D where each cell represent the length of that 1-D array at the ith index This will eliminate the need of Terabytes of RAM The second is a complete implementation where the get and set methods are implemented properly but requires multiple Gigabytes of RAM to run
{ "domain": "codereview.stackexchange", "id": 43216, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, array", "url": null }
java, array The request: Are there any bugs that have not been taken care of? Are there any improvements that can be applied? Edit 1: Some wonder what is the purpose of this. This is not a coding question but an implementation to improve upon an M.Sc. thesis implementation that deals with finding the minimum distance of a Linear Codes, an NP-Hard type of a problem. Essentially, a large number (2^40 or more) of vectors, represented as longs, is required to be stored inside of some data structure to perform operations on. Such problems use hundreds of Gigabytes and are executed on servers. The idea of using compression algorithms and writing to disk are not practical options they consume extra unneeded time (at least in my case). fastutil implemented something like this via BigArrays but the implementation here is tailored to a specific case to maximize the performance and is not based fastutil's implementation. import java.util.Arrays; /** * Uses a 1-D array where each cell stores the number of elements that needs * to be stored there. */ public class SimpleTest { /** * The structure used to store the data. */ private int[] array; /** * The amount of cells that are excluded from an array because VMs reserve * some header words in an array which reduces the <em>true</em> maximum * value. It could be at least 8 but 16 is used for extra precaution. */ private static byte offset = 16; /** * The number of cells in the array. */ private long size; /** * The number of 1-D arrays required. */ private int segments; /** * The maximum size of each 1-D array. */ private static int maxSegmentLength = Integer.MAX_VALUE - offset; /** * The size of last segment which is between {@code 1} and {@code * maxSegmentLength} (both inclusive). */ private int ancillarySegmentLength;
{ "domain": "codereview.stackexchange", "id": 43216, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, array", "url": null }
java, array public SimpleTest(long size) { if (size <= 0) { throw new RuntimeException("Size cannot be less than 1"); } this.size = size; //number of 1-D arrays with full capacity segments = (int) (size / (maxSegmentLength));//can be zero or larger //number of cells in the last 1-D array //or there will be only a single 1-D array if size < maxSegmentLength if ((int) (size % (maxSegmentLength)) != 0) { segments++; ancillarySegmentLength = (int) (size % (maxSegmentLength)); } else {//Last 1-D array is full (all 1-D arrays are perfectly full) ancillarySegmentLength = maxSegmentLength; } array = new int[segments]; if (segments == 1) {//a single 1-D array required array[0] = (int) size; } else {// for (int i = 0; i < segments - 1; i++) { array[i] = maxSegmentLength; } if (ancillarySegmentLength != 0) { array[segments - 1] = ancillarySegmentLength; } } System.out.println("=========="); System.out.println("Size: " + size); System.out.println("Total Arrays needed: " + segments); System.out.println("Size of last array: " + ancillarySegmentLength); System.out.println("=========="); } public String toString() { return Arrays.toString(array); } public static long power(long x, long n) { long result = 1; for (byte i = 0; i < n; i++) { result = result * x; } return result; }
{ "domain": "codereview.stackexchange", "id": 43216, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, array", "url": null }
java, array public static void main(String[] args) { System.out.println("Running CompleteTest..."); //extra is a value between 0 and maxSegmentLength, including both long extra = (long) (Math.random() * (maxSegmentLength + 1)); long size = maxSegmentLength * 1L + extra;// SimpleTest data = new SimpleTest(size); System.out.println("Printing the array: "); System.out.println(data); System.out.println("Run completed."); } } /** * A data structure for storing a large 1-D array into smaller 1-D array * stored inside a 2-D array. */ public class CompleteTest { /** * The structure used to store the codewords of the code. */ public byte[][] array; /** * The amount of cells that are excluded from an array because VMs reserve * some header words in an array which reduces the <em>true</em> maximum * value. It could be at least 8 but 16 is used for extra precaution. */ private static byte offset = 16; /** * The number of cells in the array. */ private long size; /** * The number of 1-D arrays required. */ private int segments; /** * The maximum size of each 1-D array. */ private static int maxSegmentLength = Integer.MAX_VALUE - offset; /** * The size of last segment which is between {@code 1} and {@code * maxSegmentLength} (both inclusive). */ private int ancillarySegmentLength; public CompleteTest(long size) { //assume size >= 1 this.size = size; //number of 1-D arrays with full capacity segments = (int) (size / (maxSegmentLength));//can be zero or larger
{ "domain": "codereview.stackexchange", "id": 43216, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, array", "url": null }
java, array //number of cells in the last 1-D array //or there will be only a single 1-D array if size < maxSegmentLength if ((int) (size % (maxSegmentLength)) != 0) { segments++; ancillarySegmentLength = (int) (size % (maxSegmentLength)); } else {//Last 1-D array is full (all 1-D arrays are perfectly full) ancillarySegmentLength = maxSegmentLength; } array = new byte[segments][]; //The last segment: if ancillarySegmentLength is 0, it's the same //as the other segments. Otherwise, allocate ancillarySegmentLength //cells where ancillarySegmentLength < maxSegmentLength if (ancillarySegmentLength == 0) { array[segments - 1] = new byte[maxSegmentLength]; } else { array[segments - 1] = new byte[ancillarySegmentLength]; } if (segments == 1) {//a single 1-D array required array[0] = new byte[(int) size]; } else { //populate all the segments except the last one for (int i = 0; i < segments - 1; i++) { array[i] = new byte[maxSegmentLength]; } //populate the last 1-D array if (ancillarySegmentLength != 0) { array[segments - 1] = new byte[ancillarySegmentLength]; } } } /** * Returns a specific element in the combination array. * * @param index the index of the element * @return the element in the index specified */ public long get(long index) { int s = (int) (index / maxSegmentLength); int i = (int) (index % maxSegmentLength); return array[s][i]; }
{ "domain": "codereview.stackexchange", "id": 43216, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, array", "url": null }
java, array /** * Sets the value specified at the appropriate index. * * @param index the index of the element to set * @param value the value to be assigned to */ public void set(long index, byte value) { int s = (int) (index / (long) maxSegmentLength); int i = (int) (index % maxSegmentLength); array[s][i] = value; } /** * Returns the number of elements. * * @return the number of elements */ public long length() { return size; } /** * Checks if the value specified is exists in the combination array. * * @param value the value to look for * @return {@code true} if the value exists, {@code false} otherwise */ public boolean contains(long value) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { if (array[i][j] == value) return true; } } return false; } /** * Prints the elements in the combination array on screen. The values * will be printed in base 10. */ public void print() { long counter = 0; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { System.out.format("(%d, %d) = %d \n", i, j, get(counter)); counter++; } System.out.println(); } }
{ "domain": "codereview.stackexchange", "id": 43216, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, array", "url": null }
java, array /** * Executes the program. * * @param args the arguments specified but will be ignored */ public static void main(String[] args) { System.out.println("Running CompleteTest..."); //extra is a value between 0 and maxSegmentLength, including both long extra = (long) (Math.random() * (maxSegmentLength + 1)); long size = maxSegmentLength * 1L + extra;// CompleteTest array = new CompleteTest(size); System.out.println("Size: " + array.size); for (int i = 0; i < array.array.length; i++) { System.out.println(array.array[i].length); } //store the sequence 0, 1, ..., 126, 127, 0, 1, ... in the array for (long i = 0; i < size; i++) { array.set(i, (byte) (i % 128)); } //check each cell to ensure the above sequence is present for (long i = 0; i < size; i++) { if (array.get(i) != (byte) (i % 128)) { System.out.println( "i = " + i + ", " + "value stored = " + array.get(i) + ", " + "correct value = " + (byte) (i % 128) ); } } //array.print(); System.out.println("Run completed."); } }
{ "domain": "codereview.stackexchange", "id": 43216, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, array", "url": null }
java, array Answer: Since the first class seems to be a proof of concept for the array partitioning and the point of the code is to remove every unnecessary piece of the code in order to maximize performance, I will only point out the issues in the coding style of the latter class. I do not even think about reusability here. Why make a proof of concept using bytes if your implementation will use long values? When you switch to long values, the memory allocations grow eight fold unless you change the segment size. The fastutil you mentioned deliberately tries to keep the memory allocations themselves below 2^31 and they align the allocation sizes to 2^X. Have you made sure your deviation from their example produces a performance gain? The offset variable should be a constant. And since it doesn't describe any offset that is meaningful to your code, you should name it private static final int JVM_OVERHEAD = 16; or something similar. In my opinion "this should be a big enough safeguard" never is in the long run, but I suppose your code will not be used as a generic library so I'll let it slide. The ancillarySegmentLengt variable is redundant. It is not used in the code and it can be calculated from size and maxSegmentLength should you ever need it. The last segment isn't really ancillary data, it's just the last segment. Even though it's purpose can be easily figured out, calling it ancillary just adds unnecessary cognitive load. The maxSegmentLength should be a constant. As long as you calculate the number of segments correctly, the whole segment allocation can be boiled down to this: long sizeLeft = size; for (int i = 0; i < array.length; i++) { array[i] = new byte[(int) Math.min(MAX_SEGMENT_LENGTH, sizeLeft)]; sizeLeft -= MAX_SEGMENT_LEFT; }
{ "domain": "codereview.stackexchange", "id": 43216, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, array", "url": null }
java, array Make the get and set methods final. That way you give the compiler the best start to optimizing the code. While at it, you should make every field, parameter and variable final, unless you really intend to change them during their lifetime. As said, it helps the compiler and it also helps the reader when following your code. You cast maxSegmentLength to long in set but not in get. Inconsistency creates confusion.
{ "domain": "codereview.stackexchange", "id": 43216, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, array", "url": null }
c, array, interview-questions, search, binary-search Title: Searching an element in a sorted array Question: I was applying for a position, and they asked me to complete a coding problem for them. I did so and submitted it, but I later found out I was rejected from the position. Anyways, I have an eclectic programming background so I'm not sure if my code is grossly wrong or if I just didn't have the best solution out there. I would like to post my code and get some feedback about it. Before I do, here's a description of a problem: You are given a sorted array of integers, say, {1, 2, 4, 4, 5, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 11, 13 }. Now you are supposed to write a program (in C or C++, but I chose C) that prompts the user for an element to search for. The program will then search for the element. If it is found, then it should return the first index the entry was found at and the number of instances of that element. If the element is not found, then it should return "not found" or something similar. Here's a simple run of it (with the array I just put up): Enter a number to search for: 4 4 was found at index 2. There are 2 instances for 4 in the array. Enter a number to search for: -4. -4 is not in the array. They made a comment that my code should scale well with large arrays (so I wrote up a binary search). Anyways, my code basically runs as follows: Prompts user for input. Then it checks if it is within bounds (bigger than a[0] in the array and smaller than the largest element of the array). If so, then I perform a binary search. If the element is found, then I wrote two while loops. One while loop will count to the left of the element found, and the second while loop will count to the right of the element found. The loops terminate when the adjacent elements do not match with the desired value.
{ "domain": "codereview.stackexchange", "id": 43217, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, array, interview-questions, search, binary-search", "url": null }
c, array, interview-questions, search, binary-search EX: 4, 4, 4, 4, 4 The bold 4 is the value the binary search landed on. One loop will check to the left of it, and another loop will check to the right of it. Their sum will be the total number of instances of the the number four. Anyways, I don't know if there are any advanced techniques that I am missing or if I just don't have the CS background and made a big error. Any constructive critiques would be appreciated! #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stddef.h> /* function prototype */ int get_num_of_ints( const int* arr, size_t r, int N, size_t* first, size_t* count ); int main() { int N; /* input variable */ int arr[]={1,1,2,3,3,4,4,4,4,5,5,7,7,7,7,8,8,8,9,11,12,12}; /* sorted */ size_t r = sizeof(arr)/sizeof(arr[0]); /* right bound */ size_t first; /* first match index */ size_t count; /* total number of matches */ /* prompts the user to enter input */ printf( "\nPlease input the integer you would like to find.\n" ); scanf( "%d", &N ); int a = get_num_of_ints( arr, r, N, &first, &count ); /* If the function returns -1 then the value is not found. Else it is returned */ if( a == -1) printf( "%d has not been found.\n", N ); else if(a >= 0){ printf( "The first matching index is %d.\n", first ); printf( "The total number of instances is %d.\n", count ); } return 0; } /* function definition */ int get_num_of_ints( const int* arr, size_t r, int N, size_t* first, size_t* count) { int lo=0; /* lower bound for search */ int m=0; /* middle value obtained */ int hi=r-1; /* upper bound for search */
{ "domain": "codereview.stackexchange", "id": 43217, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, array, interview-questions, search, binary-search", "url": null }
c, array, interview-questions, search, binary-search int w=r-1; /* used as a fixed upper bound to calculate the number of right instances of a particular value. */ /* binary search to find if a value exists */ /* first check if the element is out of bounds */ if( N < arr[0] || arr[hi] < N ){ m = -1; } else{ /* binary search to find value if it exists within given params */ while(lo <= hi){ m = (hi + lo)/2; if(arr[m] < N) lo = m+1; else if(arr[m] > N) hi = m-1; else if(arr[m]==N){ m=m; break; } } if (lo > hi) /* if it doesn't we assign it -1 */ m = -1; } /* If the value is found, then we compute left and right instances of it */ if( m >= 0 ){ int j = m-1; /* starting with the first term to the left */ int L = 0; /* total number of left instances */ /* while loop computes total number of left instances */ while( j >= 0 && arr[j] == arr[m] ){ L++; j--; } /* There are six possible outcomes of this. Depending on the outcome, we must assign the first index variable accordingly */ if( j > 0 && L > 0 ) *first=j+1; else if( j==0 && L==0) *first=m; else if( j > 0 && L==0 ) *first=m; else if(j < 0 && L==0 ) *first=m; else if( j < 0 && L > 0 ) *first=0; else if( j=0 && L > 0 ) *first=j+1; int h = m + 1; /* starting with the first term to the right */ int R = 0; /* total number of right instances */ /* while loop computes total number of right instances */ /* we fixed w earlier so that it's value does not change */ while( arr[h]==arr[m] && h <= w ){ R++; h++; }
{ "domain": "codereview.stackexchange", "id": 43217, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, array, interview-questions, search, binary-search", "url": null }
c, array, interview-questions, search, binary-search while( arr[h]==arr[m] && h <= w ){ R++; h++; } *count = (R + L + 1); /* total num of instances stored into count */ return *first; /* first instance index stored here */ } /* if value does not exist, then we return a negative value */ else if( m==-1) return -1; } Answer: I would have a few concerns about hiring someone who submitted this for a code sample. Here is what I see. First, addressing overall design, the algorithm is suboptimal, and is worst case linear instead of worst case logarithmic, because it doesn't use a binary search to find the amount of elements, but a linear one. Second, (and this is what would have really killed it for me) the variable names. Most of these are either one or two letters, and the code is very unreadable because of it. Giving your variables descriptive names is important for maintainability. Third, ignoring standard libraries. Unless instructed not to use them, you should prefer standard libraries which have implementations of binary search (e.g. the stl or bsearch) Fourth, why have get_num_of_ints return -1 has a magic value feeling to me; better to just set count = 0 and check that. Fifth, get_num_of_ints is just far too long, and tries to do way too much. It badly needs to be broken up. Sixth (and this is a personal choice), I think C++, with the STL, is a far better choice in this instance. In the spirit of "show, don't tell", here is how I would have written the assignment (untested, uncompiled) (edited to match the required function signature): #include <iostream> #include <algorithm> using namespace std; // This function signature is required: int get_num_of_ints(const int* searchBegin, size_t searchSize, int input, size_t* first, size_t* count) { const int* searchEnd = searchBegin + searchSize; const int* result = lower_bound(searchBegin, searchEnd, input); if (searchEnd == result || *result != input) return -1;
{ "domain": "codereview.stackexchange", "id": 43217, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, array, interview-questions, search, binary-search", "url": null }
c, array, interview-questions, search, binary-search if (searchEnd == result || *result != input) return -1; *first = result - searchBegin; *count = upper_bound(result, searchEnd, input) - result; return 0; } void print_search_results(const int* searchBegin, size_t searchSize, int input) { size_t first; size_t count; if (get_num_of_ints(searchBegin, searchSize, input, &first, &count) < 0) { cout << input << " is not in the array." << endl; return; } cout << input << " was found at index " << first << ". " << "There are " << count << " instances for " << input << " in the array." << endl; } bool read_input(int* input) { cout << "Enter a number to search for: "; bool succeeded = cin >> *input; cout << endl; return succeeded; } int main (int argc, char** argv) { const int searchNumbers[] = {1, 2, 4, 4, 5, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 11, 13}; const int searchNumbersSize = sizeof(searchNumbers)/sizeof(searchNumbers[0]); while(1) { int input; if(!read_input(&input)) { count << "Bad input, exiting" << endl; return 1; } print_search_results(searchNumbers, searchNumbersSize, input); } }
{ "domain": "codereview.stackexchange", "id": 43217, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, array, interview-questions, search, binary-search", "url": null }
c++, c++17, template-meta-programming, variant-type, visitor-pattern Title: visit for std::any Question: While solving an online excersise I have written some basic implementation for a visit function that works with std::any. The idea is to facilitate the declarative approach for handling std::any instead of using switch of nested if else constructions which are very hard to maintain. Unfortunatelly, C++ lacks reflection features to deduce a list of underlying types of std::any object from a dispatcher callable, so one have to provide a template list of underlying types that std::any can hold. Here is an example usage for solving the excercise: int productSum(std::vector<any> array) { struct { int operator()(int i, size_t) { return i; } int operator()(const std::vector<any>& array, size_t level = 1) { int sum = 0; for (const auto& a : array) sum += level * std::get<int>(impl::visit<int, std::vector<any>>(*this, a, level + 1)); return sum; } } dispatcher{}; return dispatcher(array); } And the implementation itself: #include <utility> #include <variant> #include <type_traits> namespace impl { template <typename T, typename... Ts> struct unique{ using type = T; };
{ "domain": "codereview.stackexchange", "id": 43218, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, template-meta-programming, variant-type, visitor-pattern", "url": null }
c++, c++17, template-meta-programming, variant-type, visitor-pattern namespace impl { template <typename T, typename... Ts> struct unique{ using type = T; }; template <typename... Ts, typename U, typename... Us, template <typename...> class TTupleT> struct unique<TTupleT<Ts...>, U, Us...> : std::conditional_t<std::disjunction_v<std::is_same<U, Ts>...>, unique<TTupleT<Ts...>, Us...>, unique<TTupleT<Ts..., U>, Us...>> {}; template <typename ... T> using unique_variant = typename unique<std::variant<>, T...>::type; // TODO: remove duplicate return values from variant template <typename ... DispatchT, typename CallableT, typename ... ArgsT> auto visit(CallableT &&callable, const std::any& any, ArgsT &&... args) { using retval_t = unique_variant<decltype(std::declval<CallableT>()(std::declval<DispatchT>(), std::declval<ArgsT>()...))...>; retval_t ret{}; // typeid can't be used within a fold expression (void)std::initializer_list<int>{(any.type() == typeid(DispatchT) && (ret = std::forward<CallableT>(callable)( std::any_cast<DispatchT>(any), std::forward<ArgsT>(args)... ), false),0)...}; return ret; } } I know that most certainly there are problems with type qualifiers, so I would appreciate any advice.
{ "domain": "codereview.stackexchange", "id": 43218, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, template-meta-programming, variant-type, visitor-pattern", "url": null }
c++, c++17, template-meta-programming, variant-type, visitor-pattern Answer: (Here's your code in Godbolt: https://godbolt.org/z/snTPjb6zW ) You have some crazy deep indentation (off the right side of my browser window). Consider switching to "Python-style" indentation, e.g. instead of // typeid can't be used within a fold expression (void)std::initializer_list<int>{(any.type() == typeid(DispatchT) && (ret = std::forward<CallableT>(callable)( std::any_cast<DispatchT>(any), std::forward<ArgsT>(args)... ), false),0)...}; return ret; you could write something like (void)std::initializer_list<int>{ ( any.type() == typeid(DispatchT) && ( ret = std::forward<CallableT>(callable)( std::any_cast<DispatchT>(any), std::forward<ArgsT>(args)... ), false ), 0 )... }; return ret; Of course this gets way easier with C++11 lambdas. Notice that my indentation style doesn't change: int dummy[] = { [&]() { if (any.type() == typeid(DispatchT)) { ret = std::forward<CallableT>(callable)( std::any_cast<DispatchT>(any), std::forward<ArgsT>(args)... ); } return 0; }() ... }; (void)dummy; return ret; // typeid can't be used within a fold expression That's not true at all. Maybe you initially forgot the parens in (x && ...)?
{ "domain": "codereview.stackexchange", "id": 43218, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, template-meta-programming, variant-type, visitor-pattern", "url": null }
c++, c++17, template-meta-programming, variant-type, visitor-pattern That's not true at all. Maybe you initially forgot the parens in (x && ...)? Design-wise, it would be easier to use (and also more performant) if you eliminated the dependency on std::variant. Instead of accepting a callable that returns X-or-Y-or-Z and then wrapping it up yourself in a std::variant<X,Y,Z> which your user then has to unwrap, it would be a ton easier to accept a callable that returns T, and then return T yourself, and let your user just use the T that you return. Like this: https://godbolt.org/z/3fEbe5s7n template<class T, class... Us> struct all_the_same { static_assert((std::is_same_v<T, Us> && ...)); using type = T; }; template <class... Ts, class Callable, class... Args> auto visit(Callable&& callable, const std::any& any, Args&&... args) { using R = typename all_the_same< decltype(std::declval<Callable>()(std::declval<Ts>(), std::declval<Args>()...))... >::type; R ret{}; Your use of std::declval<DispatchT>() is questionable. You seem to want each DispatchT to be a simple prvalue class type like std::vector<int> or int, which means that std::declval<DispatchT>() would be an xvalue (a DispatchT&&). But what you're actually receiving to dispatch on is a const std::any&, which means the thing you pull out of it ought to be a const DispatchT&. You should adjust your declval and your any_cast accordingly.
{ "domain": "codereview.stackexchange", "id": 43218, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, template-meta-programming, variant-type, visitor-pattern", "url": null }
c++, c++17, template-meta-programming, variant-type, visitor-pattern Naming-wise, I strongly recommend to use plural names for packs and singular names for non-packs. So your DispatchT... should become DispatchTs... (or in fact just Ts...); your ArgsT... should become Args...; and so on. This convention makes it easier to reason about pack-expansions at a glance. Compare your [&]() { if (any.type() == typeid(DispatchT)) { ret = std::forward<CallableT>(callable)( std::any_cast<DispatchT>(any), std::forward<ArgsT>(args)... ); } return 0; }() ... to my preferred [&]() { if (any.type() == typeid(Ts)) { ret = std::forward<Callable>(callable)( std::any_cast<const Ts&>(any), std::forward<Args>(args)... ); } return 0; }() ... I claim that mine is easier to read at a glance, because you can "brace-match" the plural nouns with the ... suffixes, without even knowing what their declarations look like. We know Ts and Args are packs; we know Callable is a single type. (We also know that Callable is the type of callable and Args... are the types of args..., without being told.)
{ "domain": "codereview.stackexchange", "id": 43218, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, template-meta-programming, variant-type, visitor-pattern", "url": null }
c++, c++17, template-meta-programming, variant-type, visitor-pattern Efficiency-wise, notice that you're not short-circuiting: you're going to evaluate any.type() == typeid(T) for every T in the pack, even if the first one is immediately a match. This is probably fine because typeid is super cheap (on Itanium-ABI platforms — I think it's more expensive on Windows), but you might consider adding a boolean has_value so you can bail early. Alternatively — better? — pull const auto& type = any.type() out into a local variable; the compiler might be able to tell that it's not modified after that point, and thus short-circuit the comparisons for you. (The compiler cannot inline or combine repeated calls to any.type() itself, though, because it's type-erased. The whole point of type-erasure is that the compiler won't be able to statically tell what that function does.) Compare to https://quuxplusone.github.io/blog/2020/09/29/oop-visit/ EDITED TO REPLY — You commented: R = typename all_the_same presumes that all the return types must be the same. std::visit [...] implies that R must be the same. I just decided to [return a] std::variant, so one could chain-pass it to another visitor. Right, std::visit basically takes many-possible-input-types and flattens them down to one-possible-output-type: the "visitor" callable must return the same type for each possible input type. Of course the programmer is free to make that single return type something complicated like std::variant<int, double> if they want to; but the STL doesn't force the programmer into that kind of complication if they don't want it. Compare: std::variant<int, double> v = 42; double r = std::visit( [](auto x) { return double(x + 1); }, v ); versus what they could have done: std::variant<int, double> v = 42; std::variant<int, double> r = std::visit( [](auto x) { return x + 1; }, v ); std::visit([](auto x) { std::cout << x; }, r); // chaining
{ "domain": "codereview.stackexchange", "id": 43218, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, template-meta-programming, variant-type, visitor-pattern", "url": null }
c++, c++17, template-meta-programming, variant-type, visitor-pattern and versus what the programmer can do if they feel like it: std::variant<int, double> v = 42; std::variant<int, double> r = std::visit( [](auto x) { return std::variant<int, double>(x + 1); }, v ); std::visit([](auto x) { std::cout << x; }, r); // chaining With my proposed API for your code, // the programmer can still deal in variants if they _want_ to... std::any v = 42; std::variant<int, double> r = impl::visit<int, double>( [](auto x) { return std::variant<int, double>(x + 1); }, v ); std::visit([](auto x) { std::cout << x; }, r); // chaining // ...they're just not _forced_ to. std::any v = 42; double r = impl::visit<int, double>( [](auto x) { return double(x + 1); }, v ); std::cout << r; // flattening
{ "domain": "codereview.stackexchange", "id": 43218, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17, template-meta-programming, variant-type, visitor-pattern", "url": null }
java, strings, library Title: Frame Strings that contain newlines Question: I have an application where I need to highlight some information that is printed to the console, so I wrote some static library methods which do that. I tested for bugs. Is my code clean and satisfying, or are there aspects to criticise? It has to work for multiple lines - given as a string that contains newlines and for arrays and lists. Compile with: javac *.java Run with: Main.java Example Output +---------------------------+ | one | | two three | | four | | let your dreams come true | | nothing is impossible | +---------------------------+ +--------+ | Single | +--------+ Main.java import java.util.List; import java.util.ArrayList; import java.util.Arrays;
{ "domain": "codereview.stackexchange", "id": 43219, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, strings, library", "url": null }
java, strings, library public class Main { public static void main(String[] args) { String string = "one\ntwo three\nfour\nlet your dreams come true\n"; string += "nothing is impossible"; System.out.println(makeBorderString(string)); System.out.println(makeBorderString("Single")); } // frames a string that contains newlines // does not work for strings that contain symbols that need more than one // space unit, for example tabs public static String makeBorderString(String value) { String[] lines = value.split("\\r?\\n"); return makeBorderStringFromArray(lines); } // does not work for strings that contain symbols that need more than one // space unit, for example tabs public static String makeBorderStringFromArray(String stringArray[]) { List<String> stringList = Arrays.asList(stringArray); return makeBorderStringFromList(stringList); } // does not work for strings that contain symbols that need more than one // space unit, for example tabs public static String makeBorderStringFromList(List<String> stringList) { // find most long line int mostLong = 0; for (int i = 0; i < stringList.size(); i++) { if (stringList.get(i).length() > mostLong) { mostLong = stringList.get(i).length(); } } StringBuilder sb = new StringBuilder(); // make upper Border border sb.append("+" + repeatSymbol('-', mostLong + 2) + "+\n"); // make body for (int i = 0; i < stringList.size(); i++) { String current = stringList.get(i); int whiteSpaceAmount = mostLong - current.length(); if (whiteSpaceAmount > 0) { String whitespace = repeatSymbol(' ', + whiteSpaceAmount); sb.append("| " + current + whitespace + " |\n"); } else {
{ "domain": "codereview.stackexchange", "id": 43219, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, strings, library", "url": null }
java, strings, library sb.append("| " + current + whitespace + " |\n"); } else { sb.append("| " + current + " |\n"); } } // make lower Border border sb.append("+" + repeatSymbol('-', mostLong + 2) + "+"); return sb.toString(); } public static String repeatSymbol(char symbol, int times) { if (times > 0) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < times; i++) { sb.append(symbol); } return sb.toString(); } return null; } }
{ "domain": "codereview.stackexchange", "id": 43219, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, strings, library", "url": null }
java, strings, library Answer: First of all, the solution is sound and rather well-structured. So, take my comments as hints towards production-quality coding. Class structure The algorithm for framing is in a class named Main, which also contains the main() method. Place it into a class with a better name, e.g. StringFramer, and omit the main() method there. This way, it's much easier to re-use it. (But maybe, you just pasted together a small class, just for this question - then everything is fine, probably.) If you want to test the functionality of your algorithm (and that's a good idea!), create test cases. You may want to read about JUnit, being a better alternative to main() methods for testing purposes. Documentation / comments // frames a string that contains newlines // does not work for strings that contain symbols that need more than one // space unit, for example tabs public static String makeBorderString(String value) { String[] lines = value.split("\\r?\\n"); return makeBorderStringFromArray(lines); } In your comment, the first line is important, as it documents the task of this method. This should become the summary in a Javadoc-formatted documentation comment (your IDE can create a template "with a single click"). The rest states a limitation. It should become part of the Javadoc as well (until you find a solution). If, on your roadmap, you plan to improve the method to support e.g. tab characters as well, a convention is to write TODO comments: // TODO find a solution for tab characters Your IDE understands this as some future task. If you feel tempted to write a comment in the middle of a method, take that as a hint that the following part might benefit from becoming a well-named method of its own, e.g. // make upper Border border sb.append("+" + repeatSymbol('-', mostLong + 2) + "+\n"); could then become addTopBorder(sb, mostLong);
{ "domain": "codereview.stackexchange", "id": 43219, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, strings, library", "url": null }
java, strings, library could then become addTopBorder(sb, mostLong); Implementation hints The code for the body can be simplified: // make body for (int i = 0; i < stringList.size(); i++) { String current = stringList.get(i); int whiteSpaceAmount = mostLong - current.length(); String whitespace = repeatSymbol(' ', whiteSpaceAmount); sb.append("| " + current + whitespace + " |\n"); } The only reason why this won't work with your current code out of the box is that the repeatSymbol() method returns null in the zero-count case instead of an empty String "". You should change that, as it also makes repeatSymbol() simpler, no longer needing the conditional: public static String repeatSymbol(char symbol, int times) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < times; i++) { sb.append(symbol); } return sb.toString(); } A loop like for (int i = 0; i < stringList.size(); i++) { String current = stringList.get(i); // ... } can be rewritten as: for (String current : stringList) { // ... } Visibility You made all methods public. For the three makeBorderStringXYZ() methods, this can be a valid decision, if you want to offer the framing algorithm for a variety of multi-line text representations. But then, the array and list version should get a documentation stating that the elements must represent single lines and not contain line break characters. I don't see a reason to make the repeatSymbol() method public. It's just meant to be an aid for the framing algorithm. If you instead want it to become a user-available string-manipulation method, place it into a StringUtils class (or similar). By default, make everything private, unless you really want foreign code to use it. Array declaration style In public static String makeBorderStringFromArray(String stringArray[]) {
{ "domain": "codereview.stackexchange", "id": 43219, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, strings, library", "url": null }
java, strings, library you use the C-style array declaration (which is frowned-upon in the Java world). Java developers prefer public static String makeBorderStringFromArray(String[] stringArray) { which more consistently declares that stringArray is a parameter with type String[]. (In the C language, there is some reason to write it the other way round, but that doesn't apply to Java - but alas, the original Java language designers allowed for that style as well.)
{ "domain": "codereview.stackexchange", "id": 43219, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, strings, library", "url": null }
c++, c++11, concurrency, trie, lock-free Title: Lock-free, thread-safe trie container Question: This is a Trie data structure for mapping strings to integers or pointers in O(n) time. Based on the idea that we never delete anything from the container, we can perform concurrent read/write operations without any locks. Note that TCMap is initialized separately, its role is to map relevant characters to indices. (We only need a subset of the ASCII table; letters, numbers, and a few symbols.) static const int TrieNChild = 40; class TrieCharMap { int m[256]; public: TrieCharMap(); TrieCharMap(const TrieCharMap& o) = delete; void operator = (const TrieCharMap& o) = delete; inline int operator [] (char x) { return m[(unsigned char)(x)]; } }; extern TrieCharMap TCMap; template <class T> class Trie { struct node { std::atomic<node*> p[TrieNChild] {}; std::atomic<T> z{}; void clear() { for (int i = 0; i < TrieNChild; i++) if (p[i]) ((node*)(p[i]))->clear(); } }; node root; std::mutex mtx; public: Trie() { } ~Trie() { root.clear(); } private: Trie(const Trie& o) {} void operator = (const Trie& o) {} public: T add(const char* s, T value) { //return old value node* x = &root; for (; *s; s++) { int i = TCMap[*s]; node* next = x->p[i]; if (!next) { next = new node; node* val = 0; if (!x->p[i].compare_exchange_strong(val, next, std::memory_order_relaxed, std::memory_order_relaxed)) { //someone else wrote the pointer, just use that delete next; next = val; } } x = next; } return x->z.exchange(value, std::memory_order_relaxed); }
{ "domain": "codereview.stackexchange", "id": 43220, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, concurrency, trie, lock-free", "url": null }
c++, c++11, concurrency, trie, lock-free T search(const char* s) { node* x = &root; for (; x && *s; s++) x = x->p[TCMap[*s]]; if (x) return x->z; return T{}; } }; Answer: Make it more generic Your Trie class is templated on the type of values stored in the trie, but it's hardcoded what the arity is. Now you can only use it for tries in which each node has exactly 40 children and for which the mapping between chars and indices is defined by TCMap. Consider making the arity a template parameter, and the mapping function a member variable: template <class T, std::size_t K> class Trie { struct node { std::atomic<node*> p[K] {}; ... } ... std::function<std::size_t(char)> charmap; public: Trie(std::function<std::size_t(char)> charmap): charmap(charmap) {} ... T search(const char* s) { ... x = x->p[charmap(*s)]; ... } }; The std::function looks heavy-weight, but the compiler might be able to optimize it away if it can see exactly what function is going to be called. Alternatively, you could just pass a reference to a std::array<int, 256> and move the mapping function into Trie itself. Consider using std::string_view if possible You tagged the post C++11, and std::string_view was only introduced in C++17, but if you can use it then it would be the preferred way of passing strings to add() and search(), as it will accept both const char * and std::strings then, and will allow you to use range-for loops: T search(std::string_view s) { ... for (auto c: s) x = x->p[TCMap[c]]; ... }
{ "domain": "codereview.stackexchange", "id": 43220, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, concurrency, trie, lock-free", "url": null }
c++, c++11, concurrency, trie, lock-free If you want to stay compatible with C++11, it might be worth adding overloads that accept const std::string &s as parameters for add() and search(). Remove mtx The mutex is not used, so it can be removed. Assert that the input is within bounds It's possible to supply an incorrect character map that returns indices larger than the number of children in a node. Consider adding an assert() statement before trying to index into the array: assert(TCMap[c] >= 0 && TCMap[c] < TrieNChild); x = x->p[TCMap[c]]; This will be able to catch bad behavior in debug builds, and should not have any overhead in release builds that define NDEBUG.
{ "domain": "codereview.stackexchange", "id": 43220, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, concurrency, trie, lock-free", "url": null }
c++, c, makefile Title: General Purpose Makefile Question: This is my "general purpose" makefile that I wrote with the following objectives in mind: Ready to use (copy/paste in a simple directory and it works out of the box) Flexible (easy to add compiler flags, link libraries, add other source directories) Settings to choose by passing them as arguments (optimizations, compiler, warnings) "IDE friendly" (multiple targets to choose from) That last point is probably somewhat subjective (I mainly use CLion and the makefile support is quite good). Obviously what seems easy to me like add a compiler flag or link a library might not be that straight forward so I would like to know what you think. In addition to your opinion on the code, its functionnalities and its ease of use, I have a few specific questions: The all target builds and then cleans the project only to leave the executable. I am also having it run the executable so it is very to use in my IDE (one click and my entire project is built and executed). What do you think about that? About the default compiler flags: would it be good practice to add others? If so, which ones? (the current flags are from CPP Best Practices) I don't have years of experience in software engineering (still a student) so I am having troubles seeing the limits of such a makefile: at what point would it be mandatory to switch to a more "advanced" build system ? #~~~~ control global settings ~~~~ # make opt=2 --> optimization for size + no debug # make opt=1 --> optimization + no debug # make opt=0 --> no optimization + debug opt=0 # make clang=1 --> use clang/clang++ # make clang=0 --> use gcc/g++ clang=0 # make no-warn=1 --> disable all warnings # make no-warn=0 --> enable all warnings no-warn=0 #~~~~ build program ~~~~ EXE_PREFIX=main #~~~~ detect operating system ~~~~ ifneq (${OS},Windows_NT) ifneq (,${findstring Ubuntu,${shell lsb_release -i 2>/dev/null}}) OS:=Ubuntu endif endif
{ "domain": "codereview.stackexchange", "id": 43221, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c, makefile", "url": null }
c++, c, makefile #~~~~ adjust project-specific settings ~~~~ CFLAGS = CPPFLAGS = CXXFLAGS = LDFLAGS = BINFLAGS = # additional include directory : CPPFLAGS+=-I header/path # linking precompiled libraries : LDFLAGS+=-L library/path -Wl,-rpath,library/path -l library_name #~~~~ source directories ~~~~# SRC_DIRS = . #~~~~ adjust platform-specific features ~~~~ ifneq (,${findstring Windows_NT,${OS}}) EXE_SUFFIX=.exe SKIP_LINE=echo. REMOVE=del /q else EXE_SUFFIX= SKIP_LINE=echo REMOVE=rm -rf endif #~~~~ deduce file names ~~~~ MAIN_C_FILES=${foreach d,${SRC_DIRS},${wildcard ${d}/${strip ${EXE_PREFIX}}*.c}} MAIN_CXX_FILES=${foreach d,${SRC_DIRS},${wildcard ${d}/${strip ${EXE_PREFIX}}*.cpp}} COMMON_C_FILES=${filter-out ${MAIN_C_FILES},${foreach d,${SRC_DIRS},${wildcard ${d}/*.c}}} COMMON_CXX_FILES=${filter-out ${MAIN_CXX_FILES},${foreach d,${SRC_DIRS},${wildcard ${d}/*.cpp}}} MAIN_OBJECT_FILES=${sort ${patsubst %.c,%.o,${MAIN_C_FILES}} \ ${patsubst %.cpp,%.o,${MAIN_CXX_FILES}}} COMMON_OBJECT_FILES=${sort ${patsubst %.c,%.o,${COMMON_C_FILES}} \ ${patsubst %.cpp,%.o,${COMMON_CXX_FILES}}} OBJECT_FILES=${MAIN_OBJECT_FILES} ${COMMON_OBJECT_FILES} DEPEND_FILES=${patsubst %.o,%.d,${OBJECT_FILES}} EXE_FILES=${sort ${patsubst %.c,%${EXE_SUFFIX},${MAIN_C_FILES}} \ ${patsubst %.cpp,%${EXE_SUFFIX},${MAIN_CXX_FILES}}} GENERATED_FILES=${DEPEND_FILES} ${OBJECT_FILES} ${EXE_FILES} GENERATED_FILES+=${wildcard output_* *~} WINDOWS_GENERATED_FILES:=${subst /,\,${GENERATED_FILES}} ifeq (${OS},Windows_NT) GENERATED_FILES=${WINDOWS_GENERATED_FILES} endif #~~~~ compiler/linker settings ~~~~ CFLAGS += -std=c99 CPPFLAGS += -Wall -Wextra -Wshadow -pedantic CXXFLAGS += -std=c++17 -Wnon-virtual-dtor LDFLAGS += BINFLAGS +=
{ "domain": "codereview.stackexchange", "id": 43221, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c, makefile", "url": null }
c++, c, makefile # consider these : # -Wold-style-cast -Wcast-align -Wunused -Woverloaded-virtual -Wpedantic -Wconversion -Wsign-conversion # -Wmisleading-indentation -Wduplicated-cond -Wduplicated-branches -Wlogical-op -Wnull-dereference # -Wuseless-cast -Wdouble-promotion -Wformat=2 -Wlifetime ifeq (${strip ${clang}},1) CC=clang CXX=clang++ else CC=gcc CXX=g++ endif ifneq (,${strip ${MAIN_CXX_FILES} ${COMMON_CXX_FILES}}) # force c++ link if there is at least one c++ source file LD:=${CXX} else LD:=${CC} endif #~~~~ debug/optimisation settings ~~~~ ifeq (${strip ${opt}},0) BINFLAGS+=-O0 -g endif ifeq (${strip ${opt}},1) BINFLAGS+=-O3 -s -DNDEBUG endif ifeq (${strip ${opt}},2) BINFLAGS+=-Os -DNDEBUG endif #~~~~ no warnings option ~~~~ ifeq (${strip ${no-warn}},1) BINFLAGS+=-w endif #~~~~ main target ~~~~ build : ${EXE_FILES} all : rebuild run rebuild : clean build clear .SUFFIXES: .SECONDARY: .PHONY: clean clear build rebuild run all #~~~~ linker command to produce the executable files (if any) ~~~~ %${EXE_SUFFIX} : %.o ${COMMON_OBJECT_FILES} @echo ==== linking [opt=${opt}] $@ ==== ${LD} -o $@ $^ ${BINFLAGS} ${LDFLAGS} @${SKIP_LINE} #~~~~ compiler command for every source file ~~~~ %.o : %.c @echo ==== compiling [opt=${opt}] $< ==== ${CC} -o $@ $< -c ${BINFLAGS} ${CPPFLAGS} ${CFLAGS} @${SKIP_LINE} %.o : %.cpp @echo ==== compiling [opt=${opt}] $< ==== ${CXX} -o $@ $< -c ${BINFLAGS} ${CPPFLAGS} ${CXXFLAGS} @${SKIP_LINE} -include ${DEPEND_FILES} #~~~~ remove all files ~~~~ clean : @echo ==== cleaning ==== ${REMOVE} ${GENERATED_FILES} @${SKIP_LINE} #~~~~ remove generated files ~~~~ clear : @echo ==== clearing ==== ${REMOVE} ${filter-out ${subst /,\,${EXE_FILES}},${GENERATED_FILES}} @${SKIP_LINE} #~~~~ run main file ~~~~ run : @echo ==== running ==== ${EXE_FILES} @${SKIP_LINE}
{ "domain": "codereview.stackexchange", "id": 43221, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c, makefile", "url": null }
c++, c, makefile #~~~~ run main file ~~~~ run : @echo ==== running ==== ${EXE_FILES} @${SKIP_LINE} Answer: The one thing I would note is that you are building object files into the same directory as the source. This means that you can potentially build debug objects and release objects in the same directory and then link them together. > make opt=1 > # Change some code in one file > make > # This make hasbuilt debug code while all the original files are > # built in release. Not all systems behave well when you link debug and release objects into the same lib/executable (they may have different ways of packing the structures). As a result, I tend to build object files into their own specific directory depending on type debug release profile. Then I know that when I build an executable / library, I simply link all the objects in a particular directory.
{ "domain": "codereview.stackexchange", "id": 43221, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c, makefile", "url": null }
c++, c, makefile Also a side nit for me is that dumping the whole command for building a C++ object dumps a lot of repetative stuff into the terminal making it hard to read. So I have made my Makefile simply echo a few important parameters when things are going well, but if there is an error then it dumps the full command the terminal. $(TARGET_MODE)/%.o: %.cpp | $(TARGET_MODE).Dir @if ( test "$(VERBOSE)" = "Off" ); then \ $(ECHO) $(call colour_text, GRAY, "$(CXX) -c $< $(OPTIMIZER_FLAGS_DISP) $(call expandFlag,$($*_CXXFLAGS))") | awk '{printf "%-80s", $$0}' ; \ elif ( test "$(VERBOSE)" = "On" ); then \ $(ECHO) '$(CXX) -c $< -o $@ $(CPPFLAGS) $(CXXFLAGS) $(call expandFlag,$($*_CXXFLAGS))' ; \ fi @export tmpfile=$(shell $(MKTEMP)); \ $(ECHO) $(call colour_text, GRAY, "$(CXX) -c $(OPTIMIZER_FLAGS_DISP) $(call expandFlag,$($*_CXXFLAGS))") $< | awk '{printf "%-80s", $$0}' ; \ $(CXX) -c $< -o $@ $(CPPFLAGS) $(CXXFLAGS) $(MOCK_HEADERS) $(call expandFlag,$($*_CXXFLAGS)) 2>$${tmpfile}; \ if [ $$? != 0 ]; \ then \ $(ECHO) $(RED_ERROR); \ $(ECHO) $(CXX) -c $< -o $@ $(CPPFLAGS) $(CXXFLAGS) $(MOCK_HEADERS) $(call expandFlag,$($*_CXXFLAGS));\ $(ECHO) "========================================";\ cat $${tmpfile}; \ exit 1; \ else \ $(ECHO) $(GREEN_OK); \ $(RM) $${tmpfile}; \ fi
{ "domain": "codereview.stackexchange", "id": 43221, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c, makefile", "url": null }
c++, c, makefile So if everything is compiling OK it looks like this: g++ -c -DCOVERAGE_test -DTHOR_COVERAGE FrameTest.cpp OK g++ -c -DCOVERAGE_test -DTHOR_COVERAGE unittest.cpp OK g++ -c -DCOVERAGE_test -DTHOR_COVERAGE BasicUpTest.cpp OK g++ -o coverage/unittest.app -DCOVERAGE_test -DTHOR_COVERAGE OK
{ "domain": "codereview.stackexchange", "id": 43221, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c, makefile", "url": null }
c++, c, makefile But if there is an error you get the full output like this: g++ -o coverage/unittest.app -DCOVERAGE_test -DTHOR_COVERAGE ERROR g++ -o coverage/unittest.app coverage/stringTest.o coverage/indexTest.o coverage/readTest.o coverage/unittest.o coverage/openTest.o coverage/tellTest.o coverage/writeTest.o coverage/seekTest.o coverage/Logging.o coverage/closeTest.o coverage/unittest.o -L./coverage -lUnitTest -L../coverage -L/home/travis/build/Loki-Astari/ThorsSerializer/third/ThorsStorage/build/dlib -L/home/travis/build/Loki-Astari/ThorsSerializer/third/ThorsStorage/build/lib -lgtest -fprofile-arcs -ftest-coverage -lpthread -L/home/travis/build/Loki-Astari/ThorsSerializer/third/ThorsStorage/build/lib -lThorsLogging17D =================================================== /home/travis/build/Loki-Astari/ThorsSerializer/third/ThorsStorage/build/lib/libThorsLogging17D.so: undefined reference to `dladdr' collect2: error: ld returned 1 exit status /home/travis/build/Loki-Astari/ThorsSerializer/third/ThorsStorage/build/tools/Makefile:438: recipe for target 'coverage/unittest.app' failed make[4]: *** [coverage/unittest.app] Error 1 /home/travis/build/Loki-Astari/ThorsSerializer/third/ThorsStorage/build/tools/Build/test.Makefile:45: recipe for target 'test/coverage/unittest.app' failed make[3]: *** [test/coverage/unittest.app] Error 2 /home/travis/build/Loki-Astari/ThorsSerializer/third/ThorsStorage/build/tools/Build/test.Makefile:28: recipe for target 'report/test' failed make[2]: *** [report/test] Error 2 /home/travis/build/Loki-Astari/ThorsSerializer/build/tools/Project.Makefile:49: recipe for target 'ThorsStorage.dir' failed make[1]: *** [ThorsStorage.dir] Error 2 /home/travis/build/Loki-Astari/ThorsSerializer/build/tools/Project.Makefile:49: recipe for target 'src.dir' failed make: *** [src.dir] Error 2 The command "export PATH=${PATH}:$(pwd)/build/bin;make" exited with 2.
{ "domain": "codereview.stackexchange", "id": 43221, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c, makefile", "url": null }
javascript, ecmascript-6, async-await, promise, modules Title: Using async / await with dynamic import() for ES6 modules Question: I am experimenting with the best way to standardise my dynamic import() expressions when importing javascript modules. import() returns a promise, so, to handle the asynchronous steps after theimport() expression, I can use either: .then() syntax; or async / await syntax Whilst I am quite familiar with the older XHR2 approach and somewhat familiar with ES2015 .then() syntax, I am less familiar with async / await syntax. I understand that I can only use await inside a function which has been declared or assigned with async. But I am trying to understand why Approach 1 works. Approach 1: (async () => { let myImportedModule = await import('/path/to/my-module.js'); myImportedModule.myFunction1(); myImportedModule.myFunction2(); })(); But Approach 2 does not. Approach 2: (async () => { await import('/path/to/my-module.js'); myFunction1(); myFunction2(); })(); Additional Notes: Clearly I have something wrong, but I thought Approach 2 would be the async / await equivalent of this snippet (using .then() syntax): import('/path/to/my-module.js') .then((myImportedModule) => { myImportedModule.myFunction1(); myImportedModule.myFunction2(); }); but that it would enable me to access myFunction1 and myFunction2 directly, without needing to give a name to the resolved Promise. Answer: Approach 2 does not work because accoring to MDN: import '/modules/my-module.js'; Is how you import a module for Import a module for its side effects only Import an entire module for side effects only, without importing anything. This runs the module's global code, but doesn't actually import any values. So, await import('/path/to/my-module.js'); won't actually import your myfunction1 and myFunction2 for you to use them, however, if you put an IIFE in there, it will be called. If you don't want to use long names to call your function, you can destructure them : (async () => {
{ "domain": "codereview.stackexchange", "id": 43222, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, ecmascript-6, async-await, promise, modules", "url": null }
javascript, ecmascript-6, async-await, promise, modules const { myFunction1, myFunction2 } = await import('/path/to/my-module.js'); myFunction1(); myFunction2(); })(); Or, call them in my-module.js and just import it and they will get called. See the answers here for es6 import for side effects meaning.
{ "domain": "codereview.stackexchange", "id": 43222, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, ecmascript-6, async-await, promise, modules", "url": null }
php Title: Verifying user login status Question: When a user logs in, I save a token (hashed password) to the user's folder on the server and send the token also to the app which is saved in localStorage. I need to check if the user's login token is valid upon every request made to the server. It's requested via AJAX using setTimeout, so next request is made only if previous call is completed (every 15 seconds). Currently I have this function that verifies the token i.e checks if the token from the app equals the one on the server: <?php if( verifyToken()) { //Success } else { //die }?> Below is the function verifyToken function verifyToken() { if ( empty( $_REQUEST['token'] ) || empty($_REQUEST['username'] ) ) { return false; } $username = $_REQUEST['username']; $user_token = $_REQUEST['token']; $secure_file = getUserDir( $username) . "/secure__.php"; if ( !file_exists( $secure_file) ) { return false; } $token = file_get_contents( $secure_file); if ( !$token ) { return false; } if( $token==$user_token ) { return true; } else { return false; } } Does my approach above have disadvantages or should I consider checking against the database every 15 seconds? I don't want to use sessions. Answer: The token is a "password" that is sent and saved in plain text Let me explain what I mean. Let's say a hacker gets access to your server, similar to what happened to GoDaddy (as an example off the top of my head). You're in a terrible position. The hacker doesn't have to do any cracking and can simply write a call like this to log in as any user using the exact values they got from the files: curl -d username=the_username -d token=the_token your.example.com
{ "domain": "codereview.stackexchange", "id": 43223, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php", "url": null }
php It is vulnerable to timing attacks The whole plain text thing mentioned above means that it's pretty easy to do a timing attack, made possible by the fact that you are using == (or ===) to check it. Any attacker can start by guessing different first letters and as soon as the response is even the slightest bit slower, they will know they have the right one. Rinse and repeat for the rest. They probably already know how long the token is supposed to be given that they can inspect what the AJAX call is sending. Crackers will run with this The ability to log into your system probably isn't as useful as the original password. Fortunately for the attacker, they have the hash of that and can get to cracking offline. Then they can try it on other sites to see who's reusing passwords. You should be following password best practices You can use password_verify to compare the password you got from the request to the stored hash of said password (note the mention that the function protects from timing attacks). Alternatively, use a solution that will do these things for you, one vetted by the community for security (e.g. an open-source framework). Other Changes You will have to do major rewrites to fix the major problems listed above. Here are the suggestions I have based on the rest of the code: Indent consistently. Your code is very, very hard to read because of your formatting. You can use an online prettifier to see what good formatting looks like. Use return types (function verifyToken(): boolean {) Use triple equals instead of double (but see above for the note about timing attacks)
{ "domain": "codereview.stackexchange", "id": 43223, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php", "url": null }
java, multithreading, asynchronous, spring Title: Collect and combine results of async calls returning completable futures in Java in a cleaner way? Question: I need an abstract way to implement this below functionality because in my code I have to use it in multiple places with different REST endpoints. If I ignore it will cause code duplication. Please suggest a good solution. This below code is working fine. I need a clean and simple way to write such calls every time I need to call an REST API call in batch and then collect the result of the batch into a list. A default way in Java or Spring or an own abstractions to handle such calls and retrievals. I want to a call a REST API then collect the result into a list and I want to make async calls to the API endpoint that will return list of objects in JSON. I need to call this REST endpoint more many times with particular batch size. /** * Retrieve basic Student Details(Student) details from Platform API service * asynchronously * API can process only 50 students so passing 50 studentIds at a time * to fetch and collect into a completable list and then process */ private List<Student> getstudentRecords(List<Integer> studentIds) throws InterruptedException, ExecutionException { List<List<Integer>> studentIdsPartitions = Lists.partition(studentIds, FETCH_STUDENT_BATCH_SIZE); List<Student> studentRecords = new ArrayList<>(); List<CompletableFuture<List<Student>>> studentRecordsOfBatchedstudentIdsFutureList = new ArrayList<>();
{ "domain": "codereview.stackexchange", "id": 43224, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, multithreading, asynchronous, spring", "url": null }
java, multithreading, asynchronous, spring // get studentRecord details from pst REST API asynchronously and collect them // in completable future list for (List<Integer> batchedstudentIds : studentIdsPartitions) { CompletableFuture<List<Student>> studentRecordsOfBatchedstudentIdsFuture = studentFetchService.retrieveStudents(batchedstudentIds); studentRecordsOfBatchedstudentIdsFutureList.add(studentRecordsOfBatchedstudentIdsFuture); } // collect studentRecord details synchronously(by blocking thread) to collect // from collected completable future list for (CompletableFuture<List<Student>> studentRecordsFuture : studentRecordsOfBatchedstudentIdsFutureList) { List<Student> StudentList = studentRecordsFuture.get(); studentRecords.addAll(StudentList); } return studentRecords; } @Component public class StudentFetchService{ @Async public CompletableFuture<List<Student>> retrieveStudents(List<Integer> studentIds) { return CompletableFuture.completedFuture( getStudentsFromPlatform(studentIds); ); } } private ResponseEntity<List<Student>> getStudentsFromPlatform(List<Integer> stdIds) { ResponseEntity<List<Student>> response; String stdIdsQueryParams = Optional.ofNullable(stdIds).orElseGet(Collections::emptyList) .stream().map(x->x.toString()).collect(Collectors.joining(",")); URI uri = UriComponentsBuilder.fromUriString("http://www.tomsheldondev.com/testapi/student") .queryParam("stdId", stdIdsQueryParams).build().encode().toUri(); response = restTemplate.exchange(uri, HttpMethod.GET, null, new ParameterizedTypeReference<List<Student>>() { }); return response; }
{ "domain": "codereview.stackexchange", "id": 43224, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, multithreading, asynchronous, spring", "url": null }
java, multithreading, asynchronous, spring Answer: Consider making the method generic and creating an interface for doing the REST API calls: static interface RequestService<T,S> { CompletableFuture<List<T>> request(List<S> inputs); } private <T,S> List<T> batchedFetch(RequestService<T,S> service, List<S> inputs) throws InterruptedException, ExecutionException { // maybe make BATCH_SIZE an input to this method List<List<S>> partitionedInput = Lists.partition(inputs, BATCH_SIZE); List<CompletableFuture<List<T>>> futureList = new ArrayList<>(); // get details from REST API asynchronously and collect them // in completable future list for (List<S> batchedInputs : partitionedInput) { CompletableFuture<List<T>> batchedFutures = service.request(batchedInputs); futureList.add(batchedFutures); } // collect responses synchronously(by blocking thread) to collect // from collected completable future list List<T> results = new ArrayList<>(futureList.size()); for (CompletableFuture<List<T>> future : futureList) { List<T> batchResults = future.get(); results.addAll(batchResults); } return results; } Now you can make calls that take different inputs and get different outputs by providing a different implementation for the RequestService: @Component public class StudentFetchService implements RequestService<Student,Integer> { @Override @Async public CompletableFuture<List<Student>> request(List<Integer> studentIds) { return CompletableFuture.completedFuture( getStudentsFromPlatform(studentIds) ); } } static class DoSomethingElseService implements RequestService<Boolean,String> { @Override public CompletableFuture<List<Boolean>> request(List<String> inputs) {
{ "domain": "codereview.stackexchange", "id": 43224, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, multithreading, asynchronous, spring", "url": null }
java, multithreading, asynchronous, spring return CompletableFuture.completedFuture( getResultsFromRestCall(inputs) ); } private List<Boolean> getResultsFromRestCall(List<String> inputs) { return Collections.emptyList(); // get real results here } } Try it out: void testIt() throws InterruptedException, ExecutionException { List<Student> students = batchedFetch(new StudentFetchService(), List.of(1,2,3)); List<Boolean> results = batchedFetch(new DoSomethingElseService(), List.of("one", "two", "three")); }
{ "domain": "codereview.stackexchange", "id": 43224, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, multithreading, asynchronous, spring", "url": null }
python, python-3.x, numpy, pandas Title: Stacking Z axis on multiple [1440x720] DataFrames (X, Y) Question: Each datum represents a point in a 1440x720 image of the globe, The values are 0-9. Each new layer is of a higher elevation. I need to structure a DataFrame in a way that allows me to "connect the values" and create geometric shapes. main.py from typing import Iterable import pandas as pd import numpy as np INDEX = pd.Index(np.linspace(90, -90, 720), name="Latitudes") COLUMNS = pd.Index(np.linspace(-180, 180, 1440), name="Longitudes") def random_frame(n: int = 10) -> Iterable[pd.DataFrame]: for _ in range(n): data = np.random.randint(9, size=(720, 1440)) yield pd.DataFrame(data, index=INDEX, columns=COLUMNS).stack() if __name__ == "__main__": df = pd.concat(random_frame(), axis=1).T df.index = df.index.rename("Elevation") * 1000 print(df)
{ "domain": "codereview.stackexchange", "id": 43225, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, pandas", "url": null }
python, python-3.x, numpy, pandas result Latitudes 90.0 ... -90.0 Longitudes -180.000000 -179.749826 -179.499653 -179.249479 -178.999305 -178.749131 -178.498958 -178.248784 -177.998610 -177.748436 ... 177.748436 177.998610 178.248784 178.498958 178.749131 178.999305 179.249479 179.499653 179.749826 180.000000 Elevation ... 0 2 2 3 8 4 2 0 0 7 0 ... 5 5 0 1 8 2 1 3 5 1 1000 7 6 8 8 4 5 0 7 6 1 ... 7 2 8 3 2 0 0 2 4 6 2000 0 3 0 5 3 2 0 2 6 1 ... 1 7 2 7 3 4 6 0 1 6 3000 4 6 1 1 6 7 3 3 3 6 ... 5 4 5 3 4 2 2 5 7 3
{ "domain": "codereview.stackexchange", "id": 43225, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, pandas", "url": null }
python, python-3.x, numpy, pandas 4000 8 8 1 8 0 3 6 4 8 3 ... 2 4 7 3 1 8 6 2 1 4 5000 6 0 5 7 0 5 8 1 6 0 ... 8 8 8 0 4 4 8 6 2 3 6000 2 1 5 2 1 6 6 6 8 5 ... 2 5 1 2 4 2 2 7 4 5 7000 6 8 5 8 5 8 7 1 3 4 ... 8 2 0 5 1 7 6 3 7 0 8000 0 2 0 7 7 4 5 4 2 5 ... 2 1 0 2 6 4 0 8 5 8 9000 6 7 1 3 6 3 4 2 6 2 ... 8 8 1 4 7 7 2 6 7 8
{ "domain": "codereview.stackexchange", "id": 43225, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, pandas", "url": null }
python, python-3.x, numpy, pandas [10 rows x 1036800 columns] Answer: Latitude, longitude and elevation are all independent variables. So why doesn't the output have a three-level index? There's only one dependent variable, "Risk", which should be your only column. np.linspace(90, -90, 720) is not good. Either include your endpoint and have 721 values, or exclude your endpoint and have 720 values. In either case the values should increment by exactly 0.25 (a quarter of one degree). Similar for COLUMNS. You've described these as "images of the globe". A (sane) image of the globe does not repeat pixels at the border of its longitudes, so I would expect that the longitudes use a half-open interval and the latitudes a closed interval.
{ "domain": "codereview.stackexchange", "id": 43225, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, numpy, pandas", "url": null }
python, python-3.x, image Title: Python script to convert scripts to png files Question: I have written a Python script that converts scripts to png files, entirely by myself without anybody's help. A picture is worth more than a thousand words so I will let the picture do the descriptions. Code import numpy as np from io import BytesIO from pathlib import Path from PIL import Image from pygments import highlight from pygments.formatters import ImageFormatter from pygments.lexers import get_lexer_by_name from pygments.style import Style from pygments.token import Name, Comment, String, Punctuation, Number, Operator, Literal, Keyword class MyStyle(Style): styles = { Keyword: 'bold #07487f bg:#00122a', Name: '#7b68ee bg:#00122a', Name.Builtin: 'italic #fb4570', Name.Class: 'bold italic #ffd700', Name.Constant: 'bold', Name.Decorator: 'bold italic', Name.Exception: 'bold italic #ff005d', Name.Function: 'bold italic #134dbc', Name.Namespace: 'bold italic #ffa000', Name.Variable.Class: 'bold', Name.Variable.Global: 'bold', Literal: '#00ff80 bg:#00122a', String: '#20ff40 bg:#00122a', String.Escape: 'italic #d06000', Number: '#00c0ff bg:#00122a', Operator: 'bold #408020 bg:#00122a', Operator.Word: 'bold #0000f0', Punctuation: '#ff00c0 bg:#00122a', Comment: 'italic #800080 bg:#00122a' }
{ "domain": "codereview.stackexchange", "id": 43226, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, image", "url": null }
python, python-3.x, image def script2png(filepath, language='python'): code = '\n'.join([i.rstrip() for i in Path( filepath).read_text(encoding='utf8').splitlines()]) formatter = ImageFormatter(style=MyStyle, full=True, font_name='Source Code Pro', font_size=16, line_number_bg='#003b6f', line_number_fg='#ff69b4', line_number_bold=True, line_pad=3) image = highlight(code, get_lexer_by_name(language), formatter) image = np.array(Image.open(BytesIO(image))) image[np.all(image == (255, 255, 255), axis=-1)] = (0, 18, 42) image = Image.fromarray(image) image.save(filepath+'.png') How is the code? This is my first time writing something like this, and I really want to know how to improve it.
{ "domain": "codereview.stackexchange", "id": 43226, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, image", "url": null }
python, python-3.x, image Answer: You're importing a lot of symbols from pygments.token. It is probably cleaner to alias that import and clean up your namespace a bit. I don't see why you're jumping through so many hoops when splitting and joining your text. Why not just read the entire file as a string and leave it be? pygments is poorly designed. It has a lot of internal inconsistencies, such as some Style members being respected for some formatter subclasses and not others. You should be moving as much styling information to your style class as possible. pygments has a deeply confused interpretation of line_number_bg: it can (and often is) expressed as Style.line_number_background_color, but the latter is only respected in CSS mode. Still: better to define it on your class, and manually pass it in for the ImageFormatter constructor that is broken and does not respect the style. Do not use Numpy or Pillow and do not replace your background by colour. Instead, define Style.background_color. Both your BytesIO and your Image should be put in a with for guaranteed closure. Unless you need to do something strange and non-standard, it is more convenient to remove your language argument and replace get_lexer_by_name with get_lexer_for_filename. If you absolutely require a .png you should be passing that format explicitly to the formatter. Otherwise, a reasonable implementation would be a script2img that allows the ImageFormatter to use its default format, whatever that may be; does not hard-code the .png suffix; and instead pulls that from formatter.image_format. Suggested from pathlib import Path from pygments import highlight from pygments.formatters import ImageFormatter from pygments.lexers import get_lexer_for_filename from pygments.style import Style import pygments.token as tokens class MyStyle(Style): background_color = '#00122a' # Only applies to HtmlFormatter line_number_background_color = '#003b6f' line_number_color = '#ff69b4'
{ "domain": "codereview.stackexchange", "id": 43226, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, image", "url": null }
python, python-3.x, image styles = { tokens.Keyword: f'bold #07487f bg:{background_color}', tokens.Name: f'#7b68ee bg:{background_color}', tokens.Name.Builtin: 'italic #fb4570', tokens.Name.Class: 'bold italic #ffd700', tokens.Name.Constant: 'bold', tokens.Name.Decorator: 'bold italic', tokens.Name.Exception: 'bold italic #ff005d', tokens.Name.Function: 'bold italic #134dbc', tokens.Name.Namespace: 'bold italic #ffa000', tokens.Name.Variable.Class: 'bold', tokens.Name.Variable.Global: 'bold', tokens.Literal: f'#00ff80 bg:{background_color}', tokens.String: f'#20ff40 bg:{background_color}', tokens.String.Escape: 'italic #d06000', tokens.Number: f'#00c0ff bg:{background_color}', tokens.Operator: f'bold #408020 bg:{background_color}', tokens.Operator.Word: 'bold #0000f0', tokens.Punctuation: f'#ff00c0 bg:{background_color}', tokens.Comment: f'italic #800080 bg:{background_color}', } def script2img(filepath: Path) -> None: formatter = ImageFormatter( style=MyStyle, full=True, line_pad=3, font_name='Source Code Pro', font_size=16, line_number_bold=True, line_number_fg=MyStyle.line_number_color, line_number_bg=MyStyle.line_number_background_color, ) buffer = highlight( code=filepath.read_text(), lexer=get_lexer_for_filename(filepath), formatter=formatter, ) with filepath.with_suffix( '.' + formatter.image_format ).open('wb') as f: f.write(buffer) if __name__ == '__main__': script2img(Path('275768.py')) Output Rendering its own source, This works equally well (still without passing a language) when inferring Java:
{ "domain": "codereview.stackexchange", "id": 43226, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, image", "url": null }
python, python-3.x, image This works equally well (still without passing a language) when inferring Java: Caching configuration If you're rendering multiple files at a time, you may want to make a class version that caches the instantiated formatter: from pathlib import Path from pygments import highlight from pygments.formatters import ImageFormatter from pygments.lexers import get_lexer_for_filename from pygments.style import Style import pygments.token as tokens class MyStyle(Style): background_color = '#00122a' # Only applies to HtmlFormatter line_number_background_color = '#003b6f' line_number_color = '#ff69b4' styles = { tokens.Keyword: f'bold #07487f bg:{background_color}', tokens.Name: f'#7b68ee bg:{background_color}', tokens.Name.Builtin: 'italic #fb4570', tokens.Name.Class: 'bold italic #ffd700', tokens.Name.Constant: 'bold', tokens.Name.Decorator: 'bold italic', tokens.Name.Exception: 'bold italic #ff005d', tokens.Name.Function: 'bold italic #134dbc', tokens.Name.Namespace: 'bold italic #ffa000', tokens.Name.Variable.Class: 'bold', tokens.Name.Variable.Global: 'bold', tokens.Literal: f'#00ff80 bg:{background_color}', tokens.String: f'#20ff40 bg:{background_color}', tokens.String.Escape: 'italic #d06000', tokens.Number: f'#00c0ff bg:{background_color}', tokens.Operator: f'bold #408020 bg:{background_color}', tokens.Operator.Word: 'bold #0000f0', tokens.Punctuation: f'#ff00c0 bg:{background_color}', tokens.Comment: f'italic #800080 bg:{background_color}', }
{ "domain": "codereview.stackexchange", "id": 43226, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, image", "url": null }
python, python-3.x, image class Highlighter: def __init__(self) -> None: self.formatter = ImageFormatter( style=MyStyle, full=True, line_pad=3, font_name='Source Code Pro', font_size=16, line_number_bold=True, line_number_fg=MyStyle.line_number_color, line_number_bg=MyStyle.line_number_background_color, ) self.extension = '.' + self.formatter.image_format def script_to_image(self, filepath: Path) -> Path: buffer = highlight( code=filepath.read_text(), lexer=get_lexer_for_filename(filepath), formatter=self.formatter, ) out_path = filepath.with_suffix(self.extension) with out_path.open('wb') as f: f.write(buffer) return out_path if __name__ == '__main__': Highlighter().script_to_image(Path('275768.py'))
{ "domain": "codereview.stackexchange", "id": 43226, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, image", "url": null }
c++, c++11, locking, wrapper, raii Title: Data Wrapper Class with Automatic Saving and Locked Read/Write Accessors Question: This is a wrapper for a synchronized data structure that: Saves periodically Keeps track of dirty flag automatically (set when a write access is requested) Maintains a lock on data Only allows access via a scoped lock object Works with any data class that has a ::save() template <class DataType> class MemDB { std::mutex mtx; DataType *data; std::atomic_bool data_changed; time_t last_save_time, save_interval; void save() { std::lock_guard<std::mutex> lock(mtx); data->save(); data_changed = false; last_save_time = time(0); } public: MemDB(DataType *data, time_t save_interval = 300) : data_changed(false), last_save_time(0), save_interval(save_interval) {} virtual ~MemDB() { save(); } void idle() { if (data_changed && time(0)-last_save_time > save_interval) save(); } template <class AccessDataType> class Accessor { std::lock_guard <std::mutex> lock; AccessDataType data; public: Accessor(std::mutex& m, AccessDataType data) : lock(m), data(data) {} Accessor(std::mutex& m, AccessDataType data, std::atomic_bool &notify_flag) : lock(m), data(data), notify_flag(notify_flag) { notify_flag = true; } Accessor(const Accessor&) = delete; void operator = (const Accessor&) = delete; AccessDataType operator ->() { return data; } }; Accessor <const DataType*> reader() { return Accessor <const DataType*>(mtx, data); } Accessor <DataType*> writer() { return Accessor <DataType*>(mtx, data, data_changed); //set data_changed only after lock acquired } }; EDIT: just some notes on usage, you basically create the MemDB object and then make sure you call idle() every once in a while.
{ "domain": "codereview.stackexchange", "id": 43227, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, locking, wrapper, raii", "url": null }
c++, c++11, locking, wrapper, raii Answer: Design review I’m afraid this design is a bad idea. I have seen multiple attempts to do something like this, and I understand the impulse. Synchronization is loud, dangerous, and takes up valuable code real estate in your algorithms, making it harder to suss out what’s actually going on. It’s only natural to want to hide all that behind a clean, simple interface. But maybe it should be loud, dangerous, and obtrusively visible. Maybe, as with other dangerous stuff, like type-punning, it should be clearly visible where you’re doing it in the code. Like reinterpret_cast, the sight of synchronization primitives and locking could serve as a red flag: “there be dragons here; check this code carefully, and do not fuck with it unless you are absolutely sure you know what you’re doing.” See, I would say the real problem is that you have data that is both shared, and mutable. That is the thing you should be trying to redesign your code to fix. The presence of the synchronization primitives and locking is a symptom of that underlying problem… it’s not the problem in-and-of itself. Okay, but let me stop speaking in abstract and show you exactly why this design is bad: This class can break your entire program, if only two instances of it exist. Actually, it only takes one instance of this class, and any other lockable. Here’s how. Imagine you have a program that has exactly two instances of MemDB in it. We’ll be unimaginative and call ’em data_1 and data_2. Let’s say you have a situation where you need to code some kind of operation involving both data_1 and data_2. Let’s say you have to remove some data from one, and put it in the other. And let’s say that transaction has to be atomic… meaning it’s either completely finished, or not started at all; there can never be a situation where it’s only half-done. For example, there is some kind of periodic auditing operation checking for fraud or cheating or whatever, and if it sees that any data is “missing”, it will panic.
{ "domain": "codereview.stackexchange", "id": 43227, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, locking, wrapper, raii", "url": null }
c++, c++11, locking, wrapper, raii No problem, though. This is trivial to code. Just lock both data sets, do the operation while holding both locks, then unlock ’em both. Simple. It’s just this: writer_1 = data_1.writer(); writer_2 = data_2.writer();
{ "domain": "codereview.stackexchange", "id": 43227, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, locking, wrapper, raii", "url": null }