text
stringlengths
1
2.12k
source
dict
c, error-handling, file-system Should the functions log errors? Or conventionally is this a job for the caller? It really depends on whether you want these functions to be part of a generic library, or if they are just private convenience functions. In the former case, I would leave the logging to the caller, and ensure an error code is returned (or possibly errno could be used as you suggested yourself). If the latter, then always logging an error might be exactly what you want, and then leaving it in these functions will make the rest of your code simpler. Should Read() or Write() or both retry until either an error occurs or all bytes are written? It seems either this will result in inconsistency or duplicate code. When would the extra complexity be worth the more graceful error handling? You should never assume that all bytes will be read or written in one go, so if the idea of these functions is that they read/write a whole file in one go, then you must handle this. Which system calls (if any) should I retry if errno == EINTR? I feel this is a slippery slope, if I do it here, I will feel obliged to do it with every system call for consistency, increasing complexity and requiring modifying older code. That's true. Again, I would say it depends. If you don't plan on using signals in any way in your code, you can probably treat EINTR as an error. If you want to have code that works in all scenarios and want it to handle any recoverable error, then you should handle the possibility of EINTR for all function calls, however tedious. How can I avoid duplicate code if the logic for the functions is almost identical except for one calling read and the other calling write?
{ "domain": "codereview.stackexchange", "id": 43018, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, error-handling, file-system", "url": null }
c, error-handling, file-system You could write a generic function that takes parameters that tell it whether to read or write, and then implement Read() and Write() as two small wrapper functions that call the generic function. However, consider that Read() takes a non-const pointer to the buffer to read the file into, but Write() takes a const pointer. If you want to make a generic function, you can't just have one Ptr parameter without requiring const-casting, which isn't great. Code style The code style you are using is very atypical. Normally, one would not start variable and function names with capitals. It is also very dense, using assignments inside if-statements, and using the comma operator seemingly just to avoid a few braces. goto statements are frowned upon, and while there is some precedence to use them for handling error cases, having a goto jump back into the middle of an if-statement is a terrible practice. Also avoid using one-letter variable names, unless it is something that is idiomatic, like i for a loop counter, or x/y/z for coordinates. Don't reuse variables for different purposes In both functions, File is an input parameter that holds the filedescriptor of a directory (not file!). However, you then reuse it to hold the filedescriptor of the file you opened. This is confusing for someone that reads your code, and might result in problems if someone wants to add another openat() call in the same function. Just use a separate variable to hold the filedescriptor of the opened file. Also note that compilers will typically do lifetime analysis of variables, and will be able to spot that they can use the same register for both variables. Inconsistencies Why are you using pread() inside Read() but the regular write() inside Write()? If you put write() in a loop to handle the case where it doesn't write everything in one go, why not do the same for read() or pread(), which have the exact same issue? Check errno for recoverable errors
{ "domain": "codereview.stackexchange", "id": 43018, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, error-handling, file-system", "url": null }
c, error-handling, file-system Check errno for recoverable errors A call to read() or write() might return -1 in case of an error, but not all errors are equal. In particular, -1 can be returned in case nothing was wrong with the file, but the system call was interrupted somehow. In that case, EINTR is returned, and you should continue trying to read/write in that case instead of returning an error. Return value A bool return type suggests that the return value indicates success or failure, and usually true means success. However, you return 1 or true when there is an error. I strongly recommend you return false in case of errors, and also avoid returning 1 or sizes cast to bool. Pointer arithmetic Pointer arithmetic on void pointers is illegal in C. You should first create a new char * variable and assign the value of the void pointer to it, then perform arithmetic on the new variable. Does the caller really know the size of a file up front? Your Read() function tries to read exactly Size bytes from the file, regardless of the actual size of the file. It is quite rare that you know in advance what the size of a file is. The caller could of course first do an fstatat() call, but then you have a possible TOCTTOU issue. If the actual use case is just: "please read this whole file into a buffer", then it would be better to have Read() take care of getting the file size by using fstat() after opening the file, and then allocating a large enough buffer, reading the file into it, and returning the buffer and its size to the caller. Possible rewrite Here is how I would rewrite Write(): bool write_buffer(int dirfd, const char *const restrict pathname, const void *restrict buf, size_t count) { int fd = openat(dirfd, pathname, O_WRONLY | O_CREAT | O_TRUNC);
{ "domain": "codereview.stackexchange", "id": 43018, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, error-handling, file-system", "url": null }
c, error-handling, file-system if (fd == -1) { warn("Could not open %s", pathname); return false; } unsigned char *ptr = buf; while (count) { ssize_t result = write(fd, ptr, count); if (result == -1) { if (errno == EINTR) { continue; } else { warn("Error writing from %s", pathname); close(fd); return false; } } ptr += result; count -= result; } if (close(fd) == -1) { warn("Error closing %s", pathname); return false; } return true; } I used warn() here as you can put a bit more information in the error message that way, and differentiate between the error happening during opening, writing or closing the file. The names of the function parameters were chosen to be the same as those for openat() and write(), so it is more familiar for those who already know those POSIX functions. And yes, the code is a lot longer, but a lot is just whitespace, and code length is not directly related to binary size or performance. It is much more important that it is readable, correct and maintainable. There is code duplication in the error handling, but every case is slightly different here; you can't close() if openat() failed, you have to print the error message before calling close() if write() failed, and again you probably can't close() again if close() failed (unless errno == EINTR again, which I didn't handle in my example).
{ "domain": "codereview.stackexchange", "id": 43018, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, error-handling, file-system", "url": null }
beginner, haskell, functional-programming Title: Validate Finnish IBANs Question: I am currently studying an online course in Haskell and there are no "model examples" of the assignments after finishing them. I'm slowly getting the hang of this, but I'd like some feedback on how could I have written this differently. This piece of code took me a lot of hours to finish, but it works now! I am especially curious whether I could've done the replace' function in a better way! The assignment was as follows: Write a function validate :: String -> Bool that, given a string validates the string as a Finnish IBAN code. The Wikipedia article explains the validation rules. And some additional rules for Finland: The length of a Finnish IBAN code is 18 Finnish IBAN begins with the country code FI. All the characters after the country code are digits. validate :: String -> Bool moveCharsToEnd :: String -> String isDigit :: Char -> Bool onlyDigits :: String -> Bool replace' :: String -> String --Replaces the country code FI with 1518 at the beginning of the string. replace' xs | x <- xs = '1':'5':'1':'8' : drop 2 xs isDigit c = c >= '0' && c <= '9' --Takes the first 6 (4) characters and puts them to end of the string. --6 because I have converted FI to 1518, so that's two additional chars. moveCharsToEnd x | x <- x = drop 6 x ++ take 6 x --Checks whether given list consists only of digits. onlyDigits [] = False onlyDigits [s] = isDigit s onlyDigits (x:xs) | isDigit x = onlyDigits xs | otherwise = False --Validates the IBAN according to rules. validate x | y <- x, length y == 18, (y !! 0 == 'F' && y !! 1 == 'I'), onlyDigits (tail (tail y)), ((read (moveCharsToEnd(replace' y)) :: Integer) `mod` 97 == 1) = True | otherwise = False
{ "domain": "codereview.stackexchange", "id": 43019, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, haskell, functional-programming", "url": null }
beginner, haskell, functional-programming Answer: Since you're using Haskell, I'm guessing you want the compiler to be picky with you. using the -Wall flag is a good idea; there's some discussion about how to take this even farther here. It's normal to put type declarations with their corresponding definitions. I see the intuition of having them all at the top, but it's not the convention. Using -Wall points out that in replace' and moveCharsToEnd, you've bound unused variables, but I think the problem is slightly deeper than that. Why are there pattern guards there at all? Neither of them are doing anything. Import the isDigit function from Data.Char. It's in base, so you're not adding a dependency by doing this. onlyDigits = all isDigit is clear enough that it no longer needs a comment explaining what it does. all is from Prelude. In validate, pattern-matching y <- x is pointless; it can't fail and there's no reason not to use the already bound x. (Even if you did just want to bind a new variable, use a where or let clause for that.) There are a couple places where splitAt can help you break up the string into it's semantic chunks. I don't think there's a way for your use of read to crash the program as it's written now, but I would still suggest against doing that. If that were to fail you'd get a runtime exception instead of False, which is bad!. There are a few ways you can rewrite that clause using readMaybe; I'll show how I imagine you might do it. Chaining together a bunch of boolean guards with , isn't something I've seen before. I would suggest negating them all, mapping each to False separately, and then have | otherwise = True. All that gets us this far: import Data.Char (isDigit) import Text.Read (readMaybe) --Replaces the country code FI with 1518 at the beginning of the string. replace' :: String -> String replace' xs = '1':'5':'1':'8' : drop 2 xs
{ "domain": "codereview.stackexchange", "id": 43019, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, haskell, functional-programming", "url": null }
beginner, haskell, functional-programming --Takes the first 6 (4) characters and puts them to end of the string. --6 because I have converted FI to 1518, so that's two additional chars. moveCharsToEnd :: String -> String moveCharsToEnd x = let (prefix, rest) = splitAt 6 x in rest ++ prefix onlyDigits :: String -> Bool onlyDigits = all isDigit --Validates the IBAN according to rules. validate :: String -> Bool validate x | length x /= 18 = False | country /= "FI" = False | not (onlyDigits digits) = False | Just i <- asMInt, i `mod` 97 /= 1 = False | Nothing <- asMInt = False | otherwise = True where (country, digits) = splitAt 2 x asMInt = readMaybe (moveCharsToEnd(replace' x)) :: Maybe Integer This is basically the same as what you wrote, give or take some tiny performance differences. That said, this doesn't seem like a case to be worrying about performance at all; worry about clarity and maintainability. In other words, make sure your code mirrors the validation instructions exactly, and make it modular if possible. You have a lot of logic that's specific to the case of Finland; I suggest writing a completely agnostic base validation, and then layering the Finland stuff on top. This is quite different from what you wrote, sorry, I'm just procrastinating on my own homework: import Data.Char (toUpper) import qualified Data.Ix as Index import Text.Read (readMaybe) type CountryCode = String -- should probably be a newtype! finland_CCode :: CountryCode finland_CCode = "FI" countryLengths :: [(CountryCode, Int)] -- I don't think base has a hashmap. countryLengths = [(finland_CCode, 18)] alpha_R :: (Char, Char) -- range definitions alpha_R = ('A', 'Z') -- assume uppercase most places; coerce at the begining. num_R :: (Char, Char) -- range definitions num_R = ('0', '9')
{ "domain": "codereview.stackexchange", "id": 43019, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, haskell, functional-programming", "url": null }
beginner, haskell, functional-programming isAlphaNum :: Char -> Bool -- this is stricter than Data.Char.IsAlphaNum isAlphaNum c = Index.inRange alpha_R c || Index.inRange num_R c ibanIntRepresentation :: String -> Maybe Integer ibanIntRepresentation iban = (concat <$> (asDigits `mapM` rearranged)) >>= readMaybe where (prefix, rest) = splitAt 4 iban rearranged = rest ++ prefix asDigits :: Char -> Maybe [Char] asDigits c | Index.inRange num_R c = Just [c] | Index.inRange alpha_R c = Just $ show $ 10 + (Index.index alpha_R c) | otherwise = Nothing -- https://en.wikipedia.org/wiki/International_Bank_Account_Number#Validating_the_IBAN. validateIBANBase :: String -> Bool validateIBANBase iban | maybe False (length uppercase /=) countryLength = False | not (all isAlphaNum uppercase) = False | maybe False (not . checkMod) (ibanIntRepresentation uppercase) = False | otherwise = True where uppercase = toUpper <$> iban countryCode = take 2 uppercase countryLength = lookup countryCode countryLengths checkMod i = i `mod` 97 == 1 -- Specifically validates a Finnish IBAN. validate :: String -> Bool validate iban | not (validateIBANBase iban) = False | country /= finland_CCode = False | not (all (Index.inRange num_R) digits) = False | otherwise = True where uppercase = toUpper <$> iban (country, digits) = splitAt 2 uppercase As a final note, wikipedia says there's additional check-digit logic for Finland, but this is outside my expertise.
{ "domain": "codereview.stackexchange", "id": 43019, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, haskell, functional-programming", "url": null }
python, performance, python-3.x, parsing, logging Title: Python script to analyse Apache log files Question: I am fairly new to Python programming language. Most of python programmers have heard the philosophy behind the python programming language. The code should be easy to read, easy to understand, simple, fast. I would like to this post to guide users on how to make codes more 'Pythonic' from examples of my script. I have recently developed a script, to parse Apache log files, and calculate (analyse) it by showing the IP counts, Status counts, amount of bytes transferred. The user can choose the output he wants to get. As I was reading my code, I realised, that it's very large, and could be optimised. I want to mention that I am not an experienced code writer either, so it obviously does have some flaws in it. Saying that it 'works' so it's 'OK' is kind of interfering with the philosophy itself. That's where my question derives from: How do I make it more 'Pythonic', more simple, more easy to read? #!/usr/bin/env python import os import sys if __name__ == '__main__': filename = sys.argv[1] try: with open(filename, 'r') as logfile: ip = [] bytes = [] status = [] for line in logfile: split = line.split() ip.append(split[0]) bytes.append(split[9]) status.append(split[8]) except OSError: print(filename, 'not existing') exit() except IndexError: print(filename, 'format not in CLF') exit() ip_list = [] status_list = [] ip_count = [] status_count = [] sort = int( input('Do you want to sort results by ip[1] or status[2]? [ANSWER]: ')) if sort == 1: for match in (ip): if match not in ip_list: ip_list.append(match) if sort == 2: for match in (status): if match not in status_list: status_list.append(match)
{ "domain": "codereview.stackexchange", "id": 43020, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, parsing, logging", "url": null }
python, performance, python-3.x, parsing, logging desired_output = int(input( 'Choose Desired Output: [count] -o- [percentage] -o- [bytes]: ')) if sort == 1: for match in ip_list: count = 0 for ip_match in ip: if match == ip_match: count += 1 ip_count.append(count) if desired_output == 1: ip_count, ip_list = zip( *sorted(zip(ip_count, ip_list), reverse=True)) for i in range(len(ip_list)): print('IP: ' + str(ip_list[i]) + ' count: ' + str(ip_count[i])) if desired_output == 2: ip_count, ip_list = zip( *sorted(zip(ip_count, ip_list), reverse=True)) for i in range(len(ip_list)): print('IP: ' + str(ip_list[i]) + ' percentage: ' + str(round(ip_count[i]/len(ip)*100, 2)) + '%') if desired_output == 3: cnt_bytes = [] for v in range(len(ip_list)): tmp = 0 for k in range(len(ip)): if ip_list[v] == ip[k]: if bytes[k] == '-': bytes[k] = 0 tmp += int(bytes[k]) cnt_bytes.append(tmp) ip_list, cnt_bytes = zip( *sorted(zip(cnt_bytes, ip_list), reverse=True)) for line in range(len(ip_list)): print('IP: ' + str(ip_list[line]) + 'bytes: ' + str(cnt_bytes[line])) if sort == 2: for match in status_list: count = 0 for status_match in status: if match == status_match: count += 1 status_count.append(count)
{ "domain": "codereview.stackexchange", "id": 43020, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, parsing, logging", "url": null }
python, performance, python-3.x, parsing, logging if desired_output == 1: status_count, status_list = zip( *sorted(zip(status_count, status_list), reverse=True)) for i in range(len(status_list)): print('Status: ' + str(status_list[i]) + ' count: ' + str(status_count[i])) if desired_output == 2: status_count, status_list = zip( *sorted(zip(status_count, status_list), reverse=True)) for i in range(len(status_list)): print('Status: ' + str(status_list[i]) + ' percentage: ' + str(round(status_count[i]/len(status)*100, 2)) + '%') if desired_output == 3: cnt_bytes = [] for v in range(len(status_list)): tmp = 0 for k in range(len(status)): if status_list[v] == status[k]: if bytes[k] == '-': bytes[k] = 0 tmp += int(bytes[k]) cnt_bytes.append(tmp) cnt_bytes, status_list = zip( *sorted(zip(cnt_bytes, status_list), reverse=True)) for line in range(len(status_list)): print('Status: ' + str(status_list[line]) + 'bytes: ' + str(cnt_bytes[line]))
{ "domain": "codereview.stackexchange", "id": 43020, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, parsing, logging", "url": null }
python, performance, python-3.x, parsing, logging Example log file: 74.125.176.81 - - [17/May/2015:11:05:28 +0000] "GET /?flav=rss20 HTTP/1.1" 200 29941 "-" "FeedBurner/1.0 (http://www.FeedBurner.com)" 66.249.73.135 - - [17/May/2015:11:05:14 +0000] "GET /blog/geekery/xdotool-2.20110530.html HTTP/1.1" 200 11936 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" 187.45.193.158 - - [17/May/2015:11:05:54 +0000] "GET /presentations/logstash-1/file/about-me/tequila-face.jpg HTTP/1.1" 200 196054 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 2.0.50727; InfoPath.1)"
{ "domain": "codereview.stackexchange", "id": 43020, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, parsing, logging", "url": null }
python, performance, python-3.x, parsing, logging Answer: If code is repetitive, you probably need some functions and better data organization. The current code is very repetitive: multiple versions of nearly-but-not-quite identical code to handle the different ways of sorting and aggregating the information. The solution is such cases usually involves some combination of (1) figuring out a way to generalize the needed behavior in one or more functions; and (2) organizing the program's information more effectively into collections of meaningful objects. Parse log lines into meaningful objects, not into three parallel lists. Currently, you extract three pieces of information from each line (IP address, N of bytes, and HTTP status code) and store that information in separate lists. This is a fateful step because it pushes you in a direction where each user choice about sorting and aggregating requires slightly different code. A more flexible approach is to convert the raw data (a collection of log lines) into meaningful data (a collection of objects holding the facts you care about from each line). Here's one way to approach it. The mindset here is to focus each function or class on a very small part of the problem: LogEntry to hold facts about one log line; main to deal with user inputs/outputs and overall program orchestration; parse_log_file to read the log file; and parse_log_line to convert a single line to a LogEntry. import sys from dataclasses import dataclass @dataclass(frozen = True) class LogEntry: ip_address : str n_bytes : int status_code : int def main(args): file_path = args[0] entries = parse_log_file(file_path) for e in entries: print(e) def parse_log_file(file_path): try: with open(file_path) as log_file: return [parse_log_line(line) for line in log_file] except OSError: abort(f'File not found: {file_path}')
{ "domain": "codereview.stackexchange", "id": 43020, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, parsing, logging", "url": null }
python, performance, python-3.x, parsing, logging def parse_log_line(line): try: xs = line.split() return LogEntry(xs[0], int(xs[9]), int(xs[8])) except IndexError: abort(f'Invalid log file format: {file_path}') def abort(msg): print(msg, file = sys.stderr) exit(1) if __name__ == '__main__': main(sys.argv[1:]) If you need to count things, consider using a Counter. Your current approach to counting things is extremely complex -- to such a degree that I lacked the patience to figure out entirely what you are trying to do. To keep things focused here, I'll assume the following simplified scenario: we want to parse the log lines and output either counts or percentages for any of the three LogEntry attributes. Embrace command-line arguments fully. You're already taking the file path on the command line. Do the same for sorting and aggregation method. Get those values from the command line, typically by using the argparse library. It's the most common strategy for scripts like this. Our argument parser needs a file path, the LogEntry field to be aggregated, and a flag to request percentages rather than counts. Here's how we could do that: import argparse def main(args): opts = parse_args(args) entries = parse_log_file(opts.file_path) n_entries = len(entries) tally = Counter(getattr(e, opts.field) for e in entries) for k, n in tally.items(): pct = n / n_entries print(k, pct if opts.percent else n) def parse_args(args): # Command-line usage: FILE_PATH FIELD [--percent] ap = argparse.ArgumentParser() ap.add_argument('file_path') ap.add_argument('field', choices = ('ip_address', 'n_bytes', 'status_code')) ap.add_argument('--percent', action = 'store_true') return ap.parse_args(args) The code shown above does not do exactly what you need. But it does provide a better foundation upon which you could build this kind of log aggregating script.
{ "domain": "codereview.stackexchange", "id": 43020, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, parsing, logging", "url": null }
java, beginner Title: Simple Console Banking System Java Question: This is a code that I just wrote is a simple application of a banking system I would like you all to review it all tell me where could I improve it, please feel free to critique it, but be aware that I'm still a beginner in this :D, please help to learn new things and also I would like to know some other mini-project to learn something so if you have something in mind it would be nice if you tell me. This is the main file of my code. Bank.Java import java.io.EOFException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Scanner; public class Bank { static private HashMap<String, User> userAccounts = new HashMap<>(); static private User User; static private Scanner in = new Scanner(System.in); static private boolean exit = false; public static void main(String[] args) throws IOException, ClassNotFoundException { //Reading the current value-key pair of the hash map to be ready to overwrite with some new changes try { FileInputStream fis = new FileInputStream("Accounts.dat"); ObjectInputStream ois = new ObjectInputStream(fis); userAccounts = (HashMap<String, User>) ois.readObject(); ois.close(); } catch (EOFException e) { System.out.println("No existing accounts please create one."); System.out.println(); } //Showing all the Hash Map for developing purposes only for (String userName : userAccounts.keySet()) { String key = userName; String value = userAccounts.get(userName).toString(); System.out.println(key + " " + value); }
{ "domain": "codereview.stackexchange", "id": 43021, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
java, beginner /////////////////////////////////////////////////////////////////////////////////////////////////// // First set of options // Log in Menu System.out.println("\t\tWelome to my Bank System"); System.out.println(); System.out.println("1: To open existing account.\t2: To create new account."); menuInput(1); /////////////////////////////////////////////////////////////////////////////////////////////////// // Second set of options // Main Menu // Printed until exit while ( !exit ) { System.out.println(); System.out.println("Chose an action of the folowing options."); System.out.println(); System.out.println("A: Display Account Infrmation.\tB: Deposit.\n" + "C: Withdraw.\t\t\tD: Check Balance.\n" + "E: Change Password.\t\tF: Delete Account.\n" + "G: Exit."); menuInput(2); } in.close(); }
{ "domain": "codereview.stackexchange", "id": 43021, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
java, beginner //Handling the input for the menu static public void menuInput(int set) throws IOException { //Input for the first set of options if ( set == 1 ) { int choice; try { System.out.print("Enter: "); if ( in.hasNextInt() ) { choice = in.nextInt(); if( choice == 1 ) { openAccount(); } else if( choice == 2 ) { createAccount(); } else { System.out.println(); System.out.println("Please enter a valid option."); in.nextLine(); menuInput(1); } } else if( in.hasNextLine() ) { System.out.println(); System.out.println("Please enter a valid option."); in.nextLine(); menuInput(1); } } catch (InputMismatchException e) { e.printStackTrace(); System.out.println(); System.out.println("Please enter a valid option."); menuInput(1); } //Input for the second set of options } else if ( set == 2 ) { String choice; try { System.out.print("Enter: "); choice = in.next(); choice = choice.toUpperCase(); switch (choice) { case "A": User.displayInfo(); saveHashMap(userAccounts); break; case "B": System.out.println(); System.out.print("Please enter any amount to deposit: "); double deposit = in.nextDouble();
{ "domain": "codereview.stackexchange", "id": 43021, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
java, beginner double deposit = in.nextDouble(); User.deposit(deposit); saveHashMap(userAccounts); break; case "C": System.out.println(); System.out.print("Please enter any amount to withdraw: "); double withdraw = in.nextDouble(); User.withdraw(withdraw); saveHashMap(userAccounts); break; case "D": User.checkBalance(); saveHashMap(userAccounts); break; case "E": System.out.println(); System.out.println("To change the password please enter the current password."); in.nextLine(); boolean correctPassword = validatePassword(User.getUserName(),0); System.out.println(); System.out.println("Please enter the new password: "); String newPassword = in.nextLine(); User.changePassword(correctPassword, newPassword); saveHashMap(userAccounts); break; case "F": deleteAccount(); break; case "G": exit = true; break; default: System.out.println(); System.out.println("Plase chose a valid option."); break; } } catch( InputMismatchException e ) { //e.printStackTrace(); System.out.println(); System.out.println("Please enter a valid option."); menuInput(2); } } }
{ "domain": "codereview.stackexchange", "id": 43021, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
java, beginner //Ask for a specific account-User object in the already updated HashMap static public void openAccount() { times++; System.out.println(); System.out.print("Please enter the user name of the account: "); if( times <= 1 ) { in.nextLine(); } String userName = in.nextLine(); if ( !(userAccounts.get(userName) == null) ) { boolean correctPassword = validatePassword(userName,0); if( correctPassword ) { User user = userAccounts.get(userName); //Set the new User object to a global object to be ready to take action in the account User = user; } else { User user = userAccounts.get(userName); User = user; } } else { System.out.println(); System.out.println("Please enter an existing account."); openAccount(); } } static int times = 0; //Creates a new account-User object and update the file and HashMap with the new account static public boolean createAccount() throws IOException { times++; System.out.println(); System.out.print("Enter a new user name for the account: "); if( times <= 1 ) { in.nextLine(); } String userName = in.nextLine(); //Checks for an existing account if( !(userAccounts.get(userName) == null) ) { System.out.println(); System.out.println("This user name already exists."); createAccount(); return false; } System.out.println(); System.out.print("Enter a new password for the account: "); String password = in.nextLine(); System.out.println(); //Creates the account-User object and updates the HashMap User user = new User(userName, password); userAccounts.put(user.getUserName(),user);
{ "domain": "codereview.stackexchange", "id": 43021, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
java, beginner //Set the new User object to a global object to be ready to take action in the account User = user; saveHashMap(userAccounts); return true; } //Deletes an account-User object from the file and HashMap static public void deleteAccount() throws IOException { System.out.println(); System.out.println("Please enter password to delete account."); in.nextLine(); boolean correctPassword = validatePassword(User.getUserName(),0); if( correctPassword ) { userAccounts.remove(User.getUserName()); saveHashMap(userAccounts); System.out.println(); System.out.println("You have successfuly deleted this account: " + User.getUserName() + "."); System.exit(0); } }
{ "domain": "codereview.stackexchange", "id": 43021, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
java, beginner static public boolean validatePassword(String userName, int tries) { User user = userAccounts.get(userName); tries++; //System.out.println(user.getPassword()); if ( tries == 1 ) { System.out.println(); System.out.print("Please enter the password: "); String password = in.nextLine(); if ( password.equals(user.getPassword()) ) { return true; } else { System.out.println(); System.out.println("Incorrect password."); validatePassword(userName,tries); } } else if ( tries == 2 ) { System.out.println(); System.out.print("Please enter the correct password: "); String password = in.nextLine(); if ( password.equals(user.getPassword()) ) { return true; } else { System.out.println(); System.out.println("Incorrect password."); validatePassword(userName,tries); } } else if ( tries == 3 ) { System.out.println(); System.out.print("Please enter the correct password: "); String password = in.nextLine(); if ( password.equals(user.getPassword()) ) { return true; } else { System.out.println(); System.out.println("Incorrect password."); validatePassword(userName,tries); } } else if ( tries == 4 ) { System.out.println(); System.out.println("You have used your 3 tries the app is going to exit."); System.exit(0); } return false; } static public void saveHashMap(HashMap<String, User> userAccounts) throws IOException { FileOutputStream fos = new FileOutputStream("Accounts.dat"); ObjectOutputStream oos = new ObjectOutputStream(fos); //Saves the HashMap to a file oos.writeObject(userAccounts); oos.close(); } }
{ "domain": "codereview.stackexchange", "id": 43021, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
java, beginner } This is another file that the main file uses. User.java import java.io.Serializable; public class User implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String userName; public String password; private double balance; private double lastTransaction; private char transaction; User (String userName, String password){ this.userName = userName; this.password = password; } public String getUserName() { return userName; } public String getPassword() { return password; } public double getBalance() { return balance; } //Updates-increases the variable balance according to the input from the user public void deposit( double deposit ) { balance += deposit; lastTransaction = deposit; transaction = 'D'; System.out.println(); System.out.printf("You have successfully deposit $%,.2f%n" , deposit); } //Updates-decreases the variable balance according to the input from the user public void withdraw(double withdraw) { balance -= withdraw; lastTransaction = withdraw; transaction = 'W'; System.out.println(); System.out.printf("You have successfully withdrawn $%,.2f%n" , withdraw); } //Displays the current balance of the user public void checkBalance() { System.out.println(); System.out.printf("Current Balance: $%,.2f%n" , balance); } //Displays all the info from the user public void displayInfo() { System.out.println(); System.out.println("User Name: " + userName); System.out.println("Password: " + password); if ( transaction == 'D' ) { System.out.printf("Last Transaction: Deposit, Amount: $%,.2f%n" , lastTransaction); } else if ( transaction == 'W' ) { System.out.printf("Last Transaction: Withdraw, Amount: $%,.2f%n" , lastTransaction); } }
{ "domain": "codereview.stackexchange", "id": 43021, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
java, beginner //Change the current password of the user public void changePassword (boolean correctPassword, String newPassword) { if( correctPassword ) { password = newPassword; } } } There is another file that the main class creates. Accounts.dat this file stores all the objects of the user class. This is my first time posting here so if there is something I'm missing please tell me and feel free to ask for any other information. Thank you very much! :D
{ "domain": "codereview.stackexchange", "id": 43021, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
java, beginner Answer: Certainly overlapping with Maarten's feedback: Don't keep all of your Bank members as statics. You should have an actual instance. Separate Bank from a text user interface class so that the logic and UI work are decoupled. Don't explicitly ois.close - instead use a try-with-resources. Destroy Showing all the Hash Map for developing purposes only with prejudice. This kind of code should never exist in an application, and instead if you're curious about the contents of the database, debug your application and look at the contents of memory. Having an "input set" indicated by an integer 1 or 2 is awkward; instead just write these as separate sections in a menu loop. Why have input numbers in the first section and input letters later? Better to be consistent. There's not really a need to in.close; that's stdin and programs nearly always leave that as-is. Consider writing a utility function that calls one of a given array of functions based on the user's input choice. With a variadic array of Runnable this is made quite easy. Don't saveHashMap after displayInfo, since nothing has changed. Rather than printf("$%,.2f%n"), use Java's own locale currency formatting. You don't nextLine() in the right places - it should be done directly after every nextDouble(). Your times variable, as it's currently written, needs to go away. Never plaintext-accept a password on the terminal. Java (and basically all other programming languages) have a facility to mask password input on the terminal. Your validatePassword needs to use a loop instead of copy-pasta-pasta-pasta. Exiting after three incorrect password attempts is almost certainly not what you want to do. Think about an attacker who walks up to a kiosk, types in a user and three junk passwords to easily terminate the application. Instead, there should be an anti-brute-force sleep() hang and then a return to the main menu.
{ "domain": "codereview.stackexchange", "id": 43021, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
java, beginner In all but the construction context, you can hold onto a map reference of weakened type Map rather than HashMap - there's only one place you need to specify the implementation flavour, and that's when you first make the empty map. Never - not for learning, development, hobby or prototyping purposes - store a password unhashed and unsalted. This is easy to get wrong, and is a whole field of study unto itself; but even a simplistic call to the Java built-in HMAC support is better than nothing. Suggested Bank.java package com.stackexchange.bank;
{ "domain": "codereview.stackexchange", "id": 43021, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
java, beginner import java.io.*; import java.util.HashMap; import java.util.Map; public class Bank { private final String filename; private final Map<String, User> userAccounts; public Bank() throws IOException, ClassNotFoundException { this("Accounts.dat"); } public Bank(String filename) throws IOException, ClassNotFoundException { this.filename = filename; Map<String, User> diskAccounts; try ( FileInputStream fis = new FileInputStream(filename); ObjectInputStream ois = new ObjectInputStream(fis); ) { diskAccounts = (Map<String, User>) ois.readObject(); } catch (EOFException | FileNotFoundException e) { diskAccounts = new HashMap<>(); } userAccounts = diskAccounts; } public void addAccount(User user) { userAccounts.put(user.getUserName(), user); } public User getAccount(String username) { return userAccounts.get(username); } public void deleteAccount(String username) { userAccounts.remove(username); } public void saveHashMap() { try( FileOutputStream fos = new FileOutputStream(filename); ObjectOutputStream oos = new ObjectOutputStream(fos); ) { oos.writeObject(userAccounts); } catch (IOException e) { throw new RuntimeException(e); } } } User.java package com.stackexchange.bank; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import java.io.Serial; import java.io.Serializable; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.util.Arrays; public class User implements Serializable {
{ "domain": "codereview.stackexchange", "id": 43021, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
java, beginner public class User implements Serializable { @Serial private static final long serialVersionUID = 1L; private static final SecretKeyFactory secrets; private static final SecureRandom rand; private static final int keyLength = 512; static { try { secrets = SecretKeyFactory.getInstance( String.format("PBKDF2WithHmacSHA%d", keyLength) ); rand = SecureRandom.getInstanceStrong(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } private final String userName; private final byte[] salt = new byte[16]; private byte[] passwordHash; private double balance; private double lastTransaction; private char transactionKind; User (String userName, char[] password) { this.userName = userName; this.passwordHash = setPassword(password); } public String getUserName() { return userName; } public double getBalance() { return balance; } //Updates-increases the variable balance according to the input from the user public void deposit(double deposit) { balance += deposit; lastTransaction = deposit; transactionKind = 'D'; } //Updates-decreases the variable balance according to the input from the user public void withdraw(double withdraw) { balance -= withdraw; lastTransaction = withdraw; transactionKind = 'W'; } public double getLastTransactionAmount() { return lastTransaction; } public char getLastTransactionKind() { return transactionKind; } private byte[] setPassword(char[] password) { rand.nextBytes(salt); return hash(password); }
{ "domain": "codereview.stackexchange", "id": 43021, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
java, beginner private byte[] hash(char[] password) { final int iterCount = 65536; KeySpec spec = new PBEKeySpec(password, salt, iterCount, keyLength); byte[] encoded; try { encoded = secrets.generateSecret(spec).getEncoded(); } catch (InvalidKeySpecException e) { throw new RuntimeException(e); } return encoded; } public boolean validatePassword(char[] candidate) { return Arrays.equals(passwordHash, hash(candidate)); } public void changePassword(char[] newPassword) { passwordHash = setPassword(newPassword); } } BankUI.java package com.stackexchange.bank; import java.io.Console; import java.io.IOException; import java.text.NumberFormat; import java.util.InputMismatchException; import java.util.Scanner; import static java.lang.System.out; public class BankUI { private final Bank bank = new Bank(); private final Scanner in = new Scanner(System.in); private final Console console = System.console(); private final NumberFormat currency = NumberFormat.getCurrencyInstance(); private boolean shouldExit = false; private User user; public BankUI() throws IOException, ClassNotFoundException { if (console == null) { throw new UnsupportedOperationException("Refusing to run in an insecure terminal."); } } public static void main(String[] args) throws IOException, ClassNotFoundException { new BankUI().mainMenu(); }
{ "domain": "codereview.stackexchange", "id": 43021, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
java, beginner public void mainMenu() { while (!shouldExit) { if (user == null) { out.printf( "Welcome to my Bank System" + "%n" + "%n1: Open existing account." + "%n2: Create new account." + "%n" ); menuInput( this::openAccount, this::createAccount ); } else { out.printf( "Choose an action of the following options." + "%n" + "%n1: Display Account Information." + "%n2: Deposit." + "%n3: Withdraw." + "%n4: Check Balance." + "%n5: Change Password." + "%n6: Delete Account." + "%n7: Exit." + "%n" ); menuInput( this::displayUserInfo, this::deposit, this::withdraw, this::checkBalance, this::changePassword, this::deleteAccount, this::exit ); } out.println(); } } public void menuInput(Runnable... options) { int choice; while (true) { out.print("Enter: "); try { choice = in.nextInt() - 1; in.nextLine(); } catch (InputMismatchException e) { out.println("Please enter a valid integer."); in.nextLine(); continue; } if (choice >= 0 && choice < options.length) break; out.println("Please enter a valid choice."); } options[choice].run(); }
{ "domain": "codereview.stackexchange", "id": 43021, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
java, beginner options[choice].run(); } public void displayUserInfo() { out.printf("User Name: %s%n", user.getUserName()); String kind; switch (user.getLastTransactionKind()) { case 'D' -> kind = "Deposit"; case 'W' -> kind = "Withdrawal"; default -> { return; } } out.printf( "Last Transaction: %s, Amount: %s%n", kind, currency.format(user.getLastTransactionAmount()) ); } public void deposit() { out.print("Please enter any amount to deposit: "); double deposit = in.nextDouble(); in.nextLine(); user.deposit(deposit); out.printf("You have successfully deposited %s%n", currency.format(deposit)); bank.saveHashMap(); } public void withdraw() { out.print("Please enter any amount to withdraw: "); double withdraw = in.nextDouble(); in.nextLine(); user.withdraw(withdraw); out.printf("You have successfully withdrawn %s%n", currency.format(withdraw)); bank.saveHashMap(); } public void checkBalance() { out.printf("Current Balance: %s%n", currency.format(user.getBalance())); } public void changePassword() { out.println("To change the password please enter the current password."); if (validatePassword()) { out.print("Please enter the new password: "); user.changePassword(console.readPassword()); bank.saveHashMap(); } else { user = null; } } public void openAccount() { out.print("Please enter the user name of the account: "); String userName = in.nextLine(); user = bank.getAccount(userName); if (user == null) { out.println("Please enter an existing account."); return; } if (!validatePassword()) user = null; }
{ "domain": "codereview.stackexchange", "id": 43021, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
java, beginner if (!validatePassword()) user = null; } public void createAccount() { out.print("Enter a new user name for the account: "); String userName = in.nextLine(); if (bank.getAccount(userName) != null) { out.println("This user name already exists."); return; } out.print("Enter a new password for the account: "); user = new User(userName, console.readPassword()); bank.addAccount(user); bank.saveHashMap(); } public void deleteAccount() { out.println("Please enter password to delete account."); if (validatePassword()) { bank.deleteAccount(user.getUserName()); out.printf("You have successfuly deleted account '%s'.%n", user.getUserName()); bank.saveHashMap(); } user = null; } public boolean validatePassword() { try { for (int tries = 0; tries < 3; tries++) { out.print("Please enter the password: "); if (user.validatePassword(console.readPassword())) return true; Thread.sleep(1000); out.println("Incorrect password."); } out.println("You have entered too many incorrect passwords."); Thread.sleep(3000); } catch (InterruptedException e) { throw new RuntimeException(e); } return false; } public void exit() { shouldExit = true; } }
{ "domain": "codereview.stackexchange", "id": 43021, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner", "url": null }
bash, shell, rags-to-riches Title: Rename files by editing their names in an editor Question: Inspired by a recent question to rename files by editing the list of names in an editor, I put together a similar script. Why: if you need to perform some complex renames that are not easy to formulate with patterns (as with the rename.pl utility), it might be handy to be able to edit the list of names in a text editor, where you will see the exact names you will get. Features: Edit names in a text editor Use the names specified as command line arguments, or else the files and directories in the current directory (resolve *) Use a sensible default text editor According to man bash, READLINE commands try $VISUAL or else $EDITOR -> looks like a good example to follow. Abort if cannot determine a suitable editor. Abort (do not rename anything) if the editor exits with error Paths containing newlines are explicitly unsupported Perform basic sanity checks: the edited text should have the same number of lines as the paths to rename Here's the script: #!/usr/bin/env bash # # SCRIPT: mv-many.sh # AUTHOR: Janos Gyerik <info@janosgyerik.com> # DATE: 2019-07-27 # # PLATFORM: Not platform dependent # # PURPOSE: Rename files and directories by editing their names in $VISUAL or $EDITOR # set -euo pipefail usage() { local exitcode=0 if [[ $# != 0 ]]; then echo "$*" >&2 exitcode=1 fi cat << EOF Usage: $0 [OPTION]... [FILES] Rename files and directories by editing their names in $editor Specify the paths to rename, or else * will be used by default. Limitations: the paths must not contain newline characters. EOF if [[ $editor == *vim ]]; then echo "Tip: to abort editing in $editor, exit with :cq command." fi cat << "EOF" Options: -h, --help Print this help EOF exit "$exitcode" } fatal() { echo "Error: $*" >&2 exit 1 } find_editor() { # Following READLINE conventions, try VISUAL first and then EDITOR
{ "domain": "codereview.stackexchange", "id": 43022, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, shell, rags-to-riches", "url": null }
bash, shell, rags-to-riches find_editor() { # Following READLINE conventions, try VISUAL first and then EDITOR if [[ ${VISUAL+x} ]]; then echo "$VISUAL" return fi # shellcheck disable=SC2153 if [[ ${EDITOR+x} ]]; then echo "$EDITOR" return fi fatal 'could not determine editor to use, please set VISUAL or EDITOR; aborting.' } editor=$(find_editor) oldnames=() while [[ $# != 0 ]]; do case $1 in -h|--help) usage ;; -|-?*) usage "Unknown option: $1" ;; *) oldnames+=("$1") ;; esac shift done work=$(mktemp) trap 'rm -f "$work"' EXIT if [[ ${#oldnames[@]} == 0 ]]; then oldnames=(*) fi printf '%s\n' "${oldnames[@]}" > "$work" "$editor" "$work" || fatal "vim exited with error; aborting without renaming." mapfile -t newnames < "$work" [[ "${#oldnames[@]}" == "${#newnames[@]}" ]] || fatal "expected ${#oldnames[@]} lines in the file, got ${#newnames[@]}; aborting without renaming." for ((i = 0; i < ${#oldnames[@]}; i++)); do old=${oldnames[i]} new=${newnames[i]} if [[ "$old" != "$new" ]]; then mv -vi "$old" "$new" fi done What do you think? I'm looking for any and all kinds of comments, suggestions, critique. Answer: Looks pretty good to me, and to Shellcheck too. find_editor is quite long-winded; it could be a one-liner: editor=${VISUAL:-${EDITOR:?could not determine editor to use, please set VISUAL or EDITOR; aborting.}}
{ "domain": "codereview.stackexchange", "id": 43022, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, shell, rags-to-riches", "url": null }
bash, shell, rags-to-riches There's a couple of Vim-isms remaining. The test if [[ $editor == *vim ]] could be generalised to a case "$editor" in … esac to support adding more editor hints, but more significantly, we have an error message that mentions vim where $editor would be more appropriate. The current implementation is very simplistic when the new names might overlap with the old names. We might need a topological sort to perform the renames in the correct order in that case. Perhaps it should be an error if the user asks for two or more files to be moved to the same target name?
{ "domain": "codereview.stackexchange", "id": 43022, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, shell, rags-to-riches", "url": null }
python, pygame Title: PixelArt made with pygame Question: I am a bit new to pygame, and I made this simple pixel art game. Is it possible to simplify, and is it possible to save your drawings and load them back again? import pygame from sys import exit def ConvertPos(pos): x, y = pos return x//SQUARE_SIZE, y//SQUARE_SIZE def DrawGrid(): for x in range(0, WIDTH, SQUARE_SIZE): for y in range(0, HEIGHT, SQUARE_SIZE): rect = pygame.Rect(x, y, SQUARE_SIZE, SQUARE_SIZE) pygame.draw.rect(screen, "Black", rect, 1) def SelectColor(): global draw_color mouse_pressed = pygame.mouse.get_pressed() bg = pygame.Rect(WIDTH, 0, SIDE, HEIGHT) pygame.draw.rect(screen, "Orange", bg) pygame.draw.rect(screen, "Purple", bg, 5) for item, color in enumerate(colors): select_color = pygame.Rect(0, 0, 120, 30) select_color.center = WIDTH+SIDE//2, HEIGHT*(item+1)/len(colors)-(HEIGHT/len(colors))/2 pygame.draw.rect(screen, color, select_color) if select_color.collidepoint(pygame.mouse.get_pos()) and mouse_pressed[0]: draw_color = color if draw_color == color: pygame.draw.rect(screen, "DarkBlue", select_color, 5) def DrawSquare(): global draw_color mouse_pos = pygame.mouse.get_pos() mouse_pressed = pygame.mouse.get_pressed() grid_x, grid_y = grid_pos = ConvertPos(mouse_pos) cursor = (grid_x*SQUARE_SIZE, grid_y*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE) for (x, y), color in pressed.items(): square = pygame.Rect(x*SQUARE_SIZE, y*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE) pygame.draw.rect(screen, color, square) if 0 < mouse_pos[0] < WIDTH-1 and 0 < mouse_pos[1] < HEIGHT-1: pygame.draw.rect(screen, draw_color, cursor, 3) if mouse_pressed[0]: pressed[grid_pos] = draw_color if mouse_pressed[2] and grid_pos in pressed: pressed.pop(grid_pos) if mouse_pressed[1]: pressed.clear()
{ "domain": "codereview.stackexchange", "id": 43023, "lm_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, pygame", "url": null }
python, pygame pygame.init() clock = pygame.time.Clock() WIDTH = 800 SIDE = 200 HEIGHT = 400 MARGIN = 50 SQUARE_SIZE = 25 screen = pygame.display.set_mode((WIDTH+SIDE, HEIGHT)) pygame.display.set_caption("PXLART") pressed = {} colors = ["Black", "Blue", "Green", "Red", "Pink", "Yellow", "White", "DarkGreen", "Brown", "Grey", "Cyan"] draw_color = "Black" while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() screen.fill("White") DrawGrid() SelectColor() DrawSquare() pygame.display.update() clock.tick(60) Answer: ConvertPos should be convert_pos and so on for your other methods due to PEP8. Don't keep global state. There are a few alternatives, a class being the easiest. Separate out your mouse handling from your drawing, and don't keep a clock or a "frame loop". You don't have any animations, so use an event loop instead. This is far less wasteful. In other words, 60 times a second, if absolutely nothing is happening from the user, the program should just wait for a new event instead of churning through hundreds of draw calls. Add PEP484 type hints. Add a __main__ guard. Don't exit() on program termination - that isn't very nice to your callers; just return. It's more typical to have y in your outer loop rather than your inner loop - this will produce iteration in the same pattern as a typewriter (left-right fast, up-down slow). Suggested import pygame from pygame.event import Event WIDTH = 800 SIDE = 200 HEIGHT = 400 MARGIN = 50 SQUARE_SIZE = 25 COLOURS = ( "Black", "Blue", "Green", "Red", "Pink", "Yellow", "White", "DarkGreen", "Brown", "Grey", "Cyan", ) def convert_pos(pos: tuple[int, int]) -> tuple[int, int]: x, y = pos return x//SQUARE_SIZE, y//SQUARE_SIZE class Game: def __init__(self) -> None: pygame.display.set_caption("PXLART")
{ "domain": "codereview.stackexchange", "id": 43023, "lm_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, pygame", "url": null }
python, pygame class Game: def __init__(self) -> None: pygame.display.set_caption("PXLART") self.screen: pygame.Surface = pygame.display.set_mode((WIDTH + SIDE, HEIGHT)) self.pressed: dict[tuple[int, int], str] = {} self.draw_color = "Black" def draw_grid(self) -> None: for y in range(0, HEIGHT, SQUARE_SIZE): for x in range(0, WIDTH, SQUARE_SIZE): rect = pygame.Rect(x, y, SQUARE_SIZE, SQUARE_SIZE) pygame.draw.rect(self.screen, "Black", rect, 1) def draw_select_colour(self) -> None: background = pygame.Rect(WIDTH, 0, SIDE, HEIGHT) pygame.draw.rect(self.screen, "Orange", background) pygame.draw.rect(self.screen, "Purple", background, 5) for item, colour in enumerate(COLOURS): select_colour = pygame.Rect(0, 0, 120, 30) select_colour.center = ( WIDTH + SIDE/2, HEIGHT/len(COLOURS)*(item + 0.5) ) pygame.draw.rect(self.screen, colour, select_colour) if self.draw_color == colour: pygame.draw.rect(self.screen, "DarkBlue", select_colour, 5) def draw_square(self) -> None: mouse_x, mouse_y = mouse_pos = pygame.mouse.get_pos() grid_x, grid_y = convert_pos(mouse_pos) cursor = (grid_x*SQUARE_SIZE, grid_y*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE) for (x, y), color in self.pressed.items(): square = pygame.Rect(x*SQUARE_SIZE, y*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE) pygame.draw.rect(self.screen, color, square) if 0 < mouse_x < WIDTH-1 and 0 < mouse_y < HEIGHT-1: pygame.draw.rect(self.screen, self.draw_color, cursor, 3) def handle_mouse(self, pos: tuple[int, int], left: bool, middle: bool, right: bool) -> None: mouse_x, mouse_y = pos if 0 <= mouse_x < WIDTH and 0 <= mouse_y < HEIGHT: grid_pos = convert_pos(pos) else: grid_pos = None
{ "domain": "codereview.stackexchange", "id": 43023, "lm_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, pygame", "url": null }
python, pygame if left: if grid_pos is None: for item, colour in enumerate(COLOURS): select_colour = pygame.Rect(0, 0, 120, 30) select_colour.center = ( WIDTH + SIDE / 2, HEIGHT / len(COLOURS) * (item + 0.5) ) if select_colour.collidepoint(pygame.mouse.get_pos()): self.draw_color = colour else: self.pressed[grid_pos] = self.draw_color elif middle: self.pressed.clear() elif right: self.pressed.pop(grid_pos, None) def draw(self) -> None: self.screen.fill("White") self.draw_grid() self.draw_select_colour() self.draw_square() pygame.display.update() def run(self) -> None: while True: event: Event = pygame.event.wait() if event.type == pygame.QUIT: return if event.type == pygame.MOUSEBUTTONDOWN: self.handle_mouse(event.pos, *( event.button == b for b in ( pygame.BUTTON_LEFT, pygame.BUTTON_MIDDLE, pygame.BUTTON_RIGHT, ) )) if event.type == pygame.MOUSEMOTION: self.handle_mouse(event.pos, *event.buttons) if event.type in {pygame.MOUSEBUTTONDOWN, pygame.MOUSEMOTION, pygame.WINDOWSHOWN}: self.draw() if __name__ == '__main__': Game().run()
{ "domain": "codereview.stackexchange", "id": 43023, "lm_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, pygame", "url": null }
c++, reinventing-the-wheel, collections, library Title: std::vector implementation learning exercise Question: I want to improve my algorithms and data structures in C++ understanding and also learn how the standard library containers are implemented. This resizing_array is based on the std::vector. My questions are: Are there any memory allocation/deallocation errors in this implementation? Is the design ok? Can it be improved? Any bugs? Any feedback not mentioned above would be interesting. resizing_array.hpp: #ifndef RESIZING_ARRAY_ #define RESIZING_ARRAY_ /* Useful resources: https://en.cppreference.com/w/cpp/container/vector https://www.cs.odu.edu/~zeil/cs361/sum18/Public/vectorImpl/index.html https://www.cs.odu.edu/~zeil/references/cpp_ref_draft_nov97/lib-containers.html Operation Speed vector() O(1) vector(n, x) O(n) // not implemented size() O(1) v[ i ] O(1) push_back(x) O(1) pop_back O(1) insert O(size()) // not implemented erase O(size()) // not implemented front, back O(1) // not implemented */ #include <iterator> #include <algorithm> #include <initializer_list> #include <iostream> // debug output namespace play { template< typename T > class resizing_array { public: template< typename input_iterator > resizing_array(input_iterator first, input_iterator last) { size_ = std::distance(first, last); capacity_ = size_; array_ = nullptr; resize_array(capacity_); std::copy(first, last, array_); } resizing_array(std::initializer_list<T> init) : size_(init.size()), capacity_(init.size()), array_(nullptr) { size_ = init.size(); capacity_ = size_; resize_array(capacity_); std::copy(init.begin(), init.end(), array_); }
{ "domain": "codereview.stackexchange", "id": 43024, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, reinventing-the-wheel, collections, library", "url": null }
c++, reinventing-the-wheel, collections, library resizing_array() : size_(0), capacity_(8), array_(nullptr) { resize_array(8); std::cout << "allocating array at address: " << array_ << std::endl; } resizing_array(const resizing_array& other) : size_(other.size()), capacity_(other.capacity()), array_(nullptr) { resize_array(capacity_); std::cout << "copy ctor allocated array at address: " << array_ << std::endl; std::copy(other.begin(), other.end(), array_); } resizing_array& operator=(const resizing_array& other) { if (this != &other) { size_ = other.size(); capacity_ = other.capacity(); free(array_); array_ = nullptr; resize_array(capacity_); std::cout << "op= allocated array at address: " << array_ << std::endl; std::copy(other.begin(), other.end(), array_); } return *this; } resizing_array(resizing_array&& other) : size_(other.size()), capacity_(other.capacity()), array_(other.begin()) { other.size_ = 0; other.capacity_ = 0; other.array_ = nullptr; } resizing_array& operator=(resizing_array&& other) { free(array_); array_ = other.array_; size_ = other.size(); capacity_ = other.capacity(); other.array_ = nullptr; other.size_ = 0; other.capacity_ = 0; } ~resizing_array() { std::cout << "deallocating array at address: " << array_ << std::endl; free(array_); } void push_back(const T& v) { if (size_ == capacity_) { resize_array(size_ * 2); capacity_ = size_ * 2; } array_[size_++] = v; } void pop_back() { --size_; }
{ "domain": "codereview.stackexchange", "id": 43024, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, reinventing-the-wheel, collections, library", "url": null }
c++, reinventing-the-wheel, collections, library void pop_back() { --size_; } size_t size() const { return size_; } T& operator[](size_t index) { return array_[index]; } const T& operator[](size_t index) const { return array_[index]; } T* begin() { return array_; } T* end() { return array_ + capacity_; } const T* begin() const { return array_; } const T* end() const { return array_ + capacity_; } size_t capacity() const { return capacity_; } private: bool resize_array(size_t new_size) { void* new_pointer = realloc(array_, new_size * sizeof(T)); if (new_pointer) { array_ = static_cast<T*>(new_pointer); std::cout << "array at address: " << array_ << " size increased to: " << new_size << std::endl; return true; } else { return false; } } size_t size_; size_t capacity_; T* array_; }; } // end of namespace play #endif // RESIZING_ARRAY_ main.cpp to exercise: #include "resizing_array.hpp" #include <cassert> using namespace play; // to test move constructor resizing_array<int> fill(std::istream& is) { std::cout << "Enter your list of integers, ctrl-D to finish: "; resizing_array<int> ra; for (int v; is >> v; ) ra.push_back(v); return ra; } int main() { resizing_array<int> ra; // Can it grow? for (size_t i = 0; i < 100; ++i) { ra.push_back(i); } // can we read elements by [index]? std::cout << "ra[0]=" << ra[0] << std::endl; std::cout << "ra[1]=" << ra[1] << std::endl; std::cout << "ra[2]=" << ra[2] << std::endl; std::cout << "ra[3]=" << ra[3] << std::endl; std::cout << "ra[4]=" << ra[4] << std::endl;
{ "domain": "codereview.stackexchange", "id": 43024, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, reinventing-the-wheel, collections, library", "url": null }
c++, reinventing-the-wheel, collections, library // can we write a value by [index]? ra[3] = 10; std::cout << "ra[3] is now =" << ra[3] << std::endl; // can we remove elements? std::cout << "current size of resizing array is: " << ra.size() << " and last element: " << ra[ra.size() - 1] << std::endl; ra.pop_back(); std::cout << "size of resizing array after pop() is: " << ra.size() << " and last element: " << ra[ra.size() - 1] << std::endl; // copy construction works? resizing_array<int> ra2(ra); std::cout << "current size of resizing array 2 is: " << ra2.size() << " and last element: " << ra2[ra2.size() - 1] << std::endl; // create a new resizing_array from begin and end iterator constructor const int raw_array[]{ 1,2,3,4,5}; size_t size = sizeof(raw_array) / sizeof(raw_array[0]); resizing_array<int> ra3(raw_array, raw_array + size); assert(ra3.size() == 5); assert(ra3[0] == raw_array[0]); assert(ra3[1] == raw_array[1]); assert(ra3[2] == raw_array[2]); assert(ra3[3] == raw_array[3]); assert(ra3[4] == raw_array[4]); // create a new resizing array from an initialisation_list resizing_array<int> ra4{1,2,3,4,5}; assert(ra4[0] == 1); assert(ra4[1] == 2); assert(ra4[2] == 3); assert(ra4[3] == 4); assert(ra4[4] == 5); // assignment operator test // will crash if haven't implemented operator= ra4 = ra3; assert(ra4[ra4.size() - 1] == ra3[ra3.size() - 1]); // move constructor and move assignment test resizing_array<int> ra5 = fill(std::cin); } Answer: Your implementation of end() seems to be wrong, since capacity_ is not always the same as size_. It should be changed to: const T* end() const { return array_ + size_; }
{ "domain": "codereview.stackexchange", "id": 43024, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, reinventing-the-wheel, collections, library", "url": null }
c++, reinventing-the-wheel, collections, library Not shure if using cout for debuging purpose is a good idea. The code looks a bit redundant in some places, as capacity_ should be changed inside resize_array and not outside. What the return value of resize_array should be good for? It is never used. It could be a good idea to throw some kind of exeption if resize_array fails instead.
{ "domain": "codereview.stackexchange", "id": 43024, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, reinventing-the-wheel, collections, library", "url": null }
python, performance, algorithm Title: Count lengths of constant subarrays Question: I have an array assuming discrete values. For each value, I am interested in how often it is assumed in a row. For instance, if my array is [5 5 5 5 5 0 0 4 1 1 5 1 1 1 1 1 3 3 3 3 2 2 5 1 1 1 1 1 1 2 2 5], then I expect as a result the following dictionary: { 0: [2], 1: [2, 5, 6], 2: [2, 2], 3: [4], 4: [1], 5: [5, 1, 1, 1] } The keys are the discrete values from the array. The value for each key is a list telling me how often the key was hit in a row when it occured. My (working) approach is this: def durations_per_occurence( array: np.ndarray, max: int, # max == np.max(array) ) -> dict: durations = {k: [] for k in range(max+1)} current_key = array[0] current_duration = 0 for key in array: if key == current_key: current_duration += 1 else: durations[current_key].append(current_duration) current_key = key current_duration = 1 durations[current_key].append(current_duration) # last entry return durations I am grateful for any advice, but particulary interested in built-in Python functionality to speed up the computation. (I often hear that for-loops are particularly slow in Python and that one should vectorize computations. Is there a neat vectorization for this particular problem?) Answer: A few initial thoughts on the code:
{ "domain": "codereview.stackexchange", "id": 43025, "lm_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", "url": null }
python, performance, algorithm Answer: A few initial thoughts on the code: Iterating through groups of consecutive elements is implemented efficiently by itertools.groupby, which for each consecutive group in a collection returns both the repeated value and an iterator through those repeated elements in the list. cardinality.count can efficiently count the number of elements in that iterable, enabling us to efficiently get the run length In cases where you have a vector with a wide range of data values, you may be creating a durations dict that is mostly empty, spending time and memory in the process. Plus you need to compute the maximum value, which takes time, adds an extra function argument, and is prone to off-by-one errors. It also reduces flexibility if, for instance, you started getting negative or fractional data (which break your code). The collections.defaultdict object smoothly handles all these issues -- it automagically creates the initial empty list for each key when it's first added, and it doesn't store keys that never show up (but it will return [] if an unadded key is accessed). Putting it all together, you end up with: from itertools import groupby from cardinality import count from collections import defaultdict def durations_per_occurence2( array: np.ndarray ) -> defaultdict: durations = defaultdict(list) for k, g in groupby(array): durations[k].append(count(g)) return durations Beyond being much more compact and pythonic, this code runs more than 10,000x faster (according to timeit) when I run with your sample data with the number 1000000 appended to the end.
{ "domain": "codereview.stackexchange", "id": 43025, "lm_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", "url": null }
python, beginner, python-3.x, palindrome Title: Finding the next palindrome number Question: I wrote a piece of code that generates the next palindromic number and that works fine. However I feel like my code isn't as efficient as it could be. Are there any tweaks that I could implement to make it run more efficiently? Input format: 4 # No. of Test Cases 800 2133 103 6 Code I have currently: def reverse(x): return int(str(x)[::-1]) def count(left, right): left_d = left % 10 right_d = int(str(right)[0]) if left < right: return 1 elif left > right: return 0 else: left //= 10 right = int(str(right)[1:]) return count(left, right) def nextPal(x): length, rev = len(str(x)), reverse(x) if length == 1: return x + 1 elif x == int("9" * length): return x + 2 elif length % 2 != 0 and x == rev: digits = list(str(x)) mid = len(digits) // 2 digits[mid] = f"{int(digits[mid]) + 1}" return int("".join(digits)) elif length % 2 == 0: x_str = str(x) left = int(x_str[:len(x_str) // 2]) right = int(x_str[len(x_str) // 2:]) left += count(left, right) return int(f"{left}{reverse(left)}") else: while rev != x: x += 1 rev = reverse(x) return x # Typically read from STDIN like 'python nextpal.py < data.txt' cases = int(input()) for _ in range(cases): case = int(input()) print(nextPal(case)) Output: 808 2222 111 7 Answer: This code has many bugs: nextPal(9) returns 10, nextPal(191) return 1101, and nextPal(8008) returns 808.
{ "domain": "codereview.stackexchange", "id": 43026, "lm_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, beginner, python-3.x, palindrome", "url": null }
python, beginner, python-3.x, palindrome nextPal(9) returns 10, nextPal(191) return 1101, and nextPal(8008) returns 808. I will not point out how to fix these bugs. The Stack Overflow site is for help fixing code, not the Code Review site. Still, since you claimed the code "works fine", it seems you were not aware of these bugs, so the question is "on topic", and a review of the code is warranted. Naming PEP 8, the Style Guide for Python Code recommends function use snake_case names, not bumpyWords. As such, nextPal should be named next_pal, or even better, next_palindrome. Unused code This variables are assigned, but never used: left_d = left % 10 right_d = int(str(right)[0]) Left Leaning Code Both the count and nextPal functions use an if return elif return else return ladder. Since every if and elif block terminates in a return statement, there is no need for the else's; the elif could simply be if statements, and the final else: removed. This results in less indentation (in this case, only in the final else blocks), and is generally more readable. Multiple assignment This statement is doing two different things: length, rev = len(str(x)), reverse(x) It is determining the number of digits of x, and it is reversing the digits of x. As completely different operations, combining them into a single statement is not appropriate. The reader has to mentally unpack the statement into two statements, grouping the first parts and second parts together. Moreover, the Python interpreter is doing extra work, creating the tuple and then unpacking the tuple ... extra work done for no reason. Simply use two statements: length = len(str(x)) rev = reverse(x) Efficiency & Hint After all your special case checks, you finally fall back on a linear search for a palindrome: while rev != x: x += 1 rev = reverse(x)
{ "domain": "codereview.stackexchange", "id": 43026, "lm_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, beginner, python-3.x, palindrome", "url": null }
python, beginner, python-3.x, palindrome This is incredibly inefficient. For any whole number x, you can determine a palindrome near x by converting x to a string and replacing the last half of the digits with the reverse of the first half of the digits. For example, 12345 becomes 12321 and 123456 becomes 123321. In these cases, the generated value is actually the previous palindrome, not the next palindrome (left to student).
{ "domain": "codereview.stackexchange", "id": 43026, "lm_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, beginner, python-3.x, palindrome", "url": null }
c#, design-patterns, interview-questions, state Title: Vending Machine implementing State Pattern Question: I was asked to implement a Vending Machine in a recent interview coding challenge. My attempt at a solution is based on the state pattern. I would like to get some code reviews on this bearing in mind I would have about 40 minutes to implement this in the interview scenario. When reviewing I would like you to consider how I have done in relation to SOLID principles. And also consider that the requirements from the interview are: Create a vending machine library Consumers of the library can list products Ability to select product After product selected, ability to insert coins When enough coins are submitted, product and change dispensed Ability to cancel Dont worry about stock levels Only one consumer at a time Think about extensibility Here is the code for review: using System; using System.Collections.Generic; using System.Linq; namespace VendingMachineV2_StatePattern { public interface IVendingMachine { List<Product> Products { get; } int CashInserted { get; } int ProductChosen { get; set; } void ChangeState(IState state); void MakeChoice(int productId); void InsertMoney(int amount); (Product, int) DispenseItem(); int RefundMoney(); void ResetMachine(); } public interface IState { (Product, int) DoWork(); } public class VendingMachine : IVendingMachine { private IState _state; public List<Product> Products { get;} public int CashInserted { get; private set; } public int ProductChosen { get; set; } public VendingMachine() { CashInserted = 0; Products = PopulateProducts(); _state = new AwaitingChoice(this); } public void ChangeState(IState state) { _state = state; }
{ "domain": "codereview.stackexchange", "id": 43027, "lm_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#, design-patterns, interview-questions, state", "url": null }
c#, design-patterns, interview-questions, state public void ChangeState(IState state) { _state = state; } public void MakeChoice(int productId) { ProductChosen = productId; _state.DoWork(); } public void InsertMoney(int amount) { CashInserted += amount; _state.DoWork(); } public (Product, int) DispenseItem() { return _state.DoWork(); } public int RefundMoney() { _state = new Canceling(this); var (product, refund) = _state.DoWork(); CashInserted = 0; return refund; } public void ResetMachine() { CashInserted = 0; ProductChosen = 0; } private static List<Product> PopulateProducts() { return new List<Product>() { new Product(1, "Guinness", 3), new Product(2, "Tayto", 2) }; } } public class AwaitingChoice : IState { private readonly IVendingMachine _vendingMachine; public AwaitingChoice(IVendingMachine vendingMachine) { _vendingMachine = vendingMachine; _vendingMachine.ResetMachine(); Console.WriteLine($"Available products: {string.Join(",", _vendingMachine.Products.Select(x => $"Id: {x.Id}, Name: {x.Name}, Price: {x.Price}").ToArray())}"); } public (Product, int) DoWork() { _vendingMachine.ChangeState(new AwaitingMoney(_vendingMachine)); return (null, 0); } }
{ "domain": "codereview.stackexchange", "id": 43027, "lm_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#, design-patterns, interview-questions, state", "url": null }
c#, design-patterns, interview-questions, state public class AwaitingMoney : IState { private readonly IVendingMachine _vendingMachine; private readonly Product _productChosen; public AwaitingMoney(IVendingMachine vendingMachine) { _vendingMachine = vendingMachine; _productChosen = _vendingMachine.Products.FirstOrDefault(x => x.Id == _vendingMachine.ProductChosen); Console.WriteLine($"You have chosen {_productChosen.Name}, price is {_productChosen.Price}, please insert coins."); } public (Product, int) DoWork() { if (_vendingMachine.CashInserted < _productChosen.Price) { Console.WriteLine($"Price is {_productChosen.Price}, you have paid {_vendingMachine.CashInserted}, please insert more coins."); } else { _vendingMachine.ChangeState(new Dispensing(_vendingMachine)); } return (null, 0); } } public class Dispensing : IState { private readonly IVendingMachine _vendingMachine; private readonly Product _productChosen; public Dispensing (IVendingMachine vendingMachine) { _vendingMachine = vendingMachine; _productChosen = _vendingMachine.Products.FirstOrDefault(x => x.Id == _vendingMachine.ProductChosen); Console.WriteLine($"You have paid, dispensing {_productChosen.Name}, please wait..."); } public (Product, int) DoWork() { var returningChange = _vendingMachine.CashInserted > _productChosen.Price ? _vendingMachine.CashInserted - _productChosen.Price : 0; Console.WriteLine($"Here is your product {_productChosen.Name}, returning change {returningChange}."); _vendingMachine.ChangeState(new AwaitingChoice(_vendingMachine)); return (_productChosen, returningChange); } }
{ "domain": "codereview.stackexchange", "id": 43027, "lm_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#, design-patterns, interview-questions, state", "url": null }
c#, design-patterns, interview-questions, state return (_productChosen, returningChange); } } public class Canceling : IState { private readonly IVendingMachine _vendingMachine; public Canceling(IVendingMachine vendingMachine) { _vendingMachine = vendingMachine; Console.WriteLine("Cancelling, please wait..."); } public (Product, int) DoWork() { var refund = _vendingMachine.CashInserted; Console.WriteLine($"Here is your refund of {refund}..."); _vendingMachine.ChangeState(new AwaitingChoice(_vendingMachine)); return (null, refund); } } public class Product { public int Id { get; } public string Name { get; } public int Price { get; } public Product(int id, string name, int price) { Id = id; Name = name; Price = price; } } class Program { static void Main(string[] args) { IVendingMachine vendingMachine = new VendingMachine(); //Choose Product vendingMachine.MakeChoice(1); //Insert money vendingMachine.InsertMoney(1); //Not enough, insert more vendingMachine.InsertMoney(3); var (product, change) = vendingMachine.DispenseItem(); Console.WriteLine($"Got my {product.Name}, change is {change}."); //Choose Product vendingMachine.MakeChoice(2); //Insert money vendingMachine.InsertMoney(1); //Ah, no coins left, I will cancel vendingMachine.RefundMoney(); Console.ReadLine(); } } }
{ "domain": "codereview.stackexchange", "id": 43027, "lm_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#, design-patterns, interview-questions, state", "url": null }
c#, design-patterns, interview-questions, state Console.ReadLine(); } } } Answer: VendingMachine internals should not be public This fundamentally subverts the idea of a state machine; that the vending machine's internal state is changed by a proscribed, orderly series of transactions/events. Why bother when I can set all the properties directly. Delete IVendingMachine A well designed class exposes functionality and hides state. In other words a class' interface exposes functionality and hides state. However the formal interface C# construct is forcing required state to be public. The public members of a class is an interface even if it does not implement a interface definition. We will design with inheritance, polymorphism, etc. such that clients must implent their particular behavior of the desired interface; this does not require a C#-keyword interface definition. With abstract classes/methods, overriding, et.al. we are still "coding to interface not implementation." Define an abstract VendingMachine Now properties can be protected and thus inherited and public methods declared abstract, requiring subclass implementation. Any temporal coupling needs - like calling PopulateProducts - can be controlled using a template method. VendingMachine constructor should require products list Client programmer needs to know what is required to instantiate a valid object. This will inhance its usability as a library. Also, the vended products will naturally vary widely. Creating an inline List(Product) is OK but no time contraint excuses creating that inside VendingMachine. I might have argued "it's just a first, rough draft" if, and only if, there was a constructor overload as an implicit acknowledgement that I know I am egregiously violating "an obvious case for composition" (or "dependency injection" if you want to impress others) . e.g.: public VendingMachine(List<Product> inventory){ inventory ?? Throw new ArgumentNullException("constructor parameter is null"); }
{ "domain": "codereview.stackexchange", "id": 43027, "lm_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#, design-patterns, interview-questions, state", "url": null }
c#, design-patterns, interview-questions, state console.WriteLine() - Not in business model! I wonder if the interviewers said anything about it. Seems like it would not be trivial to refactor it out. Consumers of the library can list products This begs for a custom Products collection, if only to impliment this one method, given the time constraints. Collections need a place for the same OO goodness we intend to put in any other class. The expedient List<someClass> means validation, searching, comparing, output formatting, etc., etc., etc. is all done differently and redundantly by every client and even multiple methods of a given client. AwaitingChoice() is a case in point. Intended to speak to the spirit of a custom collection, not say what specific parameter and return types, and implementation, must be. public class Products { private List<Product> products {get; set;} public Products (List<Product> stuff) { products = stuff ?? new List<Product>(); } public string Inventory() { return this.ToString(); // ultra trivial if Product.ToString is overridden } public bool Add(product another) { // +another.Count if existing, else add new product } public string Dispense(string selection) { //Do we have that product and count >= 1 ? } } I wouldn't expect this necessarily, given your time constraint.
{ "domain": "codereview.stackexchange", "id": 43027, "lm_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#, design-patterns, interview-questions, state", "url": null }
performance, r Title: Mapping variables in two data frames using a third data frame Question: I have two data frames, df1 and df2 of identical structure. The first three columns, id, form, and instance identify the participant and form(s). The remaining variable columns, var1, var2, and var3, contain analytic data and are largely identical except for a few slight discrepancies. I have a third data frame, map that identifies the id, form(s), and variables that have discrepancies, but does not contain the values of these discrepancies. I would like to use the map data to create a final data frame, df.final that appends two columns and places the discrepant values from df1 and df2. Below I am providing sample data as well as a clunky-but-working for loop that creates the desired df.final. It is very slow (takes several hours to run on the full dataset) - so slow in fact it is functionally unusable (this ideally needs to be updated in near real time). I am hoping someone better at coding than me can provide alternative, faster solutions. (Note that given the simplicity of the example data, there are alternate ways to compare df1 and df2, but assume these don't work and using map is the only option.) # Example data, df1 df1 <- data.frame(id = rep(sprintf("K00%s", 0:9), each = 3), form = rep(c("A","B", "B"), times = 10), instance = rep(c("None", "1", "2"), times = 10), var1 = sample(LETTERS, 30, replace = TRUE), var2 = rnbinom(30, mu = 1, size = 0.02), var3 = sample(c("Apples", "Oranges", "Pears"), 30, replace = TRUE)) # Sample data df2, same as df1 but with slight discrepancies df2 <- df1 df2[15, 4] <- "A" df2[c(4, 6, 8), 5] <- c(11,15,16) df2[27:28, 6] <- "Bannanas"
{ "domain": "codereview.stackexchange", "id": 43028, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, r", "url": null }
performance, r # Example "Map" that only indicates what ID, form, instance, and variable is discrepant map <- data.frame(id = c("K004", "K001", "K001", "K002", "K008", "K009"), form = c("B","A", "B", "B", "B", "A"), instance = c("2", "None", "2", "1", "2", "None"), variable = c("var1", rep("var2", 3), "var3", "var3")) # id form instance variable # 1 K004 B 2 var1 # 2 K001 A None var2 # 3 K001 B 2 var2 # 4 K002 B 1 var2 # 5 K008 B 2 var3 # 6 K009 A None var3 ## - - - - - - - - - - - - - - - - - - - # Currently working for-loop, but VERY slow in full data ## - - - - - - - - - - - - - - - - - - - df.final <- data.frame(matrix(NA, ncol = 6)) for (i in 1:nrow(map)){ keepcols <- c("id", "form","instance", map[i,4]) m1 <- merge(map[i,], df1[ , keepcols], by = keepcols[-4]) m2 <- merge(m1, df2[, keepcols], by = keepcols[-4]) df.final[i,] <- m2 } names(df.final) <- c(names(map), "df1_entry","df2_entry") df.final # id form instance variable df1_entry df2_entry # 1 K004 B 2 var1 P A # 2 K001 A None var2 0 11 # 3 K001 B 2 var2 0 15 # 4 K002 B 1 var2 0 16 # 5 K008 B 2 var3 Pears Bannanas # 6 K009 A None var3 Apples Bannanas Answer: You do not mention on how you create the map table, but from start with df1 and df2 to the end result I suggest to skip the whole for loop. Efficient approach would be to: convert df1 and df2 in long format use anti_join to get the differences merge the differences Code dfl1 <- df1 %>% mutate(var2 = as.factor(var2)) %>% # just make sure all are the same type pivot_longer(cols = 4:6, names_to = "variable", values_to = "entry")
{ "domain": "codereview.stackexchange", "id": 43028, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, r", "url": null }
performance, r dfl2 <- df2 %>% mutate(var2 = as.factor(var2)) %>% # just make sure all are the same type pivot_longer(cols = 4:6, names_to = "variable", values_to = "entry") merge(anti_join(dfl1, dfl2), anti_join(dfl2, dfl1), by = c("id", "form", "instance", "variable"), suffixes = c("_df1", "_df2")) # id form instance variable entry_df1 entry_df2 # 1 K001 A None var2 0 11 # 2 K001 B 2 var2 0 15 # 3 K002 B 1 var2 0 16 # 4 K004 B 2 var1 I A # 5 K008 B 2 var3 Pears Bannanas # 6 K009 A None var3 Apples Bannanas
{ "domain": "codereview.stackexchange", "id": 43028, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, r", "url": null }
c, multithreading, linux, status-monitoring Title: Multithreaded C program to calculate CPU usage of cgroups Question: I am writing a program in an environment that makes use of cgroups to identify and group processes together. I want to parse the CPU utilization of each cgroup by sampling /sys/fs/cgroup/cpuacct/.../cpuacct.stat over a 1 second interval a few times and then averaging them. It also calculates the overall CPU utilization of the system by sampling /proc/stat in the same manner. I want to do this in a multithreaded way because if I did it serially, the samples would happen serially, and the program would take a while to run. I also use PCRE to distinguish between two different process types. #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <semaphore.h> #include <pthread.h> #include <sys/uio.h> #include <pcre.h> #define ITERATIONS 3 #if !defined(CLK_TIME_PER_SECOND) && defined(_SC_CLK_TCK) # define CLK_TIME_PER_SECOND ((int) sysconf (_SC_CLK_TCK)) #endif #if !defined(CLK_TIME_PER_SECOND) && defined(CLK_TCK) # define CLK_TIME_PER_SECOND ((int) CLK_TCK) #endif #if !defined(CLK_TIME_PER_SECOND) && defined(CLOCKS_PER_SEC) # define CLK_TIME_PER_SECOND ((int) CLOCKS_PER_SEC) #endif #if !defined(CLK_TIME_PER_SECOND) # define CLK_TIME_PER_SECOND 100 #endif struct job_struct { char procid[50]; //store job information as procid,procType tuple char procType[50]; }; typedef struct { char *procid; //for passing to the threads char *procType; } sample_struct; int sumFlag, clk; //TODO: localize? long double sum1, sum2, systemUtilization, otherCPU; char *aStrRegex; const char *pcreErrorStr; int pcreErrorOffset, pcreExecRet; int subStrVec[30]; pcre *reCompiled; pcre_extra *pcreExtra; pthread_mutex_t total_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t ok_to_add = PTHREAD_COND_INITIALIZER; int sampleCGroup(char procid[], char procType[]); void *addSampletoTotal(); void *overallUtilization();
{ "domain": "codereview.stackexchange", "id": 43029, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, multithreading, linux, status-monitoring", "url": null }
c, multithreading, linux, status-monitoring void *addSampletoTotal(); void *overallUtilization(); long double getSystemUtilization(void); int getOSVersion(void); int getCPUCount(void); int main(void) { int cpus, i, jobCount, osVersion; FILE *fp; char buff[1024]; cpus = getCPUCount(); clk = CLK_TIME_PER_SECOND; osVersion = getOSVersion(); if (osVersion <= 10) { systemUtilization = getSystemUtilization(); printf("sys=%Lf\n", systemUtilization); //cgroups are not supported on certain OS versions, so print the overall utilization and exit, otherwise, try to run pthread_mutex_destroy(&total_lock); //clean up mutex lock pthread_cond_destroy(&ok_to_add); return (0); } struct job_struct jobs[cpus]; //initially size the array to be the number of CPUs sumFlag = 1; //condition variable for mutex pthread_t systr; //thread id for overall system utilization, note this should only execute on certain versions, the conditional above should have returned if not pthread_create(&systr, NULL, overallUtilization, NULL); //create the thread
{ "domain": "codereview.stackexchange", "id": 43029, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, multithreading, linux, status-monitoring", "url": null }
c, multithreading, linux, status-monitoring aStrRegex = "proc_type1"; //type1 reCompiled = pcre_compile(aStrRegex, 0, &pcreErrorStr, &pcreErrorOffset, NULL); //compile the regex if (reCompiled == NULL) { printf("ERROR: Could not compile '%s': %s\n", aStrRegex, pcreErrorStr); pthread_join(systr, NULL); //join the system utilization thread if (systemUtilization > (long double) cpus) { //sanity check for HT systemUtilization = (long double) cpus; } printf("sys=%Lf\n", systemUtilization); //print info printf("cgrType2=%f\n", 0.0); printf("cgrType1=%f\n", 0.0); printf("cgrOther=%Lf\n", systemUtilization); pthread_mutex_destroy(&total_lock); //clean up mutex lock pthread_cond_destroy(&ok_to_add); return (-1); } // Optimize the regex pcreExtra = pcre_study(reCompiled, 0, &pcreErrorStr); /* pcre_study() returns NULL for both errors and when it can not optimize the regex. The last argument is how one checks for errors (it is NULL if everything works, and points to an error string otherwise. */ if (pcreErrorStr != NULL) { printf("ERROR: Could not study '%s': %s\n", aStrRegex, pcreErrorStr); pthread_join(systr, NULL); //join the system utilization thread if (systemUtilization > (long double) cpus) { //sanity check for HT systemUtilization = (long double) cpus; } printf("sys=%Lf\n", systemUtilization); //print info printf("cgrType2=%f\n", 0.0); printf("cgrType1=%f\n", 0.0); printf("cgrOther=%Lf\n", systemUtilization); pthread_mutex_destroy(&total_lock); //clean up mutex lock pthread_cond_destroy(&ok_to_add); return (-1); } /* end if */
{ "domain": "codereview.stackexchange", "id": 43029, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, multithreading, linux, status-monitoring", "url": null }
c, multithreading, linux, status-monitoring fp = popen("/var/bin/getProcs", "r"); //open getProcs to list the procs, this returns the cgroup ID and the type if (fp == NULL) { perror("/var/bin/getProcs"); pthread_join(systr, NULL); //join the system utilization thread if (systemUtilization > (long double) cpus) { //sanity check for HT systemUtilization = (long double) cpus; } printf("sys=%Lf\n", systemUtilization); //print info printf("cgrType2=%f\n", 0.0); printf("cgrType1=%f\n", 0.0); printf("cgrOther=%Lf\n", systemUtilization); pthread_mutex_destroy(&total_lock); //clean up mutex lock pthread_cond_destroy(&ok_to_add); return (-1); } jobCount = 0; while (fgets(buff, sizeof(buff), fp) != NULL) { sscanf(buff, "%[^,],%[^,]", jobs[jobCount].procid, jobs[jobCount].procType); jobCount++; } if (jobCount == 0) { pthread_join(systr, NULL); //join the system utilization thread if (systemUtilization > (long double) cpus) { systemUtilization = (long double) cpus; } printf("sys=%Lf\n", systemUtilization); //print info printf("cgrType2=%f\n", 0.0); printf("cgrType1=%f\n", 0.0); printf("cgrOther=%Lf\n", systemUtilization); pclose(fp); //close the command pthread_mutex_destroy(&total_lock); //destroy mutex lock pthread_cond_destroy(&ok_to_add); return (0); } pthread_t tid[jobCount]; // the thread identifiers, one for each job for (i = 0; i < jobCount; i++) { sample_struct *args = malloc(sizeof *args); //allocate memory for passing the argument struct to the threads args->procid = jobs[i].procid; //assign info in job array to the arg struct args->procType = jobs[i].procType; pthread_create(&tid[i], NULL, addSampletoTotal, args); //create the thread }
{ "domain": "codereview.stackexchange", "id": 43029, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, multithreading, linux, status-monitoring", "url": null }
c, multithreading, linux, status-monitoring pthread_join(systr, NULL); //join the system utilization thread for (i = 0; i < jobCount; i++) { pthread_join(tid[i], NULL); //finish threads } pthread_mutex_destroy(&total_lock); //destroy mutex lock pthread_cond_destroy(&ok_to_add); if (systemUtilization > (long double) cpus) { //sanity check for HT systemUtilization = (long double) cpus; } if (sum2 > (long double) cpus) { sum2 = (long double) cpus; } if (sum1 > (long double) cpus) { sum1 = (long double) cpus; } otherCPU = systemUtilization - sum2 - sum1; if (otherCPU < 0.0) { otherCPU = 0.0; } printf("sys=%Lf\n", systemUtilization); //print info printf("cgrType2=%Lf\n", sum2); printf("cgrType1=%Lf\n", sum1); printf("cgrOther=%Lf\n", otherCPU); pclose(fp); //close the command return (0); } int sampleCGroup(char procid[], char procType[]) { //open the cgroup cpustat file for the job based on the procid arg char *pidPath = malloc( strlen("/sys/fs/cgroup/cpuacct/cpuacct.stat/") + strlen(procid) + 1);//+1 for the zero-terminator if (pidPath == NULL) { perror("Could not allocate memory for str\n"); return (-1); } else { strcpy(pidPath, "/sys/fs/cgroup/cpuacct/"); //create the path to the cgroup info strcat(pidPath, procid); strcat(pidPath, "/cpuacct.stat"); } long double a[2], b[2]; long double loadavg = 0.0; int i; FILE *fp; for (i = 0; i < ITERATIONS; i++) { fp = fopen(pidPath, "r"); //first sample if (fp == NULL) { perror(pidPath); return (-1); } else { if (fscanf(fp, "%*4s %Lf %*6s %Lf", &a[0], &a[1]) != 2) { perror("Could not parse first cgroup CPU sample!\n"); return (-1); } fclose(fp); sleep(1); //let 1s go by }
{ "domain": "codereview.stackexchange", "id": 43029, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, multithreading, linux, status-monitoring", "url": null }
c, multithreading, linux, status-monitoring fp = fopen(pidPath, "r"); //second sample if (fp == NULL) { perror(pidPath); return (-1); } else { if (fscanf(fp, "%*4s %Lf %*6s %Lf", &b[0], &b[1]) != 2) { perror("Could not parse second cgroup CPU sample!\n"); return (-1); } fclose(fp); } loadavg += ((b[0] + b[1]) - (a[0] + a[1])); //delta } loadavg = (loadavg / (clk * ITERATIONS)); //calculate the CPU use by delta divided by clock ticks per one second times iterations free(pidPath); //free the memory allocated to the path variable //CRITICAL SECTION BEGIN pthread_mutex_lock(&total_lock); //lock mutex while (sumFlag == 0) { pthread_cond_wait(&ok_to_add, &total_lock); //wait on ok to add signal } pcreExecRet = pcre_exec(reCompiled, pcreExtra, procType, strlen(procType), // length of string 0, // Start looking at this point 0, // OPTIONS subStrVec, 30); // Length of subStrVec if (pcreExecRet > 0) { sum1 += loadavg; } else if (pcreExecRet == PCRE_ERROR_NOMATCH) { sum2 += loadavg; } else { sum2 += loadavg; //assume type2 if this fails perror("Could not determine type!\n"); } sumFlag = 1; pthread_cond_signal(&ok_to_add); //signal that it is ok to add pthread_mutex_unlock(&total_lock); //unlock mutex //CRITICAL SECTION END return 0; //success }
{ "domain": "codereview.stackexchange", "id": 43029, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, multithreading, linux, status-monitoring", "url": null }
c, multithreading, linux, status-monitoring return 0; //success } void *addSampletoTotal(void *args) { sample_struct *actual_args = args; //get the jobs argument struct sampleCGroup(actual_args->procid, actual_args->procType); //sample the cgroup for the job passed to the thread free(actual_args); //free the memory allocated to args pthread_exit(0); //exit thread } void *overallUtilization() { systemUtilization = getSystemUtilization(); //sample the cgroup for the job passed to the thread pthread_exit(0); //exit thread } long double getSystemUtilization(void) { long double a[3], b[3]; long double loadavg = 0.0; int i; FILE *fp; /* /proc/stat columns: * 1st column : user = normal processes executing in user mode * 2nd column : nice = niced processes executing in user mode * 3rd column : system = processes executing in kernel mode * 4th column : idle = twiddling thumbs * 5th column : iowait = waiting for I/O to complete * 6th column : irq = servicing interrupts * 7th column : softirq = servicing softirqs * */ for (i = 0; i < ITERATIONS; i++) { fp = fopen("/proc/stat", "r"); //first sample if (fp == NULL) { perror("/proc/stat"); return (-1); } else { if (fscanf(fp, "%*s %Lf %Lf %Lf", &a[0], &a[1], &a[2]) != 3 ) { perror("Could not parse first system CPU sample!\n"); return (-1); } fclose(fp); sleep(1); //let 1s go by } fp = fopen("/proc/stat", "r"); //second sample if (fp == NULL) { perror("/proc/stat"); return (-1); } else { if (fscanf(fp, "%*s %Lf %Lf %Lf", &b[0], &b[1], &b[2]) != 3) { perror("Could not parse second system CPU sample!\n"); return (-1); } fclose(fp); } loadavg += ((b[0] + b[1] + b[2]) - (a[0] + a[1] + a[2])); //delta }
{ "domain": "codereview.stackexchange", "id": 43029, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, multithreading, linux, status-monitoring", "url": null }
c, multithreading, linux, status-monitoring loadavg += ((b[0] + b[1] + b[2]) - (a[0] + a[1] + a[2])); //delta } loadavg = (loadavg / (clk * ITERATIONS)); //calculate the CPU use by delta divided by clock ticks per one second times iterations return loadavg; } int getOSVersion(void) { FILE *os; int version, checkVersion, patchLevel; os = fopen("/etc/SuSE-release", "r"); //first sample if (os == NULL) { perror("/etc/SuSE-release"); return (-1); } else { if (fscanf(os, "%*s %*s %*s %*s %d %*s VERSION = %d PATCHLEVEL = %d", &version, &checkVersion, &patchLevel) != 3) { perror("Unable to read SuSE release"); return -1; } fclose(os); } if (version == checkVersion) { return version; } else { return -1; } } int getCPUCount(void) { #if defined _SC_NPROCESSORS_ONLN { long int nprocs = sysconf (_SC_NPROCESSORS_ONLN); if (nprocs > 0) return nprocs; } #elif HAVE_SCHED_GETAFFINITY_LIKE_GLIBC /* glibc >= 2.3.4 */ { cpu_set_t set; if (sched_getaffinity (0, sizeof (set), &set) == 0) { unsigned long count; # ifdef CPU_COUNT /* glibc >= 2.6 has the CPU_COUNT macro. */ count = CPU_COUNT (&set); # else size_t i; count = 0; for (i = 0; i < CPU_SETSIZE; i++) if (CPU_ISSET (i, &set)) count++; # endif if (count > 0) return count; } } #endif return 1; } In particular I want to be sure this is safe multithreading. Answer: Global Variables I see this comment just prior to the declarations for the global variables: //TODO: localize?
{ "domain": "codereview.stackexchange", "id": 43029, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, multithreading, linux, status-monitoring", "url": null }
c, multithreading, linux, status-monitoring My answer would be yes. It is very difficult to read, write, debug and maintain programs that use global variables. Global variables can be modified by any function within the program and therefore require each function to be examined before making changes in the code. In C and C++ global variables impact the namespace and they can cause linking errors if they are defined in multiple files. The answers in this stackoverflow question provide a fuller explanation. Apply Best Practices Consistently In the function sampleCGroup() the result from malloc() is tested before it is used, however, in main() the result from malloc() is not tested before it is used. Return From main() Rather than hard code values in return from main, it would be better to use the system defined symbolic constants EXIT_SUCCESS and EXIT_FAILURE. There are 2 benefits to this, it makes the code more self documenting and it makes the code more portable (may not be necessary in this case). These symbolic constants are always defined in stdlib.h. DRY Code There is a programming principle called the Don't Repeat Yourself Principle sometimes referred to as DRY code. If you find yourself repeating the same code mutiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well. The following code is repeated many times in main(), it would be better to encapsulate it in a function: pthread_join(systr, NULL); //join the system utilization thread if (systemUtilization > (long double)cpus) { //sanity check for HT systemUtilization = (long double)cpus; } printf("sys=%Lf\n", systemUtilization); //print info printf("cgrType2=%f\n", 0.0); printf("cgrType1=%f\n", 0.0); printf("cgrOther=%Lf\n", systemUtilization); pthread_mutex_destroy(&total_lock); //clean up mutex lock pthread_cond_destroy(&ok_to_add);
{ "domain": "codereview.stackexchange", "id": 43029, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, multithreading, linux, status-monitoring", "url": null }
c, multithreading, linux, status-monitoring Complexity There are two functions in the code, main() and sampleCGroup() that are too complex (do too much). The code in these 2 functions should be broken into smaller functions. Functions that are too large or too complex are very difficult to understand, this makes it much harder to write, read, debug or maintain them. A general rule of thumb is that any function that is larger than a single screen in an editor or IDE is too large, a second indication of complexity is the level of indentation in the function. In both main() and sampleCGroup() it is important to note that part of what is making these functions larger is code repetition as discussed in DRY CODE. In the case of sampleGroup() some obvious functions are: char* make_pid_path(char procid[], char procType[]) { const char* pathHead = "/sys/fs/cgroup/cpuacct/"; const char* pathTail = "/cpuacct.stat"; char* pidPath = (char*) malloc( strlen(pathHead) + strlen(pathTail) + strlen(procid) + 1);//+1 for the zero-terminator if (pidPath == NULL) { perror("Could not allocate memory for str\n"); return NULL; } else { strcpy(pidPath, "/sys/fs/cgroup/cpuacct/"); //create the path to the cgroup info strcat(pidPath, procid); strcat(pidPath, "/cpuacct.stat"); } return pidPath; } bool parse_cGroup_CPU_sample(char* pidPath, const char* pass, long double result[2]) { FILE* fp = fopen(pidPath, "r"); if (fp == NULL) { perror(pidPath); return (-1); } else { if (fscanf(fp, "%*4s %Lf %*6s %Lf", &result[0], &result[1]) != 2) { char error_buffer[256]; sprintf(error_buffer, "Could not parse %s cgroup CPU sample!\n", pass); perror(error_buffer); return false; } fclose(fp); } return true; } long double getLoadAverage(char* pidPath) { long double a[2], b[2]; long double loadavg = 0.0;
{ "domain": "codereview.stackexchange", "id": 43029, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, multithreading, linux, status-monitoring", "url": null }
c, multithreading, linux, status-monitoring for (int i = 0; i < ITERATIONS; i++) { if (!parse_cGroup_CPU_sample(pidPath, "first", a)) { return -1; } else { sleep(1); } if (!parse_cGroup_CPU_sample(pidPath, "second", b)) { return -1; } loadavg += ((b[0] + b[1]) - (a[0] + a[1])); //delta } loadavg = (loadavg / (clk * ITERATIONS)); //calculate the CPU use by delta divided by clock ticks per one second times iterations return loadavg; } int sampleCGroup(char procid[], char procType[]) { //open the cgroup cpustat file for the job based on the procid arg char* pidPath = make_pid_path(procid, procType); if (pidPath == NULL) { return -1; } long double loadavg = getLoadAverage(pidPath); free(pidPath); //free the memory allocated to the path variable if (loadavg < 0) { return -1; } //CRITICAL SECTION BEGIN pthread_mutex_lock(&total_lock); //lock mutex while (sumFlag == 0) { pthread_cond_wait(&ok_to_add, &total_lock); //wait on ok to add signal } pcreExecRet = pcre_exec(reCompiled, pcreExtra, procType, strlen(procType), // length of string 0, // Start looking at this point 0, // OPTIONS subStrVec, 30); // Length of subStrVec if (pcreExecRet > 0) { sum1 += loadavg; } else if (pcreExecRet == PCRE_ERROR_NOMATCH) { sum2 += loadavg; } else { sum2 += loadavg; //assume type2 if this fails perror("Could not determine type!\n"); } sumFlag = 1; pthread_cond_signal(&ok_to_add); //signal that it is ok to add pthread_mutex_unlock(&total_lock); //unlock mutex //CRITICAL SECTION END return 0; //success }
{ "domain": "codereview.stackexchange", "id": 43029, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, multithreading, linux, status-monitoring", "url": null }
c, multithreading, linux, status-monitoring return 0; //success } As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program. Example of a simplified main() void report_utilization_and_clean_up_mutex(int cpus) { pthread_join(systr, NULL); //join the system utilization thread if (systemUtilization > (long double)cpus) { //sanity check for HT systemUtilization = (long double)cpus; } printf("sys=%Lf\n", systemUtilization); //print info printf("cgrType2=%f\n", 0.0); printf("cgrType1=%f\n", 0.0); printf("cgrOther=%Lf\n", systemUtilization); pthread_mutex_destroy(&total_lock); //clean up mutex lock pthread_cond_destroy(&ok_to_add); } void testOperationNotSupported() { int osVersion = getOSVersion(); if (osVersion <= 10) { systemUtilization = getSystemUtilization(); printf("sys=%Lf\n", systemUtilization); //cgroups are not supported on certain OS versions, so print the overall utilization and exit, otherwise, try to run pthread_mutex_destroy(&total_lock); //clean up mutex lock pthread_cond_destroy(&ok_to_add); exit(EXIT_SUCCESS); } }
{ "domain": "codereview.stackexchange", "id": 43029, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, multithreading, linux, status-monitoring", "url": null }
c, multithreading, linux, status-monitoring void performPcreOperations(int cpus) { aStrRegex = "proc_type1"; //type1 reCompiled = pcre_compile(aStrRegex, 0, &pcreErrorStr, &pcreErrorOffset, NULL); //compile the regex if (reCompiled == NULL) { printf("ERROR: Could not compile '%s': %s\n", aStrRegex, pcreErrorStr); report_utilization_and_clean_up_mutex(cpus); exit(EXIT_FAILURE); } // Optimize the regex pcreExtra = pcre_study(reCompiled, 0, &pcreErrorStr); /* pcre_study() returns NULL for both errors and when it can not optimize the regex. The last argument is how one checks for errors (it is NULL if everything works, and points to an error string otherwise. */ if (pcreErrorStr != NULL) { printf("ERROR: Could not study '%s': %s\n", aStrRegex, pcreErrorStr); report_utilization_and_clean_up_mutex(cpus); exit(EXIT_FAILURE); } /* end if */ } struct job_struct* getJobs(int cpus, int* jobCount) { char buff[1024]; struct job_struct* jobs = (job_struct*)calloc(cpus, sizeof(*jobs)); //initially size the array to be the number of CPUs if (jobs == NULL) { fprintf(stderr, "Failed to allocate %d job structures in main()\n", cpus); exit(EXIT_FAILURE); } *jobCount = 0; FILE* fp = popen("/var/bin/getProcs", "r"); //open getProcs to list the procs, this returns the cgroup ID and the type if (fp == NULL) { perror("/var/bin/getProcs"); report_utilization_and_clean_up_mutex(cpus); return (EXIT_FAILURE); } int ljobCount = 0; while (fgets(buff, sizeof(buff), fp) != NULL) { sscanf(buff, "%[^,],%[^,]", jobs[ljobCount].procid, jobs[ljobCount].procType); ljobCount++; } *jobCount = ljobCount; return jobs; } int main(void) { int jobCount = 0; testOperationNotSupported(); int cpus = getCPUCount(); clk = CLK_TIME_PER_SECOND; struct job_struct* jobs = getJobs(cpus, &jobCount);
{ "domain": "codereview.stackexchange", "id": 43029, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, multithreading, linux, status-monitoring", "url": null }
c, multithreading, linux, status-monitoring struct job_struct* jobs = getJobs(cpus, &jobCount); sumFlag = 1; //condition variable for mutex pthread_t systr; //thread id for overall system utilization, note this should only execute on certain versions, the conditional above should have returned if not pthread_create(&systr, NULL, overallUtilization, NULL); //create the thread performPcreOperations(cpus); if (jobCount == 0) { report_utilization_and_clean_up_mutex(cpus); return (EXIT_SUCCESS); } pthread_t tid[jobCount]; // the thread identifiers, one for each job for (int i = 0; i < jobCount; i++) { sample_struct* args = malloc(sizeof * args); //allocate memory for passing the argument struct to the threads args->procid = jobs[i].procid; //assign info in job array to the arg struct args->procType = jobs[i].procType; pthread_create(&tid[i], NULL, addSampletoTotal, args); //create the thread } pthread_join(systr, NULL); //join the system utilization thread for (int i = 0; i < jobCount; i++) { pthread_join(tid[i], NULL); //finish threads } pthread_mutex_destroy(&total_lock); //destroy mutex lock pthread_cond_destroy(&ok_to_add); if (systemUtilization > (long double) cpus) { //sanity check for HT systemUtilization = (long double)cpus; } if (sum2 > (long double)cpus) { sum2 = (long double)cpus; } if (sum1 > (long double)cpus) { sum1 = (long double)cpus; } otherCPU = systemUtilization - sum2 - sum1; if (otherCPU < 0.0) { otherCPU = 0.0; } printf("sys=%Lf\n", systemUtilization); //print info printf("cgrType2=%Lf\n", sum2); printf("cgrType1=%Lf\n", sum1); printf("cgrOther=%Lf\n", otherCPU); pclose(fp); //close the command return (EXIT_SUCCESS); } There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states:
{ "domain": "codereview.stackexchange", "id": 43029, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, multithreading, linux, status-monitoring", "url": null }
c, multithreading, linux, status-monitoring that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.
{ "domain": "codereview.stackexchange", "id": 43029, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, multithreading, linux, status-monitoring", "url": null }
c, linked-list, hash-map Title: Hash table library implementation Question: I wrote my own implementation of generic hash table. I’m using linked list to resolve collision problem. I want to share my code with you and get your opinion about it, and if there are any advice or optimisations that you can point to. HashTable.h file /** * @author Abdelhakim RAFIK * @version v1.0.1 * @license MIT License * @Copyright Copyright (c) 2021 Abdelhakim RAFIK * @date Feb 2021 */ #include <stdlib.h> #include <string.h> /* hash table node definition */ typedef struct _node { unsigned char *key; void *value; struct _node *next; } ht_node_t; /* hash table definition */ typedef struct { unsigned int size; unsigned int count; ht_node_t **items; } ht_table_t; /** * create new hash table with given size * @param size items table size * @return pointer to creates hash table */ ht_table_t* ht_create(int size); /** * create items table index from given key * @param key key value * @return index of items table between 0 and table size-1 */ unsigned int ht_hash(unsigned int maxSize, unsigned char *key); /** * inset new element to hash table by given key * @param table pointer to created hash table * @param key key for value to insert * @param value element to be inserted * @param size size of element in bytes * @return 1: inserted successfully * 0: error occured while inserting value */ unsigned char ht_insert(ht_table_t* table, unsigned char *key, void *value, size_t size); /** * find associated node to given key * @param table pointer to hash table * @param key key associated to the node * @param index index of found node in items table * @param prev pointer to previous node * @return node pointer if found or NULL otherwise */ ht_node_t* ht_find_node(ht_table_t* table, unsigned char *key, unsigned int *index, ht_node_t **prev);
{ "domain": "codereview.stackexchange", "id": 43030, "lm_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, linked-list, hash-map", "url": null }
c, linked-list, hash-map /** * find value in hash table by given key * @param table pointer to hash table * @param key key of the value searching */ void* ht_find(ht_table_t* table, unsigned char *key); /** * delete value by given key * @param table pointer to hash table * @param key value's key to delete * @return 1: deleted successfully * 0: error occured while deleting the value */ unsigned char ht_delete(ht_table_t* table, unsigned char *key); /** * delete all table items * @param table pointer to hash table */ unsigned char ht_delete_all(ht_table_t* table); /** * free allocated memory for given hash table * @param table pointer to hash table */ unsigned char ht_free(ht_table_t* table); HashTable.c file /** * @author Abdelhakim RAFIK * @version v1.0.1 * @license MIT License * @Copyright Copyright (c) 2021 Abdelhakim RAFIK * @date Feb 2021 */ #include "hashTable.h" /** * create new hash table with given size * @param size items table size * @return pointer to creates hash table */ ht_table_t* ht_create(int size) { // check given table items size, should be greather than 0 if(size <= 0) return NULL; // create new hash table ht_table_t* table = (ht_table_t*) malloc(sizeof(ht_table_t)); table->size = size; table->count = 0; // create items table as pointer's table to nodes table->items = (ht_node_t**) malloc(size * sizeof(ht_node_t*)); // set all items pointers to NULL for(int i=0; i<size; ++i) table->items[i] = NULL; // return created table return table; }
{ "domain": "codereview.stackexchange", "id": 43030, "lm_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, linked-list, hash-map", "url": null }
c, linked-list, hash-map // return created table return table; } /** * create items table index from given key * @param key key value * @return index of items table between 0 and table size-1 */ unsigned int ht_hash(unsigned int maxSize, unsigned char *key) { unsigned int hashedKey = 0; // create hash from key for(; *key != '\0'; ++key) hashedKey = (hashedKey * 19 + *key) % maxSize; // return created index return hashedKey; }
{ "domain": "codereview.stackexchange", "id": 43030, "lm_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, linked-list, hash-map", "url": null }
c, linked-list, hash-map /** * inset new element to hash table by given key * @param table pointer to created hash table * @param key key for value to insert * @param value element to be inserted * @param size size of element in bytes * @return 1: inserted successfully * 0: error occured while inserting value */ unsigned char ht_insert(ht_table_t* table, unsigned char *key, void *value, size_t size) { // check table and key are not NULL if(!table || !key) return 0; // index from key unsigned int index; // check whether the element with associated key already in table and get generated index ht_node_t *newNode = ht_find_node(table, key, &index, NULL); if(newNode) { // reallocate memory for new content value newNode->value = (void*) realloc(newNode->value, size); // copy value to allocated node value memory memcpy(newNode->value, value, size); } else { // create new node newNode = (ht_node_t*) malloc(sizeof(ht_node_t)); // create node key and copy it's value newNode->key = (char*) malloc(strlen(key) + 1); strcpy(newNode->key, key); // create node value memory newNode->value = (void*) malloc(size); // copy value to allocated node value memory memcpy(newNode->value, value, size); // if index position is not empty link nodes if(table->items[index] != NULL) newNode->next = table->items[index]; else newNode->next = NULL; // add created node to items table table->items[index] = newNode; // increment table count ++table->count; } return 1; }
{ "domain": "codereview.stackexchange", "id": 43030, "lm_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, linked-list, hash-map", "url": null }
c, linked-list, hash-map /** * find associated node to given key * @param table pointer to hash table * @param key key associated to the node * @param index index of found node in items table * @param prev pointer to previous node * @return node pointer if found or NULL otherwise */ ht_node_t* ht_find_node(ht_table_t* table, unsigned char *key, unsigned int *index, ht_node_t **prev) { // get index for given key unsigned int _index = ht_hash(table->size, key); if(index) *index = _index; // get head items at index position ht_node_t* currentNode = table->items[_index]; ht_node_t* _prev = NULL; // search in linked array nodes until a NULL pointer while(currentNode) { if(strcmp(currentNode->key, key) == 0) break; // go to next linked node _prev = currentNode; currentNode = currentNode->next; } if(currentNode) { if(prev) *prev = _prev; // return found node return currentNode; } // value associated with the key not found return NULL; } /** * find value in hash table by given key * @param table pointer to hash table * @param key key of the value searching */ void* ht_find(ht_table_t* table, unsigned char *key) { // check table and key are not NULL if(!table || !key) return NULL; // get associated node to key ht_node_t *currentNode = ht_find_node(table, key, NULL, NULL); // node not found if(!currentNode) return NULL; // return node's value return currentNode->value; } /** * delete value by given key * @param table pointer to hash table * @param key value's key to delete * @return 1: deleted successfully * 0: error occured while deleting the value */ unsigned char ht_delete(ht_table_t* table, unsigned char *key) { // check table and key are not NULL if(!table || !key) return 0;
{ "domain": "codereview.stackexchange", "id": 43030, "lm_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, linked-list, hash-map", "url": null }
c, linked-list, hash-map ht_node_t *prevNode; unsigned int index; // get associated node to key ht_node_t* currentNode = ht_find_node(table, key, &index, &prevNode); // node not found if(!currentNode) return 0; // set previous node next element to current node next element if(currentNode->next != NULL) { if(prevNode != NULL) prevNode->next = currentNode->next; else table->items[index] = currentNode->next; } else if(prevNode == NULL) table->items[index] = NULL; // delete node free(currentNode->key); free(currentNode->value); free(currentNode); // decrement table count --table->count; return 1; } /** * delete all table items * @param table pointer to hash table */ unsigned char ht_delete_all(ht_table_t* table) { // check table is not NULL if(!table) return 0; // delete table items if not empty if(table->count != 0) { ht_node_t *currentNode = NULL, *nextNode = NULL; for (int i=0; i<table->size; ++i) { // get next node nextNode = table->items[i]; while(nextNode) { currentNode = nextNode; nextNode = currentNode->next; // free memory allocated by current node free(currentNode->key); free(currentNode->value); free(currentNode); } table->items[i] = NULL; } // set table count to 0 table->count = 0; } } /** * free allocated memory for given hash table * @param table pointer to hash table */ unsigned char ht_free(ht_table_t* table) { // check table is not NULL if(!table) return 0; // delete table items if not empty if(table->count != 0) ht_delete_all(table); // free table parts free(table->items); free(table); return 1; }
{ "domain": "codereview.stackexchange", "id": 43030, "lm_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, linked-list, hash-map", "url": null }
c, linked-list, hash-map Answer: I see a lot of thought went into this code. License As someone looking for a hash-table implementation, I would consider a clear MIT license an important point towards your implementation. Interface This is well done, with comments where they are most useful. As a user looking at your interface, I have some questions. return function comments ht_table_t* ht_create int size should be an unsigned type like size_t unsigned int ht_hash the hash value should be transparent, return success, (as int or boolean, depending on the version of C); maxSize is undocumented and what is that? (Ed: I see now, this is the hash function; consider a static function; it is internal to your implementation.) unsigned char ht_insert int or boolean; don't say what happens on collision ht_node_t* ht_find_node how do I deal with a ht_node_t? I assume index and prev are set, but I do not care about the internal representation void* ht_find good name, documentation unsigned char ht_delete int or boolean unsigned char ht_delete_all what happens to the memory? this causes a compile error; should be void unsigned char ht_free what does the return mean?
{ "domain": "codereview.stackexchange", "id": 43030, "lm_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, linked-list, hash-map", "url": null }
c, linked-list, hash-map unsigned char ht_free what does the return mean? I suggest a few helper static functions, internal to the implementation (private), and have the public functions return less. Code I see "HashTable.h", but in code, it's "hashTable.h". "@Copyright" doesn't fit with the other, lower-case tags. These case-inconsistencies may be bugs. In ht_create, (ht_table_t*)malloc(sizeof(ht_table_t)) could be malloc(sizeof *table). The cast is confusing, except where you want to port to C++, (as you seem to here.) If you want to specify a totally opaque type, then you should declare it in header as something like struct ht_table_t; and leave the implementation to the C file. You set all pointers to null appropriately. You don't check that memory allocations work, so you open yourself up to undefined behaviour; practically, which could be a segfault or something worse if the memory allocation fails. Because the parameter for the requested memory size comes from outside your module, and is something you don't control, I would be especially careful about checking. ht_hash should be private, static. A lot of unnecessary work could be saved by taking the remainder outside the loop. In ht_insert, you trust users a lot to take the size accurately, every time. You accept unsigned char *key, but this should be char * for consistency, and library functions depend on it. Three memory allocations, where one will do, slows down your code. However, be very careful about aligning strings.
{ "domain": "codereview.stackexchange", "id": 43030, "lm_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, linked-list, hash-map", "url": null }
java, recursion, matrix Title: Given a matrix return true if it contains the Identity matrix (by recursion) Question: I need to write recursive static method with given 3 parameters the method will return true if the sub matrix with the size of (int size) which the left corner is mat[x][x] is the identity matrix picture for example: It was part of my exam and I barely got any points,this is what i wrote: public static boolean isIdentity(int[][] mat,int x,int size) { if(x > mat.length-1 || x > mat[0].length-1 || size < 0) return false; if(size > 0) if(mat[x+1][x] != 0 || mat[x][x+1] != 0 || mat[x][x-1] != 0 || mat[x-1][x] != 0) return false; if(size == 0) return true; if(mat[x][x]== 1) { return(isIdentity(mat,x+1,size-1)); } return isIdentity(mat,x+1,size-1); } My question: I didn't use override and regret it, but can I make this work without override? My thought process was checking the diagonal for 1. If its not 1 return false. If its 1 continue the recursion with x+1(keep moving on the diagonal), and I'm not sure I used the size in the optimal way. what I wrote worked for some tests but got OutOfBoundsException for some values. Can I fix it?
{ "domain": "codereview.stackexchange", "id": 43031, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, recursion, matrix", "url": null }
java, recursion, matrix Answer: First not using @Override is fine! If there was no interface. Also @Override is used if somewhere there was a method isIdentity given. And with a static method, a stand-alone function there cannot be an override. An other remark, for the real life: follow conventions, use spaces and braces, and indentions of 4 spaces. If you have got hundred sources, are customized typing in one convention, the hundred and first source cannot be different. You will be irritated if that source comes from your new colleague. Validation Where you immediately went wrong is to validate the input. Recursion checks the input on the simple case(s) and then does the recursion on the remaining difficult but smaller problem. Add validation, check on the input parameters, best in a non-recursive function calling the recursive one. Or do it at the end. This is a practical tip, as thinking on validation takes some effort. And here validation is much: mat.length != 0, mat[0].length != 0 size >= 0, x >= 0, x <= mat.length, x <= mat[0].length x + size <= mat.length, x + size <= mat[0].length You were not perfect on the input validation, but let's take a look at the real algorithm. The algorithm they probably desired Without validation. public static boolean isIdentity(int[][] mat, int x, int size) { if (size == 0) { return true; // A matter of definition, false? } if (mat[x][x] != 1) { return false; } for (int i = 1; i < size; ++i) { if (mat[x][x + i] != 0 || mat[x + i][x] != 0) { return false; } } return size == 1 || isIdentity(mat, x + 1, size - 1); } The above checks 1000.. 0xxx.. 0xxx.. 0xxx.. :.....
{ "domain": "codereview.stackexchange", "id": 43031, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, recursion, matrix", "url": null }
java, recursion, matrix The above checks 1000.. 0xxx.. 0xxx.. 0xxx.. :..... Where xxx is left to the recursion. For 1 the check is simple. For the zeros it went wrong. You only did [x±1][x] and [x][x±1] which is wrong. I needed a for loop, from 1 upto size - 1. The recursion is linear, moving one step on the diagon as you did. But only one single recursive call needed. Here one could have done the last return as if (size == 1) { return true; } return isIdentity(mat, x + 1, size - 1); Evaluation Your algorithm did neither have an easy and full validation as far as I can see. In general not so problematic. Your algorithm however contains errors, and just on the recursion relevant code. Loop holes, code lawyer If one of the requirements was not to use loops, like the for above, one would have needed an extra parameter (i). Tips Input validation can become verbose, especially in the 2 dimensions of matrices. Doing it later, gives to you a head start, and prevents thinking stress. However do it early when it is a no-brainer. Then it may help. Make it depictable, clear, my 1000.. etcetera helps. Then it is a bit of seeing where if (size == 1) is applicated, here late, as the checks on the zeros is independent on the size, and must be done always. Keep it simple.
{ "domain": "codereview.stackexchange", "id": 43031, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, recursion, matrix", "url": null }
c++, stack, pointers Title: Generic stack data structure using linked list and smart pointers Question: I have decided to rewrite what I did here, following the suggestions to use smart pointers. I will rewrite the other data structures as well using smart pointers where appropriate. I just want to see how my code stands now, I am sure there are still areas I need to improve or fix. I again want to thank this community in their effort in evaluating my code, I really appreciate it and I believe it is slowly but surely taking my coding skills to the next level. Here is my header file: #ifndef Stack_h #define Stack_h #include <iterator> #include <memory> template <class T> class Stack { struct Node { T data; std::unique_ptr<Node> next = nullptr; template<typename... Args, typename = std::enable_if_t<std::is_constructible<T, Args&&...>::value>> explicit Node(std::unique_ptr<Node>&& next, Args&&... args) noexcept(std::is_nothrow_constructible<T, Args&&...>::value) : data{ std::forward<Args>(args)... }, next{ std::move(next) } {} // disable if noncopyable<T> for cleaner error msgs explicit Node(const T& x, std::unique_ptr<Node>&& p = nullptr) : data(x) , next(std::move(p)) {} // disable if nonmovable<T> for cleaner error msgs explicit Node(T&& x, std::unique_ptr<Node>&& p = nullptr) : data(std::move(x)) , next(std::move(p)) {} }; std::unique_ptr<Node> front = nullptr; void do_unchecked_pop() { front = std::move(front->next); } public: // Constructors Stack() = default; // empty constructor Stack(Stack const &source); // copy constructor // Rule of 5 Stack(Stack &&move) noexcept; // move constructor Stack& operator=(Stack &&move) noexcept; // move assignment operator ~Stack();
{ "domain": "codereview.stackexchange", "id": 43032, "lm_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++, stack, pointers", "url": null }
c++, stack, pointers // Overload operators Stack& operator=(Stack const &rhs); // Create an iterator class class iterator; iterator begin(); iterator end(); iterator before_begin(); // Create const iterator class class const_iterator; const_iterator cbegin() const; const_iterator cend() const; const_iterator begin() const; const_iterator end() const; const_iterator before_begin() const; const_iterator cbefore_begin() const; // Member functions template<typename... Args> iterator emplace(const_iterator pos, Args&&... args); void swap(Stack& other) noexcept; bool empty() const {return front == nullptr;} int size() const; void push(const T& theData); void push(T&& theData); T& top(); const T& top() const; void pop(); }; template <class T> class Stack<T>::iterator { Node* node = nullptr; bool before_begin = false; public: friend class Stack<T>; using iterator_category = std::forward_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = T * ; using reference = T & ; operator const_iterator() const noexcept { return const_iterator{ node }; } iterator(Node* node = nullptr, bool before = false) : node{ node }, before_begin{ before } {} bool operator!=(iterator other) const noexcept; bool operator==(iterator other) const noexcept; T& operator*() const { return node->data; } T& operator->() const { return &node->data; } iterator& operator++(); iterator operator++(int); }; template <class T> class Stack<T>::const_iterator { Node* node = nullptr; bool before_begin = false; public: friend class Stack<T>; using iterator_category = std::forward_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = const T * ; using reference = const T & ;
{ "domain": "codereview.stackexchange", "id": 43032, "lm_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++, stack, pointers", "url": null }
c++, stack, pointers const_iterator() = default; const_iterator(Node* node, bool before = false) : node{ node }, before_begin{ before } {} bool operator!=(const_iterator other) const noexcept; bool operator==(const_iterator other) const noexcept; const T& operator*() const { return node->data; } const T& operator->() const { return &node->data; } const_iterator& operator++(); const_iterator operator++(int); }; template <class T> Stack<T>::Stack(Stack<T> const& source) { try { for(auto loop = source.front.get(); loop != nullptr; loop = loop->next.get()) push(loop->data); } catch (...) { while(front != nullptr) do_unchecked_pop(); throw; } } template <class T> Stack<T>::Stack(Stack&& move) noexcept { move.swap(*this); } template <class T> Stack<T>& Stack<T>::operator=(Stack&& move) noexcept { move.swap(*this); return *this; } template <class T> Stack<T>::~Stack() { while(front != nullptr) { do_unchecked_pop(); } } template <class T> Stack<T>& Stack<T>::operator=(Stack const& rhs) { Stack copy(rhs); swap(copy); return *this; } template <class T> void Stack<T>::swap(Stack& other) noexcept { using std::swap; swap(front,other.front); } template <class T> template <typename... Args> typename Stack<T>::iterator Stack<T>::emplace(const_iterator pos, Args&&... args) { if (pos.before_begin) { emplace_front(std::forward<Args>(args)...); return begin(); } if (pos.node->next) { pos.node->next = std::make_unique<Node>(std::move(pos.node->next), std::forward<Args>(args)...); // Creating a new node that has the old next pointer with the new value and assign it to the next pointer of the current node return { pos.node->next.get() }; } } // Free function template <typename T> void swap(Stack<T>& a, Stack<T>& b) noexcept { a.swap(b); }
{ "domain": "codereview.stackexchange", "id": 43032, "lm_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++, stack, pointers", "url": null }
c++, stack, pointers template <class T> int Stack<T>::size() const { int size = 0; for (auto current = front.get(); current != nullptr; current = current->next.get()) size++; return size; } template <class T> void Stack<T>::push(const T& theData) { std::unique_ptr<Node> newNode = std::make_unique<Node>(theData); if(front) { newNode->next = std::move(front); } front = std::move(newNode); } template <class T> void Stack<T>::push(T&& theData) { std::unique_ptr<Node> newNode = std::make_unique<Node>(std::move(theData)); if(front) { newNode->next = std::move(front); } front = std::move(newNode); } template <class T> T& Stack<T>::top() { if(!empty()) { return front->data; } else { throw std::out_of_range("The stack is empty!"); } } template <class T> const T& Stack<T>::top() const { if(!empty()) { return front->data; } else { throw std::out_of_range("The stack is empty!"); } } template <class T> void Stack<T>::pop() { if(empty()) { throw std::out_of_range("The stack is empty!"); } do_unchecked_pop(); } // Iterator Implementaion//////////////////////////////////////////////// template <class T> typename Stack<T>::iterator& Stack<T>::iterator::operator++() { if (before_begin) before_begin = false; else node = node->next.get(); return *this; } template<typename T> typename Stack<T>::iterator Stack<T>::iterator::operator++(int) { auto copy = *this; ++*this; return copy; } template<typename T> bool Stack<T>::iterator::operator==(iterator other) const noexcept { return node == other.node && before_begin == other.before_begin; } template<typename T> bool Stack<T>::iterator::operator!=(iterator other) const noexcept { return !(*this == other); } template<class T> typename Stack<T>::iterator Stack<T>::begin() { return front.get(); }
{ "domain": "codereview.stackexchange", "id": 43032, "lm_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++, stack, pointers", "url": null }
c++, stack, pointers template<class T> typename Stack<T>::iterator Stack<T>::begin() { return front.get(); } template<class T> typename Stack<T>::iterator Stack<T>::end() { return {}; } template <class T> typename Stack<T>::iterator Stack<T>::before_begin() { return { front.get(), true }; } // Const Iterator Implementaion//////////////////////////////////////////////// template <class T> typename Stack<T>::const_iterator& Stack<T>::const_iterator::operator++() { if (before_begin) before_begin = false; else node = node->next.get(); return *this; } template<typename T> typename Stack<T>::const_iterator Stack<T>::const_iterator::operator++(int) { auto copy = *this; ++*this; return copy; } template<typename T> bool Stack<T>::const_iterator::operator==(const_iterator other) const noexcept { return node == other.node && before_begin == other.before_begin; } template<typename T> bool Stack<T>::const_iterator::operator!=(const_iterator other) const noexcept { return !(*this == other); } template <class T> typename Stack<T>::const_iterator Stack<T>::begin() const { return front.get(); } template <class T> typename Stack<T>::const_iterator Stack<T>::end() const { return {}; } template <class T> typename Stack<T>::const_iterator Stack<T>::cbegin() const { return begin(); } template <class T> typename Stack<T>::const_iterator Stack<T>::cend() const { return end(); } template <class T> typename Stack<T>::const_iterator Stack<T>::before_begin() const { return { front.get(), true }; } template <class T> typename Stack<T>::const_iterator Stack<T>::cbefore_begin() const { return before_begin(); } #endif /* Stack_h */ Here is the test cpp file I used: #define CATCH_CONFIG_MAIN #include "catch.h" #include "Stack.h" TEST_CASE("An empty stack", "[Stack]") { Stack<int> stack; REQUIRE(stack.empty()); REQUIRE(stack.size() == 0u); SECTION("inserting an element makes the map not empty") { stack.push(2);
{ "domain": "codereview.stackexchange", "id": 43032, "lm_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++, stack, pointers", "url": null }
c++, stack, pointers SECTION("inserting an element makes the map not empty") { stack.push(2); REQUIRE(!stack.empty()); } SECTION("inserting an element increases the size") { stack.push(4); REQUIRE(stack.size() == 1u); } SECTION("pop on empty stack does nothing") { stack.push(6); stack.pop(); REQUIRE(stack.size() == 0); REQUIRE(stack.empty()); } } TEST_CASE("Create a stack list with multiple elements", "[Stack]") { Stack<int> stack; stack.push(2); stack.push(4); stack.push(6); stack.push(8); stack.push(10); static auto init_values = std::vector<int>{2, 4, 6, 8, 10}; REQUIRE(stack.size() == init_values.size()); REQUIRE(!stack.empty()); REQUIRE(std::distance(stack.begin(), stack.end()) == init_values.size()); //REQUIRE(std::equal(stack.begin(), stack.end(), init_values.begin())); SECTION("Can find elements with std::find") { auto found = std::find(std::begin(stack), std::end(stack), 4); REQUIRE(found != std::end(stack)); REQUIRE(*found == 4); } SECTION("pop removes last element") { stack.pop(); REQUIRE(stack.top() == 8); REQUIRE(stack.size() == 4); } SECTION("copy construction") { auto second_list = stack; REQUIRE(stack.size() == init_values.size()); //REQUIRE(std::equal(stack.begin(), stack.end(), init_values.begin())); REQUIRE(second_list.size() == stack.size()); //REQUIRE(std::equal(second_list.begin(), second_list.end(), stack.begin())); } SECTION("copy assignment") { auto second_list = Stack<int>{}; second_list = stack; REQUIRE(stack.size() == init_values.size()); //REQUIRE(std::equal(stack.begin(), stack.end(), init_values.begin())); REQUIRE(second_list.size() == stack.size()); //REQUIRE(std::equal(second_list.begin(), second_list.end(), stack.begin())); }
{ "domain": "codereview.stackexchange", "id": 43032, "lm_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++, stack, pointers", "url": null }
c++, stack, pointers SECTION("move construction leaves original list in empty state") { auto second_list = Stack<int>{ std::move(stack) }; REQUIRE(stack.empty()); REQUIRE(second_list.size() == init_values.size()); // REQUIRE(std::equal(second_list.begin(), second_list.end(), init_values.begin())); } } For tests, I used the Catch2 testing framework. I guess the only problem I had was the std::equal() but other than that I am satisfied with the tests it passed. Answer: int size() const; Why not a std::size_t like the standard containers? Using a signed type here gives warnings when compiling the tests, and is likely to be a nuisance for other users. Making it unsigned gives a different signed/unsigned comparison, here: REQUIRE(std::distance(stack.begin(), stack.end()) == init_values.size()); But we can make an equivalent test that requires no cast: REQUIRE(std::next(stack.begin(), init_values.size()) == stack.end()); There's complication (and an iterator member!) for before_begin, but I don't see that used in any of the implementation, nor tested as part of the public interface. We can get rid of that, and just work with the usual range of valid and one-past-the end. We can (from C++20 onwards) default the iterators' == and != operators. The use of do_unchecked_pop to ensure that destructor and failed-construction don't throw shows that you've thought about these cases properly. That said, I thought that part of the point of using a smart-pointer to Node was that it should clean up properly without needing to write any code here? Is there a good reason we can't emplace at the end of the list? We test pos.node->next, but I think we should instead be checking that pos.node is valid (and its next can perfectly well be a null pointer). This suggests we're missing some tests.
{ "domain": "codereview.stackexchange", "id": 43032, "lm_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++, stack, pointers", "url": null }
c++, stack, pointers This implementation differs from std::stack in a few ways. Notably, its size() has linear complexity, which will likely catch out users who would normally expect it to execute in constant time.
{ "domain": "codereview.stackexchange", "id": 43032, "lm_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++, stack, pointers", "url": null }
python, algorithm, recursion, binary-search-tree Title: Binary Search Tree - My own version of delete function Question: Well, I am recently learning data structures and algorithms and I came across the Binary search tree and decided to first time use my own logic to make the delete function. I have not come across a code similar to mine in the delete function, although it is possible someone already used this logic, please share if you find any. I have tried as simply as I can to explain my logic in comments and docstrings for others to understand. try using code preview plugins or use the https://pythontutor.com/visualize.html#mode=edit website to visualize the rotation because this is the most complex logic I have ever created. My goal was to make a delete function in BST in the least line of code as possible as I have seen people using over 14 if statements for this function. In my logic, I replaced the node that I want to delete with its right child node or replaces it with left node if it only has left child node or if it has no child it will recursively look for the node and delete it. I have explained it in the code as well. I welcome constructive criticism and if someone can improve it please feel free to do that as well. I have tested it so far by inserting numbers randomly and also using large input data as well. So far the code is working. I will be waiting for your feedback, thank you. The code is as follows: class BST: def __init__(self, data): """This is a constructor Args: data (integer): This is the main root node of binary search tree self.lchild (integer): This is the left child node self.rchild (integer): This is the Right child node """ self.root = data self.lchild = None self.rchild = None def insert(self, data): """This is an insert function which is using recursion to insert new nodes into there respective places.
{ "domain": "codereview.stackexchange", "id": 43033, "lm_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, algorithm, recursion, binary-search-tree", "url": null }
python, algorithm, recursion, binary-search-tree Args: data (integer): This is a node """ # if root node is None insert the node if not self.root: self.root = data # we are ignore the duplicate values by just returning the function here if self.root == data: return else: if data < self.root: # we are caling the function recursively here to create instances of nodes if self.lchild: self.lchild.insert(data) else: # creating an object inside the left hand side of the tree self.lchild = BST(data) else: if self.rchild: self.rchild.insert(data) else: # creating an object inside the right hand side of the tree self.rchild = BST(data) def search(self, data): """This is a search function to find the desired node again using same recursive technique that we used in insert Args: data (integer): The numbder that you want to search """ if data == self.root: print(f"number {self.root} is found ") else: if data < self.root: if self.lchild: self.lchild.search(data) else: print(f"number not found") else: if self.rchild: self.rchild.search(data) else: print(f"number not found") def preorder(self): """This function will print all the nodes in pre order, in this root node comes first then left child and right child. """ print(self.root) if self.lchild: self.lchild.preorder() if self.rchild: self.rchild.preorder() def in_order(self): """This function will print all the nodes in sequence, first comes the smallest node and then root node and then all the larger numbers than root node. """ if self.lchild: self.lchild.in_order() print(self.root)
{ "domain": "codereview.stackexchange", "id": 43033, "lm_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, algorithm, recursion, binary-search-tree", "url": null }
python, algorithm, recursion, binary-search-tree print(self.root) if self.rchild: self.rchild.in_order() def del_node(self, data): """This is a delete function to delete the node from the tree, this function is using the logic in which we always replace the node we are going to delete with the right child of that node, if it has one. otherwise with the left child node or if it do not have any child nodes then simply delete the node. Args: data (integer): The node we want to delete """ if data == self.root: if self.rchild: self.root = ( self.rchild.root ) # we are replacing the root node with its right child node (self.rchild.root) self.rchild = ( self.rchild.rchild ) # here we are replacing the right node with the right node of the instance # we want to delete(I know it sounds complex but could not find a more simpler way to explain it) elif self.lchild: self.root = ( self.lchild.root ) # same logic that we did with right child node in case ifit do not have a right child self.lchild = self.lchild.lchild else: # using recursion here to keep traveling through nodes until it finds the node that we want # to delete and print "data not found" if node is not present in the tree. if data < self.root: if self.lchild: self.lchild.del_node(data) # if the node that i want to delete have no child nodes this if statement will excute on all the instances where it traveled through to find the node that I wanted to delete if data == self.lchild.root: self.lchild = None else: print("data not found") else: if self.rchild: self.rchild.del_node(data)
{ "domain": "codereview.stackexchange", "id": 43033, "lm_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, algorithm, recursion, binary-search-tree", "url": null }
python, algorithm, recursion, binary-search-tree else: if self.rchild: self.rchild.del_node(data) # if the node that i want to delete have no child nodes this if statement will excute on all the instances where it traveled through to find the node that I wanted to delete if data == self.rchild.root: self.rchild = None else: print("data not found")
{ "domain": "codereview.stackexchange", "id": 43033, "lm_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, algorithm, recursion, binary-search-tree", "url": null }
python, algorithm, recursion, binary-search-tree else: print("data not found") Answer: Address more fundamental issues before worrying about delete A BST should be able to hold false values. For example, zero. Instead of if not self.root, use if self.value is not None. [In this review I adopt the suggested renaming, changing root to value, and I extend the idea by changing data to val.] Adopt a consistent naming convention. You have preorder() but not inorder(). You have insert() but not delete(). An empty BST should be possible. Currently, your __init__() method doesn't support the most basic of behaviors: a user should be able to do this: b = BST(). Data oriented classes should return data, not print. The search() method should return a boolean; preorder() and inorder() methods should return or yield values. A BST should not allow a value of None. A ValueError should be raised if the caller tries to insert or search for None. The code is needlessly repetitive. In most cases, this occurs because you write nearly equivalent code for the left and right sides. But that repetition can be eliminated with just a little bit of generalization. A BST should be able to hold lots of data. Because you are using recursion, you will quickly run up against Python's maximum recursion depth (1000 by default). Iteration is a better strategy for a BST. For example, here are search() and insert() rewritten with the foregoing suggestions in mind. I would encourage you to apply similar edits to the rest of the class, including delete(). def search(self, val): if val is None: raise ValueError('BST cannot hold None') tree = self while True: if tree is None or tree.value is None: return False elif val == tree.value: return True else: tree = tree.lchild if val < tree.value else tree.rchild
{ "domain": "codereview.stackexchange", "id": 43033, "lm_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, algorithm, recursion, binary-search-tree", "url": null }
python, algorithm, recursion, binary-search-tree def insert(self, val): if val is None: raise ValueError('BST cannot hold None') tree = self while True: if tree.value is None: tree.value = val return elif val == tree.value: return elif val != tree.value: attr = 'lchild' if val < tree.value else 'rchild' child = getattr(tree, attr, None) if child: tree = child else: setattr(tree, attr, BST(val)) return
{ "domain": "codereview.stackexchange", "id": 43033, "lm_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, algorithm, recursion, binary-search-tree", "url": null }
java, performance, android, formatting Title: custom button class for android game engine Question: I'm a self-taught programmer and I haven't really followed industry-standard coding classes. I'm currently coding my own game engine for android, though and I was wondering if my coding style could run me into big troubles. Here's my newly written custom button class: package com.glu.engine.GUI; import android.opengl.Matrix; import android.util.Log; import com.glu.engine.vectors.Matrix4f; import com.glu.engine.vectors.Vector2f; import com.glu.engine.vectors.Vector3f; import java.util.ArrayList; public class Button{ //One thing to note is that I preffer setting my variables to public to get and set them. //I ran some tests of my own and this practice is more performant than using methods. //just custom quads to actually render the button. public GUIBase stateDefault; public GUIBase statePressed; public GUIBase stateReleased; //I'm using arraylists to make it so that I can instance the button. public ArrayList<Boolean> isPressed = new ArrayList<>(); public ArrayList<Boolean> hasBeenPressed = new ArrayList<>(); public ArrayList<Boolean> isHovering = new ArrayList<>(); public ArrayList<Boolean> hasClickedOff = new ArrayList<>(); public ArrayList<Vector2f> position = new ArrayList<>(); public ArrayList<Vector2f> size = new ArrayList<>(); public ArrayList<String> name = new ArrayList<>(); public int pressNumber; public int doOnClick; public int doOnClickRelease; public int doOnPass; public int doOnRelease;
{ "domain": "codereview.stackexchange", "id": 43034, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, android, formatting", "url": null }
java, performance, android, formatting public static final int CANNOT_PRESS = 0; // can't press the button public static final int PRESS_ONCE = 1; // can only press the button once public static final int PRESS_MTONCE = 2; // can press the button more than once public static final int STAY_ON_CLICK = 3; // doesn't change on click public static final int CHANGE_ON_CLICK = 4; // change on click public static final int STAY_ON_RELEASE = 3; // stay on the pressed state at release public static final int RETURN_ON_RELEASE = 4; // return to the default state at release public static final int CHANGE_ON_RELEASE = 5; // change to the released state at release public static final int NTG_ON_PASS = 6; // don't react when the finger goes over the button public static final int PREVIEW_ON_PASS = 7; // change to pressed icon when the finger goes over the button public static final int CHANGE_ON_PASS = 8; // change to released icon when the finger goes over the button public static final int CLICK_ON_PASS = 9; // click the button when the finger goes over the button public static final int NTG_ON_RELEASE = 10; // don't react if the finger releases when going over the button public static final int CLICK_ON_RELEASE = 11; // click the button if the finger releases when going over it public ArrayList<Integer> state = new ArrayList<>(); public static final int STATE_DEFAULT = 12; public static final int STATE_PRESSED = 13; public static final int STATE_RELEASED = 14; public Button(GUIBase stateDefault, GUIBase statePressed){ this.stateDefault = (stateDefault); this.statePressed = (statePressed); this.stateReleased = (null); position.add(new Vector2f(0,0)); this.size.add(new Vector2f(1,1));
{ "domain": "codereview.stackexchange", "id": 43034, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, android, formatting", "url": null }
java, performance, android, formatting position.add(new Vector2f(0,0)); this.size.add(new Vector2f(1,1)); this.stateDefault.position.set(0,this.position.get(0)); this.stateDefault.scale.get(0).multiply(this.size.get(0)); this.stateDefault.show.set(0,true); this.statePressed.position.set(0,this.position.get(0)); this.statePressed.scale.get(0).multiply(this.size.get(0)); this.statePressed.show.set(0,false); isPressed.add(false); hasBeenPressed.add(false); isHovering.add(false); hasClickedOff.add(false); pressNumber = PRESS_MTONCE; doOnClick = CHANGE_ON_CLICK; doOnClickRelease = RETURN_ON_RELEASE; doOnPass = NTG_ON_PASS; doOnRelease = NTG_ON_RELEASE; state.add(STATE_DEFAULT); name.add("button"+(name.size())); } public Button(GUIBase stateDefault, GUIBase statePressed, GUIBase stateReleased){ this.stateDefault = (stateDefault); this.statePressed = (statePressed); this.stateReleased = (stateReleased); position.add(new Vector2f(0,0)); this.size.add(new Vector2f(1,1)); this.stateDefault.position.set(0,this.position.get(0)); this.stateDefault.scale.get(0).multiply(this.size.get(0)); this.stateDefault.show.set(0,true); this.statePressed.position.set(0,this.position.get(0)); this.statePressed.scale.get(0).multiply(this.size.get(0)); this.statePressed.show.set(0,false); this.stateReleased.position.set(0,this.position.get(0)); this.stateReleased.scale.get(0).multiply(this.size.get(0)); this.stateReleased.show.set(0,false); isPressed.add(false); hasBeenPressed.add(false); isHovering.add(false); hasClickedOff.add(false);
{ "domain": "codereview.stackexchange", "id": 43034, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, android, formatting", "url": null }