text
stringlengths
1
2.12k
source
dict
json, rust /// Updates the _profile_ object or initializes it, if it is not present /// /// # Errors /// Returns an `[digsigctl::config::error::Error]` if the preferences file is corrupted pub fn update_or_init_profile(&mut self) -> Result<(), Error> { self.update_or_insert("profile", &[("exit_type".to_string(), "Normal".into())]) } /// Updates the _sessions_ object or initializes it, if it is not present /// /// # Errors /// Returns an `[digsigctl::config::error::Error]` if the preferences file is corrupted pub fn update_or_init_sessions(&mut self) -> Result<(), Error> { self.update_or_insert("sessions", &[("session_data_status".to_string(), 3.into())]) } fn update_or_insert(&mut self, key: &str, values: &[(String, Value)]) -> Result<(), Error> { update_or_insert( self.preferences()?, key, values .iter() .map(|(key, value)| (key.clone(), value.clone())) .collect::<Map<_, _>>(), ); Ok(()) } fn preferences(&mut self) -> Result<&mut Map<String, Value>, Error> { self.0 .as_object_mut() .ok_or(Error::NotAJsonObject("preferences")) } } fn update_or_insert(parent: &mut Map<String, Value>, key: &str, value: Map<String, Value>) { if let Some(object) = parent.get_mut(key).and_then(Value::as_object_mut) { object.extend(value); } else { parent.insert(key.to_string(), Value::Object(value)); } } This splits the Chromium configuration file handling from the passed Config object POST'ed to the webserver. Since I now also update other objects within the outer JSON object, this also allows for code deduplication, since I now have a generic update_or_insert() method and corresponding function that can both be reused.
{ "domain": "codereview.stackexchange", "id": 45015, "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": "json, rust", "url": null }
c++, multithreading Title: Print abcabc... in three threads Question: I want to implement the following case Input - integer number n Start 3 threads. The first thread prints 'a', the second prints 'b', the third prints 'c', then the first thread prints 'a' and so on Example: Input - 6, Output - "abcabc" I want to use condition variable to synchronise threads My code #include <iostream> #include <mutex> #include <condition_variable> #include <thread> void print( std::mutex& mutex, std::condition_variable& to_wait, std::condition_variable& to_notify, int count, char ch) { std::unique_lock lock(mutex); for (int i = 0; i < count; ++i) { to_wait.wait(lock); std::cout << ch; to_notify.notify_all(); } }; int main() { const int count = 10; std::condition_variable var_a; std::condition_variable var_b; std::condition_variable var_c; std::mutex mutex; auto thread_a = std::thread(&print, std::ref(mutex), std::ref(var_a), std::ref(var_b), count, 'a'); auto thread_b = std::thread(&print, std::ref(mutex), std::ref(var_b), std::ref(var_c), count, 'b'); auto thread_c = std::thread(&print, std::ref(mutex), std::ref(var_c), std::ref(var_a), count, 'c'); var_a.notify_one(); thread_a.join(); thread_b.join(); thread_c.join(); return 0; } Сould you check code for race condition and deadlocks?
{ "domain": "codereview.stackexchange", "id": 45016, "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++, multithreading", "url": null }
c++, multithreading return 0; } Сould you check code for race condition and deadlocks? Answer: This looks quite good, there are some details you have overlooked. One is that wait() can return spuriously. This means you cannot trust that the condition variable was really notified. The only safe way is to use some other variable(s) to signal whose turn it is, and check that in a loop, or to use wait() with a predicate. Another is that you have no guarantee that the threads will have started in the order you specified, or that they even will have started before the main thread executes var_a.notify_one(). Since a wait() will only wait for notifications after the waiting has started, it could thus be that the first notification is lost, and the program will not have written anything. This is solved by the same solution as mentioned above. Also, notify_all() is unnecessary in your code, you can use notify_one() instead. It doesn't really matter in your program, but just make it a habit whenever you really only need any one thread to wake up. Some alternatives to using three condition variables: Use just one condition variable, and have some variable protected by the mutex to keep track of the next thread to run. When woken up, threads check that to see if it's their turn, else they wait again. Use three mutexes, one for each thread, they all start out locked. Whenever a thread has printed its character, it unlocks the mutex of the next thread. Since C++20: use three std::barriers or std::binary_semaphores. Since C++20: use a single std::atomic<int> to keep track of whose turn it is, as from C++20 you can use wait() and notify_all() directly on atomic variables.
{ "domain": "codereview.stackexchange", "id": 45016, "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++, multithreading", "url": null }
algorithm, swift Title: Swift-function for finding missing Integers in an array of sequential Integers Question: Task description: Implement a function, which receives an array of unsorted numbers from 1 to 100. In the array zero or more numbers might be missing. The function shall return an array containing the missing numbers. Provided Test-data with expected result: var arrTest = Array(1...100) arrTest.remove(at: 25) arrTest.remove(at: 20) arrTest.remove(at: 6) print(findMissingIn(numbers: arrTest)) With these test-data your function shall return [7, 21, 26] as missing numbers. My solution: func findMissingIn(numbers: [Int]) -> [Int] { var missingNums = [Int]() for i in 1...100 { if numbers.contains(i) == false { missingNums.append(i) } } return missingNums } My function returns the expected result. So I guess it's formally correct. - Is there a better solution? - What's your opinion about my naming and coding-style in general. Would you have done it differently. How? Why? Answer: In the spirit of the Swift API Design Guidelines, in particular Prefer method and function names that make use sites form grammatical English phrases. I would call the method func missingNumbers(in numbers: [Int]) -> [Int] so that it is used as print(missingNumbers(in: arrTest)) Comparing a boolean value with true or false is unnecessary, i.e. if numbers.contains(i) == false { ... } is (in my opinion) better written as if !numbers.contains(i) { ... } Instead of an explicit loop and a temporary array we can apply filter to a range: func missingNumbers(in numbers: [Int]) -> [Int] { return (1...100).filter { !numbers.contains($0) } }
{ "domain": "codereview.stackexchange", "id": 45017, "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": "algorithm, swift", "url": null }
algorithm, swift which is concise but still easy to read. (The return keyword can be omitted if the function body consists of a single expression, that is a matter of personal taste.) If many containment test are done against the same collection of values then it can be advantageous to convert the array to a Swift Set first because Set.contains() is a \$ O(1) \$ operation. It probably makes no performance difference for 100 values, but this is what it would look like: func missingNumbers(in numbers: [Int]) -> [Int] { let set = Set(numbers) return (1...100).filter { !set.contains($0) } }
{ "domain": "codereview.stackexchange", "id": 45017, "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": "algorithm, swift", "url": null }
algorithm, reinventing-the-wheel, swift Title: Implement the Swift pow(base, exp)-function yourself Question: Task: Implement a function, which accepts two integers and results the first number raised to the power of the second number. Both numbers have to be positive. Examples: The arguments 4 and 3 shall return the result 64 The arguments 2 and 8 shall return 256 My solution (plus tests): func getPowOf(base: Int, exp: Int) -> Int { guard base > 0, exp >= 0 else { return -1 } if exp == 0 { return 1 } var result = base for _ in 1..<exp { result = (result * base) } return result } print("Result 2^0 : \(getPowOf(base: 2, exp: 0))") print("Result 2^1 : \(getPowOf(base: 2, exp: 1))") print("Result 2^2 : \(getPowOf(base: 2, exp: 2))") print("Result 2^4 : \(getPowOf(base: 2, exp: 4))") print("Result 2^10 : \(getPowOf(base: 2, exp: 10))") print("Result 3^4 : \(getPowOf(base: 3, exp: 4))") print("Result 4^3 : \(getPowOf(base: 4, exp: 3))") print("Result 5^5 : \(getPowOf(base: 5, exp: 5))") /* Result 2^0 : 1 Result 2^1 : 2 Result 2^2 : 4 Result 2^4 : 16 Result 2^10 : 1024 Result 3^4 : 81 Result 4^3 : 64 Result 5^5 : 3125 */ What's your opinion concerning my solution? Especially the argument-checks with guard and if? How would you have solved the task? What can become improved? Answer: Naming According to the Swift API Design Guidelines, abbreviations should be avoided, unless they are terms-of-art which can be easily found by a web search. Also the “get” prefix is usually not used with Swift functions. A term-of-art would be pow which is used in many programming languages. But the C math library is already imported into Swift, so defining your own pow() function can easily cause confusion. I suggest something like func power(of base: Int, exponent exp: Int) -> Int
{ "domain": "codereview.stackexchange", "id": 45018, "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": "algorithm, reinventing-the-wheel, swift", "url": null }
algorithm, reinventing-the-wheel, swift Validating the input It makes sense to require a nonnegative exponent for this integer-valued function. However, just returning -1 for invalid input is bad, as it may go unnoticed and cause errors later. Calling this function with a negative exponent is a programming error. With a precondition(exp >= 0, "exponent must be nonnegative") this can be detected early (hopefully during development) because it will cause the program to terminate. On the other hand, there is no reason to restrict the base to positive numbers. Raising zero or a negative integer to some (non-negative, integer) power is well-defined, produces an integer, and in fact already works with your existing code. Small simplifications The check for exp == 0 can be avoided if one starts with result = 1. The parentheses in result = (result * base) are not necessary, also one can use the *= operator instead. With these changes, the function would look like this: func power(of base: Int, exponent exp: Int) -> Int { precondition(exp >= 0, "exponent must be nonnegative") var result = 1 for _ in 0..<exp { result *= base } return result } A different algorithm The “exponentiation by squaring” algorithm reduces the number of multiplications from \$ e \$ to \$ \lfloor \log_2 e\rfloor \$, where \$ e \$ is the exponent. This can be faster when raising a (floating point) number to a large exponent. It does not have an advantage here because the integer arithmetic will overflow anyway for larger exponents.
{ "domain": "codereview.stackexchange", "id": 45018, "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": "algorithm, reinventing-the-wheel, swift", "url": null }
strings, complexity, palindrome Title: One Piece Treasure- Find the number of palindromic substrings in a large substring Question: I'm trying to solve the below question: A string of characters X (all in lowercase) of length n is present. We can ask a query (i,j) such that if the substring(i,j) of X is a palindromic subsequence. The query return true if the substring(i,j) of X is palindromic else returns false. Each query takes O(1) time to process. The time complexity cannot exceed n∗log(n)*log(n), i.e., we cannot ask more than n∗log(n)*log(n) queries (Assume the string is very big i.e. n is a large number) We need to determine the number of palindromic substrings in the hidden hidden string. I'm thinking of the following pseudocode: function countPalindromicSubstrings(n, query_request): count = 0 # Count palindromic substrings of odd length for center in range(n): radius = 0 while center - radius >= 0 and center + radius < n: if query_request(center - radius, center + radius): count += 1 radius += 1 else: break # Count palindromic substrings of even length for center in range(n - 1): radius = 0 while center - radius >= 0 and center + radius + 1 < n: if query_request(center - radius, center + radius + 1): count += 1 radius += 1 else: break return count I'm unable to prove this is the most optimal strategy and there doesn't exist a better strategy for getting the work done in better time complexity with Time Complexity Analysis & Correctness Argument. Answer: I think your approach is almost there. Let's suppose substring(i,j) uses half-open intervals, aka it tests [i, j). Here is how I would get O(n log n) query complexity:
{ "domain": "codereview.stackexchange", "id": 45019, "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": "strings, complexity, palindrome", "url": null }
strings, complexity, palindrome Each palindrome is of even length or odd length, as you observed. There are at most n centers of odd palindromes: 0, 1, ... , n - 1. There are at most n-1 centers of even palindromes: 0.5, 1.5, ... , n - 1.5. For simplicity, we can index by the element left of center, as you are doing: 0, 1, ... , n - 1. Each palindrome has a unique center, so we can simply compute the number of palindromes at each center and sum them up like you're doing. Suppose a palindrome of length d has radius r = ceiling(d/2) - 1. Observe that the empty string has radius -1 and that single letters have radius 0. Given a center, it takes log2(n) queries to use binary search and find its largest radius R. The key observation is noting that you can delete the leftmost / rightmost characters of a palindrome and it's still a palindrome. Thus, there are R+1 palindromes at that center. For even length palindromes, query on [center - radius, center + 2 + radius) performing binary search in radius = [0, 1, 2, ... , min(center, n - center - 2)]. For odd length palindromes, query on [center - radius, center + 1 + radius), performing binary search in radius = [0, 1, 2, ... , min(center, n - center - 1)]. If we put it all together, you get at most (2n-1) * log2(n) queries which is O(n log n). O(1) extra space is needed. Hope that helps. I'll write up some code later if I have time. EDIT: Here is an implementation that doesn't include empty strings in the count. def count_pd(n, query_request): count = 0 # odd length palindromes for center in range(n): for radius in range(1 + min(center, n - center - 1)): if query_request(center - radius, center + 1 + radius): count += 1 else: break
{ "domain": "codereview.stackexchange", "id": 45019, "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": "strings, complexity, palindrome", "url": null }
strings, complexity, palindrome # even length palindromes for center in range(n - 1): for radius in range(1 + min(center, n - center - 2)): if query_request(center - radius, center + 2 + radius): count += 1 else: break return count def fancy_pd(n, query_request): count = 0 # odd length palindromes for center in range(n): # binary search on [left, right] left = 0 # the palindrome "a" has radius 0 right = min(center, n - center - 1) while left < right: radius = (left + right + 1) // 2 if query_request(center - radius, center + 1 + radius): left = radius else: right = radius - 1 count += (left + 1) # left is now R # even length palindromes for center in range(n - 1): # binary search on [left, right] left = -1 # the palindrome "" has radius -1 right = min(center, n - center - 2) while left < right: radius = (left + right + 1) // 2 if query_request(center - radius, center + 2 + radius): left = radius else: right = radius - 1 count += (left + 1) # left is now R return count def my_query(i, j): global n_queries n_queries += 1 return target[i:j] == target[i:j][::-1] def count_vs_fancy(x): global target global n_queries target = x n_queries = 0 print("COUNT / QUERIES:", count_pd(len(x), my_query), "/", n_queries) n_queries = 0 print("FANCY / QUERIES:", fancy_pd(len(x), my_query), "/", n_queries, "\n") target = "" n_queries = 0 print("aba") count_vs_fancy("aba") print("aaaaaa") count_vs_fancy("aaaaaa") print('"".join(["a" * 2000]) + "bcb" + "".join(["a" * 2000])') count_vs_fancy("".join(["a" * 2000]) + "bcb" + "".join(["a" * 2000]))
{ "domain": "codereview.stackexchange", "id": 45019, "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": "strings, complexity, palindrome", "url": null }
strings, complexity, palindrome The tough part is avoiding off-by-one errors. Here is some output: aba COUNT / QUERIES: 4 / 6 FANCY / QUERIES: 4 / 3 aaaaaa COUNT / QUERIES: 21 / 21 FANCY / QUERIES: 21 / 14 "".join(["a" * 2000]) + "bcb" + "".join(["a" * 2000]) COUNT / QUERIES: 4004004 / 4008008 FANCY / QUERIES: 4004004 / 78305
{ "domain": "codereview.stackexchange", "id": 45019, "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": "strings, complexity, palindrome", "url": null }
java, event-handling, statistics, gui, javafx Title: A JavaFX program to find out the mouse refresh rate v2 Question: (See the continuation of this post in A JavaFX program to find out the mouse refresh rate v3.) (This post is a continuation of A JavaFX program to find out the mouse refresh rate.) After adopting the answer by @Reinderien, I ended up with this: com.github.coderodde.javafx.mouseupdaterate.MouseUpdateRateFinder.java: package com.github.coderodde.javafx.mouseupdaterate; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.input.MouseEvent; import javafx.stage.Stage; public final class MouseUpdateRateFinder extends Application { private static final int SCREEN_WIDTH = 800; private static final int SCREEN_HEIGHT = 600; public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) { Group root = new Group(); MyMouseListener listener = new MyMouseListener(); Canvas canvas = new Canvas(SCREEN_WIDTH, SCREEN_HEIGHT); // Add the event listeners: canvas.addEventHandler(MouseEvent.MOUSE_PRESSED, listener::handlePressed); canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED, listener::handleDragged); canvas.addEventHandler(MouseEvent.MOUSE_RELEASED, listener::handleReleased); root.getChildren().add(canvas); stage.setScene(new Scene(root)); stage.show(); } private static final class MyMouseListener { private long dragStartNanoseconds; private int frameCounter; public void handlePressed(MouseEvent t) { dragStartNanoseconds = System.nanoTime(); frameCounter = 0; } public void handleDragged(MouseEvent t) { frameCounter++; }
{ "domain": "codereview.stackexchange", "id": 45020, "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, event-handling, statistics, gui, javafx", "url": null }
java, event-handling, statistics, gui, javafx public void handleDragged(MouseEvent t) { frameCounter++; } public void handleReleased(MouseEvent t) { double durationInNanoseconds = System.nanoTime() - dragStartNanoseconds; double durationInSeconds = durationInNanoseconds / 1e9; String durationInSecondsString = String.format("%.2f", durationInSeconds).replace(',', '.'); String frequencyString = String.format("%.1f", frameCounter / durationInSeconds) .replace(',', '.'); System.out.printf( "%d frames in %s s, refresh rate of %s Hz.%n", frameCounter, durationInSecondsString, frequencyString); } } } Critique request Is there more room for improvement? Please tell me anything that comes to mind. Answer: LGTM. Calling .replace(',', '.') seems a curious way to address Locale concerns. Wouldn't you prefer to use the decimal format interface to obtain the desired . decimal point? Then a single format string would suffice, instead of three. Or perhaps the calling environment should be responsible for proper config, rather than this library code.
{ "domain": "codereview.stackexchange", "id": 45020, "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, event-handling, statistics, gui, javafx", "url": null }
c++, homework Title: Parsing Tokens in a Toy Interpreter Question: I'm working on a homework writing a toy interpreter. All the expressions in this language are prefix expressions. The language has a lot of lexical tokens and I wrote code as follows: Value *expression() { std::string token; cin >> token; if (token == "make") return make(); else if (token == "thing") return thing(); else if (token == "print") return print(); else if (token == "read") return read(); else if (token == "add") return new Number(*expression() + *expression()); else if (token == "sub") return new Number(*expression() - *expression()); else if (token == "mul") return new Number(*expression() * *expression()); else if (token == "div") return new Number(*expression() / *expression()); else if (token == "mod") return new Number(int(*expression()) % int(*expression())); else if (token == "true") return new Bool(true); else if (token == "false") return new Bool(false); else if (token[0] == '"') // String return new Word(token.substr(1)); else if (token[0] == ':') return thing(token.substr(1)); else // Number return new Number(std::stod(token)); } int main() { while (true) { try { auto res = expression(); } catch (const std::exception &e) { std::cerr << "Caught exception: " << e.what() << std::endl; } } return 0; }
{ "domain": "codereview.stackexchange", "id": 45021, "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++, homework", "url": null }
c++, homework But I think it's kind of ugly to have such a long (and will be longer) if-else chain, and maybe it will cost much time to compare along this chain. I don't know whether there will be some optimizations done by the compiler. I'm wondering if I have some better way to organize my code, or is this if-else chain method already good enough? The complete compilable code is: #include <exception> #include <iostream> #include <string> #include <unordered_map> using std::cin; using std::cout; using std::endl; class Value { public: virtual operator double() = 0; virtual std::string toString() = 0; }; class Number : public Value { double value; public: Number(double d) : value(d) {} operator double() { return value; } std::string toString() { return std::to_string(value); } }; class Word : public Value { std::string value; public: Word(const std::string &str) : value(str) {} Word(std::string &&str) : value(str) {} operator double() { return std::stod(value); } std::string get() { return value; } std::string toString() { return value; } }; class Bool : public Value { bool value; public: Bool(bool b) : value(b) {} Bool(const std::string &str) { if (str == "true") value = true; else if (str == "false") value = false; else throw std::invalid_argument{str + " is not a valid Bool value"}; } operator double() { throw std::invalid_argument{"Bool is not convertable to Number。"}; } std::string toString() { return value ? "true" : "false"; } }; template <typename T, typename U> T downcastOrDie(U *ptr) { auto res = dynamic_cast<T>(ptr); if (!res) throw std::invalid_argument{"dynamic cast failed"}; return res; } std::unordered_map<std::string, Value *> symbolTbl; void program(); Value *expression(); Value *make(); Value *thing(); Value *thing(const std::string &name); Value *print(); Value *read();
{ "domain": "codereview.stackexchange", "id": 45021, "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++, homework", "url": null }
c++, homework Value *expression() { std::string token; cin >> token; if (token == "make") return make(); else if (token == "thing") return thing(); else if (token == "print") return print(); else if (token == "read") return read(); else if (token == "add") return new Number(*expression() + *expression()); else if (token == "sub") return new Number(*expression() - *expression()); else if (token == "mul") return new Number(*expression() * *expression()); else if (token == "div") return new Number(*expression() / *expression()); else if (token == "mod") return new Number(int(*expression()) % int(*expression())); else if (token == "true") return new Bool(true); else if (token == "false") return new Bool(false); else if (token[0] == '"') // String return new Word(token.substr(1)); else if (token[0] == ':') return thing(token.substr(1)); else // Number return new Number(std::stod(token)); } Value *make() { auto name = expression(); auto value = expression(); symbolTbl[downcastOrDie<Word *>(name)->get()] = value; return value; } Value *thing() { return thing(downcastOrDie<Word *>(expression())->get()); } Value *thing(const std::string &name) { return symbolTbl[name]; } Value *print() { auto val = expression(); cout << val->toString() << endl; return val; } bool isDouble(const std::string &str) { bool hasDecimalPoint = false; if (str.length() == 0) return false; auto it = str.begin(); if (*it == '-') ++it; for (; it != str.end(); ++it) { if (*it == '.') { if (hasDecimalPoint) return false; else hasDecimalPoint = true; } else if (!std::isdigit(*it)) return false; } return true; } Value *read() { std::string input; cin >> input;
{ "domain": "codereview.stackexchange", "id": 45021, "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++, homework", "url": null }
c++, homework Value *read() { std::string input; cin >> input; if (isDouble(input)) { return new Number(std::stod(input)); } else { return new Word(input); } } int main() { while (true) { try { auto res = expression(); } catch (const std::exception &e) { std::cerr << "Caught exception: " << e.what() << std::endl; } } return 0; } Answer: Use a look-up table As already mentioned by Cris Luengo in the comments, you can avoid the long if-else sequence by using a look-up table. You want to map tokens to functions that will do the processing related to that token. It can look like: using action_type = std::function<Value*(std::string_view)>; static std::unordered_map<std::string, action_type> actions = { {"make", [](auto){ return make(); }}, {"thing", [](auto){ return thing(); }}, … {"add", [](auto){ return new Number(*expression() + *expression()); }}, … {":", [](auto token){ return thing(token.substr(1)); }}, }; And then expression() can be simplified to: Value *expression() { std::string token; cin >> token; if (auto action = actions.find(token); action != actions.end()) { return action(token); } else /* Number */ { return new Number(std::stod(token)); } } It will be faster too, since a std::unordered_map() uses a hash table to look up the token in \$O(1)\$ time, whereas your code has to check the token against all possible values. Avoid manual memory management Avoid calling new and delete manually in your code. It's easy to forget to call delete and to introduce a memory leak that way. For example, in just this piece of code: *expression() + *expression() You leaked two memory allocations. Instead, use std::unique_ptr<> to store your pointers in; it will automatically delete the storage when the pointer is going out of scope: std::unique_ptr<Value> make();
{ "domain": "codereview.stackexchange", "id": 45021, "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++, homework", "url": null }
c++, homework using action_type = std::function<std::unique_ptr<Value>(std::string_view)>; static std::unordered_map<std::string, action_type> actions = { {"make", [](auto){ return make(); }}, … {"add", [](auto){ return std::make_unique<Number>(*expression() + *expression()); }}, … }; std::unique_ptr<Value> expression() { … return action(token); … } Now the memory leak in the addition expression is gone. Consider using std::variant to store values You are using inheritance to be able to pass around Values of different types. This is fine, but one drawback is that you have to allocate each Value in some way, because you can only pass it around using pointers. That can result in your code making lots of memory allocations. A different way to do this is to use std::variant, which will allow you to pass Values by value (no pun intended). The code would look like: class Number /* no inheritance */ { double value; public: /* same members as before */ … }; … using Value = std::variant<Number, Word, Bool>; Value make(); using action_type = std::function<Value(std::string_view)>; static std::unordered_map<std::string, action_type> actions = { {"make", [](auto){ return make(); }}, … {"add", [](auto){ return expression() + expression(); }}, … } Value expression() { … return action(token); … } Notice how convenient it is to no longer have to deal with Values being passed around as pointer! Of course, now you still have to deal with how to add two Values together. But how does addition work now? If you could only add Numbers together, it could look like this: Value operator+(const Value& lhs_value, const Value& rhs_value) { double lhs = std::get<Number>(lhs_value); double rhs = std::get<Number>(rhs_value); return Number(lhs + rhs); }
{ "domain": "codereview.stackexchange", "id": 45021, "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++, homework", "url": null }
c++, homework Note that std::get<Number>(lhs_value) will throw an exception if lhs was a Word or a Bool. Alternatively, you can use std::visit(): Value operator+(const Value& lhs_value, const Value& rhs_value) { return std::visit([](auto& lhs, auto& rhs) { return lhs + rhs; }, lhs_value, rhs_value); } This basically unpacks the Values, so the lambda is called with the concrete types (Number, Word and/or Bool). It then relies on operator+() existing for those types. Be careful with string to double conversion All the standard library functions that deal with conversion from strings to numbers, like std::stod(), will ignore any non-number characters that occur after the number. So std::stod("123four") will return 123, and will not throw an exception. Consider using std::from_chars() instead, as it reports how far it read, and then check that it read the whole string. I/O can fail at any time Be aware that any input/output operations can fail at any time, even std::cin and std::cout: maybe the user closed the terminal, or pressed ctrl-D (on UNIX). If you don't handle this, your program will go into an infinite loop reading empty strings. In read() for example, I recommend you add: if (!std::cin.good()) { throw std::runtime_error("Error reading input"); } And of course, in main() you should know when exceptions are fatal, and break out of the while(true) loop when it is.
{ "domain": "codereview.stackexchange", "id": 45021, "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++, homework", "url": null }
c, curl Title: Download stock data from YFinance Question: As a project to get more familiar with curl, I decided to write a program that downloads stock data from Yahoo Finance, and does arbitrary analysis on that data. I would like to receive any critiques about the way I went about this, especially setting up the curl "environment", along with any other C standards I might have missed. downloader.h /** * Data Downloader Implementation. * * @author Ben Antonellis */ #include <curl/curl.h> #include <curl/easy.h> #include <string.h> #include <stdio.h> #include <time.h> #define DOWNLOAD_PATH "/tmp/stock_data.txt" int DateToUnix(char* date) { struct tm tm; time_t epoch; if (strptime(date, "%Y-%m-%d", &tm) != NULL) { epoch = mktime(&tm); } return epoch; } int FormatQueryString(char* result, char* ticker, char* start_time, char* end_time, char* interval) { char* res; time_t from = DateToUnix(start_time); time_t to = DateToUnix(end_time); if (0 > asprintf( &res, "https://query1.finance.yahoo.com/v7/finance/download/%s?period1=%ld&period2=%ld&interval=%s&events=history", ticker, from, to, interval)) return 1; strcpy(result, res); return 0; } size_t WriteData(void* ptr, size_t size, size_t n, FILE* stream) { size_t written = fwrite(ptr, size, n, stream); return written; } void DownloadData(char* url) { CURL* curl; FILE* file; CURLcode result; curl = curl_easy_init(); if (!curl) { printf("Error in DownloadData.\n"); exit(1); } file = fopen(DOWNLOAD_PATH, "wb"); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteData); curl_easy_setopt(curl, CURLOPT_WRITEDATA, file); result = curl_easy_perform(curl); //fprintf(file, "\n"); curl_easy_cleanup(curl); fclose(file); }
{ "domain": "codereview.stackexchange", "id": 45022, "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, curl", "url": null }
c, curl } program.c /** * This project downloads stock data from Yahoo Finance. * * @author Ben Antonellis */ #include <stdio.h> #include <stdlib.h> #include "downloader.h" int main(int argc, char** argv) { char* result = (char*)malloc(256); if (FormatQueryString(result, "SPY", "2020-09-01", "2020-10-01", "1mo") > 0) { printf("Error in FormatQueryString\n"); exit(1); } DownloadData(result); DateToUnix("2020-09-01"); return 0; } A specific question I have is about the malloc statement. I use 256 because that seems to be enough to fit the query string, but I'm not sure about the ramifications about allocating too much space for the query, or perhaps not enough. Answer: Enable all compiler warnings This saves you and others time. warning: implicit declaration of function 'strptime'; did you mean 'strftime'? [-Wimplicit-function-declaration] warning: comparison between pointer and integer warning: conversion from 'time_t' {aka 'long int'} to 'int' may change value [-Wconversion] warning: implicit declaration of function 'asprintf'; did you mean 'sprintf'? [-Wimplicit-function-declaration] warning: implicit declaration of function 'exit' [-Wimplicit-function-declaration] note: include '<stdlib.h>' or provide a declaration of 'exit' warning: incompatible implicit declaration of built-in function 'exit' [-Wbuiltin-declaration-mismatch] warning: variable 'result' set but not used [-Wunused-but-set-variable] Check all logic paths Indefinite value returned when strptime(...) == NULL time_t epoch; // Consider initializing here if (strptime(date, "%Y-%m-%d", &tm) != NULL) { epoch = mktime(&tm); } return epoch;
{ "domain": "codereview.stackexchange", "id": 45022, "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, curl", "url": null }
c, curl Avoid naked magic numbers Why 256 in char* result = (char*)malloc(256);? How does the following code know that is sufficient? Instead, pass the size into and have that code error if the size is insufficient. // FormatQueryString(result, "SPY",.... if (FormatQueryString(256, result, "SPY",...)) { Handle_Error(); } Cast not needed // char* result = (char*)malloc(256); char* result = malloc(256); Robust code also look for errors. if (result == NULL) { TBD_Code(); } Look for I/O failures Add tests. file = fopen(DOWNLOAD_PATH, "wb"); if (file == NULL) { // add TBD_Code(); } Remove dead code //fprintf(file, "\n"); deserves to be deleted as part of a code review. String deserves abstraction Rather than embed such a string directly in code, use a macro or object. "https://query1.finance.yahoo.com/v7/finance/download/%s?period1=%ld&period2=%ld&interval=%s&events=history" Check for curl errors curl_easy_setopt returns a value. Check it.
{ "domain": "codereview.stackexchange", "id": 45022, "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, curl", "url": null }
c++, c++17 Title: std::chrono compatible clock using CLOCK_MONOTONIC_RAW Question: We're using std::chrono::steady_clock for most of our internal queues and relative timings. However, we're on a POSIX platform and steady_clock is implemented by using clock_gettime(CLOCK_MONOTONIC, .... The CLOCK_MONOTONIC clock is not affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the clock), but is affected by the incremental adjustments performed by adjtime(3) and NTP. This clock does not count time that the system is suspended. All CLOCK_MONOTONIC variants guarantee that the time returned by consecutive calls will not go backwards, but successive calls may—depending on the architecture—return identical (not-increased) time values. Since steady_clock is affected by certain clock adjustments, in some parts of our codebase clock_gettime(CLOCK_MONOTONIC_RAW, ... is therefore used directly instead, which is ... Similar to CLOCK_MONOTONIC, but provides access to a raw hardware-based time that is not subject to NTP adjustments or the incremental adjustments performed by adjtime(3). This clock does not count time that the system is suspended. I'd like to encapsulate it in a class that could work as a replacement for steady_clock and came up with the below which is inspired by the gcc steady_clock implementation. I wonder if this is all there is to it or if I'm missing anything to make it fulfill the TrivialClock requirements? #pragma once // or a classic portable header guard #include <chrono> #include <ctime> namespace foo { struct monotonic_raw_clock { using duration = std::chrono::nanoseconds; using rep = duration::rep; using period = duration::period; using time_point = std::chrono::time_point<monotonic_raw_clock, duration>; static constexpr bool is_steady = true;
{ "domain": "codereview.stackexchange", "id": 45023, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17", "url": null }
c++, c++17 static constexpr bool is_steady = true; static inline time_point now() noexcept { std::timespec tp; // The return value from clock_gettime is ignored in the gcc steady_clock // implementation too: static_cast<void>(clock_gettime(CLOCK_MONOTONIC_RAW, &tp)); return time_point(duration(std::chrono::seconds(tp.tv_sec) + std::chrono::nanoseconds(tp.tv_nsec))); } }; } // namespace foo Answer: The implementation looks correct to me. I do want to address some potential misunderstanding though: Since steady_clock is affected by certain clock adjustments, […] It sounds scary, but it's actually much more benign, and might even be desirable. The steady clock is certainly not "jumping". What happens is that you have the computer's internal crystal oscillator that is typically not of great quality, and is speeding up and down all the time because of temperature and voltage fluctuations. Its average speed might even be several percentage points slower or faster than wall clock time. Your computer corrects for that by checking it regularly against NTP time, and then compensating for the speed difference. So the adjustments done are very gradual, and in the end you have a clock which is much more steady and correct than CLOCK_MONOTIC_RAW is. The only advantage of CLOCK_MONONOTIC_RAW might have over CLOCK_MONOTONIC is that it could be faster (but on Linux it likely has the same performance). So I recommend that you use it only if you call now() very often and need it to be as fast as possible, and don't care about the accuracy and precision of the clock.
{ "domain": "codereview.stackexchange", "id": 45023, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++17", "url": null }
java, api, rest, spring Title: Toy Robot coding puzzle with Java Question: The following code is my solution to a code challenge I submitted a few days ago. I got rejected straight away with no feedback and I've wondered why. Here is the full code repo. Requirements The application is a simulation of a toy robot moving on a square tabletop, of dimensions 5 x 5 units. There are no other obstructions on the table surface. The robot is free to roam around the surface of the table, but must be prevented from falling to destruction. Any movement that would result in the robot falling from the table must be prevented, however further valid movement commands must still be allowed. Create an application that can read in commands of the following form: PLACE X,Y,F MOVE LEFT RIGHT REPORT PLACE will put the toy robot on the table in position X,Y and facing NORTH, SOUTH, EAST or WEST. The origin (0,0) can be considered to be the SOUTH WEST most corner. MOVE will move the toy robot one unit forward in the direction it is currently facing. LEFT and RIGHT will rotate the robot 90 degrees in the specified direction without changing the position of the robot. REPORT will announce the X,Y and F of the robot. Constraints: The application must be a Spring-Boot-Application Input must be realised over the REST-API, take care when designing the REST-API The robot that is not on the table can choose the ignore the MOVE, LEFT, RIGHT and REPORT commands. The robot must not fall off the table during movement. This also includes the initial placement of the toy robot. Any move that would cause the robot to fall must be ignored. It is not required to provide any graphical output showing the movement of the toy robot. Plain input Examples: PLACE 0,0,NORTH MOVE REPORT Output: 0,1,NORTH PLACE 0,0,NORTH LEFT REPORT Output: 0,0,WEST PLACE 1,2,EAST MOVE MOVE LEFT MOVE REPORT Output: 3,3,NORTH MOVE REPORT Output: ROBOT MISSING Solution ToyRobotApplication.java package com.puzzle.toyrobot;
{ "domain": "codereview.stackexchange", "id": 45024, "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, api, rest, spring", "url": null }
java, api, rest, spring Solution ToyRobotApplication.java package com.puzzle.toyrobot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ToyRobotApplication { public static void main(String[] args) { SpringApplication.run(ToyRobotApplication.class, args); } } RobotSimulationController.java package com.puzzle.toyrobot.controller; import com.puzzle.toyrobot.model.Report; import com.puzzle.toyrobot.model.SimulationRound; import com.puzzle.toyrobot.service.RobotSimulationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class RobotSimulationController { private RobotSimulationService simulationService; @Autowired public RobotSimulationController(RobotSimulationService simulationService) { this.simulationService = simulationService; } @PostMapping @RequestMapping("/robot/simulation") public ResponseEntity<Report> newSimulationRound(@RequestBody SimulationRound simulationRound) { Report report = simulationService.start(simulationRound); return ResponseEntity.ok(report); } } RobotSimulationService.java package com.puzzle.toyrobot.service; import com.puzzle.toyrobot.model.Report; import com.puzzle.toyrobot.model.Robot; import com.puzzle.toyrobot.model.SimulationRound; import com.puzzle.toyrobot.model.command.Command; import com.puzzle.toyrobot.model.command.CommandFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @Service public class RobotSimulationService {
{ "domain": "codereview.stackexchange", "id": 45024, "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, api, rest, spring", "url": null }
java, api, rest, spring @Service public class RobotSimulationService { private final Logger log = LoggerFactory.getLogger(RobotSimulationService.class); public Report start(SimulationRound simulationRound) { Robot robot = new Robot(); Report report = new Report(); for (String commandString : simulationRound.getCommands()) { Command command = CommandFactory.getCommand(commandString); if (command != null) { command.execute(robot, report); } else { log.debug("Wrong command: " + commandString); } } return report; } } SimulationRound.java package com.puzzle.toyrobot.model; import java.util.ArrayList; import java.util.List; public class SimulationRound { private List<String> commands = new ArrayList<>(); public List<String> getCommands() { return commands; } public void setCommands(List<String> commands) { this.commands = commands; } public void addCommand(String command) { commands.add(command); } } Robot.java package com.puzzle.toyrobot.model; public class Robot { public static final Integer MAX_POSITION = 4; public static final Integer MIN_POSITION = 0; private Integer xPosition; private Integer yPosition; private CardinalDirection cardinalDirection; public Robot() { } public Robot(Integer xPosition, Integer yPosition, CardinalDirection cardinalDirection) { this.xPosition = xPosition; this.yPosition = yPosition; this.cardinalDirection = cardinalDirection; } public Integer getXPosition() { return xPosition; } public void setXPosition(Integer xPosition) { this.xPosition = xPosition; } public Integer getYPosition() { return yPosition; } public void setYPosition(Integer yPosition) { this.yPosition = yPosition; }
{ "domain": "codereview.stackexchange", "id": 45024, "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, api, rest, spring", "url": null }
java, api, rest, spring public void setYPosition(Integer yPosition) { this.yPosition = yPosition; } public CardinalDirection getCardinalDirection() { return cardinalDirection; } public void setCardinalDirection(CardinalDirection cardinalDirection) { this.cardinalDirection = cardinalDirection; } public boolean isOnTable() { return xPosition != null && yPosition != null && cardinalDirection != null; } public String getCurrentStatus() { return String.join(",", xPosition.toString(), yPosition.toString(), cardinalDirection.toString()); } public void increaseYPosition() { yPosition++; } public void decreaseYPosition() { yPosition--; } public void increaseXPosition() { xPosition++; } public void decreaseXPosition() { yPosition++; } } Report.java package com.puzzle.toyrobot.model; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class Report { private List<String> output = new ArrayList<>(); public List<String> getOutput() { return output; } public void setOutput(List<String> output) { this.output = output; } public void addOutput(String outupt) { this.output.add(outupt); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Report report = (Report) o; return Objects.equals(output, report.output); } @Override public int hashCode() { return Objects.hash(output); } } CardinalDirection.java package com.puzzle.toyrobot.model; public enum CardinalDirection { EAST, WEST, SOUTH, NORTH } Command.java package com.puzzle.toyrobot.model.command; import com.puzzle.toyrobot.model.Report; import com.puzzle.toyrobot.model.Robot; public abstract class Command {
{ "domain": "codereview.stackexchange", "id": 45024, "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, api, rest, spring", "url": null }
java, api, rest, spring public abstract class Command { public abstract void execute(Robot robot, Report report); } CommandFactory.java package com.puzzle.toyrobot.model.command; public class CommandFactory { private static final String PLACE_COMMAND_REGEX = "^(PLACE)\\s\\d+,\\d+,(NORTH|WEST|EAST|SOUTH)$"; public static Command getCommand(String commandString) { if (commandString.matches(PLACE_COMMAND_REGEX)) { return new PlaceCommand(commandString); } else if (commandString.equals(CommandType.LEFT.name())) { return new LeftCommand(); } else if (commandString.equals(CommandType.RIGHT.name())) { return new RightCommand(); } else if (commandString.equals(CommandType.REPORT.name())) { return new ReportCommand(); } else if (commandString.equals(CommandType.MOVE.name())) { return new MoveCommand(); } return null; } } CommandType,java package com.puzzle.toyrobot.model.command; public enum CommandType { PLACE, MOVE, LEFT, RIGHT, REPORT } LeftCommand.java package com.puzzle.toyrobot.model.command; import com.puzzle.toyrobot.model.CardinalDirection; import com.puzzle.toyrobot.model.Report; import com.puzzle.toyrobot.model.Robot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LeftCommand extends Command { private final Logger log = LoggerFactory.getLogger(LeftCommand.class); public void execute(Robot robot, Report report) {
{ "domain": "codereview.stackexchange", "id": 45024, "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, api, rest, spring", "url": null }
java, api, rest, spring public void execute(Robot robot, Report report) { if (!robot.isOnTable()) { log.debug("Left command ignored"); } else { switch (robot.getCardinalDirection()) { case NORTH: robot.setCardinalDirection(CardinalDirection.WEST); break; case SOUTH: robot.setCardinalDirection(CardinalDirection.EAST); break; case EAST: robot.setCardinalDirection(CardinalDirection.NORTH); break; case WEST: robot.setCardinalDirection(CardinalDirection.SOUTH); break; } log.debug("The robot is rotating 90 degree to " + robot.getCardinalDirection()); } } } MoveCommand.java package com.puzzle.toyrobot.model.command; import com.puzzle.toyrobot.model.Report; import com.puzzle.toyrobot.model.Robot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MoveCommand extends Command { private final Logger log = LoggerFactory.getLogger(MoveCommand.class); @Override public void execute(Robot robot, Report report) { if (!robot.isOnTable()) { log.debug("Move command ignored"); } else { switch (robot.getCardinalDirection()) { case NORTH: if (robot.getYPosition() < Robot.MAX_POSITION) { robot.increaseYPosition(); log.debug("The robot is moving"); } else { log.debug("Move command ignored"); } break;
{ "domain": "codereview.stackexchange", "id": 45024, "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, api, rest, spring", "url": null }
java, api, rest, spring case SOUTH: if (robot.getYPosition() > Robot.MIN_POSITION) { robot.decreaseYPosition(); log.debug("The robot is moving"); } else { log.debug("Move command ignored"); } break; case EAST: if (robot.getXPosition() < Robot.MAX_POSITION) { robot.increaseXPosition(); log.debug("The robot is moving"); } else { log.debug("Move command ignored"); } break; case WEST: if (robot.getXPosition() > Robot.MIN_POSITION) { robot.decreaseXPosition(); log.debug("The robot is moving"); } else { log.debug("Move command ignored"); } break; } } } } PlaceCommand.java package com.puzzle.toyrobot.model.command; import com.puzzle.toyrobot.model.CardinalDirection; import com.puzzle.toyrobot.model.Report; import com.puzzle.toyrobot.model.Robot; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PlaceCommand extends Command { private final Logger log = LoggerFactory.getLogger(PlaceCommand.class); private String commandString; PlaceCommand(String commandString) { this.commandString = commandString; } @Override public void execute(Robot robot, Report report) { String placementArgs = StringUtils.substringAfter(commandString, CommandType.PLACE.name()); String[] args = StringUtils.split(placementArgs, ","); Integer initialX = Integer.parseInt(args[0].trim()); Integer initialY = Integer.parseInt(args[1].trim());
{ "domain": "codereview.stackexchange", "id": 45024, "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, api, rest, spring", "url": null }
java, api, rest, spring if (initialX <= Robot.MAX_POSITION && initialX >= Robot.MIN_POSITION && initialY <= Robot.MAX_POSITION && initialY >= Robot.MIN_POSITION) { robot.setXPosition(initialX); robot.setYPosition(initialY); robot.setCardinalDirection(CardinalDirection.valueOf(args[2].trim())); log.debug("Robot is placed at " + robot.getCurrentStatus()); } else { log.debug("Place command ignored"); } } } ReportCommand.java package com.puzzle.toyrobot.model.command; import com.puzzle.toyrobot.model.Report; import com.puzzle.toyrobot.model.Robot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ReportCommand extends Command { private final Logger log = LoggerFactory.getLogger(ReportCommand.class); @Override public void execute(Robot robot, Report report) { if (!robot.isOnTable()) { log.debug("Missing Robot"); report.addOutput("ROBOT MISSING"); } else { report.addOutput(robot.getCurrentStatus()); } } } RightCommand.java package com.puzzle.toyrobot.model.command; import com.puzzle.toyrobot.model.CardinalDirection; import com.puzzle.toyrobot.model.Report; import com.puzzle.toyrobot.model.Robot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RightCommand extends Command { private final Logger log = LoggerFactory.getLogger(RightCommand.class);
{ "domain": "codereview.stackexchange", "id": 45024, "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, api, rest, spring", "url": null }
java, api, rest, spring @Override public void execute(Robot robot, Report report) { if (!robot.isOnTable()) { log.debug("Right command ignored"); } else { switch (robot.getCardinalDirection()) { case NORTH: robot.setCardinalDirection(CardinalDirection.EAST); break; case SOUTH: robot.setCardinalDirection(CardinalDirection.WEST); break; case EAST: robot.setCardinalDirection(CardinalDirection.SOUTH); break; case WEST: robot.setCardinalDirection(CardinalDirection.NORTH); break; } log.debug("The robot is rotating 90 degree to " + robot.getCardinalDirection()); } } } pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.puzzle</groupId> <artifactId>toy-robot</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>toy-robot</name> <description>Toy Robot coding puzzle</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties>
{ "domain": "codereview.stackexchange", "id": 45024, "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, api, rest, spring", "url": null }
java, api, rest, spring <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.7</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> and Finally a controller test package com.puzzle.toyrobot.controller; import com.puzzle.toyrobot.model.Report; import com.puzzle.toyrobot.model.SimulationRound; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class RobotSimulationControllerTest { @Autowired private TestRestTemplate template; @Test public void simulationReportAsExpectedTest() { Report report = new Report(); report.addOutput("0,1,NORTH");
{ "domain": "codereview.stackexchange", "id": 45024, "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, api, rest, spring", "url": null }
java, api, rest, spring Report report = new Report(); report.addOutput("0,1,NORTH"); SimulationRound round = new SimulationRound(); round.addCommand("PLACE 0,0,NORTH"); round.addCommand("LEFT"); round.addCommand("RIGHT"); round.addCommand("MOVE"); round.addCommand("REPORT"); HttpEntity<Object> simulationRound = getHttpEntity(round); ResponseEntity<Report> resultAsset = template.postForEntity("/robot/simulation", simulationRound, Report.class); Assert.assertEquals(resultAsset.getBody(), report); } @Test public void missingRobotTest() { Report report = new Report(); report.addOutput("ROBOT MISSING"); SimulationRound round = new SimulationRound(); round.addCommand("MOVE"); round.addCommand("REPORT"); HttpEntity<Object> simulationRound = getHttpEntity(round); ResponseEntity<Report> resultAsset = template.postForEntity("/robot/simulation", simulationRound, Report.class); Assert.assertEquals(resultAsset.getBody(), report); } @Test public void ignoringWrongCommandTest() { Report report = new Report(); report.addOutput("0,0,WEST"); SimulationRound round = new SimulationRound(); round.addCommand("PLACE 0,0,WEST"); round.addCommand("MOVEEEE"); round.addCommand("REPORT"); HttpEntity<Object> simulationRound = getHttpEntity(round); ResponseEntity<Report> resultAsset = template.postForEntity("/robot/simulation", simulationRound, Report.class); Assert.assertEquals(resultAsset.getBody(), report); } @Test public void ignoringCommandThatCausesFailTest() { Report report = new Report(); report.addOutput("0,0,SOUTH"); SimulationRound round = new SimulationRound(); round.addCommand("PLACE 0,0,SOUTH"); round.addCommand("MOVE"); round.addCommand("REPORT");
{ "domain": "codereview.stackexchange", "id": 45024, "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, api, rest, spring", "url": null }
java, api, rest, spring HttpEntity<Object> simulationRound = getHttpEntity(round); ResponseEntity<Report> resultAsset = template.postForEntity("/robot/simulation", simulationRound, Report.class); Assert.assertEquals(resultAsset.getBody(), report); } @Test public void simulationRoundWithoutReportTest() { Report report = new Report(); SimulationRound round = new SimulationRound(); round.addCommand("PLACE 1,2,EAST"); round.addCommand("MOVE"); round.addCommand("MOVE"); round.addCommand("LEFT"); HttpEntity<Object> simulationRound = getHttpEntity(round); ResponseEntity<Report> resultAsset = template.postForEntity("/robot/simulation", simulationRound, Report.class); Assert.assertEquals(resultAsset.getBody(), report); } private HttpEntity<Object> getHttpEntity(Object body) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return new HttpEntity<>(body, headers); } } Notes on solution: All commands will be ignored until a valid PLACE command. The robot can be re-PLACEd at any time. Any number of REPORT commands are allowed. The REST-API request body is a Simulation Round object that contains a list of commands. The REST-API response object is a Report object that contains a list of reports, which is the output of the REPORT command if any. Many Integration tests are added.
{ "domain": "codereview.stackexchange", "id": 45024, "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, api, rest, spring", "url": null }
java, api, rest, spring Answer: I didn't examine all the classes. Here is my (partial) analysis: REST API Your API consists of one call. This is clearly not what was intended by the question (they did state that they regard the design of the API as important...) First thing when designing a REST API is to decide what is(are) the entities that are represented by the API, and then decide what are the actions that can be done on these entities. Although your API is superficially desgined around a "Simulation Round" entity, in essence it is designed to take and do commands. This is more inline with a design of RPC (remote proc call) API. It also returns OK status code no matter what's the input. The entity should be the Robot. Placing the Robot is analog to creating a new entity. Moving and rotating the robot is updating its state and reporting is, naturally GETting its state . So POST /robot should accept X,Y,F as body and return a unique Robot-id PUT /robot/{id} should accept move and rotation commands and return either OK or 404 Not Found or some error indicating the command was ignored (perhaps 409 Conflict) GET /robot/{id} should return the state of the Robot (or 404) DELETE /robot/{id} will delete the specified Robot (or 404) All non GET calls should return 400 (bad request) for invalid input. I mean input that cannot be parsed at all ... and just like that, you designed a service that supports multiple robots... ENUM You should harness the power of arguments to enum to eliminate need for switch statements:
{ "domain": "codereview.stackexchange", "id": 45024, "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, api, rest, spring", "url": null }
java, api, rest, spring CommandType.java I would add an instance of Command as argument. This saves the switch statement in the command factory CardinalDirection.java I would add the result CardinalDirection of right and left rotation as parameters to the enum. This saves the switch statements in the commands. Better still, why not order the enum values by right rotation: NORTH, EAST, SOUTH, WEST and then you use the enum's ordinal() value to determine the result of right (+1) and left (-1) rotations (with wrapping of course)
{ "domain": "codereview.stackexchange", "id": 45024, "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, api, rest, spring", "url": null }
python, python-3.x, object-oriented Title: Metaclass Wrapping Builtin to Enforce Subclass Type Question: This metaclass utility is written to make subclassing builtins easier, such as int, str, and most importantly, complex. All dependencies are part of the standard library. I'm concerned with 1. readability, and 2. possible performance implications of wrapping every single inherited method of the created classes. The option enforce_all=True complicates this further by creating an intermediate class, which is then wrapped, for the reason of making calls to super() return the correct (subclass) type. This option simplifies development down the line. I've tried my best to implement best practices such as formatting, docstrings, testing, etc. I am aware that there are several unused imports. Metaclass #!/usr/bin/env python from types import MemberDescriptorType, WrapperDescriptorType # Test for inherited funcs # [getattr(complex, a) == getattr(super(complex), a, None) for a,o in complex.__dict__.items()] default_exclude = {"__new__", "__getattribute__", "__getattr__", "__setatt__"} class TypeEnforcerMetaclass(type): """ Black magic return type wrapper. Ensures that methods inhereted return proper class (that of the inheritee) :param enforce_all: Enforces return type of super() through Blacker magic. :type enforce_all: ``bool`` :param exclude: Ignores types :type enforce_all: ``bool`` Example:: >>> class A(int, metaclass=TypeEnforcerMetaclass, enforce_all=True, exclude={"real"}): ... def __repr__(self): ... return f"A({super().real})" >>> A(1) A(1) >>> A(1) + A(4) A(5) >>> A(3) * A(-3) A(-9) >>> super(A) <super: <class 'A'>, NULL> >>> type(A) <class '__main__.TypeEnforcerMetaclass'> """
{ "domain": "codereview.stackexchange", "id": 45025, "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, object-oriented", "url": null }
python, python-3.x, object-oriented def __new__(meta, name, bases, classdict, enforce_all=False, exclude=default_exclude): exclude = exclude.union(default_exclude) # Creates a new abstraction layer, so super() returns wrapped class # that has all its methods wrapped. # ┌────────────┐ ┌────────────┐ ┌────────────┐ # │ Point │⇦│ _compl │⇦│ complex │ # └────────────┘ └────────────┘ └────────────┘ superclass = bases[0] if enforce_all: # Somehow, name mangling doesn't show up on the class. Probably # __repr__ isn't being overriden inter_name = meta.__name__ + "." + superclass.__name__ inter_dict = dict(superclass.__dict__) inter_class = super(TypeEnforcerMetaclass, meta).__new__(meta, inter_name, bases, inter_dict) bases = (inter_class, *bases) # Neat trick for tuples subclass = super(TypeEnforcerMetaclass, meta).__new__(meta, name, bases, classdict) # print("new bases", bases) # print("sub:", subclass, "meta:", type(subclass)) # print("inter:", inter_class, "meta:", type(inter_class)) # # print(cls, cls.__name__, cls.mro(), cls.__dict__, sep="\n") # # print(cls, "inherets from", cls.mro()[1]) base_to_wrap = subclass.mro()[1] type_compare = subclass type_to_convert = subclass if enforce_all: type_compare = inter_class base_to_wrap = inter_class.mro()[1]
{ "domain": "codereview.stackexchange", "id": 45025, "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, object-oriented", "url": null }
python, python-3.x, object-oriented for attr, obj in base_to_wrap.__dict__.items(): if isinstance(obj, MemberDescriptorType): continue # Traverse the mro # == testing is exactly what we want for comparing overridden # definitions, if obj == getattr(type_compare, attr, None) and attr not in exclude: # Dont override __new__! # Check if the method is inhereted from base_to_wrap # Iff inherited, wrap the return type setattr( type_compare, attr, TypeEnforcerMetaclass.return_wrapper( superclass, type_to_convert, obj)) return subclass def return_wrapper(cls, convert_cls, func): """Wraps class methods and enforces type""" # print(cls, func.__name__) def convert_if(val): if isinstance(val, cls): # print("Converting", val) # print("Class:", type(val)) return convert_cls(val) else: # print("Not Converting", val) # print("Class:", val.__class__) # print("Required class", cls.__class__) return val def wrapper(*args, **kwargs): # print("Wrapper around", func) return convert_if(func(*args, **kwargs)) wrapper.__wrapped__ = func return wrapper if __name__ == "__main__": import doctest doctest.testmod() Demo code (what it makes possible) #!/usr/bin/env python from .._utils._return_wrapper import TypeEnforcerMetaclass, no_override from typing import ClassVar, Union from math import sin, cos, tan
{ "domain": "codereview.stackexchange", "id": 45025, "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, object-oriented", "url": null }
python, python-3.x, object-oriented Point = ClassVar["Point"] class Point(complex, metaclass=TypeEnforcerMetaclass, enforce_all=True): r""" :param x: x coordinate of the point :type x: ``int``, ``float`` :param y: y coordinate of the point. Stored as the imaginary component :type y: ``int``, ``float`` :: .. highlight:: python >>> a = Point(2, 3) >>> b = Point(-3, 5) >>> a Point(2.0, 3.0) >>> a + b Point(-1.0, 8.0) >>> a.midpoint(b) Point(-0.5, 4.0) >>> a * b Point(-6.0, 15.0) """ ORIGIN = 0 # Works because complex assumes 0 == 0+0j # def __new__(cls,*args, **kwargs): # if len(args) == 1: # if isinstance(args[0], complex): # return super(object, cls).__new__(args[0]) # else: # return super().__new__(*args, **kwargs) def __new__(cls, *args, **kwargs): if len(args) == 1 and isinstance(args[0], complex): return super().__new__(cls, args[0].real, args[0].imag, *args[1:], **kwargs) else: return super().__new__(cls, *args, **kwargs) def __init__(self, x, y:float=0): # self.real = x # self.imag = y pass def __repr__(self): return f"Point({self.real}, {self.imag})" def __mul__(self, other) -> "Point": """Element-wise multiplication of two points, unless other is a real.number or a conjugate. Falls back on conjugate behavior. :param other: Another point, real number, or conjugate :type other: ``int``, ``float``, ``point``, ``complex`` >>> Point(-3, 6) * Point(2, -3) Point(-6.0, -18.0) """ if isinstance(other, Point): return Point(self.real * other.real, self.imag * other.imag) return super().__mul__(other) @property def x(self): return self.real @x.setter def x(self, val): self.real = val
{ "domain": "codereview.stackexchange", "id": 45025, "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, object-oriented", "url": null }
python, python-3.x, object-oriented @x.setter def x(self, val): self.real = val @property def y(self): return self.imag @y.setter def y(self, val): self.imag = val def midpoint(self, other): """""" return self * 0.5 + other * 0.5 def distance(self, other:Point=ORIGIN) -> float: """Euclidian distance between points :param other: Point or conjugate. Interprets real numbers as (real, 0) :returns: float >>> Point(3.0, 4.0).distance() 5.0 """ return abs(self - other) def rotate(self, angle:float, center:Point=ORIGIN) -> Point: """Rotates point around center by angle :param angle: Angle in radians :param center: Center of rotation. Defaults to ORIGIN :returns: New Point with the transformation """ raise NotImplementedError @classmethod def __conj_rotation(*args): """ >>> Point._Point__conj_rotation(1.0) 1.0 """ raise NotImplementedError #return complex(cos(angle), sin(angle)) if __name__ == "__main__": import doctest doctest.testmod() Answer: shebang #!/usr/bin/env python The shebang looks beautiful, thank you. Everyone should implement like this. Very portable, and it obeys $PATH. black, isort ... tried my best to implement best practices such as formatting, docstrings, ... Largely you don't even have to think about such details. Just do this every now and again: $ black . ; isort . (First time out you might prefer black -S ., to avoid single- vs double- quote diff details.) I was initially reluctant to adopt black. The secret to making it work effectively turns out to be adding an "extra" trailing , comma in places where you desire one item per line. Also, if you're unhappy with the layout of "... foo_expression, bar_expression, ..." it can be helpful to create some more local variables: foo = ... bar = ... ..., foo, bar, ...
{ "domain": "codereview.stackexchange", "id": 45025, "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, object-oriented", "url": null }
python, python-3.x, object-oriented delete comments upon merging # Test for inherited funcs # [getattr(complex, a) == getattr(super(complex), a, None) for a,o in complex.__dict__.items()] Sorry, didn't quite follow along, there. I'm sure that snippet was useful at one point. But now we want to merge a PR down to main. This is the right time to delete commented code. Or put it in a private _method() with no callers. Similarly for printing new bases. For the various methods containing commented print statements, consider adding a keyword default argument of ... , verbose=False): to the signature. Then an if verbose: guard suffices to optionally print the debug data. Consider using a logger at DEBUG or INFO level for such debugs. cryptic docstring class TypeEnforcerMetaclass(type): """ Black magic return type wrapper. ... Sorry, but I'm not happy with that description. It's more appropriate for a # comment. When describing your Public API to a prospective caller, it is incumbent on you to peel aside the curtain concealing the Great Oz, and reveal what expectations caller can rely upon. Similarly for "through Blacker magic". Consider including an URL that offers a deeper exploration of the details. The example is beautiful, thank you.
{ "domain": "codereview.stackexchange", "id": 45025, "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, object-oriented", "url": null }
c++, array, memory-management, pointers, type-safety Title: Reusable storage for array of objects Question: My goal is to have a memory pool non-template class that is used to store arrays of objects. The same memory pool object must be reusable for a different array (difference size, different type and/or alignment). I already posted a series of questions on SO about this subject: Correctly using type-punning and erasure for array of objects type-punning and strict aliasing rule for array of objects type-punning: omitting placement new and destructors type-punning with std::aligned_alloc for array of objects What exactly does the standard array form placement new expression? I tried to sum-up all the discussions in these questions into a C++14 code. The "interesting" part is the Buffer class: #include <cstddef> #include <functional> #include <iostream> // Object constructible from a double // forcing alignment struct alignas(16) SFloat { float val = 0.f; SFloat() { std::cout << "Constructing a SFloat with default value\n"; }; SFloat(const double v) : val(static_cast<float>(v)) { std::cout << "Constructing a SFloat from " << v << '\n'; }; SFloat& operator=(SFloat&& f) { val = f.val; std::cout << "Move-assigning from a SFloat " << f.val << '\n'; return *this; } ~SFloat() { std::cout << "Destructing a SFloat holding " << val << '\n'; } }; // Serialization of Float objects std::ostream& operator<<(std::ostream& o, SFloat const& f) { return o << f.val; } // just for the sake of the example: p points to at least a sequence of 3 T // probably not the best implem, but compiles without conversion warning with // SFloat and float. template <typename T> void load(T* p) { std::cout << "starting load\n"; p[0] = static_cast<T>(3.14); p[1] = static_cast<T>(31.4); p[2] = static_cast<T>(314.); std::cout << "ending load\n"; }
{ "domain": "codereview.stackexchange", "id": 45026, "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, memory-management, pointers, type-safety", "url": null }
c++, array, memory-management, pointers, type-safety // type-punning reusable buffer // holds a non-typed buffer (actually a char*) that can be used to store any // types, according to user needs struct Buffer { // destructing functor storage // required to call the correct object destructors // using std::function to store a copy of the lambda used // @1 is there a way to avoid std::function? std::function<void(Buffer*)> Destructors = [](Buffer*) {}; // buffer address unsigned char* p = nullptr; // aligned buffer address unsigned char* paligned = nullptr; // number of stored elements size_t n = 0; // buffer size in bytes size_t s = 0;
{ "domain": "codereview.stackexchange", "id": 45026, "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, memory-management, pointers, type-safety", "url": null }
c++, array, memory-management, pointers, type-safety // computes the smallest positive offset in bytes that must be applied to p // in order to have alignment a a is supposed to be a valid alignment std::size_t OffsetForAlignement(unsigned char const* const ptr, std::size_t a) { std::size_t res = reinterpret_cast<std::size_t>(ptr) % a; if (res) { return a - res; } else { return 0; } } // allocates a char buffer large enough for N object of type T and // default-construct them // N must be > 0 template <typename T> T* DefaultAllocate(const std::size_t N) { // Destroy previously stored objects, supposedly ends lifetime of the // array object that contains them Destructors(this); std::size_t RequiredSize = sizeof(T) * N + alignof(T); if (s < RequiredSize) { std::cout << "Requiring " << RequiredSize << " bytes of storage\n"; // @2 creating a storage of RequiredSize bytes // what would be the C++17+ way of do that? std::aligned_alloc? p = reinterpret_cast<unsigned char*>(std::realloc(p, RequiredSize)); s = RequiredSize; // here should do something for the case where p is nullptr paligned = p + OffsetForAlignement(p, alignof(T)); } // @3 Form1 placement array new default construction: ill-defined in // C++14? // expecting starting an array object lifetime and the lifetime of // contained objects // expecting pointer arithmetic to be valid on tmp T* // T *tmp = new (p) T[N]; // @4 Form2 individually creating packed object in storage // expecting starting an array object lifetime and the lifetime of // contained objects // expecting pointer arithmetic to be valid on tmp T* unsigned char* pos = paligned; T* tmp = reinterpret_cast<T*>(paligned);
{ "domain": "codereview.stackexchange", "id": 45026, "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, memory-management, pointers, type-safety", "url": null }
c++, array, memory-management, pointers, type-safety unsigned char* pos = paligned; T* tmp = reinterpret_cast<T*>(paligned); for (std::size_t i = 0; i < N; ++i) { new (pos) T(); pos += sizeof(T); }
{ "domain": "codereview.stackexchange", "id": 45026, "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, memory-management, pointers, type-safety", "url": null }
c++, array, memory-management, pointers, type-safety // update nb of objects n = N; // create destructors functor // @5 supposedly ends the lifetime of the array object and of the // contained objects Destructors = [](Buffer* pobj) { T* ToDestruct = reinterpret_cast<T*>(pobj->p); // Delete elements in reverse order of creation while (pobj->n > 0) { --(pobj->n); // should be std::Destroy(ToDestruct[n]) in C++17 // I should provide my own implementation in C++14 in order to // distinguish between fundamental types and other ones // @ how to formally en the lifetime of a fundamental objects? // merely rewrite on its memory location? ToDestruct[(pobj->n)].~T(); } // @6 How to formally end the array object lifetime? }; return tmp; } // deallocate objects in buffer but not the buffer itself // actually useless // template <typename T> // void Deallocate() { // Destructors(this); // } ~Buffer() { // Ending objects lifetime Destructors(this); // Releasing storage std::free(p); } }; int main() { constexpr std::size_t N0 = 7; constexpr std::size_t N1 = 3; Buffer B; std::cout << "Test on SomeClass\n"; SFloat* ps = B.DefaultAllocate<SFloat>(N0); ps[0] = 3.14; *(ps + 1) = 31.4; ps[2] = 314.; std::cout << ps[0] << '\n'; std::cout << ps[1] << '\n'; std::cout << *(ps + 2) << '\n'; std::cout << "Test on float\n"; // reallocating, possibly using existing storage, for a different type and // size float* pf = B.DefaultAllocate<float>(N1); pf[0] = 3.14f; *(pf + 1) = 31.4f; pf[2] = 314.f; std::cout << pf[0] << '\n'; std::cout << pf[1] << '\n'; std::cout << *(pf + 2) << '\n'; return 0; }
{ "domain": "codereview.stackexchange", "id": 45026, "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, memory-management, pointers, type-safety", "url": null }
c++, array, memory-management, pointers, type-safety Live demo I would appreciate a review on this Buffer class, in C++14. Yet I'm also interested in upgrade to C++17 and beyond. I've placed // @# numbered comment in the code for focus on specific implementation issues/questions. N.B. my concern in SO was that these type-punning techniques, though well defined for single objects, seemed to be ill-defined when speaking of arrays. Note: I previously had a std::function which I replaced by a simple pointer to function. Yet I don't understand why the pointer does not become dangling when leaving the DefaultAllocate function. Answer: Use the return value of placement-new In your code you write: T* tmp = reinterpret_cast<T*>(paligned); However, at this point there is no live object of type T at paligned. You might create one later, but depending on the version of C++ you are using and how much of a language lawyer you are, use of tmp after this might still be undefined behavior. There are various ways you can get a valid pointer to T, for example using std::launder() or C++23's std::start_lifetime_as(), but there is a much simpler way: use the return value of the placement-new operator. Note that you can combine this with array allocation, so: T* tmp = new(pos) T[N];
{ "domain": "codereview.stackexchange", "id": 45026, "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, memory-management, pointers, type-safety", "url": null }
c++, array, memory-management, pointers, type-safety You might ask: why does this matter? Apart from some esoteric machines where pointers work differently depending on the type of object they point to, static analysis tools might also complain if your code is not correct according to the C++ abstract machine's memory model. Once you have a valid tmp you can reinterpret_cast<> it safely to and from char*, unsigned char* and std::byte*. Possible incorrect alignment after reallocating If you call DefaultAllocate() a second time on a given Buffer, it could be that the new T fits in the old space, but has a larger alignment requirement than the old T. Thus, this could result in returning an incorrectly aligned pointer. You have to recalculate paligned even if s >= RequiredSize. Incorrect pointer used when destructing objects You use pobj->p in Destructors when it should have been pobj->paligned at the very least. But also take into account what I said above, and ensure you use a pointer that is derived from the return value of the placement-new expressions. Note that you can capture a T* in the lambda expression, so there is no need to pass it a Buffer* and to use type-erased pointers. Missing exception handling Unless the constructor of T is marked noexcept, you must consider the possibility that construction of any object of type T might cause an exception to be thrown. If so, you must make sure that you destroy any objects you have constructed so far. C++17 has some functions to help with this, like for example std::uninitialized_value_construct(). If you cannot use it yet in a C++14 code base, it might still be helpful to look at how it is implemented. Destructors should never throw an exception, so you can mark the destructor of Buffer noexcept. Use std::uintptr_t instead of std::size_t when aligning
{ "domain": "codereview.stackexchange", "id": 45026, "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, memory-management, pointers, type-safety", "url": null }
c++, array, memory-management, pointers, type-safety Use std::uintptr_t instead of std::size_t when aligning There are computer architectures where pointers are larger than std::size_t. The correct type to use to convert a pointer to an unsigned integer type is std::uintptr_t. On the other hand, this type is an optional part of the standard, but I haven't heard of any architecture where this wasn't present. Use private to avoid exposing implementation details Users of Buffer should not be able to change any of the member variables, as this could cause problems later. Use private and public to only expose those parts of the interface that are meant for the users of it. Naming Some variables are named with capitals, others only with lower case. The same goes for function names. Pick one style and stick with it. I recommend you use either snake_case or camelCase, as those seem to be the two most used styles. But do capitalize the names of types. Also avoid unnecessarily short names, like p, n and s. These could be renamed to storage, count and size for example, although n is so commonly used for "number of" that it would be OK to keep it like that, similar to how i is a commonly used name for a loop counter. Is it useful? A Buffer is a very limited memory pool: you can only have one active allocation at a time. You might sometimes avoid reallocating memory, but new and delete are not that expensive. So your main() function could be replaced with: int main() { … std::cout << "Test on SomeClass\n"; SFloat* ps = new SFloat[N0]; … // reallocating, possibly using existing storage, for a different type and size delete[] ps; float* pf = new float[N1]; … }
{ "domain": "codereview.stackexchange", "id": 45026, "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, memory-management, pointers, type-safety", "url": null }
c++, array, memory-management, pointers, type-safety The comment is still valid: delete followed by new could very well reuse the same memory. Of course, raw new and delete should be avoided, std::vector is the appropriate thing to use here.
{ "domain": "codereview.stackexchange", "id": 45026, "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, memory-management, pointers, type-safety", "url": null }
python, python-3.x, reinventing-the-wheel, computational-geometry Title: 2D Point subclass of complex builtin Question: I'm writing a pure-python geometry tool for technical drawings / computational geometry (not a solver, as a solver has to work with constraints). I've already mentioned a previous version on code review, as an example for Metaclass Wrapping Builtin to Enforce Subclass Type. This question is about the Point class and the documentation/style/examples or packaging. I'm using Yapf/isort for formatting, and it would be helpful if I could get further best practices. Tree $ tree --gitignore . ├── conf.py ├── geometry │ ├── __init__.py │ └── point.py ├── __init__.py ├── LICENSE.MD ├── README.md ├── ROADMAP.md ├── TODO.MD └── _utils └── _type_enforcer.py point.py #!/usr/bin/env python import math from math import cos, sin, tan from typing import ClassVar, Iterable, Union from .._utils._type_enforcer import TypeEnforcerMetaclass Point = ClassVar["Point"] class Point(complex, metaclass=TypeEnforcerMetaclass, enforce_all=True): r""" :param x: x coordinate of the point. :type x: ``int``, ``float`` :param y: y coordinate, Stored as the imaginary component :type y: ``int``, ``float`` :: .. highlight:: python >>> a = Point(2, 3) >>> b = Point(-3, 5) >>> a Point(2.0, 3.0) >>> a + b Point(-1.0, 8.0) >>> a.midpoint(b) Point(-0.5, 4.0) >>> a * b Point(-6.0, 15.0) """ ORIGIN = 0 # Works because 0 == 0+0j
{ "domain": "codereview.stackexchange", "id": 45027, "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, reinventing-the-wheel, computational-geometry", "url": null }
python, python-3.x, reinventing-the-wheel, computational-geometry """ ORIGIN = 0 # Works because 0 == 0+0j def __new__(cls, *args, **kwargs): if len(args) == 1: if isinstance(args[0], complex): return super().__new__(cls, args[0].real, args[0].imag, *args[1:], **kwargs) elif isinstance(args[0], Iterable) and len(args[0]) == 2: return super().__new__(cls, args[0][0], args[0][1], *args[1:], **kwargs) else: raise ValueError( """Only complex or iterable with length 2 can be used with single-argument form""") else: return super().__new__(cls, *args, **kwargs) def __init__(self, x, y: float = 0): pass def __repr__(self): return f"Point({self.real}, {self.imag})" def __complex__(self): """Convert self to exact type complex""" return complex(self) def __getitem__(self, val): if val not in range(0, 2): raise IndexError("") def __mul__(self, other) -> "Point": """Element-wise multiplication of two points, unless other is a real.number or a complex. Falls back on complex behavior. :param other: Another point, real number, or complex :type other: ``int``, ``float``, ``point``, ``complex`` :: .. highlight:: python >>> Point(-3, 6) * Point(2, -3) Point(-6.0, -18.0) """ if isinstance(other, Point): return Point(self.real * other.real, self.imag * other.imag) return super().__mul__(other) @property def x(self): """ X coordinate of the point. Represented internally as real component :: .. highlight:: python >>> a = Point(3, 5) >>> a.x 3.0 >>> a.x = 5 >>> a Point(5.0, 5.0) """ return self.real
{ "domain": "codereview.stackexchange", "id": 45027, "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, reinventing-the-wheel, computational-geometry", "url": null }
python, python-3.x, reinventing-the-wheel, computational-geometry @x.setter def x(self, val): self.real = val @property def y(self): """ Y coordinate of the point. Represented internally as imag component :: .. highlight:: python >>> a = Point(3, 5) >>> a.y 5.0 >>> a.y = 2 >>> a Point(5.0, 2.0) """ return self.imag @y.setter def y(self, val): self.imag = val def scale(self, other, center=ORIGIN): """Scales self by other around center :param other: vector to scale self by. Floats are interpreted as scaling by (other, other) :type other: Point, Iterable, complex, float :: .. highlight:: python >>> Point(2,1).scale(2) Point(4,2) >>> Point(3,4).scale((3, 5)) Point(9, 20) >>> Point(2,2).scale(10+10j, center=Point(2,2)) Point(2,2) """ scale = 0 if isinstance(other, Point): scale = other elif isinstance(other, Iterable) and len(other) == 2: scale = Point(*other) elif isinstance(other, complex): scale = Point(other) elif hasattr(other, "real"): scale = Point(other, other) else: raise ValueError(other, "is not a valid type for Point.scale") local = self - center local *= scale return local + center def midpoint(self, other): """Midpoint between self and other, in cartesian coordinates. Floats are interpreted as Point(other, 0) :param other: coordinate to take midpoint between it and self :type other: Point, complex or float. :: .. highlight:: python >>> Point(3, 5).midpoint(Point(5, 3)) Point(4, 4) """ return self * 0.5 + other * 0.5
{ "domain": "codereview.stackexchange", "id": 45027, "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, reinventing-the-wheel, computational-geometry", "url": null }
python, python-3.x, reinventing-the-wheel, computational-geometry def distance(self, other: Point = ORIGIN) -> float: """Euclidian distance between self and other Floats are interpreted as Point(other, 0) :param other: coordinate to take euclidian distance of :returns: Euclidian distance :rtype: float :: .. highlight:: python >>> Point(3.0, 4.0).distance() 5.0 """ return abs(self - other) def taxicab_distance(self, other: Point = ORIGIN) -> float: """Returns taxicab distance between self and other. Floats are interpreted as Point(other, 0) :param other: coordinate to take taxicab distance of. :type other: Point, complex, float :returns: `abs(self.x - other.x) + abs(self.y - other.y)` :rtype: float :: .. highlight:: python >>> Point(3.0, 4.0).taxicab_distance() 7.0 >>> # 3.0 - 0.0 + 4.0 - 0.0 = 7.0 """ return abs(self.real - other.real) + abs(self.imag - other.imag) def rotate(self, theta: float, center: Point = ORIGIN) -> Point: """Rotates point around center by theta radians. Equivalent to `Point(self * cmath.exp(theta * 1j * cmath.pi))` :param theta: angle of rotation in radians :param center: center of rotation. Defaults to ORIGIN :returns: new rotated Point :rtype: Point :: .. highlight:: python >>> Point(2,3).rotate(math.pi/2) Point(-3.0, -2.0) """ local_coords = self - center # Multiplying by z, where abs(z) == 1 is the same as rotation local_coords *= Point.__conj_rotation(theta) local_coords += center return local_coords
{ "domain": "codereview.stackexchange", "id": 45027, "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, reinventing-the-wheel, computational-geometry", "url": null }
python, python-3.x, reinventing-the-wheel, computational-geometry return local_coords @staticmethod def __conj_rotation(theta: float): """Returns a complex representing a rotation vector. :param theta: theta, in radians of the rotation :type theta: float :return: representation of rotation :rtype: complex :: .. highlight:: python >>> Point._Point__conj_rotation(math.pi) (-1+...e-16j) """ return complex(cos(theta), sin(theta)) if __name__ == "__main__": import doctest doctest.testmod(optionflags=doctest.ELLIPSIS) _type_enforcer.py #!/usr/bin/env python import logging from types import MemberDescriptorType, WrapperDescriptorType default_exclude = {"__new__", "__getattribute__", "__setattribute__"} class TypeEnforcerMetaclass(type): """ Metaclass that enforces return type. Ensures that inhereted methods return proper class (that of the inheritee), as in the case of builtins. When `enforce_all == True`, creates intermediate class which is wrapped to the correct type. :param enforce_all: Enforces return type of super() :type enforce_all: ``bool`` :param exclude: Ignore special names, such as __X__. :type enforce_all: ``bool`` Example:: >>> class A(int, metaclass=TypeEnforcerMetaclass, enforce_all=True, exclude={"real"}): ... def __repr__(self): ... return f"A({super().real})" >>> A(1) A(1) >>> A(1) + A(4) A(5) >>> A(3) * A(-3) A(-9) >>> super(A) <super: <class 'A'>, NULL> >>> type(A) <class '__main__.TypeEnforcerMetaclass'> """
{ "domain": "codereview.stackexchange", "id": 45027, "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, reinventing-the-wheel, computational-geometry", "url": null }
python, python-3.x, reinventing-the-wheel, computational-geometry def __new__(meta, name, bases, classdict, enforce_all=False, exclude=default_exclude): exclude = exclude.union(default_exclude) logging.info(f"Creating class {name} in {meta.__name__}") # Creates a new abstraction layer (middleman class), so super() # returns wrapped class # that has all its methods wrapped. # ┌────────────┐ ┌────────────┐ ┌────────────┐ # │ Point │⇦│ _compl │⇦│ complex │ # └────────────┘ └────────────┘ └────────────┘ superclass = bases[0] if enforce_all: logging.debug(f"Parameter enforce_all is turned ON") # Somehow, name mangling doesn't show up when printing class. # Probably __repr__ isn't being overriden inter_name = meta.__name__ + "." + superclass.__name__ logging.debug(f"Creating intermediate class {inter_name}") inter_dict = dict(superclass.__dict__) inter_class = super(TypeEnforcerMetaclass, meta).__new__(meta, inter_name, bases, inter_dict) bases = (inter_class, *bases) # Neat trick for tuples subclass = super(TypeEnforcerMetaclass, meta).__new__(meta, name, bases, classdict) logging.debug("New Bases", bases) logging.debug("sub:", subclass, "meta:", type(subclass)) # Has the potential to cause errors if not enabled # logging.debug("inter:", inter_class, "meta:", type(inter_class)) logging.debug("Class info: ",subclass, subclass.__name__, subclass.mro(), subclass.__dict__, sep="\n") base_to_wrap = subclass.mro()[1] type_compare = subclass type_to_convert = subclass if enforce_all: type_compare = inter_class base_to_wrap = inter_class.mro()[1]
{ "domain": "codereview.stackexchange", "id": 45027, "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, reinventing-the-wheel, computational-geometry", "url": null }
python, python-3.x, reinventing-the-wheel, computational-geometry for attr, obj in base_to_wrap.__dict__.items(): if isinstance(obj, MemberDescriptorType): logging.debug("Skipping", obj, "Due to MemberDescriptor") continue # Traverse the mro # == testing is exactly what we want for comparing overridden # definitions, if obj == getattr(type_compare, attr, None) and attr not in exclude: # Dont override __new__! # Check if the method is inhereted from base_to_wrap # Iff inherited, wrap the return type logging.info("Wrapping", obj, "to return", type_to_convert.__name__) setattr( type_compare, attr, TypeEnforcerMetaclass.return_wrapper( superclass, type_to_convert, obj)) return subclass def return_wrapper(cls, convert_cls, func): """Wraps class methods and enforces type""" if isinstance(func, (str, int, float)): return func logging.debug("Decorator", cls, func.__name__) def convert_if(val): if isinstance(val, cls): logging.debug("Wrapped:", val.__class__, val) return convert_cls(val) else: logging.debug("Skipped:", val.__class__, val) logging.debug("Reason:", cls.__class__, "!=", val.__class__) return val def wrapper(*args, **kwargs): logging.debug("Wrapper", cls, func.__name__) return convert_if(func(*args, **kwargs)) wrapper.__wrapped__ = func return wrapper if __name__ == "__main__": import doctest logging.setLevel(logging.INFO) logging.info("Running doctests") doctest.testmod(report=True)
{ "domain": "codereview.stackexchange", "id": 45027, "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, reinventing-the-wheel, computational-geometry", "url": null }
python, python-3.x, reinventing-the-wheel, computational-geometry Answer: doctests Kudos for the doctests, they are very helpful. Doctests are documentation I can believe! They do not bit rot (since failing tests are quickly noticed). doctest.testmod(optionflags=doctest.ELLIPSIS) Example:: >>> class A(int, metaclass=TypeEnforcerMetaclass, enforce_all=True, exclude={"real"}): ... def __repr__(self): ... return f"A({super().real})" I do worry a little about unintended ... matching. The doctests are very nice, but they're no substitute for a test suite. The two tools have different audiences. Doctests are short, non-comprehensive, and must be understood by newbies. A test suite can be long, boring, and explore a tediously large number of odd corner cases. documentation toolchain class Point(...): r""" :param x: ... :type x: ``int``, ``float`` I guess you're using something like Sphinx? The need for a r"raw" docstring seems a little inconvenient. But maybe you really need fancy formatting of types. Docstrings ideally look good both before and after sphinx processing. That is, we prefer docstrings that aren't cluttered with formatting details, such as "highlight". Consider re-evaluating your goals and your documentation toolchain. There's more than one standard for writing docstrings, and it seems clear that you're trying to adhere to one. So write it down, preferably accompanied by an URL citation. I'm a little sad we couldn't get away with using optional type hints to document valid inputs, but maybe we really do need __new__ instead of __init__ to accomplish your desired goals. When such type annotations are used, I try to mention the type just once, so annotation and documentation can't get out of sync with one another.
{ "domain": "codereview.stackexchange", "id": 45027, "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, reinventing-the-wheel, computational-geometry", "url": null }
python, python-3.x, reinventing-the-wheel, computational-geometry limited flexibility def __new__(cls, *args, **kwargs): if len(args) == 1: if isinstance(args[0], complex): return super().__new__(cls, args[0].real, args[0].imag, *args[1:], **kwargs) Ok, we're trying to offer a lot of flexibility to the caller, kind of a DWIM Public API. Maybe that's good. I guess I'm not yet convinced, in part because I haven't seen motivating examples of tests calling into this code. I will just assume it's a Good Thing for now. I don't understand what's going on with that *args[1:] expression. Didn't we just establish that it must always be the empty list here? Recommend you elide it. And similarly where it appears again, two lines down. elif isinstance(args[0], Iterable) and len(args[0]) == 2: return super().__new__(cls, args[0][0], args[0][1], *args[1:], **kwargs) I don't understand that conjunct, it just doesn't make any sense. First we ask if .__iter__ is present. And then we take a length?!? But we never asked about .__len__. Being a container is a much stronger restriction than being iterable. Consider this example: def odds(limit=11): """Generates a small subset of the odd integers.""" yield from range(1, limit, 2) Maybe you want to assign list(args[0]) to a temp var first? At that point you know you have a container. Let's move on to the ... , args[0][0], args[0][1], ... expressions. If I pass in a set of {3, 4} we will survive the iterable and length tests. But you didn't ask if subscripting is supported; dereferencing [0] and [1] will blow up. EAFP It is easier to ask for forgiveness than permission. You've been attempting to go down the LBYL path, and it's not always easy. Embrace try! defaults def __init__(self, x, y: float = 0): pass
{ "domain": "codereview.stackexchange", "id": 45027, "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, reinventing-the-wheel, computational-geometry", "url": null }
python, python-3.x, reinventing-the-wheel, computational-geometry defaults def __init__(self, x, y: float = 0): pass Sorry, I didn't understand that. Perhaps you intended ...(self, x: float = 0.0, y: float = 0.0): ? Also, this kind of highlights the whole Union[int, float] issue, which unfairly (arbitrarily?) rejects Decimal and Fraction. Consider turning everything that you store into a float, in the interest of simplicity. It would be one of your class invariants. @x.setter def x(self, val): self.real = val Back to the invariant thing, maybe assign float(val) ? You did a bunch of validating in __new__, which the setter threatens to subvert. getitem def __getitem__(self, val): if val not in range(0, 2): raise IndexError("") I don't understand that. Didn't you want to map 0 to .real and 1 to .imag ? Also, might as well include val in the diagnostic error message. LBYL elif isinstance(other, Iterable) and len(other) == 2: scale = Point(*other) In scale() the second conjunct isn't safe because we only looked for .__iter__ and not .__len__. Embrace try! The high level design issue here is you attempt to accept roughly as many cases as numpy, but without writing down clear motivating use cases and without offering Green unit tests and coverage measurements. Recommend you scale down your ambitions, and wait for motivating use cases to organically arise. DRY def midpoint(self, other): """Midpoint between self and other, in cartesian coordinates. Floats are interpreted as Point(other, 0) :param other: coordinate to take midpoint between it and self :type other: Point, complex or float.
{ "domain": "codereview.stackexchange", "id": 45027, "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, reinventing-the-wheel, computational-geometry", "url": null }
python, python-3.x, reinventing-the-wheel, computational-geometry Here the type annotation admits Any type in a way that $ mypy *.py can check, yet the documentation restricts to a smaller set of types, hidden from mypy. def distance(self, other: Point = ORIGIN) -> float: """Euclidian distance between self and other Floats are interpreted as Point(other, 0) :param other: coordinate to take euclidian distance of Here we have a lovely annotation which is not too ambitious; it specifies exactly one type. But the documentation admits of multiple types, and is not self-consistent (a "float" is not a "coordinate"). Subsequent methods exhibit similar difficulties. Recommend you push your type documentation exclusively into the annotations, so mypy can help you out. I want to be able to believe the documentation that I'm reading. name mangling def __conj_rotation(theta: float): Recommend you rename to _conj_rotation, as name mangling is seldom what you want. Alternatively, supply automated tests involving inheritance which demonstrate some name mangling benefit to the app-level developer. This codebase appears to achieve many of its design objectives. I am skeptical that its ambition to "accept any plausible type!" is compatible with the current target code and the current automated testing code. I would be willing to delegate or accept maintenance tasks on this codebase.
{ "domain": "codereview.stackexchange", "id": 45027, "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, reinventing-the-wheel, computational-geometry", "url": null }
bash Title: Find missing files from subdirectories given the file names have sequential number Question: I have a directory structure like bellow. . ├── Course 1 │ ├── 1 - Introduction │ │ ├── 01-First Video.mp4 │ │ ├── 02-Second Video.mp4 │ │ ├── 03-Third Video.mp4 │ ├── 2 - Chapter 1 │ │ ├── 05-Nth Video.mp4 │ │ ├── 06-Nth1 Video.mp4 │ │ └── 07-Nth2 Video.mp4 │ ├── 3 - Chapter 2 │ │ ├── 08-Nth Video.mp4 │ │ ├── 09-Nth1 Video.mp4 │ │ └── 10-Nth2 Video.mp4 │ ├── 4 - Analysis │ │ ├── 11-Nth Video.mp4 │ │ ├── 12-Nth1 Video.mp4 │ │ └── 13-Nth2 Video.mp4 │ ├── 5 - Conclusion │ │ ├── 14-Nth Video.mp4 │ │ ├── 15-Nth1 Video.mp4 │ │ └── 16-Nth2 Video.mp4 ├── Course 2 │ ├── 1 - Introduction │ │ ├── 01-First Video.mp4 │ │ ├── 02-Second Video.mp4 │ │ ├── 03-Third Video.mp4 │ ├── 2 - Chapter 1 │ │ ├── 05-Nth Video.mp4 │ │ ├── 06-Nth1 Video.mp4 │ │ └── 07-Nth2 Video.mp4 │ ├── 4 - Analysis │ │ ├── 11-Nth Video.mp4 │ │ ├── 12-Nth1 Video.mp4 │ │ └── 13-Nth2 Video.mp4 │ ├── 5 - Conclusion │ │ ├── 14-Nth Video.mp4 │ │ ├── 15-Nth1 Video.mp4 │ │ └── 16-Nth2 Video.mp4 ├── Course 3 │ ├── 1 - Introduction │ │ ├── 02-First Video.mp4 │ │ ├── 03-Third Video.mp4 │ ├── 2 - Chapter 1 │ │ ├── 05-Nth Video.mp4 │ │ └── 07-Nth2 Video.mp4 │ ├── 4 - Analysis │ │ ├── 11-Nth Video.mp4 │ │ ├── 12-Nth1 Video.mp4 │ ├── 5 - Conclusion │ │ ├── 14-Nth Video.mp4 │ │ ├── 15-Nth1 Video.mp4 │ │ └── 16-Nth2 Video.mp4 I want to find if any files are missing in the directories. The code that i am using to solve this problem is: #!/usr/bin/env bash
{ "domain": "codereview.stackexchange", "id": 45028, "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": "bash", "url": null }
bash previousname="Placeholder" nextfilenumber=1 find . -type f -name "*.mp4" | sort --version-sort | while read -r line ; do coursename=$(echo $line | cut -d/ -f2) if [[ "$previousname" != "$coursename" ]]; then nextfilenumber=2 previousname=$coursename else filename=${line##*/} # https://stackoverflow.com/a/24777667/1772898 filenumber=$((10#${filename%%-*})) nextfilenumber="$((nextfilenumber+1))" temp="$((filenumber+1))" if [[ $temp -ne $nextfilenumber ]]; then echo "File(s) Before \"$coursename\"\'s \"$filename\"" nextfilenumber="$((nextfilenumber+1))" fi fi done How can I make this code better? Answer: Improve usability For the example input, the script produces the following output for Course 2: File(s) Before "Course 2"\'s "05-Nth Video.mp4" File(s) Before "Course 2"\'s "11-Nth Video.mp4" File(s) Before "Course 2"\'s "12-Nth1 Video.mp4" File(s) Before "Course 2"\'s "13-Nth2 Video.mp4" The first line I understand: a file with number 04 is missing, before seeing 05. The rest of the lines look a bit strange: I understand the objection about the file with number 11, since files with number 08, 09 and 10 are missing before that. I think it would be more user friendly to print something like: Expected a file with number 4, got: Course 2/2 - Chapter 1/05-Nth Video.mp4 Expected a file with number 8, got: Course 2/4 - Analysis/11-Nth Video.mp4 As another example, consider the output for Course 3: File(s) Before "Course 3"\'s "03-Third Video.mp4" File(s) Before "Course 3"\'s "05-Nth Video.mp4" File(s) Before "Course 3"\'s "07-Nth2 Video.mp4" File(s) Before "Course 3"\'s "11-Nth Video.mp4" File(s) Before "Course 3"\'s "12-Nth1 Video.mp4" File(s) Before "Course 3"\'s "14-Nth Video.mp4" File(s) Before "Course 3"\'s "15-Nth1 Video.mp4"
{ "domain": "codereview.stackexchange", "id": 45028, "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": "bash", "url": null }
bash Similar to the previous example, this looks a bit strange because a file with number 1 is missing, a file with number 2 is present, but the message mentions a file with number 3. Also note the message prints \' instead of simply '. Simplify the number comparison logic Instead of this: nextfilenumber="$((nextfilenumber+1))" temp="$((filenumber+1))" if [[ $temp -ne $nextfilenumber ]]; then echo "File(s) Before \"$coursename\"\'s \"$filename\"" nextfilenumber="$((nextfilenumber+1))" fi This is shorter and equivalent: if [[ $filenumber -ne $nextfilenumber ]]; then echo "File(s) Before \"$coursename\"\'s \"$filename\"" nextfilenumber="$((nextfilenumber+1))" fi nextfilenumber="$((nextfilenumber+1))" The original unnecessarily computes the next file number in the poorly named temp variable. Remove redundant quotes The double-quotes in expressions like this are unnecessary: nextfilenumber="$((nextfilenumber+1))" They are harmless, so it's ok to keep them, but then it's better to apply it consistently everywhere (example where not used: filenumber=$((10#${filename%%-*}))). Beware of running commands in a loop The script runs cut in a loop to extract a path component. Running commands in a loop can make scripts very slow. In this example you can achieve the same result using shell builtins: IFS=/ read _ coursename _ <<< "$line" Improve variable names Renaming previousname to previous_coursename would make the connection with coursename more clear. Alternative implementation Addressing the above issues and putting it together: #!/usr/bin/env bash previous_course_name= expected_file_number=1 find . -type f -name "*.mp4" | sort --version-sort | while read -r line ; do IFS=/ read _ current_course_name _ <<< "$line" if [[ "$previous_course_name" != "$current_course_name" ]]; then expected_file_number=1 previous_course_name=$current_course_name fi
{ "domain": "codereview.stackexchange", "id": 45028, "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": "bash", "url": null }
bash filename=${line##*/} # https://stackoverflow.com/a/24777667/1772898 file_number=$((10#${filename%%-*})) if [[ $file_number != $expected_file_number ]]; then echo "Expected a file with number $expected_file_number; got: $line" fi ((expected_file_number = file_number + 1)) done This produces output: Expected a file with number 4; got: ./Course 1/2 - Chapter 1/05-Nth Video.mp4 Expected a file with number 4; got: ./Course 2/2 - Chapter 1/05-Nth Video.mp4 Expected a file with number 8; got: ./Course 2/4 - Analysis/11-Nth Video.mp4 Expected a file with number 1; got: ./Course 3/1 - Introduction/02-First Video.mp4 Expected a file with number 4; got: ./Course 3/2 - Chapter 1/05-Nth Video.mp4 Expected a file with number 6; got: ./Course 3/2 - Chapter 1/07-Nth2 Video.mp4 Expected a file with number 8; got: ./Course 3/4 - Analysis/11-Nth Video.mp4 Expected a file with number 13; got: ./Course 3/5 - Conclusion/14-Nth Video.mp4
{ "domain": "codereview.stackexchange", "id": 45028, "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": "bash", "url": null }
c++, algorithm, multithreading, tcp Title: C++ Neuron Spike Raster Deserializer Question: Please help me establish a solid foundation for this computational neuroscience project. I'd like to make sure I'm moving forward with something reasonable before I begin tackling the more complex parts involving the inclusion of a linear algebra library and algorithms for decoding/interpreting incoming streams of neuron spike rasters. There are 3 main pieces of functionality that could use some review. network protocol agnostic data receive and deserialization epoll-based data read on a TCP socket deserialization from unsigned char buffer to a vector of uint64_t (event times) (If you have time to provide stylistic critiques on git maintenance, idiomatic language usage, etc. that's great too.) Below is pretty much the meat of it, but here is the repo for those who would like some more context: https://github.com/andresito00/gray-decoders/tree/master Agnostic rx/deserialization. I don't particularly like the constant resizing, but a few posts I've read seem to indicate this is a safer way to go about it. WDYT? The Receiver class containing this method is templated on Queue type (Q), Data Element Type (S), and Network Stack (T net_xport_). The following function is responsible for invoking items #2 and #3. ReceiverStatus receive(Q& q) { status_ = ReceiverStatus::kOkay; while (!stop_rx_) { // Can also do && net_xport_.get_status() == // NetCoreStatus::kOkay populated_bytes_ = rx_buffer_.size(); rx_buffer_.resize(size_); ssize_t bytes_received = net_xport_.wait_and_receive( rx_buffer_.data() + populated_bytes_, size_ - populated_bytes_);
{ "domain": "codereview.stackexchange", "id": 45029, "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++, algorithm, multithreading, tcp", "url": null }
c++, algorithm, multithreading, tcp if (bytes_received > 0) { if (static_cast<size_t>(bytes_received) < size_) { rx_buffer_.resize(static_cast<size_t>(bytes_received)); } std::vector<S> rasters; size_t bytes_deserialized = S::deserialize(rx_buffer_, rasters); q.enqueue_bulk(rasters.begin(), rasters.size()); rx_buffer_.erase(rx_buffer_.begin(), rx_buffer_.begin() + bytes_deserialized); } else if (bytes_received < 0) { if (++fail_count_ > kFailLimit) { status_ = ReceiverStatus::kError; rx_buffer_.clear(); break; } } } return ReceiverStatus::kStopped; } epoll-based receive. I've broken the network stack class into 3 stages: constructor: creates a socket, binds wait_for_connection: listens, accepts, establishes sockets of interest for polling wait_and_receive: sleeps and wakes up when there's data to populate in the rx buffer
{ "domain": "codereview.stackexchange", "id": 45029, "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++, algorithm, multithreading, tcp", "url": null }
c++, algorithm, multithreading, tcp Basically, am I "epolling" correctly here? The code works, but I'd like to hear from folks with more experience using it. ssize_t LinuxTCPCore::wait_and_receive(unsigned char* buffer, size_t num_bytes) noexcept { if (num_bytes == 0) { return 0; } int nfds = epoll_wait(epoll_fd_, events_, kMaxEvents, -1); if (nfds < 0) { status_ = NetCoreStatus::kError; } ssize_t bytes_received = 0; ssize_t curr_received = 0; for (size_t i = 0; i < static_cast<size_t>(nfds); ++i) { if (events_[i].data.fd == comm_socket_) { curr_received = read(comm_socket_, buffer, num_bytes); // EPOLLET requires that we continue reading from the FD until // EWOULDBLOCK/EAGAIN if (curr_received < 0) { if (errno == EWOULDBLOCK || errno == EAGAIN) { break; } else { status_ = NetCoreStatus::kError; return -1; } } else { buffer += curr_received; bytes_received += curr_received; } } } status_ = NetCoreStatus::kOkay; return bytes_received; } deserialization of events times (vector<unsigned char> -> vector<uint64_t>).
{ "domain": "codereview.stackexchange", "id": 45029, "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++, algorithm, multithreading, tcp", "url": null }
c++, algorithm, multithreading, tcp deserialization of events times (vector<unsigned char> -> vector<uint64_t>). I hate the memcpy and the C-style cast, but I found them to be much more legible than an attempt I made with reinterpret_cast. Originally, I was destroying the buffer and returning the vector of SpikeRasters, but I decided to allow the above generic receive routine to own and manage that memory instead. I use a 4-byte delimiter word to separate the individual structs during serialization. Should I encode a size instead? Should I use both? static size_t deserialize(const std::vector<unsigned char>& buff, std::vector<SpikeRaster<T>>& result) { auto delim_start = kDelimiter.begin(); auto delim_end = kDelimiter.end(); auto range_start = buff.begin(); auto range_end = buff.end(); auto found = range_end; size_t bytes_deserialized = 0; while ((found = std::search(range_start, range_end, delim_start, delim_end)) != range_end) { // deserialize the id auto id = *(T*)buff.data(); range_start += sizeof(id); // deserialize the raster event times auto raster_bytes = static_cast<size_t>(found - range_start); std::vector<T> current(raster_bytes / sizeof(T), 0); memcpy(current.data(), buff.data() + sizeof(id), raster_bytes); result.emplace_back(SpikeRaster<T>{id, std::move(current)}); // housekeeping for the return value, and updating the start // iterator bytes_deserialized += (sizeof(id) + raster_bytes + kDelimiter.size()); range_start = found + kDelimiter.size(); } return bytes_deserialized; } I've tried to provide a little bit of scoping for the review above, but any and all feedback on the repo is appreciated, especially in regards to class/template design, legibility, and idiomatic usage.
{ "domain": "codereview.stackexchange", "id": 45029, "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++, algorithm, multithreading, tcp", "url": null }
c++, algorithm, multithreading, tcp Answer: Receiving network data I don't understand why wait_and_receive() has a for-loop. Do you expect data from multiple sockets to be received? If so, this function is broken in many ways: num_bytes is never decreased so multiple sockets being ready could cause a buffer overflow, and data from multiple sockets can get interleaved in unexpected ways. If nfds is only ever supposed to be 1 (excluding error conditions), then there is no need to use epoll at all, just do a blocking read() directly on the socket. Note that the size of TCP packets that are being transmitted over the network do not have to match the size of a write() call. Packets can be split and reassembled by the sending operating system, by routers on the Internet, and by the receiving operating system. Even if you send() 4 bytes, the other side might have to do four recv() calls that each return 1 byte. The only guarantee you have is that the data is in the same order. Your code might seem to handle that, but you are still missng some corner cases. Consider that you recv() a packet that has the delimiter, followed by 7 bytes, just one byte short of an uint64_t. In deserialize(), found will be true, and raster_bytes will be 7. But you allocate a vector of zero elements (raster_bytes / sizeof(uint64_t) is 0). The memcpy() will overwrite memory that wasn't allocated, which might cause your program to crash, or worse: corrupt memory that will lead to problems later. When it returns, result.size() == 0, so the caller thinks no values were received, but it will erase() all the bytes received so far, so whatever values were between the received delimiter and the next one will all be lost. There is also the issue of the arbitrarily chosen delimiter of 4 bytes. Those bytes might be part of a valid raster event time. This is a very fragile way of adding delimiters to your data, and could cause your program to misinterpret the data. What you should instead do is:
{ "domain": "codereview.stackexchange", "id": 45029, "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++, algorithm, multithreading, tcp", "url": null }
c++, algorithm, multithreading, tcp Add a fixed-size header before each batch of raster event times. The header should contain the number of event times following it. The receiver should first set the receive buffer size to the size of the header, and wait for it to be filled. You then have a complete header, from which you can read the number of event times that will follow. You can then resize the receive buffer so it can accomodate all the event times. Wait for the buffer to fill again, then process the whole buffer in one go.
{ "domain": "codereview.stackexchange", "id": 45029, "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++, algorithm, multithreading, tcp", "url": null }
c++, algorithm, multithreading, tcp You can still add a delimiter in the header, this way you could detect corrupted transmissions, but that would be very rare (TCP already has a checksum for each packet that the operating system will generate and check for you). If you accept multiple connections, use one buffer per connection to avoid data getting mixed up. Performance Calling resize() often on a std::vector is most likely fine; it won't actually shrink the allocated memory unless you call shrink_to_fit(). However, if you erase() something from the start, it has to copy the remaining data over to the start. If it's very likely you'll erase everything anyway, it is fine, but if it often happens you have a lot of data left, then all that copying can become a performance issue. Ideally, you never partially erase the vector. You can do what I mentioned above and resize it exactly to the expected amount of data, so after processing everything you can just clear() the vector. Alternatively, you could use a ringbuffer or something similar to avoid copying data unnecessarily. But apart from that, there is lots of explicit copying in your code. Data from the rx_buffer_ is memcpy()'d into the vector rasters, after which it is immediately copied into the queue q. Ideally, after you've read the header and you know how many raster event times you are going to receive, you'd read() them directly into the queue. Strict aliasing violation Depending on what the type T actually is, the following code is a strict aliasing violation: // deserialize the id auto id = *(T*)buff.data(); Consider that buff.data() might not be correctly aligned for T. Depending on T and the exact CPU architecture your code is running on, this could either cause a bus error, or it could read the data incorrectly without raising any error. The correct way to handle this is to memcpy() the data: // deserialize the id T id; memcpy(&id, buff.data(), sizeof id); If you hate memcpy(), you can use std::copy_n() for a more C++ way of doing things.
{ "domain": "codereview.stackexchange", "id": 45029, "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++, algorithm, multithreading, tcp", "url": null }
beginner, bash Title: Follow-up Q: Protein databank file chain, segment and residue number modifier Question: I asked a question yesterday (Protein databank file chain, segment and residue number modifier) and received a very informative answer by J_H whose feedback I have taken onboard. Some of the feedback was new to me such as shellcheck and do going on a newline within while or for loops. I have updated my code and it runs better, I have published it on GitHub too so it might be helpful to others who run into the same issues that I did. My implementation of getopts leaves a lot to be desired and I think can be improved substantially although I am still learning. The log function might be able to be improved, especially with optional arguments to increase verbosity rather than a flag. Should there be a large body of text at the beginning of a bash script containing usage, refs, TODO etc? I should probably improve the logging with time as the phenix.pdbtools steps take around ~4/5 secs per chain. The code passes shellcheck with no issues and is as follows: #!/bin/bash
{ "domain": "codereview.stackexchange", "id": 45030, "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": "beginner, bash", "url": null }
beginner, bash # --- bash script to modify CCCP server generated PDB bundle templates # # CCCP generated poly-glycine and poly-alanine PDBs need to be modified before # they can be used, namely their segment IDs match their chain IDs (i.e. in # PyMOL it is /A/A, /B/B etc), each chain is numbered from 1 and the poly-ala # chains do not posses the side chains. Whilst this is the stated aim of the # CCCP server for which we are grateful, this script modifies them to a point # where they can be used for further design. # # The segment IDs can be changed to all of the same through segID, multiple # chains are supported (in the form of 'A B ... X Y Z', chain IDs are changed # to all of the same through chainID and the residues per chain are incremented # so that they are continuous (for example, if all chains are 28 residues long, # then chain A is untouched and chain B will start from 29 instead of 1, chain # C from 57 etc). The path to the CCCP generated bundles must be the full path. # # The paths to the Rosetta /bin/, Rosetta /database/ and phenix /bin/ must be # set before running the script. # # The CCCP server pads their files i.e. 00001, 00002...file.pdb so order is # guaranteed with the original PDBs. # # TODO: add support for allowing the templates to be used to make poly-val or # other residues, currently breaks if 'residues' is not 'gly ala' # # If there are any issues, please post an issue or pull request. # # Usage example: # $ bash modify_cccp_bundles.sh -p "/full/path/to/CCCP" -r 28 # # Author: James Thornton # Version: 1.0 # License: MIT # # References # ---------- # CCCP: https://www.grigoryanlab.org/cccp/ # Phenix: https://phenix-online.org/documentation/index.html # Rosetta: https://www.rosettacommons.org/ # ------------------------------------------------------------------- SETTINGS set -u -e -o pipefail # ------------------------------------------------------------------- DEFAULTS
{ "domain": "codereview.stackexchange", "id": 45030, "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": "beginner, bash", "url": null }
beginner, bash # ------------------------------------------------------------------- DEFAULTS # default options segID="A" # segment ID chains='A B C D' # chains existing in the CCCP bundles chainID="A" # chain ID to change the other chains to cccp_sep="poly-" # CCCP server creates folders with poly-ala, can rename dirs residues='ala gly' # residue names _VERBOSE=0 res_per_chain="" path_to_cccp_bundles="" # ------------------------------------------------------------------- CMD LINE OPTIND=1 # reset usage="$(basename "$0") [-h] [-s A] [-z 'A B'] [-c A] [-e 'poly-'] [-a 'ala gly'] -p PATH -r INT Modify CCCP generated server bundles. arguments: -p full path to CCCP bundle directory (mandatory: str) -r residues per chain (mandatory: int) -s set segment ID to value (default: 'A') -z chains list (default: 'A B C D') -c set all chain IDs to value (default: 'A') -e dir separator in CCCP dir i.e. poly-, poly_ (default: 'poly-') -a residue names list (default: 'ala gly') -v output logging to screen, must be either 0 for output (default) or 1 -h show this help message " if [[ ${#} -eq 0 ]]; then echo "$usage" exit 1 fi while getopts ':hs:z:c:e:a:p:r:v:' option; do case "$option" in h) echo "$usage" exit 1 ;; s) segID="$OPTARG" ;; z) chains="$OPTARG" ;; c) chainID="$OPTARG" ;; e) cccp_sep="$OPTARG" ;; a) residues="$OPTARG" ;; p) path_to_cccp_bundles="$OPTARG" ;; r) res_per_chain=$OPTARG ;; v) _VERBOSE=$OPTARG ;; :) printf "missing argument for -%s\n" "$OPTARG" >&2 echo "$usage" >&2 exit 1 ;; \?) printf "illegal option: -%s\n" "$OPTARG" >&2 echo "$usage" >&2 exit 1 ;; esac done shift $((OPTIND - 1)) if [ -z "$res_per_chain" ]; then echo "-r res_per_chain is mandatory: must be integer greater than 1" echo "$usage" >&2 exit 1 fi
{ "domain": "codereview.stackexchange", "id": 45030, "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": "beginner, bash", "url": null }
beginner, bash if [ -z "$path_to_cccp_bundles" ]; then echo "-r path_to_cccp_bundles is mandatory" echo "$usage" >&2 exit 1 fi if [ "$res_per_chain" -le 0 ]; then echo "-r res_per_chain is mandatory: must be integer greater than 1" echo "$usage" >&2 exit 1 fi if [ "$_VERBOSE" != 0 ] && [ "$_VERBOSE" != 1 ]; then echo "-v _VERBOSE must be either 0 for outputting messages or 1 for silent" echo "$usage" >&2 exit 1 fi # ------------------------------------------------------------------- CONSTANTS # --- temp files tmpfile="$(mktemp)" phnxtmp=phenix.out # ------------------------------------------------------------------- LOG # --- log function for verbose mode output log () { if [[ $_VERBOSE -eq 0 ]]; then echo "$@" fi } # ------------------------------------------------------------------- FUNCTIONS # --- extract first character from string and return capitalised res_one_letter_cap () { abbrev=$(printf %.1s "$1") Abbrev="${abbrev^}" echo "$Abbrev" } # --- write Rosetta residue file for all Ala or Gly write_resfiles () { res_abbrev=$(res_one_letter_cap "$1") file_name="all_${1}_resfile.res" rm -f "$file_name" # appends if exists) printf $"PIKAA %s\nstart" "$res_abbrev" >> "$file_name" log "@>> finished writing $1 resfile" }
{ "domain": "codereview.stackexchange", "id": 45030, "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": "beginner, bash", "url": null }
beginner, bash # --- execute Rosetta fix backbone to add side chains and hydrogen's exe_Rosetta_fixbb () { fullpdbpath="$path_to_cccp_bundles"/"$cccp_sep${1}"/ numfiles=$(find "$fullpdbpath" | wc -l) i=0 SECONDS=0 for pdb in "$fullpdbpath"*.pdb; do ((i++)) filename="${pdb##*/}" log "@>> starting Rosetta fixbb for $filename ($i/$(( numfiles - 1 )))" fixbb.default.linuxgccrelease -s "$pdb" -resfile \ ../all_"${1}"_resfile.res -nstruct 1 -ex1 -ex2 -database \ "$ROSETTA3_DB" > /dev/null log "@>> finished Rosetta fixbb for $filename" done DURATION=$SECONDS log "@>> Rosetta fixbb for $1 finished in ~$DURATION seconds" } # --- run Rosetta fixed backbone scripts run_Rosetta_fixbb () { create_and_cd ./poly_"${1}" && exe_Rosetta_fixbb "$1" && \ rm score.sc && cd ../ || exit } # --- rename the Rosetta output PDBs to more readable ones in the form # --- 'ala_0001.pdb', 'gly_0064' etc rename_pdbs () { log "@>> renaming ${1} pdbs" f=0 for pdb in ./poly_"${1}"/*.pdb; do ((++f)) # increment first or it doesn't work ext="${pdb##*.}" printf -v j "%04d" "$f" # pad the int to 4 d.p. i.e. 12 -> 0012 filename="${1}_${j}" mv "$pdb" ./poly_"${1}"/"${filename}"."$ext" # need to include rel path log "@>> finished renaming ${pdb} to ${filename}.${ext}" done log "@>> finished renaming ${1} pdbs" }
{ "domain": "codereview.stackexchange", "id": 45030, "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": "beginner, bash", "url": null }
beginner, bash # --- remove TER lines so chains are continuous, change all chains to 'A' or # --- user input value and set segment ID to 'A' or user value mod_segment_ter_chainid () { # remove TER lines log "@>> removing TER lines" sed -i "/TER/d" $phnxtmp # change chain to A log "@>> changing chains to $chainID" awk '{print substr($0,1,21) v substr($0,23)}' v="$chainID" $phnxtmp\ > "$tmpfile" && mv "$tmpfile" $phnxtmp # to add $segID as segment log "@>> changing segment IDs to $segID" awk '{print substr($0,1,75) v substr($0,76)}' v="$segID" $phnxtmp \ > "$tmpfile" && mv "$tmpfile" $phnxtmp } # --- increment the residue sequences of chains that are not A so that they # --- can be merged into one chain with discontinuities chain_resseq_mod () { read -ra chain_ar <<<"$chains" && len_chains=${#chain_ar[@]} && i=1 || exit while [ $i -le $((len_chains - 1)) ]; do log "@>> modifying sequence for chain ${chain_ar[$i]}" inc_resseq=$((i * res_per_chain)) phenix.pdbtools $phnxtmp modify.selection="chain ${chain_ar[$i]}" \ increment_resseq=$inc_resseq output.filename=$phnxtmp > /dev/null ((i++)) done } # --- clear the segment IDs (set as chain ID by default with the CCCP server) # --- so that they can be easily set later on, this may be redundant TODO clear_segid () { phenix.pdbtools "$1" clear_seg_id=true \ output.filename=$phnxtmp > /dev/null }
{ "domain": "codereview.stackexchange", "id": 45030, "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": "beginner, bash", "url": null }
beginner, bash # --- main function to run phenix operations run_phenix () { create_and_cd ../phenix/ for file in ../Rosetta/poly_"${res}"/*.pdb; do mkdir -p ../templates/poly_"${res}" filename="${file##*/}" cp "$file" "$filename" log "@>> clearing segment ID for $filename" clear_segid "$filename" log "@>> modifying sequence IDs for $filename" chain_resseq_mod log "@>> modifying chain IDs, segments and removing ter for $filename" mod_segment_ter_chainid log "@>> finished $filename" mv $phnxtmp ../templates/poly_"${res}"/"$filename" rm "$filename" done } # --- create directory and change to it create_and_cd () { mkdir -p "$1"; cd "$1" } # ------------------------------------------------------------------- MAIN # --- output system information to the terminal, if unwanted then comment out date=$(date '+%Y-%m-%d %H:%M:%S') kernal_v=$(uname -a) log "" log "${date}" log "${kernal_v}" log "Bash version ${BASH_VERSINFO[*]}" log "" log "@>> --- Starting CCCP bundle modifications" # --- main loop create_and_cd ./Rosetta for res in $residues; do log "@>> writing resfile for $res" write_resfiles "$res" log "@>> starting Rosetta fixed backbone for $res" run_Rosetta_fixbb "$res" log "@>> starting renaming PDBs for $res" rename_pdbs "$res" log "@>> starting phenix modifications for $res" run_phenix "$res" log "@>> finished all modifications for $res" cd ../Rosetta done # --- remove the working folders cd ../ && rm -rf ./{phenix,Rosetta} log "@>> --- Finished CCCP bundle modifications" log ""
{ "domain": "codereview.stackexchange", "id": 45030, "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": "beginner, bash", "url": null }
beginner, bash log "@>> --- Finished CCCP bundle modifications" log "" When running on my system, the command output is given as (on the GitHub repo: /example/output/command_line.txt): (base) username@username-Aspire-A315-51:~/Desktop/template_mods$ source ~/set_Phenix.sh (base) username@username-Aspire-A315-51:~/Desktop/template_mods$ source ~/set_Rosetta.sh (base) username@username-Aspire-A315-51:~/Desktop/template_mods$ bash modify_cccp_bundles.sh modify_cccp_bundles.sh [-h] [-s A] [-z 'A B'] [-c A] [-e 'poly-'] [-a 'ala gly'] -p PATH -r INT Modify CCCP generated server bundles. arguments: -p full path to CCCP bundle directory (mandatory: str) -r residues per chain (mandatory: int) -s set segment ID to value (default: 'A') -z chains list (default: 'A B C D') -c set all chain IDs to value (default: 'A') -e dir separator in CCCP dir i.e. poly-, poly_ (default: 'poly-') -a residue names list (default: 'ala gly') -v output logging to screen, must be either 0 for output (default) or 1 -h show this help message (base) username@username-Aspire-A315-51:~/Desktop/template_mods$ bash modify_cccp_bundles.sh -p "/home/username/Desktop/CCCP" -r 28 -s A -z 'A B C D' -c A -e 'poly-' -a 'ala gly' -v 0 2023-07-01 09:26:54 Linux username-Aspire-A315-51 5.15.0-76-generic #83-Ubuntu SMP Thu Jun 15 19:16:32 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux Bash version 5 1 16 1 release x86_64-pc-linux-gnu
{ "domain": "codereview.stackexchange", "id": 45030, "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": "beginner, bash", "url": null }
beginner, bash @>> --- Starting CCCP bundle modifications @>> writing resfile for ala @>> finished writing ala resfile @>> starting rosetta fixed backbone for ala @>> starting rosetta fixbb for 00001.396f8ee2d646.allbb_ala.pdb (1/2) @>> finished rosetta fixbb for 00001.396f8ee2d646.allbb_ala.pdb @>> starting rosetta fixbb for 00002.396f8ee2d646.allbb_ala.pdb (2/2) @>> finished rosetta fixbb for 00002.396f8ee2d646.allbb_ala.pdb @>> rosetta fixbb for ala finished in ~14 seconds @>> starting renaming PDBs for ala @>> renaming ala pdbs @>> finished renaming ./poly_ala/00001.396f8ee2d646.allbb_ala_0001.pdb to ala_0001.pdb @>> finished renaming ./poly_ala/00002.396f8ee2d646.allbb_ala_0001.pdb to ala_0002.pdb @>> finished renaming ala pdbs @>> starting phenix modifications for ala @>> clearing segment ID for ala_0001.pdb @>> modifying sequence IDs for ala_0001.pdb @>> modifying sequence for chain B @>> modifying sequence for chain C @>> modifying sequence for chain D @>> modifying chain IDs, segments and removing ter for ala_0001.pdb @>> removing TER lines @>> changing chains to A @>> changing segment IDs to A @>> finished ala_0001.pdb @>> clearing segment ID for ala_0002.pdb @>> modifying sequence IDs for ala_0002.pdb @>> modifying sequence for chain B @>> modifying sequence for chain C @>> modifying sequence for chain D @>> modifying chain IDs, segments and removing ter for ala_0002.pdb @>> removing TER lines @>> changing chains to A @>> changing segment IDs to A @>> finished ala_0002.pdb @>> finished all modifications for ala @>> writing resfile for gly @>> finished writing gly resfile @>> starting rosetta fixed backbone for gly @>> starting rosetta fixbb for 00001.396f8ee2d646.allbb.pdb (1/2) @>> finished rosetta fixbb for 00001.396f8ee2d646.allbb.pdb @>> starting rosetta fixbb for 00002.396f8ee2d646.allbb.pdb (2/2) @>> finished rosetta fixbb for 00002.396f8ee2d646.allbb.pdb @>> rosetta fixbb for gly finished in ~13 seconds @>> starting renaming PDBs for gly @>> renaming gly pdbs
{ "domain": "codereview.stackexchange", "id": 45030, "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": "beginner, bash", "url": null }
beginner, bash @>> starting renaming PDBs for gly @>> renaming gly pdbs @>> finished renaming ./poly_gly/00001.396f8ee2d646.allbb_0001.pdb to gly_0001.pdb @>> finished renaming ./poly_gly/00002.396f8ee2d646.allbb_0001.pdb to gly_0002.pdb @>> finished renaming gly pdbs @>> starting phenix modifications for gly @>> clearing segment ID for gly_0001.pdb @>> modifying sequence IDs for gly_0001.pdb @>> modifying sequence for chain B @>> modifying sequence for chain C @>> modifying sequence for chain D @>> modifying chain IDs, segments and removing ter for gly_0001.pdb @>> removing TER lines @>> changing chains to A @>> changing segment IDs to A @>> finished gly_0001.pdb @>> clearing segment ID for gly_0002.pdb @>> modifying sequence IDs for gly_0002.pdb @>> modifying sequence for chain B @>> modifying sequence for chain C @>> modifying sequence for chain D @>> modifying chain IDs, segments and removing ter for gly_0002.pdb @>> removing TER lines @>> changing chains to A @>> changing segment IDs to A @>> finished gly_0002.pdb @>> finished all modifications for gly @>> --- Finished CCCP bundle modifications
{ "domain": "codereview.stackexchange", "id": 45030, "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": "beginner, bash", "url": null }
beginner, bash (base) username@username-Aspire-A315-51:~/Desktop/template_mods$ How can I further improve this script so that I can apply it to future projects too please? I am quite happy to go from beginner to my first bash GitHub repo pretty quickly and I look forward to uploading more. Answer: Use local variables inside functions It's a good practice to declare local variables inside functions using the local keyword, so you don't accidentally overwrite variables in the global namespace. Adopting this practice early can help avoiding frustration later. Do not use ALL_CAPS for local variables It's recommended to avoid ALL_CAPS variable names because they may be used by system environment variables. An interesting case in this script is the SECONDS variable, which is used by Bash (see man bash, search for "SECONDS"). This variable should have been named simply seconds, and declared local. Double-quote variables used on the command line Almost everywhere the script correctly does this, except many uses of the $phnxtmp variables, for example: sed -i "/TER/d" $phnxtmp Should be: sed -i "/TER/d" "$phnxtmp" It seems shellcheck didn't flag this because the variable is defined as phnxtmp=phenix.out, so it's technically safe, for now. If ever the definition of phnxtmp changes in a way that it may contain spaces, the script will break. As unlikely as this may seem, I suggest to stick to good principles, and always double quote variables used as command parameters. Avoid unnecessary computations Instead of: while [ "$i" -le $((len_chains - 1)) ]; This is equivalent and simpler: while [ "$i" -lt "$len_chains" ]; An even simpler way is to use arithmetic context: while ((i < len_chains)); Use consistent naming for variables Some variables use snake_case, some don't:
{ "domain": "codereview.stackexchange", "id": 45030, "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": "beginner, bash", "url": null }
beginner, bash Use consistent naming for variables Some variables use snake_case, some don't: segID="A" # segment ID chains='A B C D' # chains existing in the CCCP bundles chainID="A" # chain ID to change the other chains to cccp_sep="poly-" # CCCP server creates folders with poly-ala, can rename dirs I recommend renaming segID to seg_id, and chainID to chain_id. Print error messages to stderr In some places the script prints messages to stdout before an exit 1. These look like error messages, and as such it's recommended to print them to stderr instead, as you've done in many other places. Passing shellcheck The code passes shellcheck with no issues and is as follows: Not this one: while [ $i -le $((len_chains - 1)) ]; Should be: while [ "$i" -le $((len_chains - 1)) ];
{ "domain": "codereview.stackexchange", "id": 45030, "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": "beginner, bash", "url": null }
beginner, bash while [ $i -le $((len_chains - 1)) ]; Should be: while [ "$i" -le $((len_chains - 1)) ]; Avoid cd inside scripts At several points, the script enters some directory with cd, does some work, then finally does cd ... This is generally fragile, because it's easy to forget the cd .., and the directory changes can also lead to confusion when debugging. One solution is to change the logic to work with a directory parameter. For example one way to get the list of files of a directory foo is cd foo; ls, and another way is ls foo. Same output, without changing directories. When it's too complex to make the logic work with a directory parameter, a robust though expensive alternative is to perform the logic in a (...) subshell, going with the previous example, (cd foo; ls). This is expensive because subshells have a cost, which could become visible when used in a loop, otherwise it should be negligible. Beware of GNU and BSD differences Some common commands behave slightly differently in GNU and BSD environments, for example sed and awk. If you want your script to work everywhere, it's good to be aware of the differences, and ideally run tests in both. Notably this script uses sed -i "/TER/d" $phnxtmp, which would need a bit of massaging to make it work in BSD. Since the following lines in the script modify the file using the good old fashioned pattern of redirecting to a temp file and then renaming back to the original, I suggest to avoid the -i flag and use the same good old method, as an easy way to keep the script portable. Nitpicks These are nitpicks, from top to bottom, not big issues. Instead of set -u -e -o pipefail, I use the idiom set -euo pipefail. A ; at the end of lines is unnecessary: while getopts ':hs:z:c:e:a:p:r:v:' option; do I recommend either: while getopts ':hs:z:c:e:a:p:r:v:' option; do Or: while getopts ':hs:z:c:e:a:p:r:v:' option do In other places too in the code. In the usage message, I suggest to capitalize "arguments:".
{ "domain": "codereview.stackexchange", "id": 45030, "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": "beginner, bash", "url": null }
beginner, bash In other places too in the code. In the usage message, I suggest to capitalize "arguments:". You could drop the outermost double-quotes in this assignment, they are unnecessary: usage="$(basename "$0") [-h] [-s A] [-z 'A B'] [-c A] [-e 'poly-'] [-a 'ala gly'] -p PATH -r INT The double-quotes around "$0" are perfect, the way it should be. Another example of unnecessary double-quotes: tmpfile="$(mktemp)" Instead of ${#}, I recommend using simply $#. Somewhat similarly, instead of ../all_"${1}"_resfile.res I would write either: ../all_"$1"_resfile.res "../all_${1}_resfile.res" When breaking a long line to multiple lines as here: fixbb.default.linuxgccrelease -s "$pdb" -resfile \ ../all_"${1}"_resfile.res -nstruct 1 -ex1 -ex2 -database \ "$ROSETTA3_DB" > /dev/null I recommend indenting the continuation lines for clarity: fixbb.default.linuxgccrelease -s "$pdb" -resfile \ ../all_"${1}"_resfile.res -nstruct 1 -ex1 -ex2 -database \ "$ROSETTA3_DB" > /dev/null
{ "domain": "codereview.stackexchange", "id": 45030, "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": "beginner, bash", "url": null }
console, linux, sh, installer Title: Interactive Linux upgrade script - Follow-up #1 Question: One year ago I asked for a yearly revision of my Interactive Linux upgrade script. There is nothing new to the conditions, therefore please read the original question before you decide to comment and / or vote to close as unclear. Additional notes: The script will always run interactively as I want to have full control. The script will be placed on 3 machines only, so I don't need much of generalization. As my POSIX shell scripting abilities get better, I would very much like to get further incentives. Edited slightly to avoid echo and to provide some information about the system and hardware. You can answer my original question if you are already in progress of writing it. No problem with that. #!/bin/sh set -o nounset # friendly computer description readonly computer_description='Vlasta - Laptop - Main' # color definitions readonly bold=$(tput bold) readonly bold_red=${bold}$(tput setaf 1) readonly bold_green=${bold}$(tput setaf 2) readonly bold_yellow=${bold}$(tput setaf 3) readonly bold_blue=${bold}$(tput setaf 4) readonly bold_magenta=${bold}$(tput setaf 5) readonly bold_cyan=${bold}$(tput setaf 6) readonly bold_white=${bold}$(tput setaf 7) readonly nocolor=$(tput sgr0) # to create clear blocks of texts, we separate them with this readonly block_separator='----------------------------------------' step_number=0 execute_jobs() { # process the given arguments as pairs while [ "${#}" -gt 1 ] do # increase and print the step number along with description step_number=$((step_number + 1)) printf '%s\n' "Step #${step_number}: ${bold_green}${1}${nocolor}" # print the command to be run printf '%s\n' "Command: ${bold_yellow}${2}${nocolor}" printf '%s\n' "${bold_white}${block_separator}${nocolor}"
{ "domain": "codereview.stackexchange", "id": 45031, "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": "console, linux, sh, installer", "url": null }
console, linux, sh, installer printf '%s\n' "${bold_white}${block_separator}${nocolor}" # run the actual command # ShellCheck mistakenly things we should double quote the parameter # if we did, it would become a string and we'd get command not found # shellcheck disable=SC2086 if sudo ${2} then printf '\n' else printf '%s\n\n' "${bold_red}An error occurred.${nocolor}" exit 1 fi # move to another pair of arguments shift 2 done } distro_name=$(lsb_release --id | awk '{ print $3 }') release_version=$(lsb_release --release | awk '{ print $2 }') hostname=$(cat /etc/hostname) printf '\n%s\n' "Friendly: ${bold_magenta}${computer_description}${nocolor}" printf '%s\n' "Distro : ${bold_magenta}${distro_name} ${release_version}${nocolor}" printf '%s\n' "Hostname: ${bold_magenta}${hostname}${nocolor}" printf '%s\n\n' "${bold_white}${block_separator}${nocolor}" # the sudo password request shall proceed AFTER computer / hostname # this is because the same script will always run in sequence on 3 computers if [ "$(id --user)" -ne 0 ] then sudo sh -c ":" || exit 1 fi printf '%s' "${bold_cyan}" sudo dmidecode --type 1 | grep 'System Information' --after 8 printf '%s\n\n' "${bold_white}${block_separator}${nocolor}" # execute all jobs in one go execute_jobs \ 'configure packages' 'dpkg --configure --pending' \ 'fix broken dependencies' 'apt-get --fix-broken install' \ 'update cache' 'apt-get update' \ 'upgrade packages' 'apt-get upgrade' \ 'upgrade packages with possible removals' 'apt-get dist-upgrade' \ 'remove unused packages' 'apt-get --purge autoremove' \ 'clean up old packages' 'apt-get autoclean' Answer: This looks pretty good already, I don't have anything major to add, only some ideas:
{ "domain": "codereview.stackexchange", "id": 45031, "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": "console, linux, sh, installer", "url": null }
console, linux, sh, installer Answer: This looks pretty good already, I don't have anything major to add, only some ideas: POSIX only supports short options. If a command and its short options are defined in the POSIX specifications, e.g. id -u, always adhere to the short options usage. It's a good idea to use the long options otherwise. You could test for the existence of all utilities not found in the POSIX specifications and fail early if any were not executable. Maybe wrap this inside a exec_non_posix_command function? The challenge is in checking for the options also. Your method of getting the distro name and release version is fine. A shorter way is distro_release=$(lsb_release --id --release --short | xargs), but I can't vouch for its robustness, as I don't know if the --short option is supported from the very first version of lsb_release and if the inherent assumption about the distributor ID and release ordering wouldn't be violated.
{ "domain": "codereview.stackexchange", "id": 45031, "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": "console, linux, sh, installer", "url": null }
template, c++20, constructor Title: in_place_constructor helper type Question: recently I implemented a little helper class, which can be primarily utilized on perfect forwarding constructors. Introduction As a slight example, let me pull in two of the std::pair constructors: template< class U1, class U2 > constexpr pair( U1&& x, U2&& y ); // (1) template< class... Args1, class... Args2 > constexpr pair( std::piecewise_construct_t, std::tuple<Args1...> first_args, std::tuple<Args2...> second_args ); // (2) see: cppreference.com You have the choice to either construct your first/second manually in forehand, or you have to provide the std::piecewise_construct tag object and must wrap the arguments in a tuple. Given the immobile neither copy- nor movable type: template <class... Ts> class immobile { public: ~immobile() = default; immobile(const immobile&) = delete; immobile& operator =(const immobile&) = delete; immobile(immobile&&) = delete; immobile& operator =(immobile&&) = delete; template <class... Args> requires std::constructible_from<std::tuple<Ts...>, Args...> explicit immobile(Args&&... args) : value{std::forward<Args>(args)...} { } std::tuple<Ts...> value; }; We can not use the (1) of the pair constructor - we have to use the second one: std::pair<immobile<std::string, int>, int> p1(immobile<std::string, int>{"Hello, World!", 1337}, 42); // error std::pair<immobile<std::string, int>, int> p2{std::piecewise_construct, std::tuple{"Hello, World!", 1337}, std::tuple{42}};
{ "domain": "codereview.stackexchange", "id": 45032, "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": "template, c++20, constructor", "url": null }
template, c++20, constructor This is noisy and we have to explicitly wrap our arguments as tuples and most importantly: There is absolutely no benefit for the int member to provide the argument as a tuple. Solution I would like to have the choice to individually provide the arguments of the pair elements and get rid of that std::piecewise_construct. I came up with that little helper class: namespace sl { template <class Type, class... Args> requires std::same_as<Type, std::remove_cvref_t<Type>> && std::constructible_from<Type, Args...> struct in_place_constructor { public: in_place_constructor(const in_place_constructor&) = delete; in_place_constructor& operator =(const in_place_constructor&) = delete; in_place_constructor(in_place_constructor&&) = delete; in_place_constructor& operator =(in_place_constructor&&) = delete; ~in_place_constructor() = default; [[nodiscard]] in_place_constructor() = default; [[nodiscard]] constexpr operator Type() && noexcept(std::is_nothrow_constructible_v<Type, Args...>) { return std::make_from_tuple<Type>(std::move(m_Args)); } template <class T, class... Ts> friend constexpr auto in_place(Ts&&... args) noexcept; private: std::tuple<Args...> m_Args; [[nodiscard]] explicit constexpr in_place_constructor(std::tuple<Args...>&& args) noexcept : m_Args{std::move(args)} { } }; template <class Type, class... Args> [[nodiscard]] constexpr auto in_place(Args&&... args) noexcept { return in_place_constructor<Type, Args&&...>{std::forward_as_tuple(std::forward<Args>(args)...)}; } } which let me rewrite the initialization from above as: std::pair<immobile<std::string, int>, int> p3{sl::in_place<immobile<std::string, int>>("Hello, World!", 1337), 42};
{ "domain": "codereview.stackexchange", "id": 45032, "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": "template, c++20, constructor", "url": null }
template, c++20, constructor But wait, there is more! Explicitly expecting in_place_constructor as ctor argument Custom classes can utilize that helper type for themselves and expecting that as one or multiple constructor arguments. For example: template <class T1, class T2, class T3> class MultiInPlaceExpecting { public: template <class... T1s, class... T2s, class... T3s> explicit MultiInPlaceExpecting( sl::in_place_constructor<T1, T1s...>&& args1, sl::in_place_constructor<T2, T2s...>&& args2, sl::in_place_constructor<T3, T3s...>&& args3) : value1{std::move(args1)}, value2{std::move(args2)}, value3{std::move(args3)} { } T1 value1; T2 value2; T3 value3; }; const MultiInPlaceExpecting<std::optional<int>, std::string, int> obj{ sl::in_place<std::optional<int>>(1337), {}, // default ctor {} // default ctor }; // CTAD! const MultiInPlaceExpecting obj{ sl::in_place<std::optional<int>>(1337), sl::in_place<std::string>("Hello, World!"), sl::in_place<int>(42)}; Questions Even if I'm quite hyped about my solution, I'm a bit afraid, that I missed something important. I explicitly deleted the copy and move ctors/assignments, enable the converting operator only for rvalue-refs and generally do not see much room, where it could go heavily wrong. The second question is: Is that the best I can do? Or is there anything I can improve? If you want to play around, I setup a godbolt project including some test cases: https://godbolt.org/ Thanks for your time, greetings Dominic Answer: Making better use of existing functionality You can in fact use the first form of std::pair's constructor to create a pair where one or both members are immobile. You just have to pass it something that is not immobile that can be used to construct the immobile member(s), and specify std::pair's template parameters explicitly: std::pair<immobile<std::string, int>, int> p1{std::tuple<std::string, int>{"Hello, World!", 1337}, 42};
{ "domain": "codereview.stackexchange", "id": 45032, "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": "template, c++20, constructor", "url": null }
template, c++20, constructor This is shorter than your declaration of p3. Your objection against the second form of std::pair's constructor is that it is too noisy. But you are merely replacing std::piecewise_construct with sl::in_place</* repeated type name */>, which I think is also noisy, and is not even that much shorter. Consider instead that you can create an abbreviation for std::piecewise_construct: constexpr auto pwc = std::piecewise_construct; … std::pair<immobile<std::string, int>, int> p2{pwc, std::tuple{"Hello, World!", 1337}, std::tuple{42}}; That's just one byte longer than the non-compiling definition of p1! Avoid having to repeat type names Your class sl::in_place_constructor needs to know Type at construction time. So sl::in_place() also needs to know Type. But this requires you to repeat the type name of the pair member. It would be nice if this could be avoided. Note that Type is only really necessary when calling the conversion operator. But when a conversion operator is called, the caller already knows what it wants to convert to... so could we let Type be deduced automatically? Let's make the conversion operator a template: template <class... Args> struct in_place_constructor { … template<typename Type> [[nodiscard]] constexpr operator Type() && noexcept(std::is_nothrow_constructible_v<Type, Args...>) { return std::make_from_tuple<Type>(std::move(m_Args)); } template <class... Args> friend constexpr auto in_place(Args&&... args); private: … [[nodiscard]] explicit constexpr in_place_constructor(std::tuple<Args...>&& args) : m_Args{std::move(args)} { } }; template <class... Args> [[nodiscard]] constexpr auto in_place(Args&&... args) { return in_place_constructor<Args&&...>{std::forward_as_tuple(std::forward<Args>(args)...)}; } Now you can write: std::pair<immobile<std::string, int>, int> p3{sl::in_place("Hello, World!", 1337), 42};
{ "domain": "codereview.stackexchange", "id": 45032, "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": "template, c++20, constructor", "url": null }
template, c++20, constructor Incorrect use of noexcept Be careful with noexcept: only use it when you are absolutely sure that nothing can throw. Moving arguments into a tuple? Depending on the types of the arguments, that can certainly happen. Either make noexcept conditional, or just remove it entirely: consider that none of std::pair and std::tuple's constructors are noexcept either.
{ "domain": "codereview.stackexchange", "id": 45032, "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": "template, c++20, constructor", "url": null }
python, performance, python-3.x, numpy, image Title: NumPy script to convert BGR to HSL and back Question: This is a NumPy script that converts BGR arrays to HSL arrays and back, without using OpenCV. Input and output values are arrays of 3 dimensions with values ranging from 0 to 1, the shape of the arrays are (height, width, 3) and the data type is float. I will use it in my GUI program, to implement non-separable blend modes, I have implemented 24 separable blend modes, I posted them on GitHub, I implemented them because I haven't found them in cv2. I implemented them according to this, this, this, and PhotoshopMathFP.glsl . I didn't use cv2.cvtColor(img, cv2.COLOR_BGR2HLS_FULL) because all my image operations are in float domain. I implemented all the code entirely by myself, without outside help, I haven't used a single if statement in actual computation, except for one that checks whether further operations are needed, everything is done using boolean masks, and I made the code as efficient as I can make it. I ported the code from PhotoshopMathFP.glsl to NumPy, that is all. Code import numpy as np from typing import Tuple def BGR_to_HSL_saturation_1( hsl: np.ndarray, mina: np.ndarray, maxa: np.ndarray, delta: np.ndarray, ) -> np.ndarray: quotient = np.ones(shape=hsl.shape[:2], dtype=float) safe = (mina != 0) | (maxa != 0) quotient[safe] = delta[safe] / (mina[safe] + maxa[safe]) return np.clip(quotient, 0, 1) def BGR_to_HSL_saturation_2( hsl: np.ndarray, mina: np.ndarray, maxa: np.ndarray, delta: np.ndarray, ) -> np.ndarray: quotient = np.ones(shape=hsl.shape[:2], dtype=float) safe = mina + maxa < 2 quotient[safe] = delta[safe] / (2 - mina[safe] - maxa[safe]) return np.clip(quotient, 0, 1)
{ "domain": "codereview.stackexchange", "id": 45033, "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, performance, python-3.x, numpy, image", "url": null }
python, performance, python-3.x, numpy, image def BGR_to_HSL_helper_1( hsl: np.ndarray, mina: np.ndarray, maxa: np.ndarray, delta: np.ndarray, mask: np.ndarray, ) -> np.ndarray: more = ~(less := hsl[..., 2] < 0.5) & mask less &= mask hsl[..., 1][less] = BGR_to_HSL_saturation_1(hsl, mina, maxa, delta)[less] hsl[..., 1][more] = BGR_to_HSL_saturation_2(hsl, mina, maxa, delta)[more] return hsl def BGR_to_HSL_delta( delta: np.ndarray, hsl: np.ndarray, img: np.ndarray, maxa: np.ndarray ) -> np.ndarray: ndelta = np.ones_like(hsl) safe = delta != 0 delta = delta[safe, np.newaxis] ndelta[safe] = ((maxa[safe, np.newaxis] - img[safe]) / 6 + delta / 2) / delta return ndelta def BGR_to_HSL_helper_2( hsl: np.ndarray, img: np.ndarray, maxa: np.ndarray, delta: np.ndarray, mask: np.ndarray, ) -> np.ndarray: delta = BGR_to_HSL_delta(delta, hsl, img, maxa) maxi = img == maxa[..., np.newaxis] for index, offset, color_a, color_b in ( (0, 2 / 3, 1, 2), (1, 1 / 3, 2, 0), (2, 0, 0, 1), ): maski = maxi[..., index] & mask hsl[..., 0][maski] = (offset + delta[..., color_a] - delta[..., color_b])[maski] hsl[..., 0] %= 1 return hsl def BGR_to_HSL(img: np.ndarray) -> np.ndarray: delta = (maxa := img.max(axis=-1)) - (mina := img.min(axis=-1)) hsl = np.zeros_like(img) hsl[..., 2] = (maxa + mina) / 2 mask = delta != 0.0 if mask.any(): hsl = BGR_to_HSL_helper_1(hsl, mina, maxa, delta, mask) hsl = BGR_to_HSL_helper_2(hsl, img, maxa, delta, mask) return hsl
{ "domain": "codereview.stackexchange", "id": 45033, "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, performance, python-3.x, numpy, image", "url": null }
python, performance, python-3.x, numpy, image def Hue_to_color(f1: np.ndarray, f2: np.ndarray, hue: np.ndarray) -> np.ndarray: hue %= 1 color = np.zeros_like(hue) gmask = mask = hue < 2 / 3 color[mask] = (f1 + (delta := f2 - f1) * (2 / 3 - hue) * 6)[mask] gmask |= (mask := hue < 0.5) color[mask] = f2[mask] gmask |= (mask := hue < 1 / 6) color[mask] = (f1 + delta * 6 * hue)[mask] mask = ~gmask color[mask] = f1[mask] return color def HSL_to_BGR_helper(hsl: np.ndarray) -> Tuple[np.ndarray]: bgr = np.zeros_like(hsl) empty = (y := hsl[..., 1]) == 0 bgr[empty] = np.dstack([z := hsl[..., 2]] * 3)[empty] f2 = np.zeros_like(y) mask = (less := z < 0.5) & (full := ~empty) f2[mask] = (z * (1 + y))[mask] mask = ~less & full f2[mask] = (y + z - y * z)[mask] f1 = 2 * z - f2 return bgr, f1, f2, full def HSL_to_BGR(hsl: np.ndarray) -> np.ndarray: bgr, f1, f2, full = HSL_to_BGR_helper(hsl) bgr[..., 0][full] = Hue_to_color(f1, f2, (x := hsl[..., 0]) - 1 / 3)[full] bgr[..., 1][full] = Hue_to_color(f1, f2, x)[full] bgr[..., 2][full] = Hue_to_color(f1, f2, x + 1 / 3)[full] return bgr if __name__ == "__main__": import cv2
{ "domain": "codereview.stackexchange", "id": 45033, "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, performance, python-3.x, numpy, image", "url": null }