text
stringlengths
1
2.12k
source
dict
javascript, authentication, jwt const isLoggedIn = () => !(window.localStorage.getItem("jwtToken") === null); const userSerivce = { login, logout, register, isLoggedIn } export default userSerivce; ``` Answer: Nice work, the code looks good! Couple of comments- With ES6 syntax, if you're returning an object with a property that is coming from a variable of the same name: const registrationData = { "firstName":firstName, "lastName":lastName, "email": email, "password":password }; You can completely omit the property name, and shorten the syntax like so: const registrationData = { firstName, lastName, email, password }; If you're repeating the same block of code, it makes sense to extrapolate that into a function. For example, your fetch functions are more or less identical, aside from a few parameters.. const registerResponse = await fetch(config.host + config.usersUrl, { body: JSON.stringify(registrationData), method: "POST", headers: { 'Content-Type': 'application/json' } }) could be turned into: const sendPost = async(url, body) => { const res = await fetch(url, { body, method: "POST", headers: { "Content-Type": "application/json" } }) return res } And then you can call it whenever you want to send a post... reducing repetition and leaving less room for human error. In response to your questions: There is a more secure alternative to local storage, which involves using HTTPOnly cookies. HTTPOnly cookies aren't stored in the user's browser, and exist only on the HTTPS connection itself. It is more involved than using local storage, but it's much more secure then storing session secrets in the user's browser. You can also set this cookie to only be used on a secure connection.
{ "domain": "codereview.stackexchange", "id": 43245, "lm_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, authentication, jwt", "url": null }
javascript, authentication, jwt If everything is sent over HTTPS, you won't need to hash the password clientside, as the TLS encryption mangles the passwords in transit.
{ "domain": "codereview.stackexchange", "id": 43245, "lm_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, authentication, jwt", "url": null }
c, cgi Title: C lang CGI form/string handle Question: Started playing with C and CGI forms. Is this code ok? Can it be improved/optimized? If I fill user with "user" and password with "pass" input in takelogin is user=user&password=pass In the end I want to have user = 'user' and pass = 'pass' This is the form #include <stdio.h> int main(void) { printf("%s%c%c\n", "Content-Type:text/html;charset=iso-8859-1",13,10); printf("<title>Takelogin</title>\n"); printf("<h3>Multiplication results</h3>\n"); printf("%s\n", "<form action='/takelogin.cgi' method='post'>"); printf("%s\n", "<div>Your input (80 chars max.):<BR>"); printf("%s\n", "<input type='text' name='user' size='60' maxlength='80'><br>"); printf("%s\n", "<input type='password' name='password' size='60' maxlength='80'><br>"); printf("%s\n", "<input type='submit' value='Send'></div>"); printf("%s\n", "</form>"); return 0; } And this is takelogin #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXINPUT 80 int main(void) { char *lenstr; char *user; char *pass; char input[MAXINPUT]; long len; char delim[2][2] = {"&", '='}; printf("%s%c%c\n", "Content-Type:text/html;charset=iso-8859-1",13,10); printf("<TITLE>Response</TITLE>\n"); lenstr = getenv("CONTENT_LENGTH"); if(lenstr == NULL) printf("<P>Error in invocation - wrong FORM probably."); else { fgets (input , sizeof(input) , stdin); char *loginS = malloc(sizeof(input)); strcpy(loginS, input); user = strtok(loginS, delim[0]); user = strtok(user, delim[1]); user = strtok(NULL, delim[1]); pass = strtok(input, delim[0]); pass = strtok(NULL, delim[0]); pass = strtok(pass, delim[1]); pass = strtok(NULL, delim[1]); printf("%s@%s", user, pass); free(loginS); return 0; } return 0; } Answer: Some bugs:
{ "domain": "codereview.stackexchange", "id": 43246, "lm_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, cgi", "url": null }
c, cgi Answer: Some bugs: malloc() can fail. When it does, it returns a null pointer, which we must not use as destination for strcpy(). The fixed-length input array can be overrun by the remote user. That's a pattern that causes security problems in server code (which this is, via CGI). Our strategy to avoid that (by reading only sizeof input - 1 chars) means that we silently change the user's input. Other issues: Instead of reading into input and then copying into loginS, we should allocate memory, then (if successful) call fgets(loginS, size, stdin). We should be testing for valid input before we output any headers, as we should be returning a HTTP error code (probably 400 Bad Request) rather than success (200). We could parse lenstr, and if successful, use that value to allocate a suitable size buffer instead of sizeof input chars (which will always be MAXINPUT). Don't forget + 1 for a terminating null char! I don't think the delim array is helpful - it would be clearer to put the literal strings in the code there. I know that breaks the rule of "no magic values", but I think that here the rule just obfuscates rather than clarifies the code. If the printf() fails, it might be a good idea to return EXIT_FAILURE, so the CGI engine knows that something has gone wrong (the user hasn't got their result). Instead of if/else, I prefer an early-return pattern: if (error_condition) { report_error(); cleanup_resources(); return EXIT_FAILURE; } That means less context to hold in mind whilst reading.
{ "domain": "codereview.stackexchange", "id": 43246, "lm_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, cgi", "url": null }
c++, console, image, ascii-art Title: c++ CLI Ascii image renderer Question: I am wondering if this is written well or not, I am just a beginner and would like some feedback what should I improve on. Thanks. #define STB_IMAGE_IMPLEMENTATION #include<iostream> #include "stb_image.h" #include "vector" #define LOG(x) std::cout << x << std::endl const char* density = "#$lho,. "; struct Vec3{ float x, y, z; float Average(){ return (x+y+z)/3.0f; } Vec3& operator/(float other){ x /= other; y /= other; z /= other; return *this; } }; std::ostream& operator<<(std::ostream& stream, const Vec3& other){ stream << other.x << ", " << other.y << ", " << other.z; return stream; } int main(){ std::ios_base::sync_with_stdio(false); int w, h, c; unsigned char *data = stbi_load("image.jfif", &w, &h, &c, STBI_rgb); std::vector<Vec3> vec; for (int i = 0; i < w*h*c; i+=3) vec.push_back(Vec3{ float(data[i]), float(data[i+1]), float(data[i+2]) }); int counter = 0; for (Vec3 v : vec){ if (counter%w == 0) { std::cout << "\n"; } std::cout << density[ int((v/255).Average()*(strlen(density)-1)) ] << " "; counter++; } LOG(counter); stbi_image_free(data); return 0; } Answer: Overview. This is probably not your fault but the stbi interface is badly designed C++. This is more like a C interface. The problem here are: The "Resource Allocation"/ "Resource Release" done manually There is no excapsulation of the data. The resource alocation is the big thing to me (you need to use RAII). As a consequence, the code is not exception safe, and you are going to leak the resource in any non-trivial application. Additionally, the data is actually 4 items. int w, h, c; unsigned char *data; But they are not protected from misuse and thus likely to be messed up.
{ "domain": "codereview.stackexchange", "id": 43247, "lm_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++, console, image, ascii-art", "url": null }
c++, console, image, ascii-art But they are not protected from misuse and thus likely to be messed up. Not sure running across the data converting char to float then running across the data again is it worth it. Simple run across the data and print it computing an average as you go. Code Review What does this do. #define STB_IMAGE_IMPLEMENTATION It should be made clear why you are doing this. Please be neat in your code. #include<iostream> Add an extra space after the include. Vector is standard library. It is probably not something you want to define yourself (as implied by the quotes). Or this should use <> around vector to show this is a standard library. #include "vector" Don't use macros for this: #define LOG(x) std::cout << x << std::endl Macros should normally be reserved for designed machine/architecture differences. Not writing pseudo functions. template<typename T> inline void log(T const& value) {std::cout << value << std::endl;} Don't use std::endl. std::cout << value << std::endl; This outputs a new line then flushes the buffer. This will make using the streams very inefficient (and if used a lot will significantly deteriorate the performance of an application). I would say that if you want to flush the buffer you should explicitly do it. If you want your logging to force a flush fine then keep it. But normally you sould simply output a new line. std::cout << value << "\n"; Then if you actually need to flush then ask the engineer to explicitly flush it at important points (but usually the system does it at the correct times). If this is for debugging use std::cerr this will auto flush (as it has no buffer to flush). That's a short density string. const char* density = "#$lho,. "; Sure. But is "Average" the best function for this? float Average(){ return (x+y+z)/3.0f; } See this video where he discusses some alternatives: Yes. std::ios_base::sync_with_stdio(false);
{ "domain": "codereview.stackexchange", "id": 43247, "lm_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++, console, image, ascii-art", "url": null }
c++, console, image, ascii-art Yes. std::ios_base::sync_with_stdio(false); How I would do it // I am going to use the same type of class for a point // You did but I am going to make the data points // the same as the data you get from the stbi library // so there is no need to do any conversion. struct Vec3 { unsigned char x, y, z; float Average() const { return (x+y+z)/3.0f; } }; // You are effectively manipulating an image. // So lets encapsulate that data in its own class. class Image { int w; int h; int c; unsigned char *data; public: // We know that we are doing resource management // So we need a constructor and destructor to // correctly handle the resource. // // Note we could do something fancy with a smart // pointer. But I think that is overkill for now. // But may be worth thinking about down the road. Image(std::string const& fileName) { data = stbi_load(fileName.c_str(), &w, &h, &c, STBI_rgb); } ~Image() { stbi_image_free(data); } // Need to think about the rule of 3/5 // So I am going to delete the copy operations. // You may do something more sophisticated in the // long run. Image(Image const&) = delete; Image& operator=(Image const&) = delete; // The only other operation you do is scan over the // data for the image. This is usually done via iterators // in C++. I am going to do the simplist iterator I can // probably not super exactly compliant but it will work // for this situation. You should fix up to be better. struct Iterator { // Really the iterator is simply a pointer to // a location in the raw data of them image. // So that is all we need to store. unsigned char* data;
{ "domain": "codereview.stackexchange", "id": 43247, "lm_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++, console, image, ascii-art", "url": null }
c++, console, image, ascii-art // Moving the iterator you want to move by // three data points (as the three points represent // one pixel (I believe)). Iterator& operator++() { data+=3; return *this; } // You can add post increment and or the decrement // operators. // This is the operator that gives you back a reference // to one point in the data. // We simply convert it to be a pointer of the correct // type and then convert it to a reference before // returning. Vec3& operator*() { return *reinterpret_cast<Vec3*>(data); } // The main comparison for iterators. Is checking // if they are not equal. You should probably also // test for equivelance. bool operator!=(Iterator const& rhs) const { return data != rhs.data; } }; // In C++ ranges are defined by the beginning // and one past the end. So we create iterators // at these points. Iterator begin() {return Iterator{data};} Iterator end() {return Iterator{data + w*h*c};} }; int main() { Image image("image.jfif"); for (auto const& point: image) { std::cout << point.Average() << "\n"; } } Side nots: The range based for() uses the begin() and end() methods on an object to iterat across the range. So the above for loop is actually equivelent to: { auto begin = std::begin(image); // this by default calls image.begin(). auto end = std::end(image); // this by default calls image.end(). for (auto loop = begin; loop != end; ++loop) { auto const& point = *loop; std::cout << point.Average() << "\n"; } }
{ "domain": "codereview.stackexchange", "id": 43247, "lm_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++, console, image, ascii-art", "url": null }
c++, console, image, ascii-art This shows that we are using all the methods I define above. begin() and end() to get the range. operator++() to increment the iterator and operator!=() to check we are not at the end and finally operator*() to get a reference to a point.
{ "domain": "codereview.stackexchange", "id": 43247, "lm_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++, console, image, ascii-art", "url": null }
strings, mysql, stored-procedure Title: MySQL procedure to extract a letter from a phrase Question: Create a function called GETLYRICS, which will receive as parameters a word of at most 15 letters and a number. It must return the letter of the position indicated in the number. My exercise is fine but is there any other way to do it? Here is a link to how the program works : https://www.db-fiddle.com/f/3PnzHErrf2fZFGZY67K12X/47 USE PRUEBA; DELIMITER $$ DROP FUNCTION IF EXISTS GETLYRICS$$ CREATE FUNCTION GETLYRICS(letter VARCHAR(15), number INT) RETURNS VARCHAR(1) BEGIN RETURN SUBSTR(letter,number,1); END $$ DELIMITER ; Answer: There's another interesting way of doing it with RIGHT and LEFT operators: RIGHT(LEFT(letter,number),1) It first strips the rightmost characters from the letters, then takes the first character from right. The difference with using SUBSTRING or MID is that it gets robust to wrong inputs like -1 (smaller than 0) or 18 (bigger than 15). In the former case it will output NULL, in the latter case it will get the "last" character. I've used this fiddle to play a bit: https://www.db-fiddle.com/f/3PnzHErrf2fZFGZY67K12X/228.
{ "domain": "codereview.stackexchange", "id": 43248, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, mysql, stored-procedure", "url": null }
javascript Title: Javascript grabbing sum Question: I'm wondering how the following looks for a javascript Array-sum function: function sum(...rest) { let n = 0; for (let elem of rest) { n += elem; } return n; } console.log(sum(1,2,3)); console.log(sum(2)); Is this considered overly verbose code? For example, of these examples are much more 'interesting' and generally speaking, shorter: https://stackoverflow.com/a/43363105/651174. In the above, what could be improved? Answer: Reduce You could have used Array.reduce function sum(...rest) { return rest.reduce((n, val) => n + val, 0); } Or as const sum = (...rest) => rest.reduce((n, val) => n + val, 0); Your code But there are many ways to do the same thing and there is no best way to do it. There is nothing wrong with your code and looking at your code I would do things slightly differently but mostly these are subjective style considerations to fit a larger body of work. Change the naming The Function name sum gives no clue to what it does, changing to sumArray or sumValues will be much more readable if found on its own. rest to values or numbers n to sum elem to val or item eg function sum(...values) { let sum = 0; for (let val of values) { sum += val; } return sum; } Layout and declarations I would make sum a var (more fitting of its use), val a const, and put the addition on the same line as the loop. eg function sumValues(...values) { var sum = 0; for (const val of values) { sum += val } return sum; } Personalty the arrow function would be my preferred solution incorporating the name changes to give a simple one liner. const sumValues = (...values) => values.reduce((sum, val) => sum + val, 0);
{ "domain": "codereview.stackexchange", "id": 43249, "lm_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 }
python, validation, csv Title: CSV file parser with some checks for header fields and duplicate rows Question: I have built a sample Parser class on top of the csv module for basic checks that we normally need as the first step of pre-processing. I would love a bit of feedback on the code and any areas that I can improve upon in the code to make it more efficient. import csv from exceptions import CompulsoryHeaderCheckFailed class CsvParser: def __init__(self, file: str, compulsory_headers: list): self.file = file self.compulsory_headers = compulsory_headers self.duplicate_rows = [] self.good_rows = [] self.bad_rows = [] self.log = [] def diff_headers(self): reader = csv.reader(open(self.file)) header = next(reader) return set(self.compulsory_headers) - set(header) def passes_compulsory_header_check(self): return True if not self.diff_headers() else False def is_bad_row(self, line_num: int, curr_row: tuple): if not all(curr_row): self.bad_rows.append(({"line_num": line_num, "row": list(curr_row)})) return True return False def _append_log(self, line_num: int): self.log.append({"total_num_of_rows_processed": line_num, "good_rows": self.good_rows, "bad_rows": self.bad_rows, "duplicate_rows": self.duplicate_rows, }) @property def row(self): rows = csv.reader(open(self.file)) next(rows) for _row in rows: yield _row @property def col(self): rows = csv.reader(open(self.file)) for row in rows: return row
{ "domain": "codereview.stackexchange", "id": 43250, "lm_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, validation, csv", "url": null }
python, validation, csv def _parse_rows(self): _rows = set() rows = csv.reader(open(self.file)) next(rows) line_num = 1 _rows = set() for row in rows: line_num += 1 row = tuple(row) if not (self.is_bad_row(line_num, row)): if row not in _rows: _rows.add(row) self.good_rows.append({"line_num": line_num, "row": list(row)}) else: self.duplicate_rows.append({"line_num": line_num, "row": list(row) }) self._append_log(line_num) def process_csv(self, skip_header_check=False): if skip_header_check: self._parse_rows() else: if self.passes_compulsory_header_check(): self._parse_rows() else: raise CompulsoryHeaderCheckFailed("compulsory headers missing from csv") csv_parser = CsvParser("hello.csv", compulsory_headers=["id", "student", "marks", ]) print(csv_parser.process_csv()) print(csv_parser.good_rows) print(csv_parser.bad_rows) print(csv_parser.duplicate_rows) print(csv_parser.log) Answer: Interface The interface for this class is awkward, and it's not clear how it's meant to be used.
{ "domain": "codereview.stackexchange", "id": 43250, "lm_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, validation, csv", "url": null }
python, validation, csv Is diff_headers() supposed to be part of the interface? How about passes_compulsory_header_check()? Maybe they should be considered private, to be used internally by process_csv()? The is_bad_row(line_num, curr_row) method definitely seems like it's supposed to be a private method for internal use: how else would a caller come up with a line number and a tuple of data to pass to it? The worst aspect of this method is that even though its name suggests that it just performs a test, it actually has a side-effect of maybe appending something to self.bad_rows. The _append_log() method appends to self.log, but considering that the "log" should contain a single item that is a summary of the outcome of parsing the entire file, why is self.log a list at all? For that matter, why should there be a "log" at all? As your sample usage shows, you can get that information from csv_parser.good_rows, csv_parser.bad_rows, etc. — all that's missing is the line count, and you could modify the class so that the line count could be queried likewise. It's highly unorthodox that row() is a property that is also a generator — especially since the name of the method is singular rather than plural. I don't know what the col() method is for, but it looks entirely wrong, and you never call it. The process_csv() method looks somewhat reasonable. But why is there a skip_header_check option? Couldn't the caller also effectively skip the header check by specifying no compulsory headers? It seems simpler and more Pythonic to offer just one way to accomplish a particular goal.
{ "domain": "codereview.stackexchange", "id": 43250, "lm_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, validation, csv", "url": null }
python, validation, csv Design suggestion If I had to write this class, I'd design it so that it works pretty much as a drop-in replacement for the csv.DictReader class, such that iterating over the reader streams the "good" rows, but keeps track of the bad and duplicate rows that it encounters. Implementation In several places, you write reader = csv.reader(open(self.file)), often followed by next(rows) to skip the header row. It would be better to design the class so that it opens the file just once, and makes one linear pass through its contents. Also, a csv.DictReader would be a better way to handle the header row. What exactly constitutes a "bad" row? A row that has an empty field? Your criterion is all(curr_row), but you should be aware that if the row has fewer fields than expected, that will be considered acceptable. In _parse_rows(), you initialized _rows = set() twice. To write a for loop that maintains a count while iterating, the Python idiom is to use enumerate().
{ "domain": "codereview.stackexchange", "id": 43250, "lm_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, validation, csv", "url": null }
python Title: Find max value that is multiple of 3 in an array Question: Recently, I got a code test from NAB. Please take a look at this one and give me your idea. Find the max value of an array of N integers. E.g. [ 1, -6, 2, 0, 1011, -355] Require: the max value is a multiple of 3 and the code focuses on the correctness, not performance. def solution(A): try: if not isinstance(A, list): raise TypeError max_value = max([x for x in A if x % 3 ==0]) return max_value except Exception as e: print(f"{A} is not a list") print(e) So does my code fulfill the requirements or Did I miss any edge case? P/s: They announced that was fail and only got 22/100 pts. Answer: Functions like this should not print. They should return an answer as data or, if that is impossible, either raise an exception or return None. The function should not be restricted to lists. It can easily handle any iterable. But under most circumstances, I would not bother enforcing a type check like this, because it tends to spawn additional annoying questions: if the iterable is type checked, must we also enforce that its values are numeric (or more precisely, that the values are comparable and support the % operator)? Ultimately, users of a function must understand its purpose. Docstrings and other forms of communication are often more helpful than hyper-diligent checking. The built-in max function already has a way to deal with empty sequences. Namely, the default argument. def solution(xs): return max((x for x in xs if x % 3 == 0), default = None)
{ "domain": "codereview.stackexchange", "id": 43251, "lm_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", "url": null }
c#, programming-challenge Title: LeetCode: C# fibonacci number iterative solution Question: https://leetcode.com/problems/fibonacci-number/ The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1. Given n, calculate F(n). Example 1: Input: n = 2 Output: 1 Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. Example 2: Input: n = 3 Output: 2 Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. Example 3: Input: n = 4 Output: 3 Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. Constraints: 0 <= n <= 30 here is my solution is there a way to reduce memory foot print? public class Solution { public int Fib(int n) { if (n == 0) { return 0; } if (n == 1) { return 1; } int a = 0; int b = 1; int c = 0; for(int i = 2; i <= n; i++) / { c = a+b; a = b; b = c; } return c; } } Answer: Yes you can save some memory by getting rid of i in for loop and working with input n. Although it's not good practice to change input parameters. int a = 1; int b = 1; int c = 1; for(; n > 2; n--) { c += a; a = b; b = c; } I got insteresting results by using .NET 6 and BenchmarkDotNet (I'm not benchmarking/memory expert so take it with a pinch of salt) - for Fib(30): Method Mean Error StdDev Gen 0 Allocated Optimized 14.79 ns 0.319 ns 0.283 ns - - Original 25.29 ns 0.544 ns 0.994 ns 0.0153 24 B
{ "domain": "codereview.stackexchange", "id": 43252, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, programming-challenge", "url": null }
javascript, algorithm, palindrome Title: Is my approach for Palindrome right or is there a better way to do it? Question: The code below is for checking whether the input string is palindrome or not const { argv } = require("process"); (()=>{ var palindrom01 = palindrom01; palindrom01(); function palindrom01(){ let inputNum = argv[2]; let totalLength = inputNum.length; let half_length = parseInt(totalLength/2); let flag = true; for(let i = 0, j = (totalLength - 1); i < half_length; i++){ if(inputNum.charAt(i) !== inputNum.charAt(j)){ flag = false; break; } j--; } console.log(`input ${inputNum} is Palinform => ${flag}`); } })(); This is the output of the code D:\> node .\palindrom.js 12321 input 12321 is Palinform => true D:\> node .\palindrom.js 123321 input 123321 is Palinform => true D:\> node .\palindrom.js 12345 input 12345 is Palinform => false D:\> Is Panlindrome properly implemented? if yes, is there a way better way to do it ? Answer: From a short review; palindrom01 does too much it finds the input it determines whether the input is a palindrome it prints to the console These could be 3 different functions var palindrom01 = palindrom01; -> I guess you are trying to hoist the function to the top or something. However, you can remove this complete palindrom01 is not a great function name, I would go for isPalindrome(s) which returns a boolean Most people consider the best approach a split to an array of characters, reverse, concatenate and compare to the original again In general I like self-executing functions, but it seems, in this case, it is overkill This is my counter-example, function getInput(){ return Input.value; } function isPalindrome(s){ return s === s.split('').reverse().join(''); } function showIsPalindrome(s){ console.log( `${s} is${isPalindrome(s)?'':' not'} a palindrome` ); }
{ "domain": "codereview.stackexchange", "id": 43253, "lm_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, algorithm, palindrome", "url": null }
javascript, algorithm, palindrome function showIsPalindrome(s){ console.log( `${s} is${isPalindrome(s)?'':' not'} a palindrome` ); } function controller(event){ const enterKey = 13; if(event.keyCode === enterKey){ showIsPalindrome(getInput()); } } Input.addEventListener('keypress', controller); <input id='Input'></input>
{ "domain": "codereview.stackexchange", "id": 43253, "lm_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, algorithm, palindrome", "url": null }
c++ Title: C++ shared_ptr mechanism Question: I'm so unsure that I am deallocating memory right. I am probably unable to figure out is shared_ptr destroyed or not, it seems to be impossible according to if checks, so maybe I need some try catch. I would like to listen ideas and ways of improving this code. Thanks. However, I'm so unsure that it prints that vector is empty, it might be destroyed though. Maybe there's something better solution according to C++23. #include <iostream> #include <memory> #include <vector> void fillvec(std::vector<int> &vec) { if (!vec.empty()) { unsigned index = 0; for (auto &item: vec) { std::cout << "Enter [" << ++index << "] vector's element : " << std::endl; std::cin >> item; } } else std::cout << "Impossible to fill vector." << std::endl; } void printvec(const std::vector<int> &vec) { if (!vec.empty()) { for (const auto &item : vec) { std::cout << item << "\t"; } std::cout << std::endl; } else std::cout << "Impossible to print empty vector!" << std::endl; } void clearvec(std::vector<int> &vec) { if (!vec.empty()) { vec.clear(); std::cout << "Vector has been cleared!" << std::endl; } else std::cout << "Vector is already empty!" << std::endl; }
{ "domain": "codereview.stackexchange", "id": 43254, "lm_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++", "url": null }
c++ void inputsize(int &size) { while (size > 10 || size < 1) { std::cout << "Enter vector's size : " << std::endl; std::cin >> size; if (size > 10 || size < 1) std::cout << "Enter vector's size from 1 to 10." << std::endl; } } void destroysp(std::shared_ptr<std::vector<int>> &vec) { vec.~shared_ptr(); std::cout << "Shared pointer to vector has been destroyed." << std::endl; } int main() { int n = 0; inputsize(n); std::shared_ptr<std::vector<int>> vec = std::make_shared<std::vector<int>>(n); fillvec(*vec); printvec(*vec); destroysp(vec); clearvec(*vec); printvec(*vec); } ``` Answer: Your code should work as expected. I don't see any big issues with memory management. It is not very normal to manual call the destructor: vec.~shared_ptr(); This is an exceedingly advanced thing to do and the situations where you would do it are very limited (and I would not expect anybody to do that). Remove this line. The vector will be destoryed by the shared_ptr destructor. The shared_ptr destructor will be called when execution finishes the main() function (because vec is an automatic variable in the scope of the function main). You could replace it with vec.reset(); // this will destory the container pointer. // but also sets the pointer to nullptr. // as a result you can not use `*vec` after a call to // destroysp() BUT it looks like you are learning C++ from a Java book. I know that in Java you need to create all objects with new but in C++ you can just declare local variable, they are created locally in the local scope and are automatically destroyed when they go out of scope. Hence: The thing I would change is: std::shared_ptr<std::vector<int>> vec = std::make_shared<std::vector<int>>(n); Into: std::vector<int> vec(n); Then in the rest of main you remove the * from infornt of vec.
{ "domain": "codereview.stackexchange", "id": 43254, "lm_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++", "url": null }
python, image Title: Function to resize an image whilst maintaining aspect ratio Question: I have the following function: def get_resize_dimensions(new_width: int, new_height: int, width: int, height: int) -> tuple[int, int]: """Return the new width and height of an image, resized to the new width and height but maintaining the aspect ratio. It will shorten along the edge that leaves the other edge less than or equal to the desired height. This means that we can keep the aspect ratio and pad a shorter edge with white space if needed.""" h_gt = new_height < height w_gt = new_width < width h_lt = new_height > height w_lt = new_width > width if (h_lt and w_lt) or (h_gt and w_gt): # (new_height, new_width < desired) or (new_height, new_width > desired) if new_width / width > new_height / height: return int(new_height / height * width), new_height return new_width, int(new_width / width * height) elif h_lt and w_gt: # new_height < desired, new_width > desired return int(new_height / height * width), new_height elif h_gt and w_lt: # new_height > desired, new_width < desired return new_width, int(new_height / height * height) elif new_height == height and new_width == width: # new_height, new_width = desired return new_width, new_height else: # height == width _min = min(new_width, new_height) # choose the smaller of the two return _min, _min It is described how it works in the code. It will take in an image of dimension \$(x,y)\$ and the user wants the image to be dimension \$(u,v)\$. The function will calculate \$(u*,v*)\$ such that one of these cases is true: \$u* = u, v* \leq v\$ \$u* \leq u, v* = v\$
{ "domain": "codereview.stackexchange", "id": 43255, "lm_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, image", "url": null }
python, image \$u* = u, v* \leq v\$ \$u* \leq u, v* = v\$ The key thing to note here is neither of \$u*\$ or \$v*\$ should be greater than \$u\$\ or \$v\$, respectively, and at least one of \$u*\$ equals \$u\$, or \$v*\$ equals \$v\$. This will then allow the user to pad whitespace along the shorter edge to make the image of size \$(u,v)\$. However, I feel that the code looks messy, is hard to follow and probably not a very effective or efficient way of doing it. I haven't really tested it yet so I am not 100% certain it is correct, although I am 99% sure. Is there any known algorithms to sort this or a better way I could do this? Note: There are no bounds on the input image dimensions, it could literally be anything. Edit: Some test cases: I am not 100% sure if my function works for all of these, but these are the expected outputs. I think this covers every case. Input | Output ----------------------------------- (1500,1000,900,1400) |(643,1000) (1500,1000,1000,900) |(1111,1000) (1500,1000,1600,1100)|(1455,1000) (1500,1000,1900,1100)|(1500,868) (1500,1000,1400,1100)|(1273,1000) (1500,1000,1600,900) |(1500,844) (1500,1000,1500,1000)|(1500,1000) (1500,1000,1200,1200)|(1000,1000) Answer: Focussing on the code as you've written it, there are a few things that alarmed me at a first pass.
{ "domain": "codereview.stackexchange", "id": 43255, "lm_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, image", "url": null }
python, image Separately checking A>B and B>A tends to be a bit of a red flag because of the risk that the equality case gets dropped. It can be needed, but I'd always try to partition into just two cases if possible. As you note, that's quite a lot of if statements, and quite a lot of conditions on each one. If the complexity can be reduced that's good. If not, I'd look for ways to at restructure the conditions so that they follow a more consistent pattern. This is disputable, but I'd probably go so far as to add some duplicate code to make it more readable, at least as a precursor to perhaps simplifying it down. I don't want to nitpick naming too much, but I'd favour similar levels of verbosity for similar parameters. I find new_width and width just a little bit jarring. If the latter were original_width for example, it would be smoother. Normally I'd complain about h_gt but in this structure it works OK. int will always round down. That may be what you want, but you may want to consider expressly rounding to the nearest integer instead. That is most likely to be relevant when the target aspect ratio actually matches the input aspect ratio, but floating point errors mess things up for you. Meanwhile a couple of points that I very much do like: I appreciate the use of type annotations. The docstring is clear in describing what it does and why. In terms of simplifying things, as already mentioned by ShapeOfMatter, most of the cases can be reduced to a single check. Personally I find it more intuitive to compare aspect ratios rather than lengths, using something of the shape: if new_width / new_height > width / height: # The target aspect ratio is wider than the original return round(new_height * width / height), new_height else: # The target aspect ratio is the same as or taller than the original return new_width, round(new_width * height / width)
{ "domain": "codereview.stackexchange", "id": 43255, "lm_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, image", "url": null }
python, tkinter Title: tkinter user interface skeleton for airport analysis application Question: I'm trying to make the following code meaningful as much as possible, using inheritance. The purpose is for learning. The App class is the most super class. And the Tabs class has inherited it. Can I make the following code more meaningful and break it for more better classes? Instead of creating notebook = self.notebook for all the Tabs class methods, can't I initialize it in the Tab class's init method. When it is done notebook was non recognizable. I need all the tabs background color to be same. Hence, if I can mention it in the Tabs class's init method and convert its other methods(about, ..., visualize) into child classes of Tabs class, will it be a good suggestion? kindly help import tkinter as tk from tkinter import ttk from PIL import Image, ImageTk from tkinter.filedialog import askopenfile from tkinter.font import Font class App(tk.Tk): def __init__(self): super().__init__() # intializing the window self.title("Data Visualization") # configuring size of the window self.geometry('800x650') # this removes the maximize button self.resizable(0,0)
{ "domain": "codereview.stackexchange", "id": 43256, "lm_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", "url": null }
python, tkinter # Styling the tabs s = ttk.Style() s.theme_create('pastel', settings={ ".": { "configure": { "background": '#ffffff', # All except tabs "font": 'red' } }, "TNotebook": { "configure": { "background":'#848a98', # Your margin color "tabmargins": [5, 5, 4, 4], # margins: left, top, right, separator } }, "TNotebook.Tab": { "configure": { "background": '#d9ffcc', # tab color when not selected "padding": [10, 2], # [space between text and horizontal tab-button border, space between text and vertical tab_button border] "font":"white" }, "map": { "background": [("selected", '#ccffff')], # Tab color when selected "expand": [("selected", [1, 1, 1, 0])] # text margins } } }) s.theme_use('pastel') #s.theme_use('default') s.configure('TNotebook.Tab', font=('URW Gothic L','13','bold')) #s.map("TNotebook", background= [("selected", "#ffffff")]) #Create Tab Control self.notebook = ttk.Notebook(self) class Tabs(App): def __init__(self): super().__init__() def about(self): my_font = Font( family = 'Arial', size = 15, weight = 'bold', slant = 'roman', underline = 0, overstrike = 0 ) my_font2 = Font( family = 'Arial', size = 11, #weight = 'bold', slant = 'roman', underline = 0, overstrike = 0 )
{ "domain": "codereview.stackexchange", "id": 43256, "lm_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", "url": null }
python, tkinter notebook = self.notebook f1 = tk.Frame(notebook)#,background="#FFFAF0") #logo logo = Image.open('airport.jpg') #Resize the Image using resize method resized_image= logo.resize((600,300), Image.ANTIALIAS) logo = ImageTk.PhotoImage(resized_image) logo_label = ttk.Label(f1,image=logo,relief="raised") logo_label.image = logo #logo_label.grid(column=3, row=0) logo_label.place(relx=0.12,rely=0.1) # using place notebook.add(f1, text="About" ) # Tab1 ttk.Label(f1, text="Airports, Airport-frequencies and Runways analysis", font=my_font).place(relx=0.2,rely=0.03)
{ "domain": "codereview.stackexchange", "id": 43256, "lm_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", "url": null }
python, tkinter #text box text_box = tk.Text(f1, height =10,font=my_font2) text_box.insert(1.0,"""This application allows you to analyze Airports, Airport-frequencies and Runways of Europe. • Tab "Load and Save Actions" is to load the initial data set (which consists of three CSV files) and translate it into a suitable format. \n\n• Tab "Preprocess" is to clean and prepare the initial data set, managing inconsistences, \nerrors, missing values and any specific changes required. \n\n• Tab "Visualize" is to use the prepared data set to generate output and visualisations.""" ) text_box.tag_configure("center", justify="center") text_box.tag_add("center", 1.0, "end") text_box.place(relx=0.1, rely=0.65) text_box.config(highlightthickness = 2, borderwidth=0,background='#FFFAFA') notebook.pack(expand=1, fill="both") def load_save(self): notebook = self.notebook f2 = tk.Frame(notebook,background="#ffffff") notebook.add(f2, text="Load and Save Actions" ) def preprocess(self): notebook = self.notebook f3 = tk.Frame(notebook,background="#ffffff") notebook.add(f3, text="Preprocess" ) def visualize(self): notebook = self.notebook f4 = tk.Frame(notebook,background="#ffffff") notebook.add(f4, text="Visualize" ) if __name__ == "__main__": tabs=Tabs() tabs.about() tabs.load_save() tabs.preprocess() tabs.visualize() tabs.mainloop() Answer: meaningful as much as possible, using inheritance Inheritance basically has no place here. Eventually, if your tab sections are larger and share more common elements, then perhaps having a Tab superclass would make sense, but it should absolutely not inherit from App. Can I make the following code more meaningful and break it for more better classes?
{ "domain": "codereview.stackexchange", "id": 43256, "lm_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", "url": null }
python, tkinter Can I make the following code more meaningful and break it for more better classes? I have no idea what that means, but you'll either want one single class, or perhaps eventually one class per tab. Otherwise: Don't inherit from Tk; instantiate it (has-a, not is-a). In a few places you've passed 0 where you should pass False. A mature IDE like PyCharm, or probably a type-checking tool like mypy, will tell you this. This includes the call to resizable. Long, constant literals such as your style dictionary may be better-suited to values in effectively static scope. Methods such as about should be called by your constructor, not by the instantiating code; named perhaps _make_preprocess or _setup_preprocess - not preprocess - since this isn't doing the preprocessing marked private via leading underscore; and type-hinted as returning None. You know about tk's ability to process named colours like white, since you've used that - so why would you also be passing #ffffff? Prefer the former. Some of your comments, such as # tab color when not selected, are fine since they're describing something non-obvious. Most others need to be deleted, particularly those like: logo_label.place() # using place f2 is a bad name for at least two reasons. First, it's meaningless and should include the word "frame". Second: this method should work and make sense regardless of whether the frame is actually the second frame. The notebook does not need an index for its add call. So just call it frame. Similarly, don't say my_font; this is actually the label_font. I do not have your airport.jpg so for illustrative purposes I have substituted my own. Suggested import tkinter as tk from tkinter import ttk from PIL import Image, ImageTk from tkinter.font import Font
{ "domain": "codereview.stackexchange", "id": 43256, "lm_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", "url": null }
python, tkinter class App: TAB_SETTINGS = { '.': { 'configure': { 'background': 'white', # All except tabs 'font': 'red' } }, 'TNotebook': { 'configure': { 'background': '#848a98', # Your margin color 'tabmargins': [5, 5, 4, 4], # margins: left, top, right, separator } }, 'TNotebook.Tab': { 'configure': { 'background': '#d9ffcc', # tab color when not selected 'padding': [10, 2], # space between text and horizontal tab-button border, space between text and vertical tab_button border 'font': 'white' }, 'map': { 'background': [('selected', '#ccffff')], # Tab color when selected 'expand': [('selected', [1, 1, 1, 0])] # text margins } } } def __init__(self) -> None: root = self.root = tk.Tk() root.title('Data Visualization') root.geometry('800x650') # this removes the maximize button root.resizable(False, False) s = ttk.Style() s.theme_create('pastel', settings=self.TAB_SETTINGS) s.theme_use('pastel') s.configure('TNotebook.Tab', font=('URW Gothic L', '13', 'bold')) self.notebook = ttk.Notebook(root) self._make_about() self._make_load_save() self._make_preprocess() self._make_visualise() self.run = root.mainloop def _make_about(self) -> None: label_font = Font( family='Arial', size=15, weight='bold', slant='roman', underline=False, overstrike=False, ) textbox_font = Font( family='Arial', size=11, slant='roman', underline=False, overstrike=False, )
{ "domain": "codereview.stackexchange", "id": 43256, "lm_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", "url": null }
python, tkinter frame = tk.Frame(self.notebook) logo = Image.open('airplane.png') resized_image = logo.resize((600, 300), Image.ANTIALIAS) logo = ImageTk.PhotoImage(resized_image) logo_label = ttk.Label(frame, image=logo, relief='raised') logo_label.image = logo logo_label.place(relx=0.12, rely=0.1) self.notebook.add(frame, text='About') ttk.Label( frame, text='Airports, Airport-frequencies and Runways analysis', font=label_font, ).place(relx=0.2, rely=0.03) text_box = tk.Text(frame, height=10, font=textbox_font) text_box.insert(1.0, '''This application allows you to analyze Airports, Airport-frequencies and Runways of Europe. • Tab "Load and Save Actions" is to load the initial data set (which consists of three CSV files) and translate it into a suitable format. • Tab "Preprocess" is to clean and prepare the initial data set, managing inconsistences, errors, missing values and any specific changes required. • Tab "Visualize" is to use the prepared data set to generate output and visualisations.''') text_box.tag_configure('center', justify='center') text_box.tag_add('center', 1.0, 'end') text_box.place(relx=0.1, rely=0.65) text_box.config(highlightthickness=2, borderwidth=0, background='#FFFAFA') self.notebook.pack(expand=1, fill='both') def _make_load_save(self) -> None: frame = tk.Frame(self.notebook, background='white') self.notebook.add(frame, text='Load and Save Actions') def _make_preprocess(self) -> None: frame = tk.Frame(self.notebook, background='white') self.notebook.add(frame, text='Preprocess') def _make_visualise(self) -> None: frame = tk.Frame(self.notebook, background='white') self.notebook.add(frame, text='Visualize') if __name__ == '__main__': app = App() app.run() Output
{ "domain": "codereview.stackexchange", "id": 43256, "lm_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", "url": null }
c++, c++11, portability, connect-four Title: Connect Four in C++ Question: This is a library that implements the logic of Connect Four. There's nothing related to graphics or user input here. This library is supposed to be integrated into any environment where one could run C++ (and play Connect Four). I want it to be easy and straightforward to use in virtually any platform, from Desktop to Arduino. Users of this library must be able to focus entirely on their implementation of user input and output, and leverage the logic to this library. Given such focus on portability, I tried to make this code to be 100% ISO C++, and I chose C++11 because it is -- to the best of my admittedly limited knowledge -- available everywhere by now, and allows me to use "modern" language features such as range-based loops. C++11 looks like a good compromise. The focus on portability also means that the code is supposed to run fast enough on resource-constrained devices, not waste memory, and not be unnecessarily large when compiled. (Although I admit that I don't know how large is "unnecessarily large") I have very little experience in C++ so I put a substantial effort into researching good practices to apply on this code. High-level explanation of the code: The Game class is the only class supposed to be used in the outside world. With Game::play the client informs that a player chose a column, and the Game instance uses an observer-like mechanism to notify the client that something happened. There are 2 events: CellFallThrough: Notifies the client that a cell is falling. This is supposed to allow the client to draw the animation. Win: Notifies the client that a player won the game. Here are a few principles that I tried to follow: Aggressive compiler warnings No language extensions Warnings are errors Macros kept to a minimum Strong type safety Unit tests Here are the reasoning for a few choices I made when writing the code:
{ "domain": "codereview.stackexchange", "id": 43257, "lm_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, portability, connect-four", "url": null }
c++, c++11, portability, connect-four Here are the reasoning for a few choices I made when writing the code: Using least types (uint_least8_t, int_least16_t): Those are more portable than fixed-length types (such as uint8_t) and the compiler is able to perform a few tricks to increase performance. Using uint_least8_t for board size: Board size can't be negative, so that's why it's unsigned. Also, typically the size is a single digit number, so 8 bits are more than enough. Using int_least16_t for position: It should to be possible to represent positions outside of the board. The board size is a 8-bit unsigned number, so a 16-bit, signed number is big enough for this. Using class enum: class enums offer better type safety over plain and old C enums. As far as I know, the spirit of C++ is to write high-level code without compromising performance, so that's what I tried to get here. All source files are attached below. The file system tree looks like this: connect_four |--- src |--- Board.cpp |--- Board.hpp |--- CellFallThroughEventData.hpp |--- Game.cpp |--- Game.hpp |--- Player.hpp |--- PlayResult.hpp |--- PlayResult.hpp |--- Position.hpp |--- WinEventData.hpp |--- test |--- config_main.cpp |--- game_on_cell_fall_through.cpp |--- game_on_win.cpp |--- game_play.cpp |--- helper.hpp |--- vendor |--- catch2 |--- catch.hpp |--- makefile Once you have all the files you can run the tests with make clean && make tests && ./run_tests Note: vendor/catch2/catch.hpp isn't written by me, it's the unit test library. You can find it here. src/Board.cpp #include "Board.hpp" #include <cstdint> #include "Player.hpp" #include "Position.hpp" namespace connect_four { #define at(position) (this->_cells[static_cast<std::size_t>(position.row)][static_cast<std::size_t>(position.col)])
{ "domain": "codereview.stackexchange", "id": 43257, "lm_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, portability, connect-four", "url": null }
c++, c++11, portability, connect-four Board::Board(uint_least8_t const row_count, uint_least8_t const col_count) { this->_row_count = row_count; this->_col_count = col_count; auto empty = std::make_pair(Player::PLAYER_1, false); auto row = std::vector<std::pair<Player, bool>>(col_count, empty); this->_cells.resize(row_count, row); } bool Board::is_inside(Position const position) { return position.row >= 0 && position.col >= 0 && position.row < this->_row_count && position.col < this->_col_count; } bool Board::is_empty(Position const position) { return this->is_inside(position) && !at(position).second; } bool Board::is_filled(Position const position, Player const player) { return this->is_inside(position) && at(position).second && at(position).first == player; } void Board::set(Position const position, Player const player) { at(position) = std::make_pair(player, true); } } src/Board.hpp #pragma once #include <cstdint> #include <vector> #include "Player.hpp" #include "Position.hpp" namespace connect_four { class Board { uint_least8_t _row_count; uint_least8_t _col_count; std::vector<std::vector<std::pair<Player, bool>>> _cells; public: Board(uint_least8_t const row_count, uint_least8_t const col_count); bool is_inside(Position const position); bool is_empty(Position const position); bool is_filled(Position const position, Player const player); void set(Position const position, Player const player); }; } src/CellFallThroughEventData.hpp #pragma once #include "Game.hpp" #include "Player.hpp"
{ "domain": "codereview.stackexchange", "id": 43257, "lm_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, portability, connect-four", "url": null }
c++, c++11, portability, connect-four src/CellFallThroughEventData.hpp #pragma once #include "Game.hpp" #include "Player.hpp" namespace connect_four { struct CellFallThroughEventData { connect_four::Player const player; uint_least8_t const row; uint_least8_t const col; bool const is_final_position; }; } src/Game.cpp #include "Game.hpp" #include <cstdint> #include <functional> #include <vector> #include "Board.hpp" #include "CellFallThroughEventData.hpp" #include "WinEventData.hpp" #include "Player.hpp" #include "PlayResult.hpp" #include "Position.hpp" namespace connect_four { Game::Game(uint_least8_t row_count, uint_least8_t col_count) : _board(row_count, col_count) { this->_player = Player::PLAYER_1; this->_ended = false; } PlayResult Game::play(uint_least8_t const col) { if (this->_ended) { return PlayResult::GAME_ALREADY_ENDED; } Position initial_position{0, col}; if (!this->_board.is_inside(initial_position)) { return PlayResult::COLUMN_IS_INVALID; } if (!this->_board.is_empty(initial_position)) { return PlayResult::COLUMN_IS_FULL; } auto position = this->_fall_to_right_row(initial_position); this->_board.set(position, this->_player); if (this->_check_victory(position)) { this->_ended = true; WinEventData event_data{this->_player}; for (auto const & handler : this->_win_handlers) { handler(event_data); } } else { this->_player = this->_player == Player::PLAYER_1 ? Player::PLAYER_2 : Player::PLAYER_1; } return PlayResult::SUCCESS; }
{ "domain": "codereview.stackexchange", "id": 43257, "lm_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, portability, connect-four", "url": null }
c++, c++11, portability, connect-four return PlayResult::SUCCESS; } void Game::on_event(std::function<void (CellFallThroughEventData)> const handler) { this->_cell_fall_through_handlers.push_back(handler); } void Game::on_event(std::function<void (WinEventData)> const handler) { this->_win_handlers.push_back(handler); } Position Game::_fall_to_right_row(Position position) { Position next_pos{static_cast<int_least16_t>(position.row + 1), position.col}; auto is_final = !this->_board.is_empty(next_pos); CellFallThroughEventData event_data{ this->_player, static_cast<uint_least8_t>(position.row), static_cast<uint_least8_t>(position.col), is_final }; for (auto const & handler : this->_cell_fall_through_handlers) { handler(event_data); } return is_final ? position : this->_fall_to_right_row(next_pos); } bool Game::_check_victory(Position position) { auto _check = [this, position](std::function<Position (Position, int_least16_t)> f) { auto counter = 1; int_least16_t i = 1; while (this->_board.is_filled(f(position, i), this->_player)) { counter += 1; i += 1; } i = -1; while (this->_board.is_filled(f(position, i), this->_player)) { counter += 1; i -= 1; } return counter >= 4; };
{ "domain": "codereview.stackexchange", "id": 43257, "lm_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, portability, connect-four", "url": null }
c++, c++11, portability, connect-four return counter >= 4; }; #define make_lambda(row, col) [](Position pos, int_least16_t i) \ { \ return Position{ \ static_cast<int_least16_t>(row), \ static_cast<int_least16_t>(col)}; \ } \ return _check(make_lambda(pos.row , pos.col + i)) || _check(make_lambda(pos.row + i, pos.col )) || _check(make_lambda(pos.row + i, pos.col + i)) || _check(make_lambda(pos.row - i, pos.col + i)); } } src/Game.hpp #pragma once #include <cstdint> #include <functional> #include "Board.hpp" #include "CellFallThroughEventData.hpp" #include "WinEventData.hpp" #include "Player.hpp" #include "PlayResult.hpp" #include "Position.hpp" namespace connect_four { class Game { Player _player; Board _board; bool _ended; std::vector<std::function<void (CellFallThroughEventData)>> _cell_fall_through_handlers; std::vector<std::function<void (WinEventData)>> _win_handlers; bool _check_victory(Position position); Position _fall_to_right_row(Position current_position); public: Game(uint_least8_t const row_count, uint_least8_t const col_count); PlayResult play(uint_least8_t const col); void on_event(std::function<void (CellFallThroughEventData)> const handler); void on_event(std::function<void (WinEventData)> const handler); }; } src/Player.hpp #pragma once namespace connect_four { enum class Player { PLAYER_1, PLAYER_2, }; } src/PlayResult.hpp #pragma once
{ "domain": "codereview.stackexchange", "id": 43257, "lm_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, portability, connect-four", "url": null }
c++, c++11, portability, connect-four src/PlayResult.hpp #pragma once namespace connect_four { enum class PlayResult { SUCCESS, GAME_ALREADY_ENDED, COLUMN_IS_FULL, COLUMN_IS_INVALID, }; } src/Position.hpp #pragma once #include <cstdint> namespace connect_four { struct Position { int_least16_t const row; int_least16_t const col; }; } src/WinEventData.hpp #pragma once #include "Game.hpp" #include "Player.hpp" namespace connect_four { struct WinEventData { Player const winner; }; } test/config_main.cpp #define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> test/game_on_cell_fall_through.cpp #include <vector> #include <catch2/catch.hpp> #include "Game.hpp" #include "helper.hpp" using namespace connect_four; SCENARIO("Cell fall through event happy path") { GIVEN("An empty 6-row-per-7-column board") { Game game(6, 7); std::vector<CellFallThroughEventData> memo; game.on_event(create_handler<CellFallThroughEventData>(&memo)); WHEN("The player chooses a valid column") { auto column = 4; game.play(column); THEN("6 events are emited") { REQUIRE(6 == memo.size()); } THEN("All events report the chosen column") { for (auto event : memo) { REQUIRE(column == event.col); } } THEN("All events report the 1st player") { for (auto event : memo) { REQUIRE(Player::PLAYER_1 == event.player); } } THEN("The 1st event reports the 1st row") { REQUIRE(0 == memo[0].row); } THEN("The 6th event reports the 6th row") { REQUIRE(5 == memo[5].row); }
{ "domain": "codereview.stackexchange", "id": 43257, "lm_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, portability, connect-four", "url": null }
c++, c++11, portability, connect-four THEN("The 1st event is not reported as final position") { REQUIRE(false == memo[0].is_final_position); } THEN("The 6th event is reported as final position") { REQUIRE(true == memo[5].is_final_position); } } } } test/game_on_win.cpp #include <vector> #include <catch2/catch.hpp> #include "Game.hpp" #include "helper.hpp" using namespace connect_four; SCENARIO("Win event not emited on normal, non-winning play") { GIVEN("An empty 6-row-per-7-column board") { Game game(6, 7); std::vector<WinEventData> memo; game.on_event(create_handler<WinEventData>(&memo)); WHEN("The player chooses a valid column") { game.play(0); THEN("No event is emited") { REQUIRE(0 == memo.size()); } } } } SCENARIO("Win event emited on horizontal win") { // // : 1 : 2 : 3 : 4 : 5 : 6 : 7 : // :---:---:---:---:---:---:---: // 1 : : : : : : : : // 2 : : : : : : : : // 3 : : : : : : : : // 4 : : : : : : : : // 5 : O : O : O : : : : : // 6 : X : X : X : : : : : // :---------------------------: GIVEN("A 6-row-per-7-column board with state 112233") { Game game(6, 7); std::vector<WinEventData> memo; game.on_event(create_handler<WinEventData>(&memo)); game.play(0); game.play(0); game.play(1); game.play(1); game.play(2); game.play(2); WHEN("The player chooses the 4th column") { game.play(3); THEN("1 event is emited for player 1") { REQUIRE(1 == memo.size()); REQUIRE(Player::PLAYER_1 == memo[0].winner); } } } }
{ "domain": "codereview.stackexchange", "id": 43257, "lm_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, portability, connect-four", "url": null }
c++, c++11, portability, connect-four SCENARIO("Win event emited on vertical win") { // : 1 : 2 : 3 : 4 : 5 : 6 : 7 : // :---:---:---:---:---:---:---: // 1 : : : : : : : : // 2 : : : : : : : : // 3 : : : : : : : : // 4 : X : O : : : : : : // 5 : X : O : : : : : : // 6 : X : O : : : : : : // :---------------------------: GIVEN("A 6-row-per-7-column board with state 121212") { Game game(6, 7); std::vector<WinEventData> memo; game.on_event(create_handler<WinEventData>(&memo)); game.play(0); game.play(1); game.play(0); game.play(1); game.play(0); game.play(1); WHEN("The player chooses the 1th column") { game.play(0); THEN("1 event is emited for player 1") { REQUIRE(1 == memo.size()); REQUIRE(Player::PLAYER_1 == memo[0].winner); } } } } SCENARIO("Win event emited on main diagonal win") { // : 1 : 2 : 3 : 4 : 5 : 6 : 7 : // :---:---:---:---:---:---:---: // 1 : : : : : : : : // 2 : : : : : : : : // 3 : X : : : : : : : // 4 : O : : O : : : : : // 5 : O : O : X : : : : : // 6 : X : X : O : X : : : : // :---------------------------: GIVEN("A 6-row-per-7-column board with state 1121124333") { Game game(6, 7); std::vector<WinEventData> memo; game.on_event(create_handler<WinEventData>(&memo)); game.play(0); game.play(0); game.play(1); game.play(0); game.play(0); game.play(1); game.play(3); game.play(2); game.play(2); game.play(2); WHEN("The player chooses the 2nd column") { game.play(1);
{ "domain": "codereview.stackexchange", "id": 43257, "lm_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, portability, connect-four", "url": null }
c++, c++11, portability, connect-four WHEN("The player chooses the 2nd column") { game.play(1); THEN("1 event is emited for player 1") { REQUIRE(1 == memo.size()); REQUIRE(Player::PLAYER_1 == memo[0].winner); } } } } SCENARIO("Win event emited on secondary diagonal win") { // : 1 : 2 : 3 : 4 : 5 : 6 : 7 : // :---:---:---:---:---:---:---: // 1 : : : : : : : : // 2 : : : : : : : : // 3 : : : O : : : : : // 4 : : : X : O : : : : // 5 : : X : X : O : : : : // 6 : X : O : X : O : : : : // :---------------------------: GIVEN("A 6-row-per-7-column board with state 1234243433") { Game game(6, 7); std::vector<WinEventData> memo; game.on_event(create_handler<WinEventData>(&memo)); game.play(0); game.play(1); game.play(2); game.play(3); game.play(1); game.play(3); game.play(2); game.play(3); game.play(2); game.play(2); WHEN("The player chooses the 4th column") { game.play(3); THEN("1 event is emited for player 1") { REQUIRE(1 == memo.size()); REQUIRE(Player::PLAYER_1 == memo[0].winner); } } } } SCENARIO("Win event emited on win when last play at the middle") { // : 1 : 2 : 3 : 4 : 5 : 6 : 7 : // :---:---:---:---:---:---:---: // 1 : : : : : : : : // 2 : : : : : : : : // 3 : : : : : : : : // 4 : : : : : : : : // 5 : O : O : : O : O : : : // 6 : X : X : : X : X : : : // :---------------------------: GIVEN("A 6-row-per-7-column board with state 11224455") { Game game(6, 7); std::vector<WinEventData> memo;
{ "domain": "codereview.stackexchange", "id": 43257, "lm_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, portability, connect-four", "url": null }
c++, c++11, portability, connect-four std::vector<WinEventData> memo; game.on_event(create_handler<WinEventData>(&memo)); game.play(0); game.play(0); game.play(1); game.play(1); game.play(3); game.play(3); game.play(4); game.play(4); WHEN("The player chooses the 3rd column") { game.play(2); THEN("1 event is emited for player 1") { REQUIRE(1 == memo.size()); REQUIRE(Player::PLAYER_1 == memo[0].winner); } } } } SCENARIO("Win event emited on player 2 win") { // : 1 : 2 : 3 : 4 : 5 : 6 : 7 : // :---:---:---:---:---:---:---: // 1 : : : : : : : : // 2 : : : : : : : : // 3 : : : : : : : : // 4 : : : : : : : : // 5 : X : X : X : : : : : // 6 : O : O : O : : X : : : // :---------------------------: GIVEN("A 6-row-per-7-column board with state 5112233") { Game game(6, 7); std::vector<WinEventData> memo; game.on_event(create_handler<WinEventData>(&memo)); game.play(4); game.play(0); game.play(0); game.play(1); game.play(1); game.play(2); game.play(2); WHEN("The player chooses the 4th column") { game.play(3); THEN("1 event is emited for player 2") { REQUIRE(1 == memo.size()); REQUIRE(Player::PLAYER_2 == memo[0].winner); } } } } test/game_play.cpp #include <catch2/catch.hpp> #include "Game.hpp" using namespace connect_four; SCENARIO("Play happy path") { GIVEN("An empty board") { Game game(6, 7); WHEN("The player chooses the first column") { auto play_result = game.play(0);
{ "domain": "codereview.stackexchange", "id": 43257, "lm_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, portability, connect-four", "url": null }
c++, c++11, portability, connect-four THEN("The game accepts the play") { REQUIRE(PlayResult::SUCCESS == play_result); } } } } SCENARIO("A column that is full cannot accept any more plays") { GIVEN("A board whose first column is full") { Game game(6, 7); game.play(0); game.play(0); game.play(0); game.play(0); game.play(0); game.play(0); WHEN("The player chooses the first column") { auto play_result = game.play(0); THEN("The game does not accept the play") { REQUIRE(PlayResult::COLUMN_IS_FULL == play_result); } } } } SCENARIO("The chosen column must be validated") { GIVEN("A 6-row-per-7-column board") { Game game(6, 7); WHEN("The player chooses the 8th column") { auto play_result = game.play(7); THEN("The game does not accept the play") { REQUIRE(PlayResult::COLUMN_IS_INVALID == play_result); } } } } test/helper.hpp #include <functional> #include <vector> template<typename T> std::function<void (T)> create_handler(std::vector<T>* memo) { return [memo](T event_data) mutable { memo->push_back(event_data); }; } vendor/catch2/catch.hpp https://raw.githubusercontent.com/catchorg/Catch2/v2.x/single_include/catch2/catch.hpp
{ "domain": "codereview.stackexchange", "id": 43257, "lm_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, portability, connect-four", "url": null }
c++, c++11, portability, connect-four Answer: Avoid macros whenever possible As marcinj already mentioned in the comments, you can replace the macro at() with a regular function. Macros are problematic in many ways. Here the biggest problem is that while you think you defined it inside namespace connect_four, macros are not bound at all by namespaces. When you define this, you can no longer use any function named at(), like for example std::vector::at(). I strongly recommend you make this a member function that returns a reference to a cell: std::pair<Player, bool>& Board::at(const Postion& position) { return _cells[position.row][position.col]; } This should be a complete drop-in replacement for your macro. The same goes for make_lambda(). Instead of passing a lambda to _check(), just pass extra parameters to _check() to encode the direction to check in. For example: auto _check = [this, position](int dx, int dy) { f = [dx, dy](Position pos, int i) { return Position{pos.row + dx * i, pos.col + dx * i}; } ... }; return _check(0, 1) || _check(1, 0) || _check(1, 1) || _check(-1, 1); Create a struct Cell Instead of using the add-hoc std::pair<Player, bool> for cells, create a struct that represents a cell. That makes the code simpler and easier to modify if you ever want to add more information to a cell: class Board { struct Cell { Player player; bool filled = false; }; std::vector<std::vector<Cell>> _cells; ... }; You also no longer have to remember whether Player was first or second, and you don't have to use std::make_pair(). Using a default member initialier, you also don't have to explicitly define an empty cell, you can now just write: _cells.resize(row_count, std::vector<Cell>(col_count));
{ "domain": "codereview.stackexchange", "id": 43257, "lm_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, portability, connect-four", "url": null }
c++, c++11, portability, connect-four Use a one-dimensional vector to store the cells of the board A vector of vectors is a rather inefficient data structure, since the outer vector basically is just a bunch of pointers for every column. Following pointers is less efficient on the CPU than doing a multiplication and addition. Therefore, it's recommended that you do something like this: std::vector<Cell> _cells; Cell& Board::at(const Position& position) { return _cells[position.row * _col_count + position.col]; } Board::Board(uint_least8_t const row_count, uint_least8_t const col_count) { _row_count = row_count; _col_count = col_count; _cells.resize(row_count * col_count); } Make use of default member intializers and member initializer lists Initializing variables inside the body of a constructor has a few drawbacks. The order of initialization can be different from the order in which destructors are called, and it can be less efficient since for example first it will create an empty vector _cells, and then you are resizing it. While it's not wrong, it is better to use member initializer lists and/or default member intializers where possible. For example, using member initializer lists your constructor becomes: Board::Board(uint_least8_t const row_count, uint_least8_t const col_count): _row_count(row_count), _col_count(col_count), _cells(row_count * col_count) { }
{ "domain": "codereview.stackexchange", "id": 43257, "lm_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, portability, connect-four", "url": null }
c++, c++11, portability, connect-four You have to use member initializer lists or initialization in the constructor body for those variables that depend directly on constructor parameters, like _row_count and _col_count. However, variables that do not depend on those parameters, like filled in struct Cell above, can be initialized using default member initializers. Unnecessary use of this-> It is almost never necessary to write this-> in C++. I would remove it where possible, since that will make the code much easier to read. Event handling Using callbacks to signal events to the application that uses this library is not a bad idea. However, I would stop at just providing a single slot for each callback type. Adding vectors so multiple callbacks can be registered per event type is adding unnecessary complexity to your library. If the application really needs to have multiple callbacks registered, then it could install one callback that in turn has a vector of callbacks that it will call. This reduces the responsibilities of your library. Alternatively, use another library to handle callback registration, like libsigc++.
{ "domain": "codereview.stackexchange", "id": 43257, "lm_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, portability, connect-four", "url": null }
python, performance, functional-programming, fizzbuzz Title: Fizzbuzz Solution - complexity, readability, performance, lines, obfuscation... - .sort() Question: The fizzbuzz challenge presents a lot of interesting questions for 'intermediate' programmers like myself. I have found that I don't actually know where to draw the line with, complex (hard to read but concise/efficient) code and simple (easy to read but not concise) code. Additionally, I actually do not know if my 'more efficient' code, actually performs better, or is just an expectation that complexity=efficiency. I am sure it doesn't. I made the example below after pondering this for a while and running a few tests, it is a solution using a lambda function inside the list comp. Sort of functional programming but without meaning... output = ["fizzbuzz", "buzz", "fizz"] iterList = lambda x: [x%i for i in [15, 5, 3]] fizzBuzz = [output[iterList(x).index(0)] if 0 in iterList(x) else x for x in range(1, 101)] print(fizzBuzz) The main concern I have is in regard to computational efficiency. While this code is concise, reasonably complex and works. Would it actually perform any faster than a simple 5-to-10 line if, else function? Is there any point in designating the lambda function to a variable? Why would anyone sacrifice readability for complexity if there is no incentive? I have so many questions, but I guess thats the curve with programming; you think you're so good until you realise you're so bad.
{ "domain": "codereview.stackexchange", "id": 43258, "lm_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, functional-programming, fizzbuzz", "url": null }
python, performance, functional-programming, fizzbuzz Answer: I don't want to post a full review but multi-line code should not be posted into comments. Your code is not as efficient as you think. lambda x: [x%i for i in [15, 5, 3]] The above line is very inefficient, you correctly identified the precedence of the moduli, but you did not use it to short circuit the executions. For example, 30 is a multiple of 15 and it should generate "FizzBuzz", here we only need to check whether it is a multiple of 15, because it is a multiple of 15 we don't need and shouldn't check whether it is a multiple of 5 or 3, your code performs two more redundant checks that only worsens the performance. 25 is a multiple of 5, we first check whether it is a multiple of 15, it is not, we then check whether it is a multiple of 5, it is, so log "Buzz", done, there is absolutely no reason to check if it is a multiple of 3. So you should write it like this: special = {15: 'FizzBuzz', 5: 'Buzz', 3: 'Fizz'} for i in (15, 5, 3): if not number % i: var = special[i] break break is a keyword that stops the loop, so it won't perform consecutive checks. special is a dict, if you don't know what a dictionary is, look it up. It is much better than your double list indexing. for loops also have an else clause, which executes after the loop is completed normally. So if the number is not a multiple of any of the three, to get the number itself: special = {15: 'FizzBuzz', 5: 'Buzz', 3: 'Fizz'} for i in (15, 5, 3): if not number % i: var = special[i] break else: var = number We normally wrap code we want to use repetitively inside functions, and use return to return the output back to the caller, return automatically stops the function so anything after it will not be executed. The function: special = {15: 'FizzBuzz', 5: 'Buzz', 3: 'Fizz'} def fizzbuzz(number): for i in (15, 5, 3): if not number % i: return special[i] return number
{ "domain": "codereview.stackexchange", "id": 43258, "lm_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, functional-programming, fizzbuzz", "url": null }
python, performance, functional-programming, fizzbuzz The function is much better than your three lines of code. To print first 100 fizzbuzz values: special = {15: 'FizzBuzz', 5: 'Buzz', 3: 'Fizz'} def fizzbuzz(number): for i in (15, 5, 3): if not number % i: return special[i] return number for i in range(1, 101): print(fizzbuzz(i)) Update If you only care about performance, here is a one-liner that uses generator expressions and next and I won't explain any of these two. SPECIAL = {15: 'FizzBuzz', 5: 'Buzz', 3: 'Fizz'} def fizzbuzz(number): return next((label for x, label in SPECIAL.items() if not number % x), number) Ultimate code golf: a='Fizz';b='Buzz';S={15:a+b,5:b,3:a};f=lambda n:next((l for c,l in S.items()if not n%c),n) The human readable function is 170 bytes, the one-liner is 104 bytes and the golfed version is 90 bytes. Final Edit I did some testing and here are the results: Python 3.9.10 (tags/v3.9.10:f2f3f53, Jan 17 2022, 15:14:21) [MSC v.1929 64 bit (AMD64)] Type 'copyright', 'credits' or 'license' for more information IPython 7.28.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: special = {15: 'FizzBuzz', 5: 'Buzz', 3: 'Fizz'} ...: def fizzbuzz(number): ...: for i in (15, 5, 3): ...: if not number % i: ...: return special[i] ...: return number In [2]: def fizz_buzz(n): ...: for k, v in special.items(): ...: if not n % k: ...: return v ...: return n In [3]: def FizzBuzz(number): ...: return next((label for x, label in special.items() if not number % x), number) In [4]: a='Fizz';b='Buzz';S={15:a+b,5:b,3:a};f=lambda n:next((l for c,l in S.items()if not n%c),n) In [5]: fizzbuzz(255) Out[5]: 'FizzBuzz' In [6]: fizz_buzz(255) Out[6]: 'FizzBuzz' In [7]: FizzBuzz(255) Out[7]: 'FizzBuzz' In [8]: f(255) Out[8]: 'FizzBuzz' In [9]: %timeit fizzbuzz(255) 170 ns ± 0.897 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
{ "domain": "codereview.stackexchange", "id": 43258, "lm_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, functional-programming, fizzbuzz", "url": null }
python, performance, functional-programming, fizzbuzz In [10]: %timeit fizz_buzz(255) 256 ns ± 8.71 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [11]: %timeit FizzBuzz(255) 712 ns ± 13.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [12]: %timeit f(255) 688 ns ± 8.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [13]: import dis In [14]: dis.dis(fizzbuzz) 3 0 LOAD_CONST 1 ((15, 5, 3)) 2 GET_ITER >> 4 FOR_ITER 24 (to 30) 6 STORE_FAST 1 (i) 4 8 LOAD_FAST 0 (number) 10 LOAD_FAST 1 (i) 12 BINARY_MODULO 14 POP_JUMP_IF_TRUE 4 5 16 LOAD_GLOBAL 0 (special) 18 LOAD_FAST 1 (i) 20 BINARY_SUBSCR 22 ROT_TWO 24 POP_TOP 26 RETURN_VALUE 28 JUMP_ABSOLUTE 4 6 >> 30 LOAD_FAST 0 (number) 32 RETURN_VALUE In [15]: dis.dis(fizz_buzz) 2 0 LOAD_GLOBAL 0 (special) 2 LOAD_METHOD 1 (items) 4 CALL_METHOD 0 6 GET_ITER >> 8 FOR_ITER 24 (to 34) 10 UNPACK_SEQUENCE 2 12 STORE_FAST 1 (k) 14 STORE_FAST 2 (v) 3 16 LOAD_FAST 0 (n) 18 LOAD_FAST 1 (k) 20 BINARY_MODULO 22 POP_JUMP_IF_TRUE 8 4 24 LOAD_FAST 2 (v) 26 ROT_TWO 28 POP_TOP 30 RETURN_VALUE 32 JUMP_ABSOLUTE 8 5 >> 34 LOAD_FAST 0 (n) 36 RETURN_VALUE
{ "domain": "codereview.stackexchange", "id": 43258, "lm_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, functional-programming, fizzbuzz", "url": null }
python, performance, functional-programming, fizzbuzz 5 >> 34 LOAD_FAST 0 (n) 36 RETURN_VALUE In [16]: dis.dis(FizzBuzz) 2 0 LOAD_GLOBAL 0 (next) 2 LOAD_CLOSURE 0 (number) 4 BUILD_TUPLE 1 6 LOAD_CONST 1 (<code object <genexpr> at 0x00000269CA7D69D0, file "<ipython-input-3-ca9b85259fb4>", line 2>) 8 LOAD_CONST 2 ('FizzBuzz.<locals>.<genexpr>') 10 MAKE_FUNCTION 8 (closure) 12 LOAD_GLOBAL 1 (special) 14 LOAD_METHOD 2 (items) 16 CALL_METHOD 0 18 GET_ITER 20 CALL_FUNCTION 1 22 LOAD_DEREF 0 (number) 24 CALL_FUNCTION 2 26 RETURN_VALUE Disassembly of <code object <genexpr> at 0x00000269CA7D69D0, file "<ipython-input-3-ca9b85259fb4>", line 2>: 2 0 LOAD_FAST 0 (.0) >> 2 FOR_ITER 22 (to 26) 4 UNPACK_SEQUENCE 2 6 STORE_FAST 1 (x) 8 STORE_FAST 2 (label) 10 LOAD_DEREF 0 (number) 12 LOAD_FAST 1 (x) 14 BINARY_MODULO 16 POP_JUMP_IF_TRUE 2 18 LOAD_FAST 2 (label) 20 YIELD_VALUE 22 POP_TOP 24 JUMP_ABSOLUTE 2 >> 26 LOAD_CONST 0 (None) 28 RETURN_VALUE
{ "domain": "codereview.stackexchange", "id": 43258, "lm_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, functional-programming, fizzbuzz", "url": null }
python, performance, functional-programming, fizzbuzz In [17]: dis.dis(f) 1 0 LOAD_GLOBAL 0 (next) 2 LOAD_CLOSURE 0 (n) 4 BUILD_TUPLE 1 6 LOAD_CONST 1 (<code object <genexpr> at 0x00000269CAA370E0, file "<ipython-input-4-a067fdb714e4>", line 1>) 8 LOAD_CONST 2 ('<lambda>.<locals>.<genexpr>') 10 MAKE_FUNCTION 8 (closure) 12 LOAD_GLOBAL 1 (S) 14 LOAD_METHOD 2 (items) 16 CALL_METHOD 0 18 GET_ITER 20 CALL_FUNCTION 1 22 LOAD_DEREF 0 (n) 24 CALL_FUNCTION 2 26 RETURN_VALUE Disassembly of <code object <genexpr> at 0x00000269CAA370E0, file "<ipython-input-4-a067fdb714e4>", line 1>: 1 0 LOAD_FAST 0 (.0) >> 2 FOR_ITER 22 (to 26) 4 UNPACK_SEQUENCE 2 6 STORE_FAST 1 (c) 8 STORE_FAST 2 (l) 10 LOAD_DEREF 0 (n) 12 LOAD_FAST 1 (c) 14 BINARY_MODULO 16 POP_JUMP_IF_TRUE 2 18 LOAD_FAST 2 (l) 20 YIELD_VALUE 22 POP_TOP 24 JUMP_ABSOLUTE 2 >> 26 LOAD_CONST 0 (None) 28 RETURN_VALUE In [18]:
{ "domain": "codereview.stackexchange", "id": 43258, "lm_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, functional-programming, fizzbuzz", "url": null }
python, performance, functional-programming, fizzbuzz In [18]: My original function is the fastest, it takes only about 180 nanoseconds to complete. As a general rule of thumb, if a function generates less bytecode, it is going to cost less time, because the function would be simpler for the CPU. Code golfing is a bad thing, you use less characters but the logic is poorly thought because you can only pack so many ideas inside a few characters, so the compiler generates more bytecode to compensate. And I don't use generator expressions, as you can see, generator expressions generate more code-objects which means you have more bytecode which in turn means performance degradation (very broadly speaking), because function calls are expensive.
{ "domain": "codereview.stackexchange", "id": 43258, "lm_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, functional-programming, fizzbuzz", "url": null }
python, simulation Title: Python implementation of a Galton board simulation Question: I watched a YouTube show the other day in which a variant of a Galton board is used to make a random selection from a range of movies that will be reviewed in that show. In contrast to a standard Galton board in which the ball is usually dropped from the mid-point, which results in a normal distribution, the starting position of the ball in the show is random. While watching, I was wondering whether this change really resulted in a uniform distribution of choices, and I sat down to write a Galton board simulator to test. I've ended up with a class Galton that can be initialized with different board parameters (number of rows, number of bins). It provides the method simulate() that can be called with a parameter controlling the starting position of each bead during a simulation run; the number of beads per simulation can also be specified. I believe my implementation is correct, but apart from a visual inspection of the the histograms I have no good idea how to test that formally. The class and the methods contain doc-strings, and I've used type-hints (even if I'm not not a huge fan of this feature). In which ways can my code be improved with regard to coding style, documentation style, or program logic? Is there something that I've missed? from collections import Counter from matplotlib import pyplot as plt from matplotlib.ticker import PercentFormatter from pandas import Series from random import randint class Galton: """ A Galton board class that can be used to simulate the distribution into bins of a number of beads running through the board.
{ "domain": "codereview.stackexchange", "id": 43259, "lm_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, simulation", "url": null }
python, simulation The board is assumed to comprise an even number of 'row pairs'. Whenever a bead passes through a member of a row pair in a simulated run, the bin position of the bead is moved randomly either a half-bin unit to the left or to the right. Consequently, after passing a row pair, the bin position of the bead has either moved a full bin unit to the left, stayed at the same bin unit, or moved a full bin unit to the right. If this results in a bin position outside the board, the bead is bounced back into the board by one full bin unit. """ def __init__(self, row_pairs: int, bins: int): """ Initialize a Galton board with the specified number of row pairs and bins. Arguments -------- row_pairs: int The number of "row pairs" bins: int The number of bins (zero is not included as a bin) """ self.bins = bins self.rows = row_pairs * 2 def is_valid(self, position: float) -> bool: """ Check if the argument is a valid board position. Argument -------- position: float The position value to be checked (in bin units, including half-bins) Returns ------- check: bool True if the position value is valid, or false otherwise """ return 0 < position < self.bins + 1 def move_down(self, position: float) -> float: """ Move the bead down one row on the board by updating its bin position. Argument -------- position: float The current position of the bead (in bin units, including half-bins)
{ "domain": "codereview.stackexchange", "id": 43259, "lm_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, simulation", "url": null }
python, simulation Returns ------- position: float The new position of the bead after passing a row (in bin units, including half-bins) """ d = -0.5 if randint(0, 1) else 0.5 position += d if not self.is_valid(position): position -= d * 2 return position def run_bead(self, start=None) -> int: """ Run a bead from its starting position into a final bin by passing it through the board. Argument -------- start: The starting position of the bead (see `simulate()` for details) Returns ------- position: int The bin in which the bead ends up after running through the board """ position = start or randint(1, self.bins) if not self.is_valid(position): raise ValueError("Bin position out of range") for _ in range(self.rows): position = self.move_down(position) return int(position) def simulate(self, beads: int, start=None) -> None: """ Show the histogram of results for a specified number of beads on the board. The simulation condition can be specified by specifying the `start` argument (see below). Arguments --------- beads: int The number of beads that will be used in the simulation start: int, or None If `start` is an integer, its value is used by as the starting bin position of every bead. If `start` is None (the default), the starting bin position of each bead will be randomly chosen from the possible bin positions of the board. """ count = Counter(self.run_bead(start) for _ in range(beads))
{ "domain": "codereview.stackexchange", "id": 43259, "lm_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, simulation", "url": null }
python, simulation (Series(count).sort_index() .mul(100) .div(beads) .plot(kind="bar", xlabel="Bins", ylabel="Relative frequency")) plt.xticks(rotation=0) plt.gca().yaxis.set_major_formatter(PercentFormatter()) plt.show() # Simulate a classic Galton board in which all beads are released at the # midpoint of the board: Galton(row_pairs=11, bins=21).simulate(beads=100000, start=11) # Simulate the variant used in the YouTube show in which any starting position # is possible: Galton(row_pairs=11, bins=21).simulate(beads=100000, start=None) Answer: Seems nice. I'm convinced that the probabilities at the edges are less than the ones in the middle. Mirroring wrong moves using position -= d * 2 will break the uniform distribution. But I guess it may be inside the noise. Testing random algorithms can be done with dependency injection. You can have some more parameters in __init__ like this: def __init__(self, row_pairs: int, bins: int, *, random_position: Callable = random.randint, random_direction: Callable = random.randint): (...) self.random_position = random_position self.random_direction = random_direction If you do so, and use these functions in your code, you can inject your own version whenever you want. For example that always give you the least value, or the middle one, or whatever you can implement. With deterministic implementations you can write tests. You can omit the star if you want, but it feels more natural to force these parameters as keyword-only. Let's say, you want to test what happens if all the beads start from the left, and you always get +1/2. It's one of the easiest cases. You can do it like: def my_random_position(start, stop): return start def my_random_direction(start, stop): return stop
{ "domain": "codereview.stackexchange", "id": 43259, "lm_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, simulation", "url": null }
python, simulation def my_random_direction(start, stop): return stop Galton(row_pairs=11, bins=21).simulate(beads=100000, start=11, random_position=my_random_position, random_direction=my_random_direction) If you also split simulating (creating) data from plotting it. You can write unit tests easily. You can also use mocking with the same effect, but for me dependency injection is a less magic, more functional, nicer way. UPDATE: I would use random.choice([0.5, -0.5]) instead of -0.5 if randint(0, 1) else 0.5 Maybe fractions.Fraction(1/2) would be better however. Using floating point numbers can be problematic if you want to calculate integers because of rounding errors. But 1/2 has a pretty simple binary form, and you not multiply/divide it, so it seems OK. A started to refactor on Github and I also added some test cases to show what I meant earlier.
{ "domain": "codereview.stackexchange", "id": 43259, "lm_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, simulation", "url": null }
python, python-3.x, gui, pyqt Title: PyQt6 program that helps you categorizing items Question: Interface:
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt Console output: { "Action": [ "Across The Void", "Alien Shooter 2 Conscription", "Alien Shooter 2 Reloaded", "Aquaria", "Assassin's Creed 3", "Assassin's Creed 3 Liberation", "Child of Light", "Dragon Age 2", "Dragon Age Origins", "Dragon Age Origins - Awakening", "Dreamfall", "Fable 3", "Fallout New Vegas", "Ghost 1.0", "Jade Empire", "Mass Effect 1", "Mass Effect 2", "Mass Effect 3", "Star Wars KOTOR", "Tomb Raider (2013)", "Tomb Raider Anniversary", "Tomb Raider Legend", "Tomb Raider Underworld", "Vampire The Masquerade - Bloodlines", "XCOM" ], "Adventure": [ "Across The Void", "Alien Shooter 2 Conscription", "Alien Shooter 2 Reloaded", "Aquaria", "Assassin's Creed 3", "Assassin's Creed 3 Liberation", "Avadon 1 The Black Fortress", "Avadon 2 The Corruption", "Avadon 3 The Warborn", "Avernum Escape From The Pit", "Back to the Future - The Game", "Child of Light", "Choice of Robots", "Dragon Age 2", "Dragon Age Origins", "Dragon Age Origins - Awakening", "Dreamfall", "Emerald City Confidential", "Exiled Kingdoms", "Fable 3", "Fallout New Vegas", "Forgotton Anne", "Ghost 1.0", "Headliner", "Headliner NoviNews", "Invisible Inc", "Jade Empire", "Jurassic Park - The Game", "Jydge", "Kathy Rain", "King's Bounty Crossworlds", "King's Bounty Dark Side", "Life Is Strange", "Lucid Dream Adventures", "Machinarium", "Marvel's Guardians of the Galaxy", "Mass Effect 1", "Mass Effect 2", "Mass Effect 3", "Neon Chrome", "Open Sorcery",
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt "Mass Effect 2", "Mass Effect 3", "Neon Chrome", "Open Sorcery", "Oxenfree", "Perfect Match", "Primordia", "Queen's Wish - The Conqueror", "Rising Angels Reborn", "Serafina's Saga", "Shadowrun 1 Returns", "Shadowrun 2 Dragonfall", "Shadowrun 3 Hong Kong", "Shardlight", "Shattered Pixel Dungeon", "Sorcery 1", "Sorcery 2", "Sorcery 3", "Sorcery 4", "Star Story Horizon Escape", "Star Wars KOTOR", "The Age of Decadence", "The Book of Unwritten Tales", "The Longest Journey", "The Wolf Among Us", "This War of Mine", "Tomb Raider (2013)", "Tomb Raider Anniversary", "Tomb Raider Legend", "Tomb Raider Underworld", "Unavowed", "Valiant Hearts The Great War", "Vampire The Masquerade - Bloodlines", "Whispers of a Machine", "XCOM" ], "Branching Story": [ "Across The Void", "Avadon 1 The Black Fortress", "Avadon 2 The Corruption", "Avadon 3 The Warborn", "Avernum Escape From The Pit", "Choice of Robots", "Dragon Age 2", "Dragon Age Origins", "Dragon Age Origins - Awakening", "Dreamfall", "Exiled Kingdoms", "Fable 3", "Fallout New Vegas", "Forgotton Anne", "Headliner", "Headliner NoviNews", "Heart's Blight", "Jade Empire", "Jurassic Park - The Game", "Kathy Rain", "King's Bounty Crossworlds", "King's Bounty Dark Side", "Life Is Strange", "Marvel's Guardians of the Galaxy", "Mass Effect 1", "Mass Effect 2", "Mass Effect 3", "Night of the Lesbian Vampires", "Open Sorcery", "Oxenfree", "Perfect Match", "Primordia",
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt "Open Sorcery", "Oxenfree", "Perfect Match", "Primordia", "Queen's Wish - The Conqueror", "Rising Angels Reborn", "Serafina's Saga", "Shadowrun 1 Returns", "Shadowrun 2 Dragonfall", "Shadowrun 3 Hong Kong", "Shardlight", "Sorcery 1", "Sorcery 2", "Sorcery 3", "Sorcery 4", "Star Story Horizon Escape", "Star Wars KOTOR", "The Age of Decadence", "The Longest Journey", "The Wolf Among Us", "This War of Mine", "Unavowed", "Vampire The Masquerade - Bloodlines" ], "Choices Matter": [ "Across The Void", "Avadon 1 The Black Fortress", "Avadon 2 The Corruption", "Avadon 3 The Warborn", "Avernum Escape From The Pit", "Choice of Robots", "Codex of Victory", "Demon's Rise War For The Deep", "Dragon Age 2", "Dragon Age Origins", "Dragon Age Origins - Awakening", "Dreamfall", "Exiled Kingdoms", "Fable 3", "Fallout New Vegas", "Ghost 1.0", "Headliner", "Headliner NoviNews", "Invisible Inc", "Jade Empire", "King's Bounty Crossworlds", "King's Bounty Dark Side", "Life Is Strange", "Mass Effect 1", "Mass Effect 2", "Mass Effect 3", "Open Sorcery", "Oxenfree", "Perfect Match", "Primordia", "Queen's Wish - The Conqueror", "Rising Angels Reborn", "Serafina's Saga", "Shadowrun 1 Returns", "Shadowrun 2 Dragonfall", "Shadowrun 3 Hong Kong", "Shardlight", "Shattered Pixel Dungeon", "Sid Meier's Civilization Beyond Earth", "Sorcery 1", "Sorcery 2", "Sorcery 3", "Sorcery 4", "Star Story Horizon Escape", "Star Wars KOTOR",
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt "Sorcery 4", "Star Story Horizon Escape", "Star Wars KOTOR", "The Age of Decadence", "The Longest Journey", "This War of Mine", "Unavowed", "Vampire The Masquerade - Bloodlines", "World In Conflict", "XCOM" ], "Choose Your Own Adventure": [ "Across The Void", "Avadon 1 The Black Fortress", "Avadon 2 The Corruption", "Avadon 3 The Warborn", "Avernum Escape From The Pit", "Choice of Robots", "Dragon Age 2", "Dragon Age Origins", "Dragon Age Origins - Awakening", "Dreamfall", "Exiled Kingdoms", "Fable 3", "Fallout New Vegas", "Headliner", "Headliner NoviNews", "Jade Empire", "Jurassic Park - The Game", "King's Bounty Crossworlds", "King's Bounty Dark Side", "Life Is Strange", "Marvel's Guardians of the Galaxy", "Mass Effect 1", "Mass Effect 2", "Mass Effect 3", "Open Sorcery", "Perfect Match", "Primordia", "Queen's Wish - The Conqueror", "Shadowrun 1 Returns", "Shadowrun 2 Dragonfall", "Shadowrun 3 Hong Kong", "Shardlight", "Sorcery 1", "Sorcery 2", "Sorcery 3", "Sorcery 4", "Star Story Horizon Escape", "Star Wars KOTOR", "The Age of Decadence", "The Longest Journey", "This War of Mine", "Unavowed", "Vampire The Masquerade - Bloodlines" ], "Computer RPG": [ "Avadon 1 The Black Fortress", "Avadon 2 The Corruption", "Avadon 3 The Warborn", "Avernum Escape From The Pit", "Choice of Robots", "Dragon Age 2", "Dragon Age Origins", "Dragon Age Origins - Awakening", "Exiled Kingdoms", "Fable 3", "Fallout New Vegas", "Jade Empire",
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt "Exiled Kingdoms", "Fable 3", "Fallout New Vegas", "Jade Empire", "King's Bounty Crossworlds", "King's Bounty Dark Side", "Life Is Strange", "Mass Effect 1", "Mass Effect 2", "Mass Effect 3", "Neon Chrome", "Open Sorcery", "Perfect Match", "Queen's Wish - The Conqueror", "Shadowrun 1 Returns", "Shadowrun 2 Dragonfall", "Shadowrun 3 Hong Kong", "Sorcery 1", "Sorcery 2", "Sorcery 3", "Sorcery 4", "Star Story Horizon Escape", "Star Wars KOTOR", "The Age of Decadence", "This War of Mine", "Unavowed", "Vampire The Masquerade - Bloodlines", "XCOM" ], "Dialogue Options": [ "Across The Void", "Avadon 1 The Black Fortress", "Avadon 2 The Corruption", "Avadon 3 The Warborn", "Avernum Escape From The Pit", "Back to the Future - The Game", "Choice of Robots", "Dragon Age 2", "Dragon Age Origins", "Dragon Age Origins - Awakening", "Dreamfall", "Emerald City Confidential", "Exiled Kingdoms", "Fable 3", "Fallout New Vegas", "Forgotton Anne", "Headliner", "Headliner NoviNews", "Heart's Blight", "Jade Empire", "Jurassic Park - The Game", "Kathy Rain", "King's Bounty Crossworlds", "King's Bounty Dark Side", "Life Is Strange", "Marvel's Guardians of the Galaxy", "Mass Effect 1", "Mass Effect 2", "Mass Effect 3", "Night of the Lesbian Vampires", "Open Sorcery", "Oxenfree", "Perfect Match", "Primordia", "Queen's Wish - The Conqueror", "Rising Angels Reborn", "Serafina's Saga", "Shadowrun 1 Returns", "Shadowrun 2 Dragonfall",
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt "Serafina's Saga", "Shadowrun 1 Returns", "Shadowrun 2 Dragonfall", "Shadowrun 3 Hong Kong", "Shardlight", "Sorcery 1", "Sorcery 2", "Sorcery 3", "Sorcery 4", "Star Story Horizon Escape", "Star Wars KOTOR", "The Age of Decadence", "The Book of Unwritten Tales", "The Grey Wolf and The Little Lamb", "The Longest Journey", "Unavowed", "Vampire The Masquerade - Bloodlines", "Whispers of a Machine", "Yuki's 4P" ], "Fantasy": [], "Female-Protagonist": [ "Across The Void", "Alien Shooter 2 Reloaded", "Aquaria", "Assassin's Creed 3 Liberation", "Avadon 1 The Black Fortress", "Avadon 2 The Corruption", "Avadon 3 The Warborn", "Avernum Escape From The Pit", "Child of Light", "Choice of Robots", "Contract Demon", "Dragon Age 2", "Dragon Age Origins", "Dragon Age Origins - Awakening", "Dreamfall", "Emerald City Confidential", "Exiled Kingdoms", "Fable 3", "Fallout New Vegas", "Forgotton Anne", "Ghost 1.0", "Headliner", "Headliner NoviNews", "Heart's Blight", "Jade Empire", "Kathy Rain", "King's Bounty Crossworlds", "King's Bounty Dark Side", "Life Is Strange", "Lucid Dream Adventures", "Mass Effect 1", "Mass Effect 2", "Mass Effect 3", "Night of the Lesbian Vampires", "Open Sorcery", "Oxenfree", "Perfect Match", "Queen's Wish - The Conqueror", "Rising Angels Reborn", "Serafina's Saga", "Shadowrun 1 Returns", "Shadowrun 2 Dragonfall", "Shadowrun 3 Hong Kong", "Shardlight", "Shattered Pixel Dungeon", "Sorcery 1", "Sorcery 2", "Sorcery 3",
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt "Shattered Pixel Dungeon", "Sorcery 1", "Sorcery 2", "Sorcery 3", "Sorcery 4", "Star Wars KOTOR", "The Age of Decadence", "The Grey Wolf and The Little Lamb", "The Longest Journey", "Tomb Raider (2013)", "Tomb Raider Anniversary", "Tomb Raider Legend", "Tomb Raider Underworld", "Unavowed", "Vampire The Masquerade - Bloodlines", "Whispers of a Machine", "Yuki's 4P" ], "Graphical Adventure": [], "Interactive Fiction": [], "Lesbian": [], "Moral Dilemma": [], "Multiple-Endings": [], "Real-Time Strategy": [], "Real-Time Tactics": [], "Role-Playing Games": [], "Romance": [], "Sci-Fi": [], "Side-Scroller": [], "Singleplayer": [], "Story Rich": [], "Tactical RPG": [], "Third-Person": [], "Third-Person Shooter": [], "Top-Down Shooter": [], "Turn-Based Strategy": [], "Turn-Based Tactics": [], "Visual Novel": [], "Western RPG": [], "Yuri": [] }
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt Basically a glorified json editor, but it has a GUI. When you open the program, the left part and right part are both initially empty. When you click Import Items, a QInputDialog pops up to get the absolute path of the file you want to open, the file should be a .txt file containing a newline separated list with each line an item in the list, but the program only validates if there is a file located at the inputted path and loads whatever contained inside the file as text, then puts each line as an item in the left side. When you click Import Tags, it gets your input, and the file format is expected to be the same as above. Now for each line in the text, the program creates a QGroupBox and puts it to the right side. Each box is composed of a QLabel and a QListWidget. The text of the line is inside the QLabel, and the QListWidget is initially empty. You can drag and drop items in the lists, and drag (multiple) items to the right side. The items cannot be duplicated, if the source of the drag action is the same as the destination of the drop action, the action is treated as internal move so you can sort the items by drag and drop. All lists are in PyQt6.QtWidgets.QAbstractItemView.SelectionMode.SingleSelection mode. In the left side, the items can be checked, and you can toggle the checkstates of the items by mouse clicks (you don't need to click the checkbox). When you drag an item from the left side to the right side, the program copies the item being dragged plus all checked items, into the QListWidget you dropped the items to, and updates the underlying data structures accordingly, if the items are not already inside the destination. You can't drag and drop items from right side to the left side, nor between the lists in the right side.
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt If you double click an item in the lists, that item will be deleted, and the data will be removed from the corresponding underlying data structure. If you right click on a QGroupBox on the right side, that box will be deleted and the corresponding tag will be deleted. When you import items, the left side will be cleared, then updated with the new data, the lists in the right side will all be cleared, and the data structures will also be updated. When you import tags, the right side will be cleared then updated with new data, and the underlying data structures will also be updated. If you try to add items or tags, the thing will only be added if it does not already exist in the data structures, and the check is case-insensitive. When you press Sort, the program refreshes the left-side and right-side with sorted data, and sorts the underlying data structures. If you press Print, the program outputs one of the underlying data structure to the console in the format shown above, if you press Export, the program will ask for a filepath, validate the filepath then redirect the output to that path if it is valid. Code
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt import ctypes import json import re import sys from collections import Counter from pathlib import Path from PyQt6.QtCore import * from PyQt6.QtGui import * from PyQt6.QtWidgets import * from PyQt6.sip import delete DIRECTORY = str(Path(__file__).absolute().parent).replace('\\', '/') ALIGNMENT = Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop FLAG = Qt.ItemFlag
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt MAINSTYLE = """ QListWidget {{ background: #161940; alternate-background-color: #1c1c5c; show-decoration-selected: 1; }} QListWidget::indicator {{ border: 0px solid black; width: 16px; height: 16px; }} QListWidget::indicator:unchecked {{ image: url({0}/icons/checkbox-unchecked.png); }} QListWidget::indicator:checked {{ image: url({0}/icons/checkbox-checked.png); }} QListWidget::indicator:hover {{ background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.75, x3: 0, y3: 1, stop: 0 #4080c0, stop: 0.75 #b2ffff, stop: 1 #4080c0); }} QListWidget::item {{ border: 2px groove #204080; height: 20px; color: #89cff0; }} QListWidget::item:hover {{ background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #244872, stop: 1 #00c0ff); color: #b2ffff; border: 2px groove #bfcde4; }} QListWidget::item:selected {{ border: 3px groove #4080ff; border-radius: 6px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.75, x3: 0, y3: 1, stop: 0 #4080c0, stop: 0.75 #0080c0, stop: 1 #4080c0); color: #00ffff; }} QScrollBar::vertical {{ border: 2px solid #204060; background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #004060, stop: 1 #00b2e4); position: absolute; width: 16px; }} QScrollBar::handle:vertical {{ min-height: 32px; background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #00c0ff, stop: 1 #102372); margin: 18px; }} QScrollBar::horizontal {{ border: 2px solid #204060; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #004060, stop: 1 #00b2e4); position: absolute; height: 16px; }} QScrollBar::handle:horizontal {{ min-width: 32px;
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt height: 16px; }} QScrollBar::handle:horizontal {{ min-width: 32px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #00c0ff, stop: 1 #102372); margin: 18px; }} QGroupBox {{ border: 3px groove #204080; border-radius: 6px; background: #140052; color: #b2ffff; }} QLabel {{ color: #15f4ee; font: 10pt 'Noto Serif'; }} QMainWindow {{ background: #00122b; }} QInputDialog {{ background: #00122b; }} QPushButton {{ border: 3px outset #4080c0; border-radius: 4px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.75, x3: 0, y3: 1, stop: 0 #4080c0, stop: 0.75 #00aae4, stop: 1 #4080c0); color: blue; }} QPushButton:hover {{ background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.75, x3: 0, y3: 1, stop: 0 #4080c0, stop: 0.75 #b2ffff, stop: 1 #4080c0); }} QPushButton:pressed {{ border: 3px inset #4080c0; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.75, x3: 0, y3: 1, stop: 0 #4080c0, stop: 0.75 #005572, stop: 1 #4080c0); color: #00ffff; }} QLineEdit {{ border: 2px solid #306090; border-radius: 6px; background: #1d2252; color: #b2ffff; }} """.format(DIRECTORY)
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt class Font(QFont): def __init__(self, size): super().__init__() self.setFamily("Noto Serif") self.setStyleHint(QFont.StyleHint.Times) self.setStyleStrategy(QFont.StyleStrategy.PreferAntialias) self.setPointSize(size) self.setHintingPreference(QFont.HintingPreference.PreferFullHinting) class Button(QPushButton): def __init__(self, text): super().__init__() font = Font(8) self.setFont(font) self.setFixedSize(75, 20) self.setText(text) class Label(QLabel): def __init__(self, text): super().__init__() font = Font(10) font.setBold(True) self.setFont(font) self.fontRuler = QFontMetrics(font) self.setText(text) self.autoResize() def autoResize(self): self.Height = self.fontRuler.size(0, self.text()).height() self.Width = self.fontRuler.size(0, self.text()).width() self.setFixedSize(self.Width, self.Height) class LeftPane(QListWidget): def __init__(self): super(LeftPane, self).__init__() font = Font(9) self.setFont(font) self.selected = None self.setDragDropMode(QAbstractItemView.DragDropMode.DragDrop) self.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection) self.setAlternatingRowColors(True) self.setAcceptDrops(True) self.itemClicked.connect(self.onItemClicked) def startDrag(self, actions): selected = self.selectedItems()[0].text() checked = [] for i in range(self.count()): if self.item(i).checkState() == Qt.CheckState.Checked: checked.append(self.item(i).text()) if selected not in checked: checked.append(selected) self.selected = checked super(LeftPane, self).startDrag(actions)
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt def dragEnterEvent(self, event): if event.mimeData().hasUrls(): event.accept() else: super(LeftPane, self).dragEnterEvent(event) def dragMoveEvent(self, event): if event.mimeData().hasUrls(): event.setDropAction(Qt.DropAction.CopyAction) event.accept() else: super(LeftPane, self).dragMoveEvent(event) def supportedDropActions(self) -> Qt.DropAction: return Qt.DropAction.MoveAction def dropEvent(self, event): if event.source() is self: event.setDropAction(Qt.DropAction.MoveAction) super().dropEvent(event) else: return def onItemClicked(self, item): if item.checkState() == Qt.CheckState.Unchecked: item.setCheckState(Qt.CheckState.Checked) else: item.setCheckState(Qt.CheckState.Unchecked) def mouseDoubleClickEvent(self, e: QMouseEvent) -> None: row = self.currentRow() item = self.item(row) self.takeItem(row) text = item.text() Manager.items.remove(text) Manager.lower_items.remove(text.lower()) indexer = list(Manager.tagdict) for tag, values in Manager.tagdict.items(): if text in values: index = indexer.index(tag) index1 = values.index(text) values.remove(text) taglist = window.scrollArea.Layout.itemAt(index).widget().taglist taglist.takeItem(index1)
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt class TagListWidget(QListWidget): def __init__(self, tag): super(TagListWidget, self).__init__() self.setContentsMargins(0, 0, 0, 0) font = Font(9) self.setFont(font) self.accepted = set() self.tag = tag self.setDragDropMode(QAbstractItemView.DragDropMode.DragDrop) self.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection) self.setAlternatingRowColors(True) self.setAcceptDrops(True) self.setFixedHeight(48) def dropEvent(self, event): if event.source() is self: event.setDropAction(Qt.DropAction.MoveAction) super().dropEvent(event) elif event.source().__class__.__name__ == 'LeftPane': selected = event.source().selected for item in selected: if item not in self.accepted: self.accepted.add(item) self.addItem(QListWidgetItem(item)) Manager.tagdict[self.tag].append(item) self.autoResize() def autoResize(self): count = self.count() if not count: count = 1 if count > 5: count = 5 self.setFixedHeight(24*(count+1)) def supportedDropActions(self) -> Qt.DropAction: return Qt.DropAction.MoveAction def mouseDoubleClickEvent(self, e: QMouseEvent) -> None: if e.button() == Qt.MouseButton.LeftButton: row = self.currentRow() item = self.item(row) if item: self.takeItem(row) Manager.tagdict[self.tag].remove(item.text()) self.autoResize()
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt class TagGroupBox(QGroupBox): def __init__(self, tag): super().__init__() self.setContentsMargins(3, 3, 3, 3) self.vbox = QVBoxLayout() self.vbox.setContentsMargins(3, 3, 3, 3) self.vbox.setAlignment(ALIGNMENT) self.label = Label(tag) self.vbox.addWidget(self.label) self.taglist = TagListWidget(tag) self.tag = tag self.vbox.addWidget(self.taglist) self.setLayout(self.vbox) def mousePressEvent(self, event: QMouseEvent) -> None: if event.button() == Qt.MouseButton.RightButton: if self.tag in Manager.tagdict: Manager.tagdict.pop(self.tag) Manager.tags.remove(self.tag) Manager.lower_tags.remove(self.tag.lower()) self.setParent(None) self.deleteLater() else: return super().mousePressEvent(event) class ScrollArea(QScrollArea): def __init__(self, parent): super().__init__() self.setParent(parent) self.setWidgetResizable(True) self.Widget = QWidget() palette = QPalette() brush = QBrush(QColor(0, 12, 61, 255)) brush.setStyle(Qt.BrushStyle.SolidPattern) palette.setBrush(QPalette.ColorGroup.Active, QPalette.ColorRole.Window, brush) palette.setBrush(QPalette.ColorGroup.Inactive, QPalette.ColorRole.Window, brush) self.Widget.setPalette(palette) self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOn) self.Layout = QVBoxLayout(self.Widget) self.Layout.setAlignment(ALIGNMENT) self.Layout.setSizeConstraint(QLayout.SizeConstraint.SetMinimumSize) self.setWidget(self.Widget) self.setAlignment(ALIGNMENT) self.setFrameShape(QFrame.Shape.Box) self.setFrameShadow(QFrame.Shadow.Raised)
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt class Window(QMainWindow): def __init__(self): super().__init__() frame = self.frameGeometry() center = self.screen().availableGeometry().center() frame.moveCenter(center) self.move(frame.topLeft()) font = Font(10) self.setFont(font) self.setWindowTitle('Careyina') self.setWindowIcon(ICON) self.setStyleSheet(MAINSTYLE) self.centralwidget = QWidget(self) self.vbox = QVBoxLayout(self.centralwidget) grid = QGridLayout() self.leftpane = LeftPane() grid.addWidget(self.leftpane, 0, 0, 100, 75) self.scrollArea = ScrollArea(self.centralwidget) grid.addWidget(self.scrollArea, 0, 75, 100, 25) self.vbox.addLayout(grid) buttonbar = QHBoxLayout() self.import_items = Button('Import Items') self.import_tags = Button('Import Tags') self.add_item = Button('Add Item') self.add_tag = Button('Add Tag') self.sort_btn = Button('Sort') self.print_btn = Button('Print') self.export_btn = Button('Export') for btn in [ self.import_items, self.import_tags, self.add_item, self.add_tag, self.sort_btn, self.print_btn ]: buttonbar.addWidget(btn) buttonbar.addStretch() buttonbar.addWidget(self.export_btn) self.vbox.addLayout(buttonbar) self.setCentralWidget(self.centralwidget)
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt if __name__ == '__main__': app = QApplication([]) ICON = QIcon(DIRECTORY + '/icons/icon.png') ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("Careyina") app.setStyle("Fusion") window = Window() class Manager: items = [] lower_items = [] tags = [] lower_tags = [] tagdict = dict() @staticmethod def additem(): text, ok = QInputDialog.getText( window, "Add Item", "Item:", QLineEdit.EchoMode.Normal, "" ) if ok and text: if text.lower() not in Manager.lower_items: item = QListWidgetItem(text) item.setFlags(item.flags() | FLAG.ItemIsUserCheckable | FLAG.ItemIsEnabled) item.setCheckState(Qt.CheckState.Unchecked) window.leftpane.addItem(item) Manager.items.append(text) Manager.lower_items.append(text.lower()) @staticmethod def addtag(): text, ok = QInputDialog.getText( window, "Add Tag", "Tag:", QLineEdit.EchoMode.Normal, "" ) if ok and text: if text.lower() not in Manager.lower_tags: window.scrollArea.Layout.addWidget(TagGroupBox(text)) Manager.tags.append(text) Manager.lower_tags.append(text.lower()) Manager.tagdict[text] = [] @staticmethod def refresh_left(): window.leftpane.clear() for item in Manager.items: item = QListWidgetItem(item) item.setFlags(item.flags() | FLAG.ItemIsUserCheckable | FLAG.ItemIsEnabled) item.setCheckState(Qt.CheckState.Unchecked) window.leftpane.addItem(item) @staticmethod def refresh_right():
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt @staticmethod def refresh_right(): while window.scrollArea.Layout.count(): item = window.scrollArea.Layout.takeAt(0) delete(item.widget()) delete(item) Manager.tagdict = {tag: sorted(items) for tag, items in sorted(Manager.tagdict.items())} for tag, items in Manager.tagdict.items(): tagbox = TagGroupBox(tag) window.scrollArea.Layout.addWidget(tagbox) for item in items: tagbox.taglist.addItem(QListWidgetItem(item)) tagbox.taglist.autoResize() tagbox.taglist.accepted = set(items) @staticmethod def sortall(): if not (Manager.items and Manager.tags and Manager.tagdict): return Manager.items = sorted(Manager.items) Manager.tags = sorted(Manager.tags) Manager.refresh_left() Manager.refresh_right() @staticmethod def import_items(): text, ok = QInputDialog.getText( window, "Import Items", "Filepath:", QLineEdit.EchoMode.Normal, "" ) if ok and text: if Path(text).is_file(): Manager.items = sorted(Path(text).read_text(encoding='utf8').splitlines()) Manager.lower_items = [i.lower() for i in Manager.items] Manager.refresh_left() @staticmethod def import_tags(): text, ok = QInputDialog.getText( window, "Import Tags", "Filepath:", QLineEdit.EchoMode.Normal, "" ) if ok and text: if Path(text).is_file(): Manager.tags = sorted(Path(text).read_text(encoding='utf8').splitlines())
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt Manager.tags = sorted(Path(text).read_text(encoding='utf8').splitlines()) Manager.lower_tags = [i.lower() for i in Manager.tags] Manager.tagdict = {tag: [] for tag in Manager.tags} Manager.refresh_right() @staticmethod def serialize(): return json.dumps(Manager.tagdict, ensure_ascii=False, indent=4) @staticmethod def print2console(): print(Manager.serialize()) @staticmethod def export(): text, ok = QInputDialog.getText( window, "Export to", "Filepath:", QLineEdit.EchoMode.Normal, "" ) if ok and text: try: Path(text).resolve() Path(text).write_text(Manager.serialize(), encoding='utf8') except OSError: return window.add_item.clicked.connect(Manager.additem) window.add_tag.clicked.connect(Manager.addtag) window.export_btn.clicked.connect(Manager.export) window.import_items.clicked.connect(Manager.import_items) window.import_tags.clicked.connect(Manager.import_tags) window.print_btn.clicked.connect(Manager.print2console) window.sort_btn.clicked.connect(Manager.sortall) window.show() sys.exit(app.exec())
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
python, python-3.x, gui, pyqt Icons: checkbox-checked.png checkbox-unchecked.png icon.png So how is the code? What mistakes did I make? How should I refactor it? What improvements can be made? Answer: Your imports re and collections are unused so delete them. Your replace('\\', '/') should not be necessary. So long as you keep a real Path object and don't coerce it to a string, you should not need to care about OS-specific path separators - this is much of the point of using Path in the first place. Your import * fills your namespace with tonnes of symbols. A cleaner option is to alias like import PyQy6.QtGui as gui and then gui.QFont for instance. MAINSTYLE is a good candidate for moving to a separate text file. Also, rather than positional substitution, consider using named substitution using the built-in template support. Add PEP484 typehints to parameters, such as def __init__(self, text: str) -> None. Name variables and methods in lower_snake_case, such as auto_resize instead of autoResize. event.source().__class__.__name__ == 'LeftPane' is probably not as preferable as calling isinstance. Your for btn in should use an immutable tuple () rather than a mutable list []. It's good that you have a main guard but it isn't enough. All of those symbols still exist in the global namespace. Move that code to a function. Move the Manager class to the global namespace.
{ "domain": "codereview.stackexchange", "id": 43260, "lm_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, gui, pyqt", "url": null }
algorithm, php, programming-challenge, complexity, k-sum Title: Algorithm for twoSum Question: This is my PHP algorithm for the twoSum problem in leetCode: function twoSum($nums, $target) { foreach($nums as $key1 => $num1) { foreach(array_slice($nums, $key1 + 1, null, true) as $key2 => $num2) { if ($num1 + $num2 === $target) { return [$key1, $key2]; } } } } Its purpose is to take an array and check if the sum of two distinct elements can result in the $target. Just like: twoSum([2,7,11,15], 9); // this sould return [0, 1] because 2 + 7 is 9 Initially I created an algorithm that compare the elements in $nums through brute force. Knowing that O(N2) is not that good for time complexity, I tried to refactor it and came up with the solution above. I don't think that the code still with O(N2) time complexity, but I can't think how I could calculate this algorithm in Big O Notation, I would like to know if: Can you clearly explain what is the time complexity of this algorithm and why. The way this code works still is considered brute force. Any other advice is very welcome! Answer: Hopefully it's obvious that the "worst case" runtime will happen when there is no matching pair in $nums.* ** In that situation, every (unordered) pair of numbers in $nums will be tested, so clearly the algorithm is still \$O(n^2)\$. "Brute force" is a subjective term; I would certainly consider this to be a brute-force algorithm. I suspect your first solution was something like this? for i from 0 to len(nums): for j from i+1 to len(nums): check if nums[i]+nums[j] == target
{ "domain": "codereview.stackexchange", "id": 43261, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, php, programming-challenge, complexity, k-sum", "url": null }
algorithm, php, programming-challenge, complexity, k-sum You need to be able to see that your new code is the same algorithm. To get this in sub-quadratic time, you'll need to figure out a way to reliably not do most of the comparisons. I'm not sure what your background is or what your motivation to use PHP was; for what it's worth I don't think PHP is a good tool for problems like this. * By "hopefully it's obvious" I mean "I'm too lazy to prove it". ** In which case what happens? Is return null how you want to handle failure?
{ "domain": "codereview.stackexchange", "id": 43261, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, php, programming-challenge, complexity, k-sum", "url": null }
swift, swiftui Title: SwiftUI/Swift code for changing item values in an immutable struct Question: just wanted someone to review my code and perhaps simplify it a bit. Everything is working as expected for the moment but it seems too much code for what i'm trying to achieve. Especially the function "toggleItems". It just feels ... not right. GOAL: The idea is that i'm having a list with a fixed set of items. When selecting an item, an indicator needs to light up which indicates which list item was pressed last (active state). All other list items need to be deactivated at that point. At first i was using variables in my data model (struct) but wanted to avoid that they could be changed from without the struct so i tried using an immutable struct here (credits to "Swiftful Thinking" on Youtube) SoundModel: struct SoundModel: Identifiable { let id: String let name: String let displayName: String let isActive: Bool init(id: String = UUID().uuidString, name: String, displayName: String, isActive: Bool) { self.id = id self.name = name self.displayName = displayName self.isActive = isActive } func updateActiveStateToFalse() -> SoundModel { return SoundModel(id: id, name: name, displayName: displayName, isActive: false) } func updateActiveStateToTrue() -> SoundModel { return SoundModel(id: id, name: name, displayName: displayName, isActive: true) } }
{ "domain": "codereview.stackexchange", "id": 43262, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, swiftui", "url": null }
swift, swiftui the SoundViewViewModel: class SoundViewViewModel: ObservableObject { @Published var sounds: [SoundModel] = [] init() { sounds.append(contentsOf: [ SoundModel(name: "alarm1", displayName: "Alarm 1", isActive: true), SoundModel(name: "alarm2", displayName: "Alarm 2", isActive: false), SoundModel(name: "alarm3", displayName: "Alarm 3", isActive: false), SoundModel(name: "bird1", displayName: "Bird", isActive: false), SoundModel(name: "carhorn1", displayName: "Carhorn", isActive: false), SoundModel(name: "fireAlarm1", displayName: "Fire Alarm", isActive: false), SoundModel(name: "mellow", displayName: "Mellow", isActive: false), SoundModel(name: "meltdown1", displayName: "Meltdown", isActive: false), SoundModel(name: "schoolbel1", displayName: "Schoolbel", isActive: false), SoundModel(name: "siren1", displayName: "Siren", isActive: false), SoundModel(name: "ufo1", displayName: "Ufo", isActive: false), ] ) } func toggleItems(soundItem: SoundModel) { if let index = sounds.firstIndex(where: { $0.id == soundItem.id } ) { if !soundItem.isActive { sounds[index] = soundItem.updateActiveStateToTrue() } } for sound in sounds { if let index = sounds.firstIndex(where: { $0.id == sound.id && $0.id != soundItem.id }) { if sounds[index].isActive { sounds[index] = sound.updateActiveStateToFalse() } } } } }
{ "domain": "codereview.stackexchange", "id": 43262, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, swiftui", "url": null }
swift, swiftui And my SoundView: struct SoundsView: View { @EnvironmentObject var theme: ThemeManager //var soundManager = SoundManager() @StateObject var soundViewVM = SoundViewViewModel() var body: some View { List { ForEach(soundViewVM.sounds) { sound in Button { //soundManager.playSound(name: sound.name) soundViewVM.toggleItems(soundItem: sound) } label: { HStack(alignment: .center, spacing: 2) { Text(sound.displayName) Spacer() sound.isActive ? Circle().frame(width: 10).foregroundColor(theme.lightColor) : nil } } } } .listStyle(.elliptical) .navigationTitle { HStack { Text("Sounds") Spacer() } } } } Answer: The toggleItems() function can be simplified to func toggleItems(soundItem: SoundModel) { for (index, sound) in sounds.enumerated() { if sound.id == soundItem.id { sounds[index] = sound.updateActiveStateToTrue() } else { sounds[index] = sound.updateActiveStateToFalse() } } } with one simple loop instead of two loops in your code (where the second one is essentially a nested loop). But what I would really do is to store the information about the currently selected sound in the view model, instead of having an isActive property in SoundModel: class SoundViewViewModel: ObservableObject { @Published var sounds: [SoundModel] @Published var activeSoundId : SoundModel.ID? init() { let allSounds = [ ... ] sounds = allSounds activeSoundId = allSounds.first?.id } } Then making a sound “active” becomes as simple as soundViewVM.activeSoundId = sound.id
{ "domain": "codereview.stackexchange", "id": 43262, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, swiftui", "url": null }
swift, swiftui Then making a sound “active” becomes as simple as soundViewVM.activeSoundId = sound.id without the need to traverse the array and updating each entry with a new (active or inactive) one. This makes the toggleItems() method obsolete, and the view code becomes struct SoundsView: View { @StateObject var soundViewVM = SoundViewViewModel() var body: some View { List { ForEach(soundViewVM.sounds) { sound in Button { soundViewVM.activeSoundId = sound.id } label: { HStack(alignment: .center, spacing: 2) { Text(sound.displayName) Spacer() if sound.id == soundViewVM.activeSoundId { Circle().frame(width: 10) } } } } } } } The isActive property and the updateActiveStateToFalse/True() methods in SoundModel are no longer needed. Instead of converting the UUIDs to strings one can use the UUID directly for identification: struct SoundModel: Identifiable { let id: UUID let name: String let displayName: String init(id: UUID = UUID(), name: String, displayName: String, isActive: Bool) { self.id = id self.name = name self.displayName = displayName } }
{ "domain": "codereview.stackexchange", "id": 43262, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, swiftui", "url": null }
php, median Title: Calculate a median Question: I got this as an implementation of "get me the median of those values". But it sort of doesn't feel right (too long, too many branch points) so I thought I'll post it here to see what you think. <?php private function calculateMedian($aValues) { $aToCareAbout = array(); foreach ($aValues as $mValue) { if ($mValue >= 0) { $aToCareAbout[] = $mValue; } } $iCount = count($aToCareAbout); sort($aToCareAbout, SORT_NUMERIC); if ($iCount > 2) { if ($iCount % 2 == 0) { return ($aToCareAbout[floor($iCount / 2) - 1] + $aToCareAbout[floor($iCount / 2)]) / 2; } else { return $aToCareAbout[$iCount / 2]; } } elseif (isset($aToCareAbout[0])) { return $aToCareAbout[0]; } else { return 0; } } Answer: The first part of your function filter out negative values. This has nothing to do with calculating the median itself, so should be moved away from this function. Way I would do it. Create array_median() function in a global scope (or a static method) like this: /** * Adapted from Victor T.'s answer */ function array_median($array) { // perhaps all non numeric values should filtered out of $array here? $iCount = count($array); if ($iCount == 0) { throw new DomainException('Median of an empty array is undefined'); } // if we're down here it must mean $array // has at least 1 item in the array. $middle_index = floor($iCount / 2); sort($array, SORT_NUMERIC); $median = $array[$middle_index]; // assume an odd # of items // Handle the even case by averaging the middle 2 items if ($iCount % 2 == 0) { $median = ($median + $array[$middle_index - 1]) / 2; } return $median; }
{ "domain": "codereview.stackexchange", "id": 43263, "lm_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, median", "url": null }
php, median This way we have generally available all purpose function, with naming consistent with core php functions. And your method would look like /** * The name should probably be changed, to reflect more your business intent. */ private function calculateMedian($aValues) { return array_median( array_filter( $aValues, function($v) {return (is_numeric($v) && $v >= 0);} // You can skip is_numeric() check here, if you know all values in $aValues are actually numeric ) ); } Either within calculateMedian() or in the code that calls it, you should take care of catching the DomainException that can be thrown if the array is empty)
{ "domain": "codereview.stackexchange", "id": 43263, "lm_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, median", "url": null }
python, performance, algorithm, combinatorics Title: Subset Product Algorithm Question: Subset Product is an NP-complete problem and is my favorite problem. So, I've written a slightly smarter way of solving the problem. Will performance impact matter if I use multi-cpus and my GPU? Do my variable names make sense of what I'm doing? Is there a better way to write the for-loop under the variable "max_combo"? The Python Script import itertools from itertools import combinations from functools import reduce from operator import mul from sys import exit # Give TARGET whole number > 0 and give whole number divisors > 0 for D # and see if a combination will have a total product equal to TARGET. TARGET = int(input('enter target product: ' )) D = input('Enter numbers: ').split(',') D = list(set([int(a) for a in D])) # Only divisors are allowed and must be sorted in ascending order for the algorithm to # properly work. D = sorted([i for i in D if TARGET % i==0]) # Using two-sum solution for two-product two_prod_dict = {} for a in range(0, len(D)): if TARGET//int(D[a]) in two_prod_dict: print('YES') exit(0) else: two_prod_dict[int(D[a])] = a if TARGET in D: print('YES') exit(0) # A combination's total product cannot be larger # than the TARGET. So this code section figures out # the biggest combination size. (Doing my best to save running time) max_combo = [] for a in D: max_combo.append(a) if reduce(mul,max_combo) >= TARGET: if reduce(mul,max_combo) > TARGET: max_combo.pop() break else: break This is the purpose of max_combo and in this case len(max_combo) = 5. Suppose TARGET = 120. Some of the divisors for D is 1,2,3,4,5,6,8,10,12. Notice that 5! = 120. (eg. (1,2,3,4,5) = TARGET) So, if you get a combination with six or more numbers it will go over because 6! > TARGET. Remember D is sorted in ascending order for the concept to work and it has no repeating numbers.
{ "domain": "codereview.stackexchange", "id": 43264, "lm_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, algorithm, combinatorics", "url": null }
python, performance, algorithm, combinatorics # Using any other divisor will go over TARGET. # To save running time, do it only one time. # Taking (1,2,3,4,6) will go over so stop at (1,2,3,4,5) (if there is one). # So why waste running time? for X in combinations(D, len(max_combo)): if reduce(mul, X) == TARGET: print('YES') exit(0) else: break # I'm hoping that smaller solutions # are more likely than larger solutions so start # with the smallest and work your way up. for A in range(3, len(max_combo) + 1): for X in combinations(D, A): if reduce(mul, X) == TARGET: print('YES',X) exit(0) print('NO') Answer: Reasons to put code in functions (and classes): Code on module level is evaluated right away: I can't try it out using copy&paste if there is an input() somewhere. you don't need to import sys.exit() Code in a function is documented: def subset_product(target, factors): """ For a natural number target and an iterable of natural number factors, return target equals the product of some of the factors, all or none. """ pass # that's how many a function starts out if __name__ == '__main__': help(subset_product) Do my variable names make sense? There are conventions, not following them for no obvious reason is a distraction or harms readability. target would have been impeccable. Single letter names are useful to indicate a name intended be used in its (very) restricted context, only - iteration variables get single letter names quite often (even _ if the value will not be used). You comment your code: Great, this enables others as well as your later self to get what you've been up to. Caveat: Keep comments up to date. [What is a decent way to code computing an upper limit on the number of factors]?
{ "domain": "codereview.stackexchange", "id": 43264, "lm_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, algorithm, combinatorics", "url": null }
python, performance, algorithm, combinatorics [What is a decent way to code computing an upper limit on the number of factors]? def subset_product(target, factors): """ For a natural number target and an iterable of natural numbered factors, return target equals the product of some of the factors, all or none. A factor may be given more than once. """ if target == 1: return True factors = (int(f) for f in factors) divisors = sorted(d for d in factors if 1 < d and target % d == 0) if not divisors: return False if divisors[-1] == target: return True product = 1 for i, d in enumerate(divisors): product *= d if target <= product: break if target == product: return True max_factors = i … I don't get the idea for "the for X in combinations(D, len(max_combo)) loop" - immediately following it you express hope that smaller solutions are more likely and act the type. allowing target and factors below 1 sure complicates things: def subset_product(target, factors): """ For a whole number target and an iterable of whole factors, return target equals the product of some of the factors, all or none. A factor may be given more than once. """ special_case = special_subset_product(target, factors) # 1: True 0: 0 in factors if special_case is not None: # target in factors, too? return special_case sign = -1 if target < 0 else 1 target *= sign factors = (int(f) * sign for f in factors) divisors = sorted(d for d in factors if d != 0 and d != 1 and target % d == 0) if not divisors: return False if divisors[-1] == target: return True # now *what*?
{ "domain": "codereview.stackexchange", "id": 43264, "lm_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, algorithm, combinatorics", "url": null }
javascript, beginner, programming-challenge, node.js, fizzbuzz Title: FizzBuzz in JavaScript (node.js), my first JavaScript program Question: I had just decided to learn JavaScript, so I wrote this program. I am sure you know what FizzBuzz is so I wouldn't describe it here. Console output: Welcome to Node.js v15.12.0. Type ".help" for more information. > const special = [[15, 'FizzBuzz'], [5, 'Buzz'], [3, 'Fizz']]; undefined > > function fizzbuzz (number) { ... for (let [n, label] of special) { ..... if (number % n == 0) { ....... return label; ....... } ..... } ... return number; ... }; undefined > > for (let i=1; i<=100; i++) { ... console.log(fizzbuzz(i)) ... } 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz 61 62 Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 FizzBuzz 76 77 Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 FizzBuzz 91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz undefined > It is a word for word translation of this Python program I wrote: special = {15: 'FizzBuzz', 5: 'Buzz', 3: 'Fizz'} def fizzbuzz(number): for n, label in special.items(): if not number % n: return label return number for i in range(1, 101): print(fizzbuzz(i)) JavaScript Code const special = [[15, 'FizzBuzz'], [5, 'Buzz'], [3, 'Fizz']]; function fizzbuzz (number) { for (let [n, label] of special) { if (number % n == 0) { return label; } } return number; }; for (let i=1; i<=100; i++) { console.log(fizzbuzz(i)) };
{ "domain": "codereview.stackexchange", "id": 43265, "lm_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, beginner, programming-challenge, node.js, fizzbuzz", "url": null }
javascript, beginner, programming-challenge, node.js, fizzbuzz for (let i=1; i<=100; i++) { console.log(fizzbuzz(i)) }; I don't know much about JavaScript but I am definitely no stranger to programming, I used functions, early returns, arrays and direct iteration in this tiny script I wrote in under 10 minutes. I have tried to use an object but discovered that in JavaScript the order of the key-value pairs is not preserved. So how can it be improved? Answer: A short review; special is not an evocative name, maybe divisors? special is polluting the global namespace, and should be defined within the function fizzbuzz -> fizzBuzz? I like your approach of capturing the data parts into a data structure instead of hard-coded statements. I would have added a comment that 15 is in the first place because it takes priority on 3 and 5 I would have called n divisor instead, and then number could be n It annoys me greatly that this function returns both 'numbers' and 'strings', but not enough that I would fix this in the code, it's JS after all Mandatory rewrite; function fizzBuzz (n) { //Observe that 15 is divisible by 3 and 5, so check 15 first const divisors = [[15, 'FizzBuzz'], [5, 'Buzz'], [3, 'Fizz']]; for (let [divisor, label] of divisors) { if (n % divisor == 0) { return label; } } return n; }; for (let i=1; i<=100; i++) { console.log(fizzBuzz(i)) };
{ "domain": "codereview.stackexchange", "id": 43265, "lm_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, beginner, programming-challenge, node.js, fizzbuzz", "url": null }
c++, classes, windows, role-playing-game Title: ASCII game in console Question: Overall, I want to make a game in console, something Pokemon-like but with typical rpg scenery - swords, magic and all that. I want to make player able to move around the map, find dungeons, fight some monsters (in a round-like maner, like Pokemon but you fight yourself, four moves, being able to escape, potions, etc.), take treasures. I just want to know if I am on a right path. I'll take ratings, suggestions, ideas, everything. Mostly I want to know if I include right files and if this structure of classes is optimal. Everything else is here: https://github.com/supermaciu/ascii-rpg-game-official main.cpp: #include <iostream> #include <windows.h> #include <conio.h> #include <vector> #include <string> #include <sstream> #include <cstdlib> #include <time.h> #include <algorithm> #include "Utilities.h" #include "Game.h" #include "BoardObject.h" #include "Board.h" #include "Player.h" #include "Enemy.h" #include "Teleport.h" // TODO: optimize // TODO: file reader, txt to board setup // FIX: why does it take so much time to compile // TODO: Board function to move a BoardObject to another board // TODO: optimize Board.cpp coloring // IDEA: console window widens on inventory open on the right side / slowly // TODO: threading / doing things while waiting on input int main() { //Init srand(time(NULL)); bool running = true; bool debug_mode = true; //Game / Config Game game; game.setTitle("ascii-rpg-game"); game.setCursorVisibility(false); game.resizeWindow(get_screen_width()*0.85, get_screen_height()*0.8); game.moveWindowCenter(); game.setConsoleBufferSize(0, 0); //game.maxemizeWindow(true); game.resizeableWindow(false); //game.resizeableWindow(true); // not working //game.disableInput(true); Board* board = new Board("board1", 10, 10, &game); game.set_current_board(board); Player* player = new Player(1, 1, board);
{ "domain": "codereview.stackexchange", "id": 43266, "lm_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++, classes, windows, role-playing-game", "url": null }
c++, classes, windows, role-playing-game Player* player = new Player(1, 1, board); //Board 2 Board* board2 = new Board("board2", 15, 5, &game); Board* board3 = new Board("sklep", 8, 8, &game); // TODO: shop template Teleport* t1 = new Teleport(3, 3, board); t1->setDestination(0, 0, board2); Teleport* t2 = new Teleport(3, 3, board2); t2->setDestination(0, 0, board); Teleport* t3 = new Teleport(5, 3, board); t3->setDestination(0, 0, board); Teleport* t4 = new Teleport(1, 8, board); t4->setDestination(0, 0, board3); for (int i = 0; i < board->get_width(); i++) { Void* v = new Void(i, 5, board); } //Input char move; //Initial board draw player->eventsHandler(move); game.showBoard(); while (running) { move = getch(); if (move == -32) { move = getch(); } if (move == 3 || move == 27) { running = false; } else if (move == 9) { if (debug_mode == false) { debug_mode = true; } else { debug_mode = false; } } player->eventsHandler(move); game.showBoard(); //Debug game.debug(debug_mode, player); Sleep(1); } return 0; } Teleport.h: #pragma once #include <string> #include "BoardObject.h" //has to be included -> Teleport is a derived class class Board; class Teleport : public BoardObject { private: unsigned int dest_x = 0; unsigned int dest_y = 0; Board* dest_board = nullptr; bool tp_set = false; bool dynamic = false; public: Teleport(unsigned int x, unsigned int y, Board* board); ~Teleport(); bool is_set() { return tp_set; } void setDestination(unsigned int x2, unsigned int y2, Board* board2, bool dynamic=false); void unsetDestination(); void onTouchEvent(Player* player) override; }; Game.h: #pragma once
{ "domain": "codereview.stackexchange", "id": 43266, "lm_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++, classes, windows, role-playing-game", "url": null }
c++, classes, windows, role-playing-game void onTouchEvent(Player* player) override; }; Game.h: #pragma once #include <string> #include "Utilities.h" class Board; class BoardObject; class Player; class Game { private: std::string game_name; HWND consoleWindow; // console window handle HANDLE handle; // handles changes made to command prompt COORD coord; // coordinates CONSOLE_CURSOR_INFO consoleCursorInfo; // console cursor options std::vector<Board*> boards = {}; Board* current_board = nullptr; public: Game() = default; Game(const std::string& game_name); ~Game(); HANDLE get_handle() { return this->handle; } void setTitle(const std::string& game_name); void setCursorVisibility(bool show_cursor); void resizeWindow(int width, int height); void moveWindow(int x, int y); void moveWindowCenter(); void setConsoleBufferSize(int x, int y); void maxemizeWindow(bool maxemize); void resizeableWindow(bool can_resize); void disableInput(bool disable); Board* get_current_board() { return this->current_board; }; void set_current_board(Board *board); void showBoard(); Board* getBoardByName(const std::string& name); std::vector<Board*> getAllBoards(); std::vector<BoardObject*> getAllBoardObjects(); void addBoard(Board* board) { boards.push_back(board); } void debug(bool debug_mode, Player *player); }; Board.h: #pragma once #include <vector> #include <string> class Game; class BoardObject; class Board { private: Game *game; const int BOARD_LIMIT_MIN = 2; const int BOARD_LIMIT_MAX = 100; std::string name = "nullBoard"; int width; int height;
{ "domain": "codereview.stackexchange", "id": 43266, "lm_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++, classes, windows, role-playing-game", "url": null }
c++, classes, windows, role-playing-game std::string name = "nullBoard"; int width; int height; char board[100][100] = {}; std::vector<BoardObject*> board_objects = {}; public: Board(unsigned int width, unsigned int height, Game* game); Board(const std::string& name, unsigned int width, unsigned int height, Game* game); std::string get_name() { return this->name; } void set_name(std::string name) { this->name = name; } int get_width() { return this->width; } int get_height() { return this->height; } void render(); void draw(); bool hasBoardObjects(); void addToBoard(BoardObject* board_object); void deleteFromBoard(BoardObject* board_object, bool delete_object_in_memory); std::vector<BoardObject*> getBoardObjects(); BoardObject* getBoardObjectById(int id); std::vector<BoardObject*> getBoardObjectsByClassname(std::string classname); BoardObject* getBoardObjectByCoords(int x, int y); friend class Game; }; BoardObject.h: #pragma once #include <string> #include "Game.h" class Board; class Player; class BoardObject { protected: Game *game; unsigned int x; unsigned int y; char c; int color = 0x07; // 0x, 0 -> black, 7 -> console white unsigned int id; static unsigned int ID; std::string classname = "nullBoardObject"; bool moveInto= false; bool interactWith = false; Board* board; public: BoardObject(unsigned int x, unsigned int y, char c, Board* board); std::string get_classname() { return this->classname; } int get_id() { return this->id; } int get_x() { return this->x; } int get_y() { return this->y; } void set_pos(int x, int y); char get_char() { return this->c; } void set_char(char c) { this->c = c; }
{ "domain": "codereview.stackexchange", "id": 43266, "lm_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++, classes, windows, role-playing-game", "url": null }
c++, classes, windows, role-playing-game char get_char() { return this->c; } void set_char(char c) { this->c = c; } int get_color() { return this->color; } void set_color(int color) { this->color = color; } Board* get_board() { return this->board; } void set_board(Board* board) { this->board = board; } bool get_moveInto() { return this->moveInto; } void set_moveInto(bool canMoveInto) { this->moveInto = canMoveInto; } bool get_interactWith() { return this->interactWith; } void set_interactWith(bool canBeInteractedWith) { this->interactWith = canBeInteractedWith; } virtual void onEnterEvent(Player* player) {}; virtual void onTouchEvent(Player* player) {}; friend class Game; friend class Board; }; class Void : public BoardObject { public: Void(unsigned int x, unsigned int y, Board* board); }; Player.h: #pragma once #include <string> #include "BoardObject.h" #include "Board.h" #include "Teleport.h" class Player : public BoardObject { public: char move; int kill_count = 0; Teleport* t1 = nullptr; Teleport* t2 = nullptr; private: int dirx = 0; int diry = 0; int prev_x; int prev_y; char prev_move; public: Player(unsigned int x, unsigned int y, Board* board); //BoardObject functions void set_pos(int x, int y); //Player functions int get_dirx() { return dirx; } int get_diry() { return diry; } int get_prev_x() { return prev_x; } int get_prev_y() { return prev_y; } char get_prev_move() { return prev_move; } bool canMoveInto(int x, int y); bool canMoveInto(BoardObject* bo); void movementHandler(char move); void checkOnEnterEvents(); void checkOnTouchEvents(); void eventsHandler(char move); }; Enemy.h: #pragma once #include <string>
{ "domain": "codereview.stackexchange", "id": 43266, "lm_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++, classes, windows, role-playing-game", "url": null }
c++, classes, windows, role-playing-game Enemy.h: #pragma once #include <string> #include "BoardObject.h" class Board; class Enemy : public BoardObject { public: Enemy(unsigned int x, unsigned int y, Board* board); void onEnterEvent(Player* player) override; }; Answer: Unnecessary use of this-> You almost never have to write this-> in C++. The exception is when you have member function arguments whose names are the same as member variables, like you do in the constructors. There are two ways around this: Use a different name for the member function argument, like appending a _. Use member initializer lists. An example of the latter would be: Board::Board(unsigned int width, unsigned int height, Game* game): width(std::clamp(width, BOARD_LIMIT_MIN, BOARD_LIMIT_MAX)), height(std::clamp(height, BOARD_LIMIT_MIN, BOARD_LIMIT_MAX)), game(game) { game->addBoard(this); } Avoid manual memory management Avoid calling new and delete where possible, and let containers manage their memory, or use smart pointers like std::unique_ptr. Manual memory management often ends with memory leaks. For example, the Boards allocated in main() are never deleted. Also, you didn't write a destructor for class Board, so if a Board is deleted abut still had some items in board_objects, those items will have leaked as well. For board_objects, since you only know the base type, you can use std::unique_ptr like so: std::vector<std::unique_ptr<BoardObject>> board_objects;
{ "domain": "codereview.stackexchange", "id": 43266, "lm_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++, classes, windows, role-playing-game", "url": null }
c++, classes, windows, role-playing-game In addToBoard() you would only need to replace push_back() with emplace_back(). And you can remove the delete statement from deleteFromBoard(). However, that still requires you to new an object before calling addToBoard(). You could have addToBoard() take a std::unique_ptr<BoardObject> as an r-value parameter, create new objects using std::make_unique<DerivedObject> and then std::move() them around, but that's also cumbersome. Let's revisit this: Don't let objects manage their own storage I would avoid having objects derived from BoardObject add themselves to a Board. If a Board is going to own the objects, let the Board add them to itself. However, I can see that you don't want to have to write two lines of code every time, like so: Enemy *enemy = new Enemy(x, y); board->addToBoard(enemy); Although you could make a oneliner out of it: board->addToBoard(new Enemy(x, y)); But as said before, thisd way you are still allocating a derived object manually. Wouldn't it be nice if you could let addToBoard() create an object of the right type for you? You can do that if you make it a template, like so: template <typename T, typename... Args> void addToBoard(Args&&... args) { board_objects.push_back( // Add to board_objects a std::make_unique<T>( // new unique object of type T and std::forward<Args>(args...) // forward args to its constructor ) ); } If you're not used to templates, this might look a bit complicated, but the benefit of this is that the code using it will be much simpler to write. For example, to add an enemy to the board, now you just have to write: board->addToBoard<Enemy>(x, y); If you need a pointer to the object you just added, you can modify addToBoard() to return a pointer to the object you just pushed to the vector: template <typename T, typename... Args> T* addToBoard(Args&&... args) { ... return board_objects.back().get(); }
{ "domain": "codereview.stackexchange", "id": 43266, "lm_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++, classes, windows, role-playing-game", "url": null }