text
stringlengths
1
2.12k
source
dict
javascript, vue.js <p>Ranked occurrences:</p> <ol class="half"> <li v-for="value in counter_display_values.sorted_values" v-bind:key="value"> {{ value }} </li> </ol> </div> </template> <style> .full { height: 250px; } .half { height: 110px; } </style> The implementation: Two components: Parent: CounterInDis.vue and child: CounterDisplay.vue. CounterInDis.vue has a "number" input field bound to the variable increment. And a button that fires the function increment_count. increment_count passes increment to the function is_increment_a_number that loosely checks if increment is a number, and either returns 0 if typeof increment != 'number' or returns increment. if is_increment_a_number returned a 0, increment_amount exits. otherwise: it updates the variable last_value with increment (regardless if it's increment === last_value or not). then, it adds increment to the variable count (the count). then, it passes increment to the function update_values_occurrence. update_value_occurrence creates a new entry in the values_occurrence dict if increment isn't already there with the refcount of 0, then it increments the refcount by 1. then, it (increment_count) fires the function sort_by_occurrence. sort_by_occurrence get values_occurrence's entries, sort them (which refcount is greater) then map the sorted keys to the array sorted_values. by now, computed detected changes in the variables it's watching (basically, all of them) and pass them down as props the child component. something i don't understand: inside the object returned by computed: sorted_values: this.sorted_values won't display the array in the child component. sorted_values: sorted_values shows the array inside the child component. why? inside CounterDisplay.vue: the properties of the object get displayed.
{ "domain": "codereview.stackexchange", "id": 45114, "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, vue.js", "url": null }
javascript, vue.js a v-for that iterates over* the sorted_values array and uses each value as its own key -> My reasoning is that this ensures the keys will remain unique since no value can have a duplicate. Is my reasoning correct? Is there a better way to generate the list items and move them around based on their rank? Thank you (: Answer: You don't need these: let count = 0; let increment = 0; let last_value = 0; let values_occurrence = {}; let sorted_values = []; Instead you should assign those values within the data() of your component. This is actually the reason why this.sorted_values doesn't work, because this line: sorted_values = keys_n_values.map((entry) => entry[0]); is reassigning the outer sorted_values but not this.sorted_values. As the outer sorted_values changes reference completely, the outer sorted_values is now separated from this.sorted_values. If you would have had more than one component of CounterInDis this would have caused a bug that both of them are using the same sorted_values data. Always put your component-specific values inside the component and don't use data from outside! sorted_values could actually be a computed property, and as such there's no need for the sort_by_occourence at all -- all that code can actually just be the computed property: computed: { ... sorted_values() { let keys_n_values = Object.entries(this.values_occurrence); keys_n_values.sort((a, b) => b[1] - a[1]); return keys_n_values.map((entry) => entry[0]); } } (I wouldn't use const keys_n_values because you are mutating the array with sort) this.counter can also be a computed property because it is just the sum of all values keys in the array multiplied by their value. a v-for that iterates of the sorted_values array and uses each value as its own key -> My reasoning is that this ensures the keys will remain unique since no value can have a duplicate.
{ "domain": "codereview.stackexchange", "id": 45114, "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, vue.js", "url": null }
javascript, vue.js That reasoning is correct, yes. Just a tip: v-bind:key is the same as :key. Prefer to be consistent, in some cases - e.g. :counter_display_values you are just using the colon.
{ "domain": "codereview.stackexchange", "id": 45114, "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, vue.js", "url": null }
php, datetime Title: Four functions to measure and compare months of duration from one or two dates Question: I decided to write a few related examples of code, and honestly I don't know if I am overthinking, or just trying to find what is that right way to write functions and how to use them, so that codebase can be as clean as possible and function names are easy to understand and suitable for reuse. Here's is what I have to demonstrate it, 4 separate functions: <?php // Function 0 function monthsPassed($startDate, $endDate) { $startDateObj = new DateTime($startDate); $endDateObj = new DateTime($endDate); $DateInterval = $endDateObj->diff($startDateObj); $months = (($DateInterval->y) * 12) + ($DateInterval->m); return $months; } // Function 1 function monthsPassed_CurrentDate($startDate) { $startDateObj = new DateTime($startDate); $endDateObj = new DateTime('now'); $DateInterval = $endDateObj->diff($startDateObj); $months = (($DateInterval->y) * 12) + ($DateInterval->m); return $months; } // Function 2 function hasMonthPassed($startDate, $endDate) { $monthsPassed = monthsPassed($startDate, $endDate); return $monthsPassed >= 1; } // Function 3 function hasMonthPassed_CurrentDate($startDate) { $monthsPassed = monthsPassed_CurrentDate($startDate); return $monthsPassed >= 1; } $startDate = '2000-01-11'; $endDate = '2000-02-11'; // Function 0 Call monthsPassed($startDate, $endDate); // Function 1 Call monthsPassed_CurrentDate($startDate); // Function 2 Call hasMonthPassed($startDate, $endDate); // Function 3 Call hasMonthPassed_CurrentDate($startDate);
{ "domain": "codereview.stackexchange", "id": 45115, "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, datetime", "url": null }
php, datetime // Function 3 Call hasMonthPassed_CurrentDate($startDate); Now these are fairly simple functions and I'm asking about code reuse and clarity which function should I use. Let me explain my thinking. These above all are the different variations of functions I came up with that calculate how many months passed between two dates, first two functions are more flexible, other next two are more suited for more specific case. "Function 0" takes in two string arguments - $startDate, $endDate, returns $months (integer). My observation: This function looks fairly flexible since I can pass any two valid dates. "Function 1" takes one string argument - $startDate, returns $months (integer). My observations: This function seems convenient when I need to compare it with current DateTime so I don't have to pass it manually; the function name is expressive. "Function 2" takes two string arguments - $startDate, $endDate returns boolean. My observations: This function is convenient to know whether at least one month passed between two dates. It also reuses 'monthsPassed' function, so it doesn't reimplement similar logic but promotes code reuse. The thing here is that I pass two dates. "Function 3" takes one string argument - $startDate, returns boolean. My observations: This is fairly the same as "Function 2" but I only pass $startDate, and that function takes care of comparing my $startDate with the current DateTime value, so I don't need to pass it and it promotes code reuse. Now consider such scenario that I will have to use such checks in my codebase at least 10 times, where I have to check if at least one month has passed between $startDate and currentDate.
{ "domain": "codereview.stackexchange", "id": 45115, "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, datetime", "url": null }
php, datetime Which function would you use, which one would you prefer and why? Are there any hard rules, or doesn't it matter? Should I always aim to promote code reuse in my project and by having more general functions build more specific functions from that, or should I just straightforwardly implement exact specific logic in one function and do not rely on other functions to build my more specific function like hasMonthPassed?
{ "domain": "codereview.stackexchange", "id": 45115, "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, datetime", "url": null }
php, datetime It seems that these little functions could be handy, where you don't need to pass current date, but if flexibility is needed then more general function is suitable that can return $months number. I think I'm struggling to find a good balance what should I do, having many small similar functions, and I hate to always do that guesswork if I should micro-optimize or over-engineer something small, meanwhile maybe I just need to use one way and stick to it, but would like to hear advice or opinions, what is the most viable option here. As a side question, I also would like to ask in case of providing dates to functions (maybe it does apply to elsewhere to). Is it better practice to provide dates as strings, or should I provide DateTime objects outside of a function so functions do not depend on DateTime, which maybe is cleaner, but I am confused. Should we be afraid of relying on built-in PHP classes, objects, methods, functions and using them inside of functions, or should we always strive to pass objects, other dependencies no matter what they are only outside of functions? To me it looks cleaner to pass new DateTime() to arguments, meanwhile I am not sure, because it is a built-in PHP class, so I don't feel like it would give me so much benefit of passing DateTime outside of a function, since even if I can pass other implementations that could deal with DateTime it does not guarantee that they will come with the same properties or methods, so it's like all this clean stuff is for no good use if you would have to use different methods inside of your function if you use some kind of other DateTime library. Answer: You have a bucket load of questions in your question. I'm not sure I'll be able to answer them all, but I will give it a try. First the code. Things I notice immediately are:
{ "domain": "codereview.stackexchange", "id": 45115, "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, datetime", "url": null }
php, datetime Function 1 repeats function 0 with only a slight difference. Function 3 doesn't use function 2, which would have made sense. Function names combine camelCase and snake_case. Use of parenthesis where they are not needed. The use of the variable $months inside the functions doesn't make much sense. Not using default values for parameters, see code below. Incorporating these changes gives: <?php // Function 0 & 1 function monthsBetween($date1, $date2 = NULL) { if (is_null($date2)) { $date2 = new DateTime("now"); } $interval = $date2->diff($date1); return 12 * $interval->y + $interval->m; } // Function 2 & 3 function hasMonthBetween($date1, $date2 = NULL) { return monthsBetween($date1, $date2) > 0; } $startDate = new DateTime('2000-01-11'); $endDate = new DateTime('2000-02-11'); // Function 0 Call echo monthsBetween($startDate, $endDate) . PHP_EOL; // Function 1 Call echo monthsBetween($startDate) . PHP_EOL; // Function 2 Call echo hasMonthBetween($startDate, $endDate) . PHP_EOL; // Function 3 Call echo hasMonthBetween($startDate) . PHP_EOL;
{ "domain": "codereview.stackexchange", "id": 45115, "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, datetime", "url": null }
php, datetime DEMO: https://3v4l.org/WioCJ Obviously I have chosen to turn stringy dates into PHP objects before using these functions. The reason is obvious, when you look at the code. Another good argument for this is that you often need to make sure stringy dates are valid before you use them, and converting them to objects is one way of doing this. Notice how I can merge 2 function together because of the use of NULL as the default value for the second argument. I renamed the functions slightly. I agree that "passed" and "between" are quite similar, but I felt that "between" more clearly describes that these functions look at the interval "between" the dates. Now, given this, let me look at your questions again: I think that hasMonthBetween($date1, $date2) and monthsBetween($date1, $date2) > 0 look very similar. As Your Common Sense already said; It's up to you. I'm always in favor of general functions and code reuse. This doesn't mean you cannot have a function like hasMonthBetween(). It depends on what your code needs to do. The function makes perfect sense when the question, whether two dates have a month between them, is important in your software. I prefer shorter functions, because they are easier to read and understand. It's really time to refactor when a function is longer than what fits on your computer screen. Shorter functions are often also easier to test. If this means you'll have more functions then so be it. Built-in PHP classes, objects, methods, and functions are part of the PHP language. With some exceptions, which are always documented in the manual, you can use them freely everywhere. Don't view them as risky "dependencies". Of course, some features of PHP do get deprecated over time, but it's hard to predict which those will be, and you shouldn't be held hostage by this. Finally: You can use Type declarations in your function declarations: function monthsBetween(DateTime $date1, DateTime $date2 = NULL)
{ "domain": "codereview.stackexchange", "id": 45115, "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, datetime", "url": null }
php, datetime DEMO: https://3v4l.org/68Qur This way you'll get an error message when you supply a stringy date or another type of object. Your functions don't need them, but have a look at DateTimeImmutable, they are preferred because the normal DateTime can often cause unexpected effects when you use them as function arguments.
{ "domain": "codereview.stackexchange", "id": 45115, "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, datetime", "url": null }
python, parsing, json Title: Using argparse with parameters defined in config file Question: I understand that and why using eval is generally considered bad practice in most cases (see e.g. here). Related questions on config files and argparse don't use types. (1, 2) I needed to parse a number of command line arguments and decided to store the arguments, defaults and help strings in a .json file. I read the .json and add every argument to an argparse.ArgumentParser. To specify a type I need to pass a callable like float and not the string "float". To get from the string to the callable I thought of using eval using a dict to map from string to callable using a if/else or switch and decided to use to use eval to avoid hard coding all types. I have no security concerns because the argument file is supplied by the user and the program that uses this code is targeted at scientists that will realistically want to change the file to add parameters or change defaults. (Also, it is a university project which will never be run except for grading. I handed in a version using eval.) Is there a smart solution avoiding hardcoding all types and avoiding eval, or did I find a place where eval is a sensible choice? I was only allowed to use the standard library. Minimal args.json: { "dt": { "type": "float", "help": "Time step size", "default": 0.4}, "T": { "type": "int", "help": "Time steps between outputs", "default": 50}, "f": { "type": "str", "help": "Landscape file name", "default": "small.dat"} } Runnable code, put args.json above in same directory to run: import json import argparse import pprint def setup_parser(arguments, title): parser = argparse.ArgumentParser(description=title, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
{ "domain": "codereview.stackexchange", "id": 45116, "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, parsing, json", "url": null }
python, parsing, json for key, val in arguments.items(): parser.add_argument('-%s' % key, type=eval(val["type"]), help=val["help"], default=val["default"]) return parser def read_params(parser): parameters = vars(parser.parse_args()) return parameters def get_parameters(title=None): with open("args.json") as data_file: data = json.load(data_file) parser = setup_parser(data, title) parameters = read_params(parser) return parameters if __name__ == "__main__": params = get_parameters() pprint.pprint(params) Answer: I don't like the eval here anywhere for the usual reasons. I think you have two better options here: Find the right type within all builtin types See https://stackoverflow.com/a/3222774/620382 (use builtins for python3) Use the type of the default value from json. Json types are properly translated to python. type(val['default']) will provide this type. You can check with __name__ == val['type'] if you want to keep the redundancy. Of course you then should make sure to use "default": 0.0 if the value should be float.
{ "domain": "codereview.stackexchange", "id": 45116, "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, parsing, json", "url": null }
c++, programming-challenge, design-patterns, c++17 Title: C++, sort integers using knowledge of entire vector Question: I am solving the "Sort" problem on Kattis. Mirko is a great code breaker. He knows any cipher in the world can be broken by frequency analysis. He has completely the wrong idea what frequency analysis is, however. He intercepted an enemy message. The message consists of N numbers, smaller than or equal to C. Mirko belives freqency analysis consists of sorting this sequence so that more frequent numbers appear before less frequent ones. Formally, the sequence must be sorted so that given any two numbers X and Y, X appears before Y if the number of times X appears in the original sequence is larger than the number of time Y does. If the number of appearances is equal, the number whose value appears sooner in the input should appear sooner in the sorted sequence. Help Mirko by creating a “frequency sorter”. Input First line of input contains two integers, N (1≤N≤1000), the length of the message, and C (1≤C≤1000000000), the number from the task description above. The next line contains N positive integers smaller than or equal to C, the message itself. Basically, the problem is as follows. Let xs be a nonempty vector of positive integers. There are only few integers in this vector, but they have a big range. (The maximum value c is given in the problem, but my code does not use the information.) Sort the integers according to the following criteria. For any two elements x and y of xs, if x occurs more often than y, then x appears first; if y appears more often, y appears first. If x and y appear equally often, then x occurs first if the very first occurrence of x is earlier than that of y.
{ "domain": "codereview.stackexchange", "id": 45117, "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++, programming-challenge, design-patterns, c++17", "url": null }
c++, programming-challenge, design-patterns, c++17 I use a comparison sort (provided by the C++ runtime) with a smart comparator. This comparator knows the frequency and the index of the first appearance of every element. This information is not inherent to the integers. Rather, it depends entirely on their location within the vector. This contextual information is generated when a comparator is created for a given vector. Upon application on elements x and y, it returns true if x must appear before y. I have used custom comparators before, but never have I used anything that contains state. In the disassembly with -Os I see many copy and move constructors called under sort(vector<unsigned> &). The code passes all tests, and it's not slow. But I wonder why the disassembly reveals so many copy and move calls, and whether this pattern of using heavy comparators is discouraged in C++. If this looks like a known pattern, I want to know its name. I appreciate general comments and insights. #include <vector> #include <set> #include <map> #include <algorithm> #include <iostream> typedef std::vector<unsigned> vector; /// Comparison based on knowledge of the entire vector struct compare { std::multiset<unsigned> bag; std::map<unsigned, size_t> indices; /// Extract frequency and initial index of every element. explicit compare(vector const &xs) { for (size_t i = 0u; i < xs.size(); ++i) { unsigned const x = xs[i]; bag.insert(x); if (!indices.count(x)) { indices[x] = i; } } } /// True if `x` must go before `y`. [[nodiscard]] bool operator()(unsigned x, unsigned y) const { return bag.count(x) > bag.count(y) || (bag.count(x) == bag.count(y) && indices.at(x) < indices.at(y)); } }; static void sort(vector &v) { compare c(v); std::sort(v.begin(), v.end(), c); }
{ "domain": "codereview.stackexchange", "id": 45117, "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++, programming-challenge, design-patterns, c++17", "url": null }
c++, programming-challenge, design-patterns, c++17 static void sort(vector &v) { compare c(v); std::sort(v.begin(), v.end(), c); } int main() { vector v; { // Get `n` unsigned integers from console. // Unused: `c` (upper bound for integers) unsigned n, c; std::cin >> n >> c; v.reserve(n); while (n--) { unsigned x; std::cin >> x; v.push_back(x); } } // Sort according to the problem description sort(v); // Print all for (unsigned const x : v) { std::cout << x << ' '; } return 0; } Update Summary: Used shared pointers to enforce shared ownership w/o overhead According to G. Sliepen, the internal implementation of std::sort by g++ makes many copy of the Compare object. So, I decided to keep a smart pointer inside the object that takes care of simultaneous uses by different instances of the internal function calls. #include <memory> === struct compare { private: struct vector_context { std::multiset<unsigned> bag; std::map<unsigned, size_t> indices; }; std::shared_ptr<vector_context> context; public: explicit compare(vector const &xs) : context(new vector_context) { for (size_t i = 0u; i < xs.size(); ++i) { unsigned const x = xs[i]; context->bag.insert(x); if (!context->indices.count(x)) { context->indices[x] = i; } } } [[nodiscard]] bool operator()(unsigned x, unsigned y) const { return context->bag.count(x) > context->bag.count(y) || (context->bag.count(x) == context->bag.count(y) && context->indices.at(x) < context->indices.at(y)); } }; The code change is minimal, and the runtime has improved four-fold.
{ "domain": "codereview.stackexchange", "id": 45117, "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++, programming-challenge, design-patterns, c++17", "url": null }
c++, programming-challenge, design-patterns, c++17 The code change is minimal, and the runtime has improved four-fold. Answer: The main issue is that the comparator object is passed by value. Not only from your application to std::sort(), but it's also passed by value internally in the implementation of std::sort(). This means that bag and indices get copied by value a lot. So you ideally want to generate those only once, and then have class compare store a pointer or reference to those. I think there are several possible approaches; you could keep the constructor mainly as it is, but instead of storing those vectors directly, use a std::shared_ptr to manage their storage. The default copy constructor will then just take care of updating the refcounts for you: struct compare { std::shared_ptr<std::multiset<unsigned>> bag; std::shared_ptr<std::map<unsigned, size_t>> indices; /// Extract frequency and initial index of every element. explicit compare(vector const &xs): bag{new std::multiset<unsigned>}, indices{new std::map<unsigned, size_t>}, { for (size_t i = 0u; i < xs.size(); ++i) { unsigned const x = xs[i]; bag->insert(x); if (!indices->count(x)) { (*indices)[x] = i; } } } /// True if `x` must go before `y`. [[nodiscard]] bool operator()(unsigned x, unsigned y) const { return bag->count(x) > bag_>count(y) || (bag->count(x) == bag->count(y) && indices->at(x) < indices->at(y)); } }; You can improve this further by combining bag and indices into on struct, so you only need one std::shared_ptr to hold them.
{ "domain": "codereview.stackexchange", "id": 45117, "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++, programming-challenge, design-patterns, c++17", "url": null }
python, python-3.x Title: yet another number of islands Question: i learn python and i am at beginner level in python TL`DR i did NOT read the other questions concerning this topic since i try to learn python and therefore need to do the same stoopid errors others have done to improve my knowlegde. And since i know other things than the other OPs is my code somehow different class Field (in islands.py) class Field: def __init__(self, xpos, ypos, isWater): self.xpos = xpos self.ypos = ypos self.isWater = isWater def __str__(self): iswater = "W" if self.isWater else "L" return f"{self.xpos}/{self.ypos}/{iswater}" def isAdjected(self, anotherField): if anotherField is None: return False if not isinstance(anotherField, Field): return False if anotherField.xpos == self.xpos and anotherField.ypos+1 == self.ypos: return True if anotherField.xpos == self.xpos and anotherField.ypos-1 == self.ypos: return True if anotherField.xpos+1 == self.xpos and anotherField.ypos == self.ypos: return True if anotherField.xpos-1 == self.xpos and anotherField.ypos == self.ypos: return True return False class Map (in islands.py) class Map: def __init__(self, data:list): x = 0 self.fields = list() for row in data: y = 0 for column in row: a_field = Field(x,y,column=='0') self.fields.append(a_field) y = y + 1 x = x + 1 def __str__(self): return f"island data={self.fields}" def calculate_number_of_islands(self) -> int: print ("removing all water fields") candidates = list(filter(lambda field : not field.isWater, self.fields)) islandcounter = 0 while len(candidates) > 0 : candidate = candidates.pop(0) print (f"popping next field {candidate} and expanding an island") self.expand_land(candidate, candidates) islandcounter = islandcounter + 1
{ "domain": "codereview.stackexchange", "id": 45118, "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", "url": null }
python, python-3.x return islandcounter def expand_land(self, candidate, candidates): print ("getting neighbour fields") neighbours = list(filter(lambda field : field.isAdjected(candidate), candidates)) for neighbour in neighbours: print (f" adding {neighbour}") if(neighbour in candidates): candidates.remove(neighbour) self.expand_land(neighbour, candidates) return None main method import island_parser import island #https://leetcode.com/problems/number-of-islands/description/ csvFile = 'resources\\island_01.csv' data = island_parser.read_csv(csvFile) island_map = island.Map(data) number_of_islands = island_map.calculate_number_of_islands() print (f"this map has {number_of_islands} islands") note i did not include the data parser to parse an csv into a List<List<String>> that is not part of the review data is a List<List<String>> where each String is either 0 (water) or 1 (land), example here: 1,1,0,1,0 1,1,1,1,0 0,0,0,0,0 1,0,0,1,1 resulting in an number of 3 islands any comments welcome! Answer: python != java self.isWater = isWater In Field, pep-8 asks that you name it is_water. Also, please use black to format your code. The two-space indent is distracting, makes it look like blocks were pasted in from another language. optional type hinting def __init__(self, xpos, ypos, isWater): You don't have to. But it would be a kindness to the Gentle Reader to offer the types: def __init__(self, xpos: float, ypos: float, isWater: str): (A ctor always returns None -- you can throw in ... ) -> None: if you like.) I'm sad we're accepting str instead of bool (which is a kind of int). The data parser adheres to a rather peculiar contract. If you had instead relied on the usual .read_csv() we would have obtained rows of integers just through the default behavior. Consider using a @property decorator for the {'L', 'W'} mapping: iswater = "W" if self.isWater else "L"
{ "domain": "codereview.stackexchange", "id": 45118, "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", "url": null }
python, python-3.x Whatever you do, please don't use the names iswater and isWater to represent distinct concepts. Invent a new name, perhaps terrain. It doesn't matter to the machine, but it does affect human cognition. To say nothing of making telephone conversations more difficult when we're discussing some code. use standard English def isAdjected(self, anotherField): Instead of is_adjected I think you intended is_adjacent ? if anotherField is None: return False I'm going to second-guess this design choice. In my opinion it probably makes sense to assert that it's not None, or otherwise document / insist that caller is responsible for passing in an actual Field object. The rationale is fear of a False return value masking some caller bug. if not isinstance(anotherField, Field): return False The previous test is redundant with this one, as None is definitely not a Field. And again, if this triggers I feel it is probably due to caller violating the contract. What I'm driving at is, spell out the contract, then hold the caller to it. Notice that we are not playing by the total ordering rules that are required to e.g. sort() a list. You invented your own method name, so you get to make up whatever rules you find convenient for the task at hand. if anotherField.xpos == self.xpos and anotherField.ypos+1 == self.ypos: ... if anotherField.xpos == self.xpos and anotherField.ypos-1 == self.ypos: ... if anotherField.xpos+1 == self.xpos and anotherField.ypos == self.ypos: ... if anotherField.xpos-1 == self.xpos and anotherField.ypos == self.ypos: Ok, that's just tedious. If you really want to follow that approach, at least define a vector of delta-coordinate tuples: for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
{ "domain": "codereview.stackexchange", "id": 45118, "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", "url": null }
python, python-3.x But wouldn't it be more convenient to def distance which returns the L1-norm Manhattan distance between the pair? Then you can just ask if it is exactly 1. shadowing builtins class Map: This is a lovely identifier, thank you. Fair warning, in python land we try to avoid assigning to map, as there is already a map in the builtin functions. The convention is to append a trailing _ underscore to avoid shadow meanings: map_ list_ dir_ id_ and so on. (Yeah, my apologies, python is a "small" language, but regrettably a bunch of common identifiers are already taken.) The identifier Map is distinct from map, and is unlikely to cause confusion on the telephone, so this is perfect as-is. optional type hinting class Map: def __init__(self, data: list): ... self.fields = list() Yay, type annotations, kudos, very nice. It definitely is valuable to know we're dealing with a list, especially for such an uninformative name as "data", so I thank you for that. However, for extra credit, you can also tell us what's inside the list: def __init__(self, data: list[Field]): Without that, linting with mypy will be somewhat less informative, as the list in the signature and the ... = list() assignment both have type list[Any]. a_field = Field(x, y, column == '0') That's an OK name, but somewhat unusual in this ecosystem. Prefer to simply call it field = Field( ... ). y = y + 1 x = x + 1
{ "domain": "codereview.stackexchange", "id": 45118, "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", "url": null }
python, python-3.x Gentle reminder: There's no ++ increment operator, but we do have y += 1. We seem to have a list-of-lists datastructure representing terrain, and that is perfectly fine. Please understand that there are alternatives. A list of N elements costs N+1 pointers, which typically will be 64-bit pointers. One for the list, plus one for each object pointed at. So we represent the booleans [1, 0, 1] with significantly more than three bits. Python offers arrays to efficiently store lots of things that have identical type. And if you go there, you're likely to go all the way to numpy's NDarrays, since they offer a great many convenience functions right out of the box. For example, filtering down to adjacent cells becomes very convenient. Storing N booleans in either kind of array will typically cost slighty more than 8 × N bits. That is, one byte per element is usual. If N is inconveniently large, consider using a bit vector. docstrings def expand_land(self, candidate, candidates): print ("getting neighbour fields") neighbours = list(filter(lambda field : field.isAdjected(candidate), candidates)) for neighbour in neighbours: print (f" adding {neighbour}") if(neighbour in candidates): candidates.remove(neighbour) self.expand_land(neighbour, candidates) return None
{ "domain": "codereview.stackexchange", "id": 45118, "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", "url": null }
python, python-3.x This is a nice little recursive helper, thank you for breaking it out. A bit chatty perhaps, but I'm sure we can elide the debugs once things are working, or else use a logger at DEBUG severity. Feel free to have the signature end with ...) -> None: This method definitely needs a """docstring""" which explains that we mutate the final argument. The return None at the end is weird; please elide it. Certainly it is accurate. But we don't write it explicitly when the intent is to evaluate for side effects. As written, it looks as though the method is supposed to return some useful value, and if it was a hundred-line method I would have to read through its various if clauses to see if return 42 appeared elsewhere. Consider the one-line def greet which prints Hello world. We don't make it a two-liner by finishing with return None. We let python implicitly do that. use appropriate datastructure if(neighbour in candidates): First, this isn't java, please prefer: if neighbour in candidates: Second, if I recall correctly, candidates is a list. Please understand that in will linearly scan the container, so we're probably looking at quadratic cost here. Consider using a set for the candidates. Note that only hashable (typically immutable) elements can be stored in sets, or as dict keys, so sometimes it takes a bit of rejiggering to switch to a more efficient container. quoting csvFile = 'resources\\island_01.csv' Uggh! Prefer a raw string: csv_file = r'resources\island_01.csv' Or, to be even more expressive of Author's Intent: from pathlib import Path csv_file = Path('resources/island_01.csv') (You could give it a \ backwhack instead of a / slash, it would be the same.) Welcome to python land! Recommend you routinely rely on tools like black isort mypy python -m unittest, or pytest to tidy up your source and keep it in good working order. This codebase appears to achieve its design goals. I would be willing to delegate or accept maintenance tasks on it.
{ "domain": "codereview.stackexchange", "id": 45118, "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", "url": null }
sql, sql-server, t-sql Title: Find All Recent Winners and Calculate an Encoding Question: Context I was proud of this code for a little while, but the repetition wounds me. I know that the function name sucks, but the name and interface to this function are not under my control. Performance is not a concern. Fixing the repetition is my only concern. How can I reduce it? Note the usage of the functional-programming tag. If you suggest a multi-statement table-valued function, then you've failed me. This must be an inline table-valued function. Dependencies CREATE TABLE [WINNERS] ( WINNER_ID INT NOT NULL ); CREATE TABLE [RelevantWinners] ( WINNER_ID INT NOT NULL ); INSERT INTO [WINNERS] VALUES (1), (2), (3), (4), (5); INSERT INTO [RelevantWinners] VALUES (1), (5);
{ "domain": "codereview.stackexchange", "id": 45119, "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": "sql, sql-server, t-sql", "url": null }
sql, sql-server, t-sql INSERT INTO [RelevantWinners] VALUES (1), (5); The Code For Review CREATE FUNCTION RecentWinners ( @GetAllWinners BIT ) RETURNS TABLE AS RETURN ( -- Style note: I've yet to figure out how to best indent consecutive CTEs. WITH [WinnersRelevant] AS ( SELECT -- The inclusion of a silly calculation is deliberate. 2 * [Win].[WINNER_ID] + 47 [ENCODING] FROM [Winners] [Win] WHERE EXISTS ( SELECT 1 FROM [RelevantWinners] [Rev] WHERE [Rev].[WINNER_ID] = [Win].[WINNER_ID] ) ), [WinnersAll] AS ( -- This is the first major repetition. -- It's exactly the same code as before, but without the semi-join. SELECT 2 * [Win].[WINNER_ID] + 47 [ENCODING] FROM [Winners] [Win] ) SELECT [ENCODING], -- The inclusion of a second silly calculation is deliberate. -- Pretend it's independent of the previous one. 2 * [ENCODING] + 12346 [ENCODING_2] FROM [WinnersRelevant] WHERE @GetAllWinners = 0 UNION ALL -- This is the second major repetition. -- It's exactly the same SELECT list as before. SELECT [ENCODING], 2 * [ENCODING] + 12346 [ENCODING_2] FROM [WinnersAll] WHERE @GetAllWinners = 1 ); --I'm pretty sure this is the only relevant semicolon, even under strict standards. DB Fiddle. Answer: Supply the function with SELECT 0 AS idx, * FROM Winners UNION ALL SELECT 1 AS idx, * FROM RelevantWinners and you'll have enough information available for a single SELECT to do what's needed.
{ "domain": "codereview.stackexchange", "id": 45119, "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": "sql, sql-server, t-sql", "url": null }
sql, sql-server, t-sql Title: Find All Recent Winners and Calculate an Encoding of What They Won Question: Context I was proud of this code for a little while, but the repetition wounds me. I know that the function name sucks, but the name and interface to this function are not under my control. Performance is not a concern. Note that this must be an inline table-valued function. Fixing the repetition is my only concern. How can I reduce it? This is a follow-up from this question. You do not and should not need to read that question first. This question exists because I oversimplified that one. Dependencies CREATE TABLE [WINNERS] ( WINNER_ID INT NOT NULL AMOUNT INT NOT NULL ); CREATE TABLE [RelevantWinners] ( WINNER_ID INT NOT NULL ); INSERT INTO [WINNERS] VALUES (1, 20), (2, 30), (3, 309), (4, 50), (5, 50); INSERT INTO [RelevantWinners] VALUES (1), (5); The Code For Review CREATE FUNCTION RecentWinners ( @GetAllWinners BIT ) RETURNS TABLE AS RETURN ( -- Style note: I've yet to figure out how to best indent consecutive CTEs. WITH [WinnersRelevant] AS ( SELECT -- The inclusion of a silly calculation is deliberate. 2 * [Win].[AMOUNT] + 47 [ENCODING] FROM [Winners] [Win] WHERE EXISTS ( SELECT 1 FROM [RelevantWinners] [Rev] WHERE [Rev].[WINNER_ID] = [Win].[WINNER_ID] ) ), [WinnersAll] AS ( -- This is the first major repetition. -- It's exactly the same code as before, but without the semi-join. SELECT 2 * [Win].[AMOUNT] + 47 [ENCODING] FROM [Winners] [Win] ) SELECT [ENCODING], -- The inclusion of a second silly calculation is deliberate. 2 * [ENCODING] + 12346 [ENCODING_2] FROM [WinnersRelevant] WHERE @GetAllWinners = 0
{ "domain": "codereview.stackexchange", "id": 45120, "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": "sql, sql-server, t-sql", "url": null }
sql, sql-server, t-sql UNION ALL -- This is the second major repetition. -- It's exactly the same SELECT list as before. SELECT [ENCODING], 2 * [ENCODING] + 12346 [ENCODING_2] FROM [WinnersAll] WHERE @GetAllWinners = 1 ); --I'm pretty sure this is the only relevant semicolon, even under strict standards. DB Fiddle. Answer: Just lump another sub-predicate beside your exists: create function RecentWinners(@GetAllWinners bit) returns table as return ( select encoding, 2*encoding + 12346 as encoding_2 from ( select 2*amount + 47 as encoding from Winners where @GetAllWinners=1 or exists ( select 1 from RelevantWinners as rw where rw.winner_id = Winners.winner_id ) ) as WinnersAggregate ); I don't care much for shouting, hence the lowercase.
{ "domain": "codereview.stackexchange", "id": 45120, "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": "sql, sql-server, t-sql", "url": null }
performance, rust Title: Leetcode: Maximum score from performing multiplication operations Question: I am looking for feedback on how to make my code more performant (take less time) - specifically with a top-down approach. My specific asks are: How can I make this code faster? It currently takes around 170+ ms, but I see some solutions that are in the range of 10 ms. I want to use a more functional approach to this - I want to write memo.entry().or_insert_with_key(), but I can't do that because memo needs to be recursively passed down to the subproblems. What can I do to use such a code structure? Leetcode problem description: You are given two 0-indexed integer arrays nums and multipliers of size n and m respectively, where n >= m. You begin with a score of 0. You want to perform exactly m operations. On the ith operation (0-indexed) you will: Choose one integer x from either the start or the end of the array nums. Add multipliers[i] * x to your score. Note that multipliers[0] corresponds to the first operation, multipliers[1] to the second operation, and so on. Remove x from nums. Return the maximum score after performing m operations. use std::collections::HashMap; use std::cmp::max;
{ "domain": "codereview.stackexchange", "id": 45121, "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": "performance, rust", "url": null }
performance, rust use std::collections::HashMap; use std::cmp::max; impl Solution { pub fn maximum_score(nums: Vec<i32>, multipliers: Vec<i32>) -> i32 { // State: s (start index for nums), e (end index for nums), k (number of operations remaining) // Subproblems: dp(s, e, k) = max(dp(s+1, e, k-1)+contrib(s), dp(s, e-1, k-1)+contrib(e)) // Base case: dp(x, x, any >= 1) = contrib(x) // contrib(x) = multipliers[x] * nums[s/e] let mut memo: HashMap<(usize, usize, usize), i32> = HashMap::new(); let m = multipliers.len()-1; Self::dp(0, nums.len()-1, m, &mut memo, &nums, &multipliers, m) } fn dp(start_idx: usize, end_idx: usize, num_ops_left: usize, memo: &mut HashMap<(usize, usize, usize), i32>, nums: &Vec<i32>, multipliers: &Vec<i32>, max_ops: usize) -> i32 { if !memo.contains_key(&(start_idx, end_idx, num_ops_left)) { let (from_start, from_end) = match num_ops_left { 0 => (0, 0), _ => (Self::dp(start_idx+1, end_idx, num_ops_left-1, memo, nums, multipliers, max_ops), Self::dp(start_idx, end_idx-1, num_ops_left-1, memo, nums, multipliers, max_ops)), }; memo.insert((start_idx, end_idx, num_ops_left), max(from_start + multipliers[max_ops - num_ops_left] * nums[start_idx], from_end + multipliers[max_ops - num_ops_left] * nums[end_idx])); } *memo.get(&(start_idx, end_idx, num_ops_left)).unwrap() } } Answer: I will not be commenting on the algorithm, as I've got no idea what's optimal. I will, however, be commenting on the code. Leetcode... First of all, it's just unidiomatic to: Create an empty struct just to associate functions to it, free-functions are perfectly acceptable in Rust. Take Vec<T> as parameter when not intending to modify the vector, &[T] should be preferred instead.
{ "domain": "codereview.stackexchange", "id": 45121, "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": "performance, rust", "url": null }
performance, rust I do understand, though, that those are quite likely to be Leetcode artifacts... but dp is your own function, so &[i32] please. Naming The cost of calling a function is independent from the length of its name. Prefer meaningful names, then. On the other hand, the _idx suffix is not very useful. Oh... and an alias for that complex HashMap would be nice: type MemoMap = HashMap<(usize, usize, usize), i32>; Formatting. The signature of dp is so long it runs off the side of the page. Use rustfmt (which you can invoke via cargo fmt) to format your code. Simpler is better Your use of match num_ops_left to check for 0 is unexpected, you can just use if really: let (from_start, from_end) = if num_ops_left > 0 { (Self::dp(...), Self::dp(...)) } else { (0, 0) }; In general, I advise using the simplest control-flow that works, so that when a more complex / less constrained control-flow form is used, it calls attention to itself "something special's going on here". Redundancy is not helpful You are tracking way too much state: In your hashmap. In the dp call. Let's start with the hashmap: what's num_ops_left for? At any point in time, the number of operations left to do is equal to the number of multipliers to pick from, which itself can be deduced from: multipliers.len() - (nums.len() - (end - start)) Hence, you can save space in your hashmap, and save time by not hashing redundant information. Similarly, with regard to the dp call: As mentioned, num_ops_left is redundant, and can be eliminated. Similarly, max_ops is redundant.
{ "domain": "codereview.stackexchange", "id": 45121, "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": "performance, rust", "url": null }
performance, rust As mentioned, num_ops_left is redundant, and can be eliminated. Similarly, max_ops is redundant. Instead, you should pass multipliers: &[i32] and trim multipliers at each step so that you only pass the slice of multipliers left to use. Avoid double-lookup, when possible. You are correct that unfortunately you are not going to be able to use .entry and pass &mut MemoMap to compute what to insert... but that's the rare case. The more frequent case should be that the entry is in the cache, and therefore you should vie to optimize this path. This will also eliminate the very unfortunate unwrap, at the same time. if let Some(cached) = memo.get(&(start, end)) { return cached; } let from_start = Self::dp(...); let from_end = Self::dp(...); let score = max(...); memo.insert((start, end), max); max
{ "domain": "codereview.stackexchange", "id": 45121, "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": "performance, rust", "url": null }
performance, rust Now, there's only a double-lookup on unsuccessful cache hits. Hash Flooding Hash Flooding is a Denial of Service (DoS) attack which appeared in the 2000s. It was mostly used to take down websites, by crafting specific lists of HTTP parameters where all keys would hash to the same hashmap bucket, turning each insertion into an O(N) operation, instead of an O(1) one, and thus turning inserting all the parameters into an O(N2), rather than an O(N) one. As a result, popular languages such as Python & Ruby changed their default hashing algorithms to be more collisions resistant. When Rust was created, it followed in its predecessors footsteps, and therefore also picked a more collision resistant hash algorithm by default (Sip2-4). Unfortunately, for you, it's not exactly a fast hash algorithm. And with hash lookups being a significant part of your workload, it's really something you should investigate. My typical goto is the fxhash crate, which simply uses the FxHash algorithm with the standard HashMap implementation by defining a type alias. If you can't import it, you should be able to copy/paste part of the code, it's fairly lightweight. Allocation & re-allocation Rust collections are typically created empty, with no allocation. In the case of "contiguous" collections, they then follow an exponential growth pattern, where (roughly) the allocation size doubles each time an allocation is required. In total, it means each element is roughly inserted once and moved once or twice. Not too bad. But not optimal, either. Instead, you can use their with_capacity factory function to create a suitably sized collection from the get-go, and avoid intermediate reallocations. You should be able to estimate the number of items to be inserted based on the length of nums and multipliers at the beginning, so just do it. Revised code Note: the revised code uses ahash because it's available on the playground, I'd still recommend fxhash for simplicity though. use std::cmp::max;
{ "domain": "codereview.stackexchange", "id": 45121, "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": "performance, rust", "url": null }
performance, rust use std::cmp::max; use std::collections::HashMap;
{ "domain": "codereview.stackexchange", "id": 45121, "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": "performance, rust", "url": null }
performance, rust use ahash::RandomState; struct Solution; impl Solution { pub fn maximum_score(nums: Vec<i32>, multipliers: Vec<i32>) -> i32 { // State: s (start index for nums), e (end index for nums), k (number of operations remaining) // Subproblems: dp(s, e, k) = max(dp(s+1, e, k-1)+contrib(s), dp(s, e-1, k-1)+contrib(e)) // Base case: dp(x, x, any >= 1) = contrib(x) // contrib(x) = multipliers[x] * nums[s/e] let mut memo = MemoMap::with_capacity_and_hasher( multipliers.len() * multipliers.len(), RandomState::new(), ); Self::dp(0, nums.len() - 1, &mut memo, &nums, &multipliers) } fn dp(start: usize, end: usize, memo: &mut MemoMap, nums: &[i32], multipliers: &[i32]) -> i32 { let Some((first, tail)) = multipliers.split_first() else { return 0; }; if let Some(cached) = memo.get(&(start, end)) { return *cached; } let from_start = Self::dp(start + 1, end, memo, nums, tail); let from_end = Self::dp(start, end - 1, memo, nums, tail); let score = max( from_start + first * nums[start], from_end + first * nums[end], ); memo.insert((start, end), score); score } } type MemoMap = HashMap<(usize, usize), i32, RandomState>; See it on the playground.
{ "domain": "codereview.stackexchange", "id": 45121, "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": "performance, rust", "url": null }
python, error-handling, exception, timeout, ftp Title: Catching the timed out Exception raised by the __init__ method of the class ftplib.FTP Question: Introduction I have written a Python class which uses the module ftplib. In this class I have created a private method called __connect(). Its goal is try to connect to a FTP Server. Trying the connection could be raised many type of Exception. I have emulated some of these kind of errors: a time out error a Connection refused error because the host (that is reachable) doesn't run a FTP Server My code The code of my class is store in the module ftp_connect.py, and the code inside this module is the following: import ftplib CONNECTION_TIMEOUT = 10 class FTPExport: def __init__(self, server_address, username, password): self.__server_address = server_address self.__username = username self.__password = password self.__ftpserver = None def __connect(self): try: if self.__server_address == None or self.__server_address == "": return "Server address error" self.__ftpserver = ftplib.FTP(self.__server_address, timeout=CONNECTION_TIMEOUT) return "OK" except ConnectionRefusedError as ex: return ex.args[1] except BaseException as ex: if len(ex.args) > 0: if ex.args[0] == 'timed out': return "Connection timed out" return "Connection error" else: return "Connection error" if __name__ == '__main__': # Connection timed out (the address 191.168.127.1 is not reachable on my network) ftp_export = FTPExport("191.168.127.1", "frank", "123456") print(ftp_export._FTPExport__connect())
{ "domain": "codereview.stackexchange", "id": 45122, "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, error-handling, exception, timeout, ftp", "url": null }
python, error-handling, exception, timeout, ftp My question is relative to the Timed out error. If you see my code (method __connect()) I have caught the Exception raised by an occurred Timed Out by the following snippet of code: try: ... except BaseException as ex: if len(ex.args) > 0: if ex.args[0] == 'timed out': return "Connection timed out" ... In the previous code I do: catch the BaseException because the exception raised when occurs a Timed Out has BaseException as superclass check the content of args[0] and if it is equal to timed out I'm sure that it is occurred a Time Out How to cause a time out: valid IP address but not reachable To test my code, make sure that the address 191.168.127.1 is not reachable in your network, and use the following command line: > python3 ftp_connect.py If you wait at least 10 seconds you obtain the following output: Connection timed out My question Is it possible to catch the Exception raised by the __init__ method of the class ftplib.FTP when occurs a Timed Out connection in an other way than by the generic BaseException and by checking the content of args? Answer: no name mangling self.__username = username I don't know what's going on with that __ dunder prefix. But name mangling is seldom what folks want. Prefer a single _ underscore to mark it _private: self._username = username public API def __connect(self): I was about to offer the same (_connect) advice. Until I noticed that this is no internal detail, this is the only functionality the class exports. This method is definitely public. Say so. def connect(self): singleton comparison ... server_address == None ... Prefer to ask about the address of that variable with is: ... server_address is None ... It's just kind of a weird pythonism, based on the fact that there's exactly one None object. You'll get used to it. Or your linter will remind you. Testing for empty string with ... == "" is perfect as-is.
{ "domain": "codereview.stackexchange", "id": 45122, "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, error-handling, exception, timeout, ftp", "url": null }
python, error-handling, exception, timeout, ftp raise exceptions return "Server address error" First, please write a """docstring""" explaining what this method returns. Second, shouldn't we raise rather than return the error? catch exceptions except BaseException as ex: Ok, that just seems insane. You're trapping KeyboardInterrupt and SystemExit ?!? No ctrl-C for you! Prefer except Exception: rather than BaseException. Always. cf https://www.flake8rules.com/rules/E722.html Is it possible to catch ... in another way ? Oh, thank goodness! So you are aware there must be a better way, excellent. Set a breakpoint() and then print out details of the exception: (Pdb) p type(ex) <class 'TimeoutError'> Good, we have a TimeoutError. Simply use except TimeoutError: and be done with it. Yes, you could examine its .args[0]. But that will always be a boring "timed out" message for a TimeoutError, so there's little need of that. In general, if calling code knows how to intelligently cope with a particular error (or two), it should try to catch just those errors, quite narrowly. Avoid the temptation to go wide and trap all errors. Often it is best to let an unanticipated error bubble on up the call stack, until someone deals with it or reports it in a stack trace.
{ "domain": "codereview.stackexchange", "id": 45122, "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, error-handling, exception, timeout, ftp", "url": null }
c++, error-handling, api Title: C interface exception handling with C++ implementation Question: Whilst developing a bigger project, I was in need of having basic error handling inside the context of a C interface. I came up with the following solution. // include/interface/error.h #ifndef SDK_INTERFACE_ERROR_H #define SDK_INTERFACE_ERROR_H #ifdef __cplusplus extern "C" { #endif //__cplusplus struct Error; typedef struct Error Error; typedef void(*ErrorHandler)( Error const * ); void SetExceptionHandler( ErrorHandler const * inExceptionHandler ); [[ noreturn ]] void ThrowException( Error const * inError ); #ifdef __cplusplus } #endif //__cplusplus #endif //SDK_INTERFACE_ERROR_H // source/interface/error.cpp #include "interface/error.h" #include <shared_mutex> #include <mutex> #include <cstdlib> #include <functional> namespace { std::function< void( Error const * ) > sErrorHandler = []( Error const * ){ std::abort(); }; std::shared_mutex sErrorHandlerMutex; } void SetExceptionHandler( ErrorHandler const * inExceptionHandler ) { std::unique_lock lock( sErrorHandlerMutex ); sErrorHandler = *inExceptionHandler; } void ThrowException( Error const * inError ) { std::shared_lock lock( sErrorHandlerMutex ); sErrorHandler( inError ); std::abort(); } Errors in this context means unrecoverable errors, So error handling is simply a means to provide a user of this interface time to perform a clean exit. However I still have the following questions General Code review Would it be safe to throw an exception inside an ErrorHandler, which could then be caught again outside the interface Is it safe to pass stack addresses to ThrowException Answer: Code Review: That's not a very unique header guard! #ifndef SDK_INTERFACE_ERROR_H #define SDK_INTERFACE_ERROR_H In this section the code has to be valid in both C and C++. I have not used C in a long time but is [[ noreturn ]] part of C now? [[ noreturn ]] void ThrowException( Error const * inError );
{ "domain": "codereview.stackexchange", "id": 45123, "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++, error-handling, api", "url": null }
c++, error-handling, api Would it be safe to throw an exception inside an ErrorHandler It looks like this can be called from C code. C does not know anything about C++ or exceptions. So there is no guarantee in the standard of C that exceptions will correctly propagate across any C interface. So technically NO it is not safe, you are well into at least compiler defined behavior. In practice, it will depend on your compiler tool chain. You can probably validate its safety with sufficient unit/integration tests. Is it safe to pass stack addresses to ThrowException Depends on what you do with it. But in the general sense yes that should be safe. If both sides C/C++ are using the same definition of Error and it is valid in both languages then yes it should work without any issues.
{ "domain": "codereview.stackexchange", "id": 45123, "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++, error-handling, api", "url": null }
c++, reinventing-the-wheel, template, pointers Title: C++ Shared_Ptr implementation Question: I reinvented a c++ smart pointer, shared_ptr to be precise. It is meant for practice purpose and does not attempt to replace the standard implementation. To the best of my knowledge, the code works as expected. I decided to skip the custom deleter because I want to keep things simple for now. I would love feedbacks and constructive criticism. Here is the implementation shared.hpp #ifndef SHARED_PTR_H_ #define SHARED_PTR_H_ #include <cstddef> namespace smp { template<typename T> class shared_ptr { public: explicit shared_ptr(T* ptr = nullptr); ~shared_ptr(); shared_ptr(shared_ptr& ptr); shared_ptr operator=(shared_ptr& ptr); shared_ptr(shared_ptr&& ptr) noexcept; shared_ptr operator=(shared_ptr&& ptr) noexcept; T operator*(); T* operator->() const; size_t use_count() const; void reset(); T* get(); bool unique() const; operator bool() const; private: T* obj_ptr; struct RefCount { size_t use_count_; T* object_; }* ref_cnt; }; template<typename T> shared_ptr<T> make_shared(T object); } #endif /* SHARED_PTR_H_ */ shared.cpp #include "shared.hpp" #include <algorithm> #include <iostream> namespace smp { template<typename T> shared_ptr<T>::shared_ptr(T* ptr) : obj_ptr{ptr}, ref_cnt{new RefCount()} { ref_cnt->object_ = ptr; if(ptr) ++ref_cnt->use_count_; } template<typename T> shared_ptr<T>::shared_ptr(shared_ptr& ptr) : ref_cnt{new RefCount()} { obj_ptr = ptr.obj_ptr; ref_cnt = ptr.ref_cnt; ++ref_cnt->use_count_; }
{ "domain": "codereview.stackexchange", "id": 45124, "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++, reinventing-the-wheel, template, pointers", "url": null }
c++, reinventing-the-wheel, template, pointers ++ref_cnt->use_count_; } template<typename T> shared_ptr<T> shared_ptr<T>::operator=(shared_ptr& ptr) { obj_ptr = ptr.obj_ptr; ref_cnt = ptr.ref_cnt; ++ref_cnt->use_count_; return *this; } template<typename T> shared_ptr<T>::shared_ptr(shared_ptr&& ptr) noexcept : obj_ptr{nullptr}, ref_cnt{new RefCount()} { obj_ptr = std::move(ptr.obj_ptr); ref_cnt = std::move(ptr.ref_cnt); ptr.reset(); } template<typename T> shared_ptr<T> shared_ptr<T>::operator=(shared_ptr&& ptr) noexcept { if(obj_ptr) reset(); obj_ptr = std::move(ptr.obj_ptr); ref_cnt = std::move(ptr.ref_cnt); ptr.obj_ptr = nullptr; return *this; } template<typename T> shared_ptr<T> make_shared(T object) { return shared_ptr<T>(new T{object}); } template<typename T> T shared_ptr<T>::operator*() { return *obj_ptr; } template<typename T> T* shared_ptr<T>::operator->() const { return &*obj_ptr; } template<typename T> size_t shared_ptr<T>::use_count() const { return ref_cnt->use_count_; } template<typename T> void shared_ptr<T>::reset() { obj_ptr = nullptr; if(ref_cnt) --ref_cnt->use_count_; if(ref_cnt->use_count_ == 0) ref_cnt->object_->~T(); } template<typename T> T* shared_ptr<T>::get() { return obj_ptr; } template<typename T> bool shared_ptr<T>::unique() const { return (ref_cnt->use_count_ == 1); } template<typename T> shared_ptr<T>::operator bool() const { return (obj_ptr != nullptr); } template<typename T> shared_ptr<T>::~shared_ptr() { if(obj_ptr) reset(); } }
{ "domain": "codereview.stackexchange", "id": 45124, "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++, reinventing-the-wheel, template, pointers", "url": null }
c++, reinventing-the-wheel, template, pointers Answer: Overview Templated classes "normally" should provide all the code at the point of usage. As a result you should probably not have a separate shared.cpp. Though some people put the definitions in a separate shared.tpp file that is included by the header file. Code Review: You are missing a constructor for nullptr. Though nullptr can be converted to any other type the compiler can not know what type you want in this situation so you would need to be explicit. But it would be nice to allow auto conversion from nullptr to the correct shared pointer type. void myFunc(smp::shared_ptr<int>&& ptr) { /* Stuff */} int main() { myFunc(nullptr); // This fails. // as you defined an explicit constructor. // But this is totaly safe so it would be nice if it // simply worked rather than forcing the long hand. } So I would add a constructor for this situation. smp::shared_ptr::shared_ptr(std::nullptr_t); Non standard copy constructor and move constructor: shared_ptr(shared_ptr& ptr); // Would expect const ref shared_ptr operator=(shared_ptr& ptr); // In the current state these can not catch temporary values. Most people forget the noexcept. So well done. shared_ptr(shared_ptr&& ptr) noexcept; shared_ptr operator=(shared_ptr&& ptr) noexcept; You should probably return a reference here: T operator*(); Otherwise you are going to force a copy of the internal object as it is returned. Just like the operator-> this does not affect the state of the shared pointer so this is const. In std::shared_ptr this is a noexcept operation. I could personally argue over that. But smarter people than me wrote the standard so I would go with them. T& operator*() const noexcept; Good. T* operator->() const; But like the operator* can be noexcept. T* operator->() const noexcept;
{ "domain": "codereview.stackexchange", "id": 45124, "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++, reinventing-the-wheel, template, pointers", "url": null }
c++, reinventing-the-wheel, template, pointers You don't want this accidentally converting in non boolean contexts. operator bool() const; In this situation: smp::shared_ptr<int> x(new int{6}); smp::shared_ptr<float> y(new float{5}); if (x == y) { // Because of your bool operator // they are converted to bool (for both this is true) // resulting in this code saying they are equal. std::cout << "Equal\n"; } Use the explicit here: explicit operator bool() const; The issue I have hear is that if the new fails (for RefCount) then you leak the pointer. Once you had the pointer to the constructor of a shared pointer you are seeding all responsibility of the pointer. That mean if the object fails to correctly construct you need to make sure the passed pointer is deleted. So in the situation of new failing you need to call delete on the pointer. template<typename T> shared_ptr<T>::shared_ptr(T* ptr) : obj_ptr{ptr}, ref_cnt{new RefCount()} { ref_cnt->object_ = ptr; if(ptr) ++ref_cnt->use_count_; } Add a try catch block to the initializer list: template<typename T> shared_ptr<T>::shared_ptr(T* ptr) try : obj_ptr{ptr} , ref_cnt{new RefCount()} { ref_cnt->object_ = ptr; if(ptr) ++ref_cnt->use_count_; } catch(...) { delete ptr; } If you are copying a shared_ptr then you should be using the same ref_cnt not a brand new one. You should prefer to do as much work in the initializer list as possible to prevent multiple initializations. shared_ptr<T>::shared_ptr(shared_ptr& ptr) : ref_cnt{new RefCount()} { obj_ptr = ptr.obj_ptr; ref_cnt = ptr.ref_cnt; ++ref_cnt->use_count_; } // Fixed: shared_ptr<T>::shared_ptr(shared_ptr& ptr) : obj_ptr(ptr.obj_ptr) , ref_cnt{ptr.ref_cnt} { if (obj_ptr) { ++ref_cnt->use_count_; } }
{ "domain": "codereview.stackexchange", "id": 45124, "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++, reinventing-the-wheel, template, pointers", "url": null }
c++, reinventing-the-wheel, template, pointers Here you forget to decrement the ref_counter of the previous object (so potentially allowing a leak). I would use the copy and swap idiom to provide the strong exception guarantee (it also covers self assignment). template<typename T> shared_ptr<T> shared_ptr<T>::operator=(shared_ptr& ptr) { obj_ptr = ptr.obj_ptr; // Old object potentially leaked. ref_cnt = ptr.ref_cnt; // Old ref count potentially leaked. ++ref_cnt->use_count_; return *this; } Again incorrectly increment the counter. template<typename T> shared_ptr<T>::shared_ptr(shared_ptr&& ptr) noexcept : obj_ptr{nullptr}, ref_cnt{new RefCount()} { obj_ptr = std::move(ptr.obj_ptr); ref_cnt = std::move(ptr.ref_cnt); ptr.reset(); } The reset will decrement the counter. Since you have moved the object there has been no decrement. Simpler to simply set this one up as null and then swap. This can fail. template<typename T> shared_ptr<T> shared_ptr<T>::operator=(shared_ptr&& ptr) noexcept { if(obj_ptr) reset(); If ptr is the only copy. Then calling reset is going to free the object. Thus any other code is going to now manipulate a freeed object. obj_ptr = std::move(ptr.obj_ptr); ref_cnt = std::move(ptr.ref_cnt); ptr.obj_ptr = nullptr; // If you don't reset the ref count object then // eventually `ptr` is going to go out of scope and // its destructor is going to mess with the ref count object. Simpler to simply set this one up as null and then swap. Why does the shared object have to be copied constructed? template<typename T> shared_ptr<T> make_shared(T object) { return shared_ptr<T>(new T{object}); }
{ "domain": "codereview.stackexchange", "id": 45124, "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++, reinventing-the-wheel, template, pointers", "url": null }
c++, reinventing-the-wheel, template, pointers Would be nive to allow the type T to be constructed using any of its normal constructors that take parameters. template<typename T, typename... Args> shared_ptr<T> make_shared(Args...&& args) { // Though this is the simplist way to do it. // The standard version tries to make the whole thing more efficient. // by allocating the space for the object T and the ref-count // in a single allocation (thus removing the need for an extra // call to new). return shared_ptr<T>(new T{std::forward<Args>(args)...}); } template<typename T> T* shared_ptr<T>::operator->() const { return &*obj_ptr; // Not sure why that is rewquired. } This implies you don't keep a reference count object for nullptr. But your object always has a reference counter and you will need to make sure it is updated correctly. template<typename T> shared_ptr<T>::~shared_ptr() { if(obj_ptr) // Always call reset. // Otherwise you are potentially leaking // the reference count object. reset(); } Which leads us to the reference count object handling. In reset you need to call delete on the object managed and the reference count object if the count reaches zero. template<typename T> void shared_ptr<T>::reset() { obj_ptr = nullptr; if(ref_cnt) --ref_cnt->use_count_; if(ref_cnt->use_count_ == 0) // This is not correct. // You have called the destructor but leaked the object space. ref_cnt->object_->~T(); // You need to delete the object and the memory used by the // reference count object // delete ref_cnt->object_; // delete ref_cnt; } Self Plug: Wrote a lot about shared pointers here: https://lokiastari.com/series/ Read three articles on shared pointers.
{ "domain": "codereview.stackexchange", "id": 45124, "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++, reinventing-the-wheel, template, pointers", "url": null }
java, array, iteration Title: Shrink an array of double elements (uniformly) Question: Is there a way to avoid the first loop in the method shrink? (if and while...) The utility method shrink should reduce the elements of a double array by picking up elements from the original array "with a regular step respectively offset size"... but the first element should always be included, and the last element too, if possible. public static double[] shrink(final double[] data, final int len) { if (data.length == 0 || len < 1) { throw new IllegalArgumentException("data.length == 0 || len < 1"); } double[] d = new double[len]; double step = (double) data.length / len; if (len > 1) { int i = 1; while (Math.round(step * (len - 1)) < data.length - 1) { step = (double) (data.length + i) / len; i++; } } for (int i = 0; i < len; i++) { int j = (int) Math.round(i * step); d[i] = data[j]; } return d; } public static void testShrink() { double[] data1 = {1, 2, 3, 4, 5, 6}; for (int i = 1; i <= data1.length; i++) { double[] data = new double[i]; System.arraycopy(data1, 0, data, 0, i); for (int j = 1; j <= i; j++) { double[] result = shrink(data, j); System.out.println(i + " " + j + " " + Arrays.toString(result)); } } } The output of the method testShrink should look like the following: 1 1 [1.0] 2 1 [1.0] 2 2 [1.0, 2.0] 3 1 [1.0] 3 2 [1.0, 3.0] 3 3 [1.0, 2.0, 3.0] 4 1 [1.0] 4 2 [1.0, 4.0] 4 3 [1.0, 2.0, 4.0] 4 4 [1.0, 2.0, 3.0, 4.0] 5 1 [1.0] 5 2 [1.0, 5.0] 5 3 [1.0, 3.0, 5.0] 5 4 [1.0, 2.0, 4.0, 5.0] 5 5 [1.0, 2.0, 3.0, 4.0, 5.0] 6 1 [1.0] 6 2 [1.0, 6.0] 6 3 [1.0, 3.0, 6.0] 6 4 [1.0, 3.0, 4.0, 6.0] 6 5 [1.0, 2.0, 3.0, 5.0, 6.0] 6 6 [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] I think, it's also a mathematical-like question.
{ "domain": "codereview.stackexchange", "id": 45125, "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, iteration", "url": null }
java, array, iteration I think, it's also a mathematical-like question. Answer: I don't understand the first loop. It seems like a successive approximation calculation for the step size, but that shouldn't be necessary. Instead, we know that you have two defined endpoints of a linear function: $$f(0) = 0$$ $$f(n-1) = m-1$$ $$i = f(j) = \frac {j(m-1)} {n-1}$$ That gives you your step size. It's easy enough to prevent divide-by-zero by having 1 as the minimum denominator; this also allows for len=0 to act as expected (returning an empty array). public static double[] shrink(double[] data, int len) { if (data.length < 1 || len < 0) throw new IllegalArgumentException("data.length < 1 || len < 0"); double[] d = new double[len]; double step = (data.length - 1.0d)/Integer.max(len - 1, 1); for (int j = 0; j < len; ++j) { int i = (int)Math.round(j * step); d[j] = data[i]; } return d; } Note that since this doesn't use interpolation, it introduces alias error.
{ "domain": "codereview.stackexchange", "id": 45125, "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, iteration", "url": null }
java, file Title: Program using java.io that shows the content of a text file and every three lines the program stop reading, waiting to press Enter Question: I am doing a program in Java your text using java.io that shows the content of a text file and every three lines the program stop reading, waiting to press Enter. I dont know so much about programming, so i want to improve my code an my way to program reading your coments, this is the code: package ficheros_ejercicio4; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; /** * Programa que muestra el contenido de un fichero y cada 23 líneas el fichero se parará * hasta que el usuario pulse la tecla Intro * * @author José A. Cruz */ public class ContinuaIntro { public static void main(String[] args) { // TODO Auto-generated method stub
{ "domain": "codereview.stackexchange", "id": 45126, "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, file", "url": null }
java, file public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); String seguir = ""; File f = new File("continua.txt"); try { FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); String linea; do { linea = br.readLine(); if(linea != null) { System.out.println(linea); linea=br.readLine(); if(linea != null) { System.out.println(linea); linea=br.readLine(); if(linea != null) { System.out.println(linea); System.out.println("Para continuar leyendo pulse la tecla Enter..."); linea=sc.nextLine(); } } } } while(linea.equals(seguir)); sc.close(); br.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
{ "domain": "codereview.stackexchange", "id": 45126, "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, file", "url": null }
java, file } Answer: You should move most of your code away from the main function for maintainability and testability. Your variable names (seguir) should be in English, which is the de-facto language of programming; it's fine for your user interface text to be local. You should have your stream resources in a try-with-resources or a try-finally. This program is a rough clone of the more pager (and its much more complicated big sister, the less pager). There are features of those pagers you should emulate, mostly: after every page, you should be able to read a section of the file uninterrupted by Para continuar prompts. Stock Java does not make this easy. So long as you don't use third-party libraries, the best thing to do is probably just print your prompt once, and then never again. Rely on the return character from the user to feed the last line of the page. This way, the file will appear as it does on disk. It's not necessary to close both a file reader and its associated buffered reader; only close the latter. It's easy enough to make this a much more useful program by removing the hard-coded filename and accepting it as the first command-line parameter. Suggested import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; public class Main { public static class Pager implements AutoCloseable { private final Scanner in = new Scanner(System.in); private final BufferedReader reader; private final int blockSize; public Pager(String filename, int blockSize) throws FileNotFoundException { FileReader file = new FileReader(filename); reader = new BufferedReader(file); this.blockSize = blockSize; }
{ "domain": "codereview.stackexchange", "id": 45126, "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, file", "url": null }
java, file public void run() throws IOException { while (true) { for (int i = 1; i < blockSize; ++i) { String line = reader.readLine(); if (line == null) return; System.out.println(line); } String line = reader.readLine(); if (line == null) return; System.out.print(line); in.nextLine(); } } @Override public void close() throws IOException { reader.close(); } } public static void main(String[] args) { System.out.println("Para continuar leyendo pulse la tecla Enter..."); try (Pager pager = new Pager(args[0], 3)) { pager.run(); } catch (IOException e) { e.printStackTrace(); } } }
{ "domain": "codereview.stackexchange", "id": 45126, "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, file", "url": null }
c#, object-oriented, linked-list, console, inheritance Title: Calling the base method from overriden method to add some functionality Question: I have a small Linked list program which I created for just brushing up the concepts. Following is my Node class public class Node { private int element; public int Element { get { return element; } set { element = value; } } private Node next; public Node Next { get { return next; } set { next = value; } } public Node(int e, Node n) { Element = e; Next = n; } } Here is my linked list Class Logic. public class CustomLinkedList { private int size; private Node head; private Node tail; public int Size { get { return size; } private set { size = value; } } public Node Head { get { return head; } private set { head = value; } } public Node Tail { get { return tail; } private set { tail = value; } } public CustomLinkedList() { this.size = 0; this.head = null; this.tail = null; } private bool isEmpty() { return Head == null; } public virtual void AddLast(int e) { Node newnode = new Node(e, null); if(isEmpty()) this.head = newnode; else this.tail.Next = newnode; this.tail = newnode; this.size = this.size + 1; } public Node FindLast(int e) { Node node = this.head; while(node!=null) { if(node.Element==e) return node; else node = node.Next; } return null;
{ "domain": "codereview.stackexchange", "id": 45127, "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#, object-oriented, linked-list, console, inheritance", "url": null }
c#, object-oriented, linked-list, console, inheritance } public virtual void AddFirst(int e) { Node newnode = new Node(e, null); if(isEmpty()) { this.head = newnode; this.tail = newnode; } else { newnode.Next = this.head; this.head = newnode; } this.size = this.size + 1; } public virtual void AddAfter(Node n,int e) { Node newnode = new Node(e, null); newnode.Next = n.Next; n.Next = newnode; this.size = this.size + 1; } public virtual void RemoveFirst() { this.head = this.head.Next; this.size = this.size - 1; } public virtual void RemoveLast() { Node n = this.head; while(n!=null) { if(n.Next == this.tail) { n.Next = null; this.tail = n; this.size = this.size - 1; } n = n.Next; } } public virtual void Remove(int e) { Node n = this.head; while (n != null) { if(n.Next.Element == e) { n.Next = n.Next.Next; this.size = this.size - 1; break; } n = n.Next; } } public override string ToString() { StringBuilder sb = new StringBuilder(); Node n = this.head; while(n!=null) { sb.Append(n.Element.ToString()); n = n.Next; if(n!=null) sb.Append(" -> "); } return sb.ToString(); } }
{ "domain": "codereview.stackexchange", "id": 45127, "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#, object-oriented, linked-list, console, inheritance", "url": null }
c#, object-oriented, linked-list, console, inheritance return sb.ToString(); } } After creating this class I decided to apply colors to the list output after each and every operation. I didn't wanted to implement the coloriing logic inside the class which process the linked list. So implemented the logic like this in a derived class using virtual and override methods. public sealed class ColoredCustomLinkedList : CustomLinkedList { public override void AddLast(int e) { Console.ForegroundColor = ConsoleColor.Green; base.AddLast(e); } public override void AddFirst(int e) { Console.ForegroundColor = ConsoleColor.Blue; base.AddFirst(e); } public override void AddAfter(Node n, int e) { Console.ForegroundColor = ConsoleColor.Yellow; base.AddAfter(n, e); } public override void RemoveFirst() { Console.ForegroundColor = ConsoleColor.Red; base.RemoveFirst(); } public override void RemoveLast() { Console.ForegroundColor = ConsoleColor.DarkRed; base.RemoveLast(); } public override void Remove(int e) { Console.ForegroundColor = ConsoleColor.DarkMagenta; base.Remove(e); } } I am getting the desired output as follows. Is this the right way to do this? is there any better methods to suggest? Answer: When you Generate an override in Visual Studio, a call to the base method is automatically added. This is quite a common way to extend the behavior of a method. If you do not call the base method, you can provide a completely different implementation, which is also valid.
{ "domain": "codereview.stackexchange", "id": 45127, "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#, object-oriented, linked-list, console, inheritance", "url": null }
c#, object-oriented, linked-list, console, inheritance I understand that this Colored... class is only for debugging. It mixes business logic with UI behavior. This is okay for this purpose. For a more general approach, I would create an observable collection. For this purpose, we add an event that we can attach to in order to observe changes in the collection. This allows us to separate UI stuff from the logic or to do something completely different like logging, etc. The Element is limited to int. It is easy to make the collection generic and to allow any element type. FindLast actually finds the first element. I renamed it to FindFirst in the following examples. The constructor of CustomLinkedList initializes fields to 0 and null. Fields are initialized anyway with these default values in C#. But you can keep the constructor like this for clarity if you prefer. See my appendix for coding style below. To make the list generic we also make the Node class generic: public class Node<T> { private T element; public T Element { get { return element; } set { element = value; } } private Node<T> next; public Node<T> Next { get { return next; } set { next = value; } } public Node(T e, Node<T> n) { Element = e; Next = n; } } Then we adapt the custom collection accordingly. Note that == does not work anymore on generic types. Instead, we now call Equals: public class CustomLinkedList<T> { private int size; private Node<T> head; private Node<T> tail; public int Size { get { return size; } private set { size = value; } } public Node<T> Head { get { return head; } private set { head = value; } }
{ "domain": "codereview.stackexchange", "id": 45127, "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#, object-oriented, linked-list, console, inheritance", "url": null }
c#, object-oriented, linked-list, console, inheritance public Node<T> Tail { get { return tail; } private set { tail = value; } } public CustomLinkedList() { this.size = 0; this.head = null; this.tail = null; } private bool isEmpty() { return Head == null; } public virtual void AddLast(T e) { Node<T> newnode = new Node<T>(e, null); if (isEmpty()) this.head = newnode; else this.tail.Next = newnode; this.tail = newnode; this.size = this.size + 1; } public Node<T> FindFirst(T e) { Node<T> node = this.head; while (node != null) { if (node.Element.Equals(e)) return node; else node = node.Next; } return null; } public virtual void AddFirst(T e) { Node<T> newnode = new Node<T>(e, null); if (isEmpty()) { this.head = newnode; this.tail = newnode; } else { newnode.Next = this.head; this.head = newnode; } this.size = this.size + 1; } public virtual void AddAfter(Node<T> n, T e) { Node<T> newnode = new Node<T>(e, null); newnode.Next = n.Next; n.Next = newnode; this.size = this.size + 1; } public virtual void RemoveFirst() { this.head = this.head.Next; this.size = this.size - 1; } public virtual void RemoveLast() { Node<T> n = this.head; while (n != null) { if (n.Next == this.tail) { n.Next = null; this.tail = n; this.size = this.size - 1; } n = n.Next; } }
{ "domain": "codereview.stackexchange", "id": 45127, "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#, object-oriented, linked-list, console, inheritance", "url": null }
c#, object-oriented, linked-list, console, inheritance public virtual void Remove(T e) { Node<T> n = this.head; while (n != null) { if (n.Next.Element.Equals(e)) { n.Next = n.Next.Next; this.size = this.size - 1; break; } n = n.Next; } } public override string ToString() { StringBuilder sb = new StringBuilder(); Node<T> n = this.head; while (n != null) { sb.Append(n.Element.ToString()); n = n.Next; if (n != null) sb.Append(" -> "); } return sb.ToString(); } } Implementing an observable linked list: Let us start by declaring the infrastructure types we need for the event: public enum ListOperation { AddLast, AddFirst, AddAfter, RemoveFirst, RemoveLast, Remove } public class ObservableListArgs : EventArgs { public ObservableListArgs(ListOperation operation) { Operation = operation; } public ListOperation Operation { get; } } public delegate void ListOperationDelegate(object sender, ObservableListArgs e); Now, we can implement the observable linked list like this: public sealed class ObservableLinkedList<T> : CustomLinkedList<T> { public event ListOperationDelegate CollectionChanged; private void OnCollectionChanged(ListOperation operation) { CollectionChanged?.Invoke(this, new ObservableListArgs(operation)); } public override void AddLast(T e) { base.AddLast(e); OnCollectionChanged(ListOperation.AddLast); } public override void AddFirst(T e) { base.AddFirst(e); OnCollectionChanged(ListOperation.AddFirst); } public override void AddAfter(Node<T> n, T e) { base.AddAfter(n, e); OnCollectionChanged(ListOperation.AddAfter); }
{ "domain": "codereview.stackexchange", "id": 45127, "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#, object-oriented, linked-list, console, inheritance", "url": null }
c#, object-oriented, linked-list, console, inheritance public override void RemoveFirst() { base.RemoveFirst(); OnCollectionChanged(ListOperation.RemoveFirst); } public override void RemoveLast() { base.RemoveLast(); OnCollectionChanged(ListOperation.RemoveLast); } public override void Remove(T e) { base.Remove(e); OnCollectionChanged(ListOperation.Remove); } } Now let us rewrite the console test. We declare a PrintChanges method having the same signature as our ListOperationDelegate. static void PrintChanges(object sender, ObservableListArgs e) { Console.ForegroundColor = e.Operation switch { ListOperation.AddLast => ConsoleColor.Green, ListOperation.AddFirst => ConsoleColor.Blue, ListOperation.AddAfter => ConsoleColor.Yellow, ListOperation.RemoveFirst => ConsoleColor.Red, ListOperation.RemoveLast => ConsoleColor.DarkRed, ListOperation.Remove => ConsoleColor.DarkMagenta, _ => ConsoleColor.White }; Console.WriteLine(sender.ToString()); } The new test: var list = new ObservableLinkedList<int>(); list.CollectionChanged += PrintChanges; list.AddLast(1); list.AddLast(2); list.AddLast(3); list.AddFirst(30); Node<int> node = list.FindFirst(2); list.AddAfter(node, 10); list.RemoveFirst(); list.RemoveLast(); list.Remove(2); It produces the exact same output. We can also easily create a list for strings now: var stringList = new ObservableLinkedList<string>(); stringList.CollectionChanged += PrintChanges; stringList.AddLast("Hello"); stringList.AddLast("World"); My Visual Studio code analysis proposes me some code fixes. Their behavior is configurable, and they are also a matter of personal preference. Therefore, I did not apply these changes to my example above, but I still would like to list them here as they may lead to a better coding style:
{ "domain": "codereview.stackexchange", "id": 45127, "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#, object-oriented, linked-list, console, inheritance", "url": null }
c#, object-oriented, linked-list, console, inheritance "Add braces to 'if' statement" and "Add braces to 'else' statement". "Naming rule violation: Missing prefix: '_'". Many developers prepend field names with an _. This makes it easier to distinguish between fields and local variables or parameters. "Naming rule violation: These words must begin with upper case characters: isEmpty". The widely accepted naming conventions for C# state that type, method, and property names must be written in PascalCase. "Object initialization can be simplified" and "use 'var' instead of explicit type". Instead of writing Node<T> newnode = new Node<T>(e, null); and repeating the type name twice, you can either write var newnode = new Node<T>(e, null); or Node<T> newnode = new(e, null);. I would keep the C# alias for the primitive types like int or string or when the type is not immediately obvious from the code, so. int i = 0; is more readable than var i = 0;. "Use '++' operator" and "Use '--' operator". this.size = this.size + 1; and this.size = this.size - 1; can also simply be written as this.size++; and this.size--; respectively. "Remove 'this' qualification". You can simply write size++; and size--;. If you also use the naming convention mentioned above, it becomes clear that this refers to fields, which makes the this qualification even more obsolete: _size++; and _size--;.
{ "domain": "codereview.stackexchange", "id": 45127, "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#, object-oriented, linked-list, console, inheritance", "url": null }
shell, sh, docker Title: Debian and Docker compose upgrade script Question: I'm running Debian 12 and Docker compose containers. Once a day, crontab should start the script, but the script should also be called manually. Could you rate my upgrade script file or recommend an alternative approach? Requirements for the script: Debian 12 should be (fully) upgraded Docker compose container should be stopped, pulled an updated Docker compose should then be restarted automatically docker system prune should be called afterward If a system reboot is required, the script should reboot The normal and error output should be to appear in console AND in an output file Between several steps there, should be a time waiting #!/bin/sh spath="/home/<...>/<folder>/" sname="script_all.sh" if [ $# -eq 0 ] then sh "${spath}${sname}" "arg1" 2>&1 | tee -a "${spath}log_$(date +%F_%T_%N).txt" exit fi cd $spath || exit docker compose down sleep 5 sudo apt update && sudo DEBIAN_FRONTEND=noninteractive apt upgrade -y && sudo apt autoremove -y && sudo apt autoclean sleep 5 if [ -f /var/run/reboot-required ] then at now + 2 minute -f "${spath}${sname}" sudo reboot else docker compose pull docker compose build --pull docker compose up -d sleep 5 docker system prune -a -f docker system df sleep 5 docker stats --no-stream | sort -k 2 fi Thanks in advance. Answer: shebang #! /bin/sh No bash ? Ok, suit yourself. Bash definitely offers more builtin functionality than Bourne shell. uniformly capture errors cd $spath || exit I like the sentiment, here. Consider making set -e -o pipefail the second line of this script. Then cd would bail with error status if there's trouble. If you had run the shellcheck linter, I imagine it would have asked for extra quotes around the spath expansion. Not a problem, here. But you should probably be linting, if this is code you care about. log file sh "${spath}${sname}" "arg1" ...
{ "domain": "codereview.stackexchange", "id": 45128, "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": "shell, sh, docker", "url": null }
shell, sh, docker log file sh "${spath}${sname}" "arg1" ... The literal arg1 is odd. You might have helpfully called it logging. But the whole approach is odd, better to avoid it. You can grab the output of several commands with (cmd_1; ... ; cmd_N) | tee ..., where the commands may span several lines. Better, package the body of the script as a function, perhaps named upgrade. And then upgrade 2>&1 | tee ... suffices. magic numbers docker compose down sleep 5 That 5 tuning parameter makes me nervous. Couldn't we sleep 1 in a while loop that keeps asking docker "is it down yet?", "is it down yet?" Similarly when we're waiting for it to come up. The apt stuff looks fine. But then, why are we sleeping after it? With no explanatory comment? It's all synchronous, there's nothing going on in the background. There's a bunch of sudo calls, and maybe that's what you want, for auditing. Consider consolidating them with sudo bash -c " ... " The now + 2 minute thing is just weird. Is that to give you a chance to manually poke around at the last moment? Reboot at once and be done with it. The larger system is composed of machines + people, and its reliability goes down when people invent mythologies about what's happening at the moment and what will hopefully happen "soon". docker system df sleep 5 Again, offer a # comment describing why a sleep is required at all, and why 5 is exactly what's needed there. Consider replacing it with a looping test, similar to awaiting docker down / up transitions.
{ "domain": "codereview.stackexchange", "id": 45128, "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": "shell, sh, docker", "url": null }
c++, c, strings Title: A simple and safe implementation for strnstr (search for a substring in the first n characters of char array) Question: I'd like to suggest the following implementation: // Find an instance of substr in an array of characters // the array of characters does not have to be null terminated // the search is limited to the first n characters in the array. char *strnstr(char *str, const char *substr, size_t n) { char *p = str, *pEnd = str+n; size_t substr_len = strlen(substr); if(0 == substr_len) return str; // the empty string is contained everywhere. pEnd -= (substr_len - 1); for(;p < pEnd; ++p) { if(0 == strncmp(p, substr, substr_len)) return p; } return NULL; } The rationale for the first parameter is not to be const is that you may want to use the return value pointer to modify the array in that location. for completeness, in C++, it's possible to add an overloaded variant that's const: const char *strnstr(const char *str, const char *substr, size_t n) { return strnstr((char *)str, substr, n); } Any comments? As suggested, here's a test program: #include <iostream> #include <cstring> #include <string> int main() { char s[] = "1234567890abcdefgh"; size_t n = sizeof(s) - 1; const char *patterns[] = { "efgh", "0ab", "0b", NULL }; const char *result = NULL; const char *pPattern = patterns[0]; std::cout << "array of length " << n << " is: " << s << std::endl; for (int i = 0; pPattern; pPattern = patterns[++i]) { result = strnstr(s, pPattern, n); std::cout << "finding " << pPattern << " n=" << n << ": " << (result ? result : "(null)") << std::endl; } pPattern = patterns[0]; result = strnstr(s, pPattern, n-1); std::cout << "finding " << pPattern << " n=" << n-1 << ": " << (result ? result : "(null)") << std::endl; return 0; }
{ "domain": "codereview.stackexchange", "id": 45129, "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, strings", "url": null }
c++, c, strings Output: array of length 18 is: 1234567890abcdefgh finding efgh n=18: efgh finding 0ab n=18: 0abcdefgh finding 0b n=18: (null) finding efgh n=17: (null) Answer: Design: The str as an array and searched up to n is inconsistent with string like functions and strstr(). Rather than "the search is limited to the first n characters in the array", I'd also expect characters in str that follow a null character are not searched. IMO, a design flaw. Following review assumes str[i] == 0 has no special meaning. Weak argument name str. str is the address of an array and maybe not a string. Calling a potential non-string str conveys the wrong idea. Suggest src, etc. When looking for sub-strings, I like needle and haystack. As the C version does not change str contents, recommend making that const. "The rationale for the first parameter is not to be const is that you may want to use the return value pointer to modify the array in that location." does not apply. Just cast char * the return value. Follow strstr()s tyle. // From C library. char *strstr( const char *s1, const char *s2); // Expected signatures: (spaced for clarity) // C char *strnstr(const char *src, const char *substr, size_t n); // C++ char *strnstr( char *src, const char *substr, size_t n); const char *strnstr(const char *src, const char *substr, size_t n); Using a name that is close to standard names is tricky. C reserves name with certain prefixes, etc and so does *nix, etc. Maybe use CP_strnstr() and an optional #define strnstr CP_strnstr. Corner case: Returning str with if(0 == substr_len) return str; does not make sense when size == 0. I'd expect NULL. Underflow possible. The length of the needle may be longer or shorter than the haystack // add check if (n + 1 < substr_len) { return NULL; } pEnd -= (substr_len - 1); Minor In debug mode, consider testing against NULL char *strnstr(char *str, const char *substr, size_t n) { assert(str || n == 0); assert(substr);
{ "domain": "codereview.stackexchange", "id": 45129, "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, strings", "url": null }
c, makefile Title: Rate my Makefile Question: Here's the Makefile I've built up over the last two years which I use as a template (most often verbatim apart from target name(s)). It's meant to be used for C exclusively. I've sort of cobbled it together, so it's very well possible I made a bone-headed mistake somewhere, hence why I'd like some more experienced eyes to review it! If there's anything that needs explaining, please comment and I'll update the post. TARGETS := target CC := gcc CFLAGS := -c -W -Wall -pedantic -O3 DEBUG_CFLAGS := -c -W -Wall -pedantic -g -Og LDFLAGS := -lm DEBUG_LDFLAGS := -g $(LDFLAGS) BINDIR := ./bin DEBUGDIR := ./debug OBJDIR := ./obj SRCDIR := ./src TESTDIR := ./test SOURCES := $(wildcard $(SRCDIR)/*.c) MAINS := $(TARGETS:%=$(OBJDIR)/%.o) OBJECTS := $(filter-out $(MAINS), $(SOURCES:$(SRCDIR)/%.c=$(OBJDIR)/%.o)) DEBUGOBJECTS := $(OBJECTS:$(OBJDIR)/%.o=$(DEBUGDIR)/%.do) DEBUGTARGETS := $(TARGETS:%=%.db) TESTSOURCES := $(wildcard $(TESTDIR)/*.c) TESTS := $(TESTSOURCES:$(TESTDIR)/%.c=$(BINDIR)/%) all : $(TARGETS) debug: $(DEBUGTARGETS) test : $(TESTS) $(TARGETS): % : $(OBJDIR)/%.o $(OBJECTS) $(CC) -o $@ $^ $(LDFLAGS) $(OBJECTS): $(OBJDIR)/%.o : $(SRCDIR)/%.c mkdir -p $(OBJDIR) $(CC) $(CFLAGS) $^ -o $@ $(MAINS): $(OBJDIR)/%.o : $(SRCDIR)/%.c mkdir -p $(OBJDIR) $(CC) $(CFLAGS) $^ -o $@ $(DEBUGTARGETS): $(DEBUGOBJECTS) $(CC) -o $@ $^ $(DEBUG_LDFLAGS) $(DEBUGOBJECTS): $(DEBUGDIR)/%.do : $(SRCDIR)/%.c mkdir -p $(DEBUGDIR) $(CC) $(DEBUG_CFLAGS) $^ -o $@ $(TESTS): $(BINDIR)/%_test : $(TESTDIR)/%_test.c $(filter-out $(MAINS), $(OBJECTS)) mkdir -p $(TESTDIR) mkdir -p $(BINDIR) $(CC) -o $@ $^ $(LDFLAGS) $@ clean: rm -f $(MAINS) $(OBJECTS) $(TARGETS) $(TESTS)
{ "domain": "codereview.stackexchange", "id": 45130, "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, makefile", "url": null }
c, makefile Answer: Not Enough CFLAGS You currently have c -W -Wall -pedantic -O3. First, -c shouldn’t be there; it just stops you from using CFLAGS in a single-stage compile. Move it to the targets that create object files. You don’t specify a version of the language on the command line, despite asking for -pedantic warnings. GCC defaults to -std=c90, while I would normally use -std=c17, but whatever your project uses, make it explicit and make sure everyone knows what they’re supposed to be using. There are a lot more useful warnings that you haven’t enabled, for example, implicit conversion between signed and unsigned. I typically use -std=c17 -Wall -Wextra -Wpedantic -Wconversion -Wdeprecated. If you set out to remove all warnings (disabling any specific ones that you decide not to fix, and fixing the rest), you might want -Werror. You don’t specify a submodel, but it’s very unlikely that you would want to release software that needs to run on the very earliest x86-64 CPUs without AVX or even cmpxchg16b. Or if you’re compiling and testing binaries that only you will use, and what you share will be the source, you should always add -march=native. You likely also want -flto for whole-program optimization, in your release build. I typically set the POSIX feature-test macros in a header that I include at the top of all source files, but you could set that here if you prefer. Consider a Few Debug Flags You currently have -Og, which is a good choice for debug optimization. There is no reason not to also add -march=native. If you wrote any tail-recursive calls, you might also need -foptimize-sibling-calls to avoid a stack overflow. Do You Really Want to Compile and Link Every file in the Directory? For example, if you create fop.o instead of foo.o by a typo, should that always be linked in? Better to keep a list of what object files you’re supposed to have. What if a Header Changes?
{ "domain": "codereview.stackexchange", "id": 45130, "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, makefile", "url": null }
c, makefile What if a Header Changes? Listing the object files also lets you specify header files as dependencies, so that the correct files get recompiled when you edit a header. Your make clean Does not Clean Up Your Debug Builds Your debug target creates *.do and *.db files, which your clean target never cleans.
{ "domain": "codereview.stackexchange", "id": 45130, "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, makefile", "url": null }
haskell, reinventing-the-wheel Title: Implementing Haskell's `unwords` Question: Learn You a Haskell explains the unwords function. $unwords ["hey","there","mate"] "hey there mate" Here's my implementation. unwords' :: [String] -> String unwords' [] = [] unwords' (x:xs) | null xs = x | otherwise = x ++ " " ++ unwords' xs Is there a possible implementation with fold? I tried the following, but the " " got appended to the end. $foldr (\x acc -> x ++ " " ++ acc) [] ["hey", "there", "mate"] "hey there mate " Also, how can I append a String([Char]) to another String without ++? Lastly, please critique in general. Answer: Your foldr solution doesn't work because it's using the empty list you're passing in the final step. You can use foldr1 instead, it uses the final element of the list in place of being passed an accumulator value. Looking to the folds to implement unwords isn't a bad idea, but there are other high-level functions that you can use to write a more terse or readable version. Let's start from a verbal description of what unwords is doing. Insert a space character between every String in a list, then join the resulting Strings together. The latter half of that description is easy, we know that String is really [Char], and we can easily flatten doubly-nested lists with concat. The former portion we could implement on our own, or search Hoogle for to see if anything already exists in the Prelude or other modules that could help us out. In this case, we're looking for a function with the type a -> [a] -> [a], that is, we want to pass it a value and a list and have it return a list with that value inserted between each pair of elements. As luck would have it, there's a function in Data.List that does exactly what we're looking for called intersperse that comes up as the first result if we perform that search. Using these two functions, we can write a very short version of unwords that reads almost like prose. import Data.List (intersperse) import Prelude hiding (unwords)
{ "domain": "codereview.stackexchange", "id": 45131, "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": "haskell, reinventing-the-wheel", "url": null }
haskell, reinventing-the-wheel unwords :: [String] -> String unwords = concat . intersperse " " Besides the aesthetic appeal of this solution, to me this illustrates the power of thinking about what you want to do in Haskell, instead of thinking about how it's going to be done.
{ "domain": "codereview.stackexchange", "id": 45131, "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": "haskell, reinventing-the-wheel", "url": null }
performance, matlab Title: considering only the instants of trading with the relative price avoiding stale returns Question: in my MATLAB code I describe a model for price formation with stale returns in this framework there are 2 type of trader: informed traders who always trade in the "right direction" and noise trader who make their buy/sell decision throwing a coin with likelihood of 50% for a buy/sell order. in my work the probability of arrival of an informed trader(PAIT) is fixed and equal TO 0.799, the informer trader execute their trade only when the difference between efficient price and midquote is greater in absolute value of the total costs ( bid-ask spread+ per funding cost). That's why in the first section of my code zomming on the plot of the log-prices we can see flat area : there is the arrival of an informed trader who decide to do not trade because of the higher transaction costs, in this case the price is equal to the previous one the efficient price is given by the price at the previous instant plus a random schocks ( stocks follows a martingale process) . The midquote of the bid-ask prices at time t is equal to mid_quotes(t,:) = mid_quotes(t-1,:)+... delta*(eff_prices(t,:)-mid_quotes(t-1,:)) + ... (1-delta)*sigma_m*shocksWm(t,:); where delta is speed of learning of the market maker. the observed price is equal to the following function function logp = flatten_eff_prices(p_start,n_min,ndays,mid_quotes,trader_type,buy_trade,sell_trade,zero_trade,nois_trade) logp = NaN*ones(n_min,ndays); logp(1,:) = p_start*ones(1,ndays); for j=2:n_min logp(j,:) = mid_quotes(j,:) + trader_type(j,:).*(buy_trade(j,:)+sell_trade(j,:)+zero_trade(j,:).*(logp(j-1,:)-mid_quotes(j,:)))+(1-trader_type(j,:)).*nois_trade(j,:); end end
{ "domain": "codereview.stackexchange", "id": 45132, "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": "performance, matlab", "url": null }
performance, matlab end in this function when trader type is equal to 1 the first part activates, that is there is an informed trader who can buy/sell or do not do anything because there is no convienence, if trader_type == 0 it means that there is a noise trader and the second part is activated((1-trader_type(j,:)).*nois_trade(j,:)) The process of generations of efficient prices and midquote is described in the following function function [eff_prices,mid_quotes] = midquotes_and_effprices(n_min,ndays,sigma_eff,sigma_m,delta,beta,shocksWe,shocksWm,dfactor) eff_prices = zeros(n_min,ndays); mid_quotes = zeros(n_min,ndays); for t=2:n_min eff_prices(t,:) = eff_prices(t-1,:)+sigma_eff*shocksWe(t,:)+beta*dfactor(t,:); mid_quotes(t,:) = mid_quotes(t-1,:)+ delta*(eff_prices(t,:)-mid_quotes(t-1,:)) + (1-delta)*sigma_m*shocksWm(t,:); end end after generating the log price in my script we can see that there are flat area . This happens because there are price repetitions, there is the arrival of an informed trader trader_type = double(shocks.U<par.PAIT) who decide to do not trade because abs(eff_prices-mid_quotes)<=c) What I want to do is to consider only the trading times with the relative prices ( like a real dataset) , roughly speaking I want to delete the flatness due to price repetitions nrep = 10; n_obs_per_day = 6*60*60*100; %1/10 di sec N_asset = 1; par.sigma_eff = 0.00927; par.sigma_m = 0.00927; par.delta = 0.01; par.bidask = 1.905*(10^(-4)); par.beta = 1; par.funding_cost = 0.311*(10^(-4)); par.PAIT = 0.799; par.sigma_factor = 0; shocks.U = rand(n_obs_per_day,nrep);
{ "domain": "codereview.stackexchange", "id": 45132, "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": "performance, matlab", "url": null }
performance, matlab shocks.We = cell(N_asset,1); shocks.Wm = cell(N_asset,1); shocks.p_eps = cell(N_asset,1); shocks.We = randn(n_obs_per_day,nrep)/sqrt(n_obs_per_day); shocks.Wm = randn(n_obs_per_day,nrep)/sqrt(n_obs_per_day); shocks.p_eps = double(rand(n_obs_per_day,nrep)>(1/2)); shocks.Wfactor = zeros(n_obs_per_day,nrep)/sqrt(n_obs_per_day); dfactor = par.sigma_factor*shocks.Wfactor; p_start = 0; [eff_prices,mid_quotes] = midquotes_and_effprices(n_obs_per_day,nrep,... par.sigma_eff,... par.sigma_m,... par.delta,... par.beta,... shocks.We,... shocks.Wm,... dfactor); c = par.bidask+par.funding_cost; costs = c*ones(n_obs_per_day,nrep); buy_trade = double((eff_prices-mid_quotes>costs).*par.bidask); sell_trade = double((eff_prices-mid_quotes<-costs).*(-par.bidask)); zero_trade = double((abs(eff_prices-mid_quotes)<=c)); nois_trade = double(par.bidask.*cumprod(2*shocks.p_eps-1)); trader_type = double(shocks.U<par.PAIT); logp = flatten_eff_prices(p_start,... n_obs_per_day,... nrep,... mid_quotes,... trader_type,... buy_trade,... sell_trade,... zero_trade,... nois_trade); figure; plot(logp) this is my attempt where I create a cell array with the 10 replications and for each replications we have the instant of trading and the relative price. there is no flatnees since at each instant(not equally spaced) there is a trading which can be generated by either an informed trader or a noise trader , the only problem is that the code is computationally expensive since it takes hours to run. can someone help me to improve the speed of my code? %% trading_data_combined = cell(1, nrep);
{ "domain": "codereview.stackexchange", "id": 45132, "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": "performance, matlab", "url": null }
performance, matlab for rep = 1:nrep trading_times_informed = []; trading_prices_informed = []; trading_times_noise = []; trading_prices_noise = []; for j = 2:n_obs_per_day if (shocks.U(j, rep) < par.PAIT) % informed if abs(eff_prices(j, rep) - mid_quotes(j, rep)) > c trading_times_informed = [trading_times_informed; j]; trading_prices_informed = [trading_prices_informed; logp(j, rep)]; end else % noise trader trading_times_noise = [trading_times_noise; j]; trading_prices_noise = [trading_prices_noise; logp(j, rep)]; end end combined_data = sortrows([trading_prices_informed, trading_times_informed; trading_prices_noise, trading_times_noise], 2); trading_data_combined{rep} = combined_data; end Answer: To speed up code you have to start with two things: Pay attention to the warnings that the MATLAB Editor gives you: Four lines have red squiggles underneath, hovering over them says "Variable appears to change size on every loop iteration. Consider preallocating for speed." This comes with a button "Details", where you learn much more about why these lines of code will be slow. Fix the warnings! It is these lines: trading_times_informed = [trading_times_informed; j]; trading_prices_informed = [trading_prices_informed; logp(j, rep)]; trading_times_noise = [trading_times_noise; j]; trading_prices_noise = [trading_prices_noise; logp(j, rep)];
{ "domain": "codereview.stackexchange", "id": 45132, "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": "performance, matlab", "url": null }
performance, matlab Run the code under the profiler. In the MATLAB Editor, there is a button "Run", if you click the bottom part it expands into a menu. The top options here is "Run and Time". This runs the code under the profiler, where you can learn how much each line of code takes to run. Because it takes for ever to run, I ran it for a short bit and stopped it. Two of the four lines indicated above each take 45% of the time (it's the two noise ones, which I guess are much more common than the informed trades). This means that 90% of the time is taken up just reallocating these arrays.
{ "domain": "codereview.stackexchange", "id": 45132, "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": "performance, matlab", "url": null }
performance, matlab So let's fix these four lines of code as recommended by the Editor. There are different ways of doing this. One way is to allocate enough elements to never run out: we do n_obs_per_day iterations, so none of these 4 arrays will have more elements than this. We now also need two counters (one for each pair of arrays). After the loop we will cut the arrays down to the number of used rows: trading_times_informed = zeros(n_obs_per_day, 1); trading_prices_informed = zeros(n_obs_per_day, 1); n_informed = 0; trading_times_noise = zeros(n_obs_per_day, 1); trading_prices_noise = zeros(n_obs_per_day, 1); n_noise = 0; for j = 2:n_obs_per_day if (shocks.U(j, rep) < par.PAIT) % informed if abs(eff_prices(j, rep) - mid_quotes(j, rep)) > c n_informed = n_informed + 1; trading_times_informed(n_informed) = j; trading_prices_informed(n_informed) = logp(j, rep); end else % noise trader n_noise = n_noise + 1; trading_times_noise(n_noise) = j; trading_prices_noise(n_noise) = logp(j, rep); end end trading_times_informed = trading_times_informed(1:n_informed); trading_prices_informed = trading_prices_informed(1:n_informed); trading_times_noise = trading_times_noise(1:n_noise); trading_prices_noise = trading_prices_noise(1:n_noise); The red squiggly lines are now gone. The code, running under the profiler, takes 4.3 seconds to run. The line if (shocks.U(j, rep) < par.PAIT) takes 33%, the next slowest line is only 8.3%, and it does down from there. I think this looks pretty even now. Can we speed up the code more? Yes, of course. We can vectorize the loop and reduce the amount of indexing. Do we need to? I don't think so. 4 seconds seems like a short amount of time for this experiment.
{ "domain": "codereview.stackexchange", "id": 45132, "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": "performance, matlab", "url": null }
performance, matlab The change above complicated the code a bit. In this Q&A, we learn that trading_times_noise = [trading_times_noise; j]; is a lot more expensive way to append to an array than trading_times_noise(end+1) = j; What if we use that instead? trading_times_informed = []; trading_prices_informed = []; trading_times_noise = []; trading_prices_noise = []; for j = 2:n_obs_per_day if (shocks.U(j, rep) < par.PAIT) % informed if abs(eff_prices(j, rep) - mid_quotes(j, rep)) > c trading_times_informed(end+1, 1) = j; trading_prices_informed(end+1, 1) = logp(j, rep); end else % noise trader trading_times_noise(end+1, 1) = j; trading_prices_noise(end+1, 1) = logp(j, rep); end end Now the code looks as simple as it did originally (and even a bit simpler!), but we still have the red squiggles. This is less efficient than the version where we preallocate the arrays, but the total time is still very manageable, this is a good way to append to arrays. [Note that I used trading_times_noise(end+1, 1), rather than simply trading_times_noise(end+1), because the latter creates a row vector, but this code needs a column vector. We could instead have permuted the result later. There are other things to note about the code: I would suggest adding more spaces. Typical MATLAB style uses way too few spaces, but code is easier to read with more spaces around operators and after commas. Some lines are very long: logp(j,:) = mid_quotes(j,:) + trader_type(j,:).*(buy_trade(j,:)+sell_trade(j,:)+zero_trade(j,:).*(logp(j-1,:)-mid_quotes(j,:)))+(1-trader_type(j,:)).*nois_trade(j,:);
{ "domain": "codereview.stackexchange", "id": 45132, "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": "performance, matlab", "url": null }
performance, matlab Try to break those up, computing parts separately. Or at least space out components and add line breaks: logp(j,:) = ... mid_quotes(j,:) + ... trader_type(j,:) .* ( ... buy_trade(j,:) + ... sell_trade(j,:) + ... zero_trade(j,:) .* (logp(j-1,:) - mid_quotes(j,:)) ... ) + ... (1-trader_type(j,:)) .* nois_trade(j,:); The line costs = c*ones(n_obs_per_day,nrep); is redundant. You compare one array to costs, and a different one to c directly. That is the right way to compare to a constant. Creating and using this larger constant array is inefficient.
{ "domain": "codereview.stackexchange", "id": 45132, "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": "performance, matlab", "url": null }
c, array, queue Title: Redefining queue with different front and rear Question: #include <stdio.h> #include <limits.h> #define MAX_SIZE 5 #define FULL INT_MAX #define EMPTY INT_MIN int Q[MAX_SIZE]; // linear queue // int rear = -1; int front = 0; // condition for empty is Qsize is zero (front > rear) // // condition for full is rear is at last index (rear == MAX_SIZE - 1) // // basic operations on Queue // int add_Q(int item); // if full returns (INT_MAX) else returns item inserted // int delete_item_in_Q(); // if empty returns (INT_MIN) else returns deleted item // size_t Qsize(); // returns 0 if (front > rear) else returns the current size of Q // // read operations // int rear_data(); // if empty returns (INT_MIN) else returns rear data // int front_data(); // if empty returns (INT_MIN) else returns front data // void read_Q(); void delete_Q(); void get_Q(size_t size); int main(void){ int size; printf("\nenter your size(positive) for Queue (less than %d) : ",MAX_SIZE); scanf("%d",&size); get_Q(size); read_Q(); add_Q(66); read_Q(); delete_item_in_Q(); read_Q(); delete_Q(); read_Q(); return 0; } void get_Q(size_t size){ int item; if(size > MAX_SIZE){ printf("enter valid size \n"); return; } for(int i = 0 ; i < size ; i ++){ printf("enter your queue elements : "); scanf("%d",&item); add_Q(item); } } int add_Q(int item){ return rear == (MAX_SIZE - 1) ? FULL : (Q[++rear] = item); } int delete_item_in_Q(){ return Qsize() ? Q[front++]:EMPTY; } size_t Qsize(){ if(front > rear){ front = 0;rear = -1; } return (rear - front + 1); } int front_data(){ return Qsize() ? Q[front]:EMPTY; } int rear_data(){ return Qsize() ? Q[rear]:EMPTY; } void read_Q(){ if(!Qsize()){ printf("\nthe queue is empty\n"); return; }
{ "domain": "codereview.stackexchange", "id": 45133, "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, queue", "url": null }
c, array, queue if(!Qsize()){ printf("\nthe queue is empty\n"); return; } int i = front; printf("\nthe queue is : "); while(1){ printf("%d=>",Q[i++]); if(i == MAX_SIZE){ printf("\nqueue is full\n"); return; } else if (i > rear){ putchar('\n'); return; } } } void delete_Q(){ while(1){ if(!Qsize()){ printf("\nthe queue is empty\n"); return; } printf("the deleted element is : %d\n",Q[front++]); } } In my queue(linear) rear = -1 and front = 0 unlike(front = rear = -1) and assumes user doesn't enter INT_MIN or INT_MAX. I am not checking the return values of many functons like scanf(),add_Q() for simplicity. rear and front points to valid data if (front <= rear) empty if (front > rear). Qsize() always reinitialize the index back to original in empty state In order to access queue the above conditions must be "strictly" met or else we say it is empty, so is this queue a valid one ? my teacher said that it is not a good one (rear or front is pointing at locations inside the array in empty conditions). Is there any problem in my code ? I have tried to look for errors but none was found (based on my definition). and I need a better solution that doesn't assume user never enter INT_MIN or INT_MAX (but it should return the added or deleted data). read_Q() also looks bad. I need a better one for it. Answer: Your teacher is right. This is not a good FIFO. Is there any problem in my code ? We're not ready to go there, yet. Let's first worry about problems with the design. We want to implement a queue that others would want to use, and currently this doesn't fit the bill. production use, 24x7 It is perfectly valid for a consumer to do this all day long: add_Q(get_val()); while (TRUE) { add_Q(get_val()); add_Q(get_val());
{ "domain": "codereview.stackexchange", "id": 45133, "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, queue", "url": null }
c, array, queue while (TRUE) { add_Q(get_val()); add_Q(get_val()); process(delete_item_in_Q(), delete_item_in_Q()); } That is, the queue receives an unbounded stream of values, and queue depth is bounded, it always hovers between 1 .. 3 inclusive. It never becomes EMPTY. And that's ok. It definitely never becomes FULL, though in your implementation it would. circular reasoning How can we accommodate such a usage pattern? Malloc / free of Linked List nodes is certainly one way. I'm glad you didn't go that route. Another way is to use a fixed size array as you have, but allow it to begin at any element, wherever rear points to. As elements are added, we wrap around using modulo MAX_SIZE. Let front always be the index of a free element, and rear (potentially) points at the oldest valid element. When front == rear, the queue is empty, there is no valid element. When (front + 1) % MAX_SIZE == rear then we have wrapped all the way around, and the queue is full. It will not accept any new elements. Notice that we "waste" one cell in that instance, since front == rear is reserved for the empty case rather than the full case. Define the constant to be "one more" if needed by your requirements.
{ "domain": "codereview.stackexchange", "id": 45133, "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, queue", "url": null }
c, array, queue code style If an_identifier starts with lower case, good, stick with that, avoid tacking on a capital letter. Prefer ternary a ? b : c for read-only expressions. Clearly you can do a ? readonly : sideeffect as in the OP, and it will work. But that doesn't mean it is easily readable by others. Prefer if (a) { b } else { c } for side effects, even in the case that if (a) { return b } else { return c } needs a pair of return statements. Find a code formatter / pretty-printer, and use it. Doesn't matter if it's GNU, Google, K&R, or another style, as long as it's consistent throughout the code. Find a C unit test framework and use it. Automated tests "know the answer", to give Red / Green bar results upon running. They don't require the user to eyeball what was printed and decide whether that was the right result.
{ "domain": "codereview.stackexchange", "id": 45133, "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, queue", "url": null }
c++, validation, c++14 Title: Making an input validator function Question: NOTICE: I refactored the code and made a new question like was advised. I'm making an input validator function that is inspired by @JDługosz from the following post so that other new C++ programmers can just plug it into their code for easy input validation. I have made it with a little deviation regarding the predicates and everything works perfectly! The problem is I see that I repeat myself in a couple of places in the code and I can't come up with a solution that doesn't cause needless complexity. The repetitions are: The custom exceptions are mostly glorified std::runtime_error. The Arithmetic and String predicates repeat the same static_asserts. However, what bothers me more is that MinMaxSymbols could inherit from MinSymbol and MaxSymbol, but from what I read isocpp STRONGLY recommends you don't use multiple inheritance for code reuse. Apart from that T input(const std::string& prompt) and std::string input(const std::string& prompt) repeat almost the same code but I don't see an elegant way to avoid that. Also, I can't remove the templates from the string predicates MinMaxSymbols, MinSymbols, MaxSymbols because the input function that accepts the predicate is a template template. Lastly, any feedback on the code in general is welcome! #include <type_traits> #include <stdexcept> #include <iostream> #include <string> #include <limits> #include <cstddef> /* Custom exceptions--------------------------------------------------------- */ class StreamFailure final : public std::runtime_error { public: StreamFailure(const std::ios::iostate state) : std::runtime_error{ "Stream failed (non-recoverable state)" }, m_state{ state } {} std::ios::iostate state() const noexcept { return m_state; } private: std::ios::iostate m_state; };
{ "domain": "codereview.stackexchange", "id": 45134, "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++, validation, c++14", "url": null }
c++, validation, c++14 private: std::ios::iostate m_state; }; class ExtractionFailure final : public std::runtime_error { public: ExtractionFailure() : std::runtime_error{ "Failed to extract value from stream" } {} }; class PredicateFailure final : public std::runtime_error { public: PredicateFailure() : std::runtime_error{ "Input predicate not met" } {} }; class BadPredicateParams final : public std::runtime_error { public: BadPredicateParams() : std::runtime_error{ "Bad predicate parameters" } {} }; /* Arithmetic predicates----------------------------------------------------- */ template<typename T> class Between final { public: static_assert(std::is_arithmetic<T>::value, "Only arithmetic types are supported"); constexpr Between(const T min, const T max) : m_min{ min }, m_max{ max } { if(min >= max) { throw BadPredicateParams{}; } } constexpr bool operator()(const T value) const noexcept { return value >= m_min && value <= m_max; } private: T m_min; T m_max; }; template<typename T> class GreaterThen final { public: static_assert(std::is_arithmetic<T>::value, "Only arithmetic types are supported"); constexpr GreaterThen(const T min) noexcept : m_min{ min } {} constexpr bool operator()(const T value) const noexcept { return value > m_min; } private: T m_min; }; template<typename T> class SmallerThen final { public: static_assert(std::is_arithmetic<T>::value, "Only arithmetic types are supported"); constexpr SmallerThen(const T max) noexcept : m_max{ max } {} constexpr bool operator()(const T value) const noexcept { return value < m_max; } private: T m_max; };
{ "domain": "codereview.stackexchange", "id": 45134, "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++, validation, c++14", "url": null }
c++, validation, c++14 private: T m_max; }; /* String predicates--------------------------------------------------------- */ template<typename T> class MinMaxSymbols final { public: static_assert(std::is_same<std::string, T>::value, "Only suported for std::string"); constexpr MinMaxSymbols(const std::size_t min, const std::size_t max) : m_min{ min }, m_max{ max } { if(min >= max) { throw BadPredicateParams{}; } } constexpr bool operator()(const std::string& str) const noexcept { return str.size() >= m_min && str.size() <= m_max; } private: std::size_t m_min; std::size_t m_max; }; template<typename T> class MaxSymbols final { public: static_assert(std::is_same<std::string, T>::value, "Only suported for std::string"); constexpr MaxSymbols(const std::size_t max) noexcept : m_max{ max } {} constexpr bool operator()(const std::string& str) const noexcept { return str.size() <= m_max; } private: std::size_t m_max; }; template<typename T> class MinSymbols final { public: static_assert(std::is_same<std::string, T>::value, "Only suported for std::string"); constexpr MinSymbols(const std::size_t min) noexcept : m_min{ min } {} constexpr bool operator()(const std::string& str) const noexcept { return str.size() >= m_min; } private: std::size_t m_min; }; /* Custom input-------------------------------------------------------------- */ template<typename T> T input(const std::string& prompt) { if(!prompt.empty()) { std::cout << prompt; } T temp{}; std::cin >> temp; if(std::cin.eof() || std::cin.bad()) { throw StreamFailure{ std::cin.rdstate() }; }
{ "domain": "codereview.stackexchange", "id": 45134, "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++, validation, c++14", "url": null }
c++, validation, c++14 constexpr auto max{ std::numeric_limits<std::streamsize>::max() }; if(std::cin.fail()) { std::cin.clear(); std::cin.ignore(max, '\n'); throw ExtractionFailure{}; } std::cin.ignore(max, '\n'); return temp; } template<> std::string input(const std::string& prompt) { if(!prompt.empty()) { std::cout << prompt; } std::string temp{}; std::getline(std::cin, temp); if(std::cin.eof() || std::cin.bad()) { throw StreamFailure{ std::cin.rdstate() }; } constexpr auto max{ std::numeric_limits<std::streamsize>::max() }; if(std::cin.fail()) { std::cin.clear(); std::cin.ignore(max, '\n'); throw ExtractionFailure{}; } return temp; } template<typename T, template<typename> class Predicate> T input(const std::string& prompt, Predicate<T> pred) { T temp{ input<T>(prompt) }; if(!pred(temp)) { throw PredicateFailure{}; } return temp; } int main() { int i{}; float f{}; std::string s{}; while(true) { try { i = input<int>("Enter a int between 1-4 inclusive: ", Between<int>{ 1, 4 }); std::cout << i << '\n'; i = input<int>("Enter a int greater then 4: ", GreaterThen<int>{ 4 }); std::cout << i << '\n'; i = input<int>("Enter a int smaller then 4: ", SmallerThen<int>{ 4 }); std::cout << i << '\n'; i = input<int>("Enter any number that fits a int: "); std::cout << i << '\n'; f = input<float>("Enter a float between 1.5 - 2.5 inclusive: ", Between<float>{ 1.5, 2.5 }); std::cout << f << '\n'; f = input<float>("Enter any number that fits a float: "); std::cout << f << '\n';
{ "domain": "codereview.stackexchange", "id": 45134, "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++, validation, c++14", "url": null }
c++, validation, c++14 s = input<std::string>("Enter a name (3-6 symbols): ", MinMaxSymbols<std::string>{ 3, 6 }); std::cout << s << '\n'; s = input<std::string>("Enter a name (3 symbols max): ", MaxSymbols<std::string>{ 3 }); std::cout << s << '\n'; s = input<std::string>("Enter a name (3 symbols min): ", MinSymbols<std::string>{ 3 }); std::cout << s << '\n'; s = input<std::string>("Enter any word: "); std::cout << s << '\n'; } catch(const StreamFailure& e) { std::cerr << e.what() << '\n'; std::cerr << "badbit: " << (e.state() & std::ios::badbit) << '\n'; std::cerr << "eofbit: " << (e.state() & std::ios::eofbit) << '\n'; std::cerr << "failbit: " << (e.state() & std::ios::failbit) << '\n'; } catch(const ExtractionFailure& e) { std::cerr << e.what() << '\n'; } catch(const PredicateFailure& e) { std::cerr << e.what() << '\n'; } catch(const std::exception& e) { std::cerr << e.what() << '\n'; break; } } return 0; }
{ "domain": "codereview.stackexchange", "id": 45134, "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++, validation, c++14", "url": null }
c++, validation, c++14 return 0; } Answer: Overall: Good idea. But your checks seem to be designed for machine input (not user input where a user could be told about the error and can then retry). But on the other hand you are prompting for specific details which is for humans and would only slow the machine reader down. If I assume your primary use case is for "manual human input" then retry logic being built into your class is much better than throwing an exception (which is also why streams don't throw exceptions by default). I liked the idea for validation of the input but would like the ability to chain validators so that I don't have to create a specific validator for a scenario (but could rather chain existing validators). I don't like that you are limiting things to specific category types, I would use the language's ability to use "Duck" typeing to define how the validators work for those specific types. Code Review: This class seems valid as it has more state than a simple runtime error StreamFailure(const std::ios::iostate state) : std::runtime_error{ "Stream failed (non-recoverable state)" }, m_state{ state } But the following classes may be superfluous. But it depends. Do you see users explicitly catching these errors. If the answer is yes then go ahead and keep them. But if they are simply there for the static strings they contain I am not sure they are worth the effort. class ExtractionFailure final : public std::runtime_error class PredicateFailure final : public std::runtime_error class BadPredicateParams final : public std::runtime_error
{ "domain": "codereview.stackexchange", "id": 45134, "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++, validation, c++14", "url": null }
c++, validation, c++14 Personally. I create exception classes specifically because I think that it is worth catching the exceptions. It is worth catching the exception when there is potential corrective actions available for the user of my interface. Thus in the exception I document what it means and what I think the catcher "can" do to compensate as part of the exception. If the exception is just a generic warning I use one of the standard exceptions and dump some information to a log file. A lot of C++ programmer are used to use iterator like ranges. So end is one past the end. In the class Between you are not using it this way. Here end is within the range. Mathematically you are probably correct, but you have to consider your audience. class Between final { public: ... constexpr bool operator()(const T value) const noexcept { return value >= m_min && value <= m_max; } ... }; Why are you limiting to arithmetic types? static_assert(std::is_arithmetic<T>::value, "Only arithmetic types are supported"); A lot of code in C++ uses duck typing. If the type defines the appropriate operators then why should you not be able to use it with these classes. Same comment here: class MinMaxSymbols final static_assert(std::is_same<std::string, T>::value, "Only suported for std::string"); If the class T supports the size() method then why not allow the use of this class to validate it. If you only want to support string. Why are you limiting to char type strings. Why is their no support for wchar_t strings? Design issue on input() functions.
{ "domain": "codereview.stackexchange", "id": 45134, "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++, validation, c++14", "url": null }
c++, validation, c++14 Design issue on input() functions. You are forcing an extra move operation (which on some types may be a copy). You only support std::cin? I suppose if this is only for direct manual user input then that is fine. But a lot of time the program will be developed using user input to test and validate but when it goes into production you will then be streaming input from a file or socket (or the output of one command will be streamed to the input of this command). I would make Input a wrapper class then overload the operator>>. So you usage would look like this: int i = input<int>("Testing: "); I would change it to look like: int i; // Allows any input stream. // Streams directly into the variable. // If you are not using "human input" then turn of re-checking std::cin >> Input(i, "Testing: ", humanInput); -- // You are forcing a zero construction of `temp` T temp{}; // But now you overwrite the default construction. // Seems like the initial forced zeroing is wasted. std::cin >> temp; // The stream class already has a way to automatically throw // when things go wrong. // std::cin.exceptions(std::ios::eofbit | std::ios::badbit); // see: https://cplusplus.com/reference/ios/ios/exceptions/ if(std::cin.eof() || std::cin.bad()) { throw StreamFailure{ std::cin.rdstate() }; } constexpr auto max{ std::numeric_limits<std::streamsize>::max() }; if(std::cin.fail()) { std::cin.clear(); std::cin.ignore(max, '\n'); throw ExtractionFailure{}; } // So the input worked. // Now you are ignoring the remainder of the line. // Not sure this is a good idea. I would say if there // is anything else on the line you have bad input // and throw an error. // example: Reading and int // User Types: 12T // Your code works and silently ignores the T character. // That to me looks like bad data.
{ "domain": "codereview.stackexchange", "id": 45134, "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++, validation, c++14", "url": null }
c++, validation, c++14 // example: Reading a string (for user name). // User Input "Loki Astari" // Your code works and silenlently drops the second part of the name std::cin.ignore(max, '\n'); return temp; } If this is truly checking interactive user input. Then should you not generate an error message and ask the user to try again. The only time worth bailing is if this is NOT interactive user input (it can't be fixed so stop processing now). At the moment, you are forcing the user of your code to wrap this in a try catch block. int result; while (true) { try { result = input<int>("Testing: "); break; } catch(ExtractionFailure const& e) { std::cout << "Bad Input: Try again\n"; } } I would do soemmthing like this: template<typename T> class Input { T& dst; std::string prompt; bool human; constexpr std::sszie_t max{ std::numeric_limits<std::streamsize>::max() }; public: Input(T& d, std::string prompt, bool human) : dst(d) , std::move(prompt) , human(human) {} friend std::istream& operator>>(std::istream& s, Input& dest) { dest.read(s); return s; } void read(std::istream& s) { while (true) { if(!prompt.empty() && human) { std::cout << prompt << std::endl; } if (s >> temp) { // It worked
{ "domain": "codereview.stackexchange", "id": 45134, "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++, validation, c++14", "url": null }
c++, validation, c++14 // If this is human "Line" based input then anything // else on the line may be an error. If this is // machine readable input then it may not be line based. break; } if(s.eof() || s.bad()) { // Non-correctable error throw StreamFailure{ std::cin.rdstate() }; } // Correctable Error. // So reset the stream if this is a human. if (!human) { throw ExtractionFailure{}; } // Human input line based. // So clear error ignore to the end of the line s.clear(); s.ignore(max, '\n'); std::cout << "Bad input: Try again\n"; } } }; This alternative allows a single predicate. template<typename T, template<typename> class Predicate> T input(const std::string& prompt, Predicate<T> pred) { T temp{ input<T>(prompt) }; if(!pred(temp)) { throw PredicateFailure{}; } return temp; } Have you though about chaining tests so that you can apply multiple? MyBrain brain; std::cin >> Input(brain, "Add brain characteristics: ", human) >> ValidateNerve(true) >> ValidateBundled(true) >> CheckIQLevel(85, 101 + (human ? 0 : 99));
{ "domain": "codereview.stackexchange", "id": 45134, "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++, validation, c++14", "url": null }
c++, strings, immutability Title: An immutable C++ string with ref-counting Question: Class intended to be used as main type in a key-value database where keys and values are strings. Searched features: It is a const char * Behaves like a std::string Reference counting integrated reducing the number of indirections Vampirizes string_view using ptr + len Some additional methods (contains(), trim(), etc) Basically, it is a pointer to chars where pointed memory is prefixed by the ref-counter (4-bytes) and the string length (4-bytes). An example of usage and the unit tests can be found at: https://github.com/torrentg/cstring Not 100% sure on memory alignment and thread-safety. I will appreciate your comments and suggestions. Here is cstring.hpp #pragma once #include <memory> #include <string> #include <limits> #include <atomic> #include <utility> #include <cassert> #include <cstdint> #include <stdexcept> #include <string_view> #include <type_traits> namespace gto {
{ "domain": "codereview.stackexchange", "id": 45135, "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++, strings, immutability", "url": null }
c++, strings, immutability namespace gto { /** * @brief Immutable string based on a plain C-string (char *) with ref-counting. * @details * - Shared content between multiple instances (using ref counting). * - Automatic mem dealloc (when no refs point to content). * - Same sizeof than a 'char *'. * - Null not allowed (equals to empty string). * - Empty string don't require alloc. * - String content available on debug. * - Mimics the STL basic_string class. * @details Memory layout: * * ----|----|-----------0 * ^ ^ ^ * | | |-- string content (0-ended) * | |-- string length (4-bytes) * |-- ref counter (4-bytes) * * mStr (cstring pointer) points to the string content (to allow view content on debug). * Allocated memory is aligned to ref counter type size. * Allocated memory is a multiple of ref counter type size. * @todo * - Validate assumption that sizeof(atomic<uint32_t>) == sizeof(uint32_t) * - Check that processor assumes memory alignment or we need to add __builtin_assume_aligned(a)) or __attribute((aligned(4))) * - Check that std::atomic is enough to grant integrity in a multi-threaded usage * - Explore cache invalidation impact on multi-threaded code * - Performance tests * @see https://en.cppreference.com/w/cpp/string/basic_string * @see https://github.com/torrentg/cstring * @note This class is immutable. * @version 0.9.0 */ template<typename Char, typename Traits = std::char_traits<Char>, typename Allocator = std::allocator<Char>> class basic_cstring { public: // declarations using prefix_type = std::uint32_t; using atomic_prefix_type = std::atomic<prefix_type>; using allocator_type = typename std::allocator_traits<Allocator>::template rebind_alloc<prefix_type>; using allocator_traits = std::allocator_traits<allocator_type>;
{ "domain": "codereview.stackexchange", "id": 45135, "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++, strings, immutability", "url": null }
c++, strings, immutability using traits_type = Traits; using size_type = typename std::allocator_traits<Allocator>::size_type; using difference_type = typename std::allocator_traits<Allocator>::difference_type; using value_type = Char; using const_reference = const value_type &; using const_pointer = typename std::allocator_traits<Allocator>::const_pointer; using const_iterator = const_pointer; using const_reverse_iterator = typename std::reverse_iterator<const_iterator>; using basic_cstring_view = std::basic_string_view<value_type, traits_type>; private: // declarations using pointer = typename std::allocator_traits<Allocator>::pointer; public: // static members static constexpr size_type npos = std::numeric_limits<size_type>::max(); private: // static members static allocator_type alloc; static constexpr prefix_type mEmpty[3] = {0, 0, static_cast<prefix_type>(value_type())}; private: // members //! Memory buffer with prefix_type alignment. const_pointer mStr = nullptr; private: // static methods //! Sanitize a char array pointer avoiding nulls. static inline constexpr const_pointer sanitize(const_pointer str) { return (str == nullptr ? getPtrToString(mEmpty) : str); } //! Return pointer to counter from pointer to string. static inline constexpr atomic_prefix_type * getPtrToCounter(const_pointer str) { assert(str != nullptr); pointer ptr = const_cast<pointer>(str) - 2 * sizeof(prefix_type); return reinterpret_cast<atomic_prefix_type *>(ptr); } //! Return pointer to string length from pointer to string. static inline constexpr prefix_type * getPtrToLength(const_pointer str) { assert(str != nullptr); pointer ptr = const_cast<pointer>(str) - sizeof(prefix_type); return reinterpret_cast<prefix_type *>(ptr); }
{ "domain": "codereview.stackexchange", "id": 45135, "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++, strings, immutability", "url": null }
c++, strings, immutability //! Return pointer to string from pointer to counter. static inline constexpr const_pointer getPtrToString(const prefix_type *ptr) { assert(ptr != nullptr); return reinterpret_cast<const_pointer>(ptr + 2); } //! Returns the allocated array length (of prefix_type values). //! @details It is granted that there is place for the ending '\0'. static size_type getAllocatedLength(size_type len) { return (3 + (len * sizeof(value_type)) / sizeof(prefix_type)); } //! Allocate memory for the counter + length + string + eof. Returns a pointer to string. static pointer allocate(size_type len) { assert(len > 0); assert(len <= std::numeric_limits<prefix_type>::max()); size_type n = getAllocatedLength(len); prefix_type *ptr = allocator_traits::allocate(alloc, n); assert(reinterpret_cast<std::size_t>(ptr) % alignof(prefix_type) == 0); allocator_traits::construct(alloc, ptr, 1); ptr[1] = static_cast<prefix_type>(len); return const_cast<pointer>(getPtrToString(ptr)); } //! Deallocate string memory if no more references. static void deallocate(const_pointer str) { atomic_prefix_type *ptr = getPtrToCounter(str); switch(ptr[0]) { case 0: // constant break; case 1: { // there are no more references prefix_type len = *getPtrToLength(str); size_type n = getAllocatedLength(len); allocator_traits::destroy(alloc, ptr); allocator_traits::deallocate(alloc, reinterpret_cast<prefix_type *>(ptr), n); break; } default: ptr[0]--; } } //! Increment the reference counter (except for constants). static void incrementRefCounter(const_pointer str) { atomic_prefix_type *ptr = getPtrToCounter(str); if (ptr[0] > 0) { ptr[0]++; } } public: // methods
{ "domain": "codereview.stackexchange", "id": 45135, "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++, strings, immutability", "url": null }
c++, strings, immutability public: // methods //! Default constructor. basic_cstring() : basic_cstring(nullptr) {} //! Constructor. basic_cstring(const_pointer str) : basic_cstring(str, (str == nullptr ? 0 : traits_type::length(str))) {} //! Constructor. basic_cstring(const_pointer str, size_type len) { if (str == nullptr || len == 0) { mStr = getPtrToString(mEmpty); return; } else { pointer content = allocate(len); traits_type::copy(content, str, len); content[len] = value_type(); mStr = content; } } //! Destructor. ~basic_cstring() { deallocate(mStr); } //! Copy constructor. basic_cstring(const basic_cstring &other) noexcept : mStr(other.mStr) { incrementRefCounter(mStr); } //! Move constructor. basic_cstring(basic_cstring &&other) noexcept : mStr(std::exchange(other.mStr, getPtrToString(mEmpty))) {} //! Copy assignment. basic_cstring & operator=(const basic_cstring &other) { if (mStr == other.mStr) return *this; deallocate(mStr); mStr = other.mStr; incrementRefCounter(mStr); return *this; } //! Move assignment. basic_cstring & operator=(basic_cstring &&other) noexcept { std::swap(mStr, other.mStr); return *this; } //! Return length of string. size_type size() const noexcept { return *(getPtrToLength(mStr)); } //! Return length of string. size_type length() const noexcept { return *(getPtrToLength(mStr)); } //! Test if string is empty. bool empty() const noexcept { return (length() == 0); }
{ "domain": "codereview.stackexchange", "id": 45135, "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++, strings, immutability", "url": null }
c++, strings, immutability //! Get character of string. const_reference operator[](size_type pos) const { return mStr[pos]; } //! Get character of string checking for out_of_range. const_reference at(size_type pos) const { return (empty() || pos >= length() ? throw std::out_of_range("cstring::at") : mStr[pos]); } //! Get last character of the string. const_reference back() const { return (empty() ? throw std::out_of_range("cstring::back") : mStr[length()-1]); } //! Get first character of the string. const_reference front() const { return (empty() ? throw std::out_of_range("cstring::front") : mStr[0]); } //! Returns a non-null pointer to a null-terminated character array. inline const_pointer data() const noexcept { assert(mStr != nullptr); return mStr; } //! Returns a non-null pointer to a null-terminated character array. inline const_pointer c_str() const noexcept { return data(); } //! Returns a string_view of content. inline basic_cstring_view view() const { return basic_cstring_view(mStr, length()); } // Const iterator to the begin. const_iterator cbegin() const noexcept { return view().cbegin(); } // Const iterator to the end. const_iterator cend() const noexcept { return view().cend(); } // Const reverse iterator to the begin. const_reverse_iterator crbegin() const noexcept { return view().crbegin(); } // Const reverse iterator to the end. const_reverse_iterator crend() const noexcept { return view().crend(); } //! Exchanges the contents of the string with those of other. void swap(basic_cstring &other) noexcept { std::swap(mStr, other.mStr); } //! Returns the substring [pos, pos+len). basic_cstring_view substr(size_type pos=0, size_type len=npos) const { return view().substr(pos, len); }
{ "domain": "codereview.stackexchange", "id": 45135, "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++, strings, immutability", "url": null }
c++, strings, immutability //! Compare contents. int compare(const basic_cstring &other) const noexcept { return view().compare(other.view()); } int compare(size_type pos, size_type len, const basic_cstring &other) const noexcept { return substr(pos, len).compare(other.view()); } int compare(size_type pos1, size_type len1, const basic_cstring &other, size_type pos2, size_type len2=npos) const { return substr(pos1, len1).compare(other.substr(pos2, len2)); } int compare(const_pointer str) const { return view().compare(sanitize(str)); } int compare(size_type pos, size_type len, const_pointer str) const { return substr(pos, len).compare(sanitize(str)); } int compare(size_type pos, size_type len, const_pointer str, size_type len2) const { return substr(pos, len).compare(basic_cstring_view(sanitize(str), len2)); } int compare(const basic_cstring_view other) const noexcept { return view().compare(other); } //! Checks if the string view begins with the given prefix. bool starts_with(const basic_cstring &other) const noexcept { size_type len = other.length(); return (compare(0, len, other) == 0); } bool starts_with(const basic_cstring_view sv) const noexcept { auto len = sv.length(); return (compare(0, len, sv.data()) == 0); } bool starts_with(const_pointer str) const noexcept { return starts_with(basic_cstring_view(sanitize(str))); }
{ "domain": "codereview.stackexchange", "id": 45135, "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++, strings, immutability", "url": null }
c++, strings, immutability //! Checks if the string ends with the given suffix. bool ends_with(const basic_cstring &other) const noexcept { auto len1 = length(); auto len2 = other.length(); return (len1 >= len2 && compare(len1-len2, len2, other) == 0); } bool ends_with(const basic_cstring_view sv) const noexcept { size_type len1 = length(); size_type len2 = sv.length(); return (len1 >= len2 && compare(len1-len2, len2, sv.data()) == 0); } bool ends_with(const_pointer str) const noexcept { return ends_with(basic_cstring_view(sanitize(str))); } //! Find the first ocurrence of a substring. auto find(const basic_cstring &other, size_type pos=0) const noexcept{ return view().find(other.view(), pos); } auto find(const_pointer str, size_type pos, size_type len) const { return view().find(sanitize(str), pos, len); } auto find(const_pointer str, size_type pos=0) const { return view().find(sanitize(str), pos); } auto find(value_type c, size_type pos=0) const noexcept { return view().find(c, pos); } //! Find the last occurrence of a substring. auto rfind(const basic_cstring &other, size_type pos=npos) const noexcept{ return view().rfind(other.view(), pos); } auto rfind(const_pointer str, size_type pos, size_type len) const { return view().rfind(sanitize(str), pos, len); } auto rfind(const_pointer str, size_type pos=npos) const { return view().rfind(sanitize(str), pos); } auto rfind(value_type c, size_type pos=npos) const noexcept { return view().rfind(c, pos); }
{ "domain": "codereview.stackexchange", "id": 45135, "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++, strings, immutability", "url": null }
c++, strings, immutability //! Finds the first character equal to one of the given characters. auto find_first_of(const basic_cstring &other, size_type pos=0) const noexcept { return view().find_first_of(other.view(), pos); } auto find_first_of(const_pointer str, size_type pos, size_type len) const { return view().find_first_of(sanitize(str), pos, len); } auto find_first_of(const_pointer str, size_type pos=0) const { return view().find_first_of(sanitize(str), pos); } auto find_first_of(value_type c, size_type pos=0) const noexcept { return view().find_first_of(c, pos); } //! Finds the first character equal to none of the given characters. auto find_first_not_of(const basic_cstring &other, size_type pos=0) const noexcept { return view().find_first_not_of(other.view(), pos); } auto find_first_not_of(const_pointer str, size_type pos, size_type len) const { return view().find_first_not_of(sanitize(str), pos, len); } auto find_first_not_of(const_pointer str, size_type pos=0) const { return view().find_first_not_of(sanitize(str), pos); } auto find_first_not_of(value_type c, size_type pos=0) const noexcept { return view().find_first_not_of(c, pos); } //! Finds the last character equal to one of given characters. auto find_last_of(const basic_cstring &other, size_type pos=npos) const noexcept { return view().find_last_of(other.view(), pos); } auto find_last_of(const_pointer str, size_type pos, size_type len) const { return view().find_last_of(sanitize(str), pos, len); } auto find_last_of(const_pointer str, size_type pos=npos) const { return view().find_last_of(sanitize(str), pos); } auto find_last_of(value_type c, size_type pos=npos) const noexcept { return view().find_last_of(c, pos); }
{ "domain": "codereview.stackexchange", "id": 45135, "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++, strings, immutability", "url": null }
c++, strings, immutability //! Finds the last character equal to none of the given characters. auto find_last_not_of(const basic_cstring &other, size_type pos=npos) const noexcept { return view().find_last_not_of(other.view(), pos); } auto find_last_not_of(const_pointer str, size_type pos, size_type len) const { return view().find_last_not_of(sanitize(str), pos, len); } auto find_last_not_of(const_pointer str, size_type pos=npos) const { return view().find_last_not_of(sanitize(str), pos); } auto find_last_not_of(value_type c, size_type pos=npos) const noexcept { return view().find_last_not_of(c, pos); } //! Checks if the string contains the given substring. bool contains(basic_cstring_view sv) const noexcept { return (view().find(sv) != npos); } bool contains(value_type c) const noexcept { return (find(c) != npos); } bool contains(const_pointer str) const noexcept { return (find(str) != npos); } //! Left trim spaces. basic_cstring_view ltrim() const { const_pointer ptr = mStr; while (std::isspace(*ptr)) ptr++; return basic_cstring_view(ptr); } //! Right trim spaces. basic_cstring_view rtrim() const { const_pointer ptr = mStr + length() - 1; while (ptr >= mStr && std::isspace(*ptr)) ptr--; ptr++; return basic_cstring_view(mStr, static_cast<size_type>(ptr - mStr)); } //! Trim spaces. basic_cstring_view trim() const { const_pointer ptr1 = mStr; const_pointer ptr2 = mStr + length() - 1; while (std::isspace(*ptr1)) ptr1++; while (ptr2 >= ptr1 && std::isspace(*ptr2)) ptr2--; ptr2++; return basic_cstring_view(ptr1, static_cast<size_type>(ptr2 - ptr1)); } }; // namespace gto
{ "domain": "codereview.stackexchange", "id": 45135, "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++, strings, immutability", "url": null }
c++, strings, immutability }; // namespace gto //! Static variable declaration template<typename Char, typename Traits, typename Allocator> typename gto::basic_cstring<Char, Traits, Allocator>::allocator_type gto::basic_cstring<Char, Traits, Allocator>::alloc{}; //! Comparison operators (between basic_cstring) template<typename Char, typename Traits, typename Allocator> inline bool operator==(const basic_cstring<Char,Traits,Allocator> &lhs, const basic_cstring<Char,Traits,Allocator> &rhs) noexcept { return (lhs.compare(rhs) == 0); } template<typename Char, typename Traits, typename Allocator> inline bool operator!=(const basic_cstring<Char,Traits,Allocator> &lhs, const basic_cstring<Char,Traits,Allocator> &rhs) noexcept { return (lhs.compare(rhs) != 0); } template<typename Char, typename Traits, typename Allocator> inline bool operator<(const basic_cstring<Char,Traits,Allocator> &lhs, const basic_cstring<Char,Traits,Allocator> &rhs) noexcept { return (lhs.compare(rhs) < 0); } template<typename Char, typename Traits, typename Allocator> inline bool operator<=(const basic_cstring<Char,Traits,Allocator> &lhs, const basic_cstring<Char,Traits,Allocator> &rhs) noexcept { return (lhs.compare(rhs) <= 0); } template<typename Char, typename Traits, typename Allocator> inline bool operator>(const basic_cstring<Char,Traits,Allocator> &lhs, const basic_cstring<Char,Traits,Allocator> &rhs) noexcept { return (lhs.compare(rhs) > 0); } template<typename Char, typename Traits, typename Allocator> inline bool operator>=(const basic_cstring<Char,Traits,Allocator> &lhs, const basic_cstring<Char,Traits,Allocator> &rhs) noexcept { return (lhs.compare(rhs) >= 0); }
{ "domain": "codereview.stackexchange", "id": 45135, "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++, strings, immutability", "url": null }