text
stringlengths
1
2.12k
source
dict
c++, concurrency The unnamed temporary lock_guard’s destructor runs at the next semicolon. If you don’t actually have a shared mutable resource, you don’t need the mutex. If task_infos.size() > SIZE_MAX - threads_count the index i overlfows/wraps because task_index is incremented once for each task_info (loop condition is true) plus one additional time for each thread (loop condition false). Unless threads_count is unreasonably big or you have a gigantic number of task_infos, this won’t be a problem, but if it might be, it must be mitigated by fetch_adding manually: auto process = [&task_index, &task_infos, &mutex] { for (std::size_t i{}; i < task_infos.size(); ) { if (task_index.compare_exchange_weak(i, i + 1, std::memory_order_relaxed)) execute_task(task_infos[i], mutex); } }; compare_exchange_weak is the crucial part: It compares task_index and i; if they’re equal, sets task_index to i + 1 (i.e. increments it) and returns true; else, it sets i to the current value of task_index and returns false. In our case, a return value of true, i.e. a successful increment, means that this thread has won the race for i and will perform the corresponding task. A return value of false sets i to a new value, which can be of one of two categories: An index to “bargain for” or task_infos.size(). If it is the latter, the for loop condition will fail and this thread stops doing tasks. Otherwise, it’s compare_exchange_weak again, but with the new i. About the “weak” part, it means that compare_exchange_weak is allowed return false (and not update task_index) even if i and task_index are equal (it may “spuriously fail” in technical terms). Because that is fine in our case, compare_exchange_strong is not needed. Is my reasoning in all of this correct?
{ "domain": "codereview.stackexchange", "id": 44658, "lm_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++, concurrency", "url": null }
c++, concurrency Answer: Turn the pattern into a generic function Your process_in_parallel() function only works with one specific task_info type and one execute_task() function. If you had different kinds of tasks to perform, you'd have to create multiple functions like process_in_parallel() as well. But in C++ we can avoid that by making process_in_parallel() a template: template<typename TaskInfo, typename Executor> void process_in_parallel( std::vector<TaskInfo> task_infos, Executor execute_task, std::size_t threads_count = std::thread::hardware_concurrency() ) { … } The standard library already provides this functionality Since C++17 the standard library provides parallel versions of many of the standard algorithms. For example, you can write: class task_info {…}; void execute_task(task_info); std::vector<task_info> tasks; std::for_each(std::execution::par, tasks.begin(), tasks.end(), execute_task); If you need a mutex as well, then you could have it as a global variable, or use lambda expressions to pass a mutex: void execute_task(task_info, std::mutex&); … std::mutex mutex; std::for_each(std::execution::par, tasks.begin(), tasks.end(), [&mutex](auto& task_info){ execute_task(task_info, mutex); });
{ "domain": "codereview.stackexchange", "id": 44658, "lm_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++, concurrency", "url": null }
c++, error-handling, concurrency, c++20, atomic Title: atomic spinlock mutex class Question: This here is the follow-up to this question. I was recommended to implement a Lockable type (similar to std::mutex) that can work with std::lock_guard, std::scoped_lock, etc. instead of unnecessarily writing a class similar to std::lock_guard (thus violating D.R.Y). The result is a class named spinlock_mutex. The below example snippet is very similar to what I'm trying to do in my multithreaded program. The new MRE (live): #include <atomic> #include <mutex> #include <thread> #include <stop_token> #include <vector> #include <array> #include <exception> #include <fmt/core.h> namespace util { class [[ nodiscard ]] spinlock_mutex { public: using lockable_type = std::atomic_flag; [[ nodiscard ]] constexpr spinlock_mutex( ) noexcept = default; spinlock_mutex( const spinlock_mutex& ) noexcept = delete; spinlock_mutex& operator=( const spinlock_mutex& ) noexcept = delete; void lock( ) noexcept { while ( m_lockable.test_and_set( std::memory_order_acquire ) ) { while ( m_lockable.test( std::memory_order_relaxed ) ) { } } } bool try_lock( ) noexcept { return m_lockable.test_and_set( std::memory_order_acquire ); } void unlock( ) noexcept { m_lockable.clear( std::memory_order_release ); } private: lockable_type m_lockable { }; }; } constinit util::spinlock_mutex mtx { }; constinit std::vector<std::exception_ptr> caught_exceptions { };
{ "domain": "codereview.stackexchange", "id": 44659, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, error-handling, concurrency, c++20, atomic", "url": null }
c++, error-handling, concurrency, c++20, atomic void func( const std::stop_source stop_src, const int base_value ) noexcept { for ( auto counter { 0uz }; !stop_src.stop_requested( ) && counter < 3; ++counter ) { try { fmt::print( "base value: {} --- {}\n", base_value, counter + static_cast<decltype( counter )>( base_value ) ); } catch ( ... ) { stop_src.request_stop( ); const std::lock_guard lock { mtx }; caught_exceptions.emplace_back( std::current_exception( ) ); } } } int main( ) { { // a scope to limit the lifetime of jthread objects std::stop_source stop_src { std::nostopstate }; std::array<std::jthread, 8> threads { }; try { stop_src = std::stop_source { }; for ( auto value { 0 }; auto& thrd : threads ) { thrd = std::jthread { func, stop_src, value }; value += 5; } } catch ( const std::exception& ex ) { stop_src.request_stop( ); fmt::print( "{}\n", ex.what( ) ); } } for ( const auto& ex_ptr : caught_exceptions ) { if ( ex_ptr != nullptr ) { try { std::rethrow_exception( ex_ptr ); } catch ( const std::exception& ex ) { fmt::print( "{}\n", ex.what( ) ); } } } }
{ "domain": "codereview.stackexchange", "id": 44659, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, error-handling, concurrency, c++20, atomic", "url": null }
c++, error-handling, concurrency, c++20, atomic I may have to mention that my aim is to inform the threads to return whenever an exception is caught in one thread. This is done using the copies of std::stop_source that are passed to each thread. So the constinit util::spinlock_mutex mtx { }; will only need to be locked pretty rarely since exceptions are thrown rarely. Is this a valid case to use a spinlock? With that said, do the above program and its flow control make any sense? I have thought about what could go wrong (e.g. deadlocks, uncaught exceptions, etc.) but nothing worrying caught my attention. The last for loop is there to handle the exceptions after all the std::jthreads have been destructed. That's also why the jthreads are declared in an inner scope.
{ "domain": "codereview.stackexchange", "id": 44659, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, error-handling, concurrency, c++20, atomic", "url": null }
c++, error-handling, concurrency, c++20, atomic Answer: No need to explicitly delete the copy constructor There is no need to delete the copy constructor and copy assignment operators. Since std::atomic_flag itself is non-copyable, your class will by default also be non-copyable. Consider making try_lock() [[nodiscard]] You made the class and the constructor itself [[nodiscard]], but it might make sense to apply this to try_lock() as well. Use std::mutex unless you have a very good reason not to While the spinlock class itself looks fine, I don't see why you would need to use a spinlock specifically for the use case you have. A std::mutex would do fine. Consider that exceptions will be on the slow path, the potential overhead of std::mutex is not something I would worry about at all. Also consider that adding something to a std::vector can take a long time, especially if the vector needs to grow its storage. This will mean allocating new memory and copying the old contents over. With a std::mutex, other threads will be put to sleep while this happens. With your spinlock, those threads will waste a lot of CPU cycles. Also consider that spinlocks work best if every logical thread is associated with its own hardware thread. If however the operating system decides to let two logical threads share the same hardware thread, it means that if one logical thread gets scheduled out while holding the spinlock, and another logical thread gets scheduled in that tries to lock the same spinlock, the second one will waste all of its time slice for nothing, whereas with a std::mutex this waste would not happen. Avoid locking altogether Even better than optimizing the type of lock is to not need a lock. If you know you only have 8 threads, you can declare a std::array of 8 caught exceptions, and give each thread a pointer to their own element inside that array. This way they can write to it without needing a lock.
{ "domain": "codereview.stackexchange", "id": 44659, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, error-handling, concurrency, c++20, atomic", "url": null }
php, strings, recursion Title: Recursive function for creating a cookies string Question: I've created the following function that creates a cookie string for passing to cURL. It can take a nested array or object of key-value pairs. It can either create nested cookie values as JSON, or using square brackets in cookie names. Please could someone kindly: Assess whether it's functionally correct or not, does it generate good cookies? I don't know if it's necessary for it to repeat the expires/domain/path/secure/httponly for each cookie. Help reduce the bloat. I don't like how: (a) it calls itself 3 times. (b) it has the following code twice: $keyPrefix?$keyPrefix."[".$key."]":$key (c) in the middle, it checks: if (is_object($val) || is_array($val)) - it seems a bit redundant.
{ "domain": "codereview.stackexchange", "id": 44660, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, strings, recursion", "url": null }
php, strings, recursion The function: function http_build_cookie($data, $useJson=true, $expires = 0, $path = '', $domain = '', $secure = false, $httpOnly = false, $keyPrefix = '') { if (is_object($data)) { $data = (array) $data; } if (is_array($data)) { $cookie_parts = array(); foreach ($data as $key => $val) { if ($useJson) { $cookie_parts[] = http_build_cookie( rawurlencode($key)."=" .rawurlencode(json_encode($val)), $useJson, $expires, $path, $domain, $secure, $httpOnly ); } else { if (is_object($val) || is_array($val)) { $cookie_parts[] = http_build_cookie( $val, $useJson, $expires, $path, $domain, $secure, $httpOnly, $keyPrefix?$keyPrefix."[".$key."]":$key ); } else { $cookie_parts[] = http_build_cookie( rawurlencode($keyPrefix?$keyPrefix."[".$key."]":$key)."=" .rawurlencode($val), $useJson, $expires, $path, $domain, $secure, $httpOnly ); } } } return implode('; ', $cookie_parts); } if (is_scalar($data)) { $cookie = $data; if ($expires) { $cookie .= '; expires=' . gmdate('D, d-M-Y H:i:s T', $expires); } if ($path) { $cookie .= '; path=' . $path; } if ($domain) { $cookie .= '; domain=' . $domain; } if ($secure) { $cookie .= '; secure'; } if ($httpOnly) { $cookie .= '; HttpOnly'; } return $cookie; } return ''; } Any advice would be massively appreciated!
{ "domain": "codereview.stackexchange", "id": 44660, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, strings, recursion", "url": null }
php, strings, recursion Any advice would be massively appreciated! Answer: I had a go at refactoring your code for you to make it more simple, otherwise the functionality seemed to work from what I could see. $cookie_parts = array(); // Check if data is a scalar value if (is_scalar($data)) { $cookie_parts[] = rawurlencode($keyPrefix) . '=' . rawurlencode($data); } // Check if data is an array or object elseif (is_array($data) || is_object($data)) { // Loop through array/object keys and values foreach ($data as $key => $val) { // Generate the key name based on whether a prefix is set or not $cookie_key = $keyPrefix ? $keyPrefix . '[' . $key . ']' : $key; // If value is an array/object, recursively call this function if (is_array($val) || is_object($val)) { $cookie_parts[] = http_build_cookie( $val, $useJson, $expires, $path, $domain, $secure, $httpOnly, $cookie_key ); } // If value is a scalar, generate the cookie string else { $cookie_value = $useJson ? json_encode($val) : $val; $cookie_parts[] = rawurlencode($cookie_key) . '=' . rawurlencode($cookie_value); } } } // Append the common cookie attributes to the final cookie string $cookie = implode('; ', $cookie_parts); if ($expires) { $cookie .= '; expires=' . gmdate('D, d-M-Y H:i:s T', $expires); } if ($path) { $cookie .= '; path=' . $path; } if ($domain) { $cookie .= '; domain=' . $domain; } if ($secure) { $cookie .= '; secure'; } if ($httpOnly) { $cookie .= '; HttpOnly'; } return $cookie; }
{ "domain": "codereview.stackexchange", "id": 44660, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, strings, recursion", "url": null }
python, python-3.x, turtle-graphics Title: Turtle language parser in python 3 Question: I a creating a program to parse a simple language in a text file and delegate those actions to python-turtle. You pass the path to the file(s) you want to be parsed into the program, and a turtle window is shown. This is my code: import sys import turtle import time t = turtle.Turtle() functions = { "F": t.forward, "B": t.backward, "R": t.right, "L": t.left, "H": t.seth, "C": t.circle, "U": t.penup, "D": t.pendown, "W": time.sleep, "T": t.shape, "V": t.speed, "P": t.pensize, "S": t.shapesize, "O": turtle.done } def prep_args(args): output = [] for arg in args: try: output.append(int(arg)) except: output.append(arg) return output def parse_line(line): if line.strip() == "": return action = line.strip()[0] assert action in functions, f"Unknown Action: {action}" args = line.strip().split(" ")[1:] args = prep_args(args) functions[action](*args) def parse_file(path): with open(path, "r") as f: for line in f.readlines(): parse_line(line) for argv in sys.argv[1:]: parse_file(argv) Example input file: F 100 R 90 F 50 C 20 T square W 5 V 0 S 5 U F 50 D C 30 180 5 H 90 F 3 S 1 O I would be grateful for any help to improve this program. Answer: The code is pretty small and straight-forward, I mainly see minor improvements. I find it somewhat strange that parse_file() is what calls on the main function, and how you deal with args in the files is not super easy to follow or debug; you can't really validate your arguments the way that you have set this up. It would be helpful to add an example file with this type of code. It's a bit unnecessary to call on str.split() 3 times in parse_line() def parse_line(line): line = line.strip() action = line[0] assert action in functions, f"Unknown Action: {action}"
{ "domain": "codereview.stackexchange", "id": 44661, "lm_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, turtle-graphics", "url": null }
python, python-3.x, turtle-graphics assert action in functions, f"Unknown Action: {action}" args = line.split(" ")[1:] args = prep_args(args) functions[action](*args) And instead of asserting and raising an AssertionError with a custom message to the user you could just catch the KeyError and print def parse_line(line): line = line.strip() action = line[0] args = line.split(" ")[1:] args = prep_args(args) try: functions[action](*args) except KeyError: print(f"Unknown action: {action}")
{ "domain": "codereview.stackexchange", "id": 44661, "lm_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, turtle-graphics", "url": null }
rust, graph Title: Checking if a graph is fully connected Question: After reading the rust book for some time I decided to create my first program which implements a graph. There are a few things I was wondering about, such as if the file structure is appropriate (the graph.rs just containing a few mod statements feels weird). Also to store pointers to the edges I had to use Rc and I am not sure if that is the correct choice? And finally I'm also wondering if there is a more idiomatic rust way to write certain code ? Other comments are welcome as well of course. main.rs: use crate::graph::edge::Edge; use crate::graph::graph::Graph; use crate::graph::node::Node; use std::collections::HashMap; use std::rc::Rc; pub mod graph; fn main() { let g = create_graph(); println!("graph connected: {}", g.is_fully_connected()); } fn create_graph() -> Graph { let n: Vec<Node> = vec![Node::new(), Node::new(), Node::new()]; let edge1 = &Rc::new(Edge::new(0, 1)); let edge2 = &Rc::new(Edge::new(0, 2)); let edge3 = &Rc::new(Edge::new(1, 2)); let mut neighbors = HashMap::new(); let neighbors0 = vec![Rc::clone(edge1), Rc::clone(edge2)]; let neighbors1 = vec![Rc::clone(edge1), Rc::clone(edge3)]; let neighbors2 = vec![Rc::clone(edge2), Rc::clone(edge3)]; neighbors.insert(0, neighbors0); neighbors.insert(1, neighbors1); neighbors.insert(2, neighbors2); Graph::new(n, neighbors) } graph.rs: pub mod graph; pub mod edge; pub mod node; graph/node.rs: pub struct Node { //TODO coordinates } impl Node { #[inline] pub fn new() -> Self { Node {} } } graph/edge.rs pub struct Edge { node_a: i32, node_b: i32, } impl Edge { #[inline] pub fn new(node_a: i32, node_b: i32) -> Self { Edge { node_a: node_a, node_b: node_b, } }
{ "domain": "codereview.stackexchange", "id": 44662, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, graph", "url": null }
rust, graph //if base_node is neither of the edge nodes then the result is considered random pub fn get_adj_node(&self, base_node: i32) -> i32 { if base_node == self.node_a { self.node_b } else { self.node_a } } } graph/graph.rs: use super::edge::Edge; use super::node::Node; use std::collections::HashMap; use std::collections::HashSet; use std::rc::Rc; pub struct Graph { nodes: Vec<Node>, neighbors: HashMap<i32, Vec<Rc<Edge>>>, //node index to coinciding edges } impl Graph { pub fn new(nodes: Vec<Node>, neighbors: HashMap<i32, Vec<Rc<Edge>>>) -> Self { Graph { nodes: nodes, neighbors: neighbors, } } pub fn is_fully_connected(&self) -> bool { let mut index = 0; let mut stack = vec![index]; let mut used = HashSet::from([index]); while !stack.is_empty() { index = stack.pop().unwrap(); let neighbors = match self.neighbors.get(&index) { None => continue, Some(n) => n, }; for edge in neighbors { let adj_node = edge.get_adj_node(index); if !used.contains(&adj_node) { used.insert(adj_node); stack.push(adj_node); } } } used.len() == self.nodes.len() } }
{ "domain": "codereview.stackexchange", "id": 44662, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, graph", "url": null }
rust, graph used.len() == self.nodes.len() } } Answer: Very nice! The use of Rc to store the edges is a good choice. Technically, it's probably not necessary here where your edges are only ordered pairs of ints (a primitive copyable type) -- but would become a crucial feature if you want to extend Edge with additional information, such as an edge label that can be modified or replaced. The biggest thing I see for improvement is that your Graph::new interface is rather awkward. It requires clients of your graph to pay attention to low-level, irrelevant details, constructing a HashMap and compiling edges into a Vec of Rc pointers. It would be much nicer to use a builder pattern here: your graph starts empty, and you can add vertices and edges one at a time. That is: impl Graph { pub fn new() -> Self { ... } pub fn add_node(&mut self, i: i32) { ... } pub fn add_edge(&mut self, i1: i32, i2: i32) { ... } }
{ "domain": "codereview.stackexchange", "id": 44662, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, graph", "url": null }
rust, graph If done correctly, this way, the Rc stuff should only be a local implementation detail inside Graph. I.e., your graph would construct Rc internally when adding edges and would not expose that detail to the user. Secondly, always try running cargo clippy! It's super helpful and generally gives correct suggestions for how to make Rust code more idiomatic. You have generally done well; the main thing it catches is when constructing a struct object, you can omit names that are the same as the field name like nodes: nodes and just write nodes. It also suggests implementing Default for objects that have a default (empty) object, which in your case would be Node and Graph (though I suspect Node may later change to a different interface without a default implementation). For most structs -- in your case, Edge, Node, and Graph -- you should always #[derive(Debug, Clone)] unless there is a good reason not to. Debug makes it possible to print out your graph and edges if you need to for debugging purposes, and Clone means that clients can make a deepcopy of edges and graphs if needed. Like this: #[derive(Debug, Clone)] pub struct Edge { node_a: i32, node_b: i32, } The file you named graph.rs is more commonly put in graph/mod.rs. It's not unusual that mod.rs only includes a short list of imports. Putting the main modules in main.rs is fine for a command-line tool or binary. If you want to build a library (data structure) that others will use, you would put the public module declarations in a file called lib.rs, and import them from main instead. Lastly, consider adding some unit tests! To add one, simply write a function like #[test] fn test_add_edge() { ... } which uses assert!(...) and assert_eq!(..., ...) to check behavior. You can then run the unit tests with cargo test.
{ "domain": "codereview.stackexchange", "id": 44662, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, graph", "url": null }
c++, algorithm, strings Title: Remove smiles from string in-place Question: I have a coding task. Remove smiles from string in-place. Smile is a set of characters starting from ':' and ending with one or more brackets ')' or one or more brackets '(' Example Input "AA:)))( :((" Output "AA(" Could you please review my solution? (My tests are OK, but I want to confirm that everything is OK) #include <iostream> #include <string> #include <cassert> using namespace std; string remove_smiles(string s) { int insert_idx = 0; for (int i = 0; i < s.size(); ++i) { if (s[i] == ':' and i + 1 < s.size() and (s[i + 1] == ')' or s[i + 1] == '(')) { int j = i + 1; char smile_mode = s[j]; while (j < s.size() and s[j] == smile_mode) { ++j; } i = j - 1; } else { s[insert_idx++] = s[i]; } } s.resize(insert_idx); return s; } int main() { assert(remove_smiles("") == ""); assert(remove_smiles(":)") == ""); assert(remove_smiles(":()") == ")"); assert(remove_smiles("AA:)))BB:(") == "AABB"); assert(remove_smiles("::)(XX") == ":(XX"); assert(remove_smiles(":)):))X") == "X"); assert(remove_smiles(":():))") == ")"); } Answer: Avoid using namespace std While using namespace std can save you a little bit of typing, it brings everything from the std namespace into the global namespace, including things you did not think of. It is safer to avoid doing this, or only to use it on a more restricted set of things. For example, if you would use std::string a lot, you can write: using std::string;
{ "domain": "codereview.stackexchange", "id": 44663, "lm_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, strings", "url": null }
c++, algorithm, strings Make use of the fact that std::strings are NUL-terminated It's great that you thought about bounds checking. However, since C++11, std::strings are guaranteed to have a NUL-byte at the end. You can make use of this fact and simplify your code a bit: if (s[i] == ':' and (s[i + 1] == ')' or s[i + 1] == '(')) { int j = i + 1; char smile_mode = s[j]; while (s[j] == smile_mode) { ++j; } i = j - 1; } This may or may not result in slightly more optimal code. Consider using find(), find_first_not_of() and copy() You are going through the input string character by character. For small strings this is probably fine, but for larger strings there are more optimal ways to search of a given character, like by reading multiple bytes at a time and using vector instructions. While you could try to implement such an algorithm yourself, the standard library might have implemented these already. Consider rewriting your algorithm in a way that leverages standard functions like std::string's find() and find_first_not_of(). With find() you can find the next occurence of ':', and then when you have smile_mode, you can use find_first_not_of() to find the first character that is no longer part of the smile. Once you know which part to copy, use the copy() member function to copy a whole range of characters in one go.
{ "domain": "codereview.stackexchange", "id": 44663, "lm_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, strings", "url": null }
javascript, performance, array, search, interval Title: Given a sorted list of integers, find the highest count of elements between an indeterminate but fixed size range Question: I'm trying to optimize a function that takes a sorted list of integers and tells me what is the maximum number of elements in the list between any definite size range. To be clear, the range itself isn't given, the size of it is; the lower and upper bounds can be anything as long as they are the given distance apart. Example: List Range Output Reason [0, 1, 3, 3, 4, 5, 5, 5, 5, 5, 6, 6, 7, 8, 9] 2 7 Max of 7 elements between [5,7) [0, 1, 3, 3, 4, 5, 5, 5, 5, 5, 6, 6, 7, 8, 9] 3 8 Max of 8 elements tied between [3,6) & [4,7) & [5,8) [1, 4, 6, 9, 12, 15, 24, 25, 26, 27, 40, 42, 42, 44, 45] 10 5 Max of 5 elements between [40,50) I expect the list to have anywhere between 10,000 to 1,000,000 elements and the range to be rather small in comparison so optimization is the main concern. I've written the following JavaScript that reduces through the list, and filters out everything not between the range but I can't help but wonder if there's a better way to optimize it rather than using filter since the list is sorted. let search = (list, range) => list.reduce((maxCount, val, _, arr) => { let rangedCount = arr.filter(x => x >= val && x < val + range).length; if (rangedCount > maxCount) return rangedCount; return maxCount; }, 0); Aren't I now iterating through the list once more for each element in it by using Array.filter inside Array.reduce? I'd expect that there's some better way to optimize this such as using a binary search instead of filter but - correct me if I'm wrong - a binary search could give me a random index among multiple duplicates.
{ "domain": "codereview.stackexchange", "id": 44664, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, performance, array, search, interval", "url": null }
javascript, performance, array, search, interval Answer: Inappropriate use of iteration functions Complexity When the data is sorted it is a sure sign that there is a solution with less complexity than \$O(n^2)\$ The use of 'Array.reduce' and Array.filter are inappropriate and forces your solution to have a complexity of \$O(n^2)\$ The standard Array iteration functions, Array.forEach, Array.reduce, Array.filter do not provide a way to exit before the end, or start at an index above 0. It is far more convenient in performance oriented code to just use standard loops 'for', 'while', or 'do while' loops The outer loop need only iterate to list.length - maxCount which means that in the best case the problem can be solved in \$O(n)\$ The inner loop can start at the index of the outer loop and can exit as soon as a value is outside the range. Only in the best case would it have to iterate all values. The overall complexity to solve this problem best case is \$O(n)\$ and worst is \$O(n {log} n)\$ (my estimation) Performance Performance and complexity are not the same. In performance code avoid repeating calculations. In your filter you add val + range which can be done once outside the filter. Thus if list is 1000 items long you would do an additional 999,000 needless additions. There is no need to reassign list to arr in the reduce callback list.reduce((maxCount, val, _, arr) as the callback closes over list. In this case there is little performance gain but fast code is a habit. Rewrite Rewriting your solution const search = (list, range) => list.reduce((max, val) => { const maxVal = val + range; const count = list.filter(x => x >= val && x < maxVal).length; return count > max ? count : max; }, 0); Rewriting a solution using while loops. Using the arguments you gave the rewrite runs ~10 times faster. Though this increases dramatically as the size of list grows. There is some ambiguity the rewrite assumes that. range is unsigned and can include 0
{ "domain": "codereview.stackexchange", "id": 44664, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, performance, array, search, interval", "url": null }
javascript, performance, array, search, interval range is unsigned and can include 0 const search = (list, range) => { const len = list.length; var i = 0, max = 0; while (i < len - max) { let j = i; const maxVal = list[i] + range; while (j < len && list[j] < maxVal) { j++ } max = Math.max(max, j - i++); } return max; } Additional optimisations to consider. There is an early exit if range == 0 that I did not include as I don't know how likely that would be. If the list contains many duplicate values there is a optimisation possible, though that would increase the source code complexity by a considerable amount and not worth the effort if duplicate values are rare. You could also check at start (early exit) if (range > list[list.length - 1] - list[0]) { return list.length } but only if you expect range to be large often.
{ "domain": "codereview.stackexchange", "id": 44664, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, performance, array, search, interval", "url": null }
javascript Title: Im trying to show the traffic lights in a loop Question: I am trying to build this: Build a traffic light where the lights switch from green to yellow to red after predetermined intervals and loop indefinitely. Each light should be lit for the following durations: Red light: 4000ms Yellow light: 500ms Green light: 3000ms Please review and suggest if this is the right solution let i=0; const classNames = ['red','yellow','green']; const timeouts = [4000,500,3000] const interval = setInterval(() => { const div = document.getElementById(`${classNames[i]}`) if(i>=0) { const prevDiv =(i===0)? document.getElementById(`${classNames[2]}`) : document.getElementById(`${classNames[i-1]}`) prevDiv.className='' } div.className=classNames[i]; if(i<2) { i++; }else { i=0; } },timeouts[i]) .red { background-color: red; } .yellow{ background-color: yellow; } .green { background-color: green; } <div id="red">Red</div> <div id="yellow">Yellow</div> <div id="green">Green</div>
{ "domain": "codereview.stackexchange", "id": 44665, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript Answer: Is your question on topic? Your code does not work as expected. However the rules for asking at code review states that code "...works correctly (to the best of your knowledge)" and timing bugs are very difficult for humans to detect. I assume that you were unaware of the timing issue, and potencial hidden bugs. Review There are several problems with your solution. Execution flow and order You use the variable i to select the interval for the call to setInterval callback. In the callback you change i, however the change to i is never used to start another interval, so the timer callback continues to use the interval at i = 0 resulting in each light being on for 4000ms Nothing happens if you don't execute the code. IE changing i does not affect previous use of i. Luck can cover bugs Often code can have bugs that do not occur due to pure luck. In this case you use... document.getElementById(`${classNames[i]}`)
{ "domain": "codereview.stackexchange", "id": 44665, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript ...to get elements. The luck is that the element id is the same as the element class name. If the class name or id was to change the bug would manafest and most likely throw an error. You should have used querySelector(className[i]) which would locate the first element with the class name className[i] setInterval is evil The timing function setInterval starts an ongoing timed callback. The callback is called as close as possible after the interval time. It can not be called while other code is running. It is affected by the page visibility and the OS state. If you forget to store the handle, or the variable holding the handle is lost you can not stop the timer. Thus setInterval is the only way to create a memory leak in JS. For this reason you should never ever use setInterval. Use setTimeout setTimeout is similar to setInterval however it only calls the callback once. It can not cause a memory leak. To repeat the callback one must call setTimeout again. This lets you recalculate the time till the next event in the case that the current event is late. Style points. Avoid repeating DOM queries. Store DOM elements in variable. There is no need to make string from strings. Eg document.getElementById(`${classNames[i]}`) // same as document.getElementById(classNames[i]); // classNames[i] is a string Note I ignored the unlucky bug. :( It is a bad habit declaring variables in the global scope. Use IIFE (Immediately Invoked Function Expression) to keep the global scope clean. While learning JS it is best to run your code in strict mode. To do this add the directive "use strict" to the first line of code in your JS script. Note once you have gained experience you will know why you always use strict mode. Rewrite The rewrite uses
{ "domain": "codereview.stackexchange", "id": 44665, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
javascript Rewrite The rewrite uses setTimeout to time events objects via factory function light to define each light the array lights to store all the lights elements are stored rather than queried from the DOM each time they are needed the function nextLight is used to turn off the current light, turn on the next light, and setup the timeout for the next light uses remainder operator % to cycle light index. EG lights.currentIdx = (lights.currentIdx + 1) % lights.length performance.now() to get a time in milliseconds (used to calculate when to call for the next light) Note The timing is set from the first call, if the lights fall behind (due to page visibility) they will cycle at increased speed (interval of 0) to catch up. Note Element ids are unique to the page Note lights.time - performance.now() may be negative. This is ignored by setTimeout which has the shortest timeout of > 0ms Note I changed the timing because 4000ms is way to long for me to wait on red "use strict"; (()=>{ const light = (className, interval, element) => ({className, interval, element}); const lights = [ light("red", 2000, redEl), light("yellow", 500, yellowEl), light("green", 1000, greenEl), ]; lights.currentIdx = lights.length - 1; lights.time = performance.now(); // ms since page load nextLight(); function nextLight() { var light = lights[lights.currentIdx]; light.element.classList.remove(light.className); // Next light lights.currentIdx = (lights.currentIdx + 1) % lights.length; light = lights[lights.currentIdx]; light.element.classList.add(light.className); lights.time += light.interval; setTimeout(nextLight, lights.time - performance.now()); } })(); .red { background-color: red; } .yellow { background-color: yellow; } .green { background-color: green; } <div id="redEl" >Red</div> <div id="yellowEl">Yellow</div> <div id="greenEl" >Green</div>
{ "domain": "codereview.stackexchange", "id": 44665, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
c++, c++11, collections, pointers, hash-map Title: Bidirectional map based on memory manipulation Question: This is a bidirectional map implementation that stores the values as pairs on the heap, and uses pointer arithmetic for efficient lookup. codepad link, may be easier to read #include <iostream> #include <set> #include <utility> #include <cstddef> #include <SSVUtils/SSVUtils.hpp> namespace Internal { template<typename T> struct PtrComparator { inline bool operator()(const T* mA, const T* mB) const noexcept { return *mA < *mB; } }; } template<typename T1, typename T2> class SneakyBimap { public: using BMPair = std::pair<T1, T2>; using Storage = std::vector<ssvu::Uptr<BMPair>>; template<typename T> using PtrSet = std::set<const T*, Internal::PtrComparator<T>>; using iterator = typename Storage::iterator; using const_iterator = typename Storage::const_iterator; using reverse_iterator = typename Storage::reverse_iterator; using const_reverse_iterator = typename Storage::const_reverse_iterator; private: Storage storage; PtrSet<T1> set1; PtrSet<T2> set2; template<typename T> inline BMPair* getPairImpl(const T* mPtr) const noexcept { return const_cast<BMPair*>(reinterpret_cast<const BMPair*>(mPtr)); } inline const char* getPairBasePtr(const T2* mItem) const noexcept { static_assert(std::is_standard_layout<BMPair>::value, "BMPair must have standard layout"); return reinterpret_cast<const char*>(mItem) - offsetof(BMPair, second); } inline BMPair* getPairPtr(const T1* mItem) const noexcept { return getPairImpl(mItem); } inline BMPair* getPairPtr(const T2* mItem) const noexcept { return getPairImpl(getPairBasePtr(mItem)); }
{ "domain": "codereview.stackexchange", "id": 44666, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, collections, pointers, hash-map", "url": null }
c++, c++11, collections, pointers, hash-map inline T2& getImpl(const T1* mItem) noexcept { return getPairPtr(mItem)->second; } inline T1& getImpl(const T2* mItem) noexcept { return getPairPtr(mItem)->first; } inline const T2& getImpl(const T1* mItem) const noexcept { return getPairPtr(mItem)->second; } inline const T1& getImpl(const T2* mItem) const noexcept { return getPairPtr(mItem)->first; } public: template<typename TA1, typename TA2> inline void emplace(TA1&& mArg1, TA2&& mArg2) { assert(!this->has(mArg1) && !this->has(mArg2)); auto pair(std::make_unique<std::pair<T1, T2>>(std::forward<TA1>(mArg1), std::forward<TA2>(mArg2))); set1.emplace(&(pair->first)); set2.emplace(&(pair->second)); storage.emplace_back(std::move(pair)); } inline void insert(const BMPair& mPair) { this->emplace(mPair.first, mPair.second); } template<typename T> inline void erase(const T& mKey) { assert(this->has(mKey)); const auto& pairPtr(getPairPtr(&mKey)); set1.erase(&(pairPtr->first)); set2.erase(&(pairPtr->second)); ssvu::eraseRemoveIf(storage, [&pairPtr](const ssvu::Uptr<std::pair<T1, T2>>& mI){ return mI.get() == pairPtr; }); assert(!this->has(mKey)); } inline const T2& at(const T1& mKey) const noexcept { const auto& itr(set1.find(&mKey)); if(itr == std::end(set1)) throw std::out_of_range{"mKey was not found in set1"}; return getImpl(*itr); } inline const T1& at(const T2& mKey) const noexcept { const auto& itr(set2.find(&mKey)); if(itr == std::end(set2)) throw std::out_of_range{"mKey was not found in set2"}; return getImpl(*itr); }
{ "domain": "codereview.stackexchange", "id": 44666, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, collections, pointers, hash-map", "url": null }
c++, c++11, collections, pointers, hash-map inline T2& operator[](const T1& mKey) noexcept { assert(this->has(mKey)); return getImpl(*set1.find(&mKey)); } inline T1& operator[](const T2& mKey) noexcept { assert(this->has(mKey)); return getImpl(*set2.find(&mKey)); } inline const T2& operator[](const T1& mKey) const noexcept { assert(this->has(mKey)); return getImpl(*set1.find(&mKey)); } inline const T1& operator[](const T2& mKey) const noexcept { assert(this->has(mKey)); return getImpl(*set2.find(&mKey)); } inline void clear() noexcept { storage.clear(); set1.clear(); set2.clear(); } inline bool empty() const noexcept { return storage.empty(); } inline auto size() const noexcept -> decltype(storage.size()) { return storage.size(); } inline auto count(const T1& mKey) const noexcept -> decltype(set1.count(&mKey)) { return set1.count(&mKey); } inline auto count(const T2& mKey) const noexcept -> decltype(set2.count(&mKey)) { return set2.count(&mKey); } inline auto find(const T1& mKey) const noexcept -> decltype(set1.find(&mKey)) { return set1.find(&mKey); } inline auto find(const T2& mKey) const noexcept -> decltype(set2.find(&mKey)) { return set2.find(&mKey); } inline bool has(const T1& mKey) const noexcept { return this->find(mKey) != std::end(set1); } inline bool has(const T2& mKey) const noexcept { return this->find(mKey) != std::end(set2); }
{ "domain": "codereview.stackexchange", "id": 44666, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, collections, pointers, hash-map", "url": null }
c++, c++11, collections, pointers, hash-map inline auto begin() noexcept -> decltype(storage.begin()) { return storage.begin(); } inline auto end() noexcept -> decltype(storage.end()) { return storage.end(); } inline auto begin() const noexcept -> decltype(storage.begin()) { return storage.begin(); } inline auto end() const noexcept -> decltype(storage.end()) { return storage.end(); } inline auto cbegin() const noexcept -> decltype(storage.cbegin()) { return storage.cbegin(); } inline auto cend() const noexcept -> decltype(storage.cend()) { return storage.cend(); } inline auto rbegin() noexcept -> decltype(storage.rbegin()) { return storage.rbegin(); } inline auto rend() noexcept -> decltype(storage.rend()) { return storage.rend(); } inline auto crbegin() const noexcept -> decltype(storage.crbegin()) { return storage.crbegin(); } inline auto crend() const noexcept -> decltype(storage.crend()) { return storage.crend(); } }; SSVU_TEST(SneakyBimapTests) { SneakyBimap<int, std::string> sb; SSVUT_EXPECT(sb.empty()); SSVUT_EXPECT(!sb.has(10)); SSVUT_EXPECT(!sb.has("banana")); SSVUT_EXPECT(sb.count(10) == 0); SSVUT_EXPECT(sb.count("banana") == 0); sb.emplace(10, "banana"); SSVUT_EXPECT(!sb.empty()); SSVUT_EXPECT(sb.size() == 1); SSVUT_EXPECT(sb.has(10)); SSVUT_EXPECT(sb.has("banana")); SSVUT_EXPECT(sb.count(10) == 1); SSVUT_EXPECT(sb.count("banana") == 1); SSVUT_EXPECT(sb.at(10) == "banana"); SSVUT_EXPECT(sb[10] == "banana"); SSVUT_EXPECT(sb.at("banana") == 10); SSVUT_EXPECT(sb["banana"] == 10); sb["banana"] = 25;
{ "domain": "codereview.stackexchange", "id": 44666, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, collections, pointers, hash-map", "url": null }
c++, c++11, collections, pointers, hash-map sb["banana"] = 25; SSVUT_EXPECT(!sb.empty()); SSVUT_EXPECT(sb.size() == 1); SSVUT_EXPECT(!sb.has(10)); SSVUT_EXPECT(sb.has(25)); SSVUT_EXPECT(sb.has("banana")); SSVUT_EXPECT(sb.count(10) == 0); SSVUT_EXPECT(sb.count(25) == 1); SSVUT_EXPECT(sb.count("banana") == 1); SSVUT_EXPECT(sb.at(25) == "banana"); SSVUT_EXPECT(sb[25] == "banana"); SSVUT_EXPECT(sb.at("banana") == 25); SSVUT_EXPECT(sb["banana"] == 25); sb["banana"] = 15; sb[15] = "melon"; sb.emplace(10, "cucumber"); SSVUT_EXPECT(!sb.empty()); SSVUT_EXPECT(sb.size() == 2); SSVUT_EXPECT(sb.has(10)); SSVUT_EXPECT(sb.has(15)); SSVUT_EXPECT(!sb.has(25)); SSVUT_EXPECT(sb.has("melon")); SSVUT_EXPECT(sb.has("cucumber")); SSVUT_EXPECT(!sb.has("banana")); SSVUT_EXPECT(sb.count(10) == 1); SSVUT_EXPECT(sb.count(15) == 1); SSVUT_EXPECT(sb.count(25) == 0); SSVUT_EXPECT(sb.count("melon") == 1); SSVUT_EXPECT(sb.count("cucumber") == 1); SSVUT_EXPECT(sb.count("banana") == 0); SSVUT_EXPECT(sb.at(10) == "cucumber"); SSVUT_EXPECT(sb[10] == "cucumber"); SSVUT_EXPECT(sb.at("cucumber") == 10); SSVUT_EXPECT(sb["cucumber"] == 10); SSVUT_EXPECT(sb.at(15) == "melon"); SSVUT_EXPECT(sb[15] == "melon"); SSVUT_EXPECT(sb.at("melon") == 15); SSVUT_EXPECT(sb["melon"] == 15); sb.clear(); SSVUT_EXPECT(sb.empty()); SSVUT_EXPECT(sb.size() == 0); SSVUT_EXPECT(!sb.has(10)); SSVUT_EXPECT(!sb.has(15)); SSVUT_EXPECT(!sb.has(25)); SSVUT_EXPECT(!sb.has("melon")); SSVUT_EXPECT(!sb.has("cucumber")); SSVUT_EXPECT(!sb.has("banana")); } SSVU_TEST_END(); int main() { SSVU_TEST_RUN_ALL(); return 0; } Notes:
{ "domain": "codereview.stackexchange", "id": 44666, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, collections, pointers, hash-map", "url": null }
c++, c++11, collections, pointers, hash-map int main() { SSVU_TEST_RUN_ALL(); return 0; } Notes: ssvu::eraseRemoveIf performs the erase-remove idiom on a container, with a predicate. ssvu::Uptr<T> is just an alias for std::unique_ptr<T>. SSVUT_EXPECT is a test macro - the test fails unless the boolean expression inside returns true. The real values (pairs) are stored in storage, a std::vector of std::unique_ptr<std::pair<T1, T2>>. By performing pointer arithmetic and reinterpret_cast / const_cast magic, is it possible to obtain the base address of the pair from the first or second member. This trick is used to access the members of the pairs from a pointer to their first or second member. Is there anything dangerous about this? Is there a way to avoid using std::unique_ptr, and improving the performance? If you want to compile the code yourself, SSVUtils is available here on my GitHub page. Tested on g++ 4.8 and clang++ SVN, both with -O3 and -O0 options. All tests passed. Answer: Here you assert that the type is standard layout (for use of offsetof) inline const char* getPairBasePtr(const T2* mItem) const noexcept { static_assert(std::is_standard_layout<BMPair>::value, "BMPair must have standard layout"); return reinterpret_cast<const char*>(mItem) - offsetof(BMPair, second); } For symmetry and to make sure that the first element aligns to the beginning f the class you should probably do the same here. template<typename T> inline BMPair* getPairImpl(const T* mPtr) const noexcept { return const_cast<BMPair*>(reinterpret_cast<const BMPair*>(mPtr)); } Don't need the new syntax here: inline auto begin() noexcept -> decltype(storage.begin()) { return storage.begin(); } The types of the iterators is well defined: iterator begin() noexcept { return storage.begin(); }
{ "domain": "codereview.stackexchange", "id": 44666, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, collections, pointers, hash-map", "url": null }
c++, c++11, collections, pointers, hash-map The types of the iterators is well defined: iterator begin() noexcept { return storage.begin(); } Also don't specify inline unless you have too. Members declared inside the class are automatically inline so no need to add the keyword. PS. I assume you are not doing it to force inlining because the compiler will completely ignore you. If you insert the same value you don't reuse a slot in storage: typename SneakyBimap<int,int>::BMPair data(1,2); SneakyBimap<int,int> store; store.insert(data); store.insert(data); store.insert(data); store.insert(data); store.insert(data); store.insert(data); store.insert(data); store.insert(data); store.insert(data); store.insert(data); store.insert(data); // lots of storage used. Not sure I would templatize this method: template<typename TA1, typename TA2> inline void emplace(TA1&& mArg1, TA2&& mArg2) The first thing you do is create a BMPair. auto pair(std::make_unique<std::pair<T1, T2>>(std::forward<TA1>(mArg1), std::forward<TA2>(mArg2))) And though you are forwarding the arguments to the constructor they will still need to convert the parameters as the object is constructed TA1 => T1 and TA2 => T2 so I don't think you gain any flexibility. OK. Worked it out. By doing this you only have to convert the parameters once as you create the object. Rather than once at the call site (which happens if you don't templatize the parameters) followed by a copy during construction. Nice but ugly. I would not use a vector of unique ptr. using Storage = std::vector<ssvu::Uptr<BMPair>>; As a user any dynamically allocated memory should be managed be either a smart pointer or a container. Since you are writing the container it is worth looking at writing the memory management to go with it. using Storage = std::vector<BMPair*>;
{ "domain": "codereview.stackexchange", "id": 44666, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, collections, pointers, hash-map", "url": null }
c++, c++11, collections, pointers, hash-map // OK just tried to re-write // void emplace(TA1&& mArg1, TA2&& mArg2) // using only pointers. // // It is possible but definitely non trivial // to do in an exception safe manner as you have to insert data // into three different containers all of which could throw during // insertion. // // Worth having a look at **BUT** now I think I would stick with // std::unique_ptr until my container showed signs that it was // causing efficiency problems having a good bash at it. Now that I thought about it. You emplace does not provide the strong exception guarantee. auto pair(std::make_unique<std::pair<T1, T2>>(std::forward<TA1>(mArg1), std::forward<TA2>(mArg2))); // Assume this works. set1.emplace(&(pair->first)); // Assume this fails. // And throws an exception. set2.emplace(&(pair->second)); // This is never done. // So `pair` still holds the value. storage.emplace_back(std::move(pair)); // As `pair goes out of scope it deletes the object. // This means that `set1` holds a pointer to an invalid // memory location. So now that I see that the same problems exist for both unique_ptr and pointer versions. I would go back to my original position of not using unique_ptr here. But it is non trivial and you should think about it.
{ "domain": "codereview.stackexchange", "id": 44666, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++11, collections, pointers, hash-map", "url": null }
array, rust Title: Merge Sorted Array in Rust Question: I was solving this task https://leetcode.com/explore/learn/card/fun-with-arrays/525/inserting-items-into-an-array/3253/ The main idea is to merge two sorted arrays (more details in the site) Example: Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1. My solution is working and fine in terms of time complexity, but I thin that it can be improved: Can I avoid i1 as usize in index calculation? What rust features I can apply? My solution (passed all tests) impl Solution { pub fn merge(nums1: &mut Vec<i32>, m: i32, nums2: &mut Vec<i32>, n: i32) { let mut insert_pos: i32 = m + n - 1; let mut i1 = m - 1; let mut i2 = n - 1; while i1 >= 0 && i2 >= 0 { if nums1[i1 as usize] > nums2[i2 as usize] { nums1[insert_pos as usize] = nums1[i1 as usize]; i1 -= 1; } else { nums1[insert_pos as usize] = nums2[i2 as usize]; i2 -= 1; } insert_pos -= 1; } while i1 >= 0 { nums1[insert_pos as usize] = nums1[i1 as usize]; i1 -= 1; insert_pos -= 1; } while i2 >= 0 { nums1[insert_pos as usize] = nums2[i2 as usize]; i2 -= 1; insert_pos -= 1; } } }
{ "domain": "codereview.stackexchange", "id": 44667, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, rust", "url": null }
array, rust Answer: A lot of room for improvement here! :) For the i as usize issue, the general principle is: whenever if you have variables indexing into an array, make them usize. So you have two Vec of i32, but the indexes (and lengths) should be usize. That's m, n, insert_pos, i1, and i2. Once you make this change, you can get rid of all those pesky as usize annotations, but now you have a different problem: you are using -1 to indicate when there's no more elements to insert, and -1 isn't a valid usize. Instead, best practice here is to add 1 to all your variables. The >=0 checks become >0 checks instead, and the -1 calculations are moved into the while loop. With this change, the beginning of the function becomes: pub fn merge(nums1: &mut Vec<i32>, m: usize, nums2: &mut Vec<i32>, n: usize) { let mut insert_pos = m + n; let mut i1 = m; let mut i2 = n; while i1 > 0 && i2 > 0 { if nums1[i1 - 1] > nums2[i2 - 1] { ... Our next observation for improvement is that insert_pos is always just equal to i1 + i2. So let's just replace all instances of it with i1 + i2. Once we do this, you'll notice something fascinating -- your second while loop actually does nothing and can be removed: while i1 > 0 { i1 -= 1; nums1[i1] = nums1[i1]; } Once we remove that, we're left with just the first and third loops. Before we get back to the final updated code, let's take a look at a couple of other improvements: Always try running cargo clippy! It's an automatic tool which always gives helpful suggestions to make your code more Rust-like. Here, it wants us to convert the &mut Vec<i32> arguments to &mut [i32], because the vectors are not being resized at all in the function body, which is correct. In fact, we can go further and remove the &mut keyword for nums2, as nums2 is only read from and not written to.
{ "domain": "codereview.stackexchange", "id": 44667, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, rust", "url": null }
array, rust Finally, the variables m and n are immediately assigned to i1 and i2, and otherwise removed. So it would be cleaner to just declare i1 and i2 as mut in the function signature. That is, we can write pub fn merge(nums1: &mut [i32], mut i1: usize, ... and omit the variables m and n. I would personally also rename these to n1 and n2 for clarity. Here's our final code, with all of the above changes: pub fn merge(nums1: &mut [i32], mut n1: usize, nums2: &[i32], mut n2: usize) { while n1 > 0 && n2 > 0 { if nums1[n1 - 1] > nums2[n2 - 1] { n1 -= 1; nums1[n1 + n2] = nums1[n1]; } else { n2 -= 1; nums1[n1 + n2] = nums2[n2]; } } while n2 > 0 { n2 -= 1; nums1[n2] = nums2[n2]; } } There are definitely ways to do this more concisely using more advanced Rust built-ins -- like iterators and ranges -- but not a bad start for purely imperative code.
{ "domain": "codereview.stackexchange", "id": 44667, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, rust", "url": null }
java, parsing Title: Parsing one UserData type to a preview Question: I am currently developing a web app and am using Spring as a Backend. I have some user data that is provided by one of our services and I need to display it in my frontend. The subject of the code review is the part, where I process the data in my backend to create a simpler data type that I can directly use in the frontend. This avoids that I have to mess with the incoming data in my frontend app and can directly take the data I want to display from this data type. This is my parser I wrote for this task. I tried some stuff that was relatively unknown to me before e.g. this return switch thingy. Any feedback is greatly appreciated! @Service public class UserDataParser { public ProfilePreviewData toProfilePreviewData(ExtendedUserData user) { ProfilePreviewData profilePreviewData = new ProfilePreviewData(); profilePreviewData.setAccountId(user.getId()); profilePreviewData.setAccountName(user.getName()); profilePreviewData.setAccounts(getAccountPreviewData(user)); return profilePreviewData; } private List<AccountPreviewData> getAccountPreviewData(ExtendedUserData user) { List<AccountPreviewData> accountsPreviewData = new ArrayList<>(); for (AccountData account : user.getAccounts()) { if (!account.getPublish()) continue; accountsPreviewData.add(getMinecraftAccountPreviewData(account)); } for (ExternalAccountData externalAccount : user.getExternalAccounts()) { if (!externalAccount.getPublish()) continue; accountsPreviewData.add(getExternalAccountPreviewData(externalAccount)); } return accountsPreviewData; }
{ "domain": "codereview.stackexchange", "id": 44668, "lm_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, parsing", "url": null }
java, parsing return accountsPreviewData; } private AccountPreviewData getMinecraftAccountPreviewData(AccountData account) { AccountPreviewData accountPreviewData = new AccountPreviewData(); accountPreviewData.setAccountType(AccountType.MINECRAFT); accountPreviewData.setDisplayName(account.getName()); accountPreviewData.setUniqueIdentifier(account.getUuid().toString()); return accountPreviewData; } private AccountPreviewData getExternalAccountPreviewData(ExternalAccountData accountData) { AccountPreviewData accountPreviewData = new AccountPreviewData(); AccountType type = getTypeOfExternalAccount(accountData.getTypeName()); accountPreviewData.setAccountType(type); accountPreviewData.setDisplayName(accountData.getAccountId()); accountPreviewData.setUniqueIdentifier(accountData.getName()); return accountPreviewData; } private AccountType getTypeOfExternalAccount(String typeName) { return switch (typeName) { case "Discord" -> AccountType.DISCORD; case "TeamSpeak" -> AccountType.TEAMSPEAK; default -> AccountType.UNKNOWN; }; } } ```
{ "domain": "codereview.stackexchange", "id": 44668, "lm_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, parsing", "url": null }
java, parsing Answer: Naming The class name is a bit abstract. I prefer naming services based on the concrete things they provide instead of what they consume. You of course follow the naming conventions of your organization, but to me a Parser converts transportation data format, such as an XML or JSON document, to a Java object. I prefer to use Mapper suffix for classes that convert between different type of Java objects and I use the result object type as the mapper name. So my choice for naming this class would be ProfilePreviewDataMapper. When your mapper is named after the result type, you don't need to repeat it in the method name, since the information is in the class name. The method becomes ProfilePreviewDataMapper.from(ExtendedUserData extendedUserData). Also by following this naming style, you automatically limit the scope of each class to it's return type and "accidentally" adding more and more responsibilities becomes harder, because you have to figure out different method names that break the pattern. It's easier to keep classes small and manageable. In Java, get is a special prefix for a method and it marks an accessor to a field. Getters are not expected to create new objects. Using get prefix in a method that accepts parameters and creates objects breaks one of the most widely used Java idioms, so I would recommend against that. If you want to follow your class structure, use something like createAccountPreviewData instead, as that prefix immediately signals that something new is being returned instead of returning a reference to an existing object. Also use the same prefix for all methods. Now you have to and get prefixes in methods that perform similar tasks. Structure
{ "domain": "codereview.stackexchange", "id": 44668, "lm_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, parsing", "url": null }
java, parsing Structure Consider the testability of your class. What data do you need to set up in order to unit test the getMinecraftAccountPreviewData method? I would take the three private methods and extract them into standalone mappers. The getAccountPreviewData method would become AccountPreviewDataMapper.from(ExtendedUserData extendedUserData) which gets injected into ProfilePreviewDataMapper. Apply same pattern to getMinecraftAccountPreviewData and getExternalAccountPreviewData and then you can create individual unit tests for each mapper without having to set up a lot of unnecessary data for each of them. Instead of implemeting the mappers straight up as ProfilePreviewDataMapper etc, make them interfaces instead and write the implementation in ProfilePreviewDataMapperImpl. You have now implemented S, O, L and D of the SOLID principles Style I find this "if not something, skip" logic unnecessarily difficult to follow and not using curly braces only adds to it. I would replace for (AccountData account : user.getAccounts()) { if (!account.getPublish()) continue; accountsPreviewData.add(getMinecraftAccountPreviewData(account)); }
{ "domain": "codereview.stackexchange", "id": 44668, "lm_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, parsing", "url": null }
java, parsing with for (AccountData account : user.getAccounts()) { if (account.getPublish()) { accountsPreviewData.add(getMinecraftAccountPreviewData(account)); } }
{ "domain": "codereview.stackexchange", "id": 44668, "lm_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, parsing", "url": null }
c#, beginner, calculator Title: Basic C# Calculator Question: I am a beginner programmer, I decided to make this calculator program to test my knowledge on basic C# syntax, the code executes as intended, however I would like to shorten it to be more concise. Console.WriteLine("Please select your first number: "); double numberOne = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Please select your second number: "); double numberTwo = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Please choose the operation: "); var userInput = Console.ReadLine(); if (userInput == "+") { Console.WriteLine(numberOne + numberTwo); } else if (userInput == "-") { Console.WriteLine(numberOne - numberTwo); } else if (userInput == "*") { Console.WriteLine(numberOne * numberTwo); } else if (userInput == "/") { Console.WriteLine(numberOne / numberTwo); } Answer: Your code is good, but there are a few improvements that you could make. Determining what operation your user wants. Instead of using if/else, I'd probably use a switch/case statement: switch userInput { case "+": Console.WriteLine(numberOne + numberTwo); break; case "-": Console.WriteLine(numberOne - numberTwo); break; case "*": Console.WriteLine(numberOne * numberTwo); break; case "/": Console.WriteLine(numberOne / numberTwo); break; } Error handling with user inputs I'd probably also put a default clause, just in case your user doesn't enter one of + - * /: switch userInput { ... default: Console.WriteLine("Sorry, unknown operation."); break; }
{ "domain": "codereview.stackexchange", "id": 44669, "lm_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#, beginner, calculator", "url": null }
c#, beginner, calculator I would also use a try/catch block for figuring out what numberOne and numberTwo are: try { Console.WriteLine("Please select your first number: "); double numberOne = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Please select your second number: "); double numberTwo = Convert.ToDouble(Console.ReadLine()); } catch (FormatException) { Console.WriteLine("Sorry, invalid number."); } You might also want to check whether numberTwo is not zero when dividing: switch userInput { ... case "/": if numberTwo == 0 { Console.WriteLine("Sorry, cannot divide by zero."); } else { Console.WriteLine(numberOne / numberTwo); } break; }
{ "domain": "codereview.stackexchange", "id": 44669, "lm_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#, beginner, calculator", "url": null }
python, performance, game-of-life Title: Reverse Game of Life Question: I have written code to take a cellular automaton configuration and determine a state that could have existed one time-step prior, according to Game of Life rules. The algorithm goes roughly as follows: Take a cell, and iterate through every possible 3x3 configuration of cells that could've evolved into this cell after one time step. If the configuration does not produce the correct state (i.e. live or dead), check the next. If the configuration does not overlap with the other proposed prior configurations in the area, check the next. If no configurations work, go back to the prior cell and recurse: continue iterating through possible cell configurations. If the configuration fits, put it on the grid. Go to the next cell. from collections import deque from itertools import product class CellularAutomaton: configs = tuple(product((False, True), repeat=9)) def __init__(self, rows, cols, fill=None): self.rows = rows self.cols = cols self.size = rows * cols """Cells can be False=dead, True=alive, None=undetermined. """ self.g = [[fill] * rows for _ in range(cols)] def __getitem__(self, i): r, c = i return self.g[r % self.rows][c % self.cols] def __setitem__(self, i, v): r, c = i self.g[r % self.rows][c % self.cols] = v def __eq__(self, t): """ Compare two automata. """ return all(self[i] == t[i] for i in self) def __iter__(self): yield from product(range(self.rows), range(self.cols)) def neighborhood(self, i): """ Return the indices of all adjacent cells and cell itself. """ r, c = i return ( (r-1,c-1), (r-1,c), (r-1,c+1), (r ,c-1), (r ,c), (r ,c+1), (r+1,c-1), (r+1,c), (r+1,c+1) )
{ "domain": "codereview.stackexchange", "id": 44670, "lm_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, game-of-life", "url": null }
python, performance, game-of-life def index(self, i): """ Converts 1-dimensional indices. """ return (i // self.cols, i % self.cols) def reverse(self): """ Return a new CellularAutomaton that evolves into this one after one evolution. """ rows, cols, size = self.rows, self.cols, self.size ret = CellularAutomaton(rows, cols) """Hypothesis: a stack to keep track of which cell is using which configuration. """ hypo = deque([iter(CellularAutomaton.configs)], maxlen=size+1) """A stack to keep track of which cells are changed with each configuration so if a configuration needs to be undone, we know which cells to revert. """ undo = deque([] , maxlen=size) while len(hypo)-1 < size: i = ret.index(len(hypo)-1) for cfg in hypo[-1]: nbhd = ret.neighborhood(i) """Does the configuration produce the right state? """ if self[i] != ((cfg[4] and sum(cfg) in (3, 4)) or (not cfg[4] and sum(cfg) == 3)): continue """Does the configuration fit on the automaton with previously- decided configurations? """ if any(ret[n] != c and ret[n] is not None for n, c in zip(nbhd, cfg)): continue """Only add undetermined cells to the undo stack because all other cells' states were determined by other nearby configurations. """ undo.append(tuple(n for n in nbhd if ret[n] is None)) """Update the return board with the configuration. """ for n, c in zip(nbhd, cfg): ret[n] = c
{ "domain": "codereview.stackexchange", "id": 44670, "lm_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, game-of-life", "url": null }
python, performance, game-of-life hypo.append(iter(CellularAutomaton.configs)) break else: """We iterated through every configuration and none of them worked. We need to go back to a previous cell. """ hypo.pop() for c in undo.pop(): ret[c] = None continue return ret def forward(self): """ Evolve one time-step forward. """ rows, cols = self.rows, self.cols ret = CellularAutomaton(rows, cols) for i in self: nbhd = sum(self[j] for j in self.neighborhood(i)) - self[i] ret[i] = True if nbhd == 3 else (self[i] if nbhd == 2 else False) return ret """This is a smiley face. """ end = CellularAutomaton(10, 10, False) end[2,2] = 1 end[2,3] = 1 end[7,2] = 1 end[7,3] = 1 end[1,5] = 1 end[2,6] = 1 end[3,7] = 1 end[4,7] = 1 end[5,7] = 1 end[6,7] = 1 end[7,6] = 1 end[8,5] = 1 assert end == end.reverse().forward(), "Not equal." An important constraint of this problem is that I intend to use it on automata with dimensions potentially on the order of thousands of cells, so I don't believe I can use actual recursion here due to memory constraints. Instead, I am faking recursion with stacks. I am looking for advice to make this code faster. It takes several minutes to reverse some configurations on my machine by just a single time-step. I am more concerned here about the result than the process, so I welcome algorithm changes, language/library recommendations, or even large-scale changes such as different automata systems, different boundary conditions, or other deviations from the project scope. I am not very interested in style or organization improvements, but will welcome comments on these matters nonetheless.
{ "domain": "codereview.stackexchange", "id": 44670, "lm_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, game-of-life", "url": null }
python, performance, game-of-life Answer: Reduce the search space For each cell, it looks like the code always considers all 512 possible 9x9 configurations for the previous generation. However, if the cell is currently alive, you know that the previous configuration must have had 3 or 4 live cells. There are only 126 of those configurations, so only considering those would reduce the search space by about 75%. Similarly, if the cell is dead, there are only 386 possible configurations for the previous generation, a 25% reduction. Here are the changes. Organize configs so that the configurations that would result in a live cell are in configs[1] and those that would result in a dead cell are in configs[0]: class CellularAutomaton: configs = ([],[]) for t in product((False, True), repeat=9): s = sum(t) if s == 3 or s == 4 and t[4]: configs[1].append(t) else: configs[0].append(t) Then, in reverse(), the first thing to push on the hypo stack, are the configs that could result in cell[0,0]: hypo = deque([iter(CellularAutomaton_A.configs[self[0, 0]])], maxlen=size+1) The test to make sure the chosen config produces the right state can be eliminated, because it's precomputed in the way configs was built. Lastly, after updating the return board with the configuration, we push on the stack the possible configurations for the next cell based on it's current state: nr, nc = ret.index(len(hypo)) hypo.append(iter(CellularAutomaton_A.configs[self[nr, nc]])) On my machine, the original code takes about 3.6 seconds to run the example provided. With the simple changes above, the code takes about 2.3 seconds...about 33% faster! Reduce it some more. The neighborhoods of adjacent cells overlap. This can be used to further prune the search space. Consider cells 6 and 7 below: 1 2 3 4 5 6 7 8 9 10 11 12
{ "domain": "codereview.stackexchange", "id": 44670, "lm_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, game-of-life", "url": null }
python, performance, game-of-life When cell 6 has a possible configuration, it has proposed values for cells 2, 3, 6, 7, 10 and 11 which are in the neighborhood of cell 7. When pushing possible configurations for cell 7, we know the current state of cell 7 and the proposed configuration for cell 6. Given what is known, there are at most 8 possibilities for cells 4, 8, and 12. That's 8 possible configurations instead of 512, a 98% reduction. Let's call the tuple for cells 2, 3, 6, 7, 10, 11 the "right_key" of cell 6. It is also the "left_key" of cell 7. The only valid configs for cell 7 are configs that have a left_key that matches the right_key of cell 6. As before, configs is first indexed by the current state of a cell, but each part is now a dict. The keys to the dict are the left_key of of a configuration and the values are list of configurations having the corresponding left_key. One tricky part is that cells in column 0, don't have a cell on the left to get a key from, so in that case we push an iterable over all possibilities that can result in the current value of that cell. This is done using itertools.chain.from_iterable on the values() of one of the dicts in configs. Here is code based on this idea: from collections import defaultdict, deque from itertools import chain, product def right_key(t): return t[1], t[2], t[4], t[5], t[7], t[8] def left_key(t): return t[0], t[1], t[3], t[4], t[6], t[7] class CellularAutomaton_B: configs = (defaultdict(list), defaultdict(list)) for t in product((False, True), repeat=9): s = sum(t) k = left_key(t) if s == 3 or s == 4 and t[4]: configs[1][k].append(t) else: configs[0][k].append(t) def __init__(self, rows, cols, fill=None): self.rows = rows self.cols = cols self.size = rows * cols """Cells can be False=dead, True=alive, None=undetermined. """ self.g = [[fill] * rows for _ in range(cols)]
{ "domain": "codereview.stackexchange", "id": 44670, "lm_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, game-of-life", "url": null }
python, performance, game-of-life def __getitem__(self, i): r, c = i return self.g[r % self.rows][c % self.cols] def __setitem__(self, i, v): r, c = i self.g[r % self.rows][c % self.cols] = v def __eq__(self, other): """ Compare two automata. """ return self.g == other.g def __iter__(self): yield from product(range(self.rows), range(self.cols)) def neighborhood(self, i): """ Return the indices of all adjacent cells and cell itself. """ r, c = i return ( (r-1,c-1), (r-1,c), (r-1,c+1), (r ,c-1), (r ,c), (r ,c+1), (r+1,c-1), (r+1,c), (r+1,c+1) ) def index(self, i): """ Converts 1-dimensional indices. """ return (i // self.cols, i % self.cols) def reverse(self): """ Return a new CellularAutomaton that evolves into this one after one evolution. """ rows, cols, size = self.rows, self.cols, self.size ret = CellularAutomaton_B(rows, cols) """Hypothesis: a stack to keep track of which cell is using which configuration. """ initial_hypos = chain.from_iterable(CellularAutomaton_B.configs[self[0, 0]].values()) hypo = deque([initial_hypos], maxlen=size+1) """A stack to keep track of which cells are changed with each configuration so if a configuration needs to be undone, we know which cells to revert. """ undo = deque([], maxlen=size) while len(hypo) <= size: i = ret.index(len(hypo)-1) for cfg in hypo[-1]: nbhd = ret.neighborhood(i) """Does the configuration fit on the automaton with previously- decided configurations? """ if any(ret[n] != c and ret[n] is not None for n, c in zip(nbhd, cfg)): continue
{ "domain": "codereview.stackexchange", "id": 44670, "lm_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, game-of-life", "url": null }
python, performance, game-of-life """Only add undetermined cells to the undo stack because all other cells' states were determined by other nearby configurations. """ undo.append(tuple(n for n in nbhd if ret[n] is None)) """Update the return board with the configuration. """ for n, c in zip(nbhd, cfg): ret[n] = c nr, nc = ret.index(len(hypo)) if nc: key = right_key(cfg) hypo.append(iter(CellularAutomaton_B.configs[self[nr, nc]][key])) else: first_col_hypo = chain.from_iterable(CellularAutomaton_B.configs[self[nr, nc]].values()) hypo.append(iter(first_col_hypo)) break else: """We iterated through every configuration and none of them worked. We need to go back to a previous cell. """ hypo.pop() for c in undo.pop(): ret[c] = None continue return ret def forward(self): """ Evolve one time-step forward. """ rows, cols = self.rows, self.cols ret = CellularAutomaton_B(rows, cols) for i in self: nbhd = sum(self[j] for j in self.neighborhood(i)) - self[i] ret[i] = True if nbhd == 3 else (self[i] if nbhd == 2 else False) return ret
{ "domain": "codereview.stackexchange", "id": 44670, "lm_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, game-of-life", "url": null }
python, performance, game-of-life return ret This code runs the example in about 0.6 seconds, or 1/10 the time of the original code. More? That first cell needs to consider all possible configurations. The other cells in the first row have information about the configuration of the cell to their right, which information is used in the program above. The cells in the first column have information about the cell above it, which could be used in a similar manner. The cells in the rest of the grid have information about the cell above it and the cell to it's left. Using both leaves only 2 configurations to consider (the to possible values of the bottom, right cell). Extending the code is left as an exercise for the reader.
{ "domain": "codereview.stackexchange", "id": 44670, "lm_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, game-of-life", "url": null }
ajax Title: Is there a more efficient way of using ajax to update search results? Question: I have a HTML form that allows users to filter their choices when browsing. There are multiple fields (radio button groups) that when the user clicks on them, the search results are updated accordingly. I'm doing this with an Ajax call to results.php and passing a different variable depending on the radio button group that has been clicked - like so: <script> $('input[type=radio][name=data]').on('change', function() { $.ajax({ type: "POST", url: "results.php", data: "monthlydata=" + $(this).val(), success: function(response){ $('#results').show(1000).html(response); } }); }); $('input[type=radio][name=contract_length]').on('change', function() { $.ajax({ type: "POST", url: "results.php", data: "contract_length=" + $(this).val(), success: function(response){ $('#results').show(1000).html(response); } }); }); $('input[type=radio][name=price]').on('change', function() { $.ajax({ type: "POST", url: "results.php", data: "price=" + $(this).val(), success: function(response){ $('#results').show(1000).html(response); } }); }); $('input[type=radio][name=mbprice]').on('change', function() { $.ajax({ type: "POST", url: "results.php", data: "price=" + $(this).val(), success: function(response){ $('#results').show(1000).html(response); } }); }); $('input[type=radio][name=mblength]').on('change', function() { $.ajax({ type: "POST", url: "results.php", data: "contract_length=" + $(this).val(), success: function(response){ $('#results').show(1000).html(response); } }); });
{ "domain": "codereview.stackexchange", "id": 44671, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "ajax", "url": null }
ajax $('#results').show(1000).html(response); } }); }); $('input[type=radio][name=mbdata]').on('change', function() { $.ajax({ type: "POST", url: "results.php", data: "monthlydata=" + $(this).val(), success: function(response){ $('#results').show(1000).html(response); } }); }); Everything works as I want it to - just seems a little long-winded. Thanks in advance. Answer: First, I would recommend to use a formatter to format your code, which will make it easier for you and others to read. Prettier is a very common choice. Second, to extract common functionality into a function, you need to identify the parts that are the same and the parts that change. In your example, it it basically the same code 6 times, and only the input selector and the query parameter used are different. These two things will be the parameters of the function. function updateResultsOnChange(input, queryparam) { $(input).on("change", function() { $.ajax({ type: "POST", url: "results.php", data: queryparam + "=" + $(this).val(), success: function(response) { $("#results").show(1000).html(response); } }); }); } updateResultsOnChange("input[type=radio][name=data]", "monthlydata"); updateResultsOnChange("input[type=radio][name=contract_length]", "contract_length"); updateResultsOnChange("input[type=radio][name=price]", "price"); updateResultsOnChange("input[type=radio][name=mbprice]", "price"); updateResultsOnChange("input[type=radio][name=mblength]", "contract_length"); updateResultsOnChange("input[type=radio][name=mbdata]", "monthlydata"); Also please check if you need multiple radio boxes that do the same thing, it might be confusing for users.
{ "domain": "codereview.stackexchange", "id": 44671, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "ajax", "url": null }
php, game, random, sudoku Title: Sudoku generator Question: I managed to create a Sudoku generator but I'll just go ahead and say that it generates 1 out of 500 tries on average. I'd say that's pretty inefficient and I'd like to ask you for advice on improvements. Basically what I figured is if I had defined a range of numbers that are possible for each cell, then started selecting random numbers for cells 1 by 1 and removing the respective number from its column, row and "box" ( don't really know how they're called ), then it would magically select appropriate numbers and will be left with only one single possible number for the last cell. Well that wasn't the case, but I thought if I gave it a bunch of more tries it would eventually end up as I planned it and it did, the problem is, as I already said that it is very inefficient. $loop = true; while ($loop) { $loop = false; // define and clear array $matrix = [];
{ "domain": "codereview.stackexchange", "id": 44672, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, game, random, sudoku", "url": null }
php, game, random, sudoku while ($loop) { $loop = false; // define and clear array $matrix = []; // Fill all cells with possible numbers for ($x = 1; $x < 10; $x++) { for ($y = 1; $y < 10; $y++) { for ($z = 1; $z < 10; $z++) { $matrix[$y][$x][$z] = $z; } } } // Start selecting random numbers for each cell from // the possible numbers contained in it currently for ($x = 1; $x < 10; $x++) { for ($y = 1; $y < 10; $y++) { $keys = array_keys($matrix[$x][$y]); // if there are no keys this means there are no possible // numbers for this cell, which means the generator has // failed => restart if(count($keys) == 0){ $loop = true; break 2; } // Set cell number to a random number from the possible $matrix[$x][$y] = $matrix[$x][$y][$keys[mt_rand(0, count($keys) - 1)]]; // remove the selected number from the possible numbers for // the appropriate column and row for ($z = 1; $z < 10; $z ++) { if ($z != $y) { unset($matrix[$x][$z][$matrix[$x][$y]]); } if ($z != $x) { unset($matrix[$z][$y][$matrix[$x][$y]]); } } // Define box's start ($w) and end ($W) X position if ($x < 4) { $w = 1; $W = 4; } else if ($x < 7) { $w = 4; $W = 7; } else { $w = 7; $W = 10; }
{ "domain": "codereview.stackexchange", "id": 44672, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, game, random, sudoku", "url": null }
php, game, random, sudoku // Define box's start ($z) and end ($Z) Y position if ($y < 4) { $z = 1; $Z = 4; } else if ($y < 7) { $z = 4; $Z = 7; } else { $z = 7; $Z = 10; } // Remove selected number from all cells' possible numbers // in the appropriate 3x3 box for (; $w < $W; $w++) { for ($z = $Z - 3; $z < $Z; $z++) { if (is_array($matrix[$z][$w])) { unset($matrix[$z][$w][$matrix[$x][$y]]); } } } } } } And please excuse me for the part where variables are named $z, $Z that doesn't make sense, I just have this obsession about re-using variables that I no longer need, which I know is a bad practice but I do it anyway. EDIT I currently discovered that it also produces incorrect puzzles occasionally, debugging to find the reason. Update: I figured the reason out. It was because of the fact that I was using incorrect coordinates for the removal of the selected number from the respective 3x3 grids, however after putting correct coordinates now, no puzzles are generated, it just goes on forever. I guess I will be deleting this question if I don't find a solution soon. Answer: for ($x = 1; $x < 10; $x++) { for ($y = 1; $y < 10; $y++) { for ($z = 1; $z < 10; $z++) { $matrix[$y][$x][$z] = $z; } } } Why 10? The answer is that you are taking < and started with 1 so to get to 9, you either have to use <= 9 or < 10. The <= 9 notation is more readable in this case, as you don't care about 10. for ( $x = 1; $x <= 9; $x++) { $matrix[$x] = []; for ($y = 1; $y <= 9; $y++) { $matrix[$x][$y] = range(1, 9); } }
{ "domain": "codereview.stackexchange", "id": 44672, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, game, random, sudoku", "url": null }
php, game, random, sudoku I changed the order from [$y][$x] to [$x][$y]. This allows us to initialize the elements of the first array with arrays of their own. This seems better than relying on PHP to create them implicitly when used. I replaced the innermost for loop with range, but this changes the third dimension to be 0-indexed. We'll have to make changes later. $keys = array_keys($matrix[$x][$y]); // if there are no keys this means there are no possible // numbers for this cell, which means the generator has // failed => restart if(count($keys) == 0){ $loop = true; break 2; } // Set cell number to a random number from the possible $matrix[$x][$y] = $matrix[$x][$y][$keys[mt_rand(0, count($keys) - 1)]]; We can make this code even simpler though: $keys = array_keys($matrix[$x][$y]); // if there are no keys this means there are no possible // numbers for this cell, which means the generator has // failed => restart if(count($keys) == 0){ continue 3; } // Set cell number to a random number from the possible $matrix[$x][$y] = $matrix[$x][$y][$keys[mt_rand(0, $possibility_count - 1)]]; $index = $matrix[$x][$y]-1; I changed the break 2 to a continue 3, as it seemed more directly what you are trying to do: restart the outer loop. I also added $index to store the 0-based index of that value. We'll replace later uses of $matrix[$x][$y] with it. for ($z = 1; $z < 10; $z ++) { if ($z != $y) { unset($matrix[$x][$z][$matrix[$x][$y]]); } if ($z != $x) { unset($matrix[$z][$y][$matrix[$x][$y]]); } }
{ "domain": "codereview.stackexchange", "id": 44672, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, game, random, sudoku", "url": null }
php, game, random, sudoku You're missing some logic in this. Note that $matrix[$x][$z] and $matrix[$z][$y] may not be arrays. We should check that first: for ( $z = 1; $z <= 9; $z ++ ) { if ( is_array($matrix[$x][$z]) ) { unset($matrix[$x][$z][$index]); } if ( is_array($matrix[$z][$y]) ) { unset($matrix[$z][$y][$index]); } } We no longer need to check that we aren't at the current point in the $matrix, as the is_array check will drop us out in that case. Also, this uses $index now. if ($x < 4) { $w = 1; $W = 4; } else if ($x < 7) { $w = 4; $W = 7; } else { $w = 7; $W = 10; } This would be easier to follow if you made the second values inclusive: if ( $x <= 3 ) { $w = 1; $W = 3; } else if ( $x <= 6 ) { $w = 4; $W = 6; } else { $w = 7; $W = 9; } Now we have 1-3, 4-6, 7-9. No overlap. After we do the same for $y, we need to adjust the code that uses this: for (; $w < $W; $w++) { for ($z = $Z - 3; $z < $Z; $z++) { if (is_array($matrix[$z][$w])) { unset($matrix[$z][$w][$matrix[$x][$y]]); } } } to for ( ; $w <= $W; $w++ ) { for ( ; $z <= $Z; $z++ ) { if ( is_array($matrix[$z][$w]) ) { unset($matrix[$z][$w][$index]); } } }
{ "domain": "codereview.stackexchange", "id": 44672, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, game, random, sudoku", "url": null }
php, game, random, sudoku The $z = $Z - 2 is unnecessary, as we already set the initial value of $z. Note that $w and $W are based on the value of $x while $z and $Z are based on $y. So this means that $matrix[$x][$y] should become $matrix[$w][$z]. In the second loop, you use $matrix[$x][$y] elsewhere. You do it the other way in the first loop, but $w and $z are in the second loop. for ( ; $w <= $W; $w++ ) { for ( ; $z <= $Z; $z++ ) { if ( is_array($matrix[$w][$z]) ) { unset($matrix[$w][$z][$index]); } } } The complete code is now while ( true ) { // define and clear array $matrix = array(); // Fill all cells with possible numbers for ($x = 1; $x <= 9; $x++) { $matrix[$x] = array(); for ($y = 1; $y <= 9; $y++) { $matrix[$x][$y] = range(1, 9); } } // Start selecting random numbers for each cell from // the possible numbers contained in it currently for ($x = 1; $x <= 9; $x++) { for ($y = 1; $y <= 9; $y++) { $keys = array_keys($matrix[$x][$y]); // if there are no keys this means there are no possible // numbers for this cell, which means the generator has // failed => restart if(count($keys) == 0){ continue 3; } // Set cell number to a random number from the possible $matrix[$x][$y] = $matrix[$x][$y][$keys[mt_rand(0, count($keys) - 1)]]; $index = $matrix[$x][$y]-1; // remove the selected number from the possible numbers for // the appropriate column and row for ($z = 1; $z <= 9; $z ++) { if ( is_array($matrix[$x][$z]) ) { unset($matrix[$x][$z][$index]); } if ( is_array($matrix[$z][$y]) ) { unset($matrix[$z][$y][$index]); } }
{ "domain": "codereview.stackexchange", "id": 44672, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, game, random, sudoku", "url": null }
php, game, random, sudoku // Define box's start ($w) and end ($W) X position if ( $x <= 3 ) { $w = 1; $W = 3; } else if ( $x <= 6 ) { $w = 4; $W = 6; } else { $w = 7; $W = 9; } // Define box's start ($z) and end ($Z) Y position if ( $y <= 3 ) { $z = 1; $Z = 3; } else if ( $y <= 6 ) { $z = 4; $Z = 6; } else { $z = 7; $Z = 9; } // Remove selected number from all cells' possible numbers // in the appropriate 3x3 box for ( ; $w <= $W; $w++ ) { for ( ; $z <= $Z; $z++ ) { if (is_array($matrix[$w][$z])) { unset($matrix[$w][$z][$index]); } } } } } break; } I also changed the loop control a bit. Rather than track a $loop variable, I use continue in the middle of the loop to bypass the break at the end. Note that this is a completed Sudoku board. Usually when we talk about Sudoku generators, we're talking about incomplete boards that are ready for play.
{ "domain": "codereview.stackexchange", "id": 44672, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, game, random, sudoku", "url": null }
python, tkinter, gui Title: TkInter GUI interface for STM32 MCU Question: I'm very new to Python and this is my first ever Python GUI app. I am writing a little app to interact with my STM32 Black Pill board. This is very minimal as I intend to use this as the basis for future project with specific intentions. How did I do? What can I do better? import tkinter as tk import serial.tools.list_ports from threading import * class Main(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.title("Breadboard MCU Interface") self.resizable(False, False) ### Menu Configuration ############################################################################### self.menubar = tk.Menu(self) self.configmenu = tk.Menu(self.menubar, tearoff=0) self.configmenu.add_command(label="Communications Port", command=lambda: PortConfig()) self.menubar.add_cascade(label="Configure", menu=self.configmenu) self.menubar.add_command(label="Connect", command=connect) self.config(menu=self.menubar) ### End Menu Configuration ########################################################################### ### GPIO Canvas ###################################################################################### self.gpio_canvas = tk.Canvas(self, width=325, height=100) self.gpio_canvas.create_text(170, 30, text="GPIO", font=('Helvetica 15 bold')) self.gpio_canvas.create_text(25, 55, text="Port A") self.gpio_canvas.create_text(25, 70, text="Port B") self.ports = { "A": [], "B": [] } for pin in range(16, 0, -1): self.ports['A'].append(self.gpio_canvas.create_oval(60 + (pin * 15), 50, 70 + (pin * 15), 60, fill = "green")) self.ports['B'].append(self.gpio_canvas.create_oval(60 + (pin * 15), 65, 70 + (pin * 15), 75, fill = "green"))
{ "domain": "codereview.stackexchange", "id": 44673, "lm_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, tkinter, gui", "url": null }
python, tkinter, gui self.gpio_canvas.pack(fill="both") ### End GPIO Canvas ################################################################################### def updatePinDisplay(self, portid, pinvalues): for i in range(0,16): pinvalue = ((pinvalues >> i) & 1) if pinvalue: self.gpio_canvas.itemconfig(self.ports[portid][i], fill="green2") else: self.gpio_canvas.itemconfig(self.ports[portid][i], fill="green") #self.update() class PortConfig(tk.Toplevel): def __init__(self, *args, **kwargs): def getSelection(choice): self.selected = str(choice).split(' ')[0] def setComPort(): global comport comport = self.selected connect() self.destroy() tk.Toplevel.__init__(self, *args, **kwargs) self.title("Connection Configuration") self.resizable(False, False) self.config(padx=5, pady=5) ports = serial.tools.list_ports.comports() default = tk.StringVar(self, "Please select a communications port") self.selected = None self.portslist = tk.OptionMenu(self, default, *ports, command=getSelection).pack(side="left") self.okbutton = tk.Button(self, text="OK", command=setComPort).pack(side="left", padx=10) self.focus() self.grab_set() class WorkThread(Thread): global connection def run(self): global porta_pins print("Worker thread running...") try: while connection.is_open: while connection.in_waiting: indata = connection.readline().decode('Ascii') portid, pinvalues = indata.split('#') app.updatePinDisplay(portid, int(pinvalues)) except Exception as e: print(str(e)) pass print("Worker thread closing down.")
{ "domain": "codereview.stackexchange", "id": 44673, "lm_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, tkinter, gui", "url": null }
python, tkinter, gui def connect(): global connection, connected, workthread try: connection = serial.Serial(comport, baudrate=1152000, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=2) except: pass if connection is not None: connected = True connection.write("Connection established.\r\n".encode('Ascii')) app.menubar.entryconfigure(2, label="Disconnect", command=disconnect) workthread = WorkThread() workthread.start() else: connected = False print("Connection failed.") def disconnect(): global connection, connected, workthread connection.close() connected = False workthread.join() workthread = None app.menubar.entryconfigure(2, label="Connect", command=connect) if __name__ == '__main__': comport = None connection = None connected = False workthread = None app = Main() app.mainloop() Answer: This is some pretty nice code; it's clear what is happening here. use informative names from threading import * class Main(tk.Tk): That's a bit generic. Consider using something more descriptive, perhaps: class BlackPillGui(tk.Tk): And that * star is just annoying. Please prefer from threading import Thread. globals?!? global connection, connected, workthread connection.close() Two concerns here. Prefer to put these in an object or datastructure, instead of using the global namespace. No need to declare global connection since you don't assign to it. The subsequent undeclared app reference offers an illustration of such use.
{ "domain": "codereview.stackexchange", "id": 44673, "lm_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, tkinter, gui", "url": null }
python, tkinter, gui don't represent the same concept two ways I am sad to see the connected boolean being introduced. It appears it is always identical to if connection is not None:, or just if connection:. Recommend you elide it. Kudos on using an if __name__ == '__main__': guard. Though frankly, since everything relies on Tk, it's not like a unit test could import this module and usefully test it. restraint in comments ### Menu Configuration ############################################################################### Uggh, ASCII art! If there's some coding standard which requires this, that you're trying to adhere to, then cite the reference. Otherwise, pep-8 asks that you show some restraint. In particular, when you lint your code you are apparently inhibiting E266 messages in your .flake8 config file: E266 too many leading '#' for block comment layout, magic numbers The GPIO canvas has a bunch of magic numbers for layout, with relationships among some of them. self.gpio_canvas.create_text(25, 55, text="Port A") self.gpio_canvas.create_text(25, 70, text="Port B") IDK, maybe that's OK? Consider defining things like LEFT_MARGIN = 25. comments suggest helpers The fact that you felt it necessary to point out the begin / end of Menu Configuration, and of GPIO Canvas, suggests that the __init__ ctor should have a pair of helpers: def menu_config(self): ... def gpio_canvas(self): ... use conventional names def updatePinDisplay(self, portid, pinvalues): Pep8 asks that you spell it update_pin_display. Pleaseconsiderclarifyingcertainnames such as com_port, ok_button, port_id, and pin_values. optional type hints to help the reader The plural pin values name was very helpful, thank you. And the "right shift i places" soon clarifies things. Still, when I read the signature I had in mind there was a container of values, rather than a bit vector encoded as an int. Declaring ...(self, port_id: str, pin_values: int):
{ "domain": "codereview.stackexchange", "id": 44673, "lm_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, tkinter, gui", "url": null }
python, tkinter, gui would be a kindness to the Gentle Reader. (Plus, mypy could help with linting it if you like.) mapping for business logic if pinvalue: self.gpio_canvas.itemconfig(self.ports[portid][i], fill="green2") else: self.gpio_canvas.itemconfig(self.ports[portid][i], fill="green") You can DRY up the pin coloring in this way: pin_colors = ["green", "green2"] self.gpio_canvas.itemconfig(self.ports[port_id][i], fill=pin_colors[pin_value]) This avoids pasting a pair of similar calls to itemconfig. simplify nested loops while connection.is_open: while connection.in_waiting: Recommend a simple conjunct: while (connection.is_open: and connection.in_waiting): I worry a little about failure modes, and the UX. I imagine there may be off-nominal situations where we loop forever, not obtaining any text lines. Maybe it would be useful to print() or to update a Tk text box, letting the user know we're awaiting input? And then immediately blank it out, once the input is received. no bare excepts def connect(): ... except: pass Disabling CTRL/C KeyboardInterrupt is not what you want. Prefer except Exception: Also, you could simplify print(str(e)) to the identical print(e). This code is clear, and achieves its design objectives. I would be willing to delegate or accept maintenance tasks on this codebase.
{ "domain": "codereview.stackexchange", "id": 44673, "lm_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, tkinter, gui", "url": null }
php, html, classes, form, php7 Title: PHP HTML form Class - so far so good?
{ "domain": "codereview.stackexchange", "id": 44674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html, classes, form, php7", "url": null }
php, html, classes, form, php7 Question: I am writing this class to render HTML forms. It is working as expected, so far. There are many things to be done yet (including testing). Is it ok to keep this way? /** * * This class renders (or aims to render) a valid HTML form * * Note: this documentation still needs to be completed. For now I think it does its job. * * Condensed usage: * * $form = new Form(["name"=>"myform", "method"=>"post", "action" =>"action.php", "id"=>"html_id"]); * $form->add_field(["fieldset"]); * $form->add_field(["label", ["value"=>"My Label", "for"=>"txtareaname"]]); * $form->add_field(["textarea", ["id"=>"txtareaid", "name"=>"txtareaname", "cols"=>80, "rows"=>10, "value"=>"Texto del textarea"]]); * $form->add_field(["fieldset"]); * $form->add_field(["select",["name"=>"myselect"], ["value1"=>"text1", "value2"=>"text2"]]); * $form->add_field(["text", ["name"=>"mytext", "value"=>"", "required"=>""]]); * $form->add_field(["fieldset"]); * $form->add_field(["label", ["for"=>"mycheck", "value"=>"My check?"]]); * $form->add_field(["checkbox", ["name"=>"mycheck", "value"=>"mycheck", "id"=>"mycheck"]]); * $form->add_field(["fieldset"]); * $form->add_field(["submit", ["name"=>"enviar", "value"=>"enviar"]]); * echo $form->render(); // or $output = $form->render(); * * * When this class is instantiated it takes a key-value array where the keys are any valid <form> attribute and the values * are its corresponding attribute value. There are 3 mandatory attributes: name, method and action. * Any other attribute, if present, must have a value, so it cannot be an empty string. So for a basic usage: * * $form = new Form(["name"=>"myform", "method"=>"post", "action"=>"destination.php", "id"=>"form_id"]); * echo $form->render(); * * Should output something similar to: * * <form name="myform" action="destination.php" method="post" id="form_id"> * * </form> *
{ "domain": "codereview.stackexchange", "id": 44674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html, classes, form, php7", "url": null }
php, html, classes, form, php7 * * </form> * * For adding fields add_field() is used. It takes a multidimensional array (keys are ignored) where the first * element (key [0]) is the HTML form input tag name (button, select, fieldset, etc.). * The second element (optional in some cases) is a key-value array where the keys are any valid attribute for that HTML * element * and the value its corresponding value. Optionally, it can take a 3rd element when a select or optgroup is inserted. * This 3rd element is also a key-value array where the keys are option's value attribute and the values are the text * to show. * * As well as <form> each element may have its own mandatory attributes and they will be checked. * * To add a text field: * * $form = new Form(["name"=>"myform", "method"=>"post", "action"=>"destination.php"]); * $form->add_field(["input", ["type"=>"text", "name"=>"mytext", "required"=>true, "value"=>"bool(true)"]]); * $form->add_field(["input", ["type"=>"text", "name"=>"myothertext", "required"=>"cheese tax", "value"=>"cheese tax"]]); * echo $form->render(); * * Should output something like: * * <form name='myform' action='destination.php' method='post'> * <input type='text' name='mytext' value='bool(true)' required> * <input type='text' name='myothertext' value='cheese tax' required> * </form> * * This example below should render something like the example above. Notice the add_field() method: * * $form = new Form(["name"=>"myform", "method"=>"post", "action"=>"destination.php"]); * $form->add_field(["text", ["name"=>"mytext", "required"=>""], "value"=>"string(0)"]); * $form->add_field(["text", ["name"=>"myothertext", "required"=>null, "value"=>null]]); * echo $form->render(); * * Output: * * <form name='myform' action='destination.php' method='post'>
{ "domain": "codereview.stackexchange", "id": 44674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html, classes, form, php7", "url": null }
php, html, classes, form, php7 * Output: * * <form name='myform' action='destination.php' method='post'> * <input type='text' name='mytext' value='string(0)' required> * <input type='text' name='myothertext' value='' required> * </form> * * * As <input> or <button> can be "tricky" due to the amount of types it is allowed to use the type of input * as (pseudo) element. * * Note that with boolean attributes (such as required or autofocus), if present, no matter its value, will be added. * * To insert a <select>: * * $form->add_field(["select",["name"=>"control_select"], ["value1"=>"text1", "value2"=>"text2"]]); * * To insert a <label> bind to a <textarea>: * * $form->add_field(["label", ["value"=>"My label", "for"=>"txtareaname"]]); * $form->add_field(["textarea", ["id"=>"txtareaid", "name"=>"txtareaname", "cols"=>80, "rows"=>10, "value"=>"Texto del textarea"]]); * * In the cases of labels and textareas the value attribute is considered as the text to show. * * To insert a <fieldset>: * * $form->add_field(["fieldset"]); * $form->add_field(["label", ["value"=>"My label", "for"=>"txtareaname"]]); * $form->add_field(["textarea", ["id"=>"txtareaid", "name"=>"txtareaname", "cols"=>80, "rows"=>10, "value"=>"Texto del textarea"]]); * * Take into consideration that fieldsets are closed in render() method. So if you need to add several fieldsets: * * $form->add_field(["fieldset"]); * $form->add_field(["label", ["value"=>"Etiqueta", "for"=>"txtareaname"]]); * $form->add_field(["textarea", ["id"=>"txtareaid", "name"=>"txtareaname", "cols"=>80, "rows"=>10, "value"=>"Texto del textarea"]]); * $form->add_field(["fieldset"]); * $form->add_field(["select",["name"=>"control_select"], ["value1"=>"text1", "value2"=>"text2"]]);
{ "domain": "codereview.stackexchange", "id": 44674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html, classes, form, php7", "url": null }
php, html, classes, form, php7 * $form->add_field(["text", ["name"=>"mytext", "value"=>"", "required"=>""]]); * $form->add_field(["fieldset"]); * $form->add_field(["label", ["for"=>"mycheck", "value"=>"My check?"]]); * $form->add_field(["checkbox", ["name"=>"mycheck", "value"=>"mycheck", "id"=>"mycheck"]]); * $form->add_field(["fieldset"]); * $form->add_field(["submit", ["name"=>"enviar", "value"=>"enviar"]]); * * * This class produces (or at least aims to produce) a valid HTML form block so when an error occurs an exception is raised. * Errors that may occur are incomplete data fields, missing mandatory attributes (or its values) * or trying to use an illegal form element. * * There are certain attributes like role or event handlers for example that are not supported yet. * Custom or non-standard attributes are not allowed yet. It is planned for the future. * Also it does not verifies for valid attribute's values (will be added in the future). * Javascript is not allowed yet. It is planned for the future. However, I have been told that javascript should be handled via event listeners, so.... * Nested forms or subforms are not allowed. * No sanitization is done as this class outputs HTML code straight for echoing so it is not safe to be stored in * a database and user input validation or any other kind of validation is up to the developer. * * Arrays for handling the form elements and its attributes could be optimized. I did not want to have infinite * multidimensional arrays and I think it is easier to maintain and to read as it is. It may require some extra * if and foreach statements this way. * * In the future I plan to add strict and non-strict operation modes to allow flexibility and more customization. * * In the meantime I need to improve what I have until now. I still need to polish elements special treatment, error
{ "domain": "codereview.stackexchange", "id": 44674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html, classes, form, php7", "url": null }
php, html, classes, form, php7 * handling, array optimization and logic. * * Should other HTML tags such as <br>, <p>, and others be allowed? If I allow them, then I should think bigger than * just a class for HTML forms.... I just wanted a simple class to render forms * * */ class Form { /** in here each add_field() valid output is stored. it is looped in render() */ private $output_elements = array(); private $form_elements = ['input', 'label', 'select', 'textarea', 'button', 'fieldset', 'legend', 'datalist', 'output', 'option', 'optgroup']; private $form_elements_types = array( 'input' => ['button', 'checkbox', 'color', 'date', 'datetime-local', 'email', 'file', 'hidden', 'image', 'month', 'number', 'password', 'radio', 'range', 'reset', 'search', 'submit', 'tel', 'text', 'time', 'url', 'week'], 'button' => ['submit', 'reset', 'button'], ); private $form_elements_common_attr = ['id', 'class', 'accesskey', 'style', 'tabindex']; private $form_elements_required_attr = array( 'form' => ['name', 'action', 'method'], 'select' => ['name'], 'textarea' => ['name', 'cols', 'rows'], 'button' => ['name', 'value'], 'option' => ['value', 'text'], 'input' => ['type', 'name', 'value'], ); private $form_elements_specific_attr = array( 'form' => ['target', 'enctype', 'autocomplete', 'rel', 'novalidate'], 'label' => ['for'], 'select' => ['autocomplete', 'autofocus', 'disabled', 'form', 'multiple', 'required', 'size'], 'textarea' => ['autocomplete', 'autofocus', 'disabled', 'form', 'maxlength', 'minlength', 'placeholder', 'readonly', 'required'], 'button' => ['autofocus', 'disabled', 'form', 'formaction', 'formenctype', 'formmethod', 'formtarget', 'formnovalidate'],
{ "domain": "codereview.stackexchange", "id": 44674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html, classes, form, php7", "url": null }
php, html, classes, form, php7 'fieldset' => ['disabled', 'form'], 'legend' => [], 'datalist' => [], 'output' => ['for', 'form'], 'option' => ['disabled', 'label', 'selected'], 'optgroup' => ['disabled', 'label'], 'input' => ['disabled', 'required'], 'checkbox' => ['checked'], 'color' => [], 'date' => ['max', 'min', 'step'], 'datetime-local' => ['max', 'min', 'step'], 'email' => ['list', 'maxlength', 'minlength', 'multiple', 'pattern', 'placeholder', 'readonly', 'size'], 'file' => ['accept', 'capture', 'multiple'], 'hidden' => [], 'image' => ['alt', 'formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget', 'height', 'src', 'width'], 'month' => ['list', 'max', 'min', 'readonly', 'step'], 'number' => ['list', 'max', 'min', 'placeholder', 'readonly', 'step'], 'password' => ['maxlength', 'minlength', 'pattern', 'placeholder', 'readonly', 'size'], 'radio' => ['checked', 'required'], 'range' => ['list', 'max', 'min', 'step'], 'reset' => [], 'search' => ['list', 'maxlength', 'minlength', 'pattern', 'placeholder', 'readonly', 'size', 'spellcheck'], 'submit' => ['formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget'], 'tel' => ['list', 'maxlength', 'minlength', 'pattern', 'placeholder', 'readonly', 'size'], 'text' => ['list', 'maxlength', 'minlength', 'pattern', 'placeholder', 'readonly', 'size', 'spellcheck'], 'time' => ['list', 'max', 'min', 'readonly', 'step'], 'url' => ['list', 'maxlength', 'minlength', 'pattern', 'placeholder', 'readonly', 'size', 'spellcheck'], 'week' => ['max', 'min', 'readonly', 'step'] ); private $form_elements_forbidden_attr = array(); // to implement in the future
{ "domain": "codereview.stackexchange", "id": 44674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html, classes, form, php7", "url": null }
php, html, classes, form, php7 private $form_elements_forbidden_attr = array(); // to implement in the future private $form_tag_closing = ['label', 'select', 'textarea', 'legend', 'option']; /** * * @param array $form Asociative array where the keys are the form tag attributes and the values the attribute's value * @throws Exception * * Attributes name, action and method are mandatory and cannot be empty. * The rest of the attributes, if set must have a valid value. * * Usage: * * $form = new Form(['name'=>'myform', 'action'=>'action.php', 'method'=>'post']); * * Result: * * <form name='myform' action='action.php' method='post'> * */ function __construct(array $form) { $output = "<form"; if (empty($form)) throw new Exception("Form data cannot be empty"); // this foreach could be implemented in, for example, check_required_attr() method... don't figure out if useful foreach($this->form_elements_required_attr['form'] as $attr) { if (!array_key_exists($attr, $form)) throw new Exception("Form attribute '$attr' is mandatory"); if (empty($form[$attr])) throw new Exception("Form attribute '$attr' value cannot be an empty string"); $output .= " $attr='$form[$attr]'"; } foreach($this->form_elements_specific_attr['form'] as $attr) { if (array_key_exists($attr, $form)) { if (empty($form[$attr])) throw new Exception("Form attribute '$attr' cannot be an empty string"); $output .= " $attr='$form[$attr]'"; } } foreach($this->form_elements_common_attr as $attr) { if (array_key_exists($attr, $form)) {
{ "domain": "codereview.stackexchange", "id": 44674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html, classes, form, php7", "url": null }
php, html, classes, form, php7 if (array_key_exists($attr, $form)) { if (empty($form[$attr])) throw new Exception("Form attribute '$attr' cannot be an empty string"); $output .= " $attr='$form[$attr]'"; } } $output .= ">"; $this->output_elements[] = $output; } function add_field(array $data) { $output = null; $element = null; $type = null; $attributes = null; $options = null; if (empty($data)) throw new Exception("Field data cannot be empty"); if (count($data) < 1) throw new Exception("Field data should be an array of at least one element"); $element = $data[array_keys($data)[0]]; // done this way in case user uses associative array. Should I issue a warning relative to function's parameter format? if (empty($element) or !is_string($element)) throw new Exception("Form element's name should contain only letters."); // maybe here I should use a regexp. O maybe delete it as later on is checked against an array... however, I consider it an important advice // attributes if (count($data) >= 2) { $attributes = $data[array_keys($data)[1]]; if (!is_array($attributes)) throw new Exception("Field attributes (2nd element in parameter array) should be an (empty) array"); } // options for select, optgroup, etc. if (count($data) >= 3) { $options = $data[array_keys($data)[2]]; if (!is_array($options)) throw new Exception("Options parameter (3rd element in parameter array) should be an array"); if (count($options) < 1) throw new Exception("Options cannot be empty"); // maybe yes (for JS, x ex)? } // check for allowed controls considering "trickyness" on input or button types
{ "domain": "codereview.stackexchange", "id": 44674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html, classes, form, php7", "url": null }
php, html, classes, form, php7 // check for allowed controls considering "trickyness" on input or button types $found = false; if (!in_array($element, $this->form_elements)) { foreach ($this->form_elements_types as $s_element => $s_types) { if (in_array($element, $s_types)) { $type = $element; $element = $s_element; $found = true; break; } } } else { $found = true; } if (!$found) throw new Exception("'$element': illegal form (type) element"); unset($found); $output .= "<$element"; if (array_key_exists($element, $this->form_elements_required_attr)) { foreach($this->form_elements_required_attr[$element] as $attr) { // input or button if (($attr == "type") and !is_null($type)) { // I have doubts on this validation... needs a better check $output .= " type='$type'"; } else { if (!array_key_exists($attr, $attributes)) { // yes yes, messages need to be handled better... I'll get to that later if (!is_null($type)) throw new Exception("'$element $type' attribute '$attr' is mandatory"); throw new Exception("'$element attribute '$attr' is mandatory"); } // value is the only attribute that can be an empty string but it's mandatory if (($attr != "value") and empty($attributes[$attr])) { if (!is_null($type)) throw new Exception("'$element $type' attribute '$attr' cannot be empty"); throw new Exception("$element attribute '$attr' cannot be empty"); }
{ "domain": "codereview.stackexchange", "id": 44674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html, classes, form, php7", "url": null }
php, html, classes, form, php7 } $output .= " $attr='".$attributes[$attr]."'"; } } } // element has specific non-mandatory attributes if (array_key_exists($element, $this->form_elements_specific_attr) and (!is_null($attributes))) { foreach($this->form_elements_specific_attr[$element] as $attr) { if (array_key_exists($attr, $attributes)) { if (($attr == "required") or ($attr == "autofocus")) $output .= " $attr"; else $output .= " $attr='" . $attributes[$attr] . "'"; } } } if (!is_null($attributes)) { foreach($this->form_elements_common_attr as $attr) { if (array_key_exists($attr, $attributes) and !empty($attributes[$attr])) $output .= " $attr='" . $attributes[$attr] . "'"; } } $output .= ">"; if ($element == "select") { foreach($options as $value => $text) $output .= "\n<option value='$value'>$text</option>"; } // in this cases (textarea, label, etc.) pseudo-attribute value is used as the element's text if (($element != "input") and ($element != "select")) $output .= $attributes['value']; if (in_array($element, $this->form_tag_closing)) $output .= "</$element>"; $this->output_elements[] = $output; } function render() { $output = null; $open_fieldsets = 0; foreach($this->output_elements as $element) { // to handle fieldsets I thought of adding a special attribute to: ["fieldset", ["close"=>true]], but not sure if (strpos($element, "fieldset") !== false) { if ($open_fieldsets > 0) { $output .= "\n</fieldset>";
{ "domain": "codereview.stackexchange", "id": 44674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html, classes, form, php7", "url": null }
php, html, classes, form, php7 if ($open_fieldsets > 0) { $output .= "\n</fieldset>"; $open_fieldsets--; } $open_fieldsets++; } $output .= "\n".$element; } if ($open_fieldsets != 0) $output .= "\n</fieldset>"; return $output . "\n</form>\n"; // return "\n".implode("\n", $this->output_elements)."\n</form>"; } }
{ "domain": "codereview.stackexchange", "id": 44674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html, classes, form, php7", "url": null }
php, html, classes, form, php7 Besides trying to write as standard as I am able I am trying to write something that someone else would use or at least, hopefully, use as a good starting example to more advanced developers. Answer: I have not conducted a deep review of your scripting, but I have a few pieces of superficial advice: Study PSR-12 coding standards and obey every rule. This will make your code easier for you and others to read. Specifically pay attention to when and where to write curly braces. I see A LOT of misuses/abuses of empty(). The call is most appropriate when needing to determine two things at the same time: When a variable is not declared AND when the value is falsey (which includes a zero). If a variable is unconditionally declared in a method's signature, then empty() can be replaced with a function-less truthy check or strlen() if desired. Calling empty() after isset() or array_key_exists() or key_exists() is an antipattern for the same reason. Checking count($data) < 1 after !empty() will never be satified. An empty array is "falsey" data. Use return type declarations like void and string where appropriate. I endorse the use of the sprintf() or vsprintf() to print variables to strings. This will make it easier to use double quotes in your generated HTML markup. I personally never use and or or in PHP code. This helps to avoid precedence issues and assures code consistency. Endeavor to never use magic numbers. Even checks against 1 or 2 should be avoided. If these numbers have a logical meaning, declare class level constants with indicative names which logically explain their use. If your class variables (private properties) are not expected to change, write them as constants. While much of the PHP applications running on the web are building HTML markup from PHP files, there is a growing trend to use client-side languages to generate and populate HTML documents.
{ "domain": "codereview.stackexchange", "id": 44674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html, classes, form, php7", "url": null }
php, html, classes, form, php7 When possible, try to avoid using vague variable names like $data, $output, etc. Indicative variable names like $attr, $tag, $form, and $html add meaning. As a general cue, when you find a variable declaration in a method signature that is identical to its neighboring type declaration, this is a symptom that an opportunity to convey meaning is being missed. I never declare a variable as null if it is intended to contain array-type data (see $attributes). It will be cleaner to define it as an empty array, populate it if appropriate, not check if is is an array later, and simply access it. LATE EDIT: here is an untested rewrite of the add_field() method implementing some of my advice above. Note: I don't personally like to use snake_case in my projects and I think that the logical segments of this method should be abstracted into small methods which can then be more easily managed and potentially overridden. /** * @throws Exception */ public function add_field(string $tag_name, array $attributes = [], array $options = []): void { // validate tag name if (!preg_match('/^[a-z][\w-]*$/i', $tag_name)) { // this is not well researched throw new Exception('Name of form element is not valid'); } $html = ''; $type = null; // accommodate fringe case tag names if (!in_array($tag_name, $this->form_elements)) { $found = false; foreach ($this->form_elements_types as $sub_element => $sub_types) { if (in_array($tag_name, $sub_types)) { $type = $tag_name; $tag_name = $sub_element; $found = true; break; } } if (!$found) { throw new Exception($tag_name . ': illegal form (type) element'); } } $html .= "<$tag_name";
{ "domain": "codereview.stackexchange", "id": 44674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html, classes, form, php7", "url": null }
php, html, classes, form, php7 $html .= "<$tag_name"; // required attributes foreach ($this->form_elements_required_attr[$tag_name] ?? [] as $attr) { if (!key_exists($attr, $attributes)) { throw new Exception( sprintf( '"%s%s" attribute "%s" is mandatory', $tag_name, $type === null ? '' : " $type", $attr ) ); } if ($attr !== 'value' && !strlen($attributes[$attr])) { throw new Exception( sprintf( '"%s%s" attribute "%s" cannot be empty', $tag_name, $type === null ? '' : " $type", $attr ) ); } // append valid attribute if ($attr === "type" && $type) { $html .= sprintf( ' %s="%s"', $attr, htmlentities($type ?? $attributes[$attr]) ); } } // optional attributes foreach ($this->form_elements_specific_attr[$tag_name] ?? [] as $attr) { if (key_exists($attr, $attributes)) { $html .= sprintf( ' %s%s', $attr, in_array($attr, ['required', 'autofocus']) ? '' : ' "' . htmlentities($attributes[$attr]) . '"' ); } } // common attributes foreach ($this->form_elements_common_attr as $attr) { if (key_exists($attr, $attributes) && strlen($attributes[$attr])) { $html .= sprintf( ' %s="%s"', $attr, htmlentities($attributes[$attr]) ); } } $html .= ">";
{ "domain": "codereview.stackexchange", "id": 44674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html, classes, form, php7", "url": null }
php, html, classes, form, php7 $html .= ">"; // build <select> options if ($tag_name == "select") { // todo: shouldn't <optgroup> tags be implemented here? // todo: how does a developer designate the selected option? // todo: what about multiselect fields? foreach ($options as $value => $text) { $html .= sprintf( "\n<option%s>%s</option>", $value === $text ? '' : ' value="' . htmlentities($text) . '"', $text ); } // append pseudo-attribute value as element's text (e.g. textarea, label, etc.) } elseif ($tag_name !== 'input' && key_exists('value', $attributes)) { $html .= htmlentities($attributes['value']); } // append closing tag if (in_array($tag_name, $this->form_tag_closing)) { $html .= "</$tag_name>"; } $this->output_elements[] = $html; }
{ "domain": "codereview.stackexchange", "id": 44674, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html, classes, form, php7", "url": null }
python, scrapy Title: Save data in item wihitn Scrapy and Python Question: I need to store data in Scrapy Item in parts. To update only the information that I found at the moment. I did it, but the code looks too verbose. Three lines I repeat very often: price['pricereg'] = pricereg price['priceprolong'] = priceprolong price['pricechange'] = pricechange Is it possible to make the code shorter? EMPTY_PRICE = { 'pricereg': None, 'priceprolong': None, 'pricechange': None, } item['name'] = "some name" price = item.get('price', EMPTY_PRICE) price['pricereg'] = pricereg price['priceprolong'] = priceprolong item['price'] = price item['name'] = "some name" price = item.get('price', EMPTY_PRICE) price['pricechange'] = pricechange item['price'] = price Answer: Have you tried using a collections.namedtuple or a dataclasses.dataclass rather than a dict? from collections import namedtuple Item = namedtuple('Item', ['name', 'pricereg', 'priceprolong', 'price'], defaults=['', None, None, None]) EMPTY_ITEM = Item() item['name'] = Item('name', pricereg, priceprolong, price) print(item['name']._asdict()) or from dataclasses import dataclass @dataclass class Item: name: str pricereg: int|None = None priceprolong: int|None = None price: int|None = None EMPTY_ITEM = Item() item['name'] = Item('name', pricereg, priceprolong, price) print(item['name'].pricereg) alternatively, if you're just setting the dict in one go: item['name'] = {'pricereg': pricereg, 'priceprolong': priceprolong, 'pricechange': pricechange if pricechange else None, # For defaults 'price': price} If it's to do with setting it up in parts, you can build the dict with the parts you have and do a dict.update item['name'] = {'pricereg': pricereg, 'priceprolong': priceprolong}
{ "domain": "codereview.stackexchange", "id": 44675, "lm_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, scrapy", "url": null }
python, scrapy tmp = { 'pricechange': pricechange if pricechange else None, # For defaults 'price': price} item['name'].update(tmp)
{ "domain": "codereview.stackexchange", "id": 44675, "lm_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, scrapy", "url": null }
python, performance, python-3.x, genetic-algorithm, traveling-salesman Title: Solving The Travelling Salesman Problem Using Genetic Algorithm Question: I was looking to learn about AI and found the traveling salesman problem very interesting. I also wanted to learn about genetic algorithms, so it was a fantastic combo. To clarify, this is my second project in Python, so the code might look ugly. I thought it would be better to have someone check the code and give me feedback on what I can do better to refactor or change stuff for my next projects. The task has some restrictions: The location id 1 must be the starting and the ending point The maximum distance allowed is distance <= 9000 The fitness calculation cant exceed 250000 Code: import numpy as np import random import operator import pandas as pd val10 = 0 val9 = 0 class Locations: def __init__(self, x, y): self.x = x self.y = y def dist(self, location): x_dist = abs(float(self.x) - float(location.x)) y_dist = abs(float(self.y) - float(location.y)) # √( (x2 − x1)^2 + (2 − 1)^2 ) dist = np.sqrt((x_dist ** 2) + (y_dist ** 2)) return dist def __repr__(self): return "(" + str(self.x) + "," + str(self.y) + ")" class Fitness: def __init__(self, route): self.r = route self.dist = 0 self.fit = 0.0 def route_dist(self): if self.dist == 0: path_dist = 0 for i in range(0, len(self.r)): from_location = self.r[i] to_location = None if i + 1 < len(self.r): to_location = self.r[i+1] else: to_location = self.r[0] path_dist += from_location.dist(to_location) self.dist = path_dist return self.dist def route_fittness(self): if self.fit == 0: self.fit = 1 / float(self.route_dist()) global val9 val9 = val9 + 1 return self.fit
{ "domain": "codereview.stackexchange", "id": 44676, "lm_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, genetic-algorithm, traveling-salesman", "url": null }
python, performance, python-3.x, genetic-algorithm, traveling-salesman def generate_route(location_list): route = random.sample(location_list, len(location_list)) return route def gen_zero_population(size, location_list): population = [] for i in range(0, size): population.append(generate_route(location_list)) return population def determine_fit(population): result = {} for i in range(0, len(population)): result[i] = Fitness(population[i]).route_fittness() global val10 val10 = val10 + 1 return sorted(result.items(), key=operator.itemgetter(1), reverse=True) def fit_proportionate_selection(top_pop, elite_size): result = [] df = pd.DataFrame(np.array(top_pop), columns=["index", "Fitness"]) df['cumulative_sum'] = df.Fitness.cumsum() df['Sum'] = 100*df.cumulative_sum/df.Fitness.sum() for i in range(0, elite_size): result.append(top_pop[i][0]) for i in range(0, len(top_pop) - elite_size): select = 100*random.random() for i in range(0, len(top_pop)): if select <= df.iat[i, 3]: result.append(top_pop[i][0]) break return result def select_mating_pool(populatoin, f_p_s_result): mating_pool = [] for i in range(0, len(f_p_s_result)): index = f_p_s_result[i] mating_pool.append(populatoin[index]) return mating_pool def ordered_crossover(p1, p2): child, child_p1, child_p2 = ([] for i in range(3)) first_gene = int(random.random() * len(p1)) sec_gene = int(random.random() * len(p2)) start_gene = min(first_gene, sec_gene) end_gene = max(first_gene, sec_gene) for i in range(start_gene, end_gene): child_p1.append(p1[i]) child_p2 = [item for item in p2 if item not in child_p1] child = child_p1 + child_p2 return child def ordered_crossover_pop(mating_pool, elite_size): children = [] leng = (len(mating_pool) - (elite_size)) pool = random.sample(mating_pool, len(mating_pool))
{ "domain": "codereview.stackexchange", "id": 44676, "lm_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, genetic-algorithm, traveling-salesman", "url": null }
python, performance, python-3.x, genetic-algorithm, traveling-salesman leng = (len(mating_pool) - (elite_size)) pool = random.sample(mating_pool, len(mating_pool)) for i in range(0, elite_size): children.append(mating_pool[i]) for i in range(0, leng): var = len(mating_pool)-i - 1 child = ordered_crossover(pool[i], pool[var]) children.append(child) return children def swap_mutation(one_location, mutation_rate): for i in range(len(one_location)): if (random.random() < mutation_rate): swap = int(random.random() * len(one_location)) location1 = one_location[i] location2 = one_location[swap] one_location[i] = location2 one_location[swap] = location1 return one_location def pop_mutation(population, mutation_rate): result = [] for i in range(0, len(population)): mutaded_res = swap_mutation(population[i], mutation_rate) result.append(mutaded_res) return result def next_gen(latest_gen, elite_size, mutation_rate): route_rank = determine_fit(latest_gen) selection = fit_proportionate_selection(route_rank, elite_size) mating_selection = select_mating_pool(latest_gen, selection) children = ordered_crossover_pop(mating_selection, elite_size) next_generation = pop_mutation(children, mutation_rate) return next_generation def generic_algor(population, pop_size, elite_size, mutation_rate, gen): pop = gen_zero_population(pop_size, population) print("Initial distance: " + str(1 / determine_fit(pop)[0][1])) for i in range(0, gen): pop = next_gen(pop, elite_size, mutation_rate) print("Final distance: " + str(1 / determine_fit(pop)[0][1])) best_route_index = determine_fit(pop)[0][0] best_route = pop[best_route_index] print(best_route) return best_route
{ "domain": "codereview.stackexchange", "id": 44676, "lm_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, genetic-algorithm, traveling-salesman", "url": null }
python, performance, python-3.x, genetic-algorithm, traveling-salesman def read_file(fn): a = [] with open(fn) as f: [next(f) for _ in range(6)] for line in f: line = line.rstrip() if line == 'EOF': break ID, x, y = line.split() a.append(Locations(x=x, y=y)) return a location_list = read_file(r'path_of_the_file') population = location_list pop_size = 100 elite_size = 40 mutation_rate = 0.01 gen = 100 generic_algor(population, pop_size, elite_size, mutation_rate, gen) print(val10) print(val9) Location file with x and y coordinates |Locations | |52 Locations | |Coordinates | 1 565.0 575.0 2 25.0 185.0 3 345.0 750.0 4 945.0 685.0 5 845.0 655.0 6 880.0 660.0 7 25.0 230.0 8 525.0 1000.0 9 580.0 1175.0 10 650.0 1130.0 11 1605.0 620.0 12 1220.0 580.0 13 1465.0 200.0 14 1530.0 5.0 15 845.0 680.0 16 725.0 370.0 17 145.0 665.0 18 415.0 635.0 19 510.0 875.0 20 560.0 365.0 21 300.0 465.0 22 520.0 585.0 23 480.0 415.0 24 835.0 625.0 25 975.0 580.0 26 1215.0 245.0 27 1320.0 315.0 28 1250.0 400.0 29 660.0 180.0 30 410.0 250.0 31 420.0 555.0 32 575.0 665.0 33 1150.0 1160.0 34 700.0 580.0 35 685.0 595.0 36 685.0 610.0 37 770.0 610.0 38 795.0 645.0 39 720.0 635.0 40 760.0 650.0 41 475.0 960.0 42 95.0 260.0 43 875.0 920.0 44 700.0 500.0 45 555.0 815.0 46 830.0 485.0 47 1170.0 65.0 48 830.0 610.0 49 605.0 625.0 50 595.0 360.0 51 1340.0 725.0 52 1740.0 245.0 EOF Result Initial distance: 26779.322835840427 Final distance: 16291.285326058354
{ "domain": "codereview.stackexchange", "id": 44676, "lm_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, genetic-algorithm, traveling-salesman", "url": null }
python, performance, python-3.x, genetic-algorithm, traveling-salesman Result Initial distance: 26779.322835840427 Final distance: 16291.285326058354 Answer: Overall, your code works (as said in the comments, it can reach your target if you tweak the parameters) and is pretty nice to look at, so good job! There are some things that can be improved, as there always are, here are some that I can see: Globals Using globals is dangerous and should be avoided. In your cases, one of these global variable is basically the generation count and the other population size * generation count. They can be removed without losing any value. Naming Your variable names need some love. Most of them are fine, but: some are misspelled: populatoin instead of population, generic_algor instead of genetic_algor some are undescriptive: val9, val10, fn some are needlessly abbreviated: pop, dist, genetic_algor Constants naming conversions: Constants are usually named in ALL_CAPS, allowing to clearly differentiate them for variables. In your case, these would be the genetic algorithm's parameters and the path to the location list. Throwaway variables You assign values to variables and never use them again. This happens in tuple unpacking and in loops. The convention is to use _ as a variable name in cases where this can't be avoided: for _ in range(foo): pass _, x, y = line.split() range parameters When using range, you usually specify 2 parameters, the first one being 0, which should be omitted for readability. Looping over collections You loop over indices in for loops: for i in range(foo): # do things with bars[i] In Python, it is preferred to loop over items in a collection directly: for bar in bars: # do things with bar List comprehensions In several places, you create an empty list then repeatedly append values in a loop. This can usually be replaced by a list comprehension, for better readability and performance: def gen_zero_population(size, location_list): return [generate_route(location_list) for _ in range(size)]
{ "domain": "codereview.stackexchange", "id": 44676, "lm_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, genetic-algorithm, traveling-salesman", "url": null }
python, performance, python-3.x, genetic-algorithm, traveling-salesman def pop_mutation(population, mutation_rate): return [swap_mutation(route, mutation_rate) for route in population] File parsing Your input file parsing function is hardcoded to skip the first 6 lines of the file, which are apparently comments. You can expect the actual data line to follow a certain convention, but you can't expect another location list file to have the same number of comments, including blank ones. The fix would be to skip every line that starts with a comment marker (|in your case) instead. Here's how I would do it: def read_location_file(path): locations = [] with open(path, 'r') as f: for line in f: line = line.strip() if line.startswith('|'): continue if line == 'EOF': break _, x, y = line.split() locations.append(Locations(float(x), float(y))) return locations Overkill Pandas dependency Running the algorithm can get a bit long, which makes tweaking the parameters tedious. Running a profiler on your code shows that more than 70% of execution time is spent getting values in at Pandas dataframe. Refactoring your fit_proportionate_selection method to work with arrays instead of a dataframe would probably greatly reduce running time. It would probably be much more efficient to build a cumsum and sum (probably a poor naming choice here, this doesn't look like a sum) array using numpy (see np.cumsum) and index into those arrays instead of building a dataframe and indexing into it. Alternatively, you could keep the dataframe and take advantage of Pandas' capabilities to access whole ranges at a time. Overkill Fitness class There is no point in having a full class to calculate the fitness of a route, and the whole class can be reduced to a simple function: def fitness(route): route_length = sum(route[i].dist(route[(i+1) % len(route)]) for i in range(len(route))) return 1 / route_length
{ "domain": "codereview.stackexchange", "id": 44676, "lm_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, genetic-algorithm, traveling-salesman", "url": null }
python, performance, python-3.x, genetic-algorithm, traveling-salesman Saving on complexity and allocations. Seed the RNG Execution of the algorithm rely on a random number generator. When refactoring/debugging, it can help to have consistent output, in which case you probably want to add a line akin to: random.seed(1) at the start of your script. Use a main guard You should put all top-level executed statements after a if __name__ == '__main__': guard, allowing you to reuse the function and classes in your module more easily in the future. Use string interpolation Instead of concatenating multiple strings with +, use f-strings to interpolate variables inside a string: f'({self.x}, {self.y})' instead of "(" + str(self.x) + "," + str(self.y) + ")". Don't sort a dict determine_fit returns a dict sorted by value. Dictionaries are not ordered collections. The fact that they preserve order is merely an implementation detail and can't be guaranteed to work on other implementations (and in fact won't work in older Python/CPython versions). Using sorted lists is the way to go. See this StackOverflow question (and answers) for recipes on how to do that. Meet the requirements Your algorithm finds a route with any starting point, which fails to meet one of the requirements: The location id 1 must be the starting and the ending point Since the total route length doesn't depend on the starting point, you should add a final step rotating the locations to start at the correct point. Somethings along these lines would work: `[route[(i + location_1_index) % len(route)] for i in range(len(route))]`
{ "domain": "codereview.stackexchange", "id": 44676, "lm_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, genetic-algorithm, traveling-salesman", "url": null }
c++, performance, game, api, event-handling Title: Event manager for games written in C++17 Question: This is a single header event manager that I'm using in my game. Disclaimer I ripped everything from these lovely people: https://austinmorlan.com/posts/entity_component_system/ C++ Event System - Game Engine so give me little to no credit for the ideas used, but I did write every single line myself (using they're implementations as heavy motivation). Looking for if it's readable if there are any hidden bugs (I'm an amateur C++ hobbiest programmer, ~1 year, little experience with static and used it anyway) features I should add (does this cover everything I need to make a small scale game? I have little experience and don't know if I covered everything) just an overall review would be nice (: The goals of the event manager no base event class events are just POD structs as few virtual methods as possible no explicit registering of events fast contiguous execution of functions (I dont really mind if subscribing takes longer to achieve this) simple api (no std::bind, lambdas, etc...) single header Example usage: #include <iostream> #include "EventManager.h" // events struct LevelDown { int level; }; struct LevelUp { int level; }; // event handlers / listeners / subscribers void handleLevelUp(const LevelUp& event) { std::cout << "level: " << event.level << '\n'; } void handleLevelDown(const LevelDown& event) { std::cout << "downlevel: " << event.level << '\n'; } void levelDownConsiquence(const LevelDown& event) { std::cout << "downlevel consiquence: " << event.level << '\n'; } class DownLevelClass { public: explicit DownLevelClass(EventManager* em) { em->subscribe<LevelDown>(&DownLevelClass::method, this); } private: void method(const LevelDown& event) const { std::cout << "method down level: " << event.level << '\n'; } }; int main() { EventManager em; int level{ 0 };
{ "domain": "codereview.stackexchange", "id": 44677, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, game, api, event-handling", "url": null }
c++, performance, game, api, event-handling int main() { EventManager em; int level{ 0 }; // use handle to unsubscibe auto levelUpHandle = em.subscribe<LevelUp>(&handleLevelUp); // it is not neccissary to have it if you plan on never unsubscribing em.subscribe<LevelDown>(&handleLevelDown); em.subscribe<LevelDown>(&levelDownConsiquence); DownLevelClass DLC(&em); level--; em.publishBlocking<LevelDown>({ level }); level++; em.publishBus<LevelUp>({ level }); em.publishBlocking<LevelUp>({ level }); em.pollEvents(); em.unsubscribe<LevelUp>(levelUpHandle); } This should output: downlevel: -1 downlevel consiquence: -1 method down level: -1 level: 0 level: 0 Summary of the functionality provided you can subscribe with a POD struct type and a raw function pointer you can unsubscribe by passing in the handle returned by the subscribe and the event type you can publish blocking events with the event type and the same instance of that event type (has to be pod) you can publish to the bus (same rules as publishing a blocking event) you can poll bus events by calling poll events, this is blocking unsubscribing does exactly what it says, needs event type and handle from subscribe. Implementation (EventManager.h) #pragma once #include <vector> #include <functional> #include <memory> #include <unordered_map> #include <assert.h> class ICallbackContainer { public: virtual ~ICallbackContainer() = default; virtual void callSaved() const = 0; }; template<typename EventType> class CallbackContainer : public ICallbackContainer { public: using CallbackType = std::function<void(const EventType&)>; using SubscriberHandle = size_t; SubscriberHandle addCallback(CallbackType callback); void removeCallback(SubscriberHandle handle); void operator() (const EventType& event) const { for (auto& callback : m_Callbacks) { callback(event); } }
{ "domain": "codereview.stackexchange", "id": 44677, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, game, api, event-handling", "url": null }
c++, performance, game, api, event-handling void save(const EventType& event); void callSaved() const override; private: std::vector<CallbackType> m_Callbacks{}; std::vector<SubscriberHandle> m_FreeHandles{}; std::unordered_map<SubscriberHandle, size_t> m_HandleToIndex{}; std::unordered_map<size_t, SubscriberHandle> m_IndexToHandle{}; EventType m_SavedEvent{}; }; template<typename EventType> auto CallbackContainer<EventType>::addCallback(CallbackType callback) -> SubscriberHandle { SubscriberHandle handle; size_t newIndex = m_Callbacks.size(); if (m_FreeHandles.empty()) { handle = m_Callbacks.size(); } else { handle = m_FreeHandles.back(); m_FreeHandles.pop_back(); } m_HandleToIndex[handle] = newIndex; m_IndexToHandle[newIndex] = handle; if (newIndex >= m_Callbacks.size()) { m_Callbacks.resize(newIndex + 1); } m_Callbacks[newIndex] = callback; return handle; } template<typename EventType> void CallbackContainer<EventType>::removeCallback(SubscriberHandle handle) { assert(m_HandleToIndex.find(handle) != m_HandleToIndex.end()); size_t indexOfRemovedHandle = m_HandleToIndex[handle]; size_t indexOfLastElement = m_Callbacks.size() - 1; if (indexOfRemovedHandle != indexOfLastElement) { SubscriberHandle handleOfLastElement = m_IndexToHandle[indexOfLastElement]; m_HandleToIndex[handleOfLastElement] = indexOfRemovedHandle; m_IndexToHandle[indexOfRemovedHandle] = handleOfLastElement; m_Callbacks[indexOfRemovedHandle] = m_Callbacks[indexOfLastElement]; } else { m_Callbacks.pop_back(); } m_HandleToIndex.erase(handle); m_IndexToHandle.erase(indexOfLastElement); m_FreeHandles.emplace_back(handle); } template<typename EventType> void CallbackContainer<EventType>::save(const EventType& event) { m_SavedEvent = event; }
{ "domain": "codereview.stackexchange", "id": 44677, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, game, api, event-handling", "url": null }
c++, performance, game, api, event-handling template<typename EventType> void CallbackContainer<EventType>::callSaved() const { for (auto& callback : m_Callbacks) { callback(m_SavedEvent); } } class EventManager { public: template<typename EventType, typename Function> typename CallbackContainer<EventType>::SubscriberHandle subscribe(Function callback); template<typename EventType, typename Method, typename Instance> typename CallbackContainer<EventType>::SubscriberHandle subscribe(Method callback, Instance instance); template<typename EventType> void unsubscribe(typename CallbackContainer<EventType>::SubscriberHandle handle); template<typename EventType> void publishBlocking(const EventType& event) const; template<typename EventType> void publishBlocking(EventType&& event) const; template<typename EventType> void publishBus(const EventType& event); template<typename EventType> void publishBus(EventType&& event); void pollEvents(); private: template<typename EventType> static inline CallbackContainer<EventType> s_Callbacks; std::vector<const ICallbackContainer*> m_EventBus; }; template<typename EventType, typename Function> inline typename CallbackContainer<EventType>::SubscriberHandle EventManager::subscribe(Function callback) { return s_Callbacks<EventType>.addCallback(callback); } template<typename EventType, typename Method, typename Instance> typename CallbackContainer<EventType>::SubscriberHandle EventManager::subscribe(Method callback, Instance instance) { std::function<void(const EventType&)> function{ std::bind(callback, instance, std::placeholders::_1) }; return s_Callbacks<EventType>.addCallback(std::move(function)); } template<typename EventType> inline void EventManager::unsubscribe(typename CallbackContainer<EventType>::SubscriberHandle handle) { s_Callbacks<EventType>.removeCallback(handle); }
{ "domain": "codereview.stackexchange", "id": 44677, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, game, api, event-handling", "url": null }
c++, performance, game, api, event-handling template<typename EventType> inline void EventManager::publishBlocking(const EventType& event) const { s_Callbacks<EventType>(event); } template<typename EventType> inline void EventManager::publishBlocking(EventType&& event) const { s_Callbacks<EventType>(std::forward<EventType>(event)); } template<typename EventType> void EventManager::publishBus(const EventType& event) { s_Callbacks<EventType>.save(event); m_EventBus.emplace_back(&s_Callbacks<EventType>); } template<typename EventType> void EventManager::publishBus(EventType&& event) { s_Callbacks<EventType>.save(std::forward<EventType>(event)); m_EventBus.emplace_back(&s_Callbacks<EventType>); } inline void EventManager::pollEvents() { for (const auto& callback : m_EventBus) { callback->callSaved(); } m_EventBus.clear(); } Questions I'm worried the static s_Callbacks in the EventManager class is bad scaleability (in usage and with features) features I should add (in the context of OpenGL and windows.h gamedev) is there any way to get rid of the base CallbackContainer class? do I even need too? Answer: Answers to your questions if it's readable I think the code is quite readable. I would add documentation though using Doyxgen. if there are any hidden bugs (I'm an amateur C++ hobbiest programmer, ~1 year, little experience with static and used it anyway) If you call publishBus() twice with the same event type, then the old saved event is overwritten, but now callSaved() will be called twice on the new event. features I should add (does this cover everything I need to make a small scale game? I have little experience and don't know if I covered everything)
{ "domain": "codereview.stackexchange", "id": 44677, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, game, api, event-handling", "url": null }
c++, performance, game, api, event-handling This is impossible to answer in general. There are many games that don't need an event manager to begin with. And if you do need an event manager, maybe this one suffices, even though a different one might be better. If you are working on a game, you know best yourself whether this event manager is what you need. Even better than adding features would be to see which features you can remove. I'm worried the static s_Callbacks in the EventManager class is bad What would be bad about this? It looks fine to me. scaleability (in usage and with features) I don't see any scalability issues when it comes to performance or memory usage. I'm not sure what you mean with "with features", unless: features I should add (in the context of OpenGL and windows.h gamedev) You should not add features unless necessary. Your event manager has a simple job: handle events and forward them to subscribers. Instead of making it do more different things, focus on making sure it does those few things well. is there any way to get rid of the base CallbackContainer class? do I even need too? You don't need to, but it is possible. You might use std::variant and std::visit(), but then you need to know the full set of event types up front. You could also do some form of type erasure. For example, instead of m_EventBus storing pointers to ICallbackContainer, have it store std::function<void()>s: class EventManager { … std::vector<std::function<void()>> m_EventBus; }; template<typename EventType> void EventManager::publishBus(const EventType& event) { s_Callbacks<EventType>.save(event); m_EventBus.emplace_back([&]{ s_Callbacks<EventType>.callSaved(); }); } void EventManager::pollEvents() { for (auto& callback : m_EventBus) { callback(); } m_EventBus.clear(); }
{ "domain": "codereview.stackexchange", "id": 44677, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, game, api, event-handling", "url": null }
c++, performance, game, api, event-handling This has roughly the same overhead as your solution using inheritance. Why have both publishBlocking() and publishBus()? I don't see why you have both publishBlocking() and publishBus(). Why do you need to store an event and call the subscribers later? If you really need that, then why only have the ability to store one event? I would expect a queue then where you can publish many events, and have them all polled together later. If you do not really need both, then you should follow the YAGNI principle. Mapping indices to handles You have opted to store a dense vector of callbacks. This is great if you call the callbacks much more often than you modify the set of callbacks, which is a reasonable assumption. However, now you need to map indices to handles in order to support \$O(1)\$ insertion and removal of callbacks. Using std::unordered_map is one way of doing that, but it has some overhead. You might want to use std::vectors for m_HandleToIndex and m_IndexToHandle: std::vector<SubscriberHandle> m_IndexToHandle is trivial: its size is the same as m_Callbacks, and you just store the handle for a given index at that same index. std::vector<size_t> m_HandleToIndex is now a potentially sparse vector, indexed by SubscriberHandle. It might seem bigger than necessary, but it has much less overhead than std::unordered_map, so it will still use less memory unless it has become really sparse. Accessing those std::vectors will be faster than std::unordered_maps, even if both are \$O(1)\$.
{ "domain": "codereview.stackexchange", "id": 44677, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, game, api, event-handling", "url": null }
c, binary-tree Title: A toy implementation of binary tree Question: I'm playing around with a toy implementation of binary trees in C. I have a typedef'd struct BTree like so — typedef struct BTree { struct BTree* left; void* value; struct BTree* right; } BTree; I have three functions implemented so far — BTree* genRandomTree(int depth) — Creates a balanced binary tree of depth height and fills it with random integers int height(BTree* tree) - Calculates the height of the binary tree bool isAVLBalanced(BTree* tree) - Checks if a given tree is AVL balanced I have run some basic test cases and everything seems to be in working order. I am specifically looking for advice about performance and correctness regarding any edge-cases I've failed to take into consideration. I am especially interested in any method of converting the three functions into tail-recursive form. I am specifically not looking for advice telling me not to use gcc's nested function extension (exploring this extension was part of my motivation for writing this program in the first place) or advice about not-having free'd memory. I am also aware that the recursion-heavy style I have written this in is very unidiomatic and recommended against, however, having fun with recursion was also one of my motivations for writing this program, so ¯\_(ツ)_/¯. Compiling with gcc -Wall -Wextra -Werror -Wc++-compat gives no errors or warnings. Adding -Wpedantic to the compiler options produces errors about nested functions not being ISO C compliant but nothing else. Here is the full code — #include <stdio.h> #include <stdlib.h> #include <stdbool.h> typedef struct BTree { struct BTree* left; void* value; struct BTree* right; }BTree; // generates balanced binary tree of maxDepth depth and fills it with integers BTree* genRandomTree(int depth) { BTree* _genRandomTree(int curDepth, int maxDepth) { if (curDepth == maxDepth) {return NULL;} BTree* node = (BTree*)malloc(sizeof(BTree));
{ "domain": "codereview.stackexchange", "id": 44678, "lm_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, binary-tree", "url": null }
c, binary-tree BTree* node = (BTree*)malloc(sizeof(BTree)); node->left = _genRandomTree(curDepth+1, maxDepth); node->right = _genRandomTree(curDepth+1, maxDepth); node->value = malloc(sizeof(int)); *((int *) node->value) = rand()%100; return node; } return _genRandomTree(0, depth); } // Calculates height of tree int height(BTree* tree) { int _height(BTree* tree, int curHeight) { if (!tree) { return curHeight; } int leftHeight = _height(tree->left, curHeight+1); int rightHeight = _height(tree->right, curHeight+1); return leftHeight > rightHeight ? leftHeight : rightHeight; } return _height(tree, 0); } // Checks if tree is AVL balanced bool isAVLBalanced(BTree* tree) { if (!tree) { return true; } // Null tree is trivially balanced int heightDiff = height(tree->left) - height(tree->right); int heightDiffAbs = heightDiff < 0 ? heightDiff * -1 : heightDiff; return heightDiffAbs <= 1 && isAVLBalanced(tree->left) && isAVLBalanced(tree->right); } int main() { srand(6); BTree* root = genRandomTree(3); if (isAVLBalanced(root)) { printf("Balanced\n"); } else { printf("Unbalanced\n"); } return 0; } /* Tree created by genRandomTree() after srand(6) 86 / \ / \ 12 85 /\ /\ / \ / \ 41 85 65 8 */ Answer: Nested functions are not in the C standard. It is a GCC extension, of a dubious value. Don't do it. Casting malloc is a bad practice. First, it is not necessary, and second, it may lead to a hard-to-find bugs. Along the same line, prefer sizeof value rather than sizeof (type), e.g. BTree* node = malloc(sizeof *node); Among other benefits, this avoids double maintenance. isAVLBalanced seems buggy. It only tests the heights of immediate subtrees of the root. You also need the subtrees themselves to be AVL balanced - i.e. it also needs to be recursive.
{ "domain": "codereview.stackexchange", "id": 44678, "lm_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, binary-tree", "url": null }
c, binary-tree Stylistically, * shall gravitate to a variable, not to the type. Prefer struct BTree *left; Disclaimer: this is a matter of an (heretical) opinion. You don't want to say that left is a pointer to BTree. You want to say that *left in an expression yields a BTree object.
{ "domain": "codereview.stackexchange", "id": 44678, "lm_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, binary-tree", "url": null }
javascript, performance, algorithm Title: Count matching pairs (modular equality) Question: Problem Given an array of natural numbers a. Find the number of such pairs of elements (a_i, a_j), where abs(a_i − a_j) mod 200 == 0 and i < j Solution I came up with this solution: // n - the length of numbers array // numbers - the array of natural numbers function getNumberOfGoodPairs(n, numbers) { let count = 0; const remainders = new Map(); for (const num of numbers) { const remainder = num % 100; const modifiedNum = (num - remainder) / 100; if (remainders.has(remainder)) { const nums = remainders.get(remainder); for (const num of nums) { if (Math.abs(num - modifiedNum) % 2 === 0) ++count; } nums.push(modifiedNum); } else { remainders.set(remainder, [modifiedNum]); } } return count; } Notations for (const arrayElement of array) - get elements from the array one by one and put this element into arrayElement. It is same as: for (let i = 0; i < array.length; ++i) { const arrayElement = array[i]; } new Map() - is dictionary % - is mod array.push(el) - add el to the end of array remainders.get(remainder) - returns the array of numbers which remainder is equal to remainder when dividing by 100 remainders.set(remainder, [modifiedNum]) - add to dictionary new key remainder and value [modifiedNum]. [modifiedNum] - a dynamic array with one element modifiedNum If I'm right the time complexity in worst case is O(n²). Please help me to optimize this algorithm. Answer: With a bit of algebra you can show that (1) abs(a_i − a_j) mod m == 0, m > 1 can be written as (2) (a_i − a_j) mod m == 0 if a_i >= a_j (3) (a_j − a_i) mod m == 0 if a_i <= a_j on both cases it is the same as saying (4) (b − a) mod m == 0 if b >= a
{ "domain": "codereview.stackexchange", "id": 44679, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, performance, algorithm", "url": null }