text
stringlengths
1
2.12k
source
dict
python, performance, recursion, numpy def format_combineall(output: list) -> list[set[int]]: """formats output into easily readable form""" semiflat = flatten_combine_all(output) only_sets = [] for each in semiflat: if isinstance(each, list): for every in each: if isinstance(every, set): only_sets.append(every) elif isinstance(each, set): only_sets.append(each) return only_sets def flatten_combine_all(entry: list) -> list: if isinstance(entry, list): if len(entry) == 1: return flatten_combine_all(entry[0]) else: return list(map(flatten_combine_all, entry)) if isinstance(entry, set): return entry raise TypeError(f'{entry} can only be set or list') def test() -> None: # compatibility-conflict graph from [1] A = np.array([[ 0, 1, 0, 0,-1,-1], [ 1, 0, 1, 1, 0, 1], [ 0, 1, 0,-1, 1, 0], [ 0, 1,-1, 0,-1, 0], [-1, 0, 1,-1, 0, 1], [-1, 1, 0, 0, 1, 0]]) qq = combine_all(A, set(range(6)), set(), set()) neat_output = format_combineall(qq) assert neat_output == [{0, 1, 2}, {0, 1, 3}, {1, 2, 4, 5}, {1, 3, 5}] if __name__ == '__main__': test()
{ "domain": "codereview.stackexchange", "id": 43701, "lm_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, recursion, numpy", "url": null }
performance, php, array, tree, database Title: function to group data by parent branches Question: I wrote this function to take database output like from PDO's fetchAll(PDO::FETCH_ASSOC) and turn it into a tree. For small datasets it works well. However, when I run it on an array of 54,000 elements, it takes around 65 seconds on an Intel 7700K. I was hoping it would take less than a second, though maybe that's unrealistic. I'm using PHP 8.1.8. Why is this function so slow? Is there a way to optimize this function? <?php function treeifyDbRows($inputArray, $branchRules) { $output = []; if ($branchRules != []) { $ruleSet = $branchRules[0]; $masterRule = $ruleSet[0]; $branchParents = array_column($inputArray, $masterRule); $branchParents = array_unique($branchParents); foreach ($branchParents as $branchParent) { $branchRulesAgain = []; foreach ($branchRules as $ruleSetAgain) { if ($ruleSetAgain != $ruleSet) { $branchRulesAgain[] = $ruleSetAgain; } } $branch = []; $branchChildren = array_filter($inputArray, function($e) use ($branchParent, $masterRule){return $e[$masterRule] == $branchParent;}); $branchChildren = array_values($branchChildren); foreach ($ruleSet as $rule) { $branch[$rule] = $branchChildren[0][$rule]; } $children = treeifyDbRows($branchChildren, $branchRulesAgain); if ($children != []) { $branch['children'] = $children; } $output[] = $branch; } } return $output; }
{ "domain": "codereview.stackexchange", "id": 43702, "lm_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, php, array, tree, database", "url": null }
performance, php, array, tree, database $data = [ [ "countryID" => 1, "countryName" => "USA", "regionID" => 10, "regionName" => "Indiana", "cityID" => 100, "cityName"=> "Indianapolis", ], [ "countryID" => 1, "countryName" => "USA", "regionID" => 10, "regionName" => "Indiana", "cityID" => 101, "cityName"=> "Bloomington", ], [ "countryID" => 1, "countryName" => "USA", "regionID" => 11, "regionName" => "Michigan", "cityID" => 102, "cityName"=> "Lansing", ], [ "countryID" => 2, "countryName" => "Canada", "regionID" => 12, "regionName" => "Ontario", "cityID" => 103, "cityName"=> "Toronto", ], [ "countryID" => 2, "countryName" => "Canada", "regionID" => 12, "regionName" => "Ontario", "cityID" => 104, "cityName"=> "Ottawa", ], [ "countryID" => 2, "countryName" => "Canada", "regionID" => 12, "regionName" => "Ontario", "cityID" => 105, "cityName"=> "Windsor", ], [ "countryID" => 2, "countryName" => "Canada", "regionID" => 25, "regionName" => "Quebec", "cityID" => 106, "cityName"=> "Montreal", ], ]; $rules = [ ["countryID", "countryName"], ["regionID", "regionName"], ["cityID", "cityName"], ]; $results = treeifyDbRows($data, $rules); var_dump($results); Answer: Initial review points Before addressing the questions I have a few review thoughts: The code is readable and indentation seems consistent Type declarations can be added for the function arguments to ensure the data passed is in the expected format, and the return type for the function can also be added: function treeifyDbRows(array $inputArray, array $branchRules): array
{ "domain": "codereview.stackexchange", "id": 43702, "lm_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, php, array, tree, database", "url": null }
performance, php, array, tree, database The one-line callback function passed to array_filter() can be simplified using the arrow function syntax, allowing for the elimination of the use statement. Using array_shift() to assign $ruleset from $branchRules by shifting it off the beginning of the array allows for the elimination of $branchRulesAgain and the loop to create it as the recursive call can then just use $branchRules It is a good habit to use strict equality operators - e.g. === instead of == - whenever possible, especially given the values that are juggled to be equal to false. While it may be common for idiomatic code in some languages to have opening braces on a new line for control expressions like if and for this is not the case with PHP. There are PHP Standards Recommendations followed by many PHP developers and PSR-12 section 5 covers Control Structures covers Control Structures: The general style rules for control structures are as follows: There MUST be one space after the control structure keyword There MUST NOT be a space after the opening parenthesis There MUST NOT be a space before the closing parenthesis There MUST be one space between the closing parenthesis and the opening brace The structure body MUST be indented once The body MUST be on the next line after the opening brace The closing brace MUST be on the next line after the body The body of each structure MUST be enclosed by braces. This standardizes how the structures look and reduces the likelihood of introducing errors as new lines get added to the body. Because PHP converts values to Boolean automatically when necessary the conditions to check if an array has elements can be simplified - e.g. from if ($branchRules != []) to simply if ($branchRules). When converted to a bool an array with no elements is converted to false. Addressing the Questions Why is this function so slow?
{ "domain": "codereview.stackexchange", "id": 43702, "lm_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, php, array, tree, database", "url": null }
performance, php, array, tree, database Addressing the Questions Why is this function so slow? Let’s look at what the function does- there is a foreach loop iterating over the rules, and inside that loop is a call to array_column() which iterates over the input array to get the "branch parents". Then there is a loop over the branch parents which inside contains a call to array_filter(), which again iterates over the input array. While it may be highly unlikely, it is possible that all branch parents are unique (in which case grouping may be superfluous) and in such a case for an input array with size \$n\$ it would require \$n^2\$ steps, which would be considered the worst case. In terms of time complexity this is considered to be of the order of \$O(n^2)\$. Additionally, the function recursively calls itself in order to add the child elements, which leads to even more looping! When running the function with an array containing 54,000 elements there could be as many as 2,916,000,000 steps just to get the first level of output! Is there a way to optimize this function? Ideally the input data would be sorted (which is why I asked in a comment if this is possible) and there could be a single loop to: find branch parents add branch children to a filtered array that can then be used in the recursive call
{ "domain": "codereview.stackexchange", "id": 43702, "lm_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, php, array, tree, database", "url": null }
performance, php, array, tree, database If there is no guarantee that the data will be sorted then mapping the parents and children in an associative array may be necessary, which would increase the spacial complexity. Also, the loop to add elements to $branchRulesAgain does not need to happen within the nested loop (over $branchParents) as it is not specific to the branch parent. Proposed solution The code below presumes the data is already sorted and only iterates over the inputArray once per rule/group level. It uses null coalescing to handle the case of the last element in the array - in that case there won’t be a next element so the ?? 0 makes 0 the fallback value. See a demo of it here on 3v4l.org. <?php function treeifyDbRows(array $inputArray, array $branchRules): array { $output = []; if ($branchRules) { $ruleSet = array_shift($branchRules); $masterRule = $ruleSet[0]; $branchChildren = []; foreach ($inputArray as $index => $element) { $branchChildren[] = $element; //coalesce null to 0 if (($inputArray[$index + 1][$masterRule] ?? 0) !== $element[$masterRule]) { $branch = []; foreach ($ruleSet as $rule) { $branch[$rule] = $branchChildren[0][$rule]; } $children = treeifyDbRows($branchChildren, $branchRules); if ($children) { $branch['children'] = $children; } $output[] = $branch; $branchChildren = []; } } } return $output; }
{ "domain": "codereview.stackexchange", "id": 43702, "lm_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, php, array, tree, database", "url": null }
file-system, go, coroutines Title: Finding files using multiple coroutines Question: I'm trying to write a simple program to find a certain file name within a directory tree. I use up to 30 coroutines. Is there anything wrong with this code or what needs to be improved? import ( "fmt" "io/ioutil" "path/filepath" "sync" ) const tofind = "select-test.go" func main() { wg := sync.WaitGroup{} search("/Users/user/Documents", &wg) wg.Add(1) wg.Wait() } var permit = make(chan struct{}, 30) func search(dir string, wg *sync.WaitGroup) { permit <- struct{}{} defer func() { <-permit }() defer func() { wg.Done() }() items, err := ioutil.ReadDir(dir) if err != nil { fmt.Println(err.Error()) } for _, item := range items { if item.IsDir() { wg.Add(1) go search(filepath.Join(dir, item.Name()), wg) } else { if item.Name() == tofind { fmt.Println(filepath.Join(dir, item.Name())) } } } } Answer: OK, there's a number of things I'd change about your code. I'll go through what you posted, making suggestions based on what you have already, then I'll make some additional suggestions. const tofind = "select-test.go" Just a small nit-pcik here: to improve readability, would suggest camel-casing constants like this. IMO, toFind is easier to read. In a small piece of code like this, it doesn't make that much of a difference, but as code bases grow, and the number of constants increases, it starts adding up. func main() { wg := sync.WaitGroup{} search("/Users/user/Documents", &wg) wg.Add(1) wg.Wait() }
{ "domain": "codereview.stackexchange", "id": 43703, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "file-system, go, coroutines", "url": null }
file-system, go, coroutines Seeing the call to search, passing it a pointer to the wait group, and only incrementing it after the call is bad form. It's clear that this search function will at some point call wg.Done(). Should, for whatever reason, the search function return before the main function calls wg.Add(1), you'll get a runtime panic. It's easily avoided by simply incrementing your wait group before calling functions which decrement it. When passing a waitgroup to a function, it's also more common (to the point where it's pretty much the de facto standard) to pass in the wait group first. You main function, as is, should look something like this: wg.Add(1) search(&wg, "/path/to/dir") wg.Wait() Obviously, you'll need to change the search function to match the different argument order. I'd change this function even more, but we'll cover that a bit later on. var permit = make(chan struct{}, 30) A global variable holding a channel works, but it's code smell. Declaring and assigning this variable in between functions if perfectly valid code, but it doesn't look clean. Code is written for people to read, compilers translate human readable code into instructions for computers to execute. Generally speaking, I prefer it when I'm able to open source files and see what types, constants, and variables it creates/declares/uses at the top of the file. The structure I tend to follow is: package imports constants variables types functions (New first, Exported functions next, unexported functions towards the bottom)
{ "domain": "codereview.stackexchange", "id": 43703, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "file-system, go, coroutines", "url": null }
file-system, go, coroutines types functions (New first, Exported functions next, unexported functions towards the bottom) This is a common pattern to follow, I've found. In some cases you'll see variables before constants, or the types being defined first, but generally speaking, code tends to be broken down into these groups. There is, however, a bigger concern here: because your channel is a global variable, it's not exactly "owned" by any particular function/scope. You don't explicitly close the channel, which is considered bad form. You're using this channel to ensure you have no more than 30 goroutines (not coroutines) searching the path at any given time. Once you've found what you're looking for, the channel is no longer needed, can be closed and GC'ed. That essentially means that, once the wait group is done, it should be perfectly safe to close the channel. In this case, that means the channel can be moved to the scope of main: func main() { wg := sync.WaitGroup{} ch := make(chan struct{}, 30) wg.Add(1) search(&wg, ch, "/path/to/dir") wg.Wait() wg.Done() close(ch) } Once again, you'll need to add the channel to the search arguments to something like this: func search(wg *sync.WaitGroup, ch chan struct{}, path string) Now let's look at the main part of your code, this search function. You start out writing to the channel (as mentioned above to ensure no more than 30 concurrent routines). After that you're reading from the channel and decrementing the wait group in seperate defer functions. The order in which these functions are executed is LIFO. Basically, you'll decrement the waitgroup first, and drain the channel last. Reading from a closed channel is not an issue, but I thought I'd mention it. The main thing here is that there is no real reason to have 2 anonymous functions in these defer statements. You could either write: defer func() { wg.Done() <- ch // or <-permit in your case }()
{ "domain": "codereview.stackexchange", "id": 43703, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "file-system, go, coroutines", "url": null }
file-system, go, coroutines If, for whatever reason, you want to keep these two operations as distinct defer calls, you can simply write this: defer func() { <-ch // <-permit }() defer wg.Done() // no need to wrap this call in to a function... As peterSO mentioned, in terms of performance improvements, you can easily replace ioutil.ReadDir with os.ReadDir. It'll return a slice of DirEntry objects, sorted by name. You can get the name, file-type, etc... through its interface, as documented here. The code should look something like this: entries, err := os.ReadDir(path) if err != nil { fmt.Println(err) return // exit here! } for _, entry := range entries { if entry.FileInfo().IsDir() { wg.Add(1) go search(wg, ch, filepath.Join(path, entry.Name())) continue } if entry.Name() == toFind { fmt.Printf("Found %s here: %s\n", toFind, path) return // return, we're done } }
{ "domain": "codereview.stackexchange", "id": 43703, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "file-system, go, coroutines", "url": null }
file-system, go, coroutines Having this return statement in the loop can be quite a big deal, depending on what you want your program to do. I've chosen to stop iterating over the directory items once we found a match. Having 2 files with the exact same name in a directory simply doesn't make sense, so there is no reason to keep looking in this path. The problem here is that we could very well end up in a situation where we found a file with the name we're looking for in a particular path, but we've already spun up 29 other routines that are all recursively looking for a file with the desired name. If we only want to find one match, we might end up looking through the entire file system recursively. This could take a long time, and yield no results. Imagine you're looking for a specific file (e.g. my_app_logs_20220808_err.log. There probably is only one file with this name on your system. Now imagine someone ran this code starting from the path /. That's going to scan the entire filesystem. It could relatively quickly find /logs/my_app_logs_20220808_err.log, but the program will continue to scan the entire filesystem. You'll encounter errors when you're trying to search paths like /root or /home/some_other_user_with_encrypted_files and so on... What you want to be able to do is to cancel the entire recursive search. Basically, you want to be able to cancel all search routines as soon as you found a match. Thankfully, golang has something that allows you to do exactly that very easily: func main() { ctx, cfunc := context.WithCancel(context.Background()) defer cfunc() // make sure this will always be called wg := sync.WaitGroup{} ch := make(ch struct{}, 30) wg.Add(1) go search(ctx, &wg, ch, cfunc, "/path/to/search") wg.Wait() close(ch) }
{ "domain": "codereview.stackexchange", "id": 43703, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "file-system, go, coroutines", "url": null }
file-system, go, coroutines Through context, we can signal to all routines within this particular context that they should stop doing whatever they do. To achieve this, all we have to do is pass in the cancel function and the context. Then just change the search function to this: func search(ctx context.Context, wg *sync.WaitGroup, ch chan struct{}, found func(), path string) { entries, err := os.ReadDir(path) if err != nil { fmt.Println(err) return // exit here! } for _, entry := range entries { select { case <-ctx.Done(): // run is done? return // exit this function default: // if we haven't found what we're looking for, carry on if entry.FileInfo().IsDir() { wg.Add(1) go search(ctx, wg, ch, found, filepath.Join(path, entry.Name())) continue // remove this if we're lookging for directories } if entry.Name() == toFind { fmt.Printf("Found %s here: %s\n", toFind, path) found() // call the "found" callback, which cancels the context return // and return } } } } Lastly, in case we want to be able to run this program from the command line using arguments/flags to perform a quick recursive file search using something like: $ my_search -f filename.foo -p /path/to/search We have to account for our process to be interrupted/cancelled by the user. In the main function, we basically have to handle system signals. To stop all search routines and cleanly exit the program, we can simply cancel the context, signalling any and all routines to stop doing what they're doing and return: import ( "os" "os/signal" ) func main() { ctx, cfunc := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill) defer cfunc() // the rest is the same }
{ "domain": "codereview.stackexchange", "id": 43703, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "file-system, go, coroutines", "url": null }
file-system, go, coroutines With this, the ctx.Done() channel will be closed when we receive an interrupt or kill signal, and in the search function, the select statement will enter the case <-ctx.Done() block, and return from search, execute the defer calls (decrementing the waitgroup, drain the channel). Then, the main when all this is done, the main function will close the channel and return. Nice and clean.
{ "domain": "codereview.stackexchange", "id": 43703, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "file-system, go, coroutines", "url": null }
python, numpy, opencv Title: Looking for the particles that are emitted when a fish is detected in Terraria Question: The code run perfectly fine, with no errors. However, the entirety of the code is in 1 function and is kind of hard to read. As well as that I'm not sure if and how the code could be more optimised/improved. Thank you for your suggestions and help! def ScreenShot(): pydirectinput.click(x=483, y=559 ) time.sleep(1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0) time.sleep(.1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0) time.sleep(2) x = True while x == True: if x == True: if keyboard.is_pressed('q'): # if key 'q' is pressed print('Stopped Fishing') break # finishing the loop screenie = py.screenshot() screenie.save("is_fish_there.png") print("taking a screenshot") Fishisthere = cv2.imread("is_fish_there.png") img = Fishisthere[590:614,400:690] hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) lowerrange = np.array([106, 147, 0]) upperrange = np.array([179, 255, 245]) mask = cv2.inRange(hsv, lowerrange, upperrange) blue = np.sum(mask) print (blue) if blue > 15000: print("fish has been found") win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0) time.sleep(.1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0) time.sleep(.5) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0) time.sleep(.1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0) time.sleep(1.5) #check() ScreenShot() Here is an example of is_fish_there.png:
{ "domain": "codereview.stackexchange", "id": 43704, "lm_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, numpy, opencv", "url": null }
python, numpy, opencv #check() ScreenShot() Here is an example of is_fish_there.png: Answer: Any group of things that are doing something can be broken down into smaller functions that encapsulate that particular task. The first few lines of your function are doing some setup so I have created a function that brings out that setup. You might have a better understanding of the semantics of the setup so could improve on the name instead saying something about why the mouse is moved where it is etc. def setup_fish_detection(): pydirectinput.click(x=483, y=559 ) time.sleep(1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0) time.sleep(.1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0) time.sleep(2) So with this next function, I've tried to take what could conceptually be aggregated into simply taking the screenshot from the two actions and a log that it was originally. This function is then abstracting how we take the screenshot. def take_screenshot(file_name): screenie = py.screenshot() screenie.save(file_name) print("taking a screenshot") The detection of the fish in said screenshot is another thing, this could perhaps be broken down further into gathering the metric and comparing it. def fish_in_screenshot(screenshot): img = screenshot[590:614,400:690] hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) lowerrange = np.array([106, 147, 0]) upperrange = np.array([179, 255, 245]) mask = cv2.inRange(hsv, lowerrange, upperrange) blue = np.sum(mask) print (blue) return blue > 15000
{ "domain": "codereview.stackexchange", "id": 43704, "lm_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, numpy, opencv", "url": null }
python, numpy, opencv Again with the post-detection mechanics, I'm sure you'll be able to better name what this action represents. def post_detection_handling(): win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0) time.sleep(.1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0) time.sleep(.5) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0) time.sleep(.1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0) time.sleep(1.5) The main function is then left to almost read as pseudocode. def main(): setup_fish_detection() screenshot_file_name = "is_fish_there.png" while not keyboard.is_pressed('q'): take_screenshot(screen_shot_file_name) screenshot = cv2.imread(screen_shot_file_name) if fish_in_screenshot(screenshot): print("fish has been found") post_detection_handling() print('Stopped Fishing') #check() if __name__=="__main__": main() In the main function, I've also simplified the while loop which will behave the same as the original code but not if some other places in the while loop were edited. Having the filename of the screenshot as a separate variable I find helps, it's one of those things that needs to match in the two locations its used but is something that will probably change quite a bit over time.
{ "domain": "codereview.stackexchange", "id": 43704, "lm_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, numpy, opencv", "url": null }
performance, sql, combinatorics, sqlite Title: Query for sequential column permutations in SQLite Question: For dummy's sake, let's say that I have a database with columns text, ind and sentid. You can think of it as a database with one row per word, with a word's text, its position in the sentence, and the ID of the sentence. To query for specific occurrences of n words, I join the table with itself n times. That table does not have a unique column except for the default rowid. I oftentimes want to query these columns in such a way that the integers in the n ind columns are sequential without any integer between them. Sometimes the order matters, sometimes the order does not. At the same time, each of the n columns also needs to fulfil some requirement, e.g. n0.text = 'a' AND n1.text = 'b' AND n2.text = 'c'. Put differently, in every sentence (unique sentid), find all occurrences of a b c either ordered or in any order (but sequential). I have solved the ordered case quite easily. For three columns with names ind0, ind1, ind2 you could simply have a query like the following and scale it accordingly as n columns grows. WHERE ind1 = ind0 + 1 AND ind2 = ind1 + 1
{ "domain": "codereview.stackexchange", "id": 43705, "lm_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, sql, combinatorics, sqlite", "url": null }
performance, sql, combinatorics, sqlite Perhaps there is a better way (do tell me if that is so) but I have found that this works reliably well in terms of performance (query speed). The tougher nut to crack is those cases where the integers also have to be sequential but where the order does not matter (e.g., 7 9 8, 3 1 2, 11 10 9). My current approach is "brute forcing" by simply generating all possible permutations of orders (e.g., (ind1 = ind0 + 1 AND ind2 = ind1 + 1) OR (ind0 = ind1 + 1 AND ind2 = ind0 + 1) OR ...)). But as n grows, this becomes a huge list of possibilities and my query speed seems to be really hurting on this. For example, for n=6 (the max requirement) this will generate 720 potential orders separate with OR. Such an approach, that works, is given as a minimal but documented example below for you to try out. I am looking for a more generic, SQL-y solution that hopefully positively impacts performance when querying for sequential (but not necessarily ordered) columns. Fiddle with data and current implementation here, reproducible Python code below. Note that it is possible to get multiple results per sentid, but only if at least one of the word indices differs in the three matched words. E.g. permutations of the results themselves are not needed. E.g., 1-2-0 and 3-2-1 can both be valid results for one sentid, but both 1-2-0 and 2-1-0 can't. import sqlite3 from itertools import permutations from pathlib import Path from random import shuffle def generate_all_possible_sequences(n: int) -> str: """Given an integer, generates all possible permutations of the 'n' given indices with respect to order in SQLite. What this means is that it will generate all possible permutations, e.g., for '3': 0, 1, 2; 0, 2, 1; 1, 0, 2; 1, 2, 0 etc. and then build corresponding SQLite requirements, e.g., 0, 1, 2: ind1 = ind0 + 1 AND ind2 = ind1 + 1 0, 2, 1: ind2 = ind0 + 1 AND ind1 = ind2 + 1 ...
{ "domain": "codereview.stackexchange", "id": 43705, "lm_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, sql, combinatorics, sqlite", "url": null }
performance, sql, combinatorics, sqlite and all these possibilities are then concatenated with OR to allow every possibility: ((ind1 = ind0 + 1 AND ind2 = ind1 + 1) OR (ind2 = ind0 + 1 AND ind1 = ind2 + 1) OR ...) """ idxs = list(range(n)) order_perms = [] for perm in permutations(idxs): this_perm_orders = [] for i in range(1, len(perm)): this_perm_orders.append(f"w{perm[i]}.ind = w{perm[i-1]}.ind + 1") order_perms.append(f"({' AND '.join(this_perm_orders)})") return f"({' OR '.join(order_perms)})" def main(): pdb = Path("temp.db") if pdb.exists(): pdb.unlink() conn = sqlite3.connect(str(pdb)) db_cur = conn.cursor() # Create a table of words, where each word has its text, its position in the sentence, and the ID of its sentence db_cur.execute("CREATE TABLE tbl(text TEXT, ind INTEGER, sentid INTEGER)") # Create dummy data vals = [] for sent_id in range(20): shuffled = ["a", "b", "c", "d", "e", "a", "c"] shuffle(shuffled) for word_id, word in enumerate(shuffled): vals.append((word, word_id, sent_id)) # Wrap the values in single quotes for SQLite vals = [(f"'{v}'" for v in val) for val in vals] # Convert values into INSERT commands cmds = [f"INSERT INTO tbl VALUES ({','.join(val)})" for val in vals] # Build DB db_cur.executescript(f"BEGIN TRANSACTION;{';'.join(cmds)};COMMIT;") print(f"BEGIN TRANSACTION;{';'.join(cmds)};COMMIT;\n") # Query DB for sequential occurences in ind0, ind1, and ind2: the order does not matter # but they have to be sequential query = f"""SELECT w0.ind, w1.ind, w2.ind, w0.sentid FROM tbl AS w0 JOIN tbl AS w1 USING (sentid) JOIN tbl AS w2 USING (sentid) WHERE w0.text = 'a' AND w1.text = 'b' AND w2.text = 'c' AND {generate_all_possible_sequences(3)}""" print(query) print()
{ "domain": "codereview.stackexchange", "id": 43705, "lm_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, sql, combinatorics, sqlite", "url": null }
performance, sql, combinatorics, sqlite print(query) print() print("a_idx\tb_idx\tc_idx\tsentid") for res in db_cur.execute(query).fetchall(): print("\t".join(map(str, res))) db_cur.close() conn.commit() conn.close() pdb.unlink() if __name__ == '__main__': main() Answer: I found that the easiest way to implement this is to use the following condition: AND MAX(w0.ind, w1.ind, w2.ind) - MIN(w0.ind, w1.ind, w2.ind) = 2 where 2 = the number of words that we are looking for -1. That being said, it is hard to say much about the performance since "no, indexes can't be used in expressions like MAX(...) - MIN(...) where functions are used." as @forpas mentions.
{ "domain": "codereview.stackexchange", "id": 43705, "lm_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, sql, combinatorics, sqlite", "url": null }
algorithm, go, concurrency, dining-philosophers Title: Golang implementation of dining philosophers variant Question: I would like to implement a variant of the classical dining philosophers problem which has the definition as: Implement the dining philosopher’s problem with the following constraints/modifications. There should be 5 philosophers sharing chopsticks, with one chopstick between each adjacent pair of philosophers. Each philosopher should eat only 3 times (not in an infinite loop as we did in lecture) The philosophers pick up the chopsticks in any order, not lowest-numbered first (which we did in lecture). In order to eat, a philosopher must get permission from a host which executes in its own goroutine. The host allows no more than 2 philosophers to eat concurrently. Each philosopher is numbered, 1 through 5. When a philosopher starts eating (after it has obtained necessary locks) it prints “starting to eat ” on a line by itself, where is the number of the philosopher. When a philosopher finishes eating (before it has released its locks) it prints “finishing eating ” on a line by itself, where is the number of the philosopher. I implemented the following code: package main import ( "fmt" "sync" "time" ) // define variables var numPhilo int = 5 var numCS int = 5 var eatTimes int = 3 var numEatingPhilo int = 2 type Host struct { // channel for allowed philosopher for eating eatingChannel chan *Philo // channel for submitting request to host requestChannel chan *Philo // channel for terminate signal for the daemon quitChannel chan int // bookkeeping of the current eating philosophers eatingPhilos map[int]bool // mutex to lock the modification of the eatingPhilos variable mu sync.Mutex }
{ "domain": "codereview.stackexchange", "id": 43706, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, go, concurrency, dining-philosophers", "url": null }
algorithm, go, concurrency, dining-philosophers // daemon function to manage the allowed philosophers func (pHost *Host) manage() { // daemon serving in the backend and only exits for terminate signal for { select { // handle submitted request case pPhilo := <-pHost.requestChannel: fmt.Printf("%d submitted request\n", pPhilo.idx) select { // channel is not full case pHost.eatingChannel <- pPhilo: pHost.eatingPhilos[pPhilo.idx] = true // channel is full default: finished := <-pHost.eatingChannel pHost.eatingChannel <- pPhilo currEating := make([]int, 0, numPhilo) // update bookkeeping table for tmpIdx, eating := range pHost.eatingPhilos { if eating { currEating = append(currEating, tmpIdx) } } fmt.Printf("%v have been eating, clearing up %d for %d\n", currEating, finished.idx, pPhilo.idx) pHost.eatingPhilos[finished.idx] = false pHost.eatingPhilos[pPhilo.idx] = true } case <-pHost.quitChannel: fmt.Println("stop hosting") return } } } type ChopS struct { mu sync.Mutex } type Philo struct { // index of the philosopher idx int // number of times the philosopher has eaten numEat int leftCS, rightCS *ChopS host *Host } func (pPhilo *Philo) eat(wg *sync.WaitGroup) { for pPhilo.numEat < eatTimes { // once the philosopher intends to eat, lock the corresponding chopsticks pPhilo.leftCS.mu.Lock() pPhilo.rightCS.mu.Lock() // reserve a slot in the channel for eating // if channel buffer is full, this is blocked until channel space is released pPhilo.host.requestChannel <- pPhilo
{ "domain": "codereview.stackexchange", "id": 43706, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, go, concurrency, dining-philosophers", "url": null }
algorithm, go, concurrency, dining-philosophers pPhilo.numEat++ fmt.Printf("starting to eat %d for %d time\n", pPhilo.idx, pPhilo.numEat) time.Sleep(time.Millisecond) fmt.Printf("finishing eating %d for %d time\n", pPhilo.idx, pPhilo.numEat) pPhilo.rightCS.mu.Unlock() pPhilo.leftCS.mu.Unlock() wg.Done() } } func main() { var wg sync.WaitGroup host := Host{ eatingChannel: make(chan *Philo, numEatingPhilo), requestChannel: make(chan *Philo), quitChannel: make(chan int), eatingPhilos: make(map[int]bool), } CSticks := make([]*ChopS, numCS) for i := 0; i < numCS; i++ { CSticks[i] = new(ChopS) } philos := make([]*Philo, numPhilo) for i := 0; i < numPhilo; i++ { philos[i] = &Philo{idx: i + 1, numEat: 0, leftCS: CSticks[i], rightCS: CSticks[(i+1)%5], host: &host} } go host.manage() wg.Add(numPhilo * eatTimes) for i := 0; i < numPhilo; i++ { go philos[i].eat(&wg) } wg.Wait() host.quitChannel <- 1 }
{ "domain": "codereview.stackexchange", "id": 43706, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, go, concurrency, dining-philosophers", "url": null }
algorithm, go, concurrency, dining-philosophers However, I noticed that the program is actually failing in some cases, i.e. starting to eat 1 for 1 time 1 submitted request 3 submitted request starting to eat 3 for 1 time finishing eating 3 for 1 time starting to eat 3 for 2 time finishing eating 1 for 1 time 3 submitted request [1 3] have been eating, clearing up 1 for 3 1 submitted request [3] have been eating, clearing up 3 for 1 starting to eat 1 for 2 time finishing eating 3 for 2 time finishing eating 1 for 2 time starting to eat 5 for 1 time 5 submitted request [1] have been eating, clearing up 3 for 5 finishing eating 5 for 1 time starting to eat 5 for 2 time 5 submitted request [5 1] have been eating, clearing up 1 for 5 finishing eating 5 for 2 time starting to eat 4 for 1 time 4 submitted request [5] have been eating, clearing up 5 for 4 finishing eating 4 for 1 time starting to eat 4 for 2 time 4 submitted request [4] have been eating, clearing up 5 for 4 finishing eating 4 for 2 time starting to eat 3 for 3 time 3 submitted request [4] have been eating, clearing up 4 for 3 finishing eating 3 for 3 time starting to eat 2 for 1 time 2 submitted request [3] have been eating, clearing up 4 for 2 finishing eating 2 for 1 time starting to eat 2 for 2 time 2 submitted request [3 2] have been eating, clearing up 3 for 2 finishing eating 2 for 2 time starting to eat 1 for 3 time 1 submitted request [2] have been eating, clearing up 2 for 1 finishing eating 1 for 3 time starting to eat 2 for 3 time 2 submitted request [1] have been eating, clearing up 2 for 2 5 submitted request [2 1] have been eating, clearing up 1 for 5 starting to eat 5 for 3 time finishing eating 2 for 3 time finishing eating 5 for 3 time starting to eat 4 for 3 time 4 submitted request [5 2] have been eating, clearing up 2 for 4 finishing eating 4 for 3 time stop hosting
{ "domain": "codereview.stackexchange", "id": 43706, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, go, concurrency, dining-philosophers", "url": null }
algorithm, go, concurrency, dining-philosophers where it seems sometimes two instances of the same philosopher are eating concurrently, while semaphore is locked on the chopstick level, i.e. ... [3] have been eating, clearing up 3 for 1 ... [5] have been eating, clearing up 5 for 4 ... Also according to the logs, the bookkeeping map is acting weird, when the records are misaligned with the actual finished philosopher, i.e. ... [4] have been eating, clearing up 5 for 4 ... [3] have been eating, clearing up 4 for 2 ... I checked the program with go build -race for race conditions detection, but it seems to be fine. Also not to mention there is only one goroutine running manage() and reading/writing to the map eatingPhilos. Could someone please point out which part of the implementation is improper? Anything obviously wrong or bad practice? Answer: To help resolve your issue lets add code to report when a philosopher has locked a chopstick and what they are waiting on (I also added an idx to ChopS to simplify this): pPhilo.leftCS.mu.Lock() fmt.Printf("pPhilo %d has lock on chopstick %d, waiting on %d\n", pPhilo.idx, pPhilo.leftCS.idx, pPhilo.rightCS.idx) pPhilo.rightCS.mu.Lock() Running this on my computer immediately generates a deadlock: pPhilo 2 has lock on chopstick 1, waiting on 2 pPhilo 5 has lock on chopstick 4, waiting on 0 pPhilo 1 has lock on chopstick 0, waiting on 1 pPhilo 3 has lock on chopstick 2, waiting on 3 pPhilo 4 has lock on chopstick 3, waiting on 4 fatal error: all goroutines are asleep - deadlock!
{ "domain": "codereview.stackexchange", "id": 43706, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, go, concurrency, dining-philosophers", "url": null }
algorithm, go, concurrency, dining-philosophers Adding the Printf enables us to see what is happening but can also change the order of operation (it adds a delay which other goroutines may get some runtime). If adding a Printf leads to an issue like this it is likely there is an issue with your underlying algorithm. If you look at the output you will see that every philosopher has locked their left chopstick and is waiting on the right one (but another philosopher has that). This issue can occur whether or not the Printf is there (but having the Printf makes the situation more obvious!). You can resolve this by doing something like: // once the philosopher intends to eat, lock the corresponding chopsticks for { pPhilo.leftCS.mu.Lock() // Attempt to get the right Chopstick - if someone else has it we replace the left chopstick and try // again (in order to avoid deadlocks) if pPhilo.rightCS.mu.TryLock() { // TryLock introduced in go 1.18 break } pPhilo.leftCS.mu.Unlock() } There are other ways of resolving this but I felt that the above is fairly easy to understand. Do note the warning in the docs "Note that while correct uses of TryLock do exist, they are rare, and use of TryLock is often a sign of a deeper problem in a particular use of mutexes.". The issue above is one of the points of the problem; as wikipedia says: And may end up holding a left fork thinking, staring at the right side of the plate, unable to eat because there is no right fork, until they starve. I have implemented a work around this (the philosopher puts the left fork back down) but that is not something that the rules allow. A better option might be for the philosopher to starve (perhaps ending the simulation - I've left that to you!). the bookkeeping map is acting weird 3 submitted request [1 3] have been eating, clearing up 1 for 3 1 submitted request
{ "domain": "codereview.stackexchange", "id": 43706, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, go, concurrency, dining-philosophers", "url": null }
algorithm, go, concurrency, dining-philosophers I think the issue here is that you are not expecting a philosopher who is currently eating to submit another request to eat. However there is nothing to prevent this because the philosopher does not wait for the host to inform it that it should stop eating before joining the queue again. This means that you can end up with the same philosopher eating simultaneously (this may be a metaphysical issue; consult a philosopher if in doubt). This has an impact on your output because you end up calling eatingPhilos[greedyPhilosopherIdx] = false twice (so the second call has no impact and in your list you will ignore the philosopher). Anyway that deals with the issue you raised but this is code review (and I suggested you moving your question here as you asked "Anything obviously wrong or bad practice?") so here are a few thoughts. WaitGroup You use wg.Add(numPhilo * eatTimes) and then call wg.Done for each iteration. Change this to wg.Add(numPhilo) and move the wg.Done() to the top of eat as defer wg.Done() (fewer calls and easier to understand). See my example below for another approach (I prefer to wg.Wait in the same place as the Waitgroup is created where possible because I feel it's easier to read/understand). As this is only accessed within manage it should be declared within the function and not in the struct (leaving it in the struct makes it accessible which would lead to races). eatingChannel & eatingPhilos Map Same comment as above; you can simplify things by just declaring these in manage. In fact because eatingChannel is only accessed in (pHost *Host) manage() you don't really need to use a channel for this at all (channels are really only needed for communication between goroutines). Alternative
{ "domain": "codereview.stackexchange", "id": 43706, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, go, concurrency, dining-philosophers", "url": null }
algorithm, go, concurrency, dining-philosophers Alternative I could provide further commentary but the big issue is addressing the need to prevent the same, greedy, philosopher from making additional request to eat before the host has changed their status. Doing this is a little tricky because it requires bi-directional communications between two goroutines. I've had a think about this and suggest something like the below (I've left properly dealing with a starving philosopher to you!). Hopefully the below provides some ideas and shows a few techniques you have not seen previously (Note: I have not really tested this and am sure it will have bugs!). Playground package main
{ "domain": "codereview.stackexchange", "id": 43706, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, go, concurrency, dining-philosophers", "url": null }
algorithm, go, concurrency, dining-philosophers import ( "fmt" "math/rand" "sync" "time" "golang.org/x/exp/slices" ) const ( numPhilo = 5 eatTimes = 3 numEatingPhilo = 2 ) type eatRequest struct { who int // Who is making the request finishedFnChan chan func() // When approves a response will be sent on this channel with a function to call when done } // simulateHost - the host must provide permission before a philosopher can eat // Exits when channel closed func simulateHost(requestChannel <-chan eatRequest) { awaitRequest := requestChannel finishedChan := make(chan struct { who int done chan struct{} }) var whoEating []int // tracks who is currently eating for { select { case request, ok := <-awaitRequest: if !ok { return // Closed channel means that we are done (finishedChan is guaranteed to be empty) } // Sanity check - confirm that philosopher is not being greedy! (should never happen) if slices.Index(whoEating, request.who) != -1 { panic("Multiple requests from same philosopher") } whoEating = append(whoEating, request.who) // New request always goes at the end fmt.Printf("%d started eating (currently eating %v)\n", request.who, whoEating)
{ "domain": "codereview.stackexchange", "id": 43706, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, go, concurrency, dining-philosophers", "url": null }
algorithm, go, concurrency, dining-philosophers // Let philosopher know and provide means for them to tell us when done request.finishedFnChan <- func() { d := make(chan struct{}) finishedChan <- struct { who int done chan struct{} }{who: request.who, done: d} <-d // Wait until request has been processed (ensure we should never have two active requests from one philosopher) } case fin := <-finishedChan: idx := slices.Index(whoEating, fin.who) if idx == -1 { panic("philosopher stopped eating multiple times!") } whoEating = append(whoEating[:idx], whoEating[idx+1:]...) // delete the element fmt.Printf("%d completed eating (currently eating %v)\n", fin.who, whoEating) close(fin.done) } // There has been a change in the number of philosopher's eating if len(whoEating) < numEatingPhilo { awaitRequest = requestChannel } else { awaitRequest = nil // Ignore new eat requests until a philosopher finishes (nil channel will never be selected) } } } // ChopS represents a single chopstick type ChopS struct { mu sync.Mutex idx int // Including the index can make debugging simpler } // philosopher simulates a Philosopher (brain in a vat!) func philosopher(philNum int, leftCS, rightCS *ChopS, requestToEat chan<- eatRequest) { for numEat := 0; numEat < eatTimes; numEat++ { // once the philosopher intends to eat, lock the corresponding chopsticks for { leftCS.mu.Lock() // Attempt to get the right Chopstick - if someone else has it we replace the left chopstick and try // again (in order to avoid deadlocks) if rightCS.mu.TryLock() { break } leftCS.mu.Unlock() }
{ "domain": "codereview.stackexchange", "id": 43706, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, go, concurrency, dining-philosophers", "url": null }
algorithm, go, concurrency, dining-philosophers // We have the chopsticks but need the hosts permission ffc := make(chan func()) // when accepted we will receive a function to call when done eating requestToEat <- eatRequest{ who: philNum, finishedFnChan: ffc, } doneEating := <-ffc fmt.Printf("philosopher %d starting to eat (%d feed)\n", philNum, numEat) time.Sleep(time.Millisecond * time.Duration(rand.Intn(200))) // Eating takes a random amount of time fmt.Printf("philosopher %d finished eating (%d feed)\n", philNum, numEat) rightCS.mu.Unlock() leftCS.mu.Unlock() doneEating() // Tell host that we have finished eating } fmt.Printf("philosopher %d is full\n", philNum) } func main() { CSticks := make([]*ChopS, numPhilo) for i := 0; i < numPhilo; i++ { CSticks[i] = &ChopS{idx: i} } requestChannel := make(chan eatRequest) var wg sync.WaitGroup wg.Add(numPhilo) for i := 0; i < numPhilo; i++ { go func(philNo int) { philosopher(philNo, CSticks[philNo-1], CSticks[philNo%numPhilo], requestChannel) wg.Done() }(i + 1) } go func() { wg.Wait() close(requestChannel) }() simulateHost(requestChannel) }
{ "domain": "codereview.stackexchange", "id": 43706, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, go, concurrency, dining-philosophers", "url": null }
python, integer Title: Sum numbers digit by digit Question: The problem goes like this: Given two one-dimensional arrays, for example a = (3, 4, 5) and b = (5, 6, 9), write a function that sums the arrays as a number digit by digit, i.e. producing c = (9, 1, 4). Do not use any high-level functions such as str.join() or str.split(). 345 + 569 --- 914 My solution: def sum_arr(arr1, arr2): l = max(len(arr1), len(arr2)) if len(arr1) < l: arr1 = (0,)*(l - len(arr1)) + arr1 if len(arr2) < l: arr2 = (0,)*(l - len(arr2)) + arr2 result = [0]*l carry = 0 for idx in range(l - 1, -1, -1): val = arr1[idx] + arr2[idx] + carry if val < 10: result[idx] += val carry = 0 else: result[idx] += val % 10 carry = 1 if carry: result = [1] + result return tuple(result) Is there any more concise/elegant solution? Answer: Types When I hear one-dimensional array, I think first think of a list [3, 4, 5], not a tuple (3, 4, 5). If your method is given two lists of unequal length, one of the if statements will fail with the exception: TypeError: can only concatenate tuple (not "list") to tuple You could avoid this by converting the input type to a tuple: eg) arr1 = (0,) * (digits - len(arr1)) + tuple(arr1) Variable names l is a terrible variable name. It looks too close to 1. digits or num_digits would be much clearer. Loop like a Native See talk by Ned Batchelder. Python is a scripted language. As a consequence of this, there are common coding patterns that have inefficiencies. Looping over the indices of a container is probably the most common one. It looks like: for idx in range(len(container)): # code which never uses idx except as container[idx]
{ "domain": "codereview.stackexchange", "id": 43707, "lm_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, integer", "url": null }
python, integer Instead, the code should loop over the values in the container: for value in container: # code which uses value In your case, you want to loop over two containers simultaneously, so what is done is the containers are zipped together (note: like a zipper, not file compression): for value1, value2 in zip(container1, container2): # code which uses value1 & value2 Again in your case, we need to start at the end of the arrays and work backwards. Python provides a "reverse iterator" which will start at the end and move towards the start: for digit1, digit2 in zip(reversed(arr1), reversed(arr2)): val = digit1 + digit2 + carry ... You preprocessed the inputs to ensure they were the same length. That is not necessary. zip(...) stops at the end of the shorter input stream, but zip_longest(...) won't stop until all input streams have been exhausted. We can provide a fillvalue= argument to pretend the shorter sequence has zeros at the beginning: from itertools import zip_longest ... for digit1, digit2 in zip_longest(reversed(arr1), reversed(arr2), fillvalue=0): val = digit1 + digit2 + carry ... divmod Python provides a divmod function, which both integer-divides a value by some divisor and computes the modulus after division. Using divmod(val, 10) would directly give you the carry and remainder. carry, digit_sum = divmod(digit1 + digit2 + carry, 10) Reworked code The following uses the above changes, plus adds type-hints for the arguments and return value, and a docstring for the whole function. Embedded in the docstring are two "doctest" examples, which is exercised by the doctest.testmod() in the main-guard. from itertools import zip_longest from typing import Sequence
{ "domain": "codereview.stackexchange", "id": 43707, "lm_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, integer", "url": null }
python, integer def sum_digit_by_digit(arr1: Sequence[int], arr2: Sequence[int]) -> list[int]: """ Add two non-negative integers given as two one-dimensional arrays of digits, most-significant digit first. >>> sum_digit_by_digit([3, 4, 5], [5, 6, 9]) [9, 1, 4] >>> sum_digit_by_digit((3, 4, 5), (6, 7, 9)) [1, 0, 2, 4] """ result = [] carry = 0 for digit_1, digit_2 in zip_longest(reversed(arr1), reversed(arr2), fillvalue=0): carry, digit_sum = divmod(digit_1 + digit_2 + carry, 10) result.insert(0, digit_sum) if carry: result.insert(0, carry) return result if __name__ == '__main__': import doctest doctest.testmod() As demonstrated in the doctests, the input to the function may be given as either lists or tuples. Update As noted by @Eugene Yarmash, the insert(0, ...) in the loop is an \$O(N^2)\$ operation, and this would slow down as the number of digits increases. We can use .append(), and reverse the result at the end. from itertools import zip_longest from typing import Sequence def sum_digit_by_digit(arr1: Sequence[int], arr2: Sequence[int]) -> list[int]: """ Add two non-negative integers given as two one-dimensional arrays of digits, most-significant digit first. >>> sum_digit_by_digit([3, 4, 5], [5, 6, 9]) [9, 1, 4] >>> sum_digit_by_digit((3, 4, 5), (6, 7, 9)) [1, 0, 2, 4] """ result = [] carry = 0 for digit_1, digit_2 in zip_longest(reversed(arr1), reversed(arr2), fillvalue=0): carry, digit_sum = divmod(digit_1 + digit_2 + carry, 10) result.append(digit_sum) if carry: result.append(carry) return result[::-1] if __name__ == '__main__': import doctest doctest.testmod()
{ "domain": "codereview.stackexchange", "id": 43707, "lm_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, integer", "url": null }
c++, performance, programming-challenge Title: Leetcode 14. Longest Common Prefix beats only ~50% of C++ solutions Question: The task is to find the longest common prefix. While I had no trouble to find the solution, I'm interested in the statistics of my code: Runtime: 7 ms, faster than 56.36% of C++ online submissions for Longest Common Prefix. Memory Usage: 9.3 MB, less than 54.46% of C++ online submissions for Longest Common Prefix. Although these statistics are taken to be with a grain of salt: 08/06/2022 12:06 Accepted 8 ms 9.1 MB cpp 08/06/2022 12:06 Accepted 6 ms 9.3 MB cpp 08/06/2022 12:00 Accepted 7 ms 9.3 MB cpp So appareantly my code can be optimized in 1 or 2 ways. How can I make it faster? And how can I make it more memory efficient? By what I see, I only allocate memory once, for the storage of the string I need to return. Granted, if the first string happens to be gargantually big and the other prefixes are small, this could be an issue and reserving only the size of the minimum length string would improve this. So maybe let's focus a bit more on the performance site. Try it on godbolt! #include <iostream> #include <vector> std::string f(std::vector<std::string>& strs){ std::string common = ""; common.reserve(strs[0].size()); for( std::size_t i = 0; i < strs[0].size(); ++i ){ for( auto const& str : strs ){ if( str.size() < i || str[i] != strs[0][i] ){ return common; } } common += strs[0][i]; } return common; } int main(){ std::vector<std::string> list = {"hh", "hhho", "hhh"}; std::cout << f(list) << "\n"; }
{ "domain": "codereview.stackexchange", "id": 43708, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, programming-challenge", "url": null }
c++, performance, programming-challenge Answer: Precalculate the size of the shortest string In the inner loop you are checking str.size() < i. Consider that the longest common prefix cannot be longer than the shortest string. I would first try to calculate the size of the shortest string, as this avoids the size check in the inner loop of the actual algorithm: std::string f(std::vector<std::string>& strs){ std::size_t min_size = SIZE_MAX; for (auto& str: strs) min_size = std::min(min_size, str.size()); for(std::size_t i = 0; i < min_size; ++i) for (auto& str: strs) if(str[i] != strs[0][i]) return str.substr(0, i); return strs[0]; } Memory access pattern The algorithm is quite simple, and I strongly suspect the bottleneck is how fast it can read the strings from memory. If you have a large number of strings which don't fit into the CPU cache, then the order in which you check things against each other might matter a lot. RAM access latency can be quite high, but this latency can be hidden by the CPU by looking at your memory access patterns, and prefetching memory based on that pattern. Contemporary CPUs can handle code reading and writing to a few areas in RAM simultaneously, but if for example you are comparing 100 strings, it will not be able to track that, and thus will either not prefetch (bad) or prefetch the wrong things (even worse). So it might be interesting to check only two strings against each other at a time, as that is much more likely to keep the prefetcher happy: std::string f(std::vector<std::string>& strs){ std::size_t min_size = SIZE_MAX; for (auto& str: strs) { min_size = std::min(min_size, str.size()); for (std::size_t i = 0; i < min_size; ++i) if(str[i] != strs[0][i]) { min_size = i; break; } } if (min_size == 0) break; } return strs[0].substr(0, min_size); }
{ "domain": "codereview.stackexchange", "id": 43708, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, programming-challenge", "url": null }
c++, performance, programming-challenge if (min_size == 0) break; } return strs[0].substr(0, min_size); } However, this strategy might work slower than your solution if everything already fit into the cache. You could probably find an even better solution that does something in-between the two strategies: consider checking the first cache line worth of bytes from each string against each other, then the next cache line worth of bytes if necessary, and so on. Avoid checking a given string against itself Both in your code and in my code above, the inner loop will check all strings against the first string. But that includes checking the first string against itself, which is unnecessary. Check multiple characters in one go You are checking individual characters against each other, but on contemporary computers, the CPU typically has registers that are 64 bits wide, and can thus hold 8 characters. There are even vector registers that are larger; with AVX512 you can have 64 characters in one register! For long strings, this might allow you to speed up the algorithm substantially. Say you compare 8 characters at a time, stored in uint64_ts. Then if two of those uint64_ts are equal, you know that all 8 characters are the same, and you can skip to the next set of 8 characters. But if they are not equal, you can still quickly find which of the 8 characters was the first that is not equal by XORing both uint64_ts together, and using std::countl_zero() (since C++20) or ffs() on the result.
{ "domain": "codereview.stackexchange", "id": 43708, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, programming-challenge", "url": null }
java, algorithm, comparative-review, depth-first-search Title: Shortest path in dags: Part 2/3 - the preprocessing and shortest path algorithms Question: Part 1/3 Part 3/3 I have this library for performing shortest path queries on dags (directed acyclic graphs). This post presents the shortest path algorithms and the topological sorters. Two algorithms for topologically sorting the graph nodes are compared: com.github.coderodde.graph.impl.DFSTopologicalSorter (See this; implemented iteratively in order not to cause StackOverflowError.) com.github.coderodde.graph.impl.KahnsTopologicalSorter (See the Kahn's algorithm.) The two actual shortest path algorithms: NaivePreprocessingDagShortestPathQueryRunner, follows the text books on shortest path search in dags, IndexingPreprocessingDagShortestPathQueryRunner, same as above, but with a minor tweak: we compute in \$\Theta(N)\$ a map (call it \$\mu\$ mapping dag nodes to their appearance index in the topologically sorted list \$L\$). Now, in order to find a shortest path from \$s\$ to \$t\$, we compute two indices: \$f = \mu(s)\$ and \$e = \mu(t)\$; if \$f > e\$, there is no path from \$s\$ to \$t\$, and we stop before doing any search; constant time. If, however, \$f \leq e\$, we restrict the search to that range of nodes whose indices are in the range \$[f, e]\$ instead of going through the entire \$L\$. Clearly, assuming the average out-degree is \$d\$, the running time is \$\mathcal{O}(d(\mu(t) - \mu(s)))\$. Below is the code: com.github.coderodde.graph.TopologicalSortChecker.java: package com.github.coderodde.graph; import com.github.coderodde.graph.impl.DirectedGraph; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; /** * This class contains a static method for checking whether the input node list * is topologically sorted. * * @author Rodion "rodde" Efremov * @version 1.6 (Jul 16, 2022) * @since 1.6 (Jul 16, 2022) */ public final class TopologicalSortChecker {
{ "domain": "codereview.stackexchange", "id": 43709, "lm_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, algorithm, comparative-review, depth-first-search", "url": null }
java, algorithm, comparative-review, depth-first-search /** * Checks whether the input node list is in topological order. * * @param graph the graph. * @param nodes the node list to check. * @return {@code true} if and only if the input node list is in * topological order. */ public static boolean isTopologicallySorted(DirectedGraph graph, List<Integer> nodes) { Objects.requireNonNull(nodes); Map<Integer, Integer> indices = getIndexMap(nodes); for (Integer node : nodes) { if (!isValidNodePosition(graph, node, indices)) { return false; } } return true; } /** * Returns the map mapping each node to its appearance index in the * {@code nodes} list. * * @param nodes the node list from which to compute the index map. * @return the node-to-index map. */ private static Map<Integer, Integer> getIndexMap(List<Integer> nodes) { Map<Integer, Integer> map = new HashMap<>(nodes.size()); for (int index = 0; index < nodes.size(); index++) { map.put(nodes.get(index), index); } return map; } /** * Checks that there is no parents of {@code node} on the right of * {@code node}, and that there is no children of {@code node} on the left * of {@code node}. * * @param graph the target graph. * @param node the node to check. * @param indexMap the map mapping nodes to their appearance indices. * @return {@code true} if and only if the {@code node} is in valid * position. */ private static boolean isValidNodePosition(DirectedGraph graph, Integer node, Map<Integer, Integer> indexMap) { Integer nodeIndex = indexMap.get(node);
{ "domain": "codereview.stackexchange", "id": 43709, "lm_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, algorithm, comparative-review, depth-first-search", "url": null }
java, algorithm, comparative-review, depth-first-search for (Integer parent : graph.getParentsOf(node)) { // >= in the condition in order to fail on self-loops: if (indexMap.get(parent) >= nodeIndex) { return false; } } for (Integer child : graph.getChildrenOf(node)) { if (indexMap.get(child) < nodeIndex) { return false; } } return true; } } com.github.coderodde.graph.TopologicalSorter.java: package com.github.coderodde.graph; import com.github.coderodde.graph.impl.DirectedGraph; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * This interface defines the API for topological sorters. * * @author Rodion "rodde" Efremov * @version 1.6 (Jul 15, 2022) * @since 1.6 (Jul 15, 2022) */ public interface TopologicalSorter { /** * Attempts to sort the input graph topologically. If the input graph * contains cycles, an instance of {@link GraphContainsCyclesException} is * thrown. * * @param graph the graph to sort. * @return a list of nodes in topological order. * @throws GraphContainsCyclesException if the input graph contains cycles. */ List<Integer> sort(DirectedGraph graph) throws GraphContainsCyclesException; /** * Removes and returns a node from a set of nodes. * * @param set the set to remove from. * @return a node. */ default Integer removeNodeFromSet(Set<Integer> set) { Iterator<Integer> iterator = set.iterator(); Integer node = iterator.next(); iterator.remove(); return node; }
{ "domain": "codereview.stackexchange", "id": 43709, "lm_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, algorithm, comparative-review, depth-first-search", "url": null }
java, algorithm, comparative-review, depth-first-search /** * Loads the index map from {@code nodeList} to {@code indexMap}. * * @param nodeList the (topologically sorted) list of nodes. * @param indexMap the target map mapping nodes to their appearance indices * in {@code nodeList}. */ default void loadIndexMap(List<Integer> nodeList, Map<Integer, Integer> indexMap) { for (int index = 0; index < nodeList.size(); index++) { indexMap.put(nodeList.get(index), index); } } } com.github.coderodde.graph.sp.AbstractGraphPreprocessor.java: package com.github.coderodde.graph.sp; import com.github.coderodde.graph.TopologicalSorter; import com.github.coderodde.graph.impl.DirectedGraph; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; /** * This abstract class defines the common facilities for graph preprocessor * implementations. * * @author Rodion "rodde" Efremov * @version 1.6 (Jul 19, 2022) * @since 1.6 (Jul 19, 2022) */ public abstract class AbstractGraphPreprocessor { private static final long UNSET_PREPROCESSING_DURATION = -1L; protected final List<Integer> topologicallySortedNodes; protected final Map<Integer, Integer> indexMap; protected long preprocessingDuration = UNSET_PREPROCESSING_DURATION; protected final DirectedGraph graph; public AbstractGraphPreprocessor(DirectedGraph graph) { this.graph = Objects.requireNonNull(graph); this.topologicallySortedNodes = new ArrayList<>(graph.size()); this.indexMap = new HashMap<>(graph.size()); } public abstract void preprocessGraph(); protected void preprocessGraph(TopologicalSorter topologicalSorter) { long startTime = System.currentTimeMillis();
{ "domain": "codereview.stackexchange", "id": 43709, "lm_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, algorithm, comparative-review, depth-first-search", "url": null }
java, algorithm, comparative-review, depth-first-search topologicallySortedNodes.clear(); topologicallySortedNodes.addAll(topologicalSorter.sort(graph)); topologicalSorter.loadIndexMap(topologicallySortedNodes, indexMap); long endTime = System.currentTimeMillis(); long duration = endTime - startTime; this.preprocessingDuration = duration; } public List<Integer> getTopologicallySortedNodes() { return topologicallySortedNodes; } public Map<Integer, Integer> getIndexMap() { return indexMap; } public long getPreprocessingDuration() { if (preprocessingDuration == UNSET_PREPROCESSING_DURATION) { throw new IllegalStateException("Preprocessing was not run."); } return preprocessingDuration; } protected void computeIndexMap() { for (int index = 0; index < topologicallySortedNodes.size(); index++) { indexMap.put(topologicallySortedNodes.get(index), index); } } } com.github.coderodde.graph.sp.AbstractDagShortestPathQueryRunner.java: package com.github.coderodde.graph.sp; import com.github.coderodde.graph.impl.DirectedGraph; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; /** * This abstract class defines the common facilities for the shortest path query * runner implementations. * * @author Rodion "rodde" Efremov * @version 1.6 (Jul 19, 2022) * @since 1.6 (Jul 19, 2022) */ public abstract class AbstractDagShortestPathQueryRunner { protected final DirectedGraph graph; protected final AbstractGraphPreprocessor graphPreprocessor; protected long expectedGraphModCount = -1L; public AbstractDagShortestPathQueryRunner( DirectedGraph graph, AbstractGraphPreprocessor graphPreprocessor) { this.graph = Objects.requireNonNull(graph); this.graphPreprocessor = graphPreprocessor; }
{ "domain": "codereview.stackexchange", "id": 43709, "lm_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, algorithm, comparative-review, depth-first-search", "url": null }
java, algorithm, comparative-review, depth-first-search public abstract long getPreprocessingDuration(); public abstract DirectedGraph.Path queryShortestPath(Integer sourceNode, Integer targetNode); @Override public String toString() { return getClass().getSimpleName() + "[" + graphPreprocessor.getClass().getSimpleName() + "]"; } /** * Reconstructs the shortest path. * * @param targetNode the target node in the target graph. * @param parentMap the map mapping each node to its predecessor. * @return the shortest path. */ protected DirectedGraph.Path tracebackPath(Integer targetNode, Map<Integer, Integer> parentMap) { List<Integer> pathList = new ArrayList<>(); Integer node = targetNode; while (node != null) { pathList.add(node); node = parentMap.get(node); } Collections.reverse(pathList); return new DirectedGraph.Path(graph, pathList); } protected void checkSourceNode(Integer sourceNode) { if (!graph.hasNode(sourceNode)) { throw new IllegalArgumentException( "The source node (" + sourceNode + ") is not in the graph."); } } protected void checkTargetNode(Integer targetNode) { if (!graph.hasNode(targetNode)) { throw new IllegalArgumentException( "The target node (" + targetNode + ") is not in the graph."); } } } com.github.coderodde.graph.sp.impl.IndexingPreprocessingDagShortestPathQueryRunner.java: package com.github.coderodde.graph.sp.impl;
{ "domain": "codereview.stackexchange", "id": 43709, "lm_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, algorithm, comparative-review, depth-first-search", "url": null }
java, algorithm, comparative-review, depth-first-search import com.github.coderodde.graph.PathDoesNotExistException; import com.github.coderodde.graph.impl.DirectedGraph; import com.github.coderodde.graph.sp.AbstractDagShortestPathQueryRunner; import com.github.coderodde.graph.sp.AbstractGraphPreprocessor; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * This class implements a method for running the shortest path queries in dags. * This implementation uses a simple speed-up technique: all the node in the * topologically sorted list {@code L} are mapped to their respective appearance * indices in the sorted list. Now, if the source node is {@code s} and the * target node is {@code t}, and the map is {@code m}, the search traverses * only the range {@code L[m(s) ... m(t)]}. * * @author Rodion "rodde" Efremov * @version 1.6 (Jul 19, 2022) * @since 1.6 (Jul 19, 2022) */ public class IndexingPreprocessingDagShortestPathQueryRunner extends AbstractDagShortestPathQueryRunner { private final List<Integer> topologicallySortedNodes = new ArrayList<>(); private final Map<Integer, Integer> indexMap = new HashMap<>(); /** * Constructs the preprocessing shortest path query provider. * * @param graph the graph in which to run the shortest path * search. * @param graphPreprocessor the graph preprocessor. */ public IndexingPreprocessingDagShortestPathQueryRunner( DirectedGraph graph, AbstractGraphPreprocessor graphPreprocessor) { super(graph, graphPreprocessor); } @Override public DirectedGraph.Path queryShortestPath(Integer sourceNode, Integer targetNode) { checkGraphDirtyStatus(); checkSourceNode(sourceNode); checkTargetNode(targetNode); Map<Integer, Double> costMap = new HashMap<>(); Map<Integer, Integer> parentMap = new HashMap<>();
{ "domain": "codereview.stackexchange", "id": 43709, "lm_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, algorithm, comparative-review, depth-first-search", "url": null }
java, algorithm, comparative-review, depth-first-search costMap.put(sourceNode, 0.0); parentMap.put(sourceNode, null); int sourceIndex = indexMap.get(sourceNode); int targetIndex = indexMap.get(targetNode); for (int i = sourceIndex; i <= targetIndex; i++) { Integer node = topologicallySortedNodes.get(i); if (!costMap.containsKey(node)) { continue; } if (node.equals(targetNode)) { return tracebackPath(node, parentMap); } for (Integer child : graph.getChildrenOf(node)) { if (!costMap.containsKey(child) || costMap.get(child) > costMap.get(node) + graph.getEdgeWeight(node, child)) { costMap.put(child, costMap.get(node) + graph.getEdgeWeight(node, child)); parentMap.put(child, node); } } } throw new PathDoesNotExistException(sourceNode, targetNode); } @Override public long getPreprocessingDuration() { return graphPreprocessor.getPreprocessingDuration(); } private void checkGraphDirtyStatus() { if (expectedGraphModCount != graph.getModificationCount()) { expectedGraphModCount = graph.getModificationCount(); graphPreprocessor.preprocessGraph(); topologicallySortedNodes.clear(); topologicallySortedNodes.addAll( graphPreprocessor.getTopologicallySortedNodes()); indexMap.clear(); indexMap.putAll(graphPreprocessor.getIndexMap()); } } } com.github.coderodde.graph.sp.impl.NaivePreprocessingDagShortestPathQueryRunner.java: package com.github.coderodde.graph.sp.impl;
{ "domain": "codereview.stackexchange", "id": 43709, "lm_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, algorithm, comparative-review, depth-first-search", "url": null }
java, algorithm, comparative-review, depth-first-search import com.github.coderodde.graph.PathDoesNotExistException; import com.github.coderodde.graph.impl.DirectedGraph; import com.github.coderodde.graph.sp.AbstractDagShortestPathQueryRunner; import com.github.coderodde.graph.sp.AbstractGraphPreprocessor; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * This class implements a method for running shortest path queries. * * @author Rodion "rodde" Efremov * @version 1.6 (Jul 19, 2022) * @since 1.6 (Jul 19, 2022) */ public class NaivePreprocessingDagShortestPathQueryRunner extends AbstractDagShortestPathQueryRunner { private final List<Integer> topologicallySortedNodes = new ArrayList<>(); /** * Constructs the preprocessing shortest path query provider. * * @param graph the graph in which to run the shortest path * search. * @param graphPreprocessor the graph preprocessor. */ public NaivePreprocessingDagShortestPathQueryRunner( DirectedGraph graph, AbstractGraphPreprocessor graphPreprocessor) { super(graph, graphPreprocessor); } @Override public DirectedGraph.Path queryShortestPath(Integer sourceNode, Integer targetNode) { // If this runner's expected mod count does not match the mod count of // the graph, graph is changed and so we need to re-preprocess the // graph. checkGraphDirtyStatus(); checkSourceNode(sourceNode); checkTargetNode(targetNode); Map<Integer, Double> costMap = new HashMap<>(); Map<Integer, Integer> parentMap = new HashMap<>(); costMap.put(sourceNode, 0.0); parentMap.put(sourceNode, null); for (Integer node : topologicallySortedNodes) { if (!costMap.containsKey(node)) { continue; }
{ "domain": "codereview.stackexchange", "id": 43709, "lm_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, algorithm, comparative-review, depth-first-search", "url": null }
java, algorithm, comparative-review, depth-first-search if (node.equals(targetNode)) { return tracebackPath(node, parentMap); } for (Integer child : graph.getChildrenOf(node)) { if (!costMap.containsKey(child) || costMap.get(child) > costMap.get(node) + graph.getEdgeWeight(node, child)) { costMap.put(child, costMap.get(node) + graph.getEdgeWeight(node, child)); parentMap.put(child, node); } } } throw new PathDoesNotExistException(sourceNode, targetNode); } @Override public long getPreprocessingDuration() { return graphPreprocessor.getPreprocessingDuration(); } private void checkGraphDirtyStatus() { if (expectedGraphModCount != graph.getModificationCount()) { expectedGraphModCount = graph.getModificationCount(); graphPreprocessor.preprocessGraph(); topologicallySortedNodes.clear(); topologicallySortedNodes.addAll( graphPreprocessor.getTopologicallySortedNodes()); } } } com.github.coderodde.graph.impl.DFSTopologicalSorter.java: package com.github.coderodde.graph.impl; import com.github.coderodde.graph.GraphContainsCyclesException; import com.github.coderodde.graph.TopologicalSorter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** * This class implements a method for topologically sorting graph nodes via * DFS-like algorithm. * * @author Rodion "rodde" Efremov * @version 1.6 (Jul 19, 2022) * @since 1.6 (Jul 19, 2022) */ public class DFSTopologicalSorter implements TopologicalSorter {
{ "domain": "codereview.stackexchange", "id": 43709, "lm_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, algorithm, comparative-review, depth-first-search", "url": null }
java, algorithm, comparative-review, depth-first-search @Override public List<Integer> sort(DirectedGraph graph) throws GraphContainsCyclesException { List<Integer> sortedNodes = new ArrayList<>(graph.size()); Set<Integer> unmarkedNodes = new HashSet<>(graph.getAllNodes()); Set<Integer> temporarilyMarkedNodes = new HashSet<>(); Set<Integer> permanentlyMarkedNodes = new HashSet<>(); Deque<Integer> nodeStack = new ArrayDeque<>(); Deque<Iterator<Integer>> iteratorStack = new ArrayDeque<>(); while (!unmarkedNodes.isEmpty()) { Integer root = removeNodeFromSet(unmarkedNodes); nodeStack.add(root); iteratorStack.add(graph.getChildrenOf(root).iterator()); visit(graph, nodeStack, iteratorStack, unmarkedNodes, temporarilyMarkedNodes, permanentlyMarkedNodes, sortedNodes); } Collections.reverse(sortedNodes); return sortedNodes; } private static void visit(DirectedGraph graph, Deque<Integer> nodeStack, Deque<Iterator<Integer>> iteratorStack, Set<Integer> unmarkedNodes, Set<Integer> temporarilyMarkedNodes, Set<Integer> permanentlyMarkedNodes, List<Integer> sortedNodes) { mainLoop: while (!nodeStack.isEmpty()) { Integer node = nodeStack.peek(); Iterator<Integer> iterator = iteratorStack.peek(); unmarkedNodes.remove(node); temporarilyMarkedNodes.add(node); while (iterator.hasNext()) { Integer child = iterator.next();
{ "domain": "codereview.stackexchange", "id": 43709, "lm_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, algorithm, comparative-review, depth-first-search", "url": null }
java, algorithm, comparative-review, depth-first-search while (iterator.hasNext()) { Integer child = iterator.next(); if (unmarkedNodes.contains(child)) { nodeStack.push(child); iteratorStack.push(graph.getChildrenOf(child).iterator()); continue mainLoop; } else if (temporarilyMarkedNodes.contains(child)) { throw new GraphContainsCyclesException(); } } while (!iteratorStack.isEmpty() && !iteratorStack.peek().hasNext()) { iteratorStack.pop(); node = nodeStack.pop(); temporarilyMarkedNodes.remove(node); permanentlyMarkedNodes.add(node); sortedNodes.add(node); } } } } com.github.coderodde.graph.impl.KahnsTopologicalSorter.java: package com.github.coderodde.graph.impl; import com.github.coderodde.graph.GraphContainsCyclesException; import com.github.coderodde.graph.TopologicalSorter; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** * This class implements the * <a href="https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm">Kahn's algorithm</a> for topologically sorting * graph nodes. * * @author Rodion "rodde" Efremov * @version 1.6 (Jul 19, 2022) * @since 1.6 (Jul 19, 2022) */ public class KahnsTopologicalSorter implements TopologicalSorter { @Override public List<Integer> sort(DirectedGraph graph) throws GraphContainsCyclesException { List<Integer> children = new ArrayList<>(graph.size()); // First, get a copy of the input graph, since the algorithm removes // the arcs from the graph it works on: graph = new DirectedGraph(graph); List<Integer> sortedNodeList = new ArrayList<>(graph.size()); Set<Integer> nodesToProcess = getStartNodes(graph);
{ "domain": "codereview.stackexchange", "id": 43709, "lm_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, algorithm, comparative-review, depth-first-search", "url": null }
java, algorithm, comparative-review, depth-first-search while (!nodesToProcess.isEmpty()) { Integer node = removeFromSet(nodesToProcess); sortedNodeList.add(node); children.clear(); children.addAll(graph.getChildrenOf(node)); for (Integer child : children) { graph.removeEdge(node, child); if (graph.getParentsOf(child).size() == 0) { nodesToProcess.add(child); } } } if (graph.getNumberOfEdges() > 0) { throw new GraphContainsCyclesException(); } return sortedNodeList; } private Set<Integer> getStartNodes(DirectedGraph graph) { Set<Integer> set = new HashSet<>(); for (Integer node : graph.getAllNodes()) { if (graph.getParentsOf(node).isEmpty()) { set.add(node); } } return set; } private Integer removeFromSet(Set<Integer> set) { Iterator<Integer> iterator = set.iterator(); Integer node = iterator.next(); iterator.remove(); return node; } } Critique request As always, tell me anything that comes to mind. Answer: duplicated code com.github.coderodde.graph.sp.impl.AbstractDagShortestPathQueryRunner implementations have much code in common, provide a proper method to reduce duplications (DRY) for (Integer node : topologicallySortedNodes) { if (!costMap.containsKey(node)) { continue; } if (node.equals(targetNode)) { return tracebackPath(node, parentMap); } for (Integer child : graph.getChildrenOf(node)) { if (!costMap.containsKey(child) ... ) { //shortened see next issue costMap.put(child, costMap.get(node) + graph.getEdgeWeight(node, child)); parentMap.put(child, node); } } }
{ "domain": "codereview.stackexchange", "id": 43709, "lm_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, algorithm, comparative-review, depth-first-search", "url": null }
java, algorithm, comparative-review, depth-first-search parentMap.put(child, node); } } } should be for (Integer node : topologicallySortedNodes) { if (!costMap.containsKey(node)) { continue; } if (node.equals(targetNode)) { return tracebackPath(node, parentMap); } for (Integer child : graph.getChildrenOf(node)) { expandIfRequired(node, child); } } first class collections instead of using Maps and Listss directly wrap your Collections in a class. This Clean Code Principle helps you to write more readable code let's assume you have a first class collection for costMap and see how this lightens your code: for (Integer node : topologicallySortedNodes) { if (costMap.isNotInMap(node)) { //far more readable continue; } } and as mentioned before, you can now put your conditions on the proper place: if (!costMap.containsKey(child) || costMap.get(child) > costMap.get(node) + graph.getEdgeWeight(node, child)) ... } would have a proper place: if (costMap.requiresExpansion(node, child)){ //anyone can now read this code ... }
{ "domain": "codereview.stackexchange", "id": 43709, "lm_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, algorithm, comparative-review, depth-first-search", "url": null }
javascript, beginner, html, dom Title: Find and replace text in a webpage with JavaScript Question: I am new to web development and would like to get feedback on a JavaScript library that automatically finds and replaces text on a webpage using the MutationObserver interface. EDIT: Seeing that this has gone a week unanswered I've cut out non-essential code to reduce the line count from 300 to more manageable 150. The README may also be helpful in understanding how it is meant to be used. My main questions are: As you might have inferred from the heavy use of private variables, I have a Java background. Is such usage of OOP/encapsulation idiomatic in JS? To prevent replacements made by one observer's callback from alerting other observers and creating an infinite "ping-pong" effect, I store every created TextObserver in a static class variable and deactivate them before running the callback. Is this good practice? It feels like a God object. Is there anything else I should do to make this more fit for use as a library? (UMD?) And is the README understandable? (If it is appropriate to ask for reviews on documentation here.) class TextObserver { #target; #callback; #observer; // Sometimes, MutationRecords of type 'childList' have added nodes with overlapping subtrees // Nodes can also be removed and reattached from one parent to another // This can cause resource usage to explode with "recursive" replacements, e.g. expands -> physically expands // The processed set ensures that each added node is only processed once so the above doesn't happen #processed = new Set(); // Keep track of all created observers to prevent infinite callbacks static #observers = new Set();
{ "domain": "codereview.stackexchange", "id": 43710, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, html, dom", "url": null }
javascript, beginner, html, dom // Use static read-only properties as class constants static get #IGNORED_NODES() { // Node types that implement the CharacterData interface but are not relevant or visible to the user return [Node.CDATA_SECTION_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE]; } static get #IGNORED_TAGS() { // Text nodes that are not front-facing content return ['SCRIPT', 'STYLE', 'NOSCRIPT']; } static get #CONFIG() { return { subtree: true, childList: true, characterData: true, characterDataOldValue: true, }; } constructor(callback, target = document, processExisting = true) { this.#callback = callback; // If target is entire document, manually process <title> and skip the rest of the <head> // Processing the <head> can increase runtime by a factor of two if (target === document) { document.title = callback(document.title); // Sometimes <body> may be missing, like when viewing an .SVG file in the browser if (document.body !== null) { target = document.body; } else { console.warn('Document body does not exist, exiting...'); return; } } this.#target = target; if (processExisting) { TextObserver.#flushAndSleepDuring(() => this.#processNodes(target)); }
{ "domain": "codereview.stackexchange", "id": 43710, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, html, dom", "url": null }
javascript, beginner, html, dom const observer = new MutationObserver(mutations => { const records = []; for (const textObserver of TextObserver.#observers) { // This ternary is why this section does not use flushAndSleepDuring // It allows the nice-to-have property of callbacks being processed in the order they were declared records.push(textObserver === this ? mutations : textObserver.#observer.takeRecords()); textObserver.#observer.disconnect(); } let i = 0; for (const textObserver of TextObserver.#observers) { textObserver.#observerCallback(records[i]); i++; } TextObserver.#observers.forEach(textObserver => textObserver.#observer.observe(textObserver.#target, TextObserver.#CONFIG)); }); observer.observe(target, TextObserver.#CONFIG); this.#observer = observer; TextObserver.#observers.add(this); }
{ "domain": "codereview.stackexchange", "id": 43710, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, html, dom", "url": null }
javascript, beginner, html, dom this.#observer = observer; TextObserver.#observers.add(this); } #observerCallback(mutations) { for (const mutation of mutations) { const target = mutation.target; switch (mutation.type) { case 'childList': for (const node of mutation.addedNodes) { if (node.nodeType === Node.TEXT_NODE) { if (this.#valid(node) && !this.#processed.has(node)) { node.nodeValue = this.#callback(node.nodeValue); this.#processed.add(node); } } else if (!TextObserver.#IGNORED_NODES.includes(node.nodeType)) { // If added node is not text, process subtree this.#processNodes(node); } } break; case 'characterData': if (this.#valid(target) && target.nodeValue !== mutation.oldValue) { target.nodeValue = this.#callback(target.nodeValue); this.#processed.add(target); } break; } } }
{ "domain": "codereview.stackexchange", "id": 43710, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, html, dom", "url": null }
javascript, beginner, html, dom static #flushAndSleepDuring(callback) { // Disconnect all other observers to prevent infinite callbacks const records = []; for (const textObserver of TextObserver.#observers) { // Collect pending mutation notifications records.push(textObserver.#observer.takeRecords()); textObserver.#observer.disconnect(); } // This is in its own separate loop from the above because we want to disconnect everything before proceeding // Otherwise, the mutations in the callback may trigger the other observers let i = 0; for (const textObserver of TextObserver.#observers) { textObserver.#observerCallback(records[i]); i++; } callback(); TextObserver.#observers.forEach(textObserver => textObserver.#observer.observe(textObserver.#target, TextObserver.#CONFIG)); } #valid(node) { return ( // Sometimes the node is removed from the document before we can process it, so check for valid parent node.parentNode !== null && !TextObserver.#IGNORED_NODES.includes(node.nodeType) && !TextObserver.#IGNORED_TAGS.includes(node.parentNode.tagName) // Ignore contentEditable elements as touching them messes up the cursor position && !node.parentNode.isContentEditable // HACK: workaround to avoid breaking icon fonts && !window.getComputedStyle(node.parentNode).getPropertyValue('font-family').toUpperCase().includes('ICON') ); }
{ "domain": "codereview.stackexchange", "id": 43710, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, html, dom", "url": null }
javascript, beginner, html, dom #processNodes(root) { // Process valid Text nodes const nodes = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { acceptNode: node => ( this.#valid(node) && !this.#processed.has(node)) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT }); while (nodes.nextNode()) { nodes.currentNode.nodeValue = this.#callback(nodes.currentNode.nodeValue); this.#processed.add(nodes.currentNode); } } } // A good page to try this out on would be https://en.wikipedia.org/wiki/Heck const badWordFilter = new TextObserver(text => text.replaceAll(/heck/gi, 'h*ck')); Answer: From a short review; Classes are idiomatic (and becoming more so over time), but the heavy usage of private variables makes the code harder to read for me. For production code, I would drop calls to console.warn() it does not seem warranted here Unless you are worried about observers not managed in TextObserver, I would have a static in your class called sleepMode, and in your mutation observer you leave immediately if sleepMode is on. To me that would be KISS and remove the Gode Mode problem. The name of TextObserver is not great, it is meant to replace text which is not clear from the name In the README, I would follow the Mozilla format/approach for the replacement function you pass instead of just a function that takes a string as its only argument and returns a string to replace it with I would add a feature where an observer can have a list/array of functions to apply so that the event needs to be processed only once and then have something like const grammarPolice = new TextObserver(text => text.replaceAll(/would of/gi, 'would have')); grammarPolice.add(text => text.replaceAll(/should of/gi, 'should have')); Comments are good, but some of them are too much like // Use static read-only properties as class constants I would have called valid -> isValid
{ "domain": "codereview.stackexchange", "id": 43710, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, html, dom", "url": null }
javascript, beginner, html, dom I would have called valid -> isValid Overall, my first impression was that this looked indeed like a Java coder writing, but really after a closer look, this is just battled tested code.
{ "domain": "codereview.stackexchange", "id": 43710, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, html, dom", "url": null }
python, database, django Title: Summing categories of financial records per month in a query Question: My program is working properly but I'm unconfortable with code repetition. class Movimentacao(models.Model): data = models.DateField() # complete datetime field from 2019->2022 movimentacao = models.CharField(max_length=200) # text field valor_da_operacao = models.DecimalField(max_digits=19, decimal_places=2) # decimal field # get all objects filtered by `movimentacao` field proventos = Movimentacao.objects.filter(movimentacao__in=('Dividendo', 'Juros Sobre Capital Próprio', 'Rendimento', 'Reembolso')).order_by('data', 'id') currentDate = proventos[0].data # get date from the first record lastRecord = proventos.last().id # get ID from the last record assets = [] stockSum = 0 fiiSum = 0 for m in proventos: if(m.data.month != currentDate.month or lastRecord == m.id): dataFormatada = f'{currentDate.strftime("%y")}-{currentDate.strftime("%b")}' if(lastRecord == m.id): # first if-else block (necessary but I'd like to 'remove') if(m.movimentacao == 'Dividendo'): stockSum += m.valor_da_operacao if(m.movimentacao == 'Rendimento'): fiiSum += m.valor_da_operacao assets.append([dataFormatada, 'FIIs', fiiSum]) assets.append([dataFormatada, 'Stocks', stockSum]) stockSum = 0 fiiSum = 0 currentDate = m.data # second if-else block (this one I can't remove) if(m.movimentacao == 'Dividendo'): stockSum += m.valor_da_operacao if(m.movimentacao == 'Rendimento'): fiiSum += m.valor_da_operacao As you can see, the code below is being repeteaded: if(m.movimentacao == 'Dividendo'): stockSum += m.valor_da_operacao if(m.movimentacao == 'Rendimento'): fiiSum += m.valor_da_operacao
{ "domain": "codereview.stackexchange", "id": 43711, "lm_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, database, django", "url": null }
python, database, django if(m.movimentacao == 'Rendimento'): fiiSum += m.valor_da_operacao The goal of this code is to build the assets list formatted accordingly below: [ ["19-Nov", "FII", 411.97], ["19-Nov", "Stocks", 0], ["19-Dec", "FII", 368.21], ["19-Dec", "Stocks", 1542.08], ["20-Jan", "FII", 0], ["20-Jan", "Stocks", 401.06], ] In this way, I'd like to see if it's possible to "remove" the first if-else statement, keeping the code working properly (this would be my first choice). The issue is: if I remove the first if-else statement, the variable m.movimentacao from the last object is not added inside stockSum or fiiSum variables - that was the reason I need to insert the first if-else statement. The last object can't reach the last if-else statement to be checked either m.movimentacao is a 'Dividendo' or 'Rendimento'. If not, what is the best way to avoid code repetition in this case (function use)? Answer: Mixing Portuguese and English makes this code messy. Please pick one or the other. I recommend coding consistently in English, because Python, its library, and its code ecosystem are in English, so Portuguese will always feel out of place. Why do you call .filter(movimentacao__in=('Dividendo', 'Juros Sobre Capital Próprio', 'Rendimento', 'Reembolso'), when only "Dividendo" and "Rendimento" matter for building assets? Also, wouldn't you want to do another two assets.append(…) statements at the end of this code? This date formatting code is clumsy: dataFormatada = f'{currentDate.strftime("%y")}-{currentDate.strftime("%b")}' … and it could be better expressed as dataFormatada = currentDate.strftime("%y-%b")
{ "domain": "codereview.stackexchange", "id": 43711, "lm_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, database, django", "url": null }
python, database, django … and it could be better expressed as dataFormatada = currentDate.strftime("%y-%b") But really, none of this loop should exist: all of the filtering and summation should be done by the database instead! Transferring so much data from the database to Python for analysis defeats the purpose of the database. It would be more efficient, scalable, and readable to do this in SQL rather than Python. Here's a query (and a fiddle) for postgresql that gets you the same results: SELECT DISTINCT date_trunc('month', data) AS mes, CASE WHEN movimentacao = 'Dividendo' THEN 'Stocks' ELSE 'FIIs' END AS categoria, SUM(valor_da_operacao) OVER monthly AS total FROM Movimentacao WHERE movimentacao IN ('Dividendo', 'Rendimento') WINDOW monthly AS (PARTITION BY date_trunc('month', data), movimentacao) ORDER BY mes, categoria; You can use a similar query for sqlite, except that the datetime functions are different: SELECT DISTINCT date(data, 'start of month') AS mes, CASE WHEN movimentacao = 'Dividendo' THEN 'Stocks' ELSE 'FIIs' END AS categoria, SUM(valor_da_operacao) OVER monthly AS total FROM Movimentacao WHERE movimentacao IN ('Dividendo', 'Rendimento') WINDOW monthly AS (PARTITION BY date(data, 'start of month'), movimentacao) ORDER BY mes, categoria;
{ "domain": "codereview.stackexchange", "id": 43711, "lm_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, database, django", "url": null }
python, database, django Well, almost the same results. With your Python code, if there is any month in which there is a Dividendo but no Rendimento, or vice versa, both "FIIs" and "Stocks" get appended to assets anyway — one of them having a 0 value. With some creativity and perhaps some Common Table Expressions, the SQL query can be tweaked to produce such 0 values as well: WITH MovimentacaoRelevante AS ( SELECT date(data, 'start of month') AS mes, movimentacao, valor_da_operacao FROM Movimentacao WHERE movimentacao IN ('Dividendo', 'Rendimento') ), MovimentacaoRelevanteComZeros AS ( SELECT * FROM MovimentacaoRelevante UNION ALL SELECT DISTINCT mes, 'Dividendo', 0 AS total FROM MovimentacaoRelevante UNION ALL SELECT DISTINCT mes, 'Rendimento', 0 AS total FROM MovimentacaoRelevante ) SELECT DISTINCT mes, CASE WHEN movimentacao = 'Dividendo' THEN 'Stocks' ELSE 'FIIs' END AS categoria, SUM(valor_da_operacao) OVER monthly AS total FROM MovimentacaoRelevanteComZeros WINDOW monthly AS (PARTITION BY mes, movimentacao) ORDER BY mes, categoria;
{ "domain": "codereview.stackexchange", "id": 43711, "lm_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, database, django", "url": null }
javascript, object-oriented, timer, observer-pattern Title: JS stopwatch using the observer pattern Question: I'm learning OOP and also trying to learn and implement some design patterns. This question is a follow-up of Stopwatch interface OOP (Vanilla JS) The app is available in https://nacho-p5.github.io/ Here's the code: Repo: https://github.com/nacho-p5/nacho-p5.github.io The community gave me good feedback and I made the following changes to my first codebase: Changed syntax to ES6 Methods added to prototype rather than the instance Names changed to be descriptive Replaced error handler logic when start/stop are clicked twice Time tracker logic changed. The count is calculated using Date.now() rather than counting setInterval iterations Script tag position changed to head using defer The stopwatch class should not know about the DOM -> Observer pattern implemented As I wrote in the last point, I refactored the code using the observer pattern. I had two goals doing that: Implement the observer pattern One class - One thing: separation of concerns in stopwatch, UI and controller class I know that trying to implement design patterns in a simple problem like this seems like overwork. This is purely for learning purposes. What do you think about the code? Any feedback will be appreciated :) stopwatch.js class Stopwatch { _timer = 0; isRunning = false; startTime = 0; elapsedTime = 0 observers = [] get timer() { return this._timer } set timer(val) { this._timer = val this.notifyController(val) } registerObserver(observer) { this.observers.push(observer); }; notifyController(val) { this.observers.forEach(observer => {observer.update(val)}) } updateTime() { const newTime = Date.now() - this.startTime + this.elapsedTime; this.timer = newTime; };
{ "domain": "codereview.stackexchange", "id": 43712, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, object-oriented, timer, observer-pattern", "url": null }
javascript, object-oriented, timer, observer-pattern start() { if (!this.isRunning) { this.isRunning = true; this.startTime = Date.now(); this.setIntervalID = setInterval(this.updateTime.bind(this), 100); }; }; stop() { if (this.isRunning) { clearInterval(this.setIntervalID); this.isRunning = false; this.elapsedTime = this._timer; }; }; reset() { clearInterval(this.setIntervalID); this.isRunning = false this.elapsedTime = 0; this.startTime = 0; this.timer = 0; }; }; class UI { constructor(displayID, btnStartID, btnStopID, btnResetID) { // HTML Components this.buttons = { start: document.getElementById(btnStartID), stop: document.getElementById(btnStopID), reset: document.getElementById(btnResetID) }, this.display = document.getElementById(displayID) }; resetAllButtonsStyle() { Object.values(this.buttons).forEach(e => e.classList.remove('activeBtn')) }; showButtonAsActive(btn) { this.resetAllButtonsStyle(); btn.classList.add('activeBtn') }; updateDisplay(value) { this.display.innerText = value; }; } class Controller { constructor(sw, ui) { this.sw = sw; this.ui = ui; // Add event listeners this.ui.buttons.start.addEventListener('click', function() { sw.start(); ui.showButtonAsActive(this); }); this.ui.buttons.stop.addEventListener('click', function() { if (sw.isRunning) { sw.stop(); ui.showButtonAsActive(this); }; }); this.ui.buttons.reset.addEventListener('click', function() { sw.reset(); ui.resetAllButtonsStyle(); }); } update(val) { ui.updateDisplay((val/1000).toFixed(3)) } } // Initialize classes
{ "domain": "codereview.stackexchange", "id": 43712, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, object-oriented, timer, observer-pattern", "url": null }
javascript, object-oriented, timer, observer-pattern update(val) { ui.updateDisplay((val/1000).toFixed(3)) } } // Initialize classes const ui = new UI('sw-display', 'btnStart', 'btnStop', 'btnReset'); const sw = new Stopwatch(); const controller = new Controller(sw, ui); // Register controller in sw sw.registerObserver(controller); //////////////////////// Answer: This is overall very good-looking; I would be willing to support/maintain this. I could only find one thing, which is your use of semicolons: sometimes they are missing, and sometimes they are extraneous. You can use https://jshint.com/ to check for this.
{ "domain": "codereview.stackexchange", "id": 43712, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, object-oriented, timer, observer-pattern", "url": null }
java, programming-challenge Title: Partition List in 2 parts Question: I came up with the following code while trying to solve the Leetcode partition list problem Though my solution is accepted, I am not happy with a few of the additional variables which I am creating. In the code below, I would like to avoid creation of tailEnd and headEnd variables somehow. Can you please review the code and suggest a better way to write this code. public ListNode partition(ListNode head, int x) { ListNode partitionHead = null; ListNode partitionTail = null; ListNode headEnd = null; ListNode tailEnd = null; ListNode node = head; while (node != null) { if (node.val <x ) { if (partitionHead == null) { partitionHead = node; } else { headEnd.next = node; } headEnd = node; } else { if (partitionTail == null) { partitionTail = node; } else { tailEnd.next = node; } tailEnd = node; } node = node.next; } if (tailEnd != null) { tailEnd.next = null; } if (partitionHead == null) { return partitionTail; } headEnd.next = partitionTail; return partitionHead; } Answer: violation of the IOSP it would have helped me greatly to understand your code if you had applied the clean code rule of IOSP: IOSP calls for a clear separation: Either a method contains exclusively logic, meaning transformations, control structures or API invocations. Then it’s called an Operation. Or a method does not contain any logic but exclusively calls other methods within its code basis. Then it’s called Integration. what i would have expected: if(isBelowThreshold(currentNode)){ pushToHead(currentNode ); }else{ pushToTail(currentNode); } currentNode = getNext();
{ "domain": "codereview.stackexchange", "id": 43713, "lm_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, programming-challenge", "url": null }
java, programming-challenge what i actually received: if (node.val <x ) { if (partitionHead == null) { partitionHead = node; } else { headEnd.next = node; } headEnd = node; } else { if (partitionTail == null) { partitionTail = node; } else { tailEnd.next = node; } tailEnd = node; } node = node.next; IOSP is super simple and super valuable, it: splits your code into testable methods increases readability and reduces complexity makes your code easier to change (just add a step or remove one or change order) if you need more inspiriation about read this article
{ "domain": "codereview.stackexchange", "id": 43713, "lm_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, programming-challenge", "url": null }
javascript, interview-questions Title: Grouping objects in a JavaScript array by category and counting them Question: I recently had a programming interview with a Silicon Valley tech company and wanted some different opinions on one of the problems they had me solve and how others might complete it. Essentially, given an array of objects: const events = [ {'category': 'Bug', 'date': '26.07.22', 'resolved': false}, {'category': 'Breach', 'date': '26.07.22', 'resolved': false}, {'category': 'Bug', 'date': '24.07.22', 'resolved': true}, {'category': 'Bug', 'date': '24.07.22', 'resolved': true}, {'category': 'Bug', 'date': '24.07.22', 'resolved': false}, {'category': 'Restart', 'date': '22.07.22', 'resolved': true}, {'category': 'Breach', 'date': '21.07.22', 'resolved': false}] Return another array of objects to the user that list the unique category names and how many of them were found in the original array, like so: [{category: 'Breach', count: 2}, {category: 'Bug', count: 4}, {category: 'Restart', count: 1}] How I managed it: let categoryArray = []; for (let i = 0; i < events.length; i++) { categoryArray[i] = events[i].category; } categoryArray.sort(); let count = 1; let finalObjectArray = []; for (let i = 0; i < categoryArray.length; i++) { let blankObject = { category: "", count: "" }; let curr = categoryArray[i]; let next = categoryArray[i + 1]; if (curr === next) { count++; } else { blankObject.category = categoryArray[i]; blankObject.count = count; finalObjectArray.push(blankObject); count = 1; } } Answer: The following may be more performant (less operations and memory usage), as well as easier to understand. I would say that using the sort and loop in the original code, while creative, is a bit difficult to read and doesn't take advantage of native data types and methods that could help accomplish its goals. I also might suggest adding some comments to explain the code.
{ "domain": "codereview.stackexchange", "id": 43714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, interview-questions", "url": null }
javascript, interview-questions const events = [ {'category': 'Bug', 'date': '26.07.22', 'resolved': false}, {'category': 'Breach', 'date': '26.07.22', 'resolved': false}, {'category': 'Bug', 'date': '24.07.22', 'resolved': true}, {'category': 'Bug', 'date': '24.07.22', 'resolved': true}, {'category': 'Bug', 'date': '24.07.22', 'resolved': false}, {'category': 'Restart', 'date': '22.07.22', 'resolved': true}, {'category': 'Breach', 'date': '21.07.22', 'resolved': false}]; // create categories object to count category items let categories = {}; events.forEach( ( eventObject ) => { if ( categories.hasOwnProperty( eventObject.category ) ) { categories[eventObject.category]++; } else { categories[eventObject.category] = 1; } } ); // convert object to array of objects (if this is really needed) categories = Object.keys( categories ).map( ( key ) => { return { 'category': key, 'count': categories[key] } } ); console.log( categories );
{ "domain": "codereview.stackexchange", "id": 43714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, interview-questions", "url": null }
python, c++, ffi Title: C++ wrapper to call Python code Question: I'm wondering if the following Python wrapper for C++ I'm developing is worth expanding upon and including in my portfolio. If so, I plan to add more parameter options and return types. The problem is, that I don't know if my current path is any good. Is my current implementation too amateur? I'm aware there are already libraries for this, but again, this is for fun/experience, and I need more projects in my portfolio. I currently only have one big project and feel I need more. I'm a second-year CS student hoping to apply for my first job in CS soon. /** * Constructor. Initializes m_pyObject to the specified Python class, t_objName. */ PyInterface::PyInterface(string t_objName) { char* className = new char[t_objName.length() + 1]; strcpy(className, t_objName.c_str()); PyObject * pName, * pModule, * pDict, * pClass; Py_Initialize(); // Initialize the Python Interpreter pName = PyUnicode_FromString((char*)"PythonCode"); // Build the name object pModule = PyImport_Import(pName); // Load the module object pDict = PyModule_GetDict(pModule); pClass = PyDict_GetItemString(pDict, className); if (PyCallable_Check(pClass)) { m_pyObject = PyObject_CallObject(pClass, nullptr); } else { PyErr_Print(); } // Clean up Py_DECREF(pName); Py_DECREF(pModule); Py_DECREF(pDict); Py_DECREF(pClass); delete[] className; } /** * Calls Python method, t_method, of class m_pyObject. * For use with Python methods that do not return data. */ void PyInterface::callPyMethod(string t_method) { char* methodName = new char[t_method.length() + 1]; strcpy(methodName, t_method.c_str()); PyObject_CallMethod(m_pyObject, methodName, NULL); // Call specified Python method, t_method.
{ "domain": "codereview.stackexchange", "id": 43715, "lm_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, c++, ffi", "url": null }
python, c++, ffi delete[] methodName; } /** * Calls Python method, t_method, with param t_param, of class m_pyObject. * For use with Python methods that return a long int. * * @return Python long int converted to C++ int. */ int PyInterface::callPyMethodInt(string t_method, string t_param) { char* methodName = new char[t_method.length() + 1]; strcpy(methodName, t_method.c_str()); string* paramptr = &t_param; // Create pointer to param. PyObject* returnValue = PyObject_CallMethod(m_pyObject, methodName, "(s)", paramptr); // Python class and method name with string param to be converted and used. delete[] methodName; return _PyLong_AsInt(returnValue); } #ifndef Py_Interface_H #define Py_Interface_H #include <Python.h> #include <string> using namespace std; /** * C++ class to easily interface with Python classes and methods. * * Stores member variable/pointer m_pyObject of type PyObject. * m_pyObject is a pointer to the specified Python class and is * used in subsequent method calls handled by callPyMethod and * callPyMethodInt. * * Designed to reduce redundant calls to Python and increase * modularity. */ class PyInterface { public: PyInterface(string t_objName); void callPyMethod(string t_method); int callPyMethodInt(string method, string t_param); private: PyObject* m_pyObject = nullptr; }; #endif Do I have something worth building upon? Everything works, but I don't know if this is a suitable format for a wrapper, etc.
{ "domain": "codereview.stackexchange", "id": 43715, "lm_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, c++, ffi", "url": null }
python, c++, ffi Answer: I can't answer your questions about your portfolio. It would be best to talk with a professor or student advisor about it, as this will be specific for the school or university you are at. That said, some employers might ask you for examples of your own code, so that might be a reason to keep working on this, as a cross-language utility library will show you have a substantial knowledge about the two languages involved, and how to maintain a library. There are some issues with your code though: Avoid using namespace std It saves you some typing, but it introduces problems, especially if you put using namespace std in a header file: code that includes that header file and doesn't expect this might suddenly not compile properly anymore, as it might change the order in which symbols are looked up. So never do this in header files. I would also just avoid this in the source files, but there it can do less harm. Copying strings The way you copy strings is very weird and unnecessary; if you want to access the array of chars that a std::string holds in a non-const way, just use .data() (since C++17), or .front(). But you shouldn't need this, since PyUnicode_FromString() and PyDict_GetItemString() take const char * parameters. Thus: pName = PyUnicode_FromString("PythonCode"); pClass = PyDict_GetItemString(pDict, t_objName.c_str()); Should just work fine. Even if you needed to make a mutable copy of the string, avoid manually allocating memory; just copy into another std::string. Also, don't use C functions to copy things, prefer to make use of C++ algorithms like std::copy_n() instead. Pass strings by const reference where appropriate You are passing strings by value, however that might involve making a copy. If you don't need to modify the string inside the function, then pass the string by const reference instead: class PyInterface { public: PyInterface(const std::string& t_objName); ... };
{ "domain": "codereview.stackexchange", "id": 43715, "lm_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, c++, ffi", "url": null }
python, c++, ffi PyInterface::PyInterface(const std::string& t_objName) { ... } The rest of the function doesn't have to be changed. Write generic code I plan to add more parameter options and return types. The problem is, that I don't know if my current path is any good. Consider this: how many parameter options would you need to implement? If you only had to support strings and integers, and wanted to support methods with up to 8 parameters, you'd have to write 512 functions. And then someone comes along and wants to pass floating point numbers, or 9 parameters. This would not be maintainable, and you should therefore find a way to avoid writing many functions. The solution is to write generic code that can handle any number and any type of parameter. This might be a little harder in C++ than in Python itself, but it can be done using variadic templates. It would look something like this: template<typename Ret = void, typename... Args> Ret PyInterface::callPyMethod(const std::string& t_method, const Args&... args) { std::string format = makeFormat(args...); PyObject *returnValue = PyObject_CallMethod(m_pyObject, t_method.c_str(), format.c_str(), toParameter(args)...); return unpackAs<Ret>(returnValue); } And you would call it like so: PyInterface math("math"); int sum = math.callPyMethod<int>("add", 2, 3); The above is valid code but it relies on three helper functions that do the heavy lifting: makeFormat() is another variadic template that builds a format string for the given arguments. toParameter() converts one argument to be a suitable type to pass as a parameter to PyObject_CallMethod(), for example by taking the address of an int or by calling c_str() on a std::string. unpackAs<>() does the inverse, and converts the value stored in a PyObject to a C++ type.
{ "domain": "codereview.stackexchange", "id": 43715, "lm_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, c++, ffi", "url": null }
python, c++, ffi This is left as an excercise for the reader, although if you've never done this kind of generic programming in C++ before, it might take a while. Consider making a PyMethod class It would be nice if you created a class to wrap a single method, and have it overload the function call operator, so that in the end you can write code like this: PyInterface math("math"); PyMethod add = math.getMethod("add"); int sum = add(2, 3); Make sure your Doxygen documentation is correct It looks like you are using Doxygen to document your classes and functions, which is great! However, make sure you put the documentation as much as possible into the header file, as that is what would be installed on the system if this was a proper library. It is also what a programmer or code editor would look in first to find out about the API for your library. Also make sure you document all the parameters using @param. Naming things Using t_ to prefix parameters and p to prefix a pointer is not too common in C++, but if you are going to use a prefix, use it consistently, otherwise it loses all meaning. For example, className is a pointer to char, so why is there no p in front of it? In the header file, one parameter is named method, without the t_ prefix. I would personally recommend that you don't use any prefixes, except m_ for member variables, as that one brings some real benefits, like avoiding conflicts between function names and parameter names. You have "Py" in your class and member names. Apart from this becoming noise, it also conflicts with the way types and functions from <Python.h> are named. I recommend that you drop "Py" from your own class and function names, but instead put everything in namespace Python, like so: namespace Python { class Interface { public: Interface(const std::string& objName); void call(const std::string& method); ... private: PyObject* object = nullptr; }; } The user can then write: Python::Interface foo("foo"); foo.call("bar");
{ "domain": "codereview.stackexchange", "id": 43715, "lm_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, c++, ffi", "url": null }
c#, asp.net-core, .net-core, entity-framework-core, asp.net-core-webapi Title: .Net Core 6.0 : Entity Framework - Either Or / Neither Nor / Both in Where clause Question: I am building a .Net Core 6.0 application that uses Entity Framework. I have situation where I need to apply the filter(Where clause) based on two properties (eg: Guid? skillType, string skillName). These properties may or may not have values, means that Neither of the property will have value Either of the property will have value Both properties will have value How do I construct the Where clause? I tried something like this var paginationListResult = await this.DbContext.Skills .Where(st => skillType == null || st.SkillTypeId == skillType) .Where(st => string.IsNullOrEmpty(skillName) || st.Name == skillName) .Include(sk => sk.SkillType) .Include(sk => sk.Regroupment) .Include(sk => sk.SkillRoleRequirements) .OrderBy(s => s.Name) .ToPaginateListAsync(pageIndex, itemsPerPage, default(CancellationToken)).ConfigureAwait(false); Is there a better way to handle the situation? Answer: Since you're using Entity Framework, you can use null-coalescing operator to get the property instead of the given value. This would be translated into COALESCE function, which is a standard SQL function that is supported in most of database providers. Example : .Where(st => skillType == null || st.SkillTypeId == skillType) .Where(st => string.IsNullOrEmpty(skillName) || st.Name == skillName) would be modified to this : .Where(st => st.SkillTypeId == (skillType ?? st.SkillTypeId)) .Where(st => st.Name == (skillName ?? st.Name)) In SQL, it would be translated into something similar to this query: SELECT * FROM table WHERE SkillTypeId = COALESCE(@skillType, SkillTypeId) AND Name = COALESCE(@skillName, Name)
{ "domain": "codereview.stackexchange", "id": 43716, "lm_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#, asp.net-core, .net-core, entity-framework-core, asp.net-core-webapi", "url": null }
c#, asp.net-core, .net-core, entity-framework-core, asp.net-core-webapi So, the above query will check first @skillType if null, then it will get current value of SkillTypeId and compare it to itself. This would be also applied to the Name as well. which is the same effect as 1 == 1. This is only applicable on null-coalescing operator, and because of that, you will need to handle the value to reassign null to it to avoid default values or empty or whitespace for strings before you pass it to the query. Something like this would be applicable: skillName = string.IsNullOrWhiteSpace(skillName) ? null : skillName; var paginationListResult = await this.DbContext.Skills .Where(st => st.SkillTypeId == (skillType ?? st.SkillTypeId)) .Where(st => st.Name == (skillName ?? st.Name)) .Include(sk => sk.SkillType) .Include(sk => sk.Regroupment) .Include(sk => sk.SkillRoleRequirements) .OrderBy(s => s.Name) .ToPaginateListAsync(pageIndex, itemsPerPage, default(CancellationToken)).ConfigureAwait(false);
{ "domain": "codereview.stackexchange", "id": 43716, "lm_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#, asp.net-core, .net-core, entity-framework-core, asp.net-core-webapi", "url": null }
javascript, beginner, html5, rock-paper-scissors Title: Simple Rock Paper Scissor game Question: I am new to javascript and I made a simple Rock Paper scissor game with User Interface. There will be 5 rounds and user will play against the computer by clicking any of the three buttons. See Live preview Review my code: Html: <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Rock Paper Scissors</title> <link rel="stylesheet" href="style.css" /> </head> <body> <h1 class="header">Rock Paper and Scissors</h1> <div class="round">Round 1</div> <div class="options"> <button class="rock">Rock</button> <button class="paper">Paper</button> <button class="scissor">Scissor</button> </div> <div class="result"></div> <div class="score"></div> <script type="text/javascript" src="external.js"></script> </body> </html> Javascript code: let playerScore = 0, computerScore = 0; //generate random choice function getComputerChoice(choices) { return choices[Math.floor(Math.random() * choices.length)]; } function playRound(event) { //declare a variable playerSelection and store the event nodes class let playerSelection = event.target.classList.value; //take the computer choice in another variable let computerSelection = getComputerChoice(["ROCK", "PAPER", "SCISSOR"]); //create two variables that'll reference to divs result and score const resultDiv = document.querySelector(".result"); const scoreDiv = document.querySelector(".score"); let result;
{ "domain": "codereview.stackexchange", "id": 43717, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, html5, rock-paper-scissors", "url": null }
javascript, beginner, html5, rock-paper-scissors //after any condition is met, increment each player's score and update the result if (playerSelection != null) playerSelection = playerSelection.toUpperCase(); if (playerSelection === computerSelection) { result = `It's a tie!`; } else if ( (playerSelection === "ROCK" && computerSelection === "SCISSOR") || (playerSelection === "PAPER" && computerSelection === "ROCK") || (playerSelection === "SCISSOR" && computerSelection == "PAPER") ) { result = `You won ${playerSelection} beats ${computerSelection}`; playerScore++; } else { result = `You lose ${computerSelection} beats ${playerSelection}`; computerScore++; } //update div.result resultDiv.textContent = result; //update score scoreDiv.textContent = `You : ${playerScore} Computer : ${computerScore}`; } function playGame() { let counter = 0; //call the addeventlistener 'click' and update the score div consequently const options = document.querySelector(".options"); options.addEventListener("click", (event) => { const isButton = event.target.nodeName === "BUTTON"; if (!isButton || counter >= 5) { return; } counter++; const round = document.querySelector(".round"); playRound(event); if (counter < 5) { round.textContent = `Round ${counter + 1}`; } else { displayWinner(); } }); } //after game ends function displayWinner() { const round = document.querySelector(".round"); if (computerScore > playerScore) round.textContent = "Computer won :/"; else if (playerScore > computerScore) round.textContent = "You won!"; else round.textContent = "Nobody won the game "; } //calling the function playGame(); Answer: General points Try to make the code self explanatory and avoid adding comment that state the obvious. Avoid repeated DOM queries, use variables to store elements once when your code first starts.
{ "domain": "codereview.stackexchange", "id": 43717, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, html5, rock-paper-scissors", "url": null }
javascript, beginner, html5, rock-paper-scissors Avoid repeated DOM queries, use variables to store elements once when your code first starts. Isolate your code from the global scope. There are many ways to do this. A tried and true method is to wrap the code in a function that is immediately run. Called an Immediately Invoked Function Expression (IIFE). See rewrite. Try to keep variable names short. Its is a bad habit not to wrap all blocks in {}. Example Bad habit if (foo) bar = 2; Good if (foo) { bar = 2; } Try to make functions generic and reusable. For example the function getComputerChoice which select a random item from an array could be called randomItem. You can add this to a JS file with other random functions that you can use in other project. Store magic values (strings and numbers) in constants. Place these constants in one place. Avoid giving functions too many tasks or not clearly defining the tasks by spreading them between functions. The DOM and JS Use element IDs to uniquely locate elements rather than the class name. Use data property to store data in the markup. Or it is most times best to create game related elements via code rather than as a static page. This give you far greater control over the visuals and associated data. But keeping it simple the rewrite adopts your design. Rewrite /* Common reusable functions */ const rndItem = arr => arr[Math.random() * arr.length | 0]; const query = qStr => document.querySelector(qStr); ;(()=>{ const MAX_ROUNDS = 5; const HANDS = ["ROCK", "PAPER", "SCISSOR"]; const WINS = [{hand: HANDS[0], beats: HANDS[2]}, {hand: HANDS[1], beats: HANDS[0]}, {hand: HANDS[2], beats: HANDS[1]}]; const isWin = (winHand, beatsHand) => WINS.some(w => w.hand === winHand && w.beats === beatsHand); const resultEl = query("#result"); const scoreEl = query("#score"); const roundEl = query("#round"); query("#options").addEventListener("click", playRound);
{ "domain": "codereview.stackexchange", "id": 43717, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, html5, rock-paper-scissors", "url": null }
javascript, beginner, html5, rock-paper-scissors const game = { plyScore: 0, plyHand: null, compScore: 0, compHand: null, round: 0, reset() { game.round = game.compScore = game.plyScore = 0; game.compHand = game.plyHand = null; } }; startGame();
{ "domain": "codereview.stackexchange", "id": 43717, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, html5, rock-paper-scissors", "url": null }
javascript, beginner, html5, rock-paper-scissors function startGame() { game.reset(); resultEl.textContent = "New Game. Best out of " + MAX_ROUNDS + " games"; } function displayResult() { var result = "It's a tie!"; if (isWin(game.plyHand, game.compHand)) { result = `You won ${game.plyHand} beats ${game.compHand}`; game.plyScore ++; } else if (isWin(game.compHand, game.plyHand)) { result = `You lose ${game.compHand} beats ${game.plyHand}`; game.compScore ++; } resultEl.textContent = "Results for round " + game.round + " " + result; scoreEl.textContent = `Scores You: ${game.plyScore} Computer: ${game.compScore}`; } function displayEndGame() { if (game.round === MAX_ROUNDS) { let result = "The match is a draw!"; result = game.plyScore > game.compScore ? `You win the match! ${game.plyScore} rounds to ${game.compScore}` : result; result = game.compScore > game.plyScore ? `Computer wins the match! ${game.compScore} rounds to ${game.plyScore}` : result; roundEl.textContent = result; } } function playRound(event) { if (game.round < MAX_ROUNDS && event.target.dataset.hand) { game.round ++; game.plyHand = event.target.dataset.hand; game.compHand = rndItem(HANDS); displayResult(); displayEndGame(); } } })(); <h1 class="header">Paper Scissor Rocks</h1> <div id="round" class="round">Select a hand to play</div> <div id="options" class="options"> <button id="rock" class="rock" data-hand="ROCK">Rock</button> <button id="paper" class="paper" data-hand="PAPER">Paper</button> <button id="scissor" class="scissor" data-hand="SCISSOR">Scissor</button> </div> <div id="result" class="result"></div> <div id="score" class="score"></div>
{ "domain": "codereview.stackexchange", "id": 43717, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, html5, rock-paper-scissors", "url": null }
python, pandas, pivot Title: Pivoting and then Padding a Pandas DataFrame with NaN between specific columns - Case Study Question: This question is about pivoting and padding columns, two very frequent activities in Pandas. I have a raw dataframe. I need to manipulate from long to wide and then pad NaN based on a specific rule. My code works, but I think is not efficient and elegant, plus it is not able to generalize as I highlighted at the end. Before coming here and having working code I read some very valuable questions on stack like the following ones: How to flatten a hierarchical index in columns How can I pivot a dataframe? Custom variable names when reshaping pandas dataframe from long to wide And fortunately I reached my goal, but in a very bad way and that's why I am here. But let's start showing this ugly code. # Our df for this example dict_df = {"Time":[1,1,1,1,2,2,2,2,3,3,3,3] , "KPI":["A","B","C","D","A","B","C","D","A","B","C","D"], "SKU1":[10,1,0.1,0.01,40,4,0.4,0.04,90,9,0.9,0.09], "SKU2":[20,2,0.2,0.02,50,5,0.5,0.05,100,10,1,0.1], "SKU3":[30,3,0.3,0.03,60,6,0.6,0.06,110,11,1.1,0.11], "SKU4":[70,7,0.7,0.07,80,8,0.8,0.08,120,12,1.2,0.12] } df_test = pd.DataFrame(dict_df) Time KPI SKU1 SKU2 SKU3 SKU4 0 1 A 10.00 20.00 30.00 70.00 1 1 B 1.00 2.00 3.00 7.00 2 1 C 0.10 0.20 0.30 0.70 3 1 D 0.01 0.02 0.03 0.07 4 2 A 40.00 50.00 60.00 80.00 5 2 B 4.00 5.00 6.00 8.00 6 2 C 0.40 0.50 0.60 0.80 7 2 D 0.04 0.05 0.06 0.08 8 3 A 90.00 100.00 110.00 120.00 9 3 B 9.00 10.00 11.00 12.00 10 3 C 0.90 1.00 1.10 1.20 11 3 D 0.09 0.10 0.11 0.12
{ "domain": "codereview.stackexchange", "id": 43718, "lm_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, pandas, pivot", "url": null }
python, pandas, pivot I want to filter specific KPIs: filter_kpi = ["A","B","C"] df_test_filtered = df_test[df_test["KPI"].isin(filter_kpi)] #Setting Time column as index df_test_filtered.index = df_test_filtered.Time #Pivoting the dataframe pivot_test = df_test_filtered.pivot(values = ["SKU1","SKU2","SKU3","SKU4"], columns ="KPI", index="Time") print(pivot_test) After that I flatten the columns based on the question "Custom variable names when reshaping": pivot_test.columns = [''.join(col) for col in pivot_test.columns] And got this output: SKU1A SKU1B SKU1C SKU2A SKU2B SKU2C SKU3A SKU3B SKU3C SKU4A SKU4B SKU4C Time 1 10.0 1.0 0.1 20.0 2.0 0.2 30.0 3.0 0.3 70.0 7.0 0.7 2 40.0 4.0 0.4 50.0 5.0 0.5 60.0 6.0 0.6 80.0 8.0 0.8 3 90.0 9.0 0.9 100.0 10.0 1.0 110.0 11.0 1.1 120.0 12.0 1.2 And now the ugly part of my code. The goal is to pad with 3 columns of Nan (but can be any fixed number of columns) the space between each SKU. The index now is made by 3 rows but can be of 4,2 or any other length. So between the set SKU1_, SKU2_ etc... # I initialize an empty DataFrame df_empty = pd.DataFrame() # I am defining the range that will define when to split the original dataframe data_range = np.arange(0,len(pivot_test.columns),3) #Creating the index for the empty dataframe that will be used for padding df_nan_len =np.arange(1,len(pivot_test)+1,1) df_nan = pd.DataFrame(np.nan, index=df_nan_len, columns=['0', '1','2']) #loop for each element in the range for i in data_range: #Splitting the DataFrame filter = pivot_test.iloc[:,i:i+3] df_empty = pd.concat([df_empty,filter], axis =1) df_empty = pd.concat([df_empty,df_nan], axis =1)
{ "domain": "codereview.stackexchange", "id": 43718, "lm_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, pandas, pivot", "url": null }
python, pandas, pivot And from that I get my final output: SKU1A SKU1B SKU1C 0 1 2 SKU2A SKU2B SKU2C 0 ... SKU3C 0 1 2 SKU4A SKU4B SKU4C 0 1 2 1 10.0 1.0 0.1 NaN NaN NaN 20.0 2.0 0.2 NaN ... 0.3 NaN NaN NaN 70.0 7.0 0.7 NaN NaN NaN 2 40.0 4.0 0.4 NaN NaN NaN 50.0 5.0 0.5 NaN ... 0.6 NaN NaN NaN 80.0 8.0 0.8 NaN NaN NaN 3 90.0 9.0 0.9 NaN NaN NaN 100.0 10.0 1.0 NaN ... 1.1 NaN NaN NaN 120.0 12.0 1.2 NaN NaN NaN I am already aware that if I had a different number of KPIs for example 4 or 2 this code will not work properly. The code works, but I think the loop, how I pad the NaN, it is something I can improve. Thank you for your time and patience! More information and context The data come from the IRI data source. KPI1, KP2, KP3 are just a way to describe some of the information that I get: Price Euro/Quantity Weighted distribution selling Standardized sales per business Euro Standardized sales per business quantity Standardized sales per business piece And so on, they are 8 but I wanted to create a working minimum reproducible example and that's why I choose only 3 variables. Why I need to pad? Because I inherited and excel file where this information are padded in that way and I need to attach each month the new data to the "master excel data book", after saving in *xlsx format the dataframe This is just to give you an example.
{ "domain": "codereview.stackexchange", "id": 43718, "lm_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, pandas, pivot", "url": null }
python, pandas, pivot Why I can't use just a join operation, opening the excel file and reading it? It's in the plan, my final goal. I had to fix some date issue first, because the data I receive are ordered with this time notation KW 14/2022 that I have to change in order to use as a key with the final notation 21/03/2022 How they handled the "updating process" until now? They used an excel table where in one tab you paste the data, in one tab you extend the rows and it returns the final result already padded. My goal is to create a Data Pipeline in Python to automatically handle this monthly data update. This padding solution helps me to copy and paste quickly this data for the next deadline. It is this process data quality inefficient? Yes, I am working really hard to fix it, but it is not something I decided at the beginning. Thank you again for the suggestions and time. Hopes it help. Answer: I'm sure someone will come up with a better solution than this, but hopefully some ideas here are helpful. Starting from this dataframe: SKU1A SKU1B SKU1C SKU2A SKU2B SKU2C SKU3A SKU3B SKU3C SKU4A SKU4B SKU4C Time 1 10.0 1.0 0.1 20.0 2.0 0.2 30.0 3.0 0.3 70.0 7.0 0.7 2 40.0 4.0 0.4 50.0 5.0 0.5 60.0 6.0 0.6 80.0 8.0 0.8 3 90.0 9.0 0.9 100.0 10.0 1.0 110.0 11.0 1.1 120.0 12.0 1.2 We want to work with the SKUs, so it's probably easiest to transpose this and reset the index so we can access the SKUs in a column. So we can use df = df.T df.index.name = "SKUs" df = df.reset_index() to get SKUs 1 2 3 0 SKU1A 10.0 40.0 90.0 1 SKU1B 1.0 4.0 9.0 2 SKU1C 0.1 0.4 0.9 ... Next, we want to group each of the SKUs by the initial SKU part, which we can do using group = df.groupby(df["SKUs"].str.extract("(SKU\d+)", expand=False))
{ "domain": "codereview.stackexchange", "id": 43718, "lm_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, pandas, pivot", "url": null }
python, pandas, pivot Here, the regular expression "(SKU\d+)" says to capture the letters SKU followed by any number of consecutive digits. This means SKU11A will be handled as you'd expect. Now we can get the individual groups with: groups = [group.get_group(x) for x in group.groups] Which gives, as you'd expect, a separate dataframe for each SKU (ie., a dataframe for SKU1, for SKU2, etc.). Now comes an ugly part from me. Ultimately, we want to alternate between an element from groups, and an empty dataframe of your desired structure. We can create the empty dataframe like this: desired_num_cols = 3 empty_df = pd.DataFrame( [[pd.NA] * groups[0].shape[1]] * desired_num_cols, columns=groups[0].columns ) empty_df['SKUs'] = list(range(desired_num_cols)) and now we just need to concat this in an alternating fashion with elements from groups, which we can do as follows: df = pd.concat( itertools.chain( *zip( *[ groups, itertools.cycle([empty_df]), ] ) ) ) Broken down: itertools.cycle([empty_df]) will just give an empty_df until groups is exhausted. The inner zip packs together tuples of (group, empty_df). The itertools.chain(*...) then unpacks these tuples so that we have [group1, empty_df, group2, empty_df, ...]. Now set the index to SKUs and transpose: df = df.reset_index(drop=True).set_index("SKUs") df.T and we get your final answer: SKUs SKU1A SKU1B SKU1C 0 1 2 SKU2A SKU2B SKU2C 0 1 2 SKU3A SKU3B SKU3C 0 1 2 SKU4A SKU4B SKU4C 0 1 2 1 10.0 1.0 0.1 NaN NaN NaN 20.0 2.0 0.2 NaN NaN NaN 30.0 3.0 0.3 NaN NaN NaN 70.0 7.0 0.7 NaN NaN NaN 2 40.0 4.0 0.4 NaN NaN NaN 50.0 5.0 0.5 NaN NaN NaN 60.0 6.0 0.6 NaN NaN NaN 80.0 8.0 0.8 NaN NaN NaN 3 90.0 9.0 0.9 NaN NaN NaN 100.0 10.0 1.0 NaN NaN NaN 110.0 11.0 1.1 NaN NaN NaN 120.0 12.0 1.2 NaN NaN NaN
{ "domain": "codereview.stackexchange", "id": 43718, "lm_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, pandas, pivot", "url": null }
rust, generics Title: rust: idiomatic use of generics when using a filetype-dependent writer Question: Simplified from https://github.com/132nd-vWing/tacview-splitter. External dependencies: zip crate The code would do the following: read a file from disk (determined at runtime) analyze the content, split it into a header and a body divide the body into two categories (here blue and red) for each category, write the header and the corresponding body to a separate file the output file type depends on the input file type. if the input was a txt file, write the output to a txt file otherwise the input was a txt file contained in a zip file. Write the data as a txt in a zip. Code is this: use std::fs; use std::io::Write; struct Descriptors<T: Write> { blue: T, red: T, } struct OutputFilenames { pub txt: FilenamesVariant, pub zip: FilenamesVariant, } struct FilenamesVariant { pub blue: String, pub red: String, } impl Descriptors<zip::ZipWriter<fs::File>> { pub fn new(filenames: OutputFilenames) -> Descriptors<zip::ZipWriter<fs::File>> { let options = zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Deflated); let file = fs::File::create(&filenames.zip.blue).unwrap(); let mut blue = zip::ZipWriter::new(file); blue.start_file(&filenames.txt.blue, options).unwrap(); let file = fs::File::create(&filenames.zip.red).unwrap(); let mut red = zip::ZipWriter::new(file); red.start_file(&filenames.txt.red, options).unwrap(); Descriptors { blue, red } } } impl Descriptors<fs::File> { pub fn new(filenames: OutputFilenames) -> Descriptors<fs::File> { let blue = fs::File::create(&filenames.txt.blue).unwrap(); let red = fs::File::create(&filenames.txt.red).unwrap(); Descriptors { blue, red } } }
{ "domain": "codereview.stackexchange", "id": 43719, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, generics", "url": null }
rust, generics impl<T: Write> Descriptors<T> { fn write(&mut self, header: Vec<String>, blue: Vec<String>, red: Vec<String>) { for line in &header { writeln!(self.blue, "{}", line).unwrap(); writeln!(self.red, "{}", line).unwrap(); } for line in &blue { writeln!(self.blue, "{}", line).unwrap(); } for line in &red { writeln!(self.red, "{}", line).unwrap(); } } } impl OutputFilenames { fn default() -> Self { let txt = FilenamesVariant { blue: "blue.txt".to_string(), red: "red.txt".to_string(), }; let zip = FilenamesVariant { blue: "blue.zip".to_string(), red: "red.zip".to_string(), }; Self { txt, zip } } } fn main() { let is_zip = true; // in practice this would be read from disk let output_filenames = OutputFilenames::default(); let header = vec!["some header".to_string(), "headers".to_string()]; let blue_content = vec!["blue content".to_string(), "blue".to_string()]; let red_content = vec!["red content".to_string(), "red".to_string()]; if is_zip { let mut descriptors = Descriptors::<zip::ZipWriter<fs::File>>::new(output_filenames); descriptors.write(header, blue_content, red_content); } else { let mut descriptors = Descriptors::<fs::File>::new(output_filenames); descriptors.write(header, blue_content, red_content); } } I tried to write the code in manner that would avoid code repetition, by implementing it in a Descriptor<T: Write> struct. This struct holds the descriptors independent of the output file type. Then in the main code, I can simple write to the descriptors without having to care for the exact type. Is it possible to write the code in a more generic / concise / idiomatic manner? What else would you change about this code and why? Answer: I think it's quite good, and I only have a single nitpick:
{ "domain": "codereview.stackexchange", "id": 43719, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, generics", "url": null }
rust, generics Answer: I think it's quite good, and I only have a single nitpick: use &[T] where T: AsRef<str> instead of Vec<String> for your function arguments (that's a general rule, use the least specific possible type in your arguments for maximum compatibility) Everything else is honestly opinion based, like: I would probably not handle blue and red as two separate things, because all of their code is duplicated. They can be handled as the same thing. I'd employ Box to become even more type-agnostic and store things only by their trait I don't see a big advantage of having all those structs, I think for this case simple functions are more suited Something like this: use std::fs::File; use std::io::{self, Write}; use zip::{write::FileOptions, CompressionMethod, ZipWriter}; fn create_filewriter(filename: &str) -> File { File::create(filename).unwrap() } fn create_zipwriter(filename: &str, nested_filename: &str) -> ZipWriter<File> { let mut writer = ZipWriter::new(create_filewriter(filename)); writer .start_file( nested_filename, FileOptions::default().compression_method(CompressionMethod::Deflated), ) .unwrap(); writer } fn create_writer(zip: bool, name: &str) -> Box<dyn Write> { if zip { Box::new(create_zipwriter( &format!("{name}.zip"), &format!("{name}.txt"), )) } else { Box::new(create_filewriter(&format!("{name}.txt"))) } } trait StringsWriter { fn write_strings<S: AsRef<str>>(&mut self, lines: &[S]) -> Result<(), io::Error>; } impl<T> StringsWriter for T where T: Write, { fn write_strings<S: AsRef<str>>(&mut self, lines: &[S]) -> Result<(), io::Error> { for line in lines { writeln!(self, "{}", line.as_ref())?; } Ok(()) } } fn main() { let is_zip = true; // in practice this would be read from disk let header = vec!["some header".to_string(), "headers".to_string()];
{ "domain": "codereview.stackexchange", "id": 43719, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, generics", "url": null }
rust, generics let header = vec!["some header".to_string(), "headers".to_string()]; let blue_content = vec!["blue content".to_string(), "blue".to_string()]; let red_content = vec!["red content".to_string(), "red".to_string()]; let mut blue_writer = create_writer(is_zip, "blue"); let mut red_writer = create_writer(is_zip, "red"); blue_writer.write_strings(&header).unwrap(); blue_writer.write_strings(&blue_content).unwrap(); red_writer.write_strings(&header).unwrap(); red_writer.write_strings(&red_content).unwrap(); } Again, this is mostly personal preference and I think your solution was fine as-is. I just thought I'd give you another perspective on how else this could be implemented. The next step for me would be error handling. Get rid of all the unwrap() and expect(), write a proper error enum with thiserror and propagate it through. Maybe add miette for bling. I'm unsure, though, how well those tips translate to the tacview-splitter repository.
{ "domain": "codereview.stackexchange", "id": 43719, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, generics", "url": null }
rust, api Title: rust: Set configs from env and reuse it during app's lifetime Question: After writing a basic API with rocket, I'm trying to improve it, but I'm not sure how to follow up. Each time a new request comes in, the code keeps looking for the variable from the environment. // Connect to redis pub fn connect() -> redis::Connection { let redis_host_name = env::var("REDIS_HOSTNAME").expect("missing environment variable REDIS_HOSTNAME"); let redis_password = env::var("REDIS_PASSWORD").unwrap_or_default(); //if Redis server needs secure connection let uri_scheme = match env::var("IS_TLS") { Ok(_) => "rediss", Err(_) => "redis", }; let redis_conn_url = format!("{}://:{}@{}", uri_scheme, redis_password, redis_host_name); println!("{}", redis_conn_url); redis::Client::open(redis_conn_url) .expect("Invalid connection URL") .get_connection() .expect("failed to connect to Redis") } I'm looking for a way to set the redis_conn_url right in the initialization and panic if it is missing, like so fn rocket() -> _ { let redis_conn_url: String = get_redis_url(); // panics if it does not exist set_persistent_variable("redis_conn_url", redis_conn_url); rocket::build().mount( "/", routes![routes::root],) } Later I would get it from the config instead of querying env again. Any direction on this or tips to improve the way I'm thinking about it will be appreciated. Answer: I think for your usecase, the lazy_static crate would be quite useful. For example: #[macro_use] extern crate lazy_static; use std::env; lazy_static! { static ref REDIS_HOSTNAME: String = env::var("REDIS_HOSTNAME").expect("missing environment variable REDIS_HOSTNAME"); static ref REDIS_PASSWORD: String = env::var("REDIS_PASSWORD").unwrap_or_default(); } fn main() { println!("Credentials: {:?} - {:?}", *REDIS_HOSTNAME, *REDIS_PASSWORD); }
{ "domain": "codereview.stackexchange", "id": 43720, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, api", "url": null }
c, linked-list Title: Basic Linked List C implementation Question: I've written a singly-linked list of characters. This is my 3rd C program and I'd like some feedback on what I can improve on in any aspect whatsoever. If you'd prefer to look at the repo directly it's here: https://github.com/JosephSBoyle/LinkedList Thanks in advance for your time :D linked_list.h #include <stdbool.h> // define the node struct here so we can use it within it's own definition typedef struct Node Node; struct Node { /* A node in a linked list */ char item; // character at this node Node *next; // pointer to the next node }; size_t NODE_SIZE = sizeof(Node); /* Create a new list */ Node* list(); /* Destruct a list, freeing it's memory */ void free_list(Node* sentinel); /* Add an element to the end of a list */ void add(Node* sentinel, char item); /** Delete an element from a list. * @returns true if the operation succeeded, false if there is the list is shorter than * the supplied index argument. */ bool del(Node* sentinel, size_t idx); /* Replace the value stored by the node at idx. */ bool replace(Node* sentinel, size_t idx, char item); /* Get the length of a list */ size_t len(Node* sentinel); /* Peak the idx'th node, or the last node if there are fewer than idx elements in the list. */ Node* peak(Node* sentinel, size_t idx); /* Pretty-print a list */ void print(Node* sentinel); /* Print a list as a contiguous string */ void pstring(Node* sentinel); linked_list.c #include <stdlib.h> #include <string.h> #include <stdio.h> #include "linked_list.h" #include <assert.h> Node* list(){ // create a 'sentinel node'. Node* sentinel = (Node*)malloc(NODE_SIZE); sentinel->next = NULL; sentinel->item = '\0'; return sentinel; } Node* peak(Node* sentinel, size_t idx){ Node* node = sentinel;
{ "domain": "codereview.stackexchange", "id": 43721, "lm_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", "url": null }
c, linked-list Node* peak(Node* sentinel, size_t idx){ Node* node = sentinel; // compare to idx + 1, since we want our peak to be zero-indexed // and we have a sentinel node for (size_t i=0; i != idx+1; i++){ if (node->next == NULL){ // return the sentinel node as there are fewer than idx elements in the list return sentinel; } node = node->next; } return node; } void free_list(Node* sentinel){ // traverse each node in order and free it's memory. size_t i = 0; do { i++; free(sentinel); sentinel = sentinel->next; } while (sentinel->next != NULL); } void add(Node* sentinel, char item){ // instantiate a new node Node* new_node = (Node*)malloc(NODE_SIZE); new_node->item = item; // traverse each node while (true){ if(sentinel->next == NULL){ // replace the last node with our new node. sentinel->next = new_node; break; } else { // point to the next node sentinel = sentinel->next; } } } bool del(Node* sentinel, size_t idx){ // TODO find a way to leverage peak to simplify this for (size_t i=0; i != idx; i++){ if (!sentinel){ return false; } sentinel = sentinel->next; } if (sentinel->next){ Node* index_node_ptr = sentinel->next; if (index_node_ptr->next){ sentinel->next = index_node_ptr->next; } else { free(index_node_ptr); sentinel->next = NULL; } return true; } } bool replace(Node* sentinel, size_t idx, char item){ Node* node = peak(sentinel, idx); // check if the sentinel and the peaked node are the same if (sentinel == node){ return false; } else { node->item = item; return true; }
{ "domain": "codereview.stackexchange", "id": 43721, "lm_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", "url": null }
c, linked-list } size_t len(Node* sentinel){ Node* current_node = sentinel; size_t nodes = 0; while (true){ // Check if we're at the final node. if(current_node->next == NULL){ return nodes; } nodes++; current_node = current_node->next; } } void print(Node* sentinel){ printf("["); while (sentinel->next != NULL){ sentinel = sentinel->next; printf("'%c',", sentinel->item); } printf("]\n"); } void pstring(Node* sentinel){ while (sentinel->next != NULL){ sentinel = sentinel->next; printf("%c", sentinel->item); } printf("\n"); } /* Tests */ void main(){ Node* sentinel = list(); add(sentinel, 'h'); add(sentinel, 'e'); add(sentinel, 'l'); add(sentinel, 'l'); add(sentinel, 'o'); print(sentinel); replace(sentinel, 4, '0'); pstring(sentinel); // check that deleting works for a valid index assert(del(sentinel, 4)); // and fails when that index becomes invalid. assert(!del(sentinel, 4)); // check peaking an invalid index returns the sentinel node assert(sentinel == peak(sentinel, 4)); pstring(sentinel); free_list(sentinel); } Running the code (tested on ubuntu linux): $ gcc -o run linked_list.c $ ./run
{ "domain": "codereview.stackexchange", "id": 43721, "lm_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", "url": null }
c, linked-list Running the code (tested on ubuntu linux): $ gcc -o run linked_list.c $ ./run Answer: Overall: a good code for a "my 3rd C program". Good formatting Good documentation in .h file. (Perhaps a bit more to detail expectational cases.) No need for object NODE_SIZE Simply use #define NODE_SIZE sizeof(Node). As is, each .c file that includes linked_list.h makes an object NODE_SIZE, eventually causing multiple definitions. .h files should not define any objects. Information hiding The definition of struct Node belongs in the .c file. Users of these functions never need to see the internals. Move struct Node { ...}; to the .c file. Name space Code uses common names like Node, list, add, del, peak, print, ... which are likely to collide with the rest of code. Consider a common prefix instead. linked_list_add, linked_list_del, linked_list_peek, .... Empty arguments in a declaration No arguments in a declaration matches any argument set. Use void. // Node* list(); Node* list(void); This differs from a function definition. This distinction may change in the next C version. add() may fail Since add() calls malloc(), that allocation may fail. Consider returning an error flag here too. // void add(Node* sentinel, char item); bool add(Node* sentinel, char item); What if empty list? peak() does not describe return value in this case. Exercise *.h include independence In linked_list.c, include its companion .h file first to help validate that no <xx.h> files are needed. // #include <stdlib.h> // #include <string.h> // #include <stdio.h> // #include "linked_list.h" // #include <assert.h> #include "linked_list.h" #include <stdlib.h> #include <string.h> #include <stdio.h> #include <assert.h> Use const For function that do not change the *sentinel, use const. This increase functions applicability, conveys code's intent better and allows for some optimizations not seen by lesser compilers. // Node* peak(Node* sentinel, size_t idx) Node* peak(const Node* sentinel, size_t idx)
{ "domain": "codereview.stackexchange", "id": 43721, "lm_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", "url": null }
c, linked-list NULL argument list() may fail to allocate, and should be re-written to return NULL in that case. free_list(Node* sentinel) should check if sentianl == NULL and does nothing - just like free(NULL) is OK. This simplifies calling code's error handling. Cast not needed In C, a cast is not needed to convert a void * to an object *. Further I recommend to size to the reference object and not the type. Easier to code right, review and maintain. Check allocation success. // Node* sentinel = (Node*)malloc(NODE_SIZE); Node* sentinel = malloc(sizeof sentinel[0]); if (sentinel == NULL) { return NULL; } Test code Consider moving main() test code to a 3rd file instead of linked_list.c to allow other application to use/link linked_list.c and not collide with main(). peek() return I'd expect peak() to return the item and not struct Node. Or to provide an error return, consider returning a pointer to the item and NULL on error (e.g. empty list) or some other interface - anything that does not oblige the user from needing to see Node internals. Code guards linked_list.h deserves code guards.
{ "domain": "codereview.stackexchange", "id": 43721, "lm_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", "url": null }
rust, game-of-life Title: Optimise Game of Life in Rust Question: I recently picked up Rust and was making a CLI for Conway's Game of Life. I got it working but, looking back at it, there are places it could be improved. The main one is the function that generates the next board. Specifically, the part of that function which calculates the amount of alive neighbours a cell has. fn next_step(game_array: [[bool; WIDTH]; HEIGHT]) -> [[bool; WIDTH]; HEIGHT] { let mut next_state = [[false; WIDTH]; HEIGHT]; let mut neighbours: u8; // Will never be above 8 const HEIGHT_I: isize = HEIGHT as isize; const WIDTH_I: isize = WIDTH as isize; const NEIGHBOUR_LIST: [[isize; 2]; 8] = [[-1, -1], [-1, 0], [-1, 1], [ 0, -1], [ 0, 1], [ 1, -1], [ 1, 0], [ 1, 1]]; for rownum in 0..HEIGHT { for cellnum in 0..WIDTH { // FROM HERE neighbours = 0; for [j, k] in NEIGHBOUR_LIST { // This will break if width and height are set to larger than isize::MAX if game_array[(((rownum as isize + j % HEIGHT_I) + HEIGHT_I) % HEIGHT_I) as usize] [(((cellnum as isize + k % WIDTH_I) + WIDTH_I) % WIDTH_I) as usize] { neighbours += 1; } } // TO HERE // This is the cleanest way I could find to implement Life rules if neighbours == 3 || (game_array[rownum][cellnum] && neighbours == 2) { next_state[rownum][cellnum] = true; } } } next_state } I wanted the edges of the board to loop and this is the best way I could find to check the neighbours of a cell. However, it is verbose and hard to read. Is there a better way that I am missing? HEIGHT and WIDTH are the height and width of the board and will never be above isize::MAX.
{ "domain": "codereview.stackexchange", "id": 43722, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, game-of-life", "url": null }
rust, game-of-life Answer: Your solution looks good! I would suggest the following improvements in order to make it more readable: Use type aliases to improve the readability: type State = [[bool; WIDTH]; HEIGHT]; Extract the coordinate wrapping logic into its own type to make it easier to understand: #[derive(Debug, Copy, Clone)] struct Coord { value: usize, max: usize, } impl Coord { fn new(value: usize, max: usize) -> Self { Coord { value, max, } } fn increment(&mut self) { self.value += 1; if self.value >= self.max { self.value = 0; } } fn decrement(&mut self) { self.value = self.value.checked_sub(1).unwrap_or(self.max - 1); } } Create a Cell and NeighborsIter structures that encapsulate the logic of iterating over all neigbhours of a given cell: #[derive(Debug, Copy, Clone)] struct Cell { x: Coord, y: Coord, } impl Cell { fn new(x: usize, y: usize) -> Self { Cell { x: Coord::new(x, HEIGHT), y: Coord::new(y, WIDTH), } } fn into_neighbors_iter(self) -> NeighborsIter { NeighborsIter::new(self) } } struct NeighborsIter { state: usize, cell: Cell, } impl NeighborsIter { fn new(init: Cell) -> Self { Self { state: 0, cell: init, } } } impl Iterator for NeighborsIter { type Item = Cell;
{ "domain": "codereview.stackexchange", "id": 43722, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, game-of-life", "url": null }
rust, game-of-life impl Iterator for NeighborsIter { type Item = Cell; fn next(&mut self) -> Option<Self::Item> { match self.state { 0 => { self.cell.x.decrement(); self.cell.y.decrement() } 1 => { self.cell.y.increment() } 2 => { self.cell.y.increment() } 3 => { self.cell.x.increment() } 4 => { self.cell.x.increment() } 5 => { self.cell.y.decrement() } 6 => { self.cell.y.decrement() } 7 => { self.cell.x.decrement() } _ => { return None; } } self.state += 1; Some(self.cell) } } Separate the counting of live neigbhors into its own function: fn count_neighbors(&self, cell: Cell) -> u8 { let mut neighbours: u8 = 0; for cell in cell.into_neighbors_iter() { if self.state[cell.x.value][cell.y.value] { neighbours += 1; } } neighbours } Create a Board struct and move the next_step function into it as a method: #[derive(Debug)] struct Board { state: State } impl Board { pub fn new() -> Self { Board { state: [[false; WIDTH]; HEIGHT] } } pub fn from(state: State) -> Self { Board { state } } pub fn next_step(self) -> Board { let mut next_state = [[false; WIDTH]; HEIGHT]; for row in 0..HEIGHT { for col in 0..WIDTH { match self.count_neighbors(Cell::new(row, col)) { 3 => next_state[row][col] = true, 2 if self.state[row][col] => next_state[row][col] = true, _ => {} } } } Board { state: next_state } } fn count_neighbors(&self, cell: Cell) -> u8 { let mut neighbours: u8 = 0;
{ "domain": "codereview.stackexchange", "id": 43722, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, game-of-life", "url": null }
rust, game-of-life fn count_neighbors(&self, cell: Cell) -> u8 { let mut neighbours: u8 = 0; for cell in cell.into_neighbors_iter() { if self.state[cell.x.value][cell.y.value] { neighbours += 1; } } neighbours } } Final Code: const WIDTH: usize = 10; const HEIGHT: usize = 10; type State = [[bool; WIDTH]; HEIGHT]; #[derive(Debug, Copy, Clone)] struct Coord { value: usize, max: usize, } impl Coord { fn new(value: usize, max: usize) -> Self { Coord { value, max, } } fn increment(&mut self) { self.value += 1; if self.value >= self.max { self.value = 0; } } fn decrement(&mut self) { self.value = self.value.checked_sub(1).unwrap_or(self.max - 1); } } #[derive(Debug, Copy, Clone)] struct Cell { x: Coord, y: Coord, } impl Cell { fn new(x: usize, y: usize) -> Self { Cell { x: Coord::new(x, HEIGHT), y: Coord::new(y, WIDTH), } } fn into_neighbors_iter(self) -> NeighborsIter { NeighborsIter::new(self) } } struct NeighborsIter { state: usize, cell: Cell, } impl NeighborsIter { fn new(init: Cell) -> Self { Self { state: 0, cell: init, } } } impl Iterator for NeighborsIter { type Item = Cell;
{ "domain": "codereview.stackexchange", "id": 43722, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, game-of-life", "url": null }