body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have a script that I wrote, and I'm sure that there is a better way to do it, but can't for the life of me figure it out.</p> <p>Here is the problem statement: I need to backup data to a remote location, but what actually gets backed up depends on what day of the week it is. I have a program that creates a folder with the date of business as the name (yyyymmdd). Usually this happens late at night, either at 11:55 pm or later. Which means when this scripts runs, it could possibly be the next day, though we are looking for a folder with the previous day's date. Finally, if the dated folder is for a Sunday, we need to back up the previous 3 days of data, i.e. Friday, Saturday, and Sunday. </p> <p>I am using mostly <code>if</code> statements, but there has to be a better way to this. </p> <p>Any assistance would be appreciated.</p> <p>Code:</p> <pre><code> # Get today's date $currdate = [datetime]::Today.ToString("yyyyMMdd") # If the current day is a Monday or (i.e. last DOB is Sunday), # that means that we have to grab the last 3 days (Friday, Saturday, and Sunday) of data $currdayofweek = [datetime]::Today.DayOfWeek if ( ($currdayofweek -ne 'Sunday') -or ($currdayofweek -ne 'Monday')) { # It is not Sunday or Monday, we do not have to backup the last 3 days, # only the current or previous day's data if ( !(Test-Path -Path "$iber<span class="math-container">\$currdate" -PathType Container )) { # A dated sub folder for the current day does not exist # It is after midnight and we need to use the previous day's # date of business $currdate = [datetime]::Today.AddDays(-1).ToString("yyyyMMdd") # Copy the dated sub folder, archive and settlement copyItems -sourceInput "$iber\$currdate" -destinationInput "$uncroot\$backup\" Copy-Item -Path "$iber\ARCHIVE\$currdate.zip" -Destination "$uncroot\$backup\ARCHIVE" Copy-Item -Path "$iber\EDC" -Destination "$uncroot\$backup\EDC" -Filter "$currdate.stl" -Recurse RunGenPoll -inputfolder "$iber\$</span>currdate" } else { # A dated sub folder the current day does exist # It is before midnight and we can use the current day's # date of business # Copy the dated sub folder, archive and settlement copyItems -sourceInput "$iber<span class="math-container">\$currdate" -destinationInput "$uncroot\$</span>backup\" Copy-Item -Path "$iber\ARCHIVE<span class="math-container">\$currdate.zip" -Destination "$uncroot\$</span>backup\ARCHIVE" Copy-Item -Path "$iber\EDC" -Destination "$uncroot<span class="math-container">\$backup\EDC" -Filter "$currdate.stl" -Recurse RunGenPoll -inputfolder "$iber\$</span>currdate" } } elseif ($currdayofweek -eq 'Monday') { # Day of the week is Monday # We need to see if it is Monday morning (dob Sunday), or # Monday evening (dob Monday) if ( !(Test-Path -Path "$iber\$currdate" -PathType Container) ) { # It is Monday and after midnight on Sunday # Copy Friday, Saturday and Sunday's data $currdate = [datetime]::Today.AddDays(-1).ToString("yyyyMMdd") LogInfo -LogLine "Copying Archive files to $uncroot<span class="math-container">\$backup\ARCHIVE" $archivesubs = Get-ChildItem -Path "$iber\ARCHIVE" | Where-Object { $_ -like "20*" } | Sort-Object -Descending $archivesubs | Select-Object -Index (1..$archivenum) | Copy-Item -Destination "$uncroot\$</span>backup\ARCHIVE" -Recurse -Force LogInfo -LogLine "Copying dated sub folders to $uncroot<span class="math-container">\$backup" $datedsubs = Get-ChildItem -Path "$iber"| Where-Object { $_ -like "20*" } | Sort-Object -Descending $datedsubs | Select-Object -Index (1..$datednum) | Copy-Item -Destination "$uncroot\$</span>backup" -Recurse LogInfo -LogLine "Copying EDC files" Robocopy.exe "$env:EDCPATH" "$uncroot<span class="math-container">\$backup\EDC" *.* /XF $edcexclude # Copy the dated sub folder, archive and settlement RunGenPoll -inputfolder "$iber\$</span>currdate" } else { # It is Monday and we have a dated sub folder for Monday # Copy the dated sub folder, archive and settlement copyItems -sourceInput "$iber<span class="math-container">\$currdate" -destinationInput "$uncroot\$</span>backup\" LogInfo -LogLine "Copying Archive files to $uncroot<span class="math-container">\$backup\ARCHIVE" Copy-Item -Path "$iber\ARCHIVE\$</span>currdate.zip" -Destination "$uncroot<span class="math-container">\$backup\ARCHIVE" LogInfo -LogLine "Copying EDC files" Copy-Item -Path "$iber\EDC" -Destination "$uncroot\$</span>backup\EDC" -Filter "$currdate.stl" -Recurse RunGenPoll -inputfolder "$iber<span class="math-container">\$currdate" } } else { # It is Sunday # Copy data for Friday, Saturday and Sunday LogInfo -LogLine "Copying Archive files to $uncroot\$backup\ARCHIVE" $archivesubs = Get-ChildItem -Path "$iber\ARCHIVE" | Where-Object { $_ -like "20*" } | Sort-Object -Descending $archivesubs | Select-Object -Index (1..$archivenum) | Copy-Item -Destination "$uncroot\$</span>backup\ARCHIVE" -Recurse -Force LogInfo -LogLine "Copying dated sub folders to $uncroot<span class="math-container">\$backup" $datedsubs = Get-ChildItem -Path "$iber"| Where-Object { $_ -like "20*" } | Sort-Object -Descending $datedsubs | Select-Object -Index (1..$datednum) | Copy-Item -Destination "$uncroot\$</span>backup" -Recurse LogInfo -LogLine "Copying EDC files" Robocopy.exe "$env:EDCPATH" "$uncroot<span class="math-container">\$backup\EDC" *.* /XF $edcexclude RunGenPoll -inputfolder "$iber\$</span>currdate" } </code></pre> <p>Please let me know if anyone needs any clarification on anything.</p> <p>Thanks</p>
[]
[ { "body": "<p>How about checking the current time instead of checking the existence of the subfolder.<br/></p>\n\n<p>The script below has a function to back up the data of the specified date.</p>\n\n<pre><code>function Backup-Data ([string]$Path, [string]$Dest, [datetime]$Date) {\n\n $baseName = $Date.ToString(\"yyyyMMdd\")\n Copy-Item \"$Path<span class=\"math-container\">\\$baseName\" $Dest -Recurse\n Copy-Item \"$Path\\ARCHIVE\\$</span>baseName.zip\" \"$Dest\\ARCHIVE\"\n Copy-Item \"$Path\\EDC<span class=\"math-container\">\\$baseName.stl\" \"$Dest\\EDC\"\n RunGenPoll -InputFolder \"$Path\\$</span>baseName\"\n}\n\n\n$backupPath = \"$uncroot\\$backup\"\n$now = Get-Date\n$targetDate = if ($now.Hour -lt 12) { $now.AddDays(-1).Date } else { $now.Date }\n\nif ($targetDate.DayOfWeek -eq \"Sunday\") {\n -2..0 | ForEach-Object { Backup-Data $iber $backupPath $targetDate.AddDays($_) }\n}\nelse {\n Backup-Data $iber $backupPath $targetDate\n}\n</code></pre>\n\n<p>If you run the script in the morning, the <code>$targetDate</code> will be previous day.<br/>\nIf <code>$targetDate.DayofWeek</code> is Sunday, it will backup data from two days ago to today.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T06:34:18.417", "Id": "224864", "ParentId": "224829", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T18:04:50.537", "Id": "224829", "Score": "2", "Tags": [ "shell", "powershell" ], "Title": "Script to Backup Data to Remote Location. The data to backup depends on the day of the week" }
224829
<p>For my first project with Rust, I decided to try and implement a minimal static site generator. I've never had any code review, and I've been looking for some feedback so I can get better!</p> <h3>Brief Context</h3> <p>The directory structure is the following:</p> <pre><code>./src/main.rs -&gt; the code file ./posts/*.md -&gt; a list of markdown files to covert to HTML ./compiled -&gt; the directory to place completed HTML files in. ./compiled/assets -&gt; contains the assets for the website, including header.html and footer.html, which the rust script attaches to the top/bottom of every HTML page. </code></pre> <p>Code is available on <a href="https://github.com/arya-k/blog" rel="nofollow noreferrer">Github</a>.</p> <p>Here's the code (main.rs):</p> <pre class="lang-rust prettyprint-override"><code>use chrono::prelude::*; use comrak::nodes::NodeValue; use comrak::{format_html, markdown_to_html, parse_document, Arena, ComrakOptions}; use std::ffi::OsString; use std::fs; use std::vec::Vec; use syntect::highlighting::ThemeSet; use syntect::html::highlighted_html_for_string; use syntect::parsing::SyntaxSet; static REPO_ROOT: &amp;'static str = "/Users/arya/Documents/blog"; static BASE_URL: &amp;'static str = "https://www.arya-k.dev"; #[derive(Debug)] struct Post { name: String, url: String, datestring: String, datecreated: i64, } fn remove_compiled_assets() { println!("Removing compiled assets..."); let dir = fs::read_dir(format!("{}/compiled", REPO_ROOT)).unwrap(); for entry in dir { if let Ok(entry) = entry { let path = entry.path(); if !path.is_dir() &amp;&amp; path.extension().unwrap_or(&amp;OsString::new()) == "html" { fs::remove_file(path).expect("Failed to remove a file"); } } } } fn validate_post(md: &amp;str, file_name: &amp;std::ffi::OsString, goal_name: &amp;str) -&gt; Option&lt;Post&gt; { if !md.starts_with("# ") { // if it doesn't have a title, ignore it. println!("Skipping {:?} - Missing title", file_name); return None; } else if !md.contains('\n') { // if it can't have a rawdate, ignore it. println!("Skipping {:?} - Too short", file_name); return None; } let mut lines = md.lines(); let title = &amp;(lines.next().unwrap())[2..]; let rawdate = lines.next().unwrap(); if !rawdate.starts_with("&lt;time&gt;") { // if it doesn't have a date, ignore it. println!("Skipping {:?} - Missing date", file_name); return None; } let parsed_date = Utc.datetime_from_str( &amp;format!("{} 00:00:00", rawdate), "&lt;time&gt;%b %e, %Y&lt;/time&gt; %T", ); if parsed_date.is_err() { // if date is malformed, ignore it println!("Skipping {:?} - Malformed date", file_name); return None; } // Gather info into a struct: Some(Post { name: title.to_string(), url: format!("{}/{}", BASE_URL, goal_name), datestring: rawdate.to_string(), datecreated: parsed_date.unwrap().timestamp(), }) } fn md_to_html(md: &amp;str, comrak_options: &amp;ComrakOptions) -&gt; std::string::String { let arena = Arena::new(); let root = parse_document(&amp;arena, &amp;md, &amp;comrak_options); let ps = SyntaxSet::load_defaults_newlines(); let ts = ThemeSet::load_defaults(); // parse code snippets outside of the parser to avoid quotes being html escaped. let mut code_snippets: Vec&lt;std::string::String&gt; = Vec::new(); // basic BFS let mut nodes_to_parse = vec![root]; let mut node; while nodes_to_parse.len() &gt; 0 { node = nodes_to_parse.pop().unwrap(); match &amp;mut node.data.borrow_mut().value { &amp;mut NodeValue::CodeBlock(ref mut codenode) =&gt; { let lang = std::str::from_utf8(&amp;codenode.info).unwrap(); let syntax = ps.find_syntax_by_token(lang).unwrap(); let orig_body = std::mem::replace( // replace code snippets with {{ CODE:# }} &amp;mut codenode.literal, format!("{{ CODE:{} }}", code_snippets.len()) .as_bytes() .to_vec(), ); code_snippets.push( // Save the converted code snippet so we can add it back in highlighted_html_for_string( std::str::from_utf8(&amp;orig_body).unwrap(), &amp;ps, &amp;syntax, &amp;ts.themes["base16-ocean.dark"], ), ); } _ =&gt; (), } nodes_to_parse.extend(node.children()); } let mut html = vec![]; format_html(root, comrak_options, &amp;mut html).unwrap(); // generate main html let mut html_string = std::str::from_utf8(&amp;html) .unwrap() .to_string() .replace("&lt;p&gt;&lt;time&gt;", "&lt;time&gt;") .replace("&lt;/time&gt;&lt;/p&gt;", "&lt;/time&gt;"); // avoid time getting extra escaped // Add the code snippets back in: for (i, cs) in code_snippets.iter().enumerate() { html_string = html_string.replace( &amp;format!("{{ CODE:{} }}", i), &amp;cs.lines() .skip(1) .map(|l| l.to_owned() + "\n") .collect::&lt;String&gt;() // reconnect the strings .replace("&lt;/span&gt;&lt;/pre&gt;", "&lt;/span&gt;"), ); } html_string // return final html string } fn write_index(post_structs: &amp;mut Vec&lt;Post&gt;, header: &amp;str, comrak_options: &amp;ComrakOptions) { // sort the posts: most recent first. post_structs.sort_by_key(|x| -x.datecreated); println!("Generating index"); // this is done inline since it's pretty simple let mut index = header.replace("{{ TITLE }}", "arya-k").to_string(); // reuse header index.push_str("&lt;h1 style=\"font-size:3em\"&gt;Posts&lt;/h1&gt;\n"); // say "Posts" at top of page for post in post_structs { // generate posts in order index.push_str(&amp;format!( "&lt;h1&gt;&lt;a class=\"mainpage\" href=\"{}\"&gt;{}&lt;/a&gt;&lt;/h1&gt;\n{}\n", post.url, markdown_to_html(&amp;post.name, &amp;comrak_options) // respect markdown in titles .replace("&lt;p&gt;", "") .replace("&lt;/p&gt;", ""), post.datestring )); } index.push_str( &amp;fs::read_to_string(format!("{}/compiled/assets/index_footer.html", REPO_ROOT)) .expect("Unable to read footer"), ); // this part is a custom footer fs::write(format!("{}/compiled/index.html", REPO_ROOT), index) .expect("Unable to write index file"); } fn main() { // First, remove the compiled assets remove_compiled_assets(); // Gather the head and tail strings: let header = fs::read_to_string(format!("{}/compiled/assets/head.html", REPO_ROOT)) .expect("Unable to read header") .replace("{{ BASE_URL }}", BASE_URL); let footer = "&lt;/body&gt;\n&lt;/html&gt;"; // Add support for all github extensions on Markdown let comrak_options = ComrakOptions { unsafe_: true, default_info_string: Some("bash".into()), ext_strikethrough: true, ext_table: true, ext_autolink: true, ext_tasklist: true, ..ComrakOptions::default() }; // Start parsing through all the posts: let mut post_structs: Vec&lt;Post&gt; = Vec::new(); let posts = fs::read_dir(format!("{}/posts", REPO_ROOT)).unwrap(); for post in posts { // gather info about file let safe_post = post.unwrap(); let goal_path = safe_post.path().with_extension("html"); let goal_name = goal_path.file_name().unwrap().to_str().unwrap(); println!("Compiling {:?}", safe_post.file_name()); // read markdown let md = fs::read_to_string(safe_post.path()).expect("Unable to read file"); if let Some(p) = validate_post(&amp;md, &amp;safe_post.file_name(), &amp;goal_name) { // convert to markdown + generate file: let html = format!( "{}{}{}", header.replace("{{ TITLE }}", &amp;p.name), md_to_html(&amp;md, &amp;comrak_options), footer ); // write to file fs::write(format!("{}/compiled/{}", REPO_ROOT, goal_name), html) .expect("Unable to write file"); // add to all posts post_structs.push(p); } } // create the index file using the posts write_index(&amp;mut post_structs, &amp;header, &amp;comrak_options); println!("Done!"); } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T18:18:57.733", "Id": "224830", "Score": "2", "Tags": [ "beginner", "file-system", "rust" ], "Title": "Minimal Static Site generator" }
224830
<pre><code>export const updateWatchlist = (coin: IAsset, watchlist: IAsset[]) =&gt; { watchlist.push(coin) return watchlist.map((c) =&gt; c) } </code></pre> <p>Is this 1-line-able with a lib like <a href="https://ramdajs.com/docs/" rel="nofollow noreferrer">Ramda</a>?</p>
[]
[ { "body": "<p>Figured it out :D</p>\n\n<p><a href=\"https://ramdajs.com/docs/#concat\" rel=\"nofollow noreferrer\">https://ramdajs.com/docs/#concat</a></p>\n\n<pre><code>export const updateWatchlist = (coin: IAsset, watchlist: IAsset[]) =&gt; R.concat(watchlist, [coin]);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T18:39:26.140", "Id": "436216", "Score": "1", "body": "You don't need a library [to use concat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T18:32:42.067", "Id": "224832", "ParentId": "224831", "Score": "-2" } }, { "body": "<p>You could just write</p>\n\n<pre><code>export const updateWatchlist = (coin: IAsset, list: IAsset[]) =&gt; [...list, coin];\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T18:33:55.373", "Id": "224833", "ParentId": "224831", "Score": "4" } } ]
{ "AcceptedAnswerId": "224833", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T18:22:56.480", "Id": "224831", "Score": "-1", "Tags": [ "typescript" ], "Title": "Function which updates an array and returns a map" }
224831
<p>I have made a console game using c++ without using OOP. The code works, but is it good that way or should I have used OOP?</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;utility&gt; #include &lt;vector&gt; #include &lt;Windows.h&gt; #include &lt;ctime&gt; enum direction { STOP, UP, DOWN, RIGHT, LEFT }; const unsigned short width{ 50 }, height{ 20 }; unsigned short xFruit{}, yFruit{}, xTail{}, yTail{}, score{}; bool lost{ false }; std::vector&lt;std::pair&lt;unsigned short, unsigned short&gt;&gt; snake; direction dir{ STOP }; void startGame(); void draw(); void input(); void movement(); void eatFruit(); void generateFruit(); void endGame(); void ClearScreen() { // Function which cleans the screen without flickering COORD cursorPosition; cursorPosition.X = 0; cursorPosition.Y = 0; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cursorPosition); } int main() { startGame(); while (!lost) { srand(static_cast&lt;unsigned int&gt;(time(0))); draw(); input(); movement(); eatFruit(); if (dir == UP || dir == DOWN) // To slow the vertical movement Sleep(40); else // To slow the horizontal movement Sleep(20); } endGame(); return 0; } void startGame() { srand(static_cast&lt;unsigned int&gt;(time(0))); // Start at the center snake.emplace_back(std::make_pair(width / 2, height / 2)); generateFruit(); } void draw() { /* * '#' the outer frame * '@' the head * 'o' the body * '*' the fruit */ ClearScreen(); for (unsigned short y{ 1 }; y &lt;= height; y++) { for (unsigned short x{ 1 }; x &lt;= width; x++) { if (x == 1 || x == width) std::cout &lt;&lt; '#'; else if (y == 1 || y == height) std::cout &lt;&lt; '#'; else if (x == snake.at(0).first &amp;&amp; y == snake.at(0).second) std::cout &lt;&lt; '@'; else if (std::find(snake.begin() + 1, snake.end(), std::make_pair(x, y)) != snake.end()) std::cout &lt;&lt; 'o'; else if (x == xFruit &amp;&amp; y == yFruit) std::cout &lt;&lt; '*'; else std::cout &lt;&lt; ' '; } std::cout &lt;&lt; std::endl; } std::cout &lt;&lt; "Use arrow keys to move the snake" &lt;&lt; std::endl; std::cout &lt;&lt; "Score: " &lt;&lt; score &lt;&lt; std::endl; } void input() { if (GetAsyncKeyState(VK_UP) &amp;&amp; dir != DOWN) dir = UP; else if (GetAsyncKeyState(VK_RIGHT) &amp;&amp; dir != LEFT) dir = RIGHT; else if (GetAsyncKeyState(VK_DOWN) &amp;&amp; dir != UP) dir = DOWN; else if (GetAsyncKeyState(VK_LEFT) &amp;&amp; dir != RIGHT) dir = LEFT; } void movement() { // Move each part's place of the body to the previous part's place starting from the end of the snake to the second part for (unsigned int part{snake.size() - 1}; part &gt; 0; part--) { snake.at(part) = snake.at(part - 1); } if (dir == UP) { snake.at(0).second--; // if the snake hit the top wall, move to the bottom if (snake.at(0).second &lt;= 1) snake.at(0).second = height - 1; } else if (dir == DOWN) { snake.at(0).second++; // if the snake hit the bottom wall, move to the top if (snake.at(0).second &gt;= height) snake.at(0).second = 2; } else if (dir == RIGHT) { snake.at(0).first++; // if the snake hit the right wall, move to the left if (snake.at(0).first &gt;= width) snake.at(0).first = 2; } else if (dir == LEFT) { snake.at(0).first--; // if the snake hit the left wall, move to the right if (snake.at(0).first &lt;= 1) snake.at(0).first = width - 1; } // If the snake hit itself if (std::find(snake.begin()+1, snake.end(), snake.at(0)) != snake.end()) lost = true; } void eatFruit() { if (snake.at(0).first == xFruit &amp;&amp; snake.at(0).second == yFruit) { generateFruit(); score++; // create new part of the snake if (dir == UP) { xTail = snake.back().first; yTail = snake.back().second + 1; } else if (dir == DOWN) { xTail = snake.back().first; yTail = snake.back().second - 1; } else if (dir == RIGHT) { xTail = snake.back().first - 1; yTail = snake.back().second; } else if (dir == LEFT) { xTail = snake.back().first + 1; yTail = snake.back().second; } snake.emplace_back(std::make_pair(xTail, yTail)); } } void generateFruit() { xFruit = rand() % (width - 3) + 2; yFruit = rand() % (height - 3) + 2; // To check if the fruit appeared behind the snake if (std::find(snake.begin(), snake.end(), std::make_pair(xFruit, yFruit)) != snake.end()) generateFruit(); } void endGame() { std::cout &lt;&lt; "You lost, Score: " &lt;&lt; score &lt;&lt; std::endl; std::cin.get(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T15:14:29.010", "Id": "436359", "Score": "2", "body": "Hi, and welcome to the site. It would be helpful if you could clarify how a \"snake game\" is supposed to work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T08:06:14.883", "Id": "436474", "Score": "1", "body": "The program does not build on Visual Studio 2015 x64. The problem is the first line in `movement()`: `part` is declared as `unsigned int`, however, `snake.size()-1` is `std::size_t`. The brace initialization forbids the conversion. It builds if you declare `part` as `std::size_t`." } ]
[ { "body": "<p>Only call <code>srand</code> <em>once</em>. Continually reseeding it can result in non-random random numbers.</p>\n\n<p>The statements in <code>ClearScreen</code> should be on separate lines. With them all spread out like that it is hard to see what it is doing (which doesn't seem to actually clear the screen, just move the cursor to the top left of the console).</p>\n\n<p>In <code>main</code>, the <code>if</code> statements should have curly braces because the two statement bodies are on multiple lines. This can avoid future bugs when adding code. It can also be condensed into one statement with the ternary operator. And the two constants (20 and 40) can be turned into named constants so that no commentary would be necessary.</p>\n\n<p>In <code>draw</code>, the checks for <code>x</code> or <code>y</code> equaling 1, height, or width can be removed and the <code>std::cout &lt;&lt; '#';</code> being placed outside the appropriate loop (modified to print the entire line of <code>'#'</code> characters for the top and bottom row). Then you can create a local variable <code>char ch</code> to hold the character that you want to print, and have only one <code>std::cout &lt;&lt; ch</code> instead of repeating them.</p>\n\n<p>In <code>eatFruit</code>, you don't need to determine the position of the new body segment. Just increase the length of <code>snake</code> (copying in the value of the snake's last segment, since you'll draw again before you move), and the following call to <code>move</code> will update it when the previous end moves off of that spot.</p>\n\n<p><code>generateFruit</code> can use a <code>do</code>/<code>while</code> loop instead of recursion.</p>\n\n<p>You might also consider putting in the pause right after the <code>draw</code>, rather than after the <code>input</code>. This may make the snake a bit more responsive to user input.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T06:53:22.263", "Id": "436286", "Score": "0", "body": "`ClearScreen` doesn't technically clear the screen, it moves the cursor to the top left and rewrites the previously written frame.\nThanks for your advice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T03:49:59.907", "Id": "224853", "ParentId": "224842", "Score": "3" } }, { "body": "<p>This is in addition to the answer provided by @1201ProgramAlarm, everything in their review is correct.</p>\n\n<blockquote>\n <p>I have made a console game using c++ without using OOP. The game works perfectly, but is it good that way or should I have used OOP?</p>\n</blockquote>\n\n<p><strong>Bug</strong><br>\nThe program doesn't work perfectly, the snake is supposed to die if it hits a wall. In this implementation the snake re-enters on the opposite side of the screen.</p>\n\n<p><strong>Opinion</strong><br>\nThe second part of the question, if it should be Object Oriented or not is off-topic for Code Review because it is primarily opinion based. The code is also not completely free of objects, the std::vector&lt;> container class is used, and iterators are used.</p>\n\n<p><strong>Global Variable</strong><br>\nGenerally global variables are considered a bad practice. In larger programs with multiple source files it is very difficult to write correct code, debug and maintain code using global variables. Finding where a variable value is altered becomes a huge task. A second problem with global variables in a multi-file program is that global variables are global in scope and can lead to duplicate definitions at link time. In an object oriented program all of these variables could have been global within the object but the scope would still be limited to the object itself.</p>\n\n<p>In non-object oriented programming it might be better to declare the variables in functions or procedures and pass the values into sub functions.</p>\n\n<p>The variables <code>xtail</code> and <code>ytail</code> should be declared in the function <code>void eatFruit()</code> since they are not used anywhere else in the program.</p>\n\n<p><strong>Variable Declarations and Performance</strong><br>\nThe code is primarily using <code>unsigned short</code> variables and this will affect performance because it is not the default word size. The default word size in C++ is int or unsigned int. Generally the computer instructions that are generated by the code will be using the default word size. The short type is generally used within objects to save space, which does not seem to be necessary in this case.</p>\n\n<p><strong>Use Vertical Spacing to Make the Code more Readable</strong><br>\nTo make code easier to maintain it would be better to have one variable declared per statement and each declaration on it's own line. Rather than saving vertical space, use vertical space to make the code easier to read and update:</p>\n\n<pre><code>const unsigned short width = 50;\nconst unsigned short height = 20;\n\nunsigned short xFruit;\nunsigned short yFruit;\nunsigned short score = 0;\n\nvoid ClearScreen()\n{\n // Function which cleans the screen without flickering\n COORD cursorPosition;\n\n cursorPosition.X = 0; \n cursorPosition.Y = 0;\n\n SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cursorPosition);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T01:54:00.503", "Id": "436453", "Score": "1", "body": "In this case, I feel that that \"bug\" is intended. There is specific code in `movement` to handle this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T12:31:16.373", "Id": "224888", "ParentId": "224842", "Score": "2" } } ]
{ "AcceptedAnswerId": "224853", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T22:05:45.150", "Id": "224842", "Score": "4", "Tags": [ "c++", "console", "snake-game" ], "Title": "c++ console snake game" }
224842
<p>It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.</p> <p>Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.</p> <pre><code>from time import time def is_permutation(n1, n2): """returns True if n1 is permutation of n2""" if n1 == n2: return False str1 = str(n1) str2 = str(n2) digits1 = {digit: str1.count(digit) for digit in str1} digits2 = {digit: str2.count(digit) for digit in str2} if not digits1 == digits2: return False return True def check_multiples(n, start=10): """checks 2x, 3x, 4x, 5x, 6x and returns the numbers if they are permutations.""" for x1 in range(start, n): x2 = x1 * 2 if is_permutation(x1, x2): x3 = x1 * 3 if is_permutation(x2, x3): x4 = x1 * 4 if is_permutation(x3, x4): x5 = x1 * 5 if is_permutation(x4, x5): x6 = x1 * 6 if is_permutation(x5, x6): return x1, x2, x3, x4, x5, x6 if __name__ == '__main__': start_time = time() print(check_multiples(1000000, 125000)[0]) print(f'Time: {time() - start_time} seconds.') </code></pre>
[]
[ { "body": "<ul>\n<li><p>For the umpteenth time, do not write</p>\n\n<pre><code>if not digits1 == digits2:\n return False\nreturn True\n</code></pre>\n\n<p>Do write</p>\n\n<pre><code>return digits1 == digits2\n</code></pre></li>\n<li><p>The magic number <code>125000</code> must be explained. Preferably in the code, not in comments.</p></li>\n<li><p>Seven levels of indentation should be immediately seen as a big bright red flag, style wise. At least fold it into the loop.</p></li>\n<li><p>Seven levels of indentation should be immediately seen as a big bright red flag, algorithm wise. How would you approach a question asking for 16, rather than 6, multiples? As a side note, if you continue with PE, you have a chance to encounter it.</p></li>\n<li><p>Expanding on the bullet above, please take my advice and study some math. This problem does have a nice solution. Ponder on the fact that <span class=\"math-container\">\\$142857 * 7 = 1000000 - 1\\$</span>. An <a href=\"https://en.wikipedia.org/wiki/Fermat%27s_little_theorem#Generalizations\" rel=\"nofollow noreferrer\">Euler's generalization</a> of Fermat's Little theorem is a must. PE is very fond of it.</p>\n\n<p>And stop brute forcing.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T03:24:47.637", "Id": "436272", "Score": "0", "body": "@ vnp I fully understand what you said except for the part of the seven levels of indentation, can you explain how this is doable by folding it into the loop? concerning studying some math, in fact I actually started doing so not for long but I'm currently studying." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T03:49:56.360", "Id": "436274", "Score": "0", "body": "I guess what you mean by folding into the loop is I have to calculate 2x, 3x, 4x, 5x, 6x for every number even if it is not a permutation, if that's what you mean then I will be doing 6 calculations per number(whether a permutation or not) anyway if that's not what you mean please show some example for me to understand" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T01:16:48.803", "Id": "224850", "ParentId": "224843", "Score": "1" } }, { "body": "<p><em>Disclaimer: none of this is tested</em></p>\n\n<p><strong>Getting rid of the multiple levels of indentations</strong></p>\n\n<p>First observation, instead of checking <code>is_permutation(x{n-1}, x{n})</code>, you could check <code>is_permutation(x{0}, x{n})</code>.</p>\n\n<pre><code>def check_multiples(n, start=10):\n \"\"\"checks 2x, 3x, 4x, 5x, 6x and returns the numbers if they are permutations.\"\"\"\n for x in range(start, n):\n x2 = x * 2\n if is_permutation(x, x2):\n x3 = x * 3\n if is_permutation(x, x3):\n x4 = x * 4\n if is_permutation(x, x4):\n x5 = x * 5\n if is_permutation(x, x5):\n x6 = x * 6\n if is_permutation(x, x6):\n return x, x2, x3, x4, x5, x6\n</code></pre>\n\n<p>Then, values <code>x{n}</code> are only used once, we do not need a temporary variable for them anymore. We can write:</p>\n\n<pre><code>def check_multiples(n, start=10):\n \"\"\"checks 2x, 3x, 4x, 5x, 6x and returns the numbers if they are permutations.\"\"\"\n for x in range(start, n):\n if is_permutation(x, x * 2):\n if is_permutation(x, x * 3):\n if is_permutation(x, x * 4):\n if is_permutation(x, x * 5):\n if is_permutation(x, x * 6):\n return x, x * 2, x * 3, x * 4, x * 5, x *6\n</code></pre>\n\n<p>Then, this can be written as a single test:</p>\n\n<pre><code>def check_multiples(n, start=10):\n \"\"\"checks 2x, 3x, 4x, 5x, 6x and returns the numbers if they are permutations.\"\"\"\n for x in range(start, n):\n if is_permutation(x, x * 2) and\n is_permutation(x, x * 3) and\n is_permutation(x, x * 4) and\n is_permutation(x, x * 5) and\n is_permutation(x, x * 6):\n return x, x*2, x*3, x*4, x*5, x*6\n</code></pre>\n\n<p>Then, this can be rewritten using the <code>all</code> builtin</p>\n\n<pre><code>def check_multiples(n, start=10):\n \"\"\"checks 2x, 3x, 4x, 5x, 6x and returns the numbers if they are permutations.\"\"\"\n for x in range(start, n):\n if all(is_permutation(x, x * i) for i in range(2, 7))\n return x, x*2, x*3, x*4, x*5, x*6\n</code></pre>\n\n<p><strong>Optimisation - small range</strong></p>\n\n<p>For many values of <code>x</code>, <code>x</code> and <code>6 * x</code> do not have the same number of digits (and thus can be permutations of each other). You could limit yourself to relevant values of <code>x</code>.</p>\n\n<p>Another way to do it could be to check <code>x * 6</code> then <code>x * 5</code> then ... down to <code>x * 2</code> instead of going the other way round.</p>\n\n<p><strong>Optimisation - reduce duplicated computation</strong></p>\n\n<p>Everytime we compute <code>is_permutation(x, foobar)</code>, we re-perform the same processing on the <code>x</code> value. This could be done once and for all:</p>\n\n<pre><code>def get_digit_count(n):\n s = str(n)\n return {digit: s.count(digit) for digit in s}\n\n\ndef check_multiples(n, start=10):\n \"\"\"checks 2x, 3x, 4x, 5x, 6x and returns the numbers if they are permutations.\"\"\"\n for x in range(start, n):\n digits = get_digit_count(x)\n if all(digits == get_digits_count(x * i) for i in range(2, 7))\n return x, x2, x3, x4, x5, x6\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T13:44:04.787", "Id": "224895", "ParentId": "224843", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T22:33:50.920", "Id": "224843", "Score": "2", "Tags": [ "python", "performance", "beginner", "python-3.x", "programming-challenge" ], "Title": "Project Euler # 52 Permuted multiples in Python" }
224843
<p>A coding challenge to construct a binary tree from an array. </p> <pre><code>class BinaryTreeNode { constructor(value) { this.value = value; this.left = null; this.right = null; } } function makeBst(arr){ if(!arr || arr.length &lt;= 1){ return arr; } let top = arr[Math.floor(arr.length / 2)]; let node = new BinaryTreeNode(top); let rightArr = arr.splice(Math.floor(arr.length /2), arr.length); let leftArr = arr.splice(0, Math.floor(arr.length / 2)); node.right = makeBst(rightArr); node.left = makeBst(leftArr); return node; } const arr = [1, 2, 3, 4, 5, 6, 7]; makeBst(arr); </code></pre> <p>The function returns the correct output, and all known edge cases have been accounted for. I would like feedback on cleaning up the conditional logic, as well as help determining the time and space complexity (and the possibility of improving both).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T05:57:47.450", "Id": "437241", "Score": "4", "body": "\"The function returns the correct output, and all known edge cases have been accounted for.\" Are you sure? You've added one test which doesn't look so good and can't possibly cover all edge cases. Do you have more tests? How did you validate their output?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T06:02:58.733", "Id": "437242", "Score": "2", "body": "Please verify the correctness of this code. Until then, we have doubts and per the [help/on-topic] we can't help you if the code doesn't work yet. Review is what happens *after* it works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T11:21:49.240", "Id": "437290", "Score": "1", "body": "The result of your \"test\" returns a tree with the following nodes: 4, 1, 4, 6, 7, 7. That doesn't look like correct output at all." } ]
[ { "body": "<p>This solution doesn't look correct to me. Where's <code>2</code>? Why's <code>7</code> in there twice? Why are <code>left</code> and <code>right</code> sometimes arrays and sometimes tree nodes?</p>\n\n<p>I guess you meant to use <code>slice</code> instead of <code>splice</code> (which might explain the fate of that missing <code>2</code>), and probably want to exclude the node value in the <code>right</code> branch (which might explain the extra <code>7</code>).</p>\n\n<p>If I were writing something like this, I'd probably drop that BinaryTreeNode class, since it's not really doing anything, and use a plain object. Bitwise right shift might be a little less noisy than divide and floor, and you could just do that once since you're gonna use it three times.</p>\n\n<p>Maybe something like this:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function makeBST(a) {\n let len = a.length\n let mid = len &gt;&gt; 1\n return len ? {\n value: a[mid],\n left: makeBST(a.slice(0, mid)),\n right: makeBST(a.slice(mid + 1, len)),\n } : null\n}\n</code></pre>\n\n<p>Season to taste with semicolons.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T01:18:13.727", "Id": "224851", "ParentId": "224846", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T23:35:40.347", "Id": "224846", "Score": "-2", "Tags": [ "javascript", "programming-challenge", "array", "complexity", "binary-search" ], "Title": "Challenge - Construct binary tree from array" }
224846
<p>I've written a function that returns how many Months and Days are between two dates. I want to respect calendar month boundaries, but I'm ignoring time as it's not relevant for my needs.</p> <p>I've got the following, but I feel like I'm missing thing I can do to optimize it/refactor it. So I'm looking for additional eyes to help me review this.</p> <pre class="lang-cs prettyprint-override"><code>//As opposed to TimeSpan ^_^ public readonly struct CalendarSpan { public CalendarSpan(int months, int days) { Months = months; Days = days; } public readonly int Months; public readonly int Days; } public static CalendarSpan DifferenceInMonthsAndDays(DateTime startDate, DateTime endDate) { //Ensuring that the larger of two dates is the latter argument if (startDate &gt; endDate) return DifferenceInMonthsAndDays(endDate, startDate); //Start with getting the difference in months var months = 12 * (endDate.Year - startDate.Year) + endDate.Month - startDate.Month; int days; //Add the difference in months to the smaller of the two dates var addedMonths = startDate.AddMonths(months); if (addedMonths &lt;= endDate) //So long as we can avoid negative numbers, just do the simple math days = endDate.Day - addedMonths.Day; else { //Otherwise, backoff by 1 months, and use the built in Subtract logic to get the number of days between the two dates months--; addedMonths = startDate.AddMonths(months); days = endDate.Subtract(addedMonths).Days; } return new CalendarSpan(months, days); } </code></pre> <p><strong>UPDATE</strong> I have been trying to get unit tests for this, and I honestly don't know why I ever attempted this. It is NOT an easy or straight forward thing to do at all. <em>Insert obligatory meme of Homer disappearing into the hedges</em></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T03:09:46.910", "Id": "436271", "Score": "6", "body": "This will give the same span for some combinations of dates (e.g. May 30 -> Jun 30 and May 31 -> Jun 30 will both give 1 month 0 days because [AddMonths](https://docs.microsoft.com/en-us/dotnet/api/system.datetime.addmonths?view=netframework-4.8) will return the last day of the month if the calculated day does not exist). Is this expected/acceptable behavior?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T03:26:10.173", "Id": "436273", "Score": "1", "body": "You mention `as opposed to timespan`, but you don't justify why." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T10:32:21.070", "Id": "436319", "Score": "5", "body": "Can you add some unit tests to show what output you would expect? For example with `30.01.2019` and `01.12.2019` your solution gives 10 months, 1 day but I could imagine that 10 months and 2 days would be equally likely, depending on where you start." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T10:34:37.590", "Id": "436320", "Score": "1", "body": "@tinstaafl I think that was just a comment about the naming of the struct. As to why not use a TimeSpan the reason is probably because it has no concept of months or years of a difference which makes sense for a accurate and technical result but does not fulfill the need that humans like to think in month differences." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T17:00:29.700", "Id": "436391", "Score": "0", "body": "Is the end date inclusive or exclusive? A simple example: 01.01.2020 - 01.01.2020 should yield 0 or 1 days?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T19:54:35.363", "Id": "436423", "Score": "0", "body": "@1201ProgramAlarm Correct. I'm more interested in the number of Calendar months between two dates than the number of days. I'm using this to determine how much something should charge when it's billed per calendar month for scheduling reasons (not per 30.5 days). But I also need to know the number of days when it's not enough to be a full calendar month." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T19:56:09.123", "Id": "436424", "Score": "0", "body": "@poke Hmm, I've got a bug somewhere then. `30.01.2019` to `01.12.2019` gives the same result as `31.01.2019` to `01.12.2019`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T19:58:23.837", "Id": "436425", "Score": "0", "body": "@dfhwze Yes, that's correct, It should be 0 days since they are the same date, and I'm not concerned with time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T03:56:20.550", "Id": "436456", "Score": "0", "body": "The example listed by @poke is the same as the problem I described. Since adding 10 months to January 31 gives November 31, which doesn't exist, the result will be November 30, which is the same date you get when adding 10 months to January 30." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T07:45:26.883", "Id": "436468", "Score": "4", "body": "*“It is NOT an easy or straight forward thing to do at all.”* – Welcome to the world of calendar dates… " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T12:33:50.453", "Id": "436517", "Score": "3", "body": "I've voted to close this because I think it is impossible to comment on the suitability of the code without a better specification." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T14:43:14.283", "Id": "438043", "Score": "0", "body": "Considering the difficulty of dealing with dates, wouldn't it be easier to use something like https://github.com/nodatime/nodatime ?" } ]
[ { "body": "<p>Last answer deleted (instead of substantially revising).</p>\n\n<p><strong>Notes</strong> (see comments in code)</p>\n\n<ol>\n<li><code>CalendarSpan</code> signed (date1 > date2 => negative span)</li>\n<li>Extension overload of <code>DateTime.Add()</code> taking CalendarSpan argument</li>\n<li>Unit test approach (see <code>Main()</code> which iterates positive and negative differences, using <code>DateTime</code> functions to check integrity of results) </li>\n</ol>\n\n<p>`</p>\n\n<pre><code>using System;\n\nnamespace DateDiff\n{\n static class Program\n {\n public readonly struct CalendarSpan \n {\n public CalendarSpan(int months, int days)\n {\n Months = months;\n Days = days;\n }\n public readonly int Months;\n public readonly int Days;\n }\n\n // Maintains sign-consistency, i.e. if l &gt; r returned value components are positive and if l &lt; r negative\n public static CalendarSpan MonthDaysDifference(this DateTime l, DateTime r)\n {\n var mDiff = l.Month - r.Month + 12 * (l.Year - r.Year);\n\n var dDiff = (l - r.AddMonths(mDiff)).Days;\n if (dDiff == 0 // no day, the span is a whole number of months\n || l &gt; r &amp;&amp; dDiff &gt; 0 // day and month differences ...\n || l &lt; r &amp;&amp; dDiff &lt; 0) // ... have the same sign\n return new CalendarSpan(mDiff, dDiff);\n // Signs differ\n var dSign = Math.Sign(dDiff);\n var mSign = Math.Sign(mDiff);\n // It doesn't matter which sign is which, we adjust months in the correct direction\n mDiff += dSign;\n // and recalculate days\n return new CalendarSpan(mDiff, (l - r.AddMonths(mDiff)).Days);\n }\n\n public static DateTime Add(this DateTime dt, CalendarSpan span)\n {\n return dt.AddMonths(span.Months).AddDays(span.Days);\n }\n\n // Included to suggest how to test\n static void Main(string[] args)\n {\n for (int i = 0; i &lt; 1000; i++)\n {\n var date1 = new DateTime(2017, 12, 25).AddDays(i);\n for (int j = 0; j &lt; 1000; j++)\n {\n var date2 = new DateTime(2019, 01, 01).AddDays(j);\n var dateDiff = date1.MonthDaysDifference(date2);\n //var dateDiff2 = MonthDaysDifference(date1,date2);//just checking\n if (date2.Add(dateDiff) != date1)\n {\n Console.WriteLine($\"ERROR: {date1:yyyy-MM-dd} - {date2:yyyy-MM-dd} = {dateDiff.Months} months + {dateDiff.Days} days\");\n Console.WriteLine(\"Any key to exit\");\n Console.ReadKey();\n return;\n }\n Console.WriteLine($\"{date1:yyyy-MM-dd} - {date2:yyyy-MM-dd} = {dateDiff.Months} months + {dateDiff.Days} days\");\n }\n }\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-07T09:10:47.240", "Id": "225709", "ParentId": "224848", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T00:24:09.307", "Id": "224848", "Score": "4", "Tags": [ "c#", "datetime", "interval" ], "Title": "Difference between dates in Months and Days" }
224848
<p>I'm still learning Python, but thought this was kinda a cool project to work on. Feel free to critique and let me know what to work on or change.</p> <p>main.py</p> <pre><code># -------- MODULE IMPORTS -------- import random # -------- CLASS IMPORTS -------- from phrases import Phrases # -------- GLOBAL VARIABLES -------- p_p = Phrases.phrases ref = Phrases.phrases[1] p_a = Phrases.alpha phrase_picked = 0 p_unique_letters = [] p_unique_nums = [] converted_phrase = "" """ THIS FUNCTION GENERATES A RANDOM NUMBER BETWEEN 1 &amp; 26 (NUMBER OF LETTERS IN THE ALPHABET) """ def get_rand_num(): r = random.randint(1, 26) return r """ THIS FUNCTION TAKES THE ORIGINAL PHRASE AND ITERATES OVER EVERY LETTER AND CHANGES IT TO A RANDOM LETTER BASED ON THE RANDOM NUMBER THAT IS ASSIGNED IN THE 'RUN_PUZZLE' FUNCTION """ def create_new_p(): global converted_phrase for l in p_p[phrase_picked]: if l.lower() in p_unique_letters: temp_li = p_unique_letters.index(l.lower()) temp_ni = p_unique_nums[temp_li] - 1 converted_phrase = converted_phrase + p_a[temp_ni] # IF THERE IS A SPECIAL CHARACTER IN THE PHRASE LIKE A PERIOD # OR COLON. THESE STATEMENTS WILL NOT CONVERT THE CHARACTER TO # A RANDOM CHARACTER elif l == '\'': converted_phrase = converted_phrase + "'" elif l == '\"': converted_phrase = converted_phrase + '"' elif l == ' ': converted_phrase = converted_phrase + ' ' elif l == '.': converted_phrase = converted_phrase + '.' elif l == ',': converted_phrase = converted_phrase + ',' elif l == ':': converted_phrase = converted_phrase + ':' elif l == '-': converted_phrase = converted_phrase + '-' """ PRINTS OUT THE FINAL CONVERTED PHRASE TO THE CONSOLE ALONG WITH THE VERSES REFERENCE WHICH IS IN IT'S ORIGINAL SPELLING """ print("\n" + converted_phrase.upper() + "\n\n" + ref) """ THIS FUNCTION ITERATES OVER THE ORIGINAL PHRASE AND PUTS ONLY THE **DIFFERENT** CHARACTERS INTO A LIST. EACH CHARACTER IS THEN ASSIGNED A RANDOM NUMBER BETWEEN 1 &amp; 26. """ def run_puzzle(): for l in p_p[phrase_picked]: if l.lower() not in p_unique_letters and l.lower() in p_a: p_unique_letters.append(l.lower()) p_len = len(p_unique_letters) while len(p_unique_nums) &lt; p_len: r = get_rand_num() if r not in p_unique_nums: p_unique_nums.append(r) """ UNCOMENT BELOW LINE TO SEE A MORE CLEAR OUTPUT OF HOW THE LETTERS ARE ASSIGNED TO A RANDOM NUMBER """ # print(str(p_unique_letters) + ":" + str(p_unique_nums)) create_new_p() </code></pre> <p>phrases.py</p> <pre><code># STARTS THE FIRST FUNCTION CALL OF THE PROGRAM run_puzzle() class Phrases(): # THIS IS A LIST THAT HOLDS EACH LETTER OF THE ALPHABET INDIVIDUALLY alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] # HOLDS THE CURRENT PHRASE(S) IN A LIST. # THE FIRST ITEM([0]) IS THE PHRASE # THE SECOND ITEM([1]) IS THE VERSE REFERENCE phrases = ["Good will come to those who are generous and lend freely, " "who conduct their affairs with justice.", "Psalm - 112:5"] </code></pre>
[]
[ { "body": "<p>You've essentially built a glorified <a href=\"http://practicalcryptography.com/ciphers/caesar-cipher/\" rel=\"nofollow noreferrer\">Caesar Cipher</a>. Not all of the changes I suggest below are included in the final version of the reviewed code, but they should be considered. Here they are:</p>\n\n<ul>\n<li><strong>Comments</strong>: <code>#------- IMPORT STATEMENTS ------</code>, then having one import below it, is a bit verbose. You should only comment code that needs to be explained, like an algorithm or a method. </li>\n<li><strong>Docstrings</strong>: Docstrings belong inside the method</li>\n<li><strong>Structure</strong>: There really is not need to have a separate file for <code>Phrases</code>. Having an array, or user inputed, for the phrases within the file is good enough.</li>\n<li><strong>Global Variables</strong>: It's not recommended to use global variables in your code. If it can be passed as a parameter, do it that way.</li>\n<li><strong>Alphabet</strong>: <code>string</code> has it's own stored alphabet, so you can <code>import string</code> and use, in your case, <code>string.ascii_lowercase</code> for your alphabet.</li>\n<li><strong>Main guard</strong>: You should wrap any code that isn't in a function in a main guard. <a href=\"https://stackoverflow.com/a/5544783/8968906\">Here</a> is an answer that provides a deeper and more meaningful explanation.</li>\n<li><strong>Elif Elif Elif</strong>: You had 7 <code>elif</code> checking for special characters. You can just use an <code>else</code> to catch anything not in the alphabet, and append that.</li>\n<li><strong>String Formatting</strong>: <code>print(\"\\n\" + converted_phrase.upper() + \"\\n\\n\" + ref)</code> looks very chunky. It can be simplified to <code>print(f\"\\n{converted_phrase.upper()}\\n\\n{ref}\")</code>, utilizing the <code>f\"\"</code> string formatting. Using this, you can directly implement variables into strings, instead of using <code>+</code> and separating the string.</li>\n</ul>\n\n<p><strong><em>Final Code</em></strong></p>\n\n<pre><code>import random\n\nCHART = {\n 97: 'a', 98: 'b', 99: 'c', 100: 'd', 101: 'e', 102: 'f', 103: 'g',\n 104: 'h', 105: 'i', 106: 'j', 107: 'k', 108: 'l', 109: 'm', 110: 'n',\n 111: 'o', 112: 'p', 113: 'q', 114: 'r', 115: 's', 116: 't', 117: 'u',\n 118: 'v', 119: 'w', 120: 'x', 121: 'y', 122: 'z'\n}\n\ndef create_new_phrase(text, rotations):\n \"\"\" Encodes the passed text, rotating `rotations` times \"\"\"\n new_phrase = \"\"\n for index in range(len(text)):\n new_position = ord(text[index]) + (rotations % 26)\n if new_position &gt; 122:\n new_position = 97 + (new_position - 122)\n if ord(text[index]) not in CHART:\n new_phrase += text[index]\n else:\n new_phrase += CHART[new_position]\n return new_phrase\n\nif __name__ == '__main__':\n print(create_new_phrase(\"Good will come to those who are generous and lend freely, who conduct their affairs with justice.\".lower(), random.randint(1, 24)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T04:45:17.553", "Id": "224854", "ParentId": "224849", "Score": "1" } }, { "body": "<p>A respectable program for someone learning to code with Python.</p>\n\n<h3>Style</h3>\n\n<p>Comments are good when they add useful information to help someone (likely you in the future) understand the code. MODULE IMPORT, CLASS IMPORTS, and GLOBAL VARIABLES don't really add anything. In contrast, a comment that explains what a global variable is used for and why it needs to be a global variable would be useful.</p>\n\n<p>The Phrase class doesn't really serve a purpose here. The class attributes aren't really so related as to belong in a class.</p>\n\n<p>Global variables should be avoided if possible. They represent an interface to functions that is hidden and likely undocumented. For example, you can't tell from the call <code>create_new_p()</code> at the end of <code>run_puzzle()</code> that you need to first:</p>\n\n<ol>\n<li>set <code>p_p</code> to a list of phrases,</li>\n<li>pick a phrase and store the index of the phrase in <code>phrase_picked</code>,</li>\n<li>set <code>p_unique_letters</code> to a list of the unique letters in the picked phrase,</li>\n<li>set <code>p_unique_nums</code> to a list of random integers between 1 and 26 that has the same length as <code>p_unique_letters</code>, and</li>\n<li>set <code>converted_phrase</code> to an empty string.</li>\n</ol>\n\n<p>or the function won't run correctly. It also doesn't show that the result of the call is returned in <code>converted_phrase</code>.</p>\n\n<p>Docstrings go inside the function, not before it. And please, not in all caps. All uppercase text is actually harder to read than proper mixed case text.</p>\n\n<h3>Substance</h3>\n\n<p>Looking at a call to <code>get_rand_num()</code>, you don't know what it returns without inspecting the function. However, a Python programmer, would readily understand a call to <code>random.randint(1, 26)</code>. So just use the later.</p>\n\n<p>From the doc string for <code>create_new_p()</code> (p for puzzle?), the purpose of the function is to take an input phrase and create a puzzle phrase by mapping the letters to a random permutation of the letters. For example, 'a' may be mapped to 'x' and 'b' may be mapped to 'e'. Anything that isn't a letter is unchanged.</p>\n\n<pre><code>def create_new_puzzle(phrase, letter_mapping):\n ''' Makes a cryptogram of `phrase` by replacing letters according to\n letter_mapping. Other characters are unchanged.\n '''\n\n puzzle_phrase = []\n\n for letter in phrase:\n if letter.isalpha():\n puzzle_phrase.append(letter_mapping[letter])\n else:\n puzzle_phrase.append(letter)\n\n return ''.join(puzzle_phrase)\n</code></pre>\n\n<p>In python, strings are immutable. So contcatenating a letter to a string may have to create a new string, copy the old string and the new letter into the new string. You will frequently see code that creates strings by appending letters to a list, and then using ''.join() on the list at the end to make a string.</p>\n\n<p>With experience, you will learn to write this as a list comprehension:</p>\n\n<pre><code>def create_new_puzzle(phrase, letter_mapping):\n ''' Makes a cryptogram of `phrase` by replacing letters according to\n letter_mapping. Other characters are unchanged.\n '''\n\n puzzle_phrase = [letter_mapping.get(letter,letter) for letter in phrase]\n\n return ''.join(puzzle_phrase)\n</code></pre>\n\n<p>Or, using feature of the standard library, maybe like this:</p>\n\n<pre><code>def create_new_puzzle(phrase, letter_mapping):\n ''' Makes a cryptogram of `phrase` by replacing letters according to\n letter_mapping. Other characters are unchanged.\n '''\n\n return phrase.translate(str.maketrans(letter_mapping))\n</code></pre>\n\n<p>Notice how the interface for <code>create_new_puzzle()</code> is independent from how the function is implemented. The phrase and mapping are passed in and the cryptogram gets returned. This is good because you can change the internals of the function without affecting the rest of the program.</p>\n\n<p><code>run_puzzle()</code> goes through a lot of work to build a mapping from the alphabet to a randomized alphabet. First it collects the unique letters in the phrase, and then associating a unique random number from 1 to 26 to each letter. This can be improved by realizing that it is unnecessary to get the unique letters or associating the numbers. Instead just build a mapping from the alphabet to a jumbled up version of the alphabet. This can also be made into a separate function:</p>\n\n<pre><code>import random\nimport string\n\ndef create_mapping():\n to_alphabet = list(string.ascii_uppercase)\n random.shuffle(to_alphabet)\n\n return dict(zip(string.ascii_letters, to_alphabet*2))\n</code></pre>\n\n<p>I presume phrases is supposed to be a list of phrases, so that one can be picked at random to make a cryptogram puzzle.</p>\n\n<pre><code>phrases = [\n (\"phrase one\", \"cite 1\"),\n (\"phrase two\", \"cite 2\"),\n ... etc.\n]\n</code></pre>\n\n<p>So <code>run_puzzle()</code> becomes:</p>\n\n<pre><code>import phrases\n\ndef run_puzzle():\n phrase, citation = random.choice(phrases)\n mapping = create_mapping()\n puzzle_phrase = create_new_puzzle(phrase, mapping)\n\n print(\"\\n{}\\n\\n{}\".format(puzzle_phrase, citation))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T05:35:17.673", "Id": "224857", "ParentId": "224849", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T00:49:17.127", "Id": "224849", "Score": "1", "Tags": [ "python" ], "Title": "Cryptogram Puzzle" }
224849
<pre><code>with open(filepath) as fp: #line = fp.readline() cnt = 1 while line: line = fp.readline() print("Line {}%: {}".format(cnt, line.strip())) line = line.replace('\n', '') #print('line-&gt;',line) rst = read_ct[read_ct['user_id']==line] #print(rst) if rst.shape[0] != 0: AI = rst.iloc[0,1] else: AI ='32' index=df2[df2['id']==AI].index[0] df['distances'] = cosine_similarity(df, df.iloc[0:index]) n = 1000 # or however many you want n_largest = df['distances'].nlargest(n + 1) # this contains the parent itself as the most similar entry, hence n+1 to get n children file.write(line) #file.writelines([df2.at[i,'article_id'] for i in list(n_largest.index)]) for i in list(n_largest.index): file.write(" "+df2.at[i,'article_id']) file.write('\n') #break cnt += 1 </code></pre> <p>I'm trying to write some preprocessed data to the file but it takes too long so want to gather the idea to make it faster</p> <p>its writing 1000 results for each ID want to know how to make this code "faster"</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T06:23:42.950", "Id": "436282", "Score": "0", "body": "Use the python [profiler](https://docs.python.org/3.7/library/profile.html) to see where your script is spending the most time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T14:36:59.533", "Id": "436354", "Score": "0", "body": "This code is doing a whole lot more than just writing to a file! Please explain what you are calculating. See [ask]." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T05:46:45.827", "Id": "224860", "Score": "1", "Tags": [ "python", "file", "pandas" ], "Title": "is there way to make faster to write to a file?" }
224860
<p>I have 2 data structures with me in JS. One is an array say of <strong>length N</strong>. Let's consider <code>N = 4</code>.</p> <pre><code>const arr = ['a', 'b', 'c', 'd']; </code></pre> <p>The second one is an object:</p> <pre><code>const obj = { a: 0, b: 2, c: 3, z: 5 }; </code></pre> <p>I wrote a code in Javascript, to create a new object out of <code>obj</code> which should not contain the keys which are not present in the array <code>arr</code>. As of now, the <a href="https://en.wikipedia.org/wiki/Time_complexity" rel="nofollow noreferrer">time complexity</a> of the code is <span class="math-container">\$O(n*n)\$</span> i.e., <span class="math-container">\$O(4*4)\$</span>. </p> <pre><code>standardizeFilter(queryParams: any, inputType: Array&lt;string&gt;) { const filter = {}; for (const key of Object.keys(queryParams)) { if (inputType.indexOf(key) &gt; -1) { filter[key] = this.parseValues(queryParams[key]); } } return filter; } </code></pre> <p>I'm wondering if there is a much optimal way to convert this <span class="math-container">\$O(n²)\$</span> to <span class="math-container">\$O(n)\$</span>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T06:41:30.433", "Id": "436283", "Score": "3", "body": "Loop over the array, not the object keys." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T14:35:31.517", "Id": "436352", "Score": "0", "body": "A critique about your terminology: saying \"O(4*4)\" is wrong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T16:35:42.877", "Id": "436386", "Score": "0", "body": "code review requires the full code, not just stub. Please provide the full code of the class or at least the part that has `parseValues`" } ]
[ { "body": "<p>From a short review;</p>\n\n<ul>\n<li><p>Naming</p>\n\n<ul>\n<li><code>standardizeFilter</code> is too specific/specialized, perhaps <code>standardizeObject</code>?</li>\n<li><code>queryParams</code> also seems a very specific name, whereas the functionality is very general, I would just call it <code>keys</code></li>\n<li><code>inputType</code> is not a type, it's an object, I would propose <code>source</code></li>\n</ul></li>\n<li><p>For each <code>key</code> you perform both a <code>indexOf</code> and a <code>[]</code> access, you can drop the <code>indexOf</code></p></li>\n</ul>\n\n<p>I would propose something like this:</p>\n\n<pre><code>function standardizeObject(source, keys){\n\n const o = {};\n\n for(const key of keys){\n const value = source[key];\n if(value !== undefined){\n o[key] = this.parseValues(value);\n }\n } \n\n return o;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T17:05:12.473", "Id": "224915", "ParentId": "224861", "Score": "1" } } ]
{ "AcceptedAnswerId": "224915", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T06:04:31.697", "Id": "224861", "Score": "1", "Tags": [ "javascript", "performance" ], "Title": "Create a new object that excludes specified keys" }
224861
<p>There are exactly ten ways of selecting three from five, 12345:</p> <p>123, 124, 125, 134, 135, 145, 234, 235, 245, and 345</p> <p>In combinatorics, we use the notation, 5C3=10.</p> <p>In general, nCr = n! / r! (n−r)!, where r≤n, n! = n × (n−1) × ... × 3 × 2 × 1, and 0! = 1.</p> <p>It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066.</p> <p>How many, not necessarily distinct, values of nCr for 1≤n≤100, are greater than one-million?</p> <pre><code>from time import time from math import factorial def combinations(n, r): """Assumes n, r a set of numbers and r number of numbers to choose from n. returns number of combinations.""" return factorial(n) // (factorial(r) * factorial(n - r)) def generate_combinations(n_range, minimum): """generates non-distinct combinations in range n_range inclusive that exceed the minimum.""" for n in range(1, n_range + 1): for r in range(1, n): combination = combinations(n, r) if combination &gt; minimum: yield 1 if __name__ == '__main__': START_TIME = time() print(sum(generate_combinations(100, 10**6))) print(f'Time: {time() - START_TIME} seconds.') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T07:03:48.853", "Id": "436288", "Score": "1", "body": "Project Euler problems are typically part coding and part thinking through the constraints of the problem, which can save a lot of compute time. For example, nCr has a consistent shape with a symmetry to it. I would suggest looking at whether you can use that shape to predict which runs of numbers are all high or all low." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T07:37:28.117", "Id": "436294", "Score": "1", "body": "I assume that you successfully solved PE#53? Did you have a look at the “overview for problem 53” document? 13 pages full of performance tips." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T07:39:02.623", "Id": "436295", "Score": "0", "body": "@ Martin No not really, can you post a link or something?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T07:39:49.217", "Id": "436296", "Score": "0", "body": "The link is at the bottom of https://projecteuler.net/problem=53. It becomes visible as soon as you submit a correct solution. There is also a link to a discussion thread where you can see how other people solved the problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T07:41:33.427", "Id": "436298", "Score": "0", "body": "i'll check it, thanks" } ]
[ { "body": "<p>just a little hack if you want a more fast solution,\ncan become faster if consider the similarity of the nCr and nC(n-r)</p>\n\n<pre><code>dic=[1]\n\nfor i in range(1,101):\n val =dic[-1]*i\n dic.append(val)\n\n\ndef choose(n,r):\n sol = dic[n]//(dic[n-r]*dic[r])\n return sol\n\ndef func(maxi, valu): \n count = 0\n for i in range(2,maxi+1):\n for j in range(1,i+1):\n val = choose(i,j)\n if val&gt;valu:\n count+=1 \n return count\n\n\nif __name__ == '__main__':\n from time import time\n START_TIME = time()\n print(func(100, 10**6))\n print(f'Time: {time() - START_TIME} seconds.')\n</code></pre>\n\n<p>just store all the value of factorial of a number upto 100 in dict and then process</p>\n\n<p>update suggested by @AJNeufeld , using list to store data than dictonary</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T05:36:11.263", "Id": "436458", "Score": "1", "body": "Only the last value of list `l` is ever used, so this list could be replaced by a scalar variable. Ie) `val = 1` outside the for-loop, and `val *= i` inside the for-loop. Why waste time with a dictionary, when list indexing is way faster? And `dic` is a meaningless name; how about `factorial` instead? `val = 1; factorial = [1]; for i in range(1, 101): val *= i; factorial.append(val)`. But this is still the wrong approach if you want speed, which you do since you are going through the effort of timing the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T06:13:26.273", "Id": "436463", "Score": "0", "body": "you are right, using list will do it faster, then adding the dictionary? if this is wrong approach, then how do we speed it more fast ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-14T14:00:20.783", "Id": "525493", "Score": "0", "body": "`func` is also a lousy name. You can go from an O(n^2) algorithm to an O(n) algorithm by starting at C(100,0) and incrementing `r`; if you exceed 1e6, decrement `n`. You only need to keep track of the boundary between the greater than 1e6 values and the less than 1e6 values." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T13:35:52.347", "Id": "224893", "ParentId": "224862", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T06:14:31.800", "Id": "224862", "Score": "4", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge" ], "Title": "Project Euler # 53 Combinatoric selections in Python" }
224862
<p>Here is implementation for singly linkedlist. Any suggestions are most welcome</p> <pre><code>package linkedlist; import java.util.Scanner; public class linkedlist { private int size=0; private Node newNode,oldNode,firstNode,displayNode; public void createNode(String value) { if(size==0) { newNode=new Node(value,null); firstNode=newNode; size++; } else { oldNode=newNode; newNode=new Node(value,null); oldNode.setNextNode(newNode); size++; } } public void DisplayLinklist() { displayNode=firstNode; while(true) { System.out.println(displayNode.getItem()); displayNode=displayNode.next; if(displayNode.next==null) { System.out.println(displayNode.getItem()); break; } } } private class Node{ private String item; private Node next; Node(String item,Node next){ this.item=item; this.next=next; } public String getItem() { return this.item; } public void setNextNode(Node address) { this.next=address; } } public static void main(String[] args) { linkedlist mylinklist=new linkedlist(); Scanner in=new Scanner(System.in); System.out.println("Enter the string value you want to save or press 'n'"); String input=in.next(); while(!input.equalsIgnoreCase("n")) { mylinklist.createNode(input); System.out.println("Enter the string value you want to save or press 'n'"); input=in.next(); } mylinklist.DisplayLinklist(); } } </code></pre> <p>This is very basic version and first time I am doing <code>Linkedlist</code>. I am not using any iteration, but just wanted to confirm am I on the right path?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T08:37:34.583", "Id": "436310", "Score": "0", "body": "You should have called it _very basic_ instead of .. :p Are you planning a follow-up with full implementation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T09:09:54.353", "Id": "436486", "Score": "0", "body": "yes @dfhwze.. i am learning datastructures so was trying it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T10:38:28.443", "Id": "436501", "Score": "1", "body": "Here is an interesting link about what Linus Torvalds considers \"good taste\" code. He uses a linked-list as example to show, how to improve your code, so it is more clean. You may also be interested in the slashdot article/comments linked in the blog article. https://grisha.org/blog/2013/04/02/linus-on-understanding-pointers/" } ]
[ { "body": "<p>You can have following changes:</p>\n\n<ol>\n<li>createNode\nsize++ done outside of if..else..</li>\n<li>In Node constructor if param next is always null then no need of this param.</li>\n<li>class and method name should be in camelcase as per java convention.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T07:48:35.487", "Id": "224872", "ParentId": "224871", "Score": "7" } }, { "body": "<ul>\n<li><code>size++</code> should be extracted from both branches and called only once</li>\n<li>there is no need to cache instance variables where local method variables should be used instead: <code>newNode,oldNode,displayNode</code></li>\n<li>prefer <code>while(currentNode != null)</code> over <code>while(true)</code> and <code>currentNode</code> should start with <code>firstNode</code> and be chained inside the while-loop as <code>currentNode = currentNode.next</code></li>\n<li>you should also provide <code>remove</code> and iterator functionality</li>\n<li><code>DisplayLinklist</code> should not be inside this class and it should be camel cased</li>\n<li>variable <code>firstNode</code> is usually called <code>head</code></li>\n<li>class <code>linkedlist</code> should be called <code>LinkedList</code></li>\n<li>get rid of unwanted blank lines</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T07:57:51.187", "Id": "224873", "ParentId": "224871", "Score": "13" } }, { "body": "<p>I can add that instead of <code>DisplayLinklist()</code> you should override <code>toString()</code> that returns a <code>String</code> representation of the linked list. then the caller can decide where and how to display this <code>String</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T12:32:24.853", "Id": "224889", "ParentId": "224871", "Score": "8" } }, { "body": "<p>This isn't the <em>really</em> basic linked list. For the <em>most</em> basic way of doing linked lists, you would get rid of <code>class linkedlist</code> entirely, and have <code>class Node</code> be the entire implementation. You need both getters and setters for both <code>item</code> and <code>next</code>, and those four plus the constructor are really the only primitive operations there are. Every other list operation is an algorithm built on those 5 primitives.</p>\n\n<p>It sounds like what you're trying to do is an exercise in stripping the idea of linked lists down to its essence. To do that, you need to wrap your head around the fact that there's no difference between having \"a list\" and having \"the node at the head of a list\"; each node <em>is</em> a list; and a list is nothing but the nodes and items that make it up.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T18:58:43.890", "Id": "224923", "ParentId": "224871", "Score": "6" } } ]
{ "AcceptedAnswerId": "224873", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T07:36:28.150", "Id": "224871", "Score": "8", "Tags": [ "java", "linked-list", "reinventing-the-wheel" ], "Title": "Very basic singly linked list" }
224871
<p>May be my question is not up to the standard for Code Review, but of upmost importance for reassessing methods used in my VBA coding . While preparing/testing answer for a SO post (thought to simplest of simplest questions) <a href="https://stackoverflow.com/questions/57191875/vba-cell-format-that-contain-a-specific-percentage-value">VBA cell format that contain a specific percentage value</a>, I came to a jolt that shaken whatever little confidence I had in VBA. </p> <p>I found that OP had looped more than once in the cells of Range in question and used to select each cell and test its value and then format border of the cell with desired parameters. As a thumb rule to minimize interaction with excel cell and to avoid select etc, I simply planned for go for each cell iteration of the range and test the values and according to make a union range object and finally format that range in a single go. </p> <p><em>Actually I am ashamed about the code and don’t want to reproduce it here and only concerned about the methods suitable for this type of operation. However since code review rule calls for at least 3 lines of code I am forced to paste (the never going to be finished) code here and request to ignore completely.</em> </p> <pre><code>Sub test() Dim lr As Long Dim c As Range, Rng As Range, Grt100Rng As Range, Less0Rng As Range lr = Range("G" &amp; Rows.Count).End(xlUp).Row Set Rng = Range("G3:G" &amp; lr) Dim tm As Double tm = Timer For Each c In Rng If c &gt;= 1 Then If Grt100Rng Is Nothing Then Set Grt100Rng = c Else Set Grt100Rng = Union(Grt100Rng, c) End If End If If c &lt;= 0 Then If Less0Rng Is Nothing Then Set Less0Rng = c Else Set Less0Rng = Union(Less0Rng, c) End If End If Next Debug.Print "Union at :" &amp; Timer - tm If Not Grt100Rng Is Nothing Then With Grt100Rng.Borders If GreaterThan100.Value Then .Color = vbBlue .LineStyle = xlContinuous .Weight = xlThick Else .Color = vbBlack .LineStyle = xlNone .Weight = xlThin End If End With With Less0Rng.Borders If LessThan0.Value Then .Color = vbBlue .LineStyle = xlContinuous .Weight = xlThick Else .Color = vbBlack .LineStyle = xlNone .Weight = xlThin End If End With End If Debug.Print Timer - tm End Sub </code></pre> <p>Similar working approach already tried successfully in my SO answer referred below. But this time, the above code cruelly backfired on me and taken around 80 sec for processing 10 k rows.</p> <p>Testing the values of the range from a 2D Array taken in single command ( <code>Arr=Rng.value</code>) from the range object and tried to create union range from the array row address took nearly same amount of time. When tested the OP code found it takes only 12-14 sec to process with screen updating on and 1.2 sec with screen updating off. </p> <p>I refrain from answering the post leaving comments to help OP to create Conditional format. I somehow realized (or rather conceptualize ) reading and formatting cells would be faster than creating union range and union range would only prove better option when writing cells, </p> <p>I started testing on new Range of 10-50 K rows various option to find optimized condition when creating Union range would be efficient over brute force looping and formatting cell. At testing of 10 K rows I start finding union method is being far less efficient than brute force looping. At 50 K it never finished the process. </p> <p>As the testes are being time consuming I thought of asking for experts opinion in Code Review and get what would be the optimized scenario for creating using union range for conditional formatting (in VBA) over brute force looping and formatting.</p> <p>In this context, I must refer to my answer in SO post <a href="https://stackoverflow.com/questions/55543789/is-it-possible-to-speed-up-background-text-border-formatting/55554509#55554509">Is it possible to speed-up background / text / border formatting?</a>. In this case, Union Range method reduced process time to a odd second from around 30 minutes.</p> <p>If auto filtering and creating range of <code>SpecialCells(xlCellTypeVisible)</code> is a solution, that also proved to raise error 1004 "Ms excel cannot create or use data range reference because too complex” at around range of 150 K rows. Tried and failed at <a href="https://stackoverflow.com/questions/56878950/most-efficient-vba-method-to-copy-data-from-one-sheet-to-another#comment100309150_56878950">SO Post</a>. What is the limitation of Union range?</p> <p>It made my confidence shaken. May some experts please clarify, If union range method is always less efficient, why this above referred answer brought down the time to a odd second from around 30 minutes. Any explanation,advice, good reading or information on the matter would be a bonanza.</p> <p><strong>Edit</strong>: I want to share the result of simple tests carried out today to test limit of creating range of <code>SpecialCells(xlCellTypeVisible)</code>. To keep the original post length readable, I am deleting this section and posting it as answer.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T20:54:31.027", "Id": "436433", "Score": "0", "body": "There are a variety of resources to review limitations of the `UNION` function. It looks like the post on SO was possibly based on [this site](https://wellsr.com/vba/2019/excel/use-vba-union-to-combine-ranges/), and it's instructive to review the limitations lower down on that page. Also, Craig Pearson has an [excellent updated `ProperUnion` function](http://www.cpearson.com/excel/BetterUnion.aspx) that addresses many of the limitations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T20:56:06.730", "Id": "436434", "Score": "0", "body": "[This Excel reference page](https://support.office.com/en-us/article/excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3?ocmsassetID=HP010073849&CorrelationId=59261642-3774-4d85-b4cd-19da42c5d3df&ui=en-US&rs=en-US&ad=US#BMcalculation) implies that the `Union` limit ***may*** be 2,147,483,648 cells (see \"Noncontiguous cells that can be selected\"). But I'm not convinced that is the correct number. In any case, I completely agree with the other answers on SO that the correct approach is conditional formatting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T23:39:50.243", "Id": "436446", "Score": "0", "body": "@PeterT, Many Thanks for going through the tiring question and prompt response. I wll go through all the links and come back." } ]
[ { "body": "<p>I want to share the result of simple tests carried out today to test limit of creating range of <code>SpecialCells(xlCellTypeVisible)</code>. Only to keep the original post length readable, I am posting it as answer.</p>\n\n<p>I filled the range A2:A150001 with 1 n number of times (each area length) with one 0 cell and filtered for 1 with code. </p>\n\n<pre><code>Sub FillRange()\nDim Arr(1 To 150000, 1 To 1), Rw As Long, xInt As Integer, AreaLen As Integer, Cnt As Integer\nAreaLen = InputBox(\"Enter Each area Length\", , 3)\nCnt = 0\n For Rw = 1 To 150000\n If Cnt &gt; AreaLen - 1 Then\n Cnt = 0\n xInt = 0\n Else\n Cnt = Cnt + 1\n xInt = 1\n End If\n Arr(Rw, 1) = xInt\n Next\nRange(\"A2:A150001\").Value = Arr\nActiveSheet.Range(\"$A$1:$A$150001\").AutoFilter Field:=1, Criteria1:=\"1\"\nEnd Sub\n</code></pre>\n\n<p>And then used the following code in step of 1k to creating range of <code>SpecialCells(xlCellTypeVisible)</code>\nand find where error 1004 creeps in</p>\n\n<pre><code>Sub TestSpecialCellRange()\nDim Rw As Long, Rng As Range\n For Rw = 1000 To 150000 Step 1000\n Set Rng = Nothing\n On Error Resume Next\n Set Rng = Range(\"A2:A\" &amp; Rw).SpecialCells(xlCellTypeVisible)\n If Err &lt;&gt; 0 Then\n Debug.Print \"Error at \" &amp; Rw &amp; \" Error No \" &amp; Err.Number &amp; \" : \" &amp; Err.Description\n Err.Clear\n On Error GoTo 0\n Exit For\n Else\n Debug.Print \"Success at \" &amp; Rw &amp; \" Range Area Count \" &amp; Rng.Areas.Count\n End If\n Next\nEnd Sub\n</code></pre>\n\n<p>Following are the result of debug window</p>\n\n<pre><code>At area length 1\nSuccess at 15000 Range Area Count 7500\nSuccess at 16000 Range Area Count 8000\nError at 17000 Error No 1004 : Microsoft Office Excel cannot create or use the data range reference because it is too complex. Try one or more of the following:\n• Use data that can be selected in one contiguous rectangle.\n• Use data from the same sheet.\n\nAt area length 2\nSuccess at 23000 Range Area Count 7667\nSuccess at 24000 Range Area Count 8000\nError at 25000 Error No 1004 : Microsoft Office Excel cannot create or use the data range reference \n\nAt area length 3\nSuccess at 32000 Range Area Count 8000\nError at 33000 Error No 1004 : Microsoft Office Excel cannot create or use the data range reference because it is too complex. Try one or more of the following:\n\nAt area length 4\nSuccess at 48000 Range Area Count 8000\nSuccess at 49000 Range Area Count 8167\nError at 50000 Error No 1004 : Microsoft Office Excel cannot create or use the data range reference \n\n\nAt area length 10\nSuccess at 88000 Range Area Count 8000\nSuccess at 89000 Range Area Count 8091\nSuccess at 90000 Range Area Count 8182\nError at 91000 Error No 1004 : Microsoft Office Excel cannot create or use the data range reference \n\nFinally at area length 19 I succeed to cover 150 K\nSuccess at 149000 Range Area Count 7096\nSuccess at 150000 Range Area Count 7143\n</code></pre>\n\n<p>So it may be concluded that <strong>irrespective of number of rows covered, at around 8k non contagious area of the range, the error 1004 creeps in</strong>. I also tried with covering columns of the range 1 to 5 it is always same. however this is in my old good laptop with excel 2007 only, don't know what high performance machines result would be. </p>\n\n<p><strong>Edit:</strong> Next while <strong>testing iterating <code>For each Cell in Range</code> and adding to Union range</strong> (If condition meets) with simple code like</p>\n\n<pre><code>Set Rng = Range(\"A1\") ' To avoid testing \"if Rng is nothing\" at each row\n For Each Cel In Range(\"A2:A150000\")\n Rw = Cel.Row\n If Cel.Value = 1 Then\n Set Rng = Union(Rng, Cel)\n End If\n If Rw Mod 1000 = 0 Then\n AreaCnt = Rng.Areas.Count\n Debug.Print \" Row: \" &amp; Rw &amp; \" Range Area Count : \" &amp; AreaCnt &amp; \" at \" &amp; Timer - tm\n DoEvents\n End If\n Next\n</code></pre>\n\n<p>The results shown normal behavior of union method. The time taken to process 1000 number of rows increases as the range grows heavy with non contiguous areas. Time to process 1 K cell increases to around 60 sec (at start it is 0.125 sec only) when range area count grows around 1000. Unable to achieve my target of 150 K rows with 75 K non contiguous area.</p>\n\n<p>I tweak my code to utilize 30 parameter limit of Union syntax with range array. Encouraged by improvement in performance, I further tweak the code to utilize second level of union with range array with further plan to increase level to optimize performance.</p>\n\n<pre><code>Sub CellUnion3()\nDim Rw As Long, Rng(1 To 30) As Range, AreaCnt As Long, Arr(1 To 150001) As Variant\nDim Cel As Range, Rslt(1 To 30) As Range, FinalRslt As Range\nDim tm As Double, Cnt As Long, Cnt2 As Long\n\nSet FinalRslt = Range(\"A1\") ' to avoid testing if Rng is nothing at each row\nCnt = 0\nCnt2 = 0\ntm = Timer\nSecCnt = 0\n\n For Each Cel In Range(\"A2:A150000\")\n\n If Cel.Value = 1 Then\n Cnt = Cnt + 1\n Rw = Cel.Row\n\n If Cnt &lt;= 30 Then\n Set Rng(Cnt) = Cel\n End If\n\n If Cnt = 30 Then\n Cnt = 0\n Cnt2 = Cnt2 + 1\n Set Rslt(Cnt2) = Union(Rng(1), Rng(2), Rng(3), Rng(4), Rng(5), Rng(6), Rng(7), Rng(8), Rng(9), Rng(10), _\n Rng(11), Rng(12), Rng(13), Rng(14), Rng(15), Rng(16), Rng(17), Rng(18), Rng(19), Rng(20), _\n Rng(21), Rng(22), Rng(23), Rng(24), Rng(25), Rng(26), Rng(27), Rng(28), Rng(29), Rng(30))\n If Cnt2 = 29 Then\n Cnt2 = 0\n On Error Resume Next\n Set FinalRslt = Union(FinalRslt, Rslt(1), Rslt(2), Rslt(3), Rslt(4), Rslt(5), Rslt(6), Rslt(7), Rslt(8), Rslt(9), Rslt(10), _\n Rslt(11), Rslt(12), Rslt(13), Rslt(14), Rslt(15), Rslt(16), Rslt(17), Rslt(18), Rslt(19), Rslt(20), _\n Rslt(21), Rslt(22), Rslt(23), Rslt(24), Rslt(25), Rslt(26), Rslt(27), Rslt(28), Rslt(29))\n If Err &lt;&gt; 0 Then\n Debug.Print \" Row: \" &amp; Rw &amp; \" at \" &amp; Timer - tm &amp; \" Error: \" &amp; Err.Number &amp; vbCrLf &amp; Err.Description\n Err.Clear\n On Error GoTo 0\n Exit For\n Else\n Debug.Print \" Row: \" &amp; Rw &amp; \" at \"; Timer - tm\n End If\n End If\n End If\n DoEvents\n End If\n Next\nAreaCnt = FinalRslt.Areas.Count\nDebug.Print \"Completed at \" &amp; Timer - tm &amp; \" Row: \" &amp; Rw &amp; \" Range Area Count: \" &amp; AreaCnt\nEnd Sub\n</code></pre>\n\n<p><em>The code still lacks final touches to complete union at end (if end of range reaches between accumulating 30 range array) but ignored as it is only for test purpose</em></p>\n\n<p>Few extracts of the debug log</p>\n\n<pre><code>With contiguous area length 1 separated by 1 row \nRow: 129920 at 289.71875 \nRow: 131080 at 289.765625 Error: 1004\nMethod 'Union' of object '_Global' failed\nCompleted at 289.78125 Row: 131080 Range Area Count: 32480\n\nWith contiguous area length 3 separated by 1 row \nRow: 129920 at 307.8359375 \n Row: 131080 at 307.8984375 Error: 1004\nMethod 'Union' of object '_Global' failed\nCompleted at 307.9140625 Row: 131080 Range Area Count: 32480\n\nWith contiguous area length 5 separated by 1 row, it completed 150k Row\nRow: 147204 at 236.8046875 \nRow: 148248 at 242.71875 \nRow: 149292 at 248.2109375 \nCompleted at 248.2734375 Row: 150000 Range Area Count: 24882\n</code></pre>\n\n<p>With the test results, <strong>is it to conclude that Microsoft union method is incapable of creating an union range with non contiguous area count more than 32 K?</strong></p>\n\n<p>Of course both the methods of creating range from <code>SpecialCells</code>, union and Array range can be combined and or tweaked to many simple workarounds. But the final question is </p>\n\n<p>Are we really bound by 8K non contiguous area count limitation of creating range from <code>SpecialCells</code> and 32 K non contiguous area count limitation of union Range?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T02:18:52.027", "Id": "224937", "ParentId": "224874", "Score": "0" } }, { "body": "<p>I am not saying how this is going to help, but I did the Same test on My system (Office 2010) couldn't find 2007.</p>\n\n<p>So for the Test of the Range <code>SpecialCells(xlCellTypeVisible)</code>, it took less than a second in my system to complete the Range as in your Answer using the same code on a Blank sheet.</p>\n\n<p><a href=\"https://i.stack.imgur.com/JWnng.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JWnng.gif\" alt=\"enter image description here\"></a></p>\n\n<p>Result in Debug.</p>\n\n<pre><code>Success at 1000 Range Area Count 250\nSuccess at 2000 Range Area Count 500\nSuccess at 3000 Range Area Count 750\nSuccess at 4000 Range Area Count 1000\nSuccess at 5000 Range Area Count 1250\nSuccess at 6000 Range Area Count 1500\nSuccess at 7000 Range Area Count 1750\nSuccess at 8000 Range Area Count 2000\nSuccess at 9000 Range Area Count 2250\nSuccess at 10000 Range Area Count 2500\nSuccess at 11000 Range Area Count 2750\nSuccess at 12000 Range Area Count 3000\nSuccess at 13000 Range Area Count 3250\nSuccess at 14000 Range Area Count 3500\nSuccess at 15000 Range Area Count 3750\nSuccess at 16000 Range Area Count 4000\nSuccess at 17000 Range Area Count 4250\nSuccess at 18000 Range Area Count 4500\nSuccess at 19000 Range Area Count 4750\nSuccess at 20000 Range Area Count 5000\nSuccess at 21000 Range Area Count 5250\nSuccess at 22000 Range Area Count 5500\nSuccess at 23000 Range Area Count 5750\nSuccess at 24000 Range Area Count 6000\nSuccess at 25000 Range Area Count 6250\nSuccess at 26000 Range Area Count 6500\nSuccess at 27000 Range Area Count 6750\nSuccess at 28000 Range Area Count 7000\nSuccess at 29000 Range Area Count 7250\nSuccess at 30000 Range Area Count 7500\nSuccess at 31000 Range Area Count 7750\nSuccess at 32000 Range Area Count 8000\nSuccess at 33000 Range Area Count 8250\nSuccess at 34000 Range Area Count 8500\nSuccess at 35000 Range Area Count 8750\nSuccess at 36000 Range Area Count 9000\nSuccess at 37000 Range Area Count 9250\nSuccess at 38000 Range Area Count 9500\nSuccess at 39000 Range Area Count 9750\nSuccess at 40000 Range Area Count 10000\nSuccess at 41000 Range Area Count 10250\nSuccess at 42000 Range Area Count 10500\nSuccess at 43000 Range Area Count 10750\nSuccess at 44000 Range Area Count 11000\nSuccess at 45000 Range Area Count 11250\nSuccess at 46000 Range Area Count 11500\nSuccess at 47000 Range Area Count 11750\nSuccess at 48000 Range Area Count 12000\nSuccess at 49000 Range Area Count 12250\nSuccess at 50000 Range Area Count 12500\nSuccess at 51000 Range Area Count 12750\nSuccess at 52000 Range Area Count 13000\nSuccess at 53000 Range Area Count 13250\nSuccess at 54000 Range Area Count 13500\nSuccess at 55000 Range Area Count 13750\nSuccess at 56000 Range Area Count 14000\nSuccess at 57000 Range Area Count 14250\nSuccess at 58000 Range Area Count 14500\nSuccess at 59000 Range Area Count 14750\nSuccess at 60000 Range Area Count 15000\nSuccess at 61000 Range Area Count 15250\nSuccess at 62000 Range Area Count 15500\nSuccess at 63000 Range Area Count 15750\nSuccess at 64000 Range Area Count 16000\nSuccess at 65000 Range Area Count 16250\nSuccess at 66000 Range Area Count 16500\nSuccess at 67000 Range Area Count 16750\nSuccess at 68000 Range Area Count 17000\nSuccess at 69000 Range Area Count 17250\nSuccess at 70000 Range Area Count 17500\nSuccess at 71000 Range Area Count 17750\nSuccess at 72000 Range Area Count 18000\nSuccess at 73000 Range Area Count 18250\nSuccess at 74000 Range Area Count 18500\nSuccess at 75000 Range Area Count 18750\nSuccess at 76000 Range Area Count 19000\nSuccess at 77000 Range Area Count 19250\nSuccess at 78000 Range Area Count 19500\nSuccess at 79000 Range Area Count 19750\nSuccess at 80000 Range Area Count 20000\nSuccess at 81000 Range Area Count 20250\nSuccess at 82000 Range Area Count 20500\nSuccess at 83000 Range Area Count 20750\nSuccess at 84000 Range Area Count 21000\nSuccess at 85000 Range Area Count 21250\nSuccess at 86000 Range Area Count 21500\nSuccess at 87000 Range Area Count 21750\nSuccess at 88000 Range Area Count 22000\nSuccess at 89000 Range Area Count 22250\nSuccess at 90000 Range Area Count 22500\nSuccess at 91000 Range Area Count 22750\nSuccess at 92000 Range Area Count 23000\nSuccess at 93000 Range Area Count 23250\nSuccess at 94000 Range Area Count 23500\nSuccess at 95000 Range Area Count 23750\nSuccess at 96000 Range Area Count 24000\nSuccess at 97000 Range Area Count 24250\nSuccess at 98000 Range Area Count 24500\nSuccess at 99000 Range Area Count 24750\nSuccess at 100000 Range Area Count 25000\nSuccess at 101000 Range Area Count 25250\nSuccess at 102000 Range Area Count 25500\nSuccess at 103000 Range Area Count 25750\nSuccess at 104000 Range Area Count 26000\nSuccess at 105000 Range Area Count 26250\nSuccess at 106000 Range Area Count 26500\nSuccess at 107000 Range Area Count 26750\nSuccess at 108000 Range Area Count 27000\nSuccess at 109000 Range Area Count 27250\nSuccess at 110000 Range Area Count 27500\nSuccess at 111000 Range Area Count 27750\nSuccess at 112000 Range Area Count 28000\nSuccess at 113000 Range Area Count 28250\nSuccess at 114000 Range Area Count 28500\nSuccess at 115000 Range Area Count 28750\nSuccess at 116000 Range Area Count 29000\nSuccess at 117000 Range Area Count 29250\nSuccess at 118000 Range Area Count 29500\nSuccess at 119000 Range Area Count 29750\nSuccess at 120000 Range Area Count 30000\nSuccess at 121000 Range Area Count 30250\nSuccess at 122000 Range Area Count 30500\nSuccess at 123000 Range Area Count 30750\nSuccess at 124000 Range Area Count 31000\nSuccess at 125000 Range Area Count 31250\nSuccess at 126000 Range Area Count 31500\nSuccess at 127000 Range Area Count 31750\nSuccess at 128000 Range Area Count 32000\nSuccess at 129000 Range Area Count 32250\nSuccess at 130000 Range Area Count 32500\nSuccess at 131000 Range Area Count 32750\nSuccess at 132000 Range Area Count 33000\nSuccess at 133000 Range Area Count 33250\nSuccess at 134000 Range Area Count 33500\nSuccess at 135000 Range Area Count 33750\nSuccess at 136000 Range Area Count 34000\nSuccess at 137000 Range Area Count 34250\nSuccess at 138000 Range Area Count 34500\nSuccess at 139000 Range Area Count 34750\nSuccess at 140000 Range Area Count 35000\nSuccess at 141000 Range Area Count 35250\nSuccess at 142000 Range Area Count 35500\nSuccess at 143000 Range Area Count 35750\nSuccess at 144000 Range Area Count 36000\nSuccess at 145000 Range Area Count 36250\nSuccess at 146000 Range Area Count 36500\nSuccess at 147000 Range Area Count 36750\nSuccess at 148000 Range Area Count 37000\nSuccess at 149000 Range Area Count 37250\nSuccess at 150000 Range Area Count 37500\n</code></pre>\n\n<p>For Next Loop, it was taking way long, as you said increasing with every loop, in<code>For Each Cel in Range</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T00:27:13.780", "Id": "437961", "Score": "0", "body": "Thanks for taking interest. The `SpecialCells` limit is [fixed in 2010](https://www.rondebruin.nl/win/s4/win003.htm). Could you please feedback about 32K limit of Union Range." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T21:53:47.057", "Id": "225548", "ParentId": "224874", "Score": "1" } }, { "body": "<h2>75K Non-Contiguous Areas, No Problem</h2>\n<p>My <strong>FastUnion</strong> class was able to crack the 75K non-contiguous areas goal by expanding on Ahmed AU answer using <code>Union()</code> with multiple parameters. Although, this class excels at smaller numbers of areas, my <strong>UnionCollection</strong> class far out performs it by working with smaller groups of cells at a time.</p>\n<p><a href=\"https://i.stack.imgur.com/K6U9E.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/K6U9E.png\" alt=\"enter image description here\" /></a></p>\n<h2>Results</h2>\n<p>Immediate Window ScreenShot</p>\n<h2>FastUnion:Class</h2>\n<pre><code>Option Explicit\nPrivate Const MaxArgs As Long = 30\nPrivate Groups(1 To MaxArgs) As Range\nPrivate Index As Long\nPrivate Count As Long\nPrivate Compacted As Boolean\n\nPublic Sub Add(ByRef NewRange As Range)\n If Count &lt; MaxArgs Then Count = Count + 1\n Index = Index + 1\n If Index &gt; MaxArgs Then Index = IIf(Compacted, 2, 1)\n If Groups(Index) Is Nothing Then\n Set Groups(Index) = NewRange\n Else\n Set Groups(Index) = Union(Groups(Index), NewRange)\n End If\nEnd Sub\n\nPrivate Sub Compact()\n Select Case Count\n Case 2\n Set Groups(1) = Union(Groups(1), Groups(2))\n Case 3\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3))\n Case 4\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4))\n Case 5\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5))\n Case 6\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6))\n Case 7\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7))\n Case 8\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8))\n Case 9\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9))\n Case 10\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10))\n Case 11\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11))\n Case 12\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11), Groups(12))\n Case 13\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11), Groups(12), Groups(13))\n Case 14\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11), Groups(12), Groups(13), Groups(14))\n Case 15\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11), Groups(12), Groups(13), Groups(14), Groups(15))\n Case 16\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11), Groups(12), Groups(13), Groups(14), Groups(15), Groups(16))\n Case 17\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11), Groups(12), Groups(13), Groups(14), Groups(15), Groups(16), Groups(17))\n Case 18\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11), Groups(12), Groups(13), Groups(14), Groups(15), Groups(16), Groups(17), Groups(18))\n Case 19\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11), Groups(12), Groups(13), Groups(14), Groups(15), Groups(16), Groups(17), Groups(18), Groups(19))\n Case 20\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11), Groups(12), Groups(13), Groups(14), Groups(15), Groups(16), Groups(17), Groups(18), Groups(19), Groups(20))\n Case 21\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11), Groups(12), Groups(13), Groups(14), Groups(15), Groups(16), Groups(17), Groups(18), Groups(19), Groups(20), Groups(21))\n Case 22\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11), Groups(12), Groups(13), Groups(14), Groups(15), Groups(16), Groups(17), Groups(18), Groups(19), Groups(20), Groups(21), Groups(22))\n Case 23\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11), Groups(12), Groups(13), Groups(14), Groups(15), Groups(16), Groups(17), Groups(18), Groups(19), Groups(20), Groups(21), Groups(22), Groups(23))\n Case 24\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11), Groups(12), Groups(13), Groups(14), Groups(15), Groups(16), Groups(17), Groups(18), Groups(19), Groups(20), Groups(21), Groups(22), Groups(23), Groups(24))\n Case 25\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11), Groups(12), Groups(13), Groups(14), Groups(15), Groups(16), Groups(17), Groups(18), Groups(19), Groups(20), Groups(21), Groups(22), Groups(23), Groups(24), Groups(25))\n Case 26\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11), Groups(12), Groups(13), Groups(14), Groups(15), Groups(16), Groups(17), Groups(18), Groups(19), Groups(20), Groups(21), Groups(22), Groups(23), Groups(24), Groups(25), Groups(26))\n Case 27\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11), Groups(12), Groups(13), Groups(14), Groups(15), Groups(16), Groups(17), Groups(18), Groups(19), Groups(20), Groups(21), Groups(22), Groups(23), Groups(24), Groups(25), Groups(26), Groups(27))\n Case 28\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11), Groups(12), Groups(13), Groups(14), Groups(15), Groups(16), Groups(17), Groups(18), Groups(19), Groups(20), Groups(21), Groups(22), Groups(23), Groups(24), Groups(25), Groups(26), Groups(27), Groups(28))\n Case 29\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11), Groups(12), Groups(13), Groups(14), Groups(15), Groups(16), Groups(17), Groups(18), Groups(19), Groups(20), Groups(21), Groups(22), Groups(23), Groups(24), Groups(25), Groups(26), Groups(27), Groups(28), Groups(29))\n Case 30\n Set Groups(1) = Union(Groups(1), Groups(2), Groups(3), Groups(4), Groups(5), Groups(6), Groups(7), Groups(8), Groups(9), Groups(10), Groups(11), Groups(12), Groups(13), Groups(14), Groups(15), Groups(16), Groups(17), Groups(18), Groups(19), Groups(20), Groups(21), Groups(22), Groups(23), Groups(24), Groups(25), Groups(26), Groups(27), Groups(28), Groups(29), Groups(30))\n End Select\n \n Dim n As Long\n For n = 2 To MaxArgs\n Set Groups(n) = Nothing\n Next\n Index = 2\n Compacted = True\n Count = 0\n \nEnd Sub\n\nPublic Function getRange() As Range\n Compact\n Set getRange = Groups(1)\nEnd Function\n</code></pre>\n<h2>UnionCollection:Class</h2>\n<p>The Default number of cells in a group is set to 500 which may not be optimal. The optimal group size could be determined by testing different values for the <code>CellCountGoal</code>.</p>\n<pre><code>Option Explicit\nPrivate Const DefaultCellCountGoal As Long = 500\nPrivate RangeItems As New Collection\nPrivate item As Range\nPublic CellCountGoal As Long\n\nPublic Sub Add(ByRef NewRange As Range)\n If item Is Nothing Then\n Set item = NewRange\n Else\n Set item = Union(item, NewRange)\n End If\n \n If item.CountLarge &gt;= CellCountGoal Then Compact\n\nEnd Sub\n\nPrivate Sub Class_Initialize()\n CellCountGoal = DefaultCellCountGoal\nEnd Sub\n\nPublic Function Items() As Collection\n Compact\n Set Items = RangeItems\nEnd Function\n\nPrivate Sub Compact()\n If Not item Is Nothing Then\n RangeItems.Add item\n Set item = Nothing\n End If\nEnd Sub\n</code></pre>\n<h2>Module1</h2>\n<pre><code>Option Explicit\n\nSub TestFastUnion()\n Application.ScreenUpdating = False\n Debug.Print &quot;TestFastUnionRange Results:&quot;\n Debug.Print &quot;Area Count&quot;, &quot;UnionTime&quot;, &quot;FormatTime&quot;, &quot;ProcTime&quot;\n\n TestFastUnionRange 1000, 2000, 3000, 5000, 10000, 75000\n \n Debug.Print\n Debug.Print &quot;TestUnionCollection Results:&quot;\n Debug.Print &quot;Area Count&quot;, &quot;UnionTime&quot;, &quot;FormatTime&quot;, &quot;ProcTime&quot;\n \n TestUnionCollection 1000, 2000, 3000, 5000, 10000, 75000\n \n \nEnd Sub\n\nSub TestFastUnionRange(ParamArray AreaCounts() As Variant)\n Dim AllCells As Range, Cell As Range\n Dim ProcTime As Double, FormatTime As Double, UnionTime As Double\n Dim NewUnion As FastUnion\n Dim AreaCount\n \n For Each AreaCount In AreaCounts\n Cells.ClearFormats\n Debug.Print AreaCount,\n ProcTime = Timer\n Set NewUnion = New FastUnion\n \n For Each Cell In Range(&quot;A1&quot;).Resize(AreaCount * 2)\n If Cell.Row Mod 2 = 0 Then NewUnion.Add Cell\n Next\n Set AllCells = NewUnion.getRange\n UnionTime = Round(Timer - ProcTime, 2)\n ApplyBorderFormmating AllCells, vbRed\n ProcTime = Round(Timer - ProcTime, 2)\n FormatTime = Round(ProcTime - UnionTime, 2)\n Debug.Print UnionTime, FormatTime, ProcTime\n Next\nEnd Sub\n\nSub TestUnionCollection(ParamArray AreaCounts() As Variant)\n Dim Cell As Range, item As Range\n Dim ProcTime As Double, FormatTime As Double, UnionTime As Double\n Dim NewUnion As UnionCollection\n Dim AreaCount\n \n For Each AreaCount In AreaCounts\n Cells.ClearFormats\n Debug.Print AreaCount,\n ProcTime = Timer\n Set NewUnion = New UnionCollection\n \n For Each Cell In Range(&quot;A1&quot;).Resize(AreaCount * 2)\n If Cell.Row Mod 2 = 0 Then NewUnion.Add Cell\n Next\n \n UnionTime = Round(Timer - ProcTime, 2)\n For Each item In NewUnion.Items\n ApplyBorderFormmating item, vbRed\n Next\n \n ProcTime = Round(Timer - ProcTime, 2)\n FormatTime = Round(ProcTime - UnionTime, 2)\n Debug.Print UnionTime, FormatTime, ProcTime\n Next\nEnd Sub\n\nSub ApplyBorderFormmating(Target As Range, Color As Single)\n With Target.Borders\n .Color = Color\n .LineStyle = xlContinuous\n .Weight = xlThick\n End With\nEnd Sub\n\nSub PrintCases()\n Dim list As Object\n Set list = CreateObject(&quot;System.Collections.ArrayList&quot;)\n Dim n As Long\n For n = 1 To 30\n list.Add &quot;Groups(&quot; &amp; n &amp; &quot;)&quot;\n Debug.Print String(2, vbTab); &quot;Case &quot;; n\n Debug.Print String(3, vbTab); &quot;Set AllCells = Union(&quot;; Join(list.ToArray, &quot;,&quot;); &quot;)&quot;\n Next\nEnd Sub\n</code></pre>\n<h2>Edit</h2>\n<p>I modified the <strong>FastUnion</strong> class after I realized it would reset the range after <code>Compact()</code> was ran.</p>\n<p>The OP pointed out I should list my specs.</p>\n<h1>System Specs</h1>\n<ul>\n<li>64 bit Office 365</li>\n<li>6 GB Ram</li>\n<li>2.3 MHz processor</li>\n</ul>\n<h2>Addendum</h2>\n<p>Here was my first attempt at cracking 75 K areas. It performed very well with smaller number of unions but started to slow down exponentially after 20 K unions. Although, it probably isn't practical, there may be some merit to combining it with the <strong>FastUnion</strong>. If nothing else it was interesting to write.</p>\n<h2>StingUnion:Class</h2>\n<pre><code>Option Explicit\nPrivate Const MaxAddressSize As Long = 255\nPrivate CurrentLength As Long\nPrivate Result As Range\nPrivate Parent As Worksheet\nPrivate AddressHolder As String\n\nPublic Sub Add(Source As Range)\n If Parent Is Nothing Then\n Set Parent = Source.Parent\n AddressHolder = Space(MaxAddressSize)\n End If\n \n Dim length As Long\n Dim Address As String\n Address = Source.Address(0, 0)\n length = Len(Address)\n \n If (length + CurrentLength) &gt; MaxAddressSize Then Compact\n \n If CurrentLength = 0 Then\n Mid(AddressHolder, CurrentLength + 1, length + 1) = Address\n Else\n Mid(AddressHolder, CurrentLength + 1, length + 1) = &quot;,&quot; &amp; Address\n End If\n CurrentLength = CurrentLength + length + 1\n \nEnd Sub\n\nPublic Sub Compact()\n If CurrentLength = 0 Then Exit Sub\n \n If Result Is Nothing Then\n Set Result = Parent.Range(AddressHolder)\n Else\n Set Result = Union(Result, Parent.Range(AddressHolder))\n End If\n \n CurrentLength = 0\n AddressHolder = Space(MaxAddressSize)\nEnd Sub\n\nFunction getRange() As Range\n Compact\n Set getRange = Result\nEnd Function\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T06:37:34.210", "Id": "439698", "Score": "0", "body": "First of all, Thanks for your valuable time spend on the post. I will go through it in details and come back. However at a glance, congratulate for brilliant maximum utilization of 32 argument property of Union rage into a class. +1 for that before going in details and please mention excel version used for readers . I will try it in 2007." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T10:35:36.257", "Id": "439710", "Score": "0", "body": "@AhmedAU Are you running 32 or 64 bit Office?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T12:01:30.270", "Id": "439722", "Score": "0", "body": "may treat me as Old School, still with 32 bit. Still not find time to test or study in details, may be delayed longer. Please bear .with me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T05:55:56.697", "Id": "439848", "Score": "0", "body": "the codes are like poetry and running them is like music from violin. I also created another class combining `FastUnoin` with `UnionCollenction`. After number of testing with varying conditions observed that in general Brute force Looping, Combined Fast loop_Collection method and Union_Collection method taking more or less same time (19s for 30K) for high Area counts.But final conclusion and salute to you, with ** `UnionCollenction` reducing `CellCountGoal` to 100 brought down `ProcTime` to 4.3 from 19 is the best performer in this context. **" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T05:58:18.660", "Id": "439849", "Score": "0", "body": "Another point the Combined Fast loop_Collection method gives best time of 0.18 (18.2 is formatting time only. for 30K with `CellCountGoal` of 100) for Creating range collection. This deemed fit for other application where creation of union range is absolute necessary. Finally again I have no word to thank you for wasting your valuable time on such boring topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T07:32:07.720", "Id": "439855", "Score": "0", "body": "@AhmedAU not boring at all. Thanks for the interesting topic and in depth analysis. I edited my post to include a third class. Although it that did not make the cut, it may prove useful." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T06:01:40.140", "Id": "226296", "ParentId": "224874", "Score": "4" } } ]
{ "AcceptedAnswerId": "226296", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T08:10:20.413", "Id": "224874", "Score": "4", "Tags": [ "vba", "excel" ], "Title": "Brute force looping & formatting Or Create Union range & Format? Which is efficient and when?" }
224874
<p>I was wondering what's the fastest method to compare similarity between two lists of strings (e.g. two dataframes, documents etc.) using levenshtein distance or other procedures.</p> <p>I am currently using:</p> <pre><code>def wuzzyfuzzy(df1, df2): myList = [] total = len(df1) for idx1, df1_str in enumerate(df1.col1): myDict = {} my_str = ('Progress : ' + str(round((idx1/total)*100,3))+'%') sys.stdout.write('\r' + str(my_str)) sys.stdout.flush() for idx2, df2_str in enumerate(df2.col1): s = SequenceMatcher(None, df1_str, df2_str) r = s.ratio() myDict.update({df2_str:r}) best_match = max(myDict, key=myDict.get) myList.append([df1_str, best_match, myDict[best_match]]) return myList </code></pre> <p>As the dataframes that are passed to the function have both > 30.000 values, it takes currently around <strong>6 hours</strong> to compare each value in df1 with all other values in df2 to find the best match.</p> <p>Of course I cleaned the strings as good as possible beforehand (all lowercase, get rid of punctuations etc.)</p> <p>What's the most efficient way to perfom such task?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T02:38:51.030", "Id": "436455", "Score": "0", "body": "It might help to know what the strings look like. Can you provide sample data?" } ]
[ { "body": "<p>Comparing 30,000 strings against 30,000 other strings is 900 million comparisons. It's going to take a while.</p>\n\n<p>Run the Python profiler on a small data set to see where it is spending the most time. So you can focus your efforts.</p>\n\n<h3>difflib</h3>\n\n<p>The documentation for <code>SequenceMatcher</code> says it caches information about the second sequence. So that to compare one string against a bunch of other strings, use <code>.set_seq2()</code> to set the one string, and the use <code>.set_seq()</code> to check it against each of the other strings.</p>\n\n<p>It also says that calculating <code>ratio()</code> is expensive to compute so you might want to use 'quick_ratio()<code>or</code>real_quick_ratio()` first.</p>\n\n<pre><code>def wuzzyfuzzy(df1, df2):\n myList = []\n total = len(df1)\n\n s = SequenceMatcher(isjunk=None, autojunk=False)\n\n for idx1, df1_str in enumerate(df1.col1):\n s.set_seq2(df1_str)\n\n my_str = ('Progress : ' + str(round((idx1/total)*100,3))+'%')\n sys.stdout.write('\\r' + str(my_str))\n sys.stdout.flush()\n\n best_str2 = ''\n best_ratio = 0\n\n for idx2, df2_str in enumerate(df2.col1):\n s.set_seq2(df2_str)\n\n if s.real_quick_ratio() &gt; best_ratio and s.quick_ratio() &gt; best_ratio:\n r = s.ratio()\n\n if r &gt; best_ratio:\n best_match = df2_str\n best_ratio = r\n\n myList.append([df1_str, best_match, best_ratio])\n\n return myList\n</code></pre>\n\n<p>You could also consider <code>difflib.get_close_matches(string, possibilities, n, cutoff)</code>. It compares <code>string</code> against a list <code>possibilities</code> and returns a list of upto <code>n</code> that match better than <code>cutoff</code>. </p>\n\n<pre><code>def wuzzyfuzzy(df1, df2):\n myList = []\n\n possibilities = list(df2.col1)\n\n s = SequenceMatcher(isjunk=None, autojunk=False)\n\n for idx1, df1_str in enumerate(df1.col1):\n my_str = ('Progress : ' + str(round((idx1/total)*100,3))+'%')\n sys.stdout.write('\\r' + str(my_str))\n sys.stdout.flush()\n\n # get 1 best match that has a ratio of at least 0.7\n best_match = get_close_matches(df1_str1, possibilities, 1, 0.7)\n\n s.set_seq(df1_str, best_match) \n myList.append([df1_str, best_match, s.ratio()])\n\n return myList\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T02:37:45.353", "Id": "224938", "ParentId": "224875", "Score": "2" } } ]
{ "AcceptedAnswerId": "224938", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T08:39:27.370", "Id": "224875", "Score": "5", "Tags": [ "python", "performance", "iteration", "edit-distance" ], "Title": "Finding the closest string match for each string in two dataframe columns" }
224875
<p>I've been fiddling around with some easy code challenges and there's one about determining if a triangle is equilateral, isosceles, or scalene.</p> <p>I've come up with a working solution, but I feel this could be greatly improved and/or simplified.</p> <p>The sides of a triangle come in a list e.g. [2, 2, 2] or [0, 0, 0]. </p> <p>Here's what I've got.</p> <pre><code>def is_triangle(sides): if min(sides) &lt;= 0: return False if sum(sorted(sides)[:-1]) &lt; sorted(sides)[-1]: return False return True def equilateral(sides): triangle = is_triangle(sides) if triangle: x, y, z = sides return x == y == z else: return False def isosceles(sides): triangle = is_triangle(sides) if triangle: x, y, z = sides return x == y or y == z or z == x else: return False def scalene(sides): if equilateral(sides) or isosceles(sides): return False return is_triangle(sides) </code></pre> <p>Also, I'm adding a simple unit test module.</p> <pre><code>import unittest from triangle import equilateral, isosceles, scalene class TestEquilateralTriangle(unittest.TestCase): def test_all_sides_are_equal(self): self.assertIs(equilateral([2, 2, 2]), True) def test_all_zero_sides_is_not_a_triangle(self): self.assertIs(equilateral([0, 0, 0]), False) def test_third_triangle_inequality_violation(self): self.assertIs(isosceles([3, 1, 1]), False) def test_sides_may_be_floats(self): self.assertIs(equilateral([0.5, 0.5, 0.5]), True) class TestIsoscelesTriangle(unittest.TestCase): def test_last_two_sides_are_equal(self): self.assertIs(isosceles([3, 4, 4]), True) def test_equilateral_triangles_are_also_isosceles(self): self.assertIs(isosceles([4, 4, 4]), True) def test_third_triangle_inequality_violation(self): self.assertIs(isosceles([3, 1, 1]), False) def test_sides_may_be_floats(self): self.assertIs(isosceles([0.5, 0.4, 0.5]), True) class TestScaleneTriangle(unittest.TestCase): def test_no_sides_are_equal(self): self.assertIs(scalene([5, 4, 6]), True) def test_all_sides_are_equal(self): self.assertIs(scalene([4, 4, 4]), False) def test_third_triangle_inequality_violation(self): self.assertIs(isosceles([3, 1, 1]), False) if __name__ == "__main__": unittest.main() </code></pre> <p>I'd appreciate some feedback on my code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T08:25:45.937", "Id": "436480", "Score": "0", "body": "Similar challenge: [_Determine whether three sides form a valid triangle, and classify the triangle_](/q/224810)." } ]
[ { "body": "<p>After a <em>very</em> quick pass, here's what I have for you:</p>\n\n<p>I assumed <code>... sorted(sides)[-1]:</code> was a typo, so I removed the <code>:</code>.</p>\n\n<ul>\n<li><strong>Return Expressions</strong>: It's better to return expressions than to just <code>else: return False</code>. Returning the expression that is evaluated saves time, and looks cleaner.</li>\n<li><strong>Docstrings</strong>: I'm a stickler for docstrings. Even if the method is blatantly obvious about its function, you should still include a docstring. Keeps you in the practice for when you start writing bigger programs that require more detail.</li>\n</ul>\n\n<p><strong><em>Final Code</em></strong></p>\n\n<pre><code>def is_triangle(sides):\n \"\"\" Determines if the list passed is a triangle \"\"\"\n return False if min(sides) &lt;= 0 or sum(sorted(sides)[:-1]) &lt; sorted(sides)[-1] else True\n\ndef equilateral(sides):\n \"\"\" Determines if the list passed is an equilateral triangle \"\"\"\n if is_triangle(sides):\n x, y, z = sides\n return x == y == z\n return False\n\n\ndef isosceles(sides):\n \"\"\" Determines if the list passed is an isosceles triangle \"\"\"\n if is_triangle(sides):\n x, y, z = sides\n return x == y or y == z or z == x\n return False\n\n\ndef scalene(sides):\n \"\"\" Determines if the list passed is a scalene triangle \"\"\"\n return False if equilateral(sides) or isosceles(sides) else is_triangle(sides)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T22:35:01.093", "Id": "436438", "Score": "1", "body": "I find your `is_triangle()` implementation awkward. It would be clearer to write `return min(sides) > 0 and sum(sorted(sides)[:-1])) > sorted(sides)[-1]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T14:08:17.333", "Id": "436528", "Score": "1", "body": "The `return False if ...` ternary in scalene is missing an else. Also surely it would be easier to use `not expr` instead of the pattern `False if expr else True`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T10:30:00.237", "Id": "224882", "ParentId": "224878", "Score": "6" } }, { "body": "<p>A triangle has, by definition, three sides. I find it therefore weird to take a single <code>sides</code> argument, which could be of any size. This opens you up to obscure bugs, such as these ones, which are not covered in your tests:</p>\n\n<pre><code>&gt;&gt;&gt; is_triangle([1,2,3,4])\nTrue # ?\n&gt;&gt;&gt; is_triangle([1, 1])\nTrue # ???\n&gt;&gt;&gt; is_triangle([float('nan')])\nTrue # WTF?\n</code></pre>\n\n<p>Instead, just explicitly take three arguments. The sides of a triangle are customarily called <code>a, b, c</code>.</p>\n\n<pre><code>def is_triangle(a, b, c):\n a, b, c = sorted([a, b, c])\n return a &gt; 0 and a + b &gt; c\n</code></pre>\n\n<p>This uses the fact that after the <code>sorted</code>, <code>a</code> is always the smallest side, as <a href=\"https://codereview.stackexchange.com/questions/224878/determine-if-a-triangle-is-equilateral-isosceles-or-scalene/224904?noredirect=1#comment436476_224904\">mentioned in the comments</a>.</p>\n\n<p>The only thing you need to change in your calling code is to call this with <code>is_triangle(*sides)</code>, i.e. use tuple unpacking.</p>\n\n<hr>\n\n<p>Your other functions can also be shortened a bit. Try to put multiple checks in one line to <code>return</code> right away (but don't push it if it gets too complicated).</p>\n\n<pre><code>def equilateral(a, b, c):\n return is_triangle(a, b, c) and a == b == c\n</code></pre>\n\n<p>Instead of manually checking all combinations of sides for equality, just use <code>set</code> to get rid of multiples:</p>\n\n<pre><code>def isosceles(a, b, c):\n return is_triangle(a, b, c) and len(set([a, b, c])) &lt;= 2\n\ndef scalene(a, b, c):\n return is_triangle(a, b, c) and len(set([a, b, c])) == 3\n</code></pre>\n\n<hr>\n\n<p>Note that all functions need to use <code>is_triangle</code>. You could define a decorator that makes sure the input is a triangle:</p>\n\n<pre><code>from functools import wraps\n\ndef ensure_triangle(func):\n @wraps(func)\n def wrapper(a, b, c):\n return is_triangle(a, b, c) and func(a, b, c)\n return wrapper\n\n@ensure_triangle\ndef equilateral(a, b, c):\n return a == b == c\n\n@ensure_triangle\ndef scalene(a, b, c):\n return len(set([a, b, c])) == 3\n\n@ensure_triangle\ndef isosceles(a, b, c):\n return len(set([a, b, c])) &lt;= 2\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T18:58:58.807", "Id": "436419", "Score": "8", "body": "One other change I would suggest is renaming those methods to start with `is_` for consistency and clarity. I really like the use of a decorator here." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T15:22:29.277", "Id": "224904", "ParentId": "224878", "Score": "19" } }, { "body": "<p>Consider using <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\"><code>doctest</code></a> to keep the tests close to the code and more readable. For example:</p>\n\n<pre><code>def equilateral(sides):\n '''\n True if the 'sides' argument represents an equilateral triangle\n (all sides of equal length).\n\n &gt;&gt;&gt; equilateral([2, 2, 2])\n True\n &gt;&gt;&gt; equilateral([0, 0, 0])\n False\n &gt;&gt;&gt; isosceles([3, 1, 1])\n False\n &gt;&gt;&gt; equilateral([0.5, 0.5, 0.5])\n True\n '''\n x, y, z = sides\n return is_triangle(sides) and x == y == z\n</code></pre>\n\n<p>(er, why was that <code>isosceles()</code> test in <code>TestEquilateralTriangle</code>? Is that a copy-paste error?)</p>\n\n<p>Then we can easily run all the tests:</p>\n\n<pre><code>if __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T09:35:20.547", "Id": "224960", "ParentId": "224878", "Score": "2" } } ]
{ "AcceptedAnswerId": "224904", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T09:03:39.347", "Id": "224878", "Score": "7", "Tags": [ "python", "algorithm", "python-3.x", "computational-geometry" ], "Title": "Determine if a triangle is equilateral, isosceles, or scalene" }
224878
<p>I've got below implementation for my controller and show action which implements <code>MiniMagick</code> gem. I've just wondering is there any better way to write it down? If block in a separate, private method maybe?</p> <pre><code> def show identification_document = IdentificationDocument.find(params[:id]) authorize identification_document return unless identification_document if params.has_key?(:thumbnail) document = identification_document.id_document image = MiniMagick::Image.read(document.file.read) image.resize("50x60") scaled_image_bytes = image.to_blob send_data(scaled_image_bytes, filename: identification_document.file_name) else send_data(identification_document.id_document.file.read, filename: identification_document.file_name) end end </code></pre>
[]
[ { "body": "<h2>Rubocop Report</h2>\n\n<h3>Conventions</h3>\n\n<p>Prefer <code>key?</code> over <code>has_key?</code> (<a href=\"https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Style/PreferredHashMethods\" rel=\"nofollow noreferrer\">PreferredHashMethods</a>).</p>\n\n<blockquote>\n<pre><code>if params.has_key?(:thumbnail)\n</code></pre>\n</blockquote>\n\n<pre><code>if params.key?(:thumbnail)\n</code></pre>\n\n<hr>\n\n<p>Prefer single quoted over double quoted string literals if you don't need interpolation or special symbols (<a href=\"https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Style/StringLiterals\" rel=\"nofollow noreferrer\">StringLiterals</a>).</p>\n\n<blockquote>\n<pre><code>image.resize(\"50x60\")\n</code></pre>\n</blockquote>\n\n<pre><code>image.resize('50x60')\n</code></pre>\n\n<hr>\n\n<h3>Complexity</h3>\n\n<blockquote>\n <p><em>If block in a separate, private method maybe?</em></p>\n</blockquote>\n\n<p>The <a href=\"https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Metrics/AbcSize\" rel=\"nofollow noreferrer\">AbcSize</a> complexity of your method is too high. [19.65/15] So your suggestion to put the following code in a private method, is justified.</p>\n\n<blockquote>\n<pre><code> document = identification_document.id_document\n image = MiniMagick::Image.read(document.file.read)\n image.resize(\"50x60\")\n scaled_image_bytes = image.to_blob\n</code></pre>\n</blockquote>\n\n<hr>\n\n<h3>Readability</h3>\n\n<p>Keep line sizes below 80 characters:</p>\n\n<blockquote>\n<pre><code>send_data(identification_document.id_document.file.read, filename: identification_document.file_name)\n</code></pre>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T06:54:41.837", "Id": "437876", "Score": "0", "body": "The under 80 chars rule is outdated. Screens have gotten significantly bigger and more pixels are available. There should definitely be a max char length enforced, but it can easily be 120 or 150 depending on the developers setups in an organization." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T06:56:01.783", "Id": "437877", "Score": "0", "body": "Single quote vs double quote is against the rails convention. Rails convention is double quotes all around, so I would suggest keeping the double quotes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T08:11:35.320", "Id": "437881", "Score": "0", "body": "@ekampp Thanks for the feedback, you have a link to more recent guidelines, or are you talking out of personal experience?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T08:46:18.127", "Id": "437994", "Score": "0", "body": "regarding the 80 char rule, that's from experience. The Rails convention if from reading the Rails documentation and source code." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T16:39:24.107", "Id": "225424", "ParentId": "224879", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T09:10:11.183", "Id": "224879", "Score": "2", "Tags": [ "ruby", "image", "ruby-on-rails" ], "Title": "Rails controller method to show an optionally scaled image using MiniMagick" }
224879
<p>I'm using flexbox to create a simple header, hero image with caption and footer.</p> <p>As you can see from my snippet, the header is fixed and the hero image scrolls underneath.</p> <p>Is there a way to achieve my layout without fixed or absolute positioning? I'm relatively new to flexbox and and haven't come across a solution.</p> <p>For the image, I could use the background property, but I'd like to maintain what I have to easily implement img srcset and an alt tag.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { margin: 0; } /* Flexbox */ .main-navigation, .main-navigation ul, .hero { display: flex; flex-flow: row wrap; } .main-navigation { justify-content: space-between; align-items: center; } /* Site header */ .site-header { position: fixed; top: 0; z-index: 9999; /* Always on top */ width: 100%; /* Must have width for flex */ padding: 24px; color: #fff; background-color: #021928; } /* Hero */ .hero { position: relative; /* For image */ height: 100vh; /* Fill viewport */ justify-content: center; align-items: center; } .hero img { position: absolute; top: 0; left: 0; width: 100%; z-index: -1; /* Send image to back */ height: 100vh; object-fit: cover; object-position: bottom; } /* Cosmetic */ ul { margin: 0; padding: 0; list-style: none; } li { margin-right: 12px; } li:last-child { margin: 0; } a, a:visited, a:focus, a:hover { color: #fff; } p { padding: 24px; } .caption { padding: 0; } h1 { margin: 0 0 12px; } .logo { margin: 0; } .caption { max-width: 600px; text-align: center; color: #fff; } .site-footer { padding: 24px; background-color: #021928; color: #fff; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="site-header"&gt; &lt;nav class="main-navigation"&gt; &lt;h1 class="logo"&gt;Logo&lt;/h1&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Item One&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Item Two&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Item Three&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt;&lt;!-- .site-header --&gt; &lt;div class="hero"&gt; &lt;div class="caption"&gt; &lt;h1&gt;Title goes here&lt;/h1&gt; &lt;p class="caption"&gt;And a caption&lt;/p&gt; &lt;/div&gt; &lt;img src="https://ichef.bbci.co.uk/news/660/cpsprodpb/3963/production/_103119641_7623dbe4-9ef2-4108-a2f1-a745d0640c53.jpg" alt="Kittens"&gt; &lt;/div&gt;&lt;!-- .hero --&gt; &lt;div class="main"&gt; &lt;p&gt;Main page content&lt;/p&gt; &lt;/div&gt;&lt;!-- .main --&gt; &lt;div class="site-footer"&gt; &lt;span&gt;Some information about stuff&lt;/span&gt; &lt;/div&gt;&lt;!-- .site-footer --&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>If you want the header to be \"sticky\" the only way is to make it <code>position:fixed</code>. In order to to push the rest of the content down, you need to know the headers <code>height</code>. Then you set a <code>margin-top</code> to your <code>#hero</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T16:26:53.530", "Id": "225210", "ParentId": "224880", "Score": "2" } }, { "body": "<p>Neither the fixed position of the header nor the positioning of the background image is achievable with flexbox.</p>\n\n<p>You can replace <code>fixed</code> with <code>sticky</code>. This fixes the offset of the background image for <code>.hero</code> (<code>sticky</code> effects the flow of elements). This also allows us to drop the <code>width</code> attribute which is incorrectly set to <code>width: 100%</code> (should be <code>width: calc(100% - 48px)</code>) and thus fix so that the entire header is visible.</p>\n\n<p>I think you should use <code>background-image</code>. I agree with <a href=\"https://stackoverflow.com/a/4216214/3755425\">this</a> post stating you don't need an alt for a background image. And there's decent support for <a href=\"https://caniuse.com/#search=image-set\" rel=\"nofollow noreferrer\">the image-set css property</a> (although I don't have experience with this property myself).</p>\n\n<p><a href=\"https://codepen.io/a-morn/pen/xvdVZm\" rel=\"nofollow noreferrer\">https://codepen.io/a-morn/pen/xvdVZm</a></p>\n\n<p>Edit: I recommend <a href=\"http://flexboxzombies.com/p/flexbox-zombies\" rel=\"nofollow noreferrer\">Flexbox Zombies</a> if you want to learn more about what flexbox can and can't do.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T20:29:33.053", "Id": "437207", "Score": "1", "body": "Thanks for your answer. I like position: sticky and your method for the background image." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T20:11:49.803", "Id": "225217", "ParentId": "224880", "Score": "2" } } ]
{ "AcceptedAnswerId": "225217", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T09:58:45.253", "Id": "224880", "Score": "1", "Tags": [ "html", "css" ], "Title": "Using flexbox to replace fixed and absolute positioning" }
224880
<p>I've written this code in Scala that extracts bigram statistics from the Reuters dataset. It puts the statistics in a <code>Map[String, SortedMap[String, Int]]</code>. For example, the bigrams for "hi" could look like this:</p> <pre><code>Map("hello" -&gt; SortedMap("there" -&gt; 10, "friend" -&gt; 6)) </code></pre> <p>which means that "there" follows "hi" 10 times in the dataset, and "friend" follows "hi" 6 times.</p> <p>My code takes a very long time to run, 22 minutes just for one file of 1.3 megabytes.</p> <p>The code looks like this:</p> <pre><code>import java.io.File import scala.annotation.tailrec import scala.collection.mutable import scala.io.Source import scala.util.matching.Regex import scala.collection.mutable object Main extends App { val bigrams: Bigrams = Bigrams.fromPath("src/test/resources/mini.sgm") } case class Bigrams(bigrams: BigramsMap) { def extractStatistics(path: String): Bigrams = { val entry: File = new File(path) if (entry.exists &amp;&amp; entry.isDirectory) { println("Extracting bigrams from " + entry.getPath + "/") val bigramsFromDir: BigramsMap = entry .listFiles .filter(file =&gt; file.isFile &amp;&amp; file.getName.endsWith(".sgm")) .map(Bigrams.getBigramsFrom) .foldLeft(BigramsMap())(Bigrams.merge) val bigramsFromSubDirs: Bigrams = entry .listFiles .filter(entry =&gt; entry.isDirectory) .map(entry =&gt; extractStatistics(entry.getAbsolutePath)) .foldLeft(Bigrams())(Bigrams.merge) bigramsFromSubDirs.mergeIn(bigramsFromDir) } else if (entry.exists &amp;&amp; entry.isFile) { Bigrams(Bigrams.getBigramsFrom(entry)) } else throw new RuntimeException("Incorrect path") } def getFreqs(word: String): Option[mutable.SortedMap[String, Int]] = { bigrams.get(word) } def mergeIn(bigramsIn: BigramsMap): Bigrams = { Bigrams(Bigrams.merge(bigrams, bigramsIn)) } } object Bigrams { val BODY: Regex = "(?s).*&lt;BODY&gt;(.*)&lt;/BODY&gt;(?s).*".r def apply(): Bigrams = { new Bigrams(BigramsMap()) } def fromPath(path: String): Bigrams = { new Bigrams(BigramsMap()).extractStatistics(path) } // Return a list with the markup for each article @tailrec def readArticles(remainingLines: List[String], acc: List[String]): List[String] = { if (remainingLines.size == 1) (acc.head + "\n" + remainingLines.head) +: acc.tail else { val nextLine = remainingLines.head if (nextLine.startsWith("&lt;REUTERS ")) readArticles(remainingLines.tail, nextLine +: acc) else readArticles(remainingLines.tail, (acc.head + "\n" + nextLine) +: acc.tail) } } def addBigramsFrom(tokens: List[String], oldBigrams: BigramsMap): BigramsMap = { val bigramPairs: List[(String, String)] = Bigrams.getBigrams(tokens) val newBigrams: BigramsMap = getBigramsFrom(bigramPairs) merge(oldBigrams, newBigrams) } def merge(bigrams1: Bigrams, bigrams2: Bigrams): Bigrams = { Bigrams(merge(bigrams1.bigrams, bigrams2.bigrams)) } def merge(bigrams1: BigramsMap, bigrams2: BigramsMap): BigramsMap = { BigramsMap( bigrams1.map ++ bigrams2.map .map(entry1 =&gt; entry1._1 -&gt; (entry1._2 ++ bigrams1.getOrElse(entry1._1, mutable.SortedMap[String, Int]()) .map(entry2 =&gt; entry2._1 -&gt; (entry2._2 + entry1._2.getOrElse(entry2._1, 0)))))) } def getBigramsFrom(path: File): BigramsMap = { println("Extracting bigrams from " + path.getPath) val file = Source.fromFile(path) val fileLines: List[String] = file.getLines().toList val articles: List[String] = Bigrams.readArticles(fileLines.tail, List()) val bodies: List[String] = articles.map(extractBody).filter(body =&gt; !body.isEmpty) val sentenceTokens: List[List[String]] = bodies.flatMap(getSentenceTokens) sentenceTokens.foldLeft(BigramsMap())((acc, tokens) =&gt; addBigramsFrom(tokens, acc)) } def getBigramsFrom(tokens: List[(String, String)]): BigramsMap = { BigramsMap().addAll(tokens) } def getBigrams(tokens: List[String]): List[(String, String)] = { tokens.indices. map(i =&gt; { if (i &lt; tokens.size - 1) (tokens(i), tokens(i + 1)) else null }) .filter(_ != null).toList } // Return the body of the markup of one article def extractBody(article: String): String = { try { val body: String = article match { case Bigrams.BODY(bodyGroup) =&gt; bodyGroup } body } catch { case _: MatchError =&gt; "" } } def getSentenceTokens(text: String): List[List[String]] = { val separatedBySpace: List[String] = text .replace('\n', ' ') .replaceAll(" +", " ") // regex .split(" ") .map(token =&gt; if (token.endsWith(",")) token.init.toString else token) .toList val splitAt: List[Int] = separatedBySpace.indices .filter(i =&gt; i &gt; 0 &amp;&amp; separatedBySpace(i - 1).endsWith(".") || i == 0) .toList groupBySentenceTokens( separatedBySpace, splitAt, List()) .map(sentenceTokens =&gt; sentenceTokens.init :+ sentenceTokens.last.substring(0, sentenceTokens.last.length - 1)) .map(sentenceTokens =&gt; sentenceTokens.map(sentenceToken =&gt; sentenceToken.toLowerCase)) } @tailrec def groupBySentenceTokens(tokens: List[String], splitAt: List[Int], sentences: List[List[String]]): List[List[String]] = { if (splitAt.size &lt;= 1) { if (splitAt.size == 1) { sentences :+ tokens.slice(splitAt.head, tokens.size) } else { sentences } } else groupBySentenceTokens(tokens, splitAt.tail, sentences :+ tokens.slice(splitAt.head, splitAt.tail.head)) } } case class BigramsMap(map: Map[String, mutable.SortedMap[String, Int]]) { def addAll(bigrams: List[(String, String)]): BigramsMap = { if (bigrams.isEmpty) this else { val first = bigrams.head._1 val second = bigrams.head._2 if (map.contains(first)) { if (map(first).contains(second)) { BigramsMap(map.updated(first, map(first) + (second -&gt; (map(first)(second) + 1)))).addAll(bigrams.tail) } else { BigramsMap(map.updated(first, map(first) + (second -&gt; 1))).addAll(bigrams.tail) } } else { BigramsMap(map.updated(first, mutable.SortedMap(second -&gt; 1))).addAll(bigrams.tail) } } } def get(key: String): Option[mutable.SortedMap[String, Int]] = map.get(key) def getOrElse[V1 &gt;: mutable.SortedMap[String, Int]](key: String, default: V1): V1 = map.getOrElse(key, default) } object BigramsMap { def apply(elems: (String, mutable.SortedMap[String, Int])*): BigramsMap = BigramsMap(Map(elems: _*)) def apply(): BigramsMap = BigramsMap(Map[String, mutable.SortedMap[String, Int]]()) } </code></pre> <p>Here is a small test file to run it on. Obviously, the Reuters dataset is much, much bigger. </p> <p><strong>mini.sgm:</strong></p> <pre><code>&lt;!DOCTYPE lewis SYSTEM "lewis.dtd"&gt; &lt;REUTERS TOPICS="YES" LEWISSPLIT="TEST" CGISPLIT="TRAINING-SET" OLDID="5429" NEWID="15531"&gt; &lt;DATE&gt; 9-APR-1987 09:40:15.27&lt;/DATE&gt; &lt;TOPICS&gt;&lt;D&gt;grain&lt;/D&gt;&lt;D&gt;ship&lt;/D&gt;&lt;/TOPICS&gt; &lt;PLACES&gt;&lt;D&gt;uk&lt;/D&gt;&lt;/PLACES&gt; &lt;PEOPLE&gt;&lt;/PEOPLE&gt; &lt;ORGS&gt;&lt;/ORGS&gt; &lt;EXCHANGES&gt;&lt;/EXCHANGES&gt; &lt;COMPANIES&gt;&lt;/COMPANIES&gt; &lt;UNKNOWN&gt; &amp;#5;&amp;#5;&amp;#5;C G &amp;#22;&amp;#22;&amp;#1;f0885&amp;#31;reute u f BC-LONDON-FREIGHT-MARKET 04-09 0100&lt;/UNKNOWN&gt; &lt;TEXT&gt;&amp;#2; &lt;TITLE&gt;LONDON FREIGHT MARKET FEATURES GRAIN OUT OF U.S.&lt;/TITLE&gt; &lt;DATELINE&gt; LONDON, April 9 - &lt;/DATELINE&gt;&lt;BODY&gt;Moderately active grain fixing was reported out of the U.S. But none of the business involved the significant voyages to the Continent or Japan, ship brokers said. A steady 13.50 dlrs was paid from the U.S. Gulf to Morocco and 23.25 dlrs was paid for 27,000 long tons from the Gulf to Taiwan. A vessel carrying 13,500 long tons of bagged wheat flour from the Gulf to Aqaba received a lump sum of 472,500 dlrs. Grain from the Great Lakes to Algeria made 28 dlrs against 27.75 paid for similar fixing towards the end of March. Market talk suggested a Federal Commerce vessel had been booked to move grain from the Great Lakes to Morocco on Comanav account at about 22 dlrs and 15.50 had been paid for a cargo of oilseeds from British Columbia to Japan, but no confirmation was obtainable. On the Continent, shippers agreed 19 dlrs for wheat from La Pallice to Buenaventura and 10.75 dlrs for grain from Ghent to Naples/Venice range. Elsewhere, maize from East London to Japan paid 22 dlrs. Soviet charterers reappeared in the timecharter sector and secured a 30,000 tonner from Savona for a trans-Atlantic round trip at 4,450 dlrs daily and a 31,000 tonner from Antwerp-Hamburg for a similar voyage at 4,250 dlrs daily. Reuter &amp;#3;&lt;/BODY&gt;&lt;/TEXT&gt; &lt;/REUTERS&gt; </code></pre> <p>I've looked for ways to make the code more efficient, but unsuccessfully so. I've run a profiler on my code and it seems like the <code>merge</code> function takes almost all the CPU time during execution. But I don't see any glaring inefficiencies in it. </p> <p>Is there any way to make my program run faster?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T22:17:15.367", "Id": "436873", "Score": "0", "body": "Posted code does not compile. No definition for `BigramsMap`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T09:07:39.957", "Id": "436909", "Score": "0", "body": "Sorry, added it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T09:09:58.937", "Id": "436910", "Score": "0", "body": "Can you post the results of your profiler, including the arguments used to run it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T07:51:21.413", "Id": "437261", "Score": "0", "body": "My guess is that you're paying a toll when you collect the data into `SortedMap`. As an experiment I replaced every `mutable.SortedMap` with simply `Map`. I got what appeared to be the same results (no deep analysis) only the `Map` elements were in a different order. I would suggest sorting only when and if it's needed. Maybe at the end when the results are organized for presentation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T14:40:30.457", "Id": "437322", "Score": "0", "body": "That sounds like a good idea, I will try that." } ]
[ { "body": "<p>Changing from SortedMap to Map sped up the program massively. One file now only takes a few seconds, instead of over 20 minutes. Sorting can be done at a small cost at bigram querying.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T06:29:25.090", "Id": "226298", "ParentId": "224884", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T11:30:10.980", "Id": "224884", "Score": "3", "Tags": [ "performance", "scala", "xml" ], "Title": "Counting bigrams in XML files in a directory tree" }
224884
<p>I have a simple method that receives messages from bus, builds response and send it back, and it looks like:</p> <pre><code>let readFromBusAndSendRequest = let mutable timer = new Timer(float 10000) let OnTimedEvent (frameId:uint32, projectId:uint32, cabinId:byte) (bus:IBus) : ElapsedEventHandler = new ElapsedEventHandler (fun _ _ -&gt; printfn "Publishing UM1 Request %A Frame %A" DateTime.Now framId //Create request bus.Publish&lt;RequestMessage&gt;(request, HubSubscriptionId)) match this.Bus with | Some bus -&gt; let cabinetSubscribeId = sprintf "Project.%i.Cabin.%i" this.ProjectId this.CabinId let busResponseFactory (response : BasicMessage) = match response.FrameType with | FrameType.SERVICE_LIST -&gt; let serviceListResponse : ServiceListMessage = response :?&gt; ServiceListMessage let isMessageValid = serviceListResponse.FrameWithoutCrc.IsValidCrc32(serviceListResponse.ResponseCrc32) match isMessageValid with | true -&gt; publishAck bus (serviceListResponse, RequestedService.Unknown) timer.Dispose() timer &lt;- new Timer(float 10000, AutoReset = true) timer.AutoReset &lt;- true timer.Elapsed.AddHandler(OnTimedEvent ((serviceListResponse.FrameId + 1u), this.ProjectId, byte this.CabinId) bus) timer.Start(); | false -&gt; publishNack bus (serviceListResponse, RequestedService.Unknown) NackRejectionReason.InvalidCrc | false -&gt; publishNack bus (serviceResponse, serviceResponse.RequestedService) NackRejectionReason.InvalidCrc | _ -&gt; printfn "OTHER SUPPORT" let handler = Action&lt;ResponseMessage&gt;(fun response -&gt; printfn "Response %A frame type %s response id %i" response.ProjectId (response.FrameType.ToString()) response.FrameId; busResponseFactory response |&gt; ignore) bus.Subscribe&lt;ResponseMessage&gt;(cabinetSubscribeId, handler, Action&lt;FluentConfiguration.ISubscriptionConfiguration&gt;(fun sub -&gt; sub.WithTopic(cabinetSubscribeId) |&gt; ignore)) |&gt; ignore </code></pre> <p>When I get a certain type of response(in this case SERVICE_LIST), I want it to attach an event to the Timer, and make it run each 10 seconds. All parameters needed are from message received from bus </p> <p>As you see, I used a <code>mutable</code> timer because each time I press I receive new SERVICE_LIST message, an event is added but but not removed, and believe me I tried:</p> <pre><code> timer.Elapsed.RemoveHandler(OnTimedEvent frameId) </code></pre> <p>Probably because frame id is different every time.</p> <p>Instead of dispose, but it did not work; new events were just added but not removed. So is there a better way to conquer this mess?</p> <p>I know it is because I create new event each time, but how to remove old one?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T21:22:29.000", "Id": "436590", "Score": "1", "body": "Is this real code from a real project? It's not clear what this code is really achieving (e.g. what is `frameId`, why is it always `1`?), and I feel it's probably off-topic in its current form. The reason `RemoveHandler` isn't working is because you are creating a new handler each time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T07:28:04.850", "Id": "436901", "Score": "1", "body": "Well, I have imported this to real time program, and add some more explanations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T12:35:50.663", "Id": "436928", "Score": "0", "body": "Thanks, much clearer the purpose now. However, your indentation is inconsistent and it looks like you never use the `busResponseFactory` binding, so I'm not sure this code can work. Has something gone missing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T07:12:31.240", "Id": "437256", "Score": "0", "body": "I have updated the code, `busResponseFactory` is a part of bus subscription action" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T10:25:28.207", "Id": "437277", "Score": "0", "body": "There still seems to be something missing: there must be a case where `this.Bus = None` or similar. It's best to provide as much context as you can, but if it really isn't important (i.e. doesn't interact with the other code at all) then it should be ok to just add `None -> (* snip *)` on the end." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T11:51:12.320", "Id": "224886", "Score": "1", "Tags": [ "f#" ], "Title": "F#, Timer and propperly removed ElapsedEventHandler" }
224886
<p>I have a calculator (in React) and I wonder if the way I did is is good or what I could improve. I wanted to do it like the iphone calculator (you dont only see results when you press =) and I feel like my code became a little messy. Any suggestions would be awesome! Ps. I didn't yet add more then +,-,/.*,= operations.</p> <p>I also added the code on codepen: </p> <p><a href="https://codepen.io/julianyc/pen/bXwxbg?editors=1010" rel="nofollow noreferrer">https://codepen.io/julianyc/pen/bXwxbg?editors=1010</a></p> <pre><code> const math_it_up = { ['+']: function (x, y) { console.log(x, y, typeof x, typeof y, "blaaa") return x + y }, ['-']: function (x, y) { return x - y }, ['*']: function (x, y) { console.log(x, y, typeof x, typeof y, "blaaa") return x * y }, ['/']: function (x, y) { return x / y } } class App extends React.Component { state = { result: 0, operator: "", currentNum: "", show: 0 }; onClick = (elem) =&gt; { if (isNaN(elem)) { if (elem === "=") { this.setState({ showResult: this.state.result }) } else { this.setState({ operator: elem, show: this.state.result ? this.state.result : null }) } } else { if (!this.state.currentNum) { this.setState({ currentNum: parseInt(elem), result: parseInt(elem), show: elem }) } else { if (this.state.operator) { this.setState({ currentNum: parseInt(elem), result: math_it_up[this.state.operator](this.state.result, parseInt(elem)), show: elem }) } } } }; render() { return ( &lt;div&gt; &lt;Key onClick={this.onClick}/&gt; &lt;h1&gt;{this.state.show}&lt;/h1&gt; &lt;/div&gt; ) } } const Key = ({onClick}) =&gt; { const renderNumbers = () =&gt; { const arr = [0,1,2,3,4,5,6,7,8,9]; return arr.map((val, i) =&gt; { return &lt;button key={i} name={val} onClick={(e) =&gt; onClick(e.target.name)}&gt;{val}&lt;/button&gt; }) }; const renderCalculationKeys = () =&gt; { const arr = ["+", "-", "/", "*", "="]; return arr.map((val, i) =&gt; { return &lt;button key={i} name={val} onClick={(e) =&gt; onClick(e.target.name)}&gt;{val}&lt;/button&gt; }) }; return ( &lt;div&gt; {renderNumbers()} {renderCalculationKeys()} &lt;/div&gt; ) }; ReactDOM.render( &lt;App /&gt;, document.getElementById('root') ); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T09:34:54.510", "Id": "436490", "Score": "0", "body": "ah I didnt notice, just updated it with the correct link" } ]
[ { "body": "<p>Thumbs up for putting the operators in an object, here's some improvements i would suggest : </p>\n\n<ul>\n<li>There's a typo when user clicks on \" = \", <code>show</code> instead of <code>howResult</code>.</li>\n<li>in the <code>math_it_up</code> Object you don't need the <code>[]</code>.</li>\n<li>I would Rename <code>Key</code> to <code>Pad</code> for better understanding.</li>\n<li>use <code>val</code> instead of <code>e.target.value</code> ( in <code>onClick(val)</code> ) since you have the value in there.</li>\n<li>add <code>radix parameter</code> to <code>parseInt</code> like : <code>parseInt(myVar, 10)</code> , or use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus\" rel=\"nofollow noreferrer\">Unary_plus</a> <code>+</code>.</li>\n<li>no need for the <code>parseInt</code> in the <code>else</code> of <code>if(isNaN)</code>.</li>\n<li>instead of <code>prevState.result ? prevState.result : null</code> you can do <code>prevState.result || null</code> to avoid repeating.</li>\n<li><code>setState</code> is asynchronous : \nif you need to update the state with a value that depends on the <code>this.state</code>, it's better to pass a callback to <code>setState</code> instead of an object, <a href=\"https://medium.com/@baphemot/understanding-reactjs-setstate-a4640451865b\" rel=\"nofollow noreferrer\">see this post</a> for more details.</li>\n</ul>\n\n<p>Her's a snippet of what the code would look like with the changes :</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const math_it_up = {\n \"+\": function(x, y) { \n return x + y;\n },\n \"-\": function(x, y) {\n return x - y;\n },\n \"*\": function(x, y) { \n return x * y;\n },\n \"/\": function(x, y) {\n return x / y;\n }\n};\n\nclass App extends React.Component {\n state = {\n result: 0,\n operator: \"\",\n currentNum: \"\",\n show: 0\n };\n\n onClick = elem =&gt; {\n if (isNaN(elem)) {\n if (elem === \"=\") {\n this.setState( prevState =&gt; ({ \n show: prevState.result\n }));\n } else {\n this.setState(prevState =&gt; ({\n operator: elem,\n show: prevState.result || null\n }));\n }\n } else {\n if (!this.state.currentNum) {\n this.setState({\n currentNum: elem,\n result: elem,\n show: elem\n });\n } else {\n if (this.state.operator) {\n this.setState(prevState =&gt; ({\n currentNum: elem,\n result: math_it_up[this.state.operator](prevState.result, elem),\n show: elem\n }));\n }\n }\n }\n };\n\n render() {\n return (\n &lt;div&gt;\n &lt;Pad onClick={this.onClick} /&gt;\n &lt;h1&gt;{this.state.show}&lt;/h1&gt;\n &lt;/div&gt;\n );\n }\n}\n\nconst Pad = ({ onClick }) =&gt; {\n const renderNumbers = () =&gt; {\n const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];\n return arr.map(val =&gt; {\n return (\n &lt;button key={val} name={val} onClick={() =&gt; onClick(val)}&gt;\n {val}\n &lt;/button&gt;\n );\n });\n };\n\n const renderCalculationKeys = () =&gt; {\n const arr = [\"+\", \"-\", \"/\", \"*\", \"=\"];\n return arr.map(val =&gt; {\n return (\n &lt;button key={val} name={val} onClick={() =&gt; onClick(val)}&gt;\n {val}\n &lt;/button&gt;\n );\n });\n };\n\n return (\n &lt;div&gt;\n {renderNumbers()}\n {renderCalculationKeys()}\n &lt;/div&gt;\n );\n};\n\nReactDOM.render(&lt;App /&gt;, document.getElementById(\"root\"));</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"&gt;&lt;/script&gt;\n&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"&gt;&lt;/script&gt;\n&lt;div id=\"root\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T16:14:39.563", "Id": "436556", "Score": "0", "body": "Thank you! I actually noticed there is also a mistake in my code, because I cannot add/divide etc numbers bigger then 9. How could I change my code so i can add etc numbers bigger then 9?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T21:36:28.590", "Id": "224927", "ParentId": "224892", "Score": "2" } }, { "body": "<h2>Reviewing your current app</h2>\n\n<p>Nice work so far! Calculators make educational projects because you can incrementally scale up the complexity. As the application grows, numerous design decisions in maintaining expression state need to be made and interesting parsing and equation evaluation situations arise. Here are some thoughts on the current code:</p>\n\n<h3>Typo</h3>\n\n<p><code>showResult: this.state.result</code> should be <code>show: this.state.result</code>. This typo causes <kbd>=</kbd> to break.</p>\n\n<h3>Keep style consistent</h3>\n\n<p>Code with inconsistent style is difficult to read and increases the cognitive load on any humans working with the code, increasing the chances of bugs.</p>\n\n<ul>\n<li>Instead of switching between snake_case and camelCase, use camelCase always in JS (class/component names are PascalCase).</li>\n<li>Although semicolons are, in most cases, optional (my preference is to always include them), the code switches back and forth between including them and not.</li>\n<li>Avoid goofy variable names like <code>math_it_up</code>. This is distracting and unclear.</li>\n<li>Remove <code>console.log</code> calls from code before releasing it.</li>\n</ul>\n\n<h3>Separate concerns</h3>\n\n<p>Even though pains were taken to separate <code>renderCalculationKeys</code> and <code>renderNumbers</code>, they're virtually identical code. Both share the same overburdened <code>onClick</code> handler which uses nested conditionals to differentiate the actions. Conditionals are undesirable because they make state and flow difficult to reason about and have low semantic value. Using separate handlers makes it possible to eliminate this conditional and compartmentalize handler logic into distinct chunks.</p>\n\n<h3>Use ES6 syntax</h3>\n\n<ul>\n<li><code>math_it_up</code> takes advantage of first-class functions and is easily extensible for new operations you might wish to add. Arrow functions can simplify this abstraction, eliminating noisy <code>return</code> keywords. Calling the returned function whenever code elsewhere in the class needs an evaluation is a bit of a burden; wrapping this object in an <code>evaluate()</code> function simplifies the calling code.</li>\n<li>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">destructuring</a> to avoid repeating <code>this.state</code>. If React 16.8 is available for your project, try <a href=\"https://reactjs.org/docs/hooks-intro.html\" rel=\"nofollow noreferrer\">hooks</a>.</li>\n</ul>\n\n<h3>Additional remarks</h3>\n\n<ul>\n<li>The <code>Key</code> component is misleadingly named because it actually renders plural <code>Keys</code>.</li>\n<li>Temporary variables like <code>const arr = [...]</code> which are used only once on the next line could be <code>map</code>ed in one statement, cutting out the extra step. Even if it is kept, the name <code>arr</code> could be clearer as <code>numbers</code> or <code>operators</code>.</li>\n<li><code>this.state.result ? this.state.result : null</code> could be <code>this.state.result || null</code>.</li>\n<li>Since the component is a calculator, consider calling it <code>Calculator</code> instead of <code>App</code>, which is usually a generic top-level container.</li>\n</ul>\n\n<hr>\n\n<h2>A rewrite suggestion</h2>\n\n<p>Since you've asked for the ability to add multiple numbers, you might find that the current code is a bit unwieldy due to the excessive state. There are a few ways to solve this. The approach I took is to store the expression in an array called <code>this.state.expr</code>. This makes it possible to use the length of the expression array to determine which buttons cause which action in a given state. This isn't a general solution should you wish to expand to longer equations, but it's a reasonable choice for supporting the current desired functionality.</p>\n\n<p>A user may want the option to start a fresh expression by pressing a number key directly after <kbd>=</kbd> was pressed. This can be achieved with a <code>justComputed</code> flag. I've also used parsing to avoid leading zeroes like <code>007</code>. I left Infinity as the outcome of division by zero and chose to ignore numerical overflow.</p>\n\n<p>Here's a version that addresses the above points in addition to supporting multi-digit numbers:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class Calculator extends React.Component {\n state = {expr: [\"0\"], justComputed: false};\n \n evaluate() {\n const {expr} = this.state;\n return {\n \"+\": (x, y) =&gt; x + y,\n \"-\": (x, y) =&gt; x - y,\n \"/\": (x, y) =&gt; x / y,\n \"*\": (x, y) =&gt; x * y,\n }[expr.splice(1, 1)](...expr.map(e =&gt; +e));\n }\n \n handleEq = e =&gt; {\n if (this.state.expr.length === 3) {\n this.setState({\n expr: [\"\" + this.evaluate()], \n justComputed: true\n });\n }\n };\n\n handleNum = e =&gt; {\n const {justComputed, expr} = this.state;\n const num = e.target.name;\n\n if (justComputed) {\n this.setState({\n expr: [num], \n justComputed: false\n });\n }\n else if (expr.length === 2) {\n this.setState({expr: expr.concat(num)});\n }\n else {\n this.setState({\n expr: expr.concat(+(expr.pop() + num) + \"\")\n });\n }\n };\n \n handleOp = e =&gt; {\n const {expr} = this.state;\n const op = e.target.name;\n \n if (expr.length === 1) {\n this.setState({\n expr: expr.concat(op), \n justComputed: false\n });\n }\n else if (expr.length === 2) {\n this.setState({expr: expr.pop() &amp;&amp; expr.concat(op)});\n }\n else {\n this.setState({expr: [\"\" + this.evaluate(), op]});\n }\n };\n \n render() {\n const {expr} = this.state;\n return (\n &lt;div&gt;\n &lt;Keys \n handleNum={this.handleNum} \n handleOp={this.handleOp} \n handleEq={this.handleEq} \n /&gt;\n &lt;h1&gt;{expr.length &lt; 3 ? expr[0] : expr[2]}&lt;/h1&gt;\n &lt;/div&gt;\n );\n }\n}\n\nconst Keys = ({handleNum, handleOp, handleEq}) =&gt; \n &lt;div&gt;\n {[...\"0123456789\"].map(e =&gt;\n &lt;button\n key={e}\n name={e} \n onClick={handleNum}\n &gt;{e}&lt;/button&gt;\n )}\n {[...\"+-/*\"].map(e =&gt;\n &lt;button\n key={e}\n name={e} \n onClick={handleOp}\n &gt;{e}&lt;/button&gt;\n )}\n &lt;button\n key=\"=\"\n name=\"=\"\n onClick={handleEq}\n &gt;=&lt;/button&gt;\n &lt;/div&gt;\n;\n\nReactDOM.render(&lt;Calculator /&gt;, document.getElementById(\"root\"));</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"&gt;&lt;/script&gt;\n&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"&gt;&lt;/script&gt;\n&lt;div id=\"root\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<h2>Next steps</h2>\n\n<p>Some features you might consider adding:</p>\n\n<ul>\n<li>Show the current expression as it's being built in a separate element.</li>\n<li>Support negative numbers.</li>\n<li>Add a <kbd>.</kbd> decimal button. Ensure that states such as <code>1.2.3</code> are disallowed.</li>\n<li>Add undo/redo/history support and/or <kbd>CE</kbd>, <kbd>C</kbd> and <kbd>Backspace</kbd> buttons.</li>\n<li>Add CSS and create an attractive UI.</li>\n<li>Make it possible to add long expressions such as <code>5+3*5/-2-7</code>.</li>\n<li>Add functions such as sqrt, sin, cos, tan, log, etc.</li>\n<li>Add support for parenthesis.</li>\n<li>Support big integers and scientific notation.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T22:21:58.307", "Id": "436600", "Score": "0", "body": "Be sure to also handle division by zero :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T22:10:29.610", "Id": "224995", "ParentId": "224892", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T13:27:43.923", "Id": "224892", "Score": "4", "Tags": [ "calculator", "react.js", "jsx" ], "Title": "React.js calculator" }
224892
<p>Here is a stored procedure which we use to port the data from a remote server to our data warehouse server. The SP uses a generic style where all the tables along with its schema and data will be loaded into the data warehouse.</p> <p>The script is working fine, but now we have a requirement where few of the tables like <code>customer_access</code> (which I have filtered in the query - couple more tables are there) need to be refreshed within a short time (1-2 minutes).The data count of those tables is around 500K to 1000K, hence the porting takes around 7-8 minutes.</p> <p>The logic used in the script is drop and recreate each and every time the table will be dropped and recreated.</p> <p>To make it faster I thought of using the MERGE or UPSERT logic and I need your suggestions on implementing this in a most generic way which will work for all tables.</p> <p><strong>Scored Procedure Code:</strong></p> <pre><code>CREATE OR REPLACE PROCEDURE public.load_foreign_schema_postgresql_stock( _server text, _remote_schema text, _dl_schema text DEFAULT NULL::text, _foreign_table_schema text DEFAULT NULL::text, check_ft boolean DEFAULT true, recreate_primary_keys boolean DEFAULT true, log_table_schema_name text DEFAULT NULL::text, log_table_name text DEFAULT NULL::text) LANGUAGE 'plpgsql' AS $BODY$ DECLARE tab RECORD; tab_indices RECORD; start_time TIMESTAMPTZ; pg_class TEXT := 'pg_class_stock' || now()::TEXT; pg_namespace TEXT := 'pg_namespace_stock' || now()::TEXT; pg_index TEXT := 'pg_index_stock' || now()::TEXT; pg_attribute TEXT := 'pg_attribute_stock' || now()::TEXT; foreign_server TEXT; remote_schema TEXT; foreign_schema TEXT; dl_schema TEXT; table_name TEXT; nr_rows TEXT; duration_table_load INTERVAL; duration_index_creation INTERVAL; duration_analyze INTERVAL; recreate_primary_keys BOOLEAN; index_query TEXT; BEGIN IF _foreign_table_schema ISNULL THEN _foreign_table_schema := 'ft_' || _remote_schema; END IF; IF _dl_schema ISNULL THEN _dl_schema := _remote_schema; END IF; foreign_server := _server; remote_schema := _remote_schema; dl_schema := _dl_schema; foreign_schema := _foreign_table_schema; recreate_primary_keys := load_foreign_schema_postgresql_stock.recreate_primary_keys; IF recreate_primary_keys THEN EXECUTE format('CREATE FOREIGN TABLE %1$I.%2$I ( oid OID OPTIONS (COLUMN_NAME ''oid''), relname NAME OPTIONS (COLUMN_NAME ''relname''), relnamespace OID OPTIONS (COLUMN_NAME ''relnamespace''), relkind CHAR OPTIONS (COLUMN_NAME ''relkind'') ) SERVER %3$I OPTIONS (SCHEMA_NAME ''pg_catalog'', TABLE_NAME ''pg_class'') ;', _foreign_table_schema, pg_class, _server); EXECUTE format('CREATE FOREIGN TABLE %1$I.%2$I ( oid OID OPTIONS (COLUMN_NAME ''oid''), nspname TEXT OPTIONS (COLUMN_NAME ''nspname'') ) SERVER %3$I OPTIONS (SCHEMA_NAME ''pg_catalog'', TABLE_NAME ''pg_namespace'') ;', _foreign_table_schema, pg_namespace, _server); EXECUTE format('CREATE FOREIGN TABLE %1$I.%2$I ( oid OID OPTIONS (COLUMN_NAME ''oid''), indexrelid OID OPTIONS (COLUMN_NAME ''indexrelid''), indrelid OID OPTIONS (COLUMN_NAME ''indrelid''), indisunique BOOLEAN OPTIONS (COLUMN_NAME ''indisunique''), indisprimary BOOLEAN OPTIONS (COLUMN_NAME ''indisprimary''), indkey INT2VECTOR OPTIONS (COLUMN_NAME ''indkey'') ) SERVER %3$I OPTIONS (SCHEMA_NAME ''pg_catalog'', TABLE_NAME ''pg_index'') ;', _foreign_table_schema, pg_index, _server); EXECUTE format('CREATE FOREIGN TABLE %1$I.%2$I ( attrelid OID OPTIONS (COLUMN_NAME ''attrelid''), attname NAME OPTIONS (COLUMN_NAME ''attname''), attnum SMALLINT OPTIONS (COLUMN_NAME ''attnum'') ) SERVER %3$I OPTIONS (SCHEMA_NAME ''pg_catalog'', TABLE_NAME ''pg_attribute'') ;', _foreign_table_schema, pg_attribute, _server); COMMIT; END IF; FOR tab IN ( SELECT foreign_table_schema, foreign_table_name FROM information_schema.foreign_tables WHERE foreign_table_schema = _foreign_table_schema AND foreign_server_name = _server AND foreign_table_name NOT IN (pg_class, pg_attribute, pg_namespace, pg_index) AND foreign_table_name='customer_access' ORDER BY 1, 2 ) LOOP table_name := tab.foreign_table_name; RAISE NOTICE 'Loading table %.% into %.%', tab.foreign_table_schema, tab.foreign_table_name, _dl_schema, tab.foreign_table_name; EXECUTE format('DROP TABLE IF EXISTS %I.%I;', _dl_schema, tab.foreign_table_name); start_time := clock_timestamp(); EXECUTE format('CREATE TABLE %1$I.%2$I AS SELECT * FROM %3$I.%2$I;', _dl_schema, tab.foreign_table_name, tab.foreign_table_schema); duration_table_load := clock_timestamp() - start_time; GET DIAGNOSTICS nr_rows := ROW_COUNT; RAISE NOTICE '% rows loaded into %.%', nr_rows, _dl_schema, tab.foreign_table_name; duration_index_creation := NULL; IF recreate_primary_keys THEN start_time := clock_timestamp(); index_query := format(' WITH indexes AS ( SELECT n.nspname AS schemaname, c.relname AS tablename, i.relname AS indexname, x.indisprimary, indkey, indrelid FROM (((%1$I.%5$I x JOIN %1$I.%2$I c ON ((c.oid = x.indrelid))) JOIN %1$I.%2$I i ON ((i.oid = x.indexrelid))) LEFT JOIN %1$I.%4$I n ON ((n.oid = c.relnamespace))) WHERE ((c.relkind = ANY (ARRAY [''r''::"char", ''m''::"char"])) AND (i.relkind = ''i''::"char")) AND n.nspname = %6$L AND c.relname = %7$L ), indexes_cols_pkey AS ( SELECT *, indkey[a] AS ikey FROM indexes, generate_subscripts(indkey, 1) t(a) WHERE indisprimary ), pkeys AS ( SELECT format(''ALTER TABLE %8$I.%%1$I ADD PRIMARY KEY (%%2$s)'', i.tablename, string_agg(format(''%%1$I'', attname::TEXT), '', '' ORDER BY a)) AS indexdef FROM indexes_cols_pkey i JOIN %1$I.%3$I a ON i.indrelid = a.attrelid AND a.attnum = ikey GROUP BY i.schemaname,i.tablename ) SELECT * FROM pkeys ;', tab.foreign_table_schema, pg_class, pg_attribute, pg_namespace, pg_index, remote_schema, table_name, dl_schema ); FOR tab_indices IN EXECUTE index_query LOOP RAISE NOTICE '%',tab_indices.indexdef; EXECUTE tab_indices.indexdef; END LOOP; duration_index_creation := clock_timestamp() - start_time; END IF; RAISE NOTICE 'Analyzing %.%', _dl_schema, tab.foreign_table_name; start_time := clock_timestamp(); EXECUTE format('ANALYZE %I.%I', _dl_schema, tab.foreign_table_name); duration_analyze := clock_timestamp() - start_time; RAISE NOTICE 'Done analyzing %.%', _dl_schema, tab.foreign_table_name; COMMIT; END LOOP; END $BODY$; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T13:36:49.550", "Id": "224894", "Score": "1", "Tags": [ "sql", "postgresql" ], "Title": "Merge logic for customer access" }
224894
<p>this is a simple wrapper for sqlite3 to make working with databases easier it isn't a professional implementation but it is much better than the raw c interface I saved much time and code using this wrapper instead of the raw interface any improvements will be appreciated</p> <p>HandleBase.hpp</p> <pre><code>#pragma once #include &lt;type_traits&gt; template &lt;class T, T null_value, bool no_negative = true&gt; class HandleWrapper { public: HandleWrapper() : handle(null_value) {} HandleWrapper(T h) : handle(h) { if constexpr (no_negative) { if constexpr (std::is_integral_v&lt;T&gt;) { if constexpr (null_value &gt;= 0) { if (handle &lt; 0) handle = null_value; } } else { if constexpr ((intptr_t)null_value &gt;= 0) { if ((intptr_t)handle &lt; 0) handle = null_value; } } } } bool operator==(const HandleWrapper&amp; rhs) { return handle == rhs.handle; } bool operator!=(const HandleWrapper&amp; rhs) { return handle != rhs.handle; } bool operator&gt;(const HandleWrapper&amp; rhs) { return handle &gt; rhs.handle; } bool operator&gt;=(const HandleWrapper&amp; rhs) { return handle &gt;= rhs.handle; } bool operator&lt;(const HandleWrapper&amp; rhs) { return handle &lt; rhs.handle; } bool operator&lt;=(const HandleWrapper&amp; rhs) { return handle &lt; rhs.handle; } explicit operator bool() const { return handle != null_value; } operator T() { return handle; } private: T handle; }; template &lt;class T, T null_value, bool no_negative, auto Deleter&gt; struct HandleHelper { using pointer = HandleWrapper&lt;T, null_value, no_negative&gt;; void operator()(pointer p) { Deleter(T(p)); } }; </code></pre> <p>sqlite++.h</p> <pre><code>#pragma once #include &lt;HandleBase.hpp&gt; #include &lt;memory&gt; #include &lt;sqlite3.h&gt; #include &lt;string&gt; using SqlHandle = std::unique_ptr&lt;HandleWrapper&lt;sqlite3*, nullptr, false&gt;, HandleHelper&lt;sqlite3*, nullptr, false, sqlite3_close&gt; &gt;; using SqlStatementHandle = std::unique_ptr&lt;HandleWrapper&lt;sqlite3_stmt*, nullptr, false&gt;, HandleHelper&lt;sqlite3_stmt*, nullptr, false, sqlite3_finalize&gt;&gt;; enum class SqlOpenFlags { Read = SQLITE_OPEN_READONLY, ReadWrite = SQLITE_OPEN_READWRITE, ReadWriteCreate = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, }; class SqlDb { SqlHandle handle; public: SqlDb() {} SqlDb(const std::string&amp; path); SqlDb(const std::wstring&amp; path); SqlDb(const std::string&amp; path, SqlOpenFlags flags); SqlDb(SqlDb&amp;&amp; rhs) : handle(std::move(rhs.handle)) {} SqlDb&amp; operator=(SqlDb&amp;&amp; rhs) { handle = std::move(rhs.handle); return *this; } bool Open(const std::string&amp; path); bool Open(const std::wstring&amp; path); bool Open(const std::string&amp; path, SqlOpenFlags flags); void Close() { handle.reset(); } explicit operator bool() const { return bool(handle); } sqlite3 * native_handle() { return handle.get(); } SqlHandle Release() { return std::move(handle); } int ErrorCode(); int ErrorCodeExt(); std::string ErrorStr(); std::wstring ErrorStrW(); }; class SqlQuery { SqlStatementHandle statement; std::string statement_str; public : SqlQuery() {} SqlQuery(SqlDb&amp; db, const char *stmt, ...); SqlQuery(SqlDb&amp; db, const wchar_t *stmt, ...); SqlQuery(SqlQuery&amp;&amp; rhs) : statement(std::move(rhs.statement)) {} bool Prepare(SqlDb&amp; db, const char *stmt, ...); bool Prepare(SqlDb&amp; db, const wchar_t *stmt, ...); void Close() { statement.reset(); } sqlite3_stmt * native_handle() { return statement.get(); } SqlStatementHandle Release() { return std::move(statement); } explicit operator bool() const { return bool(statement); } std::string GetStatement(); bool execute(); bool next(); int ColumnsCount(); int ColumnSize(int index); std::string GetStr(int index); std::wstring GetStrW(int index); int GetInt(int index); int64_t GetInt64(int index); double GetDouble(int index); const void *GetBlob(int index); }; </code></pre> <p>sqlite++.cpp</p> <pre><code>#include "sqlite++.h" using namespace std; SqlDb::SqlDb(const std::string &amp; path) { sqlite3 *temp_handle; sqlite3_open(path.c_str(), &amp;temp_handle); handle.reset(temp_handle); } SqlDb::SqlDb(const std::wstring &amp; path) { sqlite3 *temp_handle; sqlite3_open16(path.c_str(), &amp;temp_handle); handle.reset(temp_handle); } SqlDb::SqlDb(const std::string &amp; path, SqlOpenFlags flags) { sqlite3 *temp_handle; sqlite3_open_v2(path.c_str(), &amp;temp_handle, (int)flags, nullptr); handle.reset(temp_handle); } bool SqlDb::Open(const std::string &amp; path) { sqlite3 *temp_handle; sqlite3_open(path.c_str(), &amp;temp_handle); handle.reset(temp_handle); return bool(handle); } bool SqlDb::Open(const std::wstring &amp; path) { sqlite3 *temp_handle; sqlite3_open16(path.c_str(), &amp;temp_handle); handle.reset(temp_handle); return bool(handle); } bool SqlDb::Open(const std::string &amp; path, SqlOpenFlags flags) { sqlite3 *temp_handle; sqlite3_open_v2(path.c_str(), &amp;temp_handle, (int)flags, nullptr); handle.reset(temp_handle); return bool(handle); } int SqlDb::ErrorCode() { return sqlite3_errcode(handle.get()); } int SqlDb::ErrorCodeExt() { return sqlite3_extended_errcode(handle.get()); } std::string SqlDb::ErrorStr() { return sqlite3_errmsg(handle.get()); } std::wstring SqlDb::ErrorStrW() { return (wchar_t*)sqlite3_errmsg16(handle.get()); } SqlQuery::SqlQuery(SqlDb &amp; db, const char * stmt, ...) { va_list args; va_start(args, stmt); size_t required_size = vsnprintf(nullptr, 0, stmt, args); if (!required_size) return; unique_ptr&lt;char&gt; buff(new char[required_size + 1]); vsnprintf(buff.get(), required_size + 1, stmt, args); va_end(args); sqlite3_stmt *temp_stmt; sqlite3_prepare_v2(db.native_handle(), buff.get(), -1, &amp;temp_stmt, nullptr); statement_str = buff.get(); statement.reset(temp_stmt); } SqlQuery::SqlQuery(SqlDb &amp; db, const wchar_t * stmt, ...) { va_list args; va_start(args, stmt); size_t required_size = vswprintf(nullptr, 0, stmt, args); if (!required_size) return; unique_ptr&lt;wchar_t&gt; buff(new wchar_t[required_size + 1]); vswprintf(buff.get(), required_size + 1, stmt, args); va_end(args); sqlite3_stmt *temp_stmt; sqlite3_prepare16_v2(db.native_handle(), buff.get(), -1, &amp;temp_stmt, nullptr); statement.reset(temp_stmt); } bool SqlQuery::Prepare(SqlDb &amp; db, const char * stmt, ...) { statement.reset(); va_list args; va_start(args, stmt); size_t required_size = vsnprintf(nullptr, 0, stmt, args); if (!required_size) return false; unique_ptr&lt;char&gt; buff(new char[required_size + 1]); vsnprintf(buff.get(), required_size + 1, stmt, args); va_end(args); sqlite3_stmt *temp_stmt; sqlite3_prepare_v2(db.native_handle(), buff.get(), -1, &amp;temp_stmt, nullptr); statement_str = buff.get(); statement.reset(temp_stmt); return bool(statement); } bool SqlQuery::Prepare(SqlDb &amp; db, const wchar_t * stmt, ...) { statement.reset(); va_list args; va_start(args, stmt); size_t required_size = vswprintf(nullptr, 0, stmt, args); if (!required_size) return false; unique_ptr&lt;wchar_t&gt; buff(new wchar_t[required_size + 1]); vswprintf(buff.get(), required_size + 1, stmt, args); va_end(args); sqlite3_stmt *temp_stmt; sqlite3_prepare16_v2(db.native_handle(), buff.get(), -1, &amp;temp_stmt, nullptr); statement.reset(temp_stmt); return bool(statement); } std::string SqlQuery::GetStatement() { return statement_str; //const char *str = sqlite3_sql(statement.get()); always returns null , don't know why ? //return str ? string(str) : string(); } bool SqlQuery::execute() { return sqlite3_step(statement.get()) == SQLITE_DONE; } bool SqlQuery::next() { return sqlite3_step(statement.get()) == SQLITE_ROW; } int SqlQuery::ColumnsCount() { return sqlite3_column_count(statement.get()); } int SqlQuery::ColumnSize(int index) { return sqlite3_column_bytes(statement.get(), index); } std::string SqlQuery::GetStr(int index) { const char *str = (char*)sqlite3_column_text(statement.get(), index); return str ? string(str) : string(); } std::wstring SqlQuery::GetStrW(int index) { const wchar_t *str = (wchar_t*)sqlite3_column_text16(statement.get(), index); return str ? wstring(str) : wstring(); } int SqlQuery::GetInt(int index) { return sqlite3_column_int(statement.get(), index); } int64_t SqlQuery::GetInt64(int index) { return sqlite3_column_int64(statement.get(), index); } double SqlQuery::GetDouble(int index) { return sqlite3_column_double(statement.get(), index); } const void * SqlQuery::GetBlob(int index) { return sqlite3_column_blob(statement.get(), index); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T13:50:37.120", "Id": "224896", "Score": "1", "Tags": [ "c++", "database", "sqlite" ], "Title": "c++ sqlite3 wrapper" }
224896
<p>I am using an API to check if customers have social media profiles. </p> <p>Depending on whether they have phone or email or both there's a different search type.</p> <p>There's a lot of conditions in this function, and the real dataframe has about 50 columns. So I'm just wondering if this is the most efficient way to go about it. </p> <p>I'm aware that I'm applying this on a full row when I only need to work with a few in the df. </p> <p>So I have two fake customer records here, and I'm trying to fill the social media columns with info returned from an API call:</p> <pre><code>import pandas as pd df = pd.DataFrame(columns=['name','phone','email','facebook','foursquare','instagram','linkedin','skype','twitter'],index=range(0,2)) df['email'] = ['jim@email.com',pd.np.nan] df['name'] = ['Jim Bob','Joe Bloggs'] df['phone'] = [pd.np.nan,'35543256'] print(df) name phone email facebook foursquare instagram linkedin \ 0 Jim Bob NaN jim@email.com NaN NaN NaN NaN 1 Joe Bloggs 35543256 NaN NaN NaN NaN NaN skype twitter 0 NaN NaN 1 NaN NaN </code></pre> <p>Depending on the presence of phone/email, the function goes as follows (I believe I've commented my logic acceptably .. if something isn't clear please let me know)</p> <pre><code># the columns from the df we want to fill mycols = ['facebook','foursquare','instagram','linkedin','skype','twitter'] def checksocial(row): # if both phone and email are null if pd.isnull(row['phone']) and pd.isnull(row['email']): # do nothing # (analyzing and returning a whole row here, is this efficient?) return row # if there is no phone number but email is present elif pd.isnull(row['phone']) and pd.notnull(row['email']): # use phone to search for social media # fake API response returned_results = ['facebook','foursquare','instagram'] for socialmedia in returned_results: # if it's one of the social media profiles we are looking for if socialmedia in mycols: # add result to DF under same social media column row[socialmedia] = 'Found Social Media' # return updated row return row # if there is a phone number and email is empty elif pd.notnull(row['phone']) and pd.isnull(row['email']): # use phone to search for social media # fake API response returned_results = ['facebook','linkedin','twitter'] for socialmedia in returned_results: # if it's one of the social media profiles we are looking for if socialmedia in mycols: # add result to DF under same social media column row[socialmedia] = 'Found Social Media' # return updated row return row # repeat the same for when both email and phone are present </code></pre> <p>Applying the function:</p> <pre><code>df = df.apply(checksocial,axis=1) print(df) name phone email facebook \ 0 Jim Bob NaN jim@email.com Found Social Media 1 Joe Bloggs 35543256 NaN Found Social Media foursquare instagram linkedin skype \ 0 Found Social Media Found Social Media NaN NaN 1 NaN NaN Found Social Media NaN twitter 0 NaN 1 Found Social Media </code></pre> <p>It works fine, but the reason I'm asking for advice here is that the actual code I have is starting to become way too long. (There's parsing a json response that I didn't add here) and there are like 100,000 rows. </p> <p>I have a lot of <code>if</code> statements, and I'm working with a full row and returning it. </p> <p>Any advice on how to make this more cleaner/efficient? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T17:14:40.320", "Id": "436395", "Score": "0", "body": "What does `repeat the same for when both email and phone are present` mean exactly? Do you look up social media based on both? If so, what happens if the two lookups return different results?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T10:23:24.113", "Id": "436497", "Score": "0", "body": "I have updated the code to explain that. Basically there's a different api call for each condition, depending on the presence of phone and email. not great but that's what I have to work with." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T10:44:31.057", "Id": "436502", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>Few things to note here:</p>\n\n<p>Columns:</p>\n\n<pre><code>email_results=['facebook','foursquare','instagram']\nphone_results=['facebook','linkedin','twitter']\n</code></pre>\n\n<p>Conditions:</p>\n\n<pre><code>c1=df.phone.isna()&amp;df.email.notna()\nc2=df.phone.notna()&amp;df.email.isna()\n</code></pre>\n\n<p><strong><em>Method1</em></strong></p>\n\n<p>You can try and replace <code>if else</code> conditions with <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html\" rel=\"nofollow noreferrer\"><code>np.where</code></a> , also take a look at <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.select.html\" rel=\"nofollow noreferrer\"><code>np.select()</code></a> if you have <code>elif</code> conditions:</p>\n\n<pre><code>df[email_results]=np.where(c1[:,None],'Found Social Media',df[email_results])\ndf[phone_results]=np.where(c2[:,None],'Found Social Media',df[phone_results])\nprint(df)\n</code></pre>\n\n<p><strong><em>Method2</em></strong></p>\n\n<p>Or you can take a look at <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mask.html\" rel=\"nofollow noreferrer\"><code>df.mask()</code></a>:</p>\n\n<pre><code>df[email_results]=df[email_results].mask(c1,'Found Social Media')\ndf[phone_results]=df[phone_results].mask(c2,'Found Social Media')\nprint(df)\n</code></pre>\n\n<hr>\n\n<p><a href=\"https://i.stack.imgur.com/DAqB9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DAqB9.png\" alt=\"enter image description here\"></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T18:03:28.727", "Id": "224919", "ParentId": "224900", "Score": "1" } }, { "body": "<p><strong>EDIT</strong>: I've updated the function to check for <code>phone</code> and <code>email</code>.</p>\n\n<p>Firstly, I think it's more readable and generally preferred to put a space after each comma in a list. <a href=\"https://www.python.org/dev/peps/pep-0008/#id16\" rel=\"nofollow noreferrer\">PEP8</a> does not specifically mention this, but you will see that it is done in all their examples, i.e.:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>my_list = [\n 1, 2, 3,\n 4, 5, 6,\n]\n</code></pre>\n\n<p>Of course in the end that's up to you, it's just a guideline.</p>\n\n<p>Your conditions only depend on <code>phone</code> and <code>email</code>, so there's no need to apply you function to the whole DataFrame. Also, I'm not sure whether your <em>repeat the same for when both email and phone are present</em> means that in that case you also use the phone-lookup API call or another one. If in case both are present you give one of the two preference, you use that as default. So your function could look something like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def checksocial(phone, email):\n returned_results = []\n if pd.notnull(phone) and pd.notnull(email):\n returned_results = ['skype', 'linkedin', 'twitter'] # \"all\" api call\n elif pd.notnull(phone) or pd.notnull(email):\n returned_results = (\n ['facebook', 'linkedin', 'twitter'] if pd.notnull(phone)\n else ['facebook', 'foursquare', 'instagram']\n )\n # I guess your returned result is a dict already, then you can skip this\n result = {social: 'Found Social Media' for social in returned_results}\n return pd.Series(result)\n</code></pre>\n\n<p>You then apply it to your two indicator columns and assign the result to the rest of your columns. Result with a slightly extended df that takes into account all possibilities:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>columns = ['name', 'phone', 'email', 'facebook', 'foursquare', 'instagram',\n 'linkedin', 'skype', 'twitter']\ndf = pd.DataFrame(columns=columns, index=range(0, 4))\n\ndf['email'] = ['jim@email.com', pd.np.nan, pd.np.nan, 'jane@email.com']\ndf['name'] = ['Jim Bob', 'Joe Bloggs', 'Chuck Norris', 'Jane Doe']\ndf['phone'] = [pd.np.nan, '35543256', pd.np.nan, '123456'\n\ndf.loc[:, mycols] = df.loc[:, [\"phone\", \"email\"]].apply(\n lambda x: checksocial(*x), axis=1)\n\nprint(df)\n\n name phone email facebook \\\n0 Jim Bob NaN jim@email.com Found Social Media \n1 Joe Bloggs 35543256 NaN Found Social Media \n2 Chuck Norris NaN NaN NaN \n3 Jane Doe 123456 jane@email.com NaN \n\n foursquare instagram linkedin \\\n0 Found Social Media Found Social Media NaN \n1 NaN NaN Found Social Media \n2 NaN NaN NaN \n3 NaN NaN Found Social Media \n\n skype twitter \n0 NaN NaN \n1 NaN Found Social Media \n2 NaN NaN \n3 Found Social Media Found Social Media \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T10:29:48.917", "Id": "436498", "Score": "0", "body": "Thank you. What's the asterisk for here? : `checksocial(*x)` I have also updated my question to answer your question: \" Also, I'm not sure whether your repeat the same for when both email and phone are present means that in that case you also use the phone-lookup API call or another one.\" There's a separate API call for each condition. Not ideal but that's what I have to work with. The api call has a `type` argument for each condition. `type: phone`, `type: email` and `type: all`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T15:45:37.310", "Id": "436547", "Score": "1", "body": "I see, that's good. Then I would recommend to first make a column indicating the `type` and then apply your api function to that type column. I will update my answer in a bit to reflect that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T12:51:36.037", "Id": "436803", "Score": "1", "body": "The asterisk unpacks the values it was given, so it will pass `phone` and `email` as separate values to `checksocial`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T11:38:49.140", "Id": "437128", "Score": "0", "body": "I've marked your response as the answer, thanks. Just one more question: for the function `def checksocial`, you create an empty list: `returned_results = []` and then create `returned_results` again later: `returned_results = ['skype', 'linkedin', 'twitter']`. Why did you create the empty list first? Is it good practice to do this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T11:53:24.763", "Id": "437129", "Score": "0", "body": "also, one more if you don't mind. The second condition: `elif pd.notnull(phone) or pd.notnull(email):` would this not be used also if both phone `and` email are `notnull` like in the first condition? How can I ensure this is used only if phone `or` email is present, and not both? I hope I'm making sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T17:43:09.553", "Id": "437190", "Score": "1", "body": "If I didn't create the empty list, it could happen that `returned_results` is unassigned when it used to create the dict. Also, this way you don't need a separate condition for both `phone` and `email` being null, since it is the base case. As you write that you're parsing the json response, I guess that variable is already a dict and you don't need to create one. You'd probably want to initialise the varibable as `None` then. To your second question, `elif` (`else if`) if the first statement is true (`phone` **and** `email`), the second one is not evaluated." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T19:45:49.750", "Id": "224925", "ParentId": "224900", "Score": "1" } } ]
{ "AcceptedAnswerId": "224925", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T14:46:32.097", "Id": "224900", "Score": "3", "Tags": [ "python", "pandas" ], "Title": "Checking whether customers in a dataframe have social media accounts" }
224900
<p>I have been working on my game for quite a while. one of its key features is cross-platform local multiplayer for example 2 players on 1 keyboard and some people on the controller.</p> <p>However after finishing my script which took me a whole day to get it running just the way I want it to work. it works but is very inefficient there is very noticeable input lag when selecting players. and sometimes the input is skipped altogether.</p> <p>I suspect the main cause to be the Update function and the last 3 functions in it (AlternateInput, assignplayerInput, StartGame)</p> <p>here is the first iteration of my Working but slow code</p> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.Linq; public class InputManger : MonoBehaviour { public List&lt;string&gt; playerOrderString = new List&lt;string&gt;() { "notSelected", "notSelected", "notSelected", "notSelected" }; public bool resetPlayerSelect; public string repFor = "K"; public Image startScreenImage; public float fadeTime = 1.0f; void Update() { PlayerHasBeenSelected(); ResetInput(); AlternateInput(); assignPlayerInput(); StartGame(); } void StartGame() { if (playerOrderString[0] != "notSelected") { if (Input.GetButtonDown("Start" + playerOrderString[0])) { for (int i = 0; i &lt; playerOrderString.Count; i++) { if (playerOrderString[i] == "notSelected") { playerOrderString.RemoveAt(i); i = 0; } } playerOrderString.RemoveAll(item =&gt; item == null); GameObject.FindWithTag("GameController").GetComponent&lt;GameManager&gt;().PlayerOrder = playerOrderString.ToArray(); GameObject.FindWithTag("GameController").GetComponent&lt;GameManager&gt;().FadeTime = fadeTime; GameObject.FindWithTag("GameController").GetComponent&lt;GameManager&gt;().enabled = true; StartCoroutine(FadeOutStartScreen(fadeTime, 0.0f)); return; } } else { return; } } IEnumerator FadeOutStartScreen(float fadeTime, float fadeToValue) { float alpha = startScreenImage.color.a; for (float t = 0.0f; t &lt; 1.0f; t += Time.deltaTime / fadeTime) { Color newColor = new Color(1, 1, 1, Mathf.Lerp(alpha, fadeToValue, t)); startScreenImage.color = newColor; yield return null; } } void ResetInput() { if (resetPlayerSelect) { playerOrderString = new List&lt;string&gt;() { "notSelected", "notSelected", "notSelected", "notSelected" }; resetPlayerSelect = false; StartCoroutine(FadeOutStartScreen(fadeTime, 1.0f)); } } void AlternateInput() { if (repFor == "K") repFor = "C"; else repFor = "K"; } void assignPlayerInput() { int checkForHowManayInput; if (repFor == "K") checkForHowManayInput = 2; else checkForHowManayInput = 4; for (int unAssignedPlayer = 0; unAssignedPlayer &lt; playerOrderString.Count; unAssignedPlayer++) { if (playerOrderString[unAssignedPlayer] == "notSelected") { for (int keyboardInput = 0; keyboardInput &lt; checkForHowManayInput; keyboardInput++) { string playerOrderVale = repFor + (keyboardInput + 1); string playerThisTime = "Fire1" + playerOrderVale; if ((Input.GetButtonDown(playerThisTime)) &amp;&amp; (playerOrderString[unAssignedPlayer] == "notSelected")) { if (CheckRepetedValue(playerThisTime)) { return; } else { playerOrderString[unAssignedPlayer] = playerOrderVale; return; } } } } } } bool CheckRepetedValue(string playerThisTime) { for (int i = 0; i &lt; playerOrderString.Count; i++) { if (playerThisTime == ("Fire1" + playerOrderString[i])) { return true; } } return false; } public Text InitilizeText; void PlayerHasBeenSelected() { if (playerOrderString[0] != "notSelected") { InitilizeText.text = ""; for (int i = 0; i &lt; playerOrderString.Count; i++) { InitilizeText.text = InitilizeText.text + "\nPlayer " + (i + 1) + " is " + playerOrderString[i]; } } } } </code></pre> <p>I think the biggest reasons for the slow code would be the nested for loops in assignPlayerInput();</p> <p>I will explain a bit more about how my code works</p> <p>In unity input manager I have set up controls for 6 types of controllers which follow the pattern of thisInputK1, thisInputK2, thisInputC1... and so on where K denotes keyboard input and C denotes Controller Input.</p> <p>The numbers after that denote the different sets of keys the input requests, for example, VecticalK1 is the same as VecticalK2 but K1 uses WASD while K2 uses arrow keys same is for the controller but they use separate controllers </p>
[]
[ { "body": "<h2>Return statement demystified</h2>\n\n<p>You have 2 return statement in the following function, and both are excessive. </p>\n\n<blockquote>\n<pre><code>void StartGame()\n{\n if (playerOrderString[0] != \"notSelected\")\n {\n if (Input.GetButtonDown(\"Start\" + playerOrderString[0]))\n {\n // .. code\n return;\n }\n }\n else\n {\n return;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>The first one sits in a nested if-statement. When you walk the code, leaving the if-statement, there is no other code being called in this method, so the method returns anyway.</p>\n\n<pre><code>void StartGame()\n{\n if (playerOrderString[0] != \"notSelected\")\n {\n if (Input.GetButtonDown(\"Start\" + playerOrderString[0]))\n {\n // .. code\n }\n }\n else\n {\n return;\n }\n}\n</code></pre>\n\n<p>The second one is the only statement in an if-statement. The if-statement itself is a terminal (no other code follows this block in your method). The entire if-statement can be omitted.</p>\n\n<pre><code>void StartGame()\n{\n if (playerOrderString[0] != \"notSelected\")\n {\n if (Input.GetButtonDown(\"Start\" + playerOrderString[0]))\n {\n // .. code\n }\n }\n}\n</code></pre>\n\n<p>We could still go further from here. I would love to get rid of the nested if-statement. We could invert the outer if-statement. We have introcuded a new return statement, but this one makes sense. We actually want to exit early here.</p>\n\n<pre><code>void StartGame()\n{\n if (playerOrderString[0] == \"notSelected\")\n {\n return;\n }\n\n if (Input.GetButtonDown(\"Start\" + playerOrderString[0]))\n {\n // .. code\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T15:37:24.370", "Id": "436367", "Score": "1", "body": "In case you wonder why all the properties are _fields_. It's `unity3d` ailment. It doesn't work well with properties... so I've heard. This pattern is common to all `unity3d` questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T15:43:36.300", "Id": "436373", "Score": "1", "body": "I read your answer and have understood about where I am using the return; excessively and have changed it and removed the 2 return statements and the else statement. However, I don't understand the second part in which you say \"The second one sits in an empty if-statement, and again not followed with any statements after leaving this block. The entire if-statement can be omitted.\" as `if (Input.GetButtonDown(\"Start\" + playerOrderString[0]))` is nested in a for loop and after the for loop, there is still some code to be run." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T15:32:48.380", "Id": "224906", "ParentId": "224902", "Score": "2" } }, { "body": "<p>I have managed to solve the problem on my own. the problem was int the AssignPlayerInput() and the AlternateInput(). let me explain what was happening</p>\n\n<p>each frame the value of repFor was either \"K\" or \"C\" after which the AssignPlayerInput() would use that value to check input the frame which meant if I tried to press a K type input and a C type input only one of those would get detected depending on value of repFor So I changed my code so it would check for both K and C in a single Frame.</p>\n\n<p>here is my latest code and AssignPlayerInput() is called every frame</p>\n\n<pre><code>void AssignPlayerInput()\n {\n for (int unAssignedPlayer = 0; unAssignedPlayer &lt; playerOrderString.Count; unAssignedPlayer++)\n {\n if (playerOrderString[unAssignedPlayer] == \"notSelected\")\n {\n\n CheckInputFor(\"K\", 2, unAssignedPlayer);\n CheckInputFor(\"C\", 4, unAssignedPlayer);\n }\n }\n }\n void CheckInputFor(string repFor, int times, int unAssignedPlayer)\n {\n for (int input = 0; input &lt; times; input++)\n {\n string playerOrderVale = repFor + (input + 1);\n string playerThisTime = \"Fire1\" + playerOrderVale;\n if ((Input.GetButtonDown(playerThisTime)) &amp;&amp; (playerOrderString[unAssignedPlayer] == \"notSelected\"))\n {\n if (CheckRepetedValue(playerThisTime))\n {\n return;\n }\n else\n {\n playerOrderString[unAssignedPlayer] = playerOrderVale;\n return;\n }\n }\n }\n }\n\n<span class=\"math-container\">`</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T22:05:54.543", "Id": "224994", "ParentId": "224902", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T15:14:25.333", "Id": "224902", "Score": "3", "Tags": [ "c#", "performance", "unity3d" ], "Title": "Unity Custom InputManger for Cross-Platform Input" }
224902
<p>I recently made a logger program implementation in my game engine. Which logs any thing that I send it in either a file or the System.out printstream.</p> <p>I use it like this:</p> <pre class="lang-java prettyprint-override"><code>private static Logger logger = LogManager.getLogger(Shader.class.getName()); </code></pre> <p>And then I can call a log method like this:</p> <pre class="lang-java prettyprint-override"><code>logger.info("Info", e); // I can also pass it an exception or a throwable for it to print to the stream or write to the file. </code></pre> <p>This is a sample output (it writes the same thing to a file as well)</p> <pre><code>[July 24, 2019 7:42 PM] [com.base.engine.core.CoreEngine] INFO: 4.5.13399 Compatibility Profile Context 15.200.1062.1004 </code></pre> <p>The reason I did this was because one day I thought to myself, why not log things to a file.</p> <p>So I went on my crazy 4 hour journey to reinvent the wheel and make a logger from scratch. Mostly the reason was that I couldn't figure out how to get log4j working so I gave up and did this.</p> <p>My question is that: Is this in someone's opinion, efficient enough to be used in production and is there a way to make it better, maybe by multithreading it?.</p> <p>Here is the LogManager:</p> <pre class="lang-java prettyprint-override"><code>public class LogManager { private static HashMap&lt;String, Logger&gt; loggers = new HashMap&lt;String, Logger&gt;(); private static ArrayList&lt;LogLevel&gt; allowedLevels = new ArrayList&lt;LogLevel&gt;(); private static LogLevel currentLevel; public static FileHandler fileHandler; public static Logger getLogger(String className) { if (!loggers.containsKey(className)) { Logger resultLogger = new Logger(className); loggers.put(className, resultLogger); if (fileHandler != null) { resultLogger.setOutputForLogFile(fileHandler.out); } } return (loggers.get(className)); } public static void addFileHandler() { if (fileHandler == null) { try { fileHandler = new FileHandler("log.log", "./logs/"); fileHandler.setAppend(false); fileHandler.initializeWriter(); fileHandler.out.println("\n-------------------------------------" + getCurrentTimeAndDate() + "-------------------------------------\n"); for (Entry&lt;String, Logger&gt; entry : loggers.entrySet()) { String key = entry.getKey(); Logger value = entry.getValue(); System.out.println("Adding output " + key); value.setOutputForLogFile(fileHandler.out); } } catch (IOException e) { e.printStackTrace(); } } } public static void addAllowedLevel(LogLevel l) { if (!allowedLevels.contains(l)) { allowedLevels.add(l); } } public static void removeAllowedLevel(LogLevel l) { if (!allowedLevels.contains(l)) { allowedLevels.remove(l); } } public static boolean isLevelAllowed(LogLevel l) { if (allowedLevels.contains(l)) { return (true); } return (false); } public static void setLogLevel(LogLevel l) { currentLevel = l; } public static HashMap&lt;String, Logger&gt; getLoggers() { return loggers; } public static void setLoggers(HashMap&lt;String, Logger&gt; loggers) { LogManager.loggers = loggers; } public static LogLevel getCurrentLevel() { return currentLevel; } public static void setCurrentLevel(LogLevel currentLevel) { LogManager.currentLevel = currentLevel; } public static String getCurrentTimeAndDate() { return (DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT).format(new Date())); } static SimpleDateFormat sdf = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa"); private static String getCurrentTimeAndDateForFile() { return (sdf.format(new Date())); } public static void setFileHandler(FileHandler fileHandler) { LogManager.fileHandler = fileHandler; } } </code></pre> <p>Here is the Logger class:</p> <pre class="lang-java prettyprint-override"><code>public class Logger { private String name; private PrintWriter out; public Logger(String name) { this.name = name; // this.out = LogManager.fileHandler.out; } public Logger(String name, FileHandler fileHandler) { this.name = name; // this.out = LogManager.fileHandler.out; } public void setOutputForLogFile(PrintWriter out) { this.out = out; } public void setClassName(String className) { this.name = className; } private void println(String line) { System.out.println(line); if (out != null) { this.out.println(line); this.out.flush(); } } private void println(Throwable e) { e.printStackTrace(); if (out != null) { this.out.println(e.getClass().getSimpleName() + ": "); e.printStackTrace(this.out); this.out.flush(); } } public void log(String msg) { println(this.formatLog(LogLevel.ALL) + msg); } public void log(String msg, Throwable e) { println(this.formatLog(LogLevel.ALL) + msg); println(e); } private String formatLog(LogLevel l) { String log = "[" + LogManager.getCurrentTimeAndDate() + "] [" + this.name + "] " + l + ": "; return log; } private boolean checkAllowed(LogLevel l) { if (LogManager.getCurrentLevel() == l || LogManager.getCurrentLevel() == LogLevel.ALL || (LogManager.isLevelAllowed(l) || LogManager.isLevelAllowed(LogLevel.ALL))) { return (true); } return (false); } public boolean finnest(String msg) { if (checkAllowed(LogLevel.FINNEST)) { println(this.formatLog(LogLevel.FINNEST) + msg); return (true); } return (false); } public void finnest(String msg, Throwable e) { if (finnest(msg)) { // e.printStackTrace(); println(e); } } public boolean fine(String msg) { if (checkAllowed(LogLevel.FINE)) { println(this.formatLog(LogLevel.FINE) + msg); return (true); } return (false); } public void fine(String msg, Throwable e) { if (fine(msg)) { println(e); } } public boolean debug(String msg) { if (checkAllowed(LogLevel.DEBUG)) { println(this.formatLog(LogLevel.DEBUG) + msg); return (true); } return (false); } public void debug(String msg, Throwable e) { if (debug(msg)) { println(e); } } public boolean info(String msg) { if (checkAllowed(LogLevel.INFO)) { println(this.formatLog(LogLevel.INFO) + msg); return (true); } return (false); } public void info(String msg, Throwable e) { if (info(msg)) { println(e); } } public boolean warning(String msg) { if (checkAllowed(LogLevel.WARNING)) { println(this.formatLog(LogLevel.WARNING) + msg); return (true); } return (false); } public void warning(String msg, Throwable e) { if (warning(msg)) { println(e); } } public boolean error(String msg) { if (checkAllowed(LogLevel.ERROR)) { println(this.formatLog(LogLevel.ERROR) + msg); return (true); } return (false); } public void error(String msg, Throwable e) { if (error(msg)) { println(e); } } } </code></pre> <p>And finally here is the FileHandler class:</p> <pre class="lang-java prettyprint-override"><code>public class FileHandler { private static Logger logger = LogManager.getLogger(FileHandler.class.getName()); private String fileName, filePath; private File file; public PrintWriter out; private BufferedReader bufferedReader; private boolean append, autoFlush = true; /** * * @param fileName Needs to have the name of the file with the file extension * included * @param filePath The complete path to the file or relative ./ * @throws IOException */ public FileHandler(String fileName, String filePath) throws IOException { this.fileName = fileName; this.filePath = filePath; this.file = new File(filePath + fileName); if (!checkFileExists()) { file.createNewFile(); } this.append = false; } /** * setAppend Needs To Be Called Before Initializing Writer If The File Already * Exists. Otherwise It Will Overwrite The End Of The File. * * @throws IOException */ public void initializeWriter() throws IOException { if (!checkFileExists()) { logger.debug("File Dose Not Exist Creating: " + filePath + fileName); file.createNewFile(); } out = new PrintWriter(new FileOutputStream(file, append)); } public void initializeReader() throws IOException { File file = new File(filePath + fileName); bufferedReader = new BufferedReader(new FileReader(file)); } public boolean checkFileExists() { return file.exists(); } public void write(String line) throws IOException { if (out == null) { new Exception("Buffered Writer Not Initialized.").printStackTrace(); return; } System.out.println("ss"); out.println(line); } public String readLine() throws IOException { if (bufferedReader == null) { new Exception("Buffered Writer Not Initialized.").printStackTrace(); return null; } return bufferedReader.readLine(); } public void destroy() { this.finalize(); } @Override public void finalize() { try { super.finalize(); out.close(); bufferedReader.close(); } catch (Throwable e) { logger.error("Unable to finalize file handler.", e); // e.printStackTrace(); } } public static Logger getLogger() { return logger; } public static void setLogger(Logger logger) { FileHandler.logger = logger; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } public BufferedReader getBufferedReader() { return bufferedReader; } public void setBufferedReader(BufferedReader bufferedReader) { this.bufferedReader = bufferedReader; } public PrintWriter getOut() { return out; } public void setOut(PrintWriter out) { this.out = out; } public void setAppend(boolean append) { this.append = append; } /** * @return the autoFlush */ public boolean isAutoFlush() { return autoFlush; } /** * @param autoFlush the autoFlush to set */ public void autoFlush() { this.autoFlush = true; } } </code></pre> <p>Here is a link to the full package on my github page: <a href="https://github.com/abinash18/JavaGameEngineBackup" rel="nofollow noreferrer">github</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T15:46:24.833", "Id": "436375", "Score": "2", "body": "For common aspects, such as logging, I would never re-invent the wheel. There are mature frameworks available that are not at end of lifecycle and provide lots of customization and extension points." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T15:48:55.200", "Id": "436376", "Score": "0", "body": "yes of course but is this a good attempt at this, I know that I can flush the print writer all the way at the end of the program but how would I do so if terminates or crashed without the proper call to the stop method" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T15:49:59.077", "Id": "436377", "Score": "1", "body": "Ok if you want to use a custom logger, perhaps you should tag your question with 'reinventing-the-wheel' to avoid comments like mine :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T15:51:41.353", "Id": "436379", "Score": "1", "body": "oh thanks I'm pretty new to stack exchange so didn't know you could have a tag like that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T20:13:41.870", "Id": "436581", "Score": "0", "body": "Question for floor. OP ask about the possibility of multithreading. Generally, wouldn’t this be pointless assuming you are logging to the same file? I know I’ve seen spark applications that remedy this bottleneck by writing to an hdfs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T00:37:25.580", "Id": "436762", "Score": "1", "body": "@JosephWood it's actually a problem **because** you're writing to the same file. Without concurrency control, log entries could be interleaved. You generally want to avoid that. In addition most OSes will bundle writes by committing to RAM and then writing larger chunks at once. This may or may not alleviate log entry interleaving. If your bottleneck is logging, you're logging too much anyways..." } ]
[ { "body": "<h1>Implementation</h1>\n\n<h2>Simple fixes</h2>\n\n<p>The following section contains a handful of simple fixes that I won't really justify much, see them as quickfire opinions:</p>\n\n<ul>\n<li>Make the type of a field (or variable) declaration as high up the hierarchy as possible. This means <code>HashMap</code> should be <code>Map</code>, <code>ArrayList</code> should be <code>List</code> and so on.</li>\n<li>Use the diamond operator for initializations with generics. <code>new HashMap&lt;String, Logger&gt;()</code> turns into <code>new HashMap&lt;&gt;()</code> that way. This is not always available.</li>\n<li>Have an empty line between method bodies.</li>\n<li>Use guard clauses to reduce the level of nesting with early returns. e.g. in <code>addFileHandler</code> start with:\n\n<pre><code>if (fileHandler != null) { \n return;\n}\n</code></pre>\n\n<ul>\n<li>The same advice as for declaration types applies for method return types. You generally don't want to have a specific type returned if you can use an interface.</li>\n<li>Do not put parentheses around return values. They are not performing an actual function in that manner.</li>\n<li><code>finnest</code> should be spelled <code>finest</code> in <strong>all</strong> instances.</li>\n<li>A filed should be declared on it's own line every time.</li>\n</ul></li>\n</ul>\n\n<h2>Not so simple fixes</h2>\n\n<p>This section goes a bit more into depth. The changes suggested here require a more intimate familiarity with the Java libraries. A lot of the suggestions can carry over to other languages as well, though.</p>\n\n<p><code>getLogger</code> should make use of <code>computeIfAbsent</code>, which drastically simplifies the code to:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>return loggers.computeIfAbsent(className, name -&gt; {\n Logger result = new Logger(name);\n if (fileHandler != null) { \n result.setOutputForLogFile(fileHandler.out);\n }\n return result;\n});\n</code></pre>\n\n<p>Notice that we don't need to check for the presence of the key (<code>containsKey</code>) and we don't need to manually put the result into the map either.</p>\n\n<p>Carrying on to <code>addFileHandler</code> I personally would add an additional empty line before the <code>for</code> loop, just to separate it from the rest.</p>\n\n<p>Moving on to the allowedLevels operations.<br>\nThe semantics you are looking for here (no duplicates, quick <code>contains</code> check) are best encapsulated in a <code>Set</code>. Changing <code>allowedLevels</code> to be a <code>Set&lt;LogLevel&gt;</code> would vastly simplify your code (and speed it up) since you don't need to perform contains-checks (which are <strong>linear</strong> in an ArrayList) to avoid duplicate items. The implementations simplify to:</p>\n\n<pre><code>addAllowedLevel(LogLevel l) { allowedLevels.add(l); }\nremoveAllowedLevel(LogLevel l) { allowedLevels.remove(l); }\nisLevelAllowed(LogLevel l) { return allowedLevels.contains(l); }\n</code></pre>\n\n<hr>\n\n<p>Now we can take a look at <code>Logger</code>.</p>\n\n<p>The first thing I noticed is that your Logger can change output. Generally you wouldn't want to expose that kind of capability to the user, especially not in a multithreaded environment. Results can be somewhat unpredictable.</p>\n\n<p>Next I noticed that <code>log</code> does <strong>not</strong> perform any kind of checking whether logging is enabled at all. If no log-level were allowed, <code>log</code> should not be writing any output. Unfortunately it does...</p>\n\n<p><code>checkAllowed</code> can be simplified to directly return the condition you specified.\nNote also that the check you implemented there does not account for the typical use-case of hierarchical log-levels. I'd expect WARN and ERROR messages to be logged when I allow the INFO level. In your implementation I'd explicitly need to specify that all the log levels of INFO and higher priority are allowed. </p>\n\n<p>Additionally you're not accounting for the idea of different loggers being configured differently wrt. the logging level they have.</p>\n\n<p>Sidenote: you're abusing a boolean return of the overloads without Throwable to implement the overloads with throwable. This is somewhat ugly because you're exposing internal behaviours to external consumers.</p>\n\n<p>also: <code>formatLog</code> should be implemented in terms of <code>String.format</code> like so:</p>\n\n<pre><code> return String.format(\"[%s] [%s] %s: \", LogManager.getCurrentTimeAndDate(), name, l);\n</code></pre>\n\n<hr>\n\n<p>Lastly a quick look at <code>FileHandler</code> before comparing this to a logging library like Log4J.</p>\n\n<p>You're not actually using <code>autoFlush</code>, it doesn't change any behaviour whether it's enabled or not.\nRemove unused fields.</p>\n\n<p>In addition your code should be using the <code>java.nio.file</code> API instead of the <code>java.io.file</code> API (which is predating the nio API by almost a decade).</p>\n\n<p><code>fileName</code>, <code>filePath</code> and <code>file</code> could (and should) be declared as <code>final</code>. They are not expected to ever change. In fact, <code>fileName</code> and <code>filePath</code> are only used in the constructor and shouldn't be fields at all.</p>\n\n<p>It's most likely also a bad idea to have a Reader <strong>and</strong> a Writer open on the same file. Results from concurrent operations and non-flushed operations are very likely to be unpredictable and / or dangerous.</p>\n\n<p>Exposing getters and setters for the writer, reader and file is a bad idea as well. It allows external consumer to change the internal state of your class in ways that you don't want to have.</p>\n\n<h1>Comparison to existing logging libraries</h1>\n\n<p>Let me put it like this: You're not coming away in a good shape from this comparison.\nA large number of almost necessary features is completely missing from your implementation. Here some examples:</p>\n\n<ul>\n<li>Log-Level definitions depending on the package </li>\n<li>Log-Format customizations</li>\n<li>Hierarchical Log-Level behaviour</li>\n<li>Multi-Backend logging (one logger logging to multiple places)</li>\n<li>Log-Message formatting with arbitrary parameters</li>\n<li>Basic Threadsafety</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T16:35:10.390", "Id": "436385", "Score": "0", "body": "I was about to answer, when I saw '1 new answer'. There isn't much I could add to this one :p This will make my answer considerably shorter" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T17:08:06.020", "Id": "436392", "Score": "0", "body": "Most of the things you said were right and i had fixed most of these last night before this question was migrated here, and i was afk for a while so I didn't have time to properly edit the post. Thanks for the response. I will defiantly take your advice , it was very in depth. About the Map and List changes I heard that Hash map was faster Than map. And about the compute if absent that completely got out of my mind while i was doing this thanks." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T16:33:30.917", "Id": "224911", "ParentId": "224905", "Score": "4" } }, { "body": "<h2>Usage</h2>\n\n<p>Determining whether to log for a given level requires a comparison <code>level &gt;= minimumConfiguredLevel</code> (pseudo code) rather than an exact match or check against a set of preconfigured levels.</p>\n\n<h2>Thread-Safety</h2>\n\n<p>None of the methods are thread-safe. This could impact the state of <code>LogManager</code>, <code>Logger</code> and the file you are writing to.</p>\n\n<h2>Consistency</h2>\n\n<p>You provide 2 methods that do exactly the same.</p>\n\n<blockquote>\n<pre><code>public static void setLogLevel(LogLevel l) {\n currentLevel = l;\n}\n\npublic static void setCurrentLevel(LogLevel currentLevel) {\n LogManager.currentLevel = currentLevel;\n}\n</code></pre>\n</blockquote>\n\n<h3>API Integrity</h3>\n\n<p>You can set a level that is not allowed.</p>\n\n<blockquote>\n<pre><code>public static boolean isLevelAllowed(LogLevel l) {\n if (allowedLevels.contains(l)) {\n return (true);\n }\n return (false);\n}\n\npublic static void setLogLevel(LogLevel l) {\n currentLevel = l;\n}\n</code></pre>\n</blockquote>\n\n<p>In addition:</p>\n\n<ul>\n<li>exceptions during logging that aren't <code>IOException</code> make your calling code having to deal with them</li>\n<li>the calling thread is impacted by the logging (flushing to file all the time).</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T17:11:38.113", "Id": "436393", "Score": "0", "body": "Thanks for responding, i still don't understand what you mean by thread safety i am still a beginner so i don't know that much. And About the flush every write i have fixed that and it is now happens when the program exits. But how would I do this if it crashes or I terminate it without calling the proper stop method" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T17:13:03.930", "Id": "436394", "Score": "0", "body": "your methods are not _synchronized_: read about this here: https://stackoverflow.com/questions/21812396/what-is-the-use-of-static-synchronized-method-in-java/21812453" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T17:57:42.390", "Id": "436405", "Score": "0", "body": "but doesn't synchronizing a method only let it be called once and not multiple times?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T17:58:51.990", "Id": "436407", "Score": "0", "body": "One at a time, if multiple threads race to get access to it: https://www.baeldung.com/java-synchronized" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T18:28:32.823", "Id": "436412", "Score": "0", "body": "That's way to complicated for what I was trying to achieve, I honestly just wanted a simple logging program that could log what I sent it. Anyways the thread safety doesn't really matter in my application anyways so ill take the rest of your advice thanks." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T16:43:49.013", "Id": "224913", "ParentId": "224905", "Score": "2" } } ]
{ "AcceptedAnswerId": "224913", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T01:52:24.877", "Id": "224905", "Score": "6", "Tags": [ "java", "multithreading", "reinventing-the-wheel", "logging" ], "Title": "Would log4j be more efficient to utilize than the logger I implemented (Code Below)?" }
224905
<p>There is a follow up question <a href="https://codereview.stackexchange.com/questions/225051/linny-continued-language-development">here</a>.</p> <p>I've undertaken the project of creating my own programming language, <strong>Linny</strong>. It's a very, very simple language, with only variable creation, variable changing, and outputting to the console, but I've very proud of it. It's an interpreted language, with the interpreter being written in Python 3. The interpreter is really a hybrid of a compiler/interpreter. I can't really say where I got the idea for the syntax, I just meshed a bunch of ideas from a wide range of languages and that's what I got. I want as much criticism and nitpick as you can find. From performance to readability to bugs, anything.</p> <p><strong>How it works</strong></p> <p>You write a program in <strong>Linny</strong>, with the file extension <strong>.linny</strong>. You set the path to the file in the source code, and you run it. You can also uncomment the bottom part in the main guard, comment out the <code>for line in lines: interpret(line)</code> part, and you'll be able to input line by line commands like Python.</p> <p><strong>Syntax (sample file, script.linny)</strong></p> <pre><code>string text = "Hello" ; // semicolon MUST be one space away from ending text = "Hello_There!" ; out text ; // "out" outputs the variable to the screen type text ; // "type" returns the type of variable (integer, string, etc) boolean food = false ; out food ; type food ; integer num = 16 ; out num ; type num ; float f = 14.2 ; out f ; type f ; </code></pre> <p><strong>The Interpreter</strong></p> <pre><code>""" This program compiles and interprets programs written in `Linny` """ def interpret(line_of_code): """Interprets user inputed Linny code """ words = line_of_code if isinstance(words, str): words = words.split() #Basic empty line check if words == []: return #Comment check if "//" in words[0]: return #Interpret mode begin #If user wants to output a value if len(words) == 3 and \ words[0] == "out" and \ already_defined(words[1]) and \ words[2] == ";": print(VARIABLES[words[1]]['value']) return #If user wants to get the type of value if len(words) == 3 and \ already_defined(words[1]) and \ words[0] in MISC_KEYWORDS and \ words[2] == ";": if words[0] == "type": print(VARIABLES[words[1]]['data_type']) return #If user wants to create a value if len(words) == 5 and words[4] == ";": add_to_variables( name=words[1], value=words[3], data_type=words[0], line_number=0 ) return #If user wants to edit a value if len(words) == 4 and words[3] == ";": change_value(words[0], words[2]) return #Interpret mode end def change_value(variable, new_value): """ Changes the value of the variable to the `new_value` """ data_type = VARIABLES[variable]['data_type'] if data_type == "integer": VARIABLES[variable]['value'] = int(new_value) elif data_type == "string": VARIABLES[variable]['value'] = str(new_value) elif data_type == "float": VARIABLES[variable]['value'] = float(new_value) elif data_type == "boolean": if new_value == "true": VARIABLES[variable]['value'] = True elif new_value == "false": VARIABLES[variable]['value'] = False else: exit(f"Cannot assign boolean value to {new_value}") elif data_type == "char": if len(new_value) == 1: VARIABLES[variable]['value'] = chr(new_value) else: exit(f"char can only be one character long, not {new_value}!") else: exit(f"Not a data type") def add_to_variables(name, value, data_type, line_number): """ Checks `data_type` of passed variable, and adds it to list of variables """ if data_type == "integer": VARIABLES[name] = {'value': int(value), 'data_type': data_type} elif data_type == "string": VARIABLES[name] = {'value': value, 'data_type': data_type} elif data_type == "float": VARIABLES[name] = {'value': float(value), 'data_type': data_type} elif data_type == "boolean": if value == "true": VARIABLES[name] = {'value': True, 'data_type': data_type} elif value == "false": VARIABLES[name] = {'value': False, 'data_type': data_type} else: exit(f"SyntaxError: Expected boolean true/false on line {line_number}") elif data_type == "char": VARIABLES[name] = {'value': chr(value), 'data_type': data_type} else: exit(f"SyntaxError: {data_type} is not a valid data type on line {line_number}") def variable_syntax_check(line_number, line): """ Returns if the syntax is correct in the passed `line` """ words = line.split() if words == []: return if words[0] in list(VARIABLES.keys()): #Check if next word is = if words[1] == "=": #Check if last index that holds ; exists #try: # words[len(words - 1)] = words[len(words - 1)] #except IndexError: # exit(f"SyntaxError: Expected ; at end of line {line_number}") if words[3] == ";": add_to_variables( name=words[0], value=words[2], data_type=VARIABLES[words[0]['data_type']], line_number=line_number ) else: exit(f"SyntaxError: Expected ; at end of line {line_number}") #Check if keyword is first argument, or variable has already been defined if words[0] in VARIABLE_KEYWORDS: #Check if variable hasn't already been defined if words[1] not in VARIABLES.keys(): #Check if next word is '=' if words[2] == "=": #Check if ending is ; try: words[4] = words[4] except IndexError: exit(f"""SyntaxError: Excepted ; at end of line {line_number}""") if words[4] == ";": #Call method and pass relevent information to add to variables add_to_variables( name=words[1], value=words[3], data_type=words[0], line_number=line_number ) else: exit(f"SyntaxError: Excepted ; at end of line {line_number}") else: exit(f"SyntaxError: Expected '=' on line {line_number}") else: exit(f"SyntaxError: Variable {words[1]} has already been defined.") else: exit(f"SyntaxError: Variable {words[0]} has not been defined.") def if_logic_syntax_check(statement): """ Determines if the syntax is correct for the if statement """ expression = statement[0].split() #Determine is logic statements are correct if expression[0] in LOGIC_KEYWORDS and \ expression[2] in LOGIC_KEYWORDS and \ expression[4] in LOGIC_KEYWORDS: #Now check if variable names are correct if already_defined(expression[1]) and already_defined(expression[3]): return else: if not already_defined(expression[1]) and already_defined(expression[3]): exit(f"SyntaxError: {expression[1]} has not been defined yet.") if already_defined(expression[1]) and not already_defined(expression[3]): exit(f"SyntaxError: {expression[3]} has not been defined yet.") if not already_defined(expression[1]) and not already_defined(expression[3]): exit(f"SyntaxError: {expression[1]} and {expression[3]} have not been defined.") else: exit(f"SyntaxError: Logic keyword not spelled correctly / not included.") #Now check the body del statement[0], statement[len(statement) - 1] for i in range(len(statement)): if not statement[i][:1] == "\t": exit(f"SyntaxError: Inconsistent Tabbing") def parse_if(index, lines): """ Returns the if statement at the place in the file """ statement = [] for i in range(index, len(lines)): if lines[i][0] != "endif": statement.append(lines[i]) else: break return statement def to_list(file): """ Converts the lines in the source file to a list""" lines = [] with open(file, "r") as file_: for line in file_: if line[len(line) - 1] == "\n": lines.append(line[:len(line) - 1]) else: lines.append(line) return lines def compile_file(source_file): """ Starts compiling process """ lines = to_list(source_file) for line_number, line in enumerate(lines): if line != "": if is_variable(line.split()[0]): variable_syntax_check(line_number + 1, line) if line.split()[0] == "if": if_logic_syntax_check(parse_if(line_number, lines)) print("Code compiles!") def is_variable(word): """ Determines if the passed word is a/possibly can be a variable """ return word in VARIABLE_KEYWORDS and word not in LOGIC_KEYWORDS and word not in FUNC_KEYWORDS def already_defined(variable): """ Returns if the variable has already been defined """ return variable in list(VARIABLES.keys()) if __name__ == '__main__': #Dict of variables that have been initialized in the program VARIABLES = {} FUNCTIONS = {} VARIABLE_KEYWORDS = ["integer", "string", "float", "boolean", "char"] LOGIC_KEYWORDS = ["if", "endif", "else", "while", "for", "then", "equals", "greaterthan", "lessthan"] FUNC_KEYWORDS = ["func", "endfunc"] MISC_KEYWORDS = ["type"] ALL_KEYWORDS = VARIABLE_KEYWORDS + LOGIC_KEYWORDS + FUNC_KEYWORDS + MISC_KEYWORDS SOURCE_FILE = "Code/Python/Linny/script.linny" lines = to_list(SOURCE_FILE) for line in lines: interpret(line) """ print("[Linny Interpreter]") print("Enter in one line of code at a time!") while True: code = input("&gt;&gt;&gt; ") variable_syntax_check(0, code) """ </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T18:26:22.703", "Id": "436411", "Score": "2", "body": "I see some keywords reserved for flow control and function definition, but don't see them used anywhere. It seems like this language isn't quite ready to \"progam\" anything. A good test of readiness might be an implementation of a [Turing machine](https://en.wikipedia.org/wiki/Turing_machine) -- if you can implement one, then you can theoretically compute \"anything.\" Beyond that, it might be good to identify scenarios where your language is particularly useful (that is, goal of language design shouldn't be ability to construct a TM; focus could be on solving a class of problems)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T18:06:52.390", "Id": "436719", "Score": "1", "body": "You may want to indicate in this question that there is a follow-up (with link). -> two-way question reference" } ]
[ { "body": "<p>I'm just going to take a look at the <code>interpret</code> function for now at least. I'm also up for suggestions to improve the review as I've not had a lot of time to go through it.</p>\n\n<h3>The Interpret Function</h3>\n\n<p>To start off, the function is doing two things; it's splitting the <code>line_of_code</code> into tokens(rather strictly for a programming language) and then interpreting it. This function should probably be split into two; a tokenizing function and the actual interpreter, I'll elaborate later.</p>\n\n<p>As a bit of a tangent, most programming language would--after tokenization, create what's called an an Abstract Syntax Tree(AST) to validate code and also because things like an if statement can have a \"body\"; code nested inside of it which makes it a tree. This is enforced in Python by a visual indent, Linny does not appear to have a tree structure though. This would be a good place to begin if expanding the language as this limits the language.</p>\n\n<p>Generally, your interpret function is overall much too permissive in several places because it doesn't check every token, and the method begins with checks that are subtly wrong;</p>\n\n<ul>\n<li><p><code>words</code> is a misleading name--for a programming language they are more like tokens that Linny seems to guarantee are delimited by spaces(most languages, like Python do not).</p></li>\n<li><p><code>words</code>' type is not guaranteed to be an array by the time you check <code>words == []</code>, not unless it is passed as a string or already is an array. You'll likely want to just check that it's passed a string and raise an exception if it is not, or simply use type hints instead. Note that type <em>hints</em> aren't automatically enforced, they're there to explain to a user what the function does, ex <code>def interpret(line_of_code: str)</code> explains for a user that the code will probably error if it isn't a string.</p></li>\n<li><p><code>\"//\" in words[0]</code> will think text like <code>foo//bar</code> is <em>all</em> a comment(i.e. foo would be assumed to be a comment, not only bar) because <code>in</code> looks \"in\" the whole string. You probably want <code>words[0].startswith(\"//\")</code> for naïve approaches, but if comments are allowed without whitespace before it as the <code>foo//bar</code> example shows, more work would have to be done.</p></li>\n</ul>\n\n<blockquote>\n <p><strong>Note:</strong> All of the above code I've covered should probably be put into a function such as <code>tokenize</code>. This is so that you can create more advanced logic later and leave the <code>interpret</code> function with a single responsibility.</p>\n</blockquote>\n\n<p>The next component, the actual interpreting also has a few flaws, the most broad is that it is overall a bit hard to read/understand because of the lack of an AST. Passing in an AST to interpret it, instead of working with raw tokens, would allow the logic for parsing which command to be simplified. Overall this seems to be a reoccurring theme.</p>\n\n<p>The out command, annotated:</p>\n\n<pre><code># You commented the next line. It'd probably be better as: \"out command\" or something more descriptive.\n# You also should add a space after the \"#\"; it's the typical Python style.\n#If user wants to output a value\nif len(words) == 3 and \\ # This is probably too strict, unless you enforce one command per line.\n # Secondly, this could be added to a tokenize function.\n words[0] == \"out\" and \\ # NOTE: In an AST this would be the node name\n already_defined(words[1]) and \\ # no error happens if it isn't already defined.\n words[2] == \";\": # The tokenize function could handle this; expect a semicolon and strip it off.\n print(VARIABLES[words[1]]['value'])\n return\n</code></pre>\n\n<p>These notes apply to most, but now for the unique reviews of each one:</p>\n\n<p>For the type command, you have the checks in a bit of a weird order. You should check the tokens in number order. Also, your nested check <code>words[0] == \"type\"</code> makes your <code>words[0] in MISC_KEYWORDS</code> check redundant; you should just use the <code>words[0] == \"type\"</code> because if <code>word[0] == \"type\"</code>, <code>word[0]</code> must be in <code>MISC_KEYWORDS</code> because it's a constant(by convention) and <code>\"type\"</code> is in <code>MISC_KEYWORDS</code>, in fact it's the only item. Those constants, such as <code>MISC_KEYWORDS</code> do actually seem to be a start towards a more versatile AST or language grammar, which is great.</p>\n\n<p>Your <code>set</code> command is very flawed in its check. It only verifies that it has 5 tokens and ends with a semicolon; <code>foo bar lorem ipsum ;</code> would make your program think it's a set command. There may be checking in <code>add_to_variables</code>, but that sort of check should go in a tokenizer anyways. Then you could be passed something like <code>command</code> and check <code>command.name</code> instead.</p>\n\n<p>Your next command, <code>edit</code> has a similar issue; it doesn't check anything except a semi-colon before trying to use it. If you ever expand your program this will be an issue because if anything has 5 or 4 tokens your code as is will believe it is a <code>set</code> or <code>edit</code> command(as I've dubbed them).</p>\n\n<p>Lastly... your program just ends after this. If I give it <code>foobar lorem ipsum//this is incredibly invalid ; 12fasdf</code> the <code>interpret</code> function will just do nothing with it, at minimum a user would expect feedback that \"this is invalid\". This'd be something to catch at the tokenization stage; nothing invalid should ever be possible to feed to the interpreter function unless run directly(which it shouldn't be).</p>\n\n<p>Here's what this looks like all together, and plus a little bit.</p>\n\n<pre><code>def tokenize(line_of_code: str):\n \"\"\"Tokenizes Linny code \"\"\"\n\n # Now it's more obvious what you're doing; you're checking for an empty line.\n if line_of_code == \"\":\n return\n\n # Everything is a comment.\n if line_of_code.startswith(\"//\"):\n return\n\n tokens = tokens.split() # They were warned with the type hint, you can always be more friendly and type check though.\n # There is *way* more you could do here though, like most of the command checking etc. It's just a lot more to change so I didn't.\n\n return tokens\n\n\ndef interpret(tokens):\n \"\"\"Interprets Linny tokens\"\"\"\n\n # Out command\n if len(tokens) == 3 and \\\n tokens[0] == \"out\" and \\\n already_defined(tokens[1]) and \\\n tokens[2] == \";\":\n print(VARIABLES[tokens[1]]['value'])\n return\n\n # Type command\n if len(tokens) == 3 and \\\n tokens[0] == \"type\":\n already_defined(tokens[1]) and \\\n tokens[2] == \";\":\n print(VARIABLES[tokens[1]]['data_type'])\n return\n\n # Create a variable\n if len(tokens) == 5 and \\\n tokens[0] in VARIABLE_KEYWORDS and \\\n # no check for the name (seemingly) needed.\n tokens[2] == \"=\" and \\\n tokens[4] == \";\":\n add_to_variables(\n name=tokens[1],\n value=tokens[3],\n data_type=tokens[0],\n line_number=0 # The line number probably shouldn't always be zero, or be in the function either way.\n )\n return\n\n # Edit a variable\n if len(tokens) == 4 and \\\n is_variable(tokens[0]) == \"\" and \\\n tokens[1] == \"=\" and \\\n # is valid... value?\n tokens[3] == \";\":\n change_value(tokens[0], tokens[2])\n return\n\n # No valid commands... what should *you* do?\n\n</code></pre>\n\n<blockquote>\n <p><strong>Note:</strong> Writing a whole language is a complicated beast. I have suggested some (simplified) tips that real languages follow, but this review could spiral into minute details not seemingly to accord with the expected level of responses. I'd suggest finding some good books or articles on programming languages it if you're interesting in making a more complete one, but acquiring more programming skills would also be valuable to do prior.</p>\n</blockquote>\n\n<p>P.S. The type things in and get a result back style of coding that you describe is called a Read-eval-print loop or a <code>REPL</code>--that's (mostly) what you've made in your code.</p>\n\n<p>P.P.S. A formatter and a linter wouldn't hurt if you don't already have one.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T18:29:59.897", "Id": "224921", "ParentId": "224907", "Score": "9" } } ]
{ "AcceptedAnswerId": "224921", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T15:34:32.540", "Id": "224907", "Score": "8", "Tags": [ "python", "python-3.x", "language-design", "linny" ], "Title": "Linny: An Interpreted Programming Language" }
224907
<p>here is a code of a simple contact form that I have created, I believe that the form is <em>server-side</em> protected against empty fields, header injections, CSRF, XSS, bots using 'Google reCAPTCHA v3' and so on.. The call is done through AJAX.. I just wanted to share this code and I am open to any suggestions that can improve the security and the speed of the site.. also I wonder if there will be any extra useful meta tags to be used.. you can check the live site that I am working on <a href="https://www.rainbow-parenting.com" rel="nofollow noreferrer">here</a></p> <p>Thank you..</p> <p><strong>index.php</strong></p> <pre><code>&lt;?php session_start(); ?&gt; &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;title&gt;Rainbow Parenting&lt;/title&gt; &lt;link rel="apple-touch-icon" sizes="180x180" href="icon/apple-touch-icon.png"&gt; &lt;link rel="icon" type="image/png" sizes="32x32" href="icon/favicon-32x32.png"&gt; &lt;link rel="icon" type="image/png" sizes="16x16" href="icon/favicon-16x16.png"&gt; &lt;link rel="manifest" href="icon/site.webmanifest"&gt; &lt;link rel="mask-icon" href="icon/safari-pinned-tab.svg" color="#5bbad5"&gt; &lt;meta name="msapplication-TileColor" content="#da532c"&gt; &lt;meta name="theme-color" content="#ffffff"&gt; &lt;meta name="apple-mobile-web-app-capable" content="yes"&gt; &lt;meta name="keywords" content="..."&gt; &lt;meta name="description" content="..."&gt; &lt;meta name="subject" content="..."&gt; &lt;meta name="robots" content="index, follow"/&gt; &lt;meta name="author" content="..."&gt; &lt;link rel="canonical" href="https://www.rainbow-parenting.com"&gt; &lt;meta property="og:locale" content="en_US" /&gt; &lt;meta property="og:type" content="website"&gt; &lt;meta property="og:url" content="https://www.rainbow-parenting.com"&gt; &lt;meta property="og:title" content="..."&gt; &lt;meta property="og:description" content="..."&gt; &lt;meta property="og:image" content="https://www.rainbow-parenting.com/img/logo-temp.png"&gt; &lt;!-- Latest compiled and minified CSS --&gt; &lt;link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"&gt; &lt;!-- Theme style --&gt; &lt;link rel="stylesheet" href="css/style-temp.min.css"&gt; &lt;!-- Normalize --&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" &gt; &lt;!-- Animations --&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.min.css"&gt; &lt;!-- Font Awesome --&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css"&gt; &lt;!-- Google Fonts --&gt; &lt;link href="https://fonts.googleapis.com/css?family=Notable" rel="stylesheet"&gt; &lt;link href="https://fonts.googleapis.com/css?family=Mali" rel="stylesheet"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div class="row text-center"&gt; &lt;div class="col"&gt; &lt;img class="animated bounce shake" alt="Logo" src="img/logo-temp.png" width="150" height="auto"&gt; &lt;div&gt;&lt;br&gt; &lt;h1 class="animated bounce infinite"&gt;COMING SOON!!&lt;/h1&gt; &lt;h2 class="animated flipInX"&gt;We will be launching our new website in:&lt;/h2&gt; &lt;div class="simply-countdown simply-countdown-one animated rollIn"&gt;&lt;/div&gt; &lt;h3 class="animated flash"&gt;in the meanwhile you can still contact us by clicking the button below&lt;/h3&gt; &lt;/div&gt; &lt;div class="text-center animated jello"&gt; &lt;button class="button-temp button-temp1" id="btn-show-modal" data-toggle="modal" data-target="#modalContactForm"&gt;Contact Us&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="modal fade" id="modalContactForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"&gt; &lt;div class="modal-dialog modal-dialog-centered" role="document"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-body"&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-label="Close"&gt;&lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt;&lt;/button&gt;&lt;br&gt; &lt;form id="contactForm" name="sentMessage" novalidate="novalidate" method="post"&gt; &lt;div class="row"&gt; &lt;div class="control-group"&gt;&lt;i class="fas fa-user big-icon"&gt;&lt;/i&gt; &lt;fieldset&gt; &lt;input class="modal-input" type="text" id="name" placeholder=" " tabindex="1" required="required" data-validation-required-message="• Please enter your name." minlength="5" maxlength="20" pattern="[A-Za-z ]+" data-validation-pattern-message="Only letters &amp; whiteapces."&gt; &lt;span class="inputup"&gt;Your Name:&lt;/span&gt; &lt;/fieldset&gt;&lt;p class="help-block text-danger"&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="control-group"&gt;&lt;i class="fas fa-envelope big-icon"&gt;&lt;/i&gt; &lt;fieldset&gt; &lt;input class="modal-input" type="email" id="email" placeholder=" " tabindex="2" required="required" data-validation-required-message="• Please enter your email address."&gt; &lt;span class="inputup"&gt;Your Email:&lt;/span&gt; &lt;/fieldset&gt;&lt;p class="help-block text-danger"&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="control-group"&gt;&lt;i class="fas fa-phone big-icon"&gt;&lt;/i&gt; &lt;fieldset&gt; &lt;input class="modal-input" type="tel" id="phone" placeholder=" " tabindex="3" required="required" data-validation-required-message="• Please enter your phone number." maxlength="10" minlength="9" pattern="[0-9]+" data-validation-pattern-message="Only numbers."&gt; &lt;span class="inputup"&gt;Your Phone:&lt;/span&gt; &lt;/fieldset&gt;&lt;p class="help-block text-danger text-center"&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="control-group"&gt;&lt;i class="fas fa-pencil-alt big-icon align-top"&gt;&lt;/i&gt; &lt;fieldset&gt; &lt;textarea class="modal-input" id="message" placeholder=" " tabindex="4" required="required" data-validation-required-message="• Please enter a message." minlength="20" maxlength="1000"&gt;&lt;/textarea&gt; &lt;span class="inputup"&gt;Type Your Message Here:&lt;/span&gt; &lt;/fieldset&gt;&lt;p class="help-block text-danger text-center"&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php if (empty($_SESSION['key'])) $_SESSION['key'] = bin2hex(random_bytes(32)); //create CSRF Token $_SESSION['sec'] = hash_hmac('sha256', 'hi there : index.php', $_SESSION['key']); ?&gt; &lt;input type="hidden" id="token" value="&lt;?=$_SESSION['sec']?&gt;"&gt; &lt;div class="row"&gt; &lt;div class="control-group"&gt; &lt;button id="sendMessageButton" class="button-temp button-temp2" type="submit" name="submit" tabindex="5" data-submit="...Sending"&gt;Send &lt;i class="fas fa-paper-plane"&gt;&lt;/i&gt; &lt;/button&gt; &lt;div id="success"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response"&gt; &lt;/form&gt; &lt;/div&gt; &lt;div class="modal-footer justify-content-center"&gt; &lt;button class="button-temp button-temp3" data-dismiss="modal" aria-hidden="true"&gt;close&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- jQuery library --&gt; &lt;script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;!-- Popper JS --&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;!-- Latest compiled JavaScript --&gt; &lt;script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;!-- jqBootstrapValidation --&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jqBootstrapValidation/1.3.6/jqBootstrapValidation.min.js"&gt;&lt;/script&gt; &lt;script src="js/temp-contact_me.min.js"&gt;&lt;/script&gt; &lt;script&gt; $(function(){ $('#modalContactForm').on('shown.bs.modal', function () { $('#name').focus() }); }); &lt;/script&gt; &lt;script src="https://www.google.com/recaptcha/api.js?render=..." data-cfasync="false" async defer&gt;&lt;/script&gt; &lt;script data-cfasync="false" async defer&gt; grecaptcha.ready(function() { grecaptcha.execute('...', { action: 'homepage'}).then(function(token) { //console.log(token); // add token value to form document.getElementById('g-recaptcha-response').value = token; }); }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>temp-contact_me.js</strong></p> <pre><code>$(function() { $("#contactForm input,#contactForm textarea").jqBootstrapValidation({ preventSubmit: true, submitError: function($form, event, errors) { //alert('There was some error performing the AJAX call!'); // additional error messages or events }, submitSuccess: function($form, event) { event.preventDefault(); // prevent default submit behaviour // get values from FORM var name = $("input#name").val(); var email = $("input#email").val(); var phone = $("input#phone").val(); var message = $("textarea#message").val(); var token = $("input#token").val(); var captcha = $("input#g-recaptcha-response").val(); var firstName = name; // For Success/Failure Message // Check for white space in name for Success/Fail message if (firstName.indexOf(' ') &gt;= 0) { firstName = name.split(' ').slice(0, -1).join(' '); } $this = $("#sendMessageButton"); $this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages $.ajax({ url: "././mail/temp-contact_me.php", type: "POST", data: { name: name, phone: phone, email: email, token: token, captcha: captcha, message: message }, cache: false, success: function(data) { console.log(data) // Success message $('#success').html("&lt;div class='alert alert-success'&gt;"); $('#success &gt; .alert-success').html("&lt;button type='button' class='close' data-dismiss='alert' aria-hidden='true'&gt;&amp;times;") .append("&lt;/button&gt;"); $('#success &gt; .alert-success') .append("&lt;strong&gt;Your message has been sent. &lt;/strong&gt;"); $('#success &gt; .alert-success') .append('&lt;/div&gt;'); //clear all fields $('#contactForm').trigger("reset"); }, error: function() { // Fail message $('#success').html("&lt;div class='alert alert-danger'&gt;"); $('#success &gt; .alert-danger').html("&lt;button type='button' class='close' data-dismiss='alert' aria-hidden='true'&gt;&amp;times;") .append("&lt;/button&gt;"); $('#success &gt; .alert-danger').append($("&lt;strong&gt;").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!")); $('#success &gt; .alert-danger').append('&lt;/div&gt;'); //clear all fields $('#contactForm').trigger("reset"); }, complete: function() { setTimeout(function() { $this.prop("disabled", false); // Re-enable submit button when AJAX call is complete }, 1000); } }); }, filter: function() { return $(this).is(":visible"); }, }); $("a[data-toggle=\"tab\"]").click(function(e) { e.preventDefault(); $(this).tab("show"); }); }); /*When clicking on Full hide fail/success boxes */ $('#name').focus(function() { $('#success').html(''); }); </code></pre> <p><strong>temp-contact_me.php</strong></p> <pre><code>&lt;?php session_start(); // Only process POST reqeusts. if ($_SERVER["REQUEST_METHOD"] === "POST") { // Build POST request: $recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify'; $recaptcha_secret = '...'; $recaptcha_ip = $_SERVER['REMOTE_ADDR']; $recaptcha_response = $_POST['captcha']; // Make and decode POST request $recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&amp;response=' . $recaptcha_response . '&amp;remoteip=' . $recaptcha_ip); $recaptcha = json_decode($recaptcha); if($recaptcha-&gt;success==true) { // Take action based on the score returned: if ($recaptcha-&gt;score &gt;= 0.5) { print_r("Verified - email sent"); // Verified - send email //validate Token if (hash_equals($_SESSION['sec'], $_POST['token'])) { // Check for empty fields if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } else { //sanitizing entries function cleanInputs ($data) { trim($data); strip_tags($data); stripslashes($data); htmlspecialchars($data); htmlentities($data, ENT_QUOTES, 'UTF-8'); return ($data); } $name = cleanInputs($_POST['name']); $email_address = cleanInputs($_POST['email']); $phone = cleanInputs($_POST['phone']); $message = cleanInputs($_POST['message']); //check for header injections function has_header_inject ($str) { return preg_match ("/[\r\n]/", $str ); } if (has_header_inject($name) || has_header_inject($email_address) || has_header_inject($phone) || has_header_inject($message)) { die (); //if true, kill the process-script } else { $to = '...'; $subject = 'Website Message From: ' .$name; $headers = 'MIME-Version: 1.0' . "\r\n" . 'Content-type:text/html; charset=UTF-8' . "\r\n" . 'From: ' . $email_address . "\r\n" . 'Reply-To: ' . $email_address . "\r\n" . 'X-Priority: 2' . "\r\n" . //(values: 1 to 5- from the highest to lowest) 'MSMail-Priority: Normal' . "\r\n" . //(values: High, Normal, or Low) 'Importance: Normal' . "\r\n" . //(values: High, Normal, or Low) 'X-Mailer: PHP/' . phpversion(); $message = wordwrap($message, 80, '&lt;br/&gt;', true); $email_body = "&lt;html&gt;&lt;body&gt; You have received a new message, here are the details:&lt;br/&gt;&lt;br&gt; &lt;table rules='all' style='border-color: #666;' cellpadding='10'&gt; &lt;tr style='letter-spacing:0.7px; color: white;'&gt; &lt;td style='background: #18648F;'&gt;&lt;b&gt;Name:&lt;/b&gt;&lt;/td&gt; &lt;td style='background: #23A895;'&gt;" . $name . "&lt;/td&gt; &lt;/tr&gt; &lt;tr style='letter-spacing:0.7px; color: white;'&gt; &lt;td style='background: #18648F;'&gt;&lt;b&gt;Email:&lt;/b&gt;&lt;/td&gt; &lt;td style='background: #23A895;'&gt;" . $email_address . "&lt;/td&gt; &lt;/tr&gt; &lt;tr style='letter-spacing:0.7px; color: white;'&gt; &lt;td style='background: #18648F;'&gt;&lt;b&gt;Phone:&lt;/b&gt;&lt;/td&gt; &lt;td style='background: #23A895;'&gt;" . $phone . "&lt;/td&gt; &lt;/tr&gt; &lt;tr style='letter-spacing:0.7px; color: white;'&gt; &lt;td style='background: #18648F;'&gt;&lt;b&gt;Message:&lt;/b&gt;&lt;/td&gt; &lt;td style='background: #23A895;'&gt;" . $message . "&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt;&lt;/html&gt;"; // Send the email. if (mail($to, $subject, $email_body, $headers)) { http_response_code(200); // Set a 200 (okay) response code. echo "Thank You! Your message has been sent."; session_destroy(); } else { http_response_code(500); // Set a 500 (internal server error) response code. echo "Oops! Something went wrong and we couldn't send your message."; die (); } } } } else { echo "CSRF Token Failed!!"; die (); } } else { print_r("Not verified - show form error"); // Not verified - show form error exit; } } else { // there is an error, timeout-or-duplicate meaning you are submit the form print_r($recaptcha); exit; } } else { // Not a POST request, set a 403 (forbidden) response code. http_response_code(403); echo "There was a problem with your submission, please try again."; die (); } ?&gt; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T15:39:22.927", "Id": "224908", "Score": "2", "Tags": [ "php", "jquery", "html5", "ajax", "captcha" ], "Title": "Contact form with AJAX call and secured PHP with Google reCAPTCHA v3" }
224908
<p><strong>What is it?</strong></p> <p>The google sheet that the macros are on acts as a sort of "back-end" for the records of a behaviour system at a school. I build multiple google sheets that link to this one that pull the data. Each week the behaviour records are put in this main sheet and then formulas total up the rest. The macros are for when a pupil is added, removed or a new one starts to make sure the data stays in line with the pupil. </p> <p><strong>The Problem</strong></p> <p>When it is full of data it take too long to perform the operations and can timeout the google sheet (especially on school computers). <a href="https://docs.google.com/document/d/1JGWcjIYhf_louBon6Yh1-L470t41k-ChEwPQWMc7Kmg/edit?usp=sharing" rel="nofollow noreferrer">execution log of move pupil code</a></p> <p><strong>Solution?</strong></p> <p>From the research I have done I could try batching code (don't know how to do them in scripts) but would like to know any ways to change/ rework my code to make it way more efficient. <a href="https://docs.google.com/spreadsheets/d/1LCFoPGE9XrHrs2LkjTxKs0kh5az2PdAPsjuaHXL56nY/edit?usp=sharing" rel="nofollow noreferrer">google sheet with scripts as macros</a></p> <p><strong>Code</strong></p> <p><em>Add Pupil Code</em></p> <pre><code>function insertRow() { var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets(); var row = SpreadsheetApp.getActiveRange().getRow(); for (var i = 0; i &lt; sheets.length; i++) { sheets[i].insertRowBefore(row); } } </code></pre> <p><em>Remove Pupil Code</em></p> <pre><code>function deleteRow() { var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets(); var row = SpreadsheetApp.getActiveRange().getRow(); for (var i = 0; i &lt; sheets.length; i++) { sheets[i].deleteRow(row); } } </code></pre> <p>Move Pupil Code</p> <pre><code>function moveRow() { var ui = SpreadsheetApp.getUi(); var formResponse = ui.prompt('Move Pupil Row', 'Enter the pupils new form', ui.ButtonSet.OK_CANCEL); var currentResponse = ui.prompt('Move Pupil Row', 'Enter the current row number for this pupil', ui.ButtonSet.OK_CANCEL); var newResponse = ui.prompt('Move Pupil Row', 'Enter the new row number for this pupil', ui.ButtonSet.OK_CANCEL); if (newResponse.getSelectedButton() == ui.Button.OK) { Logger.log('Collected New Form', formResponse.getResponseText()); Logger.log('Collected Current Row', currentResponse.getResponseText()); Logger.log('Collected New Row', newResponse.getResponseText()); var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets(); var row = currentResponse.getResponseText() var newForm = formResponse.getResponseText() var pupilData = SpreadsheetApp.getActive().getSheetByName('PupilData'); var formCell = pupilData.getRange("A"+row); formCell.setValue(newForm); var newRow = newResponse.getResponseText() var newRowRange = "A"+newRow+":AP"+newRow if (row &lt; newRow) { var rowRange = "A"+row+":AP"+row } else { row = +row row = row + 1 var rowRange = "A"+row+":AP"+row } for (var i = 0; i &lt; sheets.length; i++) { sheets[i].insertRowBefore(newRow); } for (var i = 0; i &lt; sheets.length; i++) { sheets[i].getRange(rowRange).moveTo(sheets[i].getRange(newRowRange)); sheets[i].deleteRow(row); } var halfTerm1 = SpreadsheetApp.getActive().getSheetByName('HT1'); var halfTerm2 = SpreadsheetApp.getActive().getSheetByName('HT2'); var halfTerm3 = SpreadsheetApp.getActive().getSheetByName('HT3'); var halfTerm4 = SpreadsheetApp.getActive().getSheetByName('HT4'); var halfTerm5 = SpreadsheetApp.getActive().getSheetByName('HT5'); var halfTerm6 = SpreadsheetApp.getActive().getSheetByName('HT6'); var year = SpreadsheetApp.getActive().getSheetByName('Year'); halfTerm1.getRange('C5:AP').clearContent(); halfTerm2.getRange('C5:AP').clearContent(); halfTerm3.getRange('C5:AP').clearContent(); halfTerm4.getRange('C5:AP').clearContent(); halfTerm5.getRange('C5:AP').clearContent(); halfTerm6.getRange('C5:AP').clearContent(); year.getRange('C5:AP').clearContent(); } else if (newResponse.getSelectedButton() == ui.Button.CANCEL) { Logger.log('The user canceled the dialog.'); } else { Logger.log('The user closed the dialog.'); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T18:14:52.047", "Id": "224920", "Score": "3", "Tags": [ "performance", "google-apps-script", "google-sheets" ], "Title": "Google Scripts (Add, Remove & Moving Record) stop timeout" }
224920
<p>I am relatively new to scripting. My programming experience stems from a QBASIC course when I was 11, and teaching myself HTML when I was a teenager (a while ago).</p> <p>This script resides on what is essentially a log of orders for a company. Occasionally, orders will be "shorted" if all the products are not ready in time for shipment. For these cases, I decided to write a script that would update various case quantities and dollar amounts.</p> <p>The script below is working, but updating the values is very, very slow.</p> <p>The main function is "ShortMaker" but the top function "GetByName" is used to reference column headings -- I have to add columns when new products are added to our lineup, so using hard column references means I would have to change my code every time we added a new product and this was the best function I could find in my online searches. This may be the part that's slowing it down, though. Not sure. (Is there a way to tell?) Note that there <em>are</em> instances of hard column references. I have yet to update these to the new system.</p> <pre><code>function getByName(colName, row) { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheets = ss.getSheets(); var data = sheets[1].getRange('DL1:'+sheets[1].getLastColumn()+'2').getValues(); // Get top 2 rows var col = data[0].indexOf(colName); if (col != -1) { return data[row-1][col]; } } function ShortMaker() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheets = ss.getSheets(); ss.setActiveSheet(ss.getSheets()[1]); // Get Flash Report var sheet = SpreadsheetApp.getActiveSheet(); var lastRow = sheet.getLastRow(); var range = sheet.getRange("A"+":"+"I"+lastRow); var rows = range.getValues(); // Enter SO# var ui = SpreadsheetApp.getUi(); var response = ui.prompt('Adjust Order for Short','Enter SO#',ui.ButtonSet.OK_CANCEL); if (response.getSelectedButton() == ui.Button.OK) { var SONum = (response.getResponseText()); } else if (response.getSelectedButton() == ui.Button.CANCEL){return} // Enter # of products shorted var ui = SpreadsheetApp.getUi(); var response = ui.prompt('Adjust Order for Short','How many products were shorted?',ui.ButtonSet.OK_CANCEL); if (response.getSelectedButton() == ui.Button.OK) { var CODEqty = (response.getResponseText()); } else if (response.getSelectedButton() == ui.Button.CANCEL){return} var PCodes = []; var QtyCodes = []; //Enter Codes &amp; Qtys for (var i = 0; i &lt; CODEqty; ++i) { var ui = SpreadsheetApp.getUi(); var response = ui.prompt('Adjust Order for Short','Enter Product Code ',ui.ButtonSet.OK_CANCEL); if (response.getSelectedButton() == ui.Button.OK) { PCodes[i] = (response.getResponseText()); } else if (response.getSelectedButton() == ui.Button.CANCEL){return} var ui = SpreadsheetApp.getUi(); var response = ui.prompt('Adjust Order for Short','Enter Qty Shorted for Product Code '+PCodes[i],ui.ButtonSet.OK_CANCEL); if (response.getSelectedButton() == ui.Button.OK) { QtyCodes[i] = (response.getResponseText()); } } // Enter New Invoice Amount var ui = SpreadsheetApp.getUi(); var response = ui.prompt('Adjust Order for Short','Enter New Invoice Amount',ui.ButtonSet.OK_CANCEL); if (response.getSelectedButton() == ui.Button.OK) { var Invoice = (response.getResponseText()); } else if (response.getSelectedButton() == ui.Button.CANCEL){return} // Enter New Discount Amount var ui = SpreadsheetApp.getUi(); var response = ui.prompt('Adjust Order for Short','Enter New Discount Amount',ui.ButtonSet.OK_CANCEL); if (response.getSelectedButton() == ui.Button.OK) { var Discount = (response.getResponseText()); } else if (response.getSelectedButton() == ui.Button.CANCEL){return} // INSERT VALUES ONTO FLASH REPORT // ************ Edit 'var range' Column when columns are added **************** var lastRow = sheets[1].getLastRow(); var range = sheets[1].getRange("A6"+":"+"EC"+lastRow); var rows = range.getValues(); for (var i = 0; i &lt; rows.length; ++i) { var row = rows[i]; if (row[7]==SONum) { sheets[1].getRange('S'+(i+6)).setValue("SHORTED"); // Mark order Shorted var OriginalInvoice = sheets[1].getRange('AC'+(i+6)).getValue(); // Get original invoice amount sheets[1].getRange('EB'+(i+6)).setValue(OriginalInvoice); // Enter original invoice amount in short section sheets[1].getRange('AC'+(i+6)).setValue(Invoice); // Enter new invoice amount sheets[1].getRange('AA'+(i+6)).setValue(Discount); // Enter new discount amount for (var u = 0; u &lt; CODEqty; ++u) { var Pcol = getByName('LSC'+u, 2); var Qcol = getByName('LSQ'+u, 2); sheets[1].getRange(Pcol+(i+6)).setValue(PCodes[u]); // Enter Product Code sheets[1].getRange(Qcol+(i+6)).setValue(QtyCodes[u]); // Enter Qty Shorted } } } } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T20:23:04.303", "Id": "224926", "Score": "1", "Tags": [ "javascript", "performance", "google-apps-script", "google-sheets" ], "Title": "Adjust entries in Google Sheet for short orders" }
224926
<p>At the moment I have this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function getValue(str) { let result = 0; var regex = /(\d+[a-z]+)/g; match = regex.exec(str); while (match != null) { var match_str = match[0]; var last_char = match_str[match_str.length-1]; if ( last_char == 'h' ) result += parseInt(match_str) * 3600; if ( last_char == 'm' ) result += parseInt(match_str) * 60; if ( last_char == 's' ) result += parseInt(match_str); match = regex.exec(str); } return result; } console.log( getValue("4h12m32s") );</code></pre> </div> </div> </p> <p>It feels quite clumsy though. Also checking invalid values like <code>4hs</code> feels difficult.</p> <p>Is there any clever trick for something similar?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T22:42:57.217", "Id": "436439", "Score": "2", "body": "`+\"4h12m32s\".replace(/(\\d+)h(\\d+)m(\\d+)s/, (_, h, m, s) => (h * 3600) + (m * 60) + (s * 1))` ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T22:49:21.147", "Id": "436441", "Score": "0", "body": "(might as well enjoy that implicit type coercion)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T23:17:10.927", "Id": "436444", "Score": "2", "body": "@user11536834 I would expect that each unit is optional. The current code allows that; your solution doesn't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T09:53:40.833", "Id": "436659", "Score": "0", "body": "It's probably not a good idea to mix `var` and `const`/`let` - you could consider replacing them all with `const` (or `let`, when the variable needs to be reassigned)" } ]
[ { "body": "<ul>\n<li><code>getValue(str)</code> is such a vague name for the function and its parameter, it could mean anything! Furthermore, \"get\" implies that this is a getter function that retrieves something, which is not the case.</li>\n<li>Your regex is ineffective. Capturing parentheses could be useful, but you didn't actually use them right, such that you ended up having to pass a dirty string to <code>parseInt()</code> and extract the last character the harder way.</li>\n<li>You neglected to scope <code>match</code>, such that it acts as a global variable. The regex-matching statement is written twice; the assignment could be done within the loop condition instead.</li>\n<li>The <code>if</code> statements should be an if-else chain, since the conditions are mutually exclusive. However, since the branches are all so similar, a lookup table would be more elegant.</li>\n</ul>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function durationSeconds(timeExpr)\n{\n var units = {'h': 3600, 'm': 60, 's': 1};\n var regex = /(\\d+)([hms])/g;\n\n let seconds = 0;\n var match;\n while ((match = regex.exec(timeExpr))) \n {\n seconds += parseInt(match[1]) * units[match[2]];\n }\n\n return seconds;\n}\n\nconsole.log( durationSeconds(\"4h12m32s\") );</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Alternatively, if you expect that the units will be in the conventional order, you don't have to loop at all.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function durationSeconds(timeExpr)\n{\n var match = /^(?:(\\d+)h)?(?:(\\d+)m)?(?:(\\d+)s)?$/.exec(timeExpr);\n return 3600 * (parseInt(match[1]) || 0)\n + 60 * (parseInt(match[2]) || 0)\n + (parseInt(match[3]) || 0);\n}\n\nconsole.log( durationSeconds(\"4h32s\") );</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T09:45:03.437", "Id": "436491", "Score": "0", "body": "Some of your mentions were because I have extracted this from my current code base (and messed up a bit with copy pasting), but this is exactly the knowledge and cleverness I was looking for. Despite that the second one is more consise I think your first example is great and super readable. Thanks for your effort." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T09:48:18.133", "Id": "436493", "Score": "0", "body": "Btw - one last question: why the double parentheses within the while loop in your first example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T09:56:01.620", "Id": "436494", "Score": "3", "body": "One common mistake is to write `while (a = 1)` when you meant `while (a == 1)`. [The extra parentheses is a convention to emphatically say \"yes, that really is an assignment\".](https://stackoverflow.com/questions/48334266/warning-suggest-parentheses-around-assignment-while-arg-to-arg-from)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T17:01:19.603", "Id": "436711", "Score": "0", "body": "Does eslint have that warning, and does the double parenthesis silence it?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T23:15:32.823", "Id": "224932", "ParentId": "224931", "Score": "14" } }, { "body": "<h2><a href=\"https://github.com/tc39/proposal-regexp-named-groups\" rel=\"noreferrer\">Named Capture Groups</a></h2>\n<p>JavaScript <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp\" rel=\"noreferrer\">RegExp</a> has <a href=\"https://github.com/tc39/proposal-regexp-named-groups\" rel=\"noreferrer\">named capture groups</a> that can make life a lot simpler when dealing with complicated <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp\" rel=\"noreferrer\">RegExp</a>. Combined with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"noreferrer\">destructuring assignment</a> you can extract the named hours minutes and seconds as follows.</p>\n<pre><code>function toSeconds(time) {\n const {groups: {h = 0, m = 0, s = 0}} = /(?&lt;h&gt;\\d*)h(?&lt;m&gt;\\d*)m(?&lt;s&gt;\\d*)/i.exec(time);\n return h * 3.6e3 + m * 60 + s * 1; // * 1 to coerce s to Number\n}\n</code></pre>\n<p>Missing digits are set to zero in the assignment defaults.</p>\n<p>However this is limited to strings that have hours, minutes, and seconds in the correct order (hence no need to match the <code>&quot;s&quot;</code>) and will throw an error if there is a problem.</p>\n<h2>A more robust solution</h2>\n<p>You can also <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\" rel=\"noreferrer\">reduce</a> the array created by <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll\" rel=\"noreferrer\"><code>symbol.matchAll</code></a> (it returns an iterator that you convert to an array via <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"noreferrer\">spread operator</a>)</p>\n<p>It <code>RegExp[symbol.matchAll]</code> is the same call as <code>String.matchAll(RegExp)</code></p>\n<p>To handle as many variations as possible you can convert the time string to lowercase, soak up white spaces, allow for fractions, multiple periods, and negative periods.</p>\n<p>Using an IIF to wrap the periods constant via closure the function looks like</p>\n<pre><code>const toSeconds = (() =&gt; {\n const periods = {h: 3600, m: 60, s: 1};\n return time =&gt; [.../(\\-*\\d*\\.*\\d*)\\W*([hms])/g[Symbol.matchAll](time.toLowerCase())]\n .reduce((time, [, digits, type]) =&gt; periods[type] * digits + time, 0);\n})();\n</code></pre>\n<p>Or via the string</p>\n<pre><code>const toSeconds = (() =&gt; {\n const periods = {h: 3600, m: 60, s: 1};\n return time =&gt; [...time.toLowerCase().matchAll(/(\\-*\\d*\\.*\\d*)\\W*([hms])/g)]\n .reduce((time, [, digits, type]) =&gt; periods[type] * digits + time, 0);\n})();\n</code></pre>\n<p>To combat the readability the next version creates some extra variables to segregate the logic parts a little</p>\n<pre><code>const toSeconds = (() =&gt; {\n const periods = {h: 3600, m: 60, s: 1};\n const extractHMS = /(\\-*\\d*\\.*\\d*)\\W*([hms])/g;\n const sumSeconds = (time, [, digits, type]) =&gt; periods[type] * digits + time;\n\n return time =&gt; [...time.toLowerCase().matchAll(extractHMS)].reduce(sumSeconds, 0);\n})();\n</code></pre>\n<p>The snippet below shows some of the results of a variety of inputs.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const toSeconds = (() =&gt; {\n const periods = {h: 3600, m: 60, s: 1};\n return time =&gt; [.../(\\-*\\d*\\.*\\d*)\\W*([hms])/g[Symbol.matchAll](time.toLowerCase())]\n .reduce((time, [, digits, type]) =&gt;periods[type] * digits + time, 0);\n})();\n\n\n\n\"1h,1m,1s,1,,1s2m3h,3h2m1s,2H2M2S,1h 1H1s1 S1m1M,1.1s,1.2s,s,1h-5m,1 1s,hms\"\n .split(\",\")\n .forEach(time =&gt; log(\"\\\"\" + time + \"\\\" =\" , toSeconds(time)+\" seconds\"));\n \nfunction log(...data) {\n document.body.appendChild(\n Object.assign(\n document.createElement(\"div\"), {textContent: data.join(\" \")}\n )\n )\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>BTW in Javascript we put...</p>\n<ul>\n<li>the opening <code>{</code> on the same line as the statement,</li>\n<li>use camelCase for naming.</li>\n</ul>\n<p>And from many years of C style language experience I would advise you to always delimit statement blocks with <code>{</code> <code>}</code> eg Bad <code>if (foo) bar = foo</code>, Good <code>if (foo) { bar = foo }</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T09:08:23.570", "Id": "436485", "Score": "1", "body": "This code might be more robust, but it's also A LOT harder to read IMHO." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T09:22:02.810", "Id": "436487", "Score": "2", "body": "@Nzall Modern JS is progressing to less a less verbose style that to many is less readable. I will update with a more readable version." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T13:09:37.843", "Id": "436520", "Score": "1", "body": "Very nice. Might be worth mentioning that `matchAll` and named captures don't have full browser support yet, but this is surely the way forward (old regex functions all have some unfortunate deficiencies, aside from `replace`, which is awkward to use when not actually replacing something)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T13:17:24.390", "Id": "436522", "Score": "0", "body": "One other idea for the first solution could be to whack everything into Date.UTC, with 1970, 0, 1 as the first arguments, then multiply by 0.001; then you could scrap `periods` and do it all in one shot (a bit funky, but makes it really clear we're dealing with a timestamp)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T06:01:13.210", "Id": "224948", "ParentId": "224931", "Score": "10" } }, { "body": "<p>In addition:</p>\n\n<ul>\n<li>\"<strong>Always</strong> specify a radix when using parseInt.\" -- <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt\" rel=\"nofollow noreferrer\">MDN parseInt documentation</a></li>\n<li>When getValue() is given a malformed string, it ignores the malformed parts without letting anyone know something went wrong. For example, <code>2 h 500 m 600 s</code> returns <code>0</code>. It is better to throw an error when the input isn't valid (so the caller can more easily figure out why the values it got back are wrong).</li>\n<li>If you expect requirements to change in the future, you should look into harnessing the power of a real parser (or parser generator). For example, what changes do you need to do to:\n\n<ul>\n<li>Add support for uppercase letters: <code>1H2D3M</code></li>\n<li>Allow spaces: <code>30h 50 m 10s</code></li>\n<li>Allow input to be in any order: <code>5s 10m</code></li>\n<li>Allow multiple occurrences or no occurrences of a unit: <code>30h 10h</code> or <code>10s</code></li>\n<li>Add new units: <code>d</code> (days) or <code>ms</code> (milliseconds), etc.</li>\n</ul></li>\n</ul>\n\n<p>Here is what that looks like using a parser generator (PEG.js):</p>\n\n<ul>\n<li>Navigate to <a href=\"https://pegjs.org/online\" rel=\"nofollow noreferrer\">https://pegjs.org/online</a></li>\n<li>Paste the following into the grammar text area:</li>\n</ul>\n\n<pre><code>// Duration to Seconds Grammar\n// ==========================\n//\n// Accepts expressions like \"4h53m12s\" or \"4H 33M 12S\" \n// and computes the total number of seconds.\n\nstart\n = total\n\ntotal\n = left:subtotal right:total { return left + right; }\n / subtotal\n\nsubtotal\n = left:integer right:day { return left * 86400; }\n / left:integer right:hour { return left * 3600; }\n / left:integer right:minute { return left * 60; }\n / left:integer right:second { return left; }\n / left:integer right:millisecond { return left * .001; }\n\nday\n = whitespace [dD]\n\nhour\n = whitespace [hH]\n\nminute\n = whitespace [mM][^sS]\n\nsecond\n = whitespace [sS]\n\nmillisecond\n = whitespace [mM][sS]\n\ninteger\n = whitespace [0-9]+ { return parseInt(text(), 10); }\n\nwhitespace\n = [ \\t\\n\\r]*\n</code></pre>\n\n<ul>\n<li>Test it out in the right-hand pane</li>\n<li>Choose your options and click Download Parser </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T23:13:16.777", "Id": "436605", "Score": "0", "body": "Nice answer. That first bullet point is a really easy trap to fall into (as in OP and accepted answer here). I'd rather avoid `parseInt` entirely than give it a second look to make sure it's used correctly. AFAIK implicit conversion has *never* parsed leading zeros as octal (at least, not from ES3 forward)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T22:31:34.247", "Id": "224998", "ParentId": "224931", "Score": "3" } } ]
{ "AcceptedAnswerId": "224932", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T22:16:53.920", "Id": "224931", "Score": "11", "Tags": [ "javascript", "parsing", "datetime", "regex", "unit-conversion" ], "Title": "Convert a string like 4h53m12s to a total number of seconds in JavaScript" }
224931
<h3>"This is {0} cool!", "freaking"</h3> <p>I've always wanted an easy and intuitive way to inject variables into a string. So after about 10 variations, I finally came up with this function.</p> <hr> <h3>How it works</h3> <p>The concept is that I can find every pattern such as <code>{key}</code> or <code>{0}</code> or whatever <code>{taco}</code> and get a unique list of these. If there are more keys than there are variables it will raise a custom error. (<em>Keys are case sensitive.</em>)</p> <p>If it matches then it uses the index of each <code>ParamArray</code> variable and matches that to the index of the pattern list. For example <code>"{bacon} {burrito}"</code> bacon: 0, burrito: 1.</p> <p>With that match, it simply replaces every instance of the match with the value of the variable.</p> <hr> <h3>A few extra notes</h3> <p>I originally had the pattern start with a dollar sign <code>${0}</code> to copy JavaScripts syntax but decided to keep it shorter for simplicity.</p> <p>It does use the escape character <code>\</code>. Example: <code>\{test}</code> would be print <code>{test}</code>.</p> <p>It also includes shortcuts for vbNewLine <code>\n</code> and vbTab <code>\t</code>.</p> <hr> <h3>The formula</h3> <p>Make sure to first set references to <strong>Microsoft Scripting Runtime</strong> and <strong>Microsoft VBScript Regular Expressions 5.5</strong>.</p> <p>I thought about doing this late binding but figured performance is probably better with these libraries referenced and they are common enough that it should not matter.</p> <pre class="lang-vb prettyprint-override"><code>' Returns a new cloned string that replaced special {keys} with its associated pair value. ' Keys can be anything since it goes off of the index, so variables must be in proper order! ' Can't have whitespace in the key. ' Also Replaces "\t" with VbTab and "\n" with VbNewLine ' ' @author: Robert Todar &lt;https://github.com/todar&gt; ' @reference: Microsoft Scripting Runtime - [Dictionary] ' @reference: Microsoft VBScript Regular Expressions 5.5 - [RegExp, Match] ' @example: Inject("Hello, {name}!\nJS Object = {name: {name}, age: {age}}\n", "Robert", 31) Public Function Inject(ByVal source As String, ParamArray values() As Variant) As String ' Want to get a copy and not mutate original Inject = source Dim regEx As RegExp Set regEx = New RegExp ' Late Binding would be: CreateObject("vbscript.regexp") With regEx .Global = True .MultiLine = True .IgnoreCase = True ' This section is only when user passes in variables If Not IsMissing(values) Then ' Looking for pattern like: {key} ' First capture group is the full pattern: {key} ' Second capture group is just the name: key .Pattern = "(?:^|[^\\])(\{([\w\d\s]*)\})" ' Used to make sure there are even number of uniqueKeys and values. Dim keys As New Scripting.Dictionary Dim keyMatch As match For Each keyMatch In .Execute(Inject) ' Extract key name Dim key As Variant key = keyMatch.submatches(1) ' Only want to increment on unique keys. If Not keys.Exists(key) Then If (keys.Count) &gt; UBound(values) Then Err.Raise 9, "Inject", "Inject expects an equal amount of keys to values. Keys found: " &amp; Join(keys.keys, ", ") &amp; ", " &amp; key End If ' Replace {key} with the pairing value. Inject = Replace(Inject, keyMatch.submatches(0), values(keys.Count)) ' Add key to make sure it isn't looped again. keys.Add key, vbNullString End If Next End If ' Replace extra special characters. Must allow code above to run first! .Pattern = "(^|[^\\])\{" Inject = .Replace(Inject, "$1" &amp; "{") .Pattern = "(^|[^\\])\\t" Inject = .Replace(Inject, "$1" &amp; vbTab) .Pattern = "(^|[^\\])\\n" Inject = .Replace(Inject, "$1" &amp; vbNewLine) .Pattern = "(^|[^\\])\\" Inject = .Replace(Inject, "$1" &amp; "") End With End Function </code></pre> <hr> <h3>The tests for it</h3> <p>My first test is using <a href="https://regexr.com/4i4r7" rel="noreferrer">RegExr.com</a> to see if my pattern would match. Just to note, I use the first capture group as the actual replacement so the characters before will not be replaced.</p> <p><a href="https://i.stack.imgur.com/XTSX7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XTSX7.png" alt="RegExr Tests"></a></p> <hr> <p>The next step was to try it in VBA. I just copied the same lines and printed them to the immediate window.</p> <pre class="lang-vb prettyprint-override"><code>Private Sub testingInject() Debug.Print Inject("{it} works with with words.", "It") Debug.Print Inject("{0} works with digits.", "It") Debug.Print Inject("{it } works with whitespace.", "It") Debug.Print Inject("{ {it} } doesn't effect outer nestings.", "It") Debug.Print Inject("\{it} should be escaped.", "It did not but") Debug.Print Inject("Hello, {name}! {name}, \{(escaped) you} are {age} years old!.", "Robert", 31) Debug.Print Inject("Hello, {name}!\n{\n\tname: {name},\n\t age: {age}\n}", "Robert", 31) On Error Resume Next 'Expect this to fail Debug.Print Inject("Hello, {name}! How are you {Name}", "Robert") Debug.Print Err.Description End Sub </code></pre> <p>Here are the results. They printed how I expected them to.</p> <p><a href="https://i.stack.imgur.com/nhN4s.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nhN4s.png" alt="Immediate Window Results"></a></p> <hr> <h3>What I would hope for in answers</h3> <ul> <li><strong>Performance</strong> I want to make sure I'm not missing anything that might be a big trade-off of using this.</li> <li><strong>RegEx Check</strong> I am not the best at this and would love to get better at writing these. This is a good example I feel for learning.</li> <li><strong>Improvements</strong> is there anything I'm missing? Could this become even cooler?</li> <li><strong>Possible bugs</strong> really are there any tests I should be running more than what I have.</li> <li><strong>Anything really</strong> I want to continue to learn and grow as a programmer. =)</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T15:16:04.670", "Id": "436540", "Score": "2", "body": "Related: [String.Format implementation](https://codereview.stackexchange.com/q/30817/23788), for VBA/VB6 =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T15:19:00.853", "Id": "436542", "Score": "0", "body": "@MathieuGuindon I should have known you have something out there already! =) I wish you had more of your code on Github." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T15:33:57.987", "Id": "436544", "Score": "3", "body": "lol, [this comment](https://codereview.stackexchange.com/questions/30817/a-csharpish-string-format-formatting-helper#comment377274_31000) is past-me essentially wishing I'd have uploaded it all to GitHub!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T15:36:41.347", "Id": "436545", "Score": "0", "body": "Well, it being on stack overflow is better than it being written on a napkin somewhere lol." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T08:17:44.263", "Id": "437106", "Score": "0", "body": "Why do you limit your key to English letters, whitespace and numbers only? (E.g. I'm Hungarian and might use letters with accent (áéíóö...) which are not accepted currenlty) Why not just go until closing bracket (`[^}]`)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T15:34:59.390", "Id": "437169", "Score": "0", "body": "@MátéJuhász I tried the pattern `(?:^|[^\\\\])(\\{([A-zÀ-ÿ0-9\\s]*)\\})` and that seems to work for your case. Just looking for next bracket seems to get outer nested brackets as well. If you want to post the full pattern I can test it out. Or you can try it with this new [regexr post](https://regexr.com/4ic40)" } ]
[ { "body": "<h2>DISCLAIMER ˆ_ˆ</h2>\n<p>I'm not a reviewer, will be commenting on your regular expression though.</p>\n<h2>Comments</h2>\n<ul>\n<li>I guess you don't have to escape <kbd>{</kbd> or <kbd>}</kbd>.</li>\n<li><code>\\w</code> construct would already cover <code>0-9</code>, the <code>\\d</code> construct can be removed then <code>(?:^|[^\\\\])(\\{([\\w\\s]*)\\})</code>.</li>\n<li>Since we're using a character class (<code>[]</code>), maybe we'd just list our desired chars right in there without using any construct (e.g., <code>[A-Za-z0-9 ]</code>).</li>\n<li>My guess is that <code>{}</code> would be an undesired/invalid input, which if that'd be the case, we'd use <code>+</code> greedy quantifier instead of <code>*</code>.</li>\n<li>I see some capturing groups, maybe we could remove some of those also, if that'd be OK. Reducing the number of capturing groups would help in memory complexity, even though memory is not usually such a big thing (here).</li>\n</ul>\n<p>Based on these comments, maybe your expression could be modified to:</p>\n<pre><code>(?:^|[^\\\\\\r\\n]){([A-Za-z0-9 ]+)}\n</code></pre>\n<h2>Demo</h2>\n<p>If you wish to simplify/update/explore the expression, it's been explained on the top right panel of <a href=\"https://regex101.com/r/AT0mSq/1/\" rel=\"nofollow noreferrer\">regex101.com</a>. You can watch the matching steps or modify them in <a href=\"https://regex101.com/r/AT0mSq/1/debugger\" rel=\"nofollow noreferrer\">this debugger link</a>, if you'd be interested. The debugger demonstrates that how <a href=\"https://en.wikipedia.org/wiki/Comparison_of_regular_expression_engines\" rel=\"nofollow noreferrer\">a RegEx engine</a> might step by step consume some sample input strings and would perform the matching process.</p>\n<h3>RegEx Circuit</h3>\n<p><a href=\"https://jex.im/regulex/#!flags=&amp;re=%5E(a%7Cb)*%3F%24\" rel=\"nofollow noreferrer\">jex.im</a> visualizes regular expressions:</p>\n<p><a href=\"https://i.stack.imgur.com/JHWbJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JHWbJ.png\" alt=\"enter image description here\" /></a></p>\n<h3>Performance</h3>\n<p>This expression</p>\n<pre><code>^{([A-Za-z0-9 ]+)}|[^\\\\\\r\\n]{([A-Za-z0-9 ]+)}\n</code></pre>\n<p>has a better performance as compared to the first one</p>\n<pre><code>(?:^|[^\\\\\\r\\n]){([A-Za-z0-9 ]+)}\n</code></pre>\n<p>in terms of time complexity. You can look into the number of steps in the demo. Finding ways to bypass alternation (<code>|</code>) is usually a good thing, it would help in runtime.</p>\n<h3><a href=\"https://regex101.com/r/Zc3Qjr/1/\" rel=\"nofollow noreferrer\">RegEx Demo</a></h3>\n<h1>Overall looks very good!!!</h1>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-25T03:26:16.130", "Id": "248394", "ParentId": "224933", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-25T23:23:39.963", "Id": "224933", "Score": "13", "Tags": [ "vba", "regex" ], "Title": "\"String Interpolation in {language}\", \"VBA\"" }
224933
<p>I have written a bilinear interpolant, which is working moderately well except that is painfuly slow. How can rewrite the code to make it faster? Using opencv directly isn't a valid answer.</p> <pre><code>import numpy as np import numpy.linalg as la import matplotlib import matplotlib.pyplot as plt from skimage.draw import line_aa import cv2 def draw_line(img, x0, y0, x1, y1): r, c, w = line_aa(int(x0), int(y0), int(x1), int(y1)) img[r, c] = w def synth_img(sM, sN, pts_src): img = np.zeros((sM, sN)) draw_line(img.T, pts_src[0][0], pts_src[0][1], pts_src[1][0], pts_src[1][1]) draw_line(img.T, pts_src[1][0], pts_src[1][1], pts_src[2][0], pts_src[2][1]) draw_line(img.T, pts_src[2][0], pts_src[2][1], pts_src[3][0], pts_src[3][1]) draw_line(img.T, pts_src[3][0], pts_src[3][1], pts_src[0][0], pts_src[0][1]) return img sM, sN = 1440, 1450 pts_src = np.array([[ 520, 100],[ 1410, 220],[1240, 1310],[ 30, 1070]]).astype('float32') img = synth_img(sN, sM, pts_src) # Create a target image M, N = 1050, 1480 img_dst = np.zeros((N, M)) pts_dst = np.array([[0, 0], [M-1, 0], [M-1, N-1], [0, N-1]], dtype='float32') X = cv2.getPerspectiveTransform(pts_src, pts_dst) # SRC to DST X_inv = la.inv(X) # DST to SRC img_exp = cv2.warpPerspective(img, X, (M, N)) for y in np.arange(img_dst.shape[0]): for x in np.arange(img_dst.shape[1]): # Find the equivalent coordinates from DST space into SRC space Txy = X_inv @ [x, y, 1] u, v, w = Txy / Txy[-1] # Find the neighboring points of v and u (src space) n = min(max(np.floor(v).astype('int'), 0), img.shape[0]-1) s = min(max(np.ceil(v).astype('int'), 0), img.shape[0]-1) w = min(max(np.floor(u).astype('int'), 0), img.shape[1]-1) e = min(max(np.ceil(u).astype('int'), 0), img.shape[1]-1) # Find the values in neighboring values of [u, v] q00 = img[n, w] q01 = img[n, e] q10 = img[s, w] q11 = img[s, e] x0, x1, y0, y1 = w, e, n, s A = np.array([ [1, x0, y0, x0*y0], [1, x0, y1, x0*y1], [1, x1, y0, x1*y0], [1, x1, y1, x1*y1] ]) b = np.array([[ q00, q01, q10, q11 ]]).T a = la.lstsq(A, b, rcond=None)[0].ravel() z = a[0] + a[1]*u + a[2]*v + a[3]*u*v img_dst[y, x] = z plt.close() fig, ax = plt.subplots(2,2, figsize=(6,7), dpi=300, sharey=True, sharex=True) ax[0][0].imshow(img, cmap='gray') ax[0][0].set_title('Original') ax[0][1].imshow(img_exp-img_dst, cmap='gray') ax[0][1].set_title('Diff') ax[1][0].imshow(img_dst, cmap='gray') ax[1][0].set_title('Result') ax[1][1].imshow(img_exp, cmap='gray') ax[1][1].set_title('Expected') #plt.show() </code></pre> <p>After some work I have got here, almost no for loops(except for a single list comprehension). I have added functions (as hinted on a comment MCVEs are not expected here, but I will leave there for history). This code has some helper functions and I really think that there is a lot of room for improvement, I just don't know how to do.</p> <pre><code>import numpy as np import numpy.linalg as la import matplotlib import matplotlib.pyplot as plt import cv2 from itertools import product from skimage.draw import line_aa def draw_line(img, x0, y0, x1, y1): """Draw antaliased line from (x0,y0) to (x1, y1)""" r, c, w = line_aa(int(x0), int(y0), int(x1), int(y1)) img[r, c] = w def synth_img(sM, sN, pts_src): """Creates a simple synthetic image with a skewed rectangle""" img = np.zeros((sM, sN)) draw_line(img.T, pts_src[0][0], pts_src[0][1], pts_src[1][0], pts_src[1][1]) draw_line(img.T, pts_src[1][0], pts_src[1][1], pts_src[2][0], pts_src[2][1]) draw_line(img.T, pts_src[2][0], pts_src[2][1], pts_src[3][0], pts_src[3][1]) draw_line(img.T, pts_src[3][0], pts_src[3][1], pts_src[0][0], pts_src[0][1]) return img def extend_col(array): """Extend `array` adding a last columns of ones""" return np.hstack((array, np.ones((array.shape[0], 1)))) def reduce_row(array): """Reduce row space of array, dividing the whole array by the last column and returning the last first two columns""" return (array / array[-1])[:-1].T def bilinear_interp(x, y, x0, x1, y0, y1, q00, q01, q10, q11): """Do bilinear interpolation given a point, a box and values on box vetices""" q = np.array([[q00, q01], [q10, q11]]) xx = np.array([(x1 - x), (x - x0)]) yy = np.array([(y1 - y), (y - y0)]) # ATTENTION: # THIS IS DAMN UGLY. How to remove this comprehension and # transform this to a matrix/tensor multiplication? zz = np.array( [ a @ b @ c for a, b, c in zip(xx.T, q.T, yy.T)]) return zz def neigh_points(points): """Return the neighbor points of given uv""" return np.floor(points[0]), np.ceil(points[0]), np.floor(points[1]), np.ceil(points[1]) def clip(points, lower_u, upper_u, lower_v, upper_v): """Clip values in array given upper and lower limits""" u = points[:,:2] v = points[:,2:] u[u &lt; lower_u] = lower_u u[u &gt; upper_u] = upper_u v[v &lt; lower_v] = lower_v v[v &gt; upper_v] = upper_v def interpolate(M, image): """Executes the interpolation on image based on M transform matrix""" MT = M.T u, v = MT[0], MT[1] w, e = MT[2].astype('int'), MT[3].astype('int') n, s = MT[4].astype('int'), MT[5].astype('int') q00 = image[n, w] q01 = image[n, e] q10 = image[s, w] q11 = image[s, e] return bilinear_interp(u, v, w, e, n, s, q00, q01, q10, q11) def image_warp(M, img, shape): """Look ma! No for's Probably a lot to improve. """ rxc = product(range(shape[0]), range(shape[1])) uv = reduce_row(la.inv(M) @ extend_col(np.array(list(rxc))).T) uv_neigh = np.array(neigh_points(uv.T)).T lower_u, upper_u, lower_v, upper_v = 0, img.shape[1]-1, 0, img.shape[0]-1 clip(uv_neigh, lower_u, upper_u, lower_v, upper_v) coords = np.hstack((uv, uv_neigh)) # ATTENTION: # This transformation should not need the rotation, something # is wrong here in `interpolate` return np.flip(np.rot90(interpolate(coords, img).reshape(shape),3), 1).astype('uint8') def main(): sM, sN = 1440, 1450 pts_src = np.array([[ 526., 107],[ 1413, 227],[1245, 1313],[ 30, 1076]], dtype='float32') img = synth_img(sN, sM, pts_src) # Create a target image (100 dpi A4 sheet) N, M = 1480, 1050 pts_dst = np.array([[0., 0], [M-1, 0], [M-1, N-1], [0, N-1]], dtype='float32') # Get transformation matrix from SRC to DST X = cv2.getPerspectiveTransform(pts_src, pts_dst) img_dst = image_warp(X, img, (M, N)) img_exp = cv2.warpPerspective(img, X, (M, N)) plt.close() fig, ax = plt.subplots(2,2, figsize=(6,7), dpi=300) ax[0][0].imshow(img, cmap='gray') ax[0][0].set_title('Original') ax[0][1].imshow(np.abs(img_exp-img_dst), cmap='gray') ax[0][1].set_title('Diff') ax[1][0].imshow(img_dst, cmap='gray') ax[1][0].set_title('Result') ax[1][1].imshow(img_exp, cmap='gray') ax[1][1].set_title('Expected') plt.show() </code></pre> <p>Actually, my <code>image_warp</code> function mimics <code>cv2.warpPerspective</code>. Almost got there except for two things:</p> <ol> <li><p>First pixel <code>[0][0]</code> is weirdly set as 0. But looking the return from <code>zz</code> in <code>bilinear_interp</code> function the value is correct.</p></li> <li><p>Some rounding issues in values (when comparing to OpenCV's result). Tried to use <code>np.ceil</code>, <code>np.floor</code>, <code>np.round</code> and plain <code>astype('uint8')</code>, but none returned perfect results matching OpenCVs. Left as is using the option that gives the smallest error (using opencv's output as reference).</p></li> </ol> <p>About the code, I have some special concerns. There are some very ugly parts. I can point some:</p> <ol> <li><p>In <code>bilinear_inter</code> the calculation of <code>zz</code> is a VERY UGLY and slow list comprehension. Converting types there and back again.</p></li> <li><p>In <code>image_warp</code> there is an excessive number of conversion to list and numpy arrays and transposes.</p></li> <li><p>In <code>image_warp</code> I'm rotating and flipping the results. Don't know what is happening and where the error may be, since the vector space transfomation should result in the correct orientation.</p></li> <li><p>I could use <code>np.clip</code> instead my own <code>clip</code>. But I treat the first two columns differently than the last two columns. Can <code>np.clip</code> do that somehow?</p></li> <li><p>The <code>extend_col</code>/<code>reduce_row</code> trick works fine and is reasonably fast, but <em>ugly</em>. Any better approaches?</p></li> </ol> <p>Of course any other improvements are very welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T08:02:40.470", "Id": "436472", "Score": "0", "body": "Is this your real project code? I would have expected a function (perhaps with a sample \"main\" program to drive it with synthetic input). What we have here is more like the MCVE I'd expect on a [so] question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T00:13:22.913", "Id": "436613", "Score": "0", "body": "yes. Indeed a MCVE. I have changed all function calls to *inlines* inside the for-loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T20:44:17.053", "Id": "436868", "Score": "2", "body": "Out of curiosity, why is using opencv directly not a valid answer? Asking because when performance issues crop up in a language not primarily built for raw speed, seems like the usual thing to do would be delegate that stuff to a native library. Python isn't my go-to language, but if I were writing this for Lua(JIT), and found it to be unacceptably slow, I'd probably either whip something up in C or load up a suitable library (with the FFI, either way)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T11:02:04.593", "Id": "436921", "Score": "1", "body": "You're expected to show actual code from your project - not an MCVE. Changing the structure so that we're reviewing something different is off-topic for Code Review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-12T05:02:41.413", "Id": "438913", "Score": "0", "body": "Are you using a least squares fit to do linear interpolation? Yes, that will be slow... Linear interpolation is a weighted addition of the four (in 2D) values." } ]
[ { "body": "<p>I would like to share some observations about your main concerns given at the end of the question. Let's start from the back:</p>\n\n<h2>5. <code>extend_col</code>/<code>reduce_row</code></h2>\n\n<p>From what I can see, the \"trick\" here is to bring the points into a <a href=\"https://en.wikipedia.org/wiki/Homogeneous_coordinates\" rel=\"nofollow noreferrer\">homogenous coordinate system</a> and back. Therefore, I would propose to change the name of both functions to <code>to_homogeneous</code> and <code>from_homogeneous</code> or something similar. I also would propose a more straightforward implementation of <code>from_homogeneous</code>:</p>\n\n<pre><code>def to_homogeneous(array):\n \"\"\"Extend `array` adding a last columns of ones\"\"\"\n # alternatively:\n # rows, cols = array.shape\n # arr = np.empty((rows, cols+1))\n # arr[:, :-1] = array\n # arr[:, -1] = 1\n # or:\n # arr = np.ones((rows, cols+1))\n # arr[:, :-1] = array\n return np.hstack((array, np.ones((array.shape[0], 1))))\n\n\ndef from_homogeneous(array):\n \"\"\"Divide the array by the last column and return all but the last one\"\"\"\n return array[:, :-1] / array[:, -1, np.newaxis]\n</code></pre>\n\n<p>Since <span class=\"math-container\">\\$(A\\cdot B)^T=B^T\\cdot A^T\\$</span> you can get rid of some of the transpositions in <code>image_warp</code>:</p>\n\n<pre><code>rxc = np.array(list(product(range(shape[0]), range(shape[1]))))\nuv = from_homogeneous(to_homogeneous(rxc) @ la.inv(M).T)\n</code></pre>\n\n<p>I'm also relatively sure that there has to be a better way other than <code>itertools.product</code> here, but I haven't found it yet ;-)</p>\n\n<h2>4. <code>clip</code> vs. <code>np.clip</code></h2>\n\n<p>As you rightfully suspected, you could use <code>np.clip</code> for the task directly. If you look at its <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.clip.html\" rel=\"nofollow noreferrer\">documentation</a>, you'll see, that you can pass array-like arguments as upper and lower bounds.</p>\n\n<pre><code>uv_neigh = np.clip(\n uv_neigh,\n [lower_u, lower_u, lower_v, lower_v],\n [upper_u, upper_u, upper_v, upper_v]\n)\n</code></pre>\n\n<p>Please verify this yourself, for what I've seen it always delivers the same results as your original implementation.</p>\n\n<h2>3. Rotating and flipping the results in <code>image_warp</code></h2>\n\n<p>Maybe later.</p>\n\n<h2>2. Reducing conversions and transpositions</h2>\n\n<p>While talking about the 5th point, I already presented a first step towards reducing the amount of transpositions. The part where <code>uv_neigh</code> is computed is another candidate to cut some transpositions. Rewriting it to make use of the full power of numpy will help as a first step:</p>\n\n<pre><code>def neighboring_points(points):\n \"\"\"Return the neighbor points of given uv\"\"\"\n neigh_np = np.empty((points.shape[0], 4))\n neigh_np[:, 0::2] = np.floor(points)\n neigh_np[:, 1::2] = np.ceil(points)\n return neigh_np\n</code></pre>\n\n<p>This implementation creates a numpy array of the right size and then fills its 1st and 3rd column with the floored coordinates and the 2nd and 4th column with the ceiled coordinates of the points. Again, this should be fully compatible with your original implementation, but without all the transpositions and converting back and forth between Python and numpy.</p>\n\n<p>With this change also in place, <code>image_warp</code> now looks much friendlier:</p>\n\n<pre><code>def image_warp(M, img, shape):\n rxc = np.array(list(product(range(shape[0]), range(shape[1]))))\n uv = from_homogeneous(to_homogeneous(rxc) @ la.inv(M).T)\n\n uv_neigh = neighboring_points(uv)\n\n # you could also move this into a function as before\n lower_u, upper_u, lower_v, upper_v = 0, img.shape[1]-1, 0, img.shape[0]-1\n uv_neigh = np.clip(\n uv_neigh,\n [lower_u, lower_u, lower_v, lower_v],\n [upper_u, upper_u, upper_v, upper_v]\n )\n coords = np.hstack((uv, uv_neigh))\n\n return np.flip(np.rot90(interpolate(coords, img).reshape(shape), 3), 1).astype('uint8')\n</code></pre>\n\n<h2>1. List comprehension in <code>bilinear_interp</code></h2>\n\n<p>Indeed, the list comprehension here seems to be the biggest bottleneck of the code. Since I wasn't fully able to decipher all the cryptic variable names in your code and not had so much time at hand to really wrap my head around the problem, I took the lazy approach and threw the just-in-time compiler <a href=\"https://numba.pydata.org/\" rel=\"nofollow noreferrer\">numba</a> (i.e. it compiles plain Python/numpy code to a faster platform-specific code) at the problem to see how it went. This is the code I ended up with:</p>\n\n<pre><code>from numba import jit\n\n\n@jit(nopython=True)\ndef _bilinear_core(xx, q, yy):\n n = xx.shape[1]\n zz = np.empty((n, ))\n xx = xx.T\n q = q.T\n yy = yy.T\n for i in range(n):\n zz[i] = xx[i, :] @ q[i, :] @ yy[i, :].T\n return zz\n\n\ndef bilinear_interp(x, y, x0, x1, y0, y1, q00, q01, q10, q11):\n \"\"\"Do bilinear interpolation given a point, a box and\n values on box vetices\"\"\"\n q = np.array([[q00, q01], [q10, q11]])\n xx = np.array([(x1 - x), (x - x0)])\n yy = np.array([(y1 - y), (y - y0)])\n return _bilinear_core(xx, q, yy)\n</code></pre>\n\n<p>As you can see, I had to make some changes to use numba's faster <a href=\"http://numba.pydata.org/numba-doc/latest/user/jit.html#nopython\" rel=\"nofollow noreferrer\">nopython mode</a>. The biggest change is that you cannot use <code>zip(...)</code> in that mode, as well as some other convenient functions available in Python. Splitting the code up in two functions was likely not necessary, but I like to do it nevertheless to keep numba-specific modifications contained to a small scope. Other than this, the code is almost unchanged and it's still written in pure Python/numpy.</p>\n\n<p>But what are the benefits of these extra hoops you now have to jump through? Ignoring all the plotting and OpenCV's reference implementation, your <code>main</code> function runs in about <span class=\"math-container\">\\$10s\\$</span> on my old laptop. Using numba and all the changes presented here in this answer to this point, the same main function now runs in <span class=\"math-container\">\\$3.2s\\$</span>*. Not bad, isn't it?</p>\n\n<hr>\n\n<p>* When timing functions that (try to) use numba JIT, you have to take care to run the code at least twice and ignore the first measurement, since the first measurement would otherwise include the time numba needs to compile the function. In this example here, the first run takes about <span class=\"math-container\">\\$4.3s\\$</span>, which means that round about <span class=\"math-container\">\\$1.1s\\$</span> are spent on the compilation process.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T23:16:24.277", "Id": "225163", "ParentId": "224942", "Score": "6" } } ]
{ "AcceptedAnswerId": "225163", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T04:00:39.643", "Id": "224942", "Score": "9", "Tags": [ "python", "performance", "image", "numpy", "signal-processing" ], "Title": "Bilinear image interpolation" }
224942
<p>I'm learning GLSL shaders on Book of Shaders and I decided to mess around with one of the examples. I wanted to see, <strong>whats a more efficient way to calculate to mask out the color?</strong></p> <pre><code>#ifdef GL_ES precision mediump float; #endif #define TWO_PI 6.28318530718 uniform vec2 u_resolution; uniform float u_time; // Function from Iñigo Quiles // https://www.shadertoy.com/view/MsS3Wc vec3 hsb2rgb( in vec3 c ){ vec3 rgb = clamp(abs(mod(c.x*6.0+vec3(0.0,4.0,2.0),6.0)-3.0)-1.0,0.0,1.0); rgb = rgb*rgb*(3.0-2.0*rgb); return c.z * mix( vec3(1.0), rgb, c.y); } void main(){ vec2 st = gl_FragCoord.xy/u_resolution; vec3 color = vec3(0.0); // Use polar coordinates instead of cartesian vec2 toCenter = vec2(0.5)-st; float angle = atan(toCenter.y,toCenter.x); float radius = length(toCenter)*2.0; angle = angle + u_time; float outsideMask = 1.0 - step(distance(st, vec2(0.5)), 0.3); float insideMask = 1.0 - step(0.2, distance(st, vec2(0.5))); float visibleArea = 1.0 - insideMask - outsideMask; // Map the angle (-PI to PI) to the Hue (from 0 to 1) // and the Saturation to the radius color = hsb2rgb(vec3((angle/TWO_PI)+0.5,radius, 1.0)); gl_FragColor = vec4(color, visibleArea); } </code></pre> <p>Here is an image of the end result.</p> <p><a href="https://i.stack.imgur.com/7v9Vf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7v9Vf.png" alt="End Result."></a></p> <p>The <code>outsideMask</code>, <code>insideMask</code> and <code>visibleArea</code> variables in particular all have that <code>1.0</code> minus something, which seems weird to me. Any suggestions would be appreciated!</p>
[]
[ { "body": "<h2>Distance</h2>\n\n<p>In both your <code>step(...)</code> functions, you are computing <code>distance(st, vec2(0.5))</code>. If you computed this once, and stored this in a local variable, you'd be able to reuse this computed value, which should save time in your shader.</p>\n\n<p>But ... wait a second ...</p>\n\n<pre><code>vec2 toCenter = vec2(0.5)-st;\nfloat radius = length(toCenter)*2.0;\n</code></pre>\n\n<p>You've already computed this distance (length, actually), and stored it (doubled) in the local variable <code>radius</code>. We can use this value directly, by doubling your step thresholds:</p>\n\n<pre><code>float outsideMask = 1.0 - step(radius, 0.6);\nfloat insideMask = 1.0 - step(0.4, radius);\nfloat visibleArea = 1.0 - insideMask - outsideMask;\n</code></pre>\n\n<p>Or don't multiply the computed radius by 2.0 for the <code>radius</code> variable, and multiply it by 2 when you use it to compute the colour: </p>\n\n<pre><code>float radius = length(toCenter);\n\nfloat outsideMask = 1.0 - step(radius, 0.3);\nfloat insideMask = 1.0 - step(0.2, radius);\nfloat visibleArea = 1.0 - insideMask - outsideMask;\n\ncolor = hsb2rgb(vec3((angle/TWO_PI)+0.5, radius*2.0, 1.0));\n</code></pre>\n\n<h2>visibleArea</h2>\n\n<ol>\n<li><code>outsideMask = 1.0 - step(radius, 0.3)</code></li>\n<li><code>insideMask = 1.0 - step(0.2, radius)</code></li>\n<li><code>visibleArea = 1.0 - insideMask - outsideMask</code></li>\n</ol>\n\n<p>Substituting <code>insideMask</code> into (3):</p>\n\n<ol start=\"4\">\n<li><code>visibleArea = 1.0 - (1.0 - step(0.2, radius)) - outsideMask</code></li>\n<li><code>visibleArea = 1.0 - 1.0 + step(0.2, radius) - outsideMask</code></li>\n<li><code>visibleArea = step(0.2, radius) - outsideMask</code></li>\n</ol>\n\n<p>From <code>step(A,B) = 1 - step(B,A)</code>, we can reworking (1) as:</p>\n\n<ol start=\"7\">\n<li><code>outsideMask = step(0.3, radius)</code></li>\n</ol>\n\n<p>And substituting into (6):</p>\n\n<ol start=\"8\">\n<li><code>visibleArea = step(0.2, radius) - step(0.3, radius)</code></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T05:14:46.033", "Id": "224947", "ParentId": "224943", "Score": "3" } } ]
{ "AcceptedAnswerId": "224947", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T04:21:48.347", "Id": "224943", "Score": "3", "Tags": [ "mathematics", "glsl" ], "Title": "GLSL Shader that displays a Rotating Rainbow Ring" }
224943
<p>hi I have made and AI for my enemies which works perfectly but a particular section of code is repetitive and I feel that it can be optimised</p> <pre><code>void ChangeDirection() { if (movement == Vector3.left) transformModel.rotation = Quaternion.Euler(0, 270, 0); else if (movement == Vector3.right) transformModel.rotation = Quaternion.Euler(0, 90, 0); else if (movement == Vector3.back) transformModel.rotation = Quaternion.Euler(0, 180, 0); else if (movement == Vector3.forward) transformModel.rotation = Quaternion.Euler(0, 0, 0); } </code></pre> <p>the enemy will be in a tight corridor where only the following movements are possible i.e enemy can only move the vector3. right, left, back and forward. thus the code works without any issues, however, the code is repetitive and I want the enemy to move in whichever its movement vector will be.</p> <p>here is the rest my code</p> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyMovement2 : MonoBehaviour { public float speed; public Vector3 movement; public Animator animator; private GameObject gameManager; void Start() { movement = Vector3.back; gameManager = GameObject.FindWithTag("GameController"); } void OnCollisionEnter(Collision collision) { if (collision.gameObject.tag == "Wall") { CorrectPosition(new Vector3(1, 1, 1)); movement = Vector3.zero; } } public Transform transformModel; void ChangeDirection() { if (movement == Vector3.left) transformModel.rotation = Quaternion.Euler(0, 270, 0); else if (movement == Vector3.right) transformModel.rotation = Quaternion.Euler(0, 90, 0); else if (movement == Vector3.back) transformModel.rotation = Quaternion.Euler(0, 180, 0); else if (movement == Vector3.forward) transformModel.rotation = Quaternion.Euler(0, 0, 0); } void CorrectPosition(Vector3 CorrectPositionOF) { Vector3 posNow = transform.position; if (CorrectPositionOF.x == 1) posNow.x = Mathf.RoundToInt(gameObject.transform.position.x); if (CorrectPositionOF.y == 1) posNow.y = Mathf.RoundToInt(gameObject.transform.position.y); if (CorrectPositionOF.z == 1) posNow.z = Mathf.RoundToInt(gameObject.transform.position.z); transform.position = posNow; } public LayerMask whatIsWall; private Vector3[] direction = { Vector3.left, Vector3.forward, Vector3.back, Vector3.right }; void FixedUpdate() { GetComponent&lt;Rigidbody&gt;().velocity = movement * speed; animator.SetFloat("runningSpeed", GetComponent&lt;Rigidbody&gt;().velocity.magnitude); for (int i = 0; i &lt; direction.Length; i++) { RaycastHit hit; if (Physics.Raycast(transform.position, direction[i], out hit, 18, 0 &lt;&lt; 11 | 1 &lt;&lt; 8 | 1 &lt;&lt; 9) &amp;&amp; hit.collider.gameObject.tag == "Player" &amp;&amp; movement == Vector3.zero) { movement = direction[i]; ChangeDirection(); return; } } } } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>If you want <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">DRY</a> the <a href=\"https://en.wikipedia.org/wiki/KISS_principle\" rel=\"noreferrer\">KISS</a> way, I suggest substituting the if-chain..</p>\n\n<blockquote>\n<pre><code>if (movement == Vector3.left)\n transformModel.rotation = Quaternion.Euler(0, 270, 0);\nelse if (movement == Vector3.right)\n transformModel.rotation = Quaternion.Euler(0, 90, 0);\nelse if (movement == Vector3.back)\n transformModel.rotation = Quaternion.Euler(0, 180, 0);\nelse if (movement == Vector3.forward)\n transformModel.rotation = Quaternion.Euler(0, 0, 0);\n</code></pre>\n</blockquote>\n\n<p>..with a lookup map:</p>\n\n<pre><code>var rotationsEulerY = new Dictionary&lt;Vector3, int&gt;\n{\n {Vector3.left, 270}, {Vector3.right, 90}, {Vector3.back, 180}, {Vector3.forward, 0}\n};\n\nvoid ChangeDirection()\n{\n transformModel.rotation = Quaternion.Euler(0, rotationsEulerY[movement], 0);\n}\n</code></pre>\n\n<p>You could do something similar for <code>CorrectPosition</code> using a predefined map of guard conditions and assignor actions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T06:35:30.793", "Id": "436465", "Score": "0", "body": "Wow, thanks, though I think I don't comprehend it fully. from my understanding whenever ChangeDirection() is called the rotation on the y-axis is set to rotationEulerY[movment] which takes the current moment and checks it with the Vector3 defined in the dictionary and if a match is found the int value next to it is pushed out. I will use this code right now it. Though you see I plan to add a scenario where the enemy will not be confined and directly move towards the player so its movement vector won't be as it has been defined. so I want something that would work even then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T06:37:17.657", "Id": "436466", "Score": "0", "body": "That would be a follow-up question :) We can't know how you will extend your API upfront." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T07:46:53.363", "Id": "436470", "Score": "1", "body": "I guess you are right. though I did have to learn about how to use Dictionaries today. I am quite new to programming so I learn something new practically every day. one of the problems that I had was the way the need to be implemented I had to write `var rotationsEulerY = new Dictionary<Vector3, int>\n` as `Dictionary<Vector3, int> rotationsEulerY = new Dictionary<Vector3, int>`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T08:03:15.743", "Id": "436473", "Score": "0", "body": "Which version of .NET Framework you use?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T08:06:53.833", "Id": "436475", "Score": "0", "body": "well in my Unity player setting it is marked as .NET 4.x equivalent but it should be 4.6" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T08:17:41.297", "Id": "436478", "Score": "0", "body": "Ok I get it, as a local instance variable, you cannot declare _var_, so you did the right thing. Inside a method, using a _var_ is possible though." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T04:48:30.190", "Id": "224945", "ParentId": "224944", "Score": "6" } }, { "body": "<p>One downside to your approach is that if you later add more movement directions such as diagonal directions, you will have to add additional branches in <code>ChangeDirection</code> </p>\n\n<p>Another approach that would work with arbitrarily many possible <code>movement</code> directions is to use <a href=\"https://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html\" rel=\"nofollow noreferrer\"><code>Quaternion.LookRotation</code></a>. </p>\n\n<p><code>Quaternion.LookRotation</code> creates a Quaternion that:</p>\n\n<ol>\n<li>Rotates from <code>Vector3.forward</code> to a target vector </li>\n<li>Rotates <code>Vector3.up</code> as close as possible to a target vector that defaults to <code>Vector3.up</code></li>\n</ol>\n\n<p>Because what you are doing is calculating a Quaternion that rotates from <code>Vector3.forward</code> to <code>movement</code> while not rotating <code>Vector3.up</code>, using <code>Quaternion.LookRotation</code> makes for a very simple one-liner that explains itself to anyone who is familiar with the Unity API:</p>\n\n<pre><code>void ChangeDirection()\n{\n if(movement!=Vector3.zero)\n transformModel.rotation = Quaternion.LookRotation(movement);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T19:32:25.680", "Id": "436573", "Score": "1", "body": "You might get some votes if 1) made one or more observations about the posters code. 2) explained why the alternate solution might be better 3) explained what the alternate solution is because sometimes links get broken. Please see code review guidelines at https://codereview.stackexchange.com/help/how-to-answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T19:40:07.227", "Id": "436575", "Score": "0", "body": "@pacmaninbw thanks for the feedback. I added some more information. Hope that helps." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T21:57:45.980", "Id": "436596", "Score": "0", "body": "Thank you this works perfectly although I had to account for an exceptional case when the movement is vector.zero by using `void ChangeDirection()\n {\n if(movement!=Vector3.zero)\n transformModel.rotation = Quaternion.LookRotation(movement);\n }`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T22:01:18.220", "Id": "436597", "Score": "0", "body": "@FlamesWillBurst Thanks! I went ahead and included that in my answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T19:06:41.140", "Id": "224982", "ParentId": "224944", "Score": "4" } } ]
{ "AcceptedAnswerId": "224982", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T04:29:22.300", "Id": "224944", "Score": "2", "Tags": [ "c#", "vectors", "unity3d" ], "Title": "Quaternion and Vector3 transfomation Math" }
224944
<p>I spent some time today trying to write FizzBuzz in a functional/declarative style. I thought it would be a good chance to get some feedback on it since I've been doing functional programming for about a year now.</p> <p>(I know there are some similar questions asked here before, but their approach to the code has been different to mine and it would be good to get feedback more specific to my code)</p> <p>The main things I want to know are:</p> <ul> <li>How consistent is this code with the best practices in functional and declarative programming?</li> <li>Are there any bad practices in it that I should be aware of?</li> </ul> <pre><code>const isFizz = number =&gt; number % 5 === 0 const isBuzz = number =&gt; number % 3 === 0 const newArrayInRange = (min, max) =&gt; [...Array(max + 1).keys()].slice(min) const fizzBuzz = (min, max) =&gt; newArrayInRange(min, max) .map(number =&gt; { if (isFizz(number) &amp;&amp; isBuzz(number)) { return 'fizzbuzz' } if (isFizz(number)) { return 'fizz' } if (isBuzz(number)) { return 'buzz' } return number }) .join('\n') console.log(fizzBuzz(1, 100)) </code></pre>
[]
[ { "body": "<h2>Maybe some changes</h2>\n\n<ul>\n<li>Removing the arrays needed to hold the counter, its a huge overhead just for a counter.</li>\n<li>Avoiding excessive logic statements using <code>(num % val)</code> to return strings and using the empty string to add a number (see code marked <code>/*A*/</code>)</li>\n<li>Putting everything into an array to join when done as you have done. It is the quickest way to build a long string in JavaScript.</li>\n</ul>\n\n<p>Thus we end up with the following...</p>\n\n<pre><code>const fizz = num =&gt; num % 5 ? \"\" : \"fizz\";\nconst buzz = num =&gt; num % 3 ? \"\" : \"buzz\";\nconst fizzBuzz = num =&gt; fizz(num) + buzz(num);\nconst fizzBuzzer = (min, max) =&gt; {\n const res = [];\n do {\n const fb = fizzBuzz(min);\n res.push(fb ? fb : min); /*A*/\n } while (min++ &lt; max);\n\n return res.join(\"\\n\");\n}\n</code></pre>\n\n<p>Personally the function <code>fizz</code>, <code>buzz</code>, <code>fizzBuzz</code> are just adding code without good reason and would need to be closed over to avoid polluting what ever scope it is in.</p>\n\n<p>Thus the 3 function become the expression right of <code>const fb =</code> </p>\n\n<p>Also I am not a fan of arrow functions in an open scope so using a function declaration to ensure accessibility.</p>\n\n<pre><code>function fizzBuzzer(min, max) {\n const res = [];\n do {\n const fb = (min % 5 ? \"\" : \"fizz\") + (min % 3 ? \"\" : \"buzz\");\n res.push(fb ? fb : min);\n } while (min++ &lt; max);\n\n return res.join(\"\\n\");\n}\n</code></pre>\n\n<h2>You ask</h2>\n\n<blockquote>\n <p>How consistent is this code with the best practices in functional and declarative programming?</p>\n</blockquote>\n\n<p>Best practice, well that is subjective, contextual and would only have comparative meaning when compared to \"bad\" code?</p>\n\n<p>Your code is not bad, it works , it would have been worse 3 years back due to the way JS engines handled arrays, but now most optimizers recognize the pattern and make it fly.</p>\n\n<p>There is a zillion ways to write any bit of code. JS programmers can still not agree on the use of semicolons and whether or not automatic semicolon insertion was a good idea or not, so how is any bit of code ever going to be best practice.</p>\n\n<blockquote>\n <p>Are there any bad practices in it that I should be aware of?</p>\n</blockquote>\n\n<p>OMDG Yes there is.... Semicolons, where are they?</p>\n\n<hr>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Example of bad\nconst fizzBuzzard = (min, max) =&gt; {\n const next = n =&gt; n &lt;= max ? order[n % 15] : () =&gt; \"\";\n const txt = w =&gt; n =&gt; (w ? w : n + \"\\n\") + next(++n)(n);\n const [n, b, f, fb] = [txt(), txt(\"buzzard\\n\"), txt(\"fizz\\n\"), txt(\"fizzBuzzard\\n\")];\n const order = [fb, n, n, b, n, f, b, n, n, b, f, n, b, n, n];\n return next(min)(min);\n}\nconsole.log(fizzBuzzard(1, 100));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T04:38:55.863", "Id": "436624", "Score": "0", "body": "Thanks for your reply. I'm just a bit unclear about the example. My understanding was that using `while` loops and `min++` is not typical of functional programming, so your example is more of an imperitive style. Is that correct? And is this just done for performance reasons, or also readability?\n\nGood point about the semi-colons. I tend to lean to the opinion that it's OK to rely on minifiers and automatic semicolon insertion, but I know some developers (including Kyle Simpson) believe it's better to use them. I'll have to do some more research and reconsider my views about this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T23:24:26.890", "Id": "436761", "Score": "0", "body": "@AndreO JavaScript is not a functional language. All functions have side effects because they use a shared heap and a finite call stack. This means that functional loops (via recursion) can not be pure (call stack overflow can occur at any iteration) and loops via Array callback methods just move the syntax for the loop to the engine they are thus declarative loops. Functional Javascript as a paradigm is about style of which its most important part is the concept of abstract level side effects. The example I gave (first) is functional within this requirement." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T22:58:52.660", "Id": "224999", "ParentId": "224951", "Score": "3" } }, { "body": "<blockquote>\n <p>How consistent is this code with the best practices in functional and declarative programming?</p>\n</blockquote>\n\n<p>I dunno. Unless you're doing something fancy like <a href=\"https://www.youtube.com/watch?v=b0EF0VTs9Dc\" rel=\"nofollow noreferrer\">hand-rolling monads</a>, you might just be \"programming with functions\" and not really doing \"functional programming.\" You could ask Crockford about that, if he manages not to get himself dis-invited from your next local tech conference.</p>\n\n<blockquote>\n <p>Are there any bad practices in it that I should be aware of?</p>\n</blockquote>\n\n<p>Looks alright to me. </p>\n\n<hr>\n\n<p>Personally I like the other answer here. I voted for it and hope it wins the Checkmark Election, because it's very practical.</p>\n\n<p>But it's not what I'd call \"functional.\"</p>\n\n<pre><code>const fizzbuzz = (min, max) =&gt;\n Array(max + 1).fill('', min)\n .map((v, i) =&gt; i % 5 ? v : 'fizz')\n .map((v, i) =&gt; i % 3 ? v : v + 'buzz')\n .map((v, i) =&gt; v || i)\n .join('\\n').trim()\n</code></pre>\n\n<p>If the code in your question is \"functional,\" I suppose this is \"more functional,\" because we got rid of more of the flow control, chained even more functions together, and threw even more lambdas in there. I definitely wouldn't go as far as calling it \"declarative,\" though. It still looks imperative to me; a series of commands to be executed in a particular order. So, I see no reason to value something like this over Blindman67's approach.</p>\n\n<p>Some tasks are better suited to a declarative style (data transformations, things where it doesn't really matter exactly what order things happen in; think XSLT for example) and some are better suited to an imperative style (anything where you need precise flow control). Fizzbuzz could surely be done in a declarative way, with the right language or libraries. But with plain JavaScript, it seems much more straightforward to do it in an imperative way.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T05:01:46.707", "Id": "436625", "Score": "0", "body": "Thanks, you make some really good points about the limitations of doing functional programming with pure JavaScript, and also the types of tasks which functional/declarative code is/isn't suited to" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T01:10:06.357", "Id": "225002", "ParentId": "224951", "Score": "2" } }, { "body": "<p>First I would like to say that code can be functional <em>to a degree</em>, so I will point out what I like and what could be (even) more functional.</p>\n\n<p>I like <code>isFizz</code> and <code>isBuzz</code> because they are declarative and pure functions (i.e. they have no obvious side effects and are deterministic). I also like that the <code>map</code> does not use intermediate variables, because that would be a more imperative approach. </p>\n\n<p>A suggestion would be trying to reduce the potential number of evaluations in the <code>map</code> (for each <code>number</code>, both <code>isFizz</code> and <code>isBuzz</code> are potentially executed twice) without using intermediate variables. My suggestion can be found below in the <code>toTerms</code> function or the Ramdba pseudo code.</p>\n\n<p>After taking the course <a href=\"https://frontendmasters.com/courses/functional-javascript-v3/\" rel=\"nofollow noreferrer\">Functional-Light JavaScript v3</a>, I have attempted to write a declarative/functional FizzBuzz implementation too.</p>\n\n<p>In this course, Kyle Simpson recommends gradually converting to declarative style, which I found helpful. Also it resulted in a way over-engineered implementation, but I think it does show parts of the code that I really had to think about before finding an appropriate declarative alternative.</p>\n\n<p>The implementation is in <a href=\"https://jsfiddle.net/mdvanes/4wsnLzo0/\" rel=\"nofollow noreferrer\">this fiddle</a>, with my intermediate progress too. It also contains suggestions for further refactoring. This is the state at time of writing:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const range = (function rangeInner(acc) {\n return (first, last) =&gt; {\n if(first &gt; last) {\n return acc;\n }\n return rangeInner([...acc, first])(first + 1, last); \n }\n})([]);\n\nconst isMod3 = n =&gt; n % 3 === 0;\nconst isMod5 = n =&gt; n % 5 === 0;\n\nconst predicatesAndTerms = [\n [isMod3, \"Fizz\"],\n [isMod5, \"Buzz\"]\n]\n\nconst toTerms = n =&gt; predicatesAndTerms\n .reduce((acc, [predicateFn, term]) =&gt; acc += predicateFn(n) ? term : \"\", \"\");\n\nconst toFizzBuzz = n =&gt; toTerms(n) || n.toString();\n\nconsole.log(range(1, 15).map(toFizzBuzz));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>In an attempt to avoid potentially evaluating <code>isMod3</code> (<code>isFizz</code> in the question) and <code>isMod5</code> twice for each number, I refactored to a <code>reduce</code> over an array of \"predicate\" and \"term\" tuples, that is evaluated by a ternary operator that returns a value directly. I also tried to avoid intermediate variables as much as possible, forcing myself to create tiny cohesive functions instead.</p>\n\n<p>In an earlier version, I had a similar implementation of <code>range</code> as in the question, but I refactored it to try out recursion combined with a closure for the <code>acc</code> parameter, with the option to refactor it using <code>R.curry</code> later, (where R refers to <a href=\"https://ramdajs.com/\" rel=\"nofollow noreferrer\">Ramda</a>).</p>\n\n<p>Pseudo-code for further refactoring <code>toFizzBuzz</code> with Ramda could be:</p>\n\n<pre><code>const orDefault = fn =&gt; n =&gt; fn(n) || n; // looks like R.defaultTo, but executes fn over n first.\nconst toTermsOrDefault = orDefault(toTerms);\nconst toString = n =&gt; n.toString();\nconst toFizzBuzz = compose(toString, toTermsOrDefault);\n</code></pre>\n\n<p>Good luck learning FP JavaScript! If you want to discuss FP JS, I'm always interested. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T10:38:29.627", "Id": "476614", "Score": "1", "body": "Welcome to Code Review! You have presented an alternative solution, but haven't **reviewed the code**. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. If you want to get your own declarative code reviewed, please [ask](https://codereview.stackexchange.com/questions/ask) a new question. Thanks :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T10:01:47.963", "Id": "478015", "Score": "0", "body": "Thank you pointing that out, I have updated my original answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T11:23:12.050", "Id": "478029", "Score": "0", "body": "I'd switch both parts. The original user is interested in a review first, an alternative solution afterwards. Other than that this seems like an overall better answer :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-24T09:23:08.027", "Id": "242838", "ParentId": "224951", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T06:50:56.337", "Id": "224951", "Score": "2", "Tags": [ "javascript", "functional-programming", "fizzbuzz" ], "Title": "Functional / Declarative FizzBuzz" }
224951
<p>I have written some code that transforms 2 way matrices into 1 way matrices. Although it's comfortable to use, it's very sluggish and slow in execution. Does anyone have any idea how to improve the performance? I'm aware that the same transformation can be done with standard formulas, but solely for learning reasons I would like to stick with vba.</p> <p>How to use it - select whole matrix and execute the Sub.</p> <pre><code>Sub TwoToOneMatrix() Set Mrange = Selection colsX = Mrange.Columns.Count rowsX = Mrange.Rows.Count Set objects = Range(Mrange.Columns(1).Rows(2), Mrange.Columns(1).Rows(rowsX)) Set titleX = Range(Mrange.Columns(1).Rows(1), Mrange.Columns(1).Rows(1)) Set Rng = Application.InputBox("Select a range", "Obtain Range Object", Type:=8) 'Column 1 Rng.Value = titleX.Value def = 1 For j = 2 To objects.Rows.Count + 1 curCountry = Mrange.Columns(1).Rows(j) For i = 1 To colsX - 1 Rng.Offset(def, 0).Value = curCountry def = def + 1 Next i Next j 'Column 2 def = 1 Rng.Offset(0, 1).Value = "Date" For j = 1 To objects.Rows.Count For i = 2 To colsX curDate = Mrange.Columns(i).Rows(1) Rng.Offset(def, 1).Value = curDate def = def + 1 Next i Next j 'Column 3 Rng.Offset(0, 2).Value = "Values" def = 1 For r = 2 To rowsX For c = 2 To colsX Rng.Offset(def, 2).Value = Mrange.Columns(c).Rows(r) def = def + 1 Next c Next r End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T10:03:50.270", "Id": "436495", "Score": "2", "body": "Could you clarify briefly what you mean by 2 and 1 way matrices? What does your data look like before and after?" } ]
[ { "body": "<p>Your description is not very clear, but I see the usual suspects.</p>\n\n<h2>Indenting</h2>\n\n<p>Always indent your code properly - this makes it easier to read, easier to pick out the logic loops and easier to maintain. In itself, it does not guarantee code correctness.</p>\n\n<h2>Option Explicit</h2>\n\n<p>Always put <code>Option Explicit</code> at the top of your modules.</p>\n\n<h2>Variable names</h2>\n\n<p>Use descriptive variable names. For what you tell us the code is intended to do, <code>curDate</code> and <code>curCountry</code> mean nothing. Neither does <code>colsX</code>, <code>rowsX</code>, <code>def</code>, <code>Rng</code> or <code>Mrange</code>.</p>\n\n<h2>Use arrays</h2>\n\n<p>Using arrays will improve your performance significantly. The reason for this improvement is that you stop switching between the VBA Engine and the Excel Engine (which comes at a cost) and you work purely in the one context. You also stop working with complex objects, which also incur an overhead.</p>\n\n<p>The following is an example of how to adjust the code, but is not intended to be an accurate representation of your code.</p>\n\n<pre><code>Dim originalMatrix as Variant\noriginalMatrix = Selection.Value '&lt;-- creates an array from the range values - only time to touch Excel\nDim title as String\ntitle = CStr(originalMatrix(LBound(originalMatrix,1), LBound(originalMatrix,2))\nDim finalMatrix(,) As Variant '&lt;-- or whatever type you want here\nReDim finalmatrix(UBound(originalMatrix,1) * UBound(originalMatrix,2),2)\n\n' Adjust following loops to pick the right rows and columns.\nFor iterator1 = LBound(originalMatrix,1) To UBound(originalMatrix,1)\n For iterator2 = LBound(originalMatrix,2) To UBound(originalMatrix,2)\n finalMatrix(someCounter,1) = someValue1\n finalMatrix(someCounter,2) = someValue2\n Next iterator2\nNext iterator1\n\n'.... some code here to select output range and resize to match finalMatrix …\n' … and then\noutputRange.Value = finalMatrix '&lt;--- again, a light touch against the Excel model\n</code></pre>\n\n<p>The use of LBound and UBound protect you against any confusion as to whether your array is 1-based or 0-based.You could store these in variables if you wanted the code to read a bit better. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T10:09:24.640", "Id": "436660", "Score": "0", "body": "Thank you very much for providing me with the anwer. I'm going to improve my coding style accordingly to your remarks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T23:19:11.610", "Id": "225000", "ParentId": "224952", "Score": "3" } }, { "body": "<p>I've corrected my original code accordingly to @AJD tips. Now it's fully working and lightning fast.</p>\n\n<pre><code>Sub MatrixTransform()\n\nDim originalMatrix() As Variant\nDim finalMatrix() As Variant\n\noriginalMatrix() = Selection.Value\nMatrixRows = 1 + (Selection.Rows.Count - 1) * (Selection.Columns.Count - 1)\nReDim finalMatrix(MatrixRows, 3)\nfinalMatrix(1, 1) = CStr(Selection.Rows(1).Columns(1))\nfinalMatrix(1, 2) = \"Date\"\nfinalMatrix(1, 3) = \"Value\"\nk = 2\n\nFor i = 2 To Selection.Rows.Count\n For j = 2 To Selection.Columns.Count\n finalMatrix(k, 1) = originalMatrix(i, 1) 'object\n finalMatrix(k, 2) = originalMatrix(1, j) 'date\n finalMatrix(k, 3) = originalMatrix(i, j) 'value\n k = k + 1\n Next j\nNext i\n\nSet outputRng = Application.InputBox(\"Select range\", \"Obtain Range Object\", Type:=8)\nRange(outputRng, outputRng.Offset(MatrixRows, 3)).Value = finalMatrix\n\nEnd Sub\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T11:08:38.887", "Id": "225258", "ParentId": "224952", "Score": "0" } } ]
{ "AcceptedAnswerId": "225258", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T07:35:40.890", "Id": "224952", "Score": "1", "Tags": [ "vba", "excel" ], "Title": "Macro for transforming 2 way matrix into 1 way matrix" }
224952
<p>I would like some suggestions on how to make it better and also if any features that i should add to this Script. I am using beautifulsoup,requests for scraping and networkx for plotting the graph.</p> <p><a href="https://github.com/HardikM1999/WikiLinkMapper" rel="nofollow noreferrer">https://github.com/HardikM1999/WikiLinkMapper</a></p> <pre><code>import requests from bs4 import BeautifulSoup import sys import networkx as nx import matplotlib.pyplot as plt #Taking Arguments #Starting string start = sys.argv[1] #No of repetitions rep = int(sys.argv[2]) tot_list = [] #Creating graph G = nx.Graph() G.add_node(start) #recur function to scrape links def recur(url,depth,tot_list,parent,rep): if(depth&lt;=rep): page = requests.get('https://www.wikipedia.org/wiki/' + url) #parsing the page soup = BeautifulSoup(page.text,'html.parser') cnt = 0 #list for particular depth depth_list = [] for para_tag in soup.select('p'): for anchor_tag in para_tag.select('a'): if cnt&gt;rep: break #getting the link check_string = anchor_tag['href'] if check_string.startswith('#cite') == False and check_string.startswith('/wiki/Help') == False and check_string.startswith('/wiki///en:') == False and check_string.startswith('/wiki/Wikipedia') == False : cnt = cnt + 1 depth_list.append(check_string[6:]) if cnt&gt;rep: break for link in depth_list: tot_list.append((link,parent)) recur(link,depth+1,tot_list,link,rep) return tot_list tot_list = recur(start,0,tot_list,start,rep) node_sizes = [] node_sizes.append(100*len(start)) #Adding tot_list to the graph for a,b in tot_list: G.add_node(a) G.add_edge(a,b) node_sizes.append(100*len(a)) #Drawing the Graph nx.draw(G,node_color = 'orange',node_size = node_sizes,with_labels = True) plt.draw() plt.show() </code></pre>
[]
[ { "body": "<p>Wikipedia contains circular references. Currently you follow them around until your max depth is reached. Instead, keep a <code>set</code> of all sites visited so far.</p>\n\n<p>You also don't need this function to be recursive, you can make it iterative like this:</p>\n\n<pre><code>from collections import deque\n\ndef build_link_graph(start, max_pages=10):\n queue = deque([start])\n visited = set()\n i = 0\n while queue and i &lt; max_pages:\n next_url = queue.popleft()\n urls = get_links(next_url)\n i += 1\n # make sure not to visit any page twice\n queue.extend(url for url in urls if url not in visited) \n visited.update(urls)\n yield next_url, urls\n</code></pre>\n\n<p>The actual parsing can also be simplified using the <a href=\"https://www.w3schools.com/cssref/sel_element_gt.asp\" rel=\"nofollow noreferrer\">CSS selector <code>p &gt; a</code></a>, meaning all <code>a</code> tags which are contained in a <code>p</code> tag. I would also use a <a href=\"https://2.python-requests.org/en/master/user/advanced/#session-objects\" rel=\"nofollow noreferrer\"><code>requests.Session</code></a> to keep the connection alive and use the <a href=\"https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser\" rel=\"nofollow noreferrer\"><code>lxml</code> parser</a>, both of which slightly speed up the scraping.</p>\n\n<pre><code>def filter_links(links):\n blacklist = ['#cite', '/wiki/Help', '/wiki///en:', '/wiki/Wikipedia'] \n return [link for link in links \n if not any(link.startswith(prefix) for prefix in blacklist)]\n\ndef get_links(url):\n page = SESSION.get(url)\n soup = BeautifulSoup(page.text, \"lxml\")\n links = [a[\"href\"]\n for a in soup.select(\"p &gt; a\")\n if \"selflink\" not in a.get(\"class\", [])]\n return [BASE_URL + link for link in filter_links(links)]\n</code></pre>\n\n<p>With these functions, building the graph is rather easy. Note that you might want to choose a directed graph, since links are usually unidirectional. Also, <code>networkx</code> automatically adds missing nodes when adding edges, so no need to do that.</p>\n\n<pre><code>import sys\n\nif __name__ == \"__main__\":\n BASE_URL = \"'https://en.wikipedia.org'\"\n if len(sys.argv) == 2:\n start = sys.argv[1]\n else:\n start = BASE_URL + '/wiki/Earthquake_engineering'\n SESSION = requests.Session()\n g = nx.DiGraph()\n for url, urls in build_link_graph(start):\n graph.add_edges_from((url, link) for link in urls)\n</code></pre>\n\n<p>I added a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this script from another script without running the scraping</p>\n\n<hr>\n\n<p>Note that if you increase <code>max_pages</code> too much, you will run into a too many requests.response. Currently there is no code to handle that, but you might add some. The easiest way is to just <code>time.sleep</code> some time and try again afterwards. There are also other ways, some of which may not be in compliance with Wikipedia's ToS:</p>\n\n<pre><code># robots.txt for Wikipedia and friends\n# Please note: There are a lot of pages on this site, and there are\n# some misbehaved spiders out there that go _way_ too fast. If you're\n# irresponsible, your access to the site may be blocked.\n</code></pre>\n\n<p>There may be other ways to build this graph than scraping. Wikipedia supplies databases to download which should contain everything you need: <a href=\"https://en.wikipedia.org/wiki/Wikipedia:Database_download\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Wikipedia:Database_download</a> Note that it is 58 GB when uncompressed, though.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T08:57:16.143", "Id": "224958", "ParentId": "224954", "Score": "1" } } ]
{ "AcceptedAnswerId": "224958", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T08:07:45.307", "Id": "224954", "Score": "3", "Tags": [ "python", "graph", "web-scraping", "data-visualization", "wikipedia" ], "Title": "Wiki Link Mapper — A webcrawler which crawls links recursively and prints them into a graph" }
224954
<p>I'm making use of RxJS and observables within my Angular application to process the results of API calls and process data. I've written the component and it works without any issues. However after further research into RxJS and observables I've became aware that the way in which I am using subscriptions is considered bad practice.</p> <p>Essentially I have a function that subscribes to an observable, then inside the subscription a second function is called which doesn't make use of the data from the first subscription, but subscribes to a separate observable to track the state of a particular variable. Then within the same function a third method is called which does make use of data passed from the first subscription and uses it to make an API call and return some data.</p> <p>What I want to do is refactor this code so that the same behaviour occurs but so that I am making use of <code>switchMap</code> or other RxJS functions so that the bad practice within my code is removed. However I am unsure as to how I should be employing the use of switchMap etc.</p> <p>I'll post my code below with each function I have described and annotated.</p> <pre><code>initSettings(){ this.getOrganisations$().subscribe( (res: AdminOrganisation[]) =&gt; { //This is the first subscription that makes a get request to return an array of AdminOrganisation objects this.organisations = res; //this results of this subscription are used to display different input options to the user in the form of this.serial = this.organisations[0].serialRef; //a mat-list. this.currentOrganisationName = this.organisations[0].serialName; this.buildSettingsForm(this.serial); }); } buildSettingsForm(serial: string) { this.ipRangeFormGroup = this.formBuilder.group( { ipRanges: this.formBuilder.array([]) } ); this.numArrayElements = this.ipRangeFormArray.length; this.ipRangeFormArray.valueChanges.subscribe(changes =&gt; { //This is the second subscription, this one does not require any external inputs but does rely on the this.numArrayElements = this.ipRangeFormArray.length; //this.ipRangeFormArray being instantiated before it can be called, therefore it has to be create }); //syncronously and after the first subscription has recieved and utilised data. this.setSettings(serial); } setSettings(serial: string) { //This is the third subscription, this subscription utilises the this.serial variable that this.getSettingsFromSerial$(serial).subscribe(val =&gt; { //is retrieved by the first subscription and therefore relies on the data from the first this.savedSettingsState = val; //observable to function. Like the second sub, this one also needs to occur after the first this.ipRestrictionEnabled = val.ipRestrictionSettings.ipRestrictionEnabled; //has processed its data. for (const i of val.ipRestrictionSettings.ipRanges) { this.addRange(i.startRange, i.endRange, i.label); } this.displayForm = true; }); } </code></pre> <p>Once I have a grasp on how I should be utilising <code>switchMap</code>/<code>mergeMap</code>/etc I'll be more confident in making this refactorings and improvements myself. But since I am relatively new to Angular I'm unsure as to what the best practice is when making use of these functions to prevent chains of subscriptions like what I have below.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T13:40:56.170", "Id": "436525", "Score": "0", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please edit to the site standard, which is for the title to simply state the task accomplished by the code. Please see [**How to get the best value out of Code Review: Asking Questions**](https://CodeReview.StackExchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T14:43:28.607", "Id": "436530", "Score": "0", "body": "Please tell us what this code accomplishes, and show enough context so that we can understand it. See [ask]. Also, asking for a specific rewrite is tantamount to asking for code to be written, which is not really in the spirit of Code Review." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T08:41:32.897", "Id": "224956", "Score": "1", "Tags": [ "javascript", "angular-2+", "rxjs" ], "Title": "Processing the results of API calls and process data" }
224956
<p>The website I'm developing allows customers to book an appointment. They can also cancel their appointment with the following rules:</p> <ul> <li><p>if the appointment is cancelled between 48 hours and 1 hour in advance, the customer has to pay 50%.</p></li> <li><p>if the appointment is cancelled below 1 hour in advance, the customer should pay 100 %</p></li> <li><p>if the appointment is cancelled above 48 hours in advance, the customer has to pay 0%.</p></li> </ul> <p>My function to decide this:</p> <pre class="lang-js prettyprint-override"><code>decidePercentageToBePayed(cancelledReservation: Reservation) { const reservationYear = parseInt(cancelledReservation.getYear(), 10); const reservationMonth = parseInt(cancelledReservation.getMonth(), 10); const reservationDay = parseInt(cancelledReservation.getDay(), 10); const reservationHour = Utils.getTimeSlotHour(Utils.getStartSlot(cancelledReservation.period)); const reservationMinute = Utils.getTimeSlotMinute(Utils.getStartSlot(cancelledReservation.period)); const currentYear = parseInt(Utils.getCurrentYear(), 10); const currentMonth = parseInt(Utils.getCurrentMonth(), 10); const currentDay = parseInt(Utils.getCurrentDay(), 10); const currentHour = parseInt(Utils.getCurrentHour(), 10); const currentMinute = parseInt(Utils.getCurrentMinute(), 10); if (reservationYear &gt; currentYear) { if (reservationMonth === 1 &amp;&amp; currentMonth === 12) { if (currentDay === 30 &amp;&amp; reservationDay === 1 || currentDay === 31 &amp;&amp; reservationDay === 2) { if (currentHour &gt; reservationHour) { return 50; } return 0; } else if (currentDay === 31 &amp;&amp; reservationDay === 1) { return 50; } return 0; } return 0; } else if (reservationMonth - currentMonth &gt; 1) { return 0; } else if (reservationMonth - currentMonth === 1) { if (currentMonth === 2 &amp;&amp; Utils.isLeapYear()) { if (currentDay === 27 &amp;&amp; reservationDay === 1 || currentDay === 28 &amp;&amp; reservationDay === 2) { if (currentHour &gt; reservationHour) { return 50; } return 0; } else if (currentDay === 28 &amp;&amp; reservationDay === 1) { return 50; } return 0; } else if (currentMonth === 2 &amp;&amp; !Utils.isLeapYear()) { if (currentDay === 28 &amp;&amp; reservationDay === 1 || currentDay === 29 &amp;&amp; reservationDay === 2) { if (currentHour &gt; reservationHour) { return 50; } return 0; } else if (currentDay === 29 &amp;&amp; reservationDay === 1) { return 50; } return 0; } else if (Utils.has31Days(currentMonth)) { if (currentDay === 30 &amp;&amp; reservationDay === 1 || currentDay === 31 &amp;&amp; reservationDay === 2) { if (currentHour &gt; reservationHour) { return 50; } return 0; } else if (currentDay === 31 &amp;&amp; reservationDay === 1) { return 50; } return 0; } else { if (currentDay === 29 &amp;&amp; reservationDay === 1 || currentDay === 30 &amp;&amp; reservationDay === 2) { if (currentHour &gt; reservationHour) { return 50; } return 0; } else if (currentDay === 30 &amp;&amp; reservationDay === 1) { return 50; } return 0; } } else { if (reservationDay - currentDay &gt; 2) { return 0; } else if (reservationDay - currentDay === 2) { if (currentHour &gt; reservationHour) { return 50; } return 0; } else if (reservationDay - currentDay === 1) { return 50; } else { if (reservationHour - currentHour === 0) { return 100; } else if (reservationHour - currentHour === 1) { if (reservationMinute &lt; currentMinute) { return 100; } return 50; } return 50; } } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T13:00:37.613", "Id": "436519", "Score": "3", "body": "Just use the `Date` object eg to set to time `const time = new Date(year, month, day, hour, min)` (Note month starts at 0) subtract the current time from reservation time and divide by number ms in an hour eg `hours = (resTime.getTime() - curTime.getTime()) / (60 * 60 * 1000) ` then just test the hours `if (hours < 1) { return 100 } if (hours < 48) {return 50} return 0;` Details for `Date` at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T13:36:42.540", "Id": "436524", "Score": "0", "body": "@Blindman67 Had the same thought, will you create an answer out of your comment?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T14:14:20.350", "Id": "436529", "Score": "0", "body": "@konijn A little to much ambiguity (why all the `parseInt`s are there extra characters?) in the question for me to bother at the moment. All yours if you want it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T11:39:25.420", "Id": "436926", "Score": "0", "body": "@Blindman67 Utils returns date info as string because I almost always need them as string, except for this function and maybe one other. There are no extra characters, they are just the numbers as strings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T13:36:33.037", "Id": "436934", "Score": "1", "body": "@BasVelden You can coerce a string into a number using the unary operator `+` before the string. Eg `typeof +\"10\" === \"number\"` is true or the better option is via the Number object eg `const day = Number(Utils.getCurrentDay())` However I would never return a number as a string (especially if a number in its abstract form, eg year) To convert explicitly from number to string is seldom needed, JS will do it for you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T14:14:08.103", "Id": "436939", "Score": "0", "body": "@Blindman67 Your 2 comments taught me a lot actually, will you post an answer so I can accept it and have this post be over? Anyway, thank you for saving me a lot of time, cheers!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T09:12:19.887", "Id": "224959", "Score": "2", "Tags": [ "datetime", "typescript" ], "Title": "Calculate reservation cancellation penalty based on date difference" }
224959
<p><a href="https://www.geeksforgeeks.org/print-sums-subsets-given-set/" rel="noreferrer">Print sums of all subsets of a given set</a> </p> <p><strong>Problem summary</strong> : Print all subset sums of a given set of integers</p> <p>My approach is to store previous results and use them to calculate new (similar idea as DP).</p> <p><code>SubsetSum.cpp</code></p> <pre class="lang-cpp prettyprint-override"><code>#include&lt;iostream&gt; #include&lt;vector&gt; //using namespace std; bool isPowerOf2 (long long x) { /* First x in the below expression is for the case when x is 0 */ return x &amp;&amp; (!(x&amp;(x-1))); } std::vector&lt;long long&gt; subsetSums(std::vector&lt;int&gt; set) { long long total = 1&lt;&lt;set.size(); //total number of subsets = size of power set = 2^n std::vector&lt;long long&gt; sums(total, 0); sums[1] = set[0]; //std::cout &lt;&lt; sums[0] &lt;&lt; std::endl; //std::cout &lt;&lt; sums[1] &lt;&lt; std::endl; int effectiveBits = 1, prevPowOf2 = 1; for (long long i = 2; i &lt; total; ++i) { if (isPowerOf2(i)) { ++effectiveBits; prevPowOf2 *= 2; } //std::cout &lt;&lt; "e = " &lt;&lt; effectiveBits &lt;&lt; "\tp = " &lt;&lt; prevPowOf2 &lt;&lt; std::endl; sums[i] = set[effectiveBits-1] + sums[i-prevPowOf2]; //std::cout &lt;&lt; sums[i] &lt;&lt; "\n"; } return sums; } // Driver code int main() { std::vector&lt;int&gt; set = {5, 4, 3}; std::vector&lt;long long&gt; sumsOfAllSubsets = subsetSums(set); for (auto sum : sumsOfAllSubsets) std::cout &lt;&lt; sum &lt;&lt; "\n"; return 0; } </code></pre> <p>You can find the code on <a href="https://gist.github.com/Gaurav-Singh-97/6174257361b6c0e12dfd163d527ada61" rel="noreferrer">Github Gist</a> and compilation result at <a href="https://onlinegdb.com/B1Bj8DuMS" rel="noreferrer">OnlineGdb</a>.</p> <p>Along with code, please also comment on the algorithm itself.<br> Is it advisable to store previous result in practice (since it takes 2^n space)?<br> Also, is there any scope of improving time or space without trading-off the other?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T07:58:27.103", "Id": "436647", "Score": "2", "body": "My generalization and optimization inspired by this question and answers below: https://codereview.stackexchange.com/q/225018" } ]
[ { "body": "<h1>Preface</h1>\n\n<p>This is great code. Your solution is more than <span class=\"math-container\">\\$10^{42}\\$</span> times nicer than the given solutions on the linked page that promote crap like <code>#include &lt;bits/stdc++.h&gt;</code>. You are already much better than them in this regard.</p>\n\n<h1>The algorithm</h1>\n\n<p>Making use of the STL, your algorithm can be simplified like this:</p>\n\n<pre><code>std::vector&lt;long long&gt; subsetSums(const std::vector&lt;int&gt;&amp; set)\n{\n std::vector&lt;long long&gt; subset_sums{0};\n subset_sums.reserve(std::size_t(1) &lt;&lt; set.size()); // to prevent iterator invalidation\n for (int num : set)\n std::transform(subset_sums.begin(), subset_sums.end(),\n std::back_inserter(subset_sums),\n [=](number_t prev_sum){ return prev_sum + num; });\n return subset_sums;\n}\n</code></pre>\n\n<p>(You need <code>#include &lt;algorithm&gt;</code> for <code>std::transform</code> and <code>#include &lt;iterator&gt;</code> for <code>std::back_inserter</code>) Here, we first push <code>0</code> to the list of sums. Then, for each element <span class=\"math-container\">\\$x\\$</span>, we add <span class=\"math-container\">\\$x\\$</span> to the previous sums and push these new sums. Therefore:</p>\n\n<ol>\n<li><p>The initial list of sums is <code>{0}</code>.</p></li>\n<li><p>For the first element <code>5</code>, the list becomes <code>{0, 5}</code>, where <code>5 = 0 + 5</code>.</p></li>\n<li><p>For the second element <code>4</code>, the list becomes <code>{0, 5, 4, 9}</code>, where <code>{4, 9} = {0, 5} + 4</code>.</p></li>\n<li><p>For the third element <code>3</code>, the list becomes <code>{0, 5, 4, 9, 3, 8, 7, 12}</code>, where <code>{3, 8, 7, 12} = {0, 5, 4, 9} + 3</code>.</p></li>\n</ol>\n\n<h1>Miscellaneous</h1>\n\n<p>The common practice is to put a space between <code>#include</code> and the header name, as in <code>#include &lt;iostream&gt;</code>. And simply delete <code>using namespace std;</code> rather than commenting it out to show you are following good practice&nbsp;:)</p>\n\n<p>You use <code>int</code> for the original numbers, and <code>long long</code> for the sums. Don't mix different data types. Write a type alias like</p>\n\n<pre><code>using number_t = long long;\n</code></pre>\n\n<p>And use it consistently throughout your code. This makes it clear what these types are used for.</p>\n\n<p><code>i</code> should really be of an unsigned type. And <code>isPowerOf2</code> should also operate on an unsigned type. The <code>isPowerOf2</code> function can be made <code>constexpr</code>. And I prefer a looser layout with more spaces and less parentheses:</p>\n\n<pre><code>constexpr bool isPowerOf2(std::size_t x)\n{\n /* First x in the below expression is for the case when x is 0 */\n return x &amp;&amp; !(x &amp; (x - 1));\n}\n</code></pre>\n\n<p><code>1 &lt;&lt; set.size()</code> potentially overflows. <code>std::size_t(1) &lt;&lt; set.size()</code> is better. For me, it may be better to extract a function and check for overflow:</p>\n\n<pre><code>// returns 2^n\ntemplate &lt;typename T, std::enable_if_t&lt;std::is_integral_v&lt;T&gt; &amp;&amp; is_unsigned_v&lt;T&gt;, int&gt; = 0&gt;\nconstexpr T power2(T n)\n{\n assert(n &lt; std::numeric_limits&lt;T&gt;::digits);\n return T(1) &lt;&lt; n;\n}\n</code></pre>\n\n<p>Passing a <code>std::vector</code> by value may cause unnecessary copies. Pass by <code>const</code> reference instead.</p>\n\n<p><code>return 0;</code> can be omitted for the <code>main</code> function.</p>\n\n<h1>The future</h1>\n\n<p>C++20 provides us with <a href=\"https://en.cppreference.com/w/cpp/header/bit\" rel=\"nofollow noreferrer\">bit manipulation utilities</a>. We can replace <code>isPowerOf2(i)</code> with <code>std::ispow2(i)</code> (after you make <code>i</code> unsigned). The aforementioned <code>power2</code> function can also be improved with concepts:</p>\n\n<pre><code>// returns 2^n\ntemplate &lt;std::UnsignedIntegral T&gt;\nconstexpr T power2(T n)\n{\n assert(n &lt; std::numeric_limits&lt;T&gt;::digits);\n return T(1) &lt;&lt; n;\n}\n</code></pre>\n\n<p>The algorithm can also be simplified with the <a href=\"https://ericniebler.github.io/range-v3/\" rel=\"nofollow noreferrer\">Ranges library</a> and <a href=\"https://en.cppreference.com/w/cpp/utility/functional/bind_front\" rel=\"nofollow noreferrer\"><code>std::bind_front</code></a>:</p>\n\n<pre><code>std::vector&lt;number_t&gt; subsetSums(const std::vector&lt;number_t&gt;&amp; set)\n{\n std::vector&lt;number_t&gt; subset_sums{0};\n subset_sums.reserve(std::size_t(1) &lt;&lt; set.size());\n for (int num : set)\n ranges::push_back(subset_sums,\n subset_sums | ranges::view::transform(std::bind_front(ranges::plus, num)));\n return subset_sums;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T12:45:18.400", "Id": "436518", "Score": "3", "body": "Arguably, it makes sense to use a different type for the sum, as it likely has to represent a bigger range. Unfortunately, we don't know whether `long long` actually does have a bigger range than `int` (both could be simple 64-bit values, for example)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T16:19:37.343", "Id": "436557", "Score": "0", "body": "Great analysis. I now have things to learn about, like `std::transform`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T07:05:47.893", "Id": "436635", "Score": "3", "body": "exponential space algorithms are never \"great\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T07:11:49.007", "Id": "436636", "Score": "1", "body": "@WillNess Good point. I just saw your answer and upvoted. Although I never said this *algorithm* is great :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T07:13:59.320", "Id": "436637", "Score": "0", "body": "I've edited, to clarify some points. :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T12:24:08.520", "Id": "224965", "ParentId": "224964", "Score": "10" } }, { "body": "<p>This is bad. You calculate them all first, and only then print them out. And what if <em>n</em> = <em>20</em>, or <em>42</em>, or <em>100</em>? The printout will never start (and the memory will blow up before that, too). </p>\n\n<p>Instead, have your program <strong>create</strong> <em>n</em> <em>nested loops</em> <strong>at run-time</strong>, in effect enumerating the binary encoding of <i>2<sup>&hairsp;n</sup></i>, and print the sums out from the innermost loop. In pseudocode:</p>\n\n<pre><code> // {5, 4, 3}\n sum = 0\n for x in {5, 0}: // included, not included\n sum += x\n for x in {4, 0}:\n sum += x\n for x in {3, 0}:\n sum += x\n print sum\n sum -= x\n sum -= x\n sum -= x\n</code></pre>\n\n<p>You can emulate the loops creation with recursion, coding only one recursive function. Pass it the array (<code>{5, 4, 3}</code> in your example) and a zero-based index, and work as shown above with <code>x in {arr[i], 0}</code>, making the recursive call with <code>i+1</code>, if <code>i</code> is in bounds (<code>i &lt; n</code>); or print the <code>sum</code> value out, otherwise. The <code>for</code> loop can be inlined away as well, since there always are only two numbers to process, <code>arr[i]</code> and <code>0</code>.</p>\n\n<p>You did say <em>print</em>. Storing them is an insanely ginormous overkill.</p>\n\n<p><em>edit:</em>\nThus concludes the algorithmic review, which you did request. No point to reviewing the code when algorithm is unsuitable for the task. Exponential space algorithms are never good when there's a linear space algorithm to be had.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T03:36:58.137", "Id": "436619", "Score": "0", "body": "`You can emulate the loops with recursive function calls.` using recursion, I see how to *not* need different source code for different *n*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T04:35:18.467", "Id": "436623", "Score": "1", "body": "(Down-voters please comment. The tool-tip I get reads *not useful*.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T06:50:39.797", "Id": "436633", "Score": "0", "body": "@greybeard that was the point, yes. some languages actually do allow you to create (the equivalent of) nested loops in run time, which is what I meant obviously (by \"create\"), not the hard coded *n* loops. But in C and derivatives, recursion can do that. -- Re \"useful\", right now we have an exponential space algo at +9 votes, and a linear space algo at -1. Just NB. -- also, with recursion, `for` isn;t needed, it can be inlined. I wrote it that way so that correctness is self-evident." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T07:20:24.033", "Id": "436638", "Score": "0", "body": "Also, this idea can be generalized with output iterators, so that the caller can customize the output format, or choose to store the results somewhere, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T07:34:37.213", "Id": "436639", "Score": "0", "body": "Using recursion seems like a better idea than my algorithm (same time, less space). But it will also use call stack. Don't we need to consider that? Edit : Sorry, my bad. Call stack will take max n space at any time. Realized after commenting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T07:48:37.023", "Id": "436644", "Score": "0", "body": "@GauravSingh yes, exactly. it will be linear in size. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T07:51:49.177", "Id": "436645", "Score": "0", "body": "@L.F. (yes, exactly! emulating Prolog / nondeterministic programming, somewhat.) otherwise known as [\"callbacks\"](https://stackoverflow.com/search?q=user%3A849891+callback). (the link is to my answers on SO which are using this technique. both are in Lisp though, although there's some pseudocode :) )" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T07:59:42.067", "Id": "436648", "Score": "0", "body": "@WillNess I advertised your answer in my rewrite https://codereview.stackexchange.com/q/225018. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T08:00:03.533", "Id": "436649", "Score": "0", "body": "@L.F. thanks for the heads up. :)" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T22:12:56.710", "Id": "224996", "ParentId": "224964", "Score": "6" } }, { "body": "<p>Said before, but not by me: storing even half of the final result is <em>not</em> advisable. </p>\n\n<p>An <em>n</em>-bit <a href=\"https://en.m.wikipedia.org/wiki/Gray_code\" rel=\"nofollow noreferrer\">Gray-code</a> assumes every combination of <em>n</em> values of 0 (use for <em>not included</em>) and 1 (included) - while only changing <em>one</em> bit in every transition:<br>\nstart with code and sum 0<br>\nfor the changing bit <em>i</em> turning to one, add the <em>i</em>th array item<br>\nsubtract for a change from one to zero</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T04:18:04.147", "Id": "436621", "Score": "0", "body": "There are just too many ways to use this in an implementation for me to decide on one, starting with bothering not to limit array length to number of bits in a suitable integer type." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T04:16:47.743", "Id": "225007", "ParentId": "224964", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T11:43:16.273", "Id": "224964", "Score": "11", "Tags": [ "c++", "algorithm", "programming-challenge", "combinatorics" ], "Title": "Print sums of all subsets" }
224964
<p>I made a program to explore the symmetries of an equilateral triangle using Python and Turtle Graphics. It's formatted using Black Playground.</p> <p>As usual, my goal is to be writing "code that doesn't suck." What do I need to to to achieve that goal is this instance please?</p> <p>I'm guessing some repetition could be avoided, and I know globals are evil, but are they as evil as passing parameters to a <code>tkinter</code> callback?</p> <p>Would the code benefit from refactoring to be entirely OOP, or would that be overkill for something so relatively simple?</p> <pre><code>import turtle import tkinter as tk screen = turtle.Screen() class Label(turtle.Turtle): def __init__(self, coordinates=[0, 0], screen=screen): turtle.Turtle.__init__(self) self.text = "" self.color("white") self.coordinates = coordinates self.hideturtle() self.penup() self.screen = screen def show(self, message, alignment="center", size=18): self.screen.tracer(0) self.clear() self.goto(self.coordinates) self.write( message, font=("Arial", size), align=alignment ) self.screen.tracer(1) def show_labels(vertices): global label1, label2, label3 label1.show(vertices[0]) label2.show(vertices[1]) label3.show(vertices[2]) def clear_labels(): global label1, label2, label3 label1.clear() label2.clear() label3.clear() def reset(): global vertices, triangle vertices = ["A", "B", "C"] show_labels(vertices) def rotate_clockwise(): global vertices, triangle temp = vertices[-1] for i in range(len(vertices) - 1, 0, -1): vertices[i] = vertices[i - 1] vertices[0] = temp clear_labels() triangle.right(120) show_labels(vertices) def rotate_anticlockwise(): global vertices, triangle temp = vertices[0] for i in range(len(vertices) - 1): vertices[i] = vertices[i + 1] vertices[-1] = temp update_rotation() def reflect_A(): global vertices b_pos = vertices.index("B") c_pos = vertices.index("C") vertices[b_pos], vertices[c_pos] = ( vertices[c_pos], vertices[b_pos], ) update_reflection() def reflect_B(): global vertices a_pos = vertices.index("A") c_pos = vertices.index("C") vertices[a_pos], vertices[c_pos] = ( vertices[c_pos], vertices[a_pos], ) update_reflection() def reflect_C(): global vertices a_pos = vertices.index("A") b_pos = vertices.index("B") vertices[a_pos], vertices[b_pos] = ( vertices[b_pos], vertices[a_pos], ) update_reflection() def update_rotation(): global triangle clear_labels() triangle.left(120) show_labels(vertices) def update_reflection(): global triangle clear_labels() show_labels(vertices) def show_labels(vertices): global label1, label2, label3 label1.show(vertices[0]) label2.show(vertices[1]) label3.show(vertices[2]) def clear_labels(): global label1, label2, label3 label1.clear() label2.clear() label3.clear() canvas = screen.getcanvas() font = ("Helvetica", 12) reset_button = tk.Button( canvas.master, font=font, text="Reset", background="hotpink", foreground="white", bd=0, command=reset, ) canvas.create_window(0, -250, window=reset_button) rotate_clockwise_button = tk.Button( canvas.master, font=font, text="Rotate 120° clockwise", background="hotpink", foreground="white", bd=0, command=rotate_clockwise, ) canvas.create_window( 0, -150, window=rotate_clockwise_button ) rotate_anticlockwise_button = tk.Button( canvas.master, font=font, text="Rotate 120° anticlockwise", background="hotpink", foreground="white", bd=0, command=rotate_anticlockwise, ) canvas.create_window( 0, -200, window=rotate_anticlockwise_button ) reflect_A_button = tk.Button( canvas.master, font=font, text="Reflect about perp. bisector of BC", background="hotpink", foreground="white", bd=0, command=reflect_A, ) canvas.create_window(0, 100, window=reflect_A_button) reflect_B_button = tk.Button( canvas.master, font=font, text="Reflect about perp. bisector of AC", background="hotpink", foreground="white", bd=0, command=reflect_B, ) canvas.create_window(0, 150, window=reflect_B_button) reflect_C_button = tk.Button( canvas.master, font=font, text="Reflect about perp. bisector of AB", background="hotpink", foreground="white", bd=0, command=reflect_C, ) canvas.create_window(0, 200, window=reflect_C_button) screen.setup(500, 600) screen.title("Symmetries of an Equilateral Triangle") screen.bgcolor("blue") label1 = Label([-85, -55]) label2 = Label([0, 75]) label3 = Label([85, -55]) triangle = turtle.Turtle("triangle") triangle.shapesize(120 / 20) triangle.color("hotpink") triangle.right(30) vertices = ["A", "B", "C"] show_labels(vertices) turtle.done() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T14:55:52.310", "Id": "436534", "Score": "0", "body": "Just as a general comment, you can also review past answers to get a good list of things to do - and update your code before you post your question. Nonetheless, thanks for your post." } ]
[ { "body": "<p>I'm not an experienced user of either tkinter not turtle graphics, so I can't offer specific improvements with regards to those. I can offer some general Python advice though.</p>\n\n<hr>\n\n<p>I like the Label class here. It was a good choice.</p>\n\n<pre><code>def __init__(self, coordinates=[0, 0], screen=screen):\n</code></pre>\n\n<p>This line has the potential to create a nasty and hard to find bug. The issue is with coordinates=[0,0]. I'll try to highlight why with an example.</p>\n\n<pre><code>class A():\n def __init__(self, coords=[0, 0]):\n self.coords = coords\n\n\napple = A()\nbanana = A()\nprint(apple.coords, banana.coords) # [0, 0] [0, 0]\napple.coords[0] = 5\nprint(apple.coords, banana.coords) # [5, 0] [5, 0]\n</code></pre>\n\n<p>As you can see from the example, somehow two different instances are sharing the coords between them. The cause of this is that the list [0, 0] is the same list each time a new instance is made. See <a href=\"https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments\" rel=\"nofollow noreferrer\">mutable default args</a> for more info.</p>\n\n<p>I would fix it like this</p>\n\n<pre><code>class Label(turtle.Turtle):\n def __init__(self, coordinates=None, screen=screen):\n ...\n if coordinates is None:\n self.coordinates = [0, 0]\n else:\n self.coordinates = coordinates\n</code></pre>\n\n<p>Then you wont hit this problem again until you start changing the coordinates of a Label that you create with the same list. Be careful with lists!</p>\n\n<pre><code># Bad, has the same problem\ncoords = [0, 0]\none, two = Label(coords), Label(coords)\none.coordinates[0] = 5\nprint(one.coordinates, two.coordinates) # [5, 0] [5, 0]\n\n# Good, doesn't have the problem\none, two = Label([0, 0]), Label([0, 0])\none.coordinates[0] = 5\nprint(one.coordinates, two.coordinates) # [5, 0] [0, 0]\n</code></pre>\n\n<hr>\n\n<pre><code>def clear_labels():\n global label1, label2, label3\n label1.clear()\n label2.clear()\n label3.clear()\n</code></pre>\n\n<p>I would make a (global) list of labels and loop through them all. This means you can add more labels if you need to without changing much code.</p>\n\n<pre><code>all_labels = [label1, label2, label3]\n\ndef clear_labels():\n for label in all_labels:\n label.clear()\n</code></pre>\n\n<hr>\n\n<pre><code>def show_labels(vertices):\n global label1, label2, label3\n label1.show(vertices[0])\n label2.show(vertices[1])\n label3.show(vertices[2])\n</code></pre>\n\n<p>(Small aside, this function and clear_labels are defined twice)\nI would once again loop over a global list of labels. You loop over two lists at the same time with zip, for example</p>\n\n<pre><code>for number, letter in zip([1, 2, 3], ['A', 'B', 'C']):\n print(number, letter)\n\n# 1 A\n# 2 B\n# 3 C\n</code></pre>\n\n<p>The code would look like this</p>\n\n<pre><code>def show_labels(vertices):\n for label, vertex in zip(all_labels, vertices):\n label.show(vertex)\n</code></pre>\n\n<hr>\n\n<pre><code>def reset():\n global vertices, triangle\n vertices = [\"A\", \"B\", \"C\"]\n show_labels(vertices)\n</code></pre>\n\n<p>Don't set a global vertices here. Pass it in if it is needed, or construct it on the fly.</p>\n\n<hr>\n\n<pre><code>def rotate_clockwise():\n ....\n temp = vertices[-1]\n for i in range(len(vertices) - 1, 0, -1):\n vertices[i] = vertices[i - 1]\n vertices[0] = temp\n</code></pre>\n\n<p>There is a much nicer way to rotate lists using slicing. It is good in that it also works for the immutable tuple as well. See <a href=\"https://stackoverflow.com/questions/9457832/python-list-rotation\">this answer on stackoverflow</a> for the source.</p>\n\n<pre><code> clear_labels()\n triangle.right(120)\n show_labels(vertices)\n</code></pre>\n\n<p>This looks like it should be part of update_rotation, especially since rotate_anticlockwise calls update_rotation.</p>\n\n<hr>\n\n<p>In this example I'm taking a few liberties such as making one function do all the work, but I think it makes the example easier to digest. I don't know if I've put in all the globals I need to.</p>\n\n<pre><code>def reflect_A():\n global vertices\n b_pos = vertices.index(\"B\")\n c_pos = vertices.index(\"C\")\n vertices[b_pos], vertices[c_pos] = (\n vertices[c_pos],\n vertices[b_pos],\n )\n\n update_reflection()\n\ndef reflect_B():\n ...\n a_pos = vertices.index(\"A\")\n c_pos = vertices.index(\"C\")\n ...\n</code></pre>\n\n<p>Here you have a large amount of repeated code. Since only the indices change between each function, I would recommend making a new function that takes the indices to swap, and does all the work (including update_reflection).</p>\n\n<pre><code>def reflect(ind1, ind2):\n \"\"\"Reflect by swapping the vertices at ind1 and ind2.\"\"\"\n global vertices\n vertices[ind1], vertices[ind2] = vertices[ind2], vertices[ind1]\n # inlined update_reflection\n global triangle\n clear_labels()\n show_labels(vertices)\n</code></pre>\n\n<p>Then you can call reflect in each function. If you want to be fancy you can define the functions with partial. Partial turns a function into another function with some parameters set. Here is an example with partial.</p>\n\n<pre><code>def print_hello():\n print('hello')\nprint_hello() # hello\n\nfrom functools import partial\nprint_hello = partial(print, 'hello')\nprint_hello() # hello\n</code></pre>\n\n<p>And an example of defining reflect_*</p>\n\n<pre><code>reflect_A = partial(reflect, vertices.index(\"A\"), vertices.index(\"B\"))\nreflect_B = partial(reflect, vertices.index(\"A\"), vertices.index(\"C\"))\nreflect_C = partial(reflect, vertices.index(\"B\"), vertices.index(\"C\"))\n</code></pre>\n\n<hr>\n\n<p>And finally here are some nitpicks and/or food for thought.</p>\n\n<ol>\n<li>You use two different fonts, why?</li>\n<li>Can you change each function with a global to accept the parameter as an argument instead? Ideally every time you call a function with some set of parameters it should do exactly the same thing. For example, <code>f([], 'a') -&gt; ['a']</code> is good, <code>f('a') -&gt; None</code> but some global variable gets updated is bad, as it tends to make code harder to {update,maintain,understand,reason about,debug,share without other people getting mad at you}.</li>\n<li>Can you remove the turtle and do everything with tkinter? Can you remove tkinter and do everything in turtle graphics?</li>\n<li>Sometimes somebody wants to change something and does not want to edit code. Things like the colour of the background, or the title of the window, or the text when you hover over a button. Can you make a separate config file that has the full colour-scheme?</li>\n<li>What happens if you change the vertices' names from ['A', 'B', 'C'] to ['X', 'Y', 'Z']? How much of the code breaks? Should it break? Does it change everywhere it needs to?</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T15:38:15.067", "Id": "224969", "ParentId": "224967", "Score": "2" } }, { "body": "<p>Starting at the bottom of the code:</p>\n\n<p>You don't have an <code>if __name__ == '__main__':</code> block. Unless things have changed in Python 3, you really ought to have one. (This distinguishes \"module setup\" code that should be run on every import of this .py file, from \"main program\" code that should only run when the .py file is run as a program.) Arguably it's just boilerplate in this case, but I think it's <em>good-habit-forming</em> boilerplate.</p>\n\n<hr>\n\n<pre><code>font = (\"Helvetica\", 12)\n\nreset_button = tk.Button(\n canvas.master,\n font=font,\n text=\"Reset\",\n background=\"hotpink\",\n foreground=\"white\",\n bd=0,\n command=reset,\n)\n</code></pre>\n\n<p>On the other hand, this feels like <em>bad</em> boilerplate. Global variables are never nice, even when you promise their values are constant. Kneejerk, I would prefer to write</p>\n\n<pre><code>reset_button = tk.Button(\n canvas.master,\n font=(\"Helvetica\", 12),\n text=\"Reset\",\n background=\"hotpink\",\n foreground=\"white\",\n bd=0,\n command=reset,\n)\n</code></pre>\n\n<p>But you'd have to duplicate that <code>font=(\"Helvetica\", 12)</code> assignment in several places! Well, programming is the art of detecting and removing duplication. Let's take the duplicated code and factor it out:</p>\n\n<pre><code>def make_button(canvas, text, command):\n return tk.Button(\n canvas.master,\n font=(\"Helvetica\", 12),\n text=text,\n background=\"hotpink\",\n foreground=\"white\",\n bd=0,\n command=command,\n )\n\nreset_button = make_button(canvas, \"Reset\", reset)\ncanvas.create_window(0, -250, window=reset_button)\n\nrotate_clockwise_button = make_button(canvas, \"Rotate 120° clockwise\", rotate_clockwise)\ncanvas.create_window(\n 0, -150, window=rotate_clockwise_button\n)\n\nrotate_anticlockwise_button = make_button(canvas, \"Rotate 120° anticlockwise\", rotate_anticlockwise)\ncanvas.create_window(\n 0, -200, window=rotate_anticlockwise_button\n)\n\nreflect_A_button = make_button(\"Reflect about perp. bisector of BC\", reflect_A)\ncanvas.create_window(0, 100, window=reflect_A_button)\n\n[...]\n</code></pre>\n\n<p>Now we see some more repetition. We also see a bunch of one-use global variables, such as <code>reset_button</code>, which don't need to be global (or exist at all, really). We also see one surprising asymmetry: you wrote the call to <code>canvas.create_window</code> as a three-liner in one place, whereas it's a one-liner in every other place.</p>\n\n<p>So let's factor out the repetition and eliminate the asymmetry:</p>\n\n<pre><code>def create_button(canvas, x, y, text, command):\n canvas.create_window(x, y, window=make_button(canvas, text, command))\n\ncanvas = screen.getcanvas()\ncreate_button(canvas, 0, -250, \"Reset\", reset)\ncreate_button(canvas, 0, -150, \"Rotate 120° clockwise\", rotate_clockwise)\ncreate_button(canvas, 0, -200, \"Rotate 120° anticlockwise\", rotate_anticlockwise)\ncreate_button(canvas, 0, 100, \"Reflect about perp. bisector of BC\", reflect_A)\ncreate_button(canvas, 0, 150, \"Reflect about perp. bisector of AC\", reflect_B)\ncreate_button(canvas, 0, 200, \"Reflect about perp. bisector of AB\", reflect_C)\n</code></pre>\n\n<p>What took you 72 lines in the original code, now takes 21 lines.</p>\n\n<hr>\n\n<p>I suggest applying this kind of redundancy-removal everywhere you can in your code, and then re-posting it as a new question. There are more interesting possibilities to discuss, re your interest in triangle symmetries. For example, maybe instead of hard-coding ideas like \"the altitude through A hits the midpoint of BC; the altitude through B hits the midpoint of AC; the altitude through C hits the midpoint of AB,\" maybe you could encode the general principle that \"the altitude through (x) hits the midpoint of (the two labeled points that aren't x).\" You <em>might</em> approach that in roughly the same way that I approached the idea of \"how to create a button with text (x) and command (y).\"</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T16:21:23.713", "Id": "224974", "ParentId": "224967", "Score": "3" } } ]
{ "AcceptedAnswerId": "224969", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T13:06:08.917", "Id": "224967", "Score": "2", "Tags": [ "python", "tkinter", "turtle-graphics" ], "Title": "Symmetries of Triangle Python Turtle" }
224967
<p>Recently I am learning to program in Python and in order to practice I tried to program a little game which consists in a board with 9 cells. In this board each player draw an 'X' or 'O' with left or right mouse button. The next code is a simplification with only 3-cell board.</p> <h1>Code 1: View</h1> <pre><code>from tkinter import * import numpy as np from line3 import * juego = Tablero() root = Tk() def leftClick1(event): canvas1.create_line(0,0,50,50) canvas1.create_line(0, 50, 50, 0) juego.ponerFicha(0,0,1) def leftClick2(event): canvas2.create_line(0,0,50,50) canvas2.create_line(0, 50, 50, 0) juego.ponerFicha(0,1,1) def leftClick3(event): canvas3.create_line(0,0,50,50) canvas3.create_line(0, 50, 50, 0) juego.ponerFicha(0,2,1) def rightClick1(event): create_circle(24, 24, 20, canvas1) juego.ponerFicha(0,0,2) def rightClick2(event): create_circle(24, 24, 20, canvas2) juego.ponerFicha(0,1,2) def rightClick3(event): create_circle(24, 24, 20, canvas3) juego.ponerFicha(0,2,2) topFrame = Frame(root) topFrame.pack() middleFrame = Frame(root) middleFrame.pack() bottomFrame = Frame(root) bottomFrame.pack() canvas1 = Canvas(topFrame, width=50, height=50) canvas2 = Canvas(topFrame, width=50, height=50) canvas3 = Canvas(topFrame, width=50, height=50) canvas1.bind(&quot;&lt;Button-1&gt;&quot;, leftClick1) canvas2.bind(&quot;&lt;Button-1&gt;&quot;, leftClick2) canvas3.bind(&quot;&lt;Button-1&gt;&quot;, leftClick3) canvas1.bind(&quot;&lt;Button-3&gt;&quot;, rightClick1) canvas2.bind(&quot;&lt;Button-3&gt;&quot;, rightClick2) canvas3.bind(&quot;&lt;Button-3&gt;&quot;, rightClick3) canvas1.pack(side=LEFT) canvas2.pack(side=LEFT) canvas3.pack(side=LEFT) canvas1.create_line(50,50,0,50) canvas1.create_line(50,50,50,0) canvas2.create_line(50,50,0,50) canvas2.create_line(50,50,50,0) canvas3.create_line(50,50,0,50) canvas3.create_line(50,50,50,0) root.mainloop() </code></pre> <h1>Code 2: Classes and utils</h1> <pre><code>import numpy as np class Tablero: def __init__(self): self.tablero = np.zeros((3,3)) def ponerFicha(self, x, y, tipoFicha): if (self.tablero[x][y] == 0): self.tablero[x][y] = tipoFicha print(self.tablero) # Taken from StackOverFlow question def create_circle(x, y, r, canvasName): #center coordinates, radius x0 = x - r y0 = y - r x1 = x + r y1 = y + r return canvasName.create_oval(x0, y0, x1, y1) </code></pre> <p>I feel I am repeating a lot of code when I programmed two events for each cell.</p> <ul> <li>Is it possible to have one listener for all the cells?</li> <li>How could I avoid repeat so much code?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T13:05:19.497", "Id": "436555", "Score": "0", "body": "Eva, I have an answer for you if you would ask this question on Code Review." } ]
[ { "body": "<blockquote>\n <p>Is it possible to have one listener for all the cells?</p>\n</blockquote>\n\n<p>You still have to bind to each canvas but we can bind to one function that can handle all your conditions. The best way to do this is to put your canvas widgets into a list and then reference them by index.</p>\n\n<blockquote>\n <p>How could I avoid repeat so much code?</p>\n</blockquote>\n\n<p>Its good to try and reduce your code. Try to keep it DRY (Don't Repeat Yourself) is something to strive for and in this case the bast way to do this is to build a single function that can handle all your conditions based on the event being passed and an index value.</p>\n\n<p>Another helpful way to stay DRY is to know when to use a <code>for</code> loop to managed creations of widgets or variables needed. Here I have changed your code to use a for loop to build a list with your canvas widgets and apply the binds and pack all at once.</p>\n\n<p>I have also added a check to see if something has already been written to your canvas so it cannot be overwritten.</p>\n\n<p>By utilizing a list to and building our functionality around that list we can reduce the amount of code we need and at the same time make the boxes infantry scalable.</p>\n\n<p>I have added a variable called <code>np_tuple</code>. All you have to do is change the numbers to change the size of your game.</p>\n\n<p>I have combined all your code into one <code>.py</code> file but you can easily move your <code>Tablero</code> class back out.</p>\n\n<pre><code>from tkinter import *\nimport numpy as np\n\n\nclass Tablero:\n def __init__(self, np_tuple):\n self.tablero = np.zeros(np_tuple)\n\n def poner_ficha(self, x, y, tipo_ficha):\n if self.tablero[x][y] == 0:\n self.tablero[x][y] = tipo_ficha\n # print(self.tablero)\n\n\nroot = Tk()\nclist = []\nnp_tuple = (3, 3)\njuego = Tablero(np_tuple)\n\n\ndef create_circle(x, y, r, canvas_name):\n canvas_name.create_oval(x - r, y - r, x + r, y + r)\n\n\ndef click(event, xdex, ydex):\n if clist[xdex][ydex][1] == '':\n if event.num == 1:\n clist[xdex][ydex][1] = 'X'\n clist[xdex][ydex][0].create_line(0, 0, 50, 50)\n clist[xdex][ydex][0].create_line(0, 50, 50, 0)\n juego.poner_ficha(xdex, ydex, 1)\n\n else:\n clist[xdex][ydex][1] = 'O'\n create_circle(24, 24, 20, clist[xdex][ydex][0])\n juego.poner_ficha(xdex, ydex, 2)\n\n\nbox_frame = Frame(root)\nbox_frame.pack()\n\nfor x in range(np_tuple[0]):\n prep_list = []\n for y in range(np_tuple[1]):\n prep_list.append([Canvas(box_frame, width=50, height=50), ''])\n prep_list[y][0].create_line(50, 50, 0, 50)\n prep_list[y][0].create_line(50, 50, 50, 0)\n prep_list[y][0].bind(\"&lt;Button-1&gt;\", lambda e, xdex=x, ydex=y: click(e, xdex, ydex))\n prep_list[y][0].bind(\"&lt;Button-3&gt;\", lambda e, xdex=x, ydex=y: click(e, xdex, ydex))\n prep_list[y][0].grid(row=x, column=y)\n clist.append(prep_list)\n\nroot.mainloop()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T19:29:44.607", "Id": "436572", "Score": "0", "body": "@EvaMGG Sorry I had to make a quick update to the code. Please take a look now." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T19:20:17.800", "Id": "224983", "ParentId": "224972", "Score": "2" } } ]
{ "AcceptedAnswerId": "224983", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T11:41:38.573", "Id": "224972", "Score": "3", "Tags": [ "python", "beginner", "tic-tac-toe", "event-handling", "tkinter" ], "Title": "Simplified board for X's and O's using Tkinter" }
224972
<p>To teach myself Rust, I implemented a simple Quadtree over 2D points with <code>insert</code>, <code>delete</code>, <code>contain</code> function.</p> <p>My code does not seems "idiomatic rust code" to me. Also I think it's not so fast.</p> <p>I'm added 2 tests:</p> <ol> <li>simple test for check code work </li> <li>test to add 10_000 points to the quadtree</li> </ol> <p>Code:</p> <pre><code>use std::ops::DerefMut; #[derive(PartialEq, Copy, Clone)] pub struct Point { x: u32, y: u32, } impl Point { pub fn new(x: u32, y: u32) -&gt; Self { Point { x, y, } } } pub struct QuadNode { x: u32, y: u32, width: u32, height: u32, count: u8, capacity: u8, child: Vec&lt;Option&lt;Box&lt;QuadNode&gt;&gt;&gt;, elements: Vec&lt;Point&gt;, // Option? } impl QuadNode { fn new(x: u32, y: u32, width: u32, height: u32, capacity: u8) -&gt; Self { QuadNode { x, y, width, height, count: 0, capacity, child: Vec::with_capacity(capacity as usize), elements: Vec::with_capacity(capacity as usize), } } fn contain(&amp;mut self, p: &amp;Point) -&gt; bool { // bottom left let botlx = self.x - (self.width / 2); let botly = self.y - (self.height / 2); //top right let toprx = self.x + (self.width / 2); let topry = self.y + (self.height / 2); p.x &gt; botlx &amp;&amp; p.x &lt; toprx &amp;&amp; p.y &gt; botly &amp;&amp; p.y &lt; topry } fn split(&amp;mut self) { // center let x = self.x; let y = self.y; // child node width &amp;&amp; height let w = self.width / 2; let h = self.height / 2; println!("subdivade node"); self.child.push(Some(Box::new(QuadNode::new(x - w / 2, y + h / 2, w, h, self.capacity)))); self.child.push(Some(Box::new(QuadNode::new(x + w / 2, y + h / 2, w, h, self.capacity)))); self.child.push(Some(Box::new(QuadNode::new(x + w / 2, y - h / 2, w, h, self.capacity)))); self.child.push(Some(Box::new(QuadNode::new(x - w / 2, y - h / 2, w, h, self.capacity)))); } /* fn find(&amp;mut self, p: &amp;Point) -&gt; &amp;mut QuadNode { // -&gt; &amp;mut QuadNode? match self.child.len() { 0 =&gt; { // no child if self.contain(p) { return self; } else { return None; } }, _ =&gt; { // have child let mut flag: bool = false; for child in self.child.iter().filter_map(Option::as_ref) { } } } } */ fn insert(&amp;mut self, p: Point) { match self.child.len() { 0 =&gt; { if self.contain(&amp;p) { // no child if self.count &gt;= self.capacity { // need to split self.split(); self.insert(p); } else { // just push println!("insert new element"); self.count += 1; self.elements.push(p); } } } _ =&gt; { // have child for child in self.child.iter_mut().filter_map(Option::as_mut).map(Box::deref_mut) { child.insert(p); } } } } fn delete(&amp;mut self, p: Point) { match self.child.len() { 0 =&gt; { if self.contain(&amp;p) { self.remove(&amp;p); self.count -= 1; } } _ =&gt; { let mut flag: bool = false; for child in self.child.iter_mut().filter_map(Option::as_mut).map(Box::deref_mut) { flag = child.contain(&amp;p); } if flag { // parent node count -1 self.count -= 1; for child in self.child.iter_mut().filter_map(Option::as_mut).map(Box::deref_mut) { child.delete(p); } // need to un_split? if self.count &lt; self.capacity { self.clear(); } } } } } fn clear(&amp;mut self) { // add child's elements to parent node for child in self.child.iter_mut().filter_map(Option::as_mut).map(Box::deref_mut) { self.elements.extend(child.elements.iter().cloned()); // append? } // clear child node self.child.clear(); } fn remove(&amp;mut self, p: &amp;Point) { // magic remove let pos = self.elements.iter().position(|x| *x == *p).unwrap(); self.elements.remove(pos); } } fn main() {} pub struct QuadTree { root: Option&lt;Box&lt;QuadNode&gt;&gt;, } impl QuadTree { pub fn new() -&gt; Self { QuadTree { root: None, } } pub fn insert(&amp;mut self, p: Point) { match self.root { Some(ref mut root) =&gt; { root.insert(p); } None =&gt; { self.root = Some(Box::new(QuadNode::new(100_000 / 2, 100_000 / 2, 100_000, 100_000, 10))); } } } pub fn init(&amp;mut self) { match self.root { None =&gt; { self.root = Some(Box::new(QuadNode::new(100_000 / 2, 100_000 / 2, 100_000, 100_000, 10))); println!("create new node"); } _ =&gt; { return; } } } pub fn delete(&amp;mut self, p: Point) { match self.root { Some(ref mut root) =&gt; { root.delete(p); } _ =&gt; { return; } } } pub fn contain(&amp;mut self, p: &amp;Point) -&gt; bool { match self.root { Some(ref mut root) =&gt; { if root.contain(p) { return true; } else { return false; } }, _ =&gt; { return false; } } } } </code></pre> <p>Simple test:</p> <pre><code>#[cfg(test)] mod test { use super::*; #[test] fn simple_insert_five_points() { let mut qtree = QuadTree::new(); qtree.init(); let p1 = Point::new(10, 10); let p2 = Point::new(30, 30); let p3 = Point::new(40, 40); let p4 = Point::new(190, 190); let p5 = Point::new(170, 170); qtree.insert(p1); qtree.insert(p2); qtree.insert(p3); qtree.insert(p4); qtree.insert(p5); } // soo sloooow #[test] fn add_ten_thousend_point() { let mut qtree = QuadTree::new(); qtree.init(); for i in 1..10000 { qtree.insert(Point { x: i, y: i }); } } } </code></pre> <p><strong>Edit:</strong> I wrote it to use this in my game, so an example of use is something like this (in pseudocode):</p> <pre><code>fn game_loop () { input_player(); render(); for node.contain(player) { // no idea how to write this player.update(); //collision detected here } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T19:46:42.660", "Id": "436576", "Score": "0", "body": "It would be better to put a real example of calling the function into the question, pseudo code can get the question put on hold as hypothetical. Please see the code review guidelines at https://codereview.stackexchange.com/help/dont-ask and https://codereview.stackexchange.com/help/how-to-ask." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T17:38:05.400", "Id": "224978", "Score": "1", "Tags": [ "beginner", "tree", "rust" ], "Title": "Quadtree implementation in Rust" }
224978
<p>I am creating an iOS app and I want to implement Singleton Pattern. I have created "Singleton" LibraryAPI to act as an entry point UserManager object to get data from web API. after that I used a facade Pattern "method" to call UserManager implementation.</p> <pre><code>final class LibraryAPI { static let shared = LibraryAPI() private let userManager = UsersManager() private let isOnline = false private init(){ } func getUsers() -&gt; [User] { return userManager.getUsers() } } </code></pre> <p>my questions:</p> <ol> <li>if I have another Manager Class like "album" class should I use the same LibraryAPI and it will become a monolithic class and how to avoid that? </li> <li>should I create a "Singleton" LibraryAPI class for each manager object like UserLibraryAPI and albumLibraryAPI?</li> </ol> <p>Note: any references or articles are welcome :) </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-13T13:02:33.610", "Id": "439099", "Score": "0", "body": "I think this question falls out of scope for Code Review as it's about best practices, which falls into the [don't ask](https://codereview.stackexchange.com/help/dont-ask) section of the help center." } ]
[ { "body": "<p>Developing singletons isn't a good idea in most cases .Sure, you save some time taking this shortcut, but this code will bite you back later when the architecture of your app grows or when you add unit testing to your project. Here are a few reasons why you should <strong>NOT</strong> develop singletons:</p>\n\n<p><em>Note: These are excerpts from <a href=\"https://matteomanferdini.com/swift-singleton/\" rel=\"nofollow noreferrer\">this article</a> about swift singletons.</em></p>\n\n<ul>\n<li><strong>Singletons provide a globally mutable shared state.</strong> Ironically, the definition of singleton is one of the reasons why singletons are bad. The global accessibility of singletons makes shared resources accessible from anywhere, especially from code that should not have any access. Even value types like Swift structures and enumerations can access a singleton, which is a bad practice. When any part of an app can access or change the global state, you get weird and hard to fix bugs.</li>\n<li><strong>Singletons carry state around for the lifetime of the application.</strong> There are cases in which you need to reset the shared state. When you can have multiple instances, you can discard the old one and then create a new one. In a singleton, instead, resetting state might not be so natural and might require specific and complex code.</li>\n<li><strong>Singleton classes often become monoliths.</strong> This exactly correlates to your concern. Since it’s easy to access a singleton from anywhere, the chances are high that code that needs to be shared ends inside an existing singleton. Massive view controllers are not the only monolithic objects you should avoid in iOS. The same happens to singletons.</li>\n</ul>\n\n<p>If singletons are the wrong solution, what is then the correct one? The critical point here is the distinction between singletons and shared resources. In any real app, shared resources are necessary and unavoidable. There are always parts of an app’s architecture that need to be accessed from many places. Some examples are:</p>\n\n<ul>\n<li>The current global state of the app.</li>\n<li>The disk storage where data is saved, be it the file system, a database, the user defaults of the app, or a Core Data managed object context.</li>\n<li>A URL session that groups related network requests.</li>\n<li>A shared operation queue to prioritize, sequence, and schedule the asynchronous tasks of the app.</li>\n</ul>\n\n<p><strong>Conclusions</strong></p>\n\n<p>There are many articles online which try to answer the question: “when is it ok to use a singleton?”</p>\n\n<p>My answer is: <strong>never</strong>.</p>\n\n<p>That might sound a bit strict, but the drawbacks of singletons outweigh the little benefits of taking the shortcut. You can, and should, always solve the problem using dependency injection.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-08T22:00:09.673", "Id": "225798", "ParentId": "224979", "Score": "1" } }, { "body": "<p>This seems to be an extremely common way of handling networking in iOS and Swift probably because it is very simple to reason about a single global singleton object for services.</p>\n\n<p>I would recommend thinking carefully about using a singleton.</p>\n\n<p>Why not just have a NetworkManager object that you initialize?</p>\n\n<p>Even better why not separate out the services into a few logical classes? One service per class may get a bit arduous, but if you think critically you will likely be able to group services together appropriately. If you then find yourself with many Service objects, you can combine these objects with a facade pattern, that groups functionality when appropriate for a given View/ViewModel.</p>\n\n<p>You will want to use classes, or structs with non static functions because when something isn't a singleton you can use dependency injection. Instead of accessing the static methods of your singleton you can inject a NetworkProvider object into the class in the constructor that uses it. This will make your code far more robust and testable. The injected object, if you created an appropriate Protocol, can be mocked.</p>\n\n<p>Personally, I prefer something like Moya <a href=\"https://github.com/Moya/Moya/blob/master/docs/CommunityProjects.md\" rel=\"nofollow noreferrer\">https://github.com/Moya/Moya/blob/master/docs/CommunityProjects.md</a>. Its very swifty, logical, and well formatted. It also makes the relationships between services very clear. As your project gets larger, you will want to create multiple provider objects, but it provides a very concise way of writing your service layer. </p>\n\n<p>Summary - Use dependency injection and normal non static structs or classes. If you have multiple services, separate them out into a separate struct/class based on similarity or simply separate out one service into a single struct or class. A library like Moya can help to structure your code to make it more readable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-12T16:45:41.737", "Id": "225988", "ParentId": "224979", "Score": "2" } } ]
{ "AcceptedAnswerId": "225798", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T18:36:49.710", "Id": "224979", "Score": "3", "Tags": [ "object-oriented", "design-patterns", "swift" ], "Title": "Implement The Singleton Pattern for Persistency managers Swift" }
224979
<p><a href="https://codereview.stackexchange.com/q/225220/29371">Follow-Up question</a></p> <p>.Net provides <code>String.IndexOfAny(string, char[])</code> but not <code>String.IndexOfAny(string, string[])</code>.</p> <p>The existing built-in <code>String.IndexOfAny</code> takes an array of <code>char</code> and returns the lowest position of any one <code>char</code> from the array in a passed in <code>string</code> or <code>-1</code> if none are found. Essentially it is the <code>char</code> equivalent of my naive definition.</p> <p>My extension takes a <code>string</code> to search <code>s</code> and an array of <code>string</code>s to find <code>targets</code> and returns the lowest position found of any member of <code>targets</code> in <code>s</code> or <code>-1</code> if none are found.</p> <p>A naive implementation (using LINQ) isn't particularly efficient:</p> <pre><code>public static int IndexOfAny1(this string s, params string[] targets) =&gt; targets.Select(t =&gt; s.IndexOf(t)).Where(p =&gt; p &gt;= 0).DefaultIfEmpty(-1).Min(); </code></pre> <p>My improved implementation tracks the current candidate position and restricts future searches to be before that candidate position:</p> <pre><code>public static int IndexOfAny2(this string s, params string[] targets) { int? curAns = null; foreach (var target in targets) { var posAns = s.IndexOf(target, 0, curAns.HasValue ? curAns.Value + target.Length : s.Length); if (posAns &gt;= 0 &amp;&amp; (!curAns.HasValue || posAns &lt; curAns)) { curAns = posAns; if (curAns == 0) // once you're at the beginning, can't be any less break; } } return curAns ?? -1; } </code></pre> <p>This runs up to two times faster.</p> <p>Sample code to test the two methods:</p> <pre><code>Console.WriteLine($"IndexOfAny1 should be 8: {"foo bar baz".IndexOfAny1("barz", "baz")}"); Console.WriteLine($"IndexOfAny1 should be 0: {"aabbccddeeffgghh".IndexOfAny1("bbb", "hh", "aa")}"); Console.WriteLine($"IndexOfAny2 should be 8: {"foo bar baz".IndexOfAny2("barz", "baz")}"); Console.WriteLine($"IndexOfAny2 should be 0: {"aabbccddeeffgghh".IndexOfAny2("bbb", "hh", "aa")}"); </code></pre> <p>Is there a better algorithm or another way to make this faster?</p> <p>PS Test harness for testing random possibilities:</p> <pre><code>var r = new Random(); var sb = new StringBuilder(); for (int j1 = 0; j1 &lt; r.Next(80,160); ++j1) sb.Append((char)('0'+r.Next(0, 26+52))); var s = sb.ToString(); var listTargets = new List&lt;string&gt;(); for (int j1 = 0; j1 &lt; r.Next(5, 10); ++j1) if (r.NextDouble() &lt; 0.8) { var tLen = r.Next(4, Math.Min(s.Length - 4, 10)); var beginPos = r.Next(0, s.Length - tLen); listTargets.Add(s.Substring(beginPos, tLen)); } else { sb.Clear(); for (int j2 = 0; j2 &lt; r.Next(5, 10); ++j2) sb.Append((char)('0'+r.Next(0, 26+52))); listTargets.Add(sb.ToString()); } var targets = listTargets.ToArray(); if (s.IndexOfAny1(targets) != s.IndexOfAny2(targets)) Console.WriteLine($"Fail on {s} containing {String.Join(",", targets)}"); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T19:17:06.887", "Id": "437197", "Score": "3", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<h3>Review</h3>\n\n<ul>\n<li>Don't use abbreviated variable names <code>s</code>, <code>curAns</code> and <code>posAns</code>; use self describing names: <code>value</code>, <code>index</code> and <code>targetIndex</code> instead. </li>\n<li>The nullable int could be replaced with <code>-1</code>. This reads cleaner and allows you to bypass the final <code>??</code> operator in <code>curAns ?? -1</code>.</li>\n<li>You can optimize the count <code>curAns.Value + target.Length</code> with adding <code>-1</code> because we don't care about finding another match on the currently best found index.</li>\n<li>You should exit early if no targets are specified</li>\n</ul>\n\n<h3>Refactored</h3>\n\n<pre><code>public static int IndexOfAny2(this string value, params string[] targets)\n{\n var index = -1;\n if (targets == null || targets.Length == 0) return index;\n\n foreach (var target in targets)\n {\n var targetIndex = value.IndexOf(target, 0, \n index &gt; -1 ? index + target.Length - 1 : value.Length);\n\n if (targetIndex &gt;= 0 &amp;&amp; (index == -1 || targetIndex &lt; index))\n {\n index = targetIndex;\n if (index == 0)\n {\n break;\n }\n }\n }\n\n return index;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T21:24:15.560", "Id": "437059", "Score": "0", "body": "Nice, but not really helpful to my question. BTW, I don't find `value` any more compelling than `s`. Perhaps its leaks from my database knowledge, but I think using `-1` to mean `index` has no value yet is bad practice - don't use magic values when coding. If I were designing it today, `IndexOf` would return an `int?` instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T16:00:31.933", "Id": "437177", "Score": "0", "body": "Why avoid the most well known magic number (index = -1) to use it anyway at return time?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T16:11:21.437", "Id": "437183", "Score": "0", "body": "Just a matter of style or preference I guess." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T18:53:13.087", "Id": "437195", "Score": "0", "body": "I improved my `IndexOfAny2` based on your comments and added at bottom of question. Thanks for the improvements, though still not getting at the root of my question." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T20:11:07.660", "Id": "225159", "ParentId": "224980", "Score": "6" } }, { "body": "<ul>\n<li><code>\"abc\".IndexOfAny2(\"c\", \"abc\")</code> fails with an <code>ArgumentOutOfRangeException</code>, because <code>IndexOf</code> requires <code>startIndex + count</code> to not exceed the length of the string.</li>\n<li>For a tiny improvement, make <code>curAns</code> a normal integer and initialize it with <code>s.Length</code>. After the necessary changes, you'll end up with fewer checks inside the <code>foreach</code> loop.</li>\n</ul>\n\n<p>Most time is spent in <code>string.IndexOf</code> however, so for more substantial improvements you'll want to investigate more optimized (and more complex) algorithms such as Rabin-Karp, Knuth-Morris-Pratt, Boyer-Moore, Aho-Corasick, etc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T15:57:34.453", "Id": "437174", "Score": "0", "body": "I would assume based on the reference source that `String.IndexOf` being a C intrinsic is either using a direct x64 instruction or is implementing a high speed optimized algorithm already (it calls the kernel32 `FindNLSString` function). However, this did lead me to add `StringComparison.Ordinal` to my `IndexOf` call, which added some speed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T19:01:51.013", "Id": "437196", "Score": "0", "body": "Added a bug fix version of the bottom of my question, thanks for the bug report. I like your `s.Length` suggestion as the code looks nice but in practice it runs fractionally slower even with fewer tests." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T19:37:10.723", "Id": "437199", "Score": "0", "body": "@NetMage: As far as I could [find](https://stackoverflow.com/a/2584204/263535), `IndexOf` is doing a 'naive' search. Good point about `StringComparison.Ordinal`, but it depends on what behavior you need. For example, a culture-specific comparison can match `\"é\"` against `\"é\"` (which is `\"e\\u0301\"` - an 'e' followed by a combining accent), an ordinal comparison won't. I'd make it a parameter instead of hard-coding it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T19:46:51.047", "Id": "437201", "Score": "0", "body": "I did so, but of course, I can't put the improved code anywhere in a way I would like. I may ask another question with working code... BTW, I am not sure that the .Net Core usage matches the .Net Framework call to the kernel function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T19:58:55.503", "Id": "437202", "Score": "0", "body": "I'd assume that if `FindNLSString` was using a better algorithm, they would've ported it to .Net Core, given how much they're focusing on performance, but without access to the actual source there's no way to be sure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T20:03:03.580", "Id": "437203", "Score": "0", "body": "Well, the problem is .Net Core must work on MacOS/Linux, so it can't call the Windows Kernel..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T20:23:50.057", "Id": "437206", "Score": "0", "body": "They could still have ported the algorithm. Anyway, regarding `s.Length`, I did some more testing, and the results are very hit-and-miss. After comparing the fastest runs I think there's no significant difference (on my system anyway). That's interesting, because the IL is twice as short. I suppose the JITter is doing a good job with nullables." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T20:29:43.687", "Id": "437208", "Score": "0", "body": "I wouldn't be surprised if .Net developers don't have access to Windows source code." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T15:08:03.610", "Id": "225201", "ParentId": "224980", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T19:05:31.307", "Id": "224980", "Score": "2", "Tags": [ "c#", "performance", "strings", "search" ], "Title": "Best C# implementation of IndexOfAny(string, params string[])" }
224980
<p>As as final project for a MOOC I wanted to write a program that finds the exact cover set/minimum dominating set from the given social network data. So I did end up with writing this. I kinda followed this algorithm.(<a href="https://www.geeksforgeeks.org/exact-cover-problem-algorithm-x-set-1/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/exact-cover-problem-algorithm-x-set-1/</a>)</p> <p>I did test with the picture below it worked fine <a href="https://i.stack.imgur.com/wgHxu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wgHxu.png" alt="enter image description here"></a> </p> <pre><code>"keys is a sorted list by their number of 'followers'" HashSet &lt;Integer&gt; exactCoverSet = new HashSet &lt;&gt;(); HashSet &lt;Integer&gt; dominatingSet = new HashSet &lt;&gt;(); while (keysCopy.size() &gt; 0) { int col = keysCopy.removeLast(); LinkedList &lt;Integer&gt; selectedRows = new LinkedList &lt;&gt;(); selectedRows.addAll(G.exportGraph().get(col)); exactCoverSet = findCoverSet(G, nv, selectedRows, keysCopy, dominatingSet); if (exactCoverSet != null) { // if all columns are removed from the matrix then found break; } } return exactCoverSet; </code></pre> <p>above is loop to find the MDS, there are a few more classes these are the cores</p> <pre><code>public static HashSet &lt;Integer&gt; findCoverSet(Graph G, int[][] matrix, LinkedList &lt;Integer&gt; selectedRows, LinkedList &lt;Integer&gt; keys, HashSet &lt;Integer&gt; dominatingSet) { if (selectedRows.size() == 0) { return null; } LinkedList &lt;Integer&gt; keysCopy = new LinkedList &lt;&gt;(); keysCopy.addAll(keys); LinkedList &lt;Integer&gt; rowValues = new LinkedList &lt;&gt;(); rowValues.addAll(G.exportGraph().get(selectedRows.getFirst())); //add all values of the chosen row dominatingSet.add(selectedRows.removeFirst()); //remove the chosen row from loop ArrayList &lt;Integer&gt; removeRows = new ArrayList &lt;&gt;(); //remove the rows from matrix for (int num : keys) { //that are sharing the same columns with chosen row for (int val : rowValues) { if (G.exportGraph().get(num).contains(val)) { removeRows.add(num); keysCopy.removeFirstOccurrence(num); break; } } } for (int col : rowValues) { //remove the columns from matrix matrix = removeCol(matrix, col - 1); } if (keysCopy.size() == 1) { //if there is 1 left row check if its all elements are 1s int key = keysCopy.getFirst(); //if so MDS found, otherwise return null for (int j = 0; j &lt; matrix[key - 1].length; j++) { if (matrix[key - 1][j] == 0) { return null; } } } if (keysCopy.size() &gt; 0) { //if remaining columns are more than 0 then select/remove int tempKey = keysCopy.removeFirst(); //the column with the least 1s selectedRows.add(tempKey); return findCoverSet(G, matrix, selectedRows, keysCopy, dominatingSet); } return dominatingSet; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T19:39:50.947", "Id": "436574", "Score": "0", "body": "It might be better if the entire class or set of classes was included, right now there is one function and one partial function, which is concrete enough for a review. Please see the code review guidelines at https://codereview.stackexchange.com/help/dont-ask and https://codereview.stackexchange.com/help/how-to-ask." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T19:25:15.767", "Id": "224984", "Score": "1", "Tags": [ "java", "performance", "beginner", "algorithm", "programming-challenge" ], "Title": "Algorithm X implementation for Minimum Dominating Set" }
224984
<p>I have a semi-working project currently and am wondering if I am doing this the wrong way or if there is a more efficient way. I will try to be as general as possible as to keep the point concise.</p> <p>Any tips, suggestions, articles, ideas, etc. that you have, will help me greatly. I am a one man show essentially when it comes to projects like this and anything to make it more efficient would be great. Background info: So basically to summarize the project and what it accomplishes, I'll do a list:</p> <ol> <li>Log new orders that need to be sent.</li> <li>Check 3 data sources for any of the items on that order to see if they shipped or cancelled (order items can be shipped from any or all distribution centers)</li> <li>Update the count of items shipped (a field in log table) and the count of cancelled items (another field)</li> <li>If the count of items shipped (in log table) is at least one build data object with necessary data, and send to 3rd party API.</li> <li>If all items are shipped(or cancelled), update record in log table with completed flag</li> </ol> <p>I am sending nearly 100k+ orders a day. Steps 1, 2 and 3 are in a console app called the "Updater" and the rest of the steps are in a console app called the "Sender" both run on their own separate scheduled task.</p> <p>My concern here is the "Sender" portion. The thing is we have many different "companies" OR "brands". To ease the load on the data base, I queue each company separately.</p> <p>Here is my entry point</p> <pre><code> var x = Stopwatch.StartNew(); string[] companies = new string[] { "21", "1", "20", "22" }; string[] sizesWithDashes = GeneralFunctions.GetSizesWithDashesArray(); List&lt;Task&gt; taskList = new List&lt;Task&gt;(); var throttler = new SemaphoreSlim(initialCount: 2); foreach (string comp in companies) { string company = comp; DataTable data = UtilitySqlAgent.GetIntialNarvarData(comp); await throttler.WaitAsync(); try { // *This is where we begin our work* \\ await FactoryEntrance.InitalizeSenderAsync(comp, data, sizesWithDashes); } finally { Console.WriteLine($"Company {company} FINISHED"); throttler.Release(); } } await Task.WhenAll(taskList); x.Stop(); Console.WriteLine(x.Elapsed); Console.ReadLine(); </code></pre> <p>Now in this next method, there are a couple key things to keep in mind. </p> <ul> <li>Im looping through a set of unique records - all of these records will share an "Initalization Model" object which contains all the data I will need This prevents me from making unecessary queries to the </li> <li>I am attempting to process many records at once, due to the sheer amount of data that I need to get through daily.</li> <li>I am building a string filled with any completed records that need to be updated in the database to execute at the end of the process again to avoid database usage</li> </ul> <pre><code>public static async Task InitalizeSenderAsync(string comp, DataTable data, string[] allSizesWithDashes) { int i = data.Rows.Count; var throttler = new SemaphoreSlim(initialCount: 100); Console.WriteLine($"There are {data.Rows.Count} orders to send narvar"); InitalizationModel IM = await BuildInitalizationModelAsync(comp, data, allSizesWithDashes); List&lt;Task&gt; taskList = new List&lt;Task&gt;(); string updatequery = ""; List&lt;string&gt; updateList = new List&lt;string&gt;(); foreach (DataRow row in data.Rows) { await throttler.WaitAsync(); DataRow rowToProcess = row; taskList.Add(Task.Run(async () =&gt; { try { Console.WriteLine($"STARTING Company {comp}-{rowToProcess["OrderNumber"].ToString()} "); string result = await BeginProcessAsync(IM, rowToProcess); if (result != "") updateList.Add(result); } finally { i = i - 1; Console.WriteLine($"RELEASING Company {comp}-{rowToProcess["OrderNumber"].ToString()} - Remaining: {i}"); throttler.Release(); } })); } await Task.WhenAll(taskList); foreach (string q in updateList) updatequery += $"{q};\n"; UtilitySqlAgent.UpdateCompletedOrder(updatequery); } </code></pre> <p>So I'll only show two more of the methods, because they will give you an idea basically of what im doing in all of the other methods.. Essentially at this point, I passed a row from the unique records to a method that will take the row and build the objects I need, it will convert the root object into an XML object, and that will get POSTed to the 3rd party API.. If it meets the criteria, it will get updated in the log table as complete</p> <pre><code>private static MasterOrderModel BuildMasterOrderModel(DataRow row, InitalizationModel IM) { MasterOrderModel result = new MasterOrderModel(); result.NarvarID = int.Parse(row["NarvarID"].ToString()); string CurrentOrderLocateConstraint = LocateFactory.GetCurrentOrderLocateConstraint(IM.LocateIdData.Select(string.Format("NarvarID ='{0}' ", result.NarvarID))); result.CompanyNumber = row["CompanyNumber"].ToString(); result.OrderNumber = row["OrderNumber"].ToString(); result.ItemsOrdered = int.Parse(row["ItemsOrdered"].ToString()); result.ItemsShipped = int.Parse(row["ItemsShipped"].ToString()); result.ItemsCancelled = int.Parse(row["ItemsCancelled"].ToString()); result.OrderDate = DateTime.Parse(row["OrderDate"].ToString()); result.CustomerName = row["CustomerName"].ToString(); result.CustomerNumber = row["CustomerNumber"].ToString(); result.ImportDate = DateTime.Parse(row["ImportDate"].ToString()); try { result.LocateShipmentData = LocateFactory.GetLocateShipmentData(IM.LocateShipmentData, IM.LocateIdData.Select(string.Format("NarvarID ='{0}' ", result.NarvarID))); } catch (InvalidOperationException IOE) { result.LocateShipmentData = null; Console.WriteLine($"No Locate Shipment Data for order {result.CompanyNumber}-{result.OrderNumber} "); if (IOE.Message != "The source contains no DataRows.") throw; } try { result.LocateOrderedItemsData = IM.LocateOrderedItemsData.Select(string.Format($"ORDER_NUMBER in {CurrentOrderLocateConstraint}")); } catch (InvalidOperationException IOE) { result.LocateOrderedItemsData = null; Console.WriteLine($"No Locate Ordered Items for order {result.CompanyNumber}-{result.OrderNumber} "); if (IOE.Message != "The source contains no DataRows.") throw; } try { result.WmsShipmentData = IM.WmsShipmentData.Select(string.Format("NarvarID ='{0}' ", result.NarvarID)).CopyToDataTable(); } catch (InvalidOperationException IOE) { result.WmsShipmentData = null; Console.WriteLine($"No Wms Shipment Data for order {result.CompanyNumber}-{result.OrderNumber} "); if (IOE.Message != "The source contains no DataRows.") throw; } try { result.WmsOrderedItemsData = IM.WmsOrderedItemsData.Select(string.Format("Order_Number ='{0}' ", result.OrderNumber)); } catch (InvalidOperationException IOE) { result.WmsOrderedItemsData = null; Console.WriteLine($"No Wms Ordered Items for order {result.CompanyNumber}-{result.OrderNumber} "); if (IOE.Message != "The source contains no DataRows.") throw; } result.CancelledItemsData = IM.CancellationData.Select($"IHH_ORDER_NUMBER = '{result.OrderNumber}'"); result.BackorderedItemsData = IM.BackorderData.Select($"IHH_ORDER_NUMBER = '{result.OrderNumber}'"); result.allSizesWithDashes = IM.AllSizesWithDashes; result.ItemShipMethods = IM.ShipMethodData.Select($"OrderNumber = '{result.OrderNumber}'"); result.NarvarRequestModel = BuildNarvarModel(result, row); return result; } private static NarvarOrderModel BuildNarvarModel(MasterOrderModel MOM, DataRow initialDataRow) { NarvarOrderModel result = new NarvarOrderModel(); result.Order_Info = new OrderInfoModel(); result.Order_Info.Order_Number = MOM.OrderNumber; result.Order_Info.Order_Date = MOM.OrderDate; result.Order_Info.Status = "PROCESSING"; result.Order_Info.Currency_Code = null; result.Order_Info.Attributes = BuildAttributes(MOM.CompanyNumber); result.Order_Info.Billing = BuildOrderBillingModel(initialDataRow); result.Order_Info.Customer = BuildCustomerInfoModel(initialDataRow); result.Order_Info.Shipments = BuildOrderShipmentsModelList(MOM); result.Order_Info.Order_Items = BuildOrderItemsModelList(MOM, result.Order_Info.Shipments); for (int i = 0; i &lt;= result.Order_Info.Shipments.Count - 1; i++) { if (result.Order_Info.Shipments[i].Carrier == "LTL") result.Order_Info.Shipments.RemoveAt(i); } return result; } </code></pre> <p>As a benchmark, it's taking me about an hour to send more than 2k orders to the API...</p>
[]
[ { "body": "<p>You mentioned you're hitting the narvar API?</p>\n\n<p>Without having looked to deeply at your code, try to identify if it's a 'bulk' issue, you mentioned the number 200k (does this mean you hit the API 200k times a day?, see if it's rate limited by the narvar API). If this is the case, look for 'bulk import' / 'bulk actions' in the API, maybe it's throttled for your payment plan, etc... </p>\n\n<p>Whenever I hear 'smallish' numbers (like 200k per day), I think network problems. I wouldn't suspect it's due to the performance of your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T20:10:12.320", "Id": "436580", "Score": "1", "body": "According to the Narvar team we work with, they said they can handle any load we throw at them. IIRC there is no rate limit but then again I could be wrong. I will shoot an email and ask.. It's likely youre right about the network issue. I didn't really think about that. Do you think it would benefit me to build all the API request objects into a list and then hit the api afterwards? This may not help performance but possibly identify if the network is the issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T21:05:08.187", "Id": "436586", "Score": "0", "body": "Yeah, I would try that (if it's not too hard/too much work to modify your code to bundle API requests). Alternatively, you can try to comment out the network request calls (or mock them with a temporary hard-coded response if your code depends on the response), and see if that speeds up the entire application. (If you have a test environment with dummy data)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T20:05:45.733", "Id": "224988", "ParentId": "224986", "Score": "0" } }, { "body": "<h3>Use Dataflow</h3>\n\n<p>You could use the <code>ActionBlock</code> from the <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/dataflow-task-parallel-library\" rel=\"nofollow noreferrer\"><code>System.Threading.Tasks.Dataflow</code></a> package to let it handle the throttling of <code>InitalizeSenderAsync</code> method that you currently handle yourself:</p>\n\n<pre><code>var workerBlock = new ActionBlock&lt;DataRow&gt;\n(\n async row =&gt;\n {\n // body...\n },\n new ExecutionDataflowBlockOptions\n {\n MaxDegreeOfParallelism = 100 // &lt;-- throttle\n }\n);\n\nforeach (DataRow row in data.Rows)\n{\n workerBlock.Post(row); // &lt;-- feed the ActionBlock\n}\nworkerBlock.Complete();\nworkerBlock.Completion.Wait(); // &lt;-- wait for all row to be processed\n</code></pre>\n\n<h3>Use <code>StringBuilder</code> or <code>Join</code></h3>\n\n<blockquote>\n<pre><code>foreach (string q in updateList)\n updatequery += $\"{q};\\n\";\n</code></pre>\n</blockquote>\n\n<p>Building large strings in this way might harm the performance. If you care for efficiency then <code>StringBuilder.AppendLine</code> or <code>string.Join($\"{Environment.NewLine};\", updateList\")</code> are your best friends.</p>\n\n<h3>Questionable data acquisition</h3>\n\n<blockquote>\n<pre><code>catch (InvalidOperationException IOE)\n</code></pre>\n</blockquote>\n\n<p>You should try to avoid this kind of <em>no data</em> handling (<em>No Locate Ordered Items for order</em>). I think you have made this to a <em>reusable</em> pattern because you do this for every single use-case. The methods returning data should return either <code>null</code> or empty collections (like <code>IList&lt;T&gt;</code> (this is the preferred convention). Throwing exceptions is always costly and so many of these <code>try/catch</code> blocks make your ode very difficult to read. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T13:45:42.283", "Id": "436937", "Score": "0", "body": "Thank you! Very insightful! Will definitely be refactoring with these ideas in mind" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T17:53:11.907", "Id": "225050", "ParentId": "224986", "Score": "1" } }, { "body": "<h3>EntryPoint</h3>\n\n<p>Your entry point code does not make sense to me. You have prepared for asynchronously launching tasks, throtling maximum 2 tasks concurrently. However, you forgot to add tasks to <code>taskList</code> and use an <code>await</code> rather than <code>Task.Run</code>. You did implement this pattern correctly at <code>InitalizeSenderAsync</code>.</p>\n\n<blockquote>\n<pre><code>var throttler = new SemaphoreSlim(initialCount: 2);\nList&lt;Task&gt; taskList = new List&lt;Task&gt;();\n// .. code\nawait Task.WhenAll(taskList);\n</code></pre>\n</blockquote>\n\n<hr>\n\n<h3>Threading</h3>\n\n<ul>\n<li>API operations that chain async code calls, should use <code>ConfigureAwait(false);</code> in order not to postback to the initially captured synchronization context.</li>\n<li><code>InitalizeSenderAsync</code> updates a local variable <code>i = i - 1;</code> from multiple threads; use <code>Interlocked.Decrement(ref i);</code> instead for decrementing an int atomically.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T13:46:48.197", "Id": "436938", "Score": "0", "body": "Its possible i may have gotten confused amidst trying to figure out the right way to configure it.. Any who thanks for the insight! this is exactly the kind of things im trying to figure out." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T20:22:14.017", "Id": "225059", "ParentId": "224986", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T19:31:41.770", "Id": "224986", "Score": "1", "Tags": [ "c#", "object-oriented" ], "Title": "Collecting data into objects and POSTing to 3rd Party API" }
224986
<p>A function that funnels all filenames into a file and opens that file in vim. The user then changes the names, saves, and quits. Finally the function renames the files in the folder with the new names provided in the file. </p> <pre><code>bulkrename() { mkdir -p ~/.temp ls &gt; ~/.temp/newfilenames &amp;&amp; nvim ~/.temp/newfilenames local files=(*) for filenum in $(seq 1 $(ls | wc -l)); do mv ${files[${filenum}]} $(sed "${filenum}q;d" ~/.temp/newfilenames) done rm ~/.temp/newfilenames } </code></pre>
[]
[ { "body": "<h3>Always double-quote variables used in command arguments</h3>\n\n<p>The arguments of <code>mv</code> should have been double-quoted, like this:</p>\n\n<pre><code>mv \"${files[${filenum}]}\" \"$(sed \"${filenum}q;d\" ~/.temp/newfilenames)\"\n</code></pre>\n\n<h3>The script is fragile</h3>\n\n<p>As it is, the script looks very fragile:</p>\n\n<ul>\n<li><p>The list of files for editing is generated by <code>ls</code>, and then the edited list items are paired up with the <code>files</code> array generated with <code>*</code>. I'm not sure the ordering is guaranteed to be consistent, and I think it would be painful to track down in the documentation if this is indeed the case. It would be easier to generate both lists in a way to ensure consistent ordering.</p></li>\n<li><p>Using <code>ls</code> to generate the list is problematic. The output of <code>ls &gt; ...</code> will depend on active aliases. <code>command ls &gt; ...</code> would be safer.</p></li>\n<li><p>Files whose names don't change will raise errors when executing <code>mv same same</code></p></li>\n<li><p>If there are duplicate lines after editing, one of the original files may silently disappear.</p></li>\n<li><p>The script may behave unexpectedly in certain corner cases:</p>\n\n<ul>\n<li>the user deleted a line from the file</li>\n<li>the user inserted a line in the file</li>\n<li>the list of files in the directory changed while editing the file</li>\n</ul></li>\n<li><p>The user may not have a way to abort the operation. With default shell settings, even if <code>nvim</code> exits with failure, the script goes ahead with the renames, which is probably not what a user would want.</p></li>\n<li><p>Even with the double-quoting fixed, the script will not work for files whose names contain newlines. I think that's acceptable and not worth the pain to make it work, but it would be good to document (in a comment).</p></li>\n</ul>\n\n<p>To mitigate these issues, I suggest:</p>\n\n<ul>\n<li>Create an array from <code>*</code>, let's call it <code>oldnames</code></li>\n<li>Save <code>oldnames</code> to the work file: <code>printf '%s\\n' \"${oldnames[@]}\" &gt; \"$work\"\n</code></li>\n<li>Let the user edit the work file</li>\n<li>Check the exit code, and abort on failure (user can cause failure by exiting <code>nvim</code> with <code>:cq</code>)</li>\n<li>Load the content of the work file into another array: <code>mapfile -t newnames &lt; \"$work\"</code></li>\n<li>Add a sanity check to verify that the number of files match before and after.</li>\n<li>Run <code>mv</code> only for the files whose names changed, and use <code>-i</code> to avoid overwriting existing files, and <code>-v</code> to show what was actually renamed.</li>\n</ul>\n\n<h3>Use <code>mktemp</code> to create temporary files</h3>\n\n<p>The script is not safe to use concurrently.\nIt's easy enough to create a unique temporary file using <code>mktemp</code>.</p>\n\n<h3>Use <code>trap</code> to clean up temporary files</h3>\n\n<p>To make sure that temporary files get cleaned up when the script exits, use <code>trap</code>, for example:</p>\n\n<pre><code>trap 'rm -f \"$tmpfile\"' EXIT\n</code></pre>\n\n<p>Declare this trap right before creating <code>tmpfile</code>.</p>\n\n<h3>Declare all local variables as <code>local</code></h3>\n\n<p>It's good you declared <code>local files</code>. There is <code>filenum</code> too.</p>\n\n<h3>Don't use <code>seq</code></h3>\n\n<p>The <code>seq</code> utility is not installed by default in all systems,\nand Bash has a native way to use counting loops:</p>\n\n<pre><code>for ((i = 0; i &lt; size; i++)); do ...; done\n</code></pre>\n\n<h3>If you use Bash arrays, reap all the benefits</h3>\n\n<p>Instead of <code>$(ls | wc -l)</code> to find the count of files,\nyou already have that in the <code>files</code> array: <code>${#files[@]}</code>.</p>\n\n<h3>Improve performance</h3>\n\n<p>Calling <code>sed</code> in a loop to get the n-th line of a file is inefficient.\nIt would be better to read the lines into an array,\nand then use a counting loop to with the two arrays, for example:</p>\n\n<pre><code>for ((i = 0; i &lt; ${#oldnames[@]}; i++)); do\n old=${oldnames[i]}\n new=${newnames[i]}\n if [[ \"$old\" != \"$new\" ]]; then\n mv -vi \"$old\" \"$new\"\n fi\ndone\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T19:42:27.253", "Id": "436734", "Score": "0", "body": "I implemented all of your suggestions. Learned a lot from them. Thank you. [New question](https://codereview.stackexchange.com/questions/225058/bulk-file-rename-improved-safety-and-performance)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T09:55:40.417", "Id": "225022", "ParentId": "224989", "Score": "2" } } ]
{ "AcceptedAnswerId": "225022", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T20:07:36.503", "Id": "224989", "Score": "3", "Tags": [ "bash", "shell", "sh", "sed", "zsh" ], "Title": "Bulk File Rename" }
224989
<p>I am working on an iban api which is about saving the iban of some members after (iban validation) in a database. The code is split between Domain (entities, behaviour for iban validation), Database and its access (new member, retrieval, etc.).</p> <p>I am looking for feedbacks about the <code>async</code> code and the general coding style.</p> <p>The Domain entities:</p> <pre><code>module Rm.Iban.Domain type IbanState = | Unknown = 0 | Ok = 1 | Requested = 2 [&lt;CLIMutable&gt;] type Iban = { Id: Guid MemberId: int Iban: string option State: IbanState CreatedOn: DateTimeOffset UpdatedOn: DateTimeOffset option } </code></pre> <p>Domain behaviour:</p> <pre><code>module Rm.Iban.Domain.IbanValidation open System open System.Text.RegularExpressions open FSharpPlus type ValidationError = | IllegalCharacters | IncorrectLength | UnknownCountry | TypingError [&lt;AutoOpen&gt;] module private Impl = let illegalCharacters = Regex(@"[^0-9A-Za-z ]", RegexOptions.Compiled) let checkCharacters iban = if illegalCharacters.IsMatch(iban) then Error IllegalCharacters else Ok iban let cleanup = String.toUpper &gt;&gt; String.replace " " "" &gt;&gt; Ok let lengthPerCountry = dict [ ("AL", 28); ("AD", 24); ("AT", 20); ("AZ", 28); ("BE", 16); ("BH", 22); ("BA", 20); ("BR", 29); ("BG", 22); ("CR", 21); ("HR", 21); ("CY", 28); ("CZ", 24); ("DK", 18); ("DO", 28); ("EE", 20); ("FO", 18); ("FI", 18); ("FR", 27); ("GE", 22); ("DE", 22); ("GI", 23); ("GR", 27); ("GL", 18); ("GT", 28); ("HU", 28); ("IS", 26); ("IE", 22); ("IL", 23); ("IT", 27); ("KZ", 20); ("KW", 30); ("LV", 21); ("LB", 28); ("LI", 21); ("LT", 20); ("LU", 20); ("MK", 19); ("MT", 31); ("MR", 27); ("MU", 30); ("MC", 27); ("MD", 24); ("ME", 22); ("NL", 18); ("NO", 15); ("PK", 24); ("PS", 29); ("PL", 28); ("PT", 25); ("RO", 24); ("SM", 27); ("SA", 24); ("RS", 22); ("SK", 24); ("SI", 19); ("ES", 24); ("SE", 24); ("CH", 21); ("TN", 24); ("TR", 26); ("AE", 23); ("GB", 22); ("VG", 24); ] let checkLength (iban: string) = let country = iban.Substring(0, Math.Min(2, iban.Length)) match lengthPerCountry.TryGetValue(country) with | true, length -&gt; if length = iban.Length then Ok iban else Error IncorrectLength | _ -&gt; Error UnknownCountry let checkRemainder (iban: string) = let digitalIban = let rearrangedIban = iban.Substring(4) + iban.Substring(0,4) let replaceBase36LetterWithBase10String (s: string) (c: char) = s.Replace(c.ToString(), ((int)c - (int)'A' + 10).ToString()) List.fold replaceBase36LetterWithBase10String rearrangedIban [ 'A' .. 'Z' ] let remainder = let reduceOnce r n = Int32.Parse(r.ToString() + n) % 97 Regex.Matches(digitalIban.Substring(2), @"\d{1,7}") |&gt; Seq.cast |&gt; Seq.map (fun x -&gt; x.ToString()) |&gt; Seq.fold reduceOnce (reduceOnce 0 (digitalIban.Substring(0, 2))) if remainder = 1 then Ok iban else Error TypingError let format iban = Regex.Replace(iban, ".{4}", "$0 ") |&gt; Ok let validate (iban: string) = iban |&gt; checkCharacters &gt;&gt;= cleanup &gt;&gt;= checkLength &gt;&gt;= checkRemainder &gt;&gt;= format </code></pre> <p>The Entity Framework Core <code>DbContext</code>:</p> <pre><code>module Rm.Iban.Data.DbContext type IbanDbContext (options: DbContextOptions&lt;IbanDbContext&gt;) = inherit DbContext(options) [&lt;DefaultValue&gt;] val mutable private ibans: DbSet&lt;Iban&gt; member x.Ibans with get() = x.ibans and set v = x.ibans &lt;- v </code></pre> <p>The code that create</p> <pre><code>module Rm.Iban.App.IbanRetrieval open System open System.Linq open Rm.Iban.Data open Rm.Iban.Domain open Microsoft.EntityFrameworkCore type RequestError = | AlreadyRequested type MeetRequestError = | RequestNotFound | IbanInvalid of IbanValidation.ValidationError [&lt;AutoOpen&gt;] module private Impl = let memberIbansWith (context: DbContext.IbanDbContext) memberId ibanState = query { for iban in context.Ibans do where ( iban.MemberId = memberId &amp;&amp; iban.State = ibanState) } let requested (context: DbContext.IbanDbContext) memberId = async { let requested = memberIbansWith context memberId IbanState.Requested return! requested.Select(fun iban -&gt; Some iban) .SingleOrDefaultAsync() |&gt; Async.AwaitTask } let avoidDuplicateRequest (context: DbContext.IbanDbContext) memberId = async { let! exists = context.Ibans.AnyAsync(fun iban -&gt; iban.MemberId = memberId &amp;&amp; iban.State = IbanState.Requested) |&gt; Async.AwaitTask if exists then return Error AlreadyRequested else return Ok (context, memberId) } let newRequest ((context: DbContext.IbanDbContext), memberId) = async { let iban: Iban = { Id = Guid.Empty MemberId = memberId Iban = None State = IbanState.Requested CreatedOn = DateTimeOffset.UtcNow UpdatedOn = None } let iban = context.Ibans.Add iban do! context.SaveChangesAsync true |&gt; Async.AwaitTask |&gt; Async.Ignore return Ok iban.Entity } let updateRequestWith (context: DbContext.IbanDbContext) memberId ibanValue = async { match! requested context memberId with | Some iban -&gt; context.UpdateWith iban { iban with Iban = Some ibanValue State = IbanState.Ok UpdatedOn = Some DateTimeOffset.UtcNow } do! context.SaveChangesAsync true |&gt; Async.AwaitIAsyncResult |&gt; Async.Ignore return Ok iban | _ -&gt; return Error RequestNotFound } let request (context: DbContext.IbanDbContext) memberId = async { match! avoidDuplicateRequest context memberId with | Ok value -&gt; return! newRequest value | Error error -&gt; return Error error } let requested (context: DbContext.IbanDbContext) memberId = requested context memberId let meetRequest (context: DbContext.IbanDbContext) memberId ibanValue = match IbanValidation.validate ibanValue with | Ok ibanValue -&gt; updateRequestWith context memberId ibanValue | Error error -&gt; async { return Error (IbanInvalid error) } let memberIbans (context: DbContext.IbanDbContext) memberId = memberIbansWith context memberId IbanState.Ok </code></pre>
[]
[ { "body": "<p>I can't say much about the <code>Async</code> behavior of your solution, because I'm not that used to deal with asynchronous programming in F#, but at first sight it looks alright. Instead I'll concentrate on some other aspects.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> let digitalIban =\n let rearrangedIban = iban.Substring(4) + iban.Substring(0,4)\n let replaceBase36LetterWithBase10String (s: string) (c: char) =\n s.Replace(c.ToString(), ((int)c - (int)'A' + 10).ToString())\n List.fold replaceBase36LetterWithBase10String rearrangedIban [ 'A' .. 'Z' ]\n</code></pre>\n</blockquote>\n\n<p>This looks rather ineffective to me, because it iterates through the entire alphabet and query the entire <code>iban</code> string for each char in the alphabet instead of just iterate through the <code>iban</code> sequence:</p>\n\n<pre><code> let digitalIban =\n let replacer str ch =\n match ch with\n | d when Char.IsDigit ch -&gt; sprintf \"%s%c\" str ch\n | _ -&gt; sprintf \"%s%d\" str ((int)ch - (int)'A' + 10)\n\n iban.Substring(4) + iban.Substring(0,4) |&gt; Seq.fold replacer \"\"\n</code></pre>\n\n<hr>\n\n<p>You could strengthen the relation between the validation and the database retrieval modules by defining a <code>IbanString</code>:</p>\n\n<pre><code>type IbanString = \n | IbanString of string\n\nmodule IbanString =\n let toString = function IbanString(str) -&gt; str\n</code></pre>\n\n<p>The return value from <code>IbanValidation.validate</code> could then be:</p>\n\n<pre><code>Result&lt;IbanString, ValidationError&gt;\n</code></pre>\n\n<p>and then <code>updateRequestWith</code> should only accept a <code>IbanString</code> instead of an arbitrary string:</p>\n\n<pre><code>let updateRequestWith (context: DbContext.IbanDbContext) memberId (ibanValue: IbanString) = ...\n</code></pre>\n\n<p>In other situations when using <code>IbanValidation.validate</code> you know that the returned string is valid and encapsulated hence distinguishable from all other strings.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>type ValidationError =\n | IllegalCharacters\n | IncorrectLength\n | UnknownCountry\n | TypingError\n</code></pre>\n</blockquote>\n\n<p>You could augment these values with some useful information:</p>\n\n<pre><code>type ValidationError =\n | IllegalCharacters of char list\n | IncorrectLength of Actual:int * Required:int\n | UnknownCountry of string\n | TypingError of Message:string * Remainder:int\n</code></pre>\n\n<p>So for instance <code>checkCharacters</code> could be changed to:</p>\n\n<pre><code>let private checkCharacters iban =\n match illegalCharacters.Matches(iban) with\n | col when col.Count &gt; 0 -&gt; Error (IllegalCharacters(col |&gt; Seq.map (fun m -&gt; m.Value.[0]) |&gt; Seq.toList))\n | _ -&gt; Ok iban\n</code></pre>\n\n<p>... giving some information about the invalid chars found.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T20:17:58.760", "Id": "437855", "Score": "0", "body": "Thanks for your feedback!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T14:01:31.030", "Id": "225031", "ParentId": "224990", "Score": "4" } }, { "body": "<p>I'm not very experienced with EF, to me your code looks fine but there are some details you can improve as stated in the other answer, and of course other ways of writing the same which I will show you, just to illustrate, not to say it's the way to go:</p>\n\n<pre><code>module Rm.Iban.Domain.IbanValidation\n\nopen System\nopen System.Text.RegularExpressions\nopen FSharpPlus\n\ntype ValidationError =\n | IllegalCharacters\n | IncorrectLength\n | UnknownCountry\n | TypingError\n\n[&lt;AutoOpen&gt;]\nmodule private Impl =\n\n let illegalCharacters = Regex (@\"[^0-9A-Za-z ]\", RegexOptions.Compiled) // consider one liners\n\n let checkCharacters iban =\n if illegalCharacters.IsMatch iban // parens not needed\n then Error IllegalCharacters\n else Ok iban\n\n let cleanup =\n String.toUpper\n &gt;&gt; String.replace \" \" \"\"\n &gt;&gt; Ok\n\n let lengthPerCountry = dict [\n (\"AL\", 28); (\"AD\", 24); (\"AT\", 20); (\"AZ\", 28); (\"BE\", 16); (\"BH\", 22); (\"BA\", 20); (\"BR\", 29);\n (\"BG\", 22); (\"CR\", 21); (\"HR\", 21); (\"CY\", 28); (\"CZ\", 24); (\"DK\", 18); (\"DO\", 28); (\"EE\", 20);\n (\"FO\", 18); (\"FI\", 18); (\"FR\", 27); (\"GE\", 22); (\"DE\", 22); (\"GI\", 23); (\"GR\", 27); (\"GL\", 18);\n (\"GT\", 28); (\"HU\", 28); (\"IS\", 26); (\"IE\", 22); (\"IL\", 23); (\"IT\", 27); (\"KZ\", 20); (\"KW\", 30);\n (\"LV\", 21); (\"LB\", 28); (\"LI\", 21); (\"LT\", 20); (\"LU\", 20); (\"MK\", 19); (\"MT\", 31); (\"MR\", 27);\n (\"MU\", 30); (\"MC\", 27); (\"MD\", 24); (\"ME\", 22); (\"NL\", 18); (\"NO\", 15); (\"PK\", 24); (\"PS\", 29);\n (\"PL\", 28); (\"PT\", 25); (\"RO\", 24); (\"SM\", 27); (\"SA\", 24); (\"RS\", 22); (\"SK\", 24); (\"SI\", 19);\n (\"ES\", 24); (\"SE\", 24); (\"CH\", 21); (\"TN\", 24); (\"TR\", 26); (\"AE\", 23); (\"GB\", 22); (\"VG\", 24); ]\n\n let checkLength (iban: string) =\n let country = limit 2 iban // since you're using F#+ you can use this generic function, next version will ship with String.truncate\n match Dict.tryGetValue country lengthPerCountry with // also this function is available in F#+\n | Some length when length = iban.Length -&gt; Ok iban\n | None -&gt; Error UnknownCountry\n | _ -&gt; Error IncorrectLength\n // Reorganizing the cases like this makes it easier to visualize the rules.\n // My advice is try not to mix match with if, as far as practical.\n\n\n let checkRemainder (iban: string) =\n\n let digitalIban =\n let rearrangedIban = iban.[4..] + iban.[..3] // You can use F# slicing syntax\n let replaceBase36LetterWithBase10String (s: string) (c: char) =\n String.replace (string c) (string (int c - int 'A' + 10)) s // (int)c looks like a C# cast, but this is not a cast, int is a function.\n List.fold replaceBase36LetterWithBase10String rearrangedIban [ 'A' .. 'Z' ]\n // You can also use String.replace from F#+\n // Note that using string function is shorter and looks more functional than ToString, and most importantly it's culture neutral.\n // ToString without additional parameters depends on current thread culture.\n\n let remainder =\n let inline reduceOnce r n = Int32.Parse (string r + string n) % 97\n Regex.Matches (digitalIban.[2..], @\"\\d{1,7}\")\n |&gt; fold reduceOnce (reduceOnce 0 (digitalIban.[..1]))\n // This is a bit F#+ advanced stuff: Matches are part of the Foldable abstraction, so you can fold them directly with the generic fold operation.\n // then by using string and making the function online, your reduceOnce becomes polymorphic on 'r'.\n\n if remainder = 1 then Ok iban\n else Error TypingError\n\n let format iban = Regex.Replace (iban, \".{4}\", \"$0 \") |&gt; Ok\n\nlet validate =\n checkCharacters\n &gt;=&gt; cleanup\n &gt;=&gt; checkLength\n &gt;=&gt; checkRemainder\n &gt;=&gt; format\n// Is not that I am a big fun of point free functions, but I've seen many F# validation examples written in this style, by using composition with the monadic &gt;=&gt; fish operator.\n</code></pre>\n\n<p>The code that create</p>\n\n<pre><code>module Rm.Iban.App.IbanRetrieval\n\nopen System\nopen System.Linq\nopen Microsoft.FSharp.Data\nopen Domain\nopen Microsoft.EntityFrameworkCore\n\ntype RequestError =\n | AlreadyRequested\n\ntype MeetRequestError =\n | RequestNotFound\n | IbanInvalid of IbanValidation.ValidationError\n\n[&lt;AutoOpen&gt;]\nmodule private Impl =\n\n let memberIbansWith (context: DbContext.IbanDbContext) memberId ibanState = query {\n for iban in context.Ibans do\n where (\n iban.MemberId = memberId &amp;&amp;\n iban.State = ibanState) }\n\n let requested (context: DbContext.IbanDbContext) memberId =\n let requested = memberIbansWith context memberId IbanState.Requested\n requested.Select(fun iban -&gt; Some iban)\n .SingleOrDefaultAsync()\n |&gt; Async.AwaitTask\n // The async workflow is not really needed here.\n\n let avoidDuplicateRequest (context: DbContext.IbanDbContext) memberId =\n async {\n let! exists = context.Ibans.AnyAsync(fun iban -&gt;\n iban.MemberId = memberId &amp;&amp;\n iban.State = IbanState.Requested)\n |&gt; Async.AwaitTask\n if exists\n then return Error AlreadyRequested\n else return Ok (context, memberId) \n }\n\n let newRequest ((context: DbContext.IbanDbContext), memberId) =\n async {\n let iban: Iban = {\n Id = Guid.Empty\n MemberId = memberId\n Iban = None\n State = IbanState.Requested\n CreatedOn = DateTimeOffset.UtcNow\n UpdatedOn = None }\n let iban = context.Ibans.Add iban\n do! context.SaveChangesAsync true\n |&gt; Async.AwaitTask\n |&gt; Async.Ignore\n return Ok iban.Entity\n }\n\n let updateRequestWith (context: DbContext.IbanDbContext) memberId ibanValue =\n async {\n match! requested context memberId with\n | Some iban -&gt;\n context.UpdateWith iban\n { iban with\n Iban = Some ibanValue\n State = IbanState.Ok\n UpdatedOn = Some DateTimeOffset.UtcNow }\n do! context.SaveChangesAsync true\n |&gt; Async.AwaitIAsyncResult\n |&gt; Async.Ignore\n return Ok iban\n | _ -&gt;\n return Error RequestNotFound \n }\n\nlet request (context: DbContext.IbanDbContext) memberId =\n async {\n match! avoidDuplicateRequest context memberId with\n | Ok value -&gt; return! newRequest value\n | Error error -&gt; return Error error\n }\n\nlet requested (context: DbContext.IbanDbContext) memberId =\n requested context memberId\n\nlet meetRequest (context: DbContext.IbanDbContext) memberId ibanValue =\n match IbanValidation.validate ibanValue with\n | Ok ibanValue -&gt; updateRequestWith context memberId ibanValue\n | Error error -&gt; async.Return (Error (IbanInvalid error)) // here you can use directly async.Return instead of the whole workflow.\n\nlet memberIbans (context: DbContext.IbanDbContext) memberId =\n memberIbansWith context memberId IbanState.Ok\n</code></pre>\n\n<p>As I said, no big changes just some suggestions and other ways of writing the same, which doesn't mean it's better than what you had already.</p>\n\n<p>The other answer suggests some changes on the design that are interesting, regarding the IbanString suggestion, you can also use <a href=\"https://www.google.com/search?q=f%23+extending+uoms+to+arbitrary+types&amp;oq=f%23+extending+uoms+to+arbitrary+types\" rel=\"nofollow noreferrer\">a technique with UoMs</a> to distinguish between the raw strings and validated ibans, that might be slightly more efficient since UoMs are erased at runtime.</p>\n\n<p>One final note, your Validate function does a bit more than validate, you can leave it like that, it looks ok, but maybe you can change the name to reflect this, something like format and validate.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T22:56:56.187", "Id": "437067", "Score": "0", "body": "Thanks a lot for review! I have two questions however: 1) Is there anything wrong using `Task<T>` instead of `Async<T>`, I mean is it any less F#ish? 2) Since the `IbranRetrieval` module is gonna be used by an ASP.NET Core controller which leverage `Task<T>` is it ok to return `Task<T>` to avoid rechanging `Async<T>` to `Task<T>` in the ASP.NET Core API layer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T09:25:26.203", "Id": "437117", "Score": "1", "body": "Let's discuss it in the chat." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T06:14:06.820", "Id": "225072", "ParentId": "224990", "Score": "3" } } ]
{ "AcceptedAnswerId": "225072", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T20:42:39.303", "Id": "224990", "Score": "6", "Tags": [ "validation", "asynchronous", "f#", "finance", "entity-framework-core" ], "Title": "Asynchronous IBAN API with validation" }
224990
<p>This is an experiment on extending a basic built-in Common Lisp sequence function (namely <code>remove</code>), in order to provide more functionality with little or no impact on performance. The long-term goal might be to provide such extensions for many other CL functions.</p> <p>The CL sequence functions seem to provide at least 3 different kinds of abstraction: 1) data type abstraction, where a sequence can be a list, vector, or string; 2) higher-order functions, where a function can be passed as a parameter; and 3) keyword parameters, where different keyword arguments can tailor the computation for specific uses.</p> <p>The basic idea explored here is to add many more keywords, to give the programmer more capability &amp; flexibility in processing sequences. If successful, this could obviate the need to write (or recall) many sequence-supporting utility functions. It could also consolidate some of the existing CL sequence functions (eg, <code>remove</code>, <code>remove-if</code>, <code>remove-if-not</code>, <code>delete</code>, <code>delete-if</code>, <code>delete-if-not</code>, <code>remove-duplicates</code>, <code>delete-duplicates</code>) into one operation (in this case simply called "remove-sequence" with extra keywords for :destructive and :duplicates). Other non-sequence "remove related" consolidations also might be possible--eg, for <code>remhash</code>, <code>remprop</code>, etc. </p> <p>As an example, consider that there is no built-in provision for removing elements from a sequence based on their index. Along these lines, it might be convenient to have an :index-test keyword that took a function like (lambda (idx elt) (= idx elt)), such that <code>(remove-sequence (list 2 1 0) :index-test (lambda (idx elt) (= idx elt))) -&gt; (2 0)</code>. An included index-aware capability would save writing/finding the appropriate utility.</p> <p>The following extensions add many more such keywords to <code>remove-sequence</code> to see how many are required to generalize on the basic remove functionality. Note that <code>remove-sequence</code> then has only one required argument, the input sequence, with everything else specified by selecting keywords. </p> <p>The following keywords are added so far (in addition to the standard built-in sequence keywords <code>:from-end</code>, <code>:test</code>, <code>:test-not</code>, <code>:start</code>, <code>:end</code>, <code>:count</code>, <code>:key</code>):</p> <p>:item -- Simply moves the required item parameter in <code>remove</code> to a keyword for consistency. <code>(remove item sequence ...) = (remove-sequence sequence :item item ...)</code>. Example: <code>(remove-sequence (list 1 2 3) :item 1) -&gt; (2 3)</code>.</p> <p>:items -- Extends the built-in capability for removing a single item from a sequence to multiple items. More intuitive than using <code>(remove-if (lambda (elt) (position elt items)) sequence ...)</code>. Example: <code>(remove-sequence (list 1 2 3) :items '(1 2)) -&gt; (3)</code>.</p> <p>:index-test -- A designator for a function of 2 arguments: a sequence index and the corresponding element. Allows processing sequences based on element indices. Example: <code>(remove-sequence (list 2 1 0) :index-test (lambda (idx elt) (= idx elt))) -&gt; (2 0)</code></p> <p>:duplicates -- A boolean indicating whether to remove duplicates or not. Folds in the functionality of <code>remove-duplicates</code>. Example: <code>(remove-sequence (list 1 2 3 2 1) :duplicates t) -&gt; (1 2 3)</code>.</p> <p>:duplicated -- A boolean indicating whether to remove all instances of duplicated items. Example: <code>(remove-sequence (list 1 2 3 2 1) :duplicated t) -&gt; (3)</code>.</p> <p>:destructive -- A boolean indicating whether the input sequence may be modified or not. Consolidates remove &amp; delete function variations. Example: <code>(defparameter *sequence* (list 1 2 3)), (remove-sequence *sequence* :item 2 :destructive t) -&gt; (1 3)</code>, where the input sequence may be altered to produce the result for efficiency reasons.</p> <p>The basic operation <code>remove-sequence</code> is implemented as a set of nested macros, which translate a macro call with particular keyword parameters into a built-in CL sequence function. This avoids macro run-time argument evaluation difficulties, avoids extra effort in duplicating built-in CL functionality, takes advantage of the highly tuned &amp; debugged CL sequence functions, and permits compile-time checking for appropriate combinations of keywords. The function labeled <code>present-absent</code> with arguments for positive and negative keywords for each translation, determines whether a particular selection of keyword arguments in a macro call is valid or invalid. (With a total of 13 keywords so far, there are many possible combinations, some of which are inconsistent.)</p> <p>Here are a few issues that I would like to understand better:</p> <p>1) This approach builds on the established CL paradigm of specializing a basic function with keywords. But is there a downside to adding too many keywords?</p> <p>2) I can't think of any more "remove related" keywords for generalizing <code>remove-sequence</code>, but I assume there could be more. Could there be many more?</p> <p>3) Different keywords are appropriate for different basic functions (eg, remove from a sequence and remove from a tree). How does having a bunch of keywords at your disposal compare with a bunch of utilities? (I think I would prefer keywords because they seem more integrated with the language and reduce the search for relevant libraries, but my CL project experience is limited.)</p> <p>4) Is there a better way to implement the same kind of functionality? Thank you for a review...</p> <pre><code>(ql:quickload :iterate) (ql:quickload :alexandria) (defpackage :rem (:use :cl :iterate :alexandria)) (in-package :rem) (defmacro verify (expression value) "Simple test to verify that the macro expression evaluates to the given value." `(progn (unless (equalp ,expression ,value) (error "Verify failed for ~A = ~A" ',expression ,value)) ,expression)) (defmacro rem/del-item (sequence &amp;key item items from-end (test #'eql) (start 0) end count (key #'identity) destructive) "Removes/deletes item (or sequence of items) from sequence." (if items (if destructive `(delete-if (lambda (elt) (position elt ,items :test ,test)) ,sequence :from-end ,from-end :start ,start :end ,end :count ,count :key ,key) `(remove-if (lambda (elt) (position elt ,items :test ,test)) ,sequence :from-end ,from-end :start ,start :end ,end :count ,count :key ,key)) (if destructive `(delete ,item ,sequence :from-end ,from-end :test ,test :start ,start :end ,end :count ,count :key ,key) `(remove ,item ,sequence :from-end ,from-end :test ,test :start ,start :end ,end :count ,count :key ,key)))) (verify (rem/del-item '(1 2 3) :item 2) `(1 3)) (verify (rem/del-item '(1 2 nil 3) :item nil) `(1 2 3)) (verify (rem/del-item '((5 0 1 2) (5 1 2 3) (5 1 3 2) (4 1 2 3)) :item 2 :from-end t :test #'= :count 1 :key #'fourth) `((5 0 1 2) (5 1 2 3) (4 1 2 3))) (verify (rem/del-item '(1 2 3 4 5) :items '(3 4) :test #'=) `(1 2 5)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro rem/del-duplicated (sequence &amp;key (test #'eql) (start 0) end (key #'identity) destructive) "Removes/deletes all repeated sequence elements based on an equality test." `(let ((ht (make-hash-table :test ,test :size (length ,sequence)))) (iterate (for elt in-sequence (subseq ,sequence ,start ,end)) (incf (gethash (funcall ,key elt) ht 0))) ,(if destructive `(delete-if (lambda (elt) (/= 1 (gethash elt ht))) ,sequence :start ,start :end ,end :key ,key) `(remove-if (lambda (elt) (/= 1 (gethash elt ht))) ,sequence :start ,start :end ,end :key ,key)))) (verify (rem/del-duplicated '((5 0 1 2) (5 1 2 3) (5 1 3 2) (4 1 2 3)) :test #'equal :key #'cdr) `((5 0 1 2) (5 1 3 2))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro rem/del-duplicates (sequence &amp;key from-end (test #'eql) (start 0) end (key #'identity) destructive) "Removes/deletes duplicates from sequence." (if destructive `(delete-duplicates ,sequence :from-end ,from-end :test ,test :start ,start :end ,end :key ,key) `(remove-duplicates ,sequence :from-end ,from-end :test ,test :start ,start :end ,end :key ,key))) (verify (rem/del-duplicates '((5 0 1 2) (5 1 2 3) (5 1 3 2) (4 1 2 3)) :test #'equal :key #'cdr) `((5 0 1 2) (5 1 3 2) (4 1 2 3))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro rem/del-indexed (sequence &amp;key from-end index-test (start 0) end count (key #'identity) destructive) "Removes/deletes elements satisfying the index-test (index element) in sequence." `(let* ((delta (if ,from-end -1 +1)) (initial-index (if ,from-end (length ,sequence) -1)) (closure (let ((index initial-index)) (lambda (element) (incf index delta) (funcall ,index-test index (funcall ,key element)))))) ,(if destructive `(delete-if closure ,sequence :from-end ,from-end :start ,start :end ,end :count ,count :key ,key) `(remove-if closure ,sequence :from-end ,from-end :start ,start :end ,end :count ,count :key ,key)))) (verify (rem/del-indexed '(3 1 2 4) :index-test (lambda (idx elt) (= idx elt))) '(3 4)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun present-absent (positives negatives) "Determines whether a selection of keyword arguments is valid or invalid." (and (every (complement #'null) positives) (every #'null negatives))) (defmacro remove-sequence (sequence &amp;key item items (test #'eql) index-test from-end (start 0) end count (key #'identity) duplicates duplicated destructive) "Sequence operations for removing or deleting elements." (cond ((present-absent `(,sequence) `(,index-test ,duplicates ,duplicated)) `(rem/del-item ,sequence :item ,item :items ,items :from-end ,from-end :test ,test :start ,start :end ,end :count ,count :key ,key :destructive ,destructive)) ((present-absent `(,sequence ,duplicated) `(,item ,index-test ,duplicates)) `(rem/del-duplicated ,sequence :test ,test :start ,start :end ,end :key ,key :destructive ,destructive)) ((present-absent `(,sequence ,duplicates) `(,item ,index-test ,duplicated)) `(rem/del-duplicates ,sequence :from-end ,from-end :test ,test :start ,start :end ,end :key ,key :destructive ,destructive)) ((present-absent `(,sequence ,index-test) `(,item ,test ,duplicates ,duplicated)) `(rem/del-indexed ,sequence :from-end ,from-end :index-test ,index-test :start ,start :end ,end :key ,key :destructive ,destructive)) (t (error "Malformed argument list to remove-sequence.")))) (verify (remove-sequence '((5 0 1 2) (5 1 2 3) (5 1 3 2) (4 1 2 3)) :item 2 :from-end t :test #'= :count 1 :key #'fourth) '((5 0 1 2) (5 1 2 3) (4 1 2 3))) (verify (remove-sequence '(1 2 nil 3) :item nil) `(1 2 3)) (verify (remove-sequence '(1 2 3 4 5) :items '(3 4) :test #'=) `(1 2 5)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro rem/del-ht-entry (hashtable &amp;key item items (test #'eql) (key #'identity) destructive) "Removes/deletes an item (or sequence of items) from a hashtable." (if items (if destructive (if (eq `,key #'identity) `(iterate (for elt in-sequence ,items) (remhash elt ,hashtable) (finally (return ,hashtable))) `(progn (maphash (lambda (k v) (declare (ignore v)) (when (position (funcall ,key k) ,items) (remhash k ,hashtable))) ,hashtable) ,hashtable)) (if (eq `,key #'identity) `(let ((new-ht (alexandria:copy-hash-table ,hashtable))) (iterate (for elt in-sequence ,items) (remhash elt new-ht) (finally (return new-ht)))) `(let ((new-ht (alexandria:copy-hash-table ,hashtable))) (maphash (lambda (k v) (declare (ignore v)) (when (position (funcall ,key k) ,items) (remhash k new-ht))) new-ht) new-ht))) (if destructive (if (eq `,key #'identity) `(remhash ,item ,hashtable) `(progn (maphash (lambda (k v) (declare (ignore v)) (when (funcall ,test ,item (funcall ,key k)) (remhash k ,hashtable))) ,hashtable) ,hashtable)) (if (eq `,key #'identity) `(let ((new-ht (alexandria:copy-hash-table ,hashtable))) (remhash ,item ht) new-ht) `(let ((new-ht (alexandria:copy-hash-table ,hashtable))) (maphash (lambda (k v) (declare (ignore v)) (when (funcall ,test ,item (funcall ,key k)) (remhash k ht))) new-ht) new-ht))))) (defmacro rem/del-hashtable (hashtable &amp;key item items (test #'eql) (key #'identity) destructive) (cond ((present-absent `(,hashtable) '(nil)) `(rem/del-ht-entry ,hashtable :item ,item :items ,items :test ,test :key ,key :destructive ,destructive)) (t (error "Malformed argument list to rem/del-hashtable.")))) (defparameter *ht* (let ((ht (make-hash-table :test #'equal))) (setf (gethash '(1 1) ht) 'a (gethash '(2 2) ht) 'b (gethash '(3 3) ht) 'c) ht)) (verify (rem/del-hashtable *ht* :item 1 :test #'= :key #'car :destructive t) (let ((ht (make-hash-table :test #'equal))) (setf (gethash '(2 2) ht) 'b (gethash '(3 3) ht) 'c) ht)) (verify (rem/del-hashtable *ht* :items #(2 3) :test #'= :key #'car) (make-hash-table :test #'equal)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro remove+ (container &amp;key item items (test #'eql) index-test from-end (start 0) end count (key #'identity) duplicates duplicated destructive) "Generalization of remove for some types of containers." (cond ((typep container 'sequence) `(remove-sequence ,container :item ,item :items ,items :test ,test :index-test ,index-test :from-end ,from-end :start ,start :end ,end :count ,count :key ,key :duplicates ,duplicates :duplicated ,duplicated :destructive ,destructive)) ((typep container 'hash-table) `(rem/del-hashtable ,container :item ,item :items ,items :test ,test :key ,key :destructive ,destructive)) ((error "First argument must be a sequence or hash-table container object: ~A~%" container)))) (verify (remove+ '(1 2 3 4 5) :items '(3 4) :test #'=) `(1 2 5)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T17:28:31.333", "Id": "436714", "Score": "0", "body": "how should `(if destructive` work?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T18:55:50.030", "Id": "436863", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>This won't work as intendent since a macro sees source, not values:</p>\n\n<pre><code>(if destructive\n `(delete-if (lambda (elt) (position elt ,items :test ,test)) ,sequence\n :from-end ,from-end :start ,start :end ,end :count ,count :key ,key)\n `(remove-if (lambda (elt) (position elt ,items :test ,test)) ,sequence\n :from-end ,from-end :start ,start :end ,end :count ,count :key ,key))\n</code></pre>\n\n<p>Even if it were working, it is lots of duplication.</p>\n\n<pre><code>`(,(if destructive 'delete-if 'remove-if)\n (lambda (elt) (position elt ,items :test ,test)) ,sequence\n :from-end ,from-end :start ,start :end ,end :count ,count :key ,key)\n</code></pre>\n\n<p>Which still does not work, because <code>destructive</code> isn't a runtime value.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T00:52:52.817", "Id": "436764", "Score": "0", "body": "Good catch. Would it be considered bad form to require simple boolean rather than generalized boolean?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T18:32:11.253", "Id": "436858", "Score": "0", "body": "I've edited the original macro to disallow nonatomic values." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T17:37:19.183", "Id": "225048", "ParentId": "225005", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T01:45:15.673", "Id": "225005", "Score": "2", "Tags": [ "common-lisp" ], "Title": "Abstracting on Common Lisp Function Keyword Parameters" }
225005
<p>A googol (<span class="math-container">\$10^{100}\$</span>) is a massive number: one followed by one-hundred zeros; <span class="math-container">\$100^{100}\$</span> is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1.</p> <p>Considering natural numbers of the form, <span class="math-container">\$a^b\$</span>, where <span class="math-container">\$a, b &lt; 100\$</span>, what is the maximum digital sum?</p> <pre><code>def get_powers(n): """Assumes n a range, generates all numbers to the power of all numbers within the range.""" for num in range(n): for power in range(n): yield num ** power def get_digit_sum(n): """Assumes n a number, returns sum of digits.""" return sum(int(digit) for digit in str(n)) def get_maximum(n): """Assumes n a range, gets all a ** b within range, returns max sum digits.""" return max((get_digit_sum(num) for num in get_powers(n))) if __name__ == '__main__': print(get_maximum(100)) </code></pre>
[]
[ { "body": "<p>Very nice code! Here are a few small comments, most of which are not something you <em>have</em> to change but rather food for thoughts as you learn more.</p>\n\n<ul>\n<li><p>Although this is a matter of personal style, I would turn around your docstrings so what is returned comes first, if possible.</p>\n\n<p>I.e. I would write</p>\n\n<pre><code>\"\"\"Generates all numbers of the form `a ** b` for `a, b &lt; n`.\"\"\"\n\"\"\"Return the sum of digits of the number `n`.\"\"\"\n\"\"\"Return the max sum of the digits of all numbers of the form `a ** b` for `a, b &lt; n`.\"\"\"\n</code></pre></li>\n<li><p>If a generator expression is the only argument to a function, one pair of <code>()</code> can be omitted:</p>\n\n<pre><code>return max(get_digit_sum(num) for num in get_powers(n))\n</code></pre></li>\n<li><p>Although sometimes discouraged, if you need those last 10% of speed, <a href=\"https://codereview.stackexchange.com/a/224487/98493\">this is slightly faster</a> since <code>int</code> is a built-in function implemented in C:</p>\n\n<pre><code>def get_digit_sum(n):\n return sum(map(int, str(n)))\n</code></pre></li>\n<li><p>Nested <code>for</code> loops can be replaced with <code>itertools.product</code>, although here it is arguably harder to read instead of easier. For high levels of nestedness it can help increase readability, though.</p>\n\n<pre><code>from itertools import product\n\ndef get_powers(n):\n for num, power in product(range(n), range(n)):\n yield num ** power\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T12:19:38.900", "Id": "225083", "ParentId": "225006", "Score": "2" } }, { "body": "<p>Your range is too large. </p>\n\n<p>The problem asks for <strong>natural numbers</strong> of the form <span class=\"math-container\">\\$a^b\\$</span>. Natural number start at one (1, 2, 3, ...); whole numbers start at zero (0, 1, 2, 3, ...). If the problem asked for the minimum of the sum of the digits, you’d return zero, while the correct answer would be 1.</p>\n\n<p>Perhaps more importantly, you’re flirting with non-deterministic behaviour. Any positive number to the power of zero is one (<span class=\"math-container\">\\$a^0 = 1\\$</span>), and zero raised to a positive number is zero (<span class=\"math-container\">\\$0^b = 0\\$</span>); <span class=\"math-container\">\\$0^0\\$</span> is mathematically undefined. Python <strong>should</strong> return <code>NaN</code> for that expression. And the sum of digits of <code>NaN</code> is <code>ValueError</code>.</p>\n\n<p>You should use <code>for num in range(1, n)</code> to avoid both the technical <code>NaN</code> and the non-natural number results.</p>\n\n<hr>\n\n<p>Since <span class=\"math-container\">\\$1^b = 1\\$</span>, for efficiency, you could shrink the search space further: <code>for num in range(2, n)</code>, avoiding the first 100 repeated digit sums of the same natural number.</p>\n\n<p>You could also eliminate another 100 digit sums of <code>1</code> by eliminating the 0th powers (<code>for power in range(1, n)</code>). But technically, you’ve now eliminated the digit sum of the value <code>1</code>, so you should make sure it doesn’t affect the answer, or include that afterwards, such as by <code>max(..., default=get_digit_sum(1))</code>.</p>\n\n<hr>\n\n<p>You are still brute-forcing the answer. Look for ways to reduce the problem space. </p>\n\n<p><code>get_digit_sum(99**99) = 936</code>. The smallest number with a digit sum of <code>936</code> would contain <code>936/9 = 104</code> nine digits. If <span class=\"math-container\">\\$a^b &lt; 10^{104}\\$</span>, it doesn’t contain enough digits, so you don’t need to compute the digit sum for that value, and can avoid converting the number to a string, separating it into digits, converting those to int’s, and summing them together.</p>\n\n<p>Better: compute powers in the reverse order. If <span class=\"math-container\">\\$a^b &lt; 10^{104}\\$</span>, you can break out of the inner loop.</p>\n\n<p>Even better: compute the bases in the reverse order also. If <span class=\"math-container\">\\$a^{99} &lt; 10^{104}\\$</span>, you can break out of the outer loop too.</p>\n\n<p>But don’t hard code <span class=\"math-container\">\\$10^{104}\\$</span> in your program. It should calculate that limit itself. </p>\n\n<p>Even better: make the threshold dynamic. If the digit sum goes up by over 9, your minimum digit count goes up by 1, and your minimum threshold goes up as well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T13:49:21.290", "Id": "225088", "ParentId": "225006", "Score": "0" } } ]
{ "AcceptedAnswerId": "225083", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T03:36:26.317", "Id": "225006", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge" ], "Title": "Project Euler # 56 Powerful digit sum in Python" }
225006
<p>Purpose of the code is to delete all virus affected files from your pc. </p> <pre><code> private static void SearchAndDeleteFiles(String directoryName, List&lt;File&gt; files) { File directory = new File(directoryName); File[] fList = directory.listFiles(); if (fList != null) { for (File file : fList) { if (file.isFile() &amp;&amp; (file.getName().endsWith(".ccc") || file.getName().startsWith("_how_recover_anj") || file.getName().startsWith("_how_recover_jav"))) { files.add(file); System.out.println((new StringBuilder()).append(file).toString()); boolean isSuccess = file.delete(); System.out.println( (new StringBuilder()).append(file).append(" delete status: ").append(isSuccess).toString()); } else if (file.isDirectory()) { SearchAndDeleteFiles(file.getAbsolutePath(), files); } } } } </code></pre>
[]
[ { "body": "<p>For what you are trying to achieve, Java has a very nice solution since Java 7: <code>java.nio.Files</code>.</p>\n\n<p>The <code>Files</code> class comes with a lot of useful methods that do what you did more expressively and easier to understand.</p>\n\n<p>Instead of listing all files in a directory and looping over them, you can actually walk the <em>entire</em> file tree, including sub-directories, if you want.</p>\n\n<p>You can do this the \"callback-style\" or using Java Streams. I like streams, so I will try and rebuild what you did, but with <code>java.nio.Files</code> and <code>java.util.stream.Stream</code>. Also I am going to use Java 11's <code>var</code> keyword, because I don't like typing out all the types unless absolutely necessary:</p>\n\n<pre><code>/**\n * Deletes all files with their names ending in \".ccc\" or starting with\n * \"_how_recover_anj\" or \"_how_recover_jav\".\n * \n * @param directoryName The directory to search in.\n * @return A map of all files which were attempted to be deleted and their\n * deletion status.\n */\nprivate static Map&lt;File, Boolean&gt; SearchAndDeleteFiles(String directoryName) throws IOException {\n try (var fileStream = Files.walk(Paths.get(directoryName))) {\n return fileStream.map(path -&gt; path.toFile())\n .filter(file -&gt; \n file.isFile()\n &amp;&amp; (file.getName().endsWith(\".ccc\")\n || file.getName().startsWith(\"_how_recover_anj\")\n || file.getName().startsWith(\"_how_recover_jav\")))\n .peek(file -&gt; System.out.println(file))\n // Actually delete the file and record the status.\n .map(file -&gt; Map.entry(file, file.delete()))\n .peek(entry -&gt; System.out.printf(\"%s delete status: %s%n\", entry.getKey(), entry.getValue()))\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));\n } catch (IOException e) {\n throw new IOException(e);\n }\n}\n</code></pre>\n\n<p>First you see, that I actually provide some documentation. Tell the user (even your future self), what this method is supposed to do, what is wants as parameters and returns as a result.</p>\n\n<p>Also notice, that I removed the <code>files</code> argument. You changed that list and added the files that you traversed (not the ones that were successfully deleted) to that list. This is a code smell as you are modifying the incoming collection which could very possibly be immutable without checking.<br>\nIn my solution, this is no longer necessary, as we don't need any recursion and actually return which files we traversed and attempted to delete.</p>\n\n<p>Then I am following the recommendation written in the documentation and walk the file tree in a <code>try-with-resources</code> block. This makes sure, that in any case, the file handles to the directories are cleanly closed.</p>\n\n<p>The stream is expressive and pretty self-explanatory, it first maps all the file paths to actual Java File objects, filters the ones matching your criteria, then prints the file name. You don't need to construct <code>StringBuilder</code>s for every string you print, just more complex expressions and actually constructed strings.</p>\n\n<p>Then it maps the file to itself and it's deletion status. This status is then printed, just like in your method and collected into a map.<br>\nThe map is then returned.</p>\n\n<p>If any exception is thrown, it is re-thrown and the stream of paths is cleanly closed.</p>\n\n<p>The <code>Files.walk</code> method is implicitly recursive and lazy, so you don't need to worry about performance or traversing into sub-directories.</p>\n\n<p>You could make this method even more flexible, if you want, but I hope this answers your question.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T09:53:05.720", "Id": "225021", "ParentId": "225013", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T06:42:57.970", "Id": "225013", "Score": "6", "Tags": [ "java", "file-system" ], "Title": "Delete all virus-affected files with certain filenames" }
225013
<p>Currently learning from "LPTHW - Zed Shaw" and "Automating the boring stuff".</p> <p>There is a nested dictionary of the type <code>{'string1': {inner dict 1}, 'string2':{inner dict 2},...}</code>.</p> <p>I want a non nested consolidated dictionary of all the keys and values from all of the <code>{inner dicts}</code>. I have written the code below, but I am not convinced it is the most efficient way. I am looking for suggestions on how the code can be simplified by utilising logic within a single loop or by making use of some other modules and methods.</p> <p>Is that new method efficient from a processing point of view?</p> <pre><code>allGuests = {'Alice': {'apples': 5, 'pretzels': 12}, 'Bob': {'ham sandwiches': 3, 'apples': 2}, 'Carol': {'cups': 3, 'apple pies': 1}} item_list = [] count_list = [] consolidated = {} all_items_list = list(allGuests.values()) #This is a list of sub dictionaries #Loop for the number of guests who brought items for guest in range(0, len(allGuests)): #Creating 2 separate lists for 'items' and 'their count' item_list = item_list + list(all_items_list[guest].keys()) count_list = count_list + list(all_items_list[guest].values()) #Creating a consolidated dictionary for index in range(0, len(item_list)): if not consolidated.get(item_list[index]): consolidated.setdefault(item_list[index], count_list[index]) else: consolidated[item_list[index]] = consolidated[item_list[index]] + count_list[index] pprint.pprint(consolidated) </code></pre> <p>Expected output:</p> <blockquote> <pre><code>{'apple pies': 1, 'apples': 7, 'cups': 3, 'ham sandwiches': 3, 'pretzels': 12} </code></pre> </blockquote>
[]
[ { "body": "<p>Below code worked as per one suggestion on stackoverflow</p>\n\n<pre><code> consolidated = {}\n for guest in allGuests.values():\n for key, value in guest.items():\n if not consolidated.get(key):\n consolidated.setdefault(key, value)\n\n else:\n consolidated[key] = consolidated[key] + value\n\n pprint.pprint(consolidated)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T13:31:33.043", "Id": "455884", "Score": "0", "body": "Note that a self-answer, needs to be an answer (i.e. a *review*), not a code dump. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T09:40:37.740", "Id": "225019", "ParentId": "225014", "Score": "-1" } }, { "body": "<p>You can use .get method with default parameter. </p>\n\n<pre><code>consolidated = {}\nfor guest in allGuests.values():\n for key, value in guest.items():\n consolidated[key] = consolidated.get(key, 0) + value\n</code></pre>\n\n<p>Output: <code>{'apples': 7, 'pretzels': 12, 'ham sandwiches': 3, 'cups': 3, 'apple pies': 1}</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T11:30:12.570", "Id": "436667", "Score": "1", "body": "Could you also hint out why the OP's code isn't as efficient as yours?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T11:15:33.200", "Id": "225025", "ParentId": "225014", "Score": "2" } }, { "body": "<p>If your dictionary always has the structure <code>{key: {key: int}}</code>, i.e. the values of the inner dictionaries are all integers, this can be easily achieved using <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter.update\" rel=\"nofollow noreferrer\"><code>collections.Counter.update</code></a>:</p>\n\n<pre><code>from collections import Counter\n\ndef consolidate(d):\n consolidated = Counter()\n for sub_dict in d.values():\n consolidated.update(sub_dict)\n return dict(consolidated)\n\n\nif __name__ == \"__main__\":\n all_guests = {'Alice': {'apples': 5, 'pretzels': 12},\n 'Bob': {'ham sandwiches': 3, 'apples': 2},\n 'Carol': {'cups': 3, 'apple pies': 1}}\n print(consolidate(all_guests))\n # {'apple pies': 1, 'apples': 7, 'cups': 3, 'ham sandwiches': 3, 'pretzels': 12}\n</code></pre>\n\n<p>Note that Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, that recommends using <code>lower_case</code> both for functions and for variables. I also put this code into a function, so it is reusable, and only called it with the test case under a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this module without executing the test case.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T14:40:56.693", "Id": "233164", "ParentId": "225014", "Score": "3" } } ]
{ "AcceptedAnswerId": "225025", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T07:17:08.523", "Id": "225014", "Score": "4", "Tags": [ "python", "beginner", "python-3.x", "hash-map" ], "Title": "Consolidating a dictionary from nested dictionary" }
225014
<p>I have re-implemented in <strong>C++</strong> an algorithm already in JavaScript available <a href="https://codeincomplete.com/posts/bin-packing/" rel="nofollow noreferrer">here</a> and <a href="https://github.com/jakesgordon/bin-packing" rel="nofollow noreferrer">there</a>.</p> <p>C++ code works fine, but I have memory management concerns:</p> <ol> <li>I allocate memory with such statement as <code>m_root = new Block(...)</code> dangerously</li> <li>When freeing memory with <code>if (m_fit) { delete m_fit; m_fit = nullptr; }</code>, exceptions are thrown</li> </ol> <p>I feel like my C++ code is leaking memory, I wonder if something is noticeably wrong:</p> <h2>Calling the algorithm</h2> <pre class="lang-cpp prettyprint-override"><code>void createBlocks(std::vector&lt;Block&gt; &amp;blocks) { for (int i = 0; i &lt; 100; ++i) { float w = i * 1.1; // semi-random float h = i * 0.9; // semi-random float x = i - 10; // semi-random float y = i + 5; // semi-random Block block = Block(w, h, x, y); blocks.push_back(block); } } void sortDescendingInSize(std::vector&lt;Block&gt; &amp;blocks) { std::sort(blocks.begin(), blocks.end(), [](const Block&amp; first, const Block &amp;second) { float firstMaxSide = std::max( first.m_h, first.m_w); float secondMaxSide = std::max(second.m_h, second.m_w); // returns ​true if the first argument is ordered before the second // order descending return firstMaxSide &gt; secondMaxSide; }); } void main() { std::vector&lt;Block&gt; blocks = std::vector&lt;Block&gt;(); createBlocks(blocks); if (blocks.empty()) return; sortDescendingInSize(blocks); GrowingPacker growingPacker = GrowingPacker(); growingPacker.fit(blocks); for (const Block &amp;block : blocks) { if (block.m_fit &amp;&amp; block.m_item) { std::cout &lt;&lt; &lt;&lt; "w:" &lt;&lt; block.m_w &lt;&lt; "h:" &lt;&lt; block.m_h &lt;&lt; "fit-&gt;w:" &lt;&lt; block.m_fit-&gt;m_w &lt;&lt; "fit-&gt;h:" &lt;&lt; block.m_fit-&gt;m_h &lt;&lt; "fit-&gt;x:" &lt;&lt; block.m_fit-&gt;m_x &lt;&lt; "fit-&gt;y:" &lt;&lt; block.m_fit-&gt;m_y; } } } </code></pre> <h2>Algorithm class definition</h2> <pre class="lang-cpp prettyprint-override"><code>#ifndef GROWINGPACKER_H #define GROWINGPACKER_H #include "vector" #include "src/pack/block.h" class GrowingPacker { public: GrowingPacker(); void fit(std::vector&lt;Block&gt; &amp;blocks); private: Block *findNode(Block *root, float w, float h); Block *splitNode(Block *node, float w, float h); Block *growNode(float w, float h); Block *growRight(float w, float h); Block *growDown(float w, float h); private: Block *m_root; }; #endif // GROWINGPACKER_H </code></pre> <h2>Algorithm class implementation</h2> <pre class="lang-cpp prettyprint-override"><code>#include "growingpacker.h" GrowingPacker::GrowingPacker() { } void GrowingPacker::fit(std::vector&lt;Block&gt; &amp;blocks) { size_t len = blocks.size(); float w = len &gt; 0 ? blocks[0].m_w : 0; float h = len &gt; 0 ? blocks[0].m_h : 0; m_root = new Block(w,h, 0, 0); for (Block &amp;block : blocks) { Block *node = findNode(m_root, block.m_w, block.m_h); if (node) block.m_fit = splitNode(node, block.m_w, block.m_h); else block.m_fit = growNode(block.m_w, block.m_h); } return; } Block *GrowingPacker::findNode(Block *root, float w, float h) { if (root-&gt;m_used) { Block *tmp = findNode(root-&gt;m_right, w, h); if (tmp) return tmp; else return findNode(root-&gt;m_down, w, h); } else if ( w &lt;= root-&gt;m_w &amp;&amp; h &lt;= root-&gt;m_h) return root; else return nullptr; } Block *GrowingPacker::splitNode(Block *node, float w, float h) { node-&gt;m_used = true; node-&gt;m_down = new Block(node-&gt;m_w, node-&gt;m_h - h, node-&gt;m_x, node-&gt;m_y + h); node-&gt;m_right = new Block(node-&gt;m_w - w, h, node-&gt;m_x + w, node-&gt;m_y ); return node; } Block *GrowingPacker::growNode(float w, float h) { bool canGrowDown = w &lt;= m_root-&gt;m_w; bool canGrowRight = h &lt;= m_root-&gt;m_h; // attempt to keep square-ish by growing right when height is much greater than width bool shouldGrowRight = canGrowRight &amp;&amp; m_root-&gt;m_h &gt;= (m_root-&gt;m_w + w); // attempt to keep square-ish by growing down when width is much greater than height bool shouldGrowDown = canGrowDown &amp;&amp; m_root-&gt;m_w &gt;= (m_root-&gt;m_h + h); if (shouldGrowRight) return growRight(w, h); else if (shouldGrowDown) return growDown(w, h); else if (canGrowRight) return growRight(w, h); else if (canGrowDown) return growDown(w, h); else // need to ensure sensible root starting size to avoid this happening return nullptr; } Block *GrowingPacker::growRight(float w, float h) { m_root = new Block(m_root-&gt;m_w + w , m_root-&gt;m_h , 0.0f , 0.0f , true , m_root , new Block(w, m_root-&gt;m_h, m_root-&gt;m_w, 0.0f) ); Block *node = findNode(m_root, w, h); if (node) return splitNode(node, w, h); else return nullptr; } Block *GrowingPacker::growDown(float w, float h) { m_root = new Block(m_root-&gt;m_w , m_root-&gt;m_h + h , 0.0f , 0.0f , true , new Block (m_root-&gt;m_w, h, 0.0f, m_root-&gt;m_h) , m_root ); Block *node = findNode(m_root, w, h); if (node) return splitNode(node, w, h); else return nullptr; } </code></pre> <h2>Block/node class definition which is used by algorithm</h2> <pre class="lang-cpp prettyprint-override"><code>#ifndef BLOCK_H #define BLOCK_H class EditorSceneItem; class Block { public: Block(); Block(float w, float h, float x, float y); Block(float w, float h, float x, float y, bool used, Block *down, Block *right); // Copy constructor Block(const Block &amp;other); // Copy assignment operator Block &amp; operator= ( const Block&amp; other ); // Destructor ~Block(); // Move constructor Block(Block&amp;&amp; other); // Move assignment operator Block&amp; operator=(Block &amp;&amp;other); private: void freePossibleAllocatedMemory(); void releaseResourcesWithoutFreeingMemory(); void swapInto(Block&amp; destination) const noexcept; public: float m_w; float m_h; float m_x; float m_y; bool m_used; Block *m_down = nullptr; Block *m_right = nullptr; Block *m_fit = nullptr; }; #endif // BLOCK_H </code></pre> <h2>Block/node class implementation</h2> <pre class="lang-cpp prettyprint-override"><code>#include "block.h" Block::Block() : m_w(0.0f), m_h(0.0f) , m_x(0.0f), m_y(0.0f) , m_used(false) , m_down(nullptr) , m_right(nullptr) , m_fit(nullptr) { } Block::Block(float w, float h, float x, float y) : m_w(w), m_h(h) , m_x(x), m_y(y) , m_used(false) , m_down(nullptr) , m_right(nullptr) , m_fit(nullptr) { } Block::Block(float w, float h, float x, float y, bool used, Block *down, Block *right) : m_w(w), m_h(h) , m_x(x), m_y(y) , m_used(used) , m_down(down) , m_right(right) , m_fit(nullptr) { } Block::Block(const Block &amp;other) : m_w(other.m_w), m_h(other.m_h) , m_x(other.m_x), m_y(other.m_y) , m_used(other.m_used) , m_down(other.m_down) , m_right(other.m_right) , m_fit(other.m_fit) {} Block &amp; Block::operator= ( const Block&amp; other ) { // Self assignment if (&amp;other == this) return *this; this-&gt;freePossibleAllocatedMemory(); other.swapInto(*this); return *this; } Block::~Block() { freePossibleAllocatedMemory(); } Block::Block(Block&amp;&amp; other) : Block() // delegate to the default constructor { other.swapInto(*this); other.releaseResourcesWithoutFreeingMemory(); } Block&amp; Block::operator=(Block &amp;&amp;other) { // Self assignment if (this == &amp;other) return *this; this-&gt;freePossibleAllocatedMemory(); other.swapInto(*this); other.releaseResourcesWithoutFreeingMemory(); return *this; } void Block::freePossibleAllocatedMemory() { // ** STRANGE: an exception is thrown at following lines when freeing memory // Exception is avoided by commenting out lines // Exception is possibly due to bad memory management if (m_down) { delete m_down; m_down = nullptr; } if (m_right) { delete m_right; m_right = nullptr; } if (m_fit) { delete m_fit; m_fit = nullptr; } } void Block::releaseResourcesWithoutFreeingMemory() { // Release source m_w = 0.0f; m_h = 0.0f; m_x = 0.0f; m_y = 0.0f; m_used = false; m_down = nullptr; m_right = nullptr; m_fit = nullptr; } void Block::swapInto(Block&amp; destination) const noexcept { destination.m_w = m_w; // Don't check equality of float destination.m_h = m_h; destination.m_x = m_x; destination.m_y = m_y; if (destination.m_used != m_used) destination.m_used = m_used; if (destination.m_down != m_down) destination.m_down = m_down; if (destination.m_right != m_right) destination.m_right = m_right; if (destination.m_fit != m_fit) destination.m_fit = m_fit; } </code></pre> <p>Thanks for your review =)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T07:36:23.153", "Id": "436640", "Score": "2", "body": "Instead of managing memory allocation / deallocation manually you could use [smart pointers](https://en.cppreference.com/w/cpp/memory) with the correct semantics you need." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T07:57:55.270", "Id": "436646", "Score": "0", "body": "_\"When freeing memory with if (m_fit) { delete m_fit; m_fit = nullptr; }, exceptions are thrown\"_ Note that your question is _off-topic_ for Code Review. Only working code is ready for review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T08:57:10.473", "Id": "436655", "Score": "0", "body": "@πάνταῥεῖ Thanks, I edited it out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T09:04:42.623", "Id": "436656", "Score": "3", "body": "Well, I am afraid editing out doesn't make that much better. Does your code throw exceptions or not? If so, it's not working properly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T09:13:08.397", "Id": "436657", "Score": "0", "body": "Recommended read: [What is The Rule of Three?](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three)" } ]
[ { "body": "<p>As suggested by @πάνταῥεῖ I replaced all instances of <code>Block *</code> pointer in the code with <code>std::shared_ptr&lt;Block&gt;</code> and I feel much better regarding memory management. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T11:17:54.527", "Id": "436666", "Score": "0", "body": "@πάνταῥεῖ Thanks. Also the exception is resolved after implementing `std::shared_ptr<>` =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T15:48:46.653", "Id": "436825", "Score": "1", "body": "would you please explain your answer further, to make this more of a review?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T09:17:11.203", "Id": "436911", "Score": "0", "body": "@Malachi Thanks, I'm going to explain further." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T10:31:49.827", "Id": "225024", "ParentId": "225015", "Score": "0" } } ]
{ "AcceptedAnswerId": "225024", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T07:32:44.077", "Id": "225015", "Score": "-3", "Tags": [ "c++", "algorithm", "memory-management" ], "Title": "Binary tree algorithm for 2D bin packing" }
225015
<h1>Background</h1> <p>A recent question <a href="https://codereview.stackexchange.com/q/224964">Print sums of all subsets</a> made its way to the Hot Network Questions list. The problem is simple:</p> <blockquote> <h2>Print sums of all subsets of a given set</h2> <p>Given an array of integers, print sums of all subsets in it. Output sums can be printed in any order.</p> <p>Examples:</p> <pre class="lang-none prettyprint-override"><code>Input : arr[] = {2, 3} Output: 0 2 3 5 Input : arr[] = {2, 4, 5} Output : 0 2 4 5 6 7 9 11 </code></pre> </blockquote> <p>(<a href="https://www.geeksforgeeks.org/print-sums-subsets-given-set/" rel="nofollow noreferrer">Source</a>)</p> <p>The OP used an exponential space algorithm. I didn't care about this too much in my answer, but later an <a href="https://codereview.stackexchange.com/a/224996">answer</a> by Will Ness noted that exponential space is not required. The better algorithm works like this: (to quote that answer)</p> <blockquote> <p>Instead, have your program create <span class="math-container">\$n\$</span> nested loops at run-time, in effect enumerating the binary encoding of <span class="math-container">\$2^n\$</span>, and print the sums out from the innermost loop. In pseudocode:</p> <pre class="lang-none prettyprint-override"><code> // {5, 4, 3} sum = 0 for x in {5, 0}: // included, not included sum += x for x in {4, 0}: sum += x for x in {3, 0}: sum += x print sum sum -= x sum -= x sum -= x </code></pre> </blockquote> <p>I decided to implement this algorithm.</p> <h1>Code</h1> <p>I wrote the code in C++17. <code>subset_sums</code> is a generic algorithm which gives the results to an output iterator, so the user can choose to output the results or store them immediately, or customize the output format if they want, etc. I am influenced a lot by the <a href="https://ericniebler.github.io/range-v3/" rel="nofollow noreferrer">Range-v3 library</a>, so my algorithm uses iterator-sentinel pairs instead of the traditional iterator-iterator pairs, and it also supports projections. This code does <em>not</em> use the Range-v3 library, though. The <code>identity</code> function object type is standardized in C++20, so I rolled out my own version.</p> <pre><code>#include &lt;functional&gt; #include &lt;iterator&gt; #include &lt;utility&gt; namespace util { struct identity { using is_transparent = int; template &lt;typename T&gt; constexpr T&amp;&amp; operator()(T&amp;&amp; arg) const noexcept { return std::forward&lt;T&gt;(arg); } }; } template &lt;typename ForwardIt, typename Sentinel, typename OutputIt, typename Value, typename BinaryOp = std::plus&lt;&gt;, typename Proj = util::identity&gt; OutputIt subset_sums(ForwardIt first, Sentinel last, OutputIt dest, Value init, BinaryOp bin = {}, Proj proj = {}) { if (first == last) return *dest++ = init; auto value = proj(*first++); dest = subset_sums(first, last, dest, init, bin, proj); return subset_sums(first, last, dest, bin(init, value), bin, proj); } template &lt;typename ForwardIt, typename Sentinel, typename OutputIt&gt; OutputIt subset_sums(ForwardIt first, Sentinel last, OutputIt dest) { using Value = typename std::iterator_traits&lt;ForwardIt&gt;::value_type; return subset_sums(first, last, dest, Value{}); } </code></pre> <p>The <code>(first, last, dest)</code> version is a separate overload because the calculation of the value type is a bit complicated and I don't want to clutter the general version.</p> <h1>Usage example</h1> <p>The original problem:</p> <pre><code>#include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;vector&gt; using number_t = long long; int main() { std::vector&lt;number_t&gt; nums{3, 1, 4}; subset_sums(nums.begin(), nums.end(), std::ostream_iterator&lt;number_t&gt;{std::cout, "\n"}); } </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>0 4 1 5 3 7 4 8 </code></pre> <p>Same problem, but with products instead of sums:</p> <pre><code>#include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;vector&gt; using number_t = long long; int main() { std::vector&lt;number_t&gt; nums{3, 1, 4}; subset_sums(nums.begin(), nums.end(), std::ostream_iterator&lt;number_t&gt;{std::cout, "\n"}, number_t{1}, std::multiplies&lt;&gt;{}); } </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>1 4 1 4 3 12 3 12 </code></pre> <p>Possibly non-contiguous substrings in a string:</p> <pre><code>#include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;string&gt; int main() { std::string str = "review"; subset_sums(str.begin(), str.end(), std::ostream_iterator&lt;std::string&gt;{std::cout, "\n"}, std::string{}); } </code></pre> <p>Output: (the initial empty line is intentional)</p> <pre> w e ew i iw ie iew v vw ve vew vi viw vie view e ew ee eew ei eiw eie eiew ev evw eve evew evi eviw evie eview r rw re rew ri riw rie riew rv rvw rve rvew rvi rviw rvie rview re rew ree reew rei reiw reie reiew rev revw reve revew revi reviw revie review </pre> <p>I have also tested with <code>std::forward_list</code> to make sure that the algorithm works with forward iterators.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T08:38:37.867", "Id": "436650", "Score": "1", "body": "so that's what modern C++ looks like. very nice! :) the ordering that you're using (*not included; included*) has allowed you to simplify and streamline the code into just two straight recursive calls. (I used the flipped order purely because it *sounded* better, to me :)). the string-based powerset is impressive, too. although, it will require exponential number of allocations and deallocations, no? In C, to overcome that, I'd use a fixed-sized char array and have the recursive calls fill it up gradually with the letters, mutating the array cells... (again your ordering is better there)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T08:41:14.947", "Id": "436651", "Score": "0", "body": "@WillNess Yeah, I should probably overwrite the value in place instead of passing by value. You should write that as an answer :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T08:41:49.260", "Id": "436652", "Score": "0", "body": "(well, not *only* because it sounded better; I wanted to show the general structure of emulating a nondeterministic algorithm by nested loops enumeration)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T08:46:32.830", "Id": "436653", "Score": "0", "body": "modern C++ is not my strongest suit. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T08:48:37.020", "Id": "436654", "Score": "1", "body": "@WillNess With some tests, I noticed that Small String Optimization kicks in here, so no allocation and deallocation :) But unnecessarily copying everything around is definitely a problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T02:02:44.183", "Id": "436768", "Score": "0", "body": "@WillNess By the way, whether you do (not included; included) or (included; not included) does not really matter here. Just swap `init` and `bin(init, value)` in the two recursive calls to `subset_sums` and there you go :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T04:22:43.067", "Id": "436772", "Score": "0", "body": "also true! it was *recursion* that enabled this, and using the function arguments to pass the new values in, a.o.t. mutating global variables." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T07:57:40.810", "Id": "225018", "Score": "6", "Tags": [ "c++", "algorithm", "iterator", "c++17" ], "Title": "General algorithm to calculate sums of all subsets of a given sequence of numbers" }
225018
<p>I am refactoring <a href="https://github.com/jashkenas/docco/blob/d3da6e9b59aeaf197b80c3d6c982de754a14832a/docco.js#L151-L155" rel="nofollow noreferrer">this piece of code</a>.</p> <p>The main part I am fixing is:</p> <pre><code>for (i = j = 0, len = lines.length; j &lt; len; i = ++j) { line = lines[i]; lines[i] = maybeCode &amp;&amp; (match = /^([ ]{4}|[ ]{0,3}\t)/.exec(line)) ? (isText = false, line.slice(match[0].length)) : (maybeCode = /^\s*$/.test(line)) ? isText ? lang.symbol : '' : (isText = true, lang.symbol + ' ' + line); } </code></pre> <p>(I know, right?) The goal of the function is simple: starting from an array if "lines" in Markdown format, it needs to produce working Coffeescript code.</p> <p>So, for example this string:</p> <pre><code>This is text The point of this exercise is to turn this MD file into a compilable coffeescript code -- where the code bits are indented by three spaces. So, this is code: document = (options = {}, callback) -&gt; config = configure options Code can have an empty line. blah And then there is text again </code></pre> <p>Should become:</p> <pre><code># This is text # # The point if this exercis is to turn this MD file into a compilable # coffeescript code -- where the code bits are indented by three spaces. # # So, this is code: # document = (options = {}, callback) -&gt; config = configure options Code can have an empty line. blah # And then there is text again. </code></pre> <p>The idea is that:</p> <ul> <li>Any text that is indented by four spaces becomes "pure code" (the leading spaces are taken away)</li> <li>Any text that doesn't have indentation spaces become a comment (yes, coffeescript has <code>#</code> as one line comments</li> </ul> <p>The tricky part is in empty lines. If they happen between "code" (that is, indented stuff), they should be just blank lines. If they happen between indented text, they should have a leading <code>#</code> (since they are an empty line in the text which then becomes documentation).</p> <p>What follows is a working script with the way I "evolved" the beast:</p> <ul> <li><p><code>originalCode()</code> is the code as it was. It works, but it's a huge impossible to maintain one-liner</p></li> <li><p><code>fixedConditional()</code> is the same code as above, where I at least worked out how the ternary operators nested into each other</p></li> <li><p><code>ternaryIntoIf()</code> is the conversion of the existing ternary operators into IFs</p></li> <li><p><code>fullRewrite()</code> is my full rewrite.</p></li> </ul> <p>My problem is that I just <em>cannot</em> get my head around the <code>ternaryIntoIf()</code> function (which should be really easy to read) with <code>maybeCode</code> testing for empty lines, and <em>two</em> different flags, <code>isText</code> and <code>maybeCode</code>, to manage the possible case with an empty line...</p> <p>The real question is: <strong>Am I missing anything in terms of what the original code does?</strong> Do those two flags cover a case that I didn't think about? Am I missing something? </p> <p>Here is the full working code</p> <pre><code>var startingLines = `This is text The point if this exercis is to turn this MD file into a compilable coffeescript code -- where the code bits are indented by three spaces. So, this is code: document = (options = {}, callback) -&gt; config = configure options Code can have an empty line. blah And then there is text again.`.split(/\n/) var lang = { symbol: '#' } function originalCode (startingLines) { var isText, maybeCode, match var line, i, j, len var lines = [ ...startingLines ] isText = maybeCode = true for (i = j = 0, len = lines.length; j &lt; len; i = ++j) { line = lines[i] lines[i] = maybeCode &amp;&amp; (match = /^([ ]{4}|[ ]{0,3}\t)/.exec(line)) ? (isText = false, line.slice(match[0].length)) : (maybeCode = /^\s*$/.test(line)) ? isText ? lang.symbol : '' : (isText = true, lang.symbol + ' ' + line); } return lines.join('\n') } function fixedConditional (startingLines) { var isText, maybeCode, match var lines = [ ...startingLines ] isText = maybeCode = true for (let i in lines) { let line = lines[i] lines[i] = maybeCode &amp;&amp; (match = /^([ ]{4}|[ ]{0,3}\t)/.exec(line)) ? (isText = false, line.slice(match[0].length)) : (maybeCode = /^\s*$/.test(line)) ? isText ? lang.symbol : '' : (isText = true, lang.symbol + ' ' + line) } return lines.join('\n') } function ternaryIntoIf (startingLines) { var isText, maybeCode, match var lines = [ ...startingLines ] isText = maybeCode = true for (let i in lines) { let line = lines[i] if (maybeCode &amp;&amp; (match = /^([ ]{4}|[ ]{0,3}\t)/.exec(line))) { isText = false lines[i] = line.slice(match[0].length) } else { maybeCode = /^\s*$/.test(line) if (maybeCode) { lines[i] = isText ? lang.symbol : '' } else { isText = true lines[i] = lang.symbol + ' ' + line } } } return lines.join('\n') } function fullRewrite (startingLines) { var lines = [ ...startingLines ] var match var markdownIndented = /^([ ]{4}|[ ]{0,3}\t)/ var inCode = lines[0] &amp;&amp; markdownIndented.exec(lines[0]) for (let i in lines) { let line = lines[i] var emptyLine = /^\s*$/.test(line) if (emptyLine) { lines[i] = inCode ? '' : lang.symbol } else { inCode = (match = markdownIndented.exec(line)) lines[i] = inCode ? line.slice(match[0].length) : lang.symbol + ' ' + line } } return lines.join('\n') } console.log('\n\nOriginal code') console.log(originalCode(startingLines)) console.log('\n\nConditional fixed, better cycle') console.log(fixedConditional(startingLines)) console.log('\n\nTernary into if') console.log(ternaryIntoIf(startingLines)) console.log('\n\nFULL REWRITE') console.log(fullRewrite(startingLines)) <span class="math-container">````</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T10:28:01.270", "Id": "436662", "Score": "0", "body": "We can review your code _fullRewrite_, but not the original code I'm afraid. Only code written by you is subject to review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T10:32:26.653", "Id": "436663", "Score": "0", "body": "`ternaryIntoIf()` is a near-total rewrites too... The others are to show how I got there, and what the original code is supposed to do" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T10:34:01.517", "Id": "436664", "Score": "2", "body": "Your question _Am I missing anything in terms of what the original code does?_ asks about code not written by you, which you don't fully understand. You also don't know whether your rewrite accounts for all edge cases of the original code. Not knowing whether your code works as intended is also off-topic for this site. Check our help center for more details: https://codereview.stackexchange.com/help/dont-ask" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T11:49:33.590", "Id": "436668", "Score": "0", "body": "I did a code review on open source code, and spent nearly 1 hour writing my post. If it doesn't fit this site, downvote it, I will delete it, whatever. But it looks to me like a well posed, legitimate question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T11:51:03.107", "Id": "436669", "Score": "1", "body": "I upvoted and flagged your question shortly after you posted it. I upvoted because it does look like you have invested some time into it. Unfortunately, I had to flag it because it's off-topic for this site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T11:56:54.007", "Id": "436670", "Score": "0", "body": "Sorry, I didn't mean to sound cranky." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T11:58:04.463", "Id": "436671", "Score": "0", "body": "Don't worry about it. :)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T10:16:33.987", "Id": "225023", "Score": "1", "Tags": [ "javascript" ], "Title": "Simplifying this complex ternary operator in simple working code" }
225023
<p>I've implemented an updateable priority queue as a part of implementing some single-source-shortest-path algorithms (Dijkstra, BF). I'm relatively new to Python.</p> <pre><code>class UpdateableQueue: def __init__(self,iterable=None): self._heap = [] self._entry_finder = {} if iterable: for item in iterable: self._entry_finder[item[0]] = item[1] heapq.heappush(self._heap,(item[1],item[0])) def __getitem__(self, key): if key in self._entry_finder: return self._entry_finder[key] else: raise KeyError('Item not found in the priority queue') def __len__(self): return len(self._entry_finder) def __contains__(self, key): return key in self._entry_finder def push(self, key,priority): self._entry_finder[key] = priority heapq.heappush(self._heap, (priority, key)) def pop(self): if not self._heap: raise IndexError("The heap is empty") value,key = self._heap[0] while key not in self or self._entry_finder[key] != value: heapq.heappop(self._heap) if not self._heap: raise IndexError("The heap is empty") value,key = self._heap[0] value, key = heapq.heappop(self._heap) del self._entry_finder[key] return key,value </code></pre> <p>Edit: a simple test case example of the <code>UpdateableQueue</code></p> <pre><code>from UpdateableQueue.UpdateableQueue import UpdateableQueue if __name__ == "__main__": # Initalizing empty queue queue = UpdateableQueue() # Inserting key=1,priority=4 element to the queue the heap is now of size 1, and the dict size 1 queue.push(1,4) # editing key=1,priority=1 element to the queue the heap is now of size 2, and the dict size 1 queue.push(1,1) # editing key=1,priority=2 element to the queue the heap is now of size 3, and the dict size 1 queue.push(1,2) assert len(queue) == 1 # True assert 1 in queue # True # on pop we remove (key=1,value=1) from the heap and then pop out that value of (1,2), followed by # removing that key from the dict key, value = queue.pop() assert 1 not in queue #True assert key == 1 # True assert value == 2 # True # Inserting key=2,priority=5 element to the queue the heap is now of size 2, and the dict size 1 queue.push(2,5) assert len(queue) == 1 # We "clean" the remaining (1,4) element from the heap and return pop (2,5) as expected. key, value = queue.pop() assert key == 2 # True assert value == 5 # True </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T13:36:40.280", "Id": "436691", "Score": "2", "body": "Could you also show this priority queue in action?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T14:17:36.360", "Id": "436692", "Score": "3", "body": "@dfhwze Ive added a simple code example to it, let me know if there's anything else I can do." } ]
[ { "body": "<p>Your code looks good, there's not much for me to review, but here are a couple improvements/changes I would make.</p>\n\n<p><strong>Improvements</strong></p>\n\n<ul>\n<li><strong>Docstrings</strong>: You should include a <code>docstring</code> at the beginning of every method/class/module you write. This will help any documentation catch what your code is supposed to accomplish.</li>\n<li><strong>If/Else</strong>: If you return a value in the <code>if</code>, then you don't need an <code>else</code>. You should just put the <code>else</code> code after the <code>if</code>, instead of inside an <code>else</code>, like so:</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>if key in self._entry_finder:\n return self._entry_finder[key]\nelse:\n raise KeyError('Item not found in the priority queue')\n</code></pre>\n\n<p>to</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if key in self._entry_finder:\n return self._entry_finder[key]\nraise KeyError('Item not found in the priority queue')\n</code></pre>\n\n<p><strong>Updated Code</strong></p>\n\n<pre><code>class UpdateableQueue:\n \"\"\" An updateable priority queue class \"\"\"\n def __init__(self, iterable=None):\n self._heap = []\n self._entry_finder = {}\n if iterable:\n for item in iterable:\n self._entry_finder[item[0]] = item[1]\n heapq.heappush(self._heap, (item[1], item[0]))\n\n def __getitem__(self, key):\n \"\"\"\n Returns the item with the specified key, if exists. Else,\n it raises a `KeyError` exception\n \"\"\"\n if key in self._entry_finder:\n return self._entry_finder[key]\n raise KeyError('Item not found in the priority queue')\n\n def __len__(self):\n \"\"\" Returns the length of the queue \"\"\"\n return len(self._entry_finder)\n\n def __contains__(self, key):\n \"\"\" Returns a boolean based on if the key is in the queue \"\"\"\n return key in self._entry_finder\n\n def push(self, key, priority):\n \"\"\" Pushses a priority into the queue \"\"\"\n self._entry_finder[key] = priority\n heapq.heappush(self._heap, (priority, key))\n\n def pop(self):\n \"\"\" Removes a priority from the queue \"\"\"\n if not self._heap:\n raise IndexError(\"The heap is empty\")\n\n value, key = self._heap[0]\n while key not in self or self._entry_finder[key] != value:\n heapq.heappop(self._heap)\n if not self._heap:\n raise IndexError(\"The heap is empty\")\n value, key = self._heap[0]\n\n value, key = heapq.heappop(self._heap)\n del self._entry_finder[key]\n return key, value\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T00:33:27.440", "Id": "225387", "ParentId": "225030", "Score": "2" } } ]
{ "AcceptedAnswerId": "225387", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T12:45:54.473", "Id": "225030", "Score": "2", "Tags": [ "python", "beginner", "python-3.x", "priority-queue" ], "Title": "Updateable Priority Queue" }
225030
<p>Inspired by the a <a href="https://codereview.stackexchange.com/questions/224989/bulk-file-rename">recent question</a> to rename files by editing the list of names in an editor, I put together a similar <a href="https://github.com/janosgyerik/shellscripts/blob/aef88c7ef6c778e67ec1c885691ad8174dcc796f/bash/mv-many.sh" rel="nofollow noreferrer">script</a>.</p> <p>Why: if you need to perform some complex renames that are not easy to formulate with patterns (as with the <code>rename.pl</code> utility), it might be handy to be able to edit the list of names in a text editor, where you will see the exact names you will get.</p> <p>Features:</p> <ul> <li>Edit names in a text editor</li> <li>Use the names specified as command line arguments, or else the files and directories in the current directory (resolve <code>*</code>)</li> <li>Use a sensible default text editor <ul> <li>According to <code>man bash</code>, <em>READLINE</em> commands try <code>$VISUAL</code> or else <code>$EDITOR</code> -> looks like a good example to follow.</li> <li>Abort if cannot determine a suitable editor.</li> </ul></li> <li>Abort (do not rename anything) if the editor exits with error</li> <li>Paths containing newlines are explicitly unsupported</li> <li>Perform basic sanity checks: the edited text should have the same number of lines as the paths to rename</li> </ul> <p>Here's the script:</p> <pre><code>#!/usr/bin/env bash # # SCRIPT: mv-many.sh # AUTHOR: Janos Gyerik &lt;info@janosgyerik.com&gt; # DATE: 2019-07-27 # # PLATFORM: Not platform dependent # # PURPOSE: Rename files and directories by editing their names in $VISUAL or $EDITOR # set -euo pipefail usage() { local exitcode=0 if [[ $# != 0 ]]; then echo "$*" &gt;&amp;2 exitcode=1 fi cat &lt;&lt; EOF Usage: $0 [OPTION]... [FILES] Rename files and directories by editing their names in $editor Specify the paths to rename, or else * will be used by default. Limitations: the paths must not contain newline characters. EOF if [[ $editor == *vim ]]; then echo "Tip: to abort editing in $editor, exit with :cq command." fi cat &lt;&lt; "EOF" Options: -h, --help Print this help EOF exit "$exitcode" } fatal() { echo "Error: $*" &gt;&amp;2 exit 1 } find_editor() { # Following READLINE conventions, try VISUAL first and then EDITOR if [[ ${VISUAL+x} ]]; then echo "$VISUAL" return fi # shellcheck disable=SC2153 if [[ ${EDITOR+x} ]]; then echo "$EDITOR" return fi fatal 'could not determine editor to use, please set VISUAL or EDITOR; aborting.' } editor=$(find_editor) oldnames=() while [[ $# != 0 ]]; do case $1 in -h|--help) usage ;; -|-?*) usage "Unknown option: $1" ;; *) oldnames+=("$1") ;; esac shift done work=$(mktemp) trap 'rm -f "$work"' EXIT if [[ ${#oldnames[@]} == 0 ]]; then oldnames=(*) fi printf '%s\n' "${oldnames[@]}" &gt; "$work" "$editor" "$work" || fatal "vim exited with error; aborting without renaming." mapfile -t newnames &lt; "$work" [[ "${#oldnames[@]}" == "${#newnames[@]}" ]] || fatal "expected ${#oldnames[@]} lines in the file, got ${#newnames[@]}; aborting without renaming." for ((i = 0; i &lt; ${#oldnames[@]}; i++)); do old=${oldnames[i]} new=${newnames[i]} if [[ "$old" != "$new" ]]; then mv -vi "$old" "$new" fi done </code></pre> <p>What do you think? I'm looking for any and all kinds of comments, suggestions, critique.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T14:12:44.133", "Id": "225032", "Score": "4", "Tags": [ "bash", "shell", "rags-to-riches" ], "Title": "Rename files by editing their names in an editor" }
225032
<p>Is there a more natural way to do this in rust? I'm having a lot of difficulty trying to make this look clean. Type mismatches and borrowing have me stumped. What are some refactors that I could make?</p> <p><strong>Input</strong> </p> <ul> <li>Take in list of space-separated, command-line arguments</li> </ul> <p><strong>Output</strong> </p> <ul> <li>Book (join all arguments except the last)</li> <li>Reference (the last argument)</li> <li>File (looked up via the book)</li> </ul> <p>I abbreviated the <code>books_to_files</code> mapping to only include a couple examples of books with different word lengths.</p> <p><strong>Examples</strong></p> <pre><code>In: Out: Genesis 1:1 Genesis, 1:1, mhc1.txt Song of Solomon 2:2-4 Song of Solomon, 2:2-4, mhc3.txt Acts of the Apostles 3:3-9 Acts of the Apostles, 3:3-9, mhc6.txt </code></pre> <p><strong>Source Code</strong></p> <pre class="lang-rust prettyprint-override"><code>use std::env; use std::collections::HashMap; fn main() { let args: Vec&lt;String&gt; = env::args().collect(); let book: String; if args.len() == 3 { book = args[1].clone(); } else if args.len() == 4 { book = args[1].clone() + " " + &amp;args[2].clone(); } else if args.len() == 5 { book = args[1].clone() + " " + &amp;args[2].clone() + " " + &amp;args[3].clone(); } else if args.len() == 6 { book = args[1].clone() + " " + &amp;args[2].clone() + " " + &amp;args[3].clone() + " " + &amp;args[4].clone(); } else { panic!("Wrong number of arguments"); } let reference: String = args[args.len()-1].clone(); let file: String = get_file(&amp;book); println!("{}, {}, {}", book, reference, file); } fn get_file(book: &amp;String) -&gt; String { let books_to_files: HashMap&lt;&amp;str, &amp;str&gt; = [ ("Genesis", "mhc1.txt"), ("First Samuel", "mhc2.txt"), ("Song of Solmon", "mhc3.txt"), ("Acts of the Apostles", "mhc6.txt"), ("First Corinthians", "mhc6.txt"), ("Galatians", "mhc6.txt"), ].iter().cloned().collect(); books_to_files.get::&lt;str&gt;(&amp;book.to_string()).unwrap().to_string() } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T01:23:18.860", "Id": "436767", "Score": "0", "body": "Is there a reason to not require the book to be in one argument? The user can just surround the book title in quotes when calling the program from the shell." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T01:04:16.927", "Id": "436876", "Score": "0", "body": "@JayDepp That is a clever idea, I hadn't thought of that" } ]
[ { "body": "<p>I've collected a few thoughts about possible refactors you could consider below.</p>\n\n<h3>Your <code>if</code> chain isn't the most efficient way</h3>\n\n<p>As you've written it, your code will only work for titles between one and four words long. This isn't a disaster, and it will probably work for most titles, but we can rewrite your code to be shorter <em>and</em> handle any length of title. A win-win!</p>\n\n<ul>\n<li><p>We can use Iterator::skip() to throw away the executable name, as we don't care about it anyway. See <a href=\"https://doc.rust-lang.org/core/iter/trait.Iterator.html#method.skip\" rel=\"nofollow noreferrer\"><code>skip()</code></a> in the documentation.</p>\n\n<pre><code>let args: Vec&lt;String&gt; = env::args().skip(1).collect();\n</code></pre></li>\n<li><p>It'd be a good idea to check that we've been given enough arguments before continuing.</p>\n\n<pre><code>let arg_len: usize = args.len();\nif arg_len &lt; 2 {\n panic!(\"At least two arguments must be supplied!\");\n}\n</code></pre></li>\n<li><p>Now, we can be a bit clever and avoid your <code>if</code> chain all together. Using a <a href=\"https://doc.rust-lang.org/std/ops/struct.Range.html\" rel=\"nofollow noreferrer\">range</a> we can get a <a href=\"https://doc.rust-lang.org/std/primitive.slice.html\" rel=\"nofollow noreferrer\">slice</a> of our <code>args</code> vector corresponding to all but the last element. We can then use <a href=\"https://doc.rust-lang.org/std/slice/trait.SliceConcatExt.html#tymethod.join\" rel=\"nofollow noreferrer\"><code>join()</code></a> to turn that slice back into a <code>String</code>. For example, if we started with <code>vec![\"Song\", \"of\", \"Solomon\", \"2:2-4\"]</code> in <code>args</code>, we would take a slice to get <code>[\"Song\", \"of\", \"Solomon\"]</code> and rejoin them with <code>\" \"</code> in the middle to get <code>\"Song of Solomon\"</code>.</p>\n\n<pre><code>let book = args[0..(arg_len - 1)].join(\" \");\n</code></pre></li>\n</ul>\n\n<h3>Try to avoid <code>clone()</code> unless necessary</h3>\n\n<p>The first thing I noticed when I took a look at your code was that you've used <code>clone()</code> in quite a few places. We've already got rid of a lot of them with the tweak above, and you should try to avoid them all together as allocating when you don't need to is a waste of time and memory. If you <em>can</em> use an <code>&amp;str</code>, do that instead of insisting on all strings being <code>String</code>. As an aside, there is rarely any point bothering with <code>&amp;String</code> — just use <code>&amp;str</code> there.</p>\n\n<ul>\n<li><p>Putting the above into action, we can let <code>reference</code> be an <code>&amp;str</code> and avoid a clone.</p>\n\n<pre><code>let reference: &amp;str = &amp;args[args.len() - 1];\n</code></pre></li>\n<li><p>Let's also change <code>get_book</code>'s method signature as suggested above.</p>\n\n<pre><code>fn get_file(book: &amp;str) -&gt; &amp;str {\n</code></pre></li>\n<li><p>Now we can get rid of the unnecessary <code>to_string()</code> below.</p>\n\n<pre><code>books_to_files.get::&lt;str&gt;(&amp;book.to_string()).unwrap()\n</code></pre></li>\n<li><p>And tweak this line in <code>main()</code> to accept an <code>&amp;str</code>.</p>\n\n<pre><code>let file: &amp;str = get_file(&amp;book);\n</code></pre></li>\n</ul>\n\n<h3>Avoiding unwrap</h3>\n\n<p>Ideally, <code>get_book</code> ought to return an <code>Option</code> instead, so the caller can choose how they want to handle the error. As it is fatal anyway, unwrapping makes little difference, but it's worth bearing in mind as a future improvement.</p>\n\n<h3><a href=\"https://play.integer32.com/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=6465127c91bfaca0daf0bfbaf322336c\" rel=\"nofollow noreferrer\">Try it Online</a></h3>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T16:19:12.033", "Id": "225145", "ParentId": "225035", "Score": "3" } }, { "body": "<p>Rather than using a hashmap to lookup the books, we can use a match block. (This is assuming that your books are known at compile time.) Also, we can return an <code>Option&lt;&amp;'static str&gt;</code>. The option lets the caller of the function decide what to do on failure, and a <code>&amp;'static str</code> is the type of a string literal.</p>\n\n<pre><code>fn get_file(book: &amp;str) -&gt; Option&lt;&amp;'static str&gt; {\n match book {\n \"Genesis\" =&gt; Some(\"mhc1.txt\"),\n \"First Samuel\" =&gt; Some(\"mhc2.txt\"),\n \"Song of Solmon\" =&gt; Some(\"mhc3.txt\"),\n \"Acts of the Apostles\" =&gt; Some(\"mhc6.txt\"),\n \"First Corinthians\" =&gt; Some(\"mhc6.txt\"),\n \"Galatians\" =&gt; Some(\"mhc6.txt\"),\n _ =&gt; None,\n }\n}\n</code></pre>\n\n<p>Based on your response, I'll suggest having the first command line argument be the entire book name. I'd write <code>main</code> something like this. We can use slice patterns to check for the right number of arguments and bind them to variables at the same time. Then, we can try to find the file or print an error message otherwise. If the number of arguments was wrong, we also print an error showing the correct usage of the program.</p>\n\n<pre><code>fn main() {\n let args: Vec&lt;String&gt; = std::env::args().collect();\n\n if let [_, book, reference] = args.as_slice() {\n if let Some(file) = get_file(book) {\n println!(\"{}, {}, {}\", book, reference, file);\n } else {\n eprintln!(\"Could not find book!\");\n }\n } else {\n eprintln!(\"Usage: {} &lt;BOOK&gt; &lt;REFERENCE&gt;\", args[0]);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T01:07:41.307", "Id": "225170", "ParentId": "225035", "Score": "2" } }, { "body": "<p>Here are some improvements:</p>\n\n<ul>\n<li>If you don't want the first arg, <code>skip</code> it\n\n<ul>\n<li><code>env::args().skip(1).collect()</code></li>\n</ul></li>\n<li>Get the reference (last arg) with <code>pop</code></li>\n<li>Get the book (remaining args) with <code>join</code>\n\n<ul>\n<li><code>args.join(\" \")</code></li>\n</ul></li>\n<li>Use <code>&amp;str</code> when possible\n\n<ul>\n<li><code>get_file(book: &amp;str)</code></li>\n</ul></li>\n<li>Match the book to the file, with <code>match</code>\n\n<ul>\n<li><code>match book {...}</code></li>\n</ul></li>\n<li>Use an <code>Option/Some/None</code> so that <code>main</code> can handle the error\n\n<ul>\n<li><code>get_file(...) -&gt; Option&lt;&amp;str&gt;</code></li>\n</ul></li>\n</ul>\n\n<pre><code>use std::env;\n\nfn main() {\n let mut args: Vec&lt;String&gt; = env::args().skip(1).collect();\n let reference = args.pop()\n .expect(\"Expected 2+ parameters: &lt;book of the Bible&gt; &lt;reference&gt;\");\n let book = args.join(\" \");\n let file = get_file(&amp;book)\n .expect(\"Not a valid book\");\n println!(\"{}, {}, {}\", book, reference, file);\n}\n\nfn get_file(book: &amp;str) -&gt; Option&lt;&amp;str&gt; {\n match book {\n \"Genesis\" =&gt; Some(\"mhc1.txt\"),\n \"First Samuel\" =&gt; Some(\"mhc2.txt\"),\n \"Song of Solmon\" =&gt; Some(\"mhc3.txt\"),\n \"Acts of the Apostles\" =&gt; Some(\"mhc6.txt\"),\n \"First Corinthians\" =&gt; Some(\"mhc6.txt\"),\n \"Galatians\" =&gt; Some(\"mhc6.txt\"),\n _ =&gt; None\n }\n}\n</code></pre>\n\n<p>Thanks to <a href=\"https://codereview.stackexchange.com/a/225145/95032\">Aurora0001</a> and <a href=\"https://codereview.stackexchange.com/a/225170/95032\">JayDepp</a> for the helpful feedback (that make up 90% of the advice above). This code is a lot more natural now.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-12T13:42:53.367", "Id": "225976", "ParentId": "225035", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T14:55:35.623", "Id": "225035", "Score": "3", "Tags": [ "beginner", "console", "rust" ], "Title": "Join and map command line arguments in Rust" }
225035
<p>I created a test-server for RESTful integration-tests that I call <code>TeapotServer</code> because I like the status-code <code>418</code> that the server returns when the client makes a mistake and sends it an invalid request.</p> <h3>Example</h3> <p>Its API is similar to <code>JustMock</code>. I first tell it to what API I want to test, how the request should look like, how many of them I expect and what response(s) it should return.</p> <p>There are two types of assertions: - as requests arrive to validate them as soon as possible - after the request to validate whether they have been even called</p> <pre><code>public class HttpProviderExtensionsTest : IDisposable, IClassFixture&lt;TeapotServerFixture&gt; { private readonly ITeapotServerContext _serverContext; private readonly IResourceProvider _http; public HttpProviderExtensionsTest(TeapotServerFixture teapotServerFixture) { _serverContext = teapotServerFixture.GetServer("http://localhost:30002").BeginScope(); _http = HttpProvider.FromBaseUri("http://localhost:30002/api"); } [Fact] public async Task Can_send_email_and_receive_html() { _serverContext .MockPost("/api/mailr/messages/test", request =&gt; { request .AcceptsHtml() .AsUserAgent("xunit", "1.0") .WithContentTypeJson(content =&gt; { content .HasProperty("$.To") .HasProperty("$.Subject") //.HasProperty("$.From") // Boom! This property does not exist. .HasProperty("$.Body.Greeting"); }) .Occurs(1); // &lt;-- short-circuit on 2nd request }) .ArrangeResponse(builder =&gt; { builder .Once(200, "OK!"); }); var email = new Email.Html(new[] { "myemail@mail.com" }, "Test-mail") { Body = new { Greeting = "Hallo Mailr!" } }; var response = await _http.SendEmailAsync("mailr/messages/test", new UserAgent("xunit", "1.0"), email); _serverContext.Assert(); Assert.Equal("OK!", response); } public void Dispose() { _serverContext.Dispose(); _http.Dispose(); } } </code></pre> <h3>Server + Middleware</h3> <p>The <code>TeapotServer</code> is based on <code>Kestrel</code> and uses a single <code>TeapotMiddleware</code>. I use it to forward requests to assertions that can short-circuit the pipeline (unlike <a href="https://flurl.dev" rel="nofollow noreferrer"><code>Flurl</code></a> that I don't like because of its assertions that take place too late - they cannot protect you from infinite request loops).</p> <pre><code>[PublicAPI] public class TeapotServer : IDisposable { private readonly IWebHost _host; private readonly ConcurrentDictionary&lt;Guid, ITeapotServerContext&gt; _serverContexts = new ConcurrentDictionary&lt;Guid, ITeapotServerContext&gt;(); public TeapotServer(string url) { var configuration = new ConfigurationBuilder() // Tests can use their own urls so let's not use hosting.json but in-memory-collection .AddInMemoryCollection(new Dictionary&lt;string, string&gt; { ["urls"] = url // &lt;-- this is the only way that works with Kestrel }) .Build(); _host = new WebHostBuilder() .UseKestrel() .UseConfiguration(configuration) .ConfigureServices(services =&gt; { // Allows to validate requests as they arrive. services.AddSingleton((RequestAssertDelegate)Assert); // Allows to provide custom responses for each request. services.AddSingleton((ResponseMockDelegate)GetResponseFactory); }) .Configure(app =&gt; { app.UseMiddleware&lt;TeapotMiddleware&gt;(); }) .Build(); _host.StartAsync().GetAwaiter().GetResult(); // &lt;-- asp.net-core TestServer is doing this too. } //public Task Task { get; set; } // &lt;-- I think I don't need this anymore... // Creates a new server-context that separates api-mocks. public ITeapotServerContext BeginScope() { return _serverContexts.GetOrAdd(Guid.NewGuid(), id =&gt; new TeapotServerContext(Disposable.Create(() =&gt; _serverContexts.TryRemove(id, out _)))); } private void Assert(RequestCopy requestCopy) { FindApiMock(requestCopy.Method, requestCopy.Uri)?.Assert(requestCopy); } private Func&lt;HttpRequest, ResponseMock&gt; GetResponseFactory(HttpMethod method, UriString uri) { return FindApiMock(method, uri)?.GetResponseFactory(); } // Finds an api-mock that should handle the current request. [CanBeNull] private ApiMock FindApiMock(HttpMethod method, UriString uri) { if (_serverContexts.IsEmpty) throw new InvalidOperationException($"Cannot get response without a server-context. Call '{nameof(BeginScope)}' first."); var mocks = from tc in _serverContexts.Values from rm in tc where rm.Method == method &amp;&amp; rm.Uri == uri select rm; return mocks.FirstOrDefault(); } public void Dispose() { _host.StopAsync().GetAwaiter().GetResult(); _host.Dispose(); } } public delegate void RequestAssertDelegate(RequestCopy requestCopy); [CanBeNull] public delegate Func&lt;HttpRequest, ResponseMock&gt; ResponseMockDelegate(HttpMethod method, UriString path); [UsedImplicitly] internal class TeapotMiddleware { private readonly RequestDelegate _next; private readonly RequestAssertDelegate _requestAssert; private readonly ResponseMockDelegate _nextResponseMock; public TeapotMiddleware ( RequestDelegate next, RequestAssertDelegate requestAssert, ResponseMockDelegate nextResponseMock ) { _next = next; _requestAssert = requestAssert; _nextResponseMock = nextResponseMock; } public async Task Invoke(HttpContext context) { try { var uri = context.Request.Path + context.Request.QueryString; // You need this later to restore the body so don't dispose it. var bodyBackup = new MemoryStream(); // You copy it because the original stream does not support seeking. await context.Request.Body.CopyToAsync(bodyBackup); // You copy the request because otherwise it won't pass the "barrier" between the middleware and the assert. using (var bodyCopy = new MemoryStream()) { await bodyBackup.Rewind().CopyToAsync(bodyCopy); var request = new RequestCopy { Uri = uri, Method = new HttpMethod(context.Request.Method), // There is no copy-constructor. Headers = new HeaderDictionary(context.Request.Headers.ToDictionary(x =&gt; x.Key, x =&gt; x.Value)), ContentLength = context.Request.ContentLength, Content = bodyCopy }; _requestAssert(request); } // Restore body. context.Request.Body = bodyBackup; await _next(context); var responseMock = _nextResponseMock(new HttpMethod(context.Request.Method), uri); if (responseMock is null) { context.Response.StatusCode = StatusCodes.Status404NotFound; } else { using (var response = responseMock(context.Request)) { context.Response.StatusCode = response.StatusCode; context.Response.ContentType = response.ContentType; // Let's see what kind of content we got and handle it appropriately... if (response.ContentType == MimeType.Plain) { await context.Response.WriteAsync((string)response.Content); } if (response.ContentType == MimeType.Binary) { await ((Stream)response.Content).Rewind().CopyToAsync(context.Response.Body); } if (response.ContentType == MimeType.Json) { await context.Response.WriteAsync(JsonConvert.SerializeObject(response.Content)); } } } } catch (Exception ex) { // It looks like the client sent an invalid request. if (ex is DynamicException dex &amp;&amp; dex.NameMatches("AssertException")) { // "Response status code does not indicate success: 418 (I'm a teapot)." context.Response.StatusCode = StatusCodes.Status418ImATeapot; // &lt;-- I find this one funny. } // Nope, there is a problem with the server. else { context.Response.StatusCode = StatusCodes.Status500InternalServerError; } context.Response.ContentType = MimeType.Plain; await context.Response.WriteAsync(ex.ToString()); // &lt;-- dump the exception to the response stream. } } } </code></pre> <h3>Helpers</h3> <p>There is a hole bunch of helpers that provide (hopefully) a user-friendly API.</p> <hr> <p>They start with the <code>TeapotServerContext</code> that separates api-mocks between test methods. I created a couple of convenience shortcut extensions like <code>MockGet</code> to save typing. Each of those returns an <code>ApiMock</code> that stores a pair of request and response builders for a single <code>API</code>. They are used to configure request asserts and responses.</p> <pre><code>public interface ITeapotServerContext : IEnumerable&lt;ApiMock&gt;, IDisposable { ApiMock MockApi(HttpMethod method, UriString uri); void Assert(); } internal class TeapotServerContext : List&lt;ApiMock&gt;, ITeapotServerContext { private readonly IDisposable _disposer; public TeapotServerContext(IDisposable disposer) { _disposer = disposer; } public ApiMock MockApi(HttpMethod method, UriString uri) { var mock = new ApiMock(method, uri); Add(mock); return mock; } public void Assert() { foreach (var apiMock in this) { apiMock.Assert(); } } public Func&lt;HttpRequest, ResponseMock&gt; GetResponseFactory(HttpMethod method, UriString uri) { return this.FirstOrDefault(m =&gt; m.Method == method &amp;&amp; m.Uri == uri)?.GetResponseFactory(); } public void Dispose() { _disposer.Dispose(); } } public static class TeapotServerContextExtensions { public static ApiMock MockGet(this ITeapotServerContext context, string uri, Action&lt;IRequestBuilder&gt; configureRequest) { return context .MockApi(HttpMethod.Get, uri) .ArrangeRequest(configureRequest); } public static ApiMock MockPost(this ITeapotServerContext context, string uri, Action&lt;IRequestBuilder&gt; configureRequest) { return context .MockApi(HttpMethod.Post, uri) .ArrangeRequest(configureRequest); } public static ApiMock MockPut(this ITeapotServerContext context, string uri, Action&lt;IRequestBuilder&gt; configureRequest) { return context .MockApi(HttpMethod.Put, uri) .ArrangeRequest(configureRequest); } public static ApiMock MockDelete(this ITeapotServerContext context, string uri, Action&lt;IRequestBuilder&gt; configureRequest) { return context .MockApi(HttpMethod.Delete, uri) .ArrangeRequest(configureRequest); } } // Represents a single api-mock. public class ApiMock { private readonly IRequestBuilder _request; private readonly IResponseBuilder _response; public ApiMock(HttpMethod method, UriString uri) { Method = method; Uri = uri; _request = new RequestBuilder(); _response = new ResponseBuilder().Always(200, new { Message = "OK" }, MimeType.Json); } public HttpMethod Method { get; } public UriString Uri { get; } // Allows to configure request asserts. public ApiMock ArrangeRequest(Action&lt;IRequestBuilder&gt; configure) { configure(_request); return this; } // Allows to configure responses. public ApiMock ArrangeResponse(Action&lt;IResponseBuilder&gt; configure) { configure(_response.Clear()); return this; } // Validates the request either as it arrives (not-null) or afterwards (null). public void Assert(RequestCopy requestCopy = default) { try { _request.Assert(requestCopy); } catch (Exception inner) { throw DynamicException.Create("Assert", $"{Method} {Uri}", inner); } } // Tries to get the nest response. public Func&lt;HttpRequest, ResponseMock&gt; GetResponseFactory() { return request =&gt; _response?.Next(request); } } </code></pre> <h3>Request and response builders</h3> <ul> <li>The <code>RequestBuilder</code> keeps a collection of assert <code>Action</code>s and calls each of them when a request arrives. Assertions are created with convenience extensions that can validate headers, content etc.</li> <li>The <code>ResponseBuilder</code> keeps a collection of response factories. It's a queue where each item can produce either a response or <code>null</code> in which case it's removed from the queue an the next factory is used. When there are no more response factories an exception is thrown.</li> </ul> <pre><code>public interface IRequestBuilder { [NotNull] IRequestBuilder Add(Action&lt;RequestCopy&gt; assert, bool canShortCircuit); void Assert(RequestCopy requestCopy); } // Maintains a collection of request-asserts. internal class RequestBuilder : IRequestBuilder { private readonly IList&lt;(Action&lt;RequestCopy&gt; Assert, bool CanShortCircuit)&gt; _asserts = new List&lt;(Action&lt;RequestCopy&gt;, bool CanShortCircuit)&gt;(); // Adds a request assert. If it can-short-circuit then it can validate requests as they arrive. public IRequestBuilder Add(Action&lt;RequestCopy&gt; assert, bool canShortCircuit) { _asserts.Add((assert, canShortCircuit)); return this; } // Fires all asserts. public void Assert(RequestCopy requestCopy) { foreach (var (assert, canShortCircuit) in _asserts) { if (requestCopy is null &amp;&amp; !canShortCircuit) { continue; } assert(requestCopy); } } } [PublicAPI] public static class RequestBuilderExtensions { public static IRequestBuilder Occurs(this IRequestBuilder builder, int exactly) { var counter = 0; return builder.Add(request =&gt; { if (request.CanShortCircuit()) { if (++counter &gt; exactly) { throw DynamicException.Create(nameof(Occurs), $"Api was called {counter} time(s) but expected {exactly}."); } } else { if (counter != exactly) { throw DynamicException.Create(nameof(Occurs), $"Api was called {counter} time(s) but expected {exactly}."); } } }, true); } public static IRequestBuilder WithHeader(this IRequestBuilder builder, string header, params string[] expectedValues) { return builder.Add(request =&gt; { if (request.CanShortCircuit()) { if (request.Headers.TryGetValue(header, out var actualValues)) { if (actualValues.Intersect(expectedValues).Count() != expectedValues.Count()) { throw DynamicException.Create ( "DifferentHeader", $"Expected: [{expectedValues.Join(", ")}]{Environment.NewLine}" + $"Actual: [{actualValues.Join(", ")}]" ); } } else { throw DynamicException.Create ( "HeaderNotFound", $"Header '{header}' is missing." ); } } }, false); } public static IRequestBuilder WithApiVersion(this IRequestBuilder builder, string version) =&gt; builder.WithHeader("Api-Version", version); public static IRequestBuilder WithContentType(this IRequestBuilder builder, string mediaType) =&gt; builder.WithHeader("Content-Type", mediaType); public static IRequestBuilder WithContentTypeJson(this IRequestBuilder builder, Action&lt;ContentSection&lt;JToken&gt;&gt; contentAssert) { return builder.Add(request =&gt; { var content = request.DeserializeAsJToken(); contentAssert(ContentSection.FromJToken(content)); }, false); } public static IRequestBuilder AsUserAgent(this IRequestBuilder builder, string product, string version) =&gt; builder.WithHeader("User-Agent", $"{product}/{version}"); public static IRequestBuilder Accepts(this IRequestBuilder builder, string mediaType) =&gt; builder.WithHeader("Accept", mediaType); public static IRequestBuilder AcceptsJson(this IRequestBuilder builder) =&gt; builder.Accepts("application/json"); public static IRequestBuilder AcceptsHtml(this IRequestBuilder builder) =&gt; builder.Accepts("text/html"); } public interface IResponseBuilder { [NotNull] ResponseBuilder Enqueue(Func&lt;HttpRequest, ResponseMock&gt; next); ResponseBuilder Clear(); [NotNull] ResponseMock Next(HttpRequest request); } public class ResponseBuilder : IResponseBuilder { private readonly Queue&lt;Func&lt;HttpRequest, ResponseMock&gt;&gt; _responses = new Queue&lt;Func&lt;HttpRequest, ResponseMock&gt;&gt;(); public ResponseBuilder Enqueue(Func&lt;HttpRequest, ResponseMock&gt; next) { _responses.Enqueue(next); return this; } public ResponseBuilder Clear() { _responses.Clear(); return this; } // Gets the next response or throws when there are none. public ResponseMock Next(HttpRequest request) { while (_responses.Any()) { var createResponse = _responses.Peek(); var response = createResponse(request); // This response factory is empty. if (response is null) { // Remove it from the queue an try again. _responses.Dequeue(); continue; } return response; } throw DynamicException.Create("OutOfResponses", "There are no more responses"); } } [PublicAPI] public static class ResponseBuilderExtensions { public static IResponseBuilder Once(this IResponseBuilder response, int statusCode, object content, string contentType = default) { return response.Exactly(statusCode, content, content.DetermineContentType(contentType), 1); } public static IResponseBuilder Always(this IResponseBuilder response, int statusCode, object content, string contentType = default) { return response.Enqueue(request =&gt; new ResponseMock(statusCode, content, content.DetermineContentType(contentType))); } public static IResponseBuilder Exactly(this IResponseBuilder response, int statusCode, object content, string contentType, int count) { var counter = 0; return response.Enqueue(request =&gt; counter++ &lt; count ? new ResponseMock(statusCode, content, contentType) : default); } // Forwards request to response. public static IResponseBuilder Echo(this IResponseBuilder response) { return response.Enqueue(request =&gt; { var requestCopy = new MemoryStream(); request.Body.Rewind().CopyTo(requestCopy); return new ResponseMock(200, requestCopy, MimeType.Binary); }); } private static string DetermineContentType(this object content, string contentType) { return contentType ?? (content is string ? MimeType.Plain : MimeType.Json); } } </code></pre> <h3>Data</h3> <p>Other classes used here are mainly of <code>DTO</code> nature that just pass data from one place to the other.</p> <pre><code>public class ContentSection&lt;TContent&gt; where TContent : class { public ContentSection([NotNull] TContent value, string path = ".") { Value = value ?? throw new ArgumentNullException(nameof(value)); Path = path; } public TContent Value { get; } public string Path { get; } } public static class ContentSection { // You use ?? to support the null-pattern in case there is no response. public static ContentSection&lt;JToken&gt; FromJToken(JToken content, string path = ".") { return new ContentSection&lt;JToken&gt;(content ?? JToken.Parse("{}"), path); } public static ContentSection&lt;JValue&gt; FromJValue(JValue content, string path = ".") { return new ContentSection&lt;JValue&gt;(content ?? JValue.CreateNull(), path); } } // This needs to be copy because it otherwise won't pass the middleware/assert "barrier" // between the server and the "client". public class RequestCopy { public UriString Uri { get; set; } public HttpMethod Method { get; set; } public IHeaderDictionary Headers { get; set; } public long? ContentLength { get; set; } public Stream Content { get; set; } } public static class RequestCopyExtensions { public static bool CanShortCircuit(this RequestCopy request) =&gt; !(request is null); // Deserializes the content of request-copy for further analysis. public static JToken DeserializeAsJToken(this RequestCopy request) { if (request.Headers.TryGetValue("Content-Type", out var contentType) &amp;&amp; contentType != MimeType.Json) { throw new ArgumentOutOfRangeException($"This method can deserialize only {MimeType.Json} content."); } if (request.ContentLength == 0) { return default; } using (var memory = new MemoryStream()) { // You copy it because otherwise it'll get disposed when the request-copy vanishes. request.Content.Rewind().CopyTo(memory); using (var reader = new StreamReader(memory.Rewind())) { var body = reader.ReadToEnd(); return JToken.Parse(body); } } } } public class ResponseMock : IDisposable { public ResponseMock(int statusCode, object content, string contentType) { StatusCode = statusCode; Content = content; ContentType = contentType; } public int StatusCode { get; } [CanBeNull] public object Content { get; } public string ContentType { get; } public void Dispose() { (Content as IDisposable)?.Dispose(); } } </code></pre> <h3>Json assertions</h3> <p>There is also a set of extensions that simplify content validation. I currently work only with <code>JSON</code> so only this kind of extensions exist. However, the <code>ContentSection&lt;T&gt;</code> is built to support other content-types if necessary.</p> <pre><code>public static class ContentAssert { // Use this the same pattern for each assert: condition ? throw : content #region JToken helpers [NotNull] public static ContentSection&lt;JValue&gt; Value(this ContentSection&lt;JToken&gt; content, string jsonPath) { return !(content.Value.SelectToken(jsonPath) is JValue value) ? throw DynamicException.Create("ContentPropertyNotFound", $"There is no such property as '{jsonPath}'") : ContentSection.FromJValue(value, jsonPath); } [NotNull] public static ContentSection&lt;JToken&gt; HasProperty(this ContentSection&lt;JToken&gt; content, string jsonPath) { return content.Value.SelectToken(jsonPath) is null ? throw DynamicException.Create("ContentPropertyNotFound", $"There is no such property as '{jsonPath}'") : content; } #endregion #region JValue helpers [NotNull] public static ContentSection&lt;JValue&gt; IsNotNull(this ContentSection&lt;JValue&gt; content) { return content.Value.Equals(JValue.CreateNull()) ? throw DynamicException.Create("ValueNull", $"Value at '{content.Path}' is null.") : content; } [NotNull] public static ContentSection&lt;JValue&gt; IsEqual(this ContentSection&lt;JValue&gt; content, object expected) { return !content.Value.Equals(new JValue(expected)) ? throw DynamicException.Create("ValueNotEqual", $"Value at '{content.Path}' is '{content.Value}' but should be '{expected}'.") : content; } [NotNull] public static ContentSection&lt;JValue&gt; IsLike(this ContentSection&lt;JValue&gt; content, [RegexPattern] string pattern, RegexOptions options = RegexOptions.IgnoreCase) { return !Regex.IsMatch(content.Value.Value&lt;string&gt;() ?? string.Empty, pattern, options) ? throw DynamicException.Create("ValueNotLike", $"Value at '{content.Path}' is '{content.Value}' but should be like '{pattern}'.") : content; } #endregion } </code></pre> <hr> <h3>Extensibility</h3> <p>I build this framework as I use it and new assertion use-cases emerge with each project so I'd like it to be primarily extendible at this endpoint.</p> <p>I currently can do the following:</p> <ul> <li>use different <code>URL</code> for each server.</li> <li>add other content-types because <code>ContentSection&lt;T&gt;</code> is extensible via <code>T</code> and consequently I can chain specific extension to it</li> <li>add other extensions to the <code>RequestBuilder</code> supporting more request assertions</li> </ul> <h3>Questions</h3> <p>Besides extensibilty I'd like this framework to be easy to use and intuitive. It should also provide useful feedback about what went wrong and where.</p> <p>What is your rating?</p> <hr> <p><em>You can also take a look at it on <a href="https://github.com/he-dev/reusable/tree/dev/Reusable.Teapot/src" rel="nofollow noreferrer">github</a>.</em></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T15:26:57.000", "Id": "436694", "Score": "2", "body": "btw, I write _You_ in comments because I write to my future me ;-P" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T15:31:46.813", "Id": "436695", "Score": "0", "body": "Should I expand any section and add more details?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-23T21:00:07.953", "Id": "440811", "Score": "1", "body": "I thank thee for thy service" } ]
[ { "body": "<p>You allow a server to reuse an existing context when calling <code>BeginScope</code>. Does this mean multiple integration tests could reuse a context? If so, how do you handle disposal of the context? Your example shows one test that handles disposal of a possibly shared context.</p>\n\n<blockquote>\n<pre><code>public ITeapotServerContext BeginScope()\n{\n // CR: who should be allowed to handle the lifetime of a shared context?\n return _serverContexts.GetOrAdd(Guid.NewGuid(), \n id =&gt; new TeapotServerContext(Disposable.Create(\n () =&gt; _serverContexts.TryRemove(id, out _))));\n}\n</code></pre>\n</blockquote>\n\n<p>Maybe consumers of the API should not be able to dispose a context, but could register and unregister on a shared context. The server would then be responsible for lifetime management of each context. I would remove <code>IDisposable</code> from the interface definition of <code>ITeapotServerContext</code>.</p>\n\n<blockquote>\n<pre><code>public void Dispose()\n{\n // CR: what if context is shared?\n _serverContext.Dispose();\n _http.Dispose();\n}\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>The constructor of <code>TeapotServer</code> performs some configuration, followed by starting the host. I'm personally not a fan of doing anything more than storing state and configuring the instance in a constructor. Further initialisation - like IO operations - should be done in a method called <code>Initialise()</code>.</p>\n\n<blockquote>\n<pre><code>_host.StartAsync().GetAwaiter().GetResult();\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>Talking about extensibility, I'm not sure whether <code>ITeapotServerContext</code> should be an interface. I don't see any other possible implementation besides the one you provided. Its lifetime and dispose pattern is also an internal occasion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T16:56:44.123", "Id": "436709", "Score": "1", "body": "Contexts should be used on per-test basis. Since it is not possible to inject them via test-method parameters, there are only two possibilities, either create one in the constructor (it's called for each test) and dispose it after a test is run or with the `using` statement. I chose ctor as xunit handles this very nicely and reduces nesting. MSTest has the `TestInitialize` (=`.ctor`) and `TestCleanUp` (=`Dispose()`) attributes respectively. I also think I might have overused-interfaces here ;-]" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T16:22:28.290", "Id": "225042", "ParentId": "225038", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T15:21:39.663", "Id": "225038", "Score": "2", "Tags": [ "c#", "rest", "asp.net-web-api", "framework", "integration-testing" ], "Title": "418 I'm a TeapotServer for RESTful integration-tests" }
225038
<p>I have coded a <a href="https://en.wikipedia.org/wiki/Rock%E2%80%93paper%E2%80%93scissors" rel="nofollow noreferrer">rock–paper–scissors</a> game in C++, and it works exactly how I want it to. However, I was wondering if there is a way to simplify the code and clean it up. It is for a school project, so the <code>void</code> function has to be included in the code, but I feel like the <code>while</code> &amp; <code>if</code> functions could somehow be simplified.</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdlib&gt; #include &lt;string&gt; using namespace std; //defining my variables int getUserChoice, getComputerChoice; const int Rock = 1, Paper = 2, Scissors = 3, Exit = 4; char reply; void determineWinner() { //random computer choice getComputerChoice = rand() % 3; //displays the users input choice if (getUserChoice == 1) { cout &lt;&lt; "You chose Rock." &lt;&lt; endl; } else if (getUserChoice == 2) { cout &lt;&lt; "You chose Paper." &lt;&lt; endl; } else if (getUserChoice == 3) { cout &lt;&lt; "You chose Scissors." &lt;&lt; endl; } if (getUserChoice == 4) { cout &lt;&lt; "You have chosen to exit the game. The game will now end."; } //display the computers input choice if (getComputerChoice == 1) { cout &lt;&lt; "The computer chose Rock." &lt;&lt; endl; } else if (getComputerChoice == 2) { cout &lt;&lt; "The computer chose Paper." &lt;&lt; endl; } else if (getComputerChoice == 3) { cout &lt;&lt; "The computer chose Scissors." &lt;&lt; endl; } //determines winner while ( (getUserChoice == 2 &amp;&amp; getComputerChoice == 3)|| (getUserChoice == 3 &amp;&amp; getComputerChoice == 1)|| (getUserChoice == 1 &amp;&amp; getComputerChoice == 2) ) { cout &lt;&lt; "I'm sorry, the computer has beat you." &lt;&lt; endl &lt;&lt; endl; break; } while ( (getUserChoice == 1 &amp;&amp; getComputerChoice == 3)|| (getUserChoice == 2 &amp;&amp; getComputerChoice == 1)|| (getUserChoice == 3 &amp;&amp; getComputerChoice == 2) ) { cout &lt;&lt; "Congratulations, you win!" &lt;&lt; endl &lt;&lt; endl; break; } while ( (getUserChoice == getComputerChoice) ) { cout &lt;&lt; "This game is tied. " &lt;&lt; endl &lt;&lt; endl; break; } } int main() { //displays a description of the game cout &lt;&lt; "Rock, Paper, Scisscors Game!" &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; "You will be playing against the computer." &lt;&lt; endl; cout &lt;&lt; "Rock beats Scissors; Paper beats Rock; Scissors beats Paper." &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; "------------------------------------------------------------------" &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; "Please choose from the following" &lt;&lt; endl; cout &lt;&lt; "1. Rock" &lt;&lt; endl; cout &lt;&lt; "2. Paper" &lt;&lt; endl; cout &lt;&lt; "3. Scissors" &lt;&lt; endl; cout &lt;&lt; "4. Quit" &lt;&lt; endl &lt;&lt; endl; //loop sequence that allows player to play again if their input is not 4 while (getUserChoice != 4) { // play begins cin &gt;&gt; reply; cout &lt;&lt; endl; //assinging the numbers to getUserChoice switch (toupper(reply)) { case '1': getUserChoice = 1; break; case '2': getUserChoice = 2; break; case '3': getUserChoice = 3; break; case '4': getUserChoice =4; break; } //calls the void function to display the winner determineWinner(); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T09:24:28.690", "Id": "436785", "Score": "0", "body": "You might want to use `switch` instead of nested `if`s. I tasked my students with writing R-P-S while having a better AI than just random in mind: this involved interfaces and decoupling players from move evaluation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T12:13:12.230", "Id": "436801", "Score": "0", "body": "Can you elaborate why the void function has to be there? I believe it is not a good style to have a void function the determine something. \nSomething called \"determineWinner\" should usually return the winner." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T21:48:49.990", "Id": "436872", "Score": "1", "body": "The indenting in the code is .... unconventional, and worse, inconsistent (e.g. braces at offset 0, 1, and 4. And 0, 1, 4, and 8 spaces indent for non-brace lines (0 near `determineWinner();`))." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T09:19:20.183", "Id": "436912", "Score": "2", "body": "You started off well by defining some constants (`const int Rock = 1, Paper = 2, Scissors = 3, Exit = 4;`) but when I look through the code I see magic numbers (1, 2, 3) everywhere -- why not use those constants?!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:20:50.127", "Id": "437022", "Score": "0", "body": "@Kay you should use a text editor that manages indentation for you. If you don't know one, try `visual studio code`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:22:13.650", "Id": "437023", "Score": "0", "body": "@Kay you also never call `srand()`, so the random number will probably be the same every time you launch the program." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T19:21:27.280", "Id": "437045", "Score": "0", "body": "I think that you should rename `getUserChoice` and `getComputerChoice` to `userChoice` and `computerChoice`. Having `get` in the beginning makes the identifiers look like functions, which they are not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T19:31:48.347", "Id": "437047", "Score": "0", "body": "Why `toupper(reply)`? The reply should only be a digit, not a letter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T19:47:22.777", "Id": "437053", "Score": "0", "body": "After the comment `//determines winner` you have `while (...)` and then `break` inside the body. Use `if` instead." } ]
[ { "body": "<p>You can get rid of the while loops that break after the first iteration, and replace them with <code>if</code>. </p>\n\n<p>You can also get rid of some if statements, like you say. Consider</p>\n\n<pre><code> //display the computers input choice\n if (getComputerChoice == 1)\n {\n cout &lt;&lt; \"The computer chose Rock.\" &lt;&lt; endl;\n }\n\n else if (getComputerChoice == 2)\n {\n cout &lt;&lt; \"The computer chose Paper.\" &lt;&lt; endl;\n }\n\n else if (getComputerChoice == 3)\n {\n cout &lt;&lt; \"The computer chose Scissors.\" &lt;&lt; endl;\n }\n</code></pre>\n\n<p>It would be cleaner to use a switch statement: </p>\n\n<pre><code>switch (getComputerChoice) {\n case 1:\n cout &lt;&lt; \"The computer chose Rock.\" &lt;&lt; endl;\n break; // breaking is important\n case 2: \n // Case code here\n case 3: \n // Case code here\n default:\n // the switch statement reminds you that you should consider what happens if the input is something else\n}\n</code></pre>\n\n<p>The switch statement is less code for the same thing, and hence easier readable. Alternatively, you could also use a list of the possible strings, and only write the code for printing once. That feels more elegant to me, but makes the code slightly harder to understand if read by novice co-programmers.</p>\n\n<pre><code>string choices[] = {\"Rock\", \"Paper\", \"Scissors\"};\n//display the computers input choice\ncout &lt;&lt; \"The computer chose \" &lt;&lt; choices[getComputerChoice-1] &lt;&lt; \".\" &lt;&lt; endl;\n</code></pre>\n\n<p>Note the minus one because you start counting from 1 instead of 0. </p>\n\n<p>For determining whether the user won, you can use modulo computation instead of typing out all the relations. It is up to you whether you prefer more readable code (like you wrote) or code that is more easily modified for more numbers. It is not neccessarily better, but I thought I'd point out the possibility. </p>\n\n<p>The switch case in <code>main()</code> for getting the user input as integer can be replaced with </p>\n\n<pre><code>//assinging the numbers to getUserChoice\ngetUserChoice = reply - '0';\n</code></pre>\n\n<p>I prefer this because of its simplicity and less code means less possibility for errors or issues when later modifying it and forgetting to change something. This line works as described <a href=\"https://stackoverflow.com/a/5030086/2550406\">here</a></p>\n\n<blockquote>\n <p><code>a - '0'</code> is equivalent to <code>((int)a) - ((int)'0')</code>, which means the ascii\n values of the characters are subtracted from each other. Since 0 comes\n directly before 1 in the ascii table (and so on until 9), the\n difference between the two gives the number that the character a\n represents.</p>\n</blockquote>\n\n<p>Since we are already storing the choices in an array, we don't really want to have that same information at another place as well - that would make it harder to update the program. That is why I refer to the choices array from the <code>main</code> function as well.</p>\n\n<p>Also note that <code>using namespace std;</code> is fine in such a small program, but can get messy if you get confused about which functions are from which namespace.</p>\n\n<p>The comment to your question about global variables points out that it would be cleaner to instead pass <code>getUserChoice</code> as parameter. And you only access <code>getComputerChoice</code> in one function, so it would be better to not use a global variable for that. That way, it is clear to a reader that there are no evil side effects.</p>\n\n<p>Note that <code>rand()</code> is pseudorandom, and also <a href=\"https://stackoverflow.com/questions/9459035/why-does-rand-yield-the-same-sequence-of-numbers-on-every-run\">it is the same on each run</a>. Please see the link - I have not modified this in my version of your code.</p>\n\n<hr>\n\n<p>Here is the complete program as I modified it:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;cstdlib&gt;\n#include &lt;string&gt;\n\nusing namespace std;\n\nstring choices[] = {\"Rock\", \"Paper\", \"Scissors\"};\n\nvoid determineWinner(int getUserChoice)\n{ \n\n //random computer choice\n int getComputerChoice = rand() % 3 + 1; // 1, 2, or 3\n\n //displays the users input choice\n if (getUserChoice == 4)\n {\n cout &lt;&lt; \"You have chosen to exit the game. The game will now end.\" &lt;&lt; endl;\n return;\n }\n else if (getUserChoice &gt; 4)\n {\n cout &lt;&lt; \"You have chosen something weird!\" &lt;&lt; endl;\n return;\n }\n else\n {\n cout &lt;&lt; \"You chose \" &lt;&lt; choices[getUserChoice-1] &lt;&lt; \".\" &lt;&lt; endl;\n }\n\n //display the computers input choice\n cout &lt;&lt; \"The computer chose \" &lt;&lt; choices[getComputerChoice-1] &lt;&lt; \".\" &lt;&lt; endl;\n\n //determines winner\n if ((getUserChoice + 1) % 3 == getComputerChoice % 3)\n {\n cout &lt;&lt; \"I'm sorry, the computer has beat you.\" &lt;&lt; endl &lt;&lt; endl;\n }\n else if ((getUserChoice + 2) % 3 == getComputerChoice % 3)\n {\n cout &lt;&lt; \"Congratulations, you win!\" &lt;&lt; endl &lt;&lt; endl;\n }\n else\n {\n cout &lt;&lt; \"This game is tied. \" &lt;&lt; endl &lt;&lt; endl;\n } \n}\n\nint main()\n{\n //displays a description of the game\n cout &lt;&lt; \"Rock, Paper, Scisscors Game!\" &lt;&lt; endl &lt;&lt; endl;\n cout &lt;&lt; \"You will be playing against the computer.\" &lt;&lt; endl;\n cout &lt;&lt; \"Rock beats Scissors; Paper beats Rock; Scissors beats Paper.\" &lt;&lt; endl &lt;&lt; endl;\n cout &lt;&lt; \"------------------------------------------------------------------\" &lt;&lt; endl &lt;&lt; endl;\n cout &lt;&lt; \"Please choose from the following\" &lt;&lt; endl;\n for (int i=1; i&lt;4; i++)\n {\n cout &lt;&lt; ((char)((int)'0'+i)) &lt;&lt; \". \" &lt;&lt; choices[i-1] &lt;&lt; endl;\n }\n cout &lt;&lt; \"4. Quit\" &lt;&lt; endl &lt;&lt; endl;\n\n //loop sequence that allows player to play again if their input is not 4\n int getUserChoice;\n while (getUserChoice != 4)\n {\n // play begins\n char reply;\n cin &gt;&gt; reply;\n cout &lt;&lt; endl;\n\n //assinging the numbers to getUserChoice\n getUserChoice = reply - '0';\n\n //calls the void function to display the winner\n determineWinner(getUserChoice);\n\n }\n\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T16:33:21.027", "Id": "436700", "Score": "1", "body": "Your modulo math isn't quite right. `if ((getUserChoice + 1) % 3 == getComputerChoice)` will never be true if the computer picks `3` (scissors)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T16:36:01.703", "Id": "436701", "Score": "3", "body": "You shouldn't keep the `using namespace std;` in your solution. That's the 1st sin in c++ programming." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T16:40:26.357", "Id": "436702", "Score": "0", "body": "Fair enough, @Quuxplusone. I forgot that they weren't counting from 0 there. Perhaps that speaks against the modulo approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T16:46:14.577", "Id": "436704", "Score": "0", "body": "@πάνταῥεῖ What is the issue with it _in this specific program_? It is a reasonable argument that it keeps the code easy to read when the code is that simple" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T16:49:58.940", "Id": "436705", "Score": "1", "body": "@lucidbrot It's a general issue, and shouldn't become a (default) behavior." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T20:53:40.117", "Id": "436746", "Score": "1", "body": "@πάνταῥεῖ I have to keep the \"using namespace std;\" in my code as it is a class requirement. Thanks for all the wonderful comments though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T20:54:47.557", "Id": "436749", "Score": "0", "body": "@lucidbrot Thank you for your help! That cleaned it up a lot and it stayed within the guide lines of my class!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T20:58:25.087", "Id": "436750", "Score": "1", "body": "No problem @Kay, I'm happy that the initial reaction you got on stackoverflow did not scare you away from asking" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T16:23:50.007", "Id": "225043", "ParentId": "225039", "Score": "5" } }, { "body": "<p>Programming is the art of detecting and removing duplication.</p>\n\n<pre><code> //display the computers input choice\n if (getComputerChoice == 1)\n {\n cout &lt;&lt; \"The computer chose Rock.\" &lt;&lt; endl;\n }\n\n else if (getComputerChoice == 2)\n {\n cout &lt;&lt; \"The computer chose Paper.\" &lt;&lt; endl;\n }\n\n else if (getComputerChoice == 3)\n {\n cout &lt;&lt; \"The computer chose Scissors.\" &lt;&lt; endl;\n }\n</code></pre>\n\n<p>We could write this more simply with a helper function:</p>\n\n<pre><code>std::string gesture(int x) {\n if (gesture == 1) return \"Rock\";\n if (gesture == 2) return \"Paper\";\n if (gesture == 3) return \"Scissors\";\n assert(false); // this should never happen\n}\n</code></pre>\n\n<p>and then back in <code>main</code>:</p>\n\n<pre><code>std::cout &lt;&lt; \"The computer chose \" &lt;&lt; gesture(getComputerChoice) &lt;&lt; \".\\n\";\n</code></pre>\n\n<p>Notice also that I'm fully qualifying my identifiers out of <code>namespace std</code> — this is a good practice. You should do it. And I'm not wasting time typing out <code>std::endl</code> when <code>\\n</code> does the exact same thing but shorter and faster.</p>\n\n<hr>\n\n<pre><code> while (\n (getUserChoice == 2 &amp;&amp; getComputerChoice == 3)||\n (getUserChoice == 3 &amp;&amp; getComputerChoice == 1)||\n (getUserChoice == 1 &amp;&amp; getComputerChoice == 2)\n )\n\n {\n cout &lt;&lt; \"I'm sorry, the computer has beat you.\" &lt;&lt; endl &lt;&lt; endl;\n break;\n }\n</code></pre>\n\n<p>Two things: First, the use of <code>while (cond) { thing; break; }</code> to mean <code>if (cond) { thing; }</code> is <em>so</em> ridiculous that I wonder if you're trolling. (Odds are against it; but still, why would you write an <code>if</code> as a <code>while</code> and then ask real people to review it for style?)</p>\n\n<p>Second, this would be a great place to show your understanding of the structure of the game. 3 beats 2, 2 beats 1, 1 beats 3. What arithmetic operation could we use here to encode all of those results in a single expression?</p>\n\n<p>...Well, first, let's detect and remove repetition.</p>\n\n<pre><code>if (beats(getComputerChoice, getUserChoice)) {\n std::cout &lt;&lt; \"I'm sorry, the computer has beat you.\\n\\n\";\n} else if (beats(getUserChoice, getComputerChoice)) {\n std::cout &lt;&lt; \"Congratulations, you win!\\n\\n\";\n} else {\n std::cout &lt;&lt; \"This game is tied.\\n\\n\";\n}\n</code></pre>\n\n<p>Okay, now how do we write the <code>beats</code> function?</p>\n\n<pre><code>bool beats(int a, int b) {\n return ((a == 3 &amp;&amp; b == 2) || (a == 2 &amp;&amp; b == 1) || (a == 1 &amp;&amp; b == 3));\n}\n</code></pre>\n\n<p>But we can use arithmetic instead. <code>a</code> beats <code>b</code> exactly when <code>a</code> is one greater than <code>b</code>, modulo 3.</p>\n\n<pre><code>bool beats(int a, int b) {\n return (a - 1) == b % 3;\n}\n</code></pre>\n\n<p>No comment on the input/output part.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T16:44:18.187", "Id": "436703", "Score": "4", "body": "Nice explanation how to think about functions! It might be worthwile to note that [endl and \\n are only almost the same](https://stackoverflow.com/questions/213907/c-stdendl-vs-n) but flushing does not matter in this context." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T20:53:04.480", "Id": "436745", "Score": "0", "body": "@Quuxplusone Thank you but for this class I am not allowed to use the std::cout commands and I'm not sure if I would be able to use the bool function either because we haven't learned about it yet in this class and the last time I read ahead and tried to use other coding methods my instructor deducted points from my grade for reading ahead. Thank you for your post though I will definitely try to code like that once we cover it in class!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T20:59:18.940", "Id": "436751", "Score": "27", "body": "That sounds like one counter-productive instructor" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T00:44:21.953", "Id": "436763", "Score": "5", "body": "@Kay std::cout is the same as \"using namespace std; cout\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T12:18:23.513", "Id": "436802", "Score": "3", "body": "I agree with your suggest, except for the last part n transforming the beats function.\nI believe the original way of using an explicit if condition is more readable and doesn't rely on properties of the underlying data representation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T13:38:55.897", "Id": "436808", "Score": "0", "body": "@Helena: I wanted not to present it as \"here's a magic formula that happens to work,\" but explain why it makes sense (while still being concise — perhaps too concise). If we were doing, say, poker hands, and someone came up with a clever ad-hoc one-liner that happened to work, I wouldn't use it. But with R/P/S, the cyclic/modulo structure is a deliberate feature. If we were doing [Rock Paper Scissors Lizard Spock](https://bigbangtheory.fandom.com/wiki/Rock,_Paper,_Scissors,_Lizard,_Spock), I'd equally recommend that we find a way to encode `beats(a,b) => (a - b) == [1 or 3] mod 5`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T15:43:09.400", "Id": "436824", "Score": "0", "body": "@Quuxplusone Wouldn't a `switch` on `(a - b) % 3` be better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T16:45:36.593", "Id": "436836", "Score": "1", "body": "@wizzwizz4: For RPSLS, I'd work out some way to use a switch; but in this case, it seemed like more trouble than it was worth. Notice that `switch ((a - b) % 3)` will be buggy [unless](https://godbolt.org/z/q5sLpz) you add cases for `-2` and `-1`. So do you write `switch ((a + 3 - b) % 3)` — tending toward token soup — or do you just stick with `if (beats(a, b)) ... else if (beats(b, a)) ... else`? For this application, I think I'd stick with readability. But, like I said, a `switch` might be the best way to express the above \"`[1 or 3] mod 5`\" behavior." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T17:41:01.670", "Id": "436851", "Score": "2", "body": "@Quuxplusone Why would `-2` and `-1`… Oh. C's `%` operator is the remainder. I always get caught on that one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T05:42:26.810", "Id": "436888", "Score": "0", "body": "Because of the many definitions of the `%` operator (some mean remainder, some mean modulo) I'd rather ensure that its operands are always positive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T12:50:19.127", "Id": "436930", "Score": "1", "body": "Don't bet that \"while (cond) { thing; break; }\" is trolling. I have to work with code in which someone did that very thing some 10 years ago. We are still finding them 10 years later - it's a big codebase, and it would take quite some time to find, correct, and test all instances at once. We fix them if they're in the middle of something else that is being worked on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T15:05:08.020", "Id": "436959", "Score": "0", "body": "@Quuxplusone: The modulus function works for any odd `n` symbols (RPS, RPSLS, and more), as long as you lay the symbols so that every symbol beats the (cyclically) `(n-1)/2` following ones, and is beaten by the `(n-1)/2` preceding ones. Then, the result is the sign of `((a - b + (3*n-1)/2) % n) - (n-1)/2`. (Better hide this deep in a library ... and write unit tests)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T16:06:12.183", "Id": "436980", "Score": "0", "body": "@LaurentLARIZZA: Interestingly, it is _not always_ possible to do so, when `n>5`! [OEIS A096368](http://oeis.org/A096368); [\"RPS meets Borromean Rings\" (Chamberland+Herman 2014)](http://www.math.grinnell.edu/~chamberl/papers/rps.pdf). E.g., given the symbols A>(B,C,D); B>(D,E,F); C>(B,D,G); D>(E,F,G); E>(A,C,G); F>(A,C,E); G>(A,B,F) [(source)](https://www.reddit.com/r/math/comments/a8ur9k/rock_paper_scissor_variations/) you can't label A–G with integers in any way to produce your modulus property. (But with \"A>(B,C,D); B>(C,D,E); C>(D,E,F); D>(E,F,G); E>(F,G,A); F>(G,A,B); G>(A,B,C)\" you can.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T07:20:01.103", "Id": "437101", "Score": "0", "body": "@Quuxplusone : Interesting paper, I learnt something. I should have said *as long as you can lay*." } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T16:30:48.297", "Id": "225044", "ParentId": "225039", "Score": "28" } }, { "body": "<p>Nice start point. </p>\n\n<p>I'd like to suggest the following in the spirit of splitting everything into smaller functions and making the code easier to read:</p>\n\n<pre><code>#include &lt;iostream&gt;\n//#include &lt;cstdlib&gt; // We aren't using this so remove it\n#include &lt;string&gt;\n\nusing namespace std; // avoid this for larger programmes\n\nenum Options{\n Rock, Paper, Scissors, Quit\n};\n</code></pre>\n\n<p>This is a lot cleaner.</p>\n\n<p>Let's clean up main</p>\n\n<pre><code>int main()\n{\n run_game();\n return 0;\n}\n</code></pre>\n\n<p>Pretty obvious what main is doing now. No need for comments,</p>\n\n<p>and this would lead us to</p>\n\n<pre><code>void run_game() {\n Options player_choice, cpu_choice;\n bool quit = false;\n while(quit == false) {\n player_choice = get_player_choice();\n if (player_choice == Quit) {\n quit = true;\n return;\n }\n cpu_choice = get_computer_choice();\n show_results(player_choice, cpu_choice);\n }\n}\n</code></pre>\n\n<p>I've omitted the other functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T05:45:22.870", "Id": "436889", "Score": "6", "body": "Why not `bool quit = false`? Also, the `return` makes the whole variable redundant. And in addition, variables should be initialized at first use instead of declaring them at the very top of the function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T15:29:54.950", "Id": "436971", "Score": "0", "body": "Totally agree. I'll edit the post for bool as that should have been there in the first place. Quit could also be done much better (I was originally going to return the quit flag but I didn't do that in the end), but my main focus was on making it easier to read. Definitely not the best example, but a step in the right direction." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T19:16:54.083", "Id": "437042", "Score": "1", "body": "Why `while (quit == false)`? Isn't it clearer with `while (!quit)`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T03:13:29.760", "Id": "437077", "Score": "0", "body": "For most, yes. For a newer programmer, maybe not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-25T13:12:54.517", "Id": "440981", "Score": "1", "body": "Having all the comments, using the \"namespace std\", the bool function being like it is, these are all class requirements. I have tried using better and cleaner code and my teacher posted a forum saying that we are not allowed to read ahead or use Google/Youtube to help us. I don't completely agree with this since even the senior programmers use at least Google/Stack-overflow but I am just following the rules of the class! Thanks again for all the awesome suggestions for cleaning up my code!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T12:53:34.567", "Id": "225085", "ParentId": "225039", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T15:29:32.700", "Id": "225039", "Score": "16", "Tags": [ "c++", "beginner", "game", "rock-paper-scissors" ], "Title": "Writing a clean implementation of rock–paper–scissors game in C++" }
225039
<p>A previous question regarding <strong>Linny</strong> exists <a href="https://codereview.stackexchange.com/questions/224907/linny-an-interpreted-programming-language">here</a>.</p> <p>After a wonderful response on my <a href="https://codereview.stackexchange.com/questions/224907/linny-an-interpreted-programming-language">previous question</a> regarding my developing programming language, I worked on it for a couple days, and am returning for more scrutiny. What I added:</p> <ul> <li>If Statements ( no else )</li> <li>Functions ( with calls )</li> <li>For Loops</li> <li>Math operations</li> <li>User input (<strong>feed</strong>)</li> <li>Changed file extension from <strong>.linny</strong> to <strong>.lin</strong></li> <li>Added <strong>character</strong> datatype</li> <li><strong>All additions to the language are reflected in the interpreter.</strong></li> </ul> <p>I would like feedback on anything possible, as I plan on writing a game with this language in the future (expect that to be reviewed on here as well!). Any and all feedback is welcome, appreciated, and considered!</p> <p><strong>script.lin</strong></p> <pre><code>//Variable Assignments string s = "Hello" ; integer a = 12 ; integer b = 13 ; integer c = 13 ; string aa = "S" ; string bb = "S" ; float x = 7.22 ; boolean t = false ; boolean s = true ; character = "c" ; // Math operations / type output add a b =&gt; sum ; out sum ; type sum ; subtract a b =&gt; sum ; out sum ; multiply a b =&gt; sum ; out sum ; divide a b =&gt; sum ; out sum ; //User input feed string pw "Password: " ; out pw ; //Function calling func test() out a ; endfunc call test ; //If statements if a greaterthan b then out a ; out b ; endif if a lessthan b then out t ; endif if aa equals bb then out s ; endif //For loops for 2 out t ; endfor for 3 out aa ; endfor </code></pre> <p><strong>interpreter.py</strong></p> <pre><code>""" [Linny Interpreter] """ #import json VARIABLE_CACHE = {} FUNCTION_CACHE = {} VARIABLE_KEYWORDS = ["integer", "string", "float", "boolean", "character", "feed"] LOGIC_KEYWORDS = ["if", "endif", "else", "while", "for", "then", "equals", "greaterthan", "lessthan"] FUNC_KEYWORDS = ["func", "endfunc"] MISC_KEYWORDS = ["type"] ALL_KEYWORDS = VARIABLE_KEYWORDS + LOGIC_KEYWORDS + FUNC_KEYWORDS + MISC_KEYWORDS def add_to_function_cache(lines_of_code): """ Gathers all functions in the program and stores them """ for line in lines_of_code: if line.startswith("func"): function_name = parse_function_name(line) function_body = parse_function_body(function_name) FUNCTION_CACHE[function_name] = { 'code': function_body } # FUNCTION PARSER METHODS START # def parse_function_name(line): """ Returns the function name """ return line[5:][:-3] def parse_function_body(function_name): """ Returns all the code in the body of the passed function """ body = [] all_lines = get_lines() for i in range(len(all_lines)): if all_lines[i].startswith("func") and function_name in all_lines[i]: for j in range(i + 1, len(all_lines)): if all_lines[j].startswith("endfunc"): return body body.append(all_lines[j][1:-1]) # FUNCTION PARSER METHODS END # def add_to_variable_cache(line_of_code): """ Adds a variable to the program cache, after tons of checks, returns True if it was able to add to cache, False if it couldn't """ seperated_info = line_of_code.split() if len(seperated_info) == 5 and \ seperated_info[0] in VARIABLE_KEYWORDS and \ not seperated_info[1] in ALL_KEYWORDS and \ seperated_info[2] == "=" and \ not seperated_info[3] in ALL_KEYWORDS and \ seperated_info[4] == ";": data_type = seperated_info[0] name = seperated_info[1] value = seperated_info[3] if data_type == "string": value = str(value) if data_type == "integer": value = int(value) if data_type == "float": value = float(value) if data_type == "boolean": if value == "true": value = True if value == "false": value = False if data_type == "character": value = chr(value) VARIABLE_CACHE[name] = { 'data_type': data_type, 'value': value } return True return False SOURCE_FILE = "Code/Python/Linny/script.lin" def get_lines(): """ Returns all the lines in the file """ with open(SOURCE_FILE, "r") as file: all_lines = [] for line_ in file: all_lines.append(line_) return all_lines def run_code(line): """ Runs the code in passed `line` """ #Check if line is empty if line == "" or line == "\n" or line == []: return # "out (variable)" case # Usage: `out variable_name`, prints the value of the variable if line.startswith("out") and has_ending_semicolon(line): variable = line.split()[1] if variable in VARIABLE_CACHE.keys(): if isinstance(variable, str): print(str(VARIABLE_CACHE[variable]['value']).replace('"', '')) return print(VARIABLE_CACHE[variable]['value']) return # "type (variable)" case # Usage: `type variable_name`, prints the data_type of the variable_name if line.startswith("type") and has_ending_semicolon(line): variable = line.split()[1] if variable in VARIABLE_CACHE.keys(): print(VARIABLE_CACHE[variable]['data_type']) return # "feed (variable)" case # Usage: `feed data_type variable_name "prompt"`, gets user input if line.startswith("feed") and has_ending_semicolon(line): data_type = line.split()[1] variable = line.split()[2] prompt = line.split()[3].replace('"', '') value = input(prompt) VARIABLE_CACHE[variable] = { 'data_type': data_type, 'value': value } return # "call (function)" case # Usage: `call function_name`, runsfunction if line.startswith("call") and has_ending_semicolon(line): function_name = line.split()[1] if function_name in FUNCTION_CACHE.keys(): for line_of_code in FUNCTION_CACHE[function_name]['code']: run_code(line_of_code) ###### MATH COMPARISONS START ##### # "add/subtract/times/divide v1 v2 =&gt; v3" case if line.split()[0] in ["add", "subtract", "multiply", "divide"] and has_ending_semicolon(line): operator = line.split()[0] value_one = line.split()[1] value_two = line.split()[2] product = line.split()[4] #SyntaxError handling real quick if VARIABLE_CACHE[value_one] and VARIABLE_CACHE[value_two]: if VARIABLE_CACHE[value_one]['data_type'] == VARIABLE_CACHE[value_two]['data_type']: if operator == "add": VARIABLE_CACHE[product] = { 'data_type': VARIABLE_CACHE[value_one]['data_type'], 'value': VARIABLE_CACHE[value_one]['value'] + VARIABLE_CACHE[value_two]['value'] } return if operator == "subtract": VARIABLE_CACHE[product] = { 'data_type': VARIABLE_CACHE[value_one]['data_type'], 'value': VARIABLE_CACHE[value_one]['value'] - VARIABLE_CACHE[value_two]['value'] } return if operator == "multiply": VARIABLE_CACHE[product] = { 'data_type': VARIABLE_CACHE[value_one]['data_type'], 'value': VARIABLE_CACHE[value_one]['value'] * VARIABLE_CACHE[value_two]['value'] } return if operator == "divide": VARIABLE_CACHE[product] = { 'data_type': VARIABLE_CACHE[value_one]['data_type'], 'value': VARIABLE_CACHE[value_one]['value'] / VARIABLE_CACHE[value_two]['value'] } return ##### MATH COMPARISONS END ##### ##### IF STATEMENTS START ##### if line.startswith("if"): expressions = gather_expressions(line) inside_code = gather_inside_code(line, "endif") #Evaluate `if not variable then` if len(expressions) == 2: if expressions[1] in list(VARIABLE_CACHE.keys()): data_type = VARIABLE_CACHE[expressions[1]]['data_type'] if data_type == "boolean": #Now check for not if expressions[0] == "not": if not VARIABLE_CACHE[expressions[1]]['value']: for code in inside_code: run_code(code) else: exit(f"SyntaxError: {expressions[0]}") #Evaluate `if variable then` if expressions[0] in list(VARIABLE_CACHE.keys()): data_type = VARIABLE_CACHE[expressions[0]]['data_type'] if data_type == "boolean": if VARIABLE_CACHE[expressions[0]]['value']: for code in inside_code: run_code(code) #Evaluate greaterthan if expressions[1] == "greaterthan": larger = VARIABLE_CACHE[expressions[0]] smaller = VARIABLE_CACHE[expressions[2]] if larger['data_type'] == smaller['data_type']: if larger['value'] &gt; smaller['value']: for code in inside_code: run_code(code) #Evaluate lessthan if expressions[1] == "lessthan": smaller = VARIABLE_CACHE[expressions[0]] larger = VARIABLE_CACHE[expressions[2]] if smaller['data_type'] == smaller['data_type']: if smaller['value'] &lt; larger['value']: for code in inside_code: run_code(code) #Evaluate equals if expressions[1] == "equals": var_one = VARIABLE_CACHE[expressions[0]] var_two = VARIABLE_CACHE[expressions[2]] if var_one['data_type'] == var_two['data_type']: if var_one['value'] == var_two['value']: for code in inside_code: run_code(code) ##### IF STATEMENTS END ##### ##### FOR STATEMENTS START ##### if line.startswith("for"): iterations = int(line.split()[1]) inside_code = gather_inside_code(line, "endfor") for _ in range(iterations): for code in inside_code: run_code(code) ##### FOR STATEMENTS END ##### def gather_expressions(line): """ Gathers all the expressions in the if statement """ expressions = [] for word in line.split(): if word not in ["if", "then"]: expressions.append(word) return expressions def gather_inside_code(main_line, ending): """ Gathers all the code inside the statement/loop """ all_lines = get_lines() inside_code = [] for i in range(len(all_lines)): if all_lines[i] == main_line: for j in range(i + 1, len(all_lines)): if all_lines[j].startswith(ending): return inside_code inside_code.append(all_lines[j][1:-1]) return None def has_ending_semicolon(line): """ Returns True if the line ends with a semicolon, else returning False """ return False if line == "" else line.split()[-1] == ";" def main(): """ Combines all the steps for the interpreter """ #Gathers all the declared variables for line in get_lines(): add_to_variable_cache(line) #Gathers all the created functions add_to_function_cache(get_lines()) #Runs the code for line in get_lines(): run_code(line) if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T03:27:47.900", "Id": "452611", "Score": "0", "body": "Is there anything else required to execute and test the interpreter? Do you have a language specification? Any documentation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-06T03:45:17.740", "Id": "452612", "Score": "0", "body": "Some resources that may be of use: https://www.aosabook.org/en/500L/a-python-interpreter-written-in-python.html. I started writing up an answer only to realize that there's no point in my speculating, I will eagerly return once I know more about the design of the language." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T18:03:02.523", "Id": "225051", "Score": "5", "Tags": [ "python", "python-3.x", "language-design", "linny" ], "Title": "Linny: Continued Language Development" }
225051
<p>I'm playing around with using Dapper with Mediatr in a .NET Core API. It's all working nicely. </p> <p>Its a learning project for me so I am just putting together a system that will hold user details against some training qualifications/certifications. </p> <p>I am just building out the api's first and then will have a look at a UI. This initial code doesn't make sense in regards to the specifics around the user I am really just trying to work out whether fundamentally this approach of no repository is flawed. I haven't used Dapper before but have used EF so dropped repositories as they offered little benefit</p> <p>Have been reading lots of blog posts from Jimmy Bogard around dropping repositories favouring query objects and posts from Mark Seemann around design smells.</p> <p>However, I am not sure about best practice around using Dapper and although it's working, I'd like to know if there is a better approach or something I am missing.</p> <p>I am thinking about using a <code>Repository</code> but not sure it's going to add much value. </p> <p>Should I be injecting the connection into the handler? Or sharing between requests somehow? At the moment it's just the connection string that is injected in.</p> <p>As I add more handlers to the project, would the project benefit from having some sort of base class for the handlers where the <code>IDbConnection</code> would be made available from?</p> <p>Any feedback gratefully received.</p> <pre><code>public class GetUserQueryHandler : IRequestHandler&lt;GetUserQuery, ValidatedResponse&gt; { private readonly IConnectionStringProvider config; public GetUserQueryHandler(IConnectionStringProvider config) { this.config = config; } public async Task&lt;ValidatedResponse&gt; Handle(GetUserQuery request, CancellationToken cancellationToken) { using (IDbConnection conn = new SqlConnection(config.ConnectionString)) { var query = "SELECT ID, first_name, last_name FROM [user] WHERE ID = @ID"; conn.Open(); var result = conn.QuerySingleOrDefault&lt;User&gt;(query, new { ID = request.UserId }); return new ValidatedResponse(result); } } } public class User { private readonly int id; private readonly string first_name; private readonly string last_name; public User(int id, string first_name, string last_name) { this.id = id; this.first_name = first_name; this.last_name = last_name; } public int Id =&gt; id; public string Firstname =&gt; first_name; public string Surname =&gt; last_name; } public class GetUserQuery : IRequest&lt;ValidatedResponse&gt; { private readonly string _name; public GetUserQuery(string name) { _name = name; } public string Name { get { return _name; } } } public class GetApplicationQueryValidator : AbstractValidator&lt;GetUserQuery&gt; { public GetApplicationQueryValidator() { RuleFor(m =&gt; m.Name).Must(m =&gt; m == null || m.Length &gt; 2).WithMessage("Name must be greater than 5, long"); } } public class ValidatedResponse { private readonly IList&lt;string&gt; _messages = new List&lt;string&gt;(); public IEnumerable&lt;string&gt; Errors { get; } public object Result { get; } public ValidatedResponse() =&gt; Errors = new ReadOnlyCollection&lt;string&gt;(_messages); public ValidatedResponse(object result) : this() =&gt; Result = result; public ValidatedResponse AddError(string message) { _messages.Add(message); return this; } } public class ValidatorHandler&lt;TRequest, TResponse&gt; : IPipelineBehavior&lt;TRequest, TResponse&gt; where TRequest : IRequest&lt;TResponse&gt; where TResponse : class { private readonly IEnumerable&lt;IValidator&gt; _validators; public ValidatorHandler(IEnumerable&lt;IValidator&lt;TRequest&gt;&gt; validators) { _validators = validators; } public Task&lt;TResponse&gt; Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate&lt;TResponse&gt; next) { var failures = _validators .Select(v =&gt; v.Validate(request)) .SelectMany(result =&gt; result.Errors) .Where(f =&gt; f != null) .ToList(); return failures.Any() ? Errors(failures) : next(); } private static Task&lt;TResponse&gt; Errors(IEnumerable&lt;ValidationFailure&gt; failures) { var response = new ValidatedResponse(); foreach (var failure in failures) { response.AddError(failure.ErrorMessage); } return Task.FromResult(response as TResponse); } } </code></pre> <p>The <code>Startup</code> class:</p> <pre><code>public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { var connectionString = Configuration.GetConnectionString("userApi"); services.AddSingleton&lt;IConnectionStringProvider&gt;(new ConnectionStringProvider(connectionString)); AddMediatr(services); services.AddControllers(); } private static void AddMediatr(IServiceCollection services) { const string applicationAssemblyName = "UserApi"; var assembly = AppDomain.CurrentDomain.Load(applicationAssemblyName); AssemblyScanner .FindValidatorsInAssembly(assembly) .ForEach(result =&gt; services.AddScoped(result.InterfaceType, result.ValidatorType)); services.AddScoped(typeof(IPipelineBehavior&lt;,&gt;), typeof(ValidatorHandler&lt;,&gt;)); services.AddMediatR(assembly); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints =&gt; { endpoints.MapControllers(); }); } } </code></pre> <p><span class="math-container">```</span></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T20:11:09.463", "Id": "436739", "Score": "2", "body": "oh, I believe one more last thing... we need to know what this is for and what's it doing - then I think we're good ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T20:25:31.380", "Id": "436740", "Score": "0", "body": "Thanks for your prompt feedback added some more context and what I am basing this around" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T20:48:12.613", "Id": "436743", "Score": "0", "body": "@t3chb0t It's a bit weird that _GetUserQuery_ provides a _Name_, but the query gets _UserId_ from it. Is this code even working as intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T20:54:24.173", "Id": "436747", "Score": "0", "body": "The user class will be added to in terms of personal details such as date of birth and therefore hopefully will make more sense. Was just adding enough code to get Dapper working and to ask a question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T20:54:47.057", "Id": "436748", "Score": "2", "body": "@t3chb0t _the initial code doesn't make sense_ I rest my case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T10:48:22.673", "Id": "436920", "Score": "0", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[ { "body": "<h2>Separation of Concerns</h2>\n\n<blockquote>\n <p><em>I am thinking about using a Repository but not sure it's going to add much value.</em></p>\n</blockquote>\n\n<p>The problem with letting the handler interact to the database layer directly is that it is handling both service layer (<code>GetUserQuery</code>, <code>ValidatedResponse</code>) and data layer (<code>SqlConnection</code>, <code>SqlConnection</code>) contracts and APIs. Without separating these concepts, both layers depend on eachother. In this architecture, <code>User</code> is both a service as data layer contract. In more complex environments, you would have a <code>UserDto</code> (service layer) and <code>UserRecord</code> (data layer). Since we are querying, the intermediate business entity is usually omitted.</p>\n\n<blockquote>\n<pre><code>public async Task&lt;ValidatedResponse&gt; Handle(\n GetUserQuery request, CancellationToken cancellationToken)\n{\n using (IDbConnection conn = new SqlConnection(config.ConnectionString))\n {\n // .. code left out for brevity\n }\n}\n</code></pre>\n</blockquote>\n\n<p>I would refactor to keep <code>GetUserQueryHandler</code> in the service layer and create <code>UserRepository</code> in the data layer. Its interface <code>IUserRepository</code> should be stored at the business layer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T20:44:11.803", "Id": "225060", "ParentId": "225054", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T18:21:07.040", "Id": "225054", "Score": "0", "Tags": [ "c#", "asp.net-core", "dapper", "mediator" ], "Title": "Is there a better approach to implementing Dapper with Mediatr?" }
225054
<p>I wrote an implementation of a hash table in Python. <br> This implementation uses chaining for handling collisions, based on lists. <br> I also use an expansion/shrink factor of 2. <br> The expansion is done when the amount of key entries is bigger than the amount of slots from the hash table. Shrinking is done when the amount fo key entries is 1/4 of the total amount of slots. <br> *slots -> the main list where the hashing indexing is performed.</p> <p>Here is my implementation:</p> <pre><code>class HashTable: """ Hash table data structure implementation. This implementation uses chaining for collision resolution. This data structure basically receives a pair (key, value) and add it to the hash tabel structure. """ MIN_SIZE = 8 def __init__(self, hashing_function='division'): self._size = self.MIN_SIZE self._slots = [[] for _ in range(self._size)] self._hashing_function = hashing_function self._len = 0 def _hash(self, key): """ Applies hashing process to a given key and return an index from the table slots. This is done in two steps : 1. Checks if the key is a string and returns the equivalent sum of its ASCII values. 2. Applies the key hashing to an index in the slots range """ key = sum(ord(c) for c in key) if type(key) is str else key return { 'division': lambda: key % self._size }.get(self._hashing_function, lambda: None)() def get(self, key, default=None): """ Returns the value for given key if the key exists, else returns default value. Default value is None if not specified. """ index = self._hash(key) slot = self._slots[index] for pair in slot: return pair[1] if pair[0] == key else default def exist(self, key): """ Check if key already exists inside the hash table. """ index = self._hash(key) slot = self._slots[index] return key in dict(slot) def put(self, key, value): """ Inserts a key and value pair inside the hash table. The collisions are ignored as a chaining approach is taken. Repeated keys can not be added. """ if not self.exist(key): index = self._hash(key) self._slots[index].append((key,value)) self._len += 1 if self._len &gt; self._size: self._expand() def remove(self, key, default=None): """ Removes and returns a given key value and its associated value pair. If given key is not found, the given default value is returned. If default value is not provided, None is returned. """ index = self._hash(key) slot = self._slots[index] pop_index = None for i in range(len(slot)): if slot[i][0] == key: pop_index = i if pop_index is not None: removed_pair = slot.pop(pop_index) self._len -= 1 # If the amount of entries is 1/4 of the total amount of slots and # the total amount of slots is greater then the minimun size, than # a shirnking is applied ot the hash table if self._len == self._size/4 and self._size &gt; self.MIN_SIZE: self._shrink() return removed_pair else: return default def _expand(self): """ Expands the slots capacity from the hash table, applying a rehash on all (key, value) pairs to match the new size of the hash table. Applied when number of key entries is bigger than the amount of slots. """ temp_slots = [] for slot in self._slots: temp_slots += slot self._size *= 2 self._len = 0 self._slots = [[] for _ in range(self._size)] for pair in temp_slots: self.put(pair[0], pair[1]) def _shrink(self): """ Shrinks the slots capacity from the hash table, applying a rehash on all (key, value) pairs to match the new size of the hash table. Applied when number of key entries is 1/4 of the amount of slots. """ temp_slots = [] for slot in self._slots: temp_slots += slot self._size //= 2 self._len = 0 self._slots = [[] for _ in range(self._size)] for pair in temp_slots: self.put(pair[0], pair[1]) </code></pre> <p>Please, fell free to do any kind of comments about performance, a more pythonic way of doing something or anything else! :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T19:55:54.907", "Id": "436737", "Score": "3", "body": "Welcome, sojal. Could you perhaps add a bit of code where you actually use this HashTable? That code should demonstrate all important use cases. I'm especially interested in a use case where the hashing_function is not 'division'." } ]
[ { "body": "<p>Here's one suggestion related to usability. Say I want to make this code work:</p>\n\n<pre><code>h = HashTable()\nh.put('hello', 'world')\nh.put((1,2), (3, 4))\nh.put(95.7, 76.2)\n</code></pre>\n\n<p>I have to define a custom hash function to handle the tuples and floats as keys. The only way I can add a custom hash function, however, is to modify your hash table code and add it to the map in the body of the <code>_hash</code> method. That means I can't just use your code; I have to be able to modify it to customize it.</p>\n\n<p>The custom hash function I would write would look something like this:</p>\n\n<pre><code>def custom_hash():\n if type(key) is tuple:\n # turn tuple into integer\n elif type(key) is float:\n # turn float into integer\n # Otherwise the key has already been converted\n return key % self._size\n</code></pre>\n\n<p>I have to add another case to my conditional every time I need to support a new type as key. Suppose I want to use dates as keys, or booleans, or named tuples, or some new class I define. This function could turn really long and ugly after a while.</p>\n\n<p>The built-in Python dictionary avoids this by having objects which can be used as keys implement a <code>__hash__</code> method as described at <a href=\"https://stackoverflow.com/a/8998010/3376926\">https://stackoverflow.com/a/8998010/3376926</a>. Then your <code>_hash</code> method becomes this:</p>\n\n<pre><code>def _hash(key):\n return key.__hash__() % self._size\n</code></pre>\n\n<p>The key itself has logic to convert itself into an integer that your code doesn't need to know anything about, and I can add all the new key types I want without needing to modify your source.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T13:57:07.117", "Id": "436809", "Score": "1", "body": "I think that it's better to use\n```hash(key) % self._size```" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T22:56:16.450", "Id": "225064", "ParentId": "225057", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T19:29:30.490", "Id": "225057", "Score": "4", "Tags": [ "python", "hash-map" ], "Title": "Hash table implementation in Python" }
225057
<p>A function that funnels all filenames into a file and opens that file in vim. The user then changes the names, saves, and quits. Finally the function renames the files in the folder with the new names provided in the file. </p> <p>This is the update to <a href="https://codereview.stackexchange.com/questions/224989/bulk-file-rename">this previous version</a>. The update makes it impossible to destroy files, and improves performance. <a href="https://codereview.stackexchange.com/a/225022/85459">This is the answer</a> that helped develop this version.</p> <pre><code>bulkrename() { trap 'rm -f $RENAMETMP' EXIT # Make array of file names local OLDFILENAMES=( *$@ ) # Pipe array items into file seperated by new lines local RENAMETMP=$(mktemp) printf '%s\n' "${OLDFILENAMES[@]}" &gt; $RENAMETMP &amp;&amp; nvim $RENAMETMP # If user exits nvim with failure, stop the script local exitcode=$?; [[ $exitcode = 0 ]] || return $exitcode # Place new names into an array local IFS=$'\n' local NEWFILENAMES=( $( command cat $RENAMETMP ) ) # After user has edited the names, check for matching line count if [[ ${#OLDFILENAMES[@]} -ne ${#NEWFILENAMES[@]} ]]; then echo "Lines Mismatch" &amp;&amp; return 1 fi # Also check for naming conflicts for ((old = 1; old &lt;= ${#OLDFILENAMES[@]}; old++)); do for ((new = 1; new &lt; $old; new++)); do if [[ ${NEWFILENAMES[old]} = ${NEWFILENAMES[new]} ]] || \ [[ ${OLDFILENAMES[old]} = ${NEWFILENAMES[new]} ]]; then echo "File Naming Confict" &amp;&amp; return 1 fi done done # Rename the files for ((name = 1; name &lt;= ${#NEWFILENAMES[@]}; name++)); do command mv -Tnv "${OLDFILENAMES[name]}" "${NEWFILENAMES[name]}" done } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T19:40:29.360", "Id": "225058", "Score": "2", "Tags": [ "bash", "file-system", "shell", "zsh" ], "Title": "Bulk File Rename; Improved Safety and Performance" }
225058
<p>I found a class that i coded for an old project about a year ago and i haven't really touched php in a while. Now i need to use similar functionality again i thought it would be the perfect time to rewrite/improve old class. i would appreciate feedback on any errors you notice or advice on anything i should use such as design patterns etc.</p> <pre><code>include "db_config.php"; /** * */ class User { //object variables public $pdo; public $user_data; public function __construct() { $this-&gt;pdo = new PDO( "mysql:host=" . DB_SERVER . ";dbname=" . DB_DATABASE, //DSN DB_USERNAME, //Username DB_PASSWORD //Password ); $this-&gt;pdo-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this-&gt;pdo-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //add pdo error check //check to see if the if (isset($_SESSION['uid'])) { $this-&gt;user_data = array('uid' =&gt; $_SESSION['uid'], 'email' =&gt; $_SESSION['email'], 'fname' =&gt; $_SESSION['fname'], 'lname' =&gt; $_SESSION['lname']); } } /** * Register Function */ public function user_register($email, $password, $fname, $lname) { $sql = "SELECT uemail FROM user_profile WHERE uemail = :email"; $stmt = $this-&gt;pdo-&gt;prepare($sql); $stmt-&gt;bindValue(':email', $email); $stmt-&gt;execute(); $row = $stmt-&gt;fetch(PDO::FETCH_ASSOC); $rowCount = $stmt-&gt;rowCount(); if ($rowCount &gt; 0) { //Email is already registered return 0; } else {//if email doesnt exist //hash the password $hashPassword = password_hash($password, PASSWORD_BCRYPT, array("cost" =&gt; 12 )); //prepare insert statement $sql = "INSERT INTO user_profile (uemail, upass, fname, lname) VALUES (:email, :password, :fname, :lname)"; $stmt = $this-&gt;pdo-&gt;prepare($sql); //bind varaiables $stmt-&gt;bindValue(':email', $email); $stmt-&gt;bindValue(':password', $hashPassword); $stmt-&gt;bindValue(':fname', $fname); $stmt-&gt;bindValue(':lname', $lname); //execute instert statment $result = $stmt-&gt;execute(); if ($result) { //register success $this-&gt;user_login($email, $password); return 1; } } } //login function public function user_login($email, $password) { $sql = "SELECT * FROM user_profile WHERE uemail = :uemail"; $stmt = $this-&gt;pdo-&gt;prepare($sql); $stmt-&gt;bindValue(':uemail', $email); $stmt-&gt;execute(); $row = $stmt-&gt;fetch(PDO::FETCH_ASSOC); $rowCount = $stmt-&gt;rowCount(); if ($rowCount &gt; 0) { $test = password_verify($password, $row['upass']); if (password_verify($password, $row['upass'])) { $_SESSION['uid'] = $row['id']; $_SESSION['email'] = $row['uemail']; $_SESSION['fname'] = $row['fname']; $_SESSION['lname'] = $row['lname']; $_SESSION['logged_in'] = date("Y-m-d H:ia"); header("Location: index.php"); } } else { return false; } } //get first name public function get_fname($uid) { return $user_data['fname']; } public function get_lname($uid) { return $user_data['lname']; } // starting session public function get_id() { return $_SESSION['uid']; } public function check_login() { if (isset($_SESSION['logged_in'])) { return true; } else { return false; } } //logout function to destroy session public function user_logout() { $_SESSION['uid'] = FALSE; $_SESSION['email'] = FALSE; $_SESSION['fname'] = FALSE; $_SESSION['lname'] = FALSE; $_SESSION['logged_in'] = FALSE; session_unset(); session_destroy(); header("Location: login.php"); } } </code></pre> <p>also i think this was my first time using PDO so any feedback on the use or implementation of that would be appreciated Thanks in advance for the feedback</p>
[]
[ { "body": "<p>here are some comments on the class code which I hope are of some use to you.</p>\n\n<p><strong>Dependency Injection</strong>\nCreating the PDO object inside the constructor introduces a POD dependency on User class. Think about <a href=\"https://www.thinktocode.com/2017/10/10/solid-principles-in-php/\" rel=\"nofollow noreferrer\">SOLID principles</a> when writing classes. The \"S\" in \"SOLID\" stands for <em>Single Responsibility</em>. Classes should have a <code>Single responsibility</code> - one specific purpose. The User class should not be dependent about what database connection it uses.</p>\n\n<p>When building more complex software with many classes this becomes <strong>extremely</strong> important to reduce class coupling (and reduce complexity). Say if you need to mock an object (that class you want to mock because it not be written yet, or may not have been purchased yet from an external vendor) you can still test your class. </p>\n\n<p>So, pass the PDO object into the User class constructor:</p>\n\n<pre><code> // PDO object is injected into User class\n public function __construct(PDO $pdo)\n {\n $this-&gt;pdo = $pdo;\n</code></pre>\n\n<p>You <strong><em>may</em></strong> also consider (depending on your requirements) managing the user's session in another class and injecting that class into User.</p>\n\n<p><strong>Type Declarations</strong>\nType declarations (or hinting as it was known in PHP5) has been around a while now. It was available for some types in PHP5. Now in PHP7 the feature is more extensive. Also we can enforce the type of parameters and return types. What benefits does this have?</p>\n\n<ul>\n<li><p>It states intent: making it clear what types functions and methods\nsupport. It communicates to others (your team members say) what types\nare valid.</p></li>\n<li><p>It promotes better code: any use of the wrong type can cause an<br>\nexception to throw. No-one can ignore an exception.</p></li>\n<li><p>Helps when using a PHP IDE.</p></li>\n<li><p>Can help eliminates issues due to type coercion. For example, we may not wish our string to be converted to an integer.</p></li>\n</ul>\n\n<p>For more details read <a href=\"https://php.net/manual/en/migration70.new-features.php\" rel=\"nofollow noreferrer\">PHP7 new features</a></p>\n\n<p>Rather than return either 0 or 1, enforce the return type as bool. It more clearly states the intent of the method.</p>\n\n<pre><code>/**\n * Register Function \n *\n * Register a user to the system by adding record to the \n * user_profile table, and then calls login method.\n\n * @param string $email - User's email\n * @param string $password - User's password\n * @param string $fname - User's first name\n * @param string $lname - User's last name\n * @return bool - true if user is registered without error.\n*/\npublic function user_register(string $email, \n string $password, \n string $fname, \n string $lname) : bool\n{\n ....\n if ($result) {\n // register success\n $this-&gt;user_login($email, $password);\n return true;\n }\n\n ....\n return false; // user not registered\n }\n</code></pre>\n\n<p><strong>Documentation</strong> \nYou've commented some methods which is good. Consider extending this by using a documentation generator such as <a href=\"https://en.wikipedia.org/wiki/PHPDoc\" rel=\"nofollow noreferrer\">PHPDoc</a>. In fact you've used PHPDoc format for register_user(). But the method comments should document the method purpose, what it returns and what the parameters are for. </p>\n\n<p>This helps you remember when returning to code you've written some time ago (as we all have done and you have mentioned you have in your post). Many IDE's (such as Netbeans, PHPStorm) use the documentation to help interpret code. See above code for example. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T21:55:44.723", "Id": "437717", "Score": "0", "body": "I have been reading through all the answers and playing around with some of these ideas, and i have created a class to handle the db connection but i was thinking would it be better to pass the connection class to the User class or create an instance of the connection class inside the User class" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T08:24:35.530", "Id": "437752", "Score": "1", "body": "Think SOLID - Single responsibility. That's the ideal for class and function design. What is the responsibility of the User class? Should it manage Users AND open database connections? And a program that has ten classes - would the database connection be in User class then?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T21:35:00.980", "Id": "437952", "Score": "0", "body": "@Rajbir -- Your comment suggests that you have not understood the point of Dependency Injection. Please re-read the 'Dependency Injection' of this answer until you fully grasp its meaning and why it is important." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T21:39:26.207", "Id": "437953", "Score": "0", "body": "haha nah i did understand fully everything that was said in all the answers. the only reason i asked i because i saw a lot of tutorials on PDO where instances of classes where being instantiated inside other classes rather than being fully independent and being passed into the classes" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T14:59:29.480", "Id": "225137", "ParentId": "225061", "Score": "3" } }, { "body": "<p><strong>Abstraction</strong> Your class represents a user, user registration, authentication, and data access all at the same time. This is not ideal because with so many responsibilities, it is difficult to reason about and to maintain if your requirements change. To correct this, first break your class into:</p>\n\n<ul>\n<li><code>User</code></li>\n<li><code>Registration</code></li>\n<li><code>Authentication</code></li>\n<li><code>UserDb</code></li>\n</ul>\n\n<p>Once you have done this, begin the allocation of responsibilities. You do this by thinking about the questions and requests that your application must respond to; for example, <em>'can a user log in with this username and password?'</em>, <em>'register a new user with these details'</em>, <em>'what is the name of the current user?'</em>, <em>'is the current user logged in?'</em>, etc.</p>\n\n<p>Let's tackle a couple of these examples--</p>\n\n<p><em>'Can a user log in with this username and password?'</em> This can be answered by classes <code>User</code> and <code>Authentication</code>. In addition, <code>Authentication</code> needs the collaboration of <code>UserDb</code> to get user data from the database. So, you need methods <code>Authentication::validate($username, $password)</code>, <code>UserDb::findUserByUsername($username)</code>, and <code>User::hasPassword($password)</code>. Finally, the answer to the question is obtained with the following sequence of operations:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$pdo = new PDO(...);\n$userdb = new UserDb($pdo);\n$authentication = new Authentication($userdb);\n$authenticated = $authentication-&gt;validate(\"user1\", \"password1\");\n</code></pre>\n\n<p>Let's look at how your <code>UserDb</code> and <code>Authentication</code> classes might look--</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>class UserDb {\n\n private $pdo;\n\n public function __construct($pdo) {\n $this-&gt;pdo = $pdo;\n }\n\n public function findUserByUser($username) {\n $data = ...;\n return new User($data[\"username\"], $data[\"password\"], ...);\n }\n}\n\nclass Authentication {\n\n private $userdb;\n\n public function __construct($userdb) {\n $this-&gt;userdb = $userdb;\n }\n\n public function validate($username, $password) {\n $user = $this-&gt;userdb-&gt;findUserByUsername($username);\n return $user != null &amp;&amp; $user-&gt;hasPassword($password);\n } \n</code></pre>\n\n<p>To address the second request, <em>'register a new user with these details'</em>, you need classes <code>Registration</code> and <code>User</code> to own the responsibilities, for example:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>class Registration {\n\n private $userdb;\n\n public function __construct($userdb) {\n $this-&gt;userdb = $userdb;\n }\n\n public function register($username, $password) {\n $user = new User($username, $password);\n $this-&gt;userdb-&gt;saveUser($user);\n }\n}\n\nclass User {\n\n private $username, $password;\n\n public function __construct($username, $password) {\n // validate $username and $password\n $this-&gt;username = $username;\n $this-&gt;password = $password;\n }\n}\n</code></pre>\n\n<p>And, they can be used like this, with the existing <code>$userdb</code> object.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$registration = new Registration($userdb);\n$registration-&gt;register(\"user1\", \"password1\");\n</code></pre>\n\n<p>And so on--</p>\n\n<p>The idea is that each class is responsible for satisfying a set of requirements and must collaborate with other classes (with their own unique requirements) to meet them if necessary.</p>\n\n<p><strong>Dependency injection</strong> I won't comment on this, as it is already covered by @suspectus. But, I will point out that it is applied in the example above. You can see that the same <code>UserDb</code> object can be injected in both <code>Authentication</code> and <code>Registration</code>, so it is reasonable that you want <code>$userdb</code> to be a singleton.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T17:42:43.167", "Id": "225372", "ParentId": "225061", "Score": "2" } }, { "body": "<p>The <a href=\"https://codereview.stackexchange.com/a/225137/120114\">answer by suspectus</a> covers DI, type declarations and documentation well. There are a few other aspects I noticed, covered in the sections below.</p>\n\n<h3>Avoiding <code>else</code> when possible</h3>\n\n<p>Most of the methods aren't too long, though <code>user_register()</code> is a bit on the long side. There isn't really a need to have the <code>else</code> keyword, since the <code>if</code> block before it has a <code>return</code> statement. </p>\n\n<p>In <a href=\"https://www.youtube.com/watch?v=GtB5DAfOWMQ\" rel=\"nofollow noreferrer\">this presentation about cleaning up code</a> Rafael Dohms talks about limiting the indentation level to one per method and avoiding the <code>else</code> keyword. (<a href=\"https://www.slideshare.net/rdohms/bettercode-phpbenelux212alternate/11-OC_1Only_one_indentation_level\" rel=\"nofollow noreferrer\">see the slides here</a>). For instance, in the <code>user_login()</code> method, the <code>else</code> could be avoided if the logic to <code>return false</code> came first... something like:</p>\n\n<pre><code>if ($rowCount &lt; 1) { \n return false;\n} //implicit else\n$test = password_verify($password, $row['upass']);\nif (password_verify($password, $row['upass'])) {\n $_SESSION['uid'] = $row['id'];\n $_SESSION['email'] = $row['uemail'];\n $_SESSION['fname'] = $row['fname'];\n $_SESSION['lname'] = $row['lname'];\n $_SESSION['logged_in'] = date(\"Y-m-d H:ia\");\n header(\"Location: index.php\");\n}\n</code></pre>\n\n<hr>\n\n<h3>Methods accessing instance variables/properties</h3>\n\n<p>I noticed that the methods <code>get_fname()</code> and <code>get_lname()</code> utilize <code>$user_data</code> which is not a local variable but instead an instance variable. I believe that would work in Java but not PHP. It should utilize <code>$this-&gt;user_data</code> to work properly in PHP. </p>\n\n<pre><code>//get first name\npublic function get_fname($uid)\n{\n return $this-&gt;user_data['fname'];\n}\n\npublic function get_lname($uid)\n{\n return $this-&gt;user_data['lname'];\n}\n</code></pre>\n\n<hr>\n\n<h2>Simplifying boolean logic</h2>\n\n<p>The method <code>check_login()</code> can be simplified from:</p>\n\n<blockquote>\n<pre><code>public function check_login()\n{\n if (isset($_SESSION['logged_in'])) {\n return true;\n } else {\n return false;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>To just return the condition:</p>\n\n<pre><code>public function check_login()\n{\n return isset($_SESSION['logged_in']);\n}\n</code></pre>\n\n<p>This is because <a href=\"https://www.php.net/isset\" rel=\"nofollow noreferrer\"><code>isset()</code></a> returns a <a href=\"https://www.php.net/bool\" rel=\"nofollow noreferrer\"><code>bool</code></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T21:20:11.277", "Id": "225383", "ParentId": "225061", "Score": "1" } } ]
{ "AcceptedAnswerId": "225137", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T20:44:36.457", "Id": "225061", "Score": "4", "Tags": [ "php", "object-oriented", "authentication", "pdo", "session" ], "Title": "User management OOP php class" }
225061
<p>Disclaimer, I'm new to OOP, but have experience in haskell and javascript. </p> <p>Essentially, the challenge was to create a program which would shift an array a given amount of times to the left and then print the result. </p> <p>I've tried to make this more extendable by allowing the option to shift to the right.</p> <p>My code is</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; vector&lt;int&gt; rotate(vector&lt;int&gt; myVector, int direction, int count); vector&lt;int&gt; rotate(vector&lt;int&gt; myVector, int direction); void print(vector&lt;int&gt; rotatedVector); void print(vector&lt;int&gt; rotatedVector){ for(int i = 0; i &lt; rotatedVector.size(); i++){ cout &lt;&lt; rotatedVector[i] &lt;&lt; endl; } } vector&lt;int&gt; rotate(vector&lt;int&gt; myVector, int direction, int count){ while(count &gt; 0){ myVector = rotate( myVector, direction); // should I create a new variable, or just overwrite myVector each time? --count; } return myVector; } vector&lt;int&gt; rotate(vector&lt;int&gt; myVector, int direction){ const int length = myVector.size(); vector&lt;int&gt; rotatedVector(length); for(int i = 0; i &lt; myVector.size(); i++){ rotatedVector.at(i) = myVector.at((length+i-direction)%length); } return rotatedVector; } int main(){ // Array to rotate int arr[5] = {1,2,3,4,5}; // Times to rotate const int count = 2; // Creating a vector object out of array // Should I have worked with the array given? int n = sizeof(arr) / sizeof(arr[0]); vector&lt;int&gt; myVector(arr, arr + n); enum direction {left = -1, right = 1}; // should this be global? myVector = rotate(myVector, left, count); print(myVector); // Could potentially turn vector back into array? return 0 ; } </code></pre> <p>My design questions are...</p> <ol> <li><p>Is this extendable enough, how could it be made more so? </p></li> <li><p>Should the enums be made global? </p></li> <li><p>Should I have used multiple functions instead of using enums to make the rotation functions generic? (e.g a right rotation function, and a left one)</p></li> <li><p>Should I have kept with the array, instead of creating a vector from it?</p></li> <li>Was overloading the function necessary? </li> </ol> <p><strong>The most important thing I would like to clarify from this review, is the concept of "state" in these types of programming puzzles (done in C++/OOP)</strong> </p> <p>The line which overwrites the vector is...</p> <pre><code>myVector = rotate( myVector, direction); </code></pre> <p>Is it better form to perhaps implement something like...</p> <pre><code>myVector.rotate(direction); </code></pre> <p>and thus action on the same object each time? (and if so why) </p> <p>When would I use one over the other? </p> <p>In my head, I feel as though it would be best to make the vector immutable and keep creating a new one each time, but am unsure and slightly confused about which one to use.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T00:56:34.493", "Id": "436766", "Score": "0", "body": "Do you have to actually rotate the array, or is just printing it rotated enough?" } ]
[ { "body": "<p>There are two basic ways to solve this type of problem. One is having to do the rotation in place, where you can't allocate additional storage for a copy of the array. This uses less memory but takes longer, since the rotations have to go by small increments (usually 1, since that is easiest to implement). The other way is to do the rotation into a copy. This has the advantage of being faster but can take additional memory. Your implementation is a hybrid of both.</p>\n\n<p>Don't write <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><code>using namespace std;</code></a>.</p>\n\n<p>You're passing all your vectors by value, which will result in copies being made. Since you're making a new vector to store the rotated vector in, you can pass them by <code>const &amp;</code>. For example,</p>\n\n<pre><code>std::vector&lt;int&gt; rotate(const std::vector&lt;int&gt; &amp;myVector, int direction);\n</code></pre>\n\n<p><code>print</code> can take advantage of range based for loops:</p>\n\n<pre><code>void print(const vector&lt;int&gt; &amp;rotatedVector) {\n for (int v: rotatedVector){\n std::cout &lt;&lt; v &lt;&lt; '\\n';\n }\n}\n</code></pre>\n\n<p>This also avoids using <code>endl</code>, since that will do a flush which can greatly slow the rate output is displayed.</p>\n\n<p>Your two parameter <code>rotate</code> function can rotate by more than one element at a time. You can combine the two <code>rotate</code> functions into one, with an offset of <code>-direction * count</code> instead of <code>-direction</code>. (With appropriate code to precalculate that value and a check so that the result is not larger than <code>-length</code> to avoid having a negative number on the left of <code>%</code>.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T00:54:11.060", "Id": "436765", "Score": "1", "body": "See [`std::rotate()` on cppreference.com](https://en.cppreference.com/w/cpp/algorithm/rotate), especially the example implementation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T00:51:19.243", "Id": "225067", "ParentId": "225063", "Score": "2" } }, { "body": "<p>Of your questions, I think</p>\n\n<blockquote>\n <ol start=\"4\">\n <li>Should I have kept with the array, instead of creating a vector from it?</li>\n </ol>\n</blockquote>\n\n<p>is the most fundamental. Changing data structures might be a <a href=\"https://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow noreferrer\"><em>code smell</em></a>. In C++ Arrays are immutable and the reasons for using them often involve execution speed via static allocation at compile time and idempotency in concurrent execution.</p>\n\n<p><strong>Function Design</strong></p>\n\n<p>The encapsulation of the array as a vector avoids the quagmire of shared access in a concurrent environment. But the original array data type already solves that.</p>\n\n<p>On the other hand, conversion to a vector does not preserve the performance profile of the underlying data type. </p>\n\n<p>To put it another way, in the absence of knowledge about the reasons for using arrays in the part of the system that is calling <code>rotate</code>, working with the arrays rather than vectors is a conservative engineering choice.</p>\n\n<p><strong>Alternative design</strong></p>\n\n<p>Arrays make the problem one of pointer manipulation. One feature of the array abstraction is built in pointers.</p>\n\n<pre><code>// Pseudo code\n// one indexed array\nrotate(array, n){\n print(array[n+1] to array.length + \n array[1] to array[n];\n}\n</code></pre>\n\n<p><strong>Context</strong></p>\n\n<p>Coming from Javascript, the use of iteration and mutation rather than pointers is not surprising because iteration works on both arrays (as defined in ECMAscript) and the node lists returned by the API's of various browsers. Because node lists can be live, array methods don't always work but iteration always will.</p>\n\n<p><strong>Validation</strong></p>\n\n<p>The code does not validate the value of <code>n</code> relative to the length of the array. There's a design decision about what should happen when the <code>array</code> and <code>n</code> are incompatible. Is printing a message enough? Is something more heavyweight required?</p>\n\n<p><strong>Extending the problem</strong></p>\n\n<p>Adding left rotation doesn't make the code better. So long as shifting left is not part of the specification, it only makes the code more complex. Eliminating the extension removes several of your questions and simplifies the code. Engineering wise: <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNI</a>. </p>\n\n<p>Building the simplest thing that might work, provides more time for fundamental design practices including testing, data validation, and error handling. </p>\n\n<p><strong>Types</strong></p>\n\n<p>The code may break if tested against types other than <code>int</code>. As specified the problem can't assume that it won't be fed other data types. The vector could be <code>&lt;T&gt;</code> (generic). This might be a place where the <a href=\"https://en.wikipedia.org/wiki/Robustness_principle\" rel=\"nofollow noreferrer\">Robustness principle/Postel's Law</a> might be relevant.</p>\n\n<p><strong>Remarks</strong></p>\n\n<p>Keep in mind that it's ok to write C++ code that looks like it was written by someone without years of C++ experience. Haskell and Javscript are rarely used for problems where C++ excels. They are so very different. C++'s idioms don't translate to either very well...but it's probably good to reason about types in C++ based on Haskell experience.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T18:46:26.070", "Id": "225100", "ParentId": "225063", "Score": "1" } } ]
{ "AcceptedAnswerId": "225100", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T21:33:22.530", "Id": "225063", "Score": "2", "Tags": [ "c++", "object-oriented", "state" ], "Title": "N rotations of an array, either left or right, and then printing the result" }
225063
<p>A follow up for this question: <a href="https://codereview.stackexchange.com/questions/224355/implementing-linked-lists-in-python-from-scratch">Implementing Linked lists in Python from scratch</a></p> <p>Node:</p> <pre><code>class Node(): def __init__(self, key): self.key = key self.next = None </code></pre> <p>Linked list:</p> <pre><code>from node import Node class LinkedList: link_connection = ' -&gt; ' ''' init, getters, setters ''' def __init__(self, key): self.head = Node(key) self.tail = self.head self.length = 1 @property def head(self): return self.__head @head.setter def head(self, node): if node is not None: self.__head = node @property def tail(self): return self.__tail @tail.setter def tail(self, node): if node is not None: try: if node.next is None: self.__tail.next = node self.__tail = self.__tail.next except AttributeError: self.__tail = node @property def length(self): return self.__length @length.setter def length(self, value): self.__length = value ''' generator for nodes ''' ''' iterating, search etc. ''' def node_generator(self, target=None): node = self.head yield node while node.next is not None and node.next.key != target: node = node.next yield node def __iter__(self): return map(lambda node: node.key, self.node_generator()) def __str__(self): return self.link_connection.join(str(key) for key in self) def go_forward(self, steps): for node in self.node_generator(): if steps == 0: return node steps -= 1 def delete(self, target): for node in self.node_generator(target): pass node.next = node.next.next self.length -= 1 def __len__(self): return self.__length def append(self, key): node = Node(key) self.tail = node self.length += 1 def find(self, value): for node in self: if node == value: return node </code></pre> <p>Is this new implementation better?</p>
[]
[ { "body": "<h2>Specification and Unit Tests</h2>\n\n<ul>\n<li>You are lacking a clear specification for your methods. We have to guess what these methods do exactly, specially for edge cases.</li>\n<li>You should provide unit tests when providing an API class. You would have found some bugs if you did.</li>\n</ul>\n\n<h2>Review</h2>\n\n<blockquote>\n<pre><code> @head.setter\n def head(self, node):\n if node is not None:\n self.__head = node\n</code></pre>\n</blockquote>\n\n<p>There is no link from the new head to the previous one. Also, what would you do if node.next is already filled?</p>\n\n<pre><code> @head.setter\n def head(self, node):\n if node is not None:\n node.next = self.__head\n self.__head = node\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>@tail.setter\n def tail(self, node):\n if node is not None:\n try:\n if node.next is None:\n self.__tail.next = node\n self.__tail = self.__tail.next\n except AttributeError:\n self.__tail = node\n</code></pre>\n</blockquote>\n\n<p>Why would you expect an <code>AttributeError</code> here? You are only setting <code>next</code>. And why would you ignore a tail that has a next node? Why not include the tail chain?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>''' generator for nodes '''\n''' iterating, search etc. '''\ndef node_generator(self, target=None):\n node = self.head\n yield node\n while node.next is not None and node.next.key != target:\n node = node.next\n yield node\n</code></pre>\n</blockquote>\n\n<p>The spec is unclear here. You always include the head, and then continue as long as a next node's <code>key</code> does not match the specified <code>target</code>. Why not check head for the same condition?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def delete(self, target):\n for node in self.node_generator(target):\n pass\n node.next = node.next.next\n self.length -= 1\n</code></pre>\n</blockquote>\n\n<p>What if the node you want to delete is the tail? This edge case is not foreseen.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T14:42:35.310", "Id": "436812", "Score": "0", "body": "about the generator, it's because I want to return the node before the target, any suggestion to do that better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T14:44:26.213", "Id": "436813", "Score": "1", "body": "If the head is the target, should you yield only the head, or no results?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T14:50:36.323", "Id": "436815", "Score": "1", "body": "OH! I see.\nActually, I don't know what I want to return lol" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T06:43:03.470", "Id": "225074", "ParentId": "225065", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T22:58:43.987", "Id": "225065", "Score": "4", "Tags": [ "python", "beginner", "linked-list" ], "Title": "Implementing linked list from scratch - Follow up" }
225065
<p>I'm a C++ beginner working through Cracking the Coding Interview. This is question 16.8:</p> <blockquote> <p>Given any integer, print an English phrase that describes the integer (e.g., "One Thou­sand, Two Hundred Thirty Four").</p> </blockquote> <p>I have written a simple program, below, that I have confirmed works correctly to answer the question (note that I am ignoring the comma after "Thousand" in the example).</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; // English Int: Given any integer, print an English phrase that describes the integer (e.g., "One Thou­sand, Two Hundred Thirty Four"). std::vector&lt;int&gt; const magnitudes = {1000000000, 1000000, 1000, 1}; std::vector&lt;std::string&gt; const magnitude_names = {"Billion", "Million", "Thousand", ""}; std::vector&lt;std::string&gt; const number_names = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; std::vector&lt;std::string&gt; const tens_group_names = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; std::vector&lt;std::string&gt; const teens_names = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; std::string name_for_group_of_3(int group); std::string join_vector(std::vector&lt;std::string&gt; vector, std::string joiner); // -1 -&gt; "Negative One" // 0 -&gt; "Zero" int main() { int input; while (1) { std::cout &lt;&lt; "Input: "; std::cin &gt;&gt; input; if (input == 0) { std::cout &lt;&lt; "Zero" &lt;&lt; "\n"; continue; } std::vector&lt;std::string&gt; result; if (input &lt; 0) { input *= -1; result.push_back("Negative"); } for (int i = 0; i &lt; magnitudes.size(); i++) { int magnitude = magnitudes[i]; if (input / magnitude &gt; 0) { result.push_back(name_for_group_of_3(input / magnitude)); result.push_back(magnitude_names[i]); } input %= magnitude; } std::cout &lt;&lt; join_vector(result, " ") &lt;&lt; "\n"; } } // 0 -&gt; "" // 1 -&gt; "One" // 10 -&gt; "Ten" // 15 -&gt; "Fifteen" // 34 -&gt; "Thirty Four" // 456 -&gt; "Four Hundred Fifty Six" std::string name_for_group_of_3(int group) { std::vector&lt;std::string&gt; result; // group should be 0...999 if (group &lt; 0 || group &gt; 999) { throw "Bad grouping provided!"; } // Handle hundreds if (group / 100 &gt; 0) { result.push_back(number_names[group / 100] + " Hundred"); } int double_digits = group % 100; // Handle special case for 11...19 if (double_digits &gt;= 10 &amp;&amp; double_digits &lt; 20) { result.push_back(teens_names[double_digits % 10]); } else { // Handle tens group if (double_digits / 10 &gt; 0) { result.push_back(tens_group_names[double_digits / 10]); } // Handle ones if (double_digits % 10 &gt; 0) { result.push_back(number_names[double_digits % 10]); } } return join_vector(result, " "); } std::string join_vector(std::vector&lt;std::string&gt; vector, std::string joiner) { std::string str_result; for (int i = 0; i &lt; vector.size(); i++) { str_result += vector[i]; if (i &lt; vector.size()-1) { str_result += joiner; } } return str_result; } </code></pre> <p>Notes &amp; specific questions:</p> <ul> <li>Compiling with <code>g++ --std=c++11 main.cpp</code></li> <li>I can run this on the first 10000 integers 0.15s on my '15 MacBook Pro, roughly 15µs per run. Is this reasonable performance?</li> <li>I opted to build vectors of strings, then join them together later, mostly to simplify dealing with the details of space placement. This feels cleaner to me, do you agree? Am I losing significant perf by using vectors vs. string concat?</li> <li>Is it evil to be modifying <code>input</code> as I do during <code>main</code>, with <code>input %= magnitude;</code>? It feels a bit odd to modify the original user input.</li> <li>Is <code>vector</code> a terrible argument name in <code>join_vector</code>?</li> </ul> <p>I, of course, don't really know what else to ask - appreciate any &amp; all pointers!</p>
[]
[ { "body": "<h1>General</h1>\n\n<p>Compile with <code>-Wall -Wextra -pedantic-errors</code>. Warnings are preferable to runtime problems. Sometimes I also compile with <code>-ftrapv</code> to avoid signed overflow.</p>\n\n<p>You are doing much of the work inside <code>main</code>. This violates the one responsibility principle. Consider extracting a function <code>to_English</code> to do the actual work. Also, your program becomes clueless after reaching EOF or invalid input. A better <code>main</code> function looks like:</p>\n\n<pre><code>int main()\n{\n for (int num; std::cout &lt;&lt; \"Input: \", std::cin &gt;&gt; num;)\n std::cout &lt;&lt; to_English(num) &lt;&lt; \"\\n\";\n}\n</code></pre>\n\n<p>In this case, the input process is simple, so I put it in the loop condition. You may want to extract as a separate <code>get_number</code> function for more sophisticated input.</p>\n\n<p>You do not need to store the strings in vectors. Just concatenate them in place.</p>\n\n<h1>Code</h1>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n</code></pre>\n\n<p>You are missing <code>#include &lt;string&gt;</code>.</p>\n\n<pre><code>std::vector&lt;int&gt; const magnitudes = {1000000000, 1000000, 1000, 1};\n</code></pre>\n\n<p>Using <code>int</code> to hold values outside of the range <span class=\"math-container\">\\$-32\\,768 \\le n &lt; 32\\,768\\$</span> is nonportable. Use, for instance, <code>int_least32_t</code>, instead. (You need to <code>#include &lt;cstdint&gt;</code>) Write an alias for this to express the intent more explicitly: <code>using number_t = std::int_least32_t</code>, and use it consistently throughout the code.</p>\n\n<pre><code>std::string name_for_group_of_3(int group);\n</code></pre>\n\n<p>The name of the function is not entirely clear, but I cannot think of a better name either. Maybe add a comment.</p>\n\n<pre><code>std::string join_vector(std::vector&lt;std::string&gt; vector, std::string joiner);\n</code></pre>\n\n<p>Don't pass <code>vector</code>s and <code>string</code>s by value. Pass by const reference instead. Also, <code>join_strings</code> may be a better name in my opinion.</p>\n\n<pre><code>for (int i = 0; i &lt; vector.size(); i++) {\nfor (int i = 0; i &lt; vector.size(); i++) {\nif (i &lt; vector.size()-1) {\n</code></pre>\n\n<p>These lines trigger <code>-Wsign-compare</code>. Use <code>std::size_t</code> or <code>std::vector&lt;std::string&gt;::size_type</code> instead of <code>int</code>. <a href=\"https://stackoverflow.com/a/484492\">Use <code>++i</code> instead of <code>i++</code></a>.</p>\n\n<pre><code>// group should be 0...999\nif (group &lt; 0 || group &gt; 999) {\n throw \"Bad grouping provided!\";\n}\n</code></pre>\n\n<p>Never throw a string literal. Throw a <code>std::invalid_argument</code> instead. Also, an assertion may be better for logical errors.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T09:51:48.307", "Id": "225078", "ParentId": "225070", "Score": "4" } } ]
{ "AcceptedAnswerId": "225078", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T03:17:56.390", "Id": "225070", "Score": "7", "Tags": [ "c++", "beginner", "programming-challenge", "numbers-to-words" ], "Title": "CtCI 16.8: Integer to English phrase in C++" }
225070
<p>I have completed this E-Commerce Mock App in Console C# which I used object to store the data to apply some C# OOP and LINQ techniques. Since it is just a mock version, features are reduced to the minimum.</p> <p>Any code review on coding style or code refactoring will be appreciated.</p> <p>I have created 3 projects in this solution structure:</p> <ul> <li><code>ECommerceDomainModelEntities</code> - poco classes</li> <li><code>ECommerceLib</code> - library</li> <li><code>ECommerceConsoleUI</code> - Console UI (Entry Point)</li> </ul> <p><strong>ECommerceDomainModelEntities Project</strong></p> <pre><code>public class Customer { public int CustomerId { get; set; } public string Username { get; set; } public string Password { get; set; } public string FullName { get; set; } public string Email { get; set; } public string Address { get; set; } } public class OrderDetails { public int OrderDetailsId { get; set; } public int Customer_Id { get; set; } public int ProductId { get; set; } public int QuantityOrder { get; set; } public decimal TotalAmount { get; set; } } public class Product { public int Id { get; set; } public string ProductName { get; set; } public decimal UnitPrice { get; set; } } </code></pre> <p><strong>ECommerceLib Project</strong></p> <pre><code>public static class Utility { private static CultureInfo culture = new CultureInfo("ms-MY"); public static void PrintMessage(string text, ConsoleColor color) { Console.ForegroundColor = color; Console.WriteLine(text); Console.ResetColor(); } public static string FormatAmount(this decimal amt) { return string.Format(culture, "{0:C2}", amt); } public static string ReadPassword() { string password = ""; while (true) { ConsoleKeyInfo key = Console.ReadKey(true); switch (key.Key) { case ConsoleKey.Escape: return null; case ConsoleKey.Enter: return password; case ConsoleKey.Backspace: password = password.Substring(0, (password.Length - 1)); Console.Write("\b \b"); break; default: password += key.KeyChar; Console.Write("*"); break; } } } public static void PrintDotAnimation(int timer = 20) { Console.WriteLine(""); for (var x = 0; x &lt; timer; x++) { Console.Write("."); Thread.Sleep(100); } Console.WriteLine(); } } </code></pre> <p><strong>ECommerceConsoleUI Project</strong></p> <pre><code>public class eCommerce { private const decimal deliverCharges = 10.00M; private List&lt;Customer&gt; validCustomers; private readonly List&lt;OrderDetails&gt; shoppingCart; private List&lt;Product&gt; productList; public eCommerce() { InitializeCustomerList(); InitializeProductList(); shoppingCart = new List&lt;OrderDetails&gt;(); Console.Title = "Azada e-Commerce App"; } public void Execute() { var valid_Customer = Login(); while (true) { Console.Clear(); Console.WriteLine($"Login as {valid_Customer.FullName}"); Console.WriteLine("\nAzada E-Commerce App"); Console.WriteLine("1. Browse all products"); Console.WriteLine("2. View shopping cart"); Console.WriteLine("3. Logout"); Console.Write("Enter your option: "); string opt = Console.ReadLine(); switch (opt) { case "1": BrowseProducts(); AddShoppingCart(valid_Customer); break; case "2": ViewShoppingCart(valid_Customer); break; case "3": Utility.PrintDotAnimation(); valid_Customer = null; shoppingCart.Clear(); Execute(); break; default: Utility.PrintMessage("Invalid option.", ConsoleColor.Red); break; } Console.ReadKey(); } } private Customer Login() { while (true) { var userInput = new Customer(); Console.Clear(); Console.Write("Username: "); userInput.Username = Console.ReadLine(); Console.Write("Password: "); userInput.Password = Utility.ReadPassword(); var validCustomer = validCustomers .Where(c =&gt; c.Username.Equals(userInput.Username)) .Where(c =&gt; c.Password.Equals(userInput.Password)) .FirstOrDefault(); if (validCustomer != null) { Utility.PrintDotAnimation(); return validCustomer; } Utility.PrintMessage("\nInvalid username or password.", ConsoleColor.Red); Console.ReadKey(); } } private void InitializeCustomerList() { validCustomers = new List&lt;Customer&gt;(){ new Customer(){ CustomerId = 1, Username = "john", Password = "john123", FullName = "John Wong", Email = "john@gmail.com", Address = "8, Jalan Emas, 58000, Kuala Lumpur." }, new Customer(){ CustomerId = 2, Username = "mike", Password = "mike123", FullName = "Mike Lee", Email = "mike@gmail.com", Address = "13, Jalan Api, 55100, Kuala Lumpur." } }; } private void InitializeProductList() { productList = new List&lt;Product&gt;() { new Product(){ Id = 2, ProductName = "MSI Laptop GL63 8RCS 058MY", UnitPrice = 2999.00M}, new Product(){ Id = 5, ProductName = "MSI Laptop GL63 8RC 057MY", UnitPrice = 3799.00M}, new Product(){ Id = 12, ProductName = "Logitech M330 Wireless Mouse", UnitPrice = 59.00M}, new Product(){ Id = 13, ProductName = "Mechanical Keyboard with Backlight", UnitPrice = 160.00M}, new Product(){ Id = 16, ProductName = "Dell Wireless Keyboard and Mouse Combo ", UnitPrice = 70.00M} }; } private void BrowseProducts() { Console.Clear(); var table = new ConsoleTable("Product Id", "Product Name", "Unit Price"); foreach (var product in productList) table.AddRow(product.Id, product.ProductName, Utility.FormatAmount(product.UnitPrice)); table.Write(); } private void AddShoppingCart(Customer valid_Customer) { Console.Write("Enter the product ID you want to buy: "); int productId = int.Parse(Console.ReadLine()); var selectedProduct = productList.FirstOrDefault(p =&gt; p.Id == productId); if (selectedProduct == null) { Utility.PrintMessage("Product not found.", ConsoleColor.Red); return; } Console.Write("Enter quantity to buy: "); int quantity = int.Parse(Console.ReadLine()); var order = new OrderDetails(); order.Customer_Id = valid_Customer.CustomerId; order.ProductId = productId; order.QuantityOrder = quantity; order.TotalAmount = quantity * selectedProduct.UnitPrice; shoppingCart.Add(order); Utility.PrintMessage($"{selectedProduct.ProductName} added into shopping cart.", ConsoleColor.Yellow); } private void ViewShoppingCart(Customer valid_Customer) { Console.Clear(); // inner join orderdetail and product. var shoppingCart2 = from s in shoppingCart join p in productList on s.ProductId equals p.Id select new { p.ProductName, p.UnitPrice, s.QuantityOrder, s.TotalAmount }; var totalOrderAmount = 0M; totalOrderAmount = shoppingCart.Sum(s =&gt; s.TotalAmount); var table = new ConsoleTable("Product Name", "Price", "Quantity", "Total"); if (shoppingCart2.ToList().Count == 0) { Utility.PrintMessage("Shopping cart is empty. Go to browse products.", ConsoleColor.Yellow); return; } Console.WriteLine("Total Items in Shopping Cart: " + shoppingCart2.Count()); foreach (var item in shoppingCart2) table.AddRow(item.ProductName, Utility.FormatAmount(item.UnitPrice), item.QuantityOrder, Utility.FormatAmount(item.TotalAmount)); table.Options.EnableCount = false; table.Write(); Console.WriteLine("------------------------------------------"); Console.WriteLine("Delivery charges: " + Utility.FormatAmount(deliverCharges)); Console.WriteLine("Total Order Amount: " + Utility.FormatAmount(totalOrderAmount + deliverCharges)); Console.WriteLine("------------------------------------------"); Console.WriteLine("Delivery Address: " + valid_Customer.Address); Console.WriteLine("\n1. Confirm order and proceed to make payment."); Console.WriteLine("2. Clear shopping cart."); Console.WriteLine("3. Back."); Console.Write("Enter option: "); string opt2 = Console.ReadLine(); switch (opt2) { case "1": Console.WriteLine("\nChoose payment method:"); Console.WriteLine("1. Cash on delivery (COD)"); Console.WriteLine("2. Credit Card"); Console.WriteLine("3. Online eBanking"); Console.Write("Enter option: "); Console.ReadKey(); Console.WriteLine("\n\nRedirecting to payment gateway."); Utility.PrintDotAnimation(); Console.WriteLine("Info: This E-Commerce simulation app ends here...."); // You can send email to the customer upon payment. break; case "2": shoppingCart.Clear(); Utility.PrintMessage("Shopping cart is empty. Go to browse products.", ConsoleColor.Yellow); break; case "3": break; default: Utility.PrintMessage("Invalid option.", ConsoleColor.Red); break; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T06:49:44.240", "Id": "436780", "Score": "2", "body": "We have asked you before to split UI from business logic: https://codereview.stackexchange.com/questions/224139/console-based-blackjack-in-c-follow-up. And you said you were going to follow-up on that advise, but you haven't. The problem with this code, is that it's one big convoluted code mess. There is no way to reuse your business logic with another UI or as dependency of another API. I would have hoped you would have addressed this by now :-(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T07:47:39.403", "Id": "436782", "Score": "0", "body": "Yeah, I still unable to split it yet. I also didn't create any Web API for it. Any other comment besides that?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T06:16:48.847", "Id": "225073", "Score": "1", "Tags": [ "c#", "console", "linq", "e-commerce" ], "Title": "E-Commerce Mock App in Console" }
225073
<p>The task is to enhance the <code>Enumerable</code> module with a method <code>nth()</code>.</p> <p>The method shall create a new list, which contains every nth-element of the object, when it is invoked.</p> <p>For example: <code>[2, 4, 6, 8, 10, 12].nth(2)</code> shall return <code>[4, 8, 12]</code></p> <p>Here's my implementation:</p> <pre class="lang-rb prettyprint-override"><code>module Enumerable def nth(n) i = 0 ordinal = 1 relevant_iteration = n * ordinal self.select do | num | i += 1 if i == relevant_iteration ordinal += 1 relevant_iteration = ordinal * n num end end end end print [2, 4, 6, 8, 10, 12].nth(2) # =&gt; [4, 8, 12] print "\n" print (4..12).nth(3) # =&gt; [6, 9, 12] </code></pre> <p>It works as expected and it has passed the unit-tests.</p> <p>But: My solution isn't elegant. At least that's my own impression.</p> <ul> <li>Could my code be improved in regard to more compactness?</li> <li>Is my code readable and understandable? </li> <li>What could be improved?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T18:39:55.833", "Id": "437841", "Score": "0", "body": "This isn't exactly an answer because I feel like you're looking for something more complicated/interesting, but you could also do this with `def nth(n); step(n).to_a; end`" } ]
[ { "body": "<h2>nth slicing</h2>\n\n<p>Perhaps you could use a slice with map instead.</p>\n\n<pre><code>module Enumerable\n def nth(n)\n self.each_slice(n).select{|c| c.length == n}.map(&amp;:last) \n end\nend\n</code></pre>\n\n<h3>unit tests</h3>\n\n<pre><code>print [2, 4, 6, 8, 10, 12].nth(3) # =&gt; [6, 12]\nprint \"\\n\"\nprint [2, 4, 6, 8, 10].nth(3) # =&gt; [6]\nprint \"\\n\"\nprint [2, 4, 6, 8].nth(3) # =&gt; [6]\nprint \"\\n\"\nprint [2, 4, 6].nth(3) # =&gt; [6]\nprint \"\\n\"\nprint [2, 4].nth(3) # =&gt; []\nprint \"\\n\"\n</code></pre>\n\n<hr>\n\n<h2>Rubocop Report</h2>\n\n<p>Skipping an iteration should be done like this..</p>\n\n<pre><code> next unless i == relevant_iteration\n\n ordinal += 1\n relevant_iteration = ordinal * n\n</code></pre>\n\n<p>rather than..</p>\n\n<blockquote>\n<pre><code>if i == relevant_iteration\n ordinal += 1\n relevant_iteration = ordinal * n\n</code></pre>\n</blockquote>\n\n<p>General Guidelines:</p>\n\n<ul>\n<li>use 2 spaces for indentation</li>\n<li><a href=\"https://www.mikeperham.com/2018/02/28/ruby-optimization-with-one-magic-comment/\" rel=\"nofollow noreferrer\">frozen string</a></li>\n<li><code>n</code> as parameter name: min length should be 3 -> <code>takeIndex</code> instead?</li>\n</ul>\n\n<p>Refactored</p>\n\n<pre><code># frozen_string_literal: true\n\nmodule Enumerable\n def nth(takeIndex)\n i = 0\n ordinal = 1\n relevant_iteration = takeIndex * ordinal\n\n self.select do |num|\n i += 1\n\n next unless i == relevant_iteration\n\n ordinal += 1\n relevant_iteration = ordinal * takeIndex\n\n num\n end\n end\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T09:28:32.967", "Id": "436786", "Score": "2", "body": "You seem to have experience with a broad variety of programming languages. I really appreciate your participation here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T09:30:30.370", "Id": "436787", "Score": "0", "body": "@πάνταῥεῖ Thanks for this welcoming feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T05:37:30.933", "Id": "436887", "Score": "1", "body": "I dunno about renaming `n` to `skip`. In my mind, I would assume that `skip=1` means \"every second element\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T14:26:24.873", "Id": "436942", "Score": "0", "body": "@200_success you are right, skip is not the best name. I would personally accept _n_. But Ruby guidelines stipulate longer variable names." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T08:58:20.447", "Id": "225077", "ParentId": "225076", "Score": "3" } } ]
{ "AcceptedAnswerId": "225077", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T08:48:59.177", "Id": "225076", "Score": "2", "Tags": [ "beginner", "ruby", "iterator" ], "Title": "Add method to Ruby's Enumerable module that produces every nth element" }
225076
<p>My goal is to write a CPU Scheduling Simulator in C++ using the STL features as far as possible. So far, I have only written the code for FCFS and have not provided any input method.</p> <p>What sticks out most to me is the definition of the <code>process</code> class. The way I have designed the program, there is very poor encapsulation. Looking at my current situation, I have only two solutions in mind:</p> <ol> <li><p>Make all data members private. Provide accessors for PID, Arrival Time and Burst Time and mutators for the rest. However, I fear this would make my code bloated and also the use of mutators would only break encapsulation.</p></li> <li><p>Make <code>FCFS()</code>, <code>displayResult()</code> and any other algorithms that I add <code>friend</code>s of the <code>process</code> class. This allows me to control the encapsulation to a certain extent so I like this one.</p></li> </ol> <p>Another thing I tried to do was make the PID, Arrival Time and Burst Time variables <code>const</code> and public. This allowed algorithms to read their values but not modify them. However, the code wouldn't compile because <code>const</code> members aren't default assignable. </p> <p>I would like suggestions as to how I can solve the above mentioned problem and also how I can use the STL more effectively to make my code more expressive.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;limits&gt; constexpr int notYetComputed = std::numeric_limits&lt;unsigned int&gt;::max(); struct process { unsigned int m_procId; unsigned int m_arrivalTime; unsigned int m_burstTime; unsigned int m_responseTime; unsigned int m_completionTime; unsigned int m_turnaroundTime; unsigned int m_waitingTime; process(unsigned int pid, unsigned int at, unsigned int bt) : m_procId {pid}, m_arrivalTime {at}, m_burstTime {bt} { m_waitingTime = m_turnaroundTime = m_completionTime = m_responseTime = notYetComputed; } }; void displayResult(const std::vector&lt;process&gt;&amp; procs) { for(auto&amp; x : procs) std::cout &lt;&lt; "PID: " &lt;&lt; x.m_procId &lt;&lt; ", " &lt;&lt; "Waiting Time: " &lt;&lt; x.m_waitingTime &lt;&lt; ", " &lt;&lt; "Turnaround Time: " &lt;&lt; x.m_turnaroundTime &lt;&lt; ", " &lt;&lt; "Response Time: " &lt;&lt; x.m_responseTime &lt;&lt; ", " &lt;&lt; "Completion Time: " &lt;&lt; x.m_completionTime &lt;&lt; "\n"; } void FCFS(std::vector&lt;process&gt;&amp; procList) { //Sort based on arrival order. Use PID in case of same arrival time. auto arrivalOrder = [] (const process&amp; p1, const process&amp; p2) { if(p1.m_arrivalTime &lt; p2.m_arrivalTime) return true; if(p1.m_arrivalTime == p2.m_arrivalTime) return (p1.m_procId &lt; p2.m_procId); return false; }; std::sort(procList.begin(), procList.end(), arrivalOrder); unsigned int clock {0}; auto computeResult = [&amp;clock] (process&amp; pr) { pr.m_responseTime = clock - pr.m_arrivalTime; pr.m_waitingTime = (pr.m_turnaroundTime = (pr.m_completionTime = (clock += pr.m_burstTime)) - pr.m_arrivalTime) - pr.m_burstTime; }; std::for_each(procList.begin(), procList.end(), computeResult); } int main() { std::vector&lt;process&gt; procs {{0,0,5}, {1,1,3}, {2,2,8}, {3,3,6}}; FCFS(procs); //Sort based on PID before showing result std::sort(procs.begin(), procs.end(), [](const process&amp; p1, const process&amp; p2) { return p1.m_procId &lt; p2.m_procId; }); displayResult(procs); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T10:14:20.357", "Id": "436791", "Score": "3", "body": "If you can't change `const` values, there's probably a flaw in your design. Don't try to workaround this using a `const_cast<>` of such. Fix your overall design. What is _FCFS_ BTW?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T10:34:46.840", "Id": "436792", "Score": "0", "body": "I understand this question is not well received here. My fault entirely. Is this something more suited to stackexchange as this program is not really complete?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T11:10:52.570", "Id": "436796", "Score": "2", "body": "_\"as this program is not really complete?\"_ Yes that's the culprit. Don't ask for features not yet implemented or errors you get with these. It's well explained in the [help]." } ]
[ { "body": "<p>Despite its being incomplete, I think there are a few points that can be made about the current code.</p>\n\n<h3>Naming</h3>\n\n<p>Naming is always difficult, and this gives quite a few examples. Somebody who already knows the purpose of the code can probably figure out that \"FCFS\" means \"first come, first served\", but to anybody else it's probably pretty opaque.</p>\n\n<p>At least to me, a name like <code>computeResult</code> is more problematic though. This could apply about equally to essentially any function in existence, so it tells us nothing about what this particular <code>computeResult</code> actually is or does.</p>\n\n<h3>Library Usage</h3>\n\n<p>Your <code>displayResult</code> basically writes a collection of <code>process</code> objects to a stream. I'd prefer a stream inserter that writes a single object to a stream, then using a standard alorithm (or ranged for loop) to apply that to a collection of objects.</p>\n\n<pre><code>std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, process const &amp;p) { \n\n return os &lt;&lt; \"PID: \" &lt;&lt; x.m_procId &lt;&lt; \", \"\n &lt;&lt; \"Waiting Time: \" &lt;&lt; x.m_waitingTime &lt;&lt; \", \"\n &lt;&lt; \"Turnaround Time: \" &lt;&lt; x.m_turnaroundTime &lt;&lt; \", \"\n &lt;&lt; \"Response Time: \" &lt;&lt; x.m_responseTime &lt;&lt; \", \"\n &lt;&lt; \"Completion Time: \" &lt;&lt; x.m_completionTime;\n}\n</code></pre>\n\n<h3>Structure</h3>\n\n<p>It seems to me that your <code>FCFS</code> combines what are really a couple of separate functions. One is deciding the order in which to schedule the tasks. The other is going through the tasks in their chosen order, and setting the member variables for each. The initial <code>sort</code> is the only part that's really devoted to the <code>first-come-first-served</code> part. The rest would apply equally to other orders of execution.</p>\n\n<p>As such, it seems to me that this should be split into two separate things. This could be done in a number of different ways. One would be to require the code that currently calls <code>FCFS</code> to make two separate calls, one to sort the tasks, and the other to simulate executing them. Another (that I think I'd generally prefer) would be for the caller to pass a comparator object that specifies the order it wants.</p>\n\n<pre><code>template &lt;class Order&gt;\nvoid schedule(std::vector&lt;process&gt; &amp;processes, Order order) { \n\n std::sort(processes.begin(), processes.end(), order);\n\n unsigned int clock {0};\n auto computeResult = [&amp;clock] (process&amp; pr) {\n pr.m_responseTime = clock - pr.m_arrivalTime;\n pr.m_waitingTime = (pr.m_turnaroundTime = \n (pr.m_completionTime = (clock += pr.m_burstTime)) - pr.m_arrivalTime)\n - pr.m_burstTime;\n };\n\n std::for_each(procList.begin(), procList.end(), computeResult);\n}\n</code></pre>\n\n<p>Another that might be worth considering would be to have the <code>process</code> class itself specify the sorting order by defining <code>bool operator&lt;</code> for itself. This would be particularly attractive if you were going to use an inheritance hierarchy. In this case, the base class would probably define <code>operator&lt;</code> as a pure virtual function, and each derived <code>process</code> class would define <code>operator&lt;</code> to specify the order it's going to use. This strikes me as problematic though--it would allow things like passing one vector of <code>process</code>es to the scheduler, where different <code>process</code> objects tried to specify different scheduling algorithms. Unless you really want that (and are prepared for the complexity it's likely to add) this probably isn't the best option.</p>\n\n<p>In some cases this would be a pointless embellishment, but this is a scheduling simulator, so it seems nearly inevitable that you'd want to test different scheduling algorithms.</p>\n\n<h3>Clarity</h3>\n\n<p>IMO, one of the core computations is quite a bit less readable than it should be:</p>\n\n<pre><code> pr.m_waitingTime = (pr.m_turnaroundTime = \n (pr.m_completionTime = (clock += pr.m_burstTime)) - pr.m_arrivalTime)\n - pr.m_burstTime;\n</code></pre>\n\n<p>At least in my opinion, it would probably be better to break this up into a couple of pieces:</p>\n\n<pre><code>pr.m_waitingTime = clock - pr.m_arrivalTime;\npr.m_completionTime = clock + pr.m_burstTime;\npr.m_turnaroundTime = pr.m_completionTime - pr.m_arrivalTime;\nclock += pr.m_burstTime;\n</code></pre>\n\n<p>[I think I may have gotten that a little wrong--as it stands, waiting time seems to be the same as response time--sorry, I really did find the nested assignments confusing.]</p>\n\n<h3>Encapsulation</h3>\n\n<p>Being tempted to provide accessors for member variables usually points toward having gotten the functionality in the wrong places. At least to me, that seems to be the case here.</p>\n\n<p>At least in my opinion, most of the code to access the members of <code>process</code> should be in <code>process</code> itself. I'd have the <code>scheduler</code> tell the <code>process</code> to <code>execute</code> at a particular time, and the <code>process</code> would keep track of how that worked out for it:</p>\n\n<pre><code>class Process { \n unsigned int m_procId;\n unsigned int m_arrivalTime;\n unsigned int m_burstTime;\n\n unsigned int m_responseTime;\n unsigned int m_completionTime;\n unsigned int m_turnaroundTime;\n unsigned int m_waitingTime;\npublic:\n process(unsigned int pid, unsigned int at, unsigned int bt)\n : m_procId {pid}, m_arrivalTime {at}, m_burstTime {bt}\n {\n m_waitingTime = m_turnaroundTime = m_completionTime = m_responseTime = notYetComputed;\n }\n\n int execute(int clock) { \n m_responseTime = clock - m_arrivalTime;\n m_waitingTime = clock - m_arrivalTime;\n m_completionTime = clock + m_burstTime;\n m_turnaroundTime = m_completionTime - m_arrivalTime;\n return m_burstTime;\n }\n};\n</code></pre>\n\n<p>This makes our scheduler look something like this:</p>\n\n<pre><code>template &lt;class Order&gt;\nvoid schedule(std::vector&lt;process&gt; &amp;processes, Order order) { \n\n std::sort(processes.begin(), processes.end(), order);\n\n unsigned int clock {0};\n\n for (auto &amp;process : processes)\n clock += process.execute(clock);\n}\n</code></pre>\n\n<p>Now we have a clear separation of concerns. The scheduler is responsible for telling each task when to start executing. The task is responsible for doing its own book-keeping based on when it was told to execute. It then tells the scheduler how much clock time it used.</p>\n\n<p>Accessors tend to give what I'd term \"fake\" encapsulation--we've hidden the variables themselves, but the client code still knows about the internals of what it's working with. </p>\n\n<p>What we have here is closer to what I'd term \"honest\" encapsulation: we've created a really narrow interface where the scheduler and the process only know the tiniest bit about each other: the scheduler knows how to <code>execute</code> a <code>process</code>, and the <code>process</code> knows when it executes, it has to tell the caller how much clock time it used. But that's it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T15:48:15.140", "Id": "225093", "ParentId": "225079", "Score": "1" } } ]
{ "AcceptedAnswerId": "225093", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T10:08:19.157", "Id": "225079", "Score": "-2", "Tags": [ "c++", "object-oriented", "design-patterns" ], "Title": "Simple First Come First Serve Scheduling Simulator" }
225079
<p>This is the second version of my <code>FeatureToggle</code> service (see <a href="https://codereview.stackexchange.com/questions/220938/toggle-any-application-feature-on-or-off">previous question</a>). It still has the same purpose which is to help control whether a feature is <code>ON</code> or <code>OFF</code> and provide an alternative funtionality.</p> <h3>Changes</h3> <p>What is different in this version?</p> <ul> <li>I created a <code>FeatureIdentifier</code> that replaces the previous <code>string</code> <em>token</em> as a feature-key</li> <li>I created decorators for each of the features of the previous <em>god-class</em> <code>FeatureToggle</code> <ul> <li><code>FeatureToggle</code> - executes <code>body</code> when a feature is <code>ON</code> or <code>fallback</code> when it's <code>OFF</code></li> <li><code>FeatureToggler</code> - can automatically toggle between <code>ON/OFF</code> after each execution or only once with <code>ToggleOnce</code> option</li> <li><code>FeatureTelemetry</code> - logs feature statistics like execution time and whether its options are dirty</li> </ul></li> <li>I moved feature-options to the new <code>IFeatureOptionRepository</code> and created multiple decorators for new features <ul> <li><code>FeatureOptionRepository</code> - stores feature options in a dictionary and saves feature-option changes by setting <code>Saved</code> flag and removing <code>Dirty</code>. I added <code>ReaderWriterLockSlim</code> to it because I'm using it with a web-service that toggles features at runtime based on the request</li> <li><code>FeatureOptionRepositoryDecorator</code> - simplifies creating decorators by providing default and overridable implementations</li> <li><code>FeatureOptionFallback</code> - provides default feature-option when the current one is <code>None</code></li> <li><code>FeatureOptionLock</code> - prevents accidental feature-options changes</li> </ul></li> </ul> <hr> <h3>Core</h3> <p>The new <code>FeatureIdentifier</code> that currently has two properties <code>Name</code> and <code>Description</code> (this I might use later).</p> <pre><code>public class FeatureIdentifier : IEquatable&lt;FeatureIdentifier&gt;, IEquatable&lt;string&gt; { public FeatureIdentifier([NotNull] string name) { Name = name ?? throw new ArgumentNullException(nameof(name)); } [AutoEqualityProperty] public string Name { get; } public string Description { get; set; } public override string ToString() =&gt; Name; public override int GetHashCode() =&gt; AutoEquality&lt;FeatureIdentifier&gt;.Comparer.GetHashCode(this); public override bool Equals(object obj) =&gt; obj is FeatureIdentifier fn &amp;&amp; Equals(fn); public bool Equals(FeatureIdentifier featureIdentifier) =&gt; AutoEquality&lt;FeatureIdentifier&gt;.Comparer.Equals(this, featureIdentifier); public bool Equals(string name) =&gt; Equals(this, new FeatureIdentifier(name)); public static implicit operator FeatureIdentifier(string name) =&gt; new FeatureIdentifier(name); public static implicit operator FeatureIdentifier(Selector selector) =&gt; new FeatureIdentifier(selector.ToString()); public static implicit operator string(FeatureIdentifier featureIdentifier) =&gt; featureIdentifier.ToString(); } </code></pre> <p>The <code>FeatureToggle</code> with its decorators:</p> <pre><code>public interface IFeatureToggle { IFeatureOptionRepository Options { get; } Task&lt;T&gt; ExecuteAsync&lt;T&gt;(FeatureIdentifier name, Func&lt;Task&lt;T&gt;&gt; body, Func&lt;Task&lt;T&gt;&gt; fallback); } public class FeatureToggle : IFeatureToggle { public FeatureToggle(IFeatureOptionRepository options) { Options = options; } public IFeatureOptionRepository Options { get; } public async Task&lt;T&gt; ExecuteAsync&lt;T&gt;(FeatureIdentifier name, Func&lt;Task&lt;T&gt;&gt; body, Func&lt;Task&lt;T&gt;&gt; fallback) { // Not catching exceptions because the caller should handle them. return await (this.IsEnabled(name) ? body : fallback)().ConfigureAwait(false); } } public class FeatureToggler : IFeatureToggle { private readonly IFeatureToggle _featureToggle; public FeatureToggler(IFeatureToggle featureToggle) { _featureToggle = featureToggle; } public IFeatureOptionRepository Options =&gt; _featureToggle.Options; public Task&lt;T&gt; ExecuteAsync&lt;T&gt;(FeatureIdentifier name, Func&lt;Task&lt;T&gt;&gt; body, Func&lt;Task&lt;T&gt;&gt; fallback) { try { return _featureToggle.ExecuteAsync(name, body, fallback); } finally { if (Options[name].Contains(FeatureOption.Toggle)) { Options.Toggle(name); if (Options[name].Contains(FeatureOption.ToggleOnce)) { Options[name] = Options[name].RemoveFlag(FeatureOption.Toggle | FeatureOption.ToggleOnce); Options.SaveChanges(name); } } } } } public class FeatureTelemetry : IFeatureToggle { private readonly ILogger _logger; private readonly IFeatureToggle _featureToggle; public FeatureTelemetry(ILogger&lt;FeatureTelemetry&gt; logger, IFeatureToggle featureToggle) { _logger = logger; _featureToggle = featureToggle; } public IFeatureOptionRepository Options =&gt; _featureToggle.Options; public async Task&lt;T&gt; ExecuteAsync&lt;T&gt;(FeatureIdentifier name, Func&lt;Task&lt;T&gt;&gt; body, Func&lt;Task&lt;T&gt;&gt; fallback) { if (Options[name].Contains(FeatureOption.Telemetry)) { using (_logger.BeginScope().CorrelationHandle(nameof(FeatureTelemetry)).AttachElapsed()) { _logger.Log(Abstraction.Layer.Service().Meta(new { FeatureName = name }).Trace()); if (_featureToggle.IsDirty(name)) { _logger.Log(Abstraction.Layer.Service().Meta(new { CustomFeatureOptions = _featureToggle.Options[name] })); } return await _featureToggle.ExecuteAsync(name, body, fallback); } } else { return await _featureToggle.ExecuteAsync(name, body, fallback); } } } </code></pre> <p>The <code>FeatureOptionRepository</code> with its decorators:</p> <pre><code>public interface IFeatureOptionRepository { // Gets or sets feature options. [NotNull] FeatureOption this[FeatureIdentifier name] { get; set; } // Saves current options as default. void SaveChanges(FeatureIdentifier name = default); } public class FeatureOptionRepository : IFeatureOptionRepository { private readonly Dictionary&lt;FeatureIdentifier, FeatureOption&gt; _options; private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(); public FeatureOptionRepository() { _options = new Dictionary&lt;FeatureIdentifier, FeatureOption&gt;(); } public FeatureOption this[FeatureIdentifier name] { get { _lock.EnterReadLock(); try { return _options.TryGetValue(name, out var option) ? option : FeatureOption.None; } finally { _lock.ExitReadLock(); } } set { _lock.EnterWriteLock(); try { _options[name] = value.RemoveFlag(FeatureOption.Saved).SetFlag(FeatureOption.Dirty); } finally { _lock.ExitWriteLock(); } } } public void SaveChanges(FeatureIdentifier name = default) { _lock.EnterWriteLock(); try { var names = name is null ? _options.Keys.ToList() // &lt;-- prevents collection-modified-exception : new List&lt;FeatureIdentifier&gt; { name }; foreach (var n in names) { _options[n] = _options[n].RemoveFlag(FeatureOption.Dirty).SetFlag(FeatureOption.Saved); } } finally { _lock.ExitWriteLock(); } } } public abstract class FeatureOptionRepositoryDecorator : IFeatureOptionRepository { protected FeatureOptionRepositoryDecorator(IFeatureOptionRepository instance) { Instance = instance; } protected IFeatureOptionRepository Instance { get; } public virtual FeatureOption this[FeatureIdentifier name] { get =&gt; Instance[name]; set =&gt; Instance[name] = value; } public virtual void SaveChanges(FeatureIdentifier name = default) =&gt; Instance.SaveChanges(); } // Provides default feature-options if not already configured. public class FeatureOptionFallback : FeatureOptionRepositoryDecorator { private readonly FeatureOption _defaultOption; public FeatureOptionFallback(IFeatureOptionRepository options, FeatureOption defaultOption) : base(options) { _defaultOption = defaultOption; } public override FeatureOption this[FeatureIdentifier name] { get =&gt; Instance[name] is var option &amp;&amp; option == FeatureOption.None ? _defaultOption : option; set =&gt; Instance[name] = value; } public class Enabled : FeatureOptionFallback { public Enabled(IFeatureOptionRepository options, FeatureOption other = default) : base(options, FeatureOption.Enabled | (other ?? FeatureOption.None)) { } } } // Locks feature option setter. public class FeatureOptionLock : FeatureOptionRepositoryDecorator { public FeatureOptionLock(IFeatureOptionRepository options) : base(options) { } public override FeatureOption this[FeatureIdentifier name] { get =&gt; Instance[name]; set { if (Instance[name].Contains(FeatureOption.Locked)) { throw new InvalidOperationException($"Cannot set options for feature '{name}' because it's locked."); } Instance[name] = value; } } } </code></pre> <h3>Helpers</h3> <p>The most common operations are made convenient with these extensions:</p> <pre><code>public static class FeatureServiceHelpers { public static bool IsEnabled(this IFeatureToggle toggle, FeatureIdentifier name) { return toggle.Options[name].Contains(FeatureOption.Enabled); } public static bool IsLocked(this IFeatureToggle toggle, FeatureIdentifier name) { return toggle.Options[name].Contains(FeatureOption.Locked); } // Returns True if options are different from default. public static bool IsDirty(this IFeatureToggle toggle, FeatureIdentifier name) { return toggle.Options[name].Contains(FeatureOption.Dirty); } #region Execute public static async Task ExecuteAsync(this IFeatureToggle features, FeatureIdentifier name, Func&lt;Task&gt; body, Func&lt;Task&gt; fallback) { await features.ExecuteAsync&lt;object&gt; ( name, () =&gt; { body(); return default; }, () =&gt; { fallback(); return default; } ); } public static async Task ExecuteAsync(this IFeatureToggle features, FeatureIdentifier name, Func&lt;Task&gt; body) { await features.ExecuteAsync(name, body, () =&gt; Task.FromResult&lt;object&gt;(default)); } public static T Execute&lt;T&gt;(this IFeatureToggle featureToggle, FeatureIdentifier name, Func&lt;T&gt; body, Func&lt;T&gt; fallback) { return featureToggle .ExecuteAsync ( name, () =&gt; body().ToTask(), () =&gt; fallback().ToTask() ) .GetAwaiter() .GetResult(); } public static void Execute(this IFeatureToggle featureToggle, FeatureIdentifier name, Action body, Action fallback) { featureToggle .ExecuteAsync&lt;object&gt; ( name, () =&gt; { body(); return default; }, () =&gt; { fallback(); return default; } ) .GetAwaiter() .GetResult(); } public static void Execute(this IFeatureToggle featureToggle, FeatureIdentifier name, Action body) { featureToggle.Execute(name, body, () =&gt; { }); } public static T Switch&lt;T&gt;(this IFeatureToggle featureToggle, FeatureIdentifier name, T value, T fallback) { return featureToggle.Execute(name, () =&gt; value, () =&gt; fallback); } #endregion public static IFeatureOptionRepository Batch(this IFeatureOptionRepository options, IEnumerable&lt;string&gt; names, FeatureOption featureOption, BatchOption batchOption) { foreach (var name in names) { if (batchOption == BatchOption.Set) { options[name] = options[name].SetFlag(featureOption); } if (batchOption == BatchOption.Remove) { options[name] = options[name].RemoveFlag(featureOption); } } return options; } public static IFeatureToggle Toggle(this IFeatureToggle featureToggle, FeatureIdentifier name) { featureToggle.Options.Toggle(name); return featureToggle; } public static IFeatureOptionRepository Toggle(this IFeatureOptionRepository options, FeatureIdentifier name) { options[name] = options[name].Contains(FeatureOption.Enabled) ? options[name].RemoveFlag(FeatureOption.Enabled) : options[name].SetFlag(FeatureOption.Enabled); return options; } public static IFeatureToggle EnableToggler(this IFeatureToggle featureToggle, FeatureIdentifier name, bool once = true) { featureToggle.Options[name] = featureToggle.Options[name] .SetFlag(FeatureOption.Toggle) .SetFlag(once ? FeatureOption.ToggleOnce : FeatureOption.None); return featureToggle; } } public class BatchOption : Option&lt;BatchOption&gt; { public BatchOption(SoftString name, IImmutableSet&lt;SoftString&gt; values) : base(name, values) { } public static readonly BatchOption Set = CreateWithCallerName(); public static readonly BatchOption Remove = CreateWithCallerName(); } </code></pre> <h3>Options</h3> <p>These are the options that are currently supported:</p> <pre><code>public class FeatureOption : Option&lt;FeatureOption&gt; { public FeatureOption(SoftString name, IImmutableSet&lt;SoftString&gt; values) : base(name, values) { } /// &lt;summary&gt; /// Indicates that a feature is enabled. /// &lt;/summary&gt; public static readonly FeatureOption Enabled = CreateWithCallerName(); /// &lt;summary&gt; /// Indicates that a warning should be logged when a feature is dirty. /// &lt;/summary&gt; public static readonly FeatureOption WarnIfDirty = CreateWithCallerName(); /// &lt;summary&gt; /// Indicates that feature telemetry should be logged. /// &lt;/summary&gt; public static readonly FeatureOption Telemetry = CreateWithCallerName(); /// &lt;summary&gt; /// Indicates that a feature should be toggled after each execution. /// &lt;/summary&gt; public static readonly FeatureOption Toggle = CreateWithCallerName(); /// &lt;summary&gt; /// Indicates that a feature should be toggled only once. /// &lt;/summary&gt; public static readonly FeatureOption ToggleOnce = CreateWithCallerName(); /// &lt;summary&gt; /// Indicates that feature-options must not be changed. /// &lt;/summary&gt; public static readonly FeatureOption Locked = CreateWithCallerName(); /// &lt;summary&gt; /// Indicates that feature-options have been changed. /// &lt;/summary&gt; public static readonly FeatureOption Dirty = CreateWithCallerName(); // You use this to distinguish between FeatureOption.None which results in default-options. /// &lt;summary&gt; /// Indicates that feature-options have been saved. /// &lt;/summary&gt; public static readonly FeatureOption Saved = CreateWithCallerName(); } </code></pre> <h3>Tests / Examples</h3> <p>The <code>FeatureToggle</code> can be used anywhere for anything. These two tests show how the <code>Switch</code> extension is used for efficient testing.</p> <pre><code> [Fact] public void Can_configure_features_by_tags() { var builder = new ContainerBuilder(); builder.RegisterType&lt;FeatureOptionRepository&gt;().As&lt;IFeatureOptionRepository&gt;(); builder.RegisterDecorator&lt;IFeatureOptionRepository&gt;((context, parameters, instance) =&gt; new FeatureOptionFallback.Enabled(instance)); var container = builder.Build(); var options = container.Resolve&lt;IFeatureOptionRepository&gt;(); var features = new FeatureToggle(options); var names = ImmutableList&lt;Selector&gt; .Empty .AddFrom&lt;DemoFeatures&gt;() .AddFrom&lt;DatabaseFeatures&gt;() .Where&lt;TagsAttribute&gt;("io") .Format(); features.Options.Batch(names, FeatureOption.Enabled, BatchOption.Remove); features.Options.SaveChanges(); Assert.True(features.Switch(DemoFeatures.Greeting, true, false)); Assert.True(features.Switch(DemoFeatures.ReadFile, false, true)); Assert.True(features.Switch(DatabaseFeatures.Commit, false, true)); } [Fact] public void Can_undo_feature_toggle() { var featureToggle = new FeatureToggle(new FeatureOptionRepository()).DecorateWith&lt;IFeatureToggle&gt;(instance =&gt; new FeatureToggler(instance)); Assert.False(featureToggle.IsEnabled("test")); // it disabled by default featureToggle.EnableToggler("test"); // activate feature-toggler Assert.True(featureToggle.Switch("test", false, true)); // it's still disabled and will now switch Assert.True(featureToggle.IsEnabled("test")); // now it should be enabled Assert.True(featureToggle.Switch("test", true, false)); Assert.True(featureToggle.Switch("test", true, false)); Assert.True(featureToggle.IsEnabled("test")); // now it should be still be enabled because it was a one-time-switch } </code></pre> <hr> <h3>Real-world example</h3> <p>I currently use the <code>FeatureToggle</code> in an email-seding web-service. So, in <code>Startup.cs</code> I register all components with <code>Autofac</code>:</p> <blockquote><pre><code> public class Startup { public IServiceProvider ConfigureServices(IServiceCollection services) { // .. return AutofacLifetimeScopeBuilder .From(services) .Configure(builder =&gt; { builder .RegisterType&lt;FeatureOptionRepository&gt;() .As&lt;IFeatureOptionRepository&gt;() .SingleInstance(); builder .RegisterDecorator&lt;IFeatureOptionRepository&gt;( (context, parameters, repository) =&gt; new FeatureOptionFallback.Enabled(repository, FeatureOption.Telemetry)); builder .RegisterType&lt;FeatureToggle&gt;() .As&lt;IFeatureToggle&gt;() .SingleInstance(); builder .RegisterDecorator&lt;FeatureToggler, IFeatureToggle&gt;(); builder .RegisterDecorator&lt;FeatureTelemetry, IFeatureToggle&gt;(); }) .ToServiceProvider(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // .. } } </code></pre></blockquote> <p>APIs (actions) for sending emails are decorated with the <code>[SendEmail]</code> <em>filter</em>. It checks if the query-string <code>isDesignMode</code> was specified and if so, it then deactivates the feture <code>Features.SendEmail[GUID]</code> for this particular email because each email has a <code>GUID</code> that I can add to the name as an <code>[Index]</code>.</p> <blockquote><pre><code> public class SendEmail : ActionFilterAttribute { private readonly ILogger _logger; private readonly IFeatureToggle _featureToggle; public SendEmail(ILogger&lt;SendEmail&gt; logger, IFeatureToggle featureToggle) { _logger = logger; _featureToggle = featureToggle; } public override void OnActionExecuting(ActionExecutingContext context) { if (context.ActionArguments.Values.OfType&lt;IEmail&gt;().SingleOrDefault() is var email &amp;&amp; !(email is null)) { context.HttpContext.Items.SetItem(HttpContextItems.Email, email); context.HttpContext.Items.SetItem(HttpContextItems.EmailTheme, email.Theme); if (bool.TryParse(context.HttpContext.Request.Query[QueryStringNames.IsDesignMode].FirstOrDefault(), out var isDesignMode)) { if (isDesignMode) { // name: Features.SendEmail[GUID] _featureToggle.With( Features.SendEmail.Index(email.Id), f =&gt; f .Remove(FeatureOption.Enabled) // disable this feature for this email .Set(FeatureOption.Toggle) // enable toggle .Set(FeatureOption.ToggleOnce) // toggle only once .Set(FeatureOption.ToggleReset) // reset options back to default ); } } } } } </code></pre></blockquote> <p>Finally, the middleware that does the actual job and sends emails, uses the <code>FeatureToglge</code> to either send it or leave it. <code>FeatureTelemetry</code> takes care logging and <code>FeatueOptionFallback</code> enables this feature by default for all emails.</p> <blockquote><pre><code> await _featureToggle.ExecuteAsync&lt;IResource&gt; ( name: Features.SendEmail.Index(email.Id), body: async () =&gt; await _mailProvider.SendEmailAsync(smtpEmail, requestContext) ); </code></pre></blockquote> <hr> <h3>Questions</h3> <p>I believe, I managed to implement most of your suggestions and like this version much better now. What do you think? Is this more future-proof, easier to use and extendable than before? Is there anything that still could be made better?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T10:37:20.833", "Id": "436793", "Score": "1", "body": "also on [github](https://github.com/he-dev/reusable/tree/dev/Reusable.Beaver/src) + [tests](https://github.com/he-dev/reusable/blob/dev/Reusable.Tests/src/Beaver/FeatureServiceTest.cs)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T16:44:32.177", "Id": "436835", "Score": "3", "body": "`public static implicit operator FeatureIdentifier(string name)`: when you provide this operator, haven't you then lost the benefits/strength that was the meaning by introducing `FeatureIdentifier`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T16:49:18.407", "Id": "436837", "Score": "0", "body": "@HenrikHansen Mhmm maybe, but which ones? It's convenient to have this operator ;-) the benefit of having a comparer is still there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T06:41:41.643", "Id": "436895", "Score": "1", "body": "@HenrikHansen I've added a real-world example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T06:53:38.693", "Id": "436897", "Score": "0", "body": "mhmm... can anyone tell me which benefits/strenghts I am exactly loosing by using that aforementioned operator? It already has two votes but I'm still wondering what that might be ;-]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T07:14:46.560", "Id": "436899", "Score": "0", "body": "I give up. I cannot format the examples correctly. They are all broken, generics are missing, formatting is leaking, several lines of code are gone :-\\ If anyone knows how to fix it, be my hero ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T07:36:42.600", "Id": "436902", "Score": "2", "body": "@t3chb0t - I have no idea why, but the \"<--\" in your C# comments appeared to be the reason the formatting was broken. I've removed them for you :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T07:40:50.837", "Id": "436903", "Score": "1", "body": "@RobH thanks! This makes sense now as the generic arguments in the first snippet are gone too `.As()` it should be `.As<T>()`. I changed the formatting to use html element instead of backticks because of linebreaks and mixing `<` with html breaks everything. I'll need to escape this code..." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T10:36:21.077", "Id": "225080", "Score": "4", "Tags": [ "c#", "design-patterns", "thread-safety", "extension-methods", "framework" ], "Title": "Toggle any application feature ON or OFF - follow-up (v2)" }
225080
<p>Inspired by <a href="https://codereview.stackexchange.com/q/225070">CtCI 16.8: Integer to English phrase in C++</a>, I wrote a program to show the Japanese reading of an integer (positive, negative, or zero). The Japanese is written in Hepburn romanization to avoid encoding problems. Also, traditional Hepburn is used to avoid macrons.</p> <p>Unlike English, Japanese has sound changes when two words come together. The details are given at the end of the question.</p> <p>The program handles integers <span class="math-container">\$n\$</span> in the range <span class="math-container">\$-2^{63} \le n &lt; 2^{63}\$</span>.</p> <h1>Code</h1> <pre><code>/** * Integer to Japanese reading * * Japanese reading is written in Hepburn Roomaji. Traditional * Hepburn is used to avoid the need of macrons. */ #include &lt;cassert&gt; #include &lt;cstdint&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; using number_t = std::int_fast64_t; const std::vector&lt;std::string&gt; magnitudes = { "", "man", "oku", "choo", "kee", }; const std::vector&lt;std::string&gt; thousands = { "", "sen", "nisen", "sanzen", "yonsen", "gosen", "rokusen", "nanasen", "hassen", "kyuusen", }; const std::vector&lt;std::string&gt; hundreds = { "", "hyaku", "nihyaku", "sanbyaku", "yonhyaku", "gohyaku", "roppyaku", "nanahyaku", "happyaku", "kyuuhyaku", }; const std::vector&lt;std::string&gt; tens = { "", "juu", "nijuu", "sanjuu", "yonjuu", "gojuu", "rokujuu", "nanajuu", "hachijuu", "kyuujuu", }; const std::vector&lt;std::string&gt; ones = { "", "ichi", "ni", "san", "yon", "go", "roku", "nana", "hachi", "kyuu", }; // returns 10000^n constexpr number_t magnitude(std::size_t n) { number_t result = 1; while (n--) result *= 10000; return result; } constexpr bool is_vowel(char c) { switch (c) { case 'a': case 'e': case 'i': case 'o': case 'u': case 'y': return true; default: return false; } } // joins two strings according to Japanese rules void push(std::string&amp; lhs, const std::string&amp; rhs) { if (lhs.back() == 'n' &amp;&amp; is_vowel(rhs.front())) lhs += '\''; lhs += rhs; } // converts nonnegative numbers less than 10000 std::string group_name(number_t number) { assert(0 &lt;= number &amp;&amp; number &lt; 10000); std::string result = thousands[number / 1000]; number %= 1000; push(result, hundreds[number / 100]); number %= 100; push(result, tens[number / 10]); number %= 10; push(result, ones[number]); return result; } std::string to_Japanese(number_t number) { if (number == 0) return "zero"; std::string result; if (number &lt; 0) { result = "mainasu"; number = -number; } number_t mag = magnitude(magnitudes.size() - 1); for (std::size_t i = magnitudes.size(); i-- &gt; 0; mag /= 10000) { if (auto group = number / mag; group &gt; 0) { push(result, group_name(group)); push(result, magnitudes[i]); } number %= mag; } return result; } int main() { for (number_t number; std::cin &gt;&gt; number;) std::cout &lt;&lt; to_Japanese(number) &lt;&lt; "\n"; } </code></pre> <h1>Example session</h1> <pre class="lang-none prettyprint-override"><code>0 zero 1 ichi 2 ni 3 san 6789678967896789 rokusennanahyakuhachijuukyuuchoorokusennanahyakuhachijuukyuuokurokusennanahyakuhachijuukyuumanrokusennanahyakuhachijuukyuu -1234567898765432 mainasusennihyakusanjuuyonchoogosenroppyakunanajuuhachiokukyuusenhappyakunanajuurokumangosen'yonhyakusanjuuni </code></pre> <h1>Japanese numerals</h1> <p>(You can skip this part if you are familiar with Japanese.)</p> <p>In the following table, red entries involve sound change.</p> <p><span class="math-container">\begin{array}{ll} \text{Number} &amp; \text{Japanese reading} \\ 1 &amp; \text{一 (ichi)} \\ 2 &amp; \text{二 (ni)} \\ 3 &amp; \text{三 (san)} \\ 4 &amp; \text{四 (yon)} \\ 5 &amp; \text{五 (go)} \\ 6 &amp; \text{六 (roku)} \\ 7 &amp; \text{七 (nana)} \\ 8 &amp; \text{八 (hachi)} \\ 9 &amp; \text{九 (kyuu)} \\ 10 &amp; \text{十 (juu)} \\ 20 &amp; \text{二十 (nijuu)} \\ 30 &amp; \text{三十 (sanjuu)} \\ 40 &amp; \text{四十 (yonjuu)} \\ 50 &amp; \text{五十 (gojuu)} \\ 60 &amp; \text{六十 (rokujuu)} \\ 70 &amp; \text{七十 (nanajuu)} \\ 80 &amp; \text{八十 (hachijuu)} \\ 90 &amp; \text{九十 (kyuujuu)} \\ 100 &amp; \text{百 (hyaku)} \\ 200 &amp; \text{二百 (nihyaku)} \\ 300 &amp; \text{三百 } \color{red}{\text{(sanbyaku)}} \\ 400 &amp; \text{四百 (yonhyaku)} \\ 500 &amp; \text{五百 (gohyaku)} \\ 600 &amp; \text{六百 } \color{red}{\text{(roppyaku)}} \\ 700 &amp; \text{七百 (nanahyaku)} \\ 800 &amp; \text{八百 } \color{red}{\text{(happyaku)}} \\ 900 &amp; \text{九百 (kyuuhyaku)} \\ 1000 &amp; \text{千 (sen)} \\ 2000 &amp; \text{二千 (nisen)} \\ 3000 &amp; \text{三千 } \color{red}{\text{(sanzen)}} \\ 4000 &amp; \text{四千 (yonsen)} \\ 5000 &amp; \text{五千 (gosen)} \\ 6000 &amp; \text{六千 (rokusen)} \\ 7000 &amp; \text{七千 (nanasen)} \\ 8000 &amp; \text{八千 } \color{red}{\text{(hassen)}} \\ 9000 &amp; \text{九千 (kyuusen)} \\ \end{array}</span></p> <p>Larger numbers are considered the sums of smaller numbers. For example:</p> <p><span class="math-container">\begin{array}{ccccccc} 2019 &amp; = &amp; 2000 &amp; + &amp; 10 &amp; + &amp; 9 \\ \text{二千十九 (nisenjuukyuu)} &amp; &amp; \text{二千 (nisen)} &amp; &amp; \text{十 (juu)} &amp; &amp; \text{九 (kyuu)} \end{array}</span></p> <p>The missing hundred place is simply ignored.</p> <p>Four digits are considered a group, unlike English, where three digits are a group. The group markers are:</p> <p><span class="math-container">\begin{array}{ccc} 10^4 &amp; 10^8 &amp; 10^{12} &amp; 10^{16} \\ \text{万 (man)} &amp; \text{億 (oku)} &amp; \text{兆 (choo)} &amp; \text{京 (kee)} \end{array}</span></p> <p>For example, <span class="math-container">\$1\,2345\,6789\$</span> is read as 一億二千三百四十五万六千七百八十九 (ichioku nisensanbyakuyonjuugoman rokusennanahyakuhachijuukyuu). (The spaces are for ease of recognition only.) Note that 一 (ichi) is required before these group markers, unlike 十 (juu), 百 (hyaku), and 千 (sen).</p> <p>0 is ゼロ (zero).</p> <p>A negative integer <span class="math-container">\$-n\$</span> is read as マイナス (mainasu) followed by its absolute value <span class="math-container">\$n\$</span>. For example, -5 is read as マイナス五 (mainasugo), because 5 is read as 五 (go).</p> <p>When two syllables are joined, if the first syllable ends with "n" and the second starts with one of "aeiouy", then a separator ' is added between. For example, 1001 is 千一 (sen'ichi) and 1004 is 千四 (sen'yon).</p>
[]
[ { "body": "<p>I know in that in English that each word would be separate where the program is printing the all of the numbers merged together. Is this the actual functionality in Japanese?</p>\n\n<p>Since the code might be useful in many places it might be better of the translation code as in a class.</p>\n\n<p><strong>Use of Vertical Space</strong><br>\nGenerally code is easier to read and maintain when only one value is on a line. This would apply to the initialization of the vectors and the switch statement in the function <code>is_vowel()</code>. For maintenance reasons it is much easier to insert a line where it needs to be than it is to add a value to a comma separated list.</p>\n\n<p><strong>is_vowel function</strong><br>\nThere would be less code if the vowels were in a std::map rather than a switch statement. Here are discussions on <a href=\"https://stackoverflow.com/questions/931890/what-is-more-efficient-a-switch-case-or-an-stdmap\">stack overflow</a> and <a href=\"https://softwareengineering.stackexchange.com/questions/193786/map-of-functions-vs-switch-statement\">software engineering</a>.</p>\n\n<p><em>This portion of the answer has been modified to remove the statement that there might be a performance improvement using std::map. If map used a simple index into an array that might be true, however it is not a simple index into an array.</em></p>\n\n<p><strong>Assert</strong><br>\n<a href=\"https://stackoverflow.com/questions/8114008/when-should-we-use-asserts-in-c\">Assert statements are generally used for debugging purposes and terminate the program</a>. Assert statements may be removed when the code is compiled without debugging as well. I don't expect to see asserts in production level code because it implies that the code is not yet debugged.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T13:14:27.263", "Id": "436805", "Score": "2", "body": "Re first paragraph: yeah, usually a number is considered one single word in Roomaji :) Re assert statements: my intention is that a logic error should fire instead of throwing an exception. And `NDEBUG` can be used to remove the assertions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T13:18:14.523", "Id": "436806", "Score": "2", "body": "@L.F. Just curious, why are you hiding std::int_fast64_t behind the using number_t? The only reason I can think of is to change the type quickly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T13:20:53.653", "Id": "436807", "Score": "2", "body": "Partly because of your reason. And partly because I want to differentiate the values from other numbers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T09:26:07.317", "Id": "436913", "Score": "12", "body": "\"*There would be less code and the performance might be better if the vowels were in a std::map rather than a switch statement.*\" - do you have anything to support a claim that std::map is faster than a raw switch statement? Because I very much doubt that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T10:41:44.840", "Id": "436916", "Score": "5", "body": "^ Agreed with Tomas. Provide proof. `std::map` is dynamically-allocated, node-based, and definitely not cache friendly" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T10:42:33.597", "Id": "436917", "Score": "10", "body": "*\"Assert statements are generally used for debugging purposes and throw an exception.\"* - **NO.** Assert statements exist to test *preconditions*. Exceptions have nothing to do with preconditions. This answer is **harmful**." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T11:14:44.060", "Id": "436924", "Score": "7", "body": "Failed `assert()`s do not throw - they terminate the program." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T13:15:06.230", "Id": "436933", "Score": "6", "body": "*\"It is generally better to use if statements that provide error messages rather than assert statements.\"* - This is still **severely wrong** and **harmful**. They have completely different use cases. Assert -> precondition check, contract breakage, unrecoverable error. `if` statement + error -> recoverable error, can be usually handled by a human." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T14:20:43.857", "Id": "436941", "Score": "1", "body": "@pacmaninbw: robust software also does not continue after a precondition is violated. Termination is preferred to deleting client data or exposing sensitive information on the wire. Regardless, this is not what you are saying in the answer. You are saying that *\"if statements with error messages are generally better than assertions\"*, which is completely false as they have two different use cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T15:42:49.583", "Id": "436975", "Score": "1", "body": "@VittorioRomeo Assert statements are a C programming language construct that predates the C++ programming language. C++ provides alternate mechanisms for this such as throwing an uncaught exception. The benefit of exceptions is that they can be caught is necessary. If you need to continue this discussion meet me in https://chat.stackexchange.com/rooms/8595/the-2nd-monitor." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T15:44:24.197", "Id": "436976", "Score": "3", "body": "*\"C++ provides alternate mechanisms for this such as throwing an uncaught exception.\"* Throwing an exception is not an alternative to assertions. They have different use cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:06:58.537", "Id": "437010", "Score": "0", "body": "@TomášZato Switch = a bunch of CMP/GOTOs, map = a lot of stuff. You're totally right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T10:51:20.263", "Id": "437127", "Score": "1", "body": "\"I don't expect to see asserts in production level code because it implies that the code is not yet debugged.\" - This is misleading at best. Assertions will not trigger in \"release\" build, but they will still be visible in the source code. I also do not think assertions as a debug only tool is a widely held opinion. Otherwise why would there be interest in upgrading assert to a language level feature? https://herbsutter.com/2018/07/02/trip-report-summer-iso-c-standards-meeting-rapperswil/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T18:25:06.420", "Id": "437194", "Score": "0", "body": "@TomášZato Answer updated based on research." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T04:47:18.247", "Id": "437733", "Score": "0", "body": "\"Since the code might be useful in many places it might be better of the translation code as in a class.\" — That's a strange reasoning. A class is something that represents code + data as a single unit. A simple function can be made as reusable as a class." } ], "meta_data": { "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T12:59:59.890", "Id": "225086", "ParentId": "225082", "Score": "7" } }, { "body": "<p>Your magnitudes should be <code>chou</code> and <code>kei</code> (as in the <a href=\"https://en.wikipedia.org/wiki/K_computer\" rel=\"noreferrer\">supercomputer</a>, as an aside). Also, <code>to_Japanese()</code> would be better named <code>to_romaji()</code>. As an exercise, you could try <code>to_Japanese(number, KANJI|HIRAGANA|ROMAJI)</code> also.</p>\n\n<p>Furthermore, it's <a href=\"https://ja.wikipedia.org/wiki/1000000000000\" rel=\"noreferrer\"><code>icchou</code>, not <code>ichichou</code></a>, and <code>ikkei</code>, not <code>ichikei</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T00:50:33.793", "Id": "436875", "Score": "1", "body": "Thank you for correcting my Japanese! I am a beginner and sorry for the mistakes. Regarding chou vs choo: what I learned is that when おう is a long \"o\", it is written as \"oo\" instead of \"ou\". I figured out that different romaji systems differ on this. And \"ichichou\" is so silly ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T05:59:56.640", "Id": "436890", "Score": "2", "body": "Yes, there's lots of different romaji versions - I looked up the most common [Hepburn](https://en.wikipedia.org/wiki/Hepburn_romanization#O_+_O), and `choo` is correct, although I always use `chou` as it's [IME-friendly](https://en.wikipedia.org/wiki/Wāpuro_rōmaji#Spelling_conventions), but then `sennana` would be typed `sennnana`. We're now straying into [japanese.se] territory..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T00:46:12.037", "Id": "225106", "ParentId": "225082", "Score": "14" } }, { "body": "<p>I think it would be better to generate the 漢字 versions of the numbers, as it's more useful in general. Make a separate class responsible for romanization (or phonetic conversion in general so it can support kana).</p>\n\n<p>Using kanji also allows for somewhat trivially adding support for formal numbers (大字), which is kind of cool/useful.</p>\n\n<p>I would also recommend adding support for breaking up the romaji sequences as reading very large numbers in romaji with no spaces is not at all fun. It could be an optional flag. A natural place to add spaces would be between magnitudes at least, or maybe between all of the various groupings you've already put together (ones, tens, hundreds, etc.).</p>\n\n<p>As for using romaji to avoid encoding issues, I recommending biting the bullet and learning how to support Unicode correctly as it will be extremely useful.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T03:25:42.693", "Id": "436879", "Score": "1", "body": "Insightful. Although romanization is nontrivial AFAIK since one kanji can have multiple readings ... Spaces in between romaji is also a good idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T03:30:46.777", "Id": "436880", "Score": "1", "body": "@L.F. romanization doesn't have to support the entirety of Japanese, as this code is number focused, and you've already decided on the readings for each of the kanji involved anyway (or rather; there's only one right answer for these in this context); and that means katakana and hiragana phonetic readings are just as easy at that point." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T03:12:01.870", "Id": "225111", "ParentId": "225082", "Score": "8" } }, { "body": "<p>The <code>push</code> function may invoke undefined behavior. When you create a new <code>std::string</code>, I don't think it is guaranteed to be null-terminated since that would incur a runtime cost for no benefit other than C compatibility. Only after calling <code>c_str()</code> the terminating null character is there. Because the string is really empty, calling <code>back()</code> accesses an out-of-bounds element.</p>\n\n<p>You claim that your code works for <span class=\"math-container\">\\$-2^{63}\\$</span> but you didn't add that number as a test case. I would expect it to not work since <code>-(-2**63)</code> is still negative.</p>\n\n<p>Besides these two issues, your code reads well and is easy to understand. Adding the additional documentation was a very good idea for everyone not fluent in Japanese.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T05:22:30.420", "Id": "436886", "Score": "0", "body": "I see. The problem is that `back` accesses the nonexistent element. (The terminating null character doesn't change that.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T06:28:59.547", "Id": "436891", "Score": "0", "body": "@L.F. Yes, in reality most std::string implementations *will* have a terminating 0 byte at all times. And in fact C++11 and later *requires* that [`operator[]` with `pos=size()`](https://en.cppreference.com/w/cpp/string/basic_string/operator_at) references the terminating `0`. What makes `back()` UB is that https://en.cppreference.com/w/cpp/string/basic_string/back says it's UB when `.empty() == true`. And moreover that it's equivalent to `operator[](size() - 1)` which would wrap the unsigned position." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T06:31:00.477", "Id": "436892", "Score": "0", "body": "The code definitely needs a check. Also, `operator[](size() - 1)` only applies if `empty()` is false, so wrapping is irrelevant I guess." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T06:31:02.373", "Id": "436893", "Score": "1", "body": "In practice `g++ -O0` with libstdc++ (on Arch Linux) gives `0` when doing `.back()` on an empty `std::string`, so it doesn't help you detect this bug by crashing on that UB." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T06:36:37.757", "Id": "436894", "Score": "3", "body": "@L.F.: fun facts: [Legality of COW std::string implementation in C++11](//stackoverflow.com/q/12199710) shows how some of the new requirements in C++11 basically make efficient COW implementation of std::string impossible. With `.data()` also requiring a 0-terminated string, the obvious/intended implementation is to always maintain that so `.data()` and `.c_str()` can be a no-op that just returns one of the class member vars." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T05:17:49.990", "Id": "225112", "ParentId": "225082", "Score": "8" } }, { "body": "<p>You use of <code>std::vector&lt;std::string&gt;</code> for the arrays of string constants is wasteful. Both <code>std::vector</code> and <code>std::string</code> are dynamic types that can potentially allocate. A much more lightweight choice would be <code>constexpr std::array&lt;const char*&gt;</code> or <code>constexpr std::array&lt;std::string_view&gt;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T10:42:39.397", "Id": "436918", "Score": "0", "body": "Fair point. `string` is probably not dynamic in this case due to SSO, but `vector` is quite wasteful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T10:44:12.723", "Id": "436919", "Score": "1", "body": "Still, I like using the most minimal tool for the job whenever possible. Even if the constants are going to fit in SSO, it's good practice to use `std::string_view` or `const char*`. The compiler will also very likely be able to optimize better." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T10:40:36.967", "Id": "225122", "ParentId": "225082", "Score": "3" } } ]
{ "AcceptedAnswerId": "225112", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T11:44:21.317", "Id": "225082", "Score": "26", "Tags": [ "c++", "c++17", "numbers-to-words" ], "Title": "Japanese reading of an integer" }
225082
<p>Using visual studio I created a snippet which helps me surround my already written or new code into a try-catch-finally block. I use <strong>axios for REST</strong> so there had to be separate error handling method so that users can cleanly view the error result and report it to the support team.</p> <p><strong><em>Code:</em></strong></p> <pre><code>try { //Start the loading bar so user can know something is running in background this.$store.commit("isLoading", true); //Some axios code runs here... const response = await this.axios.post(process.env.VUE_APP_API_ExampleAPI, { param1: 'blaa', param2: 'blaa2' }); //Once done result is going to be shown in a modal using vuex as store //200 response requests will always return the response in the format of an object and message containing in "message" parameter this.$store.commit("successMessage", response.data.message); //Now user is shown the modal this.$store.commit("successModal", true); } catch (error) { //In case the error is via axios request if (error.isAxiosError) { var concatMessages = ''; Object.entries(error.response.data.errors).forEach(([key, value]) =&gt; concatMessages += value); this.$store.commit("errorMessage", concatMessages); this.$store.commit("errorModal", true); } //Other non-axios errors i.e. syntax error, code error etc... else { this.$store.commit("errorMessage", error.toString()); this.$store.commit("errorModal", true); } } //Finally block stops the progress bar loading indicating background process isn't anymore finally { this.$store.commit("isLoading", false); } </code></pre> <p>Now I feel like there is too much code in it despite it helps in development. I mean it is repeated in almost every function/method.</p> <p>There has to be a way to <strong>reduce this code</strong> or improve it to <strong>avoid repetition</strong> in most of the functions but I am not sure what it could be.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T16:50:22.037", "Id": "436838", "Score": "2", "body": "Welcome to Code Review! At the moment there is not really context to show how this code is used. That makes it hard for reviewers to give you meaningful and targeted feedback." } ]
[ { "body": "<h2>Refactoring to DRY Code</h2>\n\n<p>In order to avoid repetition, we could create a couple of reusable functions to enable your functions to all use the same pattern.</p>\n\n<p>The pattern:</p>\n\n<ul>\n<li>start loading</li>\n<li>await operation</li>\n<li>loading completed</li>\n<li>notify success</li>\n<li>on error: notify error</li>\n</ul>\n\n<p><strong>buildErrorMessage</strong></p>\n\n<p>Let's start by making a function that builds an error message given an error.</p>\n\n<pre><code>function buildErrorMessage(error) {\n if (error.isAxiosError) {\n let concatMessages = '';\n Object.entries(error.response.data.errors)\n .forEach(([key, value]) =&gt; concatMessages += value);\n return concatMessages;\n }\n return error.toString();\n}\n</code></pre>\n\n<p>to avoid writing code as..</p>\n\n<blockquote>\n<pre><code>if (error.isAxiosError) {\n var concatMessages = '';\n Object.entries(error.response.data.errors)\n .forEach(([key, value]) =&gt; concatMessages += value);\n this.$store.commit(\"errorMessage\", concatMessages);\n this.$store.commit(\"errorModal\", true);\n}\n//Other non-axios errors i.e. syntax error, code error etc...\nelse {\n this.$store.commit(\"errorMessage\", error.toString());\n this.$store.commit(\"errorModal\", true);\n}\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p><strong>executeInBackground</strong></p>\n\n<p>Now we could provide a wrapper function to execute other functions in the background, updating the store before, after and on error of the operation.</p>\n\n<pre><code>async function executeInBackground(operation) {\n try {\n this.$store.commit(\"isLoading\", true);\n const response = await operation();\n this.$store.commit(\"successMessage\", response.data.message);\n this.$store.commit(\"successModal\", true);\n }\n catch (error) {\n const errorMessage = buildErrorMessage(error);\n this.$store.commit(\"errorMessage\", errorMessage);\n this.$store.commit(\"errorModal\", true);\n }\n finally {\n this.$store.commit(\"isLoading\", false);\n }\n}\n</code></pre>\n\n<p>This part..</p>\n\n<pre><code> const response = await operation();\n</code></pre>\n\n<p>Is a generic replacement for your code:</p>\n\n<blockquote>\n<pre><code>//Some axios code runs here...\nconst response = await this.axios.post(process.env.VUE_APP_API_ExampleAPI, \n {param1: 'blaa', param2: 'blaa2' });\n</code></pre>\n</blockquote>\n\n<p>By replacing the specific operation with a template place holder, we can avoid repetition for every other operation that needs to follow the same pattern.</p>\n\n<hr>\n\n<p><strong>entrypoint functions</strong></p>\n\n<p>And finally, we create a function that handles the stuff from the OP.</p>\n\n<pre><code>async function processExample() {\n await executeInBackground(() \n =&gt; this.axios.post(process.env.VUE_APP_API_ExampleAPI, { \n param1: 'blaa', param2: 'blaa2' }));\n}\n</code></pre>\n\n<p>This way, you avoid redundant error handling, and update the store in a consistent fashion. Each new function that requires the same behavior should just call <code>await executeInBackground</code> with the operation that is required.</p>\n\n<p>Suppose you have another function, it gets apparent that code duplication can be avoided:</p>\n\n<pre><code>async function processSomethingElse() {\n await executeInBackground(() \n =&gt; this.axios.post(process.env.VUE_APP_API_ExampleAPI, { \n param1: 'other', param2: 'other2' }));\n}\n</code></pre>\n\n<p>And thus we have established DRY code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T20:55:34.053", "Id": "436869", "Score": "2", "body": "Thank you, this improves my code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T13:54:25.147", "Id": "225089", "ParentId": "225084", "Score": "2" } } ]
{ "AcceptedAnswerId": "225089", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T12:21:58.837", "Id": "225084", "Score": "-1", "Tags": [ "javascript", "error-handling", "user-interface", "vue.js", "axios" ], "Title": "Try-catch-finally snippet" }
225084
<p>I had created a service which does the actual play of Rock Paper Scissors. </p> <p>Below is the service which takes a PlayRequest and updates the State of Player objects given by the PlayerService. </p> <p>So the consumer of the API knows about winner, loser or tie by doing a GET on a Player. </p> <p>One of the things I feel wrong NOW is that the method play takes a PlayerRequest but uses it only for two lines, all other work is done from the injected dependencies.</p> <p>Would appreciate any comments related to State as well as SOLID principles.</p> <pre><code>@Service public class GameplayService { private PlayerService playerService; private GameSessionService gameSessionService; public GameplayService(GameSessionService gameSessionService, PlayerService playerService) { this.gameSessionService = gameSessionService; this.playerService = playerService; } public void play(PlayRequest playRequest) throws RPSException { GameSession currentSession = gameSessionService.sessions().get(playRequest.getInviteCode()); Player player = playerService.changePlayerState(playRequest.getPlayerName(), State.PLAYING); currentSession.changeStateTo(GameSession.State.PLAYING); try { Turn turn = new Turn(player, Enum.valueOf(Move.class, playRequest.getMove())); if (currentSession.rounds().isEmpty()) { createNewRound(turn, currentSession); } else if (!currentSession.rounds().isEmpty()) { Round latestRound = currentSession.latestRound(); if (OVER.equals(latestRound.getState())) { createNewRound(turn, currentSession); } else if (PLAYING.equals(latestRound.getState())) { latestRound.pushLatestTurn(turn); } } Round latestRoundAfterAllUpdates = currentSession.latestRound(); Optional&lt;Result&gt; resultOptional = latestRoundAfterAllUpdates.getResult(); if (resultOptional.isPresent()) { currentSession.changeStateTo(GameSession.State.WAITING); Result result = resultOptional.get(); if (result.isTie()) { currentSession.setTie(true); } else { currentSession.setWinner(result.getWinner()); } currentSession.getFirstPlayer().changeStateTo(State.WAITING); currentSession.getSecondPlayer().changeStateTo(State.WAITING); } } catch (InvalidOperationException e) { throw new RPSException(e.getMessage()); } } private void createNewRound(Turn turn, GameSession gameSession) { gameSession.addRound(new Round(turn)); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-08T11:18:05.833", "Id": "438485", "Score": "0", "body": "At the very least you should post the interfaces of the other classes you are using. Better would be runnable code, e.g. with unit tests that mock the parts you haven't posted." } ]
[ { "body": "<h1><a href=\"https://hackernoon.com/solid-principles-made-easy-67b1246bcdf\" rel=\"noreferrer\">SOLID Principles</a></h1>\n\n<h2>Single responsibility principle</h2>\n\n<blockquote>\n <p>A class should have one, and only one, reason to change.</p>\n</blockquote>\n\n<p>This class should take a PlayerRequest and update the state of the corresponding Players. </p>\n\n<p>The <code>public void play</code> method does more than that, by changing the state of the current game, creating a new round or pushing the latest turn. It would be easier to read the code if the <code>play</code> method was just updating the states and no more. The management of the current Round and Turn should be delegated to a different dependency. Since the Responsibility of the Service class is to update the states, it would be acceptable to have another method <code>wait</code> changing the states to <code>State.WAITING</code>.</p>\n\n<p>Creating unit tests for this class would be then much easier, as we would need only to test the expected change of states and everything else would be mocked.</p>\n\n<h2>Open-Closed Principle</h2>\n\n<blockquote>\n <p>You should be able to extend a class’s behavior, without modifying it.</p>\n</blockquote>\n\n<p>This block of code, even if moved to another class, could violate the Open-Closed Principle:</p>\n\n<pre><code> Turn turn = new Turn(player, Enum.valueOf(Move.class, playRequest.getMove()));\n if (currentSession.rounds().isEmpty()) {\n createNewRound(turn, currentSession);\n } else if (!currentSession.rounds().isEmpty()) {\n Round latestRound = currentSession.latestRound();\n if (OVER.equals(latestRound.getState())) {\n createNewRound(turn, currentSession);\n } else if (PLAYING.equals(latestRound.getState())) {\n latestRound.pushLatestTurn(turn);\n }\n }\n</code></pre>\n\n<p>It is not clear from the code if there are more possible Round States than <code>OVER</code> and <code>PLAYING</code>, but if the Game was extended and there was a new State to be handled (e.g. an <code>EXTRA</code> round), this code block would need to be changed to address it. The solution is to depend upon an abstraction to handle the Round management. Concrete classes will then handle the implementation for the different possible Round States.</p>\n\n<h2>Liskov substitution principle</h2>\n\n<blockquote>\n <p>Let <span class=\"math-container\">\\${\\displaystyle \\phi (x)}\\$</span> be a property provable about objects <span class=\"math-container\">\\${\\displaystyle x}\\$</span> of type T. Then <span class=\"math-container\">\\${\\displaystyle \\phi (y)}\\$</span> should be true for objects <span class=\"math-container\">\\${\\displaystyle y}\\$</span> of type S where S is a subtype of T.</p>\n</blockquote>\n\n<p>Following this principle will be a consequence of the abstraction made for the previous principle. The derived classes will have to not alter the expected behavior of their parent classes. This principle will be ensured by adding the correct assertions (postconditions) in the unit tests.</p>\n\n<h2>Interface Segregation Principle</h2>\n\n<blockquote>\n <p>Make fine grained interfaces that are client specific.</p>\n</blockquote>\n\n<p>As @RoToRa suggested, we would need to see the injected interfaces. They should be fine grained in order that the clients (derived classes) will only implement the methods they really use.</p>\n\n<h2>Dependency Inversion Principle</h2>\n\n<blockquote>\n <p>Depend on abstractions, not on concretions.</p>\n</blockquote>\n\n<p>Here it is pretty straight-forward: the injected dependencies of the <code>GameplayService</code> class should be abstractions (i.e. abstract classes or interfaces). Then it would be easy to change the behavior of the class in case the rules of the Game are extended.</p>\n\n<h1>General comments</h1>\n\n<p>The best way to check if your code is clean and well-written is to cover it by Unit Tests, even better if it is done using <a href=\"https://en.wikipedia.org/wiki/Test-driven_development\" rel=\"noreferrer\">TDD</a>. The complexity of the entire class would be then reduced and the feel of adding collaborators and mocking their behavior would come easier. </p>\n\n<p>Any possible null pointer exceptions, bugs or redundancies in the code would also be avoided during Unit Testing, like this unnecessary <code>if</code> condition of the <code>else</code> branch:</p>\n\n<pre><code>else if (!currentSession.rounds().isEmpty())\n</code></pre>\n\n<p>I would also use lambdas when working with Optionals and typical Java 8 features, e.g.:</p>\n\n<pre><code>resultOptional.ifPresent(result -&gt; {...})\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-13T15:13:42.873", "Id": "445028", "Score": "0", "body": "Thanks a lot for all your generous comments. You are welcome to review more code if you get the chance to: https://github.com/gavarava/rockpaperscissors" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-08T22:47:05.073", "Id": "225803", "ParentId": "225087", "Score": "5" } }, { "body": "<h1>To Your Comment</h1>\n\n<blockquote>\n <p>One of the things I feel wrong NOW is that the method play takes a PlayerRequest but uses it only for two lines, all other work is done from the injected dependencies.</p>\n</blockquote>\n\n<p>For me it feels right if the statement <code>playerService.changePlayerState(playRequest.getPlayerName(), State.PLAYING)</code> would be inside <code>currentSession.changeStateTo(GameSession.State.PLAYING)</code>.</p>\n\n<p>I would replace the statement by something like:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>gameSessionService.enterPlayingState(currentSession);\n</code></pre>\n\n<p>The reasons behind this feeling are:</p>\n\n<ul>\n<li>we loose the dependency to <code>playerService</code> in <code>GameplayService</code></li>\n<li>we loose the dependency to <code>State.PLAYING</code></li>\n<li>we reduce the number of lines and some complexity</li>\n</ul>\n\n<h1>To My Comments</h1>\n\n<p>Sadly you provide only a little code snipped of your application so it is hard to give you good advice without knowing what the other components do.. but here is my try :)</p>\n\n<h2>Reduce Complexity</h2>\n\n<p>At the first glance it is not possible to see what the method <code>play</code> do. This has multiple reasons:</p>\n\n<ul>\n<li>has 3 levels of nesting</li>\n<li>is longer than it has to be</li>\n</ul>\n\n<p>It is possible to divide <code>play</code> in 3 sections:</p>\n\n<ul>\n<li>enter the playing state</li>\n<li>play the turn</li>\n<li>evaluate the round</li>\n</ul>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>public void play(PlayRequest playRequest) throws &gt;RPSException {\n // enter playing state\n GameSession currentSession = gameSessionService.sessions().get(playRequest.getInviteCode());\n /* ... */\n\n try {\n // play turn\n Turn turn = new Turn(player, Enum.valueOf(Move.class, playRequest.getMove()));\n /* ... */\n\n // evaluate round\n Round latestRoundAfterAllUpdates = currentSession.latestRound();\n /* ... */\n } catch (InvalidOperationException e) {\n throw new RPSException(e.getMessage());\n }\n}\n</code></pre>\n</blockquote>\n\n<h2>Law of Demeter</h2>\n\n<p>The expression <code>gameSessionService.sessions().get(playRequest.getInviteCode())</code> violates the <a href=\"https://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow noreferrer\">Law of Demeter</a>.</p>\n\n<blockquote>\n <p>Only talk to your immediate friends.</p>\n</blockquote>\n\n<p><code>GameSessionService</code> is a intermediate friend of <code>GameplayService</code> but with <code>get(playRequest.getInviteCode())</code> we \"talk\" to the friend of our friend.</p>\n\n<blockquote>\n <p>The statement could be also expressed as <code>gameSessionService.prodiveBy(playRequest)</code>.</p>\n</blockquote>\n\n<p>The following statements violates the Law of Demeter too:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>currentSession.rounds().isEmpty()\ncurrentSession.getFirstPlayer().changeStateTo(State.WAITING);\ncurrentSession.getSecondPlayer().changeStateTo(State.WAITING);\n</code></pre>\n</blockquote>\n\n<h2>Feature Envy</h2>\n\n<blockquote>\n <p>A method accesses the data of another object more than its own data.</p>\n</blockquote>\n\n<p>When we look at</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>if (currentSession.rounds().isEmpty()) {\n createNewRound(turn, currentSession);\n} else if (!currentSession.rounds().isEmpty()) {\n Round latestRound = currentSession.latestRound();\n if (OVER.equals(latestRound.getState())) {\n createNewRound(turn, currentSession);\n } else if (PLAYING.equals(latestRound.getState())) {\n latestRound.pushLatestTurn(turn);\n }\n}\nRound latestRoundAfterAllUpdates = currentSession.latestRound();\nOptional&lt;Result&gt; resultOptional = latestRoundAfterAllUpdates.getResult();\n/* ... */\n\nprivate void createNewRound(Turn turn, GameSession gameSession) {\n gameSession.addRound(new Round(turn));\n}\n</code></pre>\n</blockquote>\n\n<p>We use the variable <code>currentSession</code> 6 times in this little code snipped with the goal to update it by deciding how to handle the update by its data which violates the feature envy.</p>\n\n<p>We should simply call a method on <code>currentSession</code>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Result result = currentSession.play(player, playRequest.getMove());\n</code></pre>\n\n<h1>Polymorphism and If-Else-Statements</h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>Optional&lt;Result&gt; resultOptional = latestRoundAfterAllUpdates.getResult();\n\n/* ... */\n\nResult result = resultOptional.get();\nif (result.isTie()) {\n currentSession.setTie(true);\n} else {\n currentSession.setWinner(result.getWinner());\n}\n</code></pre>\n</blockquote>\n\n<p>With an <code>Optional</code> we can express in Java that there could be no result after a method call. For example if we search in a database for a id. </p>\n\n<p>But in this case we try to express different typs of <code>Result</code>:</p>\n\n<ul>\n<li>NoResult (the optional is empty case)</li>\n<li>Tie</li>\n<li>Win</li>\n</ul>\n\n<p>The goal would be to enter the next state of the game by the <code>result</code> which could be expressed as</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>currentState.enterNextStateBy(result)\n</code></pre>\n\n<h1>The goal</h1>\n\n<p>The goal of a refactoring would be to have only some method calls which show the flow a play takes</p>\n\n<p>Form your the little snipped you provide it could look like:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public void play(PlayRequest playRequest) throws &gt;RPSException {\n GameSession session = gameSessionService.prodiveBy(playRequest);\n\n session.enterPlayState();\n Result result = session.play(player, playRequest.getMove());\n currentState.enterNextStateBy(result);\n\n}\n</code></pre>\n\n<h1>Last Advice</h1>\n\n<p>I would take a look into the <a href=\"https://en.wikipedia.org/wiki/State_pattern\" rel=\"nofollow noreferrer\">State pattern</a> to handle the states of your game.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-13T15:13:52.790", "Id": "445029", "Score": "0", "body": "Thanks a lot for all your generous comments. You are welcome to review more code if you get the chance to: https://github.com/gavarava/rockpaperscissors" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-10T21:46:21.000", "Id": "225912", "ParentId": "225087", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T13:42:25.367", "Id": "225087", "Score": "2", "Tags": [ "java", "object-oriented", "spring", "rock-paper-scissors" ], "Title": "Spring service for playing Rock Paper Scissors" }
225087
<p>Student.java</p> <pre><code>public class Student{ /* Metrics examples (out of 100): mathScore:98 scienceScore:99 englishScore:92 */ private Map&lt;String, Double&gt; metrics = new HashMap&lt;&gt;(); public Double getMetric(final String metricName) { return metrics.get(metricName); } } </code></pre> <p>Statistics</p> <pre><code>public enum Statistic { AVERAGE, MIN, MAX } </code></pre> <p>Result</p> <pre><code>public class Result { private Statistic statistic; private double value; private String metric; } </code></pre> <p>What's the most efficient way to build an engine that can perform requested statical analysis based on the requested metrics on a list of students</p> <p>Here's an example:</p> <p>Say I have a list of Students. </p> <pre><code>List&lt;Student&gt; students = [john, json, elliot, sarah, callie, matt, leigh]; //Assume each entry is an object </code></pre> <p>I also have list of metrics I'm interested in </p> <pre><code>List&lt;String&gt; metrics =["mathScore", "scienceScore"]; //Just an example. I can add additional metrics to this list or remove them. </code></pre> <p>And the statistics I want to perform</p> <pre><code>List&lt;Statistic&gt; stats = [MIN, MAX]; //Just an example. I can request additional operations if necessary. </code></pre> <p>Here's the signature of the method that needs to be efficiently built</p> <pre><code>public List&lt;Result&gt; calculate( List&lt;String&gt; requestedMetrics, List&lt;Statistic&gt; requestedStatistics, List&lt;Student&gt; students){ } </code></pre> <p>Here are my initial thoughts</p> <ol> <li>Convert requestedMetrics and requestedStatistics to sets to eliminate duplicates. </li> <li>Iterate through each metric. For each metric, iterate through each statistic and calculate it. Is there a better way? And how does one go about breaking down the implementation in to smaller functions etc. for a cleaner solution? </li> <li>What about creating a cache (map) so that we don't need to reprocess everything again and again?</li> </ol> <p>Here's my current implementation</p> <pre><code>@Component public class StatisticalAnalysis { @Override public List&lt;Result&gt; calculate(List&lt;Student&gt; students, List&lt;String&gt; metrics, List&lt;Statistic&gt; stats) { return analyze(new HashSet&lt;&gt;(students), new HashSet&lt;&gt;(metrics), new HashSet&lt;&gt;(stats)); } public List&lt;Result&gt; analyze(HashSet&lt;Student&gt; students, HashSet&lt;String&gt; metrics, HashSet&lt;Statistic&gt; stats) { List&lt;Result&gt; results = new ArrayList&lt;&gt;(metrics.size()); for (String metric : metrics) { for (Statistic stat : stats) { results.add(createResult(students, metric, stat )); } } return results; } private Result createResult(HashSet&lt;Student&gt; students, String metric, Statistic stat) { return new Result(metric, stat, calcStatValue(students, metric, stat)); } private double calcStatValue(HashSet&lt;Student&gt; students, String metric, Statistic stat) { List&lt;Double&gt; values = new ArrayList&lt;Double&gt;(students.size()); for(Student measurement: students){ Double value = measurement.getMetric(metric); if(value!=null) values.add(value); } return performStatOperation(stat, values); } private double performStatOperation(Statistic stat, List&lt;Double&gt; values) { switch (stat) { case MIN: return Collections.min(values); case MAX: return Collections.max(values); case AVERAGE: return values.stream().mapToDouble(val -&gt; val).average().orElse(0.0); default: throw new UnsupportedOperationException(String.format("Calculation of Statistic %s is currently unsupported", stat)); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T18:28:57.057", "Id": "436856", "Score": "0", "body": "@dfhwze Removed it. One of the goals of the review is to see if there's another style that's more efficient." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T18:34:49.397", "Id": "436859", "Score": "0", "body": "@dfhwze I can't specifically think of individual algorithmic improvements. But there could be enhancements that I'm missing. Also is there an alternative design style and how does that compare? Is there a disadvantage to creating smaller functions? These are just a few examples. There could be other elements to review!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T18:36:49.400", "Id": "436860", "Score": "0", "body": "When you talk about the cache, do you mean that when a student's results get added, only a delta needs to be calculated to the existing statistics?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T18:48:37.150", "Id": "436861", "Score": "0", "body": "Yes. Saving the calculations for a list of users maybe? So that if the same request is repeated, it could be pulled form cache." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T19:10:45.267", "Id": "436864", "Score": "1", "body": "Added! Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T20:05:45.227", "Id": "436865", "Score": "1", "body": "Shouldn't `List<Result> calculate` be `List<Result> result`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T20:27:51.257", "Id": "436867", "Score": "3", "body": "It's hard to believe that this code works as expected. You cannot get any information from the `Student` class since the map of metrics is initially empty and not modifiable from outside the `Student` class." } ]
[ { "body": "<p>This can be vastly simplified using a handful of tricks from functional programming. Let's first consider the operations you want to perform, given a collection of students, metrics and stats.</p>\n\n<ol>\n<li>Extract the metrics you're interested in from the students. \nIn SQL this would be equivalent to a <code>SELECT</code> clause.</li>\n<li>Perform the calculations for each of the statistics you want on the metrics you obtained.</li>\n<li>Return a <code>Result</code> for each combination of metrics and stats with the calculated value.</li>\n</ol>\n\n<p>Right now performing the calculation is something that <code>calcStatValue</code> knows about. This makes it a bit annoying to add an additional statistic like MEDIAN, because you need to track down the switch-case statement. </p>\n\n<p>To avoid this, the calculation should be the responsibility of the statistic itself. Given that you can have members on Enums, the following should work:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public enum Statistic {\n MIN(values -&gt; Collections.min(values)),\n MAX(values -&gt; Collections.max(values)),\n AVERAGE(values -&gt; values.stream().mapToDouble(v -&gt; v).average().orElse(0.0));\n\n private final Function&lt;Collection&lt;Double&gt;, Double&gt; aggregator;\n\n private Statistic(Function&lt;Collection&lt;Double&gt;, Double&gt; aggregator) {\n this.aggregator = aggregator;\n }\n\n public double performStatOperation(Collection&lt;Double&gt; values) {\n return aggregator.apply(values);\n }\n}\n</code></pre>\n\n<p>The rest of my suggestions basically boils down to some minor changes:</p>\n\n<ul>\n<li>If you preinitialize the size of <code>results</code> in <code>analyze</code>, you should use the actual number of slots you'll be using with <code>new ArrayList&lt;&gt;(metrics.size() * stats.size())</code>.</li>\n<li>You don't gain significant benefits from converting the <code>List</code> parameters to <code>HashSet</code>s. If you want to force uniqueness in the implementation, you really should be communicating that in the public API of your class by only accepting Sets in the first place.</li>\n<li><p><code>calcStatValue</code> can be simplified using streams:</p>\n\n<pre><code>return stat.performStatOperation(students.stream()\n .map(s -&gt; s.getMetric(metric))\n .collect(Collectors.toSet()));\n</code></pre></li>\n<li>A similar simplification applies to <code>analyze</code>, but I'll not write that out here.</li>\n</ul>\n\n<p>Additional remarks:</p>\n\n<ul>\n<li>The <code>results.add([..])</code> line in <code>analyze</code> has inconsistent spacing at the parentheses.</li>\n<li>Using a specific collection implementation as API (i.e. <code>HashSet</code> as parameter) should be avoided.</li>\n<li>The domain model representation sucks. Representing a metric by a String is not a good idea (because tyops), and forcing each metric to be represented in a <code>double</code> is also bad (because non-numeric metrics are a thing). In addition your API currently does not have any way to perform aggregation and analysis operations that do not yield a single result (e.g. histogramming, tallying, ...)</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T02:14:16.580", "Id": "225109", "ParentId": "225099", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T17:35:57.013", "Id": "225099", "Score": "-2", "Tags": [ "java", "statistics" ], "Title": "Efficiently calculate the statistics on a given metrics on a list of students" }
225099
<p>I'm trying to learn streams and hashmaps, in doing so I want to make a very scalable, very clean version of FizzBuzz while adhering to the book Clean Code by Robert Cecil Martin.</p> <pre><code>public class Main { public static void fizzBuzzHundredTimes(Map&lt;String, Integer&gt; fizzDivisor) throws ArithmeticException{ String output; // Avoid recreating String each iteration for (int i = 1; i &lt;= 100; i++) { final int finalI = i; // Variables used in lambda functions need to be final. output = fizzDivisor.entrySet() .stream() .filter(entry -&gt; finalI % entry.getValue() == 0) .map(entry -&gt; entry.getKey()) .collect(Collectors.joining("")); if (output.length() &gt; 0) { // the value was divisible. System.out.println(output); } else { System.out.println(i); } } } public static void main(String[] args) { Map&lt;String, Integer&gt; fizzMap = new HashMap&lt;&gt;(); fizzMap.put("Fizz",3); fizzMap.put("Buzz",5); fizzMap.put("Fuzz",7); fizzMap.put("Bizz",11); fizzMap.put("Biff",13); try{ // Avoid negative numbers fizzBuzzHundredTimes(fizzMap); } catch(Exception e){ System.err.println(e + "Was thrown"); } } } </code></pre>
[]
[ { "body": "<p>on the topic of Java 8 streams, You can replace the for loop with <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html\" rel=\"nofollow noreferrer\"><code>IntStream</code></a> which emits a stream of integer values.</p>\n\n<p>to emit a stream of values between 1 and 100 inclusive: </p>\n\n<pre><code>IntStream.rangeClosed(1, 100)\n .foreach(i -&gt; {\n //...\n });\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T06:58:24.263", "Id": "225115", "ParentId": "225101", "Score": "1" } }, { "body": "<ul>\n<li>You can use <code>output.isEmpty()</code> instead of checking its length.</li>\n<li>You might want to use a <code>LinkedHashMap</code> which presists the order of the elements as well. Right now the ordering will be seemingly random (Will it be BuzzFizzFuzzBiffBizz? Or FizzFuzzBiffBizzBuzz?) (technically it's deterministic, but it's based on the hashcodes of the strings, which is seemingly random)</li>\n<li><p>Your exception handling <code>System.err.println(e + \"Was thrown\");</code> doesn't tell you anything about why the exception happened. I would recommend using a logger (Slf4j / Log4j) and log the exception properly, or use <code>e.printStackTrace()</code> to make it easier for you to debug the problems.</p>\n\n<p>In your final version however, you should not need any exception handling as all the bugs that could cause them to appear should have been fixed - as this is an application based on pure logic and no network calls and stuff. </p></li>\n<li><p><code>String output; // Avoid recreating String each iteration</code> technically, the string is recreated each iteration anyway. There's nothing you can do to avoid that.</p>\n\n<p>You're only <em>declaring</em> it once. It's best practice to declare it in a small scope as possible, so I would recommend declaring it only when you initialize it.</p></li>\n<li>You could create another method to return a single string for a single number, instead of having one method to process all the 100 numbers.</li>\n<li><code>// Avoid negative numbers</code> I don't see how that comment is relevant at the location it is written. Negative numbers are prevented by the for-loop in your code.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T10:51:55.137", "Id": "225123", "ParentId": "225101", "Score": "2" } }, { "body": "<p>In order to be more readable, i would split the code into these three functions:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void fizzBuzzNTimes(Map&lt;String, Integer&gt; fizzDivisor, int times) {\n IntStream.rangeClosed(1,times)\n .mapToObj(n-&gt; ifEmpty( fizzBuzzForN(n,fizzDivisor), String.valueOf(n)) )\n .forEach(System.out::println);\n}\n\n\nprivate static String fizzBuzzForN(int n, Map&lt;String,Integer&gt; fizzDivisor) {\n return fizzDivisor\n .entrySet()\n .stream()\n .filter(entry -&gt; n % entry.getValue() == 0)\n .map(Map.Entry::getKey)\n .collect(Collectors.joining());\n}\n\nprivate static String ifEmpty (String value, String defaultValue) { \n return value.isEmpty() ? defaultValue : value; \n}\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T14:01:16.127", "Id": "225194", "ParentId": "225101", "Score": "2" } } ]
{ "AcceptedAnswerId": "225123", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T21:20:13.577", "Id": "225101", "Score": "3", "Tags": [ "java", "stream", "fizzbuzz" ], "Title": "A stream version of Fizz Buzz" }
225101
<p>I tried to make a dynamic tree in python. It is simple and i have gotten it to work so far. I created a function in main that generates some example data for the tree and then the main goal was to create a member function that uses recursion to print all the data (display_data()). The only issue with this that i have is the recursion depth problem, as well as the speed. Essentially the recursion and loop pattern builds up quite a bit on the overall run time. Also note this is a side project, I need to understand dynamic trees for a tic-tac-toe AI I am attempting(failing) to write.</p> <p>tree.py</p> <pre><code>class Tree(): """Implement a dynamic tree 1 / | \ / | \ 2 3 4 / \ / | \ 5 6 7 8 9 / / | \ 10 11 12 13 """ def __init__(self): self.children = [] self.data = [] def create_children(self, amount): for i in range(amount): self.children.append(Tree()) def create_data(self, data): for datum in data: self.data.append(datum) def display_data(self): print(self.data, end = ' ') for child in self.children: child.display_data() </code></pre> <p>main.py</p> <pre><code>from tree import Tree def example_data(root): """ ['Child', 1] ['nChild', 1] ['nChild', 2] ['Child', 2] ['nChild', 1] ['nChild', 2] ['Child', 3] ['nChild', 1] ['nChild', 2] """ root.create_data(["Root"]) root.create_children(3) counter = 1 for child in root.children: child.create_data(["Child", counter]) child.create_children(2) counter += 1 ncounter = 1 for nchild in child.children: nchild.create_data(["nChild", ncounter]) ncounter += 1 return root if __name__ == "__main__": root = example_data(Tree()) root.display_data() </code></pre>
[]
[ { "body": "<p>Specific suggestions:</p>\n\n<ol>\n<li>It is idiomatic to wrap the stuff after <code>if __name__ == \"__main__\":</code> in a <code>main</code> function.</li>\n<li>Rather than the generic <code>data</code> I would suggest figuring out exactly which information you want to attach to each <code>Tree</code> and creating fields for each of them rather than a fully generic <code>list</code> of stuff. This will make it much less painful to work with actual <code>Tree</code>s because you can use for example <code>tree.name</code> or <code>tree.counter</code> instead of <code>tree.data[0]</code> and <code>tree.data[1]</code>.</li>\n<li>You can <code>enumerate</code> a <code>list</code> to loop over it without maintaining a separate index variable, as in <code>for index, child in enumerate(root.children):</code></li>\n</ol>\n\n<p>In general it'll be much easier to see how to improve this code once it's wired into a production use case rather than example code. The problem with writing code to an example \"spec\" is that the example inevitably doesn't completely fit the production use case - some crucial features will be missing and others will be superfluous. For example, storing the count of children separately. This information is already encoded in the length of the <code>children</code> <code>list</code>, so you are duplicating the information for no obvious reason. This could conceivably be useful if you're dealing with giant amounts of data, but if your application is sufficiently optimized that this is a real concern you probably should look into other languages or frameworks like numpy or pandas.</p>\n\n<p>General suggestions:</p>\n\n<ol>\n<li><a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic.</li>\n<li><a href=\"https://github.com/timothycrosley/isort\" rel=\"nofollow noreferrer\"><code>isort</code></a> can group and sort your imports automatically.</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"nofollow noreferrer\"><code>flake8</code></a> with a strict complexity limit will give you more hints to write idiomatic Python:</p>\n\n<pre><code>[flake8]\nmax-complexity = 4\nignore = W503,E203\n</code></pre>\n\n<p>(The max complexity limit is not absolute by any means, but it's worth thinking hard whether you can keep it low whenever validation fails. For example, I'm working with a team on an application since a year now, and our complexity limit is up to 7 in only one place. Conversely, on an ugly old piece of code I wrote without static analysis support I recently found the complexity reaches 87!)</p></li>\n<li><p>I would then recommend adding <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> everywhere and validating them using a strict <a href=\"https://github.com/python/mypy\" rel=\"nofollow noreferrer\"><code>mypy</code></a> configuration:</p>\n\n<pre><code>[mypy]\ncheck_untyped_defs = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T05:38:57.800", "Id": "225113", "ParentId": "225105", "Score": "2" } } ]
{ "AcceptedAnswerId": "225113", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T00:37:46.910", "Id": "225105", "Score": "2", "Tags": [ "python", "performance", "tree" ], "Title": "Simple dynamic tree in Python" }
225105
<p>Note: This is part of a set of demo applications I'm writing for colleagues to show we're not limited to VBA when dealing with Excel. Considering our IT challenges (no admin on-site &amp; no local-admin privileges), this has to work on Portable Python without external libraries. Specifically, the Python 3.7.2(x64) shell from <a href="https://winpython.github.io/" rel="noreferrer">WinPython</a> (on Windows 7 and Excel 2013) is used and while in theory we should be able to use <a href="https://github.com/winpython/winpython/wiki/WPPM" rel="noreferrer">WPPM</a> to install external libraries, so far we're out of luck.</p> <p>This is a haphazard solution NOT recommended to be used in the field! If you want to fasten a screw, use a screwdriver. Not a hammer. But sometimes you only have hammers in your toolbox.</p> <hr> <p>Part of the reason I'm doing this is that we need to import/export our data from/to external sources in an ugly copy/paste style without proper information pipes. Jumping around in Excel, adding data to fields and doing something with that data. So that's the first thing I made a demo for.</p> <p>Arguably it's not doing much useful yet, but it shows a lot more of the options available than a Hello, World example. Python has something with <a href="https://en.wikipedia.org/wiki/Monty_Python_and_the_Holy_Grail" rel="noreferrer">knights</a>, so I jump around a bit following a hardcoded <a href="https://en.wikipedia.org/wiki/Knight&#39;s_tour" rel="noreferrer">Knight's Tour</a>, fill in some data, use a bit of formatting, create some calculations, it's nicely showing what it should.</p> <p>Oh, and if you think this doesn't look so bad (it does), wait till the next demo.</p> <p>I may need more functions, perhaps a couple of wrappers, but that seemed overkill at the moment. Enums may be good too, since I seem to do a lot of enumerating anyway. And more constants, though that tends to get messy. I've considered creating <code>tour_ws()</code> and <code>calc_ws()</code>, mainly to cut the code in chunks, but this would be a poor usage of functions. Perhaps passing the instance, worksheets or other objects around is a better idea, not particularly sure what that would look like though.</p> <p>The pseudo-consts are in the same file since importing from files is bit of an issue with this configuration, it seems. I know I'm not supposed to do it like this.</p> <p>As usual I'm mainly interested in doing it the right way, although that may not always be possible in this case. My naming is terrible, performance is already satisfactory. I'm not sure whether I should be handling my memory better or that the GC will take care of it. What I can't have, is the program halting its execution because the opened program (Excel) is still open.</p> <h3>knights_tour.py</h3> <pre><code>import win32com.client """ Excellent Knight's Tour """ # (X, Y) POSITIONS = [ (8, 1), (7, 3), (6, 1), (8, 2), (7, 4), (5, 3), (4, 1), (2, 2), (1, 4), (3, 3), (2, 1), (1, 3), (3, 4), (2, 6), (1, 8), (3, 7), (2, 5), (1, 7), (3, 8), (4, 6), (5, 8), (6, 6), (4, 5), (5, 7), (7, 8), (8, 6), (6, 5), (7, 7), (8, 5), (6, 4), (5, 2), (4, 4), (3, 6), (1, 5), (2, 7), (3, 5), (1, 6), (2, 8), (4, 7), (5, 5), (6, 3), (7, 1), (8, 3), (7, 5), (8, 7), (6, 8), (5, 6), (4, 8), (6, 7), (8, 8), (7, 6), (8, 4), (7, 2), (5, 1), (4, 3), (3, 1), (1, 2), (2, 4), (3, 2), (1, 1), (2, 3), (4, 2), (5, 4), (6, 2) ] # Only formulae accepting range notations are supported # Oddly enough sending English names also works on Dutch locale FORMULAE = [ "AVERAGE", "AVEDEV", "MIN", "MAX" ] # Offsets required to get to pre-defined characters # chr(65) = A # chr(72) = H # chr(10+55) = chr(65) CONST_A = 65 CONST_H = 72 OFFSET = 55 def range_format(formula, target, i): if i &lt; 9: return "={0}('{1}'!{2}{3}:{4}{5})".format( formula, target, chr(CONST_A), i, chr(CONST_H), i) elif i &lt; 10: return "" else: return "={0}('{1}'!{2}{3}:{4}{5})".format( formula, target, chr(i + OFFSET), 1, chr(i + OFFSET), 8) def main(): xls_instance = win32com.client.gencache.EnsureDispatch("Excel.Application") xls_instance.Visible = 1 wb = xls_instance.Workbooks.Add() wb.ActiveSheet.Name = "Knight Tour" # Select default sheet (Excel 2013) # Optional. The sheet is already created # and as long as only one sheet exists # it can be targetted by referring to the instance # itself. tour_ws = wb.Worksheets("Knight Tour") # Width 2.86 by Height 18.75 is exactly 25 by 25 pixels tour_ws.Columns("A:H").ColumnWidth = 2.86 tour_ws.Rows("1:8").RowHeight = 18.75 tour_ws.Range("A1:H8").FormatConditions.AddColorScale(3) # Iterate over all POSITIONS, filling them with their index + 1 # to compensate for 0-indexed list. # For some reason Cells appears to require Y before X. for idx, position in enumerate(POSITIONS): tour_ws.Cells(position[1], position[0]).Value = idx + 1 tour_ws.Range("A1:H8").VerticalAlignment = \ win32com.client.constants.xlCenter tour_ws.Range("A1:H8").HorizontalAlignment = \ win32com.client.constants.xlCenter # Create a new worksheet to jot down the demo calculations on calc_ws = wb.Worksheets.Add() calc_ws.Name = "Calculations" for idx, formula in enumerate(FORMULAE): for i in range(1, 18): calc_ws.Cells( str(i), 1 + idx).Value = range_format(formula, tour_ws.Name, i) for idx, _ in enumerate(FORMULAE): calc_ws.Range( "{0}1:{0}17".format( chr(idx + CONST_A))).FormatConditions.AddColorScale(3) if __name__ == "__main__": main() </code></pre> <h3>Result</h3> <p><a href="https://i.stack.imgur.com/kbGQE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kbGQE.png" alt="Knight Tour"></a></p> <p><a href="https://i.stack.imgur.com/WV4JG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WV4JG.png" alt="Calculations"></a></p>
[]
[ { "body": "<p>As you mention, some of this is messy and haphazard, which is a side-effect of writing one-off scripts that have a single behavior they need to perform, instead of something extensible. In that case, this review is going to largely focus on how we make this extensible and use our hammer to build a screwdriver (among other things).</p>\n\n<hr>\n\n<p>If we start at how we interact with cells and ranges, it becomes pretty clear that we have a lot of stuff going on</p>\n\n<ul>\n<li>ASCII constants and offsets</li>\n<li>Hardcoded row/column limits</li>\n<li>Hardcoded sizes</li>\n<li>etc</li>\n</ul>\n\n<p>What I think we want is a well designed <code>ExcelSheetRange</code> class that handles a few things:</p>\n\n<ul>\n<li>R1C1 vs A1 reference styles \n\n<ul>\n<li>Relative references (<code>A1</code> or <code>R[1]C[1]</code>)</li>\n<li>Absolute references (<code>$A$1</code> or <code>R1C1</code>)</li>\n<li>Semi absolute/relative reference (<code>$A1</code> or <code>A$1</code> or <code>R1C[1]</code> or <code>R[1]C1</code>)</li>\n</ul></li>\n<li>translation between an index and the Excel Cells</li>\n<li>efficient range transformations</li>\n</ul>\n\n<p>I imagine you could implement a base class <code>ExcelSheetRange</code>, then at least 2 subclasses (one each for R1C1 and A1). That would be a lot, so I'll skip it, but assuming we can do that then some of this code gets much cleaner:</p>\n\n<pre><code>return \"={0}('{1}'!{2}{3}:{4}{5})\".format(formula, target, chr(CONST_A), i, chr(CONST_H), i)\n# becomes\nreturn \"={0}('{1}'!{2})\".format(formula, target, ExcelSheetRange('A', i, 'H', i))\n\ntour_ws.Columns(\"A:H\").ColumnWidth = 2.86\n#becomes\ntour_ws.Columns(ExcelSheetRange(\"A\", 1, \"H\", 8).column_range) = 2.86\n</code></pre>\n\n<p>From there, we get a few generalizable problems:</p>\n\n<ul>\n<li>Formatting cells</li>\n<li>putting a value in a cell</li>\n<li>performing a calculation on a range</li>\n</ul>\n\n<p>You could add some enhancements to this presumed <code>ExcelSheetRange</code> class such as <code>cell_size_in_px</code>, <code>cell_color_scale</code>, <code>cell_value</code>, <code>cell_vertical_alignment</code>, etc. Then a lot of your operations get even easier</p>\n\n<pre><code>range = ExcelSheetRange(\"A\", 1, \"H\", 8)\nrange.cell_size_in_px = (25, 25) # abstracts away Microsoft's weird measurement rules\nrange.cell_color_scale = 3 # Whatever this means; if there is something more useful and understandable to put here then do that\n</code></pre>\n\n<p>Then if we have a simple <code>apply_to_sheet</code> operation we could just do</p>\n\n<pre><code>range.apply_to_sheet(tour_ws)\n# or if you want some dependency injectable method so you can test it, you could do\napply_range_to_sheet(range, tour_ws)\n</code></pre>\n\n<p>Assuming we've implemented all of this, then the program becomes pretty simple</p>\n\n<pre><code>def main():\n wb, tour_sheet, calc_sheet = get_knight_tour_workbook()\n\n knight_tour_range = ExcelSheetRange(\"A\", 1, \"H\", 8)\n knight_tour_range.cell_size_in_px = (\n 25,\n 25,\n ) # Assume property with a setter that does scaling as appropriate\n knight_tour_range.cell_color_scale = 3\n knight_tour_range.literal_values = [\n (x_pos, y_pos, value)\n for value, (x_pos, y_pox) in enumerate(positions, 1)\n ] # Assume property with a setter that stores the values in an intermediate array\n knight_tour_range.alignment = AlignmentEnum.Center # Assume this is a property with a setter that can figure out that horizontal and vertical are the same\n\n calculation_ranges = []\n\n for i, formula in enumerate(FORMULAE, 1):\n calculation_range = ExcelSheetRange(1, i, 17, i)\n calculation_range.cell_color_scale = 3\n calculation_range.calculated_values = [\n (\n i,\n row,\n get_function_call(\n row, formula, tour_sheet.Name\n ),\n )\n for row in range(1, 18)\n ]\n calculation_ranges.append(calculation_range)\n\n apply_range_to_sheet(tour_sheet, knight_tour_range)\n apply_all_ranges_to_sheet(\n calc_sheet, *calculation_ranges\n )\n</code></pre>\n\n<p>I've left it a bit hand-wavy, and there are definitely additional improvements that can be made, but we've now pretty much separated the Excel manipulations and your actual logic. </p>\n\n<p>If we wanted to get really crazy, and really generic, we could even make our \"range\" stuff completely independent of Excel, and just lean really heavily on the <code>apply_*</code> functions. Getting even crazier and more generic, we split our \"here are calculations that should eventually be performed on these sets of values\" and our \"here is how things should look\", and pass them both into some kind of \"tabular data visualization tool\" that is generic to actual visualization application, and then make an Excel implementation that quacks the same way. This is probably going too far.</p>\n\n<hr>\n\n<p>Some nitpicky things</p>\n\n<pre><code>def range_format(formula, target, i):\n if i &lt; 9:\n return \"={0}('{1}'!{2}{3}:{4}{5})\".format(\n formula, target, chr(CONST_A), i, chr(CONST_H), i)\n elif i &lt; 10:\n return \"\"\n else:\n return \"={0}('{1}'!{2}{3}:{4}{5})\".format(\n formula, target, chr(i + OFFSET), 1, chr(i + OFFSET), 8)\n</code></pre>\n\n<p>This function is a bit clunky as-is:</p>\n\n<ul>\n<li><code>elif i &lt; 10</code> should just be <code>elif i == 9</code></li>\n<li>You can use <code>f</code>-strings here</li>\n<li>You duplicate the formatting logic as well (also you don't need to specify <code>i</code> twice)</li>\n</ul>\n\n<p>I would probably want to write this:</p>\n\n<pre><code>def range_format(formula, target, i):\n if i == 9:\n return \"\"\n\n start_row = chr(CONST_A) if i &lt; 9 else chr(i + OFFSET)\n start_col = i if i &lt; 9 else 1\n end_row = chr(CONST_H) if i &lt; 9 else chr(i + OFFSET)\n end_col = i if i &lt; 9 else 8\n\n return f\"={formula}('{target}'!{start_row}{start_col}:{end_row}{end_col})\"\n</code></pre>\n\n<p>Then, as you mention, you probably want a bit better validation on the allowed functions. An <code>enum</code> would be fine to meet this need.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-11T19:36:33.797", "Id": "228869", "ParentId": "225118", "Score": "4" } } ]
{ "AcceptedAnswerId": "228869", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T08:44:50.007", "Id": "225118", "Score": "12", "Tags": [ "python", "python-3.x", "excel", "portability", "com" ], "Title": "Not so Excellent Knight's Tour" }
225118
<p>In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way:</p> <p>High Card: Highest value card.</p> <p>One Pair: Two cards of the same value.</p> <p>Two Pairs: Two different pairs.</p> <p>Three of a Kind: Three cards of the same value.</p> <p>Straight: All cards are consecutive values.</p> <p>Flush: All cards of the same suit.</p> <p>Full House: Three of a kind and a pair.</p> <p>Four of a Kind: Four cards of the same value.</p> <p>Straight Flush: All cards are consecutive values of same suit.</p> <p>Royal Flush: Ten, Jack, Queen, King, Ace, in same suit.</p> <p>The cards are valued in the order: 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace.</p> <p>The file, poker.txt, contains one-thousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1's cards and the last five are Player 2's cards. You can assume that all hands are valid (no invalid characters or repeated cards), each player's hand is in no specific order, and in each hand there is a clear winner.</p> <p>How many hands does Player 1 win?</p> <pre><code>import operator from time import time CARD_RANKS = {'2': 1, '3': 2, '4': 3, '5': 4, '6': 5, '7': 6, '8': 7, '9': 8, 'T': 9, 'J': 10, 'Q': 11, 'K': 12, 'A': 13} def get_hands(filename): """returns player 1 and player 2 hands.""" hands = open(filename).read().rstrip().split('\n') hand1 = [hand.split()[:5] for hand in hands] hand2 = [hand.split()[5:] for hand in hands] return hand1, hand2 def get_card_value(card): """returns card value ex: KC --&gt; K.""" return card[:-1] def get_card_suit(card): """returns card suit ex: 10D --&gt; D.""" return card[-1] def is_one_pair(hand): """returns True for one pair, else False.""" hand_values = [get_card_value(card) for card in hand] val_count = {card: hand_values.count(card) for card in hand_values} pair_val = [card for card in hand_values if hand_values.count(card) == 2] pair_count = sum(1 for val in val_count.values() if val == 2) if pair_count == 1: return True, pair_val[0] return False def is_two_pair(hand): """returns True for two pair, else False.""" hand_values = [get_card_value(card) for card in hand] val_count = {card: hand_values.count(card) for card in hand_values} pair_count = sum(1 for val in val_count.values() if val == 2) if pair_count == 2: return True return False def is_three_of_a_kind(hand): """returns True for three of a kind, else False.""" hand_values = [get_card_value(card) for card in hand] val_count = {card: hand_values.count(card) for card in hand_values} if 3 in val_count.values(): return True return False def is_straight(hand): """returns True for a straight, False otherwise.""" valid_ranges = [['A', '2', '3', '4', '5'], ['6', '7', '8', '9', 'T']] for index in range(2, 6): valid = [str(num) for num in range(index, index + 5)] valid_ranges.append(valid) hand_vals = [get_card_value(card) for card in hand] for valid_range in valid_ranges: check = 1 for value in valid_range: if value not in hand_vals: check = 0 if check == 1: return True return False def is_flush(hand): """returns True for a flush, False otherwise.""" return len(set(get_card_suit(card) for card in hand)) == 1 def is_full_house(hand): """returns True for a full house, False otherwise.""" if is_one_pair(hand) and is_three_of_a_kind(hand): return True return False def is_four_of_a_kind(hand): """returns True for four of a kind, False otherwise.""" hand_values = [get_card_value(card) for card in hand] val_count = {card: hand_values.count(card) for card in hand_values} if 4 in val_count.values(): return True return False def is_straight_flush(hand): """returns True for a straight flush, False otherwise.""" if is_straight(hand) and is_flush(hand): return True return False def is_royal_flush(hand): """returns True for a royal flush, False otherwise.""" hand_vals = [get_card_value(card) for card in hand] valid_cards = ['A', 'K', 'Q', 'J', 'T'] if is_flush(hand): for valid in valid_cards: if valid not in hand_vals: return False return True return False def get_first_hand_max(hand): """returns the value of the 1st maximum card in hand.""" hand_vals = {card: CARD_RANKS[card[:-1]] for card in hand} return max(hand_vals.values()) def get_second_hand_max(hand): """returns value of the 2nd maximum card in hand.""" hand_vals = sorted([(card, CARD_RANKS[card[:-1]]) for card in hand], key=operator.itemgetter(1), reverse=True) return hand_vals[1][1] def get_hand_score(hand): """returns the hand and a score.""" scores = {is_one_pair(hand): 1, is_two_pair(hand): 2, is_three_of_a_kind(hand): 3, is_straight(hand): 4, is_flush(hand): 5, is_full_house(hand): 6, is_four_of_a_kind(hand): 7, is_straight_flush(hand): 8, is_royal_flush(hand): 9} total = 0 for x, y in scores.items(): if x: total += y return hand, total def compare_hands(hand1, hand2): """returns 1 for hand1 or 2 for hand2 if either wins.""" hand1, score1 = get_hand_score(hand1) hand2, score2 = get_hand_score(hand2) if score1 == score2 == 0: max1 = get_first_hand_max(hand1) max2 = get_first_hand_max(hand2) if max1 &gt; max2: return 1 if max2 &gt; max1: return 2 if max1 == max2: max11 = get_second_hand_max(hand1) max22 = get_second_hand_max(hand2) if max11 &gt; max22: return 1 if max22 &gt; max11: return 2 if score1 == score2 == 1: max1 = CARD_RANKS[is_one_pair(hand1)[1]] max2 = CARD_RANKS[is_one_pair(hand2)[1]] if max1 &gt; max2: return 1 if max2 &gt; max1: return 2 if score1 &gt; score2: return 1 if score2 &gt; score1: return 2 if __name__ == '__main__': start_time = time() hands1, hands2 = get_hands('p054_poker.txt') scores = [compare_hands(hands1[i], hands2[i]) for i in range(len(hands1) - 1)] player1_score = sum(1 for player in scores if player == 1) print(f'Player 1 score: {player1_score}') print(f'Time: {time() - start_time} seconds.') </code></pre>
[]
[ { "body": "<p><strong>Comparison to boolean values</strong></p>\n\n<p>This has been said in <a href=\"https://codereview.stackexchange.com/questions/224843/project-euler-52-permuted-multiples-in-python/224895#224895\">other reviews before</a> but instead of</p>\n\n<pre><code>if cond:\n return True\nreturn False\n</code></pre>\n\n<p>You can and should simply write:</p>\n\n<pre><code>return cond\n</code></pre>\n\n<p>This comments applies to various parts of your code:</p>\n\n<pre><code>def is_two_pair(hand):\n \"\"\"returns True for two pair, else False.\"\"\"\n hand_values = [get_card_value(card) for card in hand]\n val_count = {card: hand_values.count(card) for card in hand_values}\n pair_count = sum(1 for val in val_count.values() if val == 2)\n return pair_count == 2\n\n\ndef is_three_of_a_kind(hand):\n \"\"\"returns True for three of a kind, else False.\"\"\"\n hand_values = [get_card_value(card) for card in hand]\n val_count = {card: hand_values.count(card) for card in hand_values}\n return 3 in val_count.values()\n\n\ndef is_full_house(hand):\n \"\"\"returns True for a full house, False otherwise.\"\"\"\n return is_one_pair(hand) and is_three_of_a_kind(hand)\n\n\ndef is_four_of_a_kind(hand):\n \"\"\"returns True for four of a kind, False otherwise.\"\"\"\n hand_values = [get_card_value(card) for card in hand]\n val_count = {card: hand_values.count(card) for card in hand_values}\n return 4 in val_count.values()\n\n\ndef is_straight_flush(hand):\n \"\"\"returns True for a straight flush, False otherwise.\"\"\"\n return is_straight(hand) and is_flush(hand)\n</code></pre>\n\n<p><strong>Improvements of <code>is_royal_flush</code></strong></p>\n\n<p>You can return directly when it is not a flush:</p>\n\n<pre><code>def is_royal_flush(hand):\n \"\"\"returns True for a royal flush, False otherwise.\"\"\"\n if not is_flush(hand):\n return False\n hand_vals = [get_card_value(card) for card in hand]\n valid_cards = ['A', 'K', 'Q', 'J', 'T']\n for valid in valid_cards:\n if valid not in hand_vals:\n return False\n return True\n</code></pre>\n\n<p>You could use the <code>all</code> builtin:</p>\n\n<pre><code>hand_vals = [get_card_value(card) for card in hand]\nvalid_cards = ['A', 'K', 'Q', 'J', 'T']\nreturn all(valid in hand_vals for valid in valid_cards)\n</code></pre>\n\n<p>You could also use set comparison:</p>\n\n<pre><code>hand_vals = {get_card_value(card) for card in hand}\nvalid_cards = {'A', 'K', 'Q', 'J', 'T'}\nreturn hand_vals == valid_cards\n</code></pre>\n\n<p><strong>Improvements in handling of <code>hands</code></strong></p>\n\n<p>Once again, <a href=\"https://codereview.stackexchange.com/questions/224646/project-euler-43-sub-string-divisibility-in-python/224928#224928\">this has been said before</a> but: in general, it is best to avoid using range when what you want is to iterate over an iterable - see also <a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"nofollow noreferrer\">Ned Batchelder's excellent talk: \"Loop like a native\"</a>.</p>\n\n<p>Here, we'd have:</p>\n\n<pre><code>scores = [compare_hands(h1, h2) for (h1, h2) in zip(hands1, hands2)]\n</code></pre>\n\n<p>Note: this leads to a slightly different behavior as the last hand used to be ignored. Was this a bug ?</p>\n\n<p>Also this suggests that things could be done in a different way: instead of returning a tuple of lists, it would make more sense to return a list of tuples.</p>\n\n<pre><code>def get_hands(filename):\n \"\"\"returns player 1 and player 2 hands.\"\"\"\n hands = open(filename).read().rstrip().split('\\n')\n return [(hand.split()[:5], hand.split()[5:]) for hand in hands]\n\n...\n\n hands = get_hands('p054_poker.txt')\n scores = [compare_hands(h1, h2) for (h1, h2) in hands]\n</code></pre>\n\n<p>Also, we could call <code>split</code> only once on each string:</p>\n\n<pre><code>def get_hands(filename):\n \"\"\"returns player 1 and player 2 hands.\"\"\"\n lines = open(filename).read().rstrip().split('\\n')\n splitted_lines = [l.split() for l in lines]\n return [(l[:5], l[5:]) for l in splitted_lines]\n</code></pre>\n\n<p><strong>Improve <code>get_first_hand_max</code></strong></p>\n\n<p>The function uses a dictionnary without any particular reason.\nWe could use a <code>set</code> with little or no change:</p>\n\n<pre><code>def get_first_hand_max(hand):\n \"\"\"returns the value of the 1st maximum card in hand.\"\"\"\n hand_vals = {CARD_RANKS[card[:-1]] for card in hand}\n return max(hand_vals)\n</code></pre>\n\n<p>or even no particular data structure:</p>\n\n<pre><code>def get_first_hand_max(hand):\n \"\"\"returns the value of the 1st maximum card in hand.\"\"\"\n return max(CARD_RANKS[card[:-1]] for card in hand)\n</code></pre>\n\n<p><strong>Improve <code>is_straight</code></strong></p>\n\n<p>The inner loop could use a break to stop as soon as check is set to 0.</p>\n\n<p>This is also a good chance to get familiar with the optional <code>else</code> clause for a for loop:</p>\n\n<pre><code> for value in valid_range:\n if value not in hand_vals:\n break\n else: # no break\n return True\n</code></pre>\n\n<p>Alternatively, this could be written with all:</p>\n\n<pre><code>def is_straight(hand):\n \"\"\"returns True for a straight, False otherwise.\"\"\"\n valid_ranges = [['A', '2', '3', '4', '5'], ['6', '7', '8', '9', 'T']]\n for index in range(2, 6):\n valid = [str(num) for num in range(index, index + 5)]\n valid_ranges.append(valid)\n hand_vals = [get_card_value(card) for card in hand]\n for valid_range in valid_ranges:\n if all(value in hand_vals for value in valid_range):\n return True\n return False\n</code></pre>\n\n<p><strong>Consistency</strong></p>\n\n<p>You have defined <code>get_card_value</code>. You should use it in <code>get_first_hand_max</code> and <code>get_second_hand_max</code>:</p>\n\n<pre><code>def get_first_hand_max(hand):\n \"\"\"returns the value of the 1st maximum card in hand.\"\"\"\n return max(CARD_RANKS[get_card_value(card)] for card in hand)\n\n\ndef get_second_hand_max(hand):\n \"\"\"returns value of the 2nd maximum card in hand.\"\"\"\n hand_vals = sorted([(card, CARD_RANKS[get_card_value(card)]) for card in hand], key=operator.itemgetter(1), reverse=True)\n return hand_vals[1][1]\n</code></pre>\n\n<p><strong>Using classes</strong></p>\n\n<p>Code could be reorganised by using well defined data structure.\nFor example, instead of using strings everywhere, we could use a <code>Card</code> object.</p>\n\n<p>This can be introduced with minimal changes:</p>\n\n<pre><code>class Card:\n def __init__(self, value, suit):\n self.value = value\n self.suit = suit\n\n @classmethod\n def from_string(cls, card):\n value = card[:-1]\n suit = card[-1]\n return cls(value, suit)\n\n def __str__(self):\n return self.value + \", \" + self.suit\n\n def __repr__(self):\n return self.__class__.__name__ + \"(\" + self.value + \", \" + self.suit +\")\"\n\n\ndef get_hands(filename):\n \"\"\"returns player 1 and player 2 hands.\"\"\"\n lines = open(filename).read().rstrip().split('\\n')\n splitted_lines = [[Card.from_string(c) for c in l.split()] for l in lines]\n return [(l[:5], l[5:]) for l in splitted_lines]\n\n\ndef get_card_value(card):\n \"\"\"returns card value ex: KC --&gt; K.\"\"\"\n return card.value\n\n\ndef get_card_suit(card):\n \"\"\"returns card suit ex: 10D --&gt; D.\"\"\"\n return card.suit\n</code></pre>\n\n<p>Once this is done, we can easily get rid of <code>get_card_value</code> and <code>get_card_suit</code>.</p>\n\n<p><strong>Using <code>Counter</code></strong></p>\n\n<p>You can use <code>Counter</code> from the collection module</p>\n\n<p><strong>Improving <code>get_hand_score</code></strong></p>\n\n<p><code>get_hand_score</code> returns both a hand and a score. I don't really understand how returning the hand is useful.</p>\n\n<p>We can simplify the code:</p>\n\n<pre><code>def get_hand_score(hand):\n \"\"\"returns the score.\"\"\"\n scores = {is_one_pair(hand): 1, is_two_pair(hand): 2, is_three_of_a_kind(hand): 3, is_straight(hand): 4,\n is_flush(hand): 5, is_full_house(hand): 6, is_four_of_a_kind(hand): 7, is_straight_flush(hand): 8,\n is_royal_flush(hand): 9}\n total = 0\n for x, y in scores.items():\n if x:\n total += y\n return total\n\n\ndef compare_hands(hand1, hand2):\n \"\"\"returns 1 for hand1 or 2 for hand2 if either wins.\"\"\"\n score1 = get_hand_score(hand1)\n score2 = get_hand_score(hand2)\n</code></pre>\n\n<p>Also, we could use <code>sum</code> in <code>get_hand_score</code>.</p>\n\n<pre><code>def get_hand_score(hand):\n \"\"\"returns the score.\"\"\"\n scores = {is_one_pair(hand): 1, is_two_pair(hand): 2, is_three_of_a_kind(hand): 3, is_straight(hand): 4,\n is_flush(hand): 5, is_full_house(hand): 6, is_four_of_a_kind(hand): 7, is_straight_flush(hand): 8,\n is_royal_flush(hand): 9}\n return sum(y for x, y in scores.items() if x)\n</code></pre>\n\n<p><strong>Simplify <code>compare_hands</code></strong></p>\n\n<p>You can consider:</p>\n\n<pre><code>if score1 &gt; score2:\n return 1\nif score2 &gt; score1:\n return 2\n</code></pre>\n\n<p>at the beginning of the function so that you can assume <code>score1 == score2</code> in the following part of the function.</p>\n\n<p>Then, we get:</p>\n\n<pre><code>def compare_hands(hand1, hand2):\n \"\"\"returns 1 for hand1 or 2 for hand2 if either wins.\"\"\"\n score1 = get_hand_score(hand1)\n score2 = get_hand_score(hand2)\n\n if score1 &gt; score2:\n return 1\n if score2 &gt; score1:\n return 2\n\n assert score1 == score2\n\n if score1 == 0:\n max1 = get_first_hand_max(hand1)\n max2 = get_first_hand_max(hand2)\n if max1 &gt; max2:\n return 1\n if max2 &gt; max1:\n return 2\n assert max1 == max2\n max11 = get_second_hand_max(hand1)\n max22 = get_second_hand_max(hand2)\n if max11 &gt; max22:\n return 1\n if max22 &gt; max11:\n return 2\n if score1 == 1:\n max1 = CARD_RANKS[is_one_pair(hand1)[1]]\n max2 = CARD_RANKS[is_one_pair(hand2)[1]]\n if max1 &gt; max2:\n return 1\n if max2 &gt; max1:\n return 2\n</code></pre>\n\n<p><em>Improve <code>is_one_pair</code></em></p>\n\n<p>The docstring is wrong as we do return <em>only</em> True.</p>\n\n<p>We could compute <code>pair_val</code> only in the <code>pair_count == 1</code> case.</p>\n\n<p>Also, we could iterate over the Counter directly:</p>\n\n<pre><code>def is_one_pair(hand):\n \"\"\"returns True for one pair, else False.\"\"\"\n hand_values = [card.value for card in hand]\n val_count = Counter(hand_values)\n pairs = [value for value, count in val_count.items() if count == 2]\n if len(pairs) == 1:\n return True, pairs[0]\n return False\n</code></pre>\n\n<p><strong>More simplification in <code>get_hand_score</code></strong></p>\n\n<p>At the moment, the function calls many functions and somehow adds their result.\nWe could just try everything starting from the higher value to the smaller value until we find a match:</p>\n\n<pre><code>def get_hand_score(hand):\n \"\"\"returns the score.\"\"\"\n if is_royal_flush(hand): return 9\n if is_straight_flush(hand): return 8\n if is_four_of_a_kind(hand): return 7\n if is_full_house(hand): return 6\n if is_flush(hand): return 5\n if is_straight(hand): return 4\n if is_three_of_a_kind(hand): return 3\n if is_two_pair(hand): return 2\n if is_one_pair(hand): return 1\n return 0\n</code></pre>\n\n<p>Or using a data structure (note that unlike in your code, we don't call always call all the functions):</p>\n\n<pre><code>def get_hand_score(hand):\n \"\"\"returns the score.\"\"\"\n scores = [\n (is_royal_flush, 9),\n (is_straight_flush, 8),\n (is_four_of_a_kind, 7),\n (is_full_house, 6),\n (is_flush, 5),\n (is_straight, 4),\n (is_three_of_a_kind, 3),\n (is_two_pair, 2),\n (is_one_pair, 1),\n ]\n for func, score in scores:\n if func(hand):\n return score\n return 0\n</code></pre>\n\n<p><strong>Storing directly rank instead of value</strong></p>\n\n<p>We could compute the ranks from the Card class directly and never rely on the \"stringed\" value:</p>\n\n<pre><code>@classmethod\ndef from_string(cls, card):\n value = CARD_RANKS[card[:-1]]\n suit = card[-1]\n return cls(value, suit)\n</code></pre>\n\n<p>There are a few places to change so I'll let you do it.</p>\n\n<p><strong>Stopping at this point</strong></p>\n\n<p>At this stage, the code I have is:</p>\n\n<pre><code>import operator\nfrom time import time\nfrom collections import Counter\n\n\nCARD_RANKS = {'2': 1, '3': 2, '4': 3, '5': 4, '6': 5, '7': 6, '8': 7, '9': 8, 'T': 9, 'J': 10, 'Q': 11, 'K': 12, 'A': 13}\n\nclass Card:\n def __init__(self, value, suit):\n self.value = value\n self.suit = suit\n\n @classmethod\n def from_string(cls, card):\n value = card[:-1] # CARD_RANKS[card[:-1] could be nice\n suit = card[-1]\n return cls(value, suit)\n\n def __str__(self):\n return self.value + \", \" + self.suit\n\n def __repr__(self):\n return self.__class__.__name__ + \"(\" + self.value + \", \" + self.suit +\")\"\n\n\n\ndef get_hands(filename):\n \"\"\"returns player 1 and player 2 hands.\"\"\"\n lines = open(filename).read().rstrip().split('\\n')\n splitted_lines = [[Card.from_string(c) for c in l.split()] for l in lines]\n return [(l[:5], l[5:]) for l in splitted_lines]\n\n\ndef is_one_pair(hand):\n \"\"\"returns True for one pair, else False.\"\"\"\n pairs = [value for value, count in Counter(card.value for card in hand).items() if count == 2]\n if len(pairs) == 1:\n return True, pairs[0]\n return False\n\n\ndef is_two_pair(hand):\n \"\"\"returns True for two pair, else False.\"\"\"\n pairs = [value for value, count in Counter(card.value for card in hand).items() if count == 2]\n return len(pairs) == 2\n\n\ndef is_three_of_a_kind(hand):\n \"\"\"returns True for three of a kind, else False.\"\"\"\n return 3 in Counter(card.value for card in hand).values()\n\n\ndef is_straight(hand):\n \"\"\"returns True for a straight, False otherwise.\"\"\"\n valid_ranges = [['A', '2', '3', '4', '5'], ['6', '7', '8', '9', 'T']]\n for index in range(2, 6):\n valid = [str(num) for num in range(index, index + 5)]\n valid_ranges.append(valid)\n hand_vals = [card.value for card in hand]\n for valid_range in valid_ranges:\n if all(value in hand_vals for value in valid_range):\n return True\n return False\n\n\ndef is_flush(hand):\n \"\"\"returns True for a flush, False otherwise.\"\"\"\n return len(set(card.suit for card in hand)) == 1\n\n\ndef is_full_house(hand):\n \"\"\"returns True for a full house, False otherwise.\"\"\"\n return is_one_pair(hand) and is_three_of_a_kind(hand)\n\n\ndef is_four_of_a_kind(hand):\n \"\"\"returns True for four of a kind, False otherwise.\"\"\"\n val_count = Counter(card.value for card in hand)\n return 4 in val_count.values()\n\n\ndef is_straight_flush(hand):\n \"\"\"returns True for a straight flush, False otherwise.\"\"\"\n return is_straight(hand) and is_flush(hand)\n\n\ndef is_royal_flush(hand):\n \"\"\"returns True for a royal flush, False otherwise.\"\"\"\n if not is_flush(hand):\n return False\n hand_vals = {card.value for card in hand}\n valid_cards = {'A', 'K', 'Q', 'J', 'T'}\n return hand_vals == valid_cards\n\n\ndef get_first_hand_max(hand):\n \"\"\"returns the value of the 1st maximum card in hand.\"\"\"\n return max(CARD_RANKS[card.value] for card in hand)\n\n\ndef get_second_hand_max(hand):\n \"\"\"returns value of the 2nd maximum card in hand.\"\"\"\n hand_vals = sorted([(card, CARD_RANKS[card.value]) for card in hand], key=operator.itemgetter(1), reverse=True)\n return hand_vals[1][1]\n\n\ndef get_hand_score(hand):\n \"\"\"returns the score.\"\"\"\n scores = [\n (is_royal_flush, 9),\n (is_straight_flush, 8),\n (is_four_of_a_kind, 7),\n (is_full_house, 6),\n (is_flush, 5),\n (is_straight, 4),\n (is_three_of_a_kind, 3),\n (is_two_pair, 2),\n (is_one_pair, 1),\n ]\n for func, score in scores:\n if func(hand):\n return score\n return 0\n\n\ndef compare_hands(hand1, hand2):\n \"\"\"returns 1 for hand1 or 2 for hand2 if either wins.\"\"\"\n score1 = get_hand_score(hand1)\n score2 = get_hand_score(hand2)\n\n if score1 &gt; score2:\n return 1\n if score2 &gt; score1:\n return 2\n\n assert score1 == score2\n\n if score1 == 0:\n max1 = get_first_hand_max(hand1)\n max2 = get_first_hand_max(hand2)\n if max1 &gt; max2:\n return 1\n if max2 &gt; max1:\n return 2\n assert max1 == max2\n max11 = get_second_hand_max(hand1)\n max22 = get_second_hand_max(hand2)\n if max11 &gt; max22:\n return 1\n if max22 &gt; max11:\n return 2\n if score1 == 1: # One Pairs\n max1 = CARD_RANKS[is_one_pair(hand1)[1]]\n max2 = CARD_RANKS[is_one_pair(hand2)[1]]\n if max1 &gt; max2:\n return 1\n if max2 &gt; max1:\n return 2\n\n\nif __name__ == '__main__':\n start_time = time()\n hands = get_hands('p054_poker.txt')\n scores = [compare_hands(h1, h2) for (h1, h2) in hands]\n player1_score = sum(1 for player in scores if player == 1)\n print(f'Player 1 score: {player1_score}')\n print(f'Time: {time() - start_time} seconds.')\n\n</code></pre>\n\n<p>Many details can still be improved.</p>\n\n<hr>\n\n<p><strong>My own solution</strong></p>\n\n<p>Reviewing your code got me thinking about how I'd implement the solution.</p>\n\n<p>I don't consider my code to be great in any ways but it may be interesting to you on various points:</p>\n\n<ul>\n<li>code organisation</li>\n<li>usage of Python standard modules</li>\n</ul>\n\n<pre><code>import collections\n\n\nclass Card:\n \"\"\"Card object (value and suit).\"\"\"\n CARD_VALUES = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14}\n\n def __init__(self, value, suit):\n self.value = value\n self.suit = suit\n\n @classmethod\n def from_string(cls, card):\n value, suit = card\n return cls(value, suit)\n\n def __str__(self):\n return str(self.value) + self.suit\n\n def __repr__(self):\n return self.__class__.__name__ + \"(\" + self.value + \", \" + self.suit + \")\"\n\n def evaluate(self):\n return Card.CARD_VALUES[self.value]\n\n\nclass Hand:\n \"\"\"Hand object (iterable of NB_CARDS cards).\"\"\"\n NB_CARDS = 5\n\n def __init__(self, cards):\n assert len(cards) == Hand.NB_CARDS\n self.cards = cards\n\n @classmethod\n def from_string(cls, string):\n cards = [Card.from_string(chunk) for chunk in string.split()]\n return cls(cards[:Hand.NB_CARDS]), cls(cards[Hand.NB_CARDS:])\n\n def __str__(self):\n return \"-\".join(str(c) for c in self.cards)\n\n def __repr__(self):\n return self.__class__.__name__ + \"(\" + repr(self.cards) + \")\"\n\n def evaluate(self):\n \"\"\"Return an arbitrarly formed tuple that can be used to\n sort hands using lexicographic order. First element is an\n integer describing the type of hand. Other values are added\n to be able to differentiate hands.\n Integers used:\n 1 High Card: Highest value card.\n 2 One Pair: Two cards of the same value.\n 3 Two Pairs: Two different pairs.\n 4 Three of a Kind: Three cards of the same value.\n 5 Straight: All cards are consecutive values.\n 6 Flush: All cards of the same suit.\n 7 Full House: Three of a kind and a pair.\n 8 Four of a Kind: Four cards of the same value.\n 9 Straight Flush: All cards are consecutive values of same suit.\n 9 Royal Flush: Ten, Jack, Queen, King, Ace, in same suit.\n \"\"\"\n values = sorted((c.evaluate() for c in self.cards), reverse=True)\n count = collections.Counter(values)\n mc, mc2 = count.most_common(2)\n mc_val, mc_nb = mc\n mc2_val, mc2_nb = mc2\n if mc_nb == 4:\n return (8, mc_val, values)\n elif mc_nb == 3:\n if mc2_nb == 2:\n return (7, mc_val, mc2_val, values)\n else:\n return (4, mc_val, values)\n elif mc_nb == 2:\n if mc2_nb == 2:\n return (3, sorted((mc_val, mc2_val)), values)\n else:\n return (2, mc_val, values)\n else:\n assert mc_nb == 1\n is_flush = len(set(c.suit for c in self.cards)) == 1\n delta = values[0] - values[-1]\n is_straight = delta == Hand.NB_CARDS - 1\n if is_straight:\n return (9 if is_flush else 5, values)\n else:\n return (6 if is_flush else 1, values)\n\n def __gt__(self, other): # Note: other magic methods should be defined as well\n return self.evaluate() &gt; other.evaluate()\n\n\ndef euler54(f='p054_poker.txt'):\n \"\"\"Solution for problem 54.\"\"\"\n ret = 0\n with open(os.path.join(resource_folder, f)) as file_:\n for l in file_:\n hand1, hand2 = Hand.from_string(l)\n ret += hand1 &gt; hand2\n return ret\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T14:31:16.650", "Id": "225132", "ParentId": "225119", "Score": "1" } }, { "body": "<p>Building on @Josay's answer a little, I would expand the Card class to include definitions of greater/less than (<code>__ge__</code>, <code>__lt__</code>), equal to (<code>__eq__</code>) and so on. This would allow you to compare cards with simple operators rather than entire functions. For example:</p>\n\n<p>(I've dropped the <code>__str__</code> and <code>__repr__</code> methods for brevity but you shouldn't!)</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Card:\n def __init__(self, value, suit):\n self.value = value\n self.suit = suit\n\n @classmethod\n def from_string(cls, card):\n value = card[:-1] # CARD_RANKS[card[:-1] could be nice\n try:\n value = int(value)\n except ValueError:\n value = {'J': 11, 'Q': 12, 'K': 13, 'A': 14}.get(value)\n suit = card[-1]\n return cls(value, suit)\n\n def __eq__(self, other):\n return self.value == other.value\n\n def __gt__(self, other):\n return self.value &gt; other.value\n\n def __lt__(self, other):\n return self.value &lt; other.value\n\n @staticmethod\n def pair(card_a, card_b):\n return card_a == card_b\n\n @staticmethod\n def three_of_kind(card_a, card_b, card_c):\n return card_a == card_b == card_c\n\n\naoh = Card.from_string('AH')\naod = Card.from_string('AD')\ntod = Card.from_string('2D')\naos = Card.from_string('AS')\n\nprint(Card.pair(aoh, aod))\n&gt;&gt;&gt; True\nprint(Card.three_of_kind(aoh, tod, aos))\n&gt;&gt;&gt; False\n</code></pre>\n\n<p>Those static methods could be changed to <code>self</code>, <code>other</code> but I think that gets confusing when making comparisons with a few or more cards.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T14:34:56.580", "Id": "225197", "ParentId": "225119", "Score": "1" } } ]
{ "AcceptedAnswerId": "225132", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T09:26:51.890", "Id": "225119", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge" ], "Title": "Project Euler # 54 Poker hands in Python" }
225119
<p>If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.</p> <p>Not all numbers produce palindromes so quickly. For example,</p> <p>349 + 943 = 1292, 1292 + 2921 = 4213 4213 + 3124 = 7337</p> <p>That is, 349 took three iterations to arrive at a palindrome.</p> <p>Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits).</p> <p>Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994.</p> <p>How many Lychrel numbers are there below ten-thousand?</p> <pre><code>from time import time def is_palindrome(number): """returns True for a palindrome, False otherwise.""" to_str = str(number) return to_str == to_str[::-1] def add_reverses(number, count): """makes a list of reverses for a number at a maximum iteration of count, breaks if palindrome found below count.""" reverses = [number] for _ in range(count): last_number = reverses[-1] new_number = int(str(reverses[-1])[::-1]) if is_palindrome(last_number + new_number): reverses.append(last_number + new_number) return reverses else: reverses.append(last_number + new_number) return reverses def count_lychrel_range(number_range, count): """returns Lychrel numbers within number_range, assumes count is the maximum iterations for a number.""" total = 0 numbers_reverses = {} for number in range(number_range): numbers_reverses[number] = add_reverses(number, count) for number, rev_sequence in numbers_reverses.items(): if len(rev_sequence) &gt;= count: total += 1 return total if __name__ == '__main__': start_time = time() n = 10000 print(f'Total Lychrel numbers below {n}: {count_lychrel_range(n, 50)}') print(f'Time: {time() - start_time} seconds.') </code></pre>
[]
[ { "body": "<p>I like the functions you've divided up work. Good job.</p>\n\n<hr>\n\n<pre><code>def is_palindrome(number):\n \"\"\"returns True for a palindrome, False otherwise.\"\"\"\n</code></pre>\n\n<p>Its a little nickpicky, but the pep on <a href=\"https://www.python.org/dev/peps/pep-0257/#one-line-docstrings\" rel=\"nofollow noreferrer\">docstrings</a> recommends </p>\n\n<blockquote>\n <p>The docstring is a phrase ending in a period. It prescribes the\n function or method's effect as a command (\"Do this\", \"Return that\"),\n not as a description; e.g. don't write \"Returns the pathname ...\".</p>\n</blockquote>\n\n<p>I would change the docs here to something more like</p>\n\n<pre><code>\"\"\"Return whether a number is the same if read backwards and forwards.\"\"\"\n</code></pre>\n\n<hr>\n\n<pre><code>last_number = reverses[-1]\nnew_number = int(str(reverses[-1])[::-1])\n</code></pre>\n\n<p>Since last_number is reverses[-1], use it. Saves a lookup.</p>\n\n<pre><code>last_number = reverses[-1]\nreversed_number = int(str(last_number[::-1]))\n</code></pre>\n\n<hr>\n\n<pre><code>if is_palindrome(last_number + new_number):\n reverses.append(last_number + new_number)\n return reverses\nelse:\n reverses.append(last_number + new_number)\n</code></pre>\n\n<p>Since you have the same code in each path, and nothing before it, you can hoist it up out of the if statement</p>\n\n<pre><code>reverses.append(last_number + new_number)\nif is_palindrome(last_number + new_number):\n return reverses\n</code></pre>\n\n<hr>\n\n<pre><code>for _ in range(count):\n ...\n if ...:\n return reverses\n ...\nreturn reverses\n</code></pre>\n\n<p>+1 for using _ as the loop variable.</p>\n\n<p>This is again nitpicky, but since you have an opportunity to make this code only have one return point, why not take it?</p>\n\n<pre><code>for _ in range(count):\n last_number = reverses[-1]\n new_number = int(str(reverses[-1])[::-1])\n\n reverses.append(last_number + new_number)\n if is_palindrome(last_number + new_number):\n break\n\nreturn reverses\n</code></pre>\n\n<hr>\n\n<pre><code>def count_lychrel_range(number_range, count):\n \"\"\"returns Lychrel numbers within number_range, assumes count is the maximum iterations for a number.\"\"\"\n</code></pre>\n\n<p>Except it takes the upper bound of the range, not a number range. The doc clears it up, but just looking at the method signature I would assume you pass in the list of numbers to iterate over or a range. Since the expected call is not</p>\n\n<pre><code>count_lychrel_range(range(500, 1000), 50)\n</code></pre>\n\n<p>I would suggest changing the names here</p>\n\n<pre><code>def count_lychrel_numbers(upper_bound, max_iterations):\n</code></pre>\n\n<hr>\n\n<p>Since you only care about the length of the list, why go through all the effort of building a list of intermediate numbers from the process? In fact, you only need the length so you can compare it to the maximum number of iterations to run. Doing the test means we can just return a yes/no answer, rather than an entire list of numbers.</p>\n\n<p>I think something like this inplace of add_reversed would be a little nicer.</p>\n\n<pre><code>def is_lychrel(number, max_iterations):\n \"\"\"Return whether a number is a lychrel number.\n A lychrel number is one which becomes a palindrome when it is repeatedly reversed and added to itself.\"\"\"\n for _ in range(max_iterations):\n reversed_number = int(str(number)[::-1])\n number += reversed_number\n if is_palindrome(number):\n return True\n return False\n</code></pre>\n\n<p>Then count_lychrel_numbers can be a simple loop</p>\n\n<pre><code>def count_lychrel_numbers(upper_bound, max_iterations):\n \"\"\"...\"\"\"\n total = 0\n for number in range(upper_bound):\n if is_lychrel(number, max_iterations):\n total += 1\n return total\n</code></pre>\n\n<p>Or if you want to use sum</p>\n\n<pre><code>def count_lychrel_numbers(upper_bound, max_iterations):\n \"\"\"...\"\"\"\n return sum(1 for number in range(upper_bound) if is_lychrel(number, max_iterations))\n</code></pre>\n\n<hr>\n\n<p>As a bonus, you can see that \"new_number\" is reversed twice. Once in is_palindrome and once in add_reverses/is_lychrel. Can you reduce it down to just one reverse without bloating the code?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T11:27:04.167", "Id": "225125", "ParentId": "225121", "Score": "1" } } ]
{ "AcceptedAnswerId": "225125", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T10:36:22.320", "Id": "225121", "Score": "2", "Tags": [ "python", "performance", "beginner", "python-3.x", "programming-challenge" ], "Title": "Project Euler # 55 Lychrel numbers in Python" }
225121
<p>Consider the following function to traverse a BST</p> <pre class="lang-lisp prettyprint-override"><code>(defun bst-traverse (fn bst) ; [1] (when bst (bst-traverse fn (node-l bst)) (funcall fn (node-elt bst)) ; [2] (bst-traverse fn (node-r bst)))) ;; [1] This is a higher order function - recieves a function which it calls on each node. ;; [2] The traverse which makes sense on a bst is the in-order traverse ;; (i.e. left first, then node, then right, which this is.) </code></pre> <p>What are some nice uses of this function?</p> <p>1) Cause a side effect at each node</p> <p><code>(bst-traverse #'princ bst)</code></p> <p>2) Cons each elt to a global var (also a side effect)</p> <p>The idea here is this is a good way to get the BST els in descending order.</p> <pre><code>(defparameter *result* nil) (bst-traverse (lambda (obj) (setf *result* (cons obj *result*))) nums) </code></pre> <p>This leads me to wondering...</p> <p>Is this higher order function any use at all without relying on a side-effect?</p> <p>It seems maybe not. Why? - because it <s>doesn't return anything</s> always returns <code>nil</code>.</p> <p>So, could we or should we make it return something to solve this 'problem'?</p> <p>The general question I'm seeking to explore here is the purity or non-purity of higher order functions in practical use cases (and hence, how to use them well).</p> <p>Any discussion/contributions appreciated.</p> <p>For the record, I started off with this</p> <pre class="lang-lisp prettyprint-override"><code>(defun in-order-traverse (bst) (when bst (in-order-traverse (node-l bst)) (format t "~A" (node-elt bst)) (in-order-traverse (node-r bst)))) </code></pre> <p>Then, when I wanted to get the BST els in reverse order, realised how completely un-reusable that function is in comparison to bst-traverse above. So, I'd like to get a better understanding of what the real flexibility of bst-traverse actually is and how to use it...</p> <p>[I've realised - the function passed <em>could</em> return something - but how would the higher order function pick which invocation of the lambda to return the return value of if any?!]</p> <hr> <p><strong>Update</strong> </p> <p>Wondering if this would be along the right lines at all</p> <pre class="lang-lisp prettyprint-override"><code>(defun bst-accumulate (fn bst) (let (result) (when bst (bst-accumulate fn (node-l bst)) (cons (funcall fn (node-elt bst)) result) (bst-accumulate fn (node-r bst))) result)) </code></pre> <p><strong>Update 2</strong></p> <p><code>bst-accumulate</code> above is wrong. This is not the first time I've fallen into the trap of thinking that consing was setting state - actually the return value of the expression above which does the cons is just lost... To achieve what I wanted to achieve above, I must firstly wrap the <code>cons</code> in a <code>setf</code> so that <code>result</code> is actually modified. Plus there's a second problem; since bst-accumulate is recursive, it will end up redefining <code>result</code> on every call. To fix that, we need a helper function so that we keep the lexical var <code>result</code> outside of the recursive function, thusly: (this time I tested it before posting :)</p> <pre class="lang-lisp prettyprint-override"><code>(defun bst-accumulate (fn bst) (let (result) (labels ((bst-acc (fn2 bst2) (when bst2 (bst-acc fn2 (node-l bst2)) (setf result (cons (funcall fn2 (node-elt bst2)) result)) (bst-acc fn2 (node-r bst2))))) (bst-acc fn bst) result))) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T12:47:18.457", "Id": "436929", "Score": "0", "body": "\"I must return `cons` for it to be useful\". I'm reciting this over and over as I make a cup of tea :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T14:46:10.590", "Id": "436948", "Score": "2", "body": "What does this traversal function have to do with binary _search_ trees? It seems to treat it naïvely as just any old binary tree." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T14:52:50.883", "Id": "436953", "Score": "1", "body": "@200_success That's a fair comment. Except for the fact that it is an in order traverse, there's nothing specific to binary _search_ trees, as you point out. I could provide the entire code for the bst, but it was only this method I wanted to ask about." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T15:46:38.797", "Id": "437339", "Score": "0", "body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 9 → 8" } ]
[ { "body": "<blockquote>\n <p>Is this higher order function any use at all without relying on a side-effect?</p>\n</blockquote>\n\n<p>The answer to this question is obviously <em>no</em>, since the function returns always <code>nil</code>.</p>\n\n<blockquote>\n <p>The general question I'm seeking to explore here is the purity or non-purity of higher order functions in practical use cases (and hence, how to use them well).</p>\n</blockquote>\n\n<p>I'm not sure to understand what you are looking for, but if you want an example of recursive higher order function on binary trees that <em>returns</em> something (without performing side effects), consider the following one, in which the function gets another parameter that “combine” the results of the visit (assuming that an empty tree is represented with <code>nil</code> and that the function should return <code>nil</code> when an empty tree is passed to it):</p>\n\n<pre><code>(defun inorder-traverse (combine fn bin-tree)\n \"in order traversal of a binary tree\"\n (when bin-tree\n (funcall combine\n (inorder-traverse combine fn (node-l bin-tree))\n (funcall fn (node-elt bin-tree))\n (inorder-traverse combine fn (node-r bin-tree)))))\n</code></pre>\n\n<p>for instance:</p>\n\n<pre><code>(defun flatten (bin-tree)\n (inorder-traverse (lambda (x y z) (append x (list y) z))\n #'identity\n bin-tree))\n</code></pre>\n\n<p>returns the list of the leaves of a binary tree in order from left to right; if the tree is a BST, the list is sorted;</p>\n\n<pre><code>(defun reverse-flatten (bin-tree)\n (inorder-traverse (lambda (x y z) (append z (list y) x))\n #'identity\n bin-tree))\n</code></pre>\n\n<p>like the previous one, only in reverse order;</p>\n\n<pre><code>(defun map-tree (fn bin-tree)\n (inorder-traverse (lambda (left el right) (mk-tree el left right))\n fn\n bin-tree))\n</code></pre>\n\n<p>returns a new tree, with the same structure of the input one, and with the elements transformed by the function <code>fn</code>;</p>\n\n<pre><code>(defun my-copy-tree (bin-tree)\n (inorder-traverse (lambda (left el right) (mk-tree el left right))\n #'identity\n bin-tree))\n</code></pre>\n\n<p>makes a copy of a binary tree;</p>\n\n<pre><code>(defun reverse-tree (bin-tree)\n (inorder-traverse (lambda (left el right) (mk-tree el right left))\n #'identity\n bin-tree))\n</code></pre>\n\n<p>a symmetrical copy of a binary tree;</p>\n\n<p>etc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T16:58:29.533", "Id": "436991", "Score": "0", "body": "Thank you Renzo, this is very mind expanding & provides much material for exploration. I knew you would come charging in to the rescue! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T14:01:53.963", "Id": "437153", "Score": "0", "body": "The map-tree function (and its relations) are *amazing!* :) So, may I attempt to abstract a principle? - we see here that by adding *additional* function parameters to a higher order function, one tends to make that higher order function even more flexible. The reason for that is that if one simply wants default behaviour for one of the function parameters, one just needs to pass in an identity function or its equivalent. In the case of the combine function, the \"equivalent of the identity function\" is simply to append its three params in the same order they are given. Anything to add?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T13:27:33.423", "Id": "437312", "Score": "0", "body": "@mwal, I substantially agree with your comment. You can even reproduce your first function (traversal only for side effects) by passing as `combine`the function `(constantly nil)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T16:08:24.337", "Id": "437347", "Score": "0", "body": "Thanks. I note also that (constantly bin-tree) is an option, to always return the original tree, following the style of mapc, which may make a side-effects-only function more useful as it allows chaining. Hence, I've added the new function tap-tree (not sure what an appropriate naming for a function like that would be in cl?) as an additional answer below." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T16:32:36.507", "Id": "225147", "ParentId": "225124", "Score": "4" } }, { "body": "<p>the typical operations like <code>mapcar</code> or <code>reduce</code> - which return a value - could also be provided in similar fashion for trees.</p>\n\n<p>Note also that your function is not tail recursive and may cause a stack overflow...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T14:04:47.677", "Id": "437154", "Score": "0", "body": "wow - I wonder what some of the reduce operations on trees look like. It would seem there may be whole families of them :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T10:44:12.007", "Id": "437505", "Score": "0", "body": "Is any tree recursion necessarily not tail recursive? How does one refactor tree recursion to be tail recursive? (& would the compiler ever intervene to make it so? - I'm just cautiously starting to read about `declare`/`declaim` `optimize`). many thanks as always." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T19:15:56.507", "Id": "225157", "ParentId": "225124", "Score": "1" } }, { "body": "<p>Following discussion in the comments on the accepted answer above, here is a function which utilises <code>inorder-traverse</code> given there to neatly allow side-effect-only in-order traversal of any binary tree, and return the original tree. Returning the original tree allows chaining, and was inspired by the function <code>mapc</code>.</p>\n\n<p>I'm not sure whether calling this \"tap\", is the best way to name it - comments welcome.</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(defun tap-tree (mapfn bin-tree)\n (inorder-traverse (constantly bin-tree) \n mapfn\n bin-tree))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T16:12:52.680", "Id": "225278", "ParentId": "225124", "Score": "0" } } ]
{ "AcceptedAnswerId": "225147", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T11:17:26.063", "Id": "225124", "Score": "2", "Tags": [ "functional-programming", "common-lisp", "visitor-pattern" ], "Title": "BST traverse as higher order function" }
225124
<p>I have solved an assignment (Exercise 33) from the <a href="https://materiaalit.github.io/2013-oo-programming/part2/week-10/" rel="nofollow noreferrer">MOOC Object-Oriented programming with Java, part II</a>, but I'm not enrolled in said course.</p> <blockquote> <p><strong>Assignment Summary</strong> </p> <p>In this exercise, you implement a dungeon game. In the game, the player is in a dungeon full of vampires. The player has to destroy the vampires before his lamp runs out of battery and the vampires can suck his blood in the darkness. The player can see the vampires with a blinking of their lamp, after which they have to move blind before the following blinking. With one move, the player can walk as many steps as they want. The game situation, i.e. the dungeon, the player and the vampires are shown in text form. The first line in the print output tells how many moves the player has left (that is to say, how much battery the lamp has). After that, the print output shows player and vampire positions, which in turn are followed by the game map.<br> The coordinates are calculated starting from the high left corner of the game board. The user can move by giving a sequence of commands and pressing Enter. The commands are:</p> <ul> <li>w go up</li> <li>s go down</li> <li>a go left</li> <li>d go right </li> </ul> <p>When the user commands are executed (the user can give many commands at once), a new game situation is drawn. If the lamp charge reac hes 0, the game ends and the text YOU LOSE is printed on the board.</p> <p>The vampires move randomly in the game, and they take one step for each step the player takes. If the player and a vampire run into each other (even momentarily) the vampire is destroyed. If a vampire tries to step outside the board, or into a place already occupied by another vampire, the move is not executed. When all the vampires are destroyed, the game ends and it prints YOU WIN. The player starts the game in the position 0,0 Player and vampires can not move out of the dungeon and two vampires cannot step into the same place </p> </blockquote> <p><strong>Question</strong>:<br> How do you refactor this code so that it follows OOP, reads better, is manageable? How can I write method names and classes better? How do you know which entities are to be made separate classes, and how to use classes efficiently? </p> <p>Feels like there is a lot of bloated classes and repeated code. Also coding took a long time, spent a lot of time in refactoring and debugging hell. How do you plan and design your code? How do you produce workable, clean code in less time? What do you focus on?</p> <p><code>Movement class</code> - translates keyboard key into direction</p> <pre class="lang-java prettyprint-override"><code>package dungeon; import useful.BiMap; import useful.Randomizer; public class MovementKey { private BiMap&lt;Direction, String&gt; movementKeys; private Randomizer randomizer; enum Direction { UP, LEFT, DOWN, RIGHT } public MovementKey() { this.movementKeys = new BiMap&lt;&gt;(); String[] keys = {"w", "a", "s", "d"}; for (int i = 0; i &lt; keys.length; i++) { this.movementKeys.put(Direction.values()[i], keys[i]); } this.randomizer = new Randomizer(); } public static int noOfKeys() { return Direction.values().length; } public Direction getRandomDirection() { int randomNumber = randomizer.random(noOfKeys()); return Direction.values()[randomNumber]; } public String getRandomKey() { return movementKeys.get(getRandomDirection()); } public Direction getDirection(String ascii) { return movementKeys.getKey(ascii); } } </code></pre> <p><code>Character class</code> - controls the player and the individual vampires</p> <pre class="lang-java prettyprint-override"><code>package dungeon; import java.util.Objects; public class Character { private Point point; private Point previousPoint; private String symbol; private MovementKey movementKey; public Character(String symbol) { this.symbol = symbol; this.point = new Point(); this.previousPoint = new Point(); this.movementKey = new MovementKey(); } public String symbol() { return symbol; } public Point point() { return point; } public MovementKey movementKey() { return movementKey; } public boolean hasMoved() { return !point.equals(previousPoint); } public boolean isAtThisPosition(Point other) { return point.equals(other); } public void rewindMove() { point = previousPoint; } public void setPoint(Point newPoint) { point = newPoint; } public void move(String command, Dungeon dungeon) throws IllegalArgumentException { previousPoint = new Point(point); try { switch (movementKey.getDirection(command)) { case UP: point.setRelativeY(-1); break; case LEFT: point.setRelativeX(-1); break; case DOWN: point.setRelativeY(1); break; case RIGHT: point.setRelativeX(1); break; default: System.out.println("Invalid command!"); } if (!dungeon.isInBoundary(point)) { rewindMove(); } } catch (NullPointerException e) { throw new IllegalArgumentException("Illegal Command : " + command); } } public String coordinates() { return String.format("%s %d %d", symbol, point.x(), point.y()); } @Override public String toString() { return symbol; } @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } Character other = (Character) object; return Objects.equals(symbol, other.symbol) &amp;&amp; point.equals(other.point); } } </code></pre> <p><code>Vampire Group</code> : controls the actions of the vampires as a group (composition over inheritance)</p> <pre class="lang-java prettyprint-override"><code>package dungeon; import java.util.*; public class VampireGroup { private List&lt;Character&gt; vampires; private boolean doesMove; public VampireGroup(int count, boolean doesMove) { this.vampires = new ArrayList&lt;&gt;(); for (int i = 0; i &lt; count; i++) { this.vampires.add(new Character("v")); } this.doesMove = doesMove; } public boolean areAshes() { return vampires.isEmpty(); } public String symbol() { return vampires.get(0).symbol(); } public Set&lt;Point&gt; getPoints() { Set&lt;Point&gt; points = new HashSet&lt;&gt;(); for (Character vampire : this.vampires) { points.add(vampire.point()); } return points; } public Character vampireAtPosition(Point point) { for (Character vampire : vampires) { if (vampire.isAtThisPosition(point)) { return vampire; } } return null; } public void removeAshes(Point playerPoint) { // do nothing if no vampires are found vampires.remove(vampireAtPosition(playerPoint)); } public void setInitialCoordinates(int length, int height, Set&lt;Point&gt; usedPoints) { for (Character vampire : vampires) { usedPoints.remove(vampire.point()); setToRandomCoordinate(length, height, vampire, getPoints()); usedPoints.add(vampire.point()); } } public void setToRandomCoordinate(int length, int height, Character vampire, Set&lt;Point&gt; usedPoints) { Point newPoint; do { newPoint = Point.randomPoint(length, height); } while (usedPoints.contains(newPoint)); vampire.setPoint(newPoint); } public void moveRandomly(Dungeon dungeon, Character vampire, Set&lt;Point&gt; usedPoints) { String key = vampire.movementKey().getRandomKey(); vampire.move(key, dungeon); if (usedPoints.contains(vampire.point())) { vampire.rewindMove(); moveRandomly(dungeon, vampire, usedPoints); } } public void move(Dungeon dungeon) { if (!doesMove) { return; } for (Character vampire : vampires) { do { moveRandomly(dungeon, vampire, dungeon.usedPoints()); } while (!vampire.hasMoved()); } } public String coordinates() { StringBuilder stringBuilder = new StringBuilder(); for (Character vampire : this.vampires) { stringBuilder.append(String.format("%s\n", vampire.coordinates())); } return stringBuilder.toString(); } } </code></pre> <p><code>Dungeon class</code> - draws grid, controls entities in the dungeon (player and vampires) </p> <pre class="lang-java prettyprint-override"><code>package dungeon; import java.util.HashSet; import java.util.Set; public class Dungeon { private int length; private int height; private int lampCount; private Character player; private VampireGroup vampires; public Dungeon(int length, int height, int lampCount) { this.length = length; this.height = height; this.lampCount = lampCount; this.player = new Character("@"); this.vampires = new VampireGroup(2, true); this.vampires.setInitialCoordinates(length, height, usedPoints()); } public void printResults() { if (vampires.areAshes()) { System.out.println("YOU WIN"); } else { System.out.println("YOU LOSE"); } } public boolean isNotClearedWhenPlayerIsAlive() { return lampCount &gt; 0 &amp;&amp; !vampires.areAshes(); } public Set&lt;Point&gt; usedPoints() { Set&lt;Point&gt; usedPoints = new HashSet&lt;&gt;(); usedPoints.add(player.point()); usedPoints.addAll(vampires.getPoints()); return usedPoints; } public void printStats() { System.out.println(lampCount); System.out.println(); printCoordinates(); System.out.println(); printGrid(player, vampires, usedPoints()); System.out.println(); } public void playersTurn(String key) throws IllegalArgumentException { player.move(key, this); } public void vampiresTurn() { vampires.removeAshes(player.point()); vampires.move(this); } public void printCoordinates() { System.out.println(player.coordinates()); System.out.println(vampires.coordinates()); } public boolean isInBoundary(Point point) { return isInRange(point.x(), length) &amp;&amp; isInRange(point.y(), height); } public void decrementLampCount() { if (player.hasMoved()) { lampCount--; } } public boolean isInRange(int value, int min, int max) { return value &gt;= min &amp;&amp; value &lt; max; } public boolean isInRange(int value, int max) { return isInRange(value, 0, max); } public void printGrid(Character player, VampireGroup vampires, Set&lt;Point&gt; usedPoints) { for (int i = 0; i &lt; height; i++) { for (int j = 0; j &lt; length; j++) { Point currentPoint = new Point(j, i); if (usedPoints.contains(currentPoint)) { if (player.isAtThisPosition(currentPoint)) { System.out.print(player); } else { System.out.print(vampires.symbol()); } } else { System.out.print('.'); } } System.out.println(); } } } </code></pre> <p><code>Point class</code> - since every character in the dungeon is a point in a 2D grid</p> <pre class="lang-java prettyprint-override"><code>package dungeon; import useful.Randomizer; import java.util.Objects; public class Point { private static Randomizer randomizer; private int x; private int y; public Point(int x, int y) { setX(x); setY(y); randomizer = new Randomizer(); } public Point() { this(0, 0); } public Point(Point other) { this(other.x, other.y); } public static Point randomPoint(int xMin, int xMax, int yMin, int yMax) { return new Point(randomizer.random(xMin, xMax), randomizer.random(yMin, yMax)); } public static Point randomPoint(int xMax, int yMax) { return randomPoint(0, xMax - 1, 0, yMax - 1); } public int y() { return y; } public int x() { return x; } public void setX(int dx) { x = dx; } public void setY(int dy) { y = dy; } public void setRelativeX(int dx) { setX(x + dx); } public void setRelativeY(int dy) { setY(y + dy); } public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } Point other = (Point) object; return x == other.x &amp;&amp; y == other.y; } public int hashCode() { return Objects.hash(x, y); } public String toString() { return String.format("(%d, %d)", x, y); } } </code></pre> <p><code>Randomizing class</code> - Helper class to simplify Random class</p> <pre class="lang-java prettyprint-override"><code>package useful; import java.util.Random; public class Randomizer extends Random { //inclusive public int random(int min, int max) { Random random = new Random(); return random.nextInt(max - min + 1) + min; } public double randomDouble(double min, int max) { Random random = new Random(); return random.nextDouble()*(max - min) + min; } //exclusive public int random(int n) { return random(0, n - 1); } } </code></pre> <p><code>BiMap class</code> - Helper class used to create |Direction &lt;---> Key| relation.</p> <pre class="lang-java prettyprint-override"><code>package useful; import java.util.HashMap; import java.util.Map; import java.util.function.BiFunction; import java.util.function.Function; public class BiMap&lt;K, V&gt; extends HashMap&lt;K, V&gt; { private Map&lt;V, K&gt; inversedMap = new HashMap&lt;&gt;(); public K getKey(V value) { return inversedMap.get(value); } @Override public V put(K key, V value) { inversedMap.put(value, key); return super.put(key, value); } @Override public void putAll(Map&lt;? extends K, ? extends V&gt; m) { super.putAll(m); for (K key : m.keySet()) { inversedMap.put(super.get(key), key); } } @Override public V remove(Object key) { inversedMap.remove(super.get(key)); return super.remove(key); } @Override public void clear() { super.clear(); inversedMap.clear(); } @Override public V putIfAbsent(K key, V value) { inversedMap.putIfAbsent(value, key); return super.putIfAbsent(key, value); } @Override public boolean remove(Object key, Object value) { inversedMap.remove(value, key); return super.remove(key, value); } @Override public boolean replace(K key, V oldValue, V newValue) { inversedMap.remove(oldValue); inversedMap.put(newValue, key); return super.replace(key, oldValue, newValue); } @Override public V replace(K key, V value) { if (super.containsKey(key)) { put(key, value); } return value; } @Override public V computeIfAbsent(K key, Function&lt;? super K, ? extends V&gt; mappingFunction) { V value = super.computeIfAbsent(key, mappingFunction); inversedMap.put(value, key); return value; } @Override public V computeIfPresent(K key, BiFunction&lt;? super K,? super V,? extends V&gt; remappingFunction) { V value = super.computeIfPresent(key, remappingFunction); inversedMap.put(value, key); return value; } @Override public V compute(K key, BiFunction&lt;? super K,? super V,? extends V&gt; remappingFunction) { V value = super.compute(key, remappingFunction); inversedMap.put(value, key); return value; } @Override public V merge(K key, V value, BiFunction&lt;? super V,? super V,? extends V&gt; remappingFunction) { V replacedValue = super.merge(key, value, remappingFunction); inversedMap.remove(value); inversedMap.put(replacedValue, key); return replacedValue; } @Override public void replaceAll(BiFunction&lt;? super K,? super V,? extends V&gt; function) { inversedMap.clear(); super.replaceAll(function); for (K key : super.keySet()) { inversedMap.put(super.get(key), key); } } } </code></pre> <p><code>UserInterface class</code> - deals with the commands given by user and executes them</p> <pre class="lang-java prettyprint-override"><code>package dungeon; import java.util.*; public class UserInterface implements AutoCloseable { private Scanner scanner; private Dungeon dungeon; public UserInterface() { this.scanner = new Scanner(System.in); this.dungeon = new Dungeon(5, 5, 14); } public void executeCommands(String multipleCommands) throws IllegalArgumentException { for (char command : multipleCommands.toCharArray()) { dungeon.playersTurn(String.valueOf(command)); } dungeon.vampiresTurn(); dungeon.decrementLampCount(); } public void run() { while (dungeon.isNotClearedWhenPlayerIsAlive()) { dungeon.printStats(); if (scanner.hasNext()) { String commandSequence = scanner.next(); try { executeCommands(commandSequence); } catch (IllegalArgumentException e) { System.out.println(e); } } System.out.println("--------------------------"); } dungeon.printResults(); } @Override public void close() { scanner.close(); } } </code></pre> <p><code>Main class</code></p> <pre class="lang-java prettyprint-override"><code>import dungeon.UserInterface; public class Main { public static void main(String[] args) { try (UserInterface ui = new UserInterface()) { ui.run(); } } } </code></pre> <p><strong>Expected Output</strong></p> <pre><code>14 @ 0 0 v 1 2 v 7 8 v 7 5 v 8 0 v 2 9 @.......v. .......... .v........ .......... .......... .......v.. .......... .......... .......v.. ..v....... ssd -------------------------- 13 @ 1 2 v 8 8 v 7 4 v 8 3 v 1 8 .......... .......... .@........ ........v. .......v.. .......... .......... .......... .v......v. .......... ssss -------------------------- 12 @ 1 6 v 6 9 v 6 5 v 8 3 .......... .......... .......... ........v. .......... ......v... .@........ .......... .......... ......v... dd -------------------------- 11 @ 3 6 v 5 9 v 6 7 v 8 1 .......... ........v. .......... .......... .......... .......... ...@...... ......v... .......... .....v.... ddds -------------------------- 10 @ 6 7 v 6 6 v 5 0 .....v.... .......... .......... .......... .......... .......... ......v... ......@... .......... .......... w -------------------------- 9 @ 6 6 v 4 0 ....v..... .......... .......... .......... .......... .......... ......@... .......... .......... .......... www -------------------------- 8 @ 6 3 v 4 0 ....v..... .......... .......... ......@... .......... .......... .......... .......... .......... .......... aa -------------------------- 7 @ 4 3 v 4 2 .......... .......... ....v..... ....@..... .......... .......... .......... .......... .......... .......... w YOU WIN </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T08:13:53.020", "Id": "437749", "Score": "0", "body": "Please don't edit your code further now answers have been posted. If the community suspects an edit even partially invalidates an existing answer, the edit will be rolled back. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>First of all, I think your code is not bad at all. The separation in classes and their respective use is quite okay.</p>\n\n<p>Nevertheless, I have a couple of suggestions that might make your code even better:</p>\n\n<h3>Try to make things as unsurprising as possible</h3>\n\n<ul>\n<li><p>Naming one of your classes <code>Character</code> is likely to send people on a wrong track, as <code>Character</code> is the name of Java's wrapper object class for <code>char</code> primitive variables.</p></li>\n<li><p>It's a good idea to adhere to naming conventions:<br>\nMethods, which only return a class attribute (\"getters\") should be named <code>get&lt;Attribute&gt;</code>, i.e. <code>getPoint</code>, <code>getPreviousPoint</code>, <code>getSymbol</code>, <code>getX</code>, <code>getY</code>, etc.\n(you have already done it right for the \"setters\": <code>setX</code>, <code>setY</code>, etc)</p></li>\n</ul>\n\n<h3>Try to keep things as local and as static as possible</h3>\n\n<ul>\n<li>Can you implement the classes, that are instantiated exactly once during the lifetime of your application in a way, that leverages that?<br>\nHere, the possible candidates <code>UserInterface</code>, <code>Scanner</code> and <code>Dungeon</code> hold the status of your game, so <code>static</code> is out of the question. (You could consider using a <em>Singleton</em> for these, if you wanted to) </li>\n<li>Methods, that are used only locally should be declared <code>private</code><br>\ne.g. <code>noOfKeys()</code> and <code>getRandomDirection()</code>, which are both used exclusively from within <code>MovementKey</code>.<br>\n(I would even include the functionality of those methods in <code>getRandomKey()</code> and erase them altogether).</li>\n</ul>\n\n<h3>Try to use existing mechanisms</h3>\n\n<p>To store the mapping from <code>Direction</code> to their respective keys (and vice versa), you create a new bidirectional Map <code>BiMap</code>, and use that in <code>MovementKey</code>.<br>\nIn my Opinion, this could be more elegantly implemented by augmenting the enum <code>Direction</code> by an attribute which holds the keys, a getter for it and a couple of convenience methods (<code>getRandomKey()</code> ...) </p>\n\n<p>This would make <code>BiMap</code> and <code>MovementKey</code> unnecessary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T14:27:07.493", "Id": "437161", "Score": "0", "body": "What about using an EnumMap field inside the MovementKey class (which has been made static)?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T10:21:01.600", "Id": "225184", "ParentId": "225126", "Score": "2" } }, { "body": "<p>Here are my comments:</p>\n\n<h2>inheritance</h2>\n\n<p>composition over inheritance is usually a good principle to follow. However, inheritance has the advantage that the compiler is aware of it and can be used to alert in case of errors. specifically, I saw that in <code>VampireGroup</code>, you declared <code>private List&lt;Character&gt; vampires;</code>. So theoretically, a player character can be placed in this list. This is where it would be beneficial to have <code>Player</code> and <code>Vampire</code> classes that inherit from <code>Character</code>. with this you could declare <code>private List&lt;Vampire&gt; vampires;</code> which is more clear and also makes the compiler guard from accidental addition of <code>Player</code> character. the other benefit is that you can further customize player and vampires separately (perhaps they can define their own symbol? more on that later).</p>\n\n<h2><code>Direction</code> enum</h2>\n\n<p>this was already mentioned by @glissi. I will add further: in <code>Character.move()</code>, you have a <code>switch</code> statement with <code>case</code> for every movement. the key binding itself is defined in the constructor of <code>MovementKey</code>. however, all these pieces of logic and data are tied together. What if you decide to expand your game to allow for diagonal (or other) movements? you will need to make code change in all the above places (possibly more that I didn't see). in CS, this is called <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a>. One place that is responsible for all logic and data pertaining to an isolated functionality.</p>\n\n<p>If you wrap your head on how to have the character movement in the enum: you can have a <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html\" rel=\"nofollow noreferrer\"><code>Function</code></a> argument to every enum value. The <code>Function</code> interface defines a method that takes one argument and returns a value. in your case, it will receive a <code>Point</code> of current position and return a new <code>Point</code> (can be same instance) in new position. Alternatively, you can have a <code>Consumer</code> that returns void (more an that later). the actual body of the functions can be specified as lambda expressions</p>\n\n<pre><code>enum Direction {\n UP((point -&gt; {point.setRelativeY(-1); return point;})),\n LEFT((point -&gt; {point.setRelativeX(-1); return point;})),\n ...\n public Function&lt;Point, Point&gt; move;\n Direction(Function&lt;Point, Point&gt; move) {\n this.move = move;\n }\n}\n</code></pre>\n\n<h2>Immutability</h2>\n\n<p><code>Point</code> class is mutable. it has setter methods that allow callers to alter the state (modify instance variables' values). In contrast, if you remove the setter methods of <code>Point</code>. it becomes immutable. if you want to move a character, you don't alter its point. instead, you assign a new point. This is similar to the immutable <code>java.lang.String</code>. There are several advantages to immutable objects: they can be better tested, are far better suited to be used in multi-threaded system and can be used by Java 8 lambda expressions (that require final objects only). All these cases are perhaps out of scope or too advanced for this exercise. however, in terms of general good practices, this principle is well known. That is why I prefer to use <code>Function</code> over <code>Consumer</code> for movement operation in the enum.</p>\n\n<h2>Separation of Concerns</h2>\n\n<p>This <a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">CS principle</a> can be viewed as a higher hierarchy variant of the Single Responsibility principle. You have a <code>UserInterface</code> class that is supposed to be the (only) place that both takes user input and displays data. Yet, there are several places that affect the output that is displayed on the console: the dungeon prints its own grid, and is responsible for the symbols of the player and of an empty point. <code>VampireGroup</code> decides the symbol of a vampire and <code>MovementKey</code> hard codes key binding. </p>\n\n<p>now what if you wanted to create an HTML version of your game that is viewed online? what if you wanted to allow users to modify key binding? with Separation of Concerns, you should create a \"black box\" game engine that has its own api.this api will have a getDungeun() method that will return a string representation of the dungeon. each user interface will know how to read this string representation and display to the user (with possibly different symbols). the string representation can be custom-made, which requires custom-made parser, or use one of the industry standard formats, like XML, JSON where you have ready made parsers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T05:56:10.123", "Id": "437472", "Score": "0", "body": "How would you used the enum class to get the Direction type from the key pressed (wasd)? Will you need a method like getDirection inside the enum class to get the Direction type from (?) parameter? Will it be good to have an attribute inside the class to hold the values of the possible keys (wasd) ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T06:38:02.557", "Id": "437476", "Score": "1", "body": "@GraceMathew, like I've written, key binding (mapping of key pressed to direction) belongs to the user interface layer. the game engine should expose the enum values to the user interface layer as the set of acceptable directions (something like `getPossibleDirections()`) and the user interface is responsible for assigning keystrokes (either default or user-assigned). the user interface then accepts user input and does the translation to enum values. these are passed to the game engine as player's turn." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T06:57:59.613", "Id": "437477", "Score": "0", "body": "How do you do the translation to the enum values and apply the function? Suppose the user types \"s\" (Direction.(?).(???) ?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T07:02:38.847", "Id": "437478", "Score": "1", "body": "the user interface can keep a `Map<String, Direction>`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T07:57:30.283", "Id": "437481", "Score": "0", "body": "And how would you apply the function? map.get(\"w\").(?);" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T08:08:50.673", "Id": "437482", "Score": "0", "body": "the user interface passes list of enum values to the game engine. the game engine is only aware of the enum values" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T08:15:29.907", "Id": "437483", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/96894/discussion-between-grace-mathew-and-sharon-ben-asher)." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T09:20:14.033", "Id": "225249", "ParentId": "225126", "Score": "3" } } ]
{ "AcceptedAnswerId": "225249", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T12:14:35.373", "Id": "225126", "Score": "6", "Tags": [ "java", "beginner", "object-oriented" ], "Title": "Object Oriented Ascii dungeon game" }
225126
<p>I am hoping to look at all the possible bots to submit to a noniterated prisoner's dilemma where both bots can reason about each other's behavior. Can I hide <code>unsafeNecessitation</code> within the definition of <code>prove</code> and/or open a fresh context for <code>prove</code>? Can I construct <code>Coops</code> such that <code>fixedpoint2</code> is true? How can my proofs be shortened? What should I write differently? In particular the asserts to duplicate hypotheses seem clumsy. How should I automate the application of unfix? How should I automate the search of what theorems to prove?</p> <pre><code>Require Setoid. Parameter Provable : Prop -&gt; Prop. Axiom Pmodus : forall {a b:Prop}, Provable (a -&gt; b) -&gt; Provable a -&gt; Provable b. Axiom loeb : forall {a:Prop}, Provable (Provable a -&gt; a) -&gt; Provable a. Axiom unsafeNecessitation: forall {a:Prop}, a -&gt; Provable a. (* WRONG *) Ltac prove := repeat match goal with | [ H : Provable _ |- _ ] =&gt; refine (Pmodus _ H); clear H end; clear; apply unsafeNecessitation; intuition. (* sometimes doesnt clear *) Parameter Fixedpoint2 : (Prop -&gt; Prop -&gt; Prop) -&gt; (Prop -&gt; Prop -&gt; Prop) -&gt; Prop. (* SHOULD BE REDUNDANT *) Notation "A &lt;3 B" := (Fixedpoint2 A B) (at level 70). Axiom fixedpoint2 : forall {a b}, a &lt;3 b = a (a &lt;3 b) (b &lt;3 a). Ltac unfix := rewrite fixedpoint2. Definition Prudent (self other:Prop) := Provable (self &lt;-&gt; other). Definition Fair (self other:Prop) := Provable other. Definition Coop (self other:Prop) := True. Definition Defect (self other:Prop) := False. Theorem prudentbotcoops : Prudent &lt;3 Prudent. unfix. prove. Qed. Theorem fairbotcoops : Fair &lt;3 Fair. unfix. apply loeb. prove. unfix. prove. Qed. Theorem p2pp : forall {a : Prop}, Provable a -&gt; Provable (Provable a). Proof. intros a pa. refine (Pmodus _ (@loeb (a /\ Provable a) _)). prove. prove. prove. Qed. Theorem prudentfaircoops : Prudent &lt;3 Fair. Proof. unfix. apply loeb. prove. unfix. apply p2pp in H. prove. unfix. assumption. unfix. exact H. Qed. Definition PA_1 (a:Prop) := (forall {a:Prop}, Provable a -&gt; a) -&gt; a. Theorem npnp : forall x, PA_1 (~Provable (~Provable x)). Proof. intros x trust pnp. apply trust. apply loeb. prove. contradict H. prove. Qed. Theorem fairdbotdefect : PA_1 (~Fair &lt;3 Defect). Proof. intros trust cooperates. rewrite fixedpoint2 in cooperates. apply trust in cooperates. rewrite fixedpoint2 in cooperates. exact cooperates. Qed. (* Take the action for which you can prove the best lower bound. *) Definition UDT (self other:Prop) := Provable (self -&gt; other) /\ ~Provable (~self -&gt; other). Theorem theyneverknowUDTcoops : forall b, PA_1(~Provable (UDT &lt;3 b)). Proof. intros b trust pub. assert (pub' := pub). apply trust in pub. rewrite fixedpoint2 in pub. firstorder. clear H. contradict H0. prove. Qed. Notation "'UC'" := (UDT &lt;3 UDT). Lemma UDTdoesntgetexploitedbyUDT : UC &lt;-&gt; ~Provable (~UC -&gt; UC). Proof. split. intro. rewrite fixedpoint2 in H. firstorder. intro. unfix. firstorder. prove. Qed. Lemma modus_tollens: forall {p q: Prop}, (p-&gt;q) -&gt; ~q -&gt; ~p. auto. Qed. Theorem udtcoops : PA_1 UC. Proof. intros trust. rewrite UDTdoesntgetexploitedbyUDT. refine (modus_tollens (Pmodus _) (theyneverknowUDTcoops UDT trust)). prove. rewrite UDTdoesntgetexploitedbyUDT. rewrite UDTdoesntgetexploitedbyUDT in H. firstorder. Qed. Theorem prudentunexploitable : forall b, PA_1 (Prudent &lt;3 b -&gt; b &lt;3 Prudent). Proof. intros b trust pb. assert (eq := pb). rewrite fixedpoint2 in eq. apply trust in eq. firstorder. Qed. Theorem UDTunexploitable : forall b, PA_1 (UDT &lt;3 b -&gt; b &lt;3 UDT). Proof. intros b trust ub. assert (ub' := ub). rewrite fixedpoint2 in ub. destruct ub as [notexp _]. apply trust in notexp. firstorder. Qed. Theorem whenPBcoopstheyknow : forall b, Prudent &lt;3 b -&gt; Provable (Prudent &lt;3 b). intro b. unfix. intro pb. apply p2pp. firstorder. Qed. Theorem prudentudtdefect : PA_1 (~Prudent &lt;3 UDT). Proof. intros trust pu. absurd (Provable (UDT &lt;3 Prudent)). exact (theyneverknowUDTcoops _ trust). assert (pu' := pu). rewrite fixedpoint2 in pu'. refine (Pmodus _ pu'). refine (Pmodus _ (whenPBcoopstheyknow _ pu)). prove. Qed. </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T15:55:51.870", "Id": "436978", "Score": "0", "body": "I don't think you can use `Provable : Prop -> Prop` like this. As you've noticed, you cannot reason about when Coq's context is empty. In short, you must either define a separate type `PROP` of object propositions, or use some Kripke semantics for provability logic to define `Provable` and the various connectives of your logic. I'm afraid the long version is too long for a comment — hope somebody can help..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T03:10:00.117", "Id": "438138", "Score": "1", "body": "You might be interested in https://github.com/JasonGross/lob-paper/blob/master/fair-bot-self-cooperates.lagda which proves in Agda that that FairBot cooperates with itself, and https://github.com/JasonGross/lob, which demonstrates how to encode Löb's theorem in both Coq and Agda both axiomatically and via an internal AST." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T13:19:56.537", "Id": "225128", "Score": "5", "Tags": [ "coq" ], "Title": "Prisoner's dilemma with Provability Logic" }
225128
<p>Consider <code>Crate::addLength()</code> in the following code:</p> <pre><code>class Crate { protected $length, $width, $height; function __construct(float $length, float $width, float $height) { $this-&gt;length = $length; $this-&gt;width = $width; $this-&gt;height = $height; } function addLength(float $length): Crate { return new self($this-&gt;length + $length, $this-&gt;width, $this-&gt;height); } } </code></pre> <p>I am concerned that <code>Crate</code> object creating a <code>Crate</code> object is a violation of Single Responsibility Principle (SRP). Crate object duties is to keep dimensions of the crate. Creating another crate object seems like introducing extra responsibilities to a class that already has responsibilities.</p> <p>With that in mind, how to I make the code better?</p> <p>The directions I think I can go are</p> <p><strong>1) Is it better to just instead increase the length of the Crate?</strong></p> <pre><code>function addLength(float $length): void { $this-&gt;length += $length; } </code></pre> <p>When doing so however, my crate becomes 'stretchy', which is typically not done in real life. Instead, a new crate is constructed with given measurements.</p> <p>Thus,</p> <p><strong>2) Is it better to instead delegate object creation to a separate class?</strong></p> <pre><code>class CrateService { function addLength(Crate $crate, float $length): Crate { return new Crate($crate-&gt;GetLength() + $length, $crate-&gt;getWidth(), $crate-&gt;getHeight()); } } </code></pre> <p>That seems to work, even if a little cumbersome - we basically call every crate's dimension individually and add the adder length, and create a new crate.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T15:14:16.170", "Id": "436963", "Score": "0", "body": "The problem with this question is that we don't know if you're going to do other things with the `Crate` class. Set the color of the crate? Fill it with stuff? Who knows? You must have other plans for this class than just setting dimensions. Objects in a program don't always follow the same rules as objects in real-life. A 'stretchy' crate is not a problem, unless there's something else that prohibits it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T15:55:32.693", "Id": "436977", "Score": "0", "body": "My plan is to 1) set up initial crate dimensions based on a pump product that will be in the crate, 2) if a motor is added to the pump (decided by customer), add a length adder to the crate's original length dimension. I may later add a price computation based on crate dimensions to the `Crate` object." } ]
[ { "body": "<p>I see no problem, given your comment, to have a 'stretchy' crate, but in my example code below you can control whether the crate can be stretched or not.</p>\n\n<pre><code>class Crate\n{\n private $length, $width, $height;\n private $resizable = true;\n\n function __construct(float $length, float $width, float $height)\n {\n list($this-&gt;length, $this-&gt;width, $this-&gt;height) = [$length, $width, $height];\n }\n\n function getDimensions(): array\n {\n return [$this-&gt;length, $this-&gt;width, $this-&gt;height];\n }\n\n function isResizable()\n {\n return $this-&gt;resizable;\n }\n\n function fixateSize()\n {\n $this-&gt;resizable = false;\n }\n\n function addLength(float $extraLength): float \n {\n return $this-&gt;length += $this-&gt;isResizable() ? $extraLength : 0;\n }\n}\n</code></pre>\n\n<p>I've added three methods; <code>getDimensions()</code>, <code>isResizable()</code> and <code>fixateSize()</code>. Note that there's no function to undo the <code>fixateSize()</code>. That is intentional: What would be the point of fixating the size if you can undo it?</p>\n\n<p>I've made the dimension and resize fields <code>private</code>. Only the <code>Crate</code> class should be responsible for manipulating these. Child classes should use the methods of <code>Crate</code> to change them, hence the <code>getDimensions()</code> method.</p>\n\n<p>Note how <code>addLength()</code> now returns the new length, and how it doesn't add the <code>$extraLength</code> when the crate size is fixated. Instead of returning the new length you could return a boolean, indicating whether the extra length is accepted. Another reason for not accepting the extra length could be that the crate would become too long.</p>\n\n<p>I wouldn't use the <code>CrateService</code> class, that just overly complicated, and the <code>addLength()</code> method that returns a new object is just weird. The name of the method doesn't suggest this at all. A better name would have been <code>cloneAndStretch()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:09:36.460", "Id": "437012", "Score": "0", "body": "Thank you. I have been reading about immutable objects in PHP (https://blog.joefallon.net/2015/08/immutable-objects-in-php/), and that is where I also get the concept and reasoning for making any changes in constructor only. I am struggling with the immutability concept, however, debating on whether I actually need it or not. The crate can be stretchy or not stretchy at code writing time (i.e. it will not change at runtime)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T17:59:34.650", "Id": "225151", "ParentId": "225133", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T14:32:03.637", "Id": "225133", "Score": "1", "Tags": [ "php", "object-oriented", "design-patterns", "constructor" ], "Title": "Adding Length dimension to a Crate Object" }
225133
<p>The <a href="https://www.hackerrank.com/challenges/time-conversion/problem" rel="nofollow noreferrer">challenge</a> (<a href="https://drive.google.com/file/d/1ly3CLJVQPiYZLZwjBls0okhaj5u2Ife5/view?usp=sharing" rel="nofollow noreferrer">PDF</a>) is to convert a time from 12-hour format (<code><i>hh</i>:<i>mm</i>:<i>ss</i>AM</code> or <code><i>hh</i>:<i>mm</i>:<i>ss</i>PM</code>) to 24-hour format.</p> <p>This is my solution, which worked for all test cases.</p> <pre><code>string timeConversion(string s) { int size = s.length(); if(s[size-2]=='A'){ string hh = s.substr(0,2); int h = stoi(hh); if(h==12){ string newh = "00"; string newTime = newh.append(s.substr(2,6)); return newTime; }else{ return s.substr(0,size-2); } } else{ string hh = s.substr(0,2); int h = stoi(hh); if(h==12){ return s.substr(0,size-2); } int inPM = h+12; string newh = to_string(inPM); string newTime = newh.append(s.substr(2,6)); return newTime; } } </code></pre> <p>Anything which I could have done in a different way in your opinion?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T14:52:46.967", "Id": "436952", "Score": "0", "body": "Please add the HackerRank Question to the question, links have been known to break." } ]
[ { "body": "<p>I think what you have is fine. There are many ways this can be done.</p>\n\n<p>For example:</p>\n\n<pre><code>string timeConversion(string s)\n{\n int hours = stoi(s.substr(0,2));\n if (s[8] == 'A')\n {\n if (hours == 12) hours = 0;\n }\n else \n {\n if (hours == 12) hours = 12;\n else hours += 12;\n }\n return ((hours &lt; 10) ? \"0\" :\"\") + to_string(hours) + s.substr(2,6);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T15:18:16.213", "Id": "436968", "Score": "0", "body": "This doesn't work for a testcase of the form `12:mm:ssPM` as `12 + 12 % 24 == 00` giving an answer of `00:mm:ss` but the question states it should be `12:mm:ss`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T14:47:52.710", "Id": "225136", "ParentId": "225134", "Score": "1" } }, { "body": "<p>Since the question gives a couple of guarantees about the input, take advantage of them. If you want to communicate these preconditions, assert them. Something like</p>\n\n<pre><code>string timeConversion(string s) {\n // Assume input is in the format hh:mm:ssAM or hh:mm:ssPM\n assert(s.length() == 10);\n int size = s.length();\n ...\n</code></pre>\n\n<hr>\n\n<pre><code>...\nif(s[size-2]=='A'){\n string hh = s.substr(0,2);\n int h = stoi(hh);\n ...\nelse{\n string hh = s.substr(0,2);\n int h = stoi(hh);\n ...\n</code></pre>\n\n<p>You do the same thing no matter which branch is taken. You can hoist this in front of the if statement</p>\n\n<pre><code>string hh = s.substr(0, 2);\nint h = stoi(hh);\nif (s[8] == 'A') {\n ...\n} else {\n ...\n}\n</code></pre>\n\n<hr>\n\n<p>After the previous step, the logic left is fairly straight-forward.</p>\n\n<ol>\n<li>If it is AM and the hours read 12, set hh = \"00\". Otherwise do nothing.</li>\n<li>If it is PM add the hours read 12, do nothing. Otherwise add 12 to the hours.</li>\n</ol>\n\n<p>This is good. One thing to note is that two paths lead to the same conclusion of do nothing or don't change the time. I would keep the exact same logic and restructure a little to avoid redoing work.</p>\n\n<pre><code>...\nif (s[8] == 'A') {\n if (h == 12) {\n // 12:mm:ssAM -&gt; 00:mm:ss\n hh = \"00\";\n }\n} else if (h != 12) {\n // 12:mm:ssPM -&gt; 12:mm:ss, otherwise add 12 hours.\n hh = to_string(h + 12);\n}\n\nreturn hh + s.substr(2, 6);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T15:11:22.793", "Id": "225140", "ParentId": "225134", "Score": "3" } }, { "body": "<p>you can eliminate one if condition using % 12 hours and add 12 hours if the period is &quot;PM&quot;</p>\n<pre><code>//https://www.hackerrank.com/challenges/time-conversion/problem\n#include &lt;bits/stdc++.h&gt;\nusing namespace std;\n/*\n@@12AM----00@@\n1AM-----01\n2AM-----02\n '\n '\n11AM----11\n@@12PM----12@@\n1PM-----13\n2PM-----14\n '\n '\n10PM----22\n11PM----23\n*/\nstring solve(string &amp;s)\n{\n //extracting hrs\n int hrs = stoi(s.substr(0, 2)) % 12;\n\n //checking if last 2nd character is P or not\n if (s[s.length() - 2] == 'P')\n {\n hrs += 12;\n }\n stringstream ss(to_string(hrs));\n //pads with 0 if variable is single digit for eg 5 is padded as 05\n ss &lt;&lt; setw(2) &lt;&lt; setfill('0') &lt;&lt; hrs;\n //replacing hrs with modified hrs\n s.replace(0, 2, ss.str());\n s.pop_back();\n s.pop_back();\n return s;\n}\nint main()\n{\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n\n string s;\n cin &gt;&gt; s;\n cout &lt;&lt; solve(s);\n\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-08T15:19:36.343", "Id": "253220", "ParentId": "225134", "Score": "0" } } ]
{ "AcceptedAnswerId": "225140", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T14:39:16.340", "Id": "225134", "Score": "3", "Tags": [ "c++", "datetime", "formatting" ], "Title": "HackerRank Time Conversion solution" }
225134
<p>I know it could be better, but I’m new to C++, so I don’t know many of the tricks, along with some of the includes that are already obsolete.</p> <p>This program asks for names as input, adds a time for rounds, and then times each player’s turn (i.e. for use in charades). Proven to compile with MinGW cpp.</p> <p>Precompiled version: <a href="https://github.com/ProjectArrow78/EasyGame" rel="nofollow noreferrer">https://github.com/ProjectArrow78/EasyGame</a></p> <pre><code>#include &lt;iostream&gt; #include &lt;cmath&gt; #include &lt;chrono&gt; #include &lt;ctime&gt; #include &lt;stdlib.h&gt; #include &lt;windows.h&gt; #include &lt;cwchar&gt; #include &lt;vector&gt; using namespace std; vector&lt;string&gt; playerlist; string currentplayer; string previousplayer; bool setprevious = true; int playercount; int playerprogression = 1; int roundtime; int timescale = 1000; // Regular timescale: 1000 void collectnames() { string playercollected; bool continuenameloop; bool firstloop = true; int playerscollected = 1; cout &lt;&lt; "How many players will there be?" &lt;&lt; endl; cin &gt;&gt; playercount; playerlist.resize (playercount); while(continuenameloop) { cout &lt;&lt; "Who is player " &lt;&lt; playerscollected &lt;&lt; "?" &lt;&lt; endl; if(firstloop == true) { cin.ignore(); firstloop = false; } getline(cin, playercollected); playerlist.insert (playerlist.begin() + playerscollected, playercollected); playerscollected++; if(playerscollected == playercount+1) { continuenameloop = false; } } } void introduction() { cout &lt;&lt; "Welcome to EasyGame" &lt;&lt; endl; collectnames(); cout &lt;&lt; "How many minutes per turn?" &lt;&lt; endl; cin &gt;&gt; roundtime; } void playerlogic() { playerprogression++; previousplayer = currentplayer; if(playerprogression &gt; playercount) { playerprogression = 1; } currentplayer = playerlist [playerprogression]; if(setprevious == true) { previousplayer = playerlist [1]; setprevious = false; } } void skipturn() { char playturn; cout &lt;&lt; "It is " &lt;&lt; playerlist [playerprogression] &lt;&lt; "'s turn!" &lt;&lt; endl; cout &lt;&lt; "Play turn? (Y/N)" &lt;&lt; endl; cin &gt;&gt; playturn; if(playturn == 'n' or playturn == 'N') { playerlogic(); skipturn(); } } void playertime() { bool runtimer = true; int timeremaining = roundtime; while(runtimer) { cout &lt;&lt; string( 100, '\n' ); cout &lt;&lt; "You have " &lt;&lt; timeremaining &lt;&lt; " minutes remaining." &lt;&lt; endl; Sleep(roundtime * timescale * 12); timeremaining--; if(timeremaining == 0) { cout &lt;&lt; string( 100, '\n' ); cout &lt;&lt; previousplayer &lt;&lt; "'s time is up! \n" &lt;&lt; endl; runtimer = false; } } } int main() { system("color 71"); SetConsoleTitle("EasyGame"); introduction(); while(true) { playerlogic(); playertime(); skipturn(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T15:13:59.203", "Id": "436962", "Score": "2", "body": "You should also include a short description of what your code does in the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T16:51:08.723", "Id": "436990", "Score": "1", "body": "@pacmaninbw _\"Proven to compuile with MinGW cpp.\"_" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T17:19:46.210", "Id": "436994", "Score": "0", "body": "@pacmaninbw Very likely `<string>` is already included already by one of the other headers. This also might depend on the compiler version." } ]
[ { "body": "<p>First, it's really not too bad for a beginner, there are functions with local variables and the function names are descriptive. I'm impressed with the fact that all <code>if</code> statements and loops use the braces (<code>{</code> and <code>}</code>) to create compound statements even though it isn't strictly necessary, it does make maintenance much easier.</p>\n\n<p><strong>Initialize Local Variables</strong><br>\nIn the function <code>collectnames()</code> the variable <code>continuenameloop</code> is uninitialized. In some program languages this isn't a problem local variables are initialized with a null value which might make <code>continuenameloop</code> false (not what is desired in this case). In C++ all local variable are unitialized which means they are in an unknown state. This may have been a typo since the other local variables are initialized.</p>\n\n<p><strong>Prefer std::NAME over using namespace std;</strong><br>\nIf you are coding professionally you probably should get out of the habit of using the \"using namespace std;\" statement. The code will more clearly define where cout and other functions are coming from (std::cin, std::cout). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The function cout you may override within your own classes. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n\n<p><strong>Global Variables</strong><br>\nGenerally global variables are considered a bad practice (2 references from stackexchange sites, <a href=\"https://stackoverflow.com/questions/484635/are-global-variables-bad\">stackoverflow</a> and <a href=\"https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so%20evil\">software engineering</a>). In larger programs with multiple source files it is very difficult to write correct code, debug and maintain code using global variables. Finding where a variable value is altered becomes a huge task. A second problem with global variables in a multi-file program is that global variables are global in scope and can lead to duplicate definitions at link time. In an object oriented program all of these variables could have been global within the object but the scope would still be limited to the object itself.</p>\n\n<p>In non-object oriented programming it might be better to declare the variables in functions or procedures and pass the values into sub functions.</p>\n\n<p><strong>Error Checking</strong><br>\nThere doesn't seem to be any error checking, users have been known to enter the wrong information. What happens if a negative value for <code>roundtime</code> is entered?</p>\n\n<p><strong>Use Objects</strong><br>\nAs the game gets more complex it might be a good idea to create classes to implement it. Most of the this current program might fit into a class called game. It might be beneficial if users were a separate class with scores, and possibly elapsed times. Using objects will allow the code to be independent from other portions of the code, and details of the implementation can be hidden.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T00:47:00.423", "Id": "225166", "ParentId": "225135", "Score": "3" } }, { "body": "<p>Make use of the <code>do</code>/<code>while</code> loop (instead of a <code>while</code> loop) where you can. Both <code>collectnames</code> and <code>playertime</code> could benefit from a <code>do</code>/<code>while</code> loop. The main difference is the the <code>do</code>/<code>while</code> loop will run once before checking the condition. Oftentimes this will allow elimination of variables. Any time you find yourself coding something like <code>flag = true; while (flag) { }</code> you probably want a <code>do</code>/<code>while</code> instead.</p>\n\n<p>In <code>collectnames</code>, using <code>do</code>/<code>while</code> can eliminate use of the (uninitialized) <code>continuenameloop</code> variable.</p>\n\n<pre><code>do {\n // ...\n playerlist.emplace_back(playercollected);\n} while (++playerscollected &lt;= playercount);\n</code></pre>\n\n<p>Note that I've also replaced <code>playerlist.insert</code> with <code>playerlist.emplace_back</code>, which is a better choice (or, sometimes, <code>push_back</code>) for adding to the end of a <code>vector</code>.</p>\n\n<p>The <code>do</code>/<code>while</code> loop in <code>playertime</code> can eliminate <code>runtimer</code>, and the \"Time's up!\" message would be outside the loop.</p>\n\n<p>Adding a space between a keyword and the <code>(</code> that follows can improve the readability.</p>\n\n<pre><code>if (condition)\nwhile (condition)\nfor (;;)\n</code></pre>\n\n<p>When calling a function, or using the <code>[]</code> array subscript, leave off the space (like you've done for most of your calls). However you choose to do it, <em>be consistent</em>. It is easier to find things with consistent spacing.</p>\n\n<p>In many places, you can use a <code>\\n</code> (or add that to a string) in place of <code>std::endl</code>. Using <code>endl</code> will flush the output buffer, which can reduce performance. If you're outputting more text in the next statement, you can replace it with the <code>\\n</code> newline.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T01:02:15.000", "Id": "225167", "ParentId": "225135", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T14:43:36.817", "Id": "225135", "Score": "3", "Tags": [ "c++", "game", "windows", "timer", "gcc" ], "Title": "A little C++ program to have timed rounds for a game" }
225135
<p>I want to filter search results by multiple filters at once. Is it possible to reduce the number of if statements? My code:</p> <pre><code> public IEnumerable&lt;Article&gt; Search(ArticleFiltersModel filters, ArticleSortOptions? options) { var result = Mapper.Map&lt;IQueryable&lt;Article&gt;&gt;(_unitOfWork.Articles.AsQueryable()); if (filters != null) Filter(ref result, filters); else result = result.Where(article =&gt; article.IsAvailable == true); if (options.HasValue) Sort(ref result, options.Value); return result; } private void Filter(ref IQueryable&lt;Article&gt; articles, ArticleFiltersModel filters) { if (filters.IsAvailable.HasValue) articles = articles.Where(article =&gt; article.IsAvailable == filters.IsAvailable); if (!string.IsNullOrEmpty(filters.Name)) articles = articles.Where(article =&gt; article.Title.Contains(filters.Name)); if (filters.AreaFrom.HasValue) articles = articles.Where(article =&gt; article.House.Area &gt;= filters.AreaFrom); if (filters.AreaTo.HasValue) articles = articles.Where(article =&gt; article.House.Area &lt;= filters.AreaTo); if (filters.PriceFrom.HasValue) articles = articles.Where(article =&gt; article.House.Area &gt;= filters.PriceFrom); if (filters.PriceTo.HasValue) articles = articles.Where(article =&gt; article.House.Area &lt;= filters.PriceTo); if (filters.Type.HasValue) articles = articles.Where(article =&gt; article.House.Type == filters.Type); if (filters.RoomsCount.HasValue) articles = articles.Where(article =&gt; article.House.RoomsCount == filters.RoomsCount); if (filters.Floors.HasValue) articles = articles.Where(article =&gt; article.House.FloorsCount == filters.Floors); if (filters.Floor.HasValue) articles = articles.Where(article =&gt; article.House.Floor == filters.Floor); if (filters.HasParking.HasValue) articles = articles.Where(article =&gt; article.House.HasParking == filters.HasParking); if (filters.WithHomeAppliances.HasValue) articles = articles.Where(article =&gt; article.House.WithHomeAppliances == filters.WithHomeAppliances); } </code></pre> <p>My filter model:</p> <pre><code>public class ArticleFiltersModel { public string Name { get; set; } public decimal? AreaFrom { get; set; } public decimal? AreaTo { get; set; } public decimal? PriceFrom { get; set; } public decimal? PriceTo { get; set; } public HouseType? Type { get; set; } public int? RoomsCount { get; set; } public bool? IsFurnished { get; set; } public int? Floors { get; set; } public int? Floor { get; set; } public bool? HasParking { get; set; } public bool? WithHomeAppliances { get; set; } public bool? IsAvailable { get; set; } } </code></pre> <h2>UPDATE</h2> <p>Article.cs:</p> <pre><code>public class Article { public int Id { get; set; } public string Title { get; set; } public int HouseId { get; set; } public House House { get; set; } public string Description { get; set; } public DateTime Added { get; set; } public bool IsAvailable { get; set; } public ICollection&lt;Realtor&gt; Realtors { get; set; } public ICollection&lt;Image&gt; Images { get; set; } } </code></pre> <p>House.cs:</p> <pre><code>public enum HouseType { House, Apartment, Condo, Cooperative, Land, Office, Restaurant, Bar, Storage, Building, Other } public class House { public int Id { get; set; } public decimal Area { get; set; } public decimal Price { get; set; } public int RoomsCount { get; set; } public bool IsFurnished { get; set; } public int FloorsCount { get; set; } public int Floor { get; set; } public bool HasParking { get; set; } public bool WithHomeAppliances { get; set; } public int AddressId { get; set; } public Address Address { get; set; } public HouseType Type { get; set; } public int PhotoId { get; set; } public Image Photo { get; set; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T16:02:30.107", "Id": "436979", "Score": "4", "body": "Check out https://codereview.stackexchange.com/q/143094/52662 to see if that helps you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T16:38:55.953", "Id": "436987", "Score": "4", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:38:01.210", "Id": "437032", "Score": "0", "body": "Could you also post the code for _Article_ for completeness?" } ]
[ { "body": "<p>Given an extension method:</p>\n\n<pre><code>public static IQueryable&lt;T&gt; NullWhere&lt;T&gt;(this IQueryable&lt;T&gt; source, Expression&lt;Func&lt;T, bool?&gt;&gt; expression, bool? compare) =&gt; compare.HasValue\n ? source.Where(Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;(Expression.Equal(expression.Body, Expression.Constant((bool)compare)), expression.Parameters))\n : source;\n</code></pre>\n\n<p>You can then use:</p>\n\n<pre><code>articles = articles.NullWhere(article =&gt; article.IsAvailable, filters.IsAvailable);\n</code></pre>\n\n<p>Note this works for equality for nullable <code>bool</code>s - you'll have to create other extension methods for nullable <code>decimal</code>s with greater-than-or-equal-to, null/empty strings with <code>string.Contains()</code>, etc. But the principle will be the same behind each.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:26:33.173", "Id": "437026", "Score": "2", "body": "I'm contemplating whether Expresssion is really required here. Why not just use the Func instead?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:31:30.103", "Id": "437028", "Score": "2", "body": "@dfhwze expressions don't have to be required. They are cool by themselfes wherever used ;-]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:36:38.920", "Id": "437030", "Score": "1", "body": "@dfhwze oh, this could end up recursive... who would be generating who? A T4 template for generating expressions to generate T4 templates to generate code generating expressions generating T4 templates... a very deep rabitt hole." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T16:32:26.670", "Id": "225146", "ParentId": "225143", "Score": "3" } }, { "body": "<p>I read it as one long <code>AND</code> operation where the result is the articles that satisfy all the valid predicates. You could therefore build an enumerable of valid predicates in an extension method:</p>\n\n<pre><code> public static class ArticleFilterExtensions\n {\n public static IEnumerable&lt;Predicate&lt;Article&gt;&gt; GetValidPredicates(this ArticleFiltersModel filter)\n {\n if (filter.IsAvailable.HasValue)\n yield return a =&gt; a.IsAvailable == filter.IsAvailable;\n if (!string.IsNullOrWhiteSpace(filter.Name))\n yield return a =&gt; a.Title.Contains(filter.Name);\n if (filter.AreaFrom.HasValue)\n yield return a =&gt; a.House.Area &gt;= filter.AreaFrom;\n // etc.\n\n if (filter.WithHomeAppliances.HasValue)\n yield return a =&gt; a.House.WithHomeAppliances == filter.WithHomeAppliances;\n }\n }\n</code></pre>\n\n<p>And your filter method could then be reduced to:</p>\n\n<pre><code>private void Filter(ref IQueryable&lt;Article&gt; articles, ArticleFiltersModel filters)\n{\n var predicates = filters.GetValidPredicates().ToList();\n articles = articles.Where(a =&gt; predicates.All(p =&gt; p(a)));\n}\n</code></pre>\n\n<p>You could then easily create an <code>OR</code> filter as </p>\n\n<pre><code>private void OrFilter(ref IQueryable&lt;Article&gt; articles, ArticleFiltersModel filters)\n{\n var predicates = filters.GetValidPredicates().ToList();\n articles = articles.Where(a =&gt; predicates.Any(p =&gt; p(a)));\n}\n</code></pre>\n\n<p>`</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T17:50:49.667", "Id": "437002", "Score": "1", "body": "+1 for using a single call to _Where_ and reusing predicates for _or_, _and_" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T17:56:24.407", "Id": "437005", "Score": "1", "body": "@dfhwze: Maybe `GetValidPredicates()` should return an array or a readonly list instead of `yield`-ing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T17:59:07.233", "Id": "437006", "Score": "0", "body": "I think we are micro-optimising in such case. But a comparative test with a huge amount of predicates could _yield_ us more info." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:12:12.233", "Id": "437014", "Score": "0", "body": "@dfhwze this would be a pretty academic test because which sane person is using _a huge amount of predicates_ in the real-world? :-P" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:14:36.883", "Id": "437016", "Score": "0", "body": "@t3chb0t Have you never worked in the _banking sector_? :p" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:15:52.903", "Id": "437019", "Score": "1", "body": "@dfhwze I guess I should answer this question with _luckily_ not insteady of _unfortunately_ haha" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T11:58:29.637", "Id": "437131", "Score": "0", "body": "@HenrikHansen Why do you add `ToList()` after `GetValidPredicates()`? `IQueryable` defers execution; `ToList()` forces immediate execution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T12:09:11.037", "Id": "437132", "Score": "0", "body": "@MY_G: The idea is that by calling `ToList()` the predicates will only be created once, while without they will be recreated for each article in the where method" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T17:08:31.820", "Id": "225148", "ParentId": "225143", "Score": "11" } }, { "body": "<p>I would further improve <a href=\"https://codereview.stackexchange.com/a/225148/59161\">Henrik Hansen</a>'s code by throwing away the <code>if</code>s and integrating the preconditions inside in the queries so they would become:</p>\n\n<pre><code>yield articles.Where(article =&gt; !filters.IsAvailable.HasValue || article.IsAvailable == filters.IsAvailable);\n</code></pre>\n\n<p>This would not only make it more readable but would show us that now we can actually generate these expressions (probably with <a href=\"https://codereview.stackexchange.com/a/225146/59161\">Jesse C. Slicer</a>'s code) which would save us a lot of typing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:48:05.393", "Id": "437034", "Score": "0", "body": "Henrik returns predicates, later used to get articles, where you return articles directly. Did you mean to inline the _if_ in the predicates or directly in the result set?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:56:31.340", "Id": "437036", "Score": "1", "body": "In this way you query every filter for every article where mine filter the filters once and then only use the valid filters on each article." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T19:00:25.380", "Id": "437037", "Score": "0", "body": "@HenrikHansen of course but the sql-server doesn't care, it can optmize it away... I'm pretty sure of that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T19:12:19.780", "Id": "437040", "Score": "0", "body": "@HenrikHansen I've had discussions about situations like this before. Should a developer write code, having optimisations by the used API and/or compiler in mind or not? I don't have an answer to that question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T19:30:28.027", "Id": "437046", "Score": "1", "body": "@dfhwze I cannot find any signifficant difference in the two execution plans, even with the help of the execution-plan comparer. I wonder whether someone already has asked this question on stack-overflow..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T09:36:35.193", "Id": "437272", "Score": "1", "body": "@t3chb0t - there are a lot of things at play here. I can tell you that I have seen an 80% reduction in cost in EF for a complex query by \"flattening\" the predicates into a single `Where` rather than using multiple `Where` calls. Projection (Select) and navigation property use can have big impacts on generated SQL - hard to test without a specific case!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T10:01:53.323", "Id": "437274", "Score": "0", "body": "@RobH I believe you. Even LINQPad often generates a more efficient query than EF. Running LINQ there and then just copy-pasting it for EF means a high risk of client-sinde execution. I now by default disable this feature. It might be similar with multiple `where`s. EF silently switches from server queries to linq. This is a performance killer for largs databases. [Client vs. Server Evaluation](https://docs.microsoft.com/en-us/ef/core/querying/client-eval). I find it should not be doing this. Only when explicitly enabled. Might be convenient for testing but not in production." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:21:21.790", "Id": "225154", "ParentId": "225143", "Score": "5" } }, { "body": "<p>How about a generic extension method that takes a boolean and an expression, whereas the expression is only evaluated in case the boolean is true:</p>\n\n<pre><code>public static IQueryable&lt;T&gt; When&lt;T&gt;(\n this IQueryable&lt;T&gt; source, bool trigger, Expression&lt;Func&lt;T, bool&gt;&gt; expression)\n{\n if (trigger)\n {\n return source.Where(expression);\n }\n\n return source;\n}\n</code></pre>\n\n<p>It allows you to chain the calls similar to what @t3chb0t suggested, but it will not even chain unnecessary filters:</p>\n\n<pre><code>articles = articles.When(filters.IsAvailable.HasValue, article =&gt; article.IsAvailable == filters.IsAvailable)\n .When(!string.IsNullOrEmpty(filters.Name), article =&gt; article.Title.Contains(filters.Name));\n</code></pre>\n\n<p>Similarly it would be possible to write an even more generic method that doesn't take <code>Expression&lt;Func&lt;T, bool&gt;&gt;</code> as third parameter but an <code>Expression&lt;Func&lt;IQueryable&lt;T&gt;, IQueryable&lt;T&gt;&gt;&gt;</code>, which would allow you to chain arbitrary methods (with a trigger).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T05:06:25.553", "Id": "225176", "ParentId": "225143", "Score": "2" } } ]
{ "AcceptedAnswerId": "225148", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T15:33:40.767", "Id": "225143", "Score": "9", "Tags": [ "c#", "linq" ], "Title": "Filter search results by multiple filters in one operation" }
225143
<p>An endpoint that my application interacts with allows you to specify which fields are returned in the JSON result. My application will then map the JSON to a POJO using Jackson. Quite often I add more fields in one place and forget to add it in the other which results in problems. I wrote a unit test to help make the process easier but I feel like there could be room for improvements.</p> <p>Here's what I have so far:</p> <pre class="lang-java prettyprint-override"><code>private static final String[] POTENTIAL_FIELDS = new String[] { "field1", "field2" }; @Test public void checkFields() { // get all constant fields Set&lt;String&gt; constantFields = Arrays.stream(POTENTIAL_FIELDS) .map(String::toLowerCase) .collect(Collectors.toSet()); // get all private fields Set&lt;String&gt; reflectFields = Arrays.stream(FieldsModel.class.getDeclaredFields()) .filter((field) -&gt; !Modifier.isStatic(field.getModifiers())) .map(field -&gt; field.getName().toLowerCase()) .collect(Collectors.toSet()); Set&lt;String&gt; symmetricDifference = Sets.symmetricDifference(constantFields, reflectFields); // check if there's a difference if (!symmetricDifference.isEmpty()) { Assert.fail(String.format("Difference: %s\n", String.join(",", symmetricDifference))); } } private static class FieldsModel { private int field1; private String field2; } </code></pre> <p>The only non-standard imports are <code>FieldsModel</code> which is what the name suggests, and <code>Sets</code> which is from Guava (<code>com.google.coom.collect.Sets</code>). <a href="https://github.com/google/guava/blob/master/guava/src/com/google/common/collect/Sets.java#L962" rel="nofollow noreferrer">Here</a> is a direct link to the method I used.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T16:36:05.163", "Id": "436984", "Score": "0", "body": "\"Here's what I have so far\" Does it work like you want it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T16:37:38.910", "Id": "436986", "Score": "0", "body": "Yes it does, it has the desired effect. I just was wondering if there was a more efficient way to find the disjunctive union than Guava's symmetricDifference or if I did something weird with Assert.fail(...)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:46:01.683", "Id": "437033", "Score": "0", "body": "Do you know how _Sets.symmetricDifference_ works? Is the algorithm available in literature or how do you suggest we can compare it to other methods?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:55:22.983", "Id": "437035", "Score": "1", "body": "@dfhwze Just edited my post to provide a direct link to that method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T19:09:24.487", "Id": "437039", "Score": "0", "body": "Your question lacks import statements, MyConstants, FieldsModel code. A reviewer has to write their own stubs, which makes it harder to test your code first-hand." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T19:33:23.920", "Id": "437048", "Score": "1", "body": "@dfhwze Edited again to include those" } ]
[ { "body": "<ol>\n<li>If you are using only one class there is no need to use ArrayList for <code>POTENTIAL_FIELDS</code> and then after converting it to set. Class will have a unique field name.</li>\n<li>If the number of class fields are not large then no need to worried about performance.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T12:51:35.333", "Id": "437668", "Score": "0", "body": "In the comments on my original question, they asked me to add in `POTENTIAL_FIELDS` so testers didn't need to. In the actual code, it's in a separate class. Also, where do you see an `ArrayList`?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T10:16:36.100", "Id": "225406", "ParentId": "225144", "Score": "0" } }, { "body": "<p>On the whole, I think this is a pretty neat solution to your problem. A couple of observations...</p>\n\n<p><strong>case == CASE</strong></p>\n\n<p>You lower case everything. Maybe this is exactly what you're after, but to me, <code>fieldOne</code> and <code>fieldone</code> aren't the same, so I'd want to know about that difference.</p>\n\n<p><strong>Developer time vs test time</strong></p>\n\n<p><code>symmetricDifference</code> gives back a set of all of the differences, it doesn't discriminate between the left and the right side. So, if you've added something to <code>FieldsModel</code> and something else to <code>POTENTIAL_FIELDS</code> they would both come back. The developer then has to go and look at both and reconcile where the problem is. In reality this might not be a problem because the developer has probably worked on one of the files recently, so would realise which one they'd missed, however it would be better if the test showed what was missing from where. You could do something like this:</p>\n\n<pre><code>String inConstantButNotModel = constantFields.stream()\n .filter(i -&gt; !reflectFields.contains(i))\n .collect(Collectors.joining(\",\"));\nString inModelButNotConstant = reflectFields.stream()\n .filter(i -&gt; !constantFields.contains(i))\n .collect(Collectors.joining(\",\"));\n\nassertThat(String.format(\"ConstantsMissing: %s\\nModelMissing: %s\\n\",\n inModelButNotConstant,\n inConstantButNotModel))\n .isEqualTo(\"ConstantsMissing: \\nModelMissing: \\n\");\n</code></pre>\n\n<p>To give output along the lines of...</p>\n\n<pre><code>ConstantsMissing: field5,field4\nModelMissing: field3\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T14:57:08.353", "Id": "466042", "Score": "0", "body": "That is a really good point and quite clever. Thank you! I'm actually going to go back to open a PR for this project even though I've been off it for awhile." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T11:24:11.790", "Id": "237627", "ParentId": "225144", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T16:17:29.517", "Id": "225144", "Score": "4", "Tags": [ "java", "unit-testing", "set", "guava" ], "Title": "Ensure difference between sets" }
225144
<p>This is the updated version of the script first posted <a href="https://codereview.stackexchange.com/questions/200044/debian-firefox-quantum-update-script">here</a>.</p> <p>Specifically, I first wanted to save the logs to a log file at <code>"$HOME/.logs/ffupgrade.log"</code>, but I'm not sure whether that is good practice or whether I should log to syslog. When logging to a file, I would add another variable <code>logfile</code> at the beginning and adapt the functions like so (similarly for <code>success</code> and <code>warning</code>):</p> <pre class="lang-bsh prettyprint-override"><code>logfile="$HOME/.logs/ffupgrade.log" error_exit() { msg="$1" echo -e "$(date) ${red}ERROR:${nocolor} ${msg}" 1&gt;&amp;2 echo "$(date) ERROR: $msg" &gt;&gt; "$logfile" exit 1 } </code></pre> <p>I'm also wondering if it's better to only run the commands that need it with <code>sudo</code> or if I should rerun the whole script as <code>sudo</code> after prompting for the password like this:</p> <pre class="lang-bsh prettyprint-override"><code>if [[ "$EUID" != 0 ]]; then warning "Please run as root" sudo "$0" "$@" fi </code></pre> <p>As always, any other comments are welcome as well.</p> <pre class="lang-bsh prettyprint-override"><code>#!/bin/bash # firefox_upgrade - program to upgrade firefox quantum red="\033[1;31m" yellow="\033[1;33m" green="\033[1;32m" nocolor="\033[0m" error_exit() { msg="$1" echo -e "$(date) ${red}ERROR:${nocolor} ${msg}" 1&gt;&amp;2 logger "ERROR: $msg" exit 1 } warning() { msg="$1" echo -e "$(date) ${yellow}WARNING:${nocolor} ${msg}" logger "WARNING: $msg" } success() { msg="$1" echo -e "$(date) ${green}SUCCESS:${nocolor} ${msg}" logger "SUCCESS: $msg" } ffbin="/opt/firefox" fflink="/usr/bin/firefox-quantum" ffpath= fffile= # check if path argument was provided if [ $# -ne 1 ]; then error_exit "usage: $0 firefox_quantum_path" fi echo "Checking for root access.." if [[ "$EUID" = 0 ]]; then success "already root" else sudo -k # make sure to ask for password on next sudo if sudo true; then success "correct password" else error_exit "wrong password" fi fi # parsing path and filename ffpath="$1" fffile="${ffpath##*/}" # check if input is a valid file if [ ! -f "$ffpath" ]; then error_exit "Invalid file! Aborting." fi # check the firefox version ffpref="${fffile%.*}" ffversion="${ffpref//[^0-9]/}" ffinstalled_version="$($fflink --version | sed 's/[^0-9]*//g')" vind=0 if [[ "$ffversion" &lt; "$ffinstalled_version" ]]; then warning "The version to be installed is lower than the installed version" vind=1 elif [[ "$ffversion" = "$ffinstalled_version" ]]; then warning "The version to be installed is the same as the installed version" vind=1 fi if [[ "$vind" = 1 ]]; then echo "Do you want to continue anyway?" select yn in "Yes" "No"; do case $yn in Yes ) : ;; No ) exit;; esac done fi # removing previous install, if existent if [ -e "$ffbin" ]; then sudo rm -rf "$ffbin" #mv "$ffbin" "$ffbin.old" success "removed previous install" else warning "$ffbin doesn't exist." fi # removing previous symlink, if existent if [ -L "$fflink" ]; then sudo rm -f "$fflink" success "removed previous symlink" else warning "$fflink doesn't exist." fi # copying the tar to /opt if ! sudo rsync -ah --progress "$ffpath" "/opt/$fffile"; then error_exit "Couldn't copy the tarball. Aborting." fi success "tarball copied" # unpacking the tar if successfully changed directory if ! sudo tar -jxvf "/opt/$fffile" -C /opt; then error_exit "Could not extract file! Aborting." fi success "tarball was extracted" # if unpack was successful, set permissions, create symlink, and remove tar sudo chmod 755 "$ffbin" success "permissions set" sudo ln -s "$ffbin/firefox" "$fflink" success "symlink created" sudo rm "/opt/$fffile" success "tarball removed from /opt" success "Firefox was upgraded" <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:31:13.207", "Id": "437027", "Score": "1", "body": "Questions need to be self contained. Post all necessary context needed to review the code you have in your question please." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T19:36:35.217", "Id": "437049", "Score": "1", "body": "What is missing from the question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T19:37:45.447", "Id": "437050", "Score": "0", "body": "Context as mentioned (links don't count)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T19:40:46.607", "Id": "437051", "Score": "2", "body": "I don't understand. Am I supposed to post the complete first version in this question? That would be quite a lot of code and not really add any value when you could just look at the previous question. Or are you referring to the logfile? If so, I will edit it to include a complete example of how that would look." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T19:43:15.753", "Id": "437052", "Score": "1", "body": "Let's start with your title: _\"Debian Firefox Quantum update script v2\"_ What does that mean??" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T21:09:09.887", "Id": "437057", "Score": "1", "body": "Well this is Code Review not stack overflow. The preview text in the title bar when you ask a question says *State the task that your code accomplishes.* My code upgrades firefox-quantum and it's the second version of one that was posted earlier. That's pretty succinct, I'd say, and certainly does not warrant a downvote." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T21:11:53.793", "Id": "437058", "Score": "2", "body": "Furthermore, I've asked you what exactly is missing, in your opinion, from the context of the question, as I'd be happy to provide additional detail. You have failed to provide an answer to that offering no explanation. I'd say that's pretty poor commentary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T08:05:33.723", "Id": "437263", "Score": "1", "body": "Since the other link is on this very site, we have some control over whether or not the link goes dead or not. I fail to see a problem as long as nobody goes sabotaging the question behind the link (and we have tools to fix that should it happen)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T08:08:50.890", "Id": "437265", "Score": "1", "body": "As to the comment on your title: it boils down to what kind of program it is, not what the program does. Both this and the older question can be improved by stating what the code does, instead of in what environment it runs in. Leave that to the question body instead. We have [meta discussions about titles](https://codereview.meta.stackexchange.com/questions/tagged/titles) if you're interested." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T16:26:47.000", "Id": "437349", "Score": "0", "body": "I understand, I will give my best attempt to change the titles of both questions to something that's more descriptive of what the program does. I also don't mind edits if anyone thinks they could be improved further." } ]
[ { "body": "<h3>To <code>sudo</code> or not to <code>sudo</code></h3>\n\n<blockquote>\n <p>I'm also wondering if it's better to only run the commands that need it with sudo or if I should rerun the whole script as sudo after prompting for the password like this:</p>\n\n<pre><code>if [[ \"$EUID\" != 0 ]]; then\n warning \"Please run as root\"\n sudo \"$0\" \"$@\"\nfi\n</code></pre>\n</blockquote>\n\n<p>Can the script do its job without <code>root</code> permissions? This script cannot, because it wants to modify files that are normally only editable by <code>root</code>, such as <code>/opt</code> and <code>/usr/bin</code>. Therefore, the script requires <code>root</code> permissions. A good way to handle this is to check if the user has <code>root</code> permission, and exit if that's not the case, for example:</p>\n\n<pre><code>if [[ \"$EUID\" != 0 ]]; then\n warning \"Please run as root\"\n exit 1\nfi\n</code></pre>\n\n<p>There's really no need to include the complexity of getting root permission in the script. With the above simple check, the user can either switch to the <code>root</code> user, or rerun the script with <code>sudo</code>. The rest of the script can assume the privilege (and responsibility) of <code>root</code>.</p>\n\n<h3>About logging</h3>\n\n<blockquote>\n <p>I first wanted to save the logs to a log file at <code>\"$HOME/.logs/ffupgrade.log\"</code>, but I'm not sure whether that is good practice or whether I should log to <code>syslog</code>.</p>\n</blockquote>\n\n<p>I don't really know. But I can reason about it.</p>\n\n<p>Does this really belong to <code>syslog</code>? The script upgrades Firefox. Let's look at something similar, for example, what happens when you upgrade software using the standard package manager of a Linux system. I just upgraded something in a Debian system I have at hand, and it didn't log anything about it in <code>syslog</code>. It may be relevant whether the upgrade is happening on explicit user action or automatically. I would conclude that when a user upgrades a package manually, it's not noteworthy enough to add to <code>syslog</code>.</p>\n\n<p>On the other hand, what happens if you keep logging to <code>~/.logs</code>? It accumulates forever without cleanup. You might want to log somewhere else that is subject to log a rotation policy in your systems by default, or document how to set it up in the script. This could be a valid argument, except that I doubt your Firefox upgrade logs will ever accumulate to anything significant. So... I would not bother about rotation. If the script is only going to run as <code>root</code>, then I would log somewhere more visible than <code>~/.logs</code>, let's say <code>/var/log</code>.</p>\n\n<blockquote>\n <p>When logging to a file, I would add another variable <code>logfile</code> at the beginning and adapt the functions like so (similarly for <code>success</code> and <code>warning</code>)</p>\n</blockquote>\n\n<p>I would add a <code>logger</code> <em>function</em> to encapsulate that logic, overriding the <code>logger</code> <em>program</em>, and then you won't need to touch the other functions.</p>\n\n<h3>Use <code>local</code> for local variables</h3>\n\n<p>It's good to use <code>local</code> for local variables in functions to avoid setting values in the global scope, which can be a source of nasty errors.</p>\n\n<h3>Double quote variables used on the command line</h3>\n\n<p><code>$fflink</code> here should be enclosed in double-quotes:</p>\n\n<blockquote>\n<pre><code>ffinstalled_version=\"$($fflink --version | sed 's/[^0-9]*//g')\"\n</code></pre>\n</blockquote>\n\n<h3>Comparing versions</h3>\n\n<p>I have a doubt about comparing versions.\nThe script removes all non-numeric characters, and then compares values lexicographically.\nAre you sure that will work reliably?\nIt would have been good to include some example versions in comments, to help assure readers.</p>\n\n<p>Also, to remove non-numeric characters, I would use <code>tr -cd 0-9</code> instead of <code>sed 's/[^0-9]*//g'</code>.</p>\n\n<h3>Verify exit codes</h3>\n\n<p>The script does some things, and tells some things to the user that might not be true, for example here:</p>\n\n<blockquote>\n<pre><code>sudo chmod 755 \"$ffbin\"\nsuccess \"permissions set\"\nsudo ln -s \"$ffbin/firefox\" \"$fflink\"\nsuccess \"symlink created\"\nsudo rm \"/opt/$fffile\"\nsuccess \"tarball removed from /opt\"\nsuccess \"Firefox was upgraded\"\n</code></pre>\n</blockquote>\n\n<p>Even if those commands fail, the script will print success messages, and happily carry on.</p>\n\n<h3>Use better variable names</h3>\n\n<p>What is <code>vind</code>?</p>\n\n<h3>Use verbose mode more</h3>\n\n<p>I would add <code>-v</code> to all interesting commands that support it, for example <code>rm</code>, <code>mv</code>.</p>\n\n<h3>Replace <code>1&gt;&amp;2</code> with <code>&gt;&amp;2</code></h3>\n\n<p>The default file descriptor redirected is <code>1</code>, no need to spell it out explicitly.</p>\n\n<h3>Simple is better than complex</h3>\n\n<p><code>[ $# != 1 ]</code> is probably more natural and therefore easier to understand than <code>[ $# -ne 1 ]</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T22:18:51.483", "Id": "437066", "Score": "0", "body": "Thanks. If you could add something concerning `logger` vs. `logfile` (I have added more detail to the question), I will accept this answer. As for the versions, you are right, there is the theoretical possibility that the version might contain letters as well, I will have to think of a better way to extract that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T05:13:25.320", "Id": "437081", "Score": "0", "body": "@iuvbio I added a section about it ;-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T20:49:02.860", "Id": "225160", "ParentId": "225152", "Score": "3" } } ]
{ "AcceptedAnswerId": "225160", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:01:15.137", "Id": "225152", "Score": "2", "Tags": [ "bash", "linux", "installer", "firefox" ], "Title": "Upgrade Firefox Quantum with logging and version check" }
225152
<p>I currently am working on a game engine written in C++ with libuv backed for io system calls. I have a FileSystem class that just 'works'. I am allow to read files without blocking but the current design I have is lacking a bit. I am hoping some of you all could comment on my code and help me improve it.</p> <p>Here are some noticeable changes:</p> <ol> <li>To start off <code>FileContext-&gt;data[64]</code>. How would I get rid of the fixed size? Basically I saw examples (there really isnt much examples of libuv) that show them using a <code>char*</code> instead of the fixed size. I tried using a <code>char*</code> but I got a <code>permission denied</code> error.</li> <li>This one is based on the first one. I have <code>FileContext-&gt;content</code> and <code>FileContext-&gt;promise</code> which in theory would return the same value after some time. Basically the former get written to by libuv using the <code>char [64]</code>. I do this because other wise I would not have the full file content string. The latter get it value set as the former value once the task get completed. How would I get rid of one or the other? I rather not have both. Even better would be on how to get rid of both of them and just have <code>FileSystem-&gt;read</code> return the promise object instead.</li> <li>FileSystem->_contexts is a raw pointer. I made it a <code>std::unique_ptr</code> and I ran into a odd bug. Basically my program crashed with undefined behavior and I wasn't quite sure so I made it a raw pointer again and it started working again.</li> <li>Should <code>FileSystem-&gt;read</code> return a <code>std::promise</code> or a <code>std::future</code> object?</li> <li>How would I go about dealing with errors? For example a <code>permission denied</code> for read a file error. I want to use <code>std::exception</code>s but I am not quite sure and would like comments on that as well. </li> </ol> <p>I think that is all that I was able to notice on my design, if you see something feel free to comment on that as well as what is above. I would very much appreciate it, thank you.</p> <pre class="lang-cpp prettyprint-override"><code>#ifndef RISKY_ENGINE_INSTANCES_FILE_SYSTEM_HEADER #define RISKY_ENGINE_INSTANCES_FILE_SYSTEM_HEADER #include &lt;future&gt; #include &lt;memory&gt; #include &lt;string&gt; #include "risky/engine/prefix.hpp" #include "risky/engine/core/ClassMaker.hpp" #include "risky/engine/instances/Instance.hpp" #if defined(RISKY_USE_LIBUV) #include &lt;uv.h&gt; #endif namespace risky { namespace engine { class Engine; class FileSystem; struct FileContext { std::string content; std::shared_ptr&lt;Engine&gt; engine; std::promise&lt;std::string&gt; promise; std::shared_ptr&lt;FileSystem&gt; fileSystem; #if defined (RISKY_USE_LIBUV) // char* data; char data[64]; uv_fs_t open; uv_fs_t read; uv_fs_t close; uv_buf_t buffer; uv_loop_t* loop; #endif }; class FileSystem: public Instance { public: explicit FileSystem(const std::shared_ptr&lt;Engine&gt;&amp; engine) noexcept; virtual ~FileSystem() noexcept; virtual std::promise&lt;std::string&gt;&amp; read(const std::string&amp; file) const noexcept; protected: std::vector&lt;FileContext*&gt; _contexts; //Todo: make these unique pointers? #if defined(RISKY_USE_LIBUV) uv_loop_t* _loop; #endif }; DECLARE_CLASS(FileSystem); } } #endif </code></pre> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include "risky/engine/core/Engine.hpp" #include "risky/engine/instances/LogService.hpp" #include "risky/engine/instances/FileSystem.hpp" namespace risky { namespace engine { DEFINE_CLASS(FileSystem, false, true, Instance) { } #if defined(RISKY_USE_LIBUV) static void on_read(uv_fs_t* request) noexcept { FileContext* context = static_cast&lt;FileContext*&gt;(request-&gt;data); uv_fs_req_cleanup(request); if (request-&gt;result &lt; 0) { //Todo: throw exception? fprintf(stderr, "error: %s\n", uv_strerror(request-&gt;result)); return; } if (request-&gt;result != 0) { context-&gt;content += context-&gt;data; std::cout &lt;&lt; context-&gt;data &lt;&lt; std::endl; //b std::cout &lt;&lt; "File content: " &lt;&lt; context-&gt;content &lt;&lt; std::endl; uv_fs_read(uv_default_loop(), &amp;context-&gt;read, context-&gt;open.result, &amp;context-&gt;buffer, 1, -1, on_read); } else { context-&gt;promise.set_value(context-&gt;content); uv_fs_close(request-&gt;loop, &amp;context-&gt;close, context-&gt;open.result, NULL); //Remove from vector delete context; } } static void on_open(uv_fs_t* request) noexcept { FileContext* context = static_cast&lt;FileContext*&gt;(request-&gt;data); if (request-&gt;result &lt; 0) { fprintf(stderr, "error: %s\n", uv_strerror(request-&gt;result)); //Todo: throw exceptions? return; } context-&gt;buffer = uv_buf_init(context-&gt;data, sizeof(context-&gt;data)); uv_fs_read(request-&gt;loop, &amp;context-&gt;read, request-&gt;result, &amp;context-&gt;buffer, 1, -1, on_read); uv_fs_req_cleanup(request); } #endif FileSystem::FileSystem(const std::shared_ptr&lt;Engine&gt;&amp; engine) noexcept : Instance(engine), _loop(engine-&gt;getEventLoop()) { } FileSystem::~FileSystem() noexcept { } std::promise&lt;std::string&gt;&amp; FileSystem::read(const std::string&amp; file) const noexcept { FileContext* context = new FileContext(); //Todo: make this a uqiue pointer? // std::unique_ptr&lt;FileContext&gt; context = std::make_unique&lt;FileContext&gt;(); #if defined(RISKY_USE_LIBUV) context-&gt;loop = _loop; context-&gt;engine = _engine; context-&gt;open.data = context; context-&gt;close.data = context; context-&gt;read.data = context; // context-&gt;fileSystem = shared_from_this(); uv_fs_open(context-&gt;loop, &amp;context-&gt;open, file.c_str(), 0, 0, on_open); #endif // _contexts.push_back(context); return context-&gt;promise; } } } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:44:09.470", "Id": "225155", "Score": "2", "Tags": [ "c++", "file-system", "asynchronous" ], "Title": "Implementing an efficient async FileSystem class based on libuv in C++" }
225155
<p>This is just an exercise. I know I should not implement encryption protocol myself. I know I should use Node's TLS package. I know I do not authenticate other side, but merely encrypting traffic.</p> <p>I have decent experience with NodeJS but not with buffers and streams. And that is where I'd like to here from you. I'd like to hear/read:</p> <ul> <li>How can I make this more modular, more elegant, more reusable, more flexible. Comments about my class <code>BufferFiller</code> are particularly welcomed.</li> <li>Any best practices when it comes to using buffers and streams to implement protocols in this asynchronous world? Any design patterns?</li> <li>How to improve performance if there is room for that.</li> </ul> <p>Server side:</p> <pre><code>const net = require('net'); crypto = require("crypto"); const algorithm = "aes-256-cbc"; const host = process.env.HOST || 'localhost'; const port = process.env.PORT || 6000; class BufferFiller { constructor(inputStream) { this.inputStream = inputStream; this.lastChunkOffset = -1; this.lastChunk = null; } fill(buffer) { let bufferFillLength = 0; if (this.lastChunk) { const copyLen = Math.min(buffer.length - bufferFillLength, this.lastChunk.length - this.lastChunkOffset); this.lastChunk.copy(buffer, bufferFillLength, this.lastChunkOffset, this.lastChunkOffset + copyLen); bufferFillLength += copyLen; this.lastChunkOffset += copyLen; } if (this.lastChunk &amp;&amp; this.lastChunkOffset === this.lastChunk.length) { this.lastChunkOffset = -1; this.lastChunk = null; } if (bufferFillLength === buffer.length) { return new Promise(resolve =&gt; resolve(this)); } return new Promise((resolve, reject) =&gt; { const onData = chunk =&gt; { let chunkOffset = 0; const copyLen = Math.min(buffer.length - bufferFillLength, chunk.length - chunkOffset); chunk.copy(buffer, bufferFillLength, chunkOffset, chunkOffset + copyLen); bufferFillLength += copyLen; chunkOffset += copyLen; if (chunkOffset &lt; chunk.length) { this.lastChunkOffset = chunkOffset; this.lastChunk = chunk; } if (bufferFillLength === buffer.length) { this.inputStream.removeListener('data', onData); this.inputStream.removeListener('error', onError); resolve(this); } }; const onError = err =&gt; { this.inputStream.removeListener('data', onData); this.inputStream.removeListener('error', onError); reject(err); }; this.inputStream.on('data', onData); this.inputStream.on('error', onError); }); } getRemainingBuffer() { if (this.lastChunk === null) { return Buffer.alloc(0); } const result = Buffer.alloc(this.lastChunk.length - this.lastChunkOffset); this.lastChunk.copy(result, 0, this.lastChunkOffset); return result; } }; function exchangeKeysAndPipeThroughDecipher(outputStream, inputStream, nextStream) { const iv = Buffer.alloc(16, 0); const alice = crypto.createDiffieHellmanGroup('modp14'); const alicePublicKey = alice.generateKeys(); const aliceGenerator = alice.getGenerator(); const alicePrime = alice.getPrime(); const buf = Buffer.allocUnsafe(4); buf.writeUInt32BE(aliceGenerator.length, 0); outputStream.write(buf); outputStream.write(aliceGenerator); outputStream.write(alicePrime); outputStream.write(alicePublicKey); const bobPublicKey = Buffer.alloc(256); new BufferFiller(inputStream) .fill(bobPublicKey) .then(filler =&gt; { const symKey = alice.computeSecret(bobPublicKey).slice(-32); const decipher = crypto.createDecipheriv(algorithm, symKey, iv); decipher.setAutoPadding(false); decipher.write(filler.getRemainingBuffer()); inputStream.pipe(decipher).pipe(nextStream); }); }; async function onClientConnected(sock) { exchangeKeysAndPipeThroughDecipher(sock, sock, process.stdout); }; // Create Server instance var server = net.createServer(onClientConnected); server.listen(port, host, function() { console.log('server listening on %j', server.address()); }); </code></pre> <p>Client side:</p> <pre><code>const net = require('net'); const crypto = require('crypto'); const algorithm = "aes-256-cbc"; const host = process.env.HOST || 'localhost'; const port = process.env.PORT || 6000; const client = new net.Socket(); class BufferFiller { constructor(inputStream) { this.inputStream = inputStream; this.lastChunkOffset = -1; this.lastChunk = null; } fill(buffer) { let bufferFillLength = 0; if (this.lastChunk) { const copyLen = Math.min(buffer.length - bufferFillLength, this.lastChunk.length - this.lastChunkOffset); this.lastChunk.copy(buffer, bufferFillLength, this.lastChunkOffset, this.lastChunkOffset + copyLen); bufferFillLength += copyLen; this.lastChunkOffset += copyLen; } if (this.lastChunk &amp;&amp; this.lastChunkOffset === this.lastChunk.length) { this.lastChunkOffset = -1; this.lastChunk = null; } if (bufferFillLength === buffer.length) { return new Promise(resolve =&gt; resolve(this)); } return new Promise((resolve, reject) =&gt; { const onData = chunk =&gt; { let chunkOffset = 0; const copyLen = Math.min(buffer.length - bufferFillLength, chunk.length - chunkOffset); chunk.copy(buffer, bufferFillLength, chunkOffset, chunkOffset + copyLen); bufferFillLength += copyLen; chunkOffset += copyLen; if (chunkOffset &lt; chunk.length) { this.lastChunkOffset = chunkOffset; this.lastChunk = chunk; } if (bufferFillLength === buffer.length) { this.inputStream.removeListener('data', onData); this.inputStream.removeListener('error', onError); resolve(this); } }; const onError = err =&gt; { this.inputStream.removeListener('data', onData); this.inputStream.removeListener('error', onError); reject(err); }; this.inputStream.on('data', onData); this.inputStream.on('error', onError); }); } getRemainingBuffer() { if (this.lastChunk === null) { return Buffer.alloc(0); } const result = Buffer.alloc(this.lastChunk.length - this.lastChunkOffset); this.lastChunk.copy(result, 0, this.lastChunkOffset); return result; } }; client.connect(port, host, function() { console.log('Client connected to: ' + host + ':' + port); const iv = Buffer.alloc(16, 0); const aliceGenLen = Buffer.allocUnsafe(4); let aliceGen; const alicePrime = Buffer.allocUnsafe(256); const alicePublicKey = Buffer.allocUnsafe(256); new BufferFiller(client) .fill(aliceGenLen) .then(filler =&gt; { const genLen = aliceGenLen.readUInt32BE(); aliceGen = Buffer.allocUnsafe(genLen); return filler.fill(aliceGen); }) .then(filler =&gt; filler.fill(alicePrime)) .then(filler =&gt; filler.fill(alicePublicKey)) .then(filler =&gt; { const bob = crypto.createDiffieHellman(alicePrime, aliceGen); const bobPublicKey = bob.generateKeys(); client.write(bobPublicKey); const symKey = bob.computeSecret(alicePublicKey); return symKey.slice(-32); }) .then(symKey =&gt; { const cipher = crypto.createCipheriv(algorithm, symKey, iv); cipher.setAutoPadding(true); process.stdin.pipe(cipher).pipe(client); }); }); client.on('close', function() { console.log('Client closed'); }); client.on('error', function(err) { console.error(err); }); </code></pre> <p>I find implementing protocols in asynchronous world particularly difficult, when you can control how much data you receive from underling buffers, nor when ('data' event triggers with what ever chunk size it wants and when ever it wants).</p> <p>I'm also stuck with Node v8.x, which supports async/await, but I didn't want to hide asynchronicity, on purpose.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T18:46:00.020", "Id": "225156", "Score": "1", "Tags": [ "javascript", "design-patterns", "node.js", "stream", "protocols" ], "Title": "Encrypted network protocol in NodeJS" }
225156
<p>I have two threads, one is the producer and other is consumer. My consumer is always late (due to some costly function call, simulated in below code using sleeps) so I have used ring buffer as I can afford to loose some events. </p> <p>I am looking to see if my locking looks alright and general c++ review comments. </p> <pre><code>#include &lt;iostream&gt; #include &lt;thread&gt; #include &lt;chrono&gt; #include &lt;vector&gt; #include &lt;atomic&gt; #include &lt;boost/circular_buffer.hpp&gt; #include &lt;condition_variable&gt; #include &lt;functional&gt; std::atomic&lt;bool&gt; mRunning; std::mutex m_mutex; std::condition_variable m_condVar; class VecBuf { private: std::vector&lt;int8_t&gt; vec; public: VecBuf() = default; VecBuf(std::vector&lt;int8_t&gt; v) { vec = v; } }; std::vector&lt;int8_t&gt; data{ 10, 20, 30 }; class Detacher { public: template&lt;typename Function, typename ... Args&gt; void createTask(Function &amp;&amp;func, Args&amp;&amp; ... args) { m_threads.emplace_back(std::forward&lt;Function&gt;(func), std::forward&lt;Args&gt;(args)...); } Detacher() = default; Detacher(const Detacher&amp;) = delete; Detacher &amp; operator=(const Detacher&amp;) = delete; Detacher(Detacher&amp;&amp;) = default; Detacher&amp; operator=(Detacher&amp;&amp;) = default; ~Detacher() { for (auto&amp; thread : m_threads) { thread.join(); } } private: std::vector&lt;std::thread&gt; m_threads; }; void foo_1(boost::circular_buffer&lt;VecBuf&gt; *cb) { while (mRunning) { std::unique_lock&lt;std::mutex&gt; mlock(m_mutex); m_condVar.wait(mlock, [=]() { return !cb-&gt;empty(); }); VecBuf local_data(cb-&gt;front()); cb-&gt;pop_front(); mlock.unlock(); if (!mRunning) { break; } //simulate time consuming function call and consume local_data here std::this_thread::sleep_for(std::chrono::milliseconds(16)); } while (cb-&gt;size()) { VecBuf local_data(cb-&gt;front()); cb-&gt;pop_front(); if (!mRunning) { break; } } } void foo_2(boost::circular_buffer&lt;VecBuf&gt; *cb) { while (mRunning) { std::unique_lock&lt;std::mutex&gt; mlock(m_mutex); while (cb-&gt;full()) { mlock.unlock(); /* can we do better than this? */ std::this_thread::sleep_for(std::chrono::milliseconds(100)); mlock.lock(); } cb-&gt;push_back(VecBuf(data)); m_condVar.notify_one(); } } int main() { mRunning = true; boost::circular_buffer&lt;VecBuf&gt; cb(100); Detacher thread_1; thread_1.createTask(foo_1, &amp;cb); Detacher thread_2; thread_2.createTask(foo_2, &amp;cb); std::this_thread::sleep_for(std::chrono::milliseconds(20000)); mRunning = false; } </code></pre>
[]
[ { "body": "<blockquote>\n<pre><code> /* can we do better than this? */\n</code></pre>\n</blockquote>\n\n<p>In a circular buffer context, the standard way to avoid busy waiting is to have two semaphores. First to block a producer when a buffer is full, and second to block a consumer when the buffer is empty. Once a process passes its semaphore, and does its job, it should signal the peer.</p>\n\n<hr>\n\n<p>The circular buffer is good when the consumer is only sometimes late <em>and</em> you cannot afford loosing data. In your situation it looks like a wrong solution: the producer becomes throttled by the rate of consumption, and the consumer is a presented with the stale data.</p>\n\n<p>A typical answer is to let the producer run at full speed, and triple-buffer the production (at least, it guarantees that the consumer would get the most recently produced data). Please forgive the shameless <a href=\"https://codereview.stackexchange.com/questions/163810/lock-free-zero-copy-triple-buffer\">self promotion</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T05:46:07.593", "Id": "437082", "Score": "0", "body": "thanks for the review comment and the link. However, in my case my consumer only blocks some time. I think it still makes sense to use semaphores instead of my current solution using condition variable + lock." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T05:47:48.607", "Id": "437083", "Score": "0", "body": "@nomanpouigt \"some time\" is quite different from \"always late\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T05:53:04.570", "Id": "437084", "Score": "0", "body": "sorry, I mean the ring buffer size is chosen such a way that it is able to acomodate the delay. Wondering in c++ there are no semaphores and it is implemented using mutexes and condition variable so if it makes sense to use semaphores." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T06:17:12.863", "Id": "437086", "Score": "0", "body": "Can you also please elaborate your solution of tripple buffer and how would it apply in my case? Do you mean don't do any locking in producer side and let it run and producer buffer needs to be tripple-buffered so that consumer can get recent data in case of overruns?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T22:56:19.420", "Id": "225162", "ParentId": "225158", "Score": "1" } } ]
{ "AcceptedAnswerId": "225162", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T19:53:06.247", "Id": "225158", "Score": "3", "Tags": [ "c++", "c++11", "circular-list", "boost", "producer-consumer" ], "Title": "Producer consumer with threads and using boost ring buffer" }
225158
<p>I have started studying algorithms using the classic CLRS book and decided to hone my C skills at the same time.</p> <p>I wrote this function implementing insertion sort in C. I have tested it and verified that it works correctly. I would like to know whether it is readable and follows best practices.</p> <p>Some points I'd like to receive feedback on:</p> <p>1) Are the variable names well chosen? I have the impression that the convention in C is to use shorter names than in other languages and chose parameter names like arr and n accordingly. Would names like array and array_size have been better instead?</p> <p>2) Instead of an array, the calling code could pass a null pointer to the function. I handle that using an int return value. Is that the best response?</p> <p>3) Are the comments explaining the inner loop necessary?</p> <pre><code>#include &lt;stddef.h&gt; #define INVALID_PARAMETER 1 /* Sorts an array of ints in-place using insertion sort. * Returns INVALID_PARAMETER if a null pointer is passed * as argument and 0 otherwise. */ int insertion_sort(int arr[], size_t n) { if (arr == NULL) { return INVALID_PARAMETER; } for(size_t i = 1; i &lt; n; i++) { int key = arr[i]; /* Look through the array backwards until finding where key must be * inserted. If the element we are looking at now is bigger than key, * it is displaced forward. Stop when an element smaller than key is * found or the start of the array is reached. */ size_t j; for(j = i; j &gt; 0 &amp;&amp; arr[j - 1] &gt; key; j--) { arr[j] = arr[j - 1]; } /* After the loop, j is either 0, what means that no element smaller * than key was found and it must be the first element in the sorted * array, or j is the position after the first element found that was * smaller than key and so it is where key must be inserted. */ arr[j] = key; } return 0; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T01:16:19.700", "Id": "437070", "Score": "1", "body": "Welcome to code review, it might be better if you included the code that tests the function as well. That would provide a concrete programming example." } ]
[ { "body": "<ul>\n<li><p>Using a symbolic constant (<code>INVALID_PARAMETER</code>) along with a literal <code>0</code> as a return value is not the cleanest solution. As a side note, a return value signifying an error is traditionally negative.</p></li>\n<li><p>The best kept secret of insertion sort is the fact that the <code>j &gt; 0 &amp;&amp; arr[j - 1] &gt; key</code> termination condition of an inner loop is suboptimal. It tests two conditions in every iteration. It is possible to get away with only one test: check wether the <code>key &lt; arr[0]</code> first. Consider an inner loop along the lines of key </p>\n\n<pre><code> int j;\n if (key &lt; arr[0]) {\n // Now key shall for sure become leftmost. Don't bother testing values.\n for (j = i; j &gt; 0; j--) {\n arr[j] = arr[j - 1];\n }\n } else {\n // Now arr[0] is a natural sentinel. Don't bother testing indices.\n for (j = i; key &lt; arr[j - 1]; j--)\n arr[j] = arr[j - 1];\n }\n }\n arr[j] = key;\n</code></pre></li>\n<li><p>Otherwise, LGTM.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T03:27:54.327", "Id": "225172", "ParentId": "225165", "Score": "2" } } ]
{ "AcceptedAnswerId": "225172", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T00:38:13.533", "Id": "225165", "Score": "4", "Tags": [ "c", "sorting", "insertion-sort" ], "Title": "Insertion Sort in C" }
225165
<p>My code compares 2 images of any shape/dimension and ranks them in order of similarity. It starts with reading from a CSV file with columns image1, image2 which contain absolute paths and then outputting to a CSV file which contain columns image1, image2, similarity, time_elapsed</p> <p>I'm more concerned with the <strong>formatting suggestions</strong> or simplifications to make the code <strong>more easy to read</strong> </p> <pre><code>import cv2 import numpy as np import csv import time #read from CSV file def read_data(): print("starting to read data") with open('input_test_data.csv') as input_data: print("opened data file") global line_count csv_reader = csv.reader(input_data, delimiter=',') set_of_images=[row for idx, row in enumerate(csv_reader) if idx == line_count] print(set_of_images) original_image = set_of_images[0][0] image_to_compare = set_of_images[0][1] line_count += 1 return [original_image, image_to_compare] # wrote column titles for result CSV file def write_header(): global line_count with open('result_data.csv', mode='w') as result: result_writer = csv.writer(result, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) result_writer.writerow(['image1', 'image2', 'similarity_ratio', 'time_elapsed']) print('wrote result header') line_count += 1 # count total number of entries in CSV file def count_images(): with open('input_test_data.csv') as input_data: print("counting number of rows in CSV file") csv_reader = csv.reader(input_data, delimiter=',') return sum(1 for row in csv_reader) # reading images def read_images(original_img: str, image_to_compare: str): original_image = cv2.imread(original_img) compared_image = cv2.imread(image_to_compare) print("Read images") return [original_image, compared_image] # preliminary check of RGB values are same def check_identical(original_image , compared_image , start_time: float, image_names): # if images are the same shape and size - could be identical if original_image.shape == compared_image.shape: print("Images have the same size and channel") difference = cv2.subtract(original_image, compared_image) # subtract RGB values between images to see difference between image organization b,g, r = cv2.split(difference) # if RGB value difference is 0 - same image if cv2.countNonZero(b) == 0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) == 0: publish_results(image_names[0], image_names[1], 0.0, start_time) print("The images are completely Equal") return True else: print("The images are NOT completely Equal") return False # if images are not identical: # use OpenCV's SIFT Algorithm to find key points and features between images def generate_keypoints(original_image: str, compared_image: str): sift = cv2.xfeatures2d.SIFT_create() key_point_image1, descriptor_image1 = sift.detectAndCompute(original_image, None) key_point_image2, descriptor_image2 = sift.detectAndCompute(compared_image, None) print("Generated keypoints for both images") return [key_point_image1, descriptor_image1, key_point_image2, descriptor_image2] # FLANN - Fast Library for Approximate Neighbors # uses Euclidean distance between common key points to judge similarity def compare_images(key_point_image1, descriptor_image1, key_point_image2, descriptor_image2 ): index_params = dict(algorithm=0, trees=5) search_params = dict() flann = cv2.FlannBasedMatcher(index_params, search_params) matches = flann.knnMatch(descriptor_image1, descriptor_image2, k=2) print("found common points in images") return matches # SIFT algorithm has high recall, but low precision # so a threshold ratio needs to be set to filter inacurate results def filter_results(matches: enumerate): good_points = 0 ratio = 0.6 # approximated through trial and error print("Matches:" + str(len(matches))) for m, n in matches: if m.distance &lt; ratio*n.distance: good_points += 1 print("Good Matches: " + str(good_points)) return [good_points, len(matches)] # Generate Similarity Score def generate_similarity_score(correct_matches: int, total_matches: int ): return 1.0 - correct_matches/total_matches # as defined in requirements, values close to 0 is most similar, so more correct matches mean similar pictures # Publish to CSV def publish_results(original_img: str, image_to_compare: str, similarity_ratio , start_time): print("writing to CSV file...") with open('result_data.csv', mode='a', newline='') as result: result_writer = csv.writer(result, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) result_writer.writerow([original_img, image_to_compare, str(similarity_ratio), str(round(time.time() - start_time, 2))] ) print("Write successful") # Main Function # reading data from CSV print("starting program") line_count = 0 # find number of items in CSV file to compare total_images_to_compare = count_images() # prepare column titles for result CSV file write_header() for img in range(line_count, total_images_to_compare): # start recording execution time start_time = time.time() # read set of images image_names = read_data() # read original image and image to compare into memory images = read_images(image_names[0], image_names[1]) # determine if identical images if (check_identical(images[0], images[1], start_time, image_names)): print("continue") # continue print("images NOT EQUAL - starting SIFT") # if images are not equal - start using SIFT to generate keypoints and features of both images to measure similarity keypoints_descriptors = generate_keypoints(images[0], images[1]) # Attempt at finding common points in both images matches = compare_images(keypoints_descriptors[0], keypoints_descriptors[1], keypoints_descriptors[2], keypoints_descriptors[3] ) print("filtering results now...") # filter out outliers and mismatches acurate_points = filter_results(matches) print("generating a score...") # find a ratio for closely matched images are score = generate_similarity_score(acurate_points[0], acurate_points[1]) # write data to CSV file publish_results(image_names[0], image_names[1], score, start_time) # increment next set of images to be compared img += 1 </code></pre> <p>This is the input_test_data.csv:</p> <pre><code>image1 image2 D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\black_and_white.jpg D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\blue_filter.jpg D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\blurred.jpg D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\cartoonized.jpg D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\exposured.jpg D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\george-washington-bridge.jpg D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\old_photo.jpg D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\overlay.jpg D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\resized.jpg D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\rotated.jpg D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\sharpened.jpg D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\sunburst.jpg D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\textured.jpg </code></pre> <p>result_data.csv:</p> <pre><code>image1 image2 similarity_ratio time_elapsed D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\black_and_white.jpg 0.308852067 3.55 D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\blue_filter.jpg 0.13136289 3.45 D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\blurred.jpg 0.944469324 1.46 D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\cartoonized.jpg 0.601731602 3.17 D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\exposured.jpg 0.736229288 2.91 D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\george-washington-bridge.jpg 1 6.25 D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\old_photo.jpg 0.637557844 4.07 D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\original_golden_bridge.jpg 0 0.14 D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\duplicate.jpg 0 3.55 D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\overlay.jpg 0.824600687 2.11 D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\resized.jpg 0.907598149 1.2 D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\rotated.jpg 0.150619495 3.51 D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\sharpened.jpg 0.522316764 5.07 D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\sunburst.jpg 0.922675026 8.92 D:\Programming\test\images\original_golden_bridge.jpg D:\Programming\test\images\textured.jpg 0.494103598 4.84 </code></pre> <p>I apologize for the formatting for the results.csv</p> <p>I also intend to replace all print statements to logging statements to make it easier for future developers and more maintainable while being professional</p>
[]
[ { "body": "<p><strong>Disclaimer:</strong> The code below is (partly) untested, so there can be some rough edges that need polishing.</p>\n\n<hr>\n\n<h2>Style</h2>\n\n<p>First, some style-related notes. Python has an official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide</a>, often just called PEP8. The part most relevant to your code IMHO is <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">documentation strings</a>. In essence, you should follow the official recommendation to put your function documentation in <code>\"\"\"triple quotes\"\"\"</code> inside the function body. An example adapted from your code:</p>\n\n<pre><code>def compare_images(key_point_image1, descriptor_image1,\n key_point_image2, descriptor_image2):\n \"\"\"\n uses Euclidean distance between common key points to judge similarity\n in FLANN (Fast Library for Approximate Neighbors) matching\n \"\"\"\n ...\n</code></pre>\n\n<p>You often use an explicit list to return multiple values from a function. This is unusual and likely unnecessary. Most often there is no explicit type when returning multiple values, e.g.</p>\n\n<pre><code>def swap(a, b):\n return b, a\n</code></pre>\n\n<p>Under the hood, Python returns a tuple from the function as can be seen if looking at <code>type(swap(1, 2))</code> which will happily print <code>tuple</code> in an interactive Python interpreter.</p>\n\n<h2>Avoid global variables</h2>\n\n<p>You should try avoid global variables whenever possible. And in your case the global variable is absolutely not necessary. We will cover that in a second.</p>\n\n<h2><code>read_data</code></h2>\n\n<p><code>read_data</code> is written wasteful. You always read the full file just to get a single line. The usual approach would be to read the file line by line and then process it accordingly. Or read the file as a whole and process its contents line by line. This would also allow you to get rid of <code>line_count</code> to keep track of which line you need to look at next. The name of the file to read should probably also be a parameter and not hardcoded. The new version of <code>read_data</code> might look like:</p>\n\n<pre><code>def read_data(input_file):\n \"\"\"read from CSV file\"\"\"\n with open(input_file) as input_data:\n csv_reader = csv.reader(input_data, delimiter=',')\n return [row for row in csv_reader]\n</code></pre>\n\n<p>This implementation uses a list comprehension to read all lines of the csv file into memory. With this, <code>count_images()</code> could simply be replaced by </p>\n\n<pre><code>images_list = read_data(...)\ntotal_images_to_compare = len(images_list)\n</code></pre>\n\n<p>You could also use a <a href=\"https://www.python.org/dev/peps/pep-0289/\" rel=\"nofollow noreferrer\">generator expression</a> which is basically a list comprehension, but not all the elements have to be kept in memory at once. Note that with a generator expression the above would not work because <code>len(...)</code> is not defined for generator expressions.</p>\n\n<p>Either version could be used as follows in the main part of the script:</p>\n\n<pre><code>for image_names in images_list:\n # read original image and image to compare into memory\n images = read_images(image_names[0], image_names[1])\n\n ...\n</code></pre>\n\n<h2><code>check_identical</code></h2>\n\n<p>Next up on the list is <code>check_identical</code>. IMHO the implementation here is also a lot more complicated than it has to be. numpy can greatly help to simplifiy the code here:</p>\n\n<pre><code>def check_identical(original_image, compared_image):\n \"\"\"preliminary check of RGB values are same\"\"\"\n if original_image.shape == compared_image.shape:\n # if images are the same shape and size - could be identical\n return np.count_nonzero(original_image - compared_image) == 0\n\n return False\n</code></pre>\n\n<p>In its core, the function still does what you did, but for the whole image instead of separately for each color channel. The major difference here is that <code>start_time</code> and <code>image_names</code> have vanished from the parameter list, since there is reason why <code>check_indentical</code> should have to care about writing anything to an output file.</p>\n\n<h2>tuple unpacking</h2>\n\n<p>There are several parts in your code where you do <code>foobar(images[0], images[1])</code>. If <code>images</code> has the same number of elements as expected by <code>foobar(...)</code>, you can simply to <code>foobar(*images)</code>. This is called <a href=\"https://stackoverflow.com/q/2238355/5682996\">tuple unpacking</a>, but also works for other sequences like <code>list</code>s.</p>\n\n<p>Also, sometimes its more understandable to assign multiple return values to named variables to better see what gets passed around, e.g.</p>\n\n<pre><code>correct_matches, total_matches = filter_results(matches)\n\nscore = generate_similarity_score(correct_matches, total_matches)\n</code></pre>\n\n<p>Sidenote: it would be also possible to do:</p>\n\n<pre><code>score = generate_similarity_score(*filter_results(matches))\n</code></pre>\n\n<h2>Hard-coded values</h2>\n\n<p>There are also quite a lot of hard-coded values in your code. Some examples:</p>\n\n<pre><code>'input_test_data.csv'\n'result_data.csv'\nindex_params = dict(algorithm=0, trees=5)\nmatches = flann.knnMatch(..., k=2)\nratio = 0.6 # approximated through trial and error\n</code></pre>\n\n<p>IMHO, they all should be function parameters that can be changed without touching the actual code. You can also assign them default values that match their current ones, so nothing in your program has to be changed. At the current state if you ever want to change some of these values, you would have to jump back to where the function is implemented and change it there directly. Though that might sound feasible for a few values, the trouble really starts if you ever get the idea to try several values in a single run (maybe in an effort to optimize a parameter).</p>\n\n<h2>The <code>main</code> function</h2>\n\n<p>Although your code boldly states <code># Main Function</code> at the end, there is not an actual <code>main</code> function to be found here. But there definitely should be one! And since we are at it, it's also good practice to make sure the <code>main</code> function of the script is only called if the file is actually used as a script, and not imported into some other code. Enter the <a href=\"https://docs.python.org/3/library/__main__.html#module-__main__\" rel=\"nofollow noreferrer\">top-level script environment</a>!</p>\n\n<pre><code># ... all the import and other functions here ...\n\ndef main():\n \"\"\"Read a list of image pairs from disk and check their similarity\"\"\"\n ...\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/a/419185/5682996\">this SO post</a> for an extended explanation about <code>__name__</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T08:44:56.463", "Id": "437268", "Score": "0", "body": "Thanks Alex! Appreciate the review!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T22:52:21.603", "Id": "225223", "ParentId": "225175", "Score": "1" } } ]
{ "AcceptedAnswerId": "225223", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T04:16:43.417", "Id": "225175", "Score": "2", "Tags": [ "python", "performance", "image", "formatting", "opencv" ], "Title": "Image Processing - Comparing 2 images and Ranking Similarity" }
225175
<p>Index &amp; Sorting</p> <p>Index</p> <p>• Counting: when the index, or the position, is dependent on the item. Count from one. (Zero-based index is mathematically wrong.)</p> <p>• Grid: when the index, or the position, is independent on the item. (e.g. JavaScript array)</p> <p>Counting arrays are used in bubble sort, merge sort, quick sort, etc. Because of the nature of the index, sorting techniques using counting arrays require comparing the items and moving the items around.</p> <p>Grid arrays are better suited for sorting.</p> <p>Grid Sort</p> <p>• Assigning the number (or other value associated with the number, such as name) to the corresponding index’s item</p> <p>• Filtering out the undefined for print, iterate, length, etc.</p> <p>• Assigning is sorting</p> <p>• No comparing. No swapping. No moving around items.</p> <p>• No need for indexOf()</p> <p>• Stable</p> <p>• Limitations : whole numbers only, size of an array</p> <p>• An example using JavaScript</p> <p>• <a href="https://code.sololearn.com/WWuuXR9rO45U/?ref=app" rel="noreferrer">https://code.sololearn.com/WWuuXR9rO45U/?ref=app</a></p> <pre><code> var test = [57, 285, 0, 854, 0, 27, 5, 5, 2885, 497, 57, 16, 803, 653, 62, 905, 975, 367, 147, 99, 58, 207643, 73, 83, 95, 24, 3, 1986, 47, 954, 1, 99, 954, 36, 67, 2, 753, 97, 3689, 79864, 5788, 479, 9865, 8900, 73, 753, 588, 19537, 489964, 30674, 578, 55, 99999, 578, 1000000, 58, 279, 3, 75, 975, 46, 785, 6789, 164, 5538, 744, 85, 2, 579, 753, 5538, 975, 158, 689, 379, 965, 57, 803, 84, 653, 85, 73, 864, 8643, 9047, 864, 783, 7, 4, 932, 5, 80, 97, 79, 849, 7, 3, 5, 10, 0]; document.write(test+”&lt;br /&gt;”); document.write(“Count: “+test.length+”&lt;br /&gt;”); document.write(“&lt;br /&gt;”); var test_original = []; var x = 0; while (x &lt; test.length){ if (test_original[test[x]] === undefined){ test_original[test[x]] = []; test_original[test[x]][0] = test[x]; } else{ test_original[test[x]].push(test[x]); } x = x + 1; } var test_defined = []; var defined_from = 0; var defined_to = test_original.length; var x = defined_from; while (x &lt; defined_to){ if (test_original[x] !== undefined){ test_defined.push(x); } x = x + 1; } var definedIndex = 0; while (definedIndex &lt; test_defined.length){ document.write(definedIndex + 1); document.write(“. “); document.write(test_defined[definedIndex]); document.write(“: “); document.write(test_original[test_defined[definedIndex]]); document.write(“&lt;br /&gt;”); definedIndex = definedIndex + 1; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T06:11:49.410", "Id": "437085", "Score": "2", "body": "Welcome to Code Review! What would this look like in a function? Your naming is a bit odd. First you declare a `test` variable with test input, then you copy it into a variable called `test_original` in an odd manner. `test_original` is not the original data, so where does the name come from?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T06:18:09.050", "Id": "437087", "Score": "0", "body": "I meant to differentiate it from test_defined. Grid Sort is like sorting into mailboxes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T06:22:14.853", "Id": "437088", "Score": "0", "body": "test_original is the sorted form. test_defined is to print." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T10:28:02.203", "Id": "437126", "Score": "2", "body": "I'd really like to see this code inside of a function with defined inputs and outputs. E.g.: Input some array, output the sorted array (or alternatively, the indices of how the input is traversed in sorted order). I challenge the statement _Grid arrays are better suited for sorting_: The algorithm uses additional memory proportional to the input array, since each value is copied to `test_original`. This can be a show stopper for large inputs. You mention \"moving items around\" as a problem of common sorting algorithms, however, this can be circumvented by sorting indices instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T19:24:47.113", "Id": "437386", "Score": "0", "body": "Instead of copying test to test_original, how about test_original holding the indices of test?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T19:48:09.817", "Id": "437396", "Score": "0", "body": "What I called counting is when the item is removed, the index or position is also removed. What I called grid is when the index or position is not removed when the item is removed. So, counting is like relative sorting. It only means the item is greater than before and smaller than after. Some number can squeeze in. Whereas grid is like absolute sorting. Once assigned to the corresponding position, it is not affected by other numbers to be sorted. I’m guessing the time graph just for sorting (not filtering out undefined) will be linear (how many numbers, time it takes to assign)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T19:49:37.417", "Id": "437397", "Score": "0", "body": "Also, grid sort is not affected by the order, such as reverse order, right order, or all same number." } ]
[ { "body": "<h2>Zero based indexing</h2>\n<blockquote>\n<p>Counting: when the index, or the position, is dependent on the item. Count from one. (Zero-based index is mathematically wrong.)</p>\n</blockquote>\n<p>I will disagree. The index does not represent a count but rather it is a position. When we measure something we start at 0. For example a length of 5 units. Unit 0 the 1st unit is at 0 to &lt; 1, and the last unit, the 5th is at 4 to &lt; 5. The set of 5 units does not contain the unit 5.</p>\n<p>It is not mathematically wrong to use zero based indexing, what is wrong is using the index to represent a count.</p>\n<h2>Array V Grid AKA hash table</h2>\n<blockquote>\n<p>Grid: when the index, or the position, is independent on the item. (e.g. JavaScript array)</p>\n</blockquote>\n<p>I think you understanding of how arrays work is leading to some bad assumptions.</p>\n<h3>Arrays</h3>\n<p>Computers use RAM that is a continuous array of addresses. We use arrays because they are very fast when we need to get or set a item at an index.</p>\n<p>To locate an item we get the RAM address of the array and add the index multiplied by the size of each item (JS arrays hold references so all array items are the same size) . In one addition and multiplication (a shift if item size is a power of two) we have the memory address of the data we want.</p>\n<p>Almost all modern CPUs have special instructions (indexed addressing) to speed up array use.</p>\n<h3>Hash table</h3>\n<p>A grid is a little more complicated.</p>\n<p>As the index can be any value we can not just offset a RAM address to find an item. We need to know where the item associated with an index is in RAM. That means that another array is needed to hold all the indexes and RAM addresses.</p>\n<p>So if you want the item of grid index 10000000, we need the address of the index 10000000 which must be found by searching the array of indexes one at a time. Then we can get the RAM offset of the item we are after.</p>\n<p>However computers have been around for a long time and some cleaver people have come up with ways to make &quot;grids&quot; somewhat faster. In javascript we call them <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\">Map</a>\nin computer science we use the term <a href=\"https://en.wikipedia.org/wiki/Hash_table\" rel=\"nofollow noreferrer\">hash table</a>.</p>\n<p>Hash tables avoid the need to search for the index by applying a hash function to the index (key). This provides an offset that we can use to get the RAM address of the data we are after.</p>\n<p>Still slower than an array as the hash function needs to be applied each time we index into the table, its a lot faster than searching all indexes each time we want an item.</p>\n<h3>When JS arrays are not arrays.</h3>\n<p>On a side note. JavaScript arrays come in two flavors</p>\n<ol>\n<li>Dense arrays, each item is held one after the other in a continuous section of memory.</li>\n<li>Sparse arrays. Sparse arrays look from the code perspective like dense array, but under the hood sparse array are actually hash tables.</li>\n</ol>\n<p>A dense array is converted to a sparse array if you add an item above the array length. Different engines have different rules but generally its a bad idea to add items to an array at random indexes (as you do in your grid sort)</p>\n<h2>Review</h2>\n<p>I am not going to review your code as I think it is moot if you consider the above information.</p>\n<p>I will say, you saw some institutionalized flaws and you created a better solution (sadly your assumptions were off). You demonstrate an initiative and a healthy skepticism of the status quo.</p>\n<p>Most people will just keep at the same old same old and nothing great ever comes from that.</p>\n<p>Keep at it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T20:06:20.413", "Id": "437399", "Score": "0", "body": "Counting is done from 1 because 0+0=0, 0-0=0. Python has an error. String method Count() does not count overlapping motifs. One of the simplest way was to check for the motif and delete up to the first character. When adding the indexes to get the original indexes, +1 had to be done because 0+0=0. If arrays, lists, etc. where the index is removed when the item is removed, it is counting. Counting should be done from 1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T22:55:50.183", "Id": "437443", "Score": "0", "body": "In length, 0 is an imaginary line where the length begins behind. The first piece of the length is 0 <= 1. 0 is not a part of the length." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T23:43:08.060", "Id": "437446", "Score": "0", "body": "@JuliaKim How old do you turn on your first birthday, or how far have you run at the start of a race. The first piece if 0 to < 1 not <= 1. The first is everything before the second and the second starts at 1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T03:57:12.293", "Id": "437633", "Score": "0", "body": "@JuliaKim regarding 1-based collections, I can tell you from experience with Lua that they are great for some things and not so great for others. You'll almost never have to worry about fencepost errors with them or things like that, but they're more awkward for things like representing a 1D array as a 2D grid, or things involving modulo operator, where you always end up subtracting 1. There are pros and cons for each; some languages even have facilities for dealing with both (Prolog's nth0 and nth1)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T17:29:10.700", "Id": "437930", "Score": "0", "body": "I used both counting type and grid type. What I call counting and grid types are based on the relationship between index and item. If the index is removed when the item is removed, the index is dependent on the item. It is counting. If the index is not removed when the item is removed, the index is independent of the item. It is a grid. Both are needed for different uses." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T17:43:10.717", "Id": "437931", "Score": "0", "body": "It isn’t about what number based index. Any number would work as long as subtracting and adding because they are all counting type. It should start from 1 because it is counting, not because 1-based index. To make a grid using counting type, ‘initialize’ with 0 to secure positions. But holding a value of 0 may not be equal to not holding any value. In JavaScript, initialized & undefined. Also, grid type doesn’t matter where it begins. I would like to see one begin from negative index. Why not make a grid using grid type?" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T14:44:53.373", "Id": "225199", "ParentId": "225178", "Score": "5" } }, { "body": "<p>First off, what @Blindman67 said.</p>\n\n<p>However, if you were to use this approach in production code, there are a few things to consider:</p>\n\n<ul>\n<li>You probably want to create a class/function with a functions like <code>add</code></li>\n<li><p>I see a few issues with your add code:</p>\n\n<pre><code>if (test_original[test[x]] === undefined){\n test_original[test[x]] = [];\n test_original[test[x]][0] = test[x];\n}\nelse{\n test_original[test[x]].push(test[x]);\n}\n</code></pre>\n\n<ul>\n<li>Accessing <code>test[x]</code> is slower than assigning it to a temp variable, and use that temp variable</li>\n<li>Even accessing several times <code>test_original[test[x]</code> is slow, you should reduce that to a maximum as well</li>\n<li><p>You can assign an array with 1 element like this:</p>\n\n<pre><code>test_original[test[x]] = [test[x]];\n</code></pre></li>\n</ul></li>\n<li>JavaScript is all about lowerCamelCase, so <code>test_original</code> should be <code>testOriginal</code>, and really I think &lt;adjective&gt;&lt;noun&gt; is better than &lt;noun&gt;&lt;adjective&gt;, so <code>originalTest</code> would be even better</li>\n<li>The Spartan naming convention has a place in JavaScript, but I would have gone with <code>i</code>(nteger) over <code>x</code></li>\n<li>Your looping over arrays is not idiomatic, I would go for <code>for(;;)</code> loops or use the <code>forEach</code> method</li>\n</ul>\n\n<p>Also, just a thought, but in your output you have </p>\n\n<ol start=\"20\">\n<li>73: 73,73,73</li>\n<li>75: 75</li>\n<li>79: 79</li>\n<li>80: 80</li>\n</ol>\n\n<p>You could just store the counts in the array, instead of arrays</p>\n\n<p><code>test_original[73]</code> would then contain <code>3</code> instead of <code>[73,73,73]</code> which saves space and is faster</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T16:01:17.207", "Id": "437574", "Score": "0", "body": "For the statement: \"_JavaScript is all about lowerCamelCase_\" should we call that _idiomatic_ Javascript? And for the statement \"_The Spartan naming convention has a in JavaScript,_\" should there be a word or something else between _a_ and _in_?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T16:10:29.693", "Id": "437578", "Score": "0", "body": "Re: word missing: yep, fixed. Re: lowerCamelCase, no, JavaScript is lowerCamelCase, period." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T18:58:36.677", "Id": "225212", "ParentId": "225178", "Score": "1" } }, { "body": "<p>There's another answer here with a great assessment of your solution. The upshot of that answer (and this one) is that you'd be better off doing a <code>test.sort()</code> and calling it a day.</p>\n\n<p>Even though you should probably consider scrapping this solution, as explained in the other answer, a few things here may be worth commenting on anyway.</p>\n\n<p>Overall, the style of your code looks about right for JavaScript written 5 to 10 years ago, but feels a bit archaic by modern standards.</p>\n\n<p>Let's look at the last bit first:</p>\n\n<pre><code>var test_defined = [];\nvar defined_from = 0;\nvar defined_to = test_original.length;\nvar x = defined_from;\nwhile (x &lt; defined_to){\n if (test_original[x] !== undefined){\n test_defined.push(x);\n }\n x = x + 1;\n}\n</code></pre>\n\n<p>Unless you want to target ancient browsers, you should get rid of function-scoped <code>var</code> and go for block-scoped <code>let</code> or <code>const</code> instead. Most languages use block scoping, and the function-scoped <code>var</code> has been an infamous source of confusion and bizarre workarounds in JavaScript.</p>\n\n<p>Also, there are lots of useful tools in the <code>Array</code> toolbox these days, and there's usually something suitable for small jobs like this. But let's back up for a second: there's an issue here; this code leaves our sorted array in a weird state, with nested elements. I'd expect a <code>gridSort</code> function to do something similar to <code>Array.prototype.sort</code>, returning an array of the same length, and with the same elements (in a different order). In other words, the resulting array should be <em>flattened</em> -- and there is an array method called <code>flat</code> to do just that. Incidentally, it will also condense the array.</p>\n\n<p>So that entire block of code could be replaced with this:</p>\n\n<pre><code>let test_defined = test_original.flat()\n</code></pre>\n\n<p>Now for the first bit of code:</p>\n\n<pre><code>var test_original = [];\nvar x = 0;\nwhile (x &lt; test.length){\n if (test_original[test[x]] === undefined){\n test_original[test[x]] = [];\n test_original[test[x]][0] = test[x];\n }\n else{\n test_original[test[x]].push(test[x]);\n }\n x = x + 1;\n}\n</code></pre>\n\n<p>This looks to me like a job for <code>reduce</code>. You could replace these 12 lines of code with 2:</p>\n\n<pre><code>var test_original = test.reduce((a, v) =&gt;\n (a[v] ? a[v].push(v) : a[v] = [v], a), [])\n</code></pre>\n\n<p>Someone might argue that this looks like a subversion of <code>reduce</code>, or an abuse of obscure language features, or that it's less readable -- and they might be right. But, you could use <code>forEach</code> instead, if you're not worried about impure callbacks, or give your variables more descriptive names, or scribble a few mustaches on it, or anything else that floats your boat. This is just an example.</p>\n\n<p>That could leave our final <code>gridSort</code> function looking something like this:</p>\n\n<pre><code>const gridSort = a =&gt;\n a.reduce((a, v) =&gt; (a[v] ? a[v].push(v) : a[v] = [v], a), []).flat()\n</code></pre>\n\n<p>Not the most readable thing in the world, to be sure... but even so, I'd bet most people would grok these 2 lines more quickly than the original 20+ lines (and this leaves you ~20 new lines to comment in excruciating detail before it adds any extra bloat to your source file).</p>\n\n<p>All that said, the most useful tool in the Array toolbox for this situation is <code>Array.prototype.sort</code>, and you should probably just use that instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T19:13:47.187", "Id": "225213", "ParentId": "225178", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T05:36:48.080", "Id": "225178", "Score": "5", "Tags": [ "javascript", "sorting" ], "Title": "I created a sorting algorithm, called Grid Sort" }
225178
<p>I want to compare the performance difference between using <code>byte[]</code> and <code>ByteBuffer</code> in Java, which approach I should use in my production code. I wrote the following Java sandbox code:</p> <pre><code>public native int MD_GetHsmInfo(int hsmIndex, int infoType, byte[] value); public native int MD_TestByteBuffer(int hsmIndex, int infoType, ByteBuffer buf); //inside main() byte[] arr = new byte[64]; h.MD_GetHsmInfo(2, 0, arr); System.out.println("&gt;" + new String(arr) + "&lt;"); ByteBuffer buf = ByteBuffer.allocateDirect(64); h.MD_TestByteBuffer(2, 1, buf); System.out.println("&gt;" + StandardCharsets.UTF_8.decode(buf).toString() + "&lt;"); </code></pre> <p>And then I have my C code - this is the one I need help with:</p> <pre><code>JNIEXPORT jint JNICALL Java_com_sprint_jni_JNISandbox_MD_1GetHsmInfo (JNIEnv *env, jobject obj, jint hsmIndex, jint infoType, jbyteArray array) { //printf("This is MD_GetHsmInfo()\n"); jboolean isCopy; jsize len = (*env)-&gt;GetArrayLength(env, array); jbyte* bp = (*env)-&gt;GetByteArrayElements(env, array, &amp;isCopy); if (!bp) { // exception handling here return 0; } jint ret = MD_GetHsmInfo(hsmIndex, infoType, bp, len); int mode = 0; // if error code is returned then do not save changes if(ret != 0) { mode = JNI_ABORT; } (*env)-&gt;ReleaseByteArrayElements(env, array, bp, mode); return ret; } JNIEXPORT jint JNICALL Java_com_sprint_jni_JNISandbox_MD_1TestByteBuffer (JNIEnv *env, jobject obj, jint hsmIndex, jint infoType, jobject buf) { jbyte *bp = (*env)-&gt;GetDirectBufferAddress(env, buf); jint len = (*env)-&gt;GetDirectBufferCapacity(env, buf); //printf("length of buffer = %d", len); jint ret = MD_GetHsmInfo(hsmIndex, infoType, bp, len); return ret; } </code></pre> <p>Both functions seem to work fine, but I would like to make both functions production-ready, so that I can demonstrate without bias which approach to use. As I am not too familiar with JNI, it is likely that my code is not written optimally, so I would appreciate any feedback on that too.</p> <hr> <p><strong>Background</strong></p> <p>In the above snippet, <code>MD_GetHsmInfo</code> is a C function which my Java code needs to call.</p> <pre><code>MD_RV MD_GetHsmInfo(uint32_t hsmIndex, MD_Info_t infoType, void *pValue, uint32_t valueLen); </code></pre> <p><code>pValue</code> is described as such:</p> <blockquote> <p>The address of the buffer to hold the information value. The buffer must have been allocated by the caller. The size of the buffer is determined by the infoType that is being obtained.</p> </blockquote> <p><code>MD_RV</code> and <code>MD_Info_t</code> are enums defined as follows:</p> <pre><code>typedef enum { MDI_HSM_DESCRIPTION = 1, //...so on } MD_Info_t; // similar implementation for MD_RV </code></pre> <p>The actual implementation of the function resides within a DLL file, but I do not have access to it yet. For now I have written a dummy implementation as follows:</p> <pre><code>int MD_GetHsmInfo(int hsmIndex, int infoType, void *pValue, int valueLen) { //printf("This is dummy implementation of MD_GetHsmInfo()\n"); char *str; if(infoType == 1) { str = "info = 1"; } else if(infoType == 2) { str = "info = 2"; } else { str = "no info"; } jbyte *jb = (jbyte*)pValue; while(*str) { *jb++ = *str++; } *jb = 0; valueLen = strlen(str); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T08:36:43.540", "Id": "437110", "Score": "0", "body": "If you had to choose, are you more interested in a comparison between approaches or a review of this specific code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T08:58:47.267", "Id": "437111", "Score": "0", "body": "@Mast I'm not that familiar with JNI and I came up with this code entirely based on what I read online. I am more interested in a comparison, but at the same time I would also like to know how I can improve my current one. Does this make sense?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T09:33:14.830", "Id": "437120", "Score": "0", "body": "@user10931326 perhaps you should mention that you're interested in performance." } ]
[ { "body": "<p><strong>Minor issues in <code>MD_GetHsmInfo()</code></strong></p>\n\n<p><code>valueLen = strlen(str);</code> serves no purpose below as the value assigned to <code>valueLen</code> is not used.</p>\n\n<pre><code>int MD_GetHsmInfo(int hsmIndex, int infoType, void *pValue, int valueLen) {\n ...\n valueLen = strlen(str);\n return 0;\n}\n</code></pre>\n\n<p>Perhaps</p>\n\n<pre><code>int MD_GetHsmInfo(int hsmIndex, int infoType, void *pValue, int *valueLen) {\n ...\n *valueLen = strlen(str);\n return 0;\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>int MD_GetHsmInfo(int hsmIndex, int infoType, void *pValue, size_t *valueLen) {\n</code></pre>\n\n<hr>\n\n<p>Cast not needed</p>\n\n<pre><code>int MD_GetHsmInfo(int hsmIndex, int infoType, void *pValue, int valueLen) {\n ...\n // jbyte *jb = (jbyte*)pValue;\n jbyte *jb = pValue;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T00:58:52.340", "Id": "225624", "ParentId": "225180", "Score": "1" } }, { "body": "<p>Term \"production ready\" certainly has different meanings for different people, but I consider it as a reason to do <em>some</em> nitpicking, at least.</p>\n\n<hr>\n\n<p>First of all, you mentioned that the actual goal is to compare the performance between <code>byte[]</code> arrays and <code>ByteBuffer</code>. This is something that one could write an essay on, and it's tremendously difficult to pull <em>objective</em> results out of such a test. In order to not distort the results, you'd have to run the test with different array/buffer sizes, consider the possible effects of GC and pinning of the JVM (which is somewhat unspecified, and thus, could only be evaluated empirically for one given VM). You'd also have to use a dummy implementation of <code>MD_GetHsmInfo</code> (as you already did), in order to not distort the results. </p>\n\n<p><sup>(Actually, I <em>should</em> have some idea about the performance difference here and the results that you could expect, but have to admit that I haven't yet evaluated this as systematically as I probably <em>should</em> have. Maybe I'll try to allocate some time for that, and extend this answer with some results later...)</sup></p>\n\n<hr>\n\n<p>You're talking about <code>ByteBuffer</code> in the text, but the code seems to be targeting <strong>direct</strong> <code>ByteBuffer</code> specifically. This may look like a detail, but when you say that the code should be \"production ready\", you have to be aware that <a href=\"https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/functions.html#GetDirectBufferAddress\" rel=\"nofollow noreferrer\"><code>GetDirectBufferAddress</code></a> may return <code>NULL</code> when the buffer is <em>not</em> a <strong>direct</strong> <code>ByteBuffer</code>. That is, it will crash when you call your function with a <code>ByteBuffer</code> that was created by calling <code>ByteBuffer.wrap(someByteArray)</code>. </p>\n\n<hr>\n\n<p>You're creating the <code>isCopy</code> variable and passing it to <a href=\"https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/functions.html#Get_PrimitiveType_ArrayElements_routines\" rel=\"nofollow noreferrer\"><code>GetByteArrayElements</code></a>, but you are not using the value of this variable. Alternatively, you can simply pass in <code>NULL</code> as the last parameter. Whether or not the returned object is a <em>copy</em> is mainly/only relevant when you release the array elements later.</p>\n\n<hr>\n\n<p>As explained in <a href=\"https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/functions.html#Release_PrimitiveType_ArrayElements_routines\" rel=\"nofollow noreferrer\"><code>ReleaseByteArrayElements</code></a>, the <code>mode</code> that is passed in as the last parameter does <strong>only</strong> have an effect if the returned elements have been a copy. But using <code>0</code> as the default and <code>JNI_ABORT</code> in case of an error should be fine.</p>\n\n<hr>\n\n<p>When the goal of the comparison is about performance, then the <a href=\"https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/functions.html#GetPrimitiveArrayCritical_ReleasePrimitiveArrayCritical\" rel=\"nofollow noreferrer\"><code>*PrimitiveArrayCritical</code></a> family of methods may be worth being mentioned: They can (roughly speaking) be used to treat the section that uses the array data as a \"critical section\", and temporarily disable the GC, making it more likely that the VM will <em>not</em> have to create a <em>copy</em> of the data that later has to be written back. </p>\n\n<p>But again, the details here are not directly specified and certainly depend on the VM and the size of the array, so it's hard or impossible to say which effect this may have on performance in practice.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T13:37:09.880", "Id": "225650", "ParentId": "225180", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T07:50:04.093", "Id": "225180", "Score": "2", "Tags": [ "java", "c", "jni" ], "Title": "Production-ready comparison between byte-array and ByteBuffer" }
225180
<p>I have a fast growing table with logs that I frequently have to delete (the server doesn't have much resources). It grows by at least two million entries every day. The database is a SQL Server 2012. </p> <p>Currently I use this script to delete entries older than 7 days:</p> <pre><code>set nocount on; declare @r int = 1 while @r &gt; 0 begin begin transaction; delete top(10000) from [Logs] where cast([Timestamp] as date) &lt; cast(dateadd(day, -7, GETUTCDATE()) as date)) set @r = @@ROWCOUNT; commit transaction; end </code></pre> <p>When I don't do it daily then it runs for a couple of hours (3-5) <em>blocking</em> other tasks that usually exit with timeouts (they need it for reporting).</p> <p>I use transactions because I sometimes need to stop it before it's finished and this is easier to do with smaller batches. Otherwise there is too much to rollback.</p> <p>The table is a pretty <em>normal</em> log:</p> <pre><code>CREATE TABLE [dbo].[Log]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [Timestamp] [datetime2](7) NOT NULL, [Environment] [nvarchar](50) NOT NULL, [Logger] [nvarchar](50) NOT NULL, [Message] [nvarchar](max) NULL, [Exception] [nvarchar](max) NULL, CONSTRAINT [PK_Log_Id] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO </code></pre> <hr> <p>Is there a way to make this script faster? Am I doing anything terribly wrong here?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T09:09:02.510", "Id": "437112", "Score": "1", "body": "How about computing `cast(dateadd(day, -7, GETUTCDATE()) as date)` once and reuse it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T09:11:01.720", "Id": "437113", "Score": "0", "body": "@Heslacher I like it, definitely will improve readability... I'll check whether the execution plan would change too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T09:18:54.657", "Id": "437114", "Score": "1", "body": "If this is a production environment, I would suggest to use a commercial tool that handles billions of logs for you: https://www.splunk.com/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T09:20:10.067", "Id": "437115", "Score": "1", "body": "If a commercial tool is not an option, consider creating an unclustered index on [Timestamp]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T09:22:30.360", "Id": "437116", "Score": "0", "body": "@dfhwze I'll take a look at that tool. Can it handle deleting too? I cannot even query the table when it grows over ~10mln rows (yeah, it's for production)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T09:26:12.170", "Id": "437118", "Score": "0", "body": "@dfhwze I'm reluctant about creating an index for it because I'm afraid with that insert ratio it might hurt performance there. I'll need to test it first how many inserts the database can manage with an index on the `Timestamp` column." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T09:32:23.363", "Id": "437119", "Score": "0", "body": "Check out these tools. They allow for very fast lookup, with date range, string pattern, regex filters, even if you have billions of records. I strongly suggest your company investigates the option of moving logs out of your own database and into the cloud." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T09:34:46.563", "Id": "437121", "Score": "0", "body": "@dfhwze we are using an ancient sql server that cannot even handle 10mln logs. Unfortunatelly a cloud will not gonna happen :-( everyone knows, nobody cares." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T09:36:43.407", "Id": "437122", "Score": "0", "body": "Then they will find out the hard way that at some point, this will be unmanagable :/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T09:37:51.410", "Id": "437123", "Score": "0", "body": "@dfhwze it already is... that's why I need this script." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T09:40:15.093", "Id": "437124", "Score": "0", "body": "if there is a quality environment with an equivalent load on the database, you could test the index there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T15:58:16.007", "Id": "437175", "Score": "1", "body": "some other options: https://stackoverflow.com/questions/24213299/how-to-delete-large-data-of-table-in-sql-without-log -> it also depends on whether you are deleting most of the records from the table, or keeping most." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T16:02:45.320", "Id": "437179", "Score": "1", "body": "@dfhwze I have an idea! I'll put all ids that I want to delete into a `cts` and then make a delete + join with that on the index without searching each time." } ]
[ { "body": "<p>Here is another recent Code Review question that has a lot of similarities to yours: <a href=\"https://codereview.stackexchange.com/q/225674/47529\">Daily SQL job to delete records older than 24 hours</a>.</p>\n<p>I think I would recommend three things here:</p>\n<ol>\n<li>Snapshot isolation</li>\n<li>Not using <code>TOP</code></li>\n<li>Doing the work in another table</li>\n</ol>\n<hr />\n<h2>Snapshot isolation</h2>\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/snapshot-isolation-in-sql-server\" rel=\"nofollow noreferrer\">Snapshot isolation</a> is a really cool tool that effectively prevents most things from blocking readers. As a result, even if your delete is running long, report-writers can still hit your table and they'll see the most recent, valid data. Then once your delete finishes, they'll start seeing the data without your deleted rows. This lets you do whatever you need to do without having to worry as much about end-users. It doesn't make your code faster, but it will somewhat reduce the need for it to be.</p>\n<hr />\n<h2>Not using <code>TOP</code></h2>\n<p>Because you're using <code>TOP</code>, you effectively force all of the data to be re-sorted every time. Additionally, <code>TOP</code> will usually introduce <a href=\"https://www.sql.kiwi/2010/08/inside-the-optimiser-row-goals-in-depth.html\" rel=\"nofollow noreferrer\">row goals</a>. This isn't necessarily a bad thing, but it may choose less-ideal plans in the interest of getting a subset of rows as quickly as possible.</p>\n<p>Because your <code>Id</code> column is an indexed <code>IDENTITY</code> column, <strong>and</strong> because we're deleting the oldest data (I'm assuming you don't generally update old data), you can do something like this:</p>\n<pre><code>DELETE FROM [Logs]\n WHERE Id BETWEEN @LowestCurrentIndex AND @HighestCurrentIndex\n AND CAST([Timestamp] AS date) &lt; CAST(DATEADD( DAY, -7, GETUTCDATE()) AS date);\n</code></pre>\n<p>This assumes you can maintain <code>@LowestCurrentIndex</code> and <code>@HighestCurrentIndex</code> as the range of values to currently consider. This will get you nice index accesses as well.</p>\n<p>A potential enhancement is to get a separate table that has all potentially affected rows, like so:</p>\n<pre><code>SELECT Id\n INTO #OldData\n FROM [Logs]\n WHERE CAST([Timestamp] AS date) &lt; CAST(DATEADD( DAY, -7, GETUTCDATE()) AS date);\n</code></pre>\n<p>Then you can just join between the two (and if you have an index on <code>#OldData.Id</code> it'll be a great merge-join) with the same bounds logic.</p>\n<pre><code>DELETE [Logs]\n FROM [Logs]\n INNER JOIN #OldData OldData\n ON [Logs].Id = OldData.Id\n WHERE OldData.Id BETWEEN @LowestCurrentIndex AND @HighestCurrentIndex -- This could be on either table\n</code></pre>\n<hr />\n<h2>Do the work in another table</h2>\n<p>If copying the data is less expensive than deleting it (very possible), then you may be able to more efficiently do the work with less user interruptions by doing all of your work in a separate table, and then switching the tables. Broadly speaking, the workflow would look like this:</p>\n<ol>\n<li>Copy all of the <em>valid</em> data into another identically formatted table (same indices, constraints, etc)</li>\n<li>Truncate the original table</li>\n<li>Perform a partition switch</li>\n</ol>\n<p>Alternatively, if partition switching isn't your jam, you can do a very similar thing manually:</p>\n<ol>\n<li>Copy all of the <em>valid</em> data into another identically formatted table (same indices, constraints, etc)</li>\n<li>Rename the original table to something else</li>\n<li>Rename the table from #1 to the original table's name</li>\n<li>Truncate the original (now renamed) table from #2</li>\n</ol>\n<p>These will result in much less index maintenance, and many of the operations can be done via minimal logging if well structured.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T15:47:12.730", "Id": "440526", "Score": "1", "body": "wow, this is a lot of interesting stuff! It'll take some time to study it and do experiments. I'll let you know when I implemented these suggestions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T15:24:56.560", "Id": "226632", "ParentId": "225181", "Score": "3" } } ]
{ "AcceptedAnswerId": "226632", "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T09:02:06.967", "Id": "225181", "Score": "3", "Tags": [ "performance", "sql", "sql-server", "logging", "transactions" ], "Title": "Deleting millions of logs in batches" }
225181
<p>This is the essence of chapter 3 of "Clojure for the Brave and True". This program is about completing the list <code>asym-hobbit-body-parts</code> by adding a given number of elements called <code>"0-&lt;name&gt;"</code> <code>"1-&lt;name&gt;"</code> and so on for every element in <code>asym-hobbit-body-parts</code> that starts with "left" and subsequently choosing a random body part to hit. This contains code from the book which I rewrote from memory after finishing chapter 3. (And I mixed it with what I learned on the <a href="https://clojure.org/guides/learn/syntax" rel="nofollow noreferrer">official homepage</a>)</p> <p>I am very curious what a clean version of this would look like.</p> <pre><code>(ns clojure-noob.core (:gen-class) (:require [clojure.string :as str] )) (def asym-hobbit-body-parts [{:name "head" :size 3} {:name "left-eye" :size 1} {:name "left-ear" :size 1} {:name "mouth" :size 1} {:name "nose" :size 1} {:name "neck" :size 2} {:name "left-shoulder" :size 3} {:name "left-upper-arm" :size 3} {:name "chest" :size 10} {:name "back" :size 10} {:name "left-forearm" :size 3} {:name "abdomen" :size 6} {:name "left-kidney" :size 1} {:name "left-hand" :size 2} {:name "left-knee" :size 2} {:name "left-thigh" :size 4} {:name "left-lower-leg" :size 3} {:name "left-achilles" :size 1} {:name "left-foot" :size 2}]) (defn make-sym-parts [asym-set num] (reduce (fn [sink, {:keys [name size] :as body-part}] (if (str/starts-with? name "left-") (into sink (apply vector body-part (for [i (range num)] {:name (str/replace name #"^left" (str i)) :size size}))) (conj sink body-part))) [] asym-set)) (defn rand-part [parts] (let [size-sum (reduce + (map :size parts)) thresh (rand size-sum)] (loop [[current &amp; remaining] parts sum (:size current)] (if (&gt; sum thresh) (:name current) (recur remaining (+ sum (:size (first remaining)))))))) (defn -main [&amp; arg] (println (rand-part (make-sym-parts asym-hobbit-body-parts 3)))) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T12:54:38.833", "Id": "437140", "Score": "0", "body": "I'm sorry, I adjusted the title. But I think you pasted the wrong link ^^" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T12:57:05.850", "Id": "437141", "Score": "0", "body": "Ah, seems the \"meta\" disappeared from the URL in in my template file. Apologies, the correct URL is https://CodeReview.Meta.StackExchange.com/q/2436 ." } ]
[ { "body": "<p>You actually already fixed up the main thing that I was going to comment on: your previous use of <code>def</code> over <code>let</code>. Just to emphasize on why it's important to choose one over the other though:</p>\n\n<pre><code>(defn f []\n (def my-var 5))\n\n(f)\n\n(println my-var)\n5 ; It leaked the state of the function and polluted the namespace\n</code></pre>\n\n<hr>\n\n<p>Beyond that, this isn't bad code. As I mentioned on SO, I'm a little rusty, so hopefully someone else will go a little more in-depth. I'll mention what I see here though:</p>\n\n<p>This might be a little over-engineering, but I don't like how the <code>asym-hobbit-body-parts</code> definition is repeating the keys <code>:name</code> and <code>:size</code> over and over. This allows typos to slip in, and makes more work for you if you want to add more parts. I'd make a \"constructor\" that automatically creates the maps from the data:</p>\n\n<pre><code>(defn new-part [part-name part-size]\n {:name part-name, :size part-size})\n\n(def asym-hobbit-body-parts [(new-part \"head\" 3)\n (new-part \"left-eye\" 1)\n (new-part \"left-ear\" 1)])\n</code></pre>\n\n<p>I like this because now there's a function that definitively says what a \"part\" is defined as, and if you ever want to change what keywords you use, you only need to change <code>new-part</code> now.</p>\n\n<p>This still has duplication though, and could be reduced down with a helper that auto-wraps vector \"tuples\":</p>\n\n<pre><code>(defn new-parts [&amp; name-size-pairs]\n (mapv #(apply new-part %) name-size-pairs))\n ; or (mapv (partial apply new-part) name-size-pairs)) ; Partially apply \"apply\"\n\n(def asym-hobbit-body-parts3 (new-parts\n [\"head\" 3]\n [\"left-eye\" 1]\n [\"left-ear\" 1]))\n</code></pre>\n\n<p>Or, if you want to get rid of the need for the wrapping vectors, you can use <code>partition</code> to cut a list of attributes into 2s:</p>\n\n<pre><code>(defn new-parts [&amp; name-size-pairs]\n (-&gt;&gt; name-size-pairs\n (partition 2) ; Cut the list into pairs of 2\n (mapv #(apply new-part %))))\n\n(def asym-hobbit-body-parts3 (new-parts\n \"head\" 3,\n \"left-eye\" 1,\n \"left-ear\" 1))\n</code></pre>\n\n<p>It really depends on how you want it to read.</p>\n\n<p>In case you aren't familiar with them, I highly recommend practicing use of <a href=\"https://clojuredocs.org/clojure.core/-%3E\" rel=\"nofollow noreferrer\"><code>-&gt;</code></a> and <a href=\"https://clojuredocs.org/clojure.core/-%3E%3E\" rel=\"nofollow noreferrer\"><code>-&gt;&gt;</code></a>. They seem a little complicated at first, but once you understand them, they have the potential to make your code much neater. They allow your code to read more easily as a series of transformations.</p>\n\n<hr>\n\n<p>I think the reduction in <code>make-sym-parts</code> is too big. When I have a call to <code>reduce</code> with a large reducing function like that, I try to move it out into its own standalone function. That gives that code a name to make it clearer what it's doing, and makes the call to <code>reduce</code> easier to understand. I decided just to make it a local function using <a href=\"https://clojuredocs.org/clojure.core/letfn\" rel=\"nofollow noreferrer\"><code>letfn</code></a>. You could also make it a global function using <code>defn</code>; but I don't think that's necessary.</p>\n\n<pre><code>(defn make-sym-parts [asym-set num]\n (letfn [(transform-lefts [sink {:keys [name] :as body-part}]\n (if (str/starts-with? name \"left-\")\n (into sink (apply vector body-part\n (for [i (range num)]\n (update body-part :name\n #(str/replace % #\"^left\" (str i))))))\n\n (conj sink body-part)))]\n\n (reduce transform-lefts [] asym-set)))\n</code></pre>\n\n<p>I also altered what you're doing in the <code>for</code> comprehension. You had a literal <code>{:name ..., :size size}</code> in there. This isn't good practice though. Pretend in the future you decide to add a new attribute to body parts. Maybe <code>:quality</code> or something. What happens if you forget to update <code>make-sym-parts</code>? Because you're reconstructing the map from scratch, the new body part will be discarded! <a href=\"https://clojuredocs.org/clojure.core/update\" rel=\"nofollow noreferrer\"><code>update</code></a> is like <code>assoc</code>, but it \"updates\" a previous value using a function instead of overwriting it like <code>assoc</code> does. The previous value is passed into the function, and the new value becomes whatever the function returns.</p>\n\n<p>This could still be improved a bit by making use of <code>mapcat</code>. Right now, you're using <code>reduce</code> instead of <code>map</code> because in some cases, you need to add multiple entries per existing element. <code>mapcat</code> (basically short for \"map then concatenate\") can help here. It will automatically flatten the resulting list. This means you can get rid of the <code>sink</code> accumulator:</p>\n\n<pre><code>(defn make-sym-parts [asym-set num]\n (letfn [(transform-lefts [{:keys [name] :as body-part}]\n (if (str/starts-with? name \"left-\")\n [body-part\n (for [i (range num)]\n (update body-part :name\n #(str/replace % #\"^left\" (str i))))]\n\n [body-part]))] ; Note how this requires a wrapping so it can be flattened\n\n (mapcat transform-lefts asym-set))) ; Lazy!\n</code></pre>\n\n<p>The major drawback here is I wouldn't be surprised if this is slower. That likely isn't an issue though.</p>\n\n<hr>\n\n<p>I was going to suggest you change <code>rand-part</code> to use <code>reduce</code> (I had a whole thing written up and everything!), then I realized that it requires knowledge of the next part in the list. It is still possible to use <code>reduce</code>, but it would require doing something messy like partitioning the list of parts into pairs, then reducing over the pairs. I think what you have here is likely neater.</p>\n\n<p>I will mention though, just in case you didn't know, <code>reduce</code> allows for an early exit using <a href=\"https://clojuredocs.org/clojure.core/reduced\" rel=\"nofollow noreferrer\"><code>reduced</code></a>. If you didn't need to use <code>remaining</code> in the loop, that would allow your <code>loop</code> here to be written using <code>reduce</code>.</p>\n\n<p>The only real two noteworthy things in <code>rand-part</code> are</p>\n\n<ul>\n<li><p>I would use <code>:keys</code> here to deconstruct <code>current</code>. You're using explicit key-access a lot which adds some bulk.</p></li>\n<li><p><code>(reduce +</code> can also be written as <code>(apply +</code>. If you look at the <a href=\"https://github.com/clojure/clojure/blob/841fa60b41bc74367fb16ec65d025ea5bde7a617/src/clj/clojure/core.clj#L985\" rel=\"nofollow noreferrer\">definition of <code>+</code></a>, it and most other binary operators have a var-arg overload to delegates to a reduction. It's not a big deal either way. From what I've seen, <code>(apply +</code> is generally regarded as more idiomatic, but not by much.</p></li>\n</ul>\n\n<p>Something like:</p>\n\n<pre><code>(defn rand-part [parts]\n (let [size-sum (apply + (map :size parts))\n thresh (rand size-sum)]\n (loop [[{:keys [name size]} &amp; remaining] parts\n sum size]\n (if (&gt; sum thresh)\n name\n (recur remaining\n (+ sum (:size (first remaining))))))))\n</code></pre>\n\n<p>Good luck and welcome to Clojure!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T19:25:36.677", "Id": "437198", "Score": "0", "body": "Wow this is a lot. Thank you for your effort. I think I'll be back in a few weeks with a real project instead of a toy example :) It is awesome that you took the time to explain all this. Sadly I can't even upvote your answer since I dont have 15 reputation yet" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T19:46:11.153", "Id": "437200", "Score": "0", "body": "@Uzaku No problem, I enjoy reviewing code. I'm looking forward to seeing what you come up with in the next couple weeks." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T15:31:56.163", "Id": "225207", "ParentId": "225186", "Score": "0" } } ]
{ "AcceptedAnswerId": "225207", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T11:23:28.880", "Id": "225186", "Score": "2", "Tags": [ "beginner", "clojure" ], "Title": "A program that expands a list of maps and chooses a random element" }
225186