body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Any chance people can read my game code and see if reformatting or rewriting is necessary for a better overall code? I'd really appreciate it.</p> <pre><code>#I implemened a random module into my program as it is needed to shuffle the 'cpu_choices' list randomly. import random import time #I implemented time module to introduce a timer which will occur when the user selects the amount of rounds they want to play # and when the match is over #---------------VARIABLES---------------# #I started to plan what variables were necessary to meet the specifications. #I designated variables to sections to make it easier for myself and future proofing as users can gain an understanding of each variable and their purpose. #GAME_RULES are capitalized to represent it is a constant - meaning they never change. GAME_RULES = ["RULES:", "- Paper wins against Rock", "- Rock wins against Scissors", "- Scissors wins against Paper", "- When asked: 'y' = yes, and 'n' = no"] cpu_choices = ["Paper", "Scissors", "Rock"] #cpu_choice isn't a constant because the order of the choices will change. (Though the list will not) player_name = 0 #Stores the player's name after input. player_score = 0 #player_score remembers the score of the player. player_history = [] #A placeholder list that holds the player's move history. player_move = 0 #player_move temporarily holds the move that the player plays. intro_loop = True #intro_loop is the condition that keeps or stops the introduction running. game_loop = True #game_loop keeps the "gameplay" section of the code running if the player wants to do another set of rounds. replay_loop = True #replay_loop keeps asking the user if they want to replay incase they enter an incorrect input. replay_choice = "y" #replay_choice is the user's input that dicides whether or not the "gameplay" loop repeats. round_repeat = True #This variable keeps the code asking what move the player wants to play if they enter the wrong thing. total_rounds = 0 #holds the # of rounds the user wants to play. round_num = 0 #round_num stores what number the current round is, as well as dictating how many times it runs. round_history = [[]] #A placeholder list that will hold the move history of the rounds. This will be used for the match overview at the end of the game. cpu_move = 0 #cpu_move temporarily holds the move that the computer plays. cpu_score = 0 #cpu_score remembers the score of the computer. cpu_history = [] #A placeholder list that holds the cpu's move history. #----------------------------------------# #This function serves as the code portion that handles the processes in a round. #(num) is a parameter which is used to insert the current round number. def round_process(num): global cpu_history global cpu_score global player_score #identifying global variables that will be used within this specific function. global player_history #changes made to these variables #resets the while loop condition round_repeat = True random.shuffle(cpu_choices) #creating a random.shuffle for the cpu choices list to allow for a random and unbiased choice of either r, p or s (obviously). #This allows the cpu move to be the first move of 'cpu_choices'. #The order of the list is shuffled, so the index should always stay the same. cpu_move = cpu_choices[0] #I implemented a while loop to make the input repeat incase the user doesn't input correctly. e.g. inputs a number or misspells a choice. while round_repeat == True: print("\n--------------\nROUND", num, "\n--------------") player_move = input("\nWhat's your move? 'Paper', 'Scissors' or 'Rock'?\t") # This input asks and stores what move the user wants to make. player_move = player_move.capitalize() #Players move is capitalized so if they type 'rock' without a capital R, the program will still recognize it as a valid answer. # This 'if' statement validates the user's input. # Otherwise they will be asked again via the else statement. Both non capitalized and capitalized inputs can be accepted, as # .capitalize is utilized in my player_move variable. if player_move == "Paper" or player_move == "Rock" or player_move == "Scissors": print("\nLocked in! You chose", player_move, "\nThe CPU chose", cpu_move) #----------SCORING----------# #The if and elif statements within the SCORING section dictate whether the user wins, draws, or loses with the cpu. #Scores are added according to the result. Wins count for two points, draws 1, losses 0. if player_move == "Paper" and cpu_move == "Rock" or player_move == "Rock" and cpu_move == "Scissors" or player_move == "Scissors" and cpu_move == "Paper": player_score += 2 #Point is added to the player's score by 2. print("\nGood work! You win this round!") elif player_move == cpu_move: player_score += 1 #this elif gives both the cpu and the player a point each. cpu_score += 1 print("\nLooks like both of you had the same idea! It's a draw!") else: cpu_score += 2 #only adds to the cpu_score because the player lost. print("\nYikes! You lose this round! He beat you with", cpu_move) print("\nYour score is", player_score) #states scores so far for player and cpu print("Computer's score is", cpu_score) # &lt;---- #player_history and cpu_history append, or add, their specific moves from each round into the list. #This is required in my specifications and can show a 'Match History' type screen in the end. player_history.append(player_move) cpu_history.append(cpu_move) #adds the cpu move for each round to the cpu_history list. round_repeat = False #the round loop breaks so player continues to next round OR end of game. else: print("\n!!!!!!!!!!!!!!!!!!!!!!!!!\nUh oh! That input is wrong. Please type either 'Paper', 'Scissors' or 'Rock'\n!!!!!!!!!!!!!!!!!!!!!!!!!") #---------------------------# #round_process the function that handles all processes in a single round, and I am using the parameter. print("-----------------------------------") print("| |") print("| ROCK PAPER SCISSORS |") print("| PYTHON REMASTERED |") print("| |") print("-----------------------------------") for rule in GAME_RULES: print(rule) # This for loop prints GAME_RULES in a list layout by printing # each rule within GAME_RULES for every cycle of the loop. # A for loop is used for iterating over a sequence while intro_loop == True: #Valid name input is stored inside the player_name variable (was formerly blank) player_name = input("\nWelcome to Rock Paper Scissors, PYTHON REMASTERED!\n What is your name?\t") if player_name != "": #If statement forces the name to not be blank and to reinput their data input. player_name = player_name.capitalize() #.capitalize capitalises the first letter of the username for a more aesthetically pleasing look. intro_loop = False print("\nWelcome", player_name) else: print("\n-------------------------\nSurely you've got a name! Try again\n-------------------------") #I started the game loop here because from here on all inputs I request from the user will be only used to play the game. while game_loop == True: try: total_rounds = int(input("\nHow many rounds would you like to play? '3', '5', '7' or '9'\t")) if total_rounds &lt; 3 or total_rounds &gt; 9 or total_rounds%2 == 0: print("\n---------------------------------\nPlease enter '3', '5', '7' or '9'\n---------------------------------") else: player_history = [] cpu_history = [] round_num = 1 cpu_score = 0 player_score = 0 replay_loop = True while round_num &lt;= total_rounds: round_process(round_num) round_num += 1 round_history = [list(a) for a in zip(player_history, cpu_history)] print("\n--------\nHistory\n--------") for i in range(0,round_num - 1): print("\nRound", str(i + 1) + ": You chose", round_history[i][0] + ". The cpu chose", round_history[i][1]) print("\n----------\nMatch Results\n----------") print("\nYou finished on a total score of", player_score, "\nThe computer finished on a total score of", cpu_score) #------------WINNER DETERMINED------------# if player_score &gt; cpu_score: print("\n You won! Congratulations", player_name, "!") elif player_score &lt; cpu_score: print("\nUnlucky mate! You lost :(") elif player_score == cpu_score: print("\nYou drew! :|") #-----------------------------------------# while replay_loop == True: replay_choice = input("\nWould you like to play again? 'y' or 'n'\t") replay_choice = replay_choice.lower() if replay_choice == "y" or replay_choice == "n": if replay_choice == "n": print("\nHave a good day", player_name,"!") game_loop = False replay_loop = False else: print("\n-----------------------\nPlease enter 'y' or 'n'\n-----------------------") #where the input is invalid, the user will be asked again until they input 'y' or 'n'. except: print("\n--------------------\nPlease enter a digit\n--------------------") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T10:44:41.147", "Id": "449865", "Score": "0", "body": "Welcome to code review, this website is for peer reviewing code, if you just have a question about formatting then this is not an appropriate place for your code. People here provide review for the overall code in terms of style, performance ..." } ]
[ { "body": "<p>Here I will modify the strings you printed such that it doesn't go over the screen.</p>\n\n<p>I don't see why you need to have <code>GAME RULES</code> as a separate variable. No harm and maybe more straightforward doing</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(\"-----------------------------------\")\nprint(\"| |\")\nprint(\"| ROCK PAPER SCISSORS |\")\nprint(\"| PYTHON REMASTERED |\")\nprint(\"| |\")\nprint(\"-----------------------------------\")\nprint(\"RULES: \")\nprint(\"- Paper wins against Rock \")\nprint(\"- Rock wins against Scissors \")\nprint(\"- Scissors wins against Paper \")\nprint(\"- When asked: 'y' = yes, 'n' = no \")\n</code></pre>\n\n<p>The intro loop is too long and can be simplified. In Python, an empty string evaluates to false. Furthermore, you can capitalize on the input itself.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Get player name\nwhile True:\n player_name = input(\"What is your name? \").capitalize()\n if player_name:\n break\n print(\"Surely you've got a name! Try again\")\n\nprint(\"Welcome\", player_name)\n</code></pre>\n\n<p>The part where it asks for the number of rounds is too complicated. Use an list to indicate the options, or at least use it to check if it is valid. Furthermore, specify the exception you are catching.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>while True:\n try:\n validRounds = [3, 5, 7, 9]\n rounds = int(input(\"How many rounds would you like to play?\" + str(validRounds)))\n if rounds in validRounds:\n break\n except ValueError:\n pass\n print(\"Please enter '3', '5', '7' or '9'\")\n\n# Put the large else part here\n</code></pre>\n\n<p>Now we look at your <code>round_process</code>. </p>\n\n<ol>\n<li><code>global</code> isn't necessary here. The function shouldn't need to know the score and history of both players. Instead, make the function return the move each of the players made.</li>\n<li>Do not shuffle the choices for the cpu, use <code>random.choice</code> instead.</li>\n<li>Use list to check existence.</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>def processRound(num):\n print(\"Round \", num)\n # Get player move\n while True:\n validMoves = ['Paper', 'Scissors', 'Rock']\n move = input(\"What's your move? \" + str(validMoves))\n if move in moves:\n break\n print(\"That input is wrong. Please type either 'Paper', 'Scissors' or 'Rock'\")\n\n # cpu move\n cpuMove = random.choice(validMoves)\n\n print(\"Locked in! You chose\", player_move, \"\\nThe CPU chose\", cpu_move)\n if move == cpuMove:\n # draw\n elif (move, cpuMove) in [('Paper', 'Rock'), ('Scissors', 'Paper'), ('Rock', 'Scissors')]:\n # win\n else:\n # lose\n\n return (move, score), (cpuMove, cpuScore)\n</code></pre>\n\n<p>Now that you know the number of rounds, use a for loop instead of a while loop.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(rounds):\n processRound(i + 1)\n</code></pre>\n\n<p>One last thing is you may consider using Enum for the moves.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T12:22:36.513", "Id": "230830", "ParentId": "230822", "Score": "1" } } ]
{ "AcceptedAnswerId": "230830", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T10:26:50.130", "Id": "230822", "Score": "2", "Tags": [ "python", "game", "rock-paper-scissors" ], "Title": "Python Rock Paper Scissors Game" }
230822
<p>I am implementing a Fibonacci range in C++17 such that it supports</p> <pre class="lang-cpp prettyprint-override"><code>#include "fib.h" #include &lt;iostream&gt; int main() { for (int x : Fibonacci()) { std::cout &lt;&lt; x &lt;&lt; std::endl; if (x &gt; 100000) { break; } } for (int x : Fibonacci(5)) { std::cout &lt;&lt; x &lt;&lt; std::endl; } for (int x : Fibonacci(3, 10)) { std::cout &lt;&lt; x &lt;&lt; std::endl; } return 0; } </code></pre> <p>Here is how I defined the header</p> <pre class="lang-cpp prettyprint-override"><code>#ifndef FIB_H #define FIB_H #include &lt;cstddef&gt; #include &lt;iterator&gt; class Fibonacci { public: class iterator { public: using iterator_category = std::forward_iterator_tag; using value_type = int; using difference_type = int; using pointer = int*; using reference = int&amp;; public: iterator() = default; iterator(int i, int a, int b); int operator*() const; iterator&amp; operator++(); bool operator!=(iterator const&amp; other) const; private: int i_ {0}; int a_ {0}; int b_ {1}; }; public: Fibonacci(); Fibonacci(int end); Fibonacci(int begin, int end); iterator begin() const; iterator end() const; private: iterator beginIt_; iterator endIt_; }; #endif </code></pre> <p>And the source code</p> <pre class="lang-cpp prettyprint-override"><code>#include "fib.h" #include &lt;iterator&gt; Fibonacci::iterator::iterator(int i, int a, int b) : i_(i), a_(a), b_(b) {} int Fibonacci::iterator::operator*() const { return b_; } Fibonacci::iterator&amp; Fibonacci::iterator::operator++() { ++i_; b_ = b_ + a_; a_ = b_ - a_; return *this; } bool Fibonacci::iterator::operator!=(Fibonacci::iterator const&amp; other) const { return i_ != other.i_; } Fibonacci::Fibonacci() : endIt_(-1, 0, 0) {} Fibonacci::Fibonacci(int end) : endIt_(end, 0, 0) {} Fibonacci::Fibonacci(int begin, int end) : beginIt_(std::next(Fibonacci::iterator(), begin)), endIt_(end, 0, 0) {} Fibonacci::iterator Fibonacci::begin() const { return beginIt_; } Fibonacci::iterator Fibonacci::end() const { return endIt_; } </code></pre> <p>I want to have a syntax similar to the standard library where the iterator of a class can be accessed using <code>::iterator</code>, therefore I nested my iterator class into the main class itself. However, this makes the source code very verbose and results in very long function name. Is there a way to make this more readable? Furthermore, is there any new C++17 feature I should be aware of that can be applied here?</p>
[]
[ { "body": "<p>Overall, I think the code looks good. Here are a few sugestions that may help you improve your code.</p>\n\n<h2>Check for overflow</h2>\n\n<p>As you know, terms of the Fibonacci sequence get very big very quickly. For this reason, it's easy to overflow the numerical range. I'd suggest addressing this by throwing an exception in <code>iterator&amp; operator++()</code>:</p>\n\n<pre><code>if (b_ &lt; a_) {\n throw std::overflow_error(\"Exceeded range of underlying type\");\n}\n</code></pre>\n\n<h2>Use an unsigned type</h2>\n\n<p>None of the terms of the Fibonacci sequence are negative, so I'd suggest that perhaps <code>unsigned</code> or even <code>unsigned long</code> might be more appropriate base types. </p>\n\n<h2>Use a template</h2>\n\n<p>It may make sense to turn this into a templated function to allow different types to be used as the base type. This would be one way to extend the range, such as with the <a href=\"http://gmplib.org/\" rel=\"nofollow noreferrer\">GNU Multiple Precision Arithmetic Library</a>.</p>\n\n<h2>Consider a different <code>operator++</code> implementation</h2>\n\n<p>The current implementation of the <code>operator++</code> is this:</p>\n\n<pre><code>iterator&amp; operator++() {\n ++i_;\n b_ = b_ + a_;\n a_ = b_ - a_;\n return *this;\n}\n</code></pre>\n\n<p>I would suggest, especially if you decide to implement templates, that this might be more efficient:</p>\n\n<pre><code>iterator&amp; operator++() {\n ++i_;\n std::swap(a_, b_);\n b_ += a_;\n if (b_ &lt; a_) {\n throw std::overflow_error(\"Exceeded range of underlying type\");\n }\n return *this;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T14:26:38.510", "Id": "230845", "ParentId": "230825", "Score": "2" } } ]
{ "AcceptedAnswerId": "230845", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T11:20:38.690", "Id": "230825", "Score": "3", "Tags": [ "c++", "c++17", "fibonacci-sequence" ], "Title": "Implement Fibonacci range" }
230825
<p>I have created a chess game in JavaScript. Right now you can only play against another human. </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>"use strict"; function Piece(x, y, type, color) { let char; let moved = false; switch (type) { case "Pawn": char = "\u2659"; break; case "Knight": char = "\u265E"; break; case "Bishop": char = "\u265D"; break; case "Rook": char = "\u265C"; break; case "Queen": char = "\u265B"; break; case "King": char = "\u265A"; break; } let fill = color === "White" ? "#fff" : "#000"; let size = Piece.prototype.tileSize; let half = size / 2; let dispX = x * size + half; let dispY = y * size + half; return { type: type, color: color, get x() { return x; }, get y() { return y; }, get moved() { return moved; }, set moved(b) { moved = b; }, moveTo(nx, ny) { x = nx; y = ny; }, moveDispTo(nx, ny) { dispX = nx; dispY = ny; }, reset() { dispX = x * size + half; dispY = y * size + half; }, draw(ctx) { ctx.fillStyle = fill; ctx.fillText(char, dispX, dispY + size * 0.1); }, }; } const canvas = document.getElementById("display"); const messages = document.getElementById("messages"); const ctx = canvas.getContext("2d"); const size = Math.min(window.innerWidth, window.innerHeight) * 0.9; const sideSize = Piece.prototype.tileSize = size / 8; const tiles = new Array(8).fill().map(() =&gt; new Array(8).fill("")); const highlights = new Array(8).fill().map(() =&gt; new Array(8).fill("#00000000")); const pieces = [ Piece(0, 0, "Rook", "Black"), Piece(1, 0, "Knight", "Black"), Piece(2, 0, "Bishop", "Black"), Piece(3, 0, "Queen", "Black"), Piece(4, 0, "King", "Black"), Piece(5, 0, "Bishop", "Black"), Piece(6, 0, "Knight", "Black"), Piece(7, 0, "Rook", "Black"), Piece(0, 1, "Pawn", "Black"), Piece(1, 1, "Pawn", "Black"), Piece(2, 1, "Pawn", "Black"), Piece(3, 1, "Pawn", "Black"), Piece(4, 1, "Pawn", "Black"), Piece(5, 1, "Pawn", "Black"), Piece(6, 1, "Pawn", "Black"), Piece(7, 1, "Pawn", "Black"), Piece(0, 6, "Pawn", "White"), Piece(1, 6, "Pawn", "White"), Piece(2, 6, "Pawn", "White"), Piece(3, 6, "Pawn", "White"), Piece(4, 6, "Pawn", "White"), Piece(5, 6, "Pawn", "White"), Piece(6, 6, "Pawn", "White"), Piece(7, 6, "Pawn", "White"), Piece(0, 7, "Rook", "White"), Piece(1, 7, "Knight", "White"), Piece(2, 7, "Bishop", "White"), Piece(3, 7, "Queen", "White"), Piece(4, 7, "King", "White"), Piece(5, 7, "Bishop", "White"), Piece(6, 7, "Knight", "White"), Piece(7, 7, "Rook", "White"), ]; canvas.width = size; canvas.height = size; ctx.textBaseline = "middle"; ctx.textAlign = "center"; ctx.font = sideSize + "px Georgia"; for (let x = 0; x &lt; 8; ++x) for (let y = 0; y &lt; 8; ++y) tiles[y][x] = y % 2 === x % 2 ? "#D2B48C" : "#A0522D"; let moving = null; let validMoves = null; let turn = false; let winScreen = false; let frameHandle; addEventListener("mousedown", e =&gt; { if (winScreen) { frameHandle = requestAnimationFrame(frame); winScreen = false; messages.innerText = ""; } if (moving === null) { const rect = canvas.getBoundingClientRect(); moving = getPieceAt(Math.floor((e.clientX - rect.x) / sideSize), Math.floor((e.clientY - rect.y) / sideSize)); if (moving === undefined || (moving.color === "White") === turn) moving = null; else validMoves = getSquaresChecked(moving); } }); addEventListener("mousemove", e =&gt; { if (moving !== null) { const rect = canvas.getBoundingClientRect(); moving.moveDispTo(e.clientX - rect.x, e.clientY - rect.y); } }); addEventListener("mouseup", e =&gt; { if (moving !== null) { const rect = canvas.getBoundingClientRect(); const tileX = Math.floor((e.clientX - rect.x) / sideSize); const tileY = Math.floor((e.clientY - rect.y) / sideSize); if (validMoves.find(m =&gt; m[0] === tileX &amp;&amp; m[1] === tileY) !== undefined) { const index = pieces.findIndex(p =&gt; p.x === tileX &amp;&amp; p.y === tileY); if (index &gt; -1) pieces.splice(index, 1); moving.moved = true; if (moving.type === "King") { if (tileX - moving.x === 2) { let rook = getPieceAt(7, moving.y); rook.moveTo(tileX - 1, moving.y); rook.reset(); } if (tileX - moving.x === -2) { let rook = getPieceAt(0, moving.y); rook.moveTo(tileX + 1, moving.y); rook.reset(); } } moving.moveTo(tileX, tileY); turn = !turn; } moving.reset(); moving = null; let checkmate = true; for (const piece of pieces) { if ((piece.color !== "White") === turn &amp;&amp; getSquaresChecked(piece).length) { checkmate = false; break; } } for (let x = 0; x &lt; 8; ++x) for (let y = 0; y &lt; 8; ++y) highlights[y][x] = "#00000000"; if (checkmate) { winScreen = true; cancelAnimationFrame(frameHandle); draw(); messages.innerText = (turn ? "White" : "Black") + " Wins!" + "\nClick to play again"; reset(); } else if (inCheck()) messages.innerText = "Check!"; else messages.innerText = ""; } }); frameHandle = requestAnimationFrame(frame); function getPieceAt(x, y) { return pieces.find(p =&gt; p.x === x &amp;&amp; p.y === y); } function getSquares(piece) { let validMoves = []; switch (piece.type) { case "Pawn": const n = piece.color === "White" ? 1 : -1; const r = piece.color === "White" ? 6 : 1; if (getPieceAt(piece.x, piece.y - 1 * n) === undefined) { validMoves.push([piece.x, piece.y - 1 * n, "#0000ff55"]); if (getPieceAt(piece.x, piece.y - 2 * n) === undefined &amp;&amp; piece.y === r) validMoves.push([piece.x, piece.y - 2 * n, "#0000ff55"]); } const left = getPieceAt(piece.x - 1, piece.y - 1 * n); const right = getPieceAt(piece.x + 1, piece.y - 1 * n); if (left !== undefined &amp;&amp; left.color !== piece.color) validMoves.push([piece.x - 1, piece.y - 1 * n, "#ff000055"]); if (right !== undefined &amp;&amp; right.color !== piece.color) validMoves.push([piece.x + 1, piece.y - 1 * n, "#ff000055"]); break; case "Knight": const moves = [ [piece.x + 2, piece.y + 1], [piece.x - 2, piece.y + 1], [piece.x + 2, piece.y - 1], [piece.x - 2, piece.y - 1], [piece.x + 1, piece.y + 2], [piece.x - 1, piece.y + 2], [piece.x + 1, piece.y - 2], [piece.x - 1, piece.y - 2], ]; for (const m of moves) { const p = getPieceAt(...m); if (p === undefined) validMoves.push(m.concat("#0000ff55")); else if (p.color !== piece.color) validMoves.push(m.concat("#ff000055")); } break; case "Bishop": for (let dx = -1; dx &lt; 2; dx += 2) for (let dy = -1; dy &lt; 2; dy += 2) { let x = piece.x + dx; let y = piece.y + dy; while (x &gt;= 0 &amp;&amp; x &lt; 8 &amp;&amp; y &gt;= 0 &amp;&amp; y &lt; 8) { const p = getPieceAt(x, y); if (p !== undefined) { if (p.color !== piece.color) validMoves.push([x, y, "#ff000055"]); break; } validMoves.push([x, y, "#0000ff55"]); x += dx; y += dy; } } break; case "Rook": for (let d = -1; d &lt; 2; d += 2) { let dx = d; let dy = 0; let x = piece.x + dx; let y = piece.y + dy; while (x &gt;= 0 &amp;&amp; x &lt; 8 &amp;&amp; y &gt;= 0 &amp;&amp; y &lt; 8) { const p = getPieceAt(x, y); if (p !== undefined) { if (p.color !== piece.color) validMoves.push([x, y, "#ff000055"]); break; } validMoves.push([x, y, "#0000ff55"]); x += dx; y += dy; } dx = 0; dy = d; x = piece.x + dx; y = piece.y + dy; while (x &gt;= 0 &amp;&amp; x &lt; 8 &amp;&amp; y &gt;= 0 &amp;&amp; y &lt; 8) { const p = getPieceAt(x, y); if (p !== undefined) { if (p.color !== piece.color) validMoves.push([x, y, "#ff000055"]); break; } validMoves.push([x, y, "#0000ff55"]); x += dx; y += dy; } } break; case "Queen": for (let dx = -1; dx &lt; 2; ++dx) for (let dy = -1; dy &lt; 2; ++dy) { let x = piece.x + dx; let y = piece.y + dy; while (x &gt;= 0 &amp;&amp; x &lt; 8 &amp;&amp; y &gt;= 0 &amp;&amp; y &lt; 8) { const p = getPieceAt(x, y); if (p !== undefined) { if (p.color !== piece.color) validMoves.push([x, y, "#ff000055"]); break; } validMoves.push([x, y, "#0000ff55"]); x += dx; y += dy; } } break; case "King": for (let dx = -1; dx &lt; 2; ++dx) for (let dy = -1; dy &lt; 2; ++dy) { const x = piece.x + dx; const y = piece.y + dy; const p = getPieceAt(x, y); if (p === undefined) validMoves.push([x, y, "#0000ff55"]); else if (p.color !== piece.color) validMoves.push([x, y, "#ff000055"]); } if (!piece.moved) { let left = getPieceAt(0, piece.y); let right = getPieceAt(7, piece.y); if (left !== undefined &amp;&amp; !left.moved &amp;&amp; getPieceAt(1, piece.y) === undefined &amp;&amp; getPieceAt(2, piece.y) === undefined &amp;&amp; getPieceAt(3, piece.y) === undefined) validMoves.push([piece.x - 2, piece.y, "#0000ff55"]) if (right !== undefined &amp;&amp; !right.moved &amp;&amp; getPieceAt(6, piece.y) === undefined &amp;&amp; getPieceAt(5, piece.y) === undefined) validMoves.push([piece.x + 2, piece.y, "#0000ff55"]) } break; } validMoves = validMoves.filter(m =&gt; m[0] &gt;= 0 &amp;&amp; m[0] &lt; 8 &amp;&amp; m[1] &gt;= 0 &amp;&amp; m[1] &lt; 8); return validMoves; } function getSquaresChecked(piece) { validMoves = getSquares(piece); for (const move of validMoves) { let x = piece.x; let y = piece.y; const index = pieces.findIndex(p =&gt; p.x === move[0] &amp;&amp; p.y === move[1]); let removed; if (index !== -1) removed = pieces.splice(index, 1)[0]; piece.moveTo(move[0], move[1]); if (inCheck()) move[2] = "rm"; else highlights[move[1]][move[0]] = move[2]; piece.moveTo(x, y); if (removed !== undefined) pieces.splice(index, 0, removed); } return validMoves.filter(a =&gt; a[2] !== "rm"); } function inCheck() { let king = pieces.find(p =&gt; p.type === "King" &amp;&amp; (p.color !== "White") === turn); if (king === undefined) return true; for (const piece of pieces) if (getSquares(piece).find(a =&gt; a[0] === king.x &amp;&amp; a[1] === king.y)) return true; return false; } function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); for (let x = 0; x &lt; 8; ++x) for (let y = 0; y &lt; 8; ++y) { ctx.fillStyle = tiles[y][x]; ctx.fillRect(x * sideSize, y * sideSize, sideSize, sideSize); ctx.fillStyle = highlights[y][x]; ctx.fillRect(x * sideSize, y * sideSize, sideSize, sideSize); } for (const piece of pieces) piece.draw(ctx); } function frame() { draw(); frameHandle = requestAnimationFrame(frame); } function reset() { pieces.splice(0, pieces.length); pieces.splice( 0, 0, Piece(0, 0, "Rook", "Black"), Piece(1, 0, "Knight", "Black"), Piece(2, 0, "Bishop", "Black"), Piece(3, 0, "Queen", "Black"), Piece(4, 0, "King", "Black"), Piece(5, 0, "Bishop", "Black"), Piece(6, 0, "Knight", "Black"), Piece(7, 0, "Rook", "Black"), Piece(0, 1, "Pawn", "Black"), Piece(1, 1, "Pawn", "Black"), Piece(2, 1, "Pawn", "Black"), Piece(3, 1, "Pawn", "Black"), Piece(4, 1, "Pawn", "Black"), Piece(5, 1, "Pawn", "Black"), Piece(6, 1, "Pawn", "Black"), Piece(7, 1, "Pawn", "Black"), Piece(0, 6, "Pawn", "White"), Piece(1, 6, "Pawn", "White"), Piece(2, 6, "Pawn", "White"), Piece(3, 6, "Pawn", "White"), Piece(4, 6, "Pawn", "White"), Piece(5, 6, "Pawn", "White"), Piece(6, 6, "Pawn", "White"), Piece(7, 6, "Pawn", "White"), Piece(0, 7, "Rook", "White"), Piece(1, 7, "Knight", "White"), Piece(2, 7, "Bishop", "White"), Piece(3, 7, "Queen", "White"), Piece(4, 7, "King", "White"), Piece(5, 7, "Bishop", "White"), Piece(6, 7, "Knight", "White"), Piece(7, 7, "Rook", "White") ); }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>html { height: 100%; display: grid; } body { margin: auto; } #messages { width: 64px; height: 64px; float: right; margin: 4px; color: red; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width"&gt; &lt;title&gt;Chess&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;canvas id="display"&gt;&lt;/canvas&gt; &lt;div id="messages"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>You could use an ENUM instead of a String for the type of piece.</p>\n\n<p>The colors (white/black \"#fff\"/\"#000\") should be declared as variables at the top, to make it easier to change.</p>\n\n<p>Try to avoid magic numbers / Strings. For example, why multiply by 0.9 here?</p>\n\n<pre><code>const size = Math.min(window.innerWidth, window.innerHeight) * 0.9;\n</code></pre>\n\n<p>You should use methods more often. Ensure your current method names make sense and are not doing too many things. If we wanted to add a rule, it's currently hard to tell where it should be added (<code>getSquares</code>).</p>\n\n<p>An example rule to add: Player must move king to avoid a checkmate (as in real chess).</p>\n\n<p>On a positive note I was surprised how well your game works, given the small amount of code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T15:39:50.550", "Id": "230849", "ParentId": "230826", "Score": "1" } } ]
{ "AcceptedAnswerId": "230849", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T11:21:50.230", "Id": "230826", "Score": "3", "Tags": [ "javascript", "canvas", "chess" ], "Title": "Chess game in JavaScript" }
230826
<p>I am using the code below trying to replicate the mobile phone feature that displays one or more contact names according to the numbers typed.</p> <p>This code is intended to be used on a JavaScript course I am teaching, so I try to keep it as simple as possible in order to walk the students through a possible scenario and the required steps to implement a solution programmatically.</p> <p>I would like to hear any suggestions for changes or comments before moving this example to class.</p> <p>Thank you very much!</p> <p>(You can find the full code, along with some pretty styling at this <a href="https://codepen.io/kostasx/pen/oNNLWre?editors=0011" rel="nofollow noreferrer">codepen link</a>) </p> <p><strong>HTML:</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;div class="tryout"&gt; &lt;p&gt;Numbers to try:&lt;/p&gt; &lt;p&gt;&lt;span&gt;&lt;/span&gt;&lt;/p&gt; &lt;/div&gt; &lt;div class="mobile"&gt; &lt;label for="number"&gt;Send SMS&lt;/label&gt; &lt;input type="text" id="number" name="number" placeholder="Enter telephone number"&gt; &lt;/div&gt; &lt;div class="found"&gt;&lt;/div&gt; </code></pre> <p><strong>JAVASCRIPT:</strong></p> <pre><code>const contacts = { kostas: 6986100100, maria: 6986100200, george: 6986300300, sofia: 6986300400, chris: 6987500500, marina: 6944600600 } const input = document.querySelector("#number"); const found = document.querySelector(".found"); input.addEventListener( "keyup", handleKeyUp ); function handleKeyUp( e ){ found.innerHTML = ""; Object.entries(contacts).map((contact)=&gt;{ let [ key, value ] = contact; let inputValue = e.target.value; value = String( value ); if ( value.indexOf( inputValue ) === 0 ){ found.innerHTML += ` &lt;p id="${key}"&gt; &lt;strong&gt;${key}&lt;/strong&gt;: ${value.replace( inputValue, `&lt;span&gt;${ inputValue }&lt;/span&gt;` )} &lt;/p&gt; `; } }) } </code></pre> <p>NOTES: Since this is intended for an audience of beginners, best practices, code organization and probably performance considerations are of great importance here.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T12:16:35.027", "Id": "449879", "Score": "1", "body": "Is this all in global scope? it depends how far down the rabbit hole you go with this, obviously having functions and variables in global scope is bad practice but this may not be something you tackle with beginners?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T13:09:15.993", "Id": "449897", "Score": "0", "body": "Yep, that is a nice addition @Magrangs. Will definitely update my code. I got to excited when I got the inspiration while I was texting a friend, so I ended up coding this without realizing I was in global scope. Thanks! :)" } ]
[ { "body": "<p>Here's a few suggestions:</p>\n\n<p>I would model the contacts list as an array of objects, like this:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const contacts = [\n { name: 'kostas', number: '6986100100' },\n { name: 'maria', number: '6986100200' },\n { name: 'george', number: '6986300300' },\n { name: 'sofia', number: '6986300400' },\n { name: 'chris', number: '6987500500' },\n { name: 'marine', number: '6944600600' }\n];\n</code></pre>\n\n<p>If you use your contacts' first name as object keys, you can't have two contacts with the same name. Moreover, if each contact is represented by an object, you can add additional information to the contact in the future. I would also write the phone numbers as a string, not a number, since phone numbers can contain non-digit characters (like <code>'+'</code>) or leading zeros.</p>\n\n<p>The search returns a list of corresponding contacts, so you might as well replace the results <code>div</code> with a list, a <code>&lt;ul class=\"found\"&gt;&lt;/ul&gt;</code> for example.</p>\n\n<p>Searching for and displaying the matches becomes easy now:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function handleKeyUp(e) {\n const inputValue = e.target.value.trim();\n\n if (inputValue) {\n found.innerHTML = contacts\n .filter(contact =&gt; contact.number.startsWith(inputValue))\n .map(\n contact =&gt;\n `&lt;li&gt;&lt;strong&gt;${contact.name}&lt;/strong&gt;: ${contact.number.replace(\n inputValue,\n `&lt;span&gt;${inputValue}&lt;/span&gt;`\n )}&lt;/li&gt;`\n )\n .join('');\n } else {\n found.innerHTML = '';\n }\n}\n</code></pre>\n\n<p>No need to convert the input value to a string, it's a string already. Notice how there's only one call to <code>found.innerHTML</code>. Your code updated the dom once for each found match, but dom operations are expensive and should be minimized.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T20:49:14.113", "Id": "230977", "ParentId": "230827", "Score": "2" } } ]
{ "AcceptedAnswerId": "230977", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T11:40:25.687", "Id": "230827", "Score": "1", "Tags": [ "javascript", "autocomplete" ], "Title": "Find mobile phone contact according to number typed" }
230827
<p>This is my solution for the MaxProductOfThree from codility, it scores 100%, but I'm not a fan of the <code>if if if</code> structure it has going on. </p> <blockquote> <p><strong><em>Task description</em></strong></p> <hr> <p>A non-empty array A consisting of N integers is given. The product of triplet (P, Q, R) equates to A[P] * A[Q] * A[R] (0 ≤ P &lt; Q &lt; R &lt; N).</p> <p>For example, array A such that:</p> <p><code>A[0] = -3 A[1] = 1 A[2] = 2 A[3] = -2 A[4] = 5 A[5] = 6</code> contains the following example triplets:</p> <p><code>(0, 1, 2)</code>, product is <code>−3 * 1 * 2 = −6 (1, 2, 4)</code>, product is <code>1 * 2 * 5 = 10</code> <code>(2, 4, 5)</code>, product is <code>2 * 5 * 6 = 60</code> Your goal is to find the maximal product of any triplet.</p> <p>Write a function:</p> <p><code>class Solution { public int solution(int[] A); }</code></p> <p>that, given a non-empty array A, returns the value of the maximal product of any triplet.</p> <p>For example, given array A such that:</p> <p><code>A[0] = -3 A[1] = 1 A[2] = 2 A[3] = -2 A[4] = 5 A[5] = 6</code> the function should return 60, as the product of triplet (2, 4, 5) is maximal.</p> <p>Write an efficient algorithm for the following assumptions:</p> <p>N is an integer within the range [3..100,000]; each element of array A is an integer within the range [−1,000..1,000].</p> </blockquote> <pre><code>using System; using System.Collections.Generic; using System.Linq; class Solution { public int solution(int[] A) { List&lt;int&gt; B = A.ToList(); int product = 1; int min1 = B.Min(); if (A.Length &gt; 3) { if (min1 &lt; 0) { B.RemoveAt(B.IndexOf(min1)); int min2 = B.Min(); if (min2 &lt; 0) { int max1 = B.Max(); if (A.Length == 4) { product = min1 * min2 * max1; } else { product = Math.Max(min1 * min2 * max1, getProductOfMaximalsForMoreThanTwoElements(B)); } } else { product = getProductOfMaximalsForMoreThanTwoElements(B); } } else { product = getProductOfMaximalsForMoreThanTwoElements(B); } } else { foreach (int element in B) { product *= element; } } return product; } private int getProductOfMaximalsForMoreThanTwoElements( List&lt;int&gt; B) { int max1 = B.Max(); B.RemoveAt(B.IndexOf(max1)); int max2 = B.Max(); B.RemoveAt(B.IndexOf(max2)); int max3 = B.Max(); return max1 * max2 * max3; } } </code></pre> <p>To be honest, the original idea was thought beforehand, but it took me a couple of tries until every test was passed, as with most of these exercises. Are there things to improve in terms of readability, logic and quality of this code?</p>
[]
[ { "body": "<p>This looks like a good attempt. Let's first start assuming we only have to deal with positive values. </p>\n\n<pre><code>private int getProductOfMaximalsForMoreThanTwoElements( List&lt;int&gt; B)\n{\n int max1 = B.Max();\n B.RemoveAt(B.IndexOf(max1));\n int max2 = B.Max();\n B.RemoveAt(B.IndexOf(max2));\n int max3 = B.Max();\n return max1 * max2 * max3;\n}\n</code></pre>\n\n<p>This method would provide the solution. So let's review it.</p>\n\n<p>Starting with a couple of style choices, method names in C# should be PascalCase. Additionally, the name of the method is vague. The method provides the product of the 3 biggest numbers: <code>GetProductOfTop3Numbers</code>.</p>\n\n<p><code>B.IndexOf(B.Max())</code> is doing unnecessary work. <code>Max</code> loops over the entire list to find the maximum value, and <code>IndexOf</code> does it all over again. That's a waste of effort. Sadly, <code>System.Linq</code> doesn't provide an <code>ArgMax</code> method, so we will have to spin our own:\"</p>\n\n<pre><code>public static int ArgMax(this IList&lt;int&gt; list) {\n var max = int.MinValue;\n var argmax = -1;\n var index = 0;\n foreach(var item in list) {\n if (item &gt; max) {\n max = item;\n argmax = index;\n }\n index++;\n }\n return argmax;\n}\n</code></pre>\n\n<p>Here, instead of looping through the list to find the maximum value, and then search the list for that value, we can just return the index we found that biggest value at. The max is then easily retrievable through <code>B[index]</code>.</p>\n\n<p>The act of searching the list for the max, and popping it can be its own method:</p>\n\n<pre><code>public static int PopMax(List&lt;int&gt; list)\n{\n var argmax = list.ArgMax();\n var max = list[argmax];\n list.RemoveAt(argmax);\n return max;\n}\n</code></pre>\n\n<p>Our initial method would then be:</p>\n\n<pre><code>private static int GetProductOfTop3Numbers(List&lt;int&gt; list) {\n var product = 1;\n product *= PopMax(list);\n product *= PopMax(list);\n product *= PopMax(list);\n return product;\n}\n</code></pre>\n\n<p>Or, more generic:</p>\n\n<pre><code>private static int GetProductOfTopNNumbers(List&lt;int&gt; list, int n) {\n var product = 1;\n for(var times = 0; times &lt; n; times++) {\n product *= PopMax(list);\n }\n return product;\n}\n</code></pre>\n\n<hr>\n\n<p>Now let's return to the actual problem: negative numbers. This is what caused you problems introducing a bunch of if-statements. Let's see if we can find something for that.</p>\n\n<p>We want the highest possible product. If we simply take the top 3 items from the list, we might risk missing out on very negative numbers. Take for instance the list <code>new [] { -5, -5, -3, -1, 0, 1, 2, 3 }</code>. In this case, the naive solution would be <code>1 * 2 * 3</code>, but actually <code>-5 * -5 * 3</code> has a bigger product. Note that if we consider negative numbers in our solution, it will always have to be a pair of negative numbers, to cancel out the <code>-</code> signs. </p>\n\n<p>This pair would then always be the two lowest entries in the list. The two most negative numbers together should provide the biggest product out of all negative numbers. The product of these can then be compared to the product of the biggest numbers, to decide which of the two sets to pick.</p>\n\n<p>Furthermore, because we will never take 3 negative numbers (because the product would be negative), we can freely take the biggest number in the list. Should this number also be negative (because the input only consists of negative numbers), this is fine as well, because it would then be the least negative number, which still would result in the biggest product.</p>\n\n<p>So, to recap:</p>\n\n<ol>\n<li>Take the biggest number</li>\n<li>Take the next two biggest numbers, or take the next two smallest numbers</li>\n<li>Check which together has the biggest product</li>\n<li>Done</li>\n</ol>\n\n<p>For the mins, we need to provide a similar <code>ArgMin</code> and <code>PopMin</code> implementations. Also realise that simultaneously popping items from the list at both ends might cause troubles if this list is very short, so be sure to copy the list:</p>\n\n<pre><code>private static int GetProductOfTopNNumbers(List&lt;int&gt; list, int n) {\n var copiedList = new List&lt;int&gt;(list);\n var product = 1;\n for(var times = 0; times &lt; n; times++) {\n product *= PopMax(copiedList);\n }\n return product;\n}\n</code></pre>\n\n<p>All in all, that leaves us with:</p>\n\n<pre><code>public int Solution(int[] A) {\n var list = A.ToList();\n var max = PopMax(list);\n return Math.Max(max * GetProductOfMinNNumbers(list, 2), max * GetProductOfTopNNumbers(list, 2));\n}\n\npublic static int ArgMin(this IList&lt;int&gt; list)\n{\n var min = int.MaxValue;\n var argmin = -1;\n var index = 0;\n foreach (var item in list)\n {\n if (item &lt; min)\n {\n min = item;\n argmin = index;\n }\n index++;\n }\n return argmin;\n}\n\npublic static int PopMin(List&lt;int&gt; list)\n{\n var argmin = list.ArgMin();\n var min = list[argmin];\n list.RemoveAt(argmin);\n return min;\n}\n\nprivate static int GetProductOfMinNNumbers(List&lt;int&gt; list, int n)\n{\n var copiedList = new List&lt;int&gt;(list);\n var product = 1;\n for (var times = 0; times &lt; n; times++)\n {\n product *= PopMin(copiedList);\n }\n return product;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-28T12:21:23.440", "Id": "451342", "Score": "0", "body": "Sorry for the delay. Great, and very detailed explanation. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T12:46:34.490", "Id": "230836", "ParentId": "230828", "Score": "1" } }, { "body": "<p>Since its multiplication, the largest possible product could only be produced by multiplying the largest numbers in the array. However, negative numbers introduce a problem, as a product of 2 negative numbers with a positive one would end up being positive too. Hence, we need to consider both cases in our solution. I would like to propose the following solution to this problem:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Solution {\n public int solution(int[] A) \n {\n Array.Sort(A); // Simple sort of the array\n int len = A.Length;\n int end = A[len - 1] * A[len - 2] * A[len - 3]; // Find the largest product of positive numbers\n int start = A[0] * A[1] * A[len - 1]; // Find the largest product, assuming 2 negative numbers\n\n return (start &gt; end) ? start : end;\n }\n}\n</code></pre>\n\n<p>In this code, we first calculate the first case, since the last 3 indices should contain the largest integers in the list, resulting in the highest product. We then calculate the second case, taking the largest number and the 2 smallest ones, which should produce a positive product if the largest number is positive and the 2 smallest are negative. Finally, we take the larger of the 2.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-24T07:45:22.223", "Id": "231246", "ParentId": "230828", "Score": "1" } } ]
{ "AcceptedAnswerId": "230836", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T11:42:31.547", "Id": "230828", "Score": "1", "Tags": [ "c#", "performance", "beginner", "array", "combinatorics" ], "Title": "MaxProductOfThree in C#" }
230828
<p>I need to add an offset to a time variable inside my class. The code below works, how do i make it more efficient, and elegant. </p> <pre><code>#include &lt;array&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; class Pressure { public: Pressure(int date, int time):m_date(date),m_time(time) { } int GetDate() { return m_date; } int GetTime() { return m_time; } void AddTime(int val) { m_time += val; } private: int m_date; int m_time; }; int main() { std::vector&lt;Pressure&gt; p; // populate the vector with values. for(int i=0; i &lt; 10; i++) { Pressure x(i,i); p.push_back(x); } int offset = 20000; // add the offset for(int i=0; i &lt; 10; i++) { p[i].AddTime(offset); } // display the data for(int i=0; i &lt; 10; i++) { std::cout &lt;&lt; p[i].GetDate() &lt;&lt; " " &lt;&lt; p[i].GetTime() &lt;&lt; "\n"; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T12:31:53.140", "Id": "449884", "Score": "1", "body": "This sounds like an XY problem. Which is going to be difficult to help with unless when know the actual problem you are trying to optimize for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T12:36:59.887", "Id": "449886", "Score": "0", "body": "there is probably a one liner way using stl to add a data of type T to a member variable of a class stored in a vector." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T12:57:56.540", "Id": "449893", "Score": "2", "body": "What are the units and valid ranges of date and time here? There are no clues in the class nor in the test program, so it's virtually impossible to review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T13:00:35.790", "Id": "449895", "Score": "0", "body": "its just seconds since epoch represented as int." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T13:59:20.977", "Id": "449911", "Score": "0", "body": "Do you mean that days is number of days since some epoch, and that time is number of seconds in range 0-86400? (Where 86400 is used only when there's a leap second). Are we supposed to carry to the day field when the seconds overflows that range? I don't see code to do that, and it's not clear what the requirements are." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T15:28:40.433", "Id": "449925", "Score": "0", "body": "i'm actually using this library https://github.com/HowardHinnant/date in another function. the only thing the program above does it generates a vector of class pressure and adds an offset to the time field, and display the result." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T18:27:48.623", "Id": "449948", "Score": "0", "body": "Why not just use [`std::time_point` `operator+=`](https://en.cppreference.com/w/cpp/chrono/time_point/operator_arith)?" } ]
[ { "body": "<p>You could use a range-based for loop and push_back( Pressure(i,i) ).</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n\nclass Pressure {\npublic:\n Pressure(int date, int time) : m_date(date), m_time(time) {\n\n }\n\n int GetDate() const {\n return m_date;\n }\n\n int GetTime() const {\n return m_time;\n }\n\n void AddTime(int val) {\n m_time += val;\n }\nprivate:\n int m_date;\n int m_time;\n};\n\nint main() {\n std::vector&lt;Pressure&gt; p;\n\n // populate the vector with values.\n p.reserve(10); // you can reserve space if you know the size ahead of time to prevent extra reallocations, but it isnt necessary for a vector this small.\n for(int i = 0; i &lt; 10; ++i) {\n p.push_back( Pressure(i,i) );\n }\n\n for(Pressure&amp; pressure : p) {\n // add offset\n pressure.AddTime(20000);\n\n // display data\n std::cout &lt;&lt; pressure.GetDate() &lt;&lt; \" \" &lt;&lt; pressure.GetTime() &lt;&lt; \"\\n\";\n }\n\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T13:46:29.400", "Id": "230843", "ParentId": "230831", "Score": "3" } } ]
{ "AcceptedAnswerId": "230843", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T12:29:18.960", "Id": "230831", "Score": "1", "Tags": [ "c++" ], "Title": "Elegant way to add a value to a member variable inside a vector" }
230831
<p>This is my first implementation of a "container" using the Rule of Five, any feedback I'll gladly accept. I've tried to make it as Exception-Safe as possible. I've made it for an assignment.</p> <p>Header</p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &lt;ostream&gt; #include "Vector.h" class String { public: String(); String(char _char); String(const char* _string); //Copy Constructor String(const String&amp; _string); //Move Constructor String(String&amp;&amp; _string) noexcept; ~String(); void reset(); size_t length() const; char* asCString() const; //Cast to const char operator const char* () const; //Bracket Operator overloads char operator[](int _index) const; char&amp; operator[](int _index); //Compare bool operator==(const String&amp; _other) const; bool operator==(const char* _chars) const; //Copy Assignment Operator String&amp; operator=(const String&amp; _other); //Move Assignment Operator String&amp; operator=(String&amp;&amp; _other) noexcept; //Add Operators String&amp; operator+=(const String&amp; _other); String&amp; operator+=(const char* _other); String operator+(const String&amp; _other) const; String operator+(const char* _other) const; //Stream Operator friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; _os, const String&amp; _string); Vector&lt;String&gt; split(const char _delimiter); void replace(const char _target, const char _replacement); void removeCharacter(char _target); String toLowerCase() const; private: unsigned int m_length; char* m_string; }; </code></pre> <p>CPP File</p> <pre class="lang-cpp prettyprint-override"><code>#include "stdafx.h" #include "String.h" #include &lt;cstring&gt; #include &lt;stdexcept&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; String::String() : m_length(0), m_string() { m_string = new char[1]; m_string[0] = '\0'; } String::String(char _char) : m_length(1) { m_string = new char[2]; m_string[0] = _char; m_string[1] = '\0'; } String::String(const char* _string) { if(!_string) { m_length = 0; m_string = new char[0]; } else { m_length = strlen(_string); m_string = new char[m_length + 1]; std::copy(_string, _string + m_length, m_string); m_string[m_length] = '\0'; } } String::String(const String&amp; _string) { char* buffer = new char[_string.m_length + 1]; std::copy(_string.m_string, _string.m_string + _string.m_length, buffer); buffer[_string.m_length] = '\0'; m_string = buffer; m_length = _string.m_length; } String::String(String&amp;&amp; _string) noexcept { const auto buffer = _string.m_string; m_length = _string.m_length; m_string = buffer; _string.reset(); } String::~String() { delete[] m_string; m_string = nullptr; } void String::reset() { m_length = 0; m_string = nullptr; } size_t String::length() const { return m_length; } char* String::asCString() const { return m_string; } String::operator const char*() const { return m_string; } char String::operator[](int _index) const { if(_index &lt; 0 || _index &gt;= m_length) { throw std::out_of_range("String index out of bounds!"); } return m_string[_index]; } char&amp; String::operator[](int _index) { if (_index &lt; 0 || _index &gt;= m_length) { throw std::out_of_range("String index out of bounds!"); } return m_string[_index]; } bool String::operator==(const String&amp; _other) const { if (!_other.m_string) return false; return strcmp(m_string, _other.m_string) == 0; } bool String::operator==(const char* _chars) const { if (!_chars) return false; return strcmp(m_string, _chars) == 0; } String&amp; String::operator=(const String&amp; _other) { if (this != &amp;_other) { char* buffer = new char[_other.m_length + 1]; std::copy(_other.m_string, _other.m_string + _other.m_length + 1, buffer); std::swap(buffer, m_string); m_length = _other.m_length; delete[] buffer; } return *this; } String&amp; String::operator=(String&amp;&amp; _other) noexcept { if (this != &amp;_other) { const auto buffer = _other.m_string; delete[] m_string; m_string = buffer; m_length = _other.m_length; _other.reset(); } return *this; } String&amp; String::operator+=(const String&amp; _other) { if (this != &amp;_other) { auto totalLength = m_length + _other.m_length; char* buffer = new char[totalLength + 1]; std::copy(m_string, m_string + m_length, buffer); std::copy(_other.m_string, _other.m_string + _other.m_length, buffer + m_length); buffer[totalLength] = '\0'; std::swap(m_string, buffer); m_length = totalLength; delete[] buffer; } return *this; } String&amp; String::operator+=(const char* _other) { const auto charLength = strlen(_other); const auto totalLength = m_length + charLength; char* buffer = new char[totalLength + 1]; std::copy(m_string, m_string + m_length, buffer); std::copy(_other, _other + charLength, buffer + m_length); buffer[totalLength] = '\0'; std::swap(m_string, buffer); m_length = totalLength; delete[] buffer; return *this; } String String::operator+(const String&amp; _other) const { const auto totalLength = m_length + _other.m_length; char* buffer = new char[totalLength + 1]; std::copy(m_string, m_string + m_length, buffer); std::copy(_other.m_string, _other.m_string + _other.m_length, buffer + m_length); buffer[totalLength] = '\0'; return String(buffer); } String String::operator+(const char* _other) const { const auto charLength = strlen(_other); const auto totalLength = m_length + charLength; char* buffer = new char[totalLength + 1]; std::copy(m_string, m_string + m_length, buffer); std::copy(_other, _other + charLength, buffer + m_length); buffer[totalLength] = '\0'; return String(buffer); } std::ostream&amp; operator&lt;&lt;(std::ostream&amp; _os, const String&amp; _string) { _os &lt;&lt; _string.m_string; return _os; } Vector&lt;String&gt; String::split(const char _delimiter) { Vector&lt;String&gt; result; char* t; char* pch = strtok_s(m_string, &amp;_delimiter, &amp;t); while (pch != nullptr) { result.push(String{ pch }); pch = strtok_s(nullptr, &amp;_delimiter, &amp;t); } return result; } void String::replace(const char _target, const char _replacement) { for (int i = 0; i &lt; m_length; i++) { if (m_string[i] == _target) { if (_replacement == 0) { removeCharacter(_target); } else { m_string[i] = _replacement; } } } } void String::removeCharacter(char _target) { auto newEnd = std::remove(m_string, m_string + m_length, ' '); *newEnd = '\0'; } String String::toLowerCase() const { String buffer = *this; for (int i = 0; i &lt; m_length; i++) { buffer[i] = tolower(buffer[i]); } return buffer; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T17:25:28.053", "Id": "449941", "Score": "0", "body": "Variable names starting with `_` are reserved for compiler implementation and should be avoided." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T15:37:26.767", "Id": "450232", "Score": "0", "body": "@super Only if followed by an uppercase letter. Or containing a double underscore." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T17:48:34.117", "Id": "450240", "Score": "0", "body": "@Deduplicator You're right. Unless it's in the global namespace. But that doesn't apply to the usage in this example, so this is actually fine then I guess. Thx." } ]
[ { "body": "<p>Here's some suggestions:</p>\n\n<h1>Header</h1>\n\n<ul>\n<li><p><code>#include &lt;ostream&gt;</code> incurs a lot of overhead. You do not need the whole <code>std::ostream</code> in the header. <code>#include &lt;iosfwd&gt;</code> is enough.</p></li>\n<li><p>It's <code>std::size_t</code>, not <code>size_t</code>. Also, you forgot to <code>#include &lt;cstddef&gt;</code>.</p></li>\n<li><p><code>asCString</code> fails to propagate <code>const</code>.</p></li>\n<li><p>Not being implicitly convertible to <code>const char*</code> is one of the basic benefits of proper containers over raw arrays. Use a named function like <code>c_str</code> instead.</p></li>\n<li><p>Consistently use <code>std::size_t</code> for indexes. Right now, you are mixing it with <code>int</code> and <code>unsigned int</code>.</p></li>\n<li><p><code>operator==</code> and <code>operator+</code> should be non-members.</p></li>\n<li><p><code>operator&lt;&lt;</code> does not need to be a friend; just declare it as a free function.</p></li>\n<li><p>Do not add top-level <code>const</code> to function parameters.</p></li>\n<li><p>The copy and move assignment operators should be merged into one; see below.</p></li>\n</ul>\n\n<h1>Implementation</h1>\n\n<ul>\n<li><p>Sort the <code>#include</code>s.</p></li>\n<li><p>The constructors are written in a very convoluted way. Use in-class member initializers to make sure you don't accidentally leave the members uninitialized:</p>\n\n<pre><code>class String {\n // ...\n std::size_t m_length{};\n char* m_string{};\n};\n</code></pre>\n\n<p>And simplify the constructors:</p>\n\n<pre><code>String::String()\n : m_length{0}, m_string{new char[1]{}}\n{\n}\n\nString::String(char c)\n : m_length{1}, m_string{new char[2]{c}}\n{\n}\n\nString::String(const String&amp; other)\n : m_length{other.m_length}, m_string{new char[m_length + 1]}\n{\n std::copy_n(other.m_string, m_length, m_string);\n m_string[m_length] = '\\0';\n}\n</code></pre></li>\n<li><p>Use <a href=\"https://stackoverflow.com/q/3279543\">copy-and-swap</a>:</p>\n\n<pre><code>String::String(String&amp;&amp; other) noexcept\n : String{}\n{\n swap(*this, other);\n}\n\n// take by value\nString&amp; operator=(String other) noexcept\n{\n swap(*this, other);\n return *this;\n}\n\n// in the class body\nfriend void swap(String&amp; lhs, String&amp; rhs) noexcept\n{\n using std::swap;\n swap(lhs.m_length, rhs.m_length);\n swap(lhs.m_string, rhs.m_string);\n}\n</code></pre></li>\n<li><p>The destructor should not set the pointer to null after <code>delete</code>ing it.</p></li>\n<li><p>Currently, there are two \"empty\" states: <code>m_length = 0, m_string = 0</code> and <code>m_length = 1, m_string = new char[1]{}</code>. The first is the <em>moved-from state</em>, whereas the second is the <em>empty string</em>. Moved-from objects are placed in a \"valid but otherwise unspecified state,\" so the only operations they should support are destruction and assignment. Therefore:</p>\n\n<ul>\n<li><p>If you want to support <code>String{nullptr}</code>, then it should be an empty string. Otherwise, just require a non-null pointer:</p>\n\n<pre><code>String::String(const char* str)\n : m_length{std::strlen(str)} // note: 'std::strlen' not 'strlen'\n , m_string{new char[m_length]}\n{\n std::copy_n(str, m_length + 1, m_string); // use 'std::copy_n'; also copy the '\\0'\n}\n</code></pre></li>\n<li><p>If I understand correctly, <code>reset</code> means <code>clear</code>. Then, it should result in an empty string.</p></li>\n<li><p>Don't check for <code>if (!_other.m_string)</code>.</p></li>\n</ul></li>\n<li><p><code>strcmp</code> is not efficient when you know the length of both strings. Use <code>std::equal</code> instead:</p>\n\n<pre><code>// non-member operator==, requires appropriate declaration\nbool operator==(const String&amp; lhs, const String&amp; rhs) noexcept\n{\n // see below for begin and end\n return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());\n}\n\nbool operator!=(const String&amp; lhs, const String&amp; rhs) noexcept\n{\n return !(lhs == rhs);\n}\n</code></pre></li>\n<li><p>The way <code>operator+=</code> handles self assignment is wrong &mdash; <code>str += str</code> is obviously not a no-op. In fact, this is one of the rare cases where I would suggest that <code>operator+=</code> delegate to <code>operator+</code>:</p>\n\n<pre><code>// friend operator+, requires appropriate declaration\nfriend String operator+(const String&amp; lhs, const String&amp; rhs)\n{\n String result;\n result.m_length = lhs.m_length + rhs.m_length;\n result.m_string = new char[result.m_length + 1];\n\n auto p = std::copy_n(lhs.m_string, lhs.m_length, result.m_length);\n std::copy_n(rhs.m_string, rhs.m_length + 1, p); // copy the '\\0'\n\n return result;\n}\n\nString&amp; String::operator+=(const String&amp; other)\n{\n *this = *this + other;\n return *this;\n}\n</code></pre></li>\n</ul>\n\n\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T11:39:31.667", "Id": "230993", "ParentId": "230834", "Score": "4" } }, { "body": "<p>I. You don't reserve space. Imagine a situation when you need to append a vector of strings of known sizes. You reallocate buffer, and copy its current contents together with appended suffix for each of those. Thus, if you add N small strings of size m each, the whole algorithm runs in N², possibly leaving the heap fragmented heavily.</p>\n\n<p>One typical strategy would be to reserve space growing logarithmically; this makes appending amortized linear.</p>\n\n<p>Even without large amount of rhs operands, when you append a small string to a large one 99% of method runtime is spent on copying the lhs contents.</p>\n\n<p>II. Member <code>operator+</code> probably deserves ref-qualification. <code>operator+() const &amp;&amp;</code> can simply reuse this object's space (well, if it's reserved).</p>\n\n<p>III. Note that <code>remove_character</code> can effectively reduce string's length in the meantime leaving it in the same buffer (so you get an implicit reserved space you can't even benefit from).</p>\n\n<p>IV. <code>reset()</code> makes the buffer leak. If it was introduced for the sole purpose of being used in move construction/assignment it should be made <code>private</code>.</p>\n\n<p>V. You're using functions for trailing zero strings so don't consider cases when <code>String</code>s have zero characters inside: in your current implementation, <code>String(\"123\\000abc\")</code> is equal to <code>String(\"123\\000def\")</code>. If it is as intended, perhaps a check in the ctor would make sense.</p>\n\n<p>Bonus. Identifiers starting with underscores. Not that it was illegal but personally I wouldn't name them this way.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T12:47:44.443", "Id": "230997", "ParentId": "230834", "Score": "3" } }, { "body": "<ol>\n<li><p>Use <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view\" rel=\"nofollow noreferrer\"><code>std::string_view</code></a> to simplify your code, avoid expensive temporaries, and to make your custom string-type more usable.</p>\n</li>\n<li><p>You have three empty states: (0, nullptr), (0, length-zero-array), (1, length-one-array). Standardize to simplify.</p>\n<p>One option to remove special cases and still have noexcept-move-ctor would be using (0, static empty string) for all empty strings.</p>\n</li>\n<li><p>Wherever you don't have a good reason to deviate from it, keep to the interface of <a href=\"https://en.cppreference.com/w/cpp/string/basic_string\" rel=\"nofollow noreferrer\"><code>std::string</code></a>. Demonstrating your individuality here just hurts everyone.</p>\n</li>\n<li><p>Implicitly casting to pointer to constant string is inadvisable. Provide the standard accessors for that instead (<code>.begin()</code>, <code>.cbegin()</code>, <code>.data()</code>, <code>.cdata()</code>, <code>.c_str()</code>, and so on. Yes, a lot of them are redundant, though were not when introduced, or had to be added anyway for conformance to common interfaces.</p>\n</li>\n<li><p>If there is no good reason to make something a member, desist. The same for <code>friend</code>. Encapsulation works best when it is actually followed where it's easy enough.</p>\n</li>\n<li><p>Using in-class-initializers, ctor-init-list and delegation allows you to simplify your code and avoid errors.</p>\n</li>\n<li><p>Range-checking is unexpectedly expensive for <code>.operator[]()</code>. That's what <code>.at()</code> is for.</p>\n</li>\n<li><p>Make self-assignment safe without explicit check. Yes, that case will be more expensive, but pessimizing the common path really hurts.</p>\n</li>\n<li><p>If you copy a null terminated string, and the result should also be null terminated, copy the terminator too. Setting it separately afterwards is worse in any respect.</p>\n</li>\n<li><p>Your implementation of <code>.replace()</code> is quadratic when the replacement is <code>\\0</code>. It should be linear. Anyway, why is your string-type not zero-clean?</p>\n</li>\n<li><p>Best get into the habit of preferring <code>++var</code> over <code>var++</code> when you don't need the value. It is more efficient for more complex types.</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T05:47:52.487", "Id": "450269", "Score": "0", "body": "The empty state is a bit tough because move should be `noexcept`. Maybe we have to support both (0, nullptr) and (0, new char[1])." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T14:16:49.900", "Id": "450289", "Score": "0", "body": "@L.F. Better keep special-casing to allocation and deallocation of empty strings, and only that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T20:46:21.610", "Id": "231020", "ParentId": "230834", "Score": "3" } } ]
{ "AcceptedAnswerId": "230993", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T12:39:01.500", "Id": "230834", "Score": "4", "Tags": [ "c++", "strings", "homework", "stl" ], "Title": "A custom String class implementation" }
230834
<p>I'm currently taking my first class for c++ and our current lab is asking us to:</p> <ul> <li>declare an array with a maximum of 100 integer</li> <li>display total of all the scores</li> <li>display the average of scores entered</li> <li>have a negative as a sentinel since the scores all will be positive (the sentinel is -1)</li> </ul> <p>afterwards We're then supposed to display the entered scores in descending order.</p> <p>What I currently have is this:</p> <hr> <pre><code>#include &lt;iomanip&gt; #include &lt;iostream&gt; using namespace std; void header(); int main() { const int number = 100; // total number of allocated array inputs. int myArray[number], //array set counter = 0; // current array input number (1~100) double total = 0, // total for all scores added up average; // the average point for the scores. header(); // for calling title and description. cout &lt;&lt; "Please enter the test scores you recieved." &lt;&lt; endl; cout &lt;&lt; "Once all scores are in, enter -1 to end input" &lt;&lt; endl &lt;&lt; endl; while (cin &gt;&gt; myArray[counter] &amp;&amp; myArray[counter] != -1) { total += myArray[counter]; // adds all inputs for grand total. counter++; average = total / counter; // grand total / number of input } cout &lt;&lt; "The total for all the scores is " &lt;&lt; total &lt;&lt; endl; cout &lt;&lt; endl &lt;&lt; "Average score is " &lt;&lt; fixed &lt;&lt; average &lt;&lt; endl; cout &lt;&lt; endl &lt;&lt; "Program ending, shutting down." &lt;&lt; endl; return 0; } void header() // simple header for lab description. { cout &lt;&lt; "***********************************" &lt;&lt; endl; cout &lt;&lt; "Lab 7:score array " &lt;&lt; endl; cout &lt;&lt; "Programmed by: ~~~ " &lt;&lt; endl; cout &lt;&lt; "This array will allow the user to enter up to 100 test scores," &lt;&lt; endl; cout &lt;&lt; "Show the total for the the inputted scores, and display the average score rounded." &lt;&lt; endl; cout &lt;&lt; "***********************************" &lt;&lt; endl &lt;&lt; endl; } </code></pre> <p>It works for the most part, but think that the while loop is probably wrong.</p> <p>Am I on the right track or is this a mess?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T12:54:41.330", "Id": "449890", "Score": "1", "body": "My apologies, though I had to only provide a little bit of it. I'll edit the post with the complete code I have written so far." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T13:16:47.860", "Id": "449904", "Score": "0", "body": "Post the complete code not fragments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T14:52:27.837", "Id": "449917", "Score": "0", "body": "The code seems to be complete now and I have retracted my VTC based on LCC. It might be best if you altered the title to just say what the code does and removed `Am I on the right track`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T17:09:04.903", "Id": "449939", "Score": "0", "body": "What do you mean it works for the most part? What about it is not working? Looks alright to me." } ]
[ { "body": "<h2>Avoid Using Namespace <code>std</code></h2>\n\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). 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<h2>Variable Naming</h2>\n\n<p>Use descriptive variable names so the code is more meaningful and comments are not as necessary, some examples</p>\n\n<p>Current name: Suggested name<br>\nnumber : maxTestScores<br>\nmyArray : testScores </p>\n\n<p>Not currently in code<br>\nendTestScoresList : -1 (make -1 a symbolic constant like <code>number</code> is).</p>\n\n<h2>Variable Declarations</h2>\n\n<p>A good programming habit to get into is to put each variable declaration in a separate statement on a separate line. Instead of </p>\n\n<pre><code> int myArray[number], //array set\n counter = 0; // current array input number (1~100)\n double total = 0, // total for all scores added up\n average; // the average point for the scores.\n</code></pre>\n\n<p>it would be better the following way because it is easier to add or delete a variable and it is easier to read and maintain the code.</p>\n\n<pre><code> int myArray[number];\n int counter = 0;\n double total = 0;\n double average = 0;\n</code></pre>\n\n<p>In C++ it is also a good habit to initialize all the variables. </p>\n\n<h2>Move Loop Invariants out of the Loop</h2>\n\n<p>In the following code the variable <code>average</code> is a loop invariant and should not be calculated within the loop. Optimizing compilers may do this for you, but it is better to remove things that don't belong in the loop.</p>\n\n<pre><code> while (std::cin &gt;&gt; myArray[counter] &amp;&amp; myArray[counter] != -1)\n {\n total += myArray[counter]; // adds all inputs for grand total.\n counter++;\n average = total / counter; // grand total / number of input\n }\n</code></pre>\n\n<p>would be better as </p>\n\n<pre><code> while (std::cin &gt;&gt; myArray[counter] &amp;&amp; myArray[counter] != -1)\n {\n total += myArray[counter]; // adds all inputs for grand total.\n counter++;\n }\n\n average = total / counter; // grand total / number of input\n</code></pre>\n\n<h2>Possible Bug</h2>\n\n<p>As was observed in another answer, if the user entered more than 100 test scores the previous code could throw an <code>index out of range error</code> and the program would crash. Rather than user a for loop as shown in the other answer, the code could be modified to test the index in the while loop:</p>\n\n<pre><code> while ((counter &lt; number) &amp;&amp; std::cin &gt;&gt; myArray[counter] &amp;&amp; myArray[counter] != -1)\n {\n total += myArray[counter++]; // adds all inputs for grand total.\n }\n\n average = total / counter; // grand total / number of input\n</code></pre>\n\n<p>By putting the test <code>(counter &lt; number)</code> first the std::cin will not be called and the loop will exit, preventing the out of range problem.</p>\n\n<h2>Complexity</h2>\n\n<p>The function <code>main()</code> is too complex (does too much). As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n\n<blockquote>\n <p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n\n<p>There are at least 3 possible additional functions that can be called from <code>main()</code>.<br>\n - Get the user input<br>\n - Calculate and print the total and average<br>\n - List the scores in decsending order </p>\n\n<p>By reducing the complexity the code becomes easier to read, write, modify and debug.</p>\n\n<h2>Prefer '\\n' Over std::endl.</h2>\n\n<p>As mentioned in another review <code>std::endl</code> calls a system function to flush the output buffer. Sometimes this is needed, but generally to improve performance <code>std::endl</code> isn't called. It might be called after a loop of <code>std::cout</code> has been completed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T18:42:20.167", "Id": "450064", "Score": "1", "body": "Since this is a plain array, there would likely be nothing that \"throws\" an `index out of range error` (at least on linux). Nothing will stop you from writing happily beyond the end of the array, maybe even for quite some time, until a segmentation fault occurs ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T19:15:13.817", "Id": "450066", "Score": "1", "body": "True, of course I meant to mention std::array as a replacement for the C style array. FYI, back in the 80's on SunOS 1.1 you could actually force a reboot this way the stack eventually got over written." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T19:06:11.387", "Id": "230869", "ParentId": "230835", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T12:40:09.220", "Id": "230835", "Score": "5", "Tags": [ "c++" ], "Title": "Displaying the total and average for an array input" }
230835
<p>For university, we have just started to learn C++ as a language, and one of our challenges to do in our spare time is to write an algorithm for <a href="https://en.wikipedia.org/wiki/Ancient_Egyptian_multiplication" rel="nofollow noreferrer">'Peasant multiplication'</a>. In the challenge, we have been told that we cannot use the multiplication operator <code>*</code>. </p> <p>My code for it is as follows.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;cmath&gt; #include &lt;string&gt; #include &lt;limits&gt; using namespace std; vector&lt;int&gt; half(float numberToHalf) { vector&lt;int&gt; steps; while (numberToHalf != 1) { steps.push_back(numberToHalf); numberToHalf = floorf(numberToHalf / 2); } steps.push_back(1); return steps; } vector&lt;int&gt; repeatedDouble(int number, int limit) { vector&lt;int&gt; doubleList; for (int i = 0; i &lt; limit; i++) { doubleList.push_back(number); number += number; } return doubleList; } int adding(vector&lt;int&gt; halfList, vector&lt;int&gt; doubleList) { int total = 0; for (int i = 0; i &lt; halfList.size(); i++) { if (halfList[i] % 2 != 0) { total += doubleList[i]; } } return total; } int verify(string timeRound) { bool roundAgain = true; int number; do { cout &lt;&lt; "Enter the " &lt;&lt; timeRound &lt;&lt; " number: " &lt;&lt; endl; cin &gt;&gt; number; if(cin.good() &amp;&amp; 0 &lt; number) { //if number entered is positive and an integer roundAgain = false; }else { //Make cin ready to take another input cin.clear(); cin.ignore(numeric_limits&lt;streamsize&gt;::max(),'\n'); //Snippet taken from https://stackoverflow.com/questions/16934183/integer-validation-for-input cout &lt;&lt; "A valid input is a POSITIVE, whole, number. No letters, words, or negatives" &lt;&lt; endl; } } while (roundAgain); return number; } int main() { int num1 = verify("First"); int num2 = verify("Second"); vector&lt;int&gt; halved = half(num1); vector&lt;int&gt; doubled = repeatedDouble(num2, halved.size()); cout &lt;&lt; "The result is: " &lt;&lt; adding(halved, doubled); } </code></pre> <p>Any help in optimising the code to make it look and run even better would be appreciated! Also, if any of you could give some tips for robustness or similar that would be great too! </p> <p>I am completely new to C++ so any tricks and tips from experienced coders would be amazing!</p>
[]
[ { "body": "<p>It looks to me that you're being too literal. When trying to convert an analog process to code it's easy to fall into that trap.</p>\n\n<p>Presently you're using 2 loops to make 2 lists. This is unnecessary. You can do everything including calculate the answer in one loop.</p>\n\n<p>You're also not checking for which number is the lesser one and which is the greater one. This is integral to the base algorithm, that you're trying to emulate.</p>\n\n<p>A simplified version could look something like this:</p>\n\n<pre><code>int PeasantMultiply(int num1, int num2)\n{\n auto pair = std::minmax(num1, num2);\n int min = pair.first;\n int max = pair.second;\n int total = 0;\n if (min != 0)\n {\n do\n {\n if (min % 2 == 1)\n {\n total += max;\n }\n min /= 2;\n max += max;\n } while (min &gt; 0);\n }\n return total;\n}\n</code></pre>\n\n<p>After looking at this code again, I came upon an optimization. Instead of using the modulus operator(<code>%</code>), I could accomplish the same thing with and extra int variable and use subtraction instead:</p>\n\n<pre><code>int PeasantMultiply(int num1, int num2)\n{\n auto pair = std::minmax(num1, num2);\n int oldMin = pair.first;\n int max = pair.second;\n int total = 0;\n int newMin = 0;\n if (oldMin != 0)\n {\n do\n {\n newMin = oldMin / 2;\n if (oldMin - newMin != newMin)\n {\n total += max;\n }\n oldMin = newMin;\n max += max;\n } while (oldMin &gt; 0);\n }\n return total;\n}\n</code></pre>\n\n<p>In my tests this saves about 10% in time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T13:42:00.607", "Id": "450014", "Score": "0", "body": "Thanks for this! Would you be able to tell me what minmax() does?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T13:47:26.567", "Id": "450015", "Score": "0", "body": "@TomScott - It returns a `pair`. `pair::first` contains the lesser number and `pair::second` is the greater number. It is in the `algorithm` header." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-16T16:16:03.560", "Id": "454048", "Score": "0", "body": "@tinstaafl, I believe this code is in error, the `max % 2 == 1` should not be in the if statement. Currently, `PeasantMultiply(5,4)` yields 25." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-17T00:28:56.983", "Id": "454100", "Score": "0", "body": "It's corrected now" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T13:18:51.890", "Id": "230905", "ParentId": "230837", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T12:48:07.033", "Id": "230837", "Score": "4", "Tags": [ "c++", "beginner", "algorithm" ], "Title": "Russian Peasant Multiplication Algorithm" }
230837
<p>Before writing this post I looked around for a library that could solve this problem. I didn't find much so I decided to try to write this.</p> <p>My problem is the following:</p> <p>I have two sets of points with coordinates x1, y1, and x2, y2. The sets have different number of elements. I want to find what is the average distance between all the elements in set 1 vs all the elements in the set 2 given a certain cutoff. This mean that, if two points (of the two different sets) are further than cutoff they should not be considered.</p> <p>The easiest solution is to perform <span class="math-container">\$O(n^2)\$</span> search and then filter the results based on the distance, but it's inefficient.</p> <p>I tried to write an algorithm that divide the space of the sets in squares of size "cutoff". For each point I can associate two indexes that tell me to which box the point belong. Looking at the indexes I can generate the lists of neighbors points and calculate the distances only between points that are in confining boxes.</p> <pre><code>#include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;time.h&gt; #include &lt;numeric&gt; using namespace std; // euclidean distance double euc(double x, double y) { return sqrt(x * x + y * y); } //calculate the distance vector between two different sets of points // set 1 of coordinate x1, y1 // set 2 of coordinate x2, y2 vector &lt;double&gt; all_dist(vector &lt;double&gt;&amp; x1, vector &lt;double&gt;&amp; x2, vector &lt;double&gt;&amp; y1, vector &lt;double&gt;&amp; y2) { vector &lt;double&gt; d(x1.size()*x2.size()); for (int i = 0; i &lt; x1.size(); ++i) { for (int j = 0; j &lt; x2.size(); ++j) { d[i*x2.size()+j]=euc(x1[i] - x2[j], y1[i] - y2[j]); } } return d; } vector &lt;double&gt; dist(vector &lt;double&gt;&amp; x1, vector &lt;double&gt;&amp; x2, vector &lt;double&gt;&amp; y1, vector &lt;double&gt;&amp; y2, double cutoff) { //we divide the space of the vectors in squares of size cutoff // each square has two indexes, one for the x coordinates and one for the y // these vectors contain the indexes for each point for the vector x1 and y1 // means: by reading the content of box_x1[n] box_y1[n] we know to which spatial // box the point "n" belongs vector &lt;int&gt; box_x1(x1.size()); vector &lt;int&gt; box_y1(y1.size()); // these vectors contain the indexes for each point for the vector x2 and y2 vector &lt;int&gt; box_x2(x2.size()); vector &lt;int&gt; box_y2(y2.size()); vector &lt;double&gt; res; // we compute the maximum number of sections (or divisions) in the x and y dimension // we need to find the maximum and minimum value for each vector double maxx = max(*max_element(x1.begin(), x1.end()), *max_element(x2.begin(), x2.end())); double minx = min(*min_element(x1.begin(), x1.end()), *min_element(x2.begin(), x2.end())); double maxy = max(*max_element(y1.begin(), y1.end()), *max_element(y2.begin(), y2.end())); double miny = min(*min_element(y1.begin(), y1.end()), *min_element(y2.begin(), y2.end())); int max_box_x = int((maxx - minx) / (1.1 * cutoff)); int max_box_y = int((maxy - miny) / (1.1 * cutoff)); for (int i = 0; i &lt; x1.size(); ++i) { box_x1[i]=(int((x1[i] - minx) / (1.1*cutoff) )); box_y1[i]=(int((y1[i] - miny) / (1.1*cutoff) )); } for (int i = 0; i &lt; x2.size(); ++i) { box_x2[i]=(int((x2[i] - minx) / (1.1*cutoff))); box_y2[i]=(int((y2[i] - miny) / (1.1*cutoff))); } // we need to create the list of neighbors points for a specific box // we need to consider all the boxes that are neighboring a specific box // this mean looking at the boxes +1 and -1 for (int i = 0; i &lt; max_box_x; ++i) { for (int j = 0; j &lt; max_box_y; ++j) { vector &lt;double&gt; points_x1c, points_y1c, points_x2c, points_y2c; for (int k = 0; k &lt; box_x1.size(); ++k) { if ((box_x1[k] == i || box_x1[k] == i + 1 || box_x1[k] == i - 1) &amp;&amp; (box_y1[k] == j || box_y1[k] == j + 1 || box_y1[k] == j - 1)) { points_x1c.push_back(x1[k]); points_y1c.push_back(y1[k]); } } for (int k = 0; k &lt; box_x2.size(); ++k) { if ((box_x2[k] == i || box_x2[k] == i + 1 || box_x2[k] == i - 1) &amp;&amp; (box_y2[k] == j || box_y2[k] == j + 1 || box_y2[k] == j - 1)) { points_x2c.push_back(x2[k]); points_y2c.push_back(y2[k]); } } // now that we have the two list of points (we have four vectors) // we can calculate the distances between these points vector &lt;double&gt; temp = all_dist(points_x1c, points_x2c, points_y1c, points_y2c); // we still accept only the distances below the cutoff vector &lt;double&gt; temp2; for (int m = 0; m &lt; temp.size(); ++m) if (temp[m] &lt; cutoff) temp2.push_back(temp[m]); move(temp2.begin(), temp2.end(), back_inserter(res)); } } return res; } int main() { int num_el = 50000; double cutoff = 200; vector&lt;double&gt; x1(num_el); vector&lt;double&gt; y1(num_el); vector&lt;double&gt; x2(num_el/2); vector&lt;double&gt; y2(num_el/2); generate(x1.begin(), x1.end(), rand); generate(y1.begin(), y1.end(), rand); generate(x2.begin(), x2.end(), rand); generate(y2.begin(), y2.end(), rand); clock_t begin_time = clock(); vector &lt;double&gt; res = dist(x1, x2, y1, y2,cutoff); cout &lt;&lt; float(clock() - begin_time) / CLOCKS_PER_SEC&lt;&lt;endl; cout &lt;&lt; accumulate(res.begin(), res.end(), 0.0) /res.size() &lt;&lt; endl; begin_time = clock(); res=all_dist(x1, x2, y1, y2); cout &lt;&lt; float(clock() - begin_time) / CLOCKS_PER_SEC &lt;&lt; endl; vector &lt;double&gt; res2; for (int i = 0; i &lt; res.size(); ++i) if (res[i] &lt; cutoff) res2.push_back(res[i]); cout &lt;&lt; accumulate(res2.begin(), res2.end(), 0.0) / res2.size() &lt;&lt; endl; } </code></pre> <p>I wonder if there are some optimizations that can be applied to the code and I also wonder if, somewhere, there is a library that does what need. I tried to measure the speed of the simple <span class="math-container">\$O(n^2)\$</span> solution vs the "box solution" (<span class="math-container">\$O(n \log n)\$</span>? I wish that). The box solution is faster but the result is not exactly the same as the <span class="math-container">\$O(n^2)\$</span>. Is this an acceptable error in such algorithm?</p> <p>I have put an image to explain my reasoning. The boxes should be squared of size cutoff (approximately). In the code we can read the variables <code>max_box_x</code> and <code>max_box_y</code> that, for the image, are respectively 4 and 3. The size of the vectors <code>box_x1</code> and <code>box_y1</code> are as big as one of the set. By looking at <code>box_x1[n]</code> and <code>box_y1[n]</code> we can tell to which box the particle with index <code>n</code> belongs.</p> <p><a href="https://i.stack.imgur.com/YkwX9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YkwX9.png" alt="Example of the two sets with and without the separation boxes"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T19:47:14.677", "Id": "449955", "Score": "0", "body": "For this site the code isn't all that long." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T13:51:01.820", "Id": "450744", "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)*. Consider pointing out the bug in a self-answer instead. Your explanation of the bug was basically a short review already." } ]
[ { "body": "<p>Some general comments:</p>\n\n<ul>\n<li><p>In terms of readability and protection from errors, you could benefit a lot from something like <code>struct point</code> which capsulates a 2-dimensional points. That is, if x and y belong together logically, they should be inside the same structure.</p></li>\n<li><p>Read about const correctness. All parameters that are not modified should be marked as <code>const</code>, again for readability and protection from errors.</p></li>\n<li><p>All <code>max_...</code> and <code>max_...</code> variables should be const as well.</p></li>\n<li><p>You are doing many unnecessary passes over your vectors with <code>max_element</code> and <code>min_element</code>, but what you actually want here is <a href=\"https://en.cppreference.com/w/cpp/algorithm/minmax_element\" rel=\"nofollow noreferrer\"><code>minmax_element</code></a>.</p></li>\n<li><p>Is <code>temp2</code> really necessary? Why not push into <code>res</code> directly?</p></li>\n<li><p>Currently, you also need to include <code>&lt;iterator&gt;</code>. Note that in C++, we also have <code>&lt;ctime&gt;</code>.</p></li>\n<li><p>For readability and potentially performance as well, don't declare all variables at the beginning of a scope. That is, <code>box_...</code> vectors and <code>res</code> can be declared much later, closer to their site of usage.</p></li>\n<li><p>You can precompute <code>cutoff * 1.1</code> instead of writing the expression each time you need the result.</p></li>\n<li><p>I don't know if you did already, but <a href=\"https://www.boost.org/doc/libs/1_71_0/libs/geometry/doc/html/index.html\" rel=\"nofollow noreferrer\">Boost.Geometry</a> could be helpful in cleaning up the code.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T08:49:20.540", "Id": "449999", "Score": "0", "body": "Thank you for the suggestions. I will apply them. I also have casted a positive vote but my reputation is too low for now. I also noticed many other style problems that I have to fix. Regarding temp2, it is possible that two particles in neighboring boxes are further apart than cutoff. For this reason I have to be sure to remove these results. I am not sure if there is another more direct way to select all the values of an array below a certain threshold and \"move\" them to the result vector." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T15:51:03.653", "Id": "230851", "ParentId": "230842", "Score": "1" } }, { "body": "<p><strong>Basics</strong>:</p>\n\n<ul>\n<li>Use a <code>point2d</code> struct to save the coordinates. It is better for the code: it is more cache friendly, and you can add methods to the structure that explain what are the functions, and you automatically impose the condition that the coordinate vectors are of appropriate size.</li>\n<li>You don't need to return the whole vector of distances, just compute the average and return it.</li>\n</ul>\n\n<p><strong>To improve performance</strong>: the box idea is sufficient but implementation leaves a lot to be desired.</p>\n\n<ul>\n<li>The size of the box doesn't necessarily needs to be <code>cutoff</code> or <code>cutoff*1.1</code>. You might want it to be different depending on the density. For low density case, consider the box resolution to be <code>cutoff/sqrt(2)</code> so that points belonging to the same box are necessarily within the correct distance and you can skip the fine-distance filtration in this case. For high density case you can make the box small enough to contain just several points - so that the coarse box-based filtration is more accurate.</li>\n<li>There is little need to arrange both sides into boxes, it is enough to arrange just one side into boxes and for each point from the other side simply find relevant boxes and then apply the fine cutoff filtration. Also now you can consider making the comparison not (box1 vs box2) but rather (point1 vs range_of_boxes2) for each row of boxes. It should be more cache friendly.</li>\n<li>In the case when you have high point density compared to cutoff size, consider switching to \"average square distance\" from \"average distance\", as in this case it is much easier and faster (O(n) vs O(n^2)) to compute average distances points1 vs points2 (as long as all points are within the cutoff distance) - also it allows certain precomputation optimizations that are impossible with \"average distance\". If this is relevant I can elaborate.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T10:58:08.903", "Id": "230899", "ParentId": "230842", "Score": "1" } }, { "body": "<p>I see a number of things that may help you improve your program. I'll start with the more superficial and progress to more substantive suggestions.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid. Know when to use it and when not to (as when writing include headers). In this particular case, I happen to think it's not terrible but it also doesn't help much.</p>\n\n<h2>Make sure you have all required <code>#include</code>s</h2>\n\n<p>The code uses <code>sqrt</code> but doesn't <code>#include &lt;cmath&gt;</code>. Also, remember that <code>sqrt</code> is in the <code>std</code> namespace, so the fully qualified name is <code>std::sqrt</code>. Additionally, <code>rand</code> is used but no <code>&lt;cstdlib&gt;</code></p>\n\n<h2>Be careful with signed and unsigned</h2>\n\n<p>In the current code, the loop integers <code>i</code> and <code>j</code> and <code>k</code> are signed <code>int</code> values, but they're being compared with <code>unsigned</code> quantities <code>x1.size()</code> and <code>x2.size()</code>. Better would be to declare them all as <code>unsigned</code> or <code>size_t</code>.</p>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>The passed vectors should not be altered (and are not altered) by the processing functions. Indicate that fact (and maybe even get a small speed boost) by specifying <code>const std::vector&amp;</code> as the function arguments.</p>\n\n<h2>Use \"range <code>for</code>\" and simplify your code</h2>\n\n<p>If you're using a C++11 compliant compiler, the use of \"range <code>for</code>\" can simplify your code. For example, the code currently contains this:</p>\n\n<pre><code>for (unsigned i = 0; i &lt; res.size(); ++i)\n if (res[i] &lt; cutoff)\n res2.push_back(res[i]);\n</code></pre>\n\n<p>It could be this:</p>\n\n<pre><code>for (auto dist: res)\n if (dist &lt; cutoff)\n res2.push_back(dist);\n</code></pre>\n\n<p>Better would be to eliminate it completely, but we'll get to that later.</p>\n\n<h2>Don't use <code>std::endl</code> if you don't really need it</h2>\n\n<p>The difference between <code>std::endl</code> and <code>'\\n'</code> is that <code>'\\n'</code> just emits a newline character, while <code>std::endl</code> actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to <em>only</em> use <code>std::endl</code> when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using <code>std::endl</code> when <code>'\\n'</code> will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.</p>\n\n<h2>Don't store data you don't need</h2>\n\n<p>Right now, the code attempts to calculate the comprehensive list of distances and puts them into a large vector. On my machine, a <code>double</code> is 8 bytes. With 50000 and 25000 points in the two sets, this means the resulting distance vector is 50000 * 25000 * 8 = 10,000,000,000 bytes or 9.3 GiB. That's a huge amount of data, which the program then mostly discards and then reduces to a single number. (On my machine, that number is always <code>-nan</code> which suggests another problem, but more on that later.) </p>\n\n<h2>Use classes more effectively</h2>\n\n<p>The description talks about points, but the program actually uses vectors of coordinates instead. I'd recommend creating a templated <code>Point2D</code> object like this:</p>\n\n<pre><code>template &lt;typename T&gt;\nclass Point2D {\npublic:\n Point2D(T x, T y) : x_(x), y_(y) {}\n T dist(const Point2D&amp; other) const {\n return std::sqrt(sqdist(other));\n }\n T sqdist(const Point2D&amp; other) const {\n const auto dx{x_ - other.x_};\n const auto dy{y_ - other.y_};\n return dx*dx + dy*dy;\n }\nprivate:\n T x_, y_;\n};\n</code></pre>\n\n<h2>Consider using a better random number generator</h2>\n\n<p>Right now, the program is using the old C-style <code>rand</code> which is not a very good random number generator. The intent is apparently to create numbers in the range <code>[0, RAND_MAX]</code> where <code>RAND_MAX</code> is implementation defined. On my machine, <code>RAND_MAX = 2147483647</code> but on yours I suspect it must be 32768. Otherwise you would also be getting <code>-nan</code> for the result or you'd have chosen a different cutoff value. So rather than relying on implementation defined values and a poor random number generator, if you are using a compiler that supports at least C++11, consider using a better random number generator. In particular, instead of <code>rand</code>, you might want to look at <a href=\"http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution\" rel=\"nofollow noreferrer\"><code>std::uniform_real_distribution</code></a> and friends in the <code>&lt;random&gt;</code> header. Here's one way to do it:</p>\n\n<pre><code>double newrand() {\n static std::random_device rd;\n static std::mt19937 gen(rd());\n static std::uniform_real_distribution&lt;double&gt; dis(0, 32768);\n return dis(gen);\n}\n</code></pre>\n\n<h2>Avoid computationally costly operations</h2>\n\n<p>The distance between every pair of points is calculated which means millions of calls to <code>std::sqrt</code>, but this is not really needed since it would be sufficient to calculate the squared distance instead and then compare with the squared cutoff value. We can go a bit further and test the square of each coordinate pair. That is, if <span class=\"math-container\">\\$(\\Delta x)^2 \\ge t^2\\$</span>, or <span class=\"math-container\">\\$(\\Delta y)^2 \\ge t^2\\$</span>, then there's no point in doing further calculations.</p>\n\n<h2>Results</h2>\n\n<p>When I first ran the program, it takes 30.9 seconds just for the <code>all_dist</code> call and a total of 55.1 seconds to finally print the answer. After applying all of the suggestions above the program runs in 0.95 seconds. Here's the revised code:</p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;ctime&gt;\n#include &lt;cmath&gt;\n#include &lt;random&gt;\n\ndouble newrand() {\n static std::random_device rd;\n static std::mt19937 gen(rd());\n static std::uniform_real_distribution&lt;double&gt; dis(0, 32768);\n return dis(gen);\n}\n\ntemplate &lt;typename T&gt;\nclass Point2D {\npublic:\n Point2D() : x_(newrand()), y_(newrand()) {}\n Point2D(T x, T y) : x_(x), y_(y) {}\n T dist(const Point2D&amp; other) const {\n return std::sqrt(sqdist(other));\n }\n T sqdist(const Point2D&amp; other) const {\n const auto dx{x_ - other.x_};\n const auto dy{y_ - other.y_};\n return dx*dx + dy*dy;\n }\n T sqdist_thr(const Point2D&amp; other, T threshold) const {\n const auto dx{x_ - other.x_};\n const auto dy{y_ - other.y_};\n if (dx &lt; threshold &amp;&amp; dy &lt; threshold)\n return dx*dx + dy*dy;\n return threshold;\n }\nprivate:\n T x_, y_;\n};\n\ndouble avgdist(const std::vector&lt;Point2D&lt;double&gt;&gt;&amp; a, const std::vector&lt;Point2D&lt;double&gt;&gt;&amp; b, double threshold) {\n const double threshold2 = threshold*threshold;\n double sum{0};\n unsigned count{0};\n for (const auto &amp;one: a) {\n for (const auto &amp;two: b) {\n auto d2 = one.sqdist_thr(two, threshold2);\n if (d2 &lt; threshold2) {\n ++count;\n sum += std::sqrt(d2);\n }\n }\n }\n return sum/count;\n}\n\nint main() {\n constexpr int num_el = 50000;\n constexpr double cutoff = 200;\n const std::vector&lt;Point2D&lt;double&gt;&gt; a(num_el);\n const std::vector&lt;Point2D&lt;double&gt;&gt; b(num_el/2);\n\n clock_t begin_time = clock();\n std::cout &lt;&lt; avgdist(a, b, cutoff) &lt;&lt; '\\n';\n std::cout &lt;&lt; float(clock() - begin_time) / CLOCKS_PER_SEC &lt;&lt; '\\n';\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T06:57:00.780", "Id": "450095", "Score": "0", "body": "A very nice and thorough answer! Out of curiosity, regarding \"maybe even get a small speed boost\" -- can we find a single case (using say Godbolt) to show that adding const actually allows the compiler to do something smarter? I learned C++ around 15 years ago and this claim was often repeated back then at least, but I wonder if it's true at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T07:08:39.363", "Id": "450097", "Score": "0", "body": "O_O impressive. I have just a question. How do I change the class Point2D to accept 2 vectors? I used random values as an example in the code. I have real position in my work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T07:50:44.480", "Id": "450098", "Score": "0", "body": "@Juho Whether `const` confers a performance advantage in this context is, of course, entirely dependent on the compiler used. For the most used compilers for desktop machines (clang, gcc, MSVC) there is likely no difference. For some embedded systems compilers I have used, I’ve observed such a difference. Measuring, as you suggest, is the way to find out what difference it makes on your particular platform, configuration and compiler." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T07:57:14.580", "Id": "450099", "Score": "0", "body": "@Fabrizio I would probably not make a change to the `Point2D` class, but rather create a function that converts two vectors of numbers into a single vector of `Point3D`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T07:59:35.333", "Id": "450100", "Score": "0", "body": "@Edward I wasn't limiting ourselves to this specific case, but I'm asking whether there is *any* case where we can see a difference in the generated code depending on whether `const` is used or not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T08:03:24.800", "Id": "450101", "Score": "0", "body": "@Juho It’s easier to find a difference with `constexpr`, but I’ll dig through my notes later today and see if I can dig up exactly such an example for you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T09:09:29.697", "Id": "450104", "Score": "0", "body": "I have another question though. Your algorithm is very fast but isn't it still a o(n^2)? Isn't it good, for some very large systems, to separate the space in boxes?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T14:27:30.837", "Id": "450156", "Score": "0", "body": "@Fabrizio Yes, it's absolutely O(n^2). Your box approach will work, or you could look at using a [k-d tree](https://en.wikipedia.org/wiki/K-d_tree) which is essentially similar for 2D." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T14:02:50.960", "Id": "450220", "Score": "0", "body": "@Juho I looked in my notes and found a few instances. The notes say it was using the Mitsubishi (now Renesas) NC30 compiler for the M16C processor, but I no longer have that compiler. The compiler, around 2003 or so, generated much better machine language code when `const` was consistently and appropriately used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T14:12:06.133", "Id": "450222", "Score": "0", "body": "@Edward OK, interesting! I still wonder if there would be cases like this on a modern gcc or so." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T15:49:31.203", "Id": "450235", "Score": "0", "body": "@Juho Maybe. You can [play here](https://godbolt.org/z/JlkWmU) and see the effects of `const` and `constexpr` vs. omitting those. Interesting, also, is how much better gcc and clang are compared with MSVC at optimizing." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T15:10:31.450", "Id": "230912", "ParentId": "230842", "Score": "3" } }, { "body": "<p>The code contain a major logical flaw.</p>\n\n<p>I tried to correct my question but @Mast made me notice that this is against the rules, sorry for my mistake.</p>\n\n<p>In the section of the code that uses the boxes there is a for loop to generate the lists points_x1c and points_y1c. In that section there is a wrong \"if\" statement.</p>\n\n<pre><code> for (int i = 0; i &lt; max_box_x; ++i) {\n for (int j = 0; j &lt; max_box_y; ++j) { \n vector &lt;double&gt; points_x1c, points_y1c, points_x2c, points_y2c;\n for (int k = 0; k &lt; box_x1.size(); ++k) {\n if ((box_x1[k] == i || box_x1[k] == i + 1 || box_x1[k] == i - 1) &amp;&amp;\n (box_y1[k] == j || box_y1[k] == j + 1 || box_y1[k] == j - 1)) {\n points_x1c.push_back(x1[k]);\n points_y1c.push_back(y1[k]);\n }\n }\n</code></pre>\n\n<p>The correct code should be the following:</p>\n\n<pre><code> for (int i = 0; i &lt; max_box_x; ++i) {\n for (int j = 0; j &lt; max_box_y; ++j) { \n vector &lt;double&gt; points_x1c, points_y1c, points_x2c, points_y2c;\n for (int k = 0; k &lt; box_x1.size(); ++k) {\n if (box_x1[k] == i &amp;&amp; box_y1[k] == j) {\n points_x1c.push_back(x1[k]);\n points_y1c.push_back(y1[k]);\n }\n }\n</code></pre>\n\n<p>This is because, for the lists points_x1c and points_y1c (logically the points belonging to a specific type) you need to take only the values for the box \"i,j\".\nObviously all the other suggestions given in the other answers still remains, the code can be better written and standardized by using these guidelines.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T14:54:52.717", "Id": "231206", "ParentId": "230842", "Score": "0" } } ]
{ "AcceptedAnswerId": "230912", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T13:38:03.903", "Id": "230842", "Score": "6", "Tags": [ "c++", "performance" ], "Title": "Distance between two different sets of points" }
230842
<h3>Problem</h3> <p>Validate if a given string can be interpreted as a decimal or scientific number.</p> <p>Some examples:</p> <pre><code>"0" =&gt; true " 0.1 " =&gt; true "abc" =&gt; false "1 a" =&gt; false "2e10" =&gt; true " -90e3 " =&gt; true " 1e" =&gt; false "e3" =&gt; false " 6e-1" =&gt; true " 99e2.5 " =&gt; false "53.5e93" =&gt; true " --6 " =&gt; false "-+3" =&gt; false "95a54e53" =&gt; false </code></pre> <h3>Code</h3> <p>I've solved the valid number LeetCode problem using Python <code>re</code> module. If you'd like to review the code and provide any change/improvement recommendations, please do so and I'd really appreciate that.</p> <pre><code>import re from typing import Optional def is_numeric(input_string: Optional[str]) -&gt; bool: """ Returns True for valid numbers and input string can be string or None """ if input_string is None: return False expression_d_construct = r"^[+-]?(?:\d*\.\d+|\d+\.\d*|\d+)[Ee][+-]?\d+$|^[+-]?(?:\d*\.\d+|\d+\.\d*|\d+)$|^[+-]?\d+$" expression_char_class = r"^[+-]?(?:[0-9]*\.[0-9]+|[0-9]+\.[0-9]*|[0-9]+)[Ee][+-]?[0-9]+$|^[+-]?(?:[0-9]*\.[0-9]+|[0-9]+\.[0-9]*|[0-9]+)$|^[+-]?[0-9]+$" if re.match(expression_d_construct, input_string.strip()) is not None and re.match(expression_char_class, input_string.strip()) is not None: return True return False if __name__ == "__main__": # ---------------------------- TEST --------------------------- DIVIDER_DASH = '-' * 50 GREEN_APPLE = '\U0001F34F' RED_APPLE = '\U0001F34E' test_input_strings = [None, "0 ", "0.1", "abc", "1 a", "2e10", "-90e3", "1e", "e3", "6e-1", "99e2.5", "53.5e93", "--6", "-+3", "95a54e53"] count = 0 for string in test_input_strings: print(DIVIDER_DASH) if is_numeric(string): print(f'{GREEN_APPLE} Test {int(count + 1)}: {string} is a valid number.') else: print(f'{RED_APPLE} Test {int(count + 1)}: {string} is an invalid number.') count += 1 </code></pre> <h3>Output</h3> <pre><code>-------------------------------------------------- Test 1: None is an invalid number. -------------------------------------------------- Test 2: 0 is a valid number. -------------------------------------------------- Test 3: 0.1 is a valid number. -------------------------------------------------- Test 4: abc is an invalid number. -------------------------------------------------- Test 5: 1 a is an invalid number. -------------------------------------------------- Test 6: 2e10 is a valid number. -------------------------------------------------- Test 7: -90e3 is a valid number. -------------------------------------------------- Test 8: 1e is an invalid number. -------------------------------------------------- Test 9: e3 is an invalid number. -------------------------------------------------- Test 10: 6e-1 is a valid number. -------------------------------------------------- Test 11: 99e2.5 is an invalid number. -------------------------------------------------- Test 12: 53.5e93 is a valid number. -------------------------------------------------- Test 13: --6 is an invalid number. -------------------------------------------------- Test 14: -+3 is an invalid number. -------------------------------------------------- Test 15: 95a54e53 is an invalid number. </code></pre> <h3>RegEx Circuit</h3> <p><a href="https://jex.im/regulex/#!flags=&amp;re=%5E(a%7Cb)*%3F%24" rel="noreferrer">jex.im</a> visualizes regular expressions: </p> <p><a href="https://i.stack.imgur.com/725JB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/725JB.png" alt="enter image description here"></a></p> <hr> <h3><a href="https://regex101.com/r/ygzjKw/1/" rel="noreferrer">RegEx Demo 1</a></h3> <h3><a href="https://regex101.com/r/OCAFF2/1/" rel="noreferrer">RegEx Demo 2</a></h3> <p>If you wish to explore the expression, it's been explained on the top right panel of <a href="https://regex101.com/r/ygzjKw/1/" rel="noreferrer">regex101.com</a>. If you'd like, you can also watch in <a href="https://regex101.com/r/ygzjKw/1/debugger" rel="noreferrer">this link</a>, how it would match against some sample inputs.</p> <hr> <h3>Source</h3> <p><a href="https://leetcode.com/problems/valid-number/" rel="noreferrer">LeetCode Valid Number</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T15:25:43.510", "Id": "449924", "Score": "4", "body": "nice apple icons" } ]
[ { "body": "<p>Instead of diving into cumbersome and lengthy regex expressions consider the following improvement/correction:</p>\n\n<p>The main thesis for the underlying aspect is:</p>\n\n<blockquote>\n <p>Numeric literals containing a decimal point or an <em>exponent</em> sign\n yield <strong>floating</strong> point numbers.</p>\n</blockquote>\n\n<p><a href=\"https://docs.python.org/3.4/library/stdtypes.html#numeric-types-int-float-complex\" rel=\"noreferrer\">https://docs.python.org/3.4/library/stdtypes.html#numeric-types-int-float-complex</a></p>\n\n<p>Therefore Python treats values like <code>53.5e93</code>, <code>-90e3</code> as float type numbers.</p>\n\n<p>Eventually I would proceed with the following approach (retaining those cute icons) including additional small optimizations:</p>\n\n<pre><code>from typing import TypeVar, Optional\n\n\ndef is_numeric(input_string: Optional[str]) -&gt; bool:\n \"\"\"\n Returns True for valid numbers. Acceptable types of items: str or None\n \"\"\"\n if input_string is None:\n return False\n\n try:\n input_string = input_string.strip()\n float(input_string)\n except ValueError:\n return False\n return True\n\n\nif __name__ == \"__main__\":\n # ---------------------------- TEST ---------------------------\n DIVIDER_DASH = '-' * 50\n GREEN_APPLE = '\\U0001F34F'\n RED_APPLE = '\\U0001F34E'\n\n test_input_strings = [None, \"0 \", \"0.1\", \"abc\", \"1 a\", \"2e10\", \"-90e3\",\n \"1e\", \"e3\", \"6e-1\", \"99e2.5\", \"53.5e93\", \"--6\", \"-+3\", \"95a54e53\"]\n\n count = 0\n for string in test_input_strings:\n print(DIVIDER_DASH)\n count += 1\n\n if is_numeric(string):\n print(f'{GREEN_APPLE} Test {count}: `{string}` is a valid number.')\n else:\n print(f'{RED_APPLE} Test {count}: `{string}` is not a valid number.')\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>--------------------------------------------------\n Test 1: `None` is not a valid number.\n--------------------------------------------------\n Test 2: `0 ` is a valid number.\n--------------------------------------------------\n Test 3: `0.1` is a valid number.\n--------------------------------------------------\n Test 4: `abc` is not a valid number.\n--------------------------------------------------\n Test 5: `1 a` is not a valid number.\n--------------------------------------------------\n Test 6: `2e10` is a valid number.\n--------------------------------------------------\n Test 7: `-90e3` is a valid number.\n--------------------------------------------------\n Test 8: `1e` is not a valid number.\n--------------------------------------------------\n Test 9: `e3` is not a valid number.\n--------------------------------------------------\n Test 10: `6e-1` is a valid number.\n--------------------------------------------------\n Test 11: `99e2.5` is not a valid number.\n--------------------------------------------------\n Test 12: `53.5e93` is a valid number.\n--------------------------------------------------\n Test 13: `--6` is not a valid number.\n--------------------------------------------------\n Test 14: `-+3` is not a valid number.\n--------------------------------------------------\n Test 15: `95a54e53` is not a valid number.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T11:03:42.133", "Id": "450003", "Score": "0", "body": "The `.strip()` part is not necessary, because python allows optional leading and trailing whitespace. Also, you can omit the `None` check and catch both `ValueError` and `TypeError`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T15:44:42.163", "Id": "230850", "ParentId": "230848", "Score": "5" } }, { "body": "<p>I'd just go with @Roman's suggestion. You should just leave it up to the language to decide what is and isn't valid.</p>\n\n<p>I'd make two further suggestions though:</p>\n\n<p>I don't think the parameter to <code>is_numeric</code> should be <code>Optional</code>; either conceptually, or to comply with the challenge. <code>None</code> will never be a valid number, so why even check it? I don't think dealing with invalid data should be that function's responsibility. Make it take just a <code>str</code>, then deal with <code>None</code>s externally. I also don't really think it's <code>is_numeric</code>'s responsibility to be dealing with trimming either; and that isn't even required:</p>\n\n<pre><code>print(float(\" 0.1 \")) # prints 0.1\n</code></pre>\n\n<p>I'd also <code>return True</code> from within the <code>try</code>. The behavior will be the same, but I find it makes it clearer the intent of the <code>try</code>.</p>\n\n<p>After the minor changes, I'd go with:</p>\n\n<pre><code>def is_numeric(input_string: str) -&gt; bool:\n \"\"\"\n Returns True for valid numbers. Acceptable types of items: str or None\n \"\"\"\n try:\n parsed = float(input_string)\n return True\n\n except ValueError:\n return False\n\nif string is not None and is_numeric(string):\n print(f'{GREEN_APPLE} Test {count}: `{string}` is a valid number.')\nelse:\n print(f'{RED_APPLE} Test {count}: `{string}` is not a valid number.')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T16:46:42.437", "Id": "230858", "ParentId": "230848", "Score": "4" } }, { "body": "<p>That regex visualisation you provided is really neat. It shows that there is a lot of potential overlap in the conditions.</p>\n\n<p>You should be able to reduce it down to something similar to this:</p>\n\n<pre><code>^[+-]?\\d+(\\.\\d+)?([Ee][+-]?\\d+)?$\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T08:39:15.883", "Id": "449996", "Score": "1", "body": "Your regex doesn't match `1.` or `.5`, both of which are matched by the regex in the OP. Your regex assumes that there will always be a leading digit before a period, and that a period will always be followed by decimals. Neither is true." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T00:57:44.270", "Id": "230881", "ParentId": "230848", "Score": "1" } } ]
{ "AcceptedAnswerId": "230850", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T15:10:45.060", "Id": "230848", "Score": "5", "Tags": [ "python", "beginner", "algorithm", "strings", "regex" ], "Title": "LeetCode 65: Valid Number (Python)" }
230848
<p>I have a form for an item (<code>Job Item</code>), that has <strong>sets of 2 fields</strong> based on a type.</p> <p>field and field + <code>_dolar</code></p> <p>e.g: <code>cogs_paid</code> and <code>cogs_paid_dollar</code></p> <p>validation example: <code>cogs_paid</code> or <code>cogs_paid_dollar</code>, if both are empty, validation fails. This goes for all sub-fields.</p> <p>What I did, my current <code>Model</code>:</p> <pre><code> class JobItem &lt; ActiveRecord::Base COGS_REQUIRED_TYPES = [ ContentType::Brief, ContentType::Feature, ContentType::Fish, ContentType::Paid, ContentType::Print, ContentType::Target ].freeze include MessageBroker message_broker model_name: 'JobItem' belongs_to :job validates :weekly_budget, presence: { if: -&gt; { COGS_REQUIRED_TYPES.include?(content_type) } } validates :cogs_brief_write_lead, presence: { if: -&gt; { content_type == ContentType::Brief &amp;&amp; cogs_brief_write_lead_dollar.blank? }, message: 'cant be empty or provide COGS Actual Cost matching entry', } validates :cogs_brief_write_copy, presence: { if: -&gt; { content_type == ContentType::Brief &amp;&amp; cogs_brief_write_copy_dollar.blank? }, message: 'cant be empty or provide COGS Actual Cost matching entry', } validates :cogs_brief_copy_edit, presence: { if: -&gt; { content_type == ContentType::Brief &amp;&amp; cogs_brief_copy_edit_dollar.blank? }, message: 'cant be empty or provide COGS Actual Cost matching entry', } validates :cogs_write_lead, presence: { if: -&gt; { content_type == ContentType::Feature &amp;&amp; cogs_write_lead_dollar.blank? }, message: 'cant be empty or provide COGS Actual Cost matching entry', } validates :cogs_interview, presence: { if: -&gt; { content_type == ContentType::Feature &amp;&amp; cogs_interview_dollar.blank? }, message: 'cant be empty or provide COGS Actual Cost matching entry', } validates :cogs_write_feature, presence: { if: -&gt; { content_type == ContentType::Feature &amp;&amp; cogs_write_feature_dollar.blank? }, message: 'cant be empty or provide COGS Actual Cost matching entry', } validates :cogs_content_edit, presence: { if: -&gt; { content_type == ContentType::Feature &amp;&amp; cogs_content_edit_dollar.blank? }, message: 'cant be empty or provide COGS Actual Cost matching entry', } validates :cogs_copy_edit, presence: { if: -&gt; { content_type == ContentType::Feature &amp;&amp; cogs_copy_edit_dollar.blank? }, message: 'cant be empty or provide COGS Actual Cost matching entry', } validates :cogs_paid_write_lead, presence: { if: -&gt; { content_type == ContentType::Paid &amp;&amp; cogs_paid_write_lead_dollar.blank? }, message: 'cant be empty or provide COGS Actual Cost matching entry', } validates :cogs_paid_interview_research, presence: { if: -&gt; { content_type == ContentType::Paid &amp;&amp; cogs_paid_interview_research_dollar.blank? }, message: 'cant be empty or provide COGS Actual Cost matching entry', } validates :cogs_paid_write_copy, presence: { if: -&gt; { content_type == ContentType::Paid &amp;&amp; cogs_paid_write_copy_dollar.blank? }, message: 'cant be empty or provide COGS Actual Cost matching entry', } validates :cogs_paid_copy_edit, presence: { if: -&gt; { content_type == ContentType::Paid &amp;&amp; cogs_paid_copy_edit_dollar.blank? }, message: 'cant be empty or provide COGS Actual Cost matching entry', } validates :cogs_paid_review, presence: { if: -&gt; { content_type == ContentType::Paid &amp;&amp; cogs_paid_review_dollar.blank? }, message: 'cant be empty or provide COGS Actual Cost matching entry', } validates :cogs_paid_publish, presence: { if: -&gt; { content_type == ContentType::Paid &amp;&amp; cogs_paid_publish_dollar.blank? }, message: 'cant be empty or provide COGS Actual Cost matching entry', } validates :cogs_design, presence: { if: -&gt; { content_type == ContentType::Print &amp;&amp; cogs_design_dollar.blank? }, message: 'cant be empty or provide COGS Actual Cost matching entry', } validates :cogs_page_edit, presence: { if: -&gt; { content_type == ContentType::Print &amp;&amp; cogs_page_edit_dollar.blank? }, message: 'cant be empty or provide COGS Actual Cost matching entry', } validates :cogs_page_proof, presence: { if: -&gt; { content_type == ContentType::Print &amp;&amp; cogs_page_proof_dollar.blank? }, message: 'cant be empty or provide COGS Actual Cost matching entry', } validates :cogs_photo_toning, presence: { if: -&gt; { content_type == ContentType::Print &amp;&amp; cogs_photo_toning_dollar.blank? }, message: 'cant be empty or provide COGS Actual Cost matching entry', } def content_type=(value) new_type = ContentType.find(value) self[:content_type] = new_type ? new_type.id.to_s : nil end ContentType.types.each do |method, klass| define_method :"#{method}?" do content_type == klass end end end </code></pre> <p>I currently have 20+ validations like the one above on my model, (for each sub-field and its type) which looks pretty ugly.</p> <p><strong>Any suggestions on how one would improve this, and reduce repetition?</strong></p> <p>What changes on every validation is: </p> <p>field ; field+<code>_dollar</code></p> <p>content_type being compared: e.g <code>ContentType::Paid</code></p>
[]
[ { "body": "<p>Changed to, on the model</p>\n\n<pre><code>\n COGS_FIELDS_PRESENCE = [\n [content_type: 'brief', cogs_field: 'cogs_brief_write_lead', cogs_field_dollar: 'cogs_brief_write_lead_dollar'],\n [content_type: 'brief', cogs_field: 'cogs_brief_write_copy', cogs_field_dollar: 'cogs_brief_write_copy_dollar'],\n .\n .\n . + 20 entries\n\n ]\n\n\n def cogs_fields_presence\n COGS_FIELDS_PRESENCE.flatten.each do |field|\n if content_type.to_s == field[:content_type] &amp;&amp; self[field[:cogs_field]].blank? &amp;&amp; self[field[:cogs_field_dollar]].blank?\n errors.add(field[:cogs_field], 'cant be empty or provide COGS Actual Cost matching entry')\n end\n end\n end\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T21:14:23.297", "Id": "231231", "ParentId": "230852", "Score": "1" } } ]
{ "AcceptedAnswerId": "231231", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T15:56:36.413", "Id": "230852", "Score": "1", "Tags": [ "ruby", "validation", "ruby-on-rails" ], "Title": "better multiple fields validation on ruby/rails" }
230852
<p>I took a simple BST implementation which is only really a set (i.e. just element, not key value), and decided to add a node count. I was translating <a href="https://algs4.cs.princeton.edu/32bst/BST.java.html" rel="noreferrer">this</a>, which is explained <a href="https://algs4.cs.princeton.edu/32bst/" rel="noreferrer">here</a>.</p> <p>In particular the put method (below called bst-insert), but it's not the same thing, the difference in the languages seem large, plus the version below is non-destructive (functional?). </p> <p>Two versions below. First the incorrect one, interesting because it shows where I started from, then the correct version which contains a fix to set node count from the newly created node, not by counting up the nodes on the old tree before the new node may have been inserted (which was the error).</p> <p>I'm reasonably happy with the correct version, but happy for any further suggestions, critique and code review :)</p> <blockquote> <pre class="lang-lisp prettyprint-override"><code>(defstruct (node (:print-function (lambda (n s d) (format s "#&lt;~A ~A ~A ~A&gt;" (node-elt n) (node-l n) (node-r n) (node-count n))))) elt (l nil) (r nil) count) (defun node-size (node) (if (null node) 0 (node-count node))) ; Incorrect version of bst-insert (defun bst-insert (obj bst &lt;) (if (null bst) (make-node :elt obj :count 1) (let ((elt (node-elt bst))) (if (eql obj elt) bst (if (funcall &lt; obj elt) (make-node :elt elt :l (bst-insert obj (node-l bst) &lt;) :r (node-r bst) ; error: we need node-size below not of node-l of parameter 'bst', as now, but ; of left subtree of *this* node being creating now, as set in the lines above. :count (+ (node-size (node-l bst)) (node-size (node-r bst)) 1)) ; &lt;- INCORRECT (make-node :elt elt :l (node-l bst) :r (bst-insert obj (node-r bst) &lt;) :count (+ (node-size (node-l bst)) (node-size (node-r bst)) 1))))))) </code></pre> <p>The above code is wrong, and gives:</p> <pre class="lang-lisp prettyprint-override"><code>[9]&gt; (setf bst (bst-insert 5 bst #'&lt;)) #&lt;6 #&lt;5 NIL NIL 1&gt; NIL 1&gt; [10]&gt; (setf bst nil) NIL [11]&gt; (setf bst (bst-insert 6 bst #'&lt;)) #&lt;6 NIL NIL 1&gt; [12]&gt; (setf bst (bst-insert 5 bst #'&lt;)) #&lt;6 #&lt;5 NIL NIL 1&gt; NIL 1&gt; ; &lt;- count for 6 should be 2, not 1. [13]&gt; </code></pre> </blockquote> <p>Correct version:</p> <pre class="lang-lisp prettyprint-override"><code>(defun bst-insert (obj bst &lt;) (if (null bst) (make-node :elt obj :count 1) (let ((elt (node-elt bst))) (if (eql obj elt) bst (if (funcall &lt; obj elt) (let ((new-l (bst-insert obj (node-l bst) &lt;))) (make-node :elt elt :l new-l :r (node-r bst) :count (+ (node-size new-l) (node-size (node-r bst)) 1))) ; &lt;- CORRECT (let ((new-r (bst-insert obj (node-r bst) &lt;))) (make-node :elt elt :l (node-l bst) :r new-r :count (+ (node-size (node-l bst)) (node-size new-r) 1)))))))) </code></pre> <p>gives</p> <pre class="lang-lisp prettyprint-override"><code>[14]&gt; (setf bst nil) NIL [15]&gt; (setf bst (bst-insert 6 bst #'&lt;)) #&lt;6 NIL NIL 1&gt; [16]&gt; (setf bst (bst-insert 5 bst #'&lt;)) #&lt;6 #&lt;5 NIL NIL 1&gt; NIL 2&gt; ; &lt;- node count of root is now correctly 2. [17]&gt; </code></pre> <p>Discussion</p> <ol> <li><p>First I forgot the 'extra' parens round let, hopefully I'll remember next time I get <code>- LET: illegal variable specification</code> that, even when you only have one expression pair in your let, you still must have 'extra' parens wrapping them as if they were a group. </p></li> <li><p>I tried moving the entire <code>make-node</code> into a <code>let</code>, but that got messy, bad idea.</p></li> <li><p>I also tried <code>prog1</code>, but since we need to update the node that's returned, that seemed wrong. </p></li> </ol> <p>I'm more or less happy with the above, but interested in any improvements of style or even functionality if anyone is partial.</p> <p>One thing I'm interested in getting toward in time is KD-trees, but seems to make sense to play with regular trees for a bit more first.</p>
[]
[ { "body": "<p>Overall looks good, so take below as a few ideas, nothing's really wrong\nwith it.</p>\n\n<p>Except using <code>setf</code> without a previous variable declaration, that's just\nnot guaranteed to even work (assuming that's what the code snippet showed with <code>(setf bst nil)</code>).</p>\n\n<hr>\n\n<p>I'm gonna try this on CCL:</p>\n\n<p>Evaluating the structure definition gives me an unused warning for the\n<code>d</code> parameter of the node printing function - consider declaring it\nignored to silence that: <code>(declare (ignore d))</code>.</p>\n\n<p><code>(l nil)</code> doesn't add much on top of <code>l</code> (same goes for <code>(r nil)</code>).\nAlso consider using a more simple positional calling convention, after\nall the <code>:elt</code>, <code>:l</code> (which really could just be <code>:left</code> btw.)\netc. gets kind of verbose:</p>\n\n<pre><code>(defstruct (node (:constructor make-node (elt count &amp;optional l r)))\n elt count l r)\n</code></pre>\n\n<p>Also I've rotated the order of elements so that <code>(make-node obj 1)</code> is\nstraightforward.</p>\n\n<p>Okay, so <code>bst-insert</code> now:</p>\n\n<p>Consider using <code>cond</code> for deep <code>if</code> blocks to reduce the level of\nindentation. I suppose here it doesn't help too much though.</p>\n\n<p><del><code>eql</code> can be simplified to <code>eq</code> here, that's sometimes important, here\nit's just for completeness' sake though.</del> Edit: Jumped to quickly on that, <code>eql</code> is correct since there were integers in the example. For a generally usable tree you might want to make it possible to customise the equality test.</p>\n\n<p>The rest of the body looks okay, a bit of reshuffling could possibly\nreduce the duplication a bit, but really it's all about clarity, how\neasy it is to discern what's happening and to detect any possible\nmistakes easily.</p>\n\n<p>Thus, I'd arrive at this, perhaps:</p>\n\n<pre><code>(defun bst-insert (obj bst &lt;)\n (if (null bst)\n (make-node obj 1)\n (let ((elt (node-elt bst)))\n (if (eq obj elt)\n bst\n (let* ((less-than (funcall &lt; obj elt))\n (old-l (node-l bst))\n (old-r (node-r bst))\n (new-l (if less-than (bst-insert obj old-l &lt;) old-l))\n (new-r (if less-than old-r (bst-insert obj old-r &lt;))))\n (make-node\n elt\n (+ (node-size new-l) (node-size new-r) 1)\n new-l\n new-r))))))\n</code></pre>\n\n<p>Personally, I'd also go for long names, or really short ones. Like,\neither <code>o</code> or <code>object</code>; <code>obj</code> and <code>elt</code> just make me wonder what is\nmeant most of the time. Note that <code>elt</code> is also a regular CL function,\nso <code>e</code> or <code>element</code> might be better.</p>\n\n<hr>\n\n<p>Wrt. your other points:</p>\n\n<ul>\n<li>There are of course macros to reduce the nesting for, say, <code>let</code>, but\nit's hardly a problem. Just remember that <code>let</code> can create multiple\nbindings, so grouping things makes sense.</li>\n<li><code>prog1</code> is useful, but as you said, I don't see much value in using it\nhere.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T19:13:05.523", "Id": "450190", "Score": "1", "body": "`EQL` can't be simplified to `EQ`. `EQ` effects are undefined for numbers and characters. The example uses numbers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T19:16:09.053", "Id": "450191", "Score": "1", "body": "Fixed, thank you." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T19:01:27.720", "Id": "230868", "ParentId": "230855", "Score": "2" } } ]
{ "AcceptedAnswerId": "230868", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T16:30:14.833", "Id": "230855", "Score": "6", "Tags": [ "algorithm", "tree", "common-lisp" ], "Title": "BST with node count" }
230855
<p>I finally made tic tac toe as a beginner(took a month and a bit) and I want to know if I made things more complicated than they should. It seems like a lot of code for a simple game but I'm not sure. Still learning and I would like some advice if there's something really bad.</p> <p>PS:I dont know a clear command other than system("cls") so even though I saw people online saying no to it I dont know an alternative.</p> <p>Code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;stdio.h&gt; #include &lt;conio.h&gt; #include &lt;time.h&gt; using namespace std; int aivall, aivaln; char p1 = ' ', p2 = ' ', p3 = ' ', p4 = ' ', p5 = ' ', p6 = ' ', p7 = ' ', p8 =' ', p9 = ' ', l; int n, endg = 0, again; int ai(int a, int b) { if (a == 1) { switch (b) { case 1: {if (p1 == 88 || p1 == 79) {again = 1;} else {p1 = 79;}} break; case 2: {if (p2 == 88 || p2 == 79) {again = 1;} else {p2 = 79;}} break; case 3: {if (p3 == 88 || p3 == 79) {again = 1;} else {p3 = 79;}} break; }} if (a == 2) { switch (b) { case 1: {if (p4 == 88 || p4 == 79) {again = 1;} else {p4 = 79;}} break; case 2: {if (p5 == 88 || p5 == 79) {again = 1;} else {p5 = 79;}} break; case 3: {if (p6 == 88 || p6 == 79) {again = 1;} else {p6 = 79;}} break; }} if (a == 3) { switch (b) { case 1: {if (p7 == 88 || p7 == 79) {again = 1;} else {p7 = 79;}} break; case 2: {if (p8 == 88 || p8 == 79) {again = 1;} else {p8 = 79;}} break; case 3: {if (p9 == 88 || p9 == 79) {again = 1;} else {p9 = 79;}} break; }} } char xno(char p1, char p2, char p3, char p4, char p5, char p6, char p7, char p8, char p9) { cout &lt;&lt; " 1 2 3 " &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; " A. " &lt;&lt; p1 &lt;&lt; " " &lt;&lt; p2 &lt;&lt; " " &lt;&lt; p3 &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; " B. " &lt;&lt; p4 &lt;&lt; " " &lt;&lt; p5 &lt;&lt; " " &lt;&lt; p6 &lt;&lt; endl; cout &lt;&lt; endl; cout &lt;&lt; " C. " &lt;&lt; p7 &lt;&lt; " " &lt;&lt; p8 &lt;&lt; " " &lt;&lt; p9 &lt;&lt; endl; cout &lt;&lt; endl;} int triplecheckx() { //vertical if (p1 == 88 &amp;&amp; p4 == 88 &amp;&amp; p7 == 88) { endg = 1; system("cls"); xno(p1,p2,p3,p4,p5,p6,p7,p8,p9); cout &lt;&lt; "Player Won!!!"; } if (p2 == 88 &amp;&amp; p5 == 88 &amp;&amp; p8 == 88) { endg = 1; system("cls"); xno(p1,p2,p3,p4,p5,p6,p7,p8,p9); cout &lt;&lt; "Player Won!!!"; } if (p3 == 88 &amp;&amp; p6 == 88 &amp;&amp; p9 == 88) { endg = 1; system("cls"); xno(p1,p2,p3,p4,p5,p6,p7,p8,p9); cout &lt;&lt; "Player Won!!!"; } //Horizontal if (p1 == 88 &amp;&amp; p2 == 88 &amp;&amp; p3 == 88) { endg = 1; system("cls"); xno(p1,p2,p3,p4,p5,p6,p7,p8,p9); cout &lt;&lt; "Player Won!!!"; } if (p4 == 88 &amp;&amp; p5 == 88 &amp;&amp; p6 == 88) { endg = 1; system("cls"); xno(p1,p2,p3,p4,p5,p6,p7,p8,p9); cout &lt;&lt; "Player Won!!!"; } if (p7 == 88 &amp;&amp; p8 == 88 &amp;&amp; p9 == 88) { endg = 1; system("cls"); xno(p1,p2,p3,p4,p5,p6,p7,p8,p9); cout &lt;&lt; "Player Won!!!"; } //Cross if (p1 == 88 &amp;&amp; p5 == 88 &amp;&amp; p9 == 88) { endg = 1; system("cls"); xno(p1,p2,p3,p4,p5,p6,p7,p8,p9); cout &lt;&lt; "Player Won!!!"; } if (p3 == 88 &amp;&amp; p5 == 88 &amp;&amp; p7 == 88) { endg = 1; system("cls"); xno(p1,p2,p3,p4,p5,p6,p7,p8,p9); cout &lt;&lt; "Player Won!!!"; } } int triplechecko() { //vertical if (p1 == 79 &amp;&amp; p4 == 79 &amp;&amp; p7 == 79) { endg = 1; system("cls"); xno(p1,p2,p3,p4,p5,p6,p7,p8,p9); cout &lt;&lt; "AI Won!!!"; } if (p2 == 79 &amp;&amp; p5 == 79 &amp;&amp; p8 == 79) { endg = 1; system("cls"); xno(p1,p2,p3,p4,p5,p6,p7,p8,p9); cout &lt;&lt; "AI Won!!!"; } if (p3 == 79 &amp;&amp; p6 == 79 &amp;&amp; p9 == 79) { endg = 1; system("cls"); xno(p1,p2,p3,p4,p5,p6,p7,p8,p9); cout &lt;&lt; "AI Won!!!"; } //Horizontal if (p1 == 79 &amp;&amp; p2 == 79 &amp;&amp; p3 == 79) { endg = 1; system("cls"); xno(p1,p2,p3,p4,p5,p6,p7,p8,p9); cout &lt;&lt; "AI Won!!!"; } if (p4 == 79 &amp;&amp; p5 == 79 &amp;&amp; p6 == 79) { endg = 1; system("cls"); xno(p1,p2,p3,p4,p5,p6,p7,p8,p9); cout &lt;&lt; "AI Won!!!"; } if (p7 == 79 &amp;&amp; p8 == 79 &amp;&amp; p9 == 79) { endg = 1; system("cls"); xno(p1,p2,p3,p4,p5,p6,p7,p8,p9); cout &lt;&lt; "AI Won!!!"; } //Cross if (p1 == 79 &amp;&amp; p5 == 79 &amp;&amp; p9 == 79) { endg = 1; system("cls"); xno(p1,p2,p3,p4,p5,p6,p7,p8,p9); cout &lt;&lt; "AI Won!!!"; } if (p3 == 79 &amp;&amp; p5 == 79 &amp;&amp; p7 == 79) { endg = 1; system("cls"); xno(p1,p2,p3,p4,p5,p6,p7,p8,p9); cout &lt;&lt; "AI Won!!!"; } } int checkalltie(char p1,char p2,char p3,char p4,char p5,char p6,char p7,char p8,char p9){ if(p1 != 32 &amp;&amp; p2 != 32 &amp;&amp; p3 != 32 &amp;&amp; p4 != 32 &amp;&amp; p5 != 32 &amp;&amp; p6 != 32 &amp;&amp; p7 != 32 &amp;&amp; p8 != 32 &amp;&amp; p9 != 32 ) { endg = 1; system("cls"); xno(p1,p2,p3,p4,p5,p6,p7,p8,p9); cout&lt;&lt;"TIE!!!";} } int numberpick() { if (l == 'A') { switch (n) { case 1: p1 = 88; break; case 2: p2 = 88; break; case 3: p3 = 88; break; } } if (l == 'B') { switch (n) { case 1: p4 = 88; break; case 2: p5 = 88; break; case 3: p6 = 88; break; } } if (l == 'C') { switch (n) { case 1: p7 = 88; break; case 2: p8 = 88; break; case 3: p9 = 88; } } } int main() { ifendg1: checkalltie(p1,p2,p3,p4,p5,p6,p7,p8,p9); while (endg == 0) { srand(time(0)); xno(p1,p2,p3,p4,p5,p6,p7,p8,p9); cout &lt;&lt; "Enter the position: "; cin &gt;&gt; l &gt;&gt; n; switch (l) { case 'A': numberpick(); case 'B': numberpick(); case 'C': numberpick(); } checkalltie(p1,p2,p3,p4,p5,p6,p7,p8,p9); triplecheckx(); if(endg==1) goto ifendg1; repeat: again = 0; aivall = (rand() % 3) + 1; aivaln = (rand() % 3) + 1; ai(aivall, aivaln); triplechecko(); if(endg==1) goto ifendg1; if (again == 1) { goto repeat; } checkalltie(p1,p2,p3,p4,p5,p6,p7,p8,p9); system("cls"); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T19:06:24.653", "Id": "449951", "Score": "1", "body": "Use `'X'` and `'O'` instead of writing `88` and `79`-- similar to how you initialized your values as `' '` and not `32` for clarity e.g. `if (p1 == 'X' && p4 == 'X' && p7 == 'X')`. Also, many of your variables are declared in global scope, so when you call `checkalltie(p1,p2,p3,p4,p5,p6,p7,p8,p9)`, you are passing variables to the function that are already in the scope of the function (because they are global). It is good practice to not declare global variables. For example, you could use an array `char p[9]` and then pass the pointer `p` into the functions that need it e.g. `checkalltie(p)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T21:22:06.840", "Id": "449971", "Score": "1", "body": "@Kyy13 Yea...I guess I could... didnt think about it though when I did this since I'm still fresh (learning from school). But yea good idea. Might actually use it for my next one! Thx. Also I had an issue where the variables wouldnt actually change(if i said for ex x=4 in a function it wont change ouside of it. dont know why) and so I just declared them globaly and left it like that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T21:27:57.653", "Id": "449973", "Score": "0", "body": "The values don't change, because the value is copied into the function. In C++ you can pass a reference instead of a value by adding an & sign after the type i.e. `foo(int& a) { a = 3; }` will allow you to update the value that is passed into foo. You can also achieve this by providing the address of the variable as a pointer, and then assigning the value by dereferencing it i.e. `foo (int* a) { *a = 3; }`. Arrays are just pointers to the first element in the array, so you can just use the array name and it will behave like the pointer method." } ]
[ { "body": "<p>The thing I would focus on to start with is reducing code duplication. If you look at your <code>triplechecko/x</code> functions, it's basically the same code over and over but with different variables.</p>\n\n<p>I would start by replacing all the <code>p1...9</code> with a container. Since it's fixed size, let's use <code>std::array</code>. Then lets see what we can do to reduce some of the code duplication.</p>\n\n<pre><code>#include &lt;array&gt;\n#include &lt;ctime&gt;\n#include &lt;iostream&gt;\n\nstd::array&lt;std::array&lt;char, 3&gt;, 3&gt; board;\n\nbool make_move(char player, char&amp; square) {\n if (square == ' ') {\n square = player;\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>It's good to give variables and function descriptive names. It might feel a bit tedious when you start out, but you increase the readability a lot. The goal is that you should be able to come back to this code in a few months and have no problem understanding what is what. Names like <code>ai</code> might feel intuitive now, but probably not later on.</p>\n\n<p><code>ai</code> function became a generic <code>make_move</code>. It does almost the same, but we take a reference to the square we want and the player value <code>'X'</code> or <code>'O'</code>. It also returns <code>true</code> or <code>false</code> depending on success. This help us remove global variables like <code>endg</code> and similar.</p>\n\n<pre><code>void print_board() {\n std::cout &lt;&lt; \" 1 2 3 \\n\\n\";\n char row_char = 'A';\n for (auto&amp; row : board) {\n std::cout &lt;&lt; row_char &lt;&lt; \". \";\n ++row_char;\n for (auto&amp; square : row) {\n std::cout &lt;&lt; square &lt;&lt; \" \";\n }\n std::cout &lt;&lt; \"\\n\\n\";\n }\n\n std::cout &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>Print the board. Using loops to loop through our 2D-array.</p>\n\n<pre><code>bool triple_check(char player, char v1, char v2, char v3) {\n if (v1 == player &amp;&amp; v2 == player &amp;&amp; v3 == player) {\n std::cout &lt;&lt; player &lt;&lt; \" won!\" &lt;&lt; std::endl;\n return true;\n }\n return false;\n}\n\nbool check_if_won(char player) {\n for (int i = 0; i &lt; 3; ++i) {\n // check rows\n if (triple_check(player, board[i][0], board[i][1], board[i][2])) return true;\n // check columns\n if (triple_check(player, board[0][i], board[1][i], board[2][i])) return true;\n }\n\n // check diagonals\n if (triple_check(player, board[0][0], board[1][1], board[2][2])) return true;\n if (triple_check(player, board[0][2], board[1][1], board[2][0])) return true;\n\n return false;\n}\n</code></pre>\n\n<p>Here I decided to split the function in two steps to make it more clear and easy to read. This replaces both <code>triplecheck</code> functions from before, and prints out if someone won. Again we are returning <code>true</code> or <code>false</code> to indicate if someone won.</p>\n\n<pre><code>bool check_tie() {\n for (auto&amp; row : board) {\n for (auto&amp; square : row) {\n if (square == ' ') return false;\n }\n }\n\n std::cout &lt;&lt; \"TIE!!!\" &lt;&lt; std::endl;\n return true;\n}\n</code></pre>\n\n<p>Checking for a tie by looping through the board, return <code>true/false</code>.</p>\n\n<pre><code>bool is_valid_input(char val) {\n if (val &gt;= 0 &amp;&amp; val &lt;= 2) return true;\n return false;\n}\n\nvoid number_pick() {\n char row, column;\n while (true) {\n std::cin &gt;&gt; row &gt;&gt; column;\n\n row -= 'A';\n column -= '1';\n\n if (is_valid_input(row) &amp;&amp; is_valid_input(column) &amp;&amp; make_move('X', board[row][column])) return;\n\n std::cout &lt;&lt; \"Invalid input. Try again: \";\n }\n}\n</code></pre>\n\n<p>Here we have the function that takes the input from the player. To make the code more clear it's again split in two where we validate the input. I also use <code>row -= 'A'</code> to make the value usable to index into the board array. Additionally we also check the return value of <code>make_move</code> to make sure the move is valid.</p>\n\n<pre><code>void reset_board() {\n for (auto&amp; row : board) {\n for (auto&amp; square : row) {\n square = ' ';\n }\n }\n}\n\nint main() {\n srand(time(0));\n reset_board();\n\n while (true) {\n print_board();\n\n std::cout &lt;&lt; \"Enter the position: \";\n number_pick();\n\n if (check_if_won('X') || check_tie()) break;\n\n while (!make_move('O', board[rand() % 3][rand() % 3]));\n\n check_if_won('O');\n }\n}\n</code></pre>\n\n<p><code>reset_board</code> initializes the board to starting state. If we want to add the option of playing several matches in a row this will come in handy again for resetting the board.</p>\n\n<p><code>while (!make_move('O', board[rand() % 3][rand() % 3]));</code> uses a while loop without a body, shown by the <code>;</code> after the condition. It just runs the <code>make_move</code> function over and over with random input until it return true. When it returns <code>true</code> the <code>!</code> in front makes the loop break.</p>\n\n<p>Now we only have 1 global variable left, the board! If we encasulated this in a class it could be a member variable, but for a small thing like this we'll leave it there.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T21:26:21.007", "Id": "449972", "Score": "0", "body": "I was not taught yet about #include <array> so I dont know anything from it but it looks interesting so I'll look into it further. Also is there any replacement for system(\"cls\")? I heard you shouldnt use system commands at all. And I used it alot!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T21:31:09.203", "Id": "449974", "Score": "0", "body": "AFAIK there is no portable way to clear the console. It's platform specific. The only real option I can think of is to use an external library like [PDCurses](https://pdcurses.org/). But often you don't need to clear the console at all since all the new content ends up at the bottom anyway where it's visible." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T20:24:40.383", "Id": "230872", "ParentId": "230856", "Score": "1" } } ]
{ "AcceptedAnswerId": "230872", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T16:43:12.673", "Id": "230856", "Score": "2", "Tags": [ "c++", "beginner", "tic-tac-toe" ], "Title": "Beginner tic-tac-toe implementation" }
230856
<p>I need to have access to a set of common data inside a few functions. The data values are determined only at runtime, and are far away in terms of control flow, so handing them to the function as an argument is out of the question. What I want to do, in the end, is</p> <p>where I have the data:</p> <pre class="lang-py prettyprint-override"><code>from .injection import offer def launch_new_case(customer_type): case_id = get_random_uuid() offer(case_id=case_id, customer_type=customer_type) launch_computation() </code></pre> <p>and then somewhere deep in the computation:</p> <pre class="lang-py prettyprint-override"><code>from .injection import retrieve def computation_step(arg1, arg2): customer_type = retrieve("customer_type") if customer_type == 1: return arg1 elif customer_type == 2: return arg2 else: case_id = retrieve("case_id") logger.error(f"Encountered invalid {customer_type=} for {case_id=}.") </code></pre> <p>The basic idea is that I have a submodule, <code>injection.py</code> that holds a module-level dictionary and provides a function to add to that dict and read from that dict. To be extra sure not to screw things up (I will have to read from the dict in a multithreading environment), I added a lock.</p> <pre class="lang-py prettyprint-override"><code># my_project/injection.py """Provide lightweight dependency injection for my_project.""" from threading import Lock import warnings __injector = {} def offer(**kwargs): """Offer objects to be injected elsewhere. Parameters ---------- kwargs Each keyword argument will be added to the injector as given """ existing_injections = set(kwargs.keys).intersection(set(__injector.keys)) if existing_injections: warnings.warn(f"Overwriting keys in injector: " f"{', '.join(existing_injections}") with Lock(): __injector.update(kwargs) def retrieve(key): """Retreive an object from the injector. Parameters ---------- key: string The key of the object to inject """ with Lock(): return __injector[key] </code></pre> <p>I am aware that usual dependency injection setups involve several classes handling the organization and distribution of the objects to be injected. What are potential pitfalls with my solution? How can it be improved?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T17:26:38.800", "Id": "449942", "Score": "6", "body": "Please provide some concrete examples of how this code is to be used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T17:55:16.483", "Id": "449945", "Score": "1", "body": "retreive => retrieve" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T07:34:18.880", "Id": "449990", "Score": "0", "body": "I updated my question with more context and snippets of the intended use. I hope this is concrete enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T14:24:55.680", "Id": "450023", "Score": "1", "body": "Much better, but in the `retrieve` function it should probably also be `with Lock()` instead of `with lock`." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T16:48:08.527", "Id": "230859", "Score": "0", "Tags": [ "python", "dependency-injection" ], "Title": "Extremely lightweight dependency injection" }
230859
<p>This is my first ever try at making reusable code. The function makes use of two images to give the illusion of turning on and turning off a button in pygame.</p> <p>I would like to know what would you do differently and if I did a good job? Thanks everyone.</p> <p>Also, this is assuming you already loaded your images and gave it a name using <code>pygame.image.load()</code> function in pygame.</p> <pre><code>""" The function `mouse_on_button() takes all the arguments needed to produce a light-able button. For example, you have an image of a thumbs up in grey and another image of a thumbs up in bright red and stack the on top of each other. They are called by clicking the position of the image. By clicking they dark image will get transformed into the lit up image and vice-versa. thumbs_up_img = pygame.image.load('thumbsup.png') thumbs_up_lit_up_img = pygame.image.load('thumbsupred.png') thumbs_up = Buttons(60, 240, 50, 50) # X, Y, Width, Height mouse_on_button(pygame, screen, thumbs_up_img, thumbs_up_lit_up_img,thumbs_up.btn_x, thumbs_up.btn_y, thumbs_up.width, thumbs_up.height, SCREEN_HEIGHT, SCREEN_WIDTH) """ class Buttons: """ This class takes the x-position and the y-position, width and height of an image. """ def __init__(self, btn_x, btn_y, width, height): self.btn_x = btn_x self.btn_y = btn_y self.width = width self.height = height def mouse_on_button(pygame, screen, off_btn, on_btn, btn_x, btn_y, width, height, SCREEN_HEIGHT, SCREEN_WIDTH): """ This function takes a dark image and a bright image to give the illusion of turning on a button. """ # Get mouse position. mouse = pygame.mouse.get_pos() # Setting up the boundries to light up or turn off around the button. if (mouse[0] &gt;= btn_x and mouse[0] &lt;= btn_x + width) and (mouse[1] &gt;= btn_y and mouse[1] &lt;= btn_y + height): # This will return the ON value of an image in the screen. return screen.blit(on_btn,(btn_x, btn_y, SCREEN_HEIGHT, SCREEN_WIDTH)) else: # This will return the OFF value of an image in the screen. return screen.blit(off_btn,(btn_x, btn_y, SCREEN_HEIGHT, SCREEN_WIDTH)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T18:33:28.413", "Id": "449949", "Score": "0", "body": "please post some context, usages/calling your `mouse_on_button` function" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T20:03:03.197", "Id": "449959", "Score": "0", "body": "Added a comment describing the func through an example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T20:38:55.430", "Id": "449965", "Score": "0", "body": "Are `DISPLAY_HEIGHT` and `DISPLAY_WIDTH` global constant values?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T21:06:22.870", "Id": "449969", "Score": "0", "body": "Yes, they describe the window size of the program. For example, 600px x 600px without the PX of course. I will take notes about all the missing info so it won't happen again. Edit: I should've said screen size for better readability. I will change it." } ]
[ { "body": "<p>I think your button class should do more. It should know if a point is within it's boundaries or not and what its image(s) is (are). It should probably also have an <code>update</code> method that can optionally be called with the mouse position. I would also rename it to singular <code>Button</code>, since each instance of the class is a single button and not a collection of buttons.</p>\n\n<pre><code>class Button:\n \"\"\"\n This class takes the x-position and the y-position, width and height of an image.\n \"\"\"\n def __init__(self, x, y, width, height, image, hover_image=None):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.image = on_image\n self.hover_image = hover_image\n\ndef point_inside(self, pos=None):\n if pos is None:\n return False\n return (self.x &lt;= pos[0] &lt;= self.x + self.width \\\n and self.y &lt;= pos[1] &lt;= self.y + self.height)\n\ndef update(self, screen, mouse_pos=None):\n if self.hover_image is not None and self.point_inside(mouse_pos):\n screen.blit(self.hover_image, (self.x, self.y, SCREEN_HEIGHT, SCREEN_WIDTH))\n else:\n screen.blit(self.image, (self.x, self.y, SCREEN_HEIGHT, SCREEN_WIDTH))\n\n\nif __name__ == \"__main__\":\n thumbs_up_img = pygame.image.load('thumbsup.png')\n thumbs_up_lit_up_img = pygame.image.load('thumbsupred.png')\n thumbs_up = Button(60, 240, 50, 50, thumbs_up_img, thumbs_up_lit_up_img)\n\n # some pygame setup\n ...\n\n while True:\n mouse = pygame.mouse.get_pos()\n button.update(screen, mouse)\n pygame.display.flip()\n</code></pre>\n\n<p>This is a bit more generic, in that it allows a button not to have a hover image and it has an <code>update</code> method, which is quite common for objects in <code>pygame</code>. You could think about off-loading the point in button boundary check to a <code>Rectangle</code> class, which might help since you will probably encounter rectangles and checking if a point is inside quite often in <code>pygame</code>.</p>\n\n<p>And would you look at that, there is already <a href=\"https://www.pygame.org/docs/ref/rect.html\" rel=\"nofollow noreferrer\"><code>pygame.Rect</code></a>, from which you could inherit. It even has the <a href=\"https://www.pygame.org/docs/ref/rect.html#pygame.Rect.collidepoint\" rel=\"nofollow noreferrer\"><code>pygame.Rect.collidepoint</code></a> method to check if a point is inside it.</p>\n\n<pre><code>class Button(pygame.Rect):\n \"\"\"\n This class takes the x-position and the y-position, width and height of an image.\n \"\"\"\n def __init__(self, x, y, width, height, image, hover_image=None):\n super().__init__(x, y, width, height)\n self.image = on_image\n self.hover_image = hover_image\n\ndef update(self, screen, mouse_pos=None):\n if self.hover_image is not None \\\n and mouse_pos is not None \\\n and self.collidepoint(mouse_pos):\n screen.blit(self.hover_image, (self.x, self.y, SCREEN_HEIGHT, SCREEN_WIDTH))\n else:\n screen.blit(self.image, (self.x, self.y, SCREEN_HEIGHT, SCREEN_WIDTH))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T13:18:41.430", "Id": "230904", "ParentId": "230860", "Score": "1" } } ]
{ "AcceptedAnswerId": "230904", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T16:55:30.370", "Id": "230860", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "pygame" ], "Title": "A class and a function to create and light up buttons in PyGame" }
230860
<p>First, I'd like to provide a little explanation on what my code is supposed to do. It is part of a middle-sized project. I restructured the code to work on its own, and also added little comments to help you understand what I'm doing. This is one of the 5 methods how spectrograms can be analyzed. Now let me give you a little physical background (I won't go in the details):</p> <p>A spectrogram is a dataset, x values mean frequency, y values mean intensity. We either have it on it's own, or we can normalize it (if <code>sam</code> and <code>ref</code> args are given). <code>_handle_input</code> function below takes care of reading the given inputs right. <a href="https://drive.google.com/file/d/1-YKFM9zPdG-ABR5kTpV4zyA6UyrXPOV3/view?usp=sharing" rel="nofollow noreferrer">In this example dataset</a>, we have it normalized. The first step is to determine the minimum and maximum points in the given dataset: we can manually feed the minimum and maximum places through <code>minx</code> and <code>maxx</code> arguments. If it's not used, we will use scipy's <code>argrelextrema</code> as default. This example we will not over-complicate things, so let's use the defaults.</p> <p>In the next step we need to specify a reference point (<code>ref_point</code> arg, preferably somewhere in the middle of x values), and get the relative positions of minimums and maximums to that point. Then we define an order: <a href="https://i.stack.imgur.com/n8JCR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n8JCR.png" alt="This figure helps"></a></p> <p>The closest extremal points are 1st order, the 2nd closest points are 2nd order, etc. Then, we multiply the order by pi, and that will be the y value of the spectral phase (which we want to calculate). <a href="https://i.stack.imgur.com/6hqL7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6hqL7.png" alt="See this picture"></a></p> <p>Now, our job to fit a polynomial to the spectral phase graph (the lower graph on the picture). The order varies from 1 to 5. From the fitted parameters then we can calculate the dispersion's coefficients, which is the purpose of the whole method. The calculation is described at the poly's docstrings. For example:</p> <pre class="lang-py prettyprint-override"><code>def poly_fit5(x, b0, b1, b2, b3, b4, b5): """ Taylor polynomial for fit b1 = GD b2 = GDD / 2 b3 = TOD / 6 b4 = FOD / 24 b5 = QOD / 120 """ return b0+b1*x+b2*x**2+b3*x**3+b4*x**4+b5*x**5 </code></pre> <p>We need the GD, GDD, etc., so the method I wrote returns these params, not the fitted parameters. I also added a decorator called <code>show_disp</code>, which immediately prints the results in the right format. </p> <p>Here is the full code: <em>Please, first download the dataset above, scroll down and uncomment the given examples to see how it's working.</em></p> <pre class="lang-py prettyprint-override"><code>import operator from functools import wraps from math import factorial import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit from scipy.signal import argrelextrema try: from lmfit import Model _has_lmfit = True except ImportError: _has_lmfit = False __all__ = ['min_max_method'] def find_nearest(array, value): array = np.asarray(array) idx = (np.abs(value - array)).argmin() return array[idx], idx def show_disp(f): #decorator to immediately print out the dispersion results @wraps(f) def wrapping(*args, **kwargs): disp, disp_std, stri = f(*args, **kwargs) labels = ['GD', 'GDD','TOD', 'FOD', 'QOD'] for i in range(len(labels)): print(labels[i] + ' = ' + str(disp[i]) + ' +/- ' + str(disp_std[i]) + ' 1/fs^{}'.format(i+1)) return disp, disp_std, stri return wrapping def _handle_input(init_x, init_y, ref, sam): """ Instead of handling the inputs in every function, there is this method. Parameters ---------- init_x: array-like x-axis data init_y: array-like y-axis data ref, sam: array-like reference and sample arm spectrum evaluated at init_x Returns ------- init_x: array-like unchanged x data y_data: array-like the proper y data """ if (len(init_x) &gt; 0) and (len(init_y) &gt; 0) and (len(sam) &gt; 0): y_data = (init_y-ref-sam)/(2*np.sqrt(ref*sam)) elif (len(ref) == 0) or (len(sam) == 0): y_data = init_y elif len(init_y) == 0 or len(init_x) == 0: raise ValueError('Please load the spectrum!\n') else: raise ValueError('Input shapes are wrong.\n') return init_x, y_data @show_disp def min_max_method(init_x, init_y, ref, sam, ref_point, maxx=None, minx=None, fit_order=5, show_graph=False): """ Calculates the dispersion with minimum-maximum method Parameters ---------- init_x: array-like x-axis data init_y: array-like y-axis data ref, sam: array-like reference and sample arm spectra evaluated at init_x ref_point: float the reference point to calculate order maxx and minx: array-like the accepted minimal and maximal places should be passed to these args fit_order: int degree of polynomial to fit data [1, 5] show_graph: bool if True returns a matplotlib plot and pauses execution until closing the window Returns ------- dispersion: array-like [GD, GDD, TOD, FOD, QOD] dispersion_std: array-like [GD_std, GDD_std, TOD_std, FOD_std, QOD_std] fit_report: lmfit report (if available) """ x_data, y_data = _handle_input(init_x, init_y, ref, sam) # handling default case when no minimum or maximum coordinates are given if maxx is None: maxInd = argrelextrema(y_data, np.greater) maxx = x_data[maxInd] if minx is None: minInd = argrelextrema(y_data, np.less) minx = x_data[minInd] _, ref_index = find_nearest(x_data, ref_point) # getting the relative distance of mins and maxs coordinates from the ref_point relNegMaxFreqs = np.array([a for a in (x_data[ref_index]-maxx) if a&lt;0]) relNegMinFreqs= np.array([b for b in (x_data[ref_index]-minx) if b&lt;0]) relNegFreqs = sorted(np.append(relNegMaxFreqs, relNegMinFreqs)) # reversing order because of the next loop relNegFreqs = relNegFreqs[::-1] relPosMaxFreqs = np.array([c for c in (x_data[ref_index]-maxx) if c&gt;0]) relPosMinFreqs= np.array([d for d in (x_data[ref_index]-minx) if d&gt;0]) relPosFreqs = sorted(np.append(relPosMinFreqs,relPosMaxFreqs)) negValues = np.zeros_like(relNegFreqs) posValues = np.zeros_like(relPosFreqs) for freq in range(len(relPosFreqs)): posValues[freq] = np.pi*(freq+1) for freq in range(len(relNegFreqs)): negValues[freq] = np.pi*(freq+1) # making sure the data is ascending in x # FIXME: Do we even need this? x_s = np.append(relPosFreqs, relNegFreqs) y_s = np.append(posValues, negValues) L = sorted(zip(x_s,y_s), key=operator.itemgetter(0)) fullXValues, fullYValues = zip(*L) # now we have the data, let's fit a function if _has_lmfit: if fit_order == 5: fitModel = Model(poly_fit5) params = fitModel.make_params(b0 = 0, b1 = 1, b2 = 1, b3 = 1, b4 = 1, b5 = 1) result = fitModel.fit(fullYValues, x=fullXValues, params=params, method='leastsq') elif fit_order == 4: fitModel = Model(poly_fit4) params = fitModel.make_params(b0 = 0, b1 = 1, b2 = 1, b3 = 1, b4 = 1) result = fitModel.fit(fullYValues, x=fullXValues, params=params, method='leastsq') elif fit_order == 3: fitModel = Model(poly_fit3) params = fitModel.make_params(b0 = 0, b1 = 1, b2 = 1, b3 = 1) result = fitModel.fit(fullYValues, x=fullXValues, params=params, method='leastsq') elif fit_order == 2: fitModel = Model(poly_fit2) params = fitModel.make_params(b0 = 0, b1 = 1, b2 = 1) result = fitModel.fit(fullYValues, x=fullXValues, params=params, method='leastsq') elif fit_order == 1: fitModel = Model(poly_fit1) params = fitModel.make_params(b0 = 0, b1 = 1) result = fitModel.fit(fullYValues, x=fullXValues, params=params, method='leastsq') else: raise ValueError('Order is out of range, please select from [1,5]') else: if fit_order == 5: popt, pcov = curve_fit(poly_fit5, fullXValues, fullYValues, maxfev = 8000) _function = poly_fit5 elif fit_order == 4: popt, pcov = curve_fit(poly_fit4, fullXValues, fullYValues, maxfev = 8000) _function = poly_fit4 elif fit_order == 3: popt, pcov = curve_fit(poly_fit3, fullXValues, fullYValues, maxfev = 8000) _function = poly_fit3 elif fit_order == 2: popt, pcov = curve_fit(poly_fit2, fullXValues, fullYValues, maxfev = 8000) _function = poly_fit2 elif fit_order == 1: popt, pcov = curve_fit(poly_fit1, fullXValues, fullYValues, maxfev = 8000) _function = poly_fit1 else: raise ValueError('Order is out of range, please select from [1,5]') try: if _has_lmfit: dispersion, dispersion_std = [], [] for name, par in result.params.items(): dispersion.append(par.value) dispersion_std.append(par.stderr) # dropping b0 param, it's not needed dispersion = dispersion[1:] dispersion_std = dispersion_std[1:] for idx in range(len(dispersion)): dispersion[idx] = dispersion[idx] * factorial(idx+1) dispersion_std[idx] = dispersion_std[idx] * factorial(idx+1) # fill up the rest with zeros while len(dispersion) &lt; 5: dispersion.append(0) dispersion_std.append(0) fit_report = result.fit_report() else: fullXValues = np.asarray(fullXValues) #for plotting dispersion, dispersion_std = [], [] for idx in range(len(popt)-1): dispersion.append(popt[idx+1]*factorial(idx+1)) while len(dispersion)&lt;5: dispersion.append(0) while len(dispersion_std)&lt;len(dispersion): dispersion_std.append(0) fit_report = '\nTo display detailed results, you must have lmfit installed.' if show_graph: fig = plt.figure(figsize=(7,7)) fig.canvas.set_window_title('Min-max method fitted') plt.plot(fullXValues, fullYValues, 'o', label='dataset') try: plt.plot(fullXValues, result.best_fit, 'r--', label='fitted') except Exception: plt.plot(fullXValues, _function(fullXValues, *popt), 'r--', label='fitted') plt.legend() plt.grid() plt.show() return dispersion, dispersion_std, fit_report #This except block exists because otherwise errors would crash PyQt5 app, and we can display the error #to the log dialog in the application. except Exception as e: return [], [], e def poly_fit5(x, b0, b1, b2, b3, b4, b5): """ Taylor polynomial for fit b1 = GD b2 = GDD / 2 b3 = TOD / 6 b4 = FOD / 24 b5 = QOD / 120 """ return b0+b1*x+b2*x**2+b3*x**3+b4*x**4+b5*x**5 def poly_fit4(x, b0, b1, b2, b3, b4): """ Taylor polynomial for fit b1 = GD b2 = GDD / 2 b3 = TOD / 6 b4 = FOD / 24 """ return b0+b1*x+b2*x**2+b3*x**3+b4*x**4 def poly_fit3(x, b0, b1, b2, b3): """ Taylor polynomial for fit b1 = GD b2 = GDD / 2 b3 = TOD / 6 """ return b0+b1*x+b2*x**2+b3*x**3 def poly_fit2(x, b0, b1, b2): """ Taylor polynomial for fit b1 = GD b2 = GDD / 2 """ return b0+b1*x+b2*x**2 def poly_fit1(x, b0, b1): """ Taylor polynomial for fit b1 = GD """ return b0+b1*x ## To test with the data I provided: # a,b,c,d = np.loadtxt('test.txt', unpack=True, delimiter=',') # min_max_method(a,b,c,d, 2.5, fit_order=2, show_graph=True) ## To see how a usual dataset looks like: # x, y = _handle_input(a,b,c,d) # plt.plot(x, y) # plt.grid() # plt.show() </code></pre> <p>Obviously there are many things to improve (ex. determining the fit order looks horrible, but I could not find a better way.) I hope this was not too hard to follow. If something's unclear, just ask. I appreciate every suggestion in the code.</p> <p><strong>EDIT:</strong></p> <p>fixed</p> <pre class="lang-py prettyprint-override"><code>dispersion[idx] = dispersion[idx] / factorial(idx+1) dispersion_std[idx] = dispersion_std[idx] / factorial(idx+1) ... dispersion.append(popt[idx+1]/factorial(idx+1)) </code></pre> <p>to </p> <pre class="lang-py prettyprint-override"><code>dispersion[idx] = dispersion[idx] * factorial(idx+1) dispersion_std[idx] = dispersion_std[idx] * factorial(idx+1) ... dispersion.append(popt[idx+1]*factorial(idx+1)) </code></pre>
[]
[ { "body": "<h2>Loop like a native</h2>\n\n<pre><code> labels = ['GD', 'GDD','TOD', 'FOD', 'QOD']\n for i in range(len(labels)):\n print(labels[i] + ' = ' + str(disp[i]) + ' +/- ' + str(disp_std[i]) + ' 1/fs^{}'.format(i+1))\n</code></pre>\n\n<p>can be improved.</p>\n\n<pre><code>labels = ('GD', 'GDD','TOD', 'FOD', 'QOD') # Immutable tuple\nfor i, (label, disp_item, disp_std_item) in enumerate(zip(labels, disp, disp_std)):\n print(f'{label} = {disp_item} ±{disp_std_item} 1/fs^{i+1}')\n</code></pre>\n\n<h2>Don't repeat yourself</h2>\n\n<pre><code> if fit_order == 5:\n fitModel = Model(poly_fit5)\n params = fitModel.make_params(b0 = 0, b1 = 1, b2 = 1, b3 = 1, b4 = 1, b5 = 1)\n result = fitModel.fit(fullYValues, x=fullXValues, params=params, method='leastsq') \n</code></pre>\n\n<p>etc. should probably be</p>\n\n<pre><code>fit_model = Model(poly_fit)\nparams = fit_model.make_params(\n b0 = 0,\n **{f'b{i}': 1 for i in range(1, fit_order+1)}\n)\nresult = fitModel.fit(fullYValues, x=fullXValues, params=params, method='leastsq') \n</code></pre>\n\n<p>where <code>poly_fit</code> is itself generalized:</p>\n\n<pre><code>def poly_fit(x, *args):\n return sum(b*x**i for i, b in enumerate(args))\n</code></pre>\n\n<p>That said, <code>numpy</code> has better and faster ways to do this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-24T13:29:41.983", "Id": "450934", "Score": "0", "body": "Thank you for answering. I know that [np.polyfit](https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html) is a faster (and maybe easier) way to achieve the same result, but usually there is not too many points to fit, so speed is not an issue there. Also the fit method may be changed later, so to me it's nice to have lmfit." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-24T02:36:59.033", "Id": "231238", "ParentId": "230862", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T17:13:35.227", "Id": "230862", "Score": "3", "Tags": [ "python", "numpy", "physics", "scipy" ], "Title": "Optical dispersion calculation from spectrograms with Python" }
230862
<p>I wrote the following function which coverts a JSON format into a CSV. I'll be glad to have a code review because I know that it could be done in a simpler way and with less lines and iterations. Before I will show you the code, I will explain what it does. The format of JSON:</p> <pre><code>[ { "subs": [ { "status": "Passed", "name": "sub1", "all_data": [ { "status": "Passed", "name": "prepare" }, { "status": "Passed", "name": "run_check" } ], "ward": "/disk/nex/sub1/tes2" }, { "status": "Passed", "name": "sub2", "all_data": [ { "status": "Passed", "name": "prepare" }, { "status": "Passed", "name": "run_check" }, { "status": "Passed", "name": "analyze_command" } ], "ward": "/disk/nex/sub2/test1" } ], "name": "Gandif/test1" }, { "subs": [ { "status": "Passed", "name": "checker", "all_data": [ { "status": "Passed", "name": "prepare" }, { "status": "Passed", "name": "analyze_command" } ], "ward": "/disk/nex/checker/tes2" } ], "name": "Gandif/test2" } ] </code></pre> <p>I want to cover this data into a CSV. I have created the following checkbox values so the user could choose which data the CSV should contain:</p> <pre><code>checkboxValues: { csv_title: {value: true, name: "CSV Title"}, main_name: {value: true, name: "Main Name"}, sub_ward: {value: true, name: "Subtest Ward"}, sub_name: {value: true, name: "Subtest Name"}, sub_status: {value: true, name: "Subtest Status"}, data_name: {value: true, name: "Data Name"}, data_status: {value: true, name: "Data Status"} } </code></pre> <p>The format of the csv file:</p> <pre><code>Main Name, Subtest Ward, Subtest Name, Subtest Status, Data Name, Data Status, Data Name, Data Status, Data Name, Data Status, ... </code></pre> <p>User could use the checkbox values to choose which data should be included in the CSV file.</p> <p>The final result for the above example should be (if all checkboxs are checked):</p> <pre><code>[ [ "Main Name", "Subtest Ward", "Subtest Name", "Subtest Status", "Data Name", "Data Status", "Data Name", "Data Status", "Data Name", "Data Status" ], [ "Gandif/test1", "/disk/nex/fub1/tes2", "fub1", "Passed", "prepare", "Passed", "run_check", "Passed" ], [ "Gandif/test1", "/disk/nex/fub2/test1", "fub2", "Passed", "prepare", "Passed", "run_check", "Passed", "analyze_command", "Passed" ], [ "Gandif/test2", "/disk/nex/checker/tes2", "checker", "Passed", "prepare", "Passed", "analyze_command", "Passed" ] ] </code></pre> <p>The function that coverts the JSON to a CSV format looks like:</p> <pre><code>JSO2CSV: function(jsondata) { if (typeof jsondata !== "undefined" &amp;&amp; jsondata) { let arr = []; let temp_arr = []; let totalAmount = 0; jsondata.forEach(main =&gt; { main.subs.forEach(sub =&gt; { let inner_array = []; if (this.checkboxValues.main_name.value) inner_array.push(main.name || 'N/A'); if (this.checkboxValues.sub_ward.value) inner_array.push(sub.ward || 'N/A'); if (this.checkboxValues.sub_name.value) inner_array.push(sub.name || 'N/A'); if (this.checkboxValues.sub_status.value) inner_array.push(sub.status || 'N/A'); sub.all_data.forEach(data =&gt; { if (this.checkboxValues.data_name.value) inner_array.push(data.name || 'N/A'); if (this.checkboxValues.data_status.value) inner_array.push(data.status || 'N/A'); }); totalAmount = (totalAmount &lt; sub.all_data.length) ? sub.all_data.length : totalAmount; temp_arr.push(inner_array); }); }); let temp = []; let result = []; for (var i = 0; i &lt; totalAmount; i++) { if (this.checkboxValues.data_name.value) temp.push(this.checkboxValues.data_name.name); if (this.checkboxValues.data_status.value) temp.push(this.checkboxValues.data_status.name); } Object.values(this.checkboxValues).map(box =&gt; { if (box.name == this.checkboxValues.data_name.name) { result = result.concat(temp); } else if (box.name == this.checkboxValues.csv_title.name) { } else if (box.name != this.checkboxValues.data_status.name &amp;&amp; box.value) { result.push(box.name); } }); arr.push(result); arr = arr.concat(temp_arr); return arr; } return []; } </code></pre> <p>It looks like my code is working but I'm trying to make it look more professional and to have better logic. For example, I'm defining too many temp arrays. Also the <code>for</code> loop probably could be done better. I'll be more then glad to see a review for this function.</p>
[]
[ { "body": "<p>Couple of things right off the bat... Your first if statment should be a catch and return. like</p>\n\n<pre><code>if (typeof jsondata == \"undefined\" || !jsondata) {\n return [];\n}\n</code></pre>\n\n<p>That will keep the rest of the code with one less indent.</p>\n\n<p>You have a stray else if satement not doing anything.</p>\n\n<pre><code>else if (box.name == this.checkboxValues.csv_title.name) {\n\n}\n</code></pre>\n\n<p>I think your temp arrays are too ambiguous, you should at least comment what they are for.</p>\n\n<p>I see no reason why the contents of this for loop </p>\n\n<pre><code>for (var i = 0; i &lt; totalAmount; i++) {\n if (this.checkboxValues.data_name.value) temp.push(this.checkboxValues.data_name.name);\n if (this.checkboxValues.data_status.value) temp.push(this.checkboxValues.data_status.name);\n }\n</code></pre>\n\n<p>cannot be nested inside <code>main.subs.forEach</code> loop. That will reduce the amount of loops you have by 1.</p>\n\n<p>Overall I have a feeling you are making this way more complicated then it has to be. I would take a look at the code for your checkboxes and see if there's an easier way to relay that information into your Typescript. </p>\n\n<p>Ultimately you should end up with something like this</p>\n\n<pre><code>JSO2CSV: function(jsondata) {\n if (typeof jsondata == \"undefined\" || !jsondata)\n return [];\n\n let boxes = this.checkboxValues;\n let header = [];\n let result = []; //final array\n\n Object.values(boxes).map(box =&gt; {\n if(box.value)\n header.push(box.name)\n });\n\n jsondata.forEach(main =&gt; {\n main.subs.forEach(sub =&gt; {\n let subarr = [];\n //Build sub array\n if (boxes.main_name.value) \n subarr.push(main.name || 'N/A');\n if (boxes.sub_ward.value)\n subarr.push(sub.ward || 'N/A');\n if (boxes.sub_name.value)\n subarr.push(sub.name || 'N/A');\n if (boxes.sub_status.value)\n subarr.push(sub.status || 'N/A');\n sub.all_data.forEach(data =&gt; {\n if (boxes.data_name.value)\n subarr.push(data.name || 'N/A');\n if (boxes.data_status.value)\n subarr.push(data.status || 'N/A');\n });\n result.push(subarr);\n //Add to header if it's too short\n while(header.length &lt; sub.all_data.length - header.length){\n if (boxes.data_name.value)\n header.push(boxes.data_name.name);\n if (boxes.data_status.value)\n heaer.push(boxes.data_status.name);\n }\n });\n });\n\n result.unshift(header);\n\n return result;\n}\n</code></pre>\n\n<p>This is sudo code, but you can get a feel.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T19:23:15.853", "Id": "449953", "Score": "0", "body": "Thank you for your review. Can you please add on how should I build the header before the `forEach` loop if I need to calculate `totalAmount `." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T19:27:15.533", "Id": "449954", "Score": "0", "body": "Sure, give me a minute." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T19:55:32.857", "Id": "449957", "Score": "0", "body": "Updated to include header. Simplified the `.map` but it looks to me like that's what you were going for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T20:21:08.027", "Id": "449961", "Score": "0", "body": "have you tested it? it looks like define `sub` twice" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T20:25:15.777", "Id": "449962", "Score": "0", "body": "Good catch, no I have not tested it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T20:35:03.103", "Id": "449964", "Score": "0", "body": "Great thank you. What should I do in case of `checkboxValues.csv_title`? If this checkbox is unchecked, I don't want to include the title." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T20:47:43.917", "Id": "449967", "Score": "0", "body": "Maybe add to your if statement under the `.map` method... something like `if(box.value && box.name != 'CSV Title')` or else use the index, since it's the first element. Or you can just check them outright without the map method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T21:07:55.963", "Id": "449970", "Score": "0", "body": "maybe use `Object.keys` instead of `Object.values` then you can get your values and keys inside map." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T18:07:28.930", "Id": "230866", "ParentId": "230863", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T17:13:54.727", "Id": "230863", "Score": "3", "Tags": [ "javascript" ], "Title": "Converting JSON to CSV with Javascript" }
230863
<h3>Problem</h3> <p>Validate if a given string can be interpreted as a decimal or scientific number.</p> <h3>Examples:</h3> <pre><code>"0" =&gt; true " 0.1 " =&gt; true "abc" =&gt; false "1 a" =&gt; false "2e10" =&gt; true " -90e3 " =&gt; true " 1e" =&gt; false "e3" =&gt; false " 6e-1" =&gt; true " 99e2.5 " =&gt; false "53.5e93" =&gt; true " --6 " =&gt; false "-+3" =&gt; false "95a54e53" =&gt; false </code></pre> <h3>Code</h3> <p>With some help, I've solved the valid number LeetCode problem using C++ regex and <a href="https://codereview.stackexchange.com/questions/230848/leetcode-65-valid-number-python">Python</a>, which apparently seems to have a simple solution though. If you'd like to review the code and provide any change/improvement recommendations, please do so and I'd really appreciate that.</p> <pre><code>#include &lt;iostream&gt; #include &lt;regex&gt; using namespace std; // trim from start (in place) static inline void ltrim(std::string &amp;s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { return !std::isspace(ch); })); } // trim from end (in place) static inline void rtrim(std::string &amp;s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return !std::isspace(ch); }).base(), s.end()); } // trim from both ends (in place) static inline void trim(std::string &amp;s) { ltrim(s); rtrim(s); } // trim from start (copying) static inline std::string ltrim_copy(std::string s) { ltrim(s); return s; } // trim from end (copying) static inline std::string rtrim_copy(std::string s) { rtrim(s); return s; } // trim from both ends (copying) static inline std::string trim_copy(std::string s) { trim(s); return s; } int main() { vector&lt;string&gt; string_vector = { " 0 "," 0.1 "," abc ", "1 a"," 2e10 "," -90e3 ","1e", " e3 "," 6e-1 "," 99e2.5 ", " 53.5e93 "," --6 "," -+3 ", " 95a54e53 " }; regex expression_one("^[+-]?(?:\\d*\\.\\d+|\\d+\\.\\d*|\\d+)[Ee][+-]?\\d+$|^[+-]?(?:\\d*\\.\\d+|\\d+\\.\\d*|\\d+)$|^[+-]?\\d+$"); regex expression_two("^[+-]?(?:[0-9]*\\.[0-9]+|[0-9]+\\.[0-9]*|[0-9]+)[Ee][+-]?[0-9]+$|^[+-]?(?:[0-9]*\\.[0-9]+|[0-9]+\\.[0-9]*|[0-9]+)$|^[+-]?[0-9]+$"); regex expression_three("^(?:(?:[+-]?(?:\\d*[.]\\d+|\\d+[.]\\d*|\\d+)[Ee][+-]?\\d+)|(?:[+-]?(?:\\d*[.]\\d+|\\d+[.]\\d*|\\d+))|[+-]?\\d+)$"); for (const auto &amp;input_string: string_vector) { auto trim_input_string = trim_copy(input_string); if (std::regex_match(trim_input_string, expression_two)) cout &lt;&lt; "1️⃣ Test Expression 1: '" &lt;&lt; input_string &lt;&lt; "' is a valid number." &lt;&lt; endl; if (std::regex_match(trim_input_string, expression_two)) cout &lt;&lt; "2️⃣ Test Expression 2: '" &lt;&lt; input_string &lt;&lt; "' is a valid number." &lt;&lt; endl; if (std::regex_match(trim_input_string, expression_two)) cout &lt;&lt; "3️⃣ Test Expression 3: '" &lt;&lt; input_string &lt;&lt; "' is a valid number." &lt;&lt; endl; } } </code></pre> <h3>Output</h3> <pre><code>1️⃣ Test Expression 1: ' 0 ' is a valid number. 2️⃣ Test Expression 2: ' 0 ' is a valid number. 3️⃣ Test Expression 3: ' 0 ' is a valid number. 1️⃣ Test Expression 1: ' 0.1 ' is a valid number. 2️⃣ Test Expression 2: ' 0.1 ' is a valid number. 3️⃣ Test Expression 3: ' 0.1 ' is a valid number. 1️⃣ Test Expression 1: ' 2e10 ' is a valid number. 2️⃣ Test Expression 2: ' 2e10 ' is a valid number. 3️⃣ Test Expression 3: ' 2e10 ' is a valid number. 1️⃣ Test Expression 1: ' -90e3 ' is a valid number. 2️⃣ Test Expression 2: ' -90e3 ' is a valid number. 3️⃣ Test Expression 3: ' -90e3 ' is a valid number. 1️⃣ Test Expression 1: ' 6e-1 ' is a valid number. 2️⃣ Test Expression 2: ' 6e-1 ' is a valid number. 3️⃣ Test Expression 3: ' 6e-1 ' is a valid number. 1️⃣ Test Expression 1: ' 53.5e93 ' is a valid number. 2️⃣ Test Expression 2: ' 53.5e93 ' is a valid number. 3️⃣ Test Expression 3: ' 53.5e93 ' is a valid number. </code></pre> <h3>RegEx Circuit</h3> <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> <p><a href="https://i.stack.imgur.com/725JB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/725JB.png" alt="enter image description here"></a></p> <hr> <h3><a href="https://regex101.com/r/ygzjKw/1/" rel="nofollow noreferrer">RegEx Demo 1</a></h3> <h3><a href="https://regex101.com/r/OCAFF2/1/" rel="nofollow noreferrer">RegEx Demo 2</a></h3> <p>If you wish to explore the expression, it's been explained on the top right panel of <a href="https://regex101.com/r/ygzjKw/1/" rel="nofollow noreferrer">regex101.com</a>. If you'd like, you can also watch in <a href="https://regex101.com/r/ygzjKw/1/debugger" rel="nofollow noreferrer">this link</a>, how it would match against some sample inputs.</p> <hr> <h3>Source</h3> <ul> <li><a href="https://leetcode.com/problems/valid-number/" rel="nofollow noreferrer">LeetCode Valid Number</a></li> <li><a href="https://codereview.stackexchange.com/questions/230848/leetcode-65-valid-number-python">LeetCode 65: Valid Number (Python)</a></li> </ul>
[]
[ { "body": "<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Don't do <code>using namespace std;</code></a>.</p></li>\n<li><p><code>inline</code> is really only useful for defining non-template functions in header files. Modern compilers generally decide what functions to actually inline themselves.</p></li>\n<li><p>To <a href=\"https://en.cppreference.com/w/cpp/string/byte/isspace\" rel=\"nofollow noreferrer\">use <code>std::isspace</code> correctly</a> we must cast the argument from a <code>char</code> to an <code>unsigned char</code> before passing it into the function.</p></li>\n<li><p><code>std::regex_match</code> has a version that takes iterators. So we don't need to copy or modify the input strings:</p>\n\n<pre><code>auto const is_not_space = [] (unsigned char c) {\n return std::isspace(c) == 0;\n};\n\nfor (auto const&amp; s: string_vector) {\n auto const begin = std::find_if(s.begin(), s.end(), is_not_space);\n auto const end = std::find_if(s.rbegin(), std::reverse_iterator(begin), is_not_space).base();\n\n if (std::regex_match(begin, end, expression_two))\n ...\n</code></pre></li>\n<li><p>The test code checks <code>expression_two</code> three times, and doesn't use <code>expression_one</code> or <code>expression_three</code>!</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T08:35:27.987", "Id": "230893", "ParentId": "230864", "Score": "2" } } ]
{ "AcceptedAnswerId": "230893", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T17:16:40.330", "Id": "230864", "Score": "2", "Tags": [ "c++", "beginner", "algorithm", "strings", "regex" ], "Title": "LeetCode 65: Valid Number (C++)" }
230864
<p>StringBuilder class is a common class that many have become accustom to, including me.</p> <p>An individual posted a question regarding if there was a comparable method in typescript. Several solutions were mention or linked, but none contained a class. Here is a small class that embodies some of the common StringBuilder methods. </p> <p>In addition, when joining numeric strings, special care must be taken with the normal typescript/javascript operators. The StringBuilder class will treat all as strings and not attempt a numeric conversion and add values.</p> <p>It can be expanded upon greatly to fit your needs. </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>export class StringBuilder { strArray: Array&lt;string&gt; = new Array&lt;string&gt;(); constructor() { } Get(nIndex:number): string { let str:string = null; if( (this.strArray.length &gt; nIndex) &amp;&amp; (nIndex &gt;= 0) ) { str = this.strArray[nIndex]; } return(str); } IsEmpty(): boolean { if(this.strArray.length == 0) return true; return(false); } Append(str: string): void { if(str != null) this.strArray.push(str); } ToString(): string { let str:string = this.strArray.join(""); return(str); } ToArrayString(delimeter: string): string { let str:string = this.strArray.join(delimeter); return(str); } Clear() { this.strArray.length = 0; } }</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T13:54:53.827", "Id": "450016", "Score": "0", "body": "Could you please supply some example code on how to use it." } ]
[ { "body": "<p>In JavaScript/TypeScript it is custom to place the opening braces at the end of the line instead of on a new line by itself.</p>\n\n<p>Insert a space between control statements and the opening round brackets. (Also don't put round brackets around the expression of a <code>return</code> statement.)</p>\n\n<p>Always use braces even when you only have one line after the statement.</p>\n\n<p>Example: </p>\n\n<pre><code>if (str != null) {\n this.strArray.push(str);\n}\n</code></pre>\n\n<p>Always have a space between the colon and type.</p>\n\n<p>Method names should start with a lower case letter, especially since you should be overriding <code>toString</code>.</p>\n\n<p>There should be a blank line between methods.</p>\n\n<hr>\n\n<p>The empty constructor is pointless and should be left out.</p>\n\n<p>The <code>Get</code> method is not really a good idea. The fact that your string builder uses an array internally shouldn't influence the interface of the class.</p>\n\n<p>If you do have a <code>Get</code> method like this, then you should consider emulating the signature of a regular array and return <code>undefined</code> instead of <code>null</code>, when the index is out of bounds. That actually would save you the checking of the bounds yourself:</p>\n\n<pre><code>get(nIndex: number): string {\n return this.strArray[nIndex];\n}\n</code></pre>\n\n<p>In <code>IsEmpty</code> the expression <code>this.strArray.length == 0</code> (should be a <code>===</code> BTW) returns a boolean, so you can return that directly:</p>\n\n<pre><code>isEmpty(): boolean {\n return this.strArray.length === 0;\n}\n</code></pre>\n\n<p>Also this may not be correct way to determine an empty StringBuilder. If the array contained only empty strings, shouldn't the StringBuilder still be consider empty? But this could be covered by the next point.</p>\n\n<p><code>Append</code> should not only ignore <code>null</code> as a parameter, but also <code>undefined</code> and empty strings, so just do:</p>\n\n<pre><code>append(str: string): void {\n if (!str) {\n this.strArray.push(str);\n }\n}\n</code></pre>\n\n<p><code>ToArrayString</code> doesn't seem to be a good method name. I'd suggest something like <code>joinToString</code>. Also there is no need to use a variable in there. </p>\n\n<pre><code>joinToString(delimeter: string): string {\n return this.strArray.join(delimeter);\n}\n</code></pre>\n\n<p>And avoid a little bit of duplicate code by having <code>toString</code> call <code>ToArrayString</code>/<code>joinToString</code>.</p>\n\n<pre><code>toString(): string {\n return this.joinToString(\"\");\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T12:02:46.457", "Id": "230900", "ParentId": "230865", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T17:29:03.453", "Id": "230865", "Score": "2", "Tags": [ "typescript" ], "Title": "StringBuilder: To Build or Not to Build" }
230865
<pre><code>tablou = input("Enter values delimited by space: ") b = tablou.split() t = [] # initial list with int() contents for l in b: r = int(l) t.append(r) </code></pre> <p>I have to do multiple assignments which require working with lists of integers/floats. Above is what I'm using for converting a string to a proper list of integers. I was wondering if there's any way to optimize the code in a such way that it won't need to use memory to keep <code>tablou</code>, <code>b</code> and the final list. I would be actually working with <code>t</code></p> <p>I'm not sure if I used the right terms to describe the issue, I'm still learning.</p>
[]
[ { "body": "<h2>Releasing memory</h2>\n\n<p>If you assign <code>None</code> to your variables, their contents is lost and the memory will (eventually) be reclaimed.</p>\n\n<pre><code>tablou = input(\"Enter values delimited by space: \")\n\nb = tablou.split()\ntablou = None\n\nt = [] # initial list with int() contents\n\nfor l in b:\n r = int(l)\n t.append(r)\nb = None\nl = None\nr = None\n</code></pre>\n\n<h2>Forgetting the variables</h2>\n\n<p>The variables <code>tablou</code>, <code>l</code>, <code>b</code>, and <code>r</code> will still exist; they will just contain the value <code>None</code>. If you accidentally use the variable <code>tablou</code> again, you won't get a <code>NameError: name 'tablou' is not defined</code>, although you may get an error stating the operation cannot be performed on the value <code>None</code>.</p>\n\n<p>Better would be to delete the variables when they are no longer needed:</p>\n\n<pre><code>del tablou\ndel l, b, r\n</code></pre>\n\n<p>After deleting the variables, it is an error to refer to them again, without first storing a value under that name.</p>\n\n<h2>List Comprehension</h2>\n\n<p>Repeatedly appending values to a list is an expensive operation. It is usually faster to create the list using \"list comprehension\".</p>\n\n<p>First, note that instead of this ...</p>\n\n<pre><code>t = []\n\nfor l in b:\n r = int(l)\n t.append(r)\n</code></pre>\n\n<p>... you could write this, eliminating the <code>r</code> variable:</p>\n\n<pre><code>t = []\n\nfor l in b:\n t.append(int(l))\n</code></pre>\n\n<p>Then, you can replace the list creation, loop, append with the following:</p>\n\n<pre><code>t = [ int(l) for l in b ]\n</code></pre>\n\n<p>This does the same thing as the former code, but without the repeated <code>append</code> call. As a bonus, the list comprehension variable, <code>l</code> does not escape into the local scope; there is no need to <code>del l</code>.</p>\n\n<h2>Mapping</h2>\n\n<p>Applying the same operation to every element of a list is called a \"mapping\", and Python comes with a built in function <code>map()</code> to do just that.</p>\n\n<p>In your specific case, you are calling <code>int( )</code> on every item in the list <code>b</code>, so instead of:</p>\n\n<pre><code>t = [ int(l) for l in b ]\n</code></pre>\n\n<p>you could write:</p>\n\n<pre><code>t = list(map(int, b))\n</code></pre>\n\n<p><strong>Advance topic</strong>: The <code>map()</code> function actually returns an iterator, rather than a list. In many cases, you can avoid the call to <code>list()</code>, which iterates over all the items the iterator can produce and builds a list of out them, and simply use the returned iterator directly.</p>\n\n<h2>One-liner</h2>\n\n<p>You can reduce your code to one line, removing all temporary variables, using nested calls:</p>\n\n<pre><code>t = list(map(int, input(\"Enter values delimited by space: \").split()))\n</code></pre>\n\n<p>I don't recommend it, however. It does not result in easy-to-understand code. It is better to separate \"user input\" from \"processing\".</p>\n\n<h2>Variable Names</h2>\n\n<p><code>t</code>, <code>r</code>, <code>l</code> and <code>b</code> are horrible variable names. Name the variables with longer, descriptive names.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T22:21:53.197", "Id": "230877", "ParentId": "230870", "Score": "6" } } ]
{ "AcceptedAnswerId": "230877", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T19:34:04.887", "Id": "230870", "Score": "3", "Tags": [ "python", "beginner", "homework" ], "Title": "Converting an input of space delimited integers to a list" }
230870
<h3>Problem</h3> <p>Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is a string that contains same characters ([A-Za-z0-9]) and the order of characters can be different. </p> <h3>Code</h3> <p>I've solved the anagram problem using a few methods with Python and JavaScript. If you'd like to review the codes and provide any change/improvement recommendations please do so, and I'd really appreciate that.</p> <h3>Python</h3> <pre><code>import re def are_anagram_naive_three(string_one: str, string_two: str) -&gt; bool: """ Returns True if two strings are anagram """ return prep_input_strings_for_naive_three(string_one) == prep_input_strings_for_naive_three(string_two) def are_anagram_naive_two(string_one: str, string_two: str) -&gt; bool: """ Returns True if two strings are anagram """ return prep_input_strings_for_naive_two(string_one) == prep_input_strings_for_naive_two(string_two) def prep_input_strings_for_naive_three(string: str) -&gt; bool: """ Prepares the input string using sorted, re.sub and lower methods """ return sorted(replace_non_letters_digits(string.lower())) def prep_input_strings_for_naive_two(string: str) -&gt; dict: """ Prepares the input string using a hashmap, re.sub and lower methods """ return generate_hashmap(replace_non_letters_digits(string_one.lower())) def generate_hashmap(string: str) -&gt; dict: """ Generates a hashmap: Keys are [A-Za-z0-9] and Values are the number of times those repeated """ hashmap_char_counter = {} for char in string: try: hashmap_char_counter[char] = hashmap_char_counter[char] + 1 except KeyError: hashmap_char_counter[char] = 1 return hashmap_char_counter def replace_non_letters_digits(string: str) -&gt; str: """ Re-subs non letters and digits of an input string """ return re.sub(r'(?i)[^a-z0-9]+', '', string) def are_anagram_naive_one(string_one: str, string_two: str) -&gt; bool: """ Returns boolean if two hashmaps of two cleaned strings are equal """ string_one = re.sub(r'(?i)[^a-z0-9]+', "", string_one) string_two = re.sub(r'(?i)[^a-z0-9]+', "", string_two) hashmap_two, hashmap_two = {}, {} for letter in string_one.lower(): if letter in hashmap_two.keys(): hashmap_two[letter] += 1 else: hashmap_two[letter] = 1 for letter in string_two.lower(): if letter in hashmap_two.keys(): hashmap_two[letter] += 1 else: hashmap_two[letter] = 1 return hashmap_two == hashmap_two if __name__ == '__main__': # ---------------------------- TEST --------------------------- DIVIDER_DASH_LINE = '-' * 50 GREEN_APPLE = '\U0001F34F' strings_one = ["fairy tales", "eat for BSE", "bad credit", "he bugs Gore", "I’m a jerk but listen", "monkeys write", "rich-chosen goofy cult", "Uncle Sam's standard rot", "vile", "enraged", "tap", "elegant man", "twelve plus one", "obecalp", "fluster", "real fun", "true lady", "store scum", "over fifty", "I am a weakish speller", "Radium came", "He bugs Gore", "I’m a jerk but listen", "I am Lord Voldemort"] strings_two = ["rail safety", "roast beef", "debit card", "George Bush", "Justin Timberlake", "New York Times", "Church of Scientology", "McDonald's restaurants", "evil", "angered", "pat", "a gentleman", "eleven plus two", "placebo", "restful", "funeral", "adultery", "customers", "forty five", "William Shakespeare", "Madam Curie", "George Bush", "Tom Marvolo Riddle"] for string_one in strings_one: for string_two in strings_two: if are_anagram_naive_one(string_one, string_two) is True and are_anagram_naive_two(string_one, string_two) is True and are_anagram_naive_three(string_one, string_two) is True: print(DIVIDER_DASH_LINE) print(f'{GREEN_APPLE} "{string_one}" and "{string_two}" are anagram.') break </code></pre> <h3>Output</h3> <pre><code>-------------------------------------------------- "fairy tales" and "rail safety" are anagram. -------------------------------------------------- "eat for BSE" and "roast beef" are anagram. -------------------------------------------------- "bad credit" and "debit card" are anagram. -------------------------------------------------- "he bugs Gore" and "George Bush" are anagram. -------------------------------------------------- "I’m a jerk but listen" and "Justin Timberlake" are anagram. -------------------------------------------------- "monkeys write" and "New York Times" are anagram. -------------------------------------------------- "rich-chosen goofy cult" and "Church of Scientology" are anagram. -------------------------------------------------- "Uncle Sam's standard rot" and "McDonald's restaurants" are anagram. -------------------------------------------------- "vile" and "evil" are anagram. -------------------------------------------------- "enraged" and "angered" are anagram. -------------------------------------------------- "tap" and "pat" are anagram. -------------------------------------------------- "elegant man" and "a gentleman" are anagram. -------------------------------------------------- "twelve plus one" and "eleven plus two" are anagram. -------------------------------------------------- "obecalp" and "placebo" are anagram. -------------------------------------------------- "fluster" and "restful" are anagram. -------------------------------------------------- "real fun" and "funeral" are anagram. -------------------------------------------------- "true lady" and "adultery" are anagram. -------------------------------------------------- "store scum" and "customers" are anagram. -------------------------------------------------- "over fifty" and "forty five" are anagram. -------------------------------------------------- "I am a weakish speller" and "William Shakespeare" are anagram. -------------------------------------------------- "Radium came" and "Madam Curie" are anagram. -------------------------------------------------- "He bugs Gore" and "George Bush" are anagram. -------------------------------------------------- "I’m a jerk but listen" and "Justin Timberlake" are anagram. -------------------------------------------------- "I am Lord Voldemort" and "Tom Marvolo Riddle" are anagram. </code></pre> <h3>JavaScript</h3> <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>// ------------------- Problem ------------------- // Check to see if two provided strings are anagrams. // One string is an anagram of another if it uses the same characters // in the same quantity. Only consider characters [A-Za-z0-9], not spaces // or punctuation. Consider capital letters to be the same as lower case // ------------------- Input Examples ------------------- // ('rail safety', 'fairy tales') --&gt; True // ('RAIL! SAFETY!', 'fairy tales') --&gt; True // ('Hi there', 'Bye there') --&gt; False function are_anagram_sort_join(string_one, string_two) { string_one = replace_non_letters_digits(string_one); string_two = replace_non_letters_digits(string_two); if (string_one.split('').sort().join('') === string_two.split('').sort().join('')) { return true; } return false; } function are_anagram_sort_stringify(string_one, string_two) { string_one = replace_non_letters_digits(string_one); string_two = replace_non_letters_digits(string_two); if (JSON.stringify(string_one.split('').sort()) === JSON.stringify(string_two.split('').sort())) { return true; } return false; } function are_anagram_naive(string_one, string_two) { string_one = replace_non_letters_digits(string_one); string_two = replace_non_letters_digits(string_two); if (string_one.length != string_two.length) { return false; } const string_one_hashmap = generate_hashmap(string_one); const string_two_hashmap = generate_hashmap(string_two); for (let char in string_one_hashmap) { if (string_one_hashmap[char] != string_two_hashmap[char]) { return false; } } return true; } function generate_hashmap(input_str) { hashmap_char_counter = {}; for (let char of input_str) { hashmap_char_counter[char] = hashmap_char_counter[char] + 1 || 1; } return hashmap_char_counter; } function replace_non_letters_digits(str) { return str.replace(/[^a-z0-9]/gi, ''); } strings_one = ["fairy tales", "eat for BSE", "bad credit", "he bugs Gore", "I’m a jerk but listen", "monkeys write", "rich-chosen goofy cult", "Uncle Sam's standard rot", "vile", "enraged", "tap", "elegant man", "twelve plus one", "obecalp", "fluster", "real fun", "true lady", "store scum", "over fifty", "I am a weakish speller", "Radium came", "He bugs Gore", "I’m a jerk but listen", "I am Lord Voldemort"]; strings_two = ["rail safety", "roast beef", "debit card", "George Bush", "Justin Timberlake", "New York Times", "Church of Scientology", "McDonald's restaurants", "evil", "angered", "pat", "a gentleman", "eleven plus two", "placebo", "restful", "funeral", "adultery", "customers", "forty five", "William Shakespeare", "Madam Curie", "George Bush", "Tom Marvolo Riddle"]; for (let string_one of strings_one) { for (let string_two of strings_two) { if (are_anagram_naive(string_one, string_two) &amp;&amp; are_anagram_sort_stringify(string_one, string_two) &amp;&amp; are_anagram_sort_join(string_one, string_two)) { console.log(' "'.concat(string_one, '" and "', string_two, '" are anagrams!')); } } }</code></pre> </div> </div> </p> <hr> <h3>Source</h3> <ul> <li><p><a href="https://www.geeksforgeeks.org/check-whether-two-strings-are-anagram-of-each-other/" rel="nofollow noreferrer">Check whether two strings are anagram of each other - Geeks for Geeks</a></p></li> <li><p><a href="https://en.wikipedia.org/wiki/Anagram" rel="nofollow noreferrer">Anagram - wiki</a></p></li> </ul>
[]
[ { "body": "<h1>Generate Hashmap</h1>\n\n<p>There is a data structure that's well optimized for this task: <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>collections.Counter</code></a>. It will take any iterable and generate a dictionary with keys being elements of your iterable and values are the number of occurrences:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\n\nx, y = 'fairy tales', 'rail safety'\nc1, c2 = Counter(x), Counter(y)\n\nc1\nCounter({'a': 2, 'f': 1, 'i': 1, 'r': 1, 'y': 1, ' ': 1, 't': 1, 'l': 1, 'e': 1, 's': 1})\n</code></pre>\n\n<p>And they also do equivalence testing:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>c1 == c2\nTrue\n</code></pre>\n\n<h1>Filtering strings</h1>\n\n<p>This could be done in a generator expression using the <code>str.isalnum</code> function, removing the need for regex:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Iterator\n\ndef clean_string(s: str) -&gt; Iterator[str]:\n \"\"\"\n yields lowercased strings that are alphanumeric characters\n only\n \"\"\"\n yield from (c for c in s.lower() if c.isalnum())\n</code></pre>\n\n<p>Which can directly be consumed by <code>Counter</code></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\n\nx, y = \"I’m a jerk but listen\", \"Justin Timberlake\"\n\nc1, c2 = Counter(clean_string(x)), Counter(clean_string(y))\n\nc1 == c2\n\nTrue\n</code></pre>\n\n<p>Alternatively, you can use the builtin <code>filter</code> and return that, which <code>Counter</code> can also consume:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def clean_string(s: str) -&gt; Iterable[str]:\n \"\"\"\n returns a filter object which yields only \n alphanumeric characters from a string\n \"\"\"\n return filter(str.isalnum, s.lower())\n</code></pre>\n\n<p>Fitting this into your <code>__main__</code> loop with a function to check string1 against string2:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def is_anagram(s1: str, s2: str) -&gt; bool:\n \"\"\"\n returns a boolean based on equivalence-testing the Counters\n of two strings. The strings are filtered to only include alphanumeric\n characters\n \"\"\"\n return Counter(clean_string(s1)) == Counter(clean_string(s2))\n\nif __name__ == \"__main__\":\n ~snip~\n for string1 in strings_one:\n for string_two in strings_two:\n anagram = is_anagram(string1, string2)\n\n if anagram:\n # print things here\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T00:35:31.170", "Id": "230880", "ParentId": "230874", "Score": "1" } } ]
{ "AcceptedAnswerId": "230880", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-16T21:44:31.903", "Id": "230874", "Score": "1", "Tags": [ "python", "javascript", "beginner", "algorithm", "strings" ], "Title": "Anagram (Python, JavaScript)" }
230874
<p>I am writing a simple script that will combine two images at a pixel level, selecting every other pixel from one image, and the other pixels from a second image.</p> <pre><code>from PIL import Image import struct print("Photo 1: ", end="") photo1 = Image.open(input()) # First image, 1920 by 1080 photo1 = photo1.convert("RGB") print("Photo 2: ", end="") photo2 = Image.open(input()) # Second image, 1920 x 1080 photo2 = photo2.convert("RGB") width = photo1.size[0] # define W and H height = photo1.size[1] print("Output file: ", end="") output = input() data = str.encode("") for y in range(0, height): # counts to 1079 row = "" for x in range(0, width):# counts to 1920 if ((y + x) % 2) == 0: # makes every other pixel and alternates # on each line, making a checker board pattern RGB = photo1.getpixel((x, y)) print("Even", y) # how far am I? else: RGB = photo2.getpixel((x, y)) print("Odd", y) # how far aim I? R, G, B = RGB # now you can use the RGB value data += struct.pack("B", R) + struct.pack("B", G) + struct.pack("B",B) # store RGB values in byte format in variable "data" new = Image.frombytes("RGB", (1920, 1080), data)# change value if not 1920 x 1080 new.save(output, "PNG") # make new image </code></pre> <p>Sorry if the copy/paste ing messes with python indentation. This script take a good 10 minutes to run on my laptop</p> <ul> <li>Intel Core i5</li> <li>8 GB ram</li> <li>Running linux (Fedora 30) Is this just going to take 10 minutes to grab all the individual pixel values, or is there any thing that is making this code inefficient?</li> </ul> <p>Also, I am using python3.7 and 3 at the moment, but I also can use 2.7 if needed.</p> <p>These are the two photos I am using:</p> <p><a href="https://i.stack.imgur.com/ZJVjI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZJVjI.jpg" alt="enter image description here"></a><a href="https://i.stack.imgur.com/JDnxC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JDnxC.jpg" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T07:11:43.300", "Id": "449988", "Score": "2", "body": "Can you add a thumbnails of input 2 images and the final resulting image into your question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T07:41:59.893", "Id": "455218", "Score": "0", "body": "Here are the photos I am using. They are just free photos found online." } ]
[ { "body": "<h2>Tuple unpacking</h2>\n\n<pre><code>width = photo1.size[0] # define W and H\nheight = photo1.size[1]\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>width, height = photo1.size\n</code></pre>\n\n<h2>Use <code>input</code> properly</h2>\n\n<p>Don't print here:</p>\n\n<pre><code>print(\"Output file: \", end=\"\")\noutput = input()\n</code></pre>\n\n<p>Instead,</p>\n\n<pre><code>output = input('Output file: ')\n</code></pre>\n\n<h2>Range default start</h2>\n\n<p>Don't include the 0 in these calls:</p>\n\n<pre><code>for y in range(0, height): # counts to 1079\n for x in range(0, width):# counts to 1920\n</code></pre>\n\n<h2>Only call <code>pack</code> once</h2>\n\n<pre><code> data += struct.pack(\"B\", R) + struct.pack(\"B\", G) + struct.pack(\"B\",B)\n</code></pre>\n\n<p>should become, I think,</p>\n\n<pre><code>data += struct.pack('BBB', R, G, B)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-24T02:44:40.973", "Id": "231239", "ParentId": "230878", "Score": "6" } }, { "body": "<p>In addition to Reinderein's answer, there are still a lot of things that could be improved in your code.</p>\n\n<h1>Hardcoded values</h1>\n\n<p>You use hardcoded values, which make the code hard to use if you want to modify the inputs or the code itself. Consider the following line:</p>\n\n<pre><code>new = Image.frombytes(\"RGB\", (1920, 1080), data)# change value if not 1920 x 1080\n</code></pre>\n\n<p>Why not just use the <code>height</code> and <code>width</code> variables that are already defined?</p>\n\n<h1>Data checks</h1>\n\n<p>Your procedure requires that the 2 input images are the same size. It would be good practice to check if this is the case before trying to combine them, and raise a relevant exception if they are not.</p>\n\n<h1>Encapsulation</h1>\n\n<p>It makes sense to encapsulate the image combining procedure in a function: pass that function 2 images, output the combined image. That way, the code is much more reusable and easy to test.</p>\n\n<p>Adding a <code>__main__</code> guard is a good idea for using the function.</p>\n\n<h1>Single responsibility</h1>\n\n<p>The image combining procedure should do just that. Your code also prints a bunch of stuff in the middle of doing that, and it really shouldn't.</p>\n\n<h1>Style</h1>\n\n<p>Your use of comments is inconsistent and all over the place. It makes the code hard to read.</p>\n\n<h1>Performance</h1>\n\n<p>There is a lot of room for improvements here, and the previous review barely tackles it. Using a single call to <code>struct.pack()</code> in the loop is probably better than 3, but the codes still takes minutes to run with 1920x1080 images. To be fair, I didn't have the patience to wait until it's done processing.</p>\n\n<p>Given how slow the code is, I understand why you included <code>print</code> statements to your loop to monitor how far along the processing is, but consider this code:</p>\n\n<pre><code>for y in range(1080):\n for x in range(1920):\n if ((y + x) % 2) == 0: \n print(\"Even\", y)\n else:\n print(\"Odd\", y)\n</code></pre>\n\n<p>This alone takes minutes to run. Comparing to this:</p>\n\n<pre><code>for y in range(1080):\n for x in range(1920):\n if ((y + x) % 2) == 0: \n _ = \"foo\"\n else:\n _ = \"bar\"\n</code></pre>\n\n<p>This runs almost instantly. The lesson here is that <code>print</code> is slow, and should not be in an inner loop, even if you discard the single responsibility principle.</p>\n\n<p>Another bottleneck is the following line in the inner loop:</p>\n\n<pre><code>data += struct.pack(\"B\", R) + struct.pack(\"B\", G) + struct.pack(\"B\",B)\n</code></pre>\n\n<p>This appends more data to the <code>data</code> variable each time the line is run, which is a bit over 2 million times for your sample images. This means reallocating memory to fit the progressively larger variable a LOT of times, which is a slow process.</p>\n\n<p>I have no experience with <code>struct</code> binary data and don't know how to preallocate the memory to fit the final data. Luckily for me, PIL has a <code>Image.fromarray()</code> method which take NumPy arrays as an input, which are easy to work with. That way, you can pre-allocate the required memory with something like <code>data = np.zeros((height, width, 3), \"uint8\")</code>, and modify the values as needed without reallocating memory.</p>\n\n<p>Using this method, the required time to combine two 1920x1080 px images drops to a couple of seconds.</p>\n\n<h1>Putting it all together</h1>\n\n<p>Here is an example of what the code could look like after applying all these recommendations:</p>\n\n<pre><code>from PIL import Image\nimport numpy as np\n\n\ndef combine_images(image_1, image_2):\n \"\"\"Combines two PIL images in a checkerboard pattern\n\n :param image_1: the first PIL image to combine\n :param image_2: the second PIL image to combine\n\n :return: A PIL Image\"\"\"\n\n image_1 = image_1.convert(\"RGB\")\n image_2 = image_2.convert(\"RGB\")\n\n if (image_1.size != image_2.size):\n raise ValueError(\"Images must be the same size\")\n width, height = image_1.size\n\n data = np.zeros((height, width, 3), \"uint8\")\n for y in range(height): \n for x in range(width):\n if ((y + x) % 2) == 0:\n data[y][x] = image_1.getpixel((x, y))\n else:\n data[y][x] = image_2.getpixel((x, y))\n return Image.fromarray(data)\n\n\nif __name__ == \"__main__\":\n image_1 = Image.open(input(\"Path to image 1:\\n\"))\n image_2 = Image.open(input(\"Path to image 2:\\n\"))\n output = input(\"Path to output:\\n\")\n\n combine_images(image_1, image_2).save(output, \"PNG\")\n\n print(\"Done!\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T11:26:27.843", "Id": "232989", "ParentId": "230878", "Score": "4" } } ]
{ "AcceptedAnswerId": "232989", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T00:13:56.397", "Id": "230878", "Score": "5", "Tags": [ "python", "performance", "python-3.x", "file", "image" ], "Title": "Python image combiner reading writing" }
230878
<p>I have a problem where I need to construct a given string from scratch for a minimum cost by either:</p> <p>Appending a new character for a cost A</p> <p>Appending a substring of my existing string for a cost B</p> <p>E.g. for a string "abcabc" with a cost of A = 10, B = 11</p> <p>a 10 ab 20 abc 30 abcabc 41</p> <p>First I tried a greedy algorithm but it didn't give the optimal answer for this problem. I had the idea to use the dijkstra algorithm and a priority queue, so for each popped node I calculated the possibilities for A and B and pushed the new nodes back onto the queue. Since you can't change keys on the priority queue I use an int array ("visited") to keep track of the visited nodes.</p> <p>However my solution isn't fast enough to finish 30000 char strings in 2 seconds so I wanted to ask for some pointers on how I could optimise/change my approach.</p> <pre><code>typedef pair&lt;int, int&gt; iPair; int solve(string &amp;s, int a, int b) { priority_queue&lt;iPair, iPair&lt;Node&gt;, greater&lt;iPair&gt;&gt; pq; int visited[s.size()]; for (int i = 0; i &lt; s.size(); ++i) visited[i] = -1; pq.push(make_pair(a, 0)); iPair p; while (!pq.empty()) { p = pq.top(); pq.pop(); if (visited[p.second] == -1) visited[p.second] = 1; else continue; if (p.second == s.size() - 1) break; // Handle append costs pq.push(make_pair(p.first + a, p.second + 1)); // Handle clone costs int j; int i = p.second; if (s.size() &gt; 2*i + 2) j = 2*i + 1; else j = s.size() - 1; for (; j &gt; i + 1; --j) { if(s.substr(0, i+1).find(s.substr(i+1, j-i)) != string::npos) { pq.push(make_pair(p.first + b, j)); break; } } } return p.current_cost; } </code></pre> <p>As I say I'm looking for how I'm out of ideas how how to optimise this code and I'm not sure Dijkstra is even the right approach. I read up how A* search can speed up Dijkstra but I couldn't come up with an easy heuristic function.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T04:43:59.010", "Id": "449984", "Score": "1", "body": "Dijkstra can work, but the reason your algorithm takes too long is in the clone costs part. You spend \\(O(n^2)\\) time finding the longest prefix from `i` that is a substring in `s[0,i)`. Also, you might want to consider dynamic programming instead of Dijkstra." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T08:11:33.900", "Id": "449993", "Score": "3", "body": "Doesn't compile. Even with the appropriate includes and a set of `using` declarations, `iPair<Node>` makes no sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T17:11:39.230", "Id": "450480", "Score": "0", "body": "@esperski, please make the necessary changes to fix the code. I don't think it requires much to turn it into **working code** so that we can re-open it for review. There's some issues (of varying subtlety) that I would like to help with." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T00:33:48.750", "Id": "230879", "Score": "1", "Tags": [ "c++", "algorithm", "strings", "time-limit-exceeded" ], "Title": "Algorithm for building a string by appending and cloning substrings" }
230879
<p>I've prepared a tenpin bowling scoring game in Java - <a href="https://github.com/chalcrow/DiusBowlingGame/tree/ac6629cd6f1e8d9da7dfe500d28ed4e64cadb404" rel="nofollow noreferrer">https://github.com/chalcrow/DiusBowlingGame</a></p> <p>I'd like a critical review of the code to identify potential improvements. The code runs like this:</p> <p><strong>Main.java</strong></p> <pre><code>package com.dius.bowling; public class Main { private DiusBowlingGame game; public static void main(String[] args) { // method to perform rolls and calculate totalscore DiusBowlingGame game = new DiusBowlingGame(); // for a new game, we must advance to the 1st frame game.startGame(); game.simulateGame(); } } </code></pre> <p><strong>Main interface (BowlingGame.java)</strong></p> <pre><code>package com.dius.bowling; /** * Interface for a bowling game. */ public interface BowlingGame { /** * roll method specifying how many pins have been knocked down * @param noOfPins no. of pins knocked down */ void roll(int noOfPins); /** * get player's current score * @return player's current score */ int score(); } </code></pre> <p><strong>DiusBowlingGame.java</strong></p> <pre><code>package com.dius.bowling; import java.util.*; import static com.dius.bowling.Constants.*; /** * Scoring system for tenpin bowls */ public class DiusBowlingGame implements BowlingGame { ArrayList&lt;BowlingFrame&gt; gameFrames = new ArrayList&lt;BowlingFrame&gt;(); public void roll (int noOfPins) { System.out.println("frame" + getCurrentFrameNo() + ", rolled " + noOfPins); doSpecialScoresForPreviousFrame(noOfPins); getCurrentFrame().frameScore += noOfPins; if (isFirstRollOfFrame()) { getCurrentFrame().roll1 = new Roll(); getCurrentFrame().roll1.pinsKnockedDown = noOfPins; // a strike can only occur on the 1st roll - we need to check if this is a strike getCurrentFrame().roll1.isStrike = this.isStrike(noOfPins); displayScore(); if (this.isStrike(noOfPins)) { advanceFrame(); } } else { // this is the 2nd roll getCurrentFrame().roll2 = new Roll(); getCurrentFrame().roll2.pinsKnockedDown = noOfPins; // a spare can only occur on the 2nd roll - we need to check if this is a spare getCurrentFrame().roll2.isSpare = this.isSpare(noOfPins); displayScore(); advanceFrame(); } } private void doSpecialScoresForPreviousFrame(int noOfPins) { if (gameFrames.size() &gt; 1) { // there has been at least one previous frame // check if any additional score should be added to the previous frame // for a strike on the previous frame, increment that frame score by score of both rolls on the current frame // for a spare on the previous frame, increment that frame score by score of the 1st roll on the current frame if( getPreviousFrame().roll1.isStrike || getPreviousFrame().roll2.isSpare &amp;&amp; isFirstRollOfFrame() ) { getPreviousFrame().frameScore += noOfPins; } } } public BowlingFrame getCurrentFrame() { BowlingFrame currentFrame = gameFrames.get(gameFrames.size() - 1); return currentFrame; } private int getCurrentFrameNo() { return gameFrames.size(); } public BowlingFrame getPreviousFrame() { return gameFrames.get(gameFrames.size() - 2); } private boolean isFirstRollOfFrame() { return getCurrentFrame().roll1 == null; } private boolean isSpare(int noOfPins) { return getCurrentFrame().roll1.pinsKnockedDown + noOfPins == pinsPerFrame; } private boolean isStrike(int noOfPins) { return noOfPins == pinsPerFrame; } /** * Activate the 1st frame of the game */ public void startGame() { advanceFrame(); }; public void advanceFrame() { if (gameFrames.size() &lt; framesPerGame) { BowlingFrame newFrame = new BowlingFrame(); gameFrames.add(newFrame); } else completeGame(); } private void completeGame() { // TODO: do something to render the game complete } public int score() { int totalGameScore = 0; for (int i=0; i &lt;= gameFrames.size() - 1; i++) { totalGameScore += gameFrames.get(i).frameScore; } return totalGameScore; } public void simulateGame() { //Frame 1- strike roll(10); //Frame2 roll(3); roll(0); //Frame3 - wipeout roll(0); roll(0); //Frame 4 - spare roll(4); roll(6); //Frame 5 roll(2); roll(6); //Frame 6 - spare roll(5); roll(5); //Frame 7 - strike roll(10); //Frame 8 - strike roll(10); //Frame 9 - spare roll(2); roll(8); //Frame 10 -spare roll(0); roll(10); } private void displayScore() { System.out.println("Total score - " + score()); } } </code></pre> <p><strong>BowlingFrame.java</strong></p> <pre><code>package com.dius.bowling; public class BowlingFrame { public Roll roll1 = null; public Roll roll2 = null; public int frameScore = 0; public BowlingFrame() {} } </code></pre> <p><strong>Roll.java</strong></p> <pre><code>package com.dius.bowling; public class Roll { public int pinsKnockedDown; public boolean isStrike; public boolean isSpare; public Roll() { } } </code></pre>
[]
[ { "body": "<p><code>BowlingFrame</code> and <code>Roll</code> contain unused information. <code>frame.roll1.isSpare</code> and <code>frame.roll2.isStrike</code> are never used. It would make more sense for <code>isStrike</code> and <code>isSpare</code> to be members of <code>BowlingFrame</code>, at which point <code>Roll</code> would only contain <code>pinsKnockedDown</code>, so that class should be removed, and <code>BowlingFrame</code> instead contain two integers for the pin counts for roll 1 &amp; 2.</p>\n\n<p>However, <code>isStrike</code> and <code>isSpare</code> are mutually exclusive, so perhaps an <code>enum</code> could be used to express <code>STRIKE</code> and <code>SPARE</code> states. You could also add states for <code>UNPLAYED</code>, <code>PARTIAL</code> &amp; <code>FINISHED</code> to track whether or not there are rolls left in the frame.</p>\n\n<p>The 10th frame scoring is flawed. A strike grants two additional rolls; a spare grants one additional roll. Neither of these are currently handled. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T04:57:52.990", "Id": "230886", "ParentId": "230883", "Score": "5" } }, { "body": "<p>please find my initial observations below.</p>\n\n<p>DiusBowlingGame: looks like a GOD class to me, you should try to reduce the responsibilities here. for example, Game simulation should never be part of the game itself and also, you can think of scoring logic as a separate strategy class on it own</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T05:16:32.543", "Id": "230887", "ParentId": "230883", "Score": "1" } }, { "body": "<p>As a completion of previous comments:</p>\n\n<pre><code>Main.java\n- remove private variable and make local game variable final\n\nDiusBowlingGame.java\n- declare gameFrames as List&lt;BowlingFrame&gt; (this is why interfaces were invented :) )\n\nBowlingFrame.java\n- create getter and setter for each public field and make them private at declaration time (OOP - incapsulation)\n\nRoll.java\n- same as in BowlingFrame.java\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T07:04:57.330", "Id": "230890", "ParentId": "230883", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T01:09:05.123", "Id": "230883", "Score": "4", "Tags": [ "java" ], "Title": "Java code for scoring bowling" }
230883
<p>I have a Web API method that returns the Active Directory security groups for the specific login user. The below code was working fine but it was taking so munch time nearly 45 sec to get the results.</p> <pre><code>DirectoryEntry root = GetDirectoryEntry() using (var groups = root.Children.Find("OU=Sample Security Groups")) { using (var directory = groups.Children.Find("OU=Permissions")) { using (var searcher = new DirectorySearcher(directory)) { searcher.Filter = `filter condition` var results = searcher.FindAll(); foreach (SearchResult result in results) { if (result != null) { using (DirectoryEntry group = result.GetDirectoryEntry()) { items.Add((string)group.Properties["sAMAccountName"].Value); } } } } } } </code></pre> <p>Update: In the <code>GetDirectoryEntry</code> method we are creating the connection to the active directory using the username and password.</p> <p>Can anyone help to optimize the code using <code>Parallel.ForEach</code> or threading etc.. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T04:05:58.527", "Id": "449981", "Score": "2", "body": "Welcome to Code Review! To get better answers you should add some more code, e.g the whole method and the `GetDirectoryEntry()` method as well." } ]
[ { "body": "<p>Let us first review the code.</p>\n\n<ul>\n<li>Stacking <code>using</code>s will reduce the level of indentation.</li>\n<li>The <code>Filter</code> of the <code>DirectorySearcher</code> can be passed to the constructor </li>\n<li>If the expected result of the <code>FindAll()</code> call will be huge, you should consider to return only needed properties, by using this <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.directoryservices.directorysearcher.-ctor?view=netframework-4.8#System_DirectoryServices_DirectorySearcher__ctor_System_DirectoryServices_DirectoryEntry_System_String_System_String___\" rel=\"nofollow noreferrer\">overloaded constructor</a> of the <code>DirectorySearcher</code> class.</li>\n<li>The <code>SearchResultCollection</code> returned by <code>DirectorySearcher.FindAll()</code> implements the <code>IDisposable</code> interface hence it should be enclosed in a <code>using</code> as well. The <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.directoryservices.directorysearcher.findall?view=netframework-4.8#remarks\" rel=\"nofollow noreferrer\">remarks section</a> of the documentation states: \n\n<blockquote>\n <p>Due to implementation restrictions, the SearchResultCollection class\n cannot release all of its unmanaged resources when it is garbage\n collected. To prevent a memory leak, you must call the Dispose method\n when the SearchResultCollection object is no longer needed.</p>\n</blockquote></li>\n</ul>\n\n<p>Implementing some of this changes could look like so </p>\n\n<pre><code>DirectoryEntry root = GetDirectoryEntry();\nusing (var groups = root.Children.Find(\"OU=Sample Security Groups\"))\nusing (var directory = groups.Children.Find(\"OU=Permissions\"))\nusing (var searcher = new DirectorySearcher(directory, \"filter condition\"))\nusing (var results = searcher.FindAll())\n{\n foreach (SearchResult result in results)\n {\n if (result != null)\n {\n using (var group = result.GetDirectoryEntry())\n {\n items.Add((string)group.Properties[\"sAMAccountName\"].Value);\n }\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>If you only need to get the <code>SamAccountName</code>'s of the groups a specific user is a member of you can use <code>UserPrincipal.FindByIdentity()</code> like so </p>\n\n<pre><code>UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, \"domain\", \"username\", \"password\"), IdentityType.SamAccountName, \"loginUser\");\n\nforeach (GroupPrincipal group in user.GetGroups())\n{\n Console.Out.WriteLine(group.SamAccountName);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T08:24:13.247", "Id": "230892", "ParentId": "230885", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T03:23:30.983", "Id": "230885", "Score": "2", "Tags": [ "c#", "asp.net-web-api", "active-directory" ], "Title": "Active Directory security groups Search application optimization" }
230885
<p>I'm posting this after reviewing the Meta Q&amp;A, <a href="https://codereview.meta.stackexchange.com/questions/6730/non-code-formula-spreadsheet"><em>Non-code formula spreadsheet</em></a>, and I believe I've got something here that meets the criteria there.</p> <p><strong>Edit:</strong> I've added documentation of the formulas below to make them easier to review.</p> <p>Occasionally I find myself analyzing data that I need to turn into a spreadsheet with two levels of indices. For example, from the mock data:</p> <pre><code>Authors and their books Sam Jones How to write comedy How to write mystery Jim Smith How to avoid writing The pleasures of procrastination The book I didn't write Bill Bailey Sally Ames The art of sleeping </code></pre> <p>I want to generate the following spreadsheet:</p> <p><a href="https://i.stack.imgur.com/ikE3Y.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ikE3Y.jpg" alt="sample 2"></a></p> <p>In words, I want to have one row for each title and I want an incrementing index for authors and another for each author's titles.</p> <p>To do this, the first step is to turn the data into the following spreadsheet:</p> <p><a href="https://i.stack.imgur.com/c3qsK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c3qsK.jpg" alt="sample 1"></a></p> <p>Doing that is simple and straightforward, and I don't need to explain how I did that. The challenge is to use the data of sheet "sample 1" to generate sheet "sample 2". Obviously, it would be easy to manipulate these data manually into that form, but the challenge is when I have a data set with hundreds or thousands of rows in the structure of "sample 1", to convert it to the structure of "sample 2".</p> <p>The formulas I have developed to do that are, in sheet "sample 2":</p> <pre><code>A5: =A4 + 1 B5: =IF(B4 = "", "", IF(ISTEXT(B4), 1, IF(H4 &lt; G4, B4, IF(B4 = 'sample 1'!B$3, "", B4 + 1)))) C5: =IF(B5 = B4, "", B5) D5: =IF(C5 = "", "", MATCH(C5, 'sample 1'!H$5:H$75, 0) + ROW('sample 1'!H$4)) E5: =IF($D5 = "", "", INDEX('sample 1'!B:B, $D5)) F5: =IF($D5 = "", "", INDEX('sample 1'!I:I, $D5)) G5: =IF(B5 = "", "", IF(F5 = "", G4, F5)) H5: =IF(B5 = "", "", IF(F5 = 0, "", IF(F5 = "", H4 + 1, 1))) I5: =IF(H5 = "", "", INDEX('sample 1'!C:C, MATCH(1, INDEX((B5 = 'sample 1'!G:G) * (H5 = 'sample 1'!J:J), 0, 1), 0))) </code></pre> <p>That's the code I'd like reviewed. Is there a simpler or more efficient way to do this?</p> <p>Documentation of what each formula does, to make them easier to review:</p> <ul> <li>A5: Simple incrementing of a number for each data row.</li> <li>B5: <strong>Author index</strong>: <ul> <li>Empty if the previous row's value is empty. </li> <li>If the previous row's value is text, meaning that this is the first data row, then 1.</li> <li>If the previous row's title index is less than the number of titles for this author, then repeat the previous row's value of the author index.</li> <li>If the previous row's title index is equal to the number of titles for this author, then we have listed all the titles for that author. So:</li> <li>If the previous row's author index equals the number of authors, then we're finished. Return empty.</li> <li>Otherwise, increment the author index.</li> </ul></li> <li>C5: Show the author index if it is different from that in the previous row.</li> <li>D5: If the author index is shown in the previous column, then get the row number of that author index in sheet "sample 1".</li> <li>E5: <strong>Author's name</strong>: If there's a value in the previous column, then get the author's name from sheet "sample 1".</li> <li>F5: <strong>Number of titles</strong>: If there's a value in D5, then get the number of this author's titles from sheet "sample 1".</li> <li>G5: Fill in this author's number of titles for rows where it's empty in the previous column. (This is used in the calculation of the next row's author index (B6).)</li> <li>H5: <strong>Title index</strong>: If the number of titles is 0, then empty. Otherwise, if this is the first title for this author, then 1, otherwise increment from the previous row's value.</li> <li>I5: <strong>Title</strong>: If there is a title index, then get the row number of the row in sheet "sample 1" with the same author index and title index, and then get the title from that row.</li> </ul> <p>In order to understand the formula for <code>I5</code>, you also need one formula from sheet "sample 1" because its values are hidden by its narrow column width:</p> <pre><code>'sample 1'!G5: =N(G4) + IF(B5 = "", 0, 1) </code></pre> <p>Documentation of that: Column <code>'sample 1'!G:G</code> provides the author index of each book.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T05:15:13.557", "Id": "455836", "Score": "0", "body": "No input after a month. I guess that at least means that no one found anything glaringly wrong with it. And no one has a simpler or more efficient way of doing it." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T06:48:14.693", "Id": "230889", "Score": "1", "Tags": [ "excel" ], "Title": "Spreadsheet to increment two levels of data indices" }
230889
<pre><code>#include &lt;iostream&gt; const bool DEBUG = false; template &lt;typename ... Args&gt; void debug(Args ... args); template &lt;typename ... Args&gt; void _debug(Args ... args) { std::cout &lt;&lt; "[" &lt;&lt; __FILE__ &lt;&lt; ":" &lt;&lt; __LINE__ &lt;&lt; "] "; (std::cout &lt;&lt; ... &lt;&lt; args) &lt;&lt; std::endl; } #define debug(args...) if (DEBUG) _debug(args); </code></pre> <p>Suppose you are running ACM or you are somewhere without a well-crafted development environment. You have written some code and wondering what is going wrong.</p> <p>Goal here is to find out what cause the problem as quickly as possible by placing tracing prints and turn them off all together by preventing code generation for them. So you can submit your code with <code>DEBUG = false</code> and it will not cause any performance issues done by calling <code>debug(...)</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T08:39:02.293", "Id": "449995", "Score": "0", "body": "Does that print file name and line number of the caller?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T08:41:53.507", "Id": "449997", "Score": "0", "body": "@MartinR GCC - https://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html MSVC - https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros?view=vs-2019" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T08:45:04.690", "Id": "449998", "Score": "3", "body": "I know what those macros are. But did you try it? – I did (with Xcode/clang on macOS) and the output was the file/number of where the template is define in the debug.hpp file, not where the macro is called in main.cpp." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T11:12:24.253", "Id": "450004", "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": "<p>Although it's a short function/macro, there are a number of problems here:</p>\n<ul>\n<li><p><code>__FILE__</code> and <code>__LINE__</code> are expanded in the function definition, rather than at the call site. We need an interface that passes those in, so that the macro is</p>\n<pre><code> #define debug(args...) if (DEBUG) _debug(__FILE__, __LINE__, args);\n</code></pre>\n</li>\n<li><p>That's a non-standard variadic macro expansion. The standard way is to write the parameter as <code>...</code> and expand it using <code>__VA_ARGS__</code>.</p>\n</li>\n<li><p>Identifiers in global scope beginning with underscore are reserved for the implementation. Use a namespace instead (e.g. <code>debugging::debug</code>).</p>\n</li>\n<li><p>Debug information should go to <code>std::clog</code>, not <code>std::cout</code>.</p>\n</li>\n<li><p>The macro doesn't play nicely in <code>if</code>/<code>else</code> statements - use the <code>do</code>...<code>while(0)</code> idiom to make it statement-like.</p>\n</li>\n<li><p>Conventional style is to use all-caps for macros (to indicate their dangers) and nothing else. We have this exactly backwards here, with <code>debug</code> and <code>DEBUG</code>.</p>\n</li>\n</ul>\n<hr />\n<h1>Improved version</h1>\n<pre><code>#include &lt;iostream&gt;\n\nnamespace debugging\n{\n#ifdef ENABLE_DEBUG\n constexpr bool debug = true;\n#else\n constexpr bool debug = false;\n#endif\n\n template &lt;typename... Args&gt;\n void print(const char* file, int line, Args... args) {\n (std::clog &lt;&lt; &quot;[&quot; &lt;&lt; file &lt;&lt; &quot;:&quot; &lt;&lt; line &lt;&lt; &quot;] &quot;\n &lt;&lt; ... &lt;&lt; args) &lt;&lt; std::endl;\n }\n}\n\n#define DEBUG(...) \\\n do { \\\n if (debugging::debug) \\\n debugging::print(__FILE__, __LINE__, __VA_ARGS__); \\\n } while (0)\n</code></pre>\n<p>And a quick test (that demonstrates that the arguments are evaluated only when we're debugging):</p>\n<pre><code>int main()\n{\n DEBUG(&quot;Started main&quot;);\n int status = 1;\n DEBUG(&quot;Leaving main, status=&quot;, status=0);\n return status;\n}\n</code></pre>\n<hr />\n<h1>Addendum</h1>\n<p>We don't need the <code>debug</code> constant - just change the definition of the macro according to whether or not we're debugging:</p>\n<pre><code>#ifndef ENABLE_DEBUG\n#define DEBUG(...) ((void)0)\n#else\n#include &lt;iostream&gt;\n\nnamespace debugging\n{\n template&lt;typename... Args&gt;\n void print(const char* file, int line, Args... args) {\n (std::clog &lt;&lt; &quot;[&quot; &lt;&lt; file &lt;&lt; &quot;:&quot; &lt;&lt; line &lt;&lt; &quot;] &quot;\n &lt;&lt; ... &lt;&lt; args) &lt;&lt; std::endl;\n }\n}\n\n#define DEBUG(...) debugging::print(__FILE__, __LINE__, __VA_ARGS__)\n#endif\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T11:13:14.080", "Id": "450005", "Score": "0", "body": "Why `constexpr bool` instead of `const bool` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T11:24:24.997", "Id": "450006", "Score": "0", "body": "Fix `error: binary expression in operand of fold-expression` pls. Adding additional parentess around init expr will do the trick." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T11:53:28.447", "Id": "450007", "Score": "0", "body": "I can't remember why I went for `constexpr` there - perhaps just defensiveness. I also considered `if constexpr` because we might be using variables that we initialize only if debugging - we don't want to trigger warnings in those cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T11:55:32.033", "Id": "450008", "Score": "0", "body": "I get no errors with GCC 9.2.0, using `-std=c++2a`. Adding more parenthesis wouldn't hurt much, but I'm not sure if it's necessary or if your compiler is buggy/old." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T00:10:52.430", "Id": "450077", "Score": "3", "body": "Note: In C++20, prefer [`std::source_location`](https://en.cppreference.com/w/cpp/utility/source_location) over `__FILE__` and `__LINE__`. Prior to C++20, consider [`std::experimental::source_location`](https://en.cppreference.com/w/cpp/experimental/source_location). In fact, with `source_location`, you could even consider making `debug(...)` a (possibly `[[gnu::always_inline]]`) function rather than a macro, possibly allowing lambda-wrapped parameters to allow lazy evaluation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T02:43:53.700", "Id": "450082", "Score": "0", "body": "@Justin how to prevent generation of any code if you have debug disabled without macros?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T03:12:40.733", "Id": "450084", "Score": "2", "body": "Why bother with defining a `constexpr` variable when you already have a preprocessor flag? Just use that for the conditional... I don't see an advantage in the indirection." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T04:09:57.823", "Id": "450086", "Score": "0", "body": "@CodyGray yeah, try to use `#define ENABLE_DEBUG` inside `if` statement. `ENABLE_DEBUG` have no value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T12:06:39.667", "Id": "450126", "Score": "0", "body": "I don't see why you need the silly `do/while(0)` idiom." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T13:39:08.907", "Id": "450144", "Score": "0", "body": "@outoftime: Since `debugging::debug` is `constexpr`, you could as well make the test an `if constexpr(debugging::debug)` (in C++17). That would prevent the code generation, and your macro would expand to an empty `do/while` if `debugging::debug` is false. And maybe make `debug` `const constexpr`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T09:45:23.960", "Id": "450277", "Score": "0", "body": "@ALX23z what do you think this code does? `if (...) DEBUG(...); else ...`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T12:16:53.530", "Id": "450281", "Score": "0", "body": "@ L.F. to this end you use extra braces `{}` for encapsulation instead of the silly extra 1-length-loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T07:59:26.247", "Id": "450392", "Score": "0", "body": "@ALX23z, braces require you to omit the usual semicolon, meaning you can't use the macro like a normal expression - see [this SO answer](//stackoverflow.com/a/154138/4850040), and other answers to the same question." } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T08:48:52.640", "Id": "230894", "ParentId": "230891", "Score": "13" } }, { "body": "<p>Each of those insertion operators can be interleaved with other calls in a multi-threaded environment.</p>\n\n<p>Consider building the string in memory first, then making a single call to std::cout. This approach will also give better behavior with stream buffering disabled as is typical with std::cerr.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T02:49:03.297", "Id": "450083", "Score": "1", "body": "What if program does some IO and I want to tie my debug info to it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T20:41:19.543", "Id": "450198", "Score": "0", "body": "I'm not too clear on what you're asking, but I think you'd like to know how to send the debug output somewhere else. You could always pass in the stream object as a parameter." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T23:10:19.823", "Id": "230927", "ParentId": "230891", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T08:22:48.637", "Id": "230891", "Score": "9", "Tags": [ "c++", "io", "c++17" ], "Title": "Print-based debugging" }
230891
<p>I wrote a min-heap using a binary tree. How can I improve the time complexity of insert and delete function to be <span class="math-container">\$\mathcal{O}(log(n))\$</span>?</p> <pre><code>''' Min Heap Tree Implementation ''' class Node: def __init__(self, data): self.data = data self.left = None self.right = None class HeapBT: def __init__(self): self.head = None def insert(self, data): if self.head is None: self.head = Node(data) return lst = [] lst.append(self.head) while lst: currentNode = lst.pop(0) if currentNode.left is None: currentNode.left = Node(data) break if currentNode.right is None: currentNode.right = Node(data) break if currentNode.left is not None: lst.append(currentNode.left) if currentNode.right is not None: lst.append(currentNode.right) self.heapifyBottomUp(data) def bfs(self): if self.head is None: return lst = [] lst.append(self.head) while lst: currentNode = lst.pop(0) print(currentNode.data) if currentNode.left is not None: lst.append(currentNode.left) if currentNode.right is not None: lst.append(currentNode.right) def heapifyBottomUp(self, data): count = 1 while count: count = 0 lst = [] lst.append(self.head) while lst: currentNode = lst.pop(0) if currentNode.left is not None: if currentNode.left.data == data: if currentNode.data &gt; currentNode.left.data: count = 1 temp = currentNode.data currentNode.data = currentNode.left.data currentNode.left.data = temp break elif currentNode.left != data: lst.append(currentNode.left) if currentNode.right is not None: if currentNode.right.data == data: if currentNode.data &gt; currentNode.right.data: count = 1 temp = currentNode.data currentNode.data = currentNode.right.data currentNode.right.data = temp break elif currentNode.right != data: lst.append(currentNode.right) def heapifyTopDown(self, node): if node is None: return if node.left is not None and node.right is not None: if node.left.data &lt; node.data and node.right.data &lt; node.data: if node.left.data &lt; node.right.data: temp = node.data node.data = node.left.data node.left.data = temp self.heapifyTopDown(node.left) return else: temp = node.data node.data = node.right.data node.right.data = temp self.heapifyTopDown(node.right) return elif node.left.data &lt; node.data and node.right.data &gt; node.data: temp = node.left.data node.left.data = node.data node.data = temp self.heapifyTopDown(node.left) return else: temp = node.right.data node.right.data = node.data node.data = temp self.heapifyTopDown(node.right) return elif node.left is not None: if node.left.data &lt; node.data: temp = node.data node.data = node.left.data node.left.data = temp self.heapifyTopDown(node.left) return elif node.right is not None: if node.right.data &lt; node.data: temp = node.data node.data = node.right.data node.right.data = node.data self.heapifyTopDown(node.right) return def pop(self): if self.head is None: return 'Heap is empty.' data = self.head.data if self.head.left is None and self.head.right is None: self.head = None return data lst = [] lst.append(self.head) while lst: currentNode = lst.pop(0) if currentNode.left is not None: lst.append(currentNode.left) if currentNode.right is not None: lst.append(currentNode.right) leafData = currentNode.data lst = [] lst.append(self.head) while lst: currentNode = lst.pop(0) if currentNode.left is not None: if currentNode.left.data == leafData: currentNode.left = None break else: lst.append(currentNode.left) if currentNode.right is not None: if currentNode.right.data == leafData: currentNode.right = None break else: lst.append(currentNode.right) self.head.data = leafData self.heapifyTopDown(self.head) return data def peek(self): if self.head is None: return 'self.head is None' return self.head.data avl = HeapBT() avl.insert(11) avl.insert(10) avl.insert(9) avl.insert(8) avl.insert(7) avl.insert(6) avl.insert(5) avl.insert(4) avl.insert(3) avl.insert(2) avl.insert(1) avl.insert(-1) avl.insert(43) avl.insert(34) avl.insert(53) avl.insert(-1123) avl.insert(-100) avl.insert(-11233) #avl.bfs() print print print(avl.pop()) print(avl.pop()) print(avl.pop()) print(avl.pop()) print(avl.pop()) print(avl.pop()) print(avl.pop()) print(avl.pop()) print(avl.pop()) print(avl.pop()) print(avl.pop()) print(avl.pop()) print(avl.pop()) print(avl.peek(),'peek') print avl.bfs() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T14:48:55.463", "Id": "450026", "Score": "2", "body": "Is there a reason why you implement binary heap using a binary tree? It is much simpler to use a list to implement binary heap, with log performance on insert and delete." } ]
[ { "body": "<p>To achieve the <span class=\"math-container\">\\$\\mathcal{O}(log(n))\\$</span> time complexity of insert and delete functions you should store the binary tree as an array - <a href=\"https://en.wikipedia.org/wiki/Binary_heap#Heap_implementation\" rel=\"nofollow noreferrer\">Heap implementation</a>. Because you need to have a link to the last element for performing insert and delete operations and the easiest (common) way to track this link is an array representation of the binary tree. You can devise your own method of tracking the last element for your binary tree representation, but I think it will be similar to the array method at the end.</p>\n\n<p><strong>My implementation:</strong></p>\n\n<pre><code>class BinHeap:\n def __init__(self):\n self.lst = []\n\n def insert(self, data):\n self.lst.append(data)\n self.heapify_up(len(self.lst) - 1)\n\n def pop_root(self):\n root = self.lst[0]\n last = self.lst.pop()\n\n if len(self.lst) &gt; 0:\n self.lst[0] = last \n self.heapify_down(0, 0)\n\n return root\n\n def heapify_down(self, parent_idx, child_idx):\n if child_idx &gt;= len(self.lst):\n return\n\n parent_greater_bool = self.lst[parent_idx] &gt; self.lst[child_idx]\n\n if parent_greater_bool:\n self.lst[parent_idx], self.lst[child_idx] = self.lst[child_idx], self.lst[parent_idx]\n\n if parent_greater_bool or parent_idx == 0:\n self.heapify_down(child_idx, child_idx * 2 + 1)\n self.heapify_down(child_idx, child_idx * 2 + 2)\n\n def heapify_up(self, child_idx):\n parent_idx = (child_idx - 1) // 2\n\n if parent_idx &lt; 0:\n return\n\n if self.lst[parent_idx] &gt; self.lst[child_idx]: \n self.lst[parent_idx], self.lst[child_idx] = self.lst[child_idx], self.lst[parent_idx]\n self.heapify_up(parent_idx)\n</code></pre>\n\n<p><strong>Testing:</strong></p>\n\n<pre><code>heap = BinHeap()\n\nheap.insert(4)\nheap.insert(5)\n\nprint(heap.lst)\n\nprint(heap.pop_root())\nprint(heap.pop_root())\n\nprint(heap.lst)\n\n###Output:\n# [4, 5]\n# 4\n# 5\n# []\n\nheap.insert(4)\nheap.insert(5)\nheap.insert(3)\nheap.insert(7)\nheap.insert(9)\nheap.insert(10)\nheap.insert(2)\n\nprint(heap.lst)\n\nprint(heap.pop_root())\nprint(heap.lst)\n\nheap.insert(1)\nprint(heap.lst)\n\n###Output:\n# [2, 5, 3, 7, 9, 10, 4]\n# 2\n# [3, 5, 4, 7, 9, 10]\n# [1, 5, 3, 7, 9, 10, 4]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T13:13:57.193", "Id": "230998", "ParentId": "230896", "Score": "1" } } ]
{ "AcceptedAnswerId": "230998", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T09:37:51.870", "Id": "230896", "Score": "4", "Tags": [ "python", "python-3.x", "heap" ], "Title": "Min Heap Tree Implementation in python 3" }
230896
<p>I am developing a high-performance(real-time) system, it requires message passing between its component. speed and accuracy is at most priority. I have explored a few options. <code>ConcurrentQueue&lt;T&gt;</code> is super fast <code>BlockingCollection&lt;T&gt;</code> provides a better API. also <code>BlockingCollection&lt;T&gt;</code> waits for the producer to produce the message. the problem is <code>BlockingCollection&lt;T&gt;</code> is not fast enough for the job. also, it uses locks internally which may lead to locking contention. so I tried to develop a queue that provides blocking behavior(waits for the producer to produce message) and does not use lock internally. here what I have come up with</p> <pre class="lang-cs prettyprint-override"><code> public class BlockingConcurrentQueue&lt;T&gt; : IDisposable { private readonly ConcurrentQueue&lt;T&gt; _internalQueue; private AutoResetEvent _autoResetEvent; private long _consumed; private long _isAddingCompleted = 0; private long _produced; private long _sleeping; public BlockingConcurrentQueue() { _internalQueue = new ConcurrentQueue&lt;T&gt;(); _produced = 0; _consumed = 0; _sleeping = 0; _autoResetEvent = new AutoResetEvent(false); } public bool IsAddingCompleted { get { return Interlocked.Read(ref _isAddingCompleted) == 1; } } public bool IsCompleted { get { if (Interlocked.Read(ref _isAddingCompleted) == 1 &amp;&amp; _internalQueue.IsEmpty) return true; else return false; } } public void CompleteAdding() { Interlocked.Exchange(ref _isAddingCompleted, 1); } public void Dispose() { _autoResetEvent.Dispose(); } public void Enqueue(T item) { _internalQueue.Enqueue(item); if (Interlocked.Read(ref _isAddingCompleted) == 1) throw new InvalidOperationException("Adding Completed."); Interlocked.Increment(ref _produced); if (Interlocked.Read(ref _sleeping) == 1) { Interlocked.Exchange(ref _sleeping, 0); _autoResetEvent.Set(); } } public bool TryDequeue(out T result) { if (Interlocked.Read(ref _consumed) == Interlocked.Read(ref _produced)) { Interlocked.Exchange(ref _sleeping, 1); _autoResetEvent.WaitOne(); } if (_internalQueue.TryDequeue(out result)) { Interlocked.Increment(ref _consumed); return true; } return false; } } </code></pre> <p>I seek your expertise to review</p> <ol> <li>Sequence Guarantee</li> <li>Any Performance improvement</li> <li>Am I doing anything wrong which may break in race condition</li> </ol>
[]
[ { "body": "<p>This question has a number of misconceptions </p>\n\n<ol>\n<li>You are unlikely to develop a real-time system using .NET because of\nunbounded GC times </li>\n<li><code>ConcurrentQueue&lt;T&gt;</code> is better than <code>BlockingCollection&lt;T&gt;</code> not because\nit does not use locks. It actually uses more locks, just in a\nsmarter way. </li>\n<li><code>ConcurrentQueue&lt;T&gt;</code> provides worse API exactly because it is faster. \nMost of the missing APIs are missing because there is no way of \nimplementing them efficiently and in a thread-safe manner</li>\n</ol>\n\n<p>Your code has a number of weaknesses:</p>\n\n<ol>\n<li><p>I don't see any reasonable use for <code>IsAddingCompleted</code> and friends</p></li>\n<li><p>I am not sure there are no race conditions. For example, lets assume we have produced == consumed == 0. Thread1 adds an item and is just before incrementing produced. Thread2 calls <code>TryDequeue</code>, since produced==consumed, it goes through and stops right before changing sleeping. Thread1 continues, changes produced to 1, checks if sleeping is 0, which it is and quits without setting the event. Thread2 continues to <code>Wait()</code>. Now we have a task and an eteranlly-waiting client.</p></li>\n<li><p>There is no way to abort a waiting <code>TryDequeue</code> and finish gracefully</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T12:14:11.747", "Id": "231192", "ParentId": "230898", "Score": "9" } } ]
{ "AcceptedAnswerId": "231192", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T10:21:51.783", "Id": "230898", "Score": "6", "Tags": [ "c#", "performance", "queue" ], "Title": "High Performance Blocking Queue C#" }
230898
<p>What I want to achieve is the following:</p> <pre class="lang-cpp prettyprint-override"><code>#include "tree.h" #include &lt;iostream&gt; int main() { Tree&lt;std::string&gt;* tA = new Tree&lt;std::string&gt;("A"); Tree&lt;std::string&gt;* tB = new Tree&lt;std::string&gt;("B", tA); Tree&lt;std::string&gt;* tC = new Tree&lt;std::string&gt;("C", tA); Tree&lt;std::string&gt;* tD = new Tree&lt;std::string&gt;("D", tB); Tree&lt;std::string&gt;* tE = new Tree&lt;std::string&gt;("E", tB); Tree&lt;std::string&gt;* tF = new Tree&lt;std::string&gt;("F", tB); for (auto cur : *tA) { std::cout &lt;&lt; "traversed from " &lt;&lt; (cur-&gt;parent ? cur-&gt;parent-&gt;val : "NULL") &lt;&lt; " to " &lt;&lt; cur-&gt;val &lt;&lt; std::endl; } // std::next(std::next(tF-&gt;begin())); return 0; } </code></pre> <p>And here is my implementation.</p> <pre class="lang-cpp prettyprint-override"><code>#ifndef TREE_H #define TREE_H #include &lt;iterator&gt; #include &lt;stack&gt; #include &lt;vector&gt; #include &lt;iostream&gt; template &lt;typename T&gt; class Tree { public: class iterator { public: using iterator_category = std::forward_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = T*; using reference = T&amp;; public: iterator() = default; iterator(Tree&lt;T&gt;* const root); Tree&lt;T&gt;* operator*() const; iterator&amp; operator++(); bool operator!=(iterator const&amp; other) const; Tree&lt;T&gt;* cur; private: std::stack&lt;Tree&lt;T&gt;*&gt; s_; }; public: Tree() = default; Tree(T const&amp; val, Tree&lt;T&gt;* parent = NULL); void* operator new(size_t size); iterator begin(); iterator end(); T val; Tree&lt;T&gt;* const parent = NULL; private: std::vector&lt;Tree&lt;T&gt;*&gt; children_; }; template &lt;typename T&gt; Tree&lt;T&gt;::iterator::iterator(Tree&lt;T&gt;* const root) : cur(root) {} template &lt;typename T&gt; Tree&lt;T&gt;* Tree&lt;T&gt;::iterator::operator*() const { return cur; } template &lt;typename T&gt; typename Tree&lt;T&gt;::iterator&amp; Tree&lt;T&gt;::iterator::operator++() { if (cur == NULL) { throw std::out_of_range("No more nodes for traversal"); } for (auto&amp; child : cur-&gt;children_) { s_.push(child); } if (s_.empty()) { cur = NULL; } else { cur = s_.top(); s_.pop(); } return *this; } template &lt;typename T&gt; bool Tree&lt;T&gt;::iterator::operator!=(Tree&lt;T&gt;::iterator const&amp; other) const { return cur != other.cur; } template &lt;typename T&gt; Tree&lt;T&gt;::Tree(T const&amp; val, Tree&lt;T&gt;* const parent) : val(val), parent(parent) { if (parent) { parent-&gt;children_.push_back(this); } } template &lt;typename T&gt; void* Tree&lt;T&gt;::operator new(size_t size) { void* p = ::new Tree&lt;T&gt;(); return p; } template &lt;typename T&gt; typename Tree&lt;T&gt;::iterator Tree&lt;T&gt;::begin() { return iterator(this); } template &lt;typename T&gt; typename Tree&lt;T&gt;::iterator Tree&lt;T&gt;::end() { return iterator(); } #endif </code></pre> <p>User should be able to directly modify <code>val</code> (hence it is public). However, they shouldn't be able to modify any parent/children relationship. Therefore I try to make <code>parent</code> a <code>const</code> pointer, but I cannot make <code>children</code> a list of <code>const</code> pointers because anything inside a <code>std::vector</code> must be assignable. I am considering exposing a <code>GetChildren()</code> method which returns a <code>const std::vector</code>, but that would be inconsistent with how I dealt with <code>parent</code>. Can anyone show a good way to resolve this?</p> <p>General reviews are welcome. More specifically, I want to know</p> <ol> <li>Is this a good and correct use of pointers?</li> <li>Is the interface well designed?</li> <li>Are there any <code>const</code> that I missed?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T14:06:54.843", "Id": "450019", "Score": "0", "body": "Does this code work as expected?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T14:21:03.733", "Id": "450021", "Score": "0", "body": "Yes, I am able to compile and run it. Is there something wrong?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T14:31:03.060", "Id": "450024", "Score": "1", "body": "What kind of tree (binary, B, B*) tree is this supposed to work for?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T14:33:14.190", "Id": "450025", "Score": "0", "body": "I am able to compile using the command `g++ main.cc -o tree -std=c++17 -Wall -static -O3 -m64 -lm`. This is a general tree (can have multiple children)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T17:24:12.867", "Id": "450055", "Score": "0", "body": "It was my compiler, needed to be upgraded." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T18:32:56.083", "Id": "450062", "Score": "0", "body": "Just curious: why all this heap and pointers?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T00:45:34.453", "Id": "450078", "Score": "0", "body": "Because I do not want to make any copy... is this reason justified?" } ]
[ { "body": "<ul>\n<li><p>Clean up allocated memory (everything <code>new</code>ed should be <code>delete</code>d), or use smart pointers to do it for you. (Perhaps each tree node should own its children, and store them in <code>unique_ptr</code>s, and the parent should be a raw pointer).</p></li>\n<li><p>There doesn't seem to be any benefit to overloading <code>operator new</code> for the <code>Tree</code> class.</p></li>\n<li><p>Currently, the iterator is more of a sub-tree iterator, as it never returns to the parent. e.g. for a tree with edges: A->B->C and A->D if you start iterating at B, you will only iterate from B to C, and never reach D.</p></li>\n<li><p>Iterators are normally defined outside of the corresponding container class. We can use an <code>iterator</code> <code>typedef</code> in the container to refer to the iterator class.</p></li>\n<li><p><code>operator*</code> should return a reference, not a pointer (<code>operator-&gt;</code> should return a pointer).</p></li>\n<li><p>We have <code>!=</code>, but no <code>==</code>.</p></li>\n<li><p>We have a pre-increment <code>operator++</code>, but not post-increment <code>operator++</code>.</p></li>\n<li><p>It would probably be best to write unit tests for things that are expected to work, e.g.: <code>*i</code> (returns a modifiable reference), <code>*i++</code> (returns a modifiable reference and then increments i to point at the next value), etc. This can be tedious, but is really the only way to ensure correctness.</p></li>\n<li><p>The full <a href=\"https://en.cppreference.com/w/cpp/named_req/ForwardIterator\" rel=\"nofollow noreferrer\">requirements for a forward iterator are listed here</a> (and in the linked pages), and many of them could be translated into tests cases. This iterator should arguably be a bidirectional iterator.</p></li>\n<li><p>Standard containers also supply a <code>const_iterator</code> version (and reverse iterators, though that's usually simple to add).</p></li>\n</ul>\n\n<p>To be honest, I'd suggest starting with something a bit simpler like an array class, and corresponding iterators.</p>\n\n<hr>\n\n<p>Note that we can traverse a tree in many different ways (depth-first in-order, depth-first pre-order, depth-first post-order, breadth-first). For a full-featured implementation of this sort of thing, see the <a href=\"https://stlab.adobe.com/group__asl__tutorials__forest.html\" rel=\"nofollow noreferrer\">ASL Forest class</a>.</p>\n\n<p>Since we're iterating nodes, not values, we don't have to worry about \"order\", but we should still call the class something like <code>tree_depth_first_iterator</code>, to distinguish it from the alternative(s).</p>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T17:16:11.707", "Id": "450052", "Score": "1", "body": "What about the use of NULL versus nullptr?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T14:20:20.880", "Id": "450224", "Score": "0", "body": "I think since C++11 we should really just use `nullptr`. My reference: https://stackoverflow.com/questions/1282295/what-exactly-is-nullptr/19014644#19014644" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T17:08:47.770", "Id": "230919", "ParentId": "230903", "Score": "3" } } ]
{ "AcceptedAnswerId": "230919", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T13:11:30.983", "Id": "230903", "Score": "3", "Tags": [ "c++", "tree", "iterator", "c++17" ], "Title": "Iterator for traversing a tree" }
230903
<p>I am parsing large XML (DB dump). So, the content looks like many different objects with their properties and dependencies (foreign keys). My way to do it - using <strong>lxml.etree</strong> (iterparse):</p> <pre class="lang-py prettyprint-override"><code> def insert_db(content): for item in xml_parser(content): if isinstance(item, DPoint): # manipulations for inserting DPoint object pass elif isinstance(item, ApotHpot): # manipulations for inserting ApotHpot object pass ... def xml_parser(xmlfile): context = ET.iterparse(xmlfile, events=('start', 'end')) context = iter(context) event, root = next(context) d_pt, a_pt, n_pt = None, None, None for event, elem in context: if event == 'start': if elem.tag == 'ApotHpot': a_pt = Object(None, None) a_pt.id = elem.attrib.get('id') n_pt = Object(None, None) designated_pt = Object(None, None) # d_pt = DPoint(None, None, None, None, ...) # n_pt = NDB(None, None, None, None, None, ...) elif elem.tag == 'DPoint': d_pt = Object(None, None) d_pt.id = elem.attrib.get('id') n_pt = Object(None, None) a_pt = Object(None, None) else: if elem.tag == 'identifier': if d_pt.id: d_pt.uuid = elem.text elif a_pt.id: airport.uuid = elem.text elif n_pt.id: n_pt.uuid = elem.text ... # and so on for the properties # yield an object when closing tag: elif elem.tag == 'DPoint': yield d_pt elif elem.tag == 'ApotHpot': yield a_pt ... root.clear() </code></pre> <p>The question is that I have a doubt about the way to create class:</p> <p><strong><em>There are variants:</em></strong></p> <p><strong>1.</strong> Define only one (common) class (as class Object in code above with only 2 arguments (all of the objects have these properties) 'uuid' and 'id'), when properties appeared (tag in XML doc), they will add dynamically to the class instance</p> <p>a)</p> <pre class="lang-py prettyprint-override"><code>class Object: def __init__(self, uuid, id): self.uuid = uuid self.id = id </code></pre> <p>then call <code>some_variable = Object(None, None)</code> <strong>or</strong></p> <p>b)</p> <pre class="lang-py prettyprint-override"><code>class Object: def __init__(self): self.uuid = None self.id = None </code></pre> <p>then call <code>some_variable = Object()</code></p> <p><strong>2.</strong> Define class for every object in DB Dump with all predefined attributes, e.g.</p> <p>a)</p> <pre class="lang-py prettyprint-override"><code>class NDB: def __init__(self, uuid, id, srid, coords, interpretation, name...): self.uuid = uuid self.id = id self.srid = srid self.coords = coords self.interpretation = interpretation self.name = name ... </code></pre> <p>call <code>some_variable = NDB(None, None, None, None, None, ...)</code></p> <p>b)</p> <pre class="lang-py prettyprint-override"><code>class NDB: def __init__(self): self.uuid = None self.id = None self.srid = None self.coords = None self.interpretation = None self.name = None ... </code></pre> <p>call <code>some_variable = NDB()</code></p> <p>and so on for all of the objects. </p> <p>Firstly I used the 2a) style, it seemed to me that it is the right approach to describe all of the objects. But the more I deepen to the XML doc the more objects I have to implement to its own class - when parsed all the doc I get 23 instances to be described in its own class with its own attributes. Therefore instead of this I wondered that the common class with dynamically attributes (or all attributes -> None as 2b)) is suitable for my case.</p> <p>I wonder if somebody help me to resolve my doubts\give some links\recommend the best practice!</p> <p><strong>ADD</strong></p> <p>Piece of a raw data is <a href="https://gist.github.com/Ezheny/1f017619d4d948fd9119a94508f8c4ab" rel="nofollow noreferrer">here</a></p> <p>As a result I would like to get the objects (refer to the data: AportHport, VR, DE, Navd, Rway, RwayDirection, RwayCentrelinePoint, Glide, Loc) with all attributes (some attributes have the same name for the objects) from XML for <code>def insert_db()</code>. Set of attributes varies (some of them were null from dumped DB) so when inserting in DB I obviously get <code>class.attribute</code> for fill my DB table. But I have to check if object <code>hasattr(cls, attribute)</code> or if it has not (in case I choose the 2b))</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T13:58:31.287", "Id": "450017", "Score": "1", "body": "Provide a testable XML fragment and respective expected result for that" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T15:28:46.247", "Id": "450027", "Score": "1", "body": "@RomanPerekhrest, added link and expected result!)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T02:05:33.307", "Id": "450654", "Score": "1", "body": "Link-only content generally doesn't work well for StackExchange sites. Please copy and paste a representative section of your XML into your question. Also, as an aside: single-file content like that is better-suited to gist than a github repository." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T09:50:11.770", "Id": "450688", "Score": "0", "body": "@Reinderien, Wow, thank you! I'll keep the gist in mind )" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-24T01:57:07.020", "Id": "450849", "Score": "0", "body": "Still waiting on that XML snippet. Otherwise: you've elided so much code that it makes it difficult to do a review. Please include all of your source." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T13:45:47.387", "Id": "230907", "Score": "3", "Tags": [ "python", "python-3.x", "object-oriented", "xml", "lxml" ], "Title": "OOP parsing for DB dump XML Python" }
230907
<p>I've built a custom control to handle user input in a human-readable format, but save in a machine-format.<br> It needs to have input validation, and to convert UI-input to a base format.</p> <p>I'm interested in knowing:</p> <ul> <li>Have I implemented this in a proper and idiomatic Angular way?</li> <li>Are there any UI and typescript mistakes?</li> <li>Have I missed anything in the implementation?</li> <li>Is there a better way to implement this sort of behaviour?</li> </ul> <hr> <p>In this case, the custom control is used to input latitudes and longitudes in "degree minute decimal-seconds" (47° 22' 0.4959"N) and save them in "decimal degrees" (47.366804405489006).</p> <p>Each degree (°) can be broken into 60 minutes ('). Each minute can be divided into 60 seconds (").</p> <hr> <h1>Main code</h1> <h2>coordinate-input.component.html</h2> <pre class="lang-html prettyprint-override"><code>&lt;input #box [placeholder]="placeholder" (blur)="triggerLostFocus()" (change)="triggerInputChange(box.value)" /&gt; </code></pre> <h2>coordinate-input.component.scss</h2> <pre class="lang-css prettyprint-override"><code>:host { display: block; } input { width: 100%; } </code></pre> <h2>coordinate-input.component.ts</h2> <pre class="lang-js prettyprint-override"><code>import { Component, Input, Renderer2, ViewChild, ElementRef, forwardRef } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR, Validator, ValidationErrors, AbstractControl, NG_VALIDATORS } from '@angular/forms'; import { degreesToDMS, dmsToDegrees, DmsParseResult } from 'app/services/utils'; import { GeographicPositionType } from 'app/models/position'; import { TranslateService } from '@ngx-translate/core'; // This component was built following guidelines/instructions from: // https://medium.com/@tarik.nzl/angular-2-custom-form-control-with-validation-json-input-2b4cf9bc2d73 @Component({ selector: 'aby-coordinate-input', templateUrl: './coordinate-input.component.html', styleUrls: ['./coordinate-input.component.scss'], providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() =&gt; CoordinateInputComponent), multi: true, }, { provide: NG_VALIDATORS, useExisting: forwardRef(() =&gt; CoordinateInputComponent), multi: true, }], }) export class CoordinateInputComponent implements ControlValueAccessor, Validator { @Input() public type: GeographicPositionType; @Input() public placeholder: string = null; @Input() public debug: boolean = false; @ViewChild('box') private inputElem: ElementRef; protected _value: number; protected _valueHumanized: string; public lastEdition: string; private parseResult: DmsParseResult = null; // The method used to emit changes back to the form. private propagateUiValueChanged = (_: any) =&gt; { }; private propagateTouched = (_: any) =&gt; { }; private validatorInputsChanged = (_: any) =&gt; { }; constructor( private renderer: Renderer2, private translator: TranslateService, ) { } triggerInputChange(newValue: string) { this.checkForChanges(newValue); } triggerLostFocus() { this.propagateTouched(true); } private checkForChanges(edit: string): void { if (this.lastEdition === edit) { return; } const result: DmsParseResult = dmsToDegrees(edit, this.type, this.translator); this.parseResult = result; if (result.success) { this._value = result.parsedValue; this._valueHumanized = edit; } this.lastEdition = edit; this.propagateUiValueChanged(this._value); this.validatorInputsChanged(this._value); } // --- BEGIN: Validator: https://angular.io/api/forms/Validator --- // "Method that performs synchronous validation against the provided control." validate(_control: AbstractControl): ValidationErrors { if (this.parseResult == null || this.parseResult.success) { return null; } return { parse: this.parseResult.errorMessage, }; } // "Registers a callback function to call when the validator inputs change." registerOnValidatorChange?(fn: () =&gt; void): void { this.validatorInputsChanged = fn; } // --- END: Validator --- // --- BEGIN: ControlValueAccessor: https://angular.io/api/forms/ControlValueAccessor --- /** * Writes a new value to the element. * @param obj The new value for the element */ writeValue(obj: any): void { const newUserValue = degreesToDMS(obj, this.type); this._value = obj; // Push value to UI; it will be received back in the callbacks. this.inputElem.nativeElement.value = newUserValue; this._valueHumanized = newUserValue; this.lastEdition = newUserValue; this.parseResult = null; } /** * Registers a callback function that is called when the control's value changes in the UI. * @param fn The callback function to register. */ registerOnChange(fn: any): void { this.propagateUiValueChanged = fn; } /** * Registers a callback function that is called by the forms API on initialization to update the form model on blur. * @param fn The callback function to register. */ registerOnTouched(fn: any): void { this.propagateTouched = fn; } /** * Function that is called by the forms API when the control status changes to or from 'DISABLED'. * Depending on the status, it enables or disables the appropriate DOM element. * @param isDisabled The disabled status to set on the element. */ setDisabledState?(isDisabled: boolean): void { // Disable the UI. this.renderer.setProperty(this.inputElem.nativeElement, 'disabled', isDisabled); } // --- END: ControlValueAccessor --- } </code></pre> <h1>Supporting code</h1> <h2>position.ts</h2> <pre class="lang-js prettyprint-override"><code>export enum GeographicPositionType { Latitude = 'Latitude', Longitude = 'Longitude', } </code></pre> <h2>utils.ts</h2> <pre class="lang-js prettyprint-override"><code>import { GeographicPositionType } from 'app/models/position'; import { TranslateService } from '@ngx-translate/core'; export const directionFromSignal = (decimalDegrees: number, positionType: GeographicPositionType): string =&gt; { switch (positionType) { case GeographicPositionType.Latitude: return decimalDegrees &gt;= 0 ? 'N' : 'S'; case GeographicPositionType.Longitude: return decimalDegrees &gt;= 0 ? 'E' : 'W'; default: throw new TypeError('Unknown geographic position type.'); } }; export const degreesToDMS = (decimalDegrees: number, positionType: GeographicPositionType): string =&gt; { if (decimalDegrees == null || Number.isNaN(decimalDegrees) || !Number.isFinite(decimalDegrees)) { return null; } const direction: string = directionFromSignal(decimalDegrees, positionType); // We need to make this absolute, or when rounding negative numbers, // it rounds down and all the math gets incorrect. const decimalDegreesAbs = Math.abs(decimalDegrees); let degrees = Math.floor(decimalDegreesAbs); const decimalMinutes = (decimalDegreesAbs - degrees) * 60; let minutes = Math.floor(decimalMinutes); let decimalSeconds = (decimalMinutes - minutes) * 60; // After rounding the seconds and the minutes might become 60, // so we need to account for that. // NOTE: we check against 59.9999 because toLocaleString rounds the value, // so 59.9999 turns into 60. But rounding before decimalSeconds would mean // any value above 59.5 would be considered 60, which we don't want. if (decimalSeconds &gt;= 59.9999) { minutes++; decimalSeconds = 0; } if (minutes === 60) { degrees++; minutes = 0; } const seconds: string = decimalSeconds.toLocaleString(undefined, { useGrouping: false, // Specifies whether to use grouping separators. minimumFractionDigits: 4, maximumFractionDigits: 4, }); // 1° 2' 3.4567"N return `${degrees}° ${minutes}' ${seconds}"${direction}`; }; export interface DmsParseResult { success: boolean; parsedValue: number; errorMessage: string; } const parsedOk = (value: number): DmsParseResult =&gt; { return { success: true, errorMessage: null, parsedValue: value, }; }; const parseError = (translator: TranslateService, reason: string, interpolateParams?: Object): DmsParseResult =&gt; { const translated: string = translator.instant('coordinateConversions.' + reason, interpolateParams); return { success: false, errorMessage: translated, parsedValue: null, }; }; const dmsRegex: RegExp = /^(\d+)°(\d+)'(\d+\.?\d*)"(\w)$/; export const normalizeDmsString = (input: string): string =&gt; { if (input == null) { return input; } let normalized = input; normalized = normalized.replace(/\s+/g, ''); normalized = normalized.replace(/º/g, '°'); normalized = normalized.replace(/´|‘|’|′/g, '\''); normalized = normalized.replace(/''|“|”|″/g, '"'); return normalized; }; const handleCleanMatch = ( translator: TranslateService, degrees: number, minutes: number, decimalSeconds: number, signal: string, positionType: GeographicPositionType, ): DmsParseResult =&gt; { const value = degrees + minutes / 60 + decimalSeconds / 3600; switch (positionType) { case GeographicPositionType.Latitude: switch (signal) { case 'N': case 'n': return parsedOk(value); case 'S': case 's': return parsedOk(-value); default: return parseError(translator, 'Signal symbol "{{signal}}" should be N or S.', {signal: signal}); } case GeographicPositionType.Longitude: switch (signal) { case 'E': case 'e': return parsedOk(value); case 'W': case 'w': return parsedOk(-value); default: return parseError(translator, 'Signal symbol "{{signal}}" should be E or W.', {signal: signal}); } default: throw new TypeError('Unknown geographic position type.'); } }; export const dmsToDegrees = (humanReadable: string, positionType: GeographicPositionType, translator: TranslateService): DmsParseResult =&gt; { if (humanReadable == null) { return parsedOk(null); } const normalized = normalizeDmsString(humanReadable); if (normalized === '') { return parsedOk(null); } const match: RegExpMatchArray = normalized.match(dmsRegex); if (match !== null &amp;&amp; match.length === 5) { const degrees = Number(match[1]); const minutes = Number(match[2]); const decimalSeconds = Number(match[3]); const signal = match[4]; return handleCleanMatch(translator, degrees, minutes, decimalSeconds, signal, positionType); } const sampleSignal = positionType === GeographicPositionType.Latitude ? 'N' : 'W'; return parseError(translator, 'Input must be in format: 12° 34\' 56.789"{{signal}}', {signal: sampleSignal}); }; </code></pre>
[]
[ { "body": "<p>A short review;</p>\n\n<ul>\n<li>Changing CSS for <code>input</code> seems too broad, just apply CSS changes to a class tied to your control</li>\n<li><code>throw new TypeError('Unknown geographic position type.');</code> seems odd, why throw this if the calling function does not catch it anyway? You need a think on how this control handles exceptions.</li>\n<li>Similarly, in <code>degreesToDMS</code> you return <code>null</code> , but the calling functions don't deal with returned <code>null</code> values. You need a think about that as well.</li>\n<li>Naming is well done</li>\n<li>Commenting is well done</li>\n<li>Design seems standard to me for a new control</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T13:12:07.177", "Id": "450733", "Score": "2", "body": "Thank you for your time! :) In Angular, component CSS is scoped to the component itself; it never affects neither parent nor children HTML elements. The error is thrown for code-completion; it is never expected to happen, unless some idiot developer (me) forgets to set the type or sets it wrongly; and then an error will be visibly thrown in the console. The null in `degreesToDms` is passed directly to the UI; the input will have an empty string, which IMO is correct according to an empty or invalid latitude/longitude." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T17:38:29.700", "Id": "231151", "ParentId": "230908", "Score": "3" } }, { "body": "<p>In additions to <a href=\"https://codereview.stackexchange.com/a/231151/207526\">konijn's remarks</a> I would add some other that I would normally add reviewing this code.</p>\n\n<p><strong>Explicit type declarations</strong></p>\n\n<p>In the following code there is no need to declare type:</p>\n\n<pre><code>public debug: boolean = false;\n</code></pre>\n\n<p>The TypeScritpt compiler will understand the type from the assigned value. </p>\n\n<p><strong>Methods with side effects</strong></p>\n\n<p>You have a method <code>checkForChanges(edit: string)</code>. It is not obvious from the method name that it produces side effects (changes the component's state). I would suggest you to rename the method to make it clear. Maybe <code>propagateChanges</code>?</p>\n\n<p><strong>Fields/variables naming</strong></p>\n\n<p>It is probably a matter of taste, but I would suggest you to use names starting with the underscore sign (<code>_value</code>) as less as possible. The only valid case I know is when you want to have <a href=\"https://stackoverflow.com/a/45167446/2065796\">a getter with the same name</a>, but it is not the case here.</p>\n\n<p><strong>Use of <code>any</code> declarations</strong></p>\n\n<p>Try to use <code>any</code> as less as possible. TypeScript encourages types and Angular framework is designed in the way that you need <code>any</code> only in case you interact with third party JS libs. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T13:32:35.400", "Id": "450741", "Score": "0", "body": "Thank you for your time. :) I like my types explicit, as much as possible. About the any, I only know the specific type in `write()`; in the other places, I couldn't figure out what type would be correct (or even if I am meant to pick a type myself); do you have suggestions of idiomatic types, or how I could find out the expected types in e.g. the `registerOnTouched(fn: any): void { }` method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T14:49:54.103", "Id": "450760", "Score": "0", "body": "Sorry, I didn't invest much time going deep into the implementation, maybe there is no other way. As for `registerOnTouched` [the documentation](https://angular.io/api/forms/ControlValueAccessor) declares it as `any`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T15:06:27.150", "Id": "450763", "Score": "0", "body": "<shrug> Such is life. Thanks for the doc link. :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T07:38:56.383", "Id": "231177", "ParentId": "230908", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T13:51:36.327", "Id": "230908", "Score": "6", "Tags": [ "validation", "typescript", "geospatial", "angular-2+", "unit-conversion" ], "Title": "Angular control for inputting latitude and longitude with validation" }
230908
<p>All I would like is for help with putting this code into separate classes as I cant seem to figure it out. I would just like to understand how this would be possible with this set of code.</p> <pre><code>using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace FinalDatabaseConnection { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //if statment dealing with sql queries once button hit private void button1_Click(object sender, EventArgs e) { lblCompleteItemInfo.Text = (""); String source = @"Data Source=WIN10-LAP-&gt;HJP\MSSQLSERVER1;Initial Catalog=VisualStudioConnect;Integrated Security=True"; SqlConnection con = new SqlConnection(source); con.Open(); if ((string) cbfunctionSelection.SelectedItem == "Find" &amp;&amp; checkBoxPCSearch.Checked) { String sqlSelectQuery = "SELECT * FROM Items Where PartCode = @SelectedPartCode"; var cmd = new SqlCommand(sqlSelectQuery, con); SetInsertParameters(cmd); SqlDataReader dr = cmd.ExecuteReader(); SetResponse(dr); AllVisible(); } else if ((string)cbfunctionSelection.SelectedItem == "Find" &amp;&amp; checkBoxNameSearch.Checked) { checkBoxPCSearch.Checked = false; String sqlSelectQuery = "SELECT * FROM Items Where Name = @SelectedName"; var cmd = new SqlCommand(sqlSelectQuery, con); SetInsertParameters(cmd); SqlDataReader dr = cmd.ExecuteReader(); SetResponse(dr); AllVisible(); } if ((String) cbfunctionSelection.SelectedItem == "Add") { checkBoxNameSearch.Checked = false; var cmd = new SqlCommand( "INSERT INTO items(Description,Colour,Manufacturer,StockLevel,Name) " + "VALUES ( @Description, @Colour, @Manufacturer, @StockLevel,@Name)", con); SetInsertParameters(cmd); cmd.ExecuteReader(); } if ((string) cbfunctionSelection.SelectedItem == "Delete") { var sqlDeleteQuery = "Delete from items where PartCode = @SelectedPartCode" ; SqlCommand cmd = new SqlCommand(sqlDeleteQuery, con); SetInsertParameters(cmd); SqlDataReader myreader; myreader = cmd.ExecuteReader(); myreader.Read(); } if ((string) cbfunctionSelection.SelectedItem == "Edit") { var cmd = new SqlCommand("update items SET Description = @Description ,Colour =@Colour ,Manufacturer = @Manufacturer,StockLevel = @StockLevel , Name = @Name where partcode = @SelectedPartCode", con); SetInsertParameters(cmd); cmd.ExecuteReader(); } else { MessageBox.Show("PLease refrence the helper text box for help i"); } con.Close(); } //setting the response for the find function private void SetResponse(SqlDataReader dr) { if (dr.Read()) { string itemDescription = (dr["Description"].ToString()); txtColour.Text = itemDescription; string itemColour = (dr["Colour"].ToString()); txtColour.Text = itemColour; string itemManufacturer = (dr["Manufacturer"].ToString()); txtColour.Text = itemManufacturer; string itemStockLevel = (dr["StockLevel"].ToString()); txtColour.Text = itemStockLevel; string itemName = (dr["Name"].ToString()); txtColour.Text = itemName; string itemPartCode = (dr["PartCode"].ToString()); txtColour.Text = itemPartCode; lblCompleteItemInfo.Text = ($"The items description is: {itemDescription} " + $"The items colour is: {itemColour} " + $"The items Manufacturer is: {itemManufacturer} " + $"The Items Stock Level is :{itemStockLevel} " + $"The Items Name is: {itemName} " + $"The items PartCode is: {itemPartCode} "); } else { MessageBox.Show("error"); } } //applying the values for sql queries through the input in tbox private void SetInsertParameters(SqlCommand cmd) { cmd.Parameters.AddWithValue("@Description", txtDescription.Text); cmd.Parameters.AddWithValue("@Colour", txtColour.Text); cmd.Parameters.AddWithValue("@Manufacturer", txtManufacturer.Text); cmd.Parameters.AddWithValue("@StockLevel", txtStockLevel.Text); cmd.Parameters.AddWithValue("@Name", txtName.Text); cmd.Parameters.AddWithValue("@PartCode", txtPartCode.Text); cmd.Parameters.AddWithValue("@SelectedPartCode", txtPartCodeEnter.Text); cmd.Parameters.AddWithValue("@SelectedName", txtNameEnter.Text); } private void AllVisible() { //txtboxes txtDescription.Visible = true; txtColour.Visible = true; txtManufacturer.Visible = true; txtStockLevel.Visible = true; txtName.Visible = true; txtPartCode.Visible = true; txtPartCodeEnter.Visible = true; txtNameEnter.Visible = true; //lbls lblDescription.Visible = true; lblColour.Visible = true; lblManufacturer.Visible = true; lblStockLevel.Visible = true; lblName.Visible = true; lblPartCode.Visible = true; lblNameEnter.Visible = true; lblPartCode.Visible = true; checkBoxNameSearch.Visible = true; checkBoxPCSearch.Visible = true; } private void cbfunctionSelection_SelectedIndexChanged(object sender, EventArgs e) { if ((String) cbfunctionSelection.SelectedItem == "Add" ) { AllVisible(); checkBoxNameSearch.Visible = false; checkBoxPCSearch.Visible = false; txtPartCodeEnter.Visible = false; txtNameEnter.Visible = false; txtPartCode.Visible = false; lblPartCode.Visible = false; lblNameEnter.Visible = false; lblPartCode.Visible = false; HelpLabel.Text = ("input the details for the item to be added."); } else if ((String) cbfunctionSelection.SelectedItem == "Find" ) { AllVisible(); txtDescription.Visible = false; txtColour.Visible = false; txtManufacturer.Visible = false; txtStockLevel.Visible = false; txtName.Visible = false; txtPartCode.Visible = false; lblDescription.Visible = false; lblColour.Visible = false; lblManufacturer.Visible = false; lblStockLevel.Visible = false; lblName.Visible = false; lblPartCode.Visible = false; HelpLabel.Text = ("input the Partcode of the item and the information will be displayed."); } else if ((String) cbfunctionSelection.SelectedItem == "Edit") { AllVisible(); lblPartCode.Visible = false; txtPartCode.Visible = false; txtNameEnter.Visible = false; lblNameEnter.Visible = false; checkBoxNameSearch.Visible = false; checkBoxPCSearch.Visible = false; HelpLabel.Text = ("Input the partcode of the item you would like to edit. Then the Information."); } else if ((String) cbfunctionSelection.SelectedItem == "Delete") { AllVisible(); txtDescription.Visible = false; txtColour.Visible = false; txtManufacturer.Visible = false; txtStockLevel.Visible = false; txtName.Visible = false; txtPartCode.Visible = false; txtNameEnter.Visible = false; checkBoxNameSearch.Visible = false; checkBoxPCSearch.Visible = false; lblDescription.Visible = false; lblColour.Visible = false; lblManufacturer.Visible = false; lblStockLevel.Visible = false; lblName.Visible = false; lblPartCode.Visible = false; lblNameEnter.Visible = false; HelpLabel.Text = ("Input the partcode of the item you would like to delete."); } } private void button1_Click_1(object sender, EventArgs e) { btnDisplayItemTable.Text = ("Refresh items table"); //This is database connection string String source = @"Data Source=WIN10-LAP-&gt;HJP\MSSQLSERVER1;Initial Catalog=VisualStudioConnect;Integrated Security=True"; //this is defining source as variable "con" to be used for SQL connection SqlConnection con = new SqlConnection(source); //opens connection con.Open(); // just message box MessageBox.Show("connected"); SqlDataAdapter sqlDa = new SqlDataAdapter("Select * From Items",source); DataTable dtb1 = new DataTable(); sqlDa.Fill(dtb1); dgv1.DataSource = dtb1; } private void button1_Click_2(object sender, EventArgs e) { new Form3().Show(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T14:00:44.253", "Id": "450018", "Score": "0", "body": "sorry apout the formatting still new to stack. I would simply like help cleaning up this code and help with breaking this down to classes. Please explain like im 5 as I am new to c#." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T14:07:01.400", "Id": "450020", "Score": "3", "body": "Welcome to Code Review! This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](//codereview.meta.stackexchange.com/q/1226)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T11:17:31.760", "Id": "450120", "Score": "0", "body": "Could you please add the content of the `Form1.Designer.cs`file as well?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T13:59:47.957", "Id": "230909", "Score": "3", "Tags": [ "c#", "sql" ], "Title": "cleaning up c# code which connects to sql database using windows form" }
230909
<p>This is our company's first attempt at an API and a mobile friendly web project, primarily we are desktop developers. We are using Identity Server 4 for serving up tokens and authentication, we have a mobile friendly web application and an API. I did a lot of the groundwork setting up the communication between the application and the API, and landed on the following wrapper framework.</p> <pre><code>public class ServiceBase { public ServiceBase(IConfiguration config, IHttpContextAccessor httpContextAccessor) { ApiDomain = config["IdentityServer:ApiResource"]; // .Result property causes the async operation to halt until it resolves. AccessToken = httpContextAccessor.HttpContext.GetTokenAsync("access_token").Result; ApiClient = new ApiHttpClient(ApiDomain, AccessToken); } protected ApiHttpClient ApiClient { get; private set; } protected string ApiDomain { get; private set; } protected string AccessToken { get; private set; } } </code></pre> <p>This is the HttpClient wrapper class that I am a little worried about - I did see a Visual Studio twitch session in which the presenters were talking about the IHttpClientFactory service methods, which got me to thinking that we should refactor. </p> <pre><code>public class ApiHttpClient: IApiHttpClient { // Article used to develop the asyn/await pattern used // https://stackoverflow.com/questions/15907356/how-to-initialize-an-object-using-async-await-pattern //Article used to develop the JSON serialize/deserialize pattern used // https://stackoverflow.com/questions/16019729/deserializing-json-object-into-a-c-sharp-list public ApiHttpClient() { } private HttpClient _httpClient; public ApiHttpClient(string baseApiUrl, string token) { BaseApiUrl = baseApiUrl; Token = token; _httpClient = new HttpClient(); _httpClient.SetBearerToken(token); } public string BaseApiUrl { get; set; } public string Token { get; set; } public string FullApiUrl { get; set; } public async Task&lt;string&gt; ApiClientAsyncString(string partialUri) { ValidateUrl(partialUri); var content = await _httpClient.GetStringAsync(FullApiUrl); return JArray.Parse(content).ToString(); } public async Task&lt;string&gt; ApiClientAsyncStringNonJson(string partialUri) { ValidateUrl(partialUri); var content = await _httpClient.GetStringAsync(FullApiUrl); return content.ToString(); } public async Task&lt;ApiContentResponse&lt;T&gt;&gt; GetAsync&lt;T&gt;(string partialUrl) where T : class { ValidateUrl(partialUrl); var response = await _httpClient.GetAsync(FullApiUrl); return new ApiContentResponse&lt;T&gt;(response); } public async Task&lt;ApiContentResponse&lt;T&gt;&gt; PostAsync&lt;T&gt;(string partialUrl, T modelView) where T : class { ValidateUrl(partialUrl); var json = JsonConvert.SerializeObject(modelView); var postContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json"); var response = await _httpClient.PostAsync(FullApiUrl, postContent); return new ApiContentResponse&lt;T&gt;(response); } public async Task&lt;ApiContentResponse&lt;U&gt;&gt; PostAsync&lt;T,U&gt;(string partialUrl, T modelView) where T : class where U : class { ValidateUrl(partialUrl); var json = JsonConvert.SerializeObject(modelView); var postContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json"); var response = await _httpClient.PostAsync(FullApiUrl, postContent); return new ApiContentResponse&lt;U&gt;(response); } public async Task&lt;ApiContentResponse&lt;T&gt;&gt; PostAsync&lt;T,K&gt;(string partialUrl, K criteria) where T: class where K: class { ValidateUrl(partialUrl); var json = JsonConvert.SerializeObject(criteria); var postContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json"); var response = await _httpClient.PostAsync(FullApiUrl, postContent); return new ApiContentResponse&lt;T&gt;(response); } public async Task&lt;ApiValueContentResponse&lt;T&gt;&gt; PostValueAsync&lt;T, K&gt;(string partialUrl, K criteria) where K : class { ValidateUrl(partialUrl); var json = JsonConvert.SerializeObject(criteria); var postContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json"); var response = await _httpClient.PostAsync(FullApiUrl, postContent); return new ApiValueContentResponse&lt;T&gt;(response); } public async Task&lt;ApiContentResponse&lt;T&gt;&gt; DeleteAsync&lt;T&gt;(string partialUrl) where T : class { ValidateUrl(partialUrl); var response = await _httpClient.DeleteAsync(FullApiUrl); return new ApiContentResponse&lt;T&gt;(response); } private void ValidateUrl(string partialUri) { if (string.IsNullOrWhiteSpace(BaseApiUrl)) { throw new ArgumentNullException("BaseApiUrl cannot be null or empty."); } if (string.IsNullOrWhiteSpace(Token)) { throw new ArgumentNullException("Token cannot be null or empty."); } if (string.IsNullOrWhiteSpace(partialUri)) { throw new ArgumentNullException("partialUri cannot be null or empty."); } FullApiUrl = UrlCombine(BaseApiUrl, partialUri); } private string UrlCombine(string partialUrl1, string partialUrl2) { if(partialUrl1.Length == 0) { return partialUrl2; } if(partialUrl2.Length == 0) { return partialUrl1; } partialUrl1 = partialUrl1.TrimEnd(new char[] { '/', '\\' }); partialUrl2 = partialUrl2.TrimStart(new char[] { '/', '\\' }); return $"{partialUrl1}/{partialUrl2}"; } </code></pre> <p>Following are response classes created to better manage the responses and standardize handling the responses.</p> <pre><code>public sealed class ApiContentResponse&lt;T&gt; where T : class { private readonly HttpResponseMessage _httpResponseMessage; private Task _initializationTask; public ApiContentResponse(HttpResponseMessage httpResponseMessage) { _httpResponseMessage = httpResponseMessage; _initializationTask = InitializeAsync(); } private async Task InitializeAsync() { var content = await _httpResponseMessage.Content.ReadAsStringAsync(); Content = JsonConvert.DeserializeObject&lt;T&gt;(content); Error = _httpResponseMessage.ReasonPhrase; RequestMessage = _httpResponseMessage.RequestMessage; StatusCode = _httpResponseMessage.StatusCode; Headers = _httpResponseMessage.Headers; Version = _httpResponseMessage.Version; IsSuccess = _httpResponseMessage.IsSuccessStatusCode; } public string Error { get; set; } public T Content { get; set; } public HttpHeaders Headers { get; set; } public HttpStatusCode StatusCode { get; set; } public HttpRequestMessage RequestMessage { get; set; } public Version Version { get; set; } public bool IsSuccess { get; set; } } public sealed class ApiValueContentResponse&lt;T&gt; { private readonly HttpResponseMessage _httpResponseMessage; private Task _initializationTask; public ApiValueContentResponse(HttpResponseMessage httpResponseMessage) { _httpResponseMessage = httpResponseMessage; _initializationTask = InitializeAsync(); } private async Task InitializeAsync() { var content = await _httpResponseMessage.Content.ReadAsStringAsync(); Content = JsonConvert.DeserializeObject&lt;T&gt;(content); Error = _httpResponseMessage.ReasonPhrase; RequestMessage = _httpResponseMessage.RequestMessage; StatusCode = _httpResponseMessage.StatusCode; Headers = _httpResponseMessage.Headers; Version = _httpResponseMessage.Version; IsSuccess = _httpResponseMessage.IsSuccessStatusCode; } public string Error { get; set; } public T Content { get; set; } public HttpHeaders Headers { get; set; } public HttpStatusCode StatusCode { get; set; } public HttpRequestMessage RequestMessage { get; set; } public Version Version { get; set; } public bool IsSuccess { get; set; } } </code></pre> <p>And an example usage of the above classes.</p> <pre><code>public interface ITestService { List&lt;TestModel&gt; GetTestObjects() {get; set;} } public class TestService: ServiceBase, ITestService { public List&lt;TestModel&gt; GetListOfTest() { var apiResults = ApiClient.GetAsync&lt;ApiTest_DTO&gt;($"api/testlist").Result; var testModels = new List&lt;TestModel&gt;(); // transformation from list of DTO to Model objects return testModels; } } public class TestController : Controller { private readonly ITestService _testService; public TestController(ITestService testService) { _testService = testService; } public async Tast&lt;IActionResult&gt; Index() { return View(_testService.GetListOfTest()); } } </code></pre> <p>Let me know if I am missing anything, I believe I have added the necessary code that I would like reviewed. We are getting closer to ready for a beta production release and I am getting nervous. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T04:15:19.947", "Id": "450087", "Score": "0", "body": "Reference [You're using HttpClient wrong and it is destabilizing your software](https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T04:15:32.817", "Id": "450088", "Score": "0", "body": "Reference [Async/Await - Best Practices in Asynchronous Programming](https://msdn.microsoft.com/en-us/magazine/jj991977.aspx)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T14:28:08.690", "Id": "450157", "Score": "0", "body": "@Nksoi - thank you for the links - I am reviewing them, already I am know I will need to change how we are using HttpClient. Would you be able to point out specifically what we are doing wrong with asyn/await? It would be helpful." } ]
[ { "body": "<h1>Async/Await</h1>\n<p>In a couple of places, you use <code>Task.Result</code> instead of <code>await Task</code>.\n<a href=\"https://stackoverflow.com/a/47290354/7412948\">This answer</a> explains more verbosely why this is considered bad practice, but the simple explanation is that <code>Task.Result</code> waits synchronously while <code>await Task</code> waits asynchronously.</p>\n<h1>HttpClient</h1>\n<p>You are correct that how the HttpClient is used can be improved. Since you are in dotnet core you have the ability to use DI and let the framework do the managing of the lifetime of your HttpClients.\nThere are a couple of ways to design this, and it depends on how the <code>ApiHttpClient</code> class is used and what its lifespan is.\nIf the class is short-lived (created for a controller to handle a request) then it can take an <code>HttpClient</code> as the only parameter in the constructor. This requires a bit of setup in the startup.cs methods for the instance to have the correct token and base url.\nIf the class is longer-lived then it can take an <code>IHttpClientFactory</code> and ask for an instance of <code>HttpClient</code> as it needs it.</p>\n<h1>General</h1>\n<h3>ApiHttpClient</h3>\n<p>The <code>ApiHttpClient</code> class looks to be a helper class at first glance, but the class properties seem to be leaking information outside that indicates not everything is encapsulated as it should.</p>\n<ol>\n<li>The constructor takes in and then sets the <code>BaseApiUrl</code>, but that <code>BaseApiUrl</code> has a public getter/setter. My assumption is that this should not change over the lifespan of the class instance thus should not be settable and probably does not need to be gettable either. Both cases are fixed if the constructor takes an <code>HttpClient</code>/<code>IHttpClientFactory</code> instead.</li>\n<li><code>FullApiUrl</code> is set in <code>ValidateUrl</code> and is publicly gettable/settable. This probably shouldn't be a property at all and should be local to the methods in which it is needed.</li>\n<li><code>Token</code> - Same as <code>BaseApiUrl</code>, probably shouldn't be publicly accessible, and with HttpClient refactor won't belong to the class at all.</li>\n<li>Code reuse could occur in many of the ApiClientAsync* methods. Consider having <code>ApiClientAsyncString</code> call <code>ApiClientAsyncStringNonJson</code> and then convert the result to Json.</li>\n</ol>\n<h3>ApiContentResponse/ApiValueContentResponse</h3>\n<ol>\n<li>The constructor calls an async method and does not await the result. Async Constructors do not exist, hence why the code probably exists in the state it is. Since the task is not awaited, there is no guarantee that once the constructor call is completed that any of the properties are actually set. The task could be waiting on <code>ReadAsStringAsync</code> indefinitely for all we know.\n<ul>\n<li>The best away that I can think is to provide the result of <code>ReadAsStringAsync</code> directly in the constructor, and possibly not provide the <code>HttpResponseMessage</code> if it is not needed.</li>\n<li>A second option (if it exists) is to use a synchronous <code>ReadAsString</code> instead, but I would recommend this less than the first option.</li>\n</ul>\n</li>\n</ol>\n<h1>Code Confidence</h1>\n<p>This might be a bit off-topic of the code posted specifically, but because it was mentioned in the original post I want to talk to it.</p>\n<p>You mention that you are nearing release to production and you are getting nervous. A way to know that code is working is by testing it. There are many layers to this and all should be used to some extent.</p>\n<ol>\n<li><strong>Unit Testing</strong> can be used to know a specific piece of code that handles valid input/output, edge cases, and error cases correctly.</li>\n<li><strong>Integration Testing</strong> can be used to verify one piece of (hopefully unit tested) code is using another piece of (hopefully unit tested) code correctly.</li>\n<li><strong>Manual Testing</strong> is the final catch-all to get your eyes and hands on the product. Do some exploratory testing, make sure the GUIs look right.</li>\n</ol>\n<p>There the amount of these tests should form a pyramid in an ideal situation. The base and most by volume being unit tests followed next by integration tests and finally (and least of all) manual tests.</p>\n<p>Finally, have a production go-live checklist. Automate as much of it as you can, but always have a smoke-test in place to verify certain critical pieces of the product are working when deployed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-24T03:55:06.467", "Id": "450856", "Score": "1", "body": "Welcome to Code Review! Good points, nice answer!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-29T14:19:00.000", "Id": "451494", "Score": "0", "body": "@Jeffrey Parks: Thank you for the detailed code review! I/we have already implemented a the HttpClientFactory and are in the process of removing `.Result` from out code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-24T03:24:08.833", "Id": "231240", "ParentId": "230910", "Score": "4" } } ]
{ "AcceptedAnswerId": "231240", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T14:20:06.607", "Id": "230910", "Score": "2", "Tags": [ "c#", "asp.net-core" ], "Title": "HttpClient Wrapper for standardized API communication" }
230910
<p>I've written a class that implements something akin to the <a href="https://en.wikipedia.org/wiki/Token_bucket" rel="nofollow noreferrer">token bucket algorithm</a> so that I may rate limit aysnc HTTP requests made from my application.</p> <p>The code works but I'm still not sure if it feels 'right', maybe just because I am new to async programming in Python.</p> <p>Specific concerns:</p> <ul> <li>It feels weird/bad how the state (<code>self.last</code>, <code>self.tokens</code>) is managed (or not managed) meaning checks in the <code>_refill</code> method.</li> <li>Maybe I shouldn't be using a context manager (<code>__aenter__</code> and <code>__aexit__</code>) for this.</li> <li>I'm not sure if I should be doing any cleaning-up in <code>__aexit__</code></li> <li>Implementation of the algorithm may not be 100% faithful as I am waiting until the bucket is empty before refilling as a batch . I think this may be OK because only one token can be consumed per request.</li> </ul> <pre class="lang-py prettyprint-override"><code>""" Typical usage example: async def rateLimitedTask(bucket): await bucket.removeToken() #wait for token #do the task which has now been rate limited ... async with TokenBucket(2, 1/5) as bucket: #make arbitrary async calls to rateLimitedTask() ... """ import asyncio import time from collections import deque class TokenBucket(): """Context manager which provides a token bucket. Attributes: tokens (collections.deque): The tokens (which manifest as timestamps) in reverse chronological order. last (float): The most recent token consumed. rate (float): See __init__ arg `tokensPerS`. capacity (int): See __init__ arg `capacity`. sleepDuration (float): See __init__ arg `refillSleepS`. """ def __init__(self, capacity=1, tokensPerS=1.0, refillSleepS=0.1): """Initialises the TokenBucket context manager. Args: capacity (int, optional): The maxiumum tokens the bucket can hold. Larger is burstier. Defaults to 1. tokensPerS (float, optional): The average replenishment rate in tokens per second. Defaults to 1. refillSleepS (float, optional): If not enough time has passed to refill; how many seconds to sleep before trying again. Defaults to 0.1. """ self.capacity = capacity self.rate = tokensPerS self.last = None self.tokens = deque([]) self.sleepDuration = refillSleepS def hasTokens(self): return len(self.tokens) &gt; 0 def isEmpty(self): return len(self.tokens) &lt; 1 async def _refill(self): """Refill the empty bucket back up to capacity. Is called only when the bucket is empty. The tokens themselves are timestamps of when the token was created. Uses monotonic time to safeguard against system clock changes. """ if self.last: #prevents unnecessary run on virgin execution while self.capacity / (time.monotonic() - self.last) &gt; self.rate: await asyncio.sleep(self.sleepDuration) if self.hasTokens(): return #another call filled the bucket already for _ in range(self.capacity): self.tokens.appendleft(time.monotonic()) async def removeToken(self): """Removes a token from the bucket and returns void. If the bucket is empty it will await its refill before returning. """ if self.isEmpty(): await self._refill() self.last = self.tokens.pop() async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): pass </code></pre> <p>Any help would be much appreciated.</p>
[]
[ { "body": "<h2>Parent-less class</h2>\n\n<pre><code>class TokenBucket():\n</code></pre>\n\n<p>can drop the parens.</p>\n\n<h2>lower_snake_case</h2>\n\n<p>These variables:</p>\n\n<ul>\n<li><code>tokensPerS</code></li>\n<li><code>refillSleepS</code></li>\n<li><code>sleepDuration</code></li>\n</ul>\n\n<p>etc., and all of your methods, should be in lower_snake_case instead of camelCase, by convention.</p>\n\n<h2>Type hints</h2>\n\n<p>PEP484 allows you to turn this</p>\n\n<pre><code>def hasTokens(self):\n</code></pre>\n\n<p>into this</p>\n\n<pre><code>def hasTokens(self) -&gt; bool:\n</code></pre>\n\n<p>and likewise for your other method parameters and returns. Among other things, it will allow you to drop your types from comments like this:</p>\n\n<pre><code>\"\"\"\n tokens (collections.deque): The tokens (which manifest as timestamps)\n in reverse chronological order.\n last (float): The most recent token consumed.\n rate (float): See __init__ arg `tokensPerS`.\n capacity (int): See __init__ arg `capacity`.\n sleepDuration (float): See __init__ arg `refillSleepS`.\n\"\"\"\n</code></pre>\n\n<p>because they'll already be in the signature.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T01:57:48.227", "Id": "231167", "ParentId": "230911", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T15:03:05.333", "Id": "230911", "Score": "3", "Tags": [ "python", "networking", "async-await" ], "Title": "Token Bucket context manager for rate limiting async calls" }
230911
<p>So I have a loop that works great, but doing some testing I notice it is a bit slow. I get an average time within the loop of about 0.11 seconds. Include that with some arrays containing a length of over 100 and the time starts making a big difference. So I mainly want to improve the speed of the loop without compromising the functionality it already has (which is taking a JSON object/array and turning it into an html format). Below is the code along with the function that is called within the loop.</p> <pre><code>let replacements = ''; let ind = 0; for (let w in obj[key]) { if (Array.isArray(obj[key])) { if (Array.isArray(obj[key][w])) { if (obj[key].length &gt; 10) { replacements += "&lt;font color='green'&gt;Array(" + obj[key].length + ")&lt;/font&gt;" break } replacements += ((ind == 0) ? "&lt;font color='green'&gt;Array(" : ", &lt;font color='green'&gt;Array(") + obj[key][w].length + ")&lt;/font&gt;"; } else { if (typeof obj[key][w] === 'object') { replacements += ((ind == 0) ? "" : ", ") + "{...}"; } else { replacements += ((ind == 0) ? "" : ", ") + ObjectString(obj[key][w], "preview"); } } } else { if (Array.isArray(obj[key][w]) || typeof obj[key][w] === 'object') { replacements += ((ind == 0) ? "" : ", ") + w + ": " + ((Array.isArray(obj[key][w])) ? "[...]" : "{...}"); } else { replacements += ((ind == 0) ? "" : ", ") + w + ": "; replacements += ObjectString(obj[key][w], "preview"); } } ind++; } function ObjectString(obj, type) { //~0.001-0.003 seconds let objString = obj; if (typeof objString == "string" &amp;&amp; !objString.match(/&lt;.*?&gt;/g)) objString = "&lt;font color='red'&gt;\"" + objString + "\"&lt;/font&gt;"; else if (/&lt;.*?&gt;/g.test(objString)) objString = ((type == "normal") ? "&lt;pre&gt;" + process(objString).replace(/&lt;/g, '&amp;lt;').replace(/&gt;/g, '&amp;gt;') + "&lt;/pre&gt;" + objString : "&lt;font color='red'&gt;\"...\"&lt;/font&gt;"); else if (typeof objString == "number" || typeof objString == "boolean") objString = "&lt;font color=' #947cf6'&gt;" + objString + "&lt;/font&gt;"; return objString } function process(str) {//~0.001 seconds var div = document.createElement('div'); div.innerHTML = str.trim(); return format(div, 0).innerHTML; } </code></pre> <p>Hopefully this can be optimized to increase its speed, but if it can't then I would at least like some help to clean it up as I am sure this isn't the most effective way to do it. Thanks!</p> <p>Edit: added the process function that was previous missing. Also for clarification I am using regular JSON arrays and objects that usually exceed 100 objects in the array. If you want an example of what that data could look like <a href="https://en.wikipedia.org/wiki/GeoJSON#Example" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/GeoJSON#Example</a> has a good structure of some of the data I am parsing (containing both objects and arrays).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T16:18:39.753", "Id": "450030", "Score": "0", "body": "What methods have you tried? I could be wrong, but `for... in` I think is slower than other methods, like a straight `for(let x = 0; x < length; x++)` method. To clean this up, you may want to look at a simple template engine like mustache. That would remove your html and probably do most of the heavy lifting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T16:39:56.407", "Id": "450040", "Score": "0", "body": "You are right with the `for...in` statement, they are generally slower. I tested moving it to a standard loop, but it seems like the major break is the check if its an array or object." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T16:57:32.040", "Id": "450046", "Score": "0", "body": "I think you're right. Is it a possibility to cast everything as desired type instead of checking? Or use the old `JSON.parse(JSON.strigify(obj))` as a cast method?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T16:59:01.760", "Id": "450047", "Score": "0", "body": "Or use `Object.keys(obj).map()` instead of checks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T17:11:26.960", "Id": "450051", "Score": "0", "body": "110ms is very slow, but that will depend on the number of items being processed. You have not provided that information also there is a function in `ObjectString` that you have not provided `process`. As it looks 110ms would produce a huge string containing too many elements to be practical. Are you sure the problem in your functions and not the DOM parsing the HTML you have created?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T17:21:22.190", "Id": "450053", "Score": "0", "body": "I edited the post with more details (including the missing function). From testing and not running parts of the loop the best that I can tell is that the DOM is not the cause (as its not added until the end) and checking if its an array or object is the slow down. Using both `Array.isArray()` and `typeof` cause a slowing of the loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T17:37:27.577", "Id": "450057", "Score": "1", "body": "`isArray` and `typeof` can execute millions of times in 110ms and not the cause of the slowdown. It is the DOM as you create a div and then add HTML to it in `process`. That will be very slow, also the function `format` what ever it does? could make it even worse" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T18:06:37.797", "Id": "450059", "Score": "0", "body": "the process function only runs when there is an html string given. Most of the time this function is not used, but just to fix/close any tags. If I comment out the part that deals with arrays it runs faster. I have tested this and gotten a time of the array test to take ~0.03 seconds." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T15:46:27.190", "Id": "450174", "Score": "0", "body": "Doing another test of the parsing of data, I can say that the process function takes about ~0.002 seconds on average. All this function does is create a node, pretty print it, then return it as its been pretty printed. It will only run when it finds that the data contains html tags. So most of the time its skipped, however isArray and typeof are taking 2-3 times longer than the parsing of the DOM (which normally doesn't make sense, but its doing it that way). I also tested checking the first character from Ranger's method, didn't change the speed much." } ]
[ { "body": "<ul>\n<li>Continuous repetitive string concatenation is bad for performance because each such operation requires re-hashing of the string due to <a href=\"https://wikipedia.org/wiki/String_interning\" rel=\"nofollow noreferrer\">String interning</a>.</li>\n<li><strong>Array</strong> enumeration using <code>for-in</code> loop is slower than <code>for-of</code> or a standard <code>for</code> loop.</li>\n<li>Things like <code>obj[key][subkey]</code> may be slow in a long loop so cache them in a variable.</li>\n<li>Do the proper performance measurements using <a href=\"https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/reference\" rel=\"nofollow noreferrer\">Devtools Timeline profiler</a> to find bottlenecks.</li>\n</ul>\n\n<hr>\n\n<p>Here's an arguably more readable and hopefully faster example:</p>\n\n<pre><code>const parts = [];\nconst group = obj[key];\n\nif (Array.isArray(group)) {\n for (const val of group) {\n if (parts.length) parts.push(', ');\n if (Array.isArray(val)) {\n const tooLong = group.length &gt; 10;\n const len = (tooLong ? group : val).length;\n parts.push(`&lt;font color=\"green\"&gt;Array(${len})&lt;/font&gt;`);\n if (tooLong) break;\n } else {\n parts.push(objectPreview(val));\n }\n }\n} else {\n for (const [key, val] of Object.entries(group)) {\n parts.push(`${parts.length ? ', ' : ''}${key}: ${\n Array.isArray(val) ? '[...]' : objectPreview(val)\n }`);\n }\n}\nconst replacements = parts.join('');\n</code></pre>\n\n<pre><code>function objectPreview(obj) {\n let str = obj;\n switch (typeof obj) {\n case 'object':\n str = '{...}';\n break;\n case 'string':\n if (/&lt;.*?&gt;/.test(obj)) {\n str = type === 'normal' ?\n `&lt;pre&gt;${process(obj).replace(/&lt;/g, '&amp;lt;').replace(/&gt;/g, '&amp;gt;')}&lt;/pre&gt;${obj}` :\n '&lt;font color=\"red\"&gt;\"...\"&lt;/font&gt;';\n } else {\n str = `&lt;font color=\"red\"&gt;\"${obj}\"&lt;/font&gt;`;\n }\n break;\n case 'number':\n case 'boolean':\n str = `&lt;font color=\"#947cf6\"&gt;${obj}&lt;/font&gt;`;\n break;\n }\n return str;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T13:11:42.167", "Id": "450450", "Score": "0", "body": "I didn't realize that calling things like `obj[key][subkey]` caused slowdown's like it has. I will keep this in mind in the future. I also didn't think about using Template literals inside my code would clean it up that much, I will also keep this in mind for the future. And the switch case for readability was also something I didn't think of (since its easier to read and maintain in this form). With testing performance of 400+ entries (the most I encounter) I see no slow down. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T09:34:33.220", "Id": "231032", "ParentId": "230913", "Score": "2" } } ]
{ "AcceptedAnswerId": "231032", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T16:05:08.540", "Id": "230913", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Improving the speed of loop in javascript for objects" }
230913
<h3>Problem</h3> <p>Write a function that accepts a string, capitalizes the first letter of each word in the string, and returns the capitalized string.</p> <h3>Examples</h3> <pre><code>function('a short sentence') =&gt; 'A Short Sentence' function('a lazy fox') =&gt; 'A Lazy Fox' function('look, it is working!') =&gt; 'Look, It Is Working!' </code></pre> <h3>Code</h3> <p>I've solved the above problem using a few methods. If you'd like to review the codes and provide any change/improvement recommendations please do so, and I'd really appreciate that.</p> <h3>Python</h3> <pre><code>def capitalize_built_in_title(sentence: str) -&gt; str: """Capitalizes the first letters and preserves the spaces""" return sentence.title() def capitalize_naive_one(sentence: str) -&gt; str: """Capitalizes the first letters and doesn't preserve the spaces""" words = sentence.split() for index_word, word in enumerate(words): word_list = split_char_by_char_list(word) for index_letter, letter in enumerate(word_list): if index_letter == 0: word_list[index_letter] = letter.upper() word = "".join(word_list) break words[index_word] = word return " ".join(words) def capitalize_naive_two(sentence: str) -&gt; str: """Capitalizes the first letters and doesn't preserve the spaces""" words = sentence.split() for index_word, word in enumerate(words): words[index_word] = word[:1].upper() + word[1:] return " ".join(words) def capitalize_naive_three(sentence: str) -&gt; str: """Capitalizes the first letters and preserves the spaces""" import regex as re split_on_first_letter = list( re.splititer(r'(?i)(?&lt;=^|\s)([a-z])', sentence)) for index, item in enumerate(split_on_first_letter): if item is not None and len(item) == 1: split_on_first_letter[index] = item.upper() return "".join(split_on_first_letter) def split_char_by_char_re(string: str): import re return re.findall(r'.', string) def split_char_by_char_regex(string: str): import regex as re return re.findall(r'.', string) def split_char_by_char_list(string: str): return list(string) if __name__ == '__main__': # ---------------------------- TEST --------------------------- DIVIDER_DASH_LINE = '-' * 50 GREEN_APPLE = '\U0001F34F' RED_APPLE = '\U0001F34E' test_sentences = ['hey there, how was your day?', ' good day! ', ' it waS GreaT!'] capitalized_sentences = [ 'Hey There, How Was Your Day?', ' Good Day! ', ' It WaS GreaT!'] # ---------------------- DONT REPEAT YOURSELF ------------------------------- for index, sentence in enumerate(test_sentences): print(DIVIDER_DASH_LINE) if capitalized_sentences[index] == capitalize_built_in_title(sentence): print(f'{GREEN_APPLE} "{sentence}" =&gt; "{capitalize_built_in_title(sentence)}"') else: print(f'{RED_APPLE} "{sentence}" =&gt; "{capitalize_built_in_title(sentence)}"') if capitalized_sentences[index] == capitalize_naive_one(sentence): print(f'{GREEN_APPLE} "{sentence}" =&gt; "{capitalize_naive_one(sentence)}"') else: print(f'{RED_APPLE} "{sentence}" =&gt; "{capitalize_naive_one(sentence)}"') if capitalized_sentences[index] == capitalize_naive_two(sentence): print(f'{GREEN_APPLE} "{sentence}" =&gt; "{capitalize_naive_two(sentence)}"') else: print(f'{RED_APPLE} "{sentence}" =&gt; "{capitalize_naive_two(sentence)}"') if capitalized_sentences[index] == capitalize_naive_three(sentence): print(f'{GREEN_APPLE} "{sentence}" =&gt; "{capitalize_naive_three(sentence)}"') else: print(f'{RED_APPLE} "{sentence}" =&gt; "{capitalize_naive_three(sentence)}"') </code></pre> <h3>Output</h3> <pre><code>-------------------------------------------------- "hey there, how was your day?" =&gt; "Hey There, How Was Your Day?" "hey there, how was your day?" =&gt; "Hey There, How Was Your Day?" "hey there, how was your day?" =&gt; "Hey There, How Was Your Day?" "hey there, how was your day?" =&gt; "Hey There, How Was Your Day?" -------------------------------------------------- " good day! " =&gt; " Good Day! " " good day! " =&gt; "Good Day!" " good day! " =&gt; "Good Day!" " good day! " =&gt; " Good Day! " -------------------------------------------------- " it waS GreaT!" =&gt; " It Was Great!" " it waS GreaT!" =&gt; "It WaS GreaT!" " it waS GreaT!" =&gt; "It WaS GreaT!" " it waS GreaT!" =&gt; " It WaS GreaT!" </code></pre> <h3>JavaScript</h3> <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>// --- Problem // Write a function that accepts a string. The function should // capitalize the first letter of each word in the string then // return the capitalized string. // --- Examples // function('a short sentence') =&gt; 'A Short Sentence' // function('a lazy fox') =&gt; 'A Lazy Fox' // function('look, it is working!') =&gt; 'Look, It Is Working!' function capitalize_naive_one(sentence) { words = []; for (let word of sentence.split(' ')) { if (word != '') { word = (word[0].toUpperCase() + word.slice(1)); } words.push(word); } return words.join(' '); } function capitalize_naive_two(sentence) { capitalized_sentence = sentence[0].toUpperCase(); for (let i = 1; i &lt; sentence.length; i++) { if (sentence[i - 1] === ' ') { capitalized_sentence += sentence[i].toUpperCase(); } else { capitalized_sentence += sentence[i]; } } return capitalized_sentence; } test_sentences = ['hey there, how was your day?', ' good day! ', ' it waS GreaT!']; capitalized_sentences = ['Hey There, How Was Your Day?', ' Good Day! ', ' It WaS GreaT!']; count = 0; for (let sentence of test_sentences) { if (capitalized_sentences[count] === capitalize_naive_one(sentence) &amp;&amp; capitalized_sentences[count] === capitalize_naive_two(sentence)) { console.log(' "'.concat(sentence, '" =&gt; "', capitalized_sentences[count], '"')); } count++; }</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T16:41:35.070", "Id": "450041", "Score": "1", "body": "You are not just capitalizing the first letter of each word, you have different variations where the same phrase gives both \"red\" and \"green\" output. Just \"capitalizing the first letter of each word\" is relatively simple." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T17:03:59.903", "Id": "450048", "Score": "1", "body": "I can cover all your \"green\" cases with single function (with retaining all spaces and without redundant lowercasing). If that suits your requirement?" } ]
[ { "body": "<h2>JavaScript</h2>\n<ul>\n<li>Javascript uses <code>camelCase</code> by convention not <code>snake_case</code></li>\n<li>Undeclared variables are placed in global scope or throw a parsing error in strict mode. The further a variable's scope is from the current scope the longer it takes to get the reference and thus the slower the code. You have not declared <code>words</code>, <code>capitalized_sentence</code> and more in the testing code</li>\n<li>Best to use constants for variables that do not change.</li>\n<li>Always use strict equality <code>===</code> and inequality <code>!==</code> as they are faster and unless you are familiar with JS type coercion safer to use as they do not coerce type.</li>\n</ul>\n<h2>Rewrite</h2>\n<p>Rewriting your function using idiomatic JS</p>\n<pre><code>function capitalize(str) {\n const words = [];\n for (const word of str.split(&quot; &quot;)) {\n if (word !== '') { word = word[0].toUpperCase() + word.slice(1) }\n words.push(word);\n }\n return words.join(&quot; &quot;);\n}\n</code></pre>\n<p>You could also do a one liner using string replace and a RegExp</p>\n<pre><code>const capitalize = str =&gt; str.replace(/\\b[a-z]/g, char =&gt; char.toUpperCase());\n</code></pre>\n<p>However the regular expression does make it a little slow.</p>\n<h2>Immutable strings</h2>\n<p>JavaScript string are immutable, and thus you must take great care when handling strings as allocation overheads can slow things down. Avoid needless copying of strings</p>\n<h2>Accessing characters</h2>\n<p>The quickest way to get at characters in a string is via <code>String.charCodeAt(idx)</code></p>\n<p>For simple capitalization if you know that the char is lower case <code>String.fromCharCode(str.charCodeAt(0) - 32)</code> is twice as fast as <code>str[0].toUpperCase()</code></p>\n<p>With the above two points in mind you can double (or better as it skips already uppercase words) the performance with the following.</p>\n<ul>\n<li>Only copies words if they need capitalization.</li>\n<li>Uses the character code to do the capitalization.</li>\n<li>Uses the one array, to avoid overhead building a second array.</li>\n</ul>\n<p>.</p>\n<pre><code>function capit(str) {\n const words = str.split(&quot; &quot;);\n var i = 0, char;\n for (const word of words) {\n word !== &quot;&quot; &amp;&amp; (char = word.charCodeAt(0)) &gt; 96 &amp;&amp; char &lt; 122 &amp;&amp; \n (words[i] = String.fromCharCode(char - 32) + word.slice(1));\n i++;\n }\n return words.join(&quot; &quot;);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T22:36:02.640", "Id": "230926", "ParentId": "230917", "Score": "1" } } ]
{ "AcceptedAnswerId": "230926", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T16:30:42.573", "Id": "230917", "Score": "1", "Tags": [ "python", "javascript", "beginner", "algorithm", "strings" ], "Title": "Capitalize the First Letter of Words in a String (JavaScript, Python)" }
230917
<p>Have you ever wanted to get just not <em>one</em> "best" element from a list, but <em>all</em> of them, or a <em>random</em> element of the best ones? That's what the Best class is here for. Opinion-based? Definitely not!</p> <p>Features:</p> <ul> <li>Should work with any kind of element.</li> <li>Should always keep track of the best elements seen so far.</li> <li>Should be able to get a list of all best elements</li> <li>Should be able to get a single best element</li> </ul> <p>I thought about supporting both <code>Comparator&lt;T&gt;</code> and <code>(T) -&gt; Double</code>, but realized that I have a use-case for actually finding out the actual <em>value</em> as well (for an implementation of Alpha-Beta pruning in Minmax algorithm). I thought that <code>(T) -&gt; Double</code> option is more flexible in the long run (feel free to convince me about otherwise).</p> <h3>Code</h3> <p>The code is written for multi-platform Kotlin projects. It should be able to compile to both JVM, JavaScript, and Kotlin Native.</p> <pre><code>class Best&lt;T&gt;(private val valueFunction: (T) -&gt; Double) { private var bestValue: Double = Double.NEGATIVE_INFINITY private var bestElements: MutableList&lt;T&gt; = mutableListOf() fun next(element: T) { val value = valueFunction(element) if (value &gt; bestValue) { bestValue = value bestElements = mutableListOf(element) } else if (value &gt;= bestValue) { bestElements.add(element) } } fun randomBest(): T = bestElements.random() fun getBest(): List&lt;T&gt; = bestElements.toList() fun firstBest(): T = bestElements.first() fun isBest(element: T): Boolean = bestElements.contains(element) fun getBestValue(): Double = bestValue } </code></pre> <h3>Tests</h3> <pre><code>class BestTest { private fun createBest(): Best&lt;String&gt; { val best = Best&lt;String&gt; { it.length.toDouble() } best.next("hi") best.next("hello") best.next("") best.next("world") return best } @Test fun empty() { val emptyBest = Best&lt;Double&gt; { it } assert(emptyBest.getBest().isEmpty()) assertThrows&lt;NoSuchElementException&gt; { emptyBest.randomBest() } assertThrows&lt;NoSuchElementException&gt; { emptyBest.firstBest() } assertFalse(emptyBest.isBest(4.2)) } @Test fun random() { val randomBest = createBest().randomBest() assertTrue(randomBest == "hello" || randomBest == "world") } @Test fun bestList() { val allBest = createBest().getBest() assertEquals(listOf("hello", "world"), allBest) } @Test fun firstBest() { assertEquals("hello", createBest().firstBest()) } @Test fun isBest() { val best = createBest() assertFalse(best.isBest("")) assertFalse(best.isBest("hi")) assertFalse(best.isBest("something random that was never added")) assertTrue(best.isBest("hello")) assertTrue(best.isBest("world")) } } </code></pre> <h3>Questions</h3> <ul> <li>Does this class seem useful? (Is it as useful as the name sounds?)</li> <li>Would this class benefit from implementing Kotlin's <code>Collection</code> interface?</li> <li>Any improvement suggestions that you can think of</li> </ul>
[]
[ { "body": "<p>I hate the name, but don't have a better one so I'll leave that for another answer.</p>\n\n<p>Here's what I do have though: why not make it <em>more</em> generic?</p>\n\n<p>I'm looking at this function:</p>\n\n<pre><code>fun next(element: T) {\n val value = valueFunction(element)\n if (value &gt; bestValue) {\n bestValue = value\n bestElements = mutableListOf(element)\n } else if (value &gt;= bestValue) {\n bestElements.add(element)\n }\n}\n</code></pre>\n\n<p>Why not make a <code>isBetterThanFunction: (T, T) -&gt; Boolean</code> and <code>isEqualToFunction: (T, T) -&gt; Boolean</code>. Then, you can support a wider array of items, and you don't need <code>valueFunction</code>.</p>\n\n<pre><code>class Best&lt;T&gt;(private val isBetterThanFunction: (T, T) -&gt; Boolean, private val isEqualToFunction: (T, T) -&gt; Boolean) {\n\n private var bestValue: ...\n private var bestElements: MutableList&lt;T&gt; = mutableListOf()\n\n fun next(element: T) {\n if (isBetterThanFunction(element, bestValue)) {\n bestValue = element\n bestElements = mutableListOf(element)\n } else if (isEqualToFunction(element, bestValue)) {\n bestElements.add(element)\n }\n }\n\n fun randomBest(): T = bestElements.random()\n fun getBest(): List&lt;T&gt; = bestElements.toList()\n fun firstBest(): T = bestElements.first()\n fun isBest(element: T): Boolean = bestElements.contains(element)\n fun getBestValue(): Double = bestValue\n\n}\n</code></pre>\n\n<p>To me, it makes things more clear. I'm no longer inferring what you mean with <code>(T) -&gt; Double</code>. How is that weighted? Well, now <em>I</em> make that decision.</p>\n\n<p>Why does this matter? What if I defined <code>best</code> as \"shortest\"? With your version, I have to get clever about it and probably negate the value or something. With this version, <em>I</em> pick how that works.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T19:53:11.713", "Id": "450068", "Score": "0", "body": "I imagine there would be quite a bit of duplicated code in a lot of cases between the `isBetterThan` and `isEqualTo`. Also, as I wrote in the question, I have a use-case for getting the actual value as well. But you are right that I had to negate the value in my minimax implementation, which is indeed a problem I would like to avoid." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T19:53:55.153", "Id": "450069", "Score": "0", "body": "Subclass and change the implementation there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T18:54:22.140", "Id": "450326", "Score": "0", "body": "What's wrong with the name? :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T18:55:17.290", "Id": "450495", "Score": "0", "body": "@SimonForsberg I just don't like it, but I don't have an alternative so take that with a grain of salt lol" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T19:40:05.297", "Id": "230923", "ParentId": "230922", "Score": "5" } }, { "body": "<p>The question whether to use <code>(T) -&gt; Double</code> or <code>Comparator&lt;T&gt;</code> probably depends on your use case. If you have a scenario where you explicitly know, that your objects can always be mapped to a double, then it's fine to use <code>(T) -&gt; Double</code>. </p>\n\n<p>On the other hand, once you have such a weighting function, then it's trivial to create a <code>Comparator</code> based on that. And (my gut says - I haven't researched it) the reverse (creating a weighting function out of a <code>Comparator</code>) may not be possible. That means a version using a <code>Comparator</code> would be more flexible.</p>\n\n<blockquote>\n <p>Does this class seem useful? (Is it as useful as the name sounds?)</p>\n</blockquote>\n\n<p>I'm sure there is a scenario where this could be used, but I don't like the name either. Maybe something like <code>BestWeightHolder</code>?</p>\n\n<blockquote>\n <p>Would this class benefit from implementing Kotlin's Collection interface?</p>\n</blockquote>\n\n<p>IMO, no, not directly. That actually touches one of my criticisms I have: You have several \"utility\" methods (<code>randomBest</code>, <code>firstBest</code> and possibly <code>contains</code>) which don't seem to fit into the purpose of the class IMO, especially since they can just as well be executed on the list returned by <code>toList</code>.</p>\n\n<p>I think you should drop those methods and replace <code>toList</code> with an <code>asCollection</code> method, which returns not a copy of the list of best items, but a direct reference of your internal list limited to the <code>Collection</code> interface (or if you want to make sure it is not cast back to a <code>MutableList</code> and modified, an instance of a thin wrapper class that implements <code>Collection</code>). The user then can use <code>first()</code>, <code>random()</code>, <code>contains()</code>and more on that.</p>\n\n<blockquote>\n <p>Any improvement suggestions that you can think of</p>\n</blockquote>\n\n<p>I'm not a big fan of the method name <code>next</code>. Methods of that name usually indicate a supplying method (as in an <code>Iterator</code>, for example). I'd suggest <code>add</code> or (following Java's <code>Integer/Long/DoubleSummaryStatistics</code> classes which have a similar function and which implement <code>Consumer&lt;T&gt;</code>) <code>accept</code>.</p>\n\n<p>One tiny thing:</p>\n\n<blockquote>\n<pre><code>} else if (value &gt;= bestValue) {\n</code></pre>\n</blockquote>\n\n<p>should use <code>==</code> instead of <code>&gt;=</code>.</p>\n\n<p>And finally, personally, following Kotlin's pattern, I would consider implementing this as an immutable class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T18:54:26.483", "Id": "450327", "Score": "0", "body": "What's wrong with the name? :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T06:52:14.117", "Id": "450376", "Score": "1", "body": "@SimonForsberg It's not the best :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T11:34:31.280", "Id": "230949", "ParentId": "230922", "Score": "5" } }, { "body": "<p>One of the things I really like about Kotlin is how the source code for existing functions in the <code>stdlib</code> are readily available and can be leveraged to quickly create very efficient functions that are similar to existing ones.</p>\n\n<p>In your particular case I suggest taking a look at <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/max.html\" rel=\"nofollow noreferrer\"><code>max</code></a>, <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/max-by.html\" rel=\"nofollow noreferrer\"><code>maxBy</code></a>, and <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/max-with.html\" rel=\"nofollow noreferrer\"><code>maxWith</code></a>. We can create our own extension functions that instead of returning a single \"max\" element returns a <code>List</code> of them. e.g. <code>maxElements</code>, <code>maxElementsBy</code>, and <code>maxElementsWith</code>.</p>\n\n<p>For this example we only need a <code>maxElementsWith</code> function which takes a <code>Comparator</code> (based on <a href=\"https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/common/src/generated/_Collections.kt#L1688-L1700\" rel=\"nofollow noreferrer\"><code>maxWith</code> source code</a>):</p>\n\n<pre><code>fun &lt;T&gt; Iterable&lt;T&gt;.maxElementsWith(comparator: Comparator&lt;in T&gt;): List&lt;T&gt; {\n val iterator = iterator()\n if (!iterator.hasNext()) return emptyList()\n var max = iterator.next()\n var maxElements = mutableListOf(max)\n while (iterator.hasNext()) {\n val e = iterator.next()\n when (comparator.compare(e, max).sign) {\n 1 -&gt; {\n max = e\n maxElements = mutableListOf(max)\n }\n 0 -&gt; maxElements.add(e)\n }\n }\n return maxElements\n}\n</code></pre>\n\n<p>You can then use <code>maxElementsWith</code> to find a single \"best\" (max) value, a list of them, a random one, etc.</p>\n\n<p>If you need the weight of the best/max values then you could first map your list of items to a list of pairs of the weight to the item. Pairs often get a bit tricky to read so you might even create a <code>WeightedValue</code> <code>data class</code> to improve readability:</p>\n\n<p>Examples:</p>\n\n<pre><code>val elements = listOf(\"hi\", \"hello\", \"\", \"world\")\n\nval bestElements = elements.maxElementsWith(compareBy(String::length))\nprintln(bestElements)\n// [hello, world]\n\nprintln(bestElements.random())\n// ${either hello or world}\n\nval newBestElements = bestElements.plus(\"supercalifragilisticexpialidocious\")\n .maxElementsWith(compareBy(String::length))\nprintln(newBestElements)\n// [supercalifragilisticexpialidocious]\n\nprintln(\n elements.map { it.length to it }\n .maxElementsWith(compareBy { it.first })\n .first()\n .first\n)\n// 5\n\ndata class WeightedValue&lt;out T, out W&gt;(val weight: W, val value: T)\n\nfun &lt;T, W&gt; Iterable&lt;T&gt;.withWeight(weigher: (T) -&gt; W): List&lt;WeightedValue&lt;T, W&gt;&gt; {\n return map { WeightedValue(weigher(it), it) }\n}\n\nprintln(\n elements.withWeight { it.length.toDouble() }\n .maxElementsWith(compareBy { it.weight })\n .first()\n .weight\n)\n// 5.0\n</code></pre>\n\n<p><a href=\"https://pl.kotl.in/N9D29SNCp\" rel=\"nofollow noreferrer\">Kotlin Playground Link</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-31T14:42:05.293", "Id": "231607", "ParentId": "230922", "Score": "2" } }, { "body": "<p>What I see here is either:</p>\n\n<ul>\n<li>Trying to sort list based on a value and getting item (or items) from top of the list. In that case you can use comparator and take stuff from top of that list. I don't see argument in being able to access actual \"value\". I see it as adding more responsibilities to the class.</li>\n<li>Trying to filter out and cache some results. In that case I see this as sequence of objects (similar to for example Rx programming) and in that case a simple .filter {} lambda would be enough for me while providing me with more flexibility with how to filter, aggregate data and what to do with them after.</li>\n</ul>\n\n<p>Overall I don't find this class useful unless for something very specific.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T14:56:38.917", "Id": "456882", "Score": "0", "body": "Sorting a list and then get one item from that list is a O(n log n) operation, while looping through the list once to get the highest value(s) is a O(n) operation and therefore much more effective. I don't see how this class is related to filtering out and caching results - to do that filtering I would have to loop through the list twice, once to find the maximum value and then once to do the filtering. This class only loops once." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T16:35:50.850", "Id": "456902", "Score": "0", "body": "I am talking about semantic value and that's what I semantically see there. We can also talk about effectivity and yes sorting big list would be ineffective. To filter stuff above some threshold (that's what I understand you are doing) you need only one loop, which can work for both cases and speed up them significantly. If you want to focus about efficiency, please specify that ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T19:04:16.500", "Id": "456922", "Score": "0", "body": "An example I gave in the question is the Alpha-Beta pruning algorithm, which while not necessarily creates a big list it takes a lot of time for each element to calculate the value, so I'd really like to avoid looping over the list any more than once. I am filtering stuff based on *the biggest value found so far*, not based on any pre-known fixed value, therefore a regular `.filter` wouldn't work unless you accept side-effects from the call to `.filter`, which IMO is bad practice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T03:32:54.067", "Id": "456975", "Score": "0", "body": "I understand what you mean. I wasn't talking literally only about `filter` (should have phrased better), but also about other lambdas. You could still implement that using `filter` and nested lambda without side effects, but that would be a bit clunky and weird way of using it. This sounds more like `maxBy` as was mentioned earlier already by mfulton26." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T15:47:34.057", "Id": "457079", "Score": "0", "body": "Exactly, this is `maxBy` with the difference that I also want the possibility of returning a collection of *all* the max's and not just one. mfulton26's suggestion of using an extension function is what I will go with. Thank you for your feedback :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T16:28:02.873", "Id": "457095", "Score": "0", "body": "You are welcome, thank you for discussion!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T07:49:23.990", "Id": "233663", "ParentId": "230922", "Score": "1" } } ]
{ "AcceptedAnswerId": "231607", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-17T19:17:27.090", "Id": "230922", "Score": "12", "Tags": [ "kotlin" ], "Title": "The Best™ class" }
230922
<p>I have created a function that will remove outliers from a series of data. Generally the data n dimensional. Loosely, an outlier is considered an outlier if it +/- deviates by 1.5 standard_deviation's from the mean (see code for more detailed explanation of what constitutes an outlier). </p> <p>The function can handle N dimensional arrays. It uses numpy and my code admittedly does not utilise numpy's iteration techniques. So I would appreciate how to improve this code and utilise numpy more.</p> <pre><code>import cv2 import numpy as np def remove_outliers(data, thresh=1.5, axis=(0,1), use_median=False): # Post: Remove outlier values from data. A value in data is considered an outlier if it is NOT mean-std_deviation*thresh &lt; value &lt; mean+std_deviation*thresh res = [] median = np.median(data, axis) mean, std_dev = cv2.meanStdDev(data) measure = median if use_median else mean lower_thresh = np.subtract(measure, np.multiply(std_dev, thresh)) upper_thresh = np.add(measure, np.multiply(std_dev, thresh)) # Handle arrays that are n dimensional if len(data.shape) == 3: data = data.reshape((int(data.size/3), 3)) for v in data: if np.all(v &gt; lower_thresh) and np.all(v &lt; upper_thresh): res.append(v) return res if __name__ == "__main__": arr = np.array([10,99,12,15,9,2,17,15]) print(arr) print(remove_outliers(arr, axis=0, thresh=1.5)) arr = np.array([[(0,10,3),(99,255,255),(100,10,9),(45,34,9)]], dtype='uint8') print(arr) print(remove_outliers(arr, thresh=1.5)) </code></pre>
[]
[ { "body": "<h1>Try to make the input and output types the same</h1>\n\n<p>In your example, <code>remove_outliers()</code> takes a NumPy array as input, but returns a regular Python list. It would be nicer to have the function return a NumPy array in this case.</p>\n\n<h1>The <code>axis</code> parameter only works when using the median</h1>\n\n<p>Make sure that when you specify axes, that the resulting behaviour of the function is what you would expect. If, for some reason, the <code>axis</code> parameter could not work with means, then you should throw an error if the caller explicitly specified which axes to work on.</p>\n\n<h1>Don't calculate values you are not going to use</h1>\n\n<p>You calculate both the median and the mean, but only use one of them. This is inefficient, just write the code as:</p>\n\n<pre><code>if use_median:\n measure = np.median(data, axis)\nelse:\n mean, std_dev = cv2.meanStdDev(data)\n measure = mean\n</code></pre>\n\n<p>I know you always need the standard deviation, but see the next comment.</p>\n\n<h1>Avoid using CV2 for something as simple as calculating mean and standard deviation</h1>\n\n<p>NumPy has functions for calculating those things as well. By avoiding importing cv2, you reduce the amount of dependencies users would have to install. As a bonus, the NumPy functions for mean and standard deviation also take an axis parameter. So consider writing:</p>\n\n<pre><code>std_dev = np.std(data, axis)\n\nif use_median:\n measure = np.median(data, axis)\nelse:\n measure = np.mean(data, axis)\n</code></pre>\n\n<h1>Don't special-case 3-dimensional data</h1>\n\n<p>Why are you reshaping the input array only if <code>len(data.shape) == 3</code>? Your should aim to make your code work generically with arrays of any number of dimensions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T13:13:23.450", "Id": "230955", "ParentId": "230928", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T00:17:00.570", "Id": "230928", "Score": "1", "Tags": [ "python", "numpy", "statistics" ], "Title": "Remove outliers from N dimensional data" }
230928
<p>After my <a href="https://codereview.stackexchange.com/a/230779/203349noredirect=1#comment449827_230728">previous code review</a>, I'm sharing my new code, and asking for better ways (which always exist) to improve the code, even with new libraries. The only thing that important to me, is the way of receiving the parameters have to be the command line [I am using Linux OS, so it's highly common to use command line params].</p> <p><strong>Project hierarchy:</strong></p> <pre><code>+src // All project's code | | --+ cmd // Command Line options parse &amp; process | | | | --- cmd_options_basic_data // Inputs | | --- cmd_options_parser // User inputs parser | | --- cmd_options_processor // Inputs processor | | --- cmd_options_progress_data // Extra data from basic inputs | | | | --+ core // Project core algorithms | | | | --- activity_analyzer // Main project's target - analyze a logger file | | --- anomalies_detector // Detect anomalies in logger | | --- log_handler // Call activity_analyzer / anomalies_detector as needed by user's input | | | | --+ useful_collections | | | | --- day // Single day class | | --- week // Days collection | | --- time_container // Analyzer single time container (e.g. Day total time / Week total time / Weekend percents). | | | | --+ utilities // Libraries extensions &amp; Exceptions | | | | --- boost_extensions | | --- std_extensions | | --- design_text // Self made library to color text | | --- exceptions // Relevant exceptions in project | | | | --- main | </code></pre> <hr> <h2>References</h2> <ul> <li><a href="https://codereview.stackexchange.com/a/230779/203349noredirect=1#comment449827_230728">Last Review</a></li> <li>The project in <a href="https://github.com/korelkashri/ComputerActivityLogReading" rel="nofollow noreferrer">GitHub</a>.</li> <li><a href="https://github.com/korelkashri/ComputerActivityLogReading/tree/0c65b8a04dd1151156a65d9cb908c8ae10ec5441" rel="nofollow noreferrer">Current project revision</a>.</li> </ul> <hr> <h2>EDIT:</h2> <h3><i>Points for CR:</i></h3> <ul> <li>Project hierarchy</li> <li>Recommended libraries that can make the code cleaner.</li> <li>Classes / Namespaces separation improvements.</li> <li>New C++17/2a features that can improve this code.</li> <li>Unclear code areas that requires more comments.</li> </ul> <hr> <h2>Selected code snippets</h2> <p><strong>main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;boost/filesystem.hpp&gt; #include &lt;boost/date_time.hpp&gt; #include "useful_collections/week.h" #include "core/log_handler.h" #include "utilities/design_text.h" #include "cmd/cmd_options_parser.h" #include "cmd/cmd_options_processor.h" #include "utilities/exceptions.h" int main(int ac, char* av[]) { cmd_options_parser command_line_options(ac, av); cmd_options_basic_data cmd_basic_data = command_line_options.get_data(); cmd_options_processor cmd_processor(cmd_basic_data); cmd_options_progress_data cmd_progress_data; /// Process basic cmd params try { cmd_progress_data = cmd_processor.process_basic_cmd_data(); } catch (exceptions::HelpMessageProducedException &amp;) { return EXIT_SUCCESS; } catch (exceptions::FileNotFoundException &amp;file_not_found_e) { std::cerr &lt;&lt; file_not_found_e.what() &lt;&lt; std::endl; return EXIT_FAILURE; } catch (std::exception &amp;e) { std::cerr &lt;&lt; e.what() &lt;&lt; std::endl; return EXIT_FAILURE; } /// Log handler initialize log_handler log_analyzer( cmd_basic_data.analyze_verbose, cmd_basic_data.analyze_activity, cmd_basic_data.log_file_path, cmd_basic_data.anomaly_detection, cmd_basic_data.normal_login_word ); log_analyzer.config_analyzer_params(cmd_progress_data.week_start_day, cmd_basic_data.sleep_hours_per_day, cmd_basic_data.study_hours_in_week); /// Log handler process log_analyzer.process(); return EXIT_SUCCESS; } </code></pre> <p><strong>week.h</strong></p> <pre><code>#ifndef COMPUTERMONITORINGSTATISTICSPARSER_WEEK_H #define COMPUTERMONITORINGSTATISTICSPARSER_WEEK_H #include &lt;iostream&gt; #include "day.h" class week { public: /** * Ctor * * @brief Initialize days list */ explicit week(); /** * @brief Prints days list */ std::string get_textual_days_list() const; /** * @brief Get day object that represent the given day_name * * @param day_name - Day's full / short name. * * @note non-case sensitivity * * @throw DayNotFoundException - if given day not found in days_list. * * @return day object of the given string day */ day get_day(const std::string &amp;day_name) const; private: void initialize_days_list(); std::vector&lt;day&gt; days_list; }; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; cout, const week&amp; week_ref); #endif //COMPUTERMONITORINGSTATISTICSPARSER_WEEK_H </code></pre> <p><strong>week.cpp</strong></p> <pre><code>#include "week.h" #include "../utilities/exceptions.h" week::week() { initialize_days_list(); } std::string week::get_textual_days_list() const { std::stringstream ss; ss &lt;&lt; "Available days:\n"; ss &lt;&lt; "\tSun [Sunday]\n"; ss &lt;&lt; "\tMon [Monday]\n"; ss &lt;&lt; "\tTue [Tuesday]\n"; ss &lt;&lt; "\tWed [Wednesday]\n"; ss &lt;&lt; "\tThu [Thursday]\n"; ss &lt;&lt; "\tFri [Friday]\n"; ss &lt;&lt; "\tSat [Saturday]" &lt;&lt; std::endl; return ss.str(); } day week::get_day(const std::string &amp;day_name) const { if (auto selected_day = std::find(days_list.begin(), days_list.end(), boost::to_lower_copy(day_name)); selected_day != days_list.end()) { // Selected day exists return *selected_day; } if (day_name == "help") { std::cout &lt;&lt; *this &lt;&lt; std::endl; throw exceptions::HelpMessageProducedException(); } throw exceptions::DayNotFoundException(); } void week::initialize_days_list() { days_list = { {"sunday", boost::date_time::weekdays::Sunday}, {"monday", boost::date_time::weekdays::Monday}, {"tuesday", boost::date_time::weekdays::Tuesday}, {"wednesday", boost::date_time::weekdays::Wednesday}, {"thursday", boost::date_time::weekdays::Thursday}, {"friday", boost::date_time::weekdays::Friday}, {"saturday", boost::date_time::weekdays::Saturday} }; } std::ostream&amp; operator&lt;&lt;(std::ostream&amp; cout, const week&amp; week_ref) { return cout &lt;&lt; week_ref.get_textual_days_list(); } </code></pre> <p><strong>cmd_options_parser.h &amp; cmd_options_parser.cpp</strong><br> Almost no changes from the last time. Previously called cmd_options.h/.cpp.</p> <p><strong>cmd_options_processor.h</strong></p> <pre><code>#ifndef COMPUTERMONITORINGSTATISTICSPARSER_CMD_OPTIONS_PROCESSOR_H #define COMPUTERMONITORINGSTATISTICSPARSER_CMD_OPTIONS_PROCESSOR_H #include &lt;iostream&gt; #include &lt;boost/date_time/date_defs.hpp&gt; #include "cmd_options_basic_data.h" #include "cmd_options_progress_data.h" class cmd_options_processor { public: /** * Ctor * * @brief initialize _options_data */ explicit cmd_options_processor(const cmd_options_basic_data &amp;options_data); /** * @brief Call basic params handlers * * @throw HelpMessageProducedException * @throw FileNotFoundException * @throw std::runtime_error - if unexpected error occurred */ [[nodiscard]] cmd_options_progress_data process_basic_cmd_data() const; private: /** * @brief --help / -h option handler * * @throw HelpMessageProducedException - if help flag was on */ void help_message_handler() const; /** * @brief --log-path / -l option handler * * @throw FileNotFoundException - if logger file not found */ void logger_path_handler() const; /** * @brief --week-start-day / -d option handler * * @throw HelpMessageProducedException - if day not found. * @throw std::runtime_error - if unexpected error occurred during the day search. * * @return week_start_day member value of cmd_options_progress_data */ [[nodiscard]] boost::date_time::weekdays week_start_day_handler() const; cmd_options_basic_data _options_data; }; #endif //COMPUTERMONITORINGSTATISTICSPARSER_CMD_OPTIONS_PROCESSOR_H </code></pre> <p><strong>cmd_options_processor.cpp</strong></p> <pre><code>#include "cmd_options_processor.h" #include "../utilities/exceptions.h" #include "../useful_collections/week.h" #include "../core/log_handler.h" #include &lt;boost/filesystem.hpp&gt; cmd_options_processor::cmd_options_processor(const cmd_options_basic_data &amp;options_data) : _options_data(options_data) { } cmd_options_progress_data cmd_options_processor::process_basic_cmd_data() const { try { cmd_options_progress_data extracted_data; help_message_handler(); logger_path_handler(); extracted_data.week_start_day = week_start_day_handler(); return extracted_data; } catch (...) { throw; } } void cmd_options_processor::help_message_handler() const { if (_options_data.help) { std::cout &lt;&lt; _options_data.visible_options &lt;&lt; "\n"; throw exceptions::HelpMessageProducedException(); } } void cmd_options_processor::logger_path_handler() const { if (!boost::filesystem::exists(_options_data.log_file_path)) { throw exceptions::FileNotFoundException(); } } boost::date_time::weekdays cmd_options_processor::week_start_day_handler() const { try { week w; return w.get_day(_options_data.week_start_day).day_symbol; } catch (exceptions::HelpMessageProducedException &amp;hd_e) { throw; } catch (exceptions::DayNotFoundException &amp;dnf_e) { std::cout &lt;&lt; "Unfamiliar day, for options list use '-d [ --week-start-day ] help'." &lt;&lt; std::endl; throw exceptions::HelpMessageProducedException(); } catch (std::exception &amp;e) { throw std::runtime_error("Unexpected error occurred during day searching."); } } </code></pre> <p><strong>log_handler.h</strong></p> <pre><code>#ifndef COMPUTERMONITORINGSTATISTICSPARSER_LOG_HANDLER_H #define COMPUTERMONITORINGSTATISTICSPARSER_LOG_HANDLER_H #include &lt;iostream&gt; #include &lt;boost/date_time.hpp&gt; #include "../useful_collections/time_container.h" #include "activity_analyzer.h" #include "anomalies_detector.h" class log_handler { public: log_handler(bool analyze_verbose, bool enable_analyze, const std::string &amp;log_path, bool anomalies_verbose, const std::string &amp;normal_login_word); void config_analyzer_params(boost::date_time::weekdays week_start_day, u_short sleep_hours_per_day, u_short study_day_hours_in_week); void process(); private: activity_analyzer analyzer; anomalies_detector detector; bool enable_analyze; }; #endif //COMPUTERMONITORINGSTATISTICSPARSER_LOG_HANDLER_H </code></pre> <p><strong>log_handler.cpp</strong></p> <pre><code>#include "log_handler.h" #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;algorithm&gt; #include &lt;iomanip&gt; #include &lt;chrono&gt; #include &lt;boost/date_time/gregorian/gregorian.hpp&gt; #include &lt;boost/date_time/posix_time/posix_time.hpp&gt; #include &lt;boost/algorithm/string.hpp&gt; #include &lt;boost/program_options.hpp&gt; #include "../utilities/std_extensions.h" #include "../utilities/boost_extensions.h" #include "../utilities/design_text.h" using namespace design_text; log_handler::log_handler(bool analyze_verbose, bool enable_analyze, const std::string &amp;log_path, bool anomalies_verbose, const std::string &amp;normal_login_word) : enable_analyze(enable_analyze), analyzer(analyze_verbose, log_path), detector(log_path, anomalies_verbose, normal_login_word) { } void log_handler::config_analyzer_params(boost::date_time::weekdays week_start_day, u_short sleep_hours_per_day, u_short study_day_hours_in_week) { analyzer.config_analyze_params(week_start_day, sleep_hours_per_day, study_day_hours_in_week); } void log_handler::process() { // Anomalies detector detector.detect(); if (enable_analyze) // Analyze logger times analyzer.analyze(); if (detector.is_error()) // Produce anomalies warning if needed std::cout &lt;&lt; "\n\n" &lt;&lt; design_text::make_colored(std::stringstream() &lt;&lt; "*** Anomaly detected! ***", design_text::Color::NONE, design_text::Color::RED, true) &lt;&lt; std::endl; } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T01:57:11.090", "Id": "230930", "Score": "2", "Tags": [ "c++", "boost" ], "Title": "program options from command line initialize [v3 - after CR]" }
230930
<p>Inspired by <a href="https://github.com/microsoft/GSL/blob/master/include/gsl/gsl_util#L95" rel="nofollow noreferrer">gsl::narrow_cast</a>, I created my own implementation with the addition of a couple of features:</p> <ul> <li>a static assert on the types to ensure the cast is actually narrowing (if future changes to the code mean the cast is no longer narrowing, we don't want to still have a <code>narrow_cast</code> there)</li> <li>the version without a runtime check still has an assert, so it's checked in debug mode</li> </ul> <pre class="lang-cpp prettyprint-override"><code>#include &lt;cassert&gt; #include &lt;exception&gt; #include &lt;iostream&gt; #include &lt;type_traits&gt; namespace details { template &lt;typename T, typename U&gt; constexpr bool is_same_signedness = std::is_signed&lt;T&gt;::value == std::is_signed&lt;U&gt;::value; template &lt;typename T, typename U&gt; constexpr bool can_fully_represent = std::is_same&lt;T, U&gt;::value || ( std::is_integral&lt;T&gt;::value &amp;&amp; std::is_integral&lt;U&gt;::value &amp;&amp; ( ( std::is_signed&lt;T&gt;::value &amp;&amp; sizeof(T) &gt; sizeof(U) ) || ( is_same_signedness&lt;T, U&gt; &amp;&amp; sizeof(T) &gt;= sizeof(U) ) ) ) || ( std::is_floating_point&lt;T&gt;::value &amp;&amp; std::is_floating_point&lt;U&gt;::value &amp;&amp; sizeof(T) &gt;= sizeof(U) ); template &lt;typename T, typename U&gt; constexpr bool static_cast_changes_value(U u) noexcept { const auto t = static_cast&lt;T&gt;(u); // this should catch most cases, but may miss dodgy unsigned to signed conversion or vice-versa if (static_cast&lt;U&gt;(t) != u) return true; if (std::is_signed&lt;T&gt;::value != std::is_signed&lt;U&gt;::value &amp;&amp; ((t &lt; T{}) != (u &lt; U{}))) return true; return false; } } // namespace details // TODO: unchecked cast for types where some loss of precision (and therefore assertion failure) is expected? template &lt;typename T, typename U&gt; constexpr T narrow_cast(U&amp;&amp; u) noexcept { static_assert(!details::can_fully_represent&lt;T, U&gt;, "we shouldn't be using narrow_cast for casts that aren't actually narrowing"); assert(!details::static_cast_changes_value&lt;T&gt;(u)); return static_cast&lt;T&gt;(std::forward&lt;U&gt;(u)); } struct narrowing_error : public std::exception {}; template &lt;typename T, typename U&gt; constexpr T narrow_cast_checked(U u) { static_assert(!details::can_fully_represent&lt;T, U&gt;, "we shouldn't be using narrow_cast for casts that aren't actually narrowing"); if (details::static_cast_changes_value&lt;T&gt;(u)) throw narrowing_error(); return static_cast&lt;T&gt;(u); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T09:24:56.190", "Id": "450105", "Score": "1", "body": "Do you really want to disallow non-narrowing uses of `narrow_cast<>()`? Consider that your `narrow_cast<>()` might be used in templates that want to allow safe narrowing of values, but might be instantiated with types such that it doesn't actually narrow. Then the use of that template will result in a compile-time error, unless it does something like `if constexpr (is_narrower<T, U>()) t = narrow_cast<T>(u); else t = u;`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T09:45:00.097", "Id": "450107", "Score": "0", "body": "I considered that case, but I would like to be able to remove as many narrow casts as possible by changing types so the casts are no longer necessary, so the compile-time error is very useful for that. Original I was just going to stick with `static_cast` for that situation, but now I'm thinking it might be useful to have a `maybe_narrow_cast` to retain the runtime assert." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T11:42:02.573", "Id": "450213", "Score": "0", "body": "Are you sure this code is intended to be C++11? You are using C++14 features." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T03:00:44.933", "Id": "450366", "Score": "0", "body": "@L.F. I was compiling with C++14, but when I went to post it I eyeballed it and thought that it was compatible with C++11, but didn't compile to check it. I'll change the tag." } ]
[ { "body": "<p>The first thing I noticed: you only support basic arithmetic types (integral and floating point). This isn't apparent from the name <code>narrow_cast</code>. Either enforce this with a static assert, or provide a mechanism to provide extensions for user defined types.</p>\n\n<p>Here's what you write:</p>\n\n<blockquote>\n<pre><code>template &lt;typename T, typename U&gt;\nconstexpr bool can_fully_represent =\n std::is_same&lt;T, U&gt;::value ||\n ( std::is_integral&lt;T&gt;::value &amp;&amp; std::is_integral&lt;U&gt;::value &amp;&amp;\n ( ( std::is_signed&lt;T&gt;::value &amp;&amp; sizeof(T) &gt; sizeof(U) ) ||\n ( is_same_signedness&lt;T, U&gt; &amp;&amp; sizeof(T) &gt;= sizeof(U) ) ) ) ||\n ( std::is_floating_point&lt;T&gt;::value &amp;&amp; std::is_floating_point&lt;U&gt;::value &amp;&amp; sizeof(T) &gt;= sizeof(U) );\n</code></pre>\n</blockquote>\n\n<p>Here's what I think should be sufficient:</p>\n\n<pre><code>template &lt;typename T, typename U&gt;\nconstexpr bool can_fully_represent =\n std::numeric_limits&lt;T&gt;::min() &lt;= std::numeric_limits&lt;U&gt;::min()\n &amp;&amp; std::numeric_limits&lt;T&gt;::max() &gt;= std::numeric_limits&lt;U&gt;::max();\n</code></pre>\n\n<p>OK, maybe I overlooked some edge cases, but that's the idea.</p>\n\n<p>The unchecked version uses a forwarding reference, whereas the check version does not. Try to keep the interface consistent.</p>\n\n<p><code>std::is_same&lt;T, U&gt;::value</code> can be simplified to <code>std::is_same_v&lt;T, U&gt;</code>. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T03:06:11.743", "Id": "450367", "Score": "0", "body": "Thanks for your comments. I agree with all of them, except that until I upgrade to C++17, I can't use the `_v` helpers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T09:24:56.220", "Id": "450409", "Score": "0", "body": "@JohnIlacqua Even if you can’t use _v, you can use is_same<T, U>{}." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T22:38:35.730", "Id": "450520", "Score": "0", "body": "I've used the braced syntax for type traits elsewhere in our codebase and gotten complaints from coworkers using MSVC that it doesn't compile. It'll accept `is_same<T, U>{}()` (it seems the implicit conversion to bool doesn't work for them?), but I think that's worse than `::value`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T11:42:45.200", "Id": "450574", "Score": "0", "body": "@JohnIlacqua OK, that sounds like a bug. You can ask a question on Stack Overflow to include the details. Don't forget to post a minimal reproducible example :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-25T03:33:10.403", "Id": "451006", "Score": "0", "body": "I decided to preempt the inevitable SO answer of \"looks like an MSVC bug, file a bug report', and just filed a bug report: https://developercommunity.visualstudio.com/content/problem/793780/msvc-sometimes-fails-to-implicitly-convert-type-tr.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T18:13:52.200", "Id": "532495", "Score": "0", "body": "@JohnIlacqua: Don't use that after you upgrade either - as you don't want to force C++17 on whoever uses your code." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T09:42:12.883", "Id": "231033", "ParentId": "230931", "Score": "4" } }, { "body": "<p>Another point in addition to @L.F.'s answer: You're defining an <code>is_same_signedness</code> value, but then - you're not using it within your <code>static_cast_changes_value()</code> function, although you could.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T20:55:25.013", "Id": "270652", "ParentId": "230931", "Score": "1" } } ]
{ "AcceptedAnswerId": "231033", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T02:54:54.900", "Id": "230931", "Score": "8", "Tags": [ "c++", "c++14", "casting" ], "Title": "An explicit cast for narrowing numeric conversions" }
230931
<p>This code reads binary file. Read data is converted into signed values and gets plotted if the user wants it.</p> <p><strong>Data looks as below:</strong></p> <p><code>00000000: 0800 01dc 0500 02a4 0000 88ff f918 a9ff ................ 00000010: fa53 88ff 3200 0161 2d00 029a 2e00 feff .S..2..a-....... 00000020: f933 f6ff fa14 efff ebff f9bf eaff fa0e .3.............. 00000030: eaff 2500 0132 1700 0232 1f00 eeff f9ef ..%..2...2...... 00000040: eeff fa73 e6ff f3ff f9a6 efff fa9c f5ff ...s............ 00000050: ecff f92c ebff fa69 eaff ffff 0188 0100 ...,...i........ 00000060: fabd f6ff 0500 01d6 0300 0211 0100 1400 ................ 00000070: 0177 1400 0205 1400 0f00 017b 0e00 02e5 .w.........{.... 00000080: 0400 ffff f949 ffff fab3 fbff 0000 01f9 .....I.......... 00000090: 0100 fa3f f3ff ffff f94c fcff fa2e f7ff ...?.....L...... 000000a0: 0200 01ad 0200 027a 0100 1b00 015c 1500 .......z.....\.. 000000b0: 026a 1400 1200 0183 0d00 02cf 0e00 1200 .j.............. 000000c0: 01f0 0a00 02c1 0d00 ffff f977 f9ff fa48 ...........w...H 000000d0: faff 1000 01eb 0400 02cb 0000 1400 0178 ...............x</code></p> <p><strong>Code:</strong> </p> <pre><code>import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation import struct from optparse import OptionParser from collections import OrderedDict import sys import binascii import time import math def twos_complement(hexstr, bits): value = int(hexstr,16) if value &amp; (1 &lt;&lt; (bits-1)): value -= 1 &lt;&lt; bits return value def reverse_digits(s): if len(s) != 4: print("wrong length passed %d!!"% (len(s))) return None return s[2:] + s[0:2] params_information = OrderedDict([("division", (5, 5)), ("fast_velocity", (30, -30)), ("test_velocity", (60, -60)), ("test_position", (22, -22)), ("another_test_velocity", (28, -28))]) class TESTParams(): def __init__(self, file_name): self.file_name = file_name self.all_params = {} self.param_size = 20 def get_param(self, param): return self.all_params[param] def plot_param(self, param): # Create a figure of size 8x6 inches, 80 dots per inch plt.figure(figsize=(8, 6), dpi=80) # Create a new subplot from a grid of 1x1 plt.subplot(1, 1, 1) plt.xlabel(str(param)) plt.ylabel("limits") x = np.linspace(params_information[param][0], params_information[param][1], num=len(self.all_params[param])) plt.plot(x, self.all_params[param]) plt.show() def get_all_params(self): """ gets division/fast/test/another_test velocity and position from file file format is binary and it has data in below format repeated till EOF struct __attribute__((__packed__)) test_data { uint16_t division; int16_t fast_velocity; int16_t test_velocity; int16_t test_position; int16_t another_test_velocity; }; Below code does converts raw characters read from file into signed 16 bit numbers before adding to the dictionary. """ with open(self.file_name) as file: data = file.read() hex_data = binascii.hexlify(data) for i in range(0, len(hex_data), self.param_size): test_data = hex_data[i:i+self.param_size] j = 0 division = 0 for param in params_information: if not param in self.all_params: self.all_params[param] = [] if param == "division": division = float(twos_complement(reverse_digits(test_data[j:j+4]), 16)) if division == 0: print("division is 0!!") return self.all_params[param].append(float(division)) else: self.all_params[param].append(float(twos_complement(reverse_digits(test_data[j:j+4]), 16)/division)) j += 4 def main(): parser = OptionParser(usage="usage: %prog [options] filename -p -v", version="%prog 1.0") parser.add_option("-f", "--file", dest='filename', help="file name to get test data from") parser.add_option("-p", "--print_all_params", default=False, dest='print_all_params', help="print all params division/fast/test/another_test velocities and position", action='store_true') parser.add_option("-o", "--plot_param", default=False, dest='plot_param', help="plot param, pass - division , fast_velocity, test_velocity , test_position another_test_velocity") (options, args) = parser.parse_args() if not options.filename: parser.error('Filename not given') p = TESTParams(options.filename) p.get_all_params() if options.verify and p.verify_all_params(): pass if options.print_all_params: for i, j, k, l, m in zip(p.get_param("division"), p.get_param("fast_velocity"), p.get_param("test_velocity"), p.get_param("test_position"), p.get_param("another_test_velocity")): print("division [%f] fast_velocity[%f] test_velocity[%f] test_position[%f] another_test_velocity[%f]"% (i, j, k, l, m)) if options.plot_param in params_information: p.plot_param(options.plot_param) if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T06:45:38.947", "Id": "450093", "Score": "1", "body": "How does the data file look? Could you include a small sample?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T15:44:58.577", "Id": "450172", "Score": "0", "body": "@Gloweye: done." } ]
[ { "body": "<h1>Error reporting</h1>\n\n<p>Errors in Python code are better represented by exceptions than by printing. Exceptions are also usually more sensible than returning special values, because the exception does not need to be checked manually. The interpreter will tell you quite clearly if you forgot to think about one ...</p>\n\n<p>So you might change your code from</p>\n\n<blockquote>\n<pre><code>print(\"wrong length passed %d!!\" % (len(s)))\nreturn None\n</code></pre>\n</blockquote>\n\n<p>to</p>\n\n<pre><code>raise ValueError(\"Wrong length passed! Found {} expected 4\".format(len(s))\n</code></pre>\n\n<p>Similarly, <code>raise ArithmeticError(\"Division by 0!\")</code> could be used in <code>get_all_params()</code>.</p>\n\n<h1>Interpreting binary data</h1>\n\n<p>Quick note: since you are working with binary data here, it won't hurt to explicitely tell Python to open the file in binary mode <code>with open(self.file_name, \"rb\") as file_:</code> (also note that I changed <code>file</code> to <code>file_</code> since <code>file</code> <a href=\"https://stackoverflow.com/a/22864250/5682996\">is/was a builtin in Python 2</a>).</p>\n\n<p>The current pipeline (bytes → hex → reverse hex → two's complement → int) is presumably more complicated than necessary. If you happen to be able to use Python 3, <a href=\"https://docs.python.org/3/library/stdtypes.html#int.from_bytes\" rel=\"nofollow noreferrer\"><code>int.from_bytes(...)</code></a> is IMHO the easiest option to integrate with your current code. <a href=\"https://docs.python.org/3/library/struct.html#struct.unpack\" rel=\"nofollow noreferrer\"><code>struct.unpack(...)</code></a> (also available in <a href=\"https://docs.python.org/2/library/struct.html#struct.unpack\" rel=\"nofollow noreferrer\">Python 2</a>) is maybe even better, since it can not just read one integer at a time, but the whole struct! Using something like <code>struct.unpack(\"&lt;Hhhhh, &lt;slice-binary-data-from-file-here)</code> (please verify byte-order before using!) could make a large chunk of your code obsolete. Both can handle different byte-orders and are also able to interpret the signed integers.</p>\n\n<h1>Command-line arguments</h1>\n\n<p><code>optparse</code> is deprecated/will not see updates in favor of <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a> both in Python 2 and in Python 3. Since <code>argparse</code> is based on <code>optparse</code>, they are very similar.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T21:32:18.240", "Id": "231062", "ParentId": "230937", "Score": "1" } } ]
{ "AcceptedAnswerId": "231062", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T04:53:43.477", "Id": "230937", "Score": "2", "Tags": [ "python", "matplotlib" ], "Title": "Binary file reading and plotting data" }
230937
<p>I wrote a Python script to format plain text to markdown title.</p> <p>for example, modify multiple lines</p> <pre><code>['1 Introduction\n', 'Part I: Applied Math and Machine Learning Basics\n', '2 Linear Algebra\n', '3 Probability and Information Theory\n', '10 Sequence Modeling: Recurrent and Recursive Nets\n', '11 Practical Methodology'] </code></pre> <p>to</p> <pre><code>['# chapter1: Introduction\n', 'Part I: Applied Math and Machine Learning Basics\n', '# chapter2: Linear Algebra\n', '# chapter3: Probability and Information Theory\n', '# chapter10: Sequence Modeling: Recurrent and Recursive Nets\n', '# chapter11: Practical Methodology'] </code></pre> <p>each chapter title in original file starts with only a number, modify them from 1 to "# chapter 1:", namely, insert "# chapter " before the number, append a colon ":" behind the number; finally write the new toc to a file.</p> <p>here is the code</p> <pre><code>import re # f_name = 'data_multi_lines_3.md' f_name = 'data_multi_lines.txt' with open(f_name) as f: line_list = f.readlines() res_list = [] for line in line_list: res_list.append(re.sub(r'^(\d{1,2})( +.*?)', r'# chapter\1:\2', line)) with open('your_file.md', 'w') as f: for item in res_list: f.write("%s" % item) </code></pre> <p>Is there a better approach to do this?</p> <p>I guess I should be concerned about the for loop although I have no idea how to improve that.</p>
[]
[ { "body": "<h1>iterator</h1>\n\n<p>There is no need for the intermediate list, just iterate over the text file line per line, and write the parsed line to the output file</p>\n\n<h1>variable name</h1>\n\n<p><code>f_name</code> those 3 characters will not make writing or executing the code any slower, but writing it in full can help you understand the code later one</p>\n\n<h1><code>re.compile</code></h1>\n\n<p>You can compile the regular expression</p>\n\n<p>For extra points, you can also name the groups:</p>\n\n<pre><code>re_pattern_chapter = re.compile(r\"^(?P&lt;chapter&gt;\\d{1,2})(?P&lt;text&gt; +.*?)\")\nre_pattern_out = r\"# chapter(?P=chapter):(?P=text)\"\n</code></pre>\n\n<hr>\n\n<pre><code>import re\n\nfile_name_in = \"data_multi_lines.txt\"\nfile_name_out = \"your_file.md\"\n\nre_pattern_chapter = re.compile(r\"^(?P&lt;chapter&gt;\\d{1,2})(?P&lt;text&gt; +.*?)\")\nre_pattern_out = r\"# chapter(?P=chapter):(?P=text)\"\n\nwith open(file_name_in, \"r\") as file_in, open(file_name_out, \"w\") as file_out:\n for line in file_name_in:\n line_parsed = re_pattern_chapter.sub(re_pattern_out, line)\n file_out.write(line_parsed)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T12:22:28.107", "Id": "230952", "ParentId": "230938", "Score": "2" } } ]
{ "AcceptedAnswerId": "230952", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T05:37:52.600", "Id": "230938", "Score": "3", "Tags": [ "python" ], "Title": "a Python script to format plain text to markdown title" }
230938
<p>i finally have been moved to PDO (from MySQLi) and i m now trying to make simple login and registration page (for training purposes).</p> <p>This code does work! But i want to know if it is secure?</p> <p>Also witch way is better for prepared statements to pass values with <code>?</code> or <code>:username</code>? Is the way i use PDO is simple or should i change something? </p> <pre><code>// Define variables and initialize with empty values $username = $password = $confirm_password = ""; $username_err = $password_err = $confirm_password_err = ""; // Processing form data when form is submitted if($_SERVER["REQUEST_METHOD"] == "POST"){ // Validate username if(empty(trim($_POST["username"]))){ $username_err = "Please enter a username."; } else{ // Prepare a select statement $sql = "SELECT id FROM users WHERE username = :username"; if($stmt = $pdo-&gt;prepare($sql)){ // Bind variables to the prepared statement as parameters $stmt-&gt;bindParam(":username", $param_username, PDO::PARAM_STR); // Set parameters $param_username = trim($_POST["username"]); // Attempt to execute the prepared statement if($stmt-&gt;execute()){ if($stmt-&gt;rowCount() == 1){ $username_err = "This username is already taken."; } else{ $username = trim($_POST["username"]); $email = trim($_POST["email"]); } } else{ echo "Oops! Something went wrong. Please try again later."; } } // Close statement unset($stmt); } // Validate password if(empty(trim($_POST["password"]))){ $password_err = "Please enter a password."; } elseif(strlen(trim($_POST["password"])) &lt; 6){ $password_err = "Password must have atleast 6 characters."; } else{ $password = trim($_POST["password"]); } // Validate confirm password if(empty(trim($_POST["confirm_password"]))){ $confirm_password_err = "Please confirm password."; } else{ $confirm_password = trim($_POST["confirm_password"]); if(empty($password_err) &amp;&amp; ($password != $confirm_password)){ $confirm_password_err = "Password did not match."; } } // Check input errors before inserting in database if(empty($username_err) &amp;&amp; empty($password_err) &amp;&amp; empty($confirm_password_err)){ // Prepare an insert statement $sql = "INSERT INTO users (username, email, password) VALUES (:username, :email, :password)"; if($stmt = $pdo-&gt;prepare($sql)){ // Bind variables to the prepared statement as parameters $stmt-&gt;bindParam(":username", $param_username, PDO::PARAM_STR); $stmt-&gt;bindParam(":email", $param_email, PDO::PARAM_STR); $stmt-&gt;bindParam(":password", $param_password, PDO::PARAM_STR); // Set parameters $param_username = $username; $param_email = $email; $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash // Attempt to execute the prepared statement if($stmt-&gt;execute()){ // Redirect to login page header("location: login"); die(); } else{ echo "Something went wrong. Please try again later."; } } // Close statement unset($stmt); } // Close connection unset($pdo); } </code></pre> <p>Thanks in advance!</p>
[]
[ { "body": "<p>I don't really like the kind of a review that is popular on this site which only states that your code has some problems but doesn't really offer any solution or improvement. </p>\n\n<p>Given for some problems listed it's really hard to find a plausible solution, I would prefer an answer where author at least tries to provide a solution, so it will be sort of a sanity check for the problem stated. </p>\n\n<p>Now to your code. It is pretty secure but not well coded. For me, the main problem here is the code repetition. For some reason each value is accessed and duplicated through many different variables. Why not to keep just one variable initialized at the top? </p>\n\n<p>Also, <code>empty()</code> is never needed when a variable is deliberately set. You can always use a variable itself for the purpose. </p>\n\n<p>The PDO code could be also improved, in two ways</p>\n\n<ul>\n<li>Positional placeholders are less verbose and there is no real use fro the named placeholder of only one variable is going to be used.</li>\n<li>Such a manual error handling (i.e. <code>if($stmt = $pdo-&gt;prepare($sql))</code>) is useless and harmful at the same time. An error message like \"Oops! Something went wrong.\" would help noone. Please read my exhaustive explanation on the <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"nofollow noreferrer\">PHP error reporting</a> for the details.</li>\n</ul>\n\n<p>So here is the <em>1st tier</em> refactoring, just to make your code tidy and meaningful:</p>\n\n<pre><code>&lt;?php\n// Processing form data when form is submitted\nif($_SERVER[\"REQUEST_METHOD\"] == \"POST\"){\n\n // why not to define a variable already with a value?\n $username = trim($_POST[\"username\"]);\n $email = trim($_POST[\"email\"]);\n $password = trim($_POST[\"password\"]);\n $confirm_password = trim($_POST[\"confirm_password\"]);\n\n // I would rather make errors an array than separate variables;\n $error = [];\n\n // Validate username\n if(!$username){\n $error['username'] = \"Please enter a username.\";\n } else{\n $sql = \"SELECT id FROM users WHERE username = ?\";\n $stmt = $pdo-&gt;prepare($sql);\n $stmt-&gt;execute([$username]);\n if($stmt-&gt;rowCount()){\n $error['username'] = \"This username is already taken.\";\n }\n }\n\n // Validate password\n if(!$password){\n $error['password'] = \"Please enter a password.\";\n } elseif(strlen($password) &lt; 6) {\n $error['password'] = \"Password must have at least 6 characters.\";\n }\n\n // Validate confirm password\n if(!$confirm_password){\n $error['confirm_password'] = \"Please enter confirm password.\";\n } elseif ($password != $confirm_password){\n $error['confirm_password'] = \"Password did not match.\";\n }\n\n // Check input errors before inserting in database\n if(!$error){\n $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash\n\n // Prepare an insert statement\n $sql = \"INSERT INTO users (username, email, password) VALUES (:username, :email, :password)\";\n\n $stmt = $pdo-&gt;prepare($sql);\n // Bind variables to the prepared statement as parameters\n $stmt-&gt;bindParam(\":username\", $username);\n $stmt-&gt;bindParam(\":email\", $email);\n $stmt-&gt;bindParam(\":password\", $param_password);\n\n $stmt-&gt;execute();\n header(\"location: login\");\n die;\n }\n}\n</code></pre>\n\n<p>Just keep in mind that refactoring is an endless process, you can improve any code. but better to do it gradually, in order for you to understand every change as opposed to adding some cargo cult code mindlessly. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T11:54:14.487", "Id": "450437", "Score": "0", "body": "To be honest, I was hoping for your answer! Thanks for explaining it in details and for this code update! I think Kiko answer also is good but will accept yours as it provides visual example. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T11:37:44.783", "Id": "231096", "ParentId": "230940", "Score": "2" } } ]
{ "AcceptedAnswerId": "231096", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T07:46:29.107", "Id": "230940", "Score": "2", "Tags": [ "php", "mysql", "pdo" ], "Title": "PDO Is this registration secure and well coded?" }
230940
<p>This is my Todo script. It's working well.</p> <p>I'm looking for feedback on what I've done well, and what I could have done better.</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>todos = { // It needs to store todos todos: [], // Settings settings: { quickDelete: false }, // Target container targetElement: document.getElementById("todos"), // Input txt box inputBox: document.getElementById("todo_input"), // Priority checkboxes - returns checked radio element priorityCheck: function() { var inputs = document.getElementsByTagName('INPUT'); var filtered; Array.prototype.forEach.call(inputs, function(input) { if (input.type === "radio" &amp;&amp; input.checked === true) { filtered = input; } }); return filtered; }, // Input button inputButton: document.getElementById("add_edit_button"), // Input label label: document.getElementById("add_edit_label"), // TOOLS // Grammar tools grammar: { fullStop: function(string) { if (string.slice(-1) === ".") { return string; } else { return string + "."; } }, capitalise: function(string) { var character = string.slice(0, 1); if (character === character.toUpperCase()) { return string; } else { return string.slice(0, 1).toUpperCase() + string.slice(1); } } }, // Create date string from date object formatDate: function(creationDate) { var lastDigit = creationDate.date.toString().split('').pop(); var days = ["sun", "mon", "tue", 'wed', "thurs", "fri", "sat"]; var months = ["jan", "feb", "march", "april", "may", "june", "july", "aug", "sep", "oct", "nov", "dec"]; var ordinalInd = ""; // Ordinal Indicator if (lastDigit == 1) { ordinalInd = "st"; } else if (lastDigit == 2) { ordinalInd = "nd"; } else if (lastDigit == 3) { ordinalInd = "rd" } else { ordinalInd = "th"; } return `${this.grammar.capitalise(days[creationDate.day])} ${creationDate.date + ordinalInd} ${this.grammar.capitalise(months[creationDate.month])} ${creationDate.year}` }, // It needs to create todos createTodo: function() { var createDate = new Date(); var textInput = this.inputBox; var grammared = ""; var priority = this.priorityCheck(); var lowCheck = document.getElementById('low'); var creationDate = { day: createDate.getDay(), date: createDate.getDate(), month: createDate.getMonth(), year: createDate.getFullYear() }; var pValues = { high: 2, medium: 1, low: 0 } if (textInput.value.length &gt; 0) { // Grammarfy grammared = this.grammar.fullStop(textInput.value); grammared = this.grammar.capitalise(grammared); this.todos.push({ todo: grammared, complete: false, creationDate: creationDate, priority: { pName: priority.value, pValue: pValues[priority.value] } }); textInput.value = ""; lowCheck.childNodes[0].checked = true; this.displayTodos(); } else { alert("Todo cannot be blank!") } }, // It needs to edit todos editTodo: function(todoIndex) { var replaceTxt = this.inputBox.value; var lowCheck = document.getElementById('low'); var pValues = { high: 2, medium: 1, low: 0 } // Grammerfy replaceTxt = this.grammar.fullStop(replaceTxt); replaceTxt = this.grammar.capitalise(replaceTxt); this.todos[todoIndex].todo = replaceTxt; this.todos[todoIndex].priority.pName = this.priorityCheck().value; this.todos[todoIndex].priority.pValue = pValues[this.priorityCheck().value]; this.displayTodos(); // Reset everything todos.inputBox.value = ""; todos.label.innerText = "Add Todo"; todos.inputButton.innerText = "Add"; todos.inputButton.setAttribute("onclick", "todos.createTodo()"); lowCheck.childNodes[0].checked = true; }, // It need to delete todos deleteTodo: function(todoIndex) { // check if quickdelete setting is true. if (this.settings.quickDelete) { this.todos.splice(todoIndex, 1); } else { var deleteIt = confirm("Are you sure you want to delete todo: '" + this.todos[todoIndex].todo + "'?"); if (deleteIt) { this.todos.splice(todoIndex, 1); } } this.displayTodos(); }, // Toggle complete todos toggleTodo: function(todoIndex) { if (this.todos[todoIndex].complete) { this.todos[todoIndex].complete = false; } else { this.todos[todoIndex].complete = true; } this.displayTodos(); }, // Mark all complete markAll: function() { this.todos.forEach(function(todo) { todo.complete = true; }); this.displayTodos(); }, // Delete all complete deleteComplete: function() { var incompleteTodos = []; this.todos.forEach(function(todo) { if (todo.complete === false) { incompleteTodos.push(todo); } }); this.todos = incompleteTodos; this.displayTodos(); }, // Delete all deleteAll: function() { if (this.settings.quickDelete) { this.todos = []; } else { var deleteAll = confirm("Are you sure you want to delete ALL todos?"); if (deleteAll) { this.todos = []; } } this.displayTodos(); }, // Store and retrieve todos locally localStore: function(todoArray) { // Store if (todoArray) { localStorage.setItem("todos", JSON.stringify(todoArray)); // Retrieve } else { return JSON.parse(localStorage.getItem("todos")); } }, // It needs to display todos displayTodos: function() { console.log("Display todos executed"); var todoList = this.targetElement; todoList.innerHTML = ""; // table header - if no todos don't show. if (this.todos.length &gt; 0) { todoList.innerHTML = "&lt;tr class='list_tr'&gt;&lt;th&gt;&lt;/th&gt;&lt;th&gt;Todo&lt;/th&gt;&lt;th&gt;Creation Date&lt;/th&gt;&lt;th&gt;Priority&lt;/th&gt;&lt;th&gt;Toggle Done&lt;/th&gt;&lt;th&gt;Delete&lt;/th&gt;&lt;th&gt;Edit&lt;/th&gt;&lt;/tr&gt;"; } else { return; } //console.log("before", this.todos); // Sort by priority this.todos.sort(function(a, b) { return b.priority.pValue - a.priority.pValue; }); //console.log("after", this.todos); this.todos.forEach(function(todo, index) { console.log("count:", index); var listTR = document.createElement('TR'); var numTD = document.createElement('TD'); var todoTD = document.createElement('TD'); var dateTD = document.createElement('TD'); var priorityTD = document.createElement('TD'); var completeTD = document.createElement('TD'); var delTD = document.createElement('TD'); var editTD = document.createElement('TD'); var numTxt = document.createTextNode(index + 1 + "."); var todoTxt = document.createTextNode(todo.todo); //date var dateTxt = ""; if (typeof todo.creationDate === "undefined") { dateTxt = "No Creation Date"; } else { dateTxt = todos.formatDate(todo.creationDate); } var completeTxt; if (todo.complete) { completeTxt = document.createTextNode("\u2714"); } else { completeTxt = document.createTextNode("X"); } var delTxt = document.createTextNode("Del"); var editTxt = document.createTextNode("Edit"); listTR.setAttribute("class", "list_tr"); listTR.append(numTD); listTR.append(todoTD); listTR.append(dateTD); listTR.append(priorityTD); listTR.append(completeTD); listTR.append(delTD); listTR.append(editTD); todoTD.setAttribute("class", "list_col list_tds"); if (todo.priority.pName === "high") { priorityTD.setAttribute("class", "high"); } else if (todo.priority.pName === "medium") { priorityTD.setAttribute("class", "medium"); } else { priorityTD.setAttribute("class", "low"); } dateTD.setAttribute("class", "creation_date"); completeTD.setAttribute("class", "complete_tds"); delTD.setAttribute("class", "del_col list_tds"); editTD.setAttribute("class", "edit_col list_tds"); numTD.append(numTxt); todoTD.append(todoTxt); dateTD.append(dateTxt); completeTD.append(completeTxt); delTD.append(delTxt); editTD.append(editTxt); todoList.append(listTR); }); }, // Event handlers handleEvents: function(targetElement, eventType) { targetElement.addEventListener(eventType, function(event) { var targetTxt = event.target.innerText; var targetIndex = event.target.parentNode.rowIndex - 1; var subButtonTxt = document.getElementById("add_edit_button"); // Toggle done if (targetTxt === "X" || targetTxt === "\u2714") { todos.toggleTodo(targetIndex); // Delete } else if (targetTxt === "Del") { todos.deleteTodo(targetIndex); // edit } else if (targetTxt === "Edit") { var makeChecked = document.getElementById(event.target.parentNode.childNodes[3].getAttribute("class")) makeChecked.childNodes[0].checked = true; todos.inputBox.value = event.target.parentNode.childNodes[1].innerText; todos.label.innerText = "Edit Todo"; todos.inputButton.innerText = "Save Edit"; todos.inputButton.setAttribute("onclick", "todos.editTodo(" + targetIndex + ")"); } else if (event.keyCode === 13 &amp;&amp; subButtonTxt.innerText === "Add") { todos.createTodo(); } else if (event.keyCode === 13 &amp;&amp; subButtonTxt.innerText === "Save Edit") { subButtonTxt.click(); } }); // window.addEventListener("load", function() { // console.log("LOAD event fired!"); // }); window.addEventListener("unload", function() { todos.localStore(todos.todos); }); } }; todos.handleEvents(todos.targetElement, "click"); todos.handleEvents(window, "keyup"); todos.todos = todos.localStore() || []; todos.displayTodos();</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body, html { font-family: verdana; color: #414141; background-color: darkgrey; } h1 { width: 450px; font-family: times; font-size: 1.8em; margin: 10px auto 20px auto; text-transform: uppercase; letter-spacing: 5px; color: lightgrey; border-bottom: 1px solid lightgrey; } h2 { width: 450px; font-family: times; font-size: 0.8em; text-align: center; margin: 10px auto 20px auto; text-transform: uppercase; letter-spacing: 5px; color: lightgrey; } button { border-radius: 5px; background-color: white; } .del_col { text-align: center; background-color: rgba(200, 0, 0, 0.3); cursor: pointer; } .edit_col { background-color: rgba(0, 200, 0, 0.3); cursor: pointer; } .list_col { text-align: left; background-color: lightGrey; min-width: 150px; } .list_tds { font-size: 0.8em; padding: 5px 10px 5px 10px; border-radius: 3px; } .complete_tds { text-align: center; background-color: white; cursor: pointer; border-radius: 3px; } .todo_box { width: 300px; padding: 20px; border-radius: 15px; background-color: #E1E1E1; } .high { background: #e20000; border-radius: 5%; } .medium { background: #ffc907; border-radius: 5%; } .low { background: #54bc00; border-radius: 5%; } .creation_date { text-align: center; font-size: 0.6em; } #todos th:nth-child(n+2) { font-size: 0.8em; font-weight: 400; color: white; background-color: darkgrey; border-radius: 3px 3px 0px 0px; padding: 5px 10px 5px 10px; } #add_edit_label { color: #414141; font-size: 0.8em; color: #A1A1A1; } #new_todos label { font-size: 1em; color: #A1A1A1; } #new_todos span { font-size: 0.8em; color: #A1A1A1; margin-right: 15px; } #todo_input { width: 300px; } #container { padding: 10px; margin: 100px 0px 100px 0px; width: 580px; margin: auto; background-color: #F1F1F1; border-radius: 20px; border: 1px solid grey; } #high { padding: 0 1px 0 0; border: 1px solid #AAA; display: inline; background: #e20000; border-radius: 5px; } #medium { padding: 0 1px 0 0; ; border: 1px solid #AAA; display: inline; background: #ffc907; border-radius: 5px; } #low { padding: 0 1px 0 0; ; border: 1px solid #AAA; display: inline; background: #54bc00; border-radius: 5px; } #new_todos { margin-left: 25px; } #quickTools li { padding-right: 25px; display: inline-block; } #quickTools ul { padding-left: 25px; list-style-type: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!doctype HTML&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Will's ToDos&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="./style.css"&gt; &lt;meta charset="utf-8"&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Will's Simple Todo's&lt;/h1&gt; &lt;h2&gt;This is my todo application, there are many like it, but this one is mine!&lt;/h2&gt; &lt;div id="container"&gt; &lt;div id="new_todos"&gt; &lt;label id="add_edit_label"&gt;Add Todo:&lt;/label&gt;&lt;br&gt; &lt;input id="todo_input" type="text"&gt;&lt;br&gt; &lt;label id="priority_label"&gt;Priority:&lt;/label&gt;&lt;br&gt; &lt;div id="high"&gt;&lt;input id="high" type="radio" name="priority" value="high"&gt;&lt;/div&gt;&lt;span&gt; High&lt;/span&gt; &lt;div id="medium"&gt;&lt;input id="medium" type="radio" name="priority" value="medium"&gt;&lt;/div&gt;&lt;span&gt; Medium&lt;/span&gt; &lt;div id="low"&gt;&lt;input id="low" type="radio" name="priority" value="low" checked&gt;&lt;/div&gt;&lt;span&gt; Low&lt;/span&gt; &lt;button id="add_edit_button" onclick="todos.createTodo()"&gt; Add&lt;/button&gt; &lt;/div&gt; &lt;br&gt; &lt;div id="todo_box"&gt; &lt;table&gt; &lt;tbody id="todos"&gt;&lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;div id="quickTools"&gt; &lt;ul&gt; &lt;li&gt;&lt;button onclick="todos.markAll()"&gt;Mark all as complete&lt;/button&gt;&lt;/li&gt; &lt;li&gt;&lt;button onclick="todos.deleteComplete()"&gt;Delete completed&lt;/button&gt;&lt;/li&gt; &lt;li&gt;&lt;button onclick="todos.deleteAll()"&gt;Delete all&lt;/button&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="./todos.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Here is the live code: <a href="https://willstodos.1mb.site/" rel="nofollow noreferrer">Will's Todos</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T11:29:33.610", "Id": "450122", "Score": "0", "body": "Greetings & Welcome! This question might get closed, because hitting 'Run code snippet' returns an error. Please fix the provided code so that it works without error, because we only review working code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T11:53:18.863", "Id": "450123", "Score": "0", "body": "Hello konijn. Thank you. I have added the HTML and CSS to make it work in code snippit. I don't know why it's throwing up a security error, but the script is working now. The working script with no error can be seen where it is hosted also. https://willstodos.1mb.site/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T11:54:54.343", "Id": "450124", "Score": "0", "body": "it's all good, I dont think it will get closed now." } ]
[ { "body": "<ul>\n<li>You are missing a number of semicolons (<code>ordinalInd = \"rd\"</code>)</li>\n<li><code>todos</code> is global (missing var/let/const)</li>\n<li>Having a variable called <code>todos</code> with a property called <code>todos</code> looks odd, perhaps call the top variable <code>app</code> or <code>widget</code>?</li>\n<li><p>Too many comments are superfluous like</p>\n\n<pre><code>// Settings\nsettings: {\n</code></pre>\n\n<p>or</p>\n\n<pre><code>// Input button\ninputButton: document.getElementById(\"add_edit_button\"),\n</code></pre></li>\n<li><code>(string.endsWith('.'))</code> is more readable than <code>(string.slice(-1) === \".\")</code></li>\n<li>Consider Spartan naming, <code>s</code> for string, <code>c</code> for char, <code>i</code> for integer</li>\n<li><p>Leverage the fact that <code>.complete</code> is a boolean</p>\n\n<pre><code>toggleTodo: function(todoIndex) {\n this.todos[todoIndex].complete = !this.todos[todoIndex].complete\n this.displayTodos();\n},\n</code></pre></li>\n<li>Consider <code>Array.filter</code> for <code>deleteComplete</code> </li>\n<li>Avoid <code>console.log</code> in production code</li>\n<li>I prefer to keep templates like <code>&lt;tr class='list_tr'&gt;&lt;th&gt;&lt;/th&gt;&lt;th&gt;Todo&lt;/th&gt;&lt;th&gt;Creation Date&lt;/th&gt;&lt;th&gt;Priority&lt;/th&gt;&lt;th&gt;Toggle Done&lt;/th&gt;&lt;th&gt;Delete&lt;/th&gt;&lt;th&gt;Edit&lt;/th&gt;&lt;/tr&gt;</code> outside of JavaScript, and hidden in the body</li>\n<li><p>Consider reading up on MVC to make the separation between data, view and controller cleaner</p></li>\n<li><p>Stick to one naming style in HTML (<code>new_todos</code> vs <code>quickTools</code>), I would stick to lowerCamelCase</p></li>\n<li><p>Don't wire your listeners in your HTML, wire them from within your JavaScript</p></li>\n</ul>\n\n<p>All in all, this code looks good. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T16:57:17.900", "Id": "450183", "Score": "2", "body": "Thank you for your excellent feedback Konijn. I really appreciate your taking the time to review my script and offer good advice. I will adopt all the points you have made, as they all make a lot of sense - I didn't even know about .endWith(), that's extremely useful! You are a credit to Stack Exchange." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T13:37:28.397", "Id": "230959", "ParentId": "230943", "Score": "2" } } ]
{ "AcceptedAnswerId": "230959", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T10:01:15.330", "Id": "230943", "Score": "3", "Tags": [ "javascript", "to-do-list" ], "Title": "Simple todo script" }
230943
<p>I made this small system that checks if you're old enough to drive. I'm new to C#, but I do know most of the basics since I also know Java. I'm trying to make my code more efficient. Any suggestions or help would be appreciated.</p> <pre><code>using System; using System.Threading; class EfficientCode { static int age = 0; static void Main(string[] args) { Console.WriteLine("This is just a simple project that takes simple and small information from you and uses it to process the information and checks whether you're allowed to drive or not. It also tells you how long is left till you drive."); Thread.Sleep(8000); // adds a 8 second delay so that the user could first read the introduction Start(); // after the 8 second delay it starts the system } static void Start() { Console.WriteLine("Enter your first name"); String firstName = Console.ReadLine(); Console.WriteLine("Enter your middle name"); String middleName = Console.ReadLine(); Console.WriteLine("Enter your last name"); String lastName = Console.ReadLine(); Console.WriteLine("Enter your age"); try { age = Convert.ToInt32(Console.ReadLine()); } catch { Console.WriteLine("ERROR: Input AGE must be a number!"); Console.WriteLine("Reinitializing questions."); Thread.Sleep(3000); // this adds a delay of 3 seconds Start(); // restarts the questions } if (ConfirmInformation(firstName, middleName, lastName, age)) { if (age &gt;= 18) { Console.WriteLine("Congratulations! You're already old enough to drive."); Environment.Exit(0); // Ends the system } else if (age == 17) { Console.WriteLine("You're almost there! You can get a learners permit.\nYou have 1 more year left to get an official drivers license!"); Environment.Exit(0); // Ends the system } else { Console.WriteLine("You'll get there. You're not old enough to have a license."); int yearsLeft = 18 - age; // gets the years left to drive Console.WriteLine("You still have " + yearsLeft + " years left to get a license."); Environment.Exit(0); // Ends the system } } else { Console.WriteLine("Reinitializing questions."); Thread.Sleep(3000); // this adds a delay of 3 seconds Start(); // restarts the questions } } static bool ConfirmInformation(String firstName, String middleName, String lastName, int age) { Console.WriteLine("======================================"); Console.WriteLine("INFORMATION CHECK:"); Console.WriteLine(""); Console.WriteLine("FIRST NAME: " + firstName); Console.WriteLine("MIDDLE NAME: " + middleName); Console.WriteLine("LAST NAME: " + lastName); Console.WriteLine("AGE: " + age); Console.WriteLine(""); Console.WriteLine("Are all those information correct? (Y/N)"); Console.WriteLine("======================================"); String booleanInput = Console.ReadLine(); if (booleanInput.Equals("yes", StringComparison.OrdinalIgnoreCase) || booleanInput.Equals("y", StringComparison.OrdinalIgnoreCase)) { return true; } else if (booleanInput.Equals("no", StringComparison.OrdinalIgnoreCase) || booleanInput.Equals("n", StringComparison.OrdinalIgnoreCase)) { return false; } else { Console.WriteLine("ERROR: Input must be either YES or NO."); return false; } return false; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T10:17:15.840", "Id": "450211", "Score": "9", "body": "Some comments regarding usability, not technical code quality: Inserting artificial delays, having the user re-enter all data when just one answer can be parsed, requesting a specific first-middle-last name format all contribute to a bad user experience. If the user can correct invalid data after the confirmation step, they should be able to keep already entered correct information." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T05:06:28.743", "Id": "450268", "Score": "4", "body": "[Falsehoods programmers believe about names with examples](https://shinesolutions.com/2018/01/08/falsehoods-programmers-believe-about-names-with-examples/)" } ]
[ { "body": "<p>First: you shouldn't use recursion to loop like that. It often ends up confusing and can technically lead to errors like <a href=\"https://stackoverflow.com/questions/26158/how-does-a-stack-overflow-occur-and-how-do-you-prevent-it\">stack overflows</a> if it goes on forever. If you need to loop, use a for loop or a while loop.</p>\n\n<p>Most of the code looks like it can be in main, I don't see a reason why start has to exist. Confirmation being separate is fine.</p>\n\n<p>You don't need to write out a try catch block for your age parsing. All the basic types in .NET have handy TryParse methods.</p>\n\n<pre><code>if (!int.TryParse(Console.ReadLine(), out int age))\n{\n /// ...\n}\n</code></pre>\n\n<p>You put a useless return false at the end of your confirmation code. As for the rest, there's a lot of ways we can handle a bunch of cases for your confirmation inputs cleanly. I think a switch is good in this case. A dictionary would also work.</p>\n\n<p><em>You could also just make the string lowercase then just check to see if the first character is y or n in your case, but we're just applying general practices.</em></p>\n\n<pre><code>string input = Console.ReadLine();\n\nswitch (input.ToLower()) // lowercase so it works\n{\n case \"yes\":\n case \"y\":\n return true;\n\n case \"no\":\n case \"n\":\n return false;\n\n default:\n // bad input code\n return false;\n}\n</code></pre>\n\n<p>You repeated Environment.Exit 3 times. Making the legal driving age a constant is a good idea. Just think, we could change it work for other countries!</p>\n\n<p>If the age isn't hardcoded, instead of checking for 17 or 18 you just check to see how many years they have left until they can drive.</p>\n\n<pre><code>const int LEGAL_DRIVING_AGE = 18; // declared somewhere, like the main class\n\nint yearsLeft = LEGAL_DRIVING_AGE - age;\n\nif (yearsLeft &lt;= 0)\n Console.WriteLine(\"You can drive!\");\n\nelse if (yearsLeft == 1)\n Console.WriteLine(\"You can get a learners permit...\");\n\nelse\n Console.WriteLine($\"You're not old enough yet. You still have {yearsLeft} years to go!\");\n\nEnvironment.Exit(0);\n</code></pre>\n\n<p>Hope that helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T14:54:22.163", "Id": "450162", "Score": "0", "body": "Thanks! I'll be using the switch way more now :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T06:06:11.290", "Id": "450270", "Score": "1", "body": "A real-world example of how this could lead to a stack overflow: A broom fell onto a keyboard, it was positioned so it held down the enter key on the number pad. (This was a networked program and caused considerable confusion in the factory for a few hours until the problem was identified as it was swallowing every task at the assembly station.)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T11:00:46.213", "Id": "230947", "ParentId": "230944", "Score": "12" } }, { "body": "<ul>\n<li><code>class EfficientCode</code> could be improved by naming the class by the purpose of the code. Otherwise your naming is good.</li>\n<li><code>static int age = 0;</code> should be a local variable in <code>Start()</code> </li>\n<li><code>Thread.Sleep(8000); // adds a 8 second delay so that the user could first read the introduction</code> shouldn't be needed because you aren't clearing the <code>Console</code> hence the user could still read it.</li>\n<li><p>Instead of <code>try..catch</code> you could take advantage of the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=netframework-4.8#System_Int32_TryParse_System_String_System_Int32__\" rel=\"nofollow noreferrer\"><code>int.TryParse()</code></a> method which returns a bool indicating the success of \"converting\" the string to an int. If you would use <code>int.TryParse</code> like below you could omit the restarting in case of an error. If the call succeeds <code>age</code> holds the integer.</p>\n\n<pre><code>while(!int.TryParse(Console.ReadLine(), out age))\n{\n Console.WriteLine(\"ERROR: The entered AGE must be a number!\");\n Console.WriteLine(\"Enter your age\");\n}\n</code></pre></li>\n<li><p><code>ConfirmInformation()</code> is doing a little bit to much. You should split it into 2 methods. One composing the output and one printing the output and asking for confirmation. </p>\n\n<pre><code>private static string ComposeOutput(String firstName, String middleName, String lastName, int age)\n{\n StringBuilder sb = new StringBuilder(100);\n sb.AppendLine(\"======================================\")\n .AppendLine(\"INFORMATION CHECK:\")\n .AppendLine()\n .AppendLine($\"FIRST NAME: {firstName}\")\n .AppendLine($\"MIDDLE NAME: {middleName}\")\n .AppendLine($\"LAST NAME: {lastName}\")\n .AppendLine($\"AGE: {age}\")\n .AppendLine()\n .AppendLine(\"Are all those information correct? (Y/N)\")\n .AppendLine(\"======================================\");\n\n return sb.ToString();\n} \n</code></pre>\n\n<p>This method uses the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder?view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>StringBuilder</code></a> class. The <code>AppendLine()</code> method is returning the <code>StringBuilder</code> itself hence we can use the method calls fluently. It uses <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated\" rel=\"nofollow noreferrer\"><code>$</code>-string interpolation</a> as well. </p>\n\n<p>The former <code>ConfirmInformation()</code> method could then look like so </p>\n\n<pre><code>private static bool ConfirmInformation(string information)\n{\n Console.Write(output);\n\n while (true)\n {\n string input = Console.ReadLine().ToLowerInvariant();\n if (input == \"y\" || input == \"yes\")\n {\n return true;\n }\n if (input == \"n\" || input == \"no\")\n {\n return false;\n }\n\n Console.WriteLine(\"ERROR: Input must be either YES or NO.\");\n Console.WriteLine();\n Console.Write(output);\n }\n}\n</code></pre>\n\n<p>I have made a <code>while(true)</code> loop here because your user wouldn't want to restart the whole process if they made a mistake.<br>\nAs a sidenode, the variable <code>String booleanInput = Console.ReadLine();</code> is misleading. If <strong>Sam the maintainer</strong> would read this method the purpose of that variable wouldn't be seen at first glance.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T12:52:56.003", "Id": "450135", "Score": "1", "body": "@OP `Int.tryParse()` is the way to go. Just want to add that when you do catch exceptions, you should always catch the specific Exceptions you're looking for. OP's current code will cause a confused user & endless loop if something else goes wrong with `ReadLine`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T14:52:34.720", "Id": "450160", "Score": "0", "body": "Thank you so much! This helped me alot. I have a question, when you did\n```CSharp\n .AppendLine($\"FIRST NAME: {firstName}\")\n .AppendLine($\"MIDDLE NAME: {middleName}\")\n .AppendLine($\"LAST NAME: {lastName}\")\n .AppendLine($\"AGE: {age}\")```\nwhat does the $ do before the string? Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T14:54:18.143", "Id": "450161", "Score": "1", "body": "Read below the code. I have added a link for explaination." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T14:55:32.037", "Id": "450163", "Score": "0", "body": "Ah yes I see it now, thanks again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T14:59:30.297", "Id": "450228", "Score": "2", "body": "I upvoted this but am surprised at some of your naming. It's odd for me to see a signature of `ConfirmInformation(string output)` where the input parameter is named output! I'd suggest renaming such \"Output\" something like \"UserPrompt\" or \"UserPromptMessage\". That would be method `ComposeUserPrompt` and `ConfirmInformation(string userPrompt)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T08:20:36.647", "Id": "450275", "Score": "0", "body": "@RickDavin agreed. Changed to `information`." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T11:16:29.967", "Id": "230948", "ParentId": "230944", "Score": "17" } }, { "body": "<p>Here is an overdone refactoring that I did. It just shows how the code could be modularized, but it is a bit too heavy-duty for a small example.</p>\n\n<pre><code>using System;\n\nnamespace OldEnoughToDrive\n{\n /// &lt;summary&gt;\n /// A container to hold attributes of a person\n /// &lt;/summary&gt;\n internal class Person\n {\n public const int LegalAge = 18;\n public string FirstName;\n public string MiddleName;\n public string LastName;\n public int Age;\n\n public override string ToString()\n {\n return $\"FIRST NAME: {FirstName}\\n\"\n + $\"MIDDLE NAME: {MiddleName}\\n\"\n + $\"LAST NAME: {LastName}\\n\"\n + $\"AGE: {Age}\";\n }\n public int GetYearsLeftToDrive()\n {\n return LegalAge - Age;\n }\n }\n\n internal class UserInput\n {\n /// &lt;summary&gt;\n /// Gets a string from the user\n /// &lt;/summary&gt;\n /// &lt;returns&gt;The user's input&lt;/returns&gt;\n public static string String(string prompt)\n {\n Console.WriteLine(prompt);\n return Console.ReadLine();\n }\n\n /// &lt;summary&gt;\n /// Gets a natural number from the user\n /// &lt;/summary&gt;\n /// &lt;param name=\"errorMsg\"&gt;Error message to show if the prompt is not a natural number&lt;/param&gt;\n /// &lt;returns&gt;A natural number from the user's input&lt;/returns&gt;\n public static int NaturalNumber(string prompt, string errorMsg)\n {\n Console.WriteLine(prompt);\n var userResponse = Console.ReadLine();\n int actualInt;\n while (!int.TryParse(userResponse, out actualInt) || actualInt &lt;= 0)\n {\n Console.WriteLine(errorMsg);\n userResponse = Console.ReadLine();\n }\n\n return actualInt;\n }\n\n /// &lt;summary&gt;\n /// Gets a boolean from the user\n /// &lt;/summary&gt;\n /// &lt;param name=\"errorMsg\"&gt;Error message to show if the input is not valid&lt;/param&gt;\n /// &lt;returns&gt;The boolean that the user entered&lt;/returns&gt;\n public static bool Boolean(string prompt, string errorMsg)\n {\n Console.WriteLine(prompt);\n while (true)\n {\n string input = Console.ReadLine()?.ToLower();\n switch (input)\n {\n case \"y\":\n case \"yes\":\n return true;\n case \"n\":\n case \"no\":\n return false;\n default:\n Console.WriteLine(errorMsg);\n break;\n }\n }\n }\n }\n\n internal class Program\n {\n private static void Main()\n {\n Console.WriteLine(\"This is just a simple project that takes simple and small information \" +\n \"from you and uses it to process the information and checks whether you're allowed to \" +\n \"drive or not. It also tells you how long is left till you drive.\");\n\n while (true)\n {\n var person = GetPersonInput();\n\n if (ConfirmInformation(person))\n {\n PrintLicenseStatus(person);\n }\n else\n {\n Console.WriteLine(\"Reinitializing questions.\");\n }\n }\n }\n\n /// &lt;summary&gt;\n /// Prints the status of the license for this person (what type of license they can hope\n /// for, or if they do not have one)\n /// &lt;/summary&gt;\n /// &lt;param name=\"person\"&gt;The person to check&lt;/param&gt;\n private static void PrintLicenseStatus(Person person)\n {\n if (person.Age &gt;= 18)\n {\n Console.WriteLine(\"Congratulations! You're already old enough to drive.\");\n }\n else if (person.Age == 17)\n {\n Console.WriteLine(\"You're almost there! You can get a learners permit.\");\n Console.WriteLine(\"You have 1 more year left to get an official drivers license!\");\n }\n else\n {\n Console.WriteLine(\"You'll get there. You're not old enough to have a license.\");\n Console.WriteLine($\"You still have {person.GetYearsLeftToDrive()} years left to \" +\n \"get a license.\");\n }\n }\n\n /// &lt;summary&gt;\n /// Builds a Person class via prompting the user for their personal information\n /// &lt;/summary&gt;\n /// &lt;returns&gt;A filled-in valid person object&lt;/returns&gt;\n private static Person GetPersonInput()\n {\n var firstName = UserInput.String(\"Enter your first name\");\n var middleName = UserInput.String(\"Enter your middle name\");\n var lastName = UserInput.String(\"Enter your last name\");\n var age = UserInput.NaturalNumber(\"Enter your age\", \"ERROR: Input AGE is invalid!\");\n return new Person\n {\n FirstName = firstName,\n MiddleName = middleName,\n LastName = lastName,\n Age = age\n };\n }\n\n /// &lt;summary&gt;\n /// Confirms the user's information by printing it to the screen\n /// &lt;/summary&gt;\n /// &lt;param name=\"person\"&gt;The person's information&lt;/param&gt;\n /// &lt;returns&gt;Whether the user has confirmed their information is valid&lt;/returns&gt;\n private static bool ConfirmInformation(Person person)\n {\n Console.WriteLine(\n new string('=', 38)\n + \"\\nINFORMATION CHECK:\\n\"\n + person\n + \"\\n\"\n + new string('=', 38)\n );\n\n return UserInput.Boolean(\"Are all those information correct? (Y/N)\",\n \"ERROR: Input must be either YES or NO.\");\n }\n }\n}\n</code></pre>\n\n<p>What I did was to refactor the app into a few components. The app is focused around getting a <code>Person</code>'s information from some <code>UserInput</code>, and those <code>UserInput</code>'s were validated and then the user's information was <code>Confirmed</code>. I took those concepts and extracted them into classes and methods.</p>\n\n<p>The validation methods were generalized to be used throughout the app if they need to be used again.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T01:57:16.533", "Id": "230981", "ParentId": "230944", "Score": "5" } } ]
{ "AcceptedAnswerId": "230948", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T10:08:44.953", "Id": "230944", "Score": "11", "Tags": [ "c#" ], "Title": "Simple code that checks if you're old enough to drive" }
230944
<p>I'm using the below code to call different methods from an API:</p> <pre><code>import requests import json from unidecode import unidecode from datetime import datetime temp_county = 'County' temp_locality = 'Locality' # Function - login session = requests.Session() def login(): # Application header header = { 'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': '{KEY}' } # User's credentials body_login = { 'username': 'user', 'password': 'pass' } # Make the login request and return the token request_url = session.post( 'https://urgentcargus.azure-api.net/api/LoginUser', json=body_login, headers=header) # Parse the token and remove double quotes token = 'Bearer ' + request_url.text.strip('"') return token # Get country code. Since it's a local product, the request will return only the code for RO def countries(): # Application header header = { 'Authorization': login(), 'Ocp-Apim-Subscription-Key': '{KEY}' } # Make the request and return the country code request_url = session.get( 'https://urgentcargus.azure-api.net/api/Countries', headers=header ) countries_dictionary = request_url.json() for country in countries_dictionary: if country['Abbreviation'] == 'RO': countryId = str(country['CountryId']) return countryId def counties(): # Application header header = { 'Authorization': login(), 'Ocp-Apim-Subscription-Key': '{KEY}' } # Load the country id params = { 'countryId': countries() } # Make the request and return the county code based on the city request_url = session.get( 'https://urgentcargus.azure-api.net/api/Counties', params=params, headers=header ) counties_dictionary = request_url.json() # Parse the city description and transliterate it to ASCII county = unidecode(temp_county) # print(county) # Return the county code for countyName in counties_dictionary: if countyName['Name'] == county: countyId = str(countyName['CountyId']) return countyId def localities(): # Application header header = { 'Authorization': login(), 'Ocp-Apim-Subscription-Key': '{KEY}' } # Load the country id and county id params = { 'countryId': countries(), 'countyId': counties() } # Make the request and return the county code based on the city request_url = session.get( 'https://urgentcargus.azure-api.net/api/Localities', params=params, headers=header, stream=True ) localities_dictionary = request_url.json() # Parse the city description and transliterate it to ASCII locality = unidecode(temp_locality) # print(county) # Return the locality code for localityName in localities_dictionary: if localityName['Name'] == locality: localityId = str(localityName['LocalityId']) return localityId # print(login()) print(countries()) print(counties()) print(localities()) </code></pre> <p>The functions are working well, with no errors or something. Problem is that it require (in my opinion) lot of time to complete all functions and return what it has to return.</p> <p>I have used <code>requests.Session()</code> in order to create one persistent session in order to save time but somehow is the same behavior.</p> <p>I've monitored how much time is required and for instance, it takes about 5 - 6 seconds to complete:</p> <pre><code>print('Process start! ' + str(datetime.now())) # here are all the functions print('Process ended! ' + str(datetime.now())) </code></pre> <p><strong>Terminal response:</strong></p> <pre class="lang-none prettyprint-override"><code>Process start! 2019-10-18 13:26:09.796132 Bearer 8JCAOoSSevSpcNDydLHSAmZORL0RGgDXV110IUhxIRWABX0TNj 1 26 163 Process ended! 2019-10-18 13:26:14.663092 </code></pre> <p>Is there any way to improve it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T10:49:32.587", "Id": "450114", "Score": "0", "body": "You are not using the variable session on your code, you are still using request. That should give you some improvement, also you should put the operations that you are making between the print statements so is clear what are you executing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T10:55:51.373", "Id": "450116", "Score": "0", "body": "@camp0 - the same functions as above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T10:59:33.090", "Id": "450117", "Score": "0", "body": "You are not using the variable session on your code, you should replace the requests.get and requests.post operations for session.get and session.post" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T11:01:32.937", "Id": "450118", "Score": "0", "body": "I've edited my code. Instead of `requests.get...` I've replace with `session.get...`. You meant like this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T12:38:52.513", "Id": "450133", "Score": "1", "body": "Yes with that change you will at least make just one TLS handshake for all your requests instead the 4, hope it helps" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T16:17:58.153", "Id": "450177", "Score": "0", "body": "@camp0, you could make an answer out of that comment. And still, the revised code calls login every time. Shouldn't the session be set up *once*, then reused?" } ]
[ { "body": "<p>You needlessly loop through the whole collection in all the methods, instead of returning as soon as you find what you need. If the thing you look for is right at the start, you still go thru all other entries.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for country in countries_dictionary:\n if country['Abbreviation'] == 'something':\n countryId = str(country['CountryId'])\nreturn countryId\n</code></pre>\n\n<p>Instead do:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for country in countries_dictionary:\n if country['Abbreviation'] == 'something':\n return str(country['CountryId'])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T17:25:04.303", "Id": "450185", "Score": "0", "body": "can you be more specific with my examples? If I just remove where I parse it, I get an error saying that `countryId` is not defined." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T18:25:21.200", "Id": "450187", "Score": "0", "body": "@cdrrr, I updated the code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T21:12:08.863", "Id": "450200", "Score": "2", "body": "First of all, you misquoted the code — the original code involved `country['Abbreviation']`. Secondly, you can get rid of the loop altogether: `return next(str(c['CountryId']) for c in countries_dictionary if c['Abbreviation'] == 'RO')`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T05:22:55.263", "Id": "450205", "Score": "0", "body": "Thanks 200_success, misquote fixed. I didn't want to change OPs code too much, just explain the concept of early return." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T16:13:21.967", "Id": "230969", "ParentId": "230946", "Score": "2" } }, { "body": "<p>Basically you need to reuse your session variable on the code, for example:</p>\n\n<pre><code>print(login(session))\nprint(countries(session))\nprint(counties(session))\nprint(localities(session))\n</code></pre>\n\n<p>And inside that functions change the calls that referrers to \"requests\" to the \"session\" variable like:</p>\n\n<pre><code>request_url = session.get(\n 'https://urgentcargus.azure-api.net/api/Localities',...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T16:23:25.530", "Id": "230970", "ParentId": "230946", "Score": "3" } } ]
{ "AcceptedAnswerId": "230969", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T10:44:59.477", "Id": "230946", "Score": "3", "Tags": [ "python", "performance", "python-3.x", "json", "api" ], "Title": "Fetching counties and localities using JSON API calls" }
230946
<p>I had to write code for a competition which calculates sum of the perimeter of three overlapping rectangles in a 2D space. rectangle A and rectangles B and rectangle c is overlapping each other.They have also one common point of interaction. i need to calculate the overlapping area of each rectangle. But there is one common overlapping area also exist, which is creating problem for me.</p> <p>Here is my code.</p> <pre> sample input 3 1 4 4 6 1 4 3 6 6 2 2 2 5 4 3 </pre> <pre><code>class Program { public static void Main() { FindPoints(); } static void FindPoints() { int T = int.Parse(Console.ReadLine()); int[,] arr = new int[T, 4]; int Counter = T; List&lt;int&gt; cost= new List&lt;int&gt;(); while (T-- &gt; 0) { string[] s = Console.ReadLine().Split(); int x1 = int.Parse(s[0]); int y1 = int.Parse(s[1]); int x2 = int.Parse(s[2]); int y2 = int.Parse(s[3]); int C = int.Parse(s[4]); cost.Add(C); for (int x = 0; x &lt;= T; x++) { for (int y = 0; y &lt;= 3; y++) { if (y == 0) arr[x, y] = x1; if (y == 1) arr[x, y] = y1; if (y == 2) arr[x, y] = x2; if (y == 3) arr[x, y] = y2; } } } if (Counter &gt; 1) { // A and B intersection int ABx5 = Math.Max(arr[2, 0], arr[1, 0]); int ABy5 = Math.Max(arr[2, 1], arr[1, 1]); int ABx6 = Math.Min(arr[2, 2], arr[1, 2]); int ABy6 = Math.Min(arr[2, 3], arr[1, 3]); // gives top-right point // of intersection rectangle A and B // no intersection if (ABx5 &gt; ABx6 || ABy5 &gt; ABy6) { Console.WriteLine("No intersection"); Console.ReadLine(); return; } // A and C intersection int ACx5 = Math.Max(arr[2, 0], arr[0, 0]); int ACy5 = Math.Max(arr[2, 1], arr[0, 1]); int ACx6 = Math.Min(arr[2, 2], arr[0, 2]); int ACy6 = Math.Min(arr[2, 3], arr[0, 3]); // no intersection if (ACx5 &gt; ACx6 || ACy5 &gt; ACy6) { Console.WriteLine("No intersection"); Console.ReadLine(); return; } // B and C intersection int BCx5 = Math.Max(arr[1, 0], arr[0, 0]); int BCy5 = Math.Max(arr[1, 1], arr[0, 1]); int BCx6 = Math.Min(arr[1, 2], arr[0, 2]); int BCy6 = Math.Min(arr[1, 3], arr[0, 3]); // no intersection if (BCx5 &gt; BCx6 || BCy5 &gt; BCy6) { Console.WriteLine("No intersection"); Console.ReadLine(); return; } // A and B and C intersection int ABCx5 = Math.Max(arr[2, 0], Math.Max(arr[1, 0], arr[0, 0])); int ABCy5 = Math.Max(arr[2, 1], Math.Max(arr[1, 1], arr[0, 1])); int ABCx6 = Math.Min(arr[2, 2], Math.Min(arr[1, 2], arr[0, 2])); int ABCy6 = Math.Min(arr[2, 3], Math.Min(arr[1, 3], arr[0, 3])); // gives top-right point // of intersection rectangle A and B and C // no intersection if (ABCx5 &gt; ABCx6 || ABCy5 &gt; ABCy6) { Console.WriteLine("No intersection"); Console.ReadLine(); return; } //Here point is a block distance between 4 to 6 block is 3 // than we need to add 1 if distance between two point is non zero int AB_1 = Math.Abs(ABx5 - ABy5 ); int AB_2 = Math.Abs(ABx6 - ABy6 ) ; //origin point id 0 int AB_Interection = AB_1 + AB_2 +1; int AC_1 = Math.Abs(ACx5 - ACy5 ) ; int AC_2 = Math.Abs(ACx6 - ACy6 ) ; //origin point id 0 int AC_Interection = AC_1 + AC_2+1; int BC_1 = Math.Abs(BCx5 - BCy5 ) + 1; int BC_2 = Math.Abs(BCx6 - BCy6 ) + 1; //origin point is not 0 means each point have one block...coutning will start from 0 // so we need to add 1 int BC_Interection = BC_1 + BC_2 ; int ABC_1 = Math.Abs(ABCx5 - ABCy5 ); int ABC_2 = Math.Abs(ABCx6 - ABCy6 ); // common interection point distance is 0 , means this is one block; // than we need to add 1 int ABC_CommonInterection = ABC_1 + ABC_2 + 1; int TotalInterectionWith_Area_A = (AB_Interection + AC_Interection)- ABC_CommonInterection; int Compensation_Money_A = TotalInterectionWith_Area_A * cost[0]; int TotalInterectionWith_Area_B = (AB_Interection + BC_Interection) - ABC_CommonInterection; int Compensation_Money_B = TotalInterectionWith_Area_B * cost[1]; int TotalInterectionWith_Area_C = (AC_Interection + BC_Interection) - ABC_CommonInterection; int Compensation_Money_C = TotalInterectionWith_Area_C * cost[2]; int Total_Compensation_Money = Compensation_Money_A + Compensation_Money_B + Compensation_Money_C; Console.WriteLine(Total_Compensation_Money); Console.ReadLine(); } } }` </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T12:22:15.150", "Id": "450127", "Score": "2", "body": "Welcome to Code Review! Does you code work as intended? If yes, please add some sample input and the resulting output to your question. If no, then your question is off-topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T12:29:28.793", "Id": "450128", "Score": "0", "body": "Yes my code is working fine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T12:34:02.950", "Id": "450129", "Score": "0", "body": "@Heslacher, I have added sample input. Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T12:34:33.830", "Id": "450130", "Score": "0", "body": "Great. What is the desired output ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T12:35:39.903", "Id": "450131", "Score": "0", "body": "@Heslacher, Output is : 35. My code is working for only one test case.I don't know the other test cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T12:47:07.450", "Id": "450134", "Score": "1", "body": "@Heslacher I have tested with may test cases. it is working fine. I don't know the website's test cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T14:12:02.473", "Id": "450154", "Score": "2", "body": "Please add a link to the website as well." } ]
[ { "body": "<h2>DRY Code</h2>\n<p>There is a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">Don't Repeat Yourself Principle</a> sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.</p>\n<p>This code repeats many times with minor variations:</p>\n<pre><code> int ABx5 = Math.Max(arr[2, 0], arr[1, 0]);\n int ABy5 = Math.Max(arr[2, 1], arr[1, 1]);\n\n\n int ABx6 = Math.Min(arr[2, 2], arr[1, 2]);\n int ABy6 = Math.Min(arr[2, 3], arr[1, 3]);\n</code></pre>\n<p>It might be better to create a function that performs this.</p>\n<h2>Complexity</h2>\n<p>The function <code>FindPoints()</code> is too complex (does too much). All software design methods include breaking the problem into smaller and smaller pieces until the problem is very easy to solve. Smaller functions are easier to read, write, debug and maintain.</p>\n<p>There is a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">Single Responsibility Principle</a> states:</p>\n<blockquote>\n<p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n<p>In addition to the possible function mentioned above in the DRY Code section, it might be better to add a function that only gets the input and creates the arrays, a function that finds the overlap of the rectangles and a function that calculates the area of each rectangle.</p>\n<h2>Variable Names</h2>\n<p>From the problem description, it is not clear why there are any variable names related to <code>money</code> or <code>compensation</code>, which means that the variables that refer to this are unclear. The variable name <code>T</code> may come from the original problem description on the website, but it isn't clear here either.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T14:40:51.110", "Id": "230962", "ParentId": "230951", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T12:18:05.987", "Id": "230951", "Score": "4", "Tags": [ "c#", "matrix" ], "Title": "overlapping rectangles c#" }
230951
<p>I'm working on a JSON to CSS converter in NodeJS, which takes a .json file and generates a .css file with its utility classes from it.</p> <p>.json example</p> <pre><code> } "breakpoints-map": { "default": "0", "sm": "only screen and (min-width: 508px)", "md": "only screen and (min-width: 768px)" }, "bg-repeat-map": { "bg-repeat": "repeat", "bg-repeat-y": "repeat-y", "bg-no-repeat": "no-repeat", "bg-repeat-x": "repeat-x" }, "bg-position-map": { "bg-pos-top": "top", "bg-pos-right-top": "top right", "bg-pos-right-center": "right", "bg-pos-right-bottom": "right bottom", "bg-pos-bottom": "bottom", "bg-pos-left-bottom": "left bottom", "bg-pos-left": "left", "bg-pos-left-top": "left top", "bg-pos-center": "center center" }, "bg-attachment-map": { "bg-att-scroll": "scroll", "bg-att-fixed": "fixed" }, "border-style-map": { "border-dotted": "dotted", "border-dashed": "dashed", "border-solid": "solid", "border-double": "double" } } </code></pre> <p>.js code</p> <pre><code> module.exports = (fileName) =&gt; { let cssWriter = fs.createWriteStream('style.css', { flags: 'a' }); fs.readFile(fileName, (error, data) =&gt; { if (error) { functions.logIt("The file cannot be found or is unreadable.", error); } else { try { const dataJson = JSON.parse(data); const breakpointMap = dataJson["breakpoints-map"] delete dataJson["breakpoints-map"]; Object.entries(breakpointMap).forEach(([breakpointKey, breakpointValue]) =&gt; { if (functions.isDefault(breakpointKey) == false) { cssWriter.write("@media " + breakpointValue + " {\n"); } Object.entries(dataJson).forEach(([mapKey, mapValues]) =&gt; { let breakpoint = (functions.isDefault(breakpointKey) == true ? "" : breakpointKey + "\\:"); let property = functions.getProperty(mapKey); Object.entries(mapValues).forEach(([classKey, classValue]) =&gt; { cssWriter.write("." + breakpoint + classKey + "{ " + property + ": " + classValue + "}\n"); }) }) if (functions.isDefault(breakpointKey) == false) { cssWriter.write("}\n"); } }) } catch (error) { functions.logIt("The file could not be parsed to JSON.", error); } } cssWriter.end(); }); }; </code></pre> <p>The <code>isDefault</code> function just checks whether the given parameter is equal to "default", in order to not put a media query around it.</p> <p>The <code>getProperty</code> function just links the right CSS property depending on the map name (width-map => width, bg-repeat-map => background-position).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T15:05:41.767", "Id": "450167", "Score": "0", "body": "Welcome to Code Review. Read the [tour] if you haven't." } ]
[ { "body": "<p>The main problem I see is that it's not obvious what the output is because there's too much auxiliary code that effectively obfuscates the logic.</p>\n\n<ul>\n<li>Offload some of the code into a function.</li>\n<li>Use template strings.</li>\n</ul>\n\n<p>If the data amount isn't in multi-megabyte range I would write a single string to improve readability:</p>\n\n<pre><code>const dataJson = JSON.parse(data);\nconst breakpointMap = dataJson['breakpoints-map'];\ndelete dataJson['breakpoints-map'];\n\nconst entryToCss = ([mapKey, mapValues], breakpoint) =&gt; {\n const property = functions.getProperty(mapKey);\n return Object.entries(mapValues)\n .map(([k, v]) =&gt; `.${breakpoint}${k}{ ${property}: ${v}}\\n`)\n .join('');\n};\n\ncssWriter.write(\n Object.entries(breakpointMap).map(([bpKey, bpVal]) =&gt; {\n const breakpoint = functions.isDefault(bpKey) ? `${bpKey}\\\\:` : '';\n return `${\n breakpoint ? `@media ${bpVal} {\\n` : ''\n }${\n Object.entries(dataJson)\n .map(entry =&gt; entryToCss(entry, breakpoint))\n .join('')\n }${\n breakpoint ? '}\\n' : ''\n }`;\n }).join('')\n);\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T08:34:21.410", "Id": "231030", "ParentId": "230956", "Score": "4" } } ]
{ "AcceptedAnswerId": "231030", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T13:17:00.893", "Id": "230956", "Score": "4", "Tags": [ "javascript", "parsing", "node.js", "json" ], "Title": "JSON to CSS in JavaScript" }
230956
<p>There is a need to have a specific structure of XML string when interacting with 3rd party system. Here are two examples:</p> <pre><code>&lt;DocumentElement&gt; &lt;Country&gt; &lt;CountryCode&gt;UA&lt;/CountryCode&gt; &lt;Name&gt;Ukraine&lt;/Name&gt; &lt;/Country&gt; &lt;/DocumentElement&gt; </code></pre> <p>and</p> <pre><code>&lt;DocumentElement&gt; &lt;Currency&gt; &lt;CurrencyCode&gt;UAH&lt;/CurrencyCode&gt; &lt;Description&gt;Hryvnia&lt;/Description&gt; &lt;/Currency&gt; &lt;/DocumentElement&gt; </code></pre> <p>Like you can see it is a common wrapping tag <code>DocumentElement</code>. So, here is <strong>approach #1</strong>:</p> <p>Have a wrapper class:</p> <pre class="lang-cs prettyprint-override"><code>[XmlRoot("DocumentElement")] public class DocumentElement&lt;T&gt; { public T InnerObject { get; set; } public DocumentElement(){} public DocumentElement(T some) { InnerObject = some; } } </code></pre> <p>And replace <code>InnerObject</code> after conversion:</p> <pre class="lang-cs prettyprint-override"><code>public static string GetXml&lt;T&gt;(T instance) where T : class { var wrapper = new DocumentElement&lt;T&gt;(instance); var writer = new StringWriter(); var serializer = new XmlSerializer(typeof(DocumentElement&lt;T&gt;)); serializer.Serialize(writer, wrapper); return writer.ToString().Replace("InnerObject", instance.GetType().Name); } </code></pre> <p>Or, <strong>approach #2</strong>:</p> <p>Throw away <code>DocumentElement</code> and just concat a needed string:</p> <pre><code>public static string GetXml&lt;T&gt;(T instance) where T : class { var writer = new StringWriter(); var serializer = new XmlSerializer(typeof(T)); serializer.Serialize(writer, instance); return "&lt;DocumentElement&gt;" + writer.ToString() + "&lt;/DocumentElement&gt;"; } </code></pre> <p>Both approaches produce a needed format but neither looks clean enough. Maybe, someone can suggest a better approach to this?</p>
[]
[ { "body": "<p>Take a look at <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/serialization/how-to-specify-an-alternate-element-name-for-an-xml-stream?view=netframework-4.8\" rel=\"nofollow noreferrer\">How to: Specify an Alternate Element Name for an XML Stream</a>. \nAlthough it is more code, I would use the mentioned <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlattributeoverrides\" rel=\"nofollow noreferrer\"><code>XmlAttributeOverrides</code></a> like so</p>\n\n<pre><code>public static string GetXml&lt;T&gt;(T instance, string sourceName = \"InnerObject\") where T : class\n{\n var wrapper = new DocumentElement&lt;T&gt;(instance);\n var writer = new StringWriter();\n var overrides = CreateOverrides(typeof(DocumentElement&lt;T&gt;), instance.GetType().Name, sourceName);\n\n var serializer = new XmlSerializer(typeof(DocumentElement&lt;T&gt;), overrides);\n serializer.Serialize(writer, wrapper);\n return writer.ToString();\n}\nprivate static XmlAttributeOverrides CreateOverrides(Type type, string destinationName, string sourceName)\n{\n var elementAttribute = new XmlElementAttribute() { ElementName = destinationName };\n var attributes = new XmlAttributes();\n attributes.XmlElements.Add(elementAttribute);\n var overrides = new XmlAttributeOverrides();\n overrides.Add(type, sourceName, attributes);\n return overrides;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T15:04:37.407", "Id": "230964", "ParentId": "230960", "Score": "1" } } ]
{ "AcceptedAnswerId": "230964", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T13:44:12.240", "Id": "230960", "Score": "0", "Tags": [ "c#", "xml", "generics" ], "Title": "Convert generic class into XML string of specific structure" }
230960
<p>I have a general question pertaining to a component from one of my apps. I have a function, <code>renderConditionals</code> that is at the core of my UI. It's incredibly sloppy looking and I am not even sure, from a conventional standpoint, that I am utilizing react correctly with regards to putting functions within the render function.</p> <p>Basically, I'd love someone to rip this apart and let me know if I'm on the right track or is this sloppy.</p> <pre><code>import React, { Component } from 'react'; import {format, addDays } from "date-fns"; import RouteModal from '../components/RouteModal' import Arrows from '../components/Arrows' import '../style/Calendar.css'; export default class Calendar extends Component { state = { fiveDayView: [new Date(), addDays(new Date(), 1), addDays(new Date(), 2), addDays(new Date(), 3), addDays(new Date(), 4)], routeId: '', show: false, colorZero: '', colorOne: '' } grabCityState = (str) =&gt; { if (str !== null) { for(let i = 0; i &lt; str.length; i++){ if (Number(str[i])){ return str.substr(0, str.indexOf(str[i])) } } } } increaseDays = (e) =&gt; { let operator; if (e.target.id === 'plus'){ operator = '+' } else{ operator = '-' } this.setState({ fiveDayView: [ addDays(this.state.fiveDayView[0], operator + 1), addDays(this.state.fiveDayView[1], operator + 1), addDays(this.state.fiveDayView[2], operator + 1), addDays(this.state.fiveDayView[3], operator + 1), addDays(this.state.fiveDayView[4], operator + 1) ], }) } pickupDeliveryMatchDate = () =&gt;{ let routeInfo = [] for(let i = 0; i &lt; this.props.apiData.length; i++){ for(let j = 0; j &lt; this.state.fiveDayView.length; j++) { if (format(this.state.fiveDayView[j], 'YYYY-MM-DD') === this.props.apiData[i].pickup_date) { routeInfo.push(this.props.apiData[i]) } } } return routeInfo } //Need to figure out how to bind this to the function below getRouteId = (e) =&gt; { this.setState({ routeId: e.target.className.split(" ")[1], show: true }) } hideModal = () =&gt; { this.setState({ show: false, routeId: '', }) } highlightLoad = (e) =&gt; { let classId = e.target.className let colorArr = document.getElementsByClassName(`${classId}`) this.setState({ colorZero: colorArr[0] ? colorArr[0].style.border : false, colorOne: colorArr[1] ? colorArr[1].style.border : false }) if (colorArr[0] &amp;&amp; colorArr[1]) { return [colorArr[0].style.border = 'solid blue 5px', colorArr[1].style.border= 'solid blue 5px'] } else if (colorArr[0]){ return colorArr[0].style.border = 'solid blue 5px' } else if (colorArr[1]){ return colorArr[1].style.border = 'solid blue 5px' } } removeHighlight = (e) =&gt; { let classId = e.target.className let colorArr = document.getElementsByClassName(`${classId}`) if (colorArr[0] &amp;&amp; colorArr[1]) { return [colorArr[0].style.border = this.state.colorZero, colorArr[1].style.border = this.state.colorOne] } else if (colorArr[0]){ return colorArr[0].style.border = this.state.colorZero } else if (colorArr[1]){ return colorArr[1].style.border = this.state.colorOne } } // set className to ID to do some testing... not a big deal but for learning! renderConditionals = (pickupDel, hazmat, sameday, id, delivery_id, delivery_location, j, color) =&gt; { if (pickupDel === false &amp;&amp; hazmat === true &amp;&amp; sameday === true) { return &lt;span key={j}&gt; &lt;div id="location" onKeyDown={this.getRouteId} key={j} onClick={this.getRouteId}&gt; &lt;p onMouseEnter={this.highlightLoad} onMouseLeave={this.removeHighlight} tabIndex="0" className={['load-clickables', id].join(" ")} style={{backgroundColor: color ? color : this.props.seededColorGenerator(id, delivery_id)}}&gt;{this.grabCityState(delivery_location)}&lt;i style={{color: '#252525'}} className="fas fa-radiation-alt"&gt;&lt;/i&gt;&lt;i style={{color: '#252525'}} className="fas fa-exclamation"&gt;&lt;/i&gt;&lt;/p&gt; &lt;/div&gt; &lt;/span&gt; } else if (pickupDel === true &amp;&amp; hazmat === true &amp;&amp; sameday === true) { return &lt;span key={j}&gt; &lt;div id="location" onKeyDown={this.getRouteId} key={j} onClick={this.getRouteId}&gt; &lt;p onMouseEnter={this.highlightLoad} onMouseLeave={this.removeHighlight} tabIndex="0" className={['load-clickables', id].join(" ")} style={{backgroundColor: '#252525', color: '#fdfd96', border: `solid 5px ${color ? color : this.props.seededColorGenerator(id, delivery_id)}`}}&gt;{this.grabCityState(delivery_location)}&lt;i style={{color: '#fdfd96'}} className="fas fa-radiation-alt"&gt;&lt;/i&gt;&lt;i style={{color: '#fdfd96'}} className="fas fa-exclamation"&gt;&lt;/i&gt;&lt;/p&gt; &lt;/div&gt; &lt;/span&gt; } else if (pickupDel === true &amp;&amp; hazmat === false &amp;&amp; sameday === true) { return &lt;span key={j}&gt; &lt;div id="location" onKeyDown={this.getRouteId} key={j} onClick={this.getRouteId}&gt; &lt;p onMouseEnter={this.highlightLoad} onMouseLeave={this.removeHighlight} tabIndex="0" className={['load-clickables', id].join(" ")} style={{backgroundColor: '#252525', color: '#fdfd96', border: `solid 5px ${color ? color : this.props.seededColorGenerator(id, delivery_id)}`}}&gt;{this.grabCityState(delivery_location)}&lt;i style={{color: '#fdfd96'}} className="fas fa-exclamation"&gt;&lt;/i&gt;&lt;/p&gt; &lt;/div&gt; &lt;/span&gt; } else if (pickupDel === true &amp;&amp; hazmat === true &amp;&amp; sameday === false) { return &lt;span key={j}&gt; &lt;div id="location" onKeyDown={this.getRouteId} key={j} onClick={this.getRouteId}&gt; &lt;p onMouseEnter={this.highlightLoad} onMouseLeave={this.removeHighlight} tabIndex="0" className={['load-clickables', id].join(" ")} style={{backgroundColor: '#252525', color: '#fdfd96', border: `solid 5px ${color ? color : this.props.seededColorGenerator(id, delivery_id)}`}}&gt;{this.grabCityState(delivery_location)}&lt;i style={{color: '#fdfd96'}} className="fas fa-radiation-alt"&gt;&lt;/i&gt;&lt;/p&gt; &lt;/div&gt; &lt;/span&gt; } else if (pickupDel === true &amp;&amp; hazmat === false &amp;&amp; sameday === false) { return &lt;span key={j}&gt; &lt;div id="location" onKeyDown={this.getRouteId} key={j} onClick={this.getRouteId}&gt; &lt;p onMouseEnter={this.highlightLoad} onMouseLeave={this.removeHighlight} tabIndex="0" className={['load-clickables', id].join(" ")} style={{backgroundColor: '#252525', color: '#fdfd96', border: `solid 5px ${color ? color : this.props.seededColorGenerator(id, delivery_id)}`}}&gt;{this.grabCityState(delivery_location)}&lt;/p&gt; &lt;/div&gt; &lt;/span&gt; } else if (pickupDel === false &amp;&amp; hazmat === false &amp;&amp; sameday === true) { return &lt;span key={j}&gt; &lt;div id="location" onKeyDown={this.getRouteId} key={j} onClick={this.getRouteId}&gt; &lt;p onMouseEnter={this.highlightLoad} onMouseLeave={this.removeHighlight} tabIndex="0" className={['load-clickables', id].join(" ")} style={{backgroundColor: color ? color : this.props.seededColorGenerator(id, delivery_id)}}&gt;{this.grabCityState(delivery_location)}&lt;i style={{color: '#252525'}} className="fas fa-exclamation"&gt;&lt;/i&gt;&lt;/p&gt; &lt;/div&gt; &lt;/span&gt; } else if (pickupDel === false &amp;&amp; hazmat === true &amp;&amp; sameday === false) { return &lt;span key={j}&gt; &lt;div id="location" onKeyDown={this.getRouteId} key={j} onClick={this.getRouteId}&gt; &lt;p onMouseEnter={this.highlightLoad} onMouseLeave={this.removeHighlight} tabIndex="0" className={['load-clickables', id].join(" ")} style={{backgroundColor: color ? color : this.props.seededColorGenerator(id, delivery_id)}}&gt;{this.grabCityState(delivery_location)}&lt;i style={{color: '#252525'}} className="fas fa-radiation-alt"&gt;&lt;/i&gt;&lt;/p&gt; &lt;/div&gt; &lt;/span&gt; } else{ return &lt;span key={j}&gt; &lt;div id="location" onKeyDown={this.getRouteId} key={j} onClick={this.getRouteId}&gt; &lt;p onMouseEnter={this.highlightLoad} onMouseLeave={this.removeHighlight} tabIndex="0" className={['load-clickables', id].join(" ")} style={{backgroundColor: color ? color : this.props.seededColorGenerator(id, delivery_id)}}&gt;{this.grabCityState(delivery_location)}&lt;/p&gt; &lt;/div&gt; &lt;/span&gt; } } render(){ console.log('hi') return( &lt;div className="calendar-container"&gt; &lt;Arrows {...this.props}{...this.state} grabCityState={this.grabCityState} getCustForm={this.props.getCustForm} getForm={this.props.getForm} increaseDays={this.increaseDays} decreaseDays={this.decreaseDays} /&gt; &lt;div className="routeInfo"&gt; {this.state.fiveDayView.map(function(days, i){ return &lt;div className="days" key={i}&gt; &lt;div&gt; &lt;div className='month'&gt; &lt;div id='day-title-one'&gt;&lt;h3&gt;{format(days, 'ddd')}&lt;/h3&gt;&lt;/div&gt; &lt;div id='day-title-two'&gt;&lt;p&gt;{format(days, 'D')}&lt;/p&gt;&lt;/div&gt; &lt;/div&gt; {this.pickupDeliveryMatchDate().map(function(day, j){ if (day.delivery_date === format(days, 'YYYY-MM-DD')){ return this.renderConditionals(day.local_delivery, day.hazmat, day.sameday, day.id, day.delivery_id, day.delivery_location, j, day.color) } else{ return null } }, this)} &lt;/div&gt; &lt;/div&gt; }, this)} &lt;/div&gt; &lt;div className="title"&gt;&amp;nbsp;&lt;/div&gt; &lt;div className="routeInfo"&gt; {this.state.fiveDayView.map(function(days, i){ return &lt;div className="days" key={i}&gt; &lt;div&gt; &lt;div className='month'&gt; &lt;div id='day-title-one'&gt;&lt;h3&gt;{format(days, 'ddd')}&lt;/h3&gt;&lt;/div&gt; &lt;div id='day-title-two'&gt;&lt;p&gt;{format(days, 'D')}&lt;/p&gt;&lt;/div&gt; &lt;/div&gt; {this.pickupDeliveryMatchDate().map(function(day, j){ // need to fgiure out how to tie in your new boolean values to display local cities as #252525 if (day.pickup_date === format(days, 'YYYY-MM-DD')){ return this.renderConditionals(day.local_pickup, day.hazmat, day.sameday, day.id, day.delivery_id, day.pickup_location, j, day.color) } else{ return null } }, this)} &lt;/div&gt; &lt;/div&gt; }, this)} &lt;/div&gt; &lt;br /&gt; &lt;br /&gt; &lt;RouteModal {...this.state} getForm={this.props.getForm} closeModal={this.hideModal} handleChange={this.props.handleChange} {...this.props} show={this.state.show} grabCityState={this.grabCityState} handleClose={this.hideModal} /&gt; &lt;/div&gt; ) } } <span class="math-container">````</span> </code></pre>
[]
[ { "body": "<p>Waaaay too much duplicate code</p>\n\n<p>For example, in your <code>renderConditionals</code> function</p>\n\n<pre><code>&lt;span key={j}&gt;\n &lt;div id=\"location\" onKeyDown={this.getRouteId} key={j} onClick={this.getRouteId}&gt;\n &lt;p onMouseEnter={this.highlightLoad} onMouseLeave={this.removeHighlight} tabIndex=\"0\" className={['load-clickables', id].join(\" \")} style={{backgroundColor: color ? color : this.props.seededColorGenerator(id, delivery_id)}}&gt;{this.grabCityState(delivery_location)}&lt;i style={{color: '#252525'}} className=\"fas fa-exclamation\"&gt;&lt;/i&gt;&lt;/p&gt;\n &lt;/div&gt;\n&lt;/span&gt;\n</code></pre>\n\n<p>is identical to</p>\n\n<pre><code>&lt;span key={j}&gt;\n &lt;div id=\"location\" onKeyDown={this.getRouteId} key={j} onClick={this.getRouteId}&gt;\n &lt;p onMouseEnter={this.highlightLoad} onMouseLeave={this.removeHighlight} tabIndex=\"0\" className={['load-clickables', id].join(\" \")} style={{backgroundColor: color ? color : this.props.seededColorGenerator(id, delivery_id)}}&gt;{this.grabCityState(delivery_location)}&lt;i style={{color: '#252525'}} className=\"fas fa-radiation-alt\"&gt;&lt;/i&gt;&lt;/p&gt;\n &lt;/div&gt;\n&lt;/span&gt;\n</code></pre>\n\n<p>Except for the class added to the icon. The easiest way to fix this is to break these items into their own component:</p>\n\n<pre><code>import React, { Component } from 'react';\n\nexport default class Location extends Component {\n\n render(){\n const { key, id, color, delivery_id, delivery_location, pickupDel, hazmat, sameday,\n handleOnKeyDown, handleOnClick, handleOnMouseEnter, handleonMouseLeave,\n grabCityState, seededColorGenerator\n } = this.props\n\n return(\n &lt;span key={key}&gt;\n &lt;div id=\"location\" onKeyDown={handleOnKeyDown} key={j} onClick={handleOnClick}&gt;\n &lt;p onMouseEnter={handleOnMouseEnter} onMouseLeave={handleonMouseLeave} \n tabIndex=\"0\" className={`load-clickables ${id}`} \n style={{backgroundColor: color ? color : seededColorGenerator(id, delivery_id)}}&gt;\n {grabCityState(delivery_location)}\n &lt;i style={{color: '#252525'}} className={`fas ${ hazmat &amp;&amp; 'fa-radiation-alt' } ${ sameday &amp;&amp; 'fa-exclamation'}`}&gt;&lt;/i&gt;\n &lt;/p&gt;\n &lt;/div&gt;\n &lt;/span&gt;\n )\n }\n\n}\n</code></pre>\n\n<p>I've thrown this location component together. It takes all the common stuff you use in every component, and receives more specific things as generic props. Then you import it into your main calendar component and pass it the props it needs.</p>\n\n<p>Now using it would look something like:</p>\n\n<pre><code>renderConditionals = (pickupDel, hazmat, sameday, id, delivery_id, delivery_location, j, color) =&gt; \n&lt;Location key={j} id={id} delivery_id={delivery_id} delivery_location={delivery_location} \n hazmat={hazmat} sameday={sameday} color={color} pickupDel={pickupDel} \n handleOnKeyDown={this.getRouteId} handleOnClick={this.getRouteId} handleMouseEnter={this.highlightLoad} handleMouseLeave={this.removeHighlight}\n grabCityState={this.grabCityState} seededColorGenerator={this.seededColorGenerator}\n/&gt;\n</code></pre>\n\n<p>Now you don't need a big if else statement full of copied code.\nKeep in mind I don't 100% understand what things are going on here, I didnt even read your functions, I'm just looking at how things are structured, which is where I think you are the most unfocused. The key takeaway is that if you ever have to copy and paste code in the same project, it can almost definitely be modualized and reused. It might make sense to move functions like <code>seededColorGenerator</code> and <code>grabCityState</code> into the location component if they are not used elsewhere, instead of passing them as props.</p>\n\n<p>Also, I noticed in your highlighting function, you are using document selectors to change the style of things: </p>\n\n<pre><code>let colorArr = document.getElementsByClassName(`${classId}`)`\n</code></pre>\n\n<p>We do not ever use document selectors, or directly query or modify the DOM directly in react. You should always be setting a components class by passing it's style props.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T20:35:32.910", "Id": "450196", "Score": "0", "body": "Thanks a ton! This is a great help and a good reminder to be more thoughtful about DRYing up my code. I'll implement this exactly and see how it goes. I appreciate you taking the time out of your day to dive in." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T19:18:15.863", "Id": "450496", "Score": "0", "body": "You definitely lead me to the right path but the problem is, and it's the main reason why my code was so ugly, is because of the logic I had to implement to have all the correct color options. One load may be hazmat, while the other is only sameday or vice versa. There are multiple color combinations I have to account for, so I brute forced it with if/else.\n\nUnfortunately, yours does not cover that aspect of renderConditionals()" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T15:09:00.747", "Id": "450595", "Score": "0", "body": "Yes, your requirements for styling seems pretty complicated, alot of logic is unavoidable. However moving location to it's own component is still the right thing to do. You should move the logic that determines it's colors and icon to the location component and calculate the logic there. That way you still avoid duplicating the spans, divs, common props etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T14:39:45.413", "Id": "450757", "Score": "0", "body": "I agree with you and I am 100% sticking with your implementation.\n\nBy the way, do you think this will noticeably help performance?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T15:43:03.087", "Id": "450775", "Score": "1", "body": "No probably not, it's mostly just for readability and maintanability. If you're having performance issues you're probably rendering too often." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T19:05:30.250", "Id": "230974", "ParentId": "230963", "Score": "1" } } ]
{ "AcceptedAnswerId": "230974", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T14:43:26.883", "Id": "230963", "Score": "3", "Tags": [ "javascript", "react.js" ], "Title": "Handling heavy conditional rendering in react" }
230963
<p>I have some code that I want to repeat in the best way possible. I'm looking for some advice to an approach. Function, object, other?</p> <p>Thanks!</p> <pre><code>// There are many #mad-1, #mad-2, #mad-3 etc // There are many radioButtons1Value, radioButtons2Value etc // There are many radio1subtract, radio2subtract etc let radio1subtract = null; let radioButtons1Value = null let radio2subtract = null; let radioButtons2Value = null if (document.querySelector('#mad-1')) { document.querySelector(`#mad-1 input`).addEventListener('click', (e) =&gt; { if(!document.querySelector('#basket-case').classList.contains('touched')) { extrasSetup(e); radioButtons1Value = parseInt(e.target.dataset.price); radio1subtract = radioButtons1Value; localExtrasCalc(staticPrice); parseAndUpdate(); } else if(e.target.classList.contains('radioClicked')) { radioButtons1Value = 0; noVatExtra = noVatExtra - radio1subtract; parseAndUpdate(); e.target.disabled = true; } }) } if (document.querySelector('#mad-2')) { document.querySelector(`#mad-2 input`).addEventListener('click', (e) =&gt; { if(!document.querySelector('#basket-case').classList.contains('touched')) { extrasSetup(e); radioButtons2Value = parseInt(e.target.dataset.price); radio2subtract = radioButtons2Value; localExtrasCalc(staticPrice); parseAndUpdate(); } else if(e.target.classList.contains('radioClicked')) { radioButtons2Value = 0; noVatExtra = noVatExtra - radio2subtract; parseAndUpdate(); e.target.disabled = true; } }) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T15:41:08.560", "Id": "450170", "Score": "1", "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.Meta.StackExchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T15:41:22.250", "Id": "450171", "Score": "0", "body": "This is off topic since your current solution does not work for all inputs. You should also post what the code is actually doing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T15:46:50.500", "Id": "450175", "Score": "1", "body": "Ok added in a better title and added in the extra code that I want there to be some kind of function for. Cheers!" } ]
[ { "body": "<p>You have some state you're maintaining, and you need a function that sets up callbacks to modify that state. </p>\n\n<p>So basically, just do that.</p>\n\n<p>You can probably do it better than I'm about to.</p>\n\n<pre><code>\nconst newState = () =&gt; {\n let _radioSubtract = null;\n let _radioButtonsValue = null;\n return {\n getRadioSubtract: () =&gt; { return _radioSubtract; },\n getRadioButtonsValue: () =&gt; { return _radioButtonsValue; },\n set: (radioSubtract, radioButtonsValue) =&gt; {\n _radioSubtract = radioSubtract;\n _radioButtonsValue = radioButtonsValue;\n },\n };\n}\n\nconst setHandler = (madID, state) =&gt; {\n const mad = document.querySelector(`#${madID}`)\n if (mad) {\n mad.addEventListener('click', (e) =&gt; {\n if(!document.querySelector('#basket-case').classList.contains('touched')) {\n extrasSetup(e);\n state.set(parseInt(e.target.dataset.price), parseInt(e.target.dataset.price));\n localExtrasCalc(staticPrice);\n parseAndUpdate();\n } else if(e.target.classList.contains('radioClicked')) {\n state.set(state.getRadioSubtract(), 0);\n noVatExtra = noVatExtra - state.getRadioSubtract();\n parseAndUpdate();\n e.target.disabled = true;\n }\n }); \n }\n}\n\nsetHandler('mad-1', newState());\nsetHandler('mad-2', newState());\n</code></pre>\n\n<p>I basically ignored everything in your code that I didn't understand or that you haven't talked about. Also I haven't tested this at all. You probably won't be able to use it as-is, but I think it's the pattern you're looking for.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T16:05:28.483", "Id": "230968", "ParentId": "230966", "Score": "0" } } ]
{ "AcceptedAnswerId": "230968", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T15:38:35.577", "Id": "230966", "Score": "-1", "Tags": [ "javascript" ], "Title": "Code reuse when generating dynamic variables" }
230966
<blockquote> <p>Roy is working on HackerEarth Profile. Right now he is working on User Statistics. One of the statistics data (Code Streak) is as follows:</p> <p>Given the User Activity Data, find the maximum number of continuous correct solutions submitted by any user. Seems easy eh? Here's the catch! In order to maximize this number a user could have submitted a correct answer to the same problem which he has already solved. Now such cases cannot be tolerated. (See test case for clarification). Also in all the continuous correct submissions multiple correct submissions to same problem should be counted only once.</p> <p>User Activity Data will be as follows: Total number of submissions by the user - N For each submission its Submission ID - S and Result - R (Solved or Unsolved) will be given. Solved is represented by integer 1 and Unsolved by 0.</p> <p>Input: First line contains integer T - number of test cases. T test cases follow. First line of each test case will contain N. Next N lines each will contain two space separated integers S and R.</p> <p>Ouput: For each test case output in a single line the required answer.</p> <p>Constraints: <br/> 1 &lt;= T &lt;= 1000<br/> 1 &lt;= N &lt;= 1000000 (10^6)<br/> 1 &lt;= S &lt;= 1000000 (10^6) <br/> 0 &lt;= R &lt;= 1 <br/></p> </blockquote> <pre><code>Sample Input 3 6 1 0 2 1 3 1 4 1 5 1 6 0 5 1 1 2 0 3 1 1 1 2 1 4 1 1 2 1 2 1 3 1 Sample Output 4 2 3 </code></pre> <p>Problem <a href="https://www.hackerearth.com/problem/algorithm/roy-and-code-streak/" rel="nofollow noreferrer">Link</a></p> <p>How to improve this code with more use of advance C++ features and to improve time complexity.</p> <pre><code>#include &lt;cstdio&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; int main() { unsigned int t, n, s, r; scanf("%d", &amp;t); while (t--) { unsigned int count = 0, max_count = 0; scanf("%d", &amp;n); std::vector&lt;bool&gt; status(1000000, false); for (unsigned int i = 0; i &lt; n; ++i) { scanf("%d%d", &amp;s, &amp;r); if (r == 1 &amp;&amp; status[s] == false) { count++; status[s] = true; } else if (r == 0) { count = 0; } max_count = std::max(count, max_count); } printf("%d\n", max_count); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T16:22:41.843", "Id": "450178", "Score": "2", "body": "I don't understand the use of `std::vector<bool> status(1000000, false);` in your solution at all. How does that help to solve the problem when defined within the `while` loop? Also hardcoding `1000000` elements looks not right for me. Did your code pass the test cases when submitted?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T03:59:41.653", "Id": "450203", "Score": "0", "body": "Yeah, my code submitted successfully for all test cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T12:53:31.780", "Id": "450218", "Score": "0", "body": "I looked at some of your other questions, you know the proper way to do input and output in C++, why are you using scanf and printf?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T16:15:56.587", "Id": "450236", "Score": "0", "body": "@pacmaninbw I have read on a codeforces blog that they are fast compared to `cin` and `cout`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T07:29:13.823", "Id": "450274", "Score": "0", "body": "Why do you go to competitive programming sites anyway if you want to actually write good C++ code? [Learning C++ from \"competitive programming\" is like learning English from a rap contest.](https://stackoverflow.com/users/560648/lightness-races-in-orbit)" } ]
[ { "body": "<p>Not sure what you mean by advanced c++ features, but you could use an <code>std::unordered_set</code> to store the submission id.</p>\n\n<pre><code>#include &lt;cstdio&gt;\n#include &lt;unordered_set&gt;\n#include &lt;algorithm&gt;\n\nint main() {\n unsigned int t, n, s, r;\n std::unordered_set&lt;int&gt; seen;\n\n scanf(\"%d\", &amp;t);\n while (t--) {\n unsigned int count = 0, max_count = 0;\n\n seen.clear();\n\n scanf(\"%d\", &amp;n);\n\n for (unsigned int i = 0; i &lt; n; ++i) {\n scanf(\"%d%d\", &amp;s, &amp;r);\n\n if (seen.count(s) == 0) {\n if (r == 1) {\n count++;\n }\n seen.insert(s);\n }\n if (r == 0) {\n count = 0\n }\n max_count = std::max(count, max_count);\n }\n printf(\"%d\\n\", max_count);\n }\n}\n</code></pre>\n\n<p>I'm not at a PC with a C++ compiler, so this hasn't been tested.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T07:20:57.007", "Id": "230984", "ParentId": "230967", "Score": "1" } }, { "body": "<p>Don't use <code>printf</code> and <code>scanf</code>. They are not faster, sometimes <em>slower</em>, and prone to undefined behavior. Use I/O streams instead. In fact, <strong>every single call to <code>printf</code> and <code>scanf</code> in your code is undefined behavior</strong> &mdash; you are consistently using <code>%d</code> to print <code>unsigned int</code>s.</p>\n\n<p>You can call</p>\n\n<pre><code>std::ios_base::sync_with_stdio(false);\n</code></pre>\n\n<p>before doing any I/O operation to turn off synchronization with <code>cstdio</code>, making the streams faster.</p>\n\n<blockquote>\n <p>@pacmaninbw I have read on a codeforces blog that they are fast\n compared to <code>cin</code> and <code>cout</code>. –\n <a href=\"https://codereview.stackexchange.com/users/130800/coder\">coder</a> <a href=\"https://codereview.stackexchange.com/questions/230967/hackerearth-challenge-roy-and-code-streak#comment450236_230967\">16\n hours\n ago</a></p>\n</blockquote>\n\n<p>Disregard it. \"Competitive programming style C++\" is a completely different language than the correct, proper C++. <a href=\"https://stackoverflow.com/users/560648/lightness-races-in-orbit\">Learning C++ from \"competitive programming\" is like learning English a rap contest.</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T08:34:10.393", "Id": "231029", "ParentId": "230967", "Score": "2" } } ]
{ "AcceptedAnswerId": "231029", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T16:04:55.200", "Id": "230967", "Score": "-1", "Tags": [ "c++", "programming-challenge" ], "Title": "Hackerearth challenge - Roy and Code Streak" }
230967
<h3>Problem</h3> <p>Write a method to return a boolean if an input grid is magic square.</p> <hr> <p>A magic square is a <span class="math-container">\$NxN\$</span> square grid (where N is the number of cells on each side) filled with distinct positive integers in the range <span class="math-container">\${1,2,...,n^{2}}\$</span> such that each cell contains a different integer and the sum of the integers in each row, column and diagonal is equal. The sum is called the magic constant or magic sum of the magic square. </p> <p><a href="https://i.stack.imgur.com/cmWko.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cmWko.png" alt="enter image description here"></a></p> <hr> <h3>Code</h3> <p>I've tried to solve the above problem. If you'd like to review the code and provide any change/improvement recommendations please do so, and I'd really appreciate that.</p> <pre><code>from typing import List import numpy as np def is_magic_square(grid: List[List[int]]) -&gt; bool: """Returns a boolean if an input grid is magic square""" try: grid_length = len(grid) magic_sum = float(grid_length * (grid_length ** 2 + 1) / 2) diag_positive, diag_negative = [], [] diag_count_positive = 0 diag_count_negative = grid_length - 1 col_grid = np.zeros(shape=(grid_length, grid_length)) unique_elements = set() for index_row, lists in enumerate(grid): diag_negative.append(lists[diag_count_negative]) diag_count_negative -= 1 if len(grid[index_row]) != grid_length: return False if sum(lists) != magic_sum: return False for index_col in range(grid_length): unique_elements.add(lists[index_col]) col_grid[index_col][index_row] = lists[index_col] if index_col == grid_length and index_row == grid_length - 1 and len(unique_elements) != grid_length ** 2 - 1: return False if index_row == grid_length - 1: sum_col = sum(col_grid) temp_col = np.array([magic_sum] * grid_length) if str(temp_col) != str(sum_col): return False if diag_count_positive == index_row: diag_positive.append(lists[index_row]) diag_count_positive += 1 if diag_count_positive == grid_length and sum(diag_positive) != magic_sum: return False if index_row == grid_length - 1 and sum(diag_negative) != magic_sum: return False except: return False return True if __name__ == '__main__': # ---------------------------- TEST --------------------------- DIVIDER_DASH_LINE = '-' * 50 GREEN_APPLE = '\U0001F34F' RED_APPLE = '\U0001F34E' magic_squares = [ [[4, 3, 8], [9, 5, 1], [2, 7, 6]], [[9, 3, 22, 16, 15], [2, 21, 20, 14, 8], [25, 19, 13, 7, 1], [18, 12, 6, 5, 24], [11, 10, 4, 23, 17]], [[60, 53, 44, 37, 4, 13, 20, 29], [3, 14, 19, 30, 59, 54, 43, 38], [58, 55, 42, 39, 2, 15, 18, 31], [1, 16, 17, 32, 57, 56, 41, 40], [61, 52, 45, 36, 5, 12, 21, 28], [6, 11, 22, 27, 62, 51, 46, 35], [63, 50, 47, 34, 7, 10, 23, 26], [8, 9, 24, 25, 64, 49, 48, 33]], [[35, 26, 17, 1, 62, 53, 44], [46, 37, 21, 12, 3, 64, 55], [57, 41, 32, 23, 14, 5, 66], [61, 52, 43, 34, 25, 16, 7], [2, 63, 54, 45, 36, 27, 11], [13, 4, 65, 56, 47, 31, 22], [24, 15, 6, 67, 51, 42, 33]], [[1, 35, 4, 33, 32, 6], [25, 11, 9, 28, 8, 30], [24, 14, 18, 16, 17, 22], [13, 23, 19, 21, 20, 15], [12, 26, 27, 10, 29, 7], [36, 2, 34, 3, 5, 31]], [[16, 14, 7, 30, 23], [24, 17, 10, 8, 31], [32, 25, 18, 11, 4], [5, 28, 26, 19, 12], [13, 6, 29, 22, 20]], [[1, 14, 4, 15], [8, 11, 5, 10], [13, 2, 16, 3], [12, 7, 9, 6]], [[8, 1, 6], [3, 5, 7], [4, 9, 2]] ] for magic_square in magic_squares: print(DIVIDER_DASH_LINE) if is_magic_square(magic_square) is True: print(f'{GREEN_APPLE} "{magic_square}" is a magic square.') else: print(f'{RED_APPLE} "{magic_square}" is not a magic square.') </code></pre> <h3>Output</h3> <pre><code>-------------------------------------------------- "[[4, 3, 8], [9, 5, 1], [2, 7, 6]]" is a magic square. -------------------------------------------------- "[[9, 3, 22, 16, 15], [2, 21, 20, 14, 8], [25, 19, 13, 7, 1], [18, 12, 6, 5, 24], [11, 10, 4, 23, 17]]" is a magic square. -------------------------------------------------- "[[60, 53, 44, 37, 4, 13, 20, 29], [3, 14, 19, 30, 59, 54, 43, 38], [58, 55, 42, 39, 2, 15, 18, 31], [1, 16, 17, 32, 57, 56, 41, 40], [61, 52, 45, 36, 5, 12, 21, 28], [6, 11, 22, 27, 62, 51, 46, 35], [63, 50, 47, 34, 7, 10, 23, 26], [8, 9, 24, 25, 64, 49, 48, 33]]" is a magic square. -------------------------------------------------- "[[35, 26, 17, 1, 62, 53, 44], [46, 37, 21, 12, 3, 64, 55], [57, 41, 32, 23, 14, 5, 66], [61, 52, 43, 34, 25, 16, 7], [2, 63, 54, 45, 36, 27, 11], [13, 4, 65, 56, 47, 31, 22], [24, 15, 6, 67, 51, 42, 33]]" is not a magic square. -------------------------------------------------- "[[1, 35, 4, 33, 32, 6], [25, 11, 9, 28, 8, 30], [24, 14, 18, 16, 17, 22], [13, 23, 19, 21, 20, 15], [12, 26, 27, 10, 29, 7], [36, 2, 34, 3, 5, 31]]" is a magic square. -------------------------------------------------- "[[16, 14, 7, 30, 23], [24, 17, 10, 8, 31], [32, 25, 18, 11, 4], [5, 28, 26, 19, 12], [13, 6, 29, 22, 20]]" is not a magic square. -------------------------------------------------- "[[1, 14, 4, 15], [8, 11, 5, 10], [13, 2, 16, 3], [12, 7, 9, 6]]" is a magic square. -------------------------------------------------- "[[8, 1, 6], [3, 5, 7], [4, 9, 2]]" is a magic square. </code></pre> <h3>Source</h3> <ul> <li><a href="https://en.wikipedia.org/wiki/Magic_square" rel="noreferrer">Magic Square - Wiki</a></li> </ul>
[]
[ { "body": "<p>I normally don't like to do complete rewrites for reviews as I don't think that they're usually helpful. Here though, the major problem that I see with your code is you're trying to do far too much \"manually\". You aren't making good use of built-in Python constructs that automate some of the painful elements. You also have everything in one massive block. I rewrote this from scratch to show how I'd approach the problem fresh.</p>\n\n<p>There are a few discrete problems to solve here:</p>\n\n<ul>\n<li><p>Check that each sums correctly:</p>\n\n<ul>\n<li>Rows</li>\n<li>Columns</li>\n<li>Diagonals</li>\n</ul></li>\n<li><p>Check that the square is in fact a square.</p></li>\n<li><p>Check that it contains the correct set of numbers.</p></li>\n</ul>\n\n<p>I see each of these as distinct problems that should be handled separately. In your current code, you have everything mixed together in one massive function which makes it difficult to tell what is responsible for what job. It's simply not very easy code to read.</p>\n\n<p>I ended up breaking the problem up into multiple <em>tiny</em> functions, then tying everything together in <code>is_magic_square</code>:</p>\n\n<pre><code>from typing import List, Iterable, Callable\nfrom functools import partial\n\nGrid = List[List[int]] # Might as well create an alias for this\n\ndef has_correct_dimensions(grid: Grid) -&gt; bool:\n \"\"\"Returns whether or not the grid is a non-jagged square.\"\"\"\n return all(len(row) == len(grid) for row in grid)\n\n\ndef is_normal_square(grid: Grid) -&gt; bool:\n \"\"\"Returns whether or not the function contains unique numbers from 1 to n**2.\"\"\"\n max_n = len(grid[0]) ** 2\n # Does the set of numbers in the flattened grid contain the same numbers as a range set from 1 to n**2?\n return set(e for row in grid for e in row) == set(range(1, max_n + 1)) \n\n\ndef check_each(iterable: Iterable[Iterable[int]], magic_sum: int) -&gt; bool:\n \"\"\"Returns whether or not every sub-iterable collection sums to the magic sum\"\"\"\n return all(sum(elem) == magic_sum for elem in iterable)\n\n\ndef diagonal_of(grid: Grid, y_indexer: Callable[[int], int]) -&gt; Iterable[int]:\n \"\"\"Generates a line of elements from the grid. y = y_indexer(x).\"\"\"\n return (grid[y_indexer(x)][x] for x in range(len(grid)))\n\n\ndef is_magic_square(grid: Grid) -&gt; bool:\n \"\"\"Returns whether or not the supplied grid is a proper normal magic square.\"\"\"\n n_rows = len(grid)\n magic_sum = n_rows * (n_rows ** 2 + 1) / 2\n\n check = partial(check_each, magic_sum=magic_sum)\n\n return is_normal_square(grid) and \\\n has_correct_dimensions(grid) and \\\n check(grid) and \\ # Rows\n check(zip(*grid)) and \\ # Columns\n check([diagonal_of(grid, lambda x: x),\n diagonal_of(grid, lambda x: len(grid) - x - 1)])\n</code></pre>\n\n<p>Notice how I have small functions with well defined jobs. Also note how I'm making fairly extensive use of high-level Python helpers. <code>all</code> is great whenever you need to ensure that something is True across over an entire collection. And <code>zip</code> can be used to break the grid into columns. </p>\n\n<p>Even with this all broken up into functions, it's still 7 lines shorter than the original. It's also ~10x faster which I certainly didn't expect since I'm doing expensive shortcut stuff like <code>set(e for row in grid for e in row) == set(range(1, max_n + 1))</code>.</p>\n\n<p>My solutions is far from perfect though. Like I said above, I'm doing a few things quite wastefully. I'm using a lot of lazy operations (like with generator expressions), and repeatedly putting a whole <code>range</code> into a set over and over.</p>\n\n<p>The <code>return</code> in <code>is_magic_square</code> could probably be broken up too. I think it's fine, but it might make some people gag. It could be cleaned up a bit using <code>all</code>:</p>\n\n<pre><code>return all([is_normal_square(grid),\n has_correct_dimensions(grid),\n check(grid),\n check(zip(*grid)),\n check([diagonal_of(grid, lambda x: x),\n diagonal_of(grid, lambda x: len(grid) - x - 1)])])\n</code></pre>\n\n<p>At least that gets rid of the ugly line continuations.</p>\n\n<hr>\n\n<p>The major thing in your code that I will point out though is this atrocity:</p>\n\n<pre><code>except:\n return False\n</code></pre>\n\n<p>I think I've mentioned this before: don't do this. If you need to catch an exception, specify the exception, and keep the <code>try</code> in the narrowest scope necessary.</p>\n\n<p>Why? Because, case and point, when I tried to time your function, <code>timeit</code> was showing that your function was executing <em>one million times in 2 seconds</em>. I was blown away. Then I ran the tests though and saw that your code was returning <code>False</code> for every test. After some quick checking, I realized that I had forgotten to import numpy when I pasted your code.</p>\n\n<p>Your code was returning a valid result even though the required packages for the code to run weren't even imported. Stuff like that will eventually bite you via long, painful debugging sessions. Silencing errors is, in my opinion, literally one of the worst things you can possibly do when programming.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T21:10:32.593", "Id": "230978", "ParentId": "230972", "Score": "6" } }, { "body": "<p>One should almost never use a bare <code>except</code> clause. It should always list the exceptions to be caught.</p>\n\n<p>The code would be easier to read and understand, if it were written in section that each tested one aspect of a magic square. Like, is is a square, does it have all the numbers in sequence, do the rows add up to the magic number, do the columns, do the diagonals. Here is a pure python version:</p>\n\n<pre><code>def is_magic_square(grid: List[List[int]]) -&gt; bool:\n \"\"\"Returns a boolean if an input grid is magic square\"\"\"\n\n grid_length = len(grid)\n grid_area = grid_length**2\n magic_sum = float(grid_length * (grid_length ** 2 + 1) / 2)\n\n # check the length of all rows\n if any(len(row) != grid_length for row in grid):\n return False\n\n # check it has all the numbers in sequence \n if set(x for row in grid for x in row) != set(range(1, grid_area + 1)):\n return False\n\n # check all the rows add up to the magic_number\n if any(sum(row) != magic_sum for row in grid):\n return False\n\n # check all the columns add up to the magic_number\n if any(sum(row[col] for row in grid) != magic_sum for col in range(grid_length)):\n return False\n\n # check each diagonal adds up to the magic_number\n if (sum(grid[i][i] for i in range(grid_length)) != magic_sum\n or sum(grid[i][grid_length-i-1] for i in range(grid_length)) != magic_sum ):\n return False\n\n return True\n</code></pre>\n\n<p>Your code used numpy, it has many useful functions for this task. So here is an alternative version using numpy:</p>\n\n<pre><code>def is_magic_square2(grid: List[List[int]]) -&gt; bool:\n \"\"\"Returns a boolean if an input grid is magic square\"\"\"\n\n grid_length = len(grid)\n magic_sum = float(grid_length * (grid_length ** 2 + 1) / 2)\n\n # check the length of all rows\n if any(len(row) != grid_length for row in grid):\n return False\n\n npgrid = np.array(grid)\n\n # check it has all ints from 1 to grid_length**2 (inclusive)\n if len(np.setdiff1d(npgrid, np.arange(1, grid_length**2 + 1))):\n return False\n\n # check all the rows add up to the magic_number\n if any(np.not_equal(npgrid.sum(axis=0), magic_sum)):\n return False\n\n # check all the columns add up to the magic_number\n if any(np.not_equal(npgrid.sum(axis=1), magic_sum)):\n return False\n\n # check both diagonals add up to the magic_number\n if (npgrid.diagonal().sum() != magic_sum\n or np.fliplr(npgrid).diagonal().sum() != magic_sum):\n return False\n\n return True\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T22:57:29.520", "Id": "230980", "ParentId": "230972", "Score": "4" } } ]
{ "AcceptedAnswerId": "230978", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T18:35:13.637", "Id": "230972", "Score": "7", "Tags": [ "python", "beginner", "algorithm", "matrix", "mathematics" ], "Title": "Magic Square (Python)" }
230972
<p>The <a href="http://mongodb.github.io/mongo-scala-driver/2.6/getting-started/quick-tour/" rel="nofollow noreferrer">Mongo-Scala Driver</a> (v2.6) currently only supports asynchronous operations, although my use cases often seem to lend themselves well to synchronous reads. This may be to block downstream code execution, or to save off the result-set of documents for later use. I'm guessing there may be a way to do this with Futures, but my current implementation doesn't utilize them.</p> <p>At the moment, I use the following function to perform "synchronous" reads and return a list of documents. It serves my needs of blocking downstream code execution and returning a reusable list of documents, but it doesn't feel like the <i>cleanest</i> way to approach the problem - the use of <code>var</code> in Scala, and <code>while()</code> loops with a <code>Thread.sleep()</code> just feel like bandaids for a better solution. Is there a better way to do this?</p> <pre><code>// This is the code I'm looking for feedback on import org.mongodb.scala._ import org.mongodb.scala.bson.Document import org.mongodb.scala.model.Filters import scala.collection.mutable.ListBuffer /* This function optionally takes filters if you do not wish to return the entire collection. * Future implementation may include optional {Sorts, Projections, Aggregates} */ def getDocsSync(db: MongoDatabase, collectionName: String, filters: Option[conversions.Bson]): ListBuffer[Document] = { val docs = scala.collection.mutable.ListBuffer[Document]() var processing = true val query = if (filters.isDefined) { // conditionally apply filters db.getCollection(collectionName).find(filters.get) } else { db.getCollection(collectionName).find() } query.subscribe( (doc: Document) =&gt; docs.append(doc), // add doc to mutable list (e: Throwable) =&gt; throw e, // handle errors here () =&gt; processing = false // deontes that we've reached the end of the collection ) while (processing) { Thread.sleep(100) // wait here until all docs have been returned } docs } </code></pre> <pre><code>// sample usage of 'synchronous' query val client: MongoClient = MongoClient(uriString) val db: MongoDatabase = client.getDatabase(dbName) val allDocs = getDocsSync(db, "myCollection", Option.empty) val someDocs = getDocsSync(db, "myCollection", Option(Filters.eq("fieldName", "foo"))) </code></pre> <p>For reference, I'll include a typical asynchronous usage pattern for the Mongo-Scala Driver. As a quick note, I'd like to point out that I use this pattern whenever possible since it doesn't require the entire collection to be loaded into memory, which makes async a must for large collections.</p> <pre><code>// typical asynchronous usage pattern db.getCollection(collectionName).find().subscribe( (doc: org.mongodb.scala.bson.Document) =&gt; { // operate on an individual document here }, (e: Throwable) =&gt; { // do something with errors here, if desired }, () =&gt; { // deontes that we've reached the end of the collection } ) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T18:44:01.547", "Id": "230973", "Score": "2", "Tags": [ "scala", "asynchronous", "mongodb" ], "Title": "Synchronous use of Mongo-Scala Driver" }
230973
<p><strong>TLDR:</strong> I don't develop for a living. If someone could point me in the right direction to make my script more readable/pythonic I would appreciate the assistance. </p> <p>In particular I'm struggling with the charts found in <code>makeCharts()</code> and code-flow throughout. </p> <p>I have tried writing <code>makeCharts()</code> section as a for loop <code>for workbook.add_chart({"type": "pie"}) as piechart</code>, but received a <code>_exit error</code> which I guess makes sense as I'm not writing till the end of the function.</p> <p><strong>Background</strong>: We use a Security Incident Response Platform which has a available API but somewhat awful reporting. To offset this I have been writing a personal project script while learning pandas which pulls the last 30/60/90 day case metrics and creates some charts. The below is my current complete script sans identifying information. </p> <p><strong>Objectives:</strong> I really have been struggling to make this script:</p> <p>A) More Pythonic (specifically <code>makeCharts()</code> and <code>main()</code>).</p> <p>B) Faster I timed it at 42seconds across 350+ entries, which leads me to believe my <code>main()</code> loop could be improved.</p> <p>C) Easier to read code-flow in the process of addressing the above.</p> <pre><code># imports # defined globals start = time.time() def main(api): # Finds all cases on SIRP endpoint # Creates all30, all60, all90 dictionaries from epoch all30, all60, all90 = {}, {}, {} response = api.find_cases(range="all", sort=[]) def addToDict(arg, response, i): arg[(i)] = { "Name": response.json()[i]["title"], "ID": response.json()[i]["id"], "Owner": response.json()[i]["owner"], "Severity": response.json()[i]["severity"], "Created": (time.strftime( "%m/%d/%Y %H:%M:%S", time.gmtime(response.json()[i]["createdAt"] / 1000.0))) } if 'endDate' in response.json()[i]: arg[(i)].update({ "Closed": (time.strftime( "%m/%d/%Y %H:%M:%S", time.gmtime(response.json()[i]["endDate"] / 1000.0))), "Resolution": response.json()[i]["resolutionStatus"] }) return if response.status_code == 200: i = 0 while i &lt; len(response.json()): if (response.json()[i]["createdAt"] / 1000) &gt; time.mktime( (datetime.date.today() - datetime.timedelta(days=30)).timetuple()): addToDict(all30, response, i) if (response.json()[i]["createdAt"] / 1000) &gt; time.mktime( (datetime.date.today() - datetime.timedelta(days=60)).timetuple()): addToDict(all60, response, i) else: addToDict(all90, response, i) i += 1 makeSS(all30, all60, all90) def makeSS(all30, all60, all90): # creates (4) dataframes in pandas # all30/df1 - 30day dataframe from all30 dict # all60/df2 - 60day dataframe from all60 dict # all90/df3 - 90 day dataframe from all90 dict # df4 - separate sheet for chart data df1 = pd.DataFrame( all30, index=['Created', 'Severity', 'Owner', 'Name', 'Closed', 'Resolution']).transpose() df2 = pd.DataFrame( all60, index=['Created', 'Severity', 'Owner', 'Name', 'Closed', 'Resolution']).transpose() df3 = pd.DataFrame( all90, index=['Created', 'Severity', 'Owner', 'Name', 'Closed', 'Resolution']).transpose() df4 = pd.DataFrame({ 'Created': (df1.count()['Created']), 'Closed': (df1.count()['Closed']), 'Owner': (df1['Owner'].value_counts().to_dict()), 'Resolution': (df1['Resolution'].value_counts().to_dict()), 'Severity': (df1['Severity'].value_counts().to_dict()) }) makeCharts(df1, df2, df3, df4) def makeCharts(df1, df2, df3, df4): # create pie charts, xlsx and save locally with pd.ExcelWriter("foo.xlsx", engine="xlsxwriter", options={"strings_to_urls": False}) as writer: workbook = writer.book worksheet = workbook.add_worksheet("Summary Charts") worksheet.hide_gridlines(2) piechart = workbook.add_chart({"type": "pie"}) piechart.set_title({'name': 'New vs. Closed Cases'}) piechart.set_style(10) piechart.add_series({ 'name': 'Open vs. Closed Cases Last 30', 'categories': '=Tracking!$B$1:$C$1', 'values': '=Tracking!$B$2:$C$2', }) worksheet.insert_chart("D2", piechart, { 'x_offset': 25, 'y_offset': 10 }) piechart1 = workbook.add_chart({"type": "pie"}) piechart1.set_title({'name': 'Severities'}) piechart1.set_style(10) piechart1.add_series({ 'name': 'Severity Last 30', 'categories': '=Tracking!$A$2:$A$4', 'values': '=Tracking!$F$2:$F$4', }) worksheet.insert_chart("M2", piechart1, { 'x_offset': 25, 'y_offset': 10 }) piechart2 = workbook.add_chart({"type": "pie"}) piechart2.set_title({'name': 'Resolution Last 30'}) piechart2.set_style(10) piechart2.add_series({ 'name': 'Resolution Last 30', 'categories': '=Tracking!$A$5:$A$6', 'values': '=Tracking!$E$5:$E$6', }) worksheet.insert_chart("D19", piechart2, { 'x_offset': 25, 'y_offset': 10 }) piechart3 = workbook.add_chart({"type": "pie"}) piechart3.set_title({'name': 'Case Ownership Last 30'}) piechart3.set_style(10) piechart3.add_series({ 'name': 'Case Ownership Last 30', 'categories': '=Tracking!$A$7:$A$10', 'values': '=Tracking!$D$7:$D$10', }) worksheet.insert_chart("M19", piechart3, { 'x_offset': 25, 'y_offset': 10 }) df1.to_excel(writer, sheet_name="Cases newer than 30 Days", startrow=1, header=False) formatSS((writer.sheets["Cases newer than 30 Days"]), workbook, df1) df2.to_excel(writer, sheet_name="Cases older than 60 days", startrow=1, header=False) formatSS((writer.sheets["Cases older than 60 days"]), workbook, df2) df3.to_excel(writer, sheet_name="Cases older than 90 days", startrow=1, header=False) formatSS((writer.sheets["Cases older than 90 days"]), workbook, df3) df4.to_excel(writer, sheet_name="Tracking") writer.save() send() def formatSS(worksheet, workbook, arg): # add width to columns, filter, freeze worksheet.set_column("A:A", 3.5, workbook.add_format()) worksheet.set_column("B:B", 17.25, workbook.add_format()) worksheet.set_column("C:C", 10, workbook.add_format()) worksheet.set_column("D:D", 10, workbook.add_format()) worksheet.set_column("E:E", 100, workbook.add_format()) worksheet.set_column("F:F", 17.25, workbook.add_format()) worksheet.set_column("G:G", 11.25, workbook.add_format()) worksheet.freeze_panes(1, 0) worksheet.autofilter("A1:G100") header_format = workbook.add_format({ "bold": True, "text_wrap": True, "valign": "top", "fg_color": "#CCCCCC", "border": 1, }) for col_num, value in enumerate(arg.columns.values): worksheet.write(0, col_num + 1, value, header_format) return worksheet, workbook def send(): # send the created xlsx msg = MIMEMultipart() msg["From"] = "Address@Domain.com" msg["To"] = sendTo msg["Subject"] = "Metrics" msg.attach( MIMEText("Attached are the requested case metrics in .XLSX format.")) part = MIMEBase("application", "octet-stream") part.set_payload(open("Foo.xlsx", "rb").read()) encoders.encode_base64(part) part.add_header("Content-Disposition", 'attachment; filename="Foo.xlsx"') msg.attach(part) smtp = smtplib.SMTP(smtp_server) smtp.starttls() smtp.sendmail(msg["From"], [msg["To"]], msg.as_string()) smtp.quit() main(api) print('It took', time.time() - start, 'seconds.') exit() </code></pre>
[]
[ { "body": "<p>Complex refactoring/improvements:</p>\n\n<p>Involved <em>Refactoring</em> techniques: <strong>Rename variable</strong>, <strong>Rename function</strong>, <strong>Extract variable</strong>, <strong>Extract function</strong>, <strong>Substitute Algorithm</strong>, <strong>Slide statements</strong>, <strong>Split phase</strong> (well-known classics <a href=\"https://refactoring.com/catalog/\" rel=\"nofollow noreferrer\">https://refactoring.com/catalog/</a>) + eliminating duplication and rearranging responsibility</p>\n\n<p>Completely different OOP approach to your script, representing <code>SIRPPipeline</code> (<em>SIRP</em> Pipeline) which is initialized with passed <code>api</code> component/client, composed and running as a set of consecutive operations/phases:<br> \n<em>loading data | making dataframes | making/building charts | send email</em>.</p>\n\n<p>In more details:</p>\n\n<ul>\n<li><p><strong><code>loading data</code></strong>. Covered by instance method <code>_load_data</code> which initiates API call to fetch the crucial source data and, if successful, populates target days dictionaries with records data (method <code>_fill_day_dicts</code>)</p></li>\n<li><p><strong><code>making dataframes</code></strong>. Covered by method <code>make_dataframes</code> which has a concrete single responsibility: construct 4 crucial dataframes (<em>30 days, 60 days, 90 days, counts</em>)</p></li>\n<li><p><strong><code>making/building charts</code></strong>. Covered by complex method <code>make_charts</code>. It initiates <code>ExcelWriter</code> object, declares inner functions for internal usage: <code>_insert_pie_chart</code> (builds and inserts pie chart to specified worksheet) and <code>_df_days_to_excel</code> (writes passed dataframe to <em>writer</em> object). <code>_set_workbook_layout</code> method establishes workbook/worksheet layout/format and saves it to worksheet.</p></li>\n<li><p><strong><code>send email</code></strong>. Static method <code>send_email</code> builds and sends an email related to \"case metrics\" pipeline event. The old function <code>send</code> was too generalized while <code>send_email</code> method reflects concrete purpose in scope of pipeline.</p></li>\n</ul>\n\n<hr>\n\n<pre><code>import datetime\nimport smtplib\nimport time\nfrom email import encoders\nfrom email.mime.base import MIMEBase\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\nimport pandas as pd\n\n\nclass SIRPPipeline:\n TIME_FMT = \"%m/%d/%Y %H:%M:%S\"\n DF_INDEX = ['Created', 'Severity', 'Owner', 'Name', 'Closed', 'Resolution']\n\n def __init__(self, api):\n \"\"\"Security Incident Response Platform prosessing pipeline.\n Accepts API object on initialization phase.\n \"\"\"\n self._api = api\n self._all30_dict = {}\n self._all60_dict = {}\n self._all90_dict = {}\n\n self._df_30days = None\n self._df_60days = None\n self._df_90days = None\n self._df_counts = None\n self._dataset = None\n\n def _load_data(self):\n # Finds all cases on SIRP endpoint\n self._api_response = self._api.find_cases(range=\"all\", sort=[])\n\n if self._api_response.status_code == 200:\n self._dataset = self._api_response.json()\n self._fill_day_dicts()\n\n @staticmethod\n def _add_record(days_dict, record, key):\n days_dict[key] = {\n \"Name\": record[\"title\"],\n \"ID\": record[\"id\"],\n \"Owner\": record[\"owner\"],\n \"Severity\": record[\"severity\"],\n \"Created\": (time.strftime(\n SIRPPipeline.TIME_FMT,\n time.gmtime(record[\"createdAt\"] / 1000.0)))\n }\n if 'endDate' in record:\n days_dict.update({\n \"Closed\": (time.strftime(\n SIRPPipeline.TIME_FMT,\n time.gmtime(record[\"endDate\"] / 1000.0))),\n \"Resolution\": record[\"resolutionStatus\"]\n })\n\n def _fill_day_dicts(self):\n today = datetime.date.today()\n\n for i, record in enumerate(self._dataset):\n if (record[\"createdAt\"] / 1000) &gt; time.mktime(\n (today - datetime.timedelta(days=30)).timetuple()):\n self._add_record(self._all30_dict, record, key=i)\n\n elif (record[\"createdAt\"] / 1000) &gt; time.mktime(\n (today - datetime.timedelta(days=60)).timetuple()):\n self._add_record(self._all60_dict, record, key=i)\n\n else:\n self._add_record(self._all90_dict, record, key=i)\n\n def make_dataframes(self):\n \"\"\"Creates (4) pandas dataframes:\n - df_30days dataframe from all30 dict\n - df_60days dataframe from all60 dict\n - df_90days dataframe from all90 dict\n - df_counts - separate sheet for chart data\n \"\"\"\n self._df_30days = pd.DataFrame(self._all30_dict, index=SIRPPipeline.DF_INDEX).transpose()\n self._df_60days = pd.DataFrame(self._all60_dict, index=SIRPPipeline.DF_INDEX).transpose()\n self._df_90days = pd.DataFrame(self._all90_dict, index=SIRPPipeline.DF_INDEX).transpose()\n self._df_counts = pd.DataFrame({\n 'Created': (self._df_30days.count()['Created']),\n 'Closed': (self._df_30days.count()['Closed']),\n 'Owner': (self._df_30days['Owner'].value_counts().to_dict()),\n 'Resolution': (self._df_30days['Resolution'].value_counts().to_dict()),\n 'Severity': (self._df_30days['Severity'].value_counts().to_dict())\n })\n\n @staticmethod\n def _set_workbook_layout(workbook, worksheet, df):\n # add width to columns, filter, freeze\n worksheet.set_column(\"A:A\", 3.5, workbook.add_format())\n worksheet.set_column(\"B:B\", 17.25, workbook.add_format())\n worksheet.set_column(\"C:C\", 10, workbook.add_format())\n worksheet.set_column(\"D:D\", 10, workbook.add_format())\n worksheet.set_column(\"E:E\", 100, workbook.add_format())\n worksheet.set_column(\"F:F\", 17.25, workbook.add_format())\n worksheet.set_column(\"G:G\", 11.25, workbook.add_format())\n worksheet.freeze_panes(1, 0)\n worksheet.autofilter(\"A1:G100\")\n\n header_format = workbook.add_format({\n \"bold\": True,\n \"text_wrap\": True,\n \"valign\": \"top\",\n \"fg_color\": \"#CCCCCC\",\n \"border\": 1,\n })\n\n for col_num, value in enumerate(df.columns.values, 1):\n worksheet.write(0, col_num, value, header_format)\n\n def make_charts(self):\n\n def _insert_pie_chart(wbook, wsheet, title, cell_pos, series):\n piechart = wbook.add_chart({\"type\": \"pie\"})\n piechart.set_title({'name': title})\n piechart.set_style(10)\n piechart.add_series(series)\n wsheet.insert_chart(cell_pos, piechart, {\n 'x_offset': 25,\n 'y_offset': 10\n })\n\n def _df_days_to_excel(writer, sheet_name, df_days):\n df_days.to_excel(writer, sheet_name=sheet_name, startrow=1, header=False)\n self._set_workbook_layout(writer.book, (writer.sheets[sheet_name]), df_days)\n\n # create pie charts, xlsx and save locally\n with pd.ExcelWriter(\"foo.xlsx\",\n engine=\"xlsxwriter\",\n options={\"strings_to_urls\": False}) as writer:\n workbook = writer.book\n worksheet = workbook.add_worksheet(\"Summary Charts\")\n worksheet.hide_gridlines(2)\n\n _insert_pie_chart(workbook, worksheet, title='New vs. Closed Cases', cell_pos='D2', series={\n 'name': 'Open vs. Closed Cases Last 30',\n 'categories': '=Tracking!$B$1:$C$1',\n 'values': '=Tracking!$B$2:$C$2',\n })\n _insert_pie_chart(workbook, worksheet, title='Severities', cell_pos='M2', series={\n 'name': 'Severity Last 30',\n 'categories': '=Tracking!$A$2:$A$4',\n 'values': '=Tracking!$F$2:$F$4',\n })\n _insert_pie_chart(workbook, worksheet, title='Resolution Last 30', cell_pos='D19', series={\n 'name': 'Resolution Last 30',\n 'categories': '=Tracking!$A$5:$A$6',\n 'values': '=Tracking!$E$5:$E$6',\n })\n _insert_pie_chart(workbook, worksheet, title='Case Ownership Last 30', cell_pos='M19', series={\n 'name': 'Case Ownership Last 30',\n 'categories': '=Tracking!$A$7:$A$10',\n 'values': '=Tracking!$D$7:$D$10',\n })\n\n _df_days_to_excel(writer, sheet_name=\"Cases newer than 30 Days\", df_days=self._df_30days)\n _df_days_to_excel(writer, sheet_name=\"Cases older than 60 days\", df_days=self._df_60days)\n _df_days_to_excel(writer, sheet_name=\"Cases newer than 90 Days\", df_days=self._df_90days)\n\n self._df_counts.to_excel(writer, sheet_name=\"Tracking\")\n writer.save()\n\n @staticmethod\n def send_mail():\n # send_mail the created xlsx\n msg = MIMEMultipart()\n msg[\"From\"] = \"Address@Domain.com\"\n msg[\"To\"] = send_to # consider `send_to` declaration\n msg[\"Subject\"] = \"Metrics\"\n msg.attach(\n MIMEText(\"Attached are the requested case metrics in .XLSX format.\"))\n part = MIMEBase(\"application\", \"octet-stream\")\n part.set_payload(open(\"Foo.xlsx\", \"rb\").read())\n encoders.encode_base64(part)\n part.add_header(\"Content-Disposition\",\n 'attachment; filename=\"Foo.xlsx\"')\n msg.attach(part)\n smtp = smtplib.SMTP(smtp_server) # consider `smtp_server` declaration\n smtp.starttls()\n smtp.sendmail(msg[\"From\"], [msg[\"To\"]], msg.as_string())\n smtp.quit()\n\n def run(self):\n self._load_data()\n self.make_dataframes() # may be protected\n self.make_charts() # may be protected\n self.send_mail()\n\n\ndef main(api):\n pipe = SIRPPipeline(api)\n pipe.run()\n\n\n# api initialization\n# ...\nstart = time.time()\nmain(api)\nprint('It took', time.time() - start, 'seconds.')\nexit()\n</code></pre>\n\n<p>As for time performance, it requires an appropriate testable sample data for realistic measurements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T13:22:45.287", "Id": "450451", "Score": "1", "body": "Thank you very much for this well thought out answer, I really appreciate it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T14:02:35.160", "Id": "450462", "Score": "1", "body": "@ImNotLeet, you're welcome. It's great if it's helped you to find the \"way\"." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T17:44:34.960", "Id": "231006", "ParentId": "230975", "Score": "2" } } ]
{ "AcceptedAnswerId": "231006", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T19:40:26.417", "Id": "230975", "Score": "5", "Tags": [ "python", "excel", "pandas", "statistics", "data-visualization" ], "Title": "Fetch, plot, and send security incident statistics with Excel" }
230975
<p><a href="https://leetcode.com/problems/daily-temperatures/" rel="nofollow noreferrer">https://leetcode.com/problems/daily-temperatures/</a><br></p> <blockquote> <p>Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.</p> <p>For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].</p> <p>Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].</p> </blockquote> <p>Please review for performance.</p> <pre><code>using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ArrayQuestions { /// &lt;summary&gt; /// https://leetcode.com/problems/daily-temperatures/ /// &lt;/summary&gt; [TestClass] public class DailyTemperaturesTest { [TestMethod] public void ExmapleTest() { int[] temperatures = {73, 74, 75, 71, 69, 72, 76, 73}; int[] days = {1, 1, 4, 2, 1, 1, 0, 0}; CollectionAssert.AreEqual(days, DailyTemperaturesClass.DailyTemperatures(temperatures)); } [TestMethod] public void SmallExampleTest() { int[] temperatures = {73, 72, 73, 74}; int[] days = {3, 1, 1, 0}; CollectionAssert.AreEqual(days, DailyTemperaturesClass.DailyTemperatures(temperatures)); } } public class DailyTemperaturesClass { public static int[] DailyTemperatures(int[] T) { int[] days = new int[T.Length]; // we are using a stack to remeber all the temps we saw until now, // the next time we see one which is higher we pop all the temps which are lower Stack&lt;int&gt; stack = new Stack&lt;int&gt;(); for (int i = T.Length - 1; i &gt;= 0; i--) { //if the current temp is greater or equals to the top of the stack // pop all until found one which is higher temp then T[i] while (stack.Count &gt; 0 &amp;&amp; T[i] &gt;= T[stack.Peek()]) { stack.Pop(); } if (stack.Count == 0) { days[i] = 0; } else { days[i] = stack.Peek() - i; // number of days between higher temp to i } stack.Push(i);// we push current temp to the Top of the stack. } return days; } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T20:03:29.077", "Id": "230976", "Score": "1", "Tags": [ "c#", "programming-challenge", "stack" ], "Title": "LeetCode: Daily Temperatures C#" }
230976
<p>This past week, I had a coding interview where I have failed badly. The feedback that I get from the recruiter was that my code reminded the team of older ways of coding in C#. This led them to believe that I haven’t had much experience with newer version of the framework.</p> <p>This made me quite confused as I literally don't know exactly what should I change so that my code could look more modern.</p> <p>Was it about performance? Was my way of solving did not make use of the best practices? Any help will be greatly appreciated.</p> <p>First of all, here is the problem. <a href="https://i.stack.imgur.com/o3Yxe.png" rel="noreferrer"><img src="https://i.stack.imgur.com/o3Yxe.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/RzpDZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RzpDZ.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/vtRII.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vtRII.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/Z5vds.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Z5vds.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/OJzdz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OJzdz.png" alt="enter image description here"></a></p> <p>As for the file of orders, it looks like this:</p> <pre><code>{ "order-001": { "destination" : "YYZ" }, "order-002": { "destination" : "YYZ" }, "order-003": { "destination" : "YYZ" }, "order-004": { "destination" : "YYZ" }, ... } </code></pre> <p>Instead of creating a big constant file for the schedules, I have decided to read them from a JSON file that I've filled using the scenario above.</p> <pre><code>{ "1": { "departure": "YUL", "arrival": "YYZ", "day": 1 }, "2": { "departure": "YUL", "arrival": "YYC", "day": 1 }, "3": { "departure": "YUL", "arrival": "YVR", "day": 1 }, "4": { "departure": "YUL", "arrival": "YYZ", "day": 2 }, "5": { "departure": "YUL", "arrival": "YYC", "day": 2 }, "6": { "departure": "YUL", "arrival": "YVR", "day": 2 } } </code></pre> <p>Here is the code I have produced so that I can solve the problem:</p> <p>First of all, I have a class called Loader which allows me to load all the elements of the JSON files into objects</p> <p>Loader.cs</p> <pre class="lang-cs prettyprint-override"><code>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Transport.ly { public static class Loader { public static List&lt;Order&gt; LoadOrders() { List&lt;Order&gt; data; using (StreamReader r = new StreamReader(Constants.Path.JsonPath)) { string json = r.ReadToEnd(); data = JsonConvert.DeserializeObject&lt;Dictionary&lt;string, Order&gt;&gt;(json).Select(p =&gt; new Order { Code = p.Key, Destination = p.Value.Destination, Priority = Int32.Parse( p.Key.Substring(p.Key.LastIndexOf('-') + 1)) }).ToList(); } return data; } public static Dictionary&lt;int, Schedule&gt; LoadScenarioSchedule() { Dictionary&lt;int, Schedule&gt; data; using (StreamReader r = new StreamReader(Constants.Path.ScenarioPath)) { string json = r.ReadToEnd(); data = JsonConvert.DeserializeObject&lt;Dictionary&lt;int, Schedule&gt;&gt;(json); } return data; } } } </code></pre> <p>An order class</p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections.Generic; using System.Text; namespace Transport.ly { /// &lt;summary&gt; /// Represent an order /// &lt;/summary&gt; public class Order { public Order() { _loaded = false; } public Order(string destination, string code, bool loaded, int priority) { _priority = priority; _loaded = loaded; _code = code; _destination = destination; } private string _destination; private string _code; private int _priority; private bool _loaded; public string Destination { get =&gt; _destination; set =&gt; _destination = value; } public string Code { get =&gt; _code; set =&gt; _code = value; } public bool Loaded { get =&gt; _loaded; set =&gt; _loaded = value; } public int Priority { get =&gt; _priority; set =&gt; _priority = value; } } } </code></pre> <p>A class representing the schedules</p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections.Generic; using System.Text; namespace Transport.ly { /// &lt;summary&gt; /// Represent a schedule /// &lt;/summary&gt; public class Schedule { public Schedule() { _loaded = false; } public Schedule(int day, string departure, string arrival) { _day = day; _departure = departure; _arrival = arrival; } private int _day; private string _departure; private string _arrival; private bool _loaded; public bool Loaded { get =&gt; _loaded; set =&gt; _loaded = value; } public string Arrival { get =&gt; _arrival; set =&gt; _arrival = value; } public string Departure { get =&gt; _departure; set =&gt; _departure = value; } public int Day { get =&gt; _day; set =&gt; _day = value; } } } </code></pre> <p>A class that represent a flight </p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections.Generic; using System.Text; namespace Transport.ly { /// &lt;summary&gt; /// This class represent a flight /// &lt;/summary&gt; public class Flight { public Flight() { _orders = new List&lt;Order&gt;(); } public Flight(int number, Schedule schedule, List&lt;Order&gt; orders) { _orders = orders; _schedule = schedule; _number = number; } private int _number; private Schedule _schedule; private List&lt;Order&gt; _orders; public List&lt;Order&gt; Orders { get =&gt; _orders; } public Schedule Schedule { get =&gt; _schedule; } public int Number { get =&gt; _number; } } } </code></pre> <p>Inventory.cs</p> <pre class="lang-cs prettyprint-override"><code>using System.Collections.Generic; using System.Linq; namespace Transport.ly { public class Inventory { public Inventory() { _schedules = new Dictionary&lt;int, Schedule&gt;(); _orders = new List&lt;Order&gt;(); _flights = new List&lt;Flight&gt;(); } public Inventory(string name, Dictionary&lt;int, Schedule&gt; schedules, List&lt;Order&gt; orders) { _name = name; _schedules = schedules; _orders = orders; _flights = new List&lt;Flight&gt;(); } public void LoadSchedule( int key) { _schedules[key].Loaded = true; } /// &lt;summary&gt; /// this function returns schedules that are loaded /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public Dictionary&lt;int ,Schedule&gt; GetLoadedSchedules() { return _schedules.Where(s =&gt; s.Value.Loaded) .ToDictionary(dict =&gt; dict.Key, dict =&gt; dict.Value); } /// &lt;summary&gt; /// this function returns schedules that are not loaded yet /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public Dictionary&lt;int, Schedule&gt; GetAvailableSchedules() { return _schedules.Where(s =&gt; s.Value.Loaded == false) .ToDictionary(dict =&gt; dict.Key, dict =&gt; dict.Value); } public List&lt;Order&gt; GetOrders() { return _orders; } public Dictionary&lt;int, Schedule&gt; GetSchedules() { return _schedules; } /// &lt;summary&gt; /// Generate Flight itineraries and return what hasbeen generate. /// This function return only orders that are loaded. In other words, /// Orders that have scedule. associated to them. /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public List&lt;Flight&gt; GenerateFlights() { var loadedSchedules = GetLoadedSchedules(); List&lt;Schedule&gt; sortedSchedule = new List&lt;Schedule&gt;(); sortedSchedule = loadedSchedules.Values.ToList(); sortedSchedule.Sort((emp1, emp2) =&gt; emp1.Day.CompareTo(emp2.Day)); int flightNumber = 1; List&lt;Order&gt; ordersByPriority = _orders.OrderBy(o =&gt; o.Priority).ToList(); foreach (Schedule schedule in sortedSchedule) { //if the schedule is already assigned to a flight, no need to add it if (_flights.Any(item =&gt; item.Schedule.Day == schedule.Day &amp;&amp; item.Schedule.Arrival == schedule.Arrival &amp;&amp; item.Schedule.Departure == schedule.Departure)) { flightNumber++; continue; } List&lt;Order&gt; orders = new List&lt;Order&gt;(); //get 20 orders that has the same destination for (int i = 0; i &lt; ordersByPriority.Count; i++) { //Check if the order has the same destination as the scedule and if the order is not //already loaded on a previous flights if (schedule.Arrival == ordersByPriority[i].Destination &amp;&amp; !ordersByPriority[i].Loaded) { orders.Add(ordersByPriority[i]); ordersByPriority[i].Loaded = true; if (orders.Count == Constants.Rule.PlaneBoxCountLimit) { break; } } } _flights.Add(new Flight(flightNumber, schedule, orders)); flightNumber++; } return _flights; } private string _name; private List&lt;Order&gt; _orders; private Dictionary&lt;int, Schedule&gt; _schedules; private List&lt;Flight&gt; _flights; } } </code></pre> <p>A class containing the srting constants</p> <pre class="lang-cs prettyprint-override"><code>using System.IO; namespace Transport.ly { public static class Constants { public static class Messages { public const string ChooseDeparture = "Choose departure Location"; public const string PressAnyKey = "\nPress any key to go to the main menu..."; public const string QuiApplicationMenu = "[ 0 ] Quit application\n"; public const string ReturnToMainMenu = "[ 0 ] Return to main menu\n"; public const string Tryagain = "Try again!!"; } public static class Header { public const string MainMenu = "========= Transport.ly ============"; public const string ChooseScheduleToLoad = "========= Choose a schedule to Load ============"; public const string LoadedSchedules = "=========Loaded schedules ============"; public const string BatchOfOrders = "========= Bathch of Orders ==========="; } public static class MenuOptions { public static readonly string[] MainMenu = { "1. Load a schedule", "2. List out the schedules", "3. Generate flight itineraries ", "5. Exit"}; } public static class Path { public readonly static string JsonPath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Files\\coding-assigment-orders.json"); public readonly static string ScenarioPath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Files\\scheduledFlights.json"); } public static class Rule { public const int PlaneCount = 2; public const int DepartureHour = 12; public const int ArrivalHour = 0; public const int PlaneBoxCountLimit = 20; } } } </code></pre> <p>And finaly the main</p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections.Generic; using System.Linq; namespace Transport.ly { class Program { static void Main(string[] args) { Inventory transportLy = new Inventory("Transport.ly", Loader.LoadScenarioSchedule(), Loader.LoadOrders()); MainMenu(transportLy); } static void MainMenu(Inventory inventory) { while (true) { int userChoice; do { Console.Clear(); DisplayMAinMenu(); Console.WriteLine(Constants.Messages.QuiApplicationMenu); } while (!int.TryParse(Console.ReadLine(), out userChoice) || userChoice &lt; 0 || userChoice &gt; 3); Console.Clear(); switch (userChoice) { case 1: MenuLoadSchedules(inventory); break; case 2: DisplayLoadedSchedules(inventory.GetLoadedSchedules()); Console.WriteLine(); Console.WriteLine(Constants.Messages.PressAnyKey); Console.ReadKey(); break; case 3: DisplayFlights(inventory.GenerateFlights(), inventory.GetOrders()); Console.WriteLine(Constants.Messages.PressAnyKey); Console.ReadKey(); break; case 0: Environment.Exit(0); break; default: Console.WriteLine(Constants.Messages.Tryagain); break; } } } static void MenuLoadSchedules(Inventory inventory) { while (true) { int option; do { Console.Clear(); DisplayAvailableSchedules(inventory.GetAvailableSchedules()); Console.WriteLine(Constants.Messages.ReturnToMainMenu); } while (!int.TryParse(Console.ReadLine(), out option) || option &lt; 0 || !inventory.GetAvailableSchedules().ContainsKey(option) &amp;&amp; option != 0); if (option != 0) { inventory.LoadSchedule(option); Console.Clear(); Console.WriteLine("Schedule : " + option + " loaded"); Console.WriteLine(Constants.Messages.PressAnyKey); Console.ReadKey(); } else { return; } Console.Clear(); } } static public void DisplayMAinMenu() { Console.WriteLine(Constants.Header.MainMenu); Console.WriteLine(); foreach (string option in Constants.MenuOptions.MainMenu) Console.WriteLine(option); } static public void DisplayAvailableSchedules(Dictionary&lt;int, Schedule&gt; availableSchedules) { Console.WriteLine(Constants.Header.ChooseScheduleToLoad); Console.WriteLine(); foreach (KeyValuePair&lt;int, Schedule&gt; entry in availableSchedules) { Console.WriteLine(entry.Key+ ". Departure: " + entry.Value.Departure + " Arrival: " + entry.Value.Arrival + " Day: " + entry.Value.Day); } } static public void DisplayLoadedSchedules(Dictionary&lt;int, Schedule&gt; schedules) { Console.WriteLine(Constants.Header.LoadedSchedules); Console.WriteLine(); foreach (KeyValuePair&lt;int, Schedule&gt; entry in schedules) { Console.WriteLine(entry.Key + ". Departure: " + entry.Value.Departure + " Arrival: " + entry.Value.Arrival + " Day: " + entry.Value.Day); } } static public void DisplayFlights(List&lt;Flight&gt; flights, List&lt;Order&gt; AllOrder) { foreach (Order order in AllOrder) { Console.WriteLine(Constants.Header.BatchOfOrders); Console.WriteLine(); if (order.Loaded) { //get other informations foreach (Flight flight in flights) { if (flight.Orders.FirstOrDefault(item =&gt; item.Code == order.Code &amp;&amp; item.Destination == order.Destination) != null) { Console.WriteLine("order: "+ order.Code+ ", flightNumber: "+flight.Number + ", departure: "+flight.Schedule.Departure+ ", arrival: "+flight.Schedule.Arrival+", day: "+flight.Schedule.Day); } } } else { Console.WriteLine("order: "+order.Code+", flightNumber: not scheduled"); } } } } } </code></pre>
[]
[ { "body": "<p>I also think you are using older styles. For example:</p>\n\n<pre><code>private bool _loaded;\npublic bool Loaded { get =&gt; _loaded; set =&gt; _loaded = value; }\n</code></pre>\n\n<p>Is awkward and really should have a better name:</p>\n\n<pre><code>public bool IsLoaded {get; set;}\n</code></pre>\n\n<p>Looks like they would appreciate some OOP. I would think there would be a class for airports. Just Googling on 3 letter airport codes and Wikipedia, I whipped this up in 10 minutes:</p>\n\n<pre><code>public class Airport\n{\n private Airport() { }\n\n public string Id { get; private set; }\n public string Name { get; private set; }\n public string City { get; private set; }\n public TimeZoneInfo TimeZone { get; private set; }\n // add other pertinent properties such as Province or Country\n\n public override string ToString() =&gt; $\"{Name} ({Id}), {City} {TimeZone.DisplayName}\";\n\n // Helpful link on IATA 3 letter codes:\n // https://www.nationsonline.org/oneworld/IATA_Codes/IATA_Code_Y.htm\n\n public static Airport YUL =&gt; new Airport\n {\n Id = \"YUL\",\n Name = \"Dorval\",\n City = \"Montreal\",\n TimeZone = TimeZoneInfo.FindSystemTimeZoneById(\"Eastern Standard Time\")\n };\n\n public static Airport YYZ =&gt; new Airport\n {\n Id = \"YYZ\",\n Name = \"Toronto Pearson International Airport\",\n City = \"Toronto\",\n TimeZone = TimeZoneInfo.FindSystemTimeZoneById(\"Eastern Standard Time\")\n };\n\n // Calgary and Vancouver left as exercise\n}\n</code></pre>\n\n<p>If they want OOP, give them OOP! </p>\n\n<p>Also, I would not make too many assumptions though they were assumed in the directions. This may be the questioners lulling you into taking short-cuts and making your code too rigid.</p>\n\n<ul>\n<li>I would not assume all flights leave only from Montreal's Dorval\nairport. </li>\n<li>I would not assume all flights leave exactly at noon. </li>\n<li>I would not assume the departing and destination airports are in the \nsame time zone or country.</li>\n</ul>\n\n<p>Heeding that advice, if I were to make a <code>Flight</code> class, I would have a <code>Departing</code> airport (not assume it's Montreal), a <code>Destination</code> airport, a <code>DepartingTime</code> (not assuming Noon Montreal), and <code>ArrivingTime</code>. Internally, all <code>DateTime</code> objects would be UTC. Displayed times would be local to the respective airport. That is the departing time is local the the departing airport, but the arrival time would be local the the destination airport, which is why I included <code>TimeZone</code> as a property in the <code>Airport</code> class.</p>\n\n<p>Maybe one acceptable assumption would be that an <code>Unspecified</code> date and time would also be considered local to the respective airport. Or you may prompt for clarity of throw an exception.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T16:01:03.397", "Id": "231004", "ParentId": "230982", "Score": "2" } }, { "body": "<p>The main thing which can be recognized as a Junior Developer code is a poor possibility of code support in the future. \nTo archive such a point you need to use some common architectural patterns. First of all the code should be tested and error handled.\nAlso, you were asked to provide SOLID code which again means a bunch of patterns (IoC as DI is a must today in the development cycle). For example, the Loader class is not SOLID at all. Try to use microservices architecture for this purpose. \nAlso, I can see a strange code like:</p>\n\n<pre><code>return _schedules.Where(s =&gt; s.Value.Loaded == false)\n .ToDictionary(dict =&gt; dict.Key, dict =&gt; dict.Value);\n</code></pre>\n\n<p>I mean why this:</p>\n\n<pre><code>s.Value.Loaded == false\n</code></pre>\n\n<p>and not just </p>\n\n<pre><code>s=&gt;!s.Value.Loaded\n</code></pre>\n\n<p>Actually, after this row of code, I would decline your candidature for the Middle developer role. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T13:38:44.327", "Id": "450283", "Score": "1", "body": "Could you define IoC as DI for those of us that don't understand?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T17:32:45.497", "Id": "450318", "Score": "0", "body": "IoC - is Inversion Of Control; DI - Dependency Injection which is a private case of IoC pattern. This is a very big theme to highlight it with one comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T13:45:14.890", "Id": "450456", "Score": "0", "body": "Thx for your response. you told me that the loader class is not SOLID. The goal of my loader class was to load the JSON files into the programs. I don't quite understand how I could use microservice architecture to do that. Could you give me more details about the implementation of that architecture?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T14:35:10.817", "Id": "450586", "Score": "0", "body": "Microservice architecture is an insanely off-topic suggestion for an exercise that is expected to take no more than 90 minutes. As an interviewer I'd dismiss a microservices answer as a massive overengineering and an inability to work to a given schedule." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T18:18:17.173", "Id": "450606", "Score": "2", "body": "Note that “SOLID” here has a specific meaning. Here’s a quick intro https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T13:02:04.570", "Id": "231038", "ParentId": "230982", "Score": "3" } }, { "body": "<p>As it was a coding interview, you should give importance to some points. Here are those what I think from your coding exercise:</p>\n\n<ol>\n<li>You need to complete your exercise within the time specified. So, don’t waste you time to beautifying things or creating more functionalities which are not required. This kind of interview is conducted to see your skills and experience which is clearly mentioned.</li>\n<li>Make sure your output matches with sample output. If you an average developer, a single character can harm you. But if your code is extraordinary level then it may not be an issue.</li>\n<li>Focus on the coding styles like any principles or design patterns need to use. For this you need use best practices and SOLID principle of OOD. So, you must not violate SOLID principle while coding.</li>\n<li>Take few minutes to think how you should design classes, interfaces etc. If you have well amount of experience, then it wouldn’t take much time to design thing in your head.</li>\n<li>In scenario, flight schedules are given. So, you need to create Schedule class. These 6 schedules will be created using collection which are hard coded for this exercise so save time. However, you created schedule in a JSON file which is a waste of your time to complete this exercise.</li>\n<li>Each plane has a capacity of 20 box each and each box represents 1 order. So, you need to create a Plane/Flight class and Order class. A Plane/Flight class will have a property of Schedule class, a collection of Order property and integer Capacity property. You can hard code or use constant for capacity as it’s set to 20 but it’s good to make it flexible. Furthermore, you need to read Orders from JSON file.</li>\n</ol>\n\n<p><strong>USER STORY #1</strong></p>\n\n<ul>\n<li>It gives you full information about Schedule class properties. It will have FlightNumber, Departure, Arrival, Day and IsLoaded properties. It also said that you don’t need to load Orders as you only need to show not loaded schedules.</li>\n</ul>\n\n<p><strong>USER STORY #2</strong></p>\n\n<ul>\n<li>It says Order has priority and it should be loaded in Plane/Flight using priorities. So, Order class will have Code, Destination, Priority and Schedule properties. Though orders are in JSON file are arranged by priorities but it’s good to sort by priority.</li>\n</ul>\n\n<p><strong>Here are some code samples:</strong></p>\n\n<pre><code>class Schedule\n{\n //use auto properties\n public int FlightNumber { get; set; }\n public string Departure { get; set; }\n public string Arrival { get; set; }\n public int Day { get; set; }\n public bool IsLoaded { get; set; }\n\n public override string ToString()\n {\n //use string interpolation\n return $\"{FlightNumber}. Departure: {Departure}, Arrival: {Arrival}, Day: {Day}\";\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>class Flight\n{\n //use auto properties\n public int Capacity { get; private set; }\n public Schedule Schedule { get; private set; }\n public IList&lt;Order&gt; Orders { get; set; }\n\n public Flight(int capacity, Schedule schedule)\n {\n Capacity = capacity;\n schedule.IsLoaded = true;\n Schedule = schedule;\n Orders = new List&lt;Order&gt;();\n }\n\n public string FlightSchedule()\n {\n //use string interpolation\n return $\"Flight: {Schedule.FlightNumber}, departure: {Schedule.Departure}, arrival: {Schedule.Arrival}, day: {Schedule.Day}\";\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>class Order\n{\n //use auto properties\n public int Priority { get; set; }\n public string Code { get; set; }\n public string Destination { get; set; }\n public Schedule Schedule { get; set; }\n\n public bool IsNotLoaded()\n {\n return Schedule == null;\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>class Menu\n{\n public string Header { get; set; }\n public IList&lt;string&gt; Items { get; set; }\n public int ExitValue { get; set; }\n\n public Menu()\n {\n Items = new List&lt;string&gt;();\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>class FileReader\n{\n public static string ReadAllText(string path)\n {\n return File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), path));\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>interface IOrderRepository\n{\n IList&lt;Order&gt; GetOrders();\n}\n</code></pre>\n\n<hr>\n\n<pre><code>class OrderRepository : IOrderRepository\n{\n public IList&lt;Order&gt; GetOrders()\n {\n var jsonString = FileReader.ReadAllText(\"JSON Files\\\\coding-assigment-orders.json\");\n\n var orders = JsonConvert.DeserializeObject&lt;Dictionary&lt;string, Order&gt;&gt;(jsonString).Select(p =&gt;\n new Order { Code = p.Key, Destination = p.Value.Destination, Priority = int.Parse(p.Key.Substring(p.Key.LastIndexOf('-') + 1)) }).ToList();\n\n return orders;\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>interface IScheduleRepository\n{\n IList&lt;Schedule&gt; GetSchedules();\n}\n</code></pre>\n\n<hr>\n\n<pre><code>class ScheduleRepository : IScheduleRepository\n{\n public IList&lt;Schedule&gt; GetSchedules()\n {\n //use implicitly typed variables\n var flightNo = 1;\n var day = 1;\n var schedules = new List&lt;Schedule&gt;();\n\n schedules.Add(new Schedule { FlightNumber = flightNo++, Departure = \"YUL\", Arrival = \"YYZ\", Day = day, IsLoaded = false });\n schedules.Add(new Schedule { FlightNumber = flightNo++, Departure = \"YUL\", Arrival = \"YYC\", Day = day, IsLoaded = false });\n schedules.Add(new Schedule { FlightNumber = flightNo++, Departure = \"YUL\", Arrival = \"YVR\", Day = day, IsLoaded = false });\n\n day++;\n schedules.Add(new Schedule { FlightNumber = flightNo++, Departure = \"YUL\", Arrival = \"YYZ\", Day = day, IsLoaded = false });\n schedules.Add(new Schedule { FlightNumber = flightNo++, Departure = \"YUL\", Arrival = \"YYC\", Day = day, IsLoaded = false });\n schedules.Add(new Schedule { FlightNumber = flightNo++, Departure = \"YUL\", Arrival = \"YVR\", Day = day, IsLoaded = false });\n\n return schedules;\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>class MenuManager\n{\n public virtual int DisplayAndRead(Menu menu)\n {\n Console.Clear();\n Console.WriteLine(\"======= {0} =======\\n\", menu.Header);\n\n foreach (var item in menu.Items)\n {\n Console.WriteLine(item);\n }\n\n Console.Write(\"\\nEnter your choice: \");\n\n int userInput;\n int.TryParse(Console.ReadLine(), out userInput);\n\n return userInput;\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>class InformationManager : MenuManager\n{\n public override int DisplayAndRead(Menu menu)\n {\n Console.WriteLine(menu.Header);\n\n foreach (var item in menu.Items)\n {\n Console.WriteLine(item);\n }\n\n Console.Write(\"\\nPress any key to return to main menu... \");\n Console.ReadKey();\n\n return 0;\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>class ScheduleManager\n{\n public static string LoadedMessage(Schedule schedule)\n {\n return $\"Schedule {schedule.FlightNumber} loaded\";\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>class ItinenaryManager\n{\n public static string Itinerary(Order order)\n {\n return order.IsNotLoaded() ? $\"order: {order.Code}, flightNumber: not scheduled\"\n : $\"order: {order.Code}, flightNumber: {order.Schedule.FlightNumber}, departure: {order.Schedule.Departure}, arrival: {order.Schedule.Arrival}, day: {order.Schedule.Day}\";\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>class InventoryManager\n{\n public IList&lt;Order&gt; Orders { get; private set; }\n public IList&lt;Flight&gt; FlightsScheduled { get; private set; }\n public IList&lt;Schedule&gt; Schedules { get; private set; }\n\n public InventoryManager()\n {\n FlightsScheduled = new List&lt;Flight&gt;();\n Schedules = new ScheduleRepository().GetSchedules();\n }\n\n public void ProcessFlightScheduleMenuUserChoice(int userChoice)\n {\n if (userChoice &gt; 0 &amp;&amp; userChoice &lt;= Schedules.Count)\n {\n var selectedSchedule = Schedules.FirstOrDefault(s =&gt; !s.IsLoaded &amp;&amp; s.FlightNumber == userChoice);\n if (selectedSchedule != null)\n {\n var scheduledFlight = new Flight(20, selectedSchedule);\n FlightsScheduled.Add(scheduledFlight);\n FlightsScheduled = FlightsScheduled.OrderBy(f =&gt; f.Schedule.FlightNumber).ToList();\n DisplayScheduleLoadedMessage(selectedSchedule);\n }\n }\n }\n\n public void DisplayScheduleLoadedMessage(Schedule schedule)\n {\n var menu = new Menu()\n {\n Items = new List&lt;string&gt;()\n {\n $\"{ScheduleManager.LoadedMessage(schedule)}\"\n }\n };\n\n new InformationManager().DisplayAndRead(menu);\n }\n\n public void DisplayLoadedSchedules()\n {\n var menu = new Menu()\n {\n Header = \"\\n======= Loaded schedules =======\\n\"\n };\n\n foreach (var flight in FlightsScheduled)\n {\n menu.Items.Add(flight.FlightSchedule());\n }\n\n new InformationManager().DisplayAndRead(menu);\n }\n\n public void DisplayFlightItineraries()\n {\n LoadOrdersInFlights();\n\n var menu = new Menu()\n {\n Header = \"\\n======= Flight itineraries =======\\n\"\n };\n\n foreach (var order in Orders)\n {\n menu.Items.Add(ItinenaryManager.Itinerary(order));\n }\n\n new InformationManager().DisplayAndRead(menu);\n }\n\n private void LoadOrdersInFlights()\n {\n Orders = new OrderRepository().GetOrders().OrderBy(o =&gt; o.Priority).ToList();\n\n foreach (var schedule in Schedules)\n {\n if (schedule.IsLoaded)\n {\n var loadedFlights = FlightsScheduled.Where(f =&gt; f.Schedule == schedule).ToList();\n\n foreach (var flight in loadedFlights)\n {\n var flightOrders = Orders.Where(o =&gt; o.IsNotLoaded() &amp;&amp; o.Destination == schedule.Arrival).Take(flight.Capacity).Select(o =&gt; { o.Schedule = schedule; return o; }).ToList();\n flight.Orders = flightOrders;\n }\n }\n }\n }\n\n public Menu GetFlightScheduleMenu()\n {\n var menu = new Menu\n {\n Header = \"Choose a schedule to load\"\n };\n\n foreach (var item in Schedules)\n {\n if (!item.IsLoaded)\n {\n menu.Items.Add(item.ToString());\n }\n }\n\n menu.ExitValue = Schedules.Count + 1;\n menu.Items.Add($\"{menu.ExitValue}. Main menu\");\n\n return menu;\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n var inventory = new InventoryManager();\n\n ReadMainMenuUserChoice(inventory);\n }\n\n private static void ReadMainMenuUserChoice(InventoryManager inventory)\n {\n int userChoice;\n Models.Menu menu = GetMainMenu();\n\n do\n {\n userChoice = new MenuManager().DisplayAndRead(menu);\n ProcessMainMenuUserChoice(userChoice, inventory);\n } while (userChoice != menu.ExitValue);\n }\n\n private static void ProcessMainMenuUserChoice(int userChoice, InventoryManager inventory)\n {\n switch (userChoice)\n {\n case 1:\n ReadFlightScheduleMenuUserChoice(inventory);\n break;\n case 2:\n inventory.DisplayLoadedSchedules();\n break;\n case 3:\n inventory.DisplayFlightItineraries();\n break;\n case 4:\n Environment.Exit(0);\n break;\n }\n }\n\n\n private static void ReadFlightScheduleMenuUserChoice(InventoryManager inventory)\n {\n int userChoice;\n Models.Menu menu;\n\n do\n {\n menu = inventory.GetFlightScheduleMenu();\n userChoice = new MenuManager().DisplayAndRead(menu);\n inventory.ProcessFlightScheduleMenuUserChoice(userChoice);\n } while (userChoice != menu.ExitValue);\n }\n\n private static Models.Menu GetMainMenu()\n {\n var menu = new Models.Menu\n {\n Header = \"Transport.ly\",\n Items = new List&lt;string&gt;()\n {\n \"1. Load a schedule\",\n \"2. List out loaded flight schedules\",\n \"3. Generate flight itineraries\",\n }\n };\n\n menu.ExitValue = menu.Items.Count + 1;\n menu.Items.Add($\"{menu.ExitValue}. Exit\");\n\n return menu;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Please check code below each comment and know how to write it. I should suggest you to use <strong>ReSharper</strong> for Visual Studio. It will help you to make your code little better and inform about code issues. However, <strong>ReSharper</strong> can’t implement any principles or design patters.</p>\n\n<p>I hope you've read other comments, so I've skipped those.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-24T15:24:16.427", "Id": "231268", "ParentId": "230982", "Score": "2" } } ]
{ "AcceptedAnswerId": "231268", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T04:02:16.960", "Id": "230982", "Score": "7", "Tags": [ "c#", "object-oriented", "interview-questions" ], "Title": "Inventory coding interview exercicse" }
230982
<p>My task was : Create a Python application to display the active status of your IT project. Everyone the project has its own unique number that is generated at the stage of receipt project into the company. The company offers three types of project implementation: Standard Project, 10 Day Project, and Investor Project. "Project for 10 days "has a markup of 60% of the total cost of the project, and" Project for investor ”provides a 20% discount for the customer, if available investor company. If the investment does not meet the deadlines, the company bears losses - 5% of the project cost for each overdue week. The program must provide the user with the following functionality:</p> <p>-show projects by id</p> <p>-type of project and his price</p> <p>-your data must be saved in json format </p> <p>I want you to give me some recommendations about this code.This is my code.</p> <pre><code>**#Data_module.py** import random import datetime #dict in which i will save project data json_data={} class StandartProject(): '''Base class of projects''' def __init__(self,price,deadline): #random indentificator of every project self.id=self.create_id() #start price of project self.price=price self.deadline=deadline #price after calculating of difference self.__endprice=None self.handler_end_price() def create_id(self): while True : id = random.randint(10000,99999) if id not in json_data: return id @property def endprice(self): return self.__endprice @endprice.setter def endprice(self,value): if 0&lt;value: self.__endprice=value else: self.__endprice=0 def __str__(self): return 'Standart' def handler_end_price(self): '''calculate weeks difference to fine new price''' today=datetime.datetime.today() deadline=datetime.datetime.strptime(self.deadline,"%d.%m.%Y") time_delta=(deadline-today).days # obj delta with attribute days if time_delta&lt;0: weeks_later=abs(time_delta)//7 self.endprice=self.price*(1-weeks_later*0.05) #value can be "-" (fixed in property) else: self.endprice=self.price class TenDaysProject(StandartProject): def __init__(self,price,deadline,bonus=1.6): StandartProject.__init__(self,price,deadline) self.price*=bonus def __str__(self): return "TenDays" class InvestorsProgect(StandartProject): def __init__(self,price,deadline,bonus=0.8): StandartProject.__init__(self,price,deadline) self.price*=bonus def __str__(self): return "Investors" #**main_file.py** import sys from design import * from PyQt5 import QtCore, QtGui, QtWidgets import Data_module import inspect import random import json from Data_module import json_data TYPES_PROJECTS_DICT = {cls.__name__: cls for cls in Data_module.__dict__.values() if inspect.isclass(cls) and issubclass(cls, Data_module.StandartProject)} class MyWin(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.ui = Ui_Form() self.ui.setupUi(self) self.setFixedSize(500, 500) self.setObjectName('MainWidget') self.setStyleSheet('''#MainWidget { background-color: #267; }''') # key - str format of project class ; value - class for key in TYPES_PROJECTS_DICT: self.ui.comboBox_type.addItem(key) # self.ui.tabWidget.indexOf(self.ui.tab).clicked.connect(self.print__) self.ui.pushButton_add.clicked.connect(self.addProject) self.ui.pushButton_find.clicked.connect(self.handler_find_button) self.ui.pushButton_clear.clicked.connect(self.ui.textEdit_result.clear) # self.ui.pushButton_del_item.clicked.connect(self.handler_del_item) def closeEvent(self, event, *args, **kwargs): reply = QtWidgets.QMessageBox.question( self, "Message", "Do you want to save your Projects Data ?", QtWidgets.QMessageBox.Save | QtWidgets.QMessageBox.Close , QtWidgets.QMessageBox.Save) if reply==QtWidgets.QMessageBox.Save: self.write_json_data() event.accept() def handler_find_button(self): id = int(self.ui.lineEdit_id.text()) if 9999 &lt; id &lt; 100000 and (id in json_data): # ! result = "" for key, value in json_data[id].items(): result += str(key) + " = " + str(value) + "\n" self.ui.textEdit_result.setText(result) '''self.ui.textEdit_result.setText(f"Searched id = {id}" f"Type = {json_data[id][]}")''' else: self.ui.textEdit_result.setText("Write correct id :)") self.ui.lineEdit_id.setText("") def write_one_data_in_table(self, id, data=json_data): raw = len(json_data) - 1 # when our table hasn't any empty rows if raw == (self.ui.tableWidget.rowCount() - 1): pass self.ui.tableWidget.setItem(raw, 0, QtWidgets.QTableWidgetItem(str(id))) data = list(json_data[id].values()) for column in range(len(data)): self.ui.tableWidget.setItem(raw, column + 1, QtWidgets.QTableWidgetItem(str(data[column]))) '''def write_all_date_in_table(self, data=json_data): raw = 0 for key in json_data: raw += 1 self.ui.tableWidget.setItem(raw, 0, QtWidgets.QTableWidgetItem(str(key))) tmp_list = list(json_data[key].values()) for column in range(len(tmp_list)): self.ui.tableWidget.setItem(raw, column + 1, QtWidgets.QTableWidgetItem(str(tmp_list[column])))''' def addProject(self): TYPE, base_price, deadline = self.collectingProjectData() obj = TYPES_PROJECTS_DICT[TYPE](base_price, deadline) json_data[obj.id] = {"Type": TYPE, "Price": base_price, "EndPrice": obj.endprice, "Deadline": obj.deadline } # import pprint # pprint.pprint(json_data,indent=4) self.write_one_data_in_table(obj.id) def write_json_data(self, data=json_data): with open("data_file.json", "w") as write_file: json.dump(data, write_file) '''def get_data_now(self): return QtCore.QDate.currentDate()''' def collectingProjectData(self): TYPE = self.ui.comboBox_type.currentText() base_price = self.ui.spinBox_baseprice.value() deadline = self.ui.dateEdit_deadline.date().toString("dd.MM.yyyy") return TYPE, base_price, deadline if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) myapp = MyWin() myapp.show() sys.exit(app.exec_()) **#design.py** from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(478, 475) self.tabWidget = QtWidgets.QTabWidget(Form) self.tabWidget.setGeometry(QtCore.QRect(10, 10, 480, 480)) self.tabWidget.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.tabWidget.setObjectName("tabWidget") self.tab = QtWidgets.QWidget() self.tab.setObjectName("tab") self.verticalLayout = QtWidgets.QVBoxLayout(self.tab) self.verticalLayout.setObjectName("verticalLayout") self.label_tab1_projects = QtWidgets.QLabel(self.tab) font = QtGui.QFont() font.setPointSize(14) self.label_tab1_projects.setFont(font) self.label_tab1_projects.setAlignment(QtCore.Qt.AlignCenter) self.label_tab1_projects.setObjectName("label_tab1_projects") self.verticalLayout.addWidget(self.label_tab1_projects) self.tableWidget = QtWidgets.QTableWidget(self.tab) self.tableWidget.setObjectName("tableWidget") self.tableWidget.setColumnCount(6) self.tableWidget.setRowCount(12) self.tableWidget.setHorizontalHeaderLabels(["Id", "Type", "Price", "EndPrice", "Deadline", "WorkDoneReally"]) self.verticalLayout.addWidget(self.tableWidget) self.tabWidget.addTab(self.tab, "") self.tab_2 = QtWidgets.QWidget() self.tab_2.setObjectName("tab_2") self.label_tab2_Type = QtWidgets.QLabel(self.tab_2) self.label_tab2_Type.setGeometry(QtCore.QRect(40, 60, 91, 21)) font = QtGui.QFont() font.setPointSize(12) self.label_tab2_Type.setFont(font) self.label_tab2_Type.setObjectName("label_tab2_Type") self.spinBox_baseprice = QtWidgets.QSpinBox(self.tab_2) self.spinBox_baseprice.setGeometry(QtCore.QRect(260, 100, 141, 31)) self.spinBox_baseprice.setMaximum(100000) self.spinBox_baseprice.setMinimum(1) self.spinBox_baseprice.setObjectName("spinBox_baseprice") self.dateEdit_done = QtWidgets.QDateEdit(self.tab_2) self.dateEdit_done.setGeometry(QtCore.QRect(260, 200, 141, 31)) self.dateEdit_done.setMinimumDate(QtCore.QDate(2019, 10, 2)) self.dateEdit_done.setObjectName("dateEdit_done") self.label_tab2_defdline = QtWidgets.QLabel(self.tab_2) self.label_tab2_defdline.setGeometry(QtCore.QRect(40, 160, 71, 21)) font = QtGui.QFont() font.setPointSize(12) self.label_tab2_defdline.setFont(font) self.label_tab2_defdline.setObjectName("label_tab2_deadline") self.label_tab2_workwillbe = QtWidgets.QLabel(self.tab_2) self.label_tab2_workwillbe.setGeometry(QtCore.QRect(40, 200, 151, 31)) font = QtGui.QFont() font.setPointSize(12) self.label_tab2_workwillbe.setFont(font) self.label_tab2_workwillbe.setObjectName("label_tab2_workwillbe") self.comboBox_type = QtWidgets.QComboBox(self.tab_2) self.comboBox_type.setGeometry(QtCore.QRect(260, 50, 141, 31)) self.comboBox_type.setObjectName("comboBox_type") self.label_tab2_baseprise = QtWidgets.QLabel(self.tab_2) self.label_tab2_baseprise.setGeometry(QtCore.QRect(40, 110, 91, 20)) font = QtGui.QFont() font.setPointSize(12) self.label_tab2_baseprise.setFont(font) self.label_tab2_baseprise.setObjectName("label_tab2_baseprise") self.label_tab2_addingprojects = QtWidgets.QLabel(self.tab_2) self.label_tab2_addingprojects.setGeometry(QtCore.QRect(10, 0, 431, 31)) font = QtGui.QFont() font.setPointSize(14) font.setItalic(True) self.label_tab2_addingprojects.setFont(font) self.label_tab2_addingprojects.setAlignment(QtCore.Qt.AlignCenter) self.label_tab2_addingprojects.setObjectName("label_tab2_addingprojects") self.dateEdit_deadline = QtWidgets.QDateEdit(self.tab_2) self.dateEdit_deadline.setGeometry(QtCore.QRect(260, 150, 141, 31)) self.dateEdit_deadline.setMinimumDateTime(QtCore.QDateTime(QtCore.QDate(2017, 10, 1), QtCore.QTime(0, 0, 0))) self.dateEdit_deadline.setMinimumDate(QtCore.QDate(2017, 10, 1)) self.dateEdit_deadline.setObjectName("dateEdit_deadline") self.pushButton_add = QtWidgets.QPushButton(self.tab_2) self.pushButton_add.setGeometry(QtCore.QRect(40, 280, 361, 31)) self.pushButton_add.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.pushButton_add.setObjectName("pushButton_add") self.tabWidget.addTab(self.tab_2, "") self.tab_3 = QtWidgets.QWidget() self.tab_3.setObjectName("tab_3") self.label_writeid = QtWidgets.QLabel(self.tab_3) self.label_writeid.setGeometry(QtCore.QRect(20, 20, 131, 41)) font = QtGui.QFont() font.setPointSize(14) self.label_writeid.setFont(font) self.label_writeid.setObjectName("label_writeid") self.lineEdit_id = QtWidgets.QLineEdit(self.tab_3) self.lineEdit_id.setGeometry(QtCore.QRect(170, 30, 181, 21)) self.lineEdit_id.setMaxLength(5) self.lineEdit_id.setValidator(QtGui.QIntValidator(10000,99999)) self.lineEdit_id.setObjectName("lineEdit_id") self.textEdit_result = QtWidgets.QTextEdit(self.tab_3) self.textEdit_result.setGeometry(QtCore.QRect(20, 120, 421, 251)) self.textEdit_result.setObjectName("textEdit_result") self.textEdit_result.setFontPointSize (16) self.textEdit_result.setReadOnly(True) self.label_result_table = QtWidgets.QLabel(self.tab_3) self.label_result_table.setGeometry(QtCore.QRect(20, 80, 421, 21)) font = QtGui.QFont() font.setPointSize(14) self.label_result_table.setFont(font) self.label_result_table.setObjectName("label_result_table") #self.pushButton_del_item = QtWidgets.QPushButton(self.tab_3) #self.pushButton_del_item.setGeometry(QtCore.QRect(20, 390, 191, 23)) #self.pushButton_del_item.setObjectName("pushButton_del_item") self.pushButton_clear = QtWidgets.QPushButton(self.tab_3) self.pushButton_clear.setGeometry(QtCore.QRect(224, 390, 211, 23)) self.pushButton_clear.setObjectName("pushButton_clear") self.pushButton_find = QtWidgets.QPushButton(self.tab_3) self.pushButton_find.setGeometry(QtCore.QRect(360, 30, 81, 23)) self.pushButton_find.setObjectName("pushButton_find") self.tabWidget.addTab(self.tab_3, "") self.retranslateUi(Form) self.tabWidget.setCurrentIndex(1) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Form")) self.label_tab1_projects.setText(_translate("Form", "Projects ")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("Form", "Tab 1")) self.label_tab2_Type.setText(_translate("Form", "Type :")) self.label_tab2_defdline.setText(_translate("Form", "Dedline :")) self.label_tab2_workwillbe.setText(_translate("Form", "Work will be done :")) self.label_tab2_baseprise.setText(_translate("Form", "Base price :")) self.label_tab2_addingprojects.setText(_translate("Form", "Adding Projects")) self.pushButton_add.setText(_translate("Form", "ADD")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("Form", "Tab 2")) self.label_writeid.setText(_translate("Form", "Write Id :")) self.label_result_table.setText(_translate("Form", "Result table :")) #self.pushButton_del_item.setText(_translate("Form", "Delete item")) self.pushButton_clear.setText(_translate("Form", "Clear \"Result table\"")) self.pushButton_find.setText(_translate("Form", "Find")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("Form", "Tab 3")) </code></pre>
[]
[ { "body": "<p>Your data is saved in the file <code>data_file.json</code>, but when you re-enter you do not read the data to put it in the<code>tableWidget</code>.</p>\n\n<hr>\n\n<p>The <code>handler_find_button</code> method I would start like this:</p>\n\n<pre><code>def handler_find_button(self):\n if not self.ui.lineEdit_id.text():\n self.ui.textEdit_result.setText(\"Write correct id :)\")\n return\n ...\n</code></pre>\n\n<hr>\n\n<p>Shaping <code>id</code> randomly will cause you problems sooner or later. This is your key and should never be repeated!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T23:11:01.650", "Id": "231123", "ParentId": "230987", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T09:28:11.427", "Id": "230987", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "object-oriented", "pyqt" ], "Title": "Simple projects planner on PyQt5" }
230987
<p>I am trying to solve this problem:</p> <blockquote> <p>Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has.</p> <p>Unfortunately, Igor could only get <em>v</em> liters of paint. He did the math and concluded that digit <em>d</em> requires <span class="math-container">\$a_d\$</span> liters of paint. Besides, Igor heard that Tanya doesn't like zeroes. That's why Igor won't use them in his number.</p> <p>Help Igor find the maximum number he can write on the fence.</p> <p>Input The first line contains a positive integer <em>v</em> (0 ≤ v ≤ <span class="math-container">\$10^6\$</span>). The second line contains nine positive integers <span class="math-container">\$a_1\$</span>, <span class="math-container">\$a_2\$</span>, ..., <span class="math-container">\$a_9\$</span> (1 ≤ <span class="math-container">\$a_i\$</span> ≤ <span class="math-container">\$10^5\$</span>).</p> <p>Output Print the maximum number Igor can write on the fence. If he has too little paint for any digit (so, he cannot write anything), print -1.</p> </blockquote> <p><a href="https://codeforces.com/problemset/problem/349/B" rel="nofollow noreferrer">https://codeforces.com/problemset/problem/349/B</a></p> <p>My solution that works correctly, but times out:</p> <pre><code>from collections import defaultdict v = int(input()) a = [int(i) for i in input().split()] cache = {} def dfs(v): if v in cache: return cache[v] res = 0 for i, num in enumerate(a): if num == v: res = max(res, i+1) if num &lt; v: x = dfs(v-num) if x &gt; 0: s = str(i+1) + str(x) else: s = str(i+1) sorted_nums = sorted([str(i) for i in s], reverse=True) l = int("".join(sorted_nums)) res = max(res, l) cache[v] = res return res ans = dfs(v) if ans == 0: print(-1) else: print(ans) </code></pre> <p>How do I optimize it in terms of time complexity?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T22:03:32.517", "Id": "450258", "Score": "0", "body": "Use maximum possible number of digits first (lowest price) then improve it as much as possible starting from highest order. It is `O(n)` no recursion, no DP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T23:57:18.270", "Id": "450259", "Score": "0", "body": "Largest time I have for my solution is 62ms." } ]
[ { "body": "<p><strong>General strategy for optimizations on programming challenges</strong></p>\n\n<p>To optimize your code, you need to be able to perform some measure on different inputs and you want to make sure your optimization does not break anything.</p>\n\n<p>You usually want both things to be performed easily - automatically and instantly if possible. This is usually possible with simple tests. For programming challenges, this is even simpler because they usually correspond to task with a well defined input and a well defined output and on top of that, examples may be provided.</p>\n\n<p>Thus, this leads to the general rule of thumb about desirable properties of your code:</p>\n\n<ul>\n<li><p>you want your code to be testable then</p></li>\n<li><p>you want your code to be tested (with potentially failing tests) then</p></li>\n<li><p>you want your code to be correct (all tests pass)</p></li>\n<li><p>you want your code to be fast</p></li>\n</ul>\n\n<p>Applying this to your code:</p>\n\n<ul>\n<li>define <code>dfs</code> as a function taking both inputs <code>a</code> and <code>v</code> as parameters</li>\n<li>write a function to test <code>dfs</code> using input/output like you did but also a function with automated tests based on the provided example</li>\n<li>rename <code>dfs</code> for something conveying the name of the problem solved without giving the implementation details</li>\n<li>see that having a cache breaks leads to wrong behavior when we want to call <code>dfs</code> with different inputs -> we can remove it for the time being</li>\n<li>we can see that the import is useless</li>\n</ul>\n\n<p>At this point, we have:</p>\n\n<pre><code>def max_nb_painted(v, a):\n \"\"\"Return the the maximum number Igor can write on the fence (or -1 if he has too little paint for any digit)\"\"\"\n res = 0\n for i, num in enumerate(a):\n if num == v:\n res = max(res, i+1)\n if num &lt; v:\n x = max_nb_painted(v-num, a)\n if x &gt; 0:\n s = str(i+1) + str(x)\n else:\n s = str(i+1)\n sorted_nums = sorted([str(i) for i in s], reverse=True)\n l = int(\"\".join(sorted_nums))\n res = max(res, l)\n return -1 if res == 0 else res\n\ndef test_max_nb_painted_io():\n \"\"\"Test based on std input/ouput.\"\"\"\n v = int(input())\n a = [int(i) for i in input().split()]\n print(max_nb_painted(v, a))\n\ndef test_max_nb_painted_auto():\n \"\"\"Automated tests.\"\"\"\n # Note: you could use a proper unit-tests framework for this\n print(max_nb_painted(5, [5, 4, 3, 2, 1, 2, 3, 4, 5]) == 55555)\n print(max_nb_painted(2, [9, 11, 1, 12, 5, 8, 9, 10, 6]) == 33)\n print(max_nb_painted(0, [1, 1, 1, 1, 1, 1, 1, 1, 1]) == -1)\n\ntest_max_nb_painted_auto()\n</code></pre>\n\n<p><strong>More tests</strong></p>\n\n<p>The provided tests only cover the case where the painted number contain a unique digit. Let's try to add other tests:</p>\n\n<pre><code> assert max_nb_painted(1, [1, 1, 1, 1, 1, 1, 1, 1, 1]) == 9\n assert max_nb_painted(1, [1, 1, 1, 1, 1, 1, 1, 1, 1]) == 9\n assert max_nb_painted(5, [2, 2, 2, 2, 2, 2, 2, 2, 3]) == 98\n assert max_nb_painted(50, [9, 10, 11, 12, 13, 14, 15, 16, 17]) == 61111\n assert max_nb_painted(70, [19, 20, 21, 22, 23, 24, 25, 26, 27]) == 961\n</code></pre>\n\n<p>Also, we can add tests with returned value as big as we want which can be useful for benchmark purposes:</p>\n\n<pre><code> n = 6 # Length of expected return value\n c = 1 # Cost per digit\n assert max_nb_painted(n * c, [c] * 9) == int(str(9) * n)\n</code></pre>\n\n<p><strong>A different algorithm</strong></p>\n\n<p>Instead of using dfs blingly, we can try to solve the issue manually and see how we'd do it.</p>\n\n<p>We can easily compute the length of the returned value based on the minimal cost in <code>a</code>.</p>\n\n<p>Also, if we want to improve the corresponding value, we'd do it from the left hand side.</p>\n\n<pre><code>def max_nb_painted(v, a):\n # Evaluate maximum length based on digit with minimal cost\n min_cost = min(a)\n max_len = v // min_cost\n if max_len == 0:\n return -1\n # The base would be to use only that digit\n # But we try to use bigger digits (from the left)\n min_dig = a.index(min_cost) + 1\n rem_v = v - max_len * min_cost\n n = 0\n for i in range(max_len):\n n = 10 * n + min_dig\n for digit, cost in reversed(list(enumerate(a, start=1))):\n if digit &gt;= min_dig:\n if cost - min_cost &lt;= rem_v:\n n += digit - min_dig\n rem_v += min_cost - cost\n break\n return n\n</code></pre>\n\n<p>This can be significatively improved. For instance, we could precompute the digits that may be useful in order not to iterate over the whole list:</p>\n\n<pre><code> relevant_digits = list(reversed([(digit, cost) for digit, cost in enumerate(a, start=1) if digit &gt; min_dig and cost - min_cost &lt;= rem_v]))\n for i in range(max_len):\n n = 10 * n + min_dig\n for digit, cost in relevant_digits:\n if cost - min_cost &lt;= rem_v:\n n += digit - min_dig\n rem_v += min_cost - cost\n break\n return n\n</code></pre>\n\n<p><strong>Conclusion</strong></p>\n\n<p>Despite multiple attempts, I did not reach anything better than \"Time limit exceeded on test 25\".</p>\n\n<p>I do not have any ideas left except maybe trying to be starter when picking <code>min_dig</code> (by starting from the right) or pruning the list of relevant digits when we update <code>rem_v</code>.</p>\n\n<p>My best try is:</p>\n\n<pre><code>def max_nb_painted(v, a):\n # Evaluate maximum length based on digit with minimal cost\n min_cost = min(a)\n max_len = v // min_cost\n if max_len == 0:\n return -1\n # The base would be to use only that digit\n # But we try to use bigger digits (from the left)\n v -= max_len * min_cost\n relevant_digits = []\n for digit, cost in reversed(list(enumerate(a, start=1))):\n delta_cost = cost - min_cost\n if delta_cost &lt;= v:\n if delta_cost == 0:\n min_dig = digit\n break\n relevant_digits.append((digit, delta_cost))\n n = 0\n for i in range(max_len):\n n *= 10\n for digit, delta_cost in relevant_digits:\n if delta_cost &lt;= v:\n n += digit\n v -= delta_cost\n relevant_digits = [(digit, delta_cost) for digit, delta_cost in relevant_digits if delta_cost &lt;= v]\n break\n else:\n n += min_dig \n return n\n</code></pre>\n\n<p>but it is not good enough :(</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T06:14:01.060", "Id": "450271", "Score": "0", "body": "Have you even tried you solution on codeforces? Do you imagine how long dealing with big numers will take? Have you any idea what complexity you have?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T09:32:05.460", "Id": "450276", "Score": "0", "body": "@outoftime Thanks for the suggestion. Initially I did want to bother registering to codeforces but I should have." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T23:39:53.627", "Id": "231024", "ParentId": "230991", "Score": "1" } }, { "body": "<p>There is no need to comment your code. It is totally broken. Very first thing you need to do is to calculate your complexity. ACM is not about code quality, it is not about language. It is about algorithms. You can write the ugliest code ever but can it be executed? Not a problem if you have <em>satisfying algorithm complexity</em>.</p>\n\n<p>You can not just write different code without thinking about the algorithm and how your changes influence complexity. Moreover, you have to write code that will follow your algorithm.</p>\n\n<p>General strategies for optimizing code for programming challenges? What? If there where such strategies no one would be challenging anymore. That is why it is so difficult and those competitions exist even now.</p>\n\n<p>There are classes of problems that can be solved effectively with specific algorithm\\approach. Competition task itself never describes what class or problems it is and what algorithm to use, you have to find it out by yourself. Determine the class of the problem you are trying to solve and then choose an algorithm that will satisfy the problem's memory/time requirements.</p>\n\n<p>First of all. The problem you are trying to solve can be recognized as \"implementation\" when it didn't relate to any specific class directly. You have to do what it says. Implementation class requires you to be flexible minded, especially in this case because you have time requirements that brute-force didn't meet. </p>\n\n<h2>Algorithm</h2>\n\n<p>We have a set of digits with their costs. How to construct the largest possible number from it? We have to research the relation between numbers order and digits they have.</p>\n\n<p><span class=\"math-container\">$$ \nA &gt; B =\n\\begin{cases}\n true &amp; \\text{if } dc(A) &gt; dc(B) &amp; \\text{(1)}\n \\\\\n true &amp; \\text{if } dc(A) = dc(B) \\text{ and } \\\\\n &amp; \\text{if } h(A) &gt; h(B) \\text{ or } h(A) = h(B) \\text{ and } t(A) &gt; t(B) &amp; \\text{(2)}\n \\\\\n false &amp; \\text{else}\n\\end{cases}\n$$</span></p>\n\n<p>, where <br>\n<span class=\"math-container\">\\$ X = \\left( x_1, x_2, \\dots, x_n \\right) \\$</span> - number or vector of <span class=\"math-container\">\\$ n \\$</span> digits <br>\n<span class=\"math-container\">\\$ dc(X) = |X| = n \\$</span> - is number of digits in number (digits count) <br>\n<span class=\"math-container\">\\$ h(X) = x_1 \\$</span> - returns digit of the highest order (head), e.g. <span class=\"math-container\">\\$ h(123) = 1 \\$</span> <br>\n<span class=\"math-container\">\\$ t(X) = X' = \\left( x_2, \\dots, x_n \\right) \\$</span> - returns number without the highest order digit (tail), e.g. <span class=\"math-container\">\\$ t(123) = 23 \\$</span></p>\n\n<p>Let's look at those rules and figure out rules that will give us the biggest possible number using the given set of digits.</p>\n\n<p><span class=\"math-container\">\\$ \\text{(1)} \\$</span> consequence: more digits you have - better. That means we have to be greedy and take as much as possible digits with the lowest price.</p>\n\n<p><span class=\"math-container\">\\$ \\text{(2)} \\$</span> consequence: is it obvious that some times we will have enough amount of paint to replace digit with the bigger one but not enough to add another one. Now we know that we have to replace digits starting from the number's head.</p>\n\n<p>Now let's take a look at how much digits we will have in the worst case. It is around <span class=\"math-container\">\\$ 10^6 \\$</span>. </p>\n\n<p>With such a number of characters to output, we can not output by a single character at a time because input\\output operations took too much time. I hope there is no need to prove that IO takes a long time.</p>\n\n<p>Let's consider using python's big numbers. We will not look at their implementation, just pretend that we have <span class=\"math-container\">\\$ 10^6 \\$</span> digits to write and we know exactly what is it.</p>\n\n<pre><code>start = time.time()\nnum = 1;\nfor _ in range(10**5):\n num = num * 10 + 1\nfinish = time.time()\nprint (finish - start)\n</code></pre>\n\n<p>Takes 4 seconds to complete and it is still <span class=\"math-container\">\\$ 10^5 \\$</span>. No, we can not use python's big integers.</p>\n\n<p>We can not build a string because it is <a href=\"https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str\" rel=\"nofollow noreferrer\">an immutable object</a> and we will copy it every time on change, same as with big integers.</p>\n\n<p>More or less acceptable will be to make a list with the required amount of digits in it and then use <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\"><code>str.join()</code></a>. Let's stick with this approach for a while and continue research.</p>\n\n<p>So, first, we will find the highest digit with the lowest price <span class=\"math-container\">\\$ d \\$</span>, determine the length of the resulting number <span class=\"math-container\">\\$ n = \\lfloor \\frac{v}{\\text{lowest cost}} \\rfloor \\$</span> and make a resulting list of <span class=\"math-container\">\\$ d \\$</span> repeated <span class=\"math-container\">\\$ n \\$</span> times.</p>\n\n<p>Now, while we have some paint to spare, we will loop through digits from the highest to lowest and try to replace as many head digits as possible.</p>\n\n<p>But yeah, now when we spell it, you can see that you do not actually need that list at all. You need to know how much digits to write and who it will be starting from the head of the result.</p>\n\n<p>One can say: \"hey, this is greedy problem class, not implementation\" - yeah we are all smart now.</p>\n\n<h1>Implementation</h1>\n\n<p>Here is my implementation of described algorithm:</p>\n\n<pre><code>from copy import deepcopy\n\n\nclass Digit(object):\n def __init__(self, _cost, _value):\n self.cost = _cost\n self.value = _value\n\n\ndef main():\n v = int(input())\n a = list(map(int, input().split()))\n a = tuple(Digit(cost, digit+1) for digit, cost in enumerate(a))\n low_digit = deepcopy(min(a, key=lambda digit: digit.cost*10 - digit.value))\n\n if low_digit.cost &gt; v:\n print(-1)\n return\n\n digits = v // low_digit.cost\n v -= digits * low_digit.cost\n for i in range(9):\n a[i].cost -= low_digit.cost\n low_digit.cost = 0\n\n for better in reversed(a):\n if better.cost &gt; 0 and better.value &gt; low_digit.value:\n count = v // better.cost\n v -= count * better.cost\n digits -= count\n print(str(better.value) * count, end='')\n print(str(low_digit.value) * digits)\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T10:25:33.263", "Id": "231034", "ParentId": "230991", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T11:20:37.213", "Id": "230991", "Score": "2", "Tags": [ "python", "algorithm", "time-limit-exceeded" ], "Title": "Color The Fence codeforces - TLE" }
230991
<p><strong>Problem:</strong> JavaScript does not provide a random BigInt so there is a need to generate a random BigInt within a given range that is evenly distributed.</p> <p><strong>Solution</strong> I have tried many algorithms with a emphasis on speed. The best solution builds an array of random Int32 converted to string and padded with zeros which are then joined converted to a BigInt with the return being <code>BitInt % range</code></p> <pre><code>function randBigInt2(range) { // returns BigInt 0 to (range non inclusive) var rand = [], digits = range.toString().length / 9 + 2 | 0; while (digits--) { rand.push(("" + (Math.random() * 1000000000 | 0)).padStart(9, "0")); } return BigInt(rand.join("")) % range; // Leading zeros are ignored } </code></pre> <p>As <code>Math.log</code> can not be used to get the number of digits in <code>range</code> I am forced to use a hack of converting <code>range</code> to a string and using the string length to get log<sub>10</sub></p> <p>The generated array of digits is at least 9 digits longer than the required <code>range</code> to counter the problem of bias to numbers that end in digits less than the least significant digit. Though the bias still exists, it is so small that I am unable to detect it in any tests.</p> <p>If the range is a multiple of 10 there is no bias</p> <p>The alternative function that uses BigInt in the calculation is about 2-4% slower.</p> <pre><code>function randBigInt(range) { var rand = 0n, digits = range.toString().length / 9 + 2 | 0; while(digits--) { rand *= 1000000000n; rand += BigInt(Math.random() * 1000000000 | 0); } return rand % range; } </code></pre> <p>Are there any flaws in my logic?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T18:06:40.833", "Id": "450489", "Score": "1", "body": "I'd use the entire meaningful part of Math.random - at least 15 digits are guaranteed by IEEE754 spec." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T11:54:26.067", "Id": "450576", "Score": "0", "body": "@wOxxOm Unfortunately BigInt math in JS is SLOW.. Using `rand += BigInt(Math.floor(Math.random() * 1e15));` 40% fewer iterations and will increase performance for small ranges by 50%. Its even at 1e140 and 20% slower at 1e1500. Also tried `rand += BigInt(Math.trunc(Math.random() * 1e15));` BigInt will not convert if there is a fractional component. Using the string `Math.random().toString()` gives 15 digits but will shorten the notation if it can eg 1e-14 so add overhead and thus nit worth it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-29T08:13:27.403", "Id": "473735", "Score": "0", "body": "I haven't done research in that regard, but I wonder if using `Crypto.getRandomValues()` with a `BigUint64Array` would be more efficient for very large numbers." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T11:22:25.203", "Id": "230992", "Score": "3", "Tags": [ "javascript", "performance", "random" ], "Title": "JavaScript random BigInt" }
230992
<p>In this class I made a webscraper for a cryptocurrency website to get the name and the price of each currency. There are maybe API's that I can also use, but I thought it is better to gain some knowledge doing it with scraping. </p> <pre><code>import requests from bs4 import BeautifulSoup import json class Coins: def __init__(self): self.url = "https://www.coinbase.com/price" self.new_list = [] # Check if I get a 200 status code and if so, create instance from bs4 def get_response(self): self.response = requests.get(self.url) if self.response: print("Access granted") self.soup = BeautifulSoup(self.response.text, 'lxml') else: print("Error") # Select the class and get the data def get_data(self): info = self.soup.find_all(class_="Header__StyledHeader-sc-1q6y56a-0 hZxUBM TextElement__Spacer-sc-18l8wi5-0 hpeTzd") # Here, I only want to get the name and the price of the crypto, I don't want to get other information and thats why I am using the modulo operator. for x,e in enumerate(info): if x % 3 == 2: # print("I dont need this information") pass else: self.new_list.append(e.text) return self.new_list # From the information that I got and appended into a list, make a dict def make_dict(self): self.my_dict = {self.new_list[x]:self.new_list[x + 1] for x in range(0, len(self.new_list), 2)} return self.my_dict # Save the data into a json file def save_data(self): with open('data.json','w') as output: json.dump(self.my_dict, output, indent=2) if __name__ == '__main__': test = Coins() test.get_response() test.get_data() test.make_dict() test.save_data() </code></pre> <p>One of my concern is: I try to access variables inside a method, is using <code>self</code> a good idea? For example in the method <code>save_data()</code>. I wanted to pass the function <code>get_data()</code> in <code>json.dump()</code> but it didn't work out. So I changed in <code>make_dict()</code> the variable to <code>self.my_dict</code> to access it in the method <code>save_data()</code> and it worked out, but is it a good practice or not at all?</p> <p>This is my first time actually working with classes. I appreciate any feedback to improve myself.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T12:49:35.550", "Id": "450217", "Score": "0", "body": "The use of `I tried` in the first sentence can indicate that the code is not working as intended. Code review is a site where only working code is reviewed. Is this code working as expected?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T12:54:31.413", "Id": "450219", "Score": "1", "body": "Yes, it is working as expected" } ]
[ { "body": "<p>Here is an alternate implementation:</p>\n\n<pre><code>#!/usr/bin/env python3\n\nfrom bs4 import BeautifulSoup\nfrom pprint import pprint\nimport re\nimport requests\n\n\nclass Coins:\n table_re = re.compile('^AssetTable__Table-')\n\n def __init__(self, url=\"https://www.coinbase.com/price\"):\n self.url = url\n self.session = requests.Session()\n\n # Check if I get a 200 status code and if so, create instance from bs4\n def _get_response(self) -&gt; BeautifulSoup:\n response = self.session.get(self.url)\n response.raise_for_status()\n return BeautifulSoup(response.text, 'lxml')\n\n # Select the class and get the data\n def get_data(self) -&gt; dict:\n soup = self._get_response()\n table = soup.find('table', attrs={'class': self.table_re})\n prices = {}\n for row in table.tbody.find_all('tr'):\n cells = row.find_all('td')\n if len(cells) &lt; 6:\n continue\n name = cells[1].find('h4').text\n price = cells[2].find('h4').text\n prices[name] = price\n return prices\n</code></pre>\n\n<p>Note:</p>\n\n<ul>\n<li>Do not rely on long, terrible, possibly dynamically-generated CSS class names</li>\n<li>If you want to reuse this class to repeatedly fetch prices, then the members should be the session and the URL, and the data should be restricted to the function</li>\n<li>Don't write <code>access granted</code>. Other than it being corny, you should only throw an exception if there's a failure, not write to <code>stdout</code> if there's a success in the data retrieval method. Such progress indicators are best left to the calling function above.</li>\n<li>Just index into the cells. Don't use the modulus.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T08:15:58.447", "Id": "450542", "Score": "1", "body": "Thanks for your notes. I appreciate the work that you have done for me. I will use your feedback to improve my coding." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T03:59:05.973", "Id": "231127", "ParentId": "230994", "Score": "2" } } ]
{ "AcceptedAnswerId": "231127", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T11:46:23.707", "Id": "230994", "Score": "3", "Tags": [ "python", "beautifulsoup" ], "Title": "Webscraping cryptocurrency" }
230994
<p>This is my OnAppearingAsync method where I as a page load in Xamarin I filter data, group it together, set data based on it, order the groups e.t.c. However the code is rather long and looks a bit messy, I've tried to refactor it myself but I always get stuck on where I'm supposed to start. </p> <p>How can I improve this? Everything works beautifully and efficiently as far I know, I just believe it would never pass any code review in current status (We don't have code review though)</p> <pre><code>public async Task OnAppearingAsync(string houseCode) { HouseCode = houseCode; var client = AppClientHelper.Get(); var groupHolders = new ObservableCollection&lt;SubBrandGroup&gt;(); // Get The Groups List&lt;SubBrandViewModel&gt; subBrandViewModels = client.GetSubBrandViewModels(HouseCode); // Filter the subBrands var filteredSubBrands = subBrandViewModels.Where(item =&gt; CurrentCustomerCardViewModel.AllowedCategories.AllowedSubBrands.Contains(item.Code)).ToList(); foreach (var subBrandViewModel in filteredSubBrands) { var basicItems = client.GetBaiscItemViewModelsBySubGroup(subBrandViewModel.HouseCode, subBrandViewModel.Code); // Apply the proper price, unique customer values e.t.c foreach (var basicItem in basicItems) { basicItem.PropertyChanged += OnOrderCountUpdate; await SetUniqueBrandStatusBrandStatus(basicItem); } // Order Item in SubGroup by alphabetical order var sortedItems = basicItems.OrderBy(item =&gt; item.Description).ToList(); SubBrandGroup subBrand = new SubBrandGroup(subBrandViewModel.Name, true, subBrandViewModel.AdditionalCollateralItem, sortedItems); // Add group if not empty if (subBrand.Count != 0) { groupHolders.Add(subBrand); } Currency = basicItems.FirstOrDefault()?.Currency; } if (groupHolders.Count == 0) return; // Order the groups int[] map = { 0, 2, 5, 3, 1, 4 }; // Sort the group var sortedGroups = groupHolders.OrderBy(x =&gt; map[(int)x.AdditionalCollateralItem]).ToList(); // Assign the new sorted items to the list ProductList = new ObservableCollection&lt;SubBrandGroup&gt;(sortedGroups); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T12:32:16.067", "Id": "230996", "Score": "2", "Tags": [ "c#", "object-oriented", "xaml", "xamarin" ], "Title": "Initializing Group Data Mess" }
230996
<p>Consider this example</p> <blockquote> <p>Suppose that 3 balls are randomly selected from an urn containing 3 red, 4 white, and 5 blue balls. If we let X and Y denote, respectively, the number of red and white balls chosen, then the joint probability mass function of <span class="math-container">\$X\$</span> and <span class="math-container">\$Y\$</span>, <span class="math-container">\$p(i,j) = P\{X=i,Y=j\}\$</span>, is given by</p> </blockquote> <p><a href="https://i.stack.imgur.com/ZrTif.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZrTif.png" alt="enter image description here"></a></p> <p>This code is to plot such a joint probability mass function table.</p> <pre><code>arr = np.empty((4,4), dtype='U30') sample_space = [] red_balls = 3 white_balls = 4 blue_balls = 5 for i in range(4): for j in range(4): r = comb(red_balls, i) w = comb(white_balls, j) b = comb(blue_balls, 3-i-j) result = int(r*w*b) arr[i][j] = r'$\dfrac{{{}}}{{{}}}$'.format(result, 220) sample_space.append(result) pd.DataFrame(arr) </code></pre> <p>And I got.</p> <p><a href="https://i.stack.imgur.com/uNN5x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uNN5x.png" alt="enter image description here"></a></p> <h1>question</h1> <p>if I want to compute the marginal probability I have to add another empty array which is inefficient, is there a better way to do that?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T14:03:20.387", "Id": "450221", "Score": "0", "body": "what is the issue?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T14:13:07.593", "Id": "450223", "Score": "6", "body": "In my opinion, hard-coding `220` is cheating." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T13:14:02.617", "Id": "455877", "Score": "1", "body": "What is `comb` in the code? Where does it come from?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T15:15:27.973", "Id": "455903", "Score": "1", "body": "As Georgy stated, please include the full code you have, this'll help provide a good review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T19:54:51.273", "Id": "455952", "Score": "0", "body": "Since you've hardcoded the `220`, this is expected. You didn't finish the assignment, you tried to hack your way around it. This code isn't finished." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T13:33:00.047", "Id": "230999", "Score": "1", "Tags": [ "python", "numpy", "pandas" ], "Title": "A python script to plot a joint probability mass function table" }
230999
<p>I am practicing Go and try to implement Boyer Moore Horspool Algorithm in Go, It returns all ocurrance of a "phrase" in a given text. This code is working, but I would be pleased to have any feedback and suggestions from Go Gurus, about all aspect of my code.</p> <pre><code>package boyer_moore_horspool_search type badMatchTable struct{ table [256]int pattern string } func newBadMatchTable(pattern string) *badMatchTable{ b := badMatchTable{ pattern: pattern, } b.table = [256]int{} b.table = b.generateTable() return &amp;b } func (b *badMatchTable) generateTable() [256]int{ for i := 0; i &lt; 256 ; i++ { b.table[i] = len(b.pattern) } lastPatternByte := len(b.pattern) - 1 for i := 0; i &lt; lastPatternByte ; i++ { b.table[int(b.pattern[i])] = lastPatternByte - i } return b.table } func Search(text string, pattern string) []int{ var indexes []int byteText := []byte(text) bytePattern := []byte(pattern) textLength := len(byteText) patternLength := len(bytePattern) if textLength == 0 || patternLength == 0 || patternLength &gt; textLength{ return indexes } lastPatternByte := patternLength - 1 mt := newBadMatchTable(pattern) index := 0 for index &lt;= (textLength - patternLength) { for i := lastPatternByte ; byteText[index + i] == bytePattern[i]; i-- { if i == 0{ indexes = append(indexes, index) break } } index += mt.table[byteText[index + lastPatternByte]] } return indexes } </code></pre> <p>And this is the test file:</p> <pre><code>import ( "fmt" "testing" ) func TestSearch(t *testing.T) { indexes := Search("Hello, we want to find word Guru, so this #phrase has the word Guru.", "word Guru") fmt.Printf("Occurance: %v\n", len(indexes)) for _, i := range indexes { fmt.Printf("Index: %v\n", i) } } </code></pre>
[]
[ { "body": "<p>I added</p>\n\n<pre><code>func BenchmarkSearch(b *testing.B) {\n c := \"Hello, we want to find word Guru, so this #phrase has the word Guru.\"\n s := \"word Guru\"\n for i := 0; i &lt; b.N; i++ {\n Search(c, s)\n }\n}\n</code></pre>\n\n<p>Then i ran</p>\n\n<pre><code>$ go test -v -bench=. -benchmem -memprofile=mem.out\n</code></pre>\n\n<p>It yielded </p>\n\n<pre><code>goos: linux\ngoarch: amd64\npkg: test/boyermoor\nBenchmarkSearch-4 2000000 780 ns/op 104 B/op 3 allocs/op\nPASS\nok test/boyermoor 2.360s\n</code></pre>\n\n<p>Now i open pprof to get detailed stats</p>\n\n<pre><code>$ go tool pprof mem.out\n\n(pprof) list Sear\nTotal: 268.52MB\nROUTINE ======================== test/boyermoor.BenchmarkSearch in /home/mh-cbon/gow/src/test/boyermoor/main_test.go\n 0 268.52MB (flat, cum) 100% of Total\n . . 18:\n . . 19:func BenchmarkSearch(b *testing.B) {\n . . 20: c := \"Hello, we want to find word Guru, so this #phrase has the word Guru.\"\n . . 21: s := \"word Guru\"\n . . 22: for i := 0; i &lt; b.N; i++ {\n . 268.52MB 23: Search(c, s)\n . . 24: }\n . . 25:}\nROUTINE ======================== test/boyermoor.Search in /home/mh-cbon/gow/src/test/boyermoor/main.go\n 268.52MB 268.52MB (flat, cum) 100% of Total\n . . 36:}\n . . 37:\n . . 38:func Search(text string, pattern string) []int {\n . . 39:\n . . 40: var indexes []int\n 208.52MB 208.52MB 41: byteText := []byte(text)\n . . 42: bytePattern := []byte(pattern)\n . . 43:\n . . 44: textLength := len(byteText)\n . . 45: patternLength := len(bytePattern)\n . . 46:\n . . 47: if textLength == 0 || patternLength == 0 || patternLength &gt; textLength {\n . . 48: return indexes\n . . 49: }\n . . 50:\n . . 51: lastPatternByte := patternLength - 1\n . . 52:\n . . 53: mt := newBadMatchTable(pattern)\n . . 54: index := 0\n . . 55: for index &lt;= (textLength - patternLength) {\n . . 56: for i := lastPatternByte; byteText[index+i] == bytePattern[i]; i-- {\n . . 57: if i == 0 {\n 60MB 60MB 58: indexes = append(indexes, index)\n . . 59: break\n . . 60: }\n . . 61: }\n . . 62:\n . . 63: index += mt.table[byteText[index+lastPatternByte]]\n</code></pre>\n\n<p>You have allocations that are totally superfluous, given current test case, and they could be avoided by changing the input parameters types.</p>\n\n<p>Lets give it a try</p>\n\n<p>The code is updated to</p>\n\n<pre><code>package main\n\nfunc main() {\n\n}\n\ntype badMatchTable struct {\n table [256]int\n pattern []byte\n}\n\nfunc newBadMatchTable(pattern []byte) *badMatchTable {\n b := badMatchTable{\n pattern: pattern,\n }\n\n b.table = [256]int{}\n b.table = b.generateTable()\n\n return &amp;b\n}\n\nfunc (b *badMatchTable) generateTable() [256]int {\n\n for i := 0; i &lt; 256; i++ {\n b.table[i] = len(b.pattern)\n }\n\n lastPatternByte := len(b.pattern) - 1\n\n for i := 0; i &lt; lastPatternByte; i++ {\n b.table[int(b.pattern[i])] = lastPatternByte - i\n }\n\n return b.table\n}\n\nfunc Search(text, pattern []byte) []int {\n\n var indexes []int\n\n textLength := len(text)\n patternLength := len(pattern)\n\n if textLength == 0 || patternLength == 0 || patternLength &gt; textLength {\n return indexes\n }\n\n lastPatternByte := patternLength - 1\n\n mt := newBadMatchTable(pattern)\n index := 0\n for index &lt;= (textLength - patternLength) {\n for i := lastPatternByte; text[index+i] == pattern[i]; i-- {\n if i == 0 {\n indexes = append(indexes, index)\n break\n }\n }\n\n index += mt.table[text[index+lastPatternByte]]\n }\n\n return indexes\n}\n</code></pre>\n\n<p>I behncmarked again</p>\n\n<pre><code>$ go test -v -bench=. -benchmem -memprofile=mem.out\ngoos: linux\ngoarch: amd64\npkg: test/boyermoor\nBenchmarkSearch-4 2000000 669 ns/op 24 B/op 2 allocs/op\nPASS\nok test/boyermoor 2.023s\n</code></pre>\n\n<p>Those are small improvements.</p>\n\n<p>I change the code again to remove the int slice allocation</p>\n\n<pre><code>package boyermoor\n\ntype badMatchTable struct {\n table [256]int\n pattern []byte\n}\n\nfunc newBadMatchTable(pattern []byte) *badMatchTable {\n b := badMatchTable{\n pattern: pattern,\n }\n\n b.table = [256]int{}\n b.table = b.generateTable()\n\n return &amp;b\n}\n\nfunc (b *badMatchTable) generateTable() [256]int {\n\n for i := 0; i &lt; 256; i++ {\n b.table[i] = len(b.pattern)\n }\n\n lastPatternByte := len(b.pattern) - 1\n\n for i := 0; i &lt; lastPatternByte; i++ {\n b.table[int(b.pattern[i])] = lastPatternByte - i\n }\n\n return b.table\n}\n\nfunc Search(text, pattern []byte, indexes []int) []int {\n\n // var indexes []int\n indexes = indexes[:0]\n\n textLength := len(text)\n patternLength := len(pattern)\n\n if textLength == 0 || patternLength == 0 || patternLength &gt; textLength {\n return indexes\n }\n\n lastPatternByte := patternLength - 1\n\n mt := newBadMatchTable(pattern)\n index := 0\n for index &lt;= (textLength - patternLength) {\n for i := lastPatternByte; text[index+i] == pattern[i]; i-- {\n if i == 0 {\n indexes = append(indexes, index)\n break\n }\n }\n\n index += mt.table[text[index+lastPatternByte]]\n }\n\n return indexes\n}\n</code></pre>\n\n<p>The benchmark is modified to</p>\n\n<pre><code>func BenchmarkSearch(b *testing.B) {\n indexes := make([]int, 0, 100)\n c := []byte(\"Hello, we want to find word Guru, so this #phrase has the word Guru.\")\n s := []byte(\"word Guru\")\n for i := 0; i &lt; b.N; i++ {\n indexes = Search(c, s, indexes)\n }\n}\n</code></pre>\n\n<p>Now i got</p>\n\n<pre><code>goos: linux\ngoarch: amd64\npkg: test/boyermoor\nBenchmarkSearch-4 3000000 597 ns/op 0 B/op 0 allocs/op\nPASS\nok test/boyermoor 2.402s\n</code></pre>\n\n<p>That is more substantial.</p>\n\n<p>In the details, you rewrite the generateTable this way to save a few more ops</p>\n\n<pre><code>func (b *badMatchTable) generateTable() [256]int {\n\n k := len(b.pattern)\n for i := 0; i &lt; 256; i++ {\n b.table[i] = k\n }\n\n lastPatternByte := k - 1\n\n for i := 0; i &lt; lastPatternByte; i++ {\n b.table[b.pattern[i]] = lastPatternByte - i\n }\n\n return b.table\n}\n</code></pre>\n\n<p>At that point, consider that your algorithm is 1/ cpu bound 2/ a bunch of tight loops. So to get much out of the runtime, squeeze as many instructions as possible.</p>\n\n<p>Given the last state of the code, let just get ride of the <code>badTable</code> struct. So the whole thing is contained into one function call.</p>\n\n<pre><code>func Search(text, pattern []byte, indexes []int) []int {\n\n // var indexes []int\n indexes = indexes[:0]\n\n textLength := len(text)\n patternLength := len(pattern)\n\n if textLength == 0 || patternLength == 0 || patternLength &gt; textLength {\n return indexes\n }\n\n lastPatternByte := patternLength - 1\n\n table := [256]int{}\n {\n k := len(pattern)\n for i := 0; i &lt; 256; i++ {\n table[i] = k\n }\n\n lastPatternByte := k - 1\n for i := 0; i &lt; lastPatternByte; i++ {\n table[pattern[i]] = lastPatternByte - i\n }\n }\n\n index := 0\n for index &lt;= (textLength - patternLength) {\n for i := lastPatternByte; text[index+i] == pattern[i]; i-- {\n if i == 0 {\n indexes = append(indexes, index)\n break\n }\n }\n\n index += table[text[index+lastPatternByte]]\n }\n\n return indexes\n}\n</code></pre>\n\n<p>And now it gives us</p>\n\n<pre><code>goos: linux\ngoarch: amd64\npkg: test/boyermoor\nBenchmarkSearch-4 5000000 339 ns/op 0 B/op 0 allocs/op\nBenchmarkSearch-4 5000000 340 ns/op 0 B/op 0 allocs/op\nBenchmarkSearch-4 5000000 341 ns/op 0 B/op 0 allocs/op\nBenchmarkSearch-4 5000000 338 ns/op 0 B/op 0 allocs/op\nPASS\n</code></pre>\n\n<p>Now we have a good 2 times improvement.</p>\n\n<p>But this is not all about performance, it is also about usability for other devs. So the API can be presented this way, which produces a decent trade between the two.</p>\n\n<pre><code>type Horspool struct {\n table [256]int\n indexes []int\n}\n\nfunc (t *Horspool) Search(text, pattern []byte) []int {\n\n table := t.table\n indexes := t.indexes\n if cap(indexes) &lt; 1 {\n indexes = make([]int, 0, 100)\n }\n indexes = indexes[:0]\n\n textLength := len(text)\n patternLength := len(pattern)\n\n if textLength == 0 || patternLength == 0 || patternLength &gt; textLength {\n t.indexes = indexes\n return indexes\n }\n\n lastPatternByte := patternLength - 1\n\n {\n for i := 0; i &lt; 256; i++ {\n table[i] = patternLength\n }\n\n lastPatternByte := patternLength - 1\n for i := 0; i &lt; lastPatternByte; i++ {\n table[pattern[i]] = lastPatternByte - i\n }\n }\n\n index := 0\n for index &lt;= (textLength - patternLength) {\n for i := lastPatternByte; text[index+i] == pattern[i]; i-- {\n if i == 0 {\n indexes = append(indexes, index)\n break\n }\n }\n\n index += table[text[index+lastPatternByte]]\n }\n t.indexes = indexes\n return indexes\n}\n</code></pre>\n\n<p>It gives me a slightly slower program</p>\n\n<pre><code>BenchmarkSearch-4 5000000 370 ns/op 0 B/op 0 allocs/op\n</code></pre>\n\n<p>I have not tried to understand as to why it is slower because here is a more interesting case involving struct alignment and padding. See this code,</p>\n\n<pre><code>type Horspool struct {\n indexes []int\n table [256]int\n}\n</code></pre>\n\n<p>And check the results</p>\n\n<pre><code>BenchmarkSearch-4 3000000 480 ns/op 0 B/op 0 allocs/op\n</code></pre>\n\n<p>read more: <a href=\"https://dave.cheney.net/2015/10/09/padding-is-hard\" rel=\"nofollow noreferrer\">https://dave.cheney.net/2015/10/09/padding-is-hard</a></p>\n\n<p>FTR, consider this is an old algorithm and that it is not utf-8 valid. Go being utf-8 first, this should be improved.</p>\n\n<p>If my understanding of the algorithm is correct, the fix is rather simple</p>\n\n<pre><code>type Horspool struct {\n table map[rune]int\n indexes []int\n}\n\nfunc (t *Horspool) Search(text, pattern []rune) []int {\n\n table := t.table\n if table == nil {\n table = map[rune]int{}\n } else {\n for r := range table {\n delete(table, r)\n }\n }\n indexes := t.indexes\n if cap(indexes) &lt; 1 {\n indexes = make([]int, 0, 100)\n }\n indexes = indexes[:0]\n\n textLength := len(text)\n patternLength := len(pattern)\n\n if textLength == 0 || patternLength == 0 || patternLength &gt; textLength {\n return indexes\n }\n\n lastPatternByte := patternLength - 1\n\n {\n for _, r := range pattern {\n table[r] = patternLength\n }\n\n for i := 0; i &lt; lastPatternByte; i++ {\n table[pattern[i]] = patternLength - 1 - i\n }\n }\n\n index := 0\n for index &lt;= (textLength - patternLength) {\n for i := lastPatternByte; text[index+i] == pattern[i]; i-- {\n if i == 0 {\n indexes = append(indexes, index)\n break\n }\n }\n x, ok := table[text[index+lastPatternByte]]\n if ok {\n index += x\n } else {\n index += lastPatternByte\n }\n }\n t.table = table\n t.indexes = indexes\n return indexes\n}\n</code></pre>\n\n<p>But, take care of maps. \n<a href=\"https://stackoverflow.com/questions/58475257/map-delete-doesnt-actually-delete-entries\">https://stackoverflow.com/questions/58475257/map-delete-doesnt-actually-delete-entries</a></p>\n\n<p>Use a simple counter to free-it-by-allocation regularly.</p>\n\n<p>Finally, as somewhat expected the code is slower by a factor 2</p>\n\n<pre><code>goos: linux\ngoarch: amd64\npkg: test/boyermoor\nBenchmarkSearch-4 2000000 756 ns/op 0 B/op 0 allocs/op\nPASS\nok test/boyermoor 2.282s\n</code></pre>\n\n<p>Two notes:</p>\n\n<ul>\n<li>There might be more interesting/subtle optimizations that i m not aware of myself, i did the obvious.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T16:26:54.817", "Id": "450301", "Score": "0", "body": "Thank you, how do you call your Search func, so it has 0 alloc? I changed my Search fun to your version, but it still has allocs/op. (talking about the version you mentioned you got 0 alloc)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T16:32:43.550", "Id": "450303", "Score": "1", "body": "I preallocated it. If you don't preallocate, go runtime will allocate when you `append`. see https://stackoverflow.com/a/38654841/4466350 (i updated my answer). But anyways, what matter most is that you understand the overall procedure to optimize your go code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T16:36:20.973", "Id": "450305", "Score": "1", "body": "you can also check for online resources like https://github.com/dgryski/go-perfbook to get more ideas" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T14:40:57.550", "Id": "231039", "ParentId": "231000", "Score": "3" } } ]
{ "AcceptedAnswerId": "231039", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T14:22:23.523", "Id": "231000", "Score": "7", "Tags": [ "algorithm", "strings", "go", "search" ], "Title": "Boyer Moore Horspool Search Algorithm in Go" }
231000
<p>I am learning C# and for an experiment I tried implementing the Caesar Cypher cryptography method which just offsets every character of the string <em>n</em> characters. How can I make this simple program better?</p> <pre><code>string original = Console.ReadLine(); string encrypted = ""; int key = 1; foreach (var l in original) { if (!l.Equals(' ')) { if (l.Equals('z')) { char next = 'a'; encrypted += next; } else { double next = (int)l + key; encrypted += (char)next; } } else { encrypted += ' '; } } Console.WriteLine(encrypted); </code></pre>
[]
[ { "body": "<p>Afew things I noticed:</p>\n\n<p>Concatenating strings using the plus operator(<code>+</code>), is very inefficient. Each concatenation creates a new string. This due to strings being immutable. Using a <code>char</code> array or the <code>StringBuilder</code> is much more efficient.</p>\n\n<p>The variable <code>next</code> is a <code>double</code> but the value you're assigning to it is 2 ints added together. It would make much more sense to have this as a <code>char</code>. In fact you should declare this before the <code>if</code> block to be able to use it in each condition.</p>\n\n<p><code>Equals</code> isn't doing what you appear to think it does. <code>Equals</code> is for testing whether 2 objects are the same. <code>==</code> is for testing whether 2 objects values are the same.</p>\n\n<p>You appear to expect only lower case characters and spaces. However you don't seem to have any mechanism for testing whether the string complies with that.</p>\n\n<p>You can simplify getting the replacement character by using the modulus(<code>%</code>) operator. Something like this should work: <code>newChar = (char)(((oldChar - 'a') + key) % 26) + 'a'</code></p>\n\n<p>Your code won't work right if the string has words from a language that uses two bytes to represent one character.</p>\n\n<p>Right now you've hardcoded the key. It would be better to have a method that takes the string and the key as parameters.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T20:45:04.887", "Id": "231019", "ParentId": "231001", "Score": "3" } }, { "body": "<p><strong>Think Objects</strong></p>\n\n<p>This problem has 2, readily apparent, main parts, the message to be encrypted and the \"cipher machine\" that encrypts it. <strong>Thinking through the problem identifying its parts</strong> is the way to start out on the Yellow Brick Road of OO goodness. So we already have enough start writing code!</p>\n\n<pre><code>public string message;\n\npublic class CaesarCipher {\n public string encrypt (string clearText) { ... }\n}\n</code></pre>\n\n<p>Now it's suddenly obvious we need to decrypt too!</p>\n\n<pre><code>public class CaesarCipher {\n public string encrypt (string clearText) { ... }\n public string decrypt (string secretText) { ... }\n} \n</code></pre>\n\n<hr>\n\n<p>Your code is suggestive of <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.ienumerator?view=netframework-4.8\" rel=\"nofollow noreferrer\">the <code>IEnumerator</code> interface</a>, which has a <code>MoveNext()</code> method and <code>Current</code> (position) property. This allows <code>foreach</code> statements on a <code>CaesarCipher</code> object:</p>\n\n<pre><code>public class CaesarCipher : IEnumerator { ... }\n\nCaesarCipher littleOrphanAnnieDecoderRing = new CaesarCipher();\n\nforeach ( var alphaBit in littleOrphanAnnieDecoderRing ) { ... }\n</code></pre>\n\n<p>FORGET THIS FOR NOW. It's advanced and confusing. <a href=\"https://en.wikipedia.org/wiki/Caesar_cipher\" rel=\"nofollow noreferrer\">The Wikipedia article</a> shows a simple modulus arithmetic formula</p>\n\n<hr>\n\n<p><strong>Learn to count from zero and be a hero</strong></p>\n\n<p>If you can read a clock you know modulus arithmetic. The clock starts at 12 counts 1,2,3... and automatically resets at 12 and keeps going.</p>\n\n<p>But ask any military person (me!) - the clock is 24 hours and starts at zero. So 12:35 am is \"zero thirty-five hours\". 00:00 is exactly midnight.</p>\n\n<p>Like the military, the programming world counts from zero. Modulus arithmetic works because we start with zero. For programming generally we avoid oodles of \"off by 1\" errors by starting with zero.</p>\n\n<hr>\n\n<p><strong>CaesarCipher details</strong></p>\n\n<p>.</p>\n\n<pre><code> public class CaesarCipher {\n public CaesarCipher( int encryptionKey );\n public string encrypt ( string clearText ) { ... }\n public string decrypt ( string secretText ) { ... }\n } \n</code></pre>\n\n<p>I leave implementation to you but here's the basics. </p>\n\n<p>A is zero, Z is 25, etc. This is a fixed reference. I think a single <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.array?view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>Array</code></a> would work. Read the documentation! Learn how to reference array elements and/or array element indexes.</p>\n\n<p>Pass an offset value to the constructor. Add the offset to encrypt, subtract the offset to decrypt. Or vice versa! See <a href=\"https://en.wikipedia.org/wiki/Caesar_cipher\" rel=\"nofollow noreferrer\">the Wikipedia article</a></p>\n\n<pre><code>littleOrphanAnnieDecoderRing = new CaesarCipher(3);\nstring scrambled = littleOrphanAnnieDecoderRing.encrypt(\"X\"); \nscrambled == \"A\"; // true\n</code></pre>\n\n<hr>\n\n<p><strong><em>Feel The Force</em></strong></p>\n\n<ul>\n<li><p>Viewing the real-world problem as interacting objects is very important. We want to identify functionality. Delay specific algorithm implementation details as much as practical.</p></li>\n<li><p>Note how OO is kinda \"outside - in\" approach while your code is definitely \"inside - out\"</p></li>\n<li><p>Outside-in seems to result in compilable code from the beginning. Inside-out seems to require lots of complex code up front. </p></li>\n<li><p>Designing data structures - the <code>CaesarCipher</code> class w/ an encapsulated Array lookup - simplifies the hell out of subsequent code. This is HUGE.</p>\n\n<ul>\n<li>The revelation that the clock is actually 24 hours with modulus behavior. This \"24 data structure\" removes 12 o'clock ambiguity, removes the need for am/pm qualifiers, and will greatly simplify the calculation code itself. If we want a 12 hour clock we can start with (inherit) the 24HourClock class because it is a more fundamental structure in the <a href=\"https://www.apple.com/shop/buy-watch/apple-watch\" rel=\"nofollow noreferrer\">Apple Store</a> quadrant of the time telling universe.</li>\n</ul></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T21:05:40.853", "Id": "231021", "ParentId": "231001", "Score": "1" } } ]
{ "AcceptedAnswerId": "231019", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T14:32:21.733", "Id": "231001", "Score": "2", "Tags": [ "c#", "beginner", "caesar-cipher" ], "Title": "Caesar Cypher Implementation" }
231001
<p>this is an update of the implementation after I followed the feedback from <a href="https://codereview.stackexchange.com/questions/230903/iterator-for-traversing-a-tree">Iterator for traversing a tree</a>. After that I did changed quite a bit on the design and decided to ask for another round of review. Hope this is allowed.</p> <p>First is on what I want to achieve and the tests I made to ensure it is correct. For this, please help review to see if the test cases are good.</p> <p>main.cpp</p> <pre class="lang-cpp prettyprint-override"><code>#include "tree.h" #include &lt;cassert&gt; #include &lt;exception&gt; #include &lt;iostream&gt; void traverse(Tree&lt;std::string&gt; root) { for (auto cur : root) { auto parent = cur.GetParent(); std::cout &lt;&lt; "traversed from " &lt;&lt; (parent ? parent-&gt;val : "NULL") &lt;&lt; " to " &lt;&lt; cur.val &lt;&lt; std::endl; } } int main() { Tree&lt;std::string&gt; tA = Tree&lt;std::string&gt;("A"); Tree&lt;std::string&gt; tB = Tree&lt;std::string&gt;("B", &amp;tA); Tree&lt;std::string&gt; tC = Tree&lt;std::string&gt;("C", &amp;tA); Tree&lt;std::string&gt; tD = Tree&lt;std::string&gt;("D", &amp;tB); Tree&lt;std::string&gt; tE = Tree&lt;std::string&gt;("E", &amp;tB); Tree&lt;std::string&gt; tF = Tree&lt;std::string&gt;("F", &amp;tB); traverse(tA); try { std::next(std::next(tF.begin())); } catch (std::exception&amp; e) { std::cout &lt;&lt; e.what() &lt;&lt; std::endl; } auto it = tA.begin(); assert(it-&gt;val == "A"); ++it; assert(it-&gt;val == "C"); auto it2 = it++; assert(it-&gt;val == "B"); assert(it2-&gt;val == "C"); assert(it == tB.begin()); assert(it2 == tC.begin()); assert(it != it2); auto newNode = Tree&lt;std::string&gt;("A"); assert(newNode != tA); return 0; } </code></pre> <p>What this iterator does is to iterate through its subtree. I hope to get a critical review of the design of the interface.</p> <p>tree.h</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iterator&gt; #include &lt;stack&gt; #include &lt;vector&gt; template &lt;typename T&gt; class Tree { public: class iterator { public: using iterator_category = std::forward_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = T*; using reference = T&amp;; public: iterator() = default; iterator(Tree&lt;T&gt;* root); Tree&lt;T&gt;&amp; operator*() const; Tree&lt;T&gt;* operator-&gt;() const; iterator&amp; operator++(); iterator const operator++(int); bool operator==(iterator const&amp; other) const; bool operator!=(iterator const&amp; other) const; Tree&lt;T&gt;* cur; private: std::stack&lt;Tree&lt;T&gt;*&gt; s_; }; public: explicit Tree(T const&amp; val, Tree&lt;T&gt;* parent = nullptr); Tree&lt;T&gt;* GetParent() const; std::vector&lt;Tree&lt;T&gt;*&gt; const GetChildren() const; iterator begin(); iterator end(); bool operator==(Tree&lt;T&gt; const&amp; root) const; bool operator!=(Tree&lt;T&gt; const&amp; root) const; T val; private: Tree&lt;T&gt;* parent_ = nullptr; std::vector&lt;Tree&lt;T&gt;*&gt; children_; }; </code></pre> <p>If you have little time, you can skip the review on the implementation, but I will attach it here as well.</p> <p>Also tree.h, under the snippet above.</p> <pre class="lang-cpp prettyprint-override"><code>template &lt;typename T&gt; Tree&lt;T&gt;::iterator::iterator(Tree&lt;T&gt;* root) : cur(root) {} template &lt;typename T&gt; Tree&lt;T&gt;&amp; Tree&lt;T&gt;::iterator::operator*() const { return *cur; } template &lt;typename T&gt; Tree&lt;T&gt;* Tree&lt;T&gt;::iterator::operator-&gt;() const { return cur; } template &lt;typename T&gt; typename Tree&lt;T&gt;::iterator&amp; Tree&lt;T&gt;::iterator::operator++() { if (cur == nullptr) { throw std::out_of_range("No more nodes for traversal"); } for (auto&amp; child : cur-&gt;children_) { s_.push(child); } if (s_.empty()) { cur = nullptr; } else { cur = s_.top(); s_.pop(); } return *this; } template &lt;typename T&gt; typename Tree&lt;T&gt;::iterator const Tree&lt;T&gt;::iterator::operator++(int) { Tree&lt;T&gt;::iterator tmp(*this); ++*this; return tmp; } template &lt;typename T&gt; bool Tree&lt;T&gt;::iterator::operator==(Tree&lt;T&gt;::iterator const&amp; other) const { return *cur == *other.cur; } template &lt;typename T&gt; bool Tree&lt;T&gt;::iterator::operator!=(Tree&lt;T&gt;::iterator const&amp; other) const { return !(cur == other.cur); } template &lt;typename T&gt; Tree&lt;T&gt;::Tree(T const&amp; val, Tree&lt;T&gt;* const parent) : val(val), parent_(parent) { if (parent) { parent-&gt;children_.push_back(this); } } template &lt;typename T&gt; Tree&lt;T&gt;* Tree&lt;T&gt;::GetParent() const { return parent_; } template &lt;typename T&gt; std::vector&lt;Tree&lt;T&gt;*&gt; const Tree&lt;T&gt;::GetChildren() const { return children_; } template &lt;typename T&gt; typename Tree&lt;T&gt;::iterator Tree&lt;T&gt;::begin() { return iterator(this); } template &lt;typename T&gt; typename Tree&lt;T&gt;::iterator Tree&lt;T&gt;::end() { return iterator(); } template &lt;typename T&gt; bool Tree&lt;T&gt;::operator==(Tree&lt;T&gt; const&amp; other) const { return val == other.val &amp;&amp; parent_ == other.parent_ &amp;&amp; children_ == other.children_; } template &lt;typename T&gt; bool Tree&lt;T&gt;::operator!=(Tree&lt;T&gt; const&amp; other) const { return !(*this == other); } </code></pre> <p>This is compiled using</p> <pre><code>g++ main.cc -o tree -std=c++17 -Wall -static -O3 -m64 -lm </code></pre> <p>Finally, even if you don't have the answer to the design, I still hope you can throw me some questions such that I can ponder them.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T15:05:56.933", "Id": "450229", "Score": "0", "body": "Is there a way to specify a depth first traversal versus a breadth first traversal?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T15:29:26.033", "Id": "450230", "Score": "1", "body": "Currently there is none, but I think it's good to have it, but can't think of a way to expose this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T15:43:15.950", "Id": "450234", "Score": "0", "body": "Sorry the current implementation is depth first. Pusing all the children on. Then popping a child and pushing all its children on top repeatdifly gives you a depth first traversal." } ]
[ { "body": "<p>My problem with this iterator is that it is very expensive to copy; as you have to copy a stack when you copy the iterator.</p>\n\n<p>The main point of iterator is that it should be <strong>\"cheap\"</strong> to make copies. All algorithms that use iterators pass them by value (and all the advice you see on these pages that we give is to pass iterators by value) as a result iterators are copied a lot and as a result need to be \"cheap\" to copy.</p>\n\n<p>The reason you need the stack is that your tree has no internal structure (yes it's a tree, but there is no relationship between parents parent and child), because there is no internal structure you need to maintain extra state to keep your position.</p>\n\n<p>If we look at trees that exist in the standard library (std::set). This is an ordered binary tree (probably (the standard does not exactly specify but let's assume it is for the sake of argument. It is also probably balanced but let's not over complicate things for this analysis)).</p>\n\n<p>Lets: Look at a set with the values: 12, 25, 37, 50, 75, 62, 85</p>\n\n<p>Sorry for the bad drawing of a tree. Hope it is understandable:</p>\n\n<pre><code> 50\n / \\\n / \\\n / \\\n 25 75\n / \\ / \\\n 12 37 62 85\n</code></pre>\n\n<p>Each Node needs three pointers. Left/Right/Parent (the parent is only required to help iterators). The rules for creating an iterator are then trivial.</p>\n\n<pre><code> 1. begin() =&gt; Always return the left most node. Iterator(12)\n 2. ++\n 1. If you have right pointer go down right then find the left most child.\n 2. If you have no children. Go Up.\n a: If you just came from the left child stop.\n b: otherwise recursively up until you were a left child.\n c: When you are null you are out.\n</code></pre>\n\n<p>The rules are simple enough that you don't need to keep extra state in the iterator.</p>\n\n<p>So from <code>Iterator(12)</code> no children so go up and get <code>Iterator(25)</code> next it has a right child <code>Iterator(37)</code> next it has no children go up (but I was the child so go up again now we are <code>Iterator(50)</code> etc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T18:07:03.100", "Id": "450243", "Score": "0", "body": "So I'm an idiot that can't recognize the difference between DFS and BFS but it would still be nice to have a choice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T15:38:18.530", "Id": "231003", "ParentId": "231002", "Score": "10" } }, { "body": "<p>Martin York already has a very good point about the iterator, so I'll not comment on that.</p>\n\n<h1>Avoid writing types twice</h1>\n\n<p>In <code>main.cpp</code> you are writing statements like:</p>\n\n<pre><code>Tree&lt;std::string&gt; tA = Tree&lt;std::string&gt;(\"A\");\n</code></pre>\n\n<p>You are needlessly repeating the type. Also, it might cause errors if you wanted the same type on both sides, but made a mistake, and if one type is implicitly convertible to the other. Write one of the following lines instead:</p>\n\n<pre><code>Tree&lt;std::string&gt; tA(\"A\"); // or:\nauto tA = Tree&lt;std::string&gt;(\"A\");\n</code></pre>\n\n<h1>Trees are made of nodes, and a node is not a tree</h1>\n\n<p>A tree structure is a collection of nodes with certain relationships between the nodes. However, in your code a <code>Tree&lt;&gt;</code> is just one node. This is very confusing. It would be much nicer to have two types to distinguish between those concepts. For example:</p>\n\n<pre><code>class Tree {\n public:\n class Node {\n ...\n };\n\n class Iterator {\n ...\n };\n\n Iterator begin();\n Iterator end();\n ...\n\n private:\n Node *root;\n};\n</code></pre>\n\n<p>Once you have that in place, you can starting thinking about having the <code>Tree</code> manage the lifetime of the nodes.</p>\n\n<h1>No need to repeat <code>&lt;T&gt;</code> inside the template</h1>\n\n<p>Inside a class template you don't have to repeat the <code>&lt;T&gt;</code> for every time you reference the class itself. So for example:</p>\n\n<pre><code>template &lt;typename T&gt;\nclass Tree {\n ...\n std::vector&lt;Tree *&gt; children;\n ...\n};\n</code></pre>\n\n<h1>Lifetime of tree nodes</h1>\n\n<p>Your node class references other nodes via raw pointers. That is very fragile. Take for example this bit of code:</p>\n\n<pre><code>Tree&lt;int&gt; tA(1);\n\nif (some_condition) {\n // add a second item\n Tree&lt;int&gt; tB(1, &amp;tA);\n}\n\ntraverse(tA);\n</code></pre>\n\n<p>At this point, <code>tA</code> has a reference to <code>tB</code>, but the latter has gone out of scope, so the reference is no longer valid, leading to a crash at best.</p>\n\n<p>Instead of storing references to child nodes in the <code>children_</code> member variable, you could perhaps make that variable hold actual nodes, like so:</p>\n\n<pre><code>template &lt;typename T&gt;\nclass TreeNode {\n public:\n void addChild(T t) {\n children.push_back(t);\n }\n\n T val;\n\n private:\n std::vector&lt;TreeNode&gt; children_;\n}\n</code></pre>\n\n<p>And use it like so:</p>\n\n<pre><code>TreeNode&lt;int&gt; tA(1);\ntA.addChild(2);\n</code></pre>\n\n<p>Of course, the above is simplified, and you'd want to avoid making copies by using move semantics. But explicit ownership is the safest thing to implement.</p>\n\n<p>Another option would be to use <code>shared_ptr&lt;&gt;</code> to manage the lifetime of nodes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T20:14:00.380", "Id": "231018", "ParentId": "231002", "Score": "9" } } ]
{ "AcceptedAnswerId": "231003", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T14:32:25.977", "Id": "231002", "Score": "10", "Tags": [ "c++", "object-oriented", "tree", "iterator", "c++17" ], "Title": "Iterator for traversing a tree [v2]" }
231002
<p>OK, I have a customer list that has approx 80k records. I need to search and compare looking for duplicates, but duplicates could be an exact match, or a similar match (only some data matches) so it gives a confidence score.</p> <p>My first block of code takes 3 hours to process and returns 1.25 Billion results.</p> <p>Does anyone see a way to streamline this a bit so it doesn't take quite so long?</p> <pre><code>INSERT INTO DataDupe SELECT 'CUST', ranking AS score, Duplicate.data_uid, originalCustNo, NULL FROM ( SELECT FirstCompany.data_uid AS originalCustNo, Duplicate.*, CASE WHEN FirstCompany.data_uid = Duplicate.data_uid THEN 2 ELSE 0 END /* Company */ + CASE WHEN FirstCompany.data1 = Duplicate.data1 THEN 2 ELSE 0 END /* First/Last */ + CASE WHEN FirstCompany.data2 = Duplicate.data2 AND FirstCompany.data3 = Duplicate.data3 THEN 2 ELSE 0 END /* Address1 */ + CASE WHEN FirstCompany.data4 = Duplicate.data4 THEN 2 ELSE 0 END /* Address2 */ + CASE WHEN FirstCompany.data5 = Duplicate.data5 THEN 1 ELSE 0 END /* City/State */ + CASE WHEN FirstCompany.data6 = Duplicate.data6 AND FirstCompany.data7 = Duplicate.data7 THEN 1 ELSE 0 END /* Country */ + CASE WHEN FirstCompany.data8 = Duplicate.data8 THEN 1 ELSE 0 END /* Phone1 */ + CASE WHEN FirstCompany.data9 = Duplicate.data9 THEN 1 ELSE 0 END /* Phone2 */ + CASE WHEN FirstCompany.data10 = Duplicate.data10 THEN 1 ELSE 0 END /* Email */ + CASE WHEN FirstCompany.data11 = Duplicate.data11 THEN 1 ELSE 0 END /* Addr Type */ + CASE WHEN FirstCompany.data12 = Duplicate.data12 THEN 1 ELSE 0 END AS ranking FROM ( SELECT data_uid, data1, data2, data3, data4, data5, data6, data7, data8, data9, data10, data11, data12 FROM ( SELECT TOP (100) data_uid, data1, data2, data3, data4, data5, data6, data7, data8, data9, data10, data11, data12, ROW_NUMBER() OVER (PARTITION BY data1 ORDER BY data_uid) AS ordering FROM DataCheck ) FC WHERE ordering = 1 ) AS FirstCompany JOIN DataCheck Duplicate ON Duplicate.data_uid &gt;= FirstCompany.data_uid) Duplicate JOIN (VALUES (12, 'Original'), (11, ''), (10, ''), (9, ''), (8, ''), (7, ''), (6, 'Original'), (5, 'Duplicate'), (4, 'Duplicate'), (3, 'Likely Dupe'), (2, 'Possible Dupe'), (1, 'Not Likely Dupe'), (0, 'Not A Dupe') ) RankMapping(score, description) ON RankMapping.score = Duplicate.ranking ORDER BY Duplicate.originalCustNo, Duplicate.ranking DESC </code></pre> <p>My next Query I'm trying to only return the results that have possible matches. I've been staring at this too long. I'm not getting any results, but I should have like 20k. What am I missing? </p> <pre><code>SELECT dd.score, dd.data_original, CUST.CUSTNUM, CUST.COMPANY, CUST.FIRSTNAME, CUST.LASTNAME, CUST.ADDR, CUST.ADDR2, CUST.CITY, CUST.STATE, CUST.COUNTRY, CUST.PHONE, CUST.PHONE2, CUST.EMAIL, CUST.ADDR_TYPE FROM DataDupe dd LEFT JOIN MailOrderManager.dbo.CUST ON dd.data_uid = CUST.CUSTNUM WHERE score &gt; 6 GROUP BY dd.score, dd.data_original, CUST.CUSTNUM, CUST.COMPANY, CUST.FIRSTNAME, CUST.LASTNAME, CUST.ADDR, CUST.ADDR2, CUST.CITY, CUST.STATE, CUST.COUNTRY, CUST.PHONE, CUST.PHONE2, CUST.EMAIL, CUST.ADDR_TYPE HAVING COUNT(dd.data_original) &gt; 1 ORDER BY dd.data_original ASC, dd.score DESC </code></pre> <p>I am not sure using the straight score is the best way to get results. For example, if a record has first, last, phone1, and email it has a score of 6, if another record has the same first last and email, it has a score of 3. If you could null = null for the columns missing data it gets more complicated.</p> <p>I'm thinking it may make more sense to compare the score to the original and use:</p> <pre><code>CASE WHEN dd.data_original = CUST.CUSTNUM THEN 0 ELSE (SELECT score FROM DataDupe WHERE data_uid = dd.data_original) - dd.score END AS conf_score, </code></pre> <p>SQL for the two data tables. Actual data is pretty generic company, name address info, but I can't give it for security reasons. I can say that not all columns have data for each record (ie Address 2, Phone 2, and Email are supplied on maybe 200 records, about 20% are for individuals not companies, so there is no company name, etc)</p> <pre><code>CREATE TABLE DataCheck ( id int identity(1,1), data_table varchar(60) NOT NULL, data_field varchar(60) DEFAULT NULL, data_uid varchar(60) NOT NULL, data1 varchar(255) NOT NULL, data2 varchar(255) DEFAULT NULL, data3 varchar(255) DEFAULT NULL, data4 varchar(255) DEFAULT NULL, data5 varchar(255) DEFAULT NULL, data6 varchar(255) DEFAULT NULL, data7 varchar(255) DEFAULT NULL, data8 varchar(255) DEFAULT NULL, data9 varchar(255) DEFAULT NULL, data10 varchar(255) DEFAULT NULL, data11 varchar(255) DEFAULT NULL, data12 varchar(255) DEFAULT NULL, data_type varchar(60) NOT NULL ) CREATE TABLE DataDupe ( id int identity(1,1), data_table varchar(60) NOT NULL, score int, data_uid varchar(60) NOT NULL, data_original varchar(255) NOT NULL, action varchar(60) DEFAULT NULL ) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T21:32:16.460", "Id": "450257", "Score": "0", "body": "Please also post the SQL to create the tables that are queried." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T00:14:05.310", "Id": "450261", "Score": "0", "body": "@BCdotWEB Done!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T18:19:14.223", "Id": "457575", "Score": "0", "body": "3hrs on `SELECT TOP (100) * FROM DataCheck` even if it has billions of rows, you still getting only 100 rows, You must check the indexes and also test the query performance on the `SELECT TOP (100) * FROM DataCheck` alone, see how much it takes." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T18:08:43.303", "Id": "231007", "Score": "2", "Tags": [ "sql", "sql-server" ], "Title": "SQL Code That Looks for Dupes with Confidence Score, 3hr / 1.2 BILLION Rows Returned. Optimize?" }
231007
<p>This function will check a word with some letters missing, missing letters will be indicated by an "_ " (notice that there is a space after the underscore). The word with missing letters needs to be checked against a full word and if both words are found to be identical ( disregarding the "_ " the function should return True otherwise False.</p> <p>This is part of a problem set from the MIT Online Course. here is how i managed to do this:</p> <pre class="lang-py prettyprint-override"><code> def match_with_gaps(my_word, other_word): ''' my_word: string with "_" characters other_word: string, regular English word returns: boolean, True if all the actual letters of my_word match the corresponding letters of other_word, or the letter is the special symbol "_", and my_word and other_word are of the same length; False otherwise: ''' my_word = my_word.replace(' ','') for char in my_word: if char.isalpha(): if my_word.count(char) != other_word.count(char): return False return len(my_word) == len(other_word) </code></pre> <p>An example :</p> <pre><code>a = match_with_gaps('a p p _ e', 'apple') b = match_with_gaps('a p p _ c', 'apple') print(a) &gt;&gt; outputs : True print(b) &gt;&gt; outputs : False </code></pre> <p>I also came up with another way:</p> <pre><code>def match_with_gaps(my_word, other_word): ''' my_word: string with _ characters, current guess of secret word other_word: string, regular English word returns: boolean, True if all the actual letters of my_word match the corresponding letters of other_word, or the letter is the special symbol _ , and my_word and other_word are of the same length; False otherwise: ''' my_word = my_word.replace(' ', '') if len(my_word) != len(other_word): return False else: for i in range(len(my_word)): if my_word[i] != '_' and ( my_word[i] != other_word[i] \ or my_word.count(my_word[i]) != other_word.count(my_word[i]) \ ): return False return True </code></pre> <p>which will give the same output but using a different method.</p> <p>Which way is more efficient / will give more accurate results? and is there a third better method? Please give reason to your answer. And thanks in advance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T18:50:47.287", "Id": "450246", "Score": "0", "body": "What should be the output for `match_with_gaps('_ _ _ _e', 'apple')` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T18:52:12.717", "Id": "450247", "Score": "0", "body": "It should return True." } ]
[ { "body": "<p>Your 2nd approach is better that 1st as it adds <em>length</em> comparison, but</p>\n\n<ul>\n<li>it has redundant <code>else:</code> branch. The 1st <code>if</code> condition, if positive, has unambiguous statement <code>return False</code> <em>terminating</em> function call</li>\n<li><code>my_word.count(my_word[i])</code>, <code>other_word.count(my_word[i]</code> calls will traverse sequence of chars (word) on each loop iteration for equal characters (trying to <em>\"run ahead\"</em>)</li>\n</ul>\n\n<hr>\n\n<p>Consider the following approach with builtin <a href=\"https://docs.python.org/3/library/functions.html#any\" rel=\"nofollow noreferrer\"><code>any</code></a> function (returns <code>True</code> if any element of the <em>iterable</em> is true):</p>\n\n<pre><code>def match_with_gaps(my_word, full_word):\n '''\n my_word: string with _ characters, current guess of secret word\n full_word: string, regular English word\n returns: boolean, True if all the actual letters of my_word match the\n corresponding letters of full_word, or the letter is the special symbol\n _ , and my_word and full_word are of the same length;\n False otherwise\n '''\n my_word = my_word.replace(' ', '')\n\n # check for length OR respective characters mismatch\n if len(my_word) != len(full_word) \\\n or any(c1 != '_' and c1 != c2 for c1, c2 in zip(my_word, full_word)):\n return False\n\n return True\n\nprint(match_with_gaps('a p p _ e', 'apple')) # True\nprint(match_with_gaps('a p p _ c', 'apple')) # False\nprint(match_with_gaps('a _ _ _ _', 'apple')) # True\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T19:13:54.477", "Id": "231014", "ParentId": "231009", "Score": "1" } }, { "body": "<p>Your second method is better than the first, solely due to the fact that it has one less bug than the first one:</p>\n\n<pre><code>In [5]: match_with_gaps(\"a p e _ p\", \"apple\")\nOut[5]: True\n\nIn [6]: match_with_gaps2(\"a p e _ p\", \"apple\")\nOut[6]: False\n</code></pre>\n\n<p>However, both fail if a character is masked that appears more than once:</p>\n\n<pre><code>In [7]: match_with_gaps(\"a p _ l e\", \"apple\")\nOut[7]: False\n\nIn [8]: match_with_gaps2(\"a p _ l e\", \"apple\")\nOut[8]: False\n</code></pre>\n\n<p>While you do check that the count of each character is the same, this does not mean that the words are the same. And the counts may differ because some character are masked.</p>\n\n<p>The second approach is also slightly better because it checks the length first, there's no need for a complicated algorithm if that is not the case.</p>\n\n<p>In your second function I would use a few tricks to reduce the amount of indentation you have to deal with. You also should not check the count of the characters, since you are going to go through all characters anyway and it actually introduces the second bug:</p>\n\n<pre><code>def match_with_gaps(my_word, other_word):\n '''\n my_word: string with _ characters, current guess of secret word\n other_word: string, regular English word\n returns: boolean, True if all the actual letters of my_word match the \n corresponding letters of other_word, or the letter is the special symbol\n _ , and my_word and other_word are of the same length;\n False otherwise: \n '''\n my_word = my_word.replace(' ', '')\n if len(my_word) != len(other_word):\n return False\n for c1, c2 in zip(my_word, other_word):\n if c1 == '_':\n continue\n if c1 != c2:\n return False\n return True\n</code></pre>\n\n<p>You could make this more compact using <code>all</code>:</p>\n\n<pre><code>def match_with_gaps(my_word, other_word):\n '''\n my_word: string with _ characters, current guess of secret word\n other_word: string, regular English word\n returns: boolean, True if all the actual letters of my_word match the \n corresponding letters of other_word, or the letter is the special symbol\n _ , and my_word and other_word are of the same length;\n False otherwise: \n '''\n my_word = my_word.replace(' ', '')\n if len(my_word) != len(other_word):\n return False\n return all(c1 in ('_', c2) for c1, c2 in zip(my_word, other_word))\n</code></pre>\n\n<p>If you <em>do</em> want to compare counts of characters, you should use <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>collections.Counter</code></a>, instead of <code>list.count</code>. The former goes through the whole iterable once and sum up the occurrences of each unique element, whereas you need to call <code>list.count</code> for each unique element and each call traverses the whole iterable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T10:32:27.570", "Id": "231035", "ParentId": "231009", "Score": "1" } } ]
{ "AcceptedAnswerId": "231035", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T18:43:02.773", "Id": "231009", "Score": "1", "Tags": [ "python" ], "Title": "A function that checks if a word is similar to another word and returns a boolean" }
231009
<h3>Problem</h3> <p>Write a program to return a boolean if an input grid is magic square.</p> <hr> <p>A magic square of order <span class="math-container">\$N\$</span> is an arrangement of <span class="math-container">\$N^2\$</span> distinct integers in a square such that the <span class="math-container">\$N\$</span> numbers in all rows and columns and both diagonals sum to the same constant, known as magic sum or magic constant, <span class="math-container">\$magic\_sum\$</span>. A magic square contains the integers from <span class="math-container">\$1\$</span> to <span class="math-container">\$N^2\$</span>.</p> <p>The magic sum of a normal magic square depends only on one variable, <span class="math-container">\$N\$</span>:</p> <blockquote> <h1><span class="math-container">\$magic\_sum = \dfrac{N(N^2+1)}{2}\$</span></h1> </blockquote> <p><a href="https://i.stack.imgur.com/cmWko.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cmWko.png" alt="magic sum formula"></a></p> <h3>Code</h3> <p><a href="https://codereview.stackexchange.com/questions/230972/magic-square-python">We've solved "if a grid is magic square" problem with five methods</a>, which I've just slightly modified those and included <code>timeit</code> benchmarking. If you would like to review the code, or add other methods or anything else or provide any change/improvement recommendations please do so, and I'd really appreciate that.</p> <pre><code>import numpy as np from typing import List, Iterable, Callable from functools import partial Grid = List[List[int]] # Might as well create an alias for this def has_correct_dimensions(grid: Grid) -&gt; bool: """Returns whether or not the grid is a non-jagged square.""" return all(len(row) == len(grid) for row in grid) def is_normal_square(grid: Grid) -&gt; bool: """Returns whether or not the function contains unique numbers from 1 to n**2.""" max_n = len(grid[0]) ** 2 # Does the set of numbers in the flattened grid contain the same numbers as a range set from 1 to n**2? return set(e for row in grid for e in row) == set(range(1, max_n + 1)) def check_each(iterable: Iterable[Iterable[int]], magic_sum: int) -&gt; bool: """Returns whether or not every sub-iterable collection sums to the magic sum""" return all(sum(elem) == magic_sum for elem in iterable) def diagonal_of(grid: Grid, y_indexer: Callable[[int], int]) -&gt; Iterable[int]: """Generates a line of elements from the grid. y = y_indexer(x).""" return (grid[y_indexer(x)][x] for x in range(len(grid))) def magic_constant(grid: Grid) -&gt; int: """Returns the magic sum integer value""" return len(grid) * (len(grid) ** 2 + 1) / 2 def is_magic_square_multifunctions(grid: Grid) -&gt; bool: """Returns whether or not the supplied grid is a proper normal magic square.""" magic_sum = magic_constant(grid) check = partial(check_each, magic_sum=magic_sum) return is_normal_square(grid) and \ has_correct_dimensions(grid) and \ check(grid) and \ check(zip(*grid)) and \ check([diagonal_of(grid, lambda x: x), diagonal_of(grid, lambda x: len(grid) - x - 1)]) def is_magic_square_linguini(grid: Grid) -&gt; bool: length = len(grid) if length == 0: return False magic_sum = magic_constant(grid) sum_three, sum_four = int(), int() for index_row in range(length): sum_one, sum_two = int(), int() unique_elements = dict() for index_col in range(length): if grid[index_row][index_col] in unique_elements: return False unique_elements[grid[index_row][index_col]] = True sum_one += grid[index_row][index_col] sum_two += grid[index_col][index_row] if index_row == index_col: sum_three += grid[index_col][index_row] if (index_row + index_col) == length - 1: sum_four += grid[index_row][index_col] if sum_one != magic_sum or sum_two != magic_sum: return False if sum_three != magic_sum or sum_four != magic_sum: return False return True def is_magic_square_vermicelli(grid: List[List[int]]) -&gt; bool: """Returns a boolean if an input grid is magic square""" grid_length = len(grid) magic_sum = magic_constant(grid) diag_positive, diag_negative = [], [] diag_count_positive, diag_count_negative = 0, grid_length - 1 col_grid = np.zeros(shape=(grid_length, grid_length)) unique_elements = set() for index_row, lists in enumerate(grid): diag_negative.append(lists[diag_count_negative]) diag_count_negative -= 1 if len(grid[index_row]) != grid_length: return False if sum(lists) != magic_sum: return False for index_col in range(grid_length): unique_elements.add(lists[index_col]) col_grid[index_col][index_row] = lists[index_col] if index_col == grid_length and index_row == grid_length - 1 and len(unique_elements) != grid_length ** 2 - 1: return False if index_row == grid_length - 1: sum_col, temp_col = sum(col_grid), np.array( [magic_sum] * grid_length) if str(temp_col) != str(sum_col): return False if diag_count_positive == index_row: diag_positive.append(lists[index_row]) diag_count_positive += 1 if diag_count_positive == grid_length and sum(diag_positive) != magic_sum: return False if index_row == grid_length - 1 and sum(diag_negative) != magic_sum: return False return True def is_magic_square_single_method(grid: List[List[int]]) -&gt; bool: """Returns a boolean if an input grid is magic square""" grid_length = len(grid) grid_area = grid_length ** 2 magic_sum = magic_constant(grid) # check the length of all rows if any(len(row) != grid_length for row in grid): return False # check it has all the numbers in sequence if set(x for row in grid for x in row) != set(range(1, grid_area + 1)): return False # check all the rows add up to the magic_number if any(sum(row) != magic_sum for row in grid): return False # check all the columns add up to the magic_number if any(sum(row[col] for row in grid) != magic_sum for col in range(grid_length)): return False # check each diagonal adds up to the magic_number if (sum(grid[i][i] for i in range(grid_length)) != magic_sum or sum(grid[i][grid_length - i - 1] for i in range(grid_length)) != magic_sum): return False return True def is_magic_square_numpy(grid: List[List[int]]) -&gt; bool: """Returns a boolean if an input grid is magic square""" grid_length = len(grid) magic_sum = magic_constant(grid) # check the length of all rows if any(len(row) != grid_length for row in grid): return False npgrid = np.array(grid) # check it has all ints from 1 to grid_length**2 (inclusive) if len(np.setdiff1d(npgrid, np.arange(1, grid_length ** 2 + 1))): return False # check all the rows add up to the magic_number if any(np.not_equal(npgrid.sum(axis=0), magic_sum)): return False # check all the columns add up to the magic_number if any(np.not_equal(npgrid.sum(axis=1), magic_sum)): return False # check both diagonals add up to the magic_number if (npgrid.diagonal().sum() != magic_sum or np.fliplr(npgrid).diagonal().sum() != magic_sum): return False return True if __name__ == '__main__': # ---------------------------- TEST --------------------------- import timeit import cProfile DIVIDER_DASH_LINE = '-' * 50 GREEN_APPLE = '\U0001F34F' RED_APPLE = '\U0001F34E' magic_squares = ( [[4, 3, 8], [9, 5, 1], [2, 7, 6]], [[8, 1, 6], [3, 5, 7], [4, 9, 2]], [[1, 14, 4, 15], [8, 11, 5, 10], [13, 2, 16, 3], [12, 7, 9, 6]], [[9, 3, 22, 16, 15], [2, 21, 20, 14, 8], [25, 19, 13, 7, 1], [18, 12, 6, 5, 24], [11, 10, 4, 23, 17]], [[16, 14, 7, 30, 23], [24, 17, 10, 8, 31], [32, 25, 18, 11, 4], [5, 28, 26, 19, 12], [13, 6, 29, 22, 20]], [[1, 35, 4, 33, 32, 6], [25, 11, 9, 28, 8, 30], [24, 14, 18, 16, 17, 22], [13, 23, 19, 21, 20, 15], [12, 26, 27, 10, 29, 7], [36, 2, 34, 3, 5, 31]], [[35, 26, 17, 1, 62, 53, 44], [46, 37, 21, 12, 3, 64, 55], [57, 41, 32, 23, 14, 5, 66], [61, 52, 43, 34, 25, 16, 7], [2, 63, 54, 45, 36, 27, 11], [13, 4, 65, 56, 47, 31, 22], [24, 15, 6, 67, 51, 42, 33]], [[60, 53, 44, 37, 4, 13, 20, 29], [3, 14, 19, 30, 59, 54, 43, 38], [58, 55, 42, 39, 2, 15, 18, 31], [1, 16, 17, 32, 57, 56, 41, 40], [61, 52, 45, 36, 5, 12, 21, 28], [6, 11, 22, 27, 62, 51, 46, 35], [63, 50, 47, 34, 7, 10, 23, 26], [8, 9, 24, 25, 64, 49, 48, 33]], [[22, 47, 16, 41, 10, 35, 4], [5, 23, 48, 17, 42, 11, 29], [30, 6, 24, 49, 18, 36, 12], [13, 31, 7, 25, 43, 19, 37], [38, 14, 32, 1, 26, 44, 20], [21, 39, 8, 33, 2, 27, 45], [46, 15, 40, 9, 34, 3, 28]], [[8, 58, 59, 5, 4, 62, 63, 1], [49, 15, 14, 52, 53, 11, 10, 56], [41, 23, 22, 44, 45, 19, 18, 48], [32, 34, 35, 29, 28, 38, 39, 25], [40, 26, 27, 37, 36, 30, 31, 33], [17, 47, 46, 20, 21, 43, 42, 24], [9, 55, 54, 12, 13, 51, 50, 16], [64, 2, 3, 61, 60, 6, 7, 57]], [[37, 78, 29, 70, 21, 62, 13, 54, 5], [6, 38, 79, 30, 71, 22, 63, 14, 46], [47, 7, 39, 80, 31, 72, 23, 55, 15], [16, 48, 8, 40, 81, 32, 64, 24, 56], [57, 17, 49, 9, 41, 73, 33, 65, 25], [26, 58, 18, 50, 1, 42, 74, 34, 66], [67, 27, 59, 10, 51, 2, 43, 75, 35], [36, 68, 19, 60, 11, 52, 3, 44, 76], [77, 28, 69, 20, 61, 12, 53, 4, 45]], ) test_methods = ( ("Multifunctions", is_magic_square_multifunctions), ("Linguine", is_magic_square_linguini), ("Vermicelli", is_magic_square_vermicelli), ("Single Method", is_magic_square_single_method), ("Numpy", is_magic_square_numpy), ) # --------------------------------- PROFILING AND BANCHMARK SETTINGS -------------------------------------- NUMBER_OF_RUNS = 64 CPROFILING_ON = False BENCHMARK_ON = True for description, method in test_methods: print((GREEN_APPLE + RED_APPLE) * 5) for magic_square in magic_squares: if CPROFILING_ON is True: print(f'{description} cProfiling: ', cProfile.run("method(magic_square)")) if BENCHMARK_ON is True: print(f'{description} Benchmark: ', timeit.Timer( f'for i in range({NUMBER_OF_RUNS}): {method(magic_square)}', 'gc.enable()').timeit()) if method(magic_square) is True: print(f'{GREEN_APPLE} {description}: "{magic_square}" is a magic square.') else: print(f'{RED_APPLE} {description}: "{magic_square}" is not a magic square.') </code></pre> <h3>Test</h3> <p>These variables can be assigned differently for testing:</p> <pre><code>NUMBER_OF_RUNS = 64 CPROFILING_ON = False BENCHMARK_ON = True </code></pre> <h3>A Sample Output</h3> <pre><code> Multifunctions Benchmark: 5.588784874 Multifunctions: "[[4, 3, 8], [9, 5, 1], [2, 7, 6]]" is a magic square. Multifunctions Benchmark: 5.549960512000001 Multifunctions: "[[8, 1, 6], [3, 5, 7], [4, 9, 2]]" is a magic square. Multifunctions Benchmark: 5.783070463 Multifunctions: "[[1, 14, 4, 15], [8, 11, 5, 10], [13, 2, 16, 3], [12, 7, 9, 6]]" is a magic square. Multifunctions Benchmark: 6.041834480999999 Multifunctions: "[[9, 3, 22, 16, 15], [2, 21, 20, 14, 8], [25, 19, 13, 7, 1], [18, 12, 6, 5, 24], [11, 10, 4, 23, 17]]" is a magic square. Multifunctions Benchmark: 6.304372493999999 Multifunctions: "[[16, 14, 7, 30, 23], [24, 17, 10, 8, 31], [32, 25, 18, 11, 4], [5, 28, 26, 19, 12], [13, 6, 29, 22, 20]]" is not a magic square. Multifunctions Benchmark: 6.737646978000001 Multifunctions: "[[1, 35, 4, 33, 32, 6], [25, 11, 9, 28, 8, 30], [24, 14, 18, 16, 17, 22], [13, 23, 19, 21, 20, 15], [12, 26, 27, 10, 29, 7], [36, 2, 34, 3, 5, 31]]" is a magic square. Multifunctions Benchmark: 6.330970278999999 Multifunctions: "[[35, 26, 17, 1, 62, 53, 44], [46, 37, 21, 12, 3, 64, 55], [57, 41, 32, 23, 14, 5, 66], [61, 52, 43, 34, 25, 16, 7], [2, 63, 54, 45, 36, 27, 11], [13, 4, 65, 56, 47, 31, 22], [24, 15, 6, 67, 51, 42, 33]]" is not a magic square. Multifunctions Benchmark: 6.320764873000002 Multifunctions: "[[60, 53, 44, 37, 4, 13, 20, 29], [3, 14, 19, 30, 59, 54, 43, 38], [58, 55, 42, 39, 2, 15, 18, 31], [1, 16, 17, 32, 57, 56, 41, 40], [61, 52, 45, 36, 5, 12, 21, 28], [6, 11, 22, 27, 62, 51, 46, 35], [63, 50, 47, 34, 7, 10, 23, 26], [8, 9, 24, 25, 64, 49, 48, 33]]" is a magic square. Multifunctions Benchmark: 6.070653400000005 Multifunctions: "[[22, 47, 16, 41, 10, 35, 4], [5, 23, 48, 17, 42, 11, 29], [30, 6, 24, 49, 18, 36, 12], [13, 31, 7, 25, 43, 19, 37], [38, 14, 32, 1, 26, 44, 20], [21, 39, 8, 33, 2, 27, 45], [46, 15, 40, 9, 34, 3, 28]]" is a magic square. Multifunctions Benchmark: 5.944438742000003 Multifunctions: "[[8, 58, 59, 5, 4, 62, 63, 1], [49, 15, 14, 52, 53, 11, 10, 56], [41, 23, 22, 44, 45, 19, 18, 48], [32, 34, 35, 29, 28, 38, 39, 25], [40, 26, 27, 37, 36, 30, 31, 33], [17, 47, 46, 20, 21, 43, 42, 24], [9, 55, 54, 12, 13, 51, 50, 16], [64, 2, 3, 61, 60, 6, 7, 57]]" is a magic square. Multifunctions Benchmark: 5.747417926999994 Multifunctions: "[[37, 78, 29, 70, 21, 62, 13, 54, 5], [6, 38, 79, 30, 71, 22, 63, 14, 46], [47, 7, 39, 80, 31, 72, 23, 55, 15], [16, 48, 8, 40, 81, 32, 64, 24, 56], [57, 17, 49, 9, 41, 73, 33, 65, 25], [26, 58, 18, 50, 1, 42, 74, 34, 66], [67, 27, 59, 10, 51, 2, 43, 75, 35], [36, 68, 19, 60, 11, 52, 3, 44, 76], [77, 28, 69, 20, 61, 12, 53, 4, 45]]" is a magic square. Linguine Benchmark: 5.696244382999993 Linguine: "[[4, 3, 8], [9, 5, 1], [2, 7, 6]]" is a magic square. Linguine Benchmark: 5.674139272000005 Linguine: "[[8, 1, 6], [3, 5, 7], [4, 9, 2]]" is a magic square. Linguine Benchmark: 5.92109452599999 Linguine: "[[1, 14, 4, 15], [8, 11, 5, 10], [13, 2, 16, 3], [12, 7, 9, 6]]" is a magic square. Linguine Benchmark: 5.958363641999995 Linguine: "[[9, 3, 22, 16, 15], [2, 21, 20, 14, 8], [25, 19, 13, 7, 1], [18, 12, 6, 5, 24], [11, 10, 4, 23, 17]]" is a magic square. Linguine Benchmark: 5.686515516 Linguine: "[[16, 14, 7, 30, 23], [24, 17, 10, 8, 31], [32, 25, 18, 11, 4], [5, 28, 26, 19, 12], [13, 6, 29, 22, 20]]" is not a magic square. Linguine Benchmark: 5.728992446999996 Linguine: "[[1, 35, 4, 33, 32, 6], [25, 11, 9, 28, 8, 30], [24, 14, 18, 16, 17, 22], [13, 23, 19, 21, 20, 15], [12, 26, 27, 10, 29, 7], [36, 2, 34, 3, 5, 31]]" is a magic square. Linguine Benchmark: 5.650582772000007 Linguine: "[[35, 26, 17, 1, 62, 53, 44], [46, 37, 21, 12, 3, 64, 55], [57, 41, 32, 23, 14, 5, 66], [61, 52, 43, 34, 25, 16, 7], [2, 63, 54, 45, 36, 27, 11], [13, 4, 65, 56, 47, 31, 22], [24, 15, 6, 67, 51, 42, 33]]" is not a magic square. Linguine Benchmark: 5.616721932000004 Linguine: "[[60, 53, 44, 37, 4, 13, 20, 29], [3, 14, 19, 30, 59, 54, 43, 38], [58, 55, 42, 39, 2, 15, 18, 31], [1, 16, 17, 32, 57, 56, 41, 40], [61, 52, 45, 36, 5, 12, 21, 28], [6, 11, 22, 27, 62, 51, 46, 35], [63, 50, 47, 34, 7, 10, 23, 26], [8, 9, 24, 25, 64, 49, 48, 33]]" is a magic square. Linguine Benchmark: 5.492888303000001 Linguine: "[[22, 47, 16, 41, 10, 35, 4], [5, 23, 48, 17, 42, 11, 29], [30, 6, 24, 49, 18, 36, 12], [13, 31, 7, 25, 43, 19, 37], [38, 14, 32, 1, 26, 44, 20], [21, 39, 8, 33, 2, 27, 45], [46, 15, 40, 9, 34, 3, 28]]" is a magic square. Linguine Benchmark: 5.574545161999993 Linguine: "[[8, 58, 59, 5, 4, 62, 63, 1], [49, 15, 14, 52, 53, 11, 10, 56], [41, 23, 22, 44, 45, 19, 18, 48], [32, 34, 35, 29, 28, 38, 39, 25], [40, 26, 27, 37, 36, 30, 31, 33], [17, 47, 46, 20, 21, 43, 42, 24], [9, 55, 54, 12, 13, 51, 50, 16], [64, 2, 3, 61, 60, 6, 7, 57]]" is a magic square. Linguine Benchmark: 5.479747597999989 Linguine: "[[37, 78, 29, 70, 21, 62, 13, 54, 5], [6, 38, 79, 30, 71, 22, 63, 14, 46], [47, 7, 39, 80, 31, 72, 23, 55, 15], [16, 48, 8, 40, 81, 32, 64, 24, 56], [57, 17, 49, 9, 41, 73, 33, 65, 25], [26, 58, 18, 50, 1, 42, 74, 34, 66], [67, 27, 59, 10, 51, 2, 43, 75, 35], [36, 68, 19, 60, 11, 52, 3, 44, 76], [77, 28, 69, 20, 61, 12, 53, 4, 45]]" is a magic square. Vermicelli Benchmark: 5.610320167999987 Vermicelli: "[[4, 3, 8], [9, 5, 1], [2, 7, 6]]" is a magic square. Vermicelli Benchmark: 5.473386472000016 Vermicelli: "[[8, 1, 6], [3, 5, 7], [4, 9, 2]]" is a magic square. Vermicelli Benchmark: 5.50186076 Vermicelli: "[[1, 14, 4, 15], [8, 11, 5, 10], [13, 2, 16, 3], [12, 7, 9, 6]]" is a magic square. Vermicelli Benchmark: 5.465219862999987 Vermicelli: "[[9, 3, 22, 16, 15], [2, 21, 20, 14, 8], [25, 19, 13, 7, 1], [18, 12, 6, 5, 24], [11, 10, 4, 23, 17]]" is a magic square. Vermicelli Benchmark: 5.538681058999998 Vermicelli: "[[16, 14, 7, 30, 23], [24, 17, 10, 8, 31], [32, 25, 18, 11, 4], [5, 28, 26, 19, 12], [13, 6, 29, 22, 20]]" is not a magic square. Vermicelli Benchmark: 5.466972800000008 Vermicelli: "[[1, 35, 4, 33, 32, 6], [25, 11, 9, 28, 8, 30], [24, 14, 18, 16, 17, 22], [13, 23, 19, 21, 20, 15], [12, 26, 27, 10, 29, 7], [36, 2, 34, 3, 5, 31]]" is a magic square. Vermicelli Benchmark: 5.542082810000011 Vermicelli: "[[35, 26, 17, 1, 62, 53, 44], [46, 37, 21, 12, 3, 64, 55], [57, 41, 32, 23, 14, 5, 66], [61, 52, 43, 34, 25, 16, 7], [2, 63, 54, 45, 36, 27, 11], [13, 4, 65, 56, 47, 31, 22], [24, 15, 6, 67, 51, 42, 33]]" is not a magic square. Vermicelli Benchmark: 5.477112298999998 Vermicelli: "[[60, 53, 44, 37, 4, 13, 20, 29], [3, 14, 19, 30, 59, 54, 43, 38], [58, 55, 42, 39, 2, 15, 18, 31], [1, 16, 17, 32, 57, 56, 41, 40], [61, 52, 45, 36, 5, 12, 21, 28], [6, 11, 22, 27, 62, 51, 46, 35], [63, 50, 47, 34, 7, 10, 23, 26], [8, 9, 24, 25, 64, 49, 48, 33]]" is a magic square. Vermicelli Benchmark: 5.534445683000001 Vermicelli: "[[22, 47, 16, 41, 10, 35, 4], [5, 23, 48, 17, 42, 11, 29], [30, 6, 24, 49, 18, 36, 12], [13, 31, 7, 25, 43, 19, 37], [38, 14, 32, 1, 26, 44, 20], [21, 39, 8, 33, 2, 27, 45], [46, 15, 40, 9, 34, 3, 28]]" is a magic square. Vermicelli Benchmark: 5.473650165999999 Vermicelli: "[[8, 58, 59, 5, 4, 62, 63, 1], [49, 15, 14, 52, 53, 11, 10, 56], [41, 23, 22, 44, 45, 19, 18, 48], [32, 34, 35, 29, 28, 38, 39, 25], [40, 26, 27, 37, 36, 30, 31, 33], [17, 47, 46, 20, 21, 43, 42, 24], [9, 55, 54, 12, 13, 51, 50, 16], [64, 2, 3, 61, 60, 6, 7, 57]]" is a magic square. Vermicelli Benchmark: 5.516359977000008 Vermicelli: "[[37, 78, 29, 70, 21, 62, 13, 54, 5], [6, 38, 79, 30, 71, 22, 63, 14, 46], [47, 7, 39, 80, 31, 72, 23, 55, 15], [16, 48, 8, 40, 81, 32, 64, 24, 56], [57, 17, 49, 9, 41, 73, 33, 65, 25], [26, 58, 18, 50, 1, 42, 74, 34, 66], [67, 27, 59, 10, 51, 2, 43, 75, 35], [36, 68, 19, 60, 11, 52, 3, 44, 76], [77, 28, 69, 20, 61, 12, 53, 4, 45]]" is a magic square. Single Method Benchmark: 5.792159653999988 Single Method: "[[4, 3, 8], [9, 5, 1], [2, 7, 6]]" is a magic square. Single Method Benchmark: 5.452938262999993 Single Method: "[[8, 1, 6], [3, 5, 7], [4, 9, 2]]" is a magic square. Single Method Benchmark: 5.8117709149999826 Single Method: "[[1, 14, 4, 15], [8, 11, 5, 10], [13, 2, 16, 3], [12, 7, 9, 6]]" is a magic square. Single Method Benchmark: 5.46323830099999 Single Method: "[[9, 3, 22, 16, 15], [2, 21, 20, 14, 8], [25, 19, 13, 7, 1], [18, 12, 6, 5, 24], [11, 10, 4, 23, 17]]" is a magic square. Single Method Benchmark: 5.8472462789999895 Single Method: "[[16, 14, 7, 30, 23], [24, 17, 10, 8, 31], [32, 25, 18, 11, 4], [5, 28, 26, 19, 12], [13, 6, 29, 22, 20]]" is not a magic square. Single Method Benchmark: 5.433652160999998 Single Method: "[[1, 35, 4, 33, 32, 6], [25, 11, 9, 28, 8, 30], [24, 14, 18, 16, 17, 22], [13, 23, 19, 21, 20, 15], [12, 26, 27, 10, 29, 7], [36, 2, 34, 3, 5, 31]]" is a magic square. Single Method Benchmark: 5.805129637999983 Single Method: "[[35, 26, 17, 1, 62, 53, 44], [46, 37, 21, 12, 3, 64, 55], [57, 41, 32, 23, 14, 5, 66], [61, 52, 43, 34, 25, 16, 7], [2, 63, 54, 45, 36, 27, 11], [13, 4, 65, 56, 47, 31, 22], [24, 15, 6, 67, 51, 42, 33]]" is not a magic square. Single Method Benchmark: 5.48093770700001 Single Method: "[[60, 53, 44, 37, 4, 13, 20, 29], [3, 14, 19, 30, 59, 54, 43, 38], [58, 55, 42, 39, 2, 15, 18, 31], [1, 16, 17, 32, 57, 56, 41, 40], [61, 52, 45, 36, 5, 12, 21, 28], [6, 11, 22, 27, 62, 51, 46, 35], [63, 50, 47, 34, 7, 10, 23, 26], [8, 9, 24, 25, 64, 49, 48, 33]]" is a magic square. Single Method Benchmark: 5.818483440999984 Single Method: "[[22, 47, 16, 41, 10, 35, 4], [5, 23, 48, 17, 42, 11, 29], [30, 6, 24, 49, 18, 36, 12], [13, 31, 7, 25, 43, 19, 37], [38, 14, 32, 1, 26, 44, 20], [21, 39, 8, 33, 2, 27, 45], [46, 15, 40, 9, 34, 3, 28]]" is a magic square. Single Method Benchmark: 5.494786433999991 Single Method: "[[8, 58, 59, 5, 4, 62, 63, 1], [49, 15, 14, 52, 53, 11, 10, 56], [41, 23, 22, 44, 45, 19, 18, 48], [32, 34, 35, 29, 28, 38, 39, 25], [40, 26, 27, 37, 36, 30, 31, 33], [17, 47, 46, 20, 21, 43, 42, 24], [9, 55, 54, 12, 13, 51, 50, 16], [64, 2, 3, 61, 60, 6, 7, 57]]" is a magic square. Single Method Benchmark: 5.769875240999994 Single Method: "[[37, 78, 29, 70, 21, 62, 13, 54, 5], [6, 38, 79, 30, 71, 22, 63, 14, 46], [47, 7, 39, 80, 31, 72, 23, 55, 15], [16, 48, 8, 40, 81, 32, 64, 24, 56], [57, 17, 49, 9, 41, 73, 33, 65, 25], [26, 58, 18, 50, 1, 42, 74, 34, 66], [67, 27, 59, 10, 51, 2, 43, 75, 35], [36, 68, 19, 60, 11, 52, 3, 44, 76], [77, 28, 69, 20, 61, 12, 53, 4, 45]]" is a magic square. Numpy Benchmark: 5.541609400999988 Numpy: "[[4, 3, 8], [9, 5, 1], [2, 7, 6]]" is a magic square. Numpy Benchmark: 5.829946971000027 Numpy: "[[8, 1, 6], [3, 5, 7], [4, 9, 2]]" is a magic square. Numpy Benchmark: 5.444178211999997 Numpy: "[[1, 14, 4, 15], [8, 11, 5, 10], [13, 2, 16, 3], [12, 7, 9, 6]]" is a magic square. Numpy Benchmark: 5.820747697000002 Numpy: "[[9, 3, 22, 16, 15], [2, 21, 20, 14, 8], [25, 19, 13, 7, 1], [18, 12, 6, 5, 24], [11, 10, 4, 23, 17]]" is a magic square. Numpy Benchmark: 5.5407621650000465 Numpy: "[[16, 14, 7, 30, 23], [24, 17, 10, 8, 31], [32, 25, 18, 11, 4], [5, 28, 26, 19, 12], [13, 6, 29, 22, 20]]" is not a magic square. Numpy Benchmark: 5.764756991000013 Numpy: "[[1, 35, 4, 33, 32, 6], [25, 11, 9, 28, 8, 30], [24, 14, 18, 16, 17, 22], [13, 23, 19, 21, 20, 15], [12, 26, 27, 10, 29, 7], [36, 2, 34, 3, 5, 31]]" is a magic square. Numpy Benchmark: 5.588026968999998 Numpy: "[[35, 26, 17, 1, 62, 53, 44], [46, 37, 21, 12, 3, 64, 55], [57, 41, 32, 23, 14, 5, 66], [61, 52, 43, 34, 25, 16, 7], [2, 63, 54, 45, 36, 27, 11], [13, 4, 65, 56, 47, 31, 22], [24, 15, 6, 67, 51, 42, 33]]" is not a magic square. Numpy Benchmark: 5.712816462999967 Numpy: "[[60, 53, 44, 37, 4, 13, 20, 29], [3, 14, 19, 30, 59, 54, 43, 38], [58, 55, 42, 39, 2, 15, 18, 31], [1, 16, 17, 32, 57, 56, 41, 40], [61, 52, 45, 36, 5, 12, 21, 28], [6, 11, 22, 27, 62, 51, 46, 35], [63, 50, 47, 34, 7, 10, 23, 26], [8, 9, 24, 25, 64, 49, 48, 33]]" is a magic square. Numpy Benchmark: 5.540658426999983 Numpy: "[[22, 47, 16, 41, 10, 35, 4], [5, 23, 48, 17, 42, 11, 29], [30, 6, 24, 49, 18, 36, 12], [13, 31, 7, 25, 43, 19, 37], [38, 14, 32, 1, 26, 44, 20], [21, 39, 8, 33, 2, 27, 45], [46, 15, 40, 9, 34, 3, 28]]" is a magic square. Numpy Benchmark: 5.761296496999989 Numpy: "[[8, 58, 59, 5, 4, 62, 63, 1], [49, 15, 14, 52, 53, 11, 10, 56], [41, 23, 22, 44, 45, 19, 18, 48], [32, 34, 35, 29, 28, 38, 39, 25], [40, 26, 27, 37, 36, 30, 31, 33], [17, 47, 46, 20, 21, 43, 42, 24], [9, 55, 54, 12, 13, 51, 50, 16], [64, 2, 3, 61, 60, 6, 7, 57]]" is a magic square. Numpy Benchmark: 5.583522877999997 Numpy: "[[37, 78, 29, 70, 21, 62, 13, 54, 5], [6, 38, 79, 30, 71, 22, 63, 14, 46], [47, 7, 39, 80, 31, 72, 23, 55, 15], [16, 48, 8, 40, 81, 32, 64, 24, 56], [57, 17, 49, 9, 41, 73, 33, 65, 25], [26, 58, 18, 50, 1, 42, 74, 34, 66], [67, 27, 59, 10, 51, 2, 43, 75, 35], [36, 68, 19, 60, 11, 52, 3, 44, 76], [77, 28, 69, 20, 61, 12, 53, 4, 45]]" is a magic square. </code></pre> <h3>Source</h3> <ul> <li><p><a href="https://codereview.stackexchange.com/questions/230972/magic-square-python">Magic Square (Python)</a></p></li> <li><p><a href="https://leetcode.com/problems/magic-squares-in-grid/" rel="nofollow noreferrer">Magic Squares In Grid - LeetCode</a></p></li> <li><p><a href="https://www.geeksforgeeks.org/magic-square/" rel="nofollow noreferrer">Magic Square - Geeks for Geeks</a></p></li> </ul>
[]
[ { "body": "<p>Overall this is quite reasonable. Good job!</p>\n\n<h2>Boolean conditions</h2>\n\n<p>No need to write</p>\n\n<pre><code> if CPROFILING_ON is True:\n</code></pre>\n\n<p>Just write</p>\n\n<pre><code> if CPROFILING_ON:\n</code></pre>\n\n<h2>Int constructor</h2>\n\n<p>This:</p>\n\n<pre><code> sum_one, sum_two = int(), int()\n</code></pre>\n\n<p>is just a goofier way of writing</p>\n\n<pre><code> sum_one, sum_two = 0, 0\n</code></pre>\n\n<p>The latter is clearer.</p>\n\n<h2>Set instead of dict</h2>\n\n<p><code>unique_elements</code> should be a <code>set</code>, not a <code>dict</code>. You never use the value, just the key.</p>\n\n<h2>Line continuations</h2>\n\n<pre><code>return is_normal_square(grid) and \\\n has_correct_dimensions(grid) and \\\n check(grid) and \\\n check(zip(*grid)) and \\\n check([diagonal_of(grid, lambda x: x),\n diagonal_of(grid, lambda x: len(grid) - x - 1)])\n</code></pre>\n\n<p>has a lot of continuations; preferred is usually</p>\n\n<pre><code>return (\n is_normal_square(grid) and\n has_correct_dimensions(grid) and\n check(grid) and\n check(zip(*grid)) and\n check([diagonal_of(grid, lambda x: x),\n diagonal_of(grid, lambda x: len(grid) - x - 1)])\n)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T01:40:11.273", "Id": "231166", "ParentId": "231010", "Score": "3" } }, { "body": "<p>Here's a solution with conditional returns. A benefit with this approach is that it saves time by not doing a full check as soon as a non-magic property is discovered. This function takes <code>square</code> as a list of lists (rows).</p>\n\n<pre><code>from typing import List\n\ndef is_really_magic(square: List[List[int]]) -&gt; bool:\n dim = len(square)\n magic_const = dim * (dim**2 +1) // 2\n dia_sum = 0\n dia_sum2 = 0\n for y in range(dim):\n if sum(square[y]) != magic_const:\n return False\n col_sum = 0\n for row in square:\n col_sum += row[y]\n if col_sum != magic_const:\n return False \n dia_sum += square[y][y]\n dia_sum2 += square[y][dim-1-y]\n if dia_sum != magic_const or dia_sum2 != magic_const:\n return False\n return True\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T22:41:30.190", "Id": "457599", "Score": "0", "body": "Welcome to Code Review! Thank you for supplying an answer. I cleaned up the formatting. Was `:p square: ` supposed to be formatted a special way? if so, feel free to correct my change on that if formatting `square` as inline code is wrong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T23:02:47.587", "Id": "457603", "Score": "0", "body": "Thanks for the welcoming! I just use :p parameter: as a way to distinguish when I speak of parameters or variable names." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T22:17:40.930", "Id": "234007", "ParentId": "231010", "Score": "2" } } ]
{ "AcceptedAnswerId": "231166", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T18:45:07.917", "Id": "231010", "Score": "5", "Tags": [ "python", "performance", "beginner", "algorithm", "mathematics" ], "Title": "Magic Square with Five Methods (Python)" }
231010
<p>I have a class, 'TaskCoordinator' which has 'BaseTask's applied to it. </p> <p>The BaseTasks have OnStarted, OnFinished and OnCancelled events which are triggered to notify the calling class of their events.</p> <p>GroupTasks consist of a collection of BaseTasks to be executed one after another or all at the same time.</p> <p>Tasks which derive from PropertyTransformation apply to a .Net Property and as such I needed a way to ensure that there are never more then one task targeting the same property, to achieve this I override GetHashCode to return the hash of the object + property name and use it to determine if there are any collisions when applying a task.</p> <p>Below is the class in question.</p> <pre><code>public class TaskCoordinator : IDisposable { private readonly CancellationTokenSource _cancellationToken; private readonly ConcurrentDictionary&lt;BaseTask, ConcurrentQueue&lt;BaseTask&gt;&gt; _tasks; /// &lt;summary&gt; /// Orchestrate the order of execution of tasks /// &lt;/summary&gt; public TaskCoordinator() { _cancellationToken = new CancellationTokenSource(); _tasks = new ConcurrentDictionary&lt;BaseTask, ConcurrentQueue&lt;BaseTask&gt;&gt;(); } /// &lt;summary&gt; /// Clean up by cancelling all pending &amp; running tasks /// &lt;/summary&gt; public void Dispose() { _cancellationToken.Cancel(); } /// &lt;summary&gt; /// Add a task to be executed /// &lt;/summary&gt; /// &lt;param name="action"&gt;&lt;/param&gt; public void Apply(BaseTask task) { if (task == null) { return; } TryToStartTask(task); } private void TryToStartTask(BaseTask task) { if (_tasks.TryGetValue(task, out var taskQueue)) { if (taskQueue == null) { taskQueue = new ConcurrentQueue&lt;BaseTask&gt;(); _tasks.TryAdd(task, taskQueue); } taskQueue.Enqueue(task); } else { StartTask(task).ConfigureAwait(false); } } private async Task StartTask(BaseTask task) { task.RaiseOnStarted(EventArgs.Empty); try { if (task is ParallelGroupTask parallelGroupTask) { await RunParallel(parallelGroupTask).ConfigureAwait(false); } else if (task is SequentialGroupTask sequentialGroupTask) { await RunSequential(sequentialGroupTask).ConfigureAwait(false); } else { await Run(task).ConfigureAwait(false); } task.RaiseOnFinished(EventArgs.Empty); RunNextTask(task); } catch (TaskCanceledException) { task.RaiseOnCancelled(); } } private async Task Run(BaseTask task) { await task.StartAsync(_cancellationToken).ConfigureAwait(false); } private async Task RunParallel(ParallelGroupTask task) { if (task.Tasks.Count == 0) { return; } bool isRunning = true; int finishedTaskCount = 0; foreach (var taskTask in task.Tasks) { taskTask.OnFinished += (s, e) =&gt; { if (++finishedTaskCount &gt;= task.Tasks.Count) { isRunning = false; } }; Apply(taskTask); } while (isRunning) { await Task.Delay(1).ConfigureAwait(false); } } private async Task RunSequential(SequentialGroupTask task) { if (task.Tasks.Count == 0) { return; } ConnectSequentialTasks(task.Tasks); var isRunning = true; //When the last task finishes set running to false task.Tasks[task.Tasks.Count - 1].OnFinished += (s, e) =&gt; { isRunning = false; }; Apply(task.Tasks[0]); while (isRunning) { await Task.Delay(1).ConfigureAwait(false); } } private void ConnectSequentialTasks(List&lt;BaseTask&gt; tasks) { for (var i = 1; i &lt; tasks.Count; i++) { var localIndex = i; tasks[localIndex - 1].OnFinished += (s, e) =&gt; { Apply(tasks[localIndex]); }; } } private void RunNextTask(BaseTask completedTask) { if (_tasks.TryGetValue(completedTask, out var taskQueue) &amp;&amp; taskQueue.TryDequeue(out var nextTask)) { StartTask(nextTask).ConfigureAwait(false); } else { _tasks.TryRemove(completedTask, out _); } } } </code></pre> <p>Here is the abstract BaseTask which all Tasks derive:</p> <pre><code> public abstract class BaseTask { protected BaseTask(TimeSpan duration) { Duration = duration; _cancellationToken = new CancellationTokenSource(); } public TimeSpan Duration { get; set; } protected CancellationTokenSource _cancellationToken { get; set; } public event EventHandler&lt;EventArgs&gt; OnStarted; public event EventHandler&lt;EventArgs&gt; OnFinished; public event EventHandler&lt;EventArgs&gt; OnCancelled; /// &lt;summary&gt; /// Start the task /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public Task StartAsync() { return StartAsync(_cancellationToken); } /// &lt;summary&gt; /// Start the task with the given CancellationToken /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public Task StartAsync(CancellationTokenSource cancellationToken) { _cancellationToken = cancellationToken; if (_cancellationToken.IsCancellationRequested) { RaiseOnCancelled(); return Task.FromCanceled(_cancellationToken.Token); } return InternalTask(); } /// &lt;summary&gt; /// Interrupt the task /// &lt;/summary&gt; public void Cancel() { _cancellationToken.Cancel(); } internal void RaiseOnStarted(EventArgs args) { OnStarted?.Invoke(this, args); } internal void RaiseOnFinished(EventArgs args) { if (_cancellationToken.IsCancellationRequested) { RaiseOnCancelled(); } else { OnFinished?.Invoke(this, args); } } internal void RaiseOnCancelled() { OnCancelled?.Invoke(this, EventArgs.Empty); } protected abstract Task InternalTask(); } </code></pre> <p>I am quite happy with my solution in its current state as it seems to works well for my needs. Given the topics used in this class I am worried the solution may be some what 'hacked' together and a more elegant / reliable solution exists for me needs.</p> <p>Reliablity and deadlock aversion are #1 priority with low CPU overhead coming in second and finally speed being third in my priority list.</p> <p>For additional context here is the GitHub Repo.</p> <p><a href="https://github.com/Timmoth/AptacodeTaskPlex" rel="nofollow noreferrer">https://github.com/Timmoth/AptacodeTaskPlex</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T09:06:32.530", "Id": "450406", "Score": "0", "body": "I really don't understand the problem you're solving with this code. Can you explain the business requirement some more?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T19:11:16.867", "Id": "231013", "Score": "2", "Tags": [ "c#", "asynchronous", "concurrency", "task-parallel-library" ], "Title": "Concurrent execution and coordination of C# tasks" }
231013
<p>I need to inizialize an JArray with a JObject that contain a property areaNum that is an incremental integer. </p> <p>Right now I wrote the below code, which works ok if I have a small number of JObjects, otherwise it takes too long. </p> <p>I'm looking for a way to write the below code that take in consideration the performance at time side </p> <p>i need to initialize an JArray with n JObject that contain the areaNum that is a incremental number</p> <pre><code>Function csvToWebSocketStringSuper3(lclrow As CsvRow) As String Dim panelsArray As New JArray() Dim panel As New JObject For i As Integer = 1 To 5 panel = New JObject( New JProperty("areaNum", i), New JProperty("numbers", New JArray({New JArray({}),New JArray({}),New JArray({})})), New JProperty("systems", New JArray({""})), New JProperty("multiplier", New JArray({""})), New JProperty("qp", false), New JProperty("series", false), New JProperty("noseries", false), New JProperty("twodigit", false), New JProperty("onedigit", false), New JProperty("void", false)) panelsArray.Add(panel) Next i Dim obj As JObject = New JObject( New JProperty("playslipID", 2331), New JProperty("ticketID", 2100) , New JProperty("participationMethod", 0), New JProperty("multidraws", New JArray({formatStringToEmptyORIntegerReplace0(lclrow.getMultipleDraws)})), New JProperty("advancedraws", New JArray({formatStringToEmptyORIntegerReplace0(lclrow.getDrawOffsets)})), New JProperty("proto", New JArray({formatStringToEmptyORIntegerReplace0(lclrow.getProductId)})), New JProperty("areas", panelsArray )) Return JsonConvert.SerializeObject(obj) </code></pre>
[]
[ { "body": "<p>Instead of creating <code>JObject</code> after <code>JObject</code> you should create it once without the <code>areaNum</code> property. Then in a loop you should <code>DeepClone()</code> it and use <code>AddFirst()</code>, if positions matter, to add the <code>areNum</code> property like so </p>\n\n<pre><code> Dim original As JObject = New JObject(\n New JProperty(\"numbers\", New JArray({New JArray({}), New JArray({}), New JArray({})})),\n New JProperty(\"systems\", New JArray({\"\"})),\n New JProperty(\"multiplier\", New JArray({\"\"})),\n New JProperty(\"qp\", False),\n New JProperty(\"series\", False),\n New JProperty(\"noseries\", False),\n New JProperty(\"twodigit\", False),\n New JProperty(\"onedigit\", False),\n New JProperty(\"void\", False))\n\n For i As Integer = 1 To 5\n Dim panel As JObject = original.DeepClone\n panel.AddFirst(New JProperty(\"areaNum\", i))\n panelsArray.Add(panel)\n Next i\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T10:47:02.733", "Id": "450425", "Score": "0", "body": "Thank you. one more question: if in the for loop o would like to set to true the property New JProperty(\"qp\", False) how i can do it ? is there a way to set the property value of the clone object ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T10:51:12.037", "Id": "450426", "Score": "0", "body": "You can access a `JProperty` of a `JObject` by using its `Item` property like: `panel.Item(\"qp\") = \"true\"`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T10:42:25.137", "Id": "231092", "ParentId": "231022", "Score": "0" } } ]
{ "AcceptedAnswerId": "231092", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T22:34:50.293", "Id": "231022", "Score": "0", "Tags": [ "vb.net" ], "Title": "Inizialize an Jarray wih n JObject that contain an progressive index" }
231022
<p>I have an array of nested objects. How do I get an object with null values using only a particular key in the array of objects?</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>let headers = [{ title: 'Arun', id: 'arunId', onClick: 'onClickArun' }, { title: "George", id: 'georgeId', onClick: '', children: [{ title: 'David', id: 'davidId', onClick: 'onClickDavid' }, { title: 'Patrick', id: 'patrickId', onClick: 'onClickPatrick' } ] }, { title: 'Mark', id: 'markId', onClick: 'onClickMark' } ] const headersMap = ({ onClick, children }) =&gt; (onClick ? { onClick } : _.map(children, headersMap)); const headersFlatMap = _.flatMap(headers, headersMap); const headerObj = _.reduce(_.map(headersFlatMap, 'onClick'), (ac, a) =&gt; ({ ...ac, [a]: null }), {}); console.log(headerObj)</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>The code works good, but is there a way to optimize it?</p> <p>Expected Output:</p> <pre><code>{ "onClickArun": null, "onClickDavid": null, "onClickPatrick": null, "onClickMark": null } </code></pre> <p>Any help is greatly appreciated. Thanks.</p>
[]
[ { "body": "<h2>Performance.</h2>\n\n<ul>\n<li><code>map</code> and <code>flatMap</code> create copies of the arrays. </li>\n<li>For each new item added to the result you rebuild the whole results object <code>({ ...ac, [a]: null})</code> </li>\n<li>For each property in the result you create a temp object to hold the key value pair.</li>\n</ul>\n\n<p>These CPU, memory allocation, and GC burdens that can be avoided. </p>\n\n<p>Some will argue that the overhead for small data sets is trivial and thus inconsequential. </p>\n\n<p>Performance always matters and coding without though of performances leads to poor design habits that will bite. Many small inconsequential performance extras can quickly sum up to overall poor performance. Especially true in JavaScript where the target platform's capabilities vary so greatly. What is inconsequential on a top end desktop can be unusable on a $15 tablet.</p>\n\n<h2>Design</h2>\n\n<p>If you have followed the Code Review posting rules and your code is production code then it is very poor quality, as it is flat, in the global scope, and not reusable at all.</p>\n\n<p>You should always write code inside a function. Even if its just an example writing functions will result in better design.</p>\n\n<h2>Style</h2>\n\n<ul>\n<li>The indenting is poor and obscuring the logic.</li>\n<li>You have redundant code. Unneeded brackets <code>()</code> in <code>headersMap</code>.</li>\n<li>Poor naming of the <code>_.reduce</code> callbacks arguments</li>\n</ul>\n\n<h2>Rewrite</h2>\n\n<p>Using your algorithm and rewriting into a named function your code is more readable, reusable, and cleaner (name space wise) as</p>\n\n<pre><code>function namedEvents(eventList) {\n const map = ({onClick, children}) =&gt; onClick ? {onClick} : _.map(children, map);\n const reduce = (result, child) =&gt; ({...result, [child]: null});\n return _.reduce(\n _.map(_.flatMap(eventList, map), 'onClick'),\n reduce, \n {}\n );\n}\n</code></pre>\n\n<p>Avoiding the needless re-creation of results for each entry you get</p>\n\n<pre><code>function namedEvents(eventList) {\n const map = ({onClick, children}) =&gt; onClick ? {onClick} : _.map(children, map);\n const reduce = (result, child) =&gt; (result[child] = null, result);\n return _.reduce(\n _.map(_.flatMap(eventList, map), 'onClick'),\n reduce, \n {}\n );\n}\n</code></pre>\n\n<h2>Redesign</h2>\n\n<p>To avoid the CPU overhead the code can be written as a simple recursive function. The functions below are an order of magnitude quicker than your algorithm. </p>\n\n<p>There is no need to load lodDash.js thus improving the page load time.</p>\n\n<p>As you already use recursion I will assume that there are no cyclic references in the dataset.</p>\n\n<p>Your code ignores children if <code>onClick</code> is truthy so will do the same</p>\n\n<p>For the best re-usability the key <code>\"onClick\"</code> name can be passed as an argument. </p>\n\n<pre><code>function namedEvents(eventList, results = {}, key = \"onClick\") {\n for (const child of eventList) {\n if (child[key]) { results[child[key]] = null }\n else if (child.children) { namedEvents(child.children, results, key) }\n }\n return results;\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>function namedEvents(eventList, results = {}, key = \"onClick\") {\n for (const child of eventList) {\n if (child[key]) { \n results[child[key]] = null;\n } else if (child.children) { \n namedEvents(child.children, results, key);\n }\n }\n return results;\n}\n</code></pre>\n\n<p>Or not having an adaptive <code>key</code> name</p>\n\n<pre><code>function namedEvents(eventList, results = {}) {\n for (const {onClick, children} of eventList) {\n if (onClick) { results[onClick] = null }\n else if (children) { namedEvents(children, results) }\n }\n return results;\n}\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>function namedEvents(eventList, results = {}) {\n return eventList.reduce((result, {onClick, children}) =&gt; \n onClick? (results[onClick] = null, results) : \n children ? namedEvents(children, results) : results,\n results\n );\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T23:50:47.830", "Id": "450352", "Score": "0", "body": "So crisp and clear. Thanks @Blindman67" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T23:47:44.330", "Id": "231070", "ParentId": "231026", "Score": "3" } } ]
{ "AcceptedAnswerId": "231070", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T03:02:25.430", "Id": "231026", "Score": "1", "Tags": [ "javascript", "array", "lodash.js" ], "Title": "Get an object with null values from an array of nested objects" }
231026
<p>I've been slowly learning Haskell over the past few months. I made a small module to graph functions using Gloss, and I would like feedback on how idiomatic it is (looking for ways to simplify using standard functions and to make it more pointfree).</p> <p>Graph.hs</p> <pre class="lang-hs prettyprint-override"><code>module Graph (graph) where import Graphics.Gloss graph :: (Float -&gt; Float) -&gt; (Float, Float, Float, Float) -&gt; Float -&gt; Picture graph f (l, r, b, t) dx = pictures $ map Line visible where points :: [(Float, Float)] points = [(x, f x) | x &lt;- [l,l+dx..r]] pairs :: [[(Float, Float)]] pairs = zipWith (\x y -&gt; [x,y]) points $ tail points visible :: [[(Float, Float)]] visible = filter (all (\(_,y) -&gt; b &lt;= y &amp;&amp; t &gt;= y)) $ pairs </code></pre> <p>Main.hs</p> <pre class="lang-hs prettyprint-override"><code>import Graphics.Gloss import Graph main :: IO () main = display FullScreen white . scale 20 20 . pictures $ [ color blue $ graph f (-10, 10, -10, 10) 0.001, color black $ Line [(0, -10), (0, 10)], color black $ Line [(-10, 0), (10, 0)] ] where f :: Float -&gt; Float f x = 1 / (x - 1) </code></pre> <p>Output <a href="https://i.stack.imgur.com/F4KWw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/F4KWw.png" alt="Output"></a></p>
[]
[ { "body": "<p>You should simplify using standard functions and make it more pointfree.</p>\n\n<pre><code>import Data.List.Split\n\ngraph :: (Float -&gt; Float) -&gt; (Float, Float, Float, Float) -&gt; Float -&gt; Picture\ngraph f (l, r, b, t) dx = pictures $ map Line\n $ wordsBy (\\(_,y) -&gt; b &gt; y || t &lt; y) [(x, f x) | x &lt;- [l,l+dx..r]]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T12:54:23.173", "Id": "231037", "ParentId": "231027", "Score": "-4" } }, { "body": "<p>This looks great. Honestly, there isn't anything I'd change. You could make it more pointfree in some parts, but that's not going be more readable or maintainable.</p>\n\n<h1>Magic numbers</h1>\n\n<p>The only part I'd change are the static dimensions in <code>main</code>. Those are fine in a toy program, but a proper one will need some kind of configuration, so make sure that you use proper values from the beginning:</p>\n\n<pre><code>main :: IO ()\nmain = display FullScreen white . scale width height . pictures $ [\n color blue $ graph f (l, r, b, t) 0.001,\n color black $ Line [(origin, b), (origin, t)],\n color black $ Line [(l, origin), (r, origin)]\n ]\n where\n f :: Float -&gt; Float\n f x = 1 / (x - 1)\n\n -- easy configurable:\n (l, r, b, t) = (-10, 10, -10, 10)\n width = 20\n height = 20\n origin = 0\n</code></pre>\n\n<p>That way you can also exchange the values with proper command line interpretation</p>\n\n<pre><code>main :: IO ()\nmain = do\n (l, r, b, t) &lt;- getDimensions\n let width = r - l\n let height = t - b\n let origin = ...\n display FullScreen white . scale width height . pictures $ [\n...\n</code></pre>\n\n<p>After all, <em>no magic numbers</em> is a good practice in both imperative and functional languages.</p>\n\n<p>Next, I'd introduce <code>GraphBound</code> as a type synonym, just to make <code>graph</code>'s type signature easier on the eye:</p>\n\n<pre><code>-- | Graph boundaries, given in (left, right, bottom, top) order\ntype GraphBound = (Float, Float, Float, Float)\n\ngraph :: (Float -&gt; Float) -&gt; GraphBound -&gt; Float -&gt; Picture\ngraph f (l, r, b, t) dx = pictures $ map Line visible\n ...\n</code></pre>\n\n<p>You might even exchange <code>GraphBound</code> with a proper <code>data</code> type later which checks does not export its constructor to make sure that you don't end up with <code>left = 20</code> and <code>right = -10</code>:</p>\n\n<pre><code>makeGraph :: Float -&gt; Float -&gt; Float -&gt; Float -&gt; Maybe GraphBound\n</code></pre>\n\n<p>However, that's an overkill, so let's not focus on that for too long.</p>\n\n<h1>List comprehensions vs. point-free</h1>\n\n<p>Now let's get back to your original query. Is it possible to make <code>graph</code> more point-free?</p>\n\n<p>Sure:</p>\n\n<pre><code>graph :: (Float -&gt; Float) -&gt; (Float, Float, Float, Float) -&gt; Float -&gt; Picture\ngraph f (l, r, b, t) = pictures . map Line \n . filter (all (\\(_,y) -&gt; b &lt;= y &amp;&amp; t &gt;= y)) \n . (tail &gt;&gt;= flip (zipWith (\\x y -&gt; [x, y]))) \n . map (\\x -&gt; (x, f x)) \n . flip (enumFromThenTo l) r . (l+)\n</code></pre>\n\n<p>The point <code>dx</code> is completely gone from <code>graph</code>. However, the function is now unreadable. We went from a perfectly understandable function to a highly complex one. It gets a lot more readable if we use some helpers, but at that point we're almost back to your original function:</p>\n\n<pre><code>graph :: (Float -&gt; Float) -&gt; (Float, Float, Float, Float) -&gt; Float -&gt; Picture\ngraph f (l, r, b, t) = pictures . map Line . filter inGraph\n . segments . points . ranged\n where\n inGraph (_,y) = fall (\\(_,y) -&gt; b &lt;= y &amp;&amp; t &gt;= y)\n segments ps = zipWith (\\x y -&gt; [x, y]) ps $ tail ps\n ...\n</code></pre>\n\n<p>That's not better than your original version, because <strong>your original version is already very good to begin with</strong>. The only change I could envision is a list comprehension in <code>visible</code>, but that's a matter of preference:</p>\n\n<pre><code>graph :: (Float -&gt; Float) -&gt; (Float, Float, Float, Float) -&gt; Float -&gt; Picture\ngraph f (l, r, b, t) dx = pictures lines\n where\n points = [(x, f x) | x &lt;- [l,l+dx..r]]\n pairs = zipWith (\\x y -&gt; [x,y]) points $ tail points\n\n lines = [Line segment | segment &lt;- pairs, all (\\(_,y) -&gt; b &lt;= y &amp;&amp; t &gt;= y)) segment]\n</code></pre>\n\n<p>But you're the judge on which variant <em>you</em> want to use.</p>\n\n<h1>Other remarks</h1>\n\n<p>Thank you for using type signatures. Keep in mind that it's uncommon to use them in local bindings (<code>where</code>), as the outer function's signature should fix all types already. Inner type signatures can be a hassle if you change your outer type signature later, but they're sometimes necessary.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T15:14:24.293", "Id": "231147", "ParentId": "231027", "Score": "3" } } ]
{ "AcceptedAnswerId": "231147", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T07:08:56.187", "Id": "231027", "Score": "5", "Tags": [ "beginner", "haskell", "data-visualization" ], "Title": "Haskell Graphing Module (Gloss)" }
231027
<p>Writing an EventLoop in C++. Few requirements, from a user perspective:</p> <ol> <li>Must be simple to use (as simple as the Javascript event loop)</li> <li>No type casting, no complex registering of event handler. Plain and simple API.</li> <li>Event handlers have the proper event type passed to them as reference.</li> <li>Should be able to register handlers and inject events in event handler themselves (prevent race conditions)</li> <li>User can define events by just creating a class that derives from Event. There should be no need to implement a function or do anything in that class (POCO).</li> <li>header only</li> </ol> <p>From a maintainer perspective:</p> <ol> <li>As static as possible (avoid dynamic cast, dynamic allocation, pointers...)</li> <li>As efficient as possible (as few object copy as possible)</li> </ol> <pre class="lang-cpp prettyprint-override"><code>#include &lt;algorithm&gt; #include &lt;condition_variable&gt; #include &lt;functional&gt; #include &lt;iostream&gt; #include &lt;map&gt; #include &lt;mutex&gt; #include &lt;queue&gt; #include &lt;thread&gt; #include &lt;typeindex&gt; // Pre-declaration class Message; class Event {}; // Represent a function that will be called with an event. typedef std::function&lt;void(Event&amp;)&gt; EventHandler; // Utility function for our Event map. template&lt;typename T&gt; auto get_event_type() -&gt; std::type_index { return std::type_index(typeid(T)); } // User defined event. POCO! class KeyDownEvent: public Event { public: KeyDownEvent(int _key): key(_key) {} int key; }; // Another user defined event. class TimeoutEvent: public Event { public: TimeoutEvent() {} }; // A message is an event and its associated event handler. Designed inspired by // https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop. class Message { public: template &lt;typename EventType&gt; Message(EventType &amp;&amp;event, EventHandler event_handler) : m_event(std::make_unique&lt;EventType&gt;(std::move(event))), m_event_handler(event_handler) {} template &lt;typename EventType&gt; Message(Message&amp;&amp; message) : m_event(std::move(message.m_event)), m_event_handler(message.m_event_handler) {} std::unique_ptr&lt;Event&gt; m_event; EventHandler m_event_handler; }; class EventLoop { public: [[ noreturn ]] void run() { while (true) { std::unique_lock&lt;std::mutex&gt; lock(m_message_queue_mutex); // Wait for an event m_event_cv.wait(lock, [&amp;]{ return m_message_queue.size() &gt; 0; }); // Retrieve the injected event Message message = std::move(m_message_queue.front()); m_message_queue.pop(); // Unlock before notify, is this necessary? Where did I saw that? lock.unlock(); m_event_cv.notify_one(); // Call the event listener message.m_event_handler(*message.m_event.get()); } } template&lt;class EventType&gt; void add_event_listener(std::function&lt;void(EventType&amp;)&gt; event_listener) { std::lock_guard&lt;std::mutex&gt; guard(m_event_listeners_mutex); std::type_index event_type = get_event_type&lt;EventType&gt;(); // If the event_type as no listener yet... if (m_event_listeners.find(event_type) == m_event_listeners.end()) { // ... create the vector of listeners m_event_listeners[event_type] = { [&amp;event_listener](Event&amp; e) { event_listener(static_cast&lt;EventType&amp;&gt;(e)); } }; } else { // ... or append to the existing one. m_event_listeners[event_type].push_back([&amp;event_listener](Event&amp; e) { event_listener(static_cast&lt;EventType&amp;&gt;(e)); }); } } // Convert an event to a message to be handled by the event loop. template &lt;class EventType, typename ...EventParamsType&gt; void inject_event(EventParamsType&amp;&amp;... event_params) { std::lock_guard&lt;std::mutex&gt; listener_guard(m_event_listeners_mutex); std::vector&lt;EventHandler&gt;&amp; listeners = m_event_listeners[get_event_type&lt;EventType&gt;()]; std::lock_guard&lt;std::mutex&gt; event_guard(m_message_queue_mutex); std::for_each(listeners.begin(), listeners.end(), [this, &amp;event_params...](EventHandler &amp;listener) { EventType event = EventType(std::forward&lt;EventParamsType&gt;(event_params)...); m_message_queue.emplace(std::move(event), listener); }); m_event_cv.notify_one(); } private: std::queue&lt;Message&gt; m_message_queue; std::mutex m_message_queue_mutex; std::condition_variable m_event_cv; std::map&lt;std::type_index, std::vector&lt;EventHandler&gt;&gt; m_event_listeners; std::mutex m_event_listeners_mutex; }; </code></pre> <p>Could be used this way:</p> <pre class="lang-cpp prettyprint-override"><code>int main() { EventLoop eventLoop; std::thread mainThread(&amp;EventLoop::run, &amp;eventLoop); // Register event handlers eventLoop.add_event_listener&lt;KeyDownEvent&gt;([](KeyDownEvent&amp; event) { std::cout &lt;&lt; "*" &lt;&lt; event.key &lt;&lt; "*" &lt;&lt; std::endl; }); eventLoop.add_event_listener&lt;TimeoutEvent&gt;([](TimeoutEvent&amp;) { std::cout &lt;&lt; "timeout!" &lt;&lt; std::endl; }); do { int key = getchar(); if (key != 10) { eventLoop.inject_event&lt;KeyDownEvent&gt;(key); } } while (true); } </code></pre> <p>This <code>EventLoop</code> is basically an event <a href="https://en.wikipedia.org/wiki/Reactor_pattern" rel="noreferrer"><code>Reactor</code></a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T10:58:39.123", "Id": "450278", "Score": "0", "body": "Why all those `this->`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T11:23:35.290", "Id": "450279", "Score": "0", "body": "A bad habit I got from typescript which helps me separate local variable and class members." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T13:33:55.883", "Id": "450282", "Score": "0", "body": "Welcome to code review. Fortunately or unfortunately this question might be considered off-topic because the example usage isn't even a function, let alone a class or code module." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T14:10:44.783", "Id": "450287", "Score": "0", "body": "@pacmaninbw, So if I put the example usage in a function would that make the question on-topic? Could you point me to the guidelines of the site?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T14:12:38.157", "Id": "450288", "Score": "0", "body": "It would help, Do you have any unit testing code for it? Posting an entire program would be difficult." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T01:55:30.920", "Id": "450365", "Score": "2", "body": "Welcome to Code Review! Please see our [Help] page for guidelines about posting new questions and getting the most from your post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T13:38:07.903", "Id": "450453", "Score": "0", "body": "@Malachi is it accepted to post a link to an external page documenting the end-result (code after comment taken into account) ? If yes, where should I put the link, in a comment?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T16:56:16.963", "Id": "450478", "Score": "0", "body": "@LukeSkywalker that is acceptable, you could also post a [follow up question](https://codereview.meta.stackexchange.com/questions/1065/how-to-post-a-follow-up-question) we have a process described in the link I gave." } ]
[ { "body": "<pre><code>template &lt;typename EventType&gt;\nMessage(EventType &amp;&amp;event, EventHandler event_handler):\n m_event(std::make_unique&lt;EventType&gt;(std::move(event))),\n m_event_handler(event_handler) {}\n</code></pre>\n\n<p>Requiring an r-value <code>event</code> seems unnecessary here; we should probably take it by value.</p>\n\n<hr>\n\n<pre><code> template &lt;typename EventType&gt;\n Message(Message&amp;&amp; message) :\n m_event(std::move(message.m_event)),\n m_event_handler(message.m_event_handler) {}\n</code></pre>\n\n<p><strong>bug:</strong> This move constructor shouldn't have a template parameter.</p>\n\n<hr>\n\n<pre><code> template&lt;class EventType&gt;\n void add_event_listener(std::function&lt;void(EventType&amp;)&gt; event_listener) {\n ...\n\n if (m_event_listeners.find(event_type) == m_event_listeners.end()) {\n m_event_listeners[event_type] = {\n [event_listener](Event&amp; e) { event_listener(static_cast&lt;EventType&amp;&gt;(e)); }\n };\n }\n else {\n m_event_listeners[event_type].push_back([&amp;event_listener] (Event&amp; e) {\n event_listener(static_cast&lt;EventType&amp;&gt;(e));\n });\n }\n }\n</code></pre>\n\n<p><strong>bug:</strong> <code>event_listener</code> <em>must</em> be captured by value, not by reference, in both these lambdas (as a local variable it will be dead before the reference is used).</p>\n\n<p>Note that we don't need the <code>find</code> and two separate branches; <code>operator[]</code> will add an empty vector for us so we can just do:</p>\n\n<pre><code> m_event_listeners[event_type].push_back([event_listener] (Event&amp; e) {\n event_listener(static_cast&lt;EventType&amp;&gt;(e));\n });\n</code></pre>\n\n<hr>\n\n<pre><code>[[noreturn]] void run() {\n while (true) {\n ...\n m_event_cv.notify_one();\n ...\n }\n}\n</code></pre>\n\n<p>I don't understand the reason for calling <code>m_event_cv.notify_one()</code> here. Are we trying to allow multiple threads to call <code>run()</code>? </p>\n\n<p>If so, they'll miss out on messages, since we've removed one from the queue.</p>\n\n<p>If not, the next iteration of the <code>run()</code> loop will carry on processing if there are messages on the queue, since the <a href=\"https://en.cppreference.com/w/cpp/thread/condition_variable/wait\" rel=\"nofollow noreferrer\">predicate is checked before waiting</a>. So there should be no need to call notify again.</p>\n\n<hr>\n\n<pre><code>template &lt;class EventType, typename ...EventParamsType&gt;\nvoid inject_event(EventParamsType&amp;&amp;... event_params) {\n</code></pre>\n\n<p>The perfect forwarding here seems more complicated than passing in an <code>EventType</code> argument.</p>\n\n<hr>\n\n<pre><code>typedef std::function&lt;void(Event&amp;)&gt; EventHandler;\n...\nMessage(EventType event, EventHandler event_handler):\n...\nvoid add_event_listener(std::function&lt;void(EventType&amp;)&gt; event_listener) {\n...\n std::for_each(listeners.begin(), listeners.end(), [this, &amp;event](EventHandler &amp;listener) {\n</code></pre>\n\n<p>Consistency: we should choose either \"listener\" or \"handler\", and stick with it.</p>\n\n<hr>\n\n<pre><code>...\n std::for_each(listeners.begin(), listeners.end(), [this, &amp;event_params...](EventHandler &amp;listener) {\n EventType event = EventType(std::forward&lt;EventParamsType&gt;(event_params)...);\n m_message_queue.emplace(std::move(event), listener);\n });\n\n...\n\nstd::queue&lt;Message&gt; m_message_queue;\n</code></pre>\n\n<p>We could perhaps:</p>\n\n<ul>\n<li>Make the <code>Event</code> argument to <code>EventHandler</code> a <code>const&amp;</code>.</li>\n<li>Have an <code>Event</code> queue, instead of a <code>Message</code> queue (or technically a <code>std::queue&lt;std::pair&lt;std::unique_ptr&lt;Event&gt;, std::type_index&gt;&gt;</code> queue).</li>\n<li>Lock, copy, unlock, and call the relevant listeners for the event in the <code>run()</code> function.</li>\n</ul>\n\n<p>This would allow us to avoid storing and copying the <code>Event</code> so many times. We'd also have one iteration of <code>run()</code> per event, instead of one iteration per listener per event.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T19:12:48.580", "Id": "231054", "ParentId": "231031", "Score": "3" } }, { "body": "<h2>Summary</h2>\n\n<p>Feel free to ignore opinion: </p>\n\n<h3>Personal opinion</h3>\n\n<p>I don't like \"Snake Case\" and I don't see it very often in C++ projects (though an argument against me is the C++ standard library does use it).</p>\n\n<p>I also prefer not to use \"m_\" to identify member variables. It tends to mean that people have not though enough about unique meaningful names elsewhere and need to use the prefix to make things things unique. But on the other hand its not a negative (though I would advice adding build tools to enforce it long term so that half the code uses \"m_\" and another half the code fails to follow the convention.</p>\n\n<p>I don't like the indention level is only two spaces. Its a bit small and makes it hard to read. I would prefer at least 4 spaces.</p>\n\n<p>Why do half your functions use:</p>\n\n<pre><code>auto function() -&gt; type\n</code></pre>\n\n<p>While half use the:</p>\n\n<pre><code>type function()\n</code></pre>\n\n<p>I would prefer to use one form consistently rather than a mixture. Though if you use the second form you can use the first form for those exceptional situations where it is required that you use the first form.</p>\n\n<h2>Code Review</h2>\n\n<p>Interesting that you even need an <code>Event</code> base if there are no virtual members.</p>\n\n<pre><code>class Event {};\n</code></pre>\n\n<hr>\n\n<p>The class <code>EventLoop</code> is a little dense in terms of code and comments and this makes it hard to read. This is definitely a case where the comments hinder the readability. You should simply remove these.</p>\n\n<pre><code> [[ noreturn ]] void run() {\n while (true) {\n std::unique_lock&lt;std::mutex&gt; lock(m_message_queue_mutex);\n // Wait for an event\n m_event_cv.wait(lock, [&amp;]{ return m_message_queue.size() &gt; 0; });\n // Retrieve the injected event\n Message message = std::move(m_message_queue.front());\n m_message_queue.pop();\n // Unlock before notify, is this necessary? Where did I saw that?\n lock.unlock();\n m_event_cv.notify_one();\n // Call the event listener\n message.m_event_handler(*message.m_event.get());\n }\n }\n</code></pre>\n\n<p>Let's remove the comments and add some vertical white space and break into two logical functions. Note by using <code>getNextEvent()</code> I don't need to explicitly <code>unlock()</code> the <code>lock</code> as this is done as <code>getNextEvent()</code> exits with the destructor of <code>lock</code>.</p>\n\n<pre><code> private:\n Message getNextEvent()\n {\n std::unique_lock&lt;std::mutex&gt; lock(m_message_queue_mutex);\n m_event_cv.wait(lock, [&amp;]{ return m_message_queue.size() &gt; 0; });\n\n Message message = std::move(m_message_queue.front());\n m_message_queue.pop();\n\n return message;\n }\n\n public:\n [[ noreturn ]] void run() {\n while (true) {\n Message message = getNextEvent();\n\n m_event_cv.notify_one();\n message.m_event_handler(*message.m_event.get());\n }\n }\n</code></pre>\n\n<hr>\n\n<p>Not sure a <code>noreturn</code> is appropriate.</p>\n\n<pre><code> [[ noreturn ]] void run() {\n</code></pre>\n\n<p>Most application have a way to exit. So when the user selects exit your event loop should exit. </p>\n\n<hr>\n\n<pre><code> // Unlock before notify, is this necessary? Where did I saw that?\n lock.unlock();\n m_event_cv.notify_one();\n</code></pre>\n\n<p>Is it necessary? No. It will still work either way.</p>\n\n<p>Will it be more efficient? That will depend on the implementation. ITs hard to make a determination either way. But unlocking first will avoid a potential inefficiency. So I would do it this way but that does not provide anything.</p>\n\n<hr>\n\n<p>You don't need an <code>else</code> here</p>\n\n<pre><code> if (m_event_listeners.find(event_type) == m_event_listeners.end()) {\n m_event_listeners[event_type] = {\n [&amp;event_listener](Event&amp; e) { event_listener(static_cast&lt;EventType&amp;&gt;(e)); }\n };\n } else {\n m_event_listeners[event_type].push_back([&amp;event_listener](Event&amp; e) {\n event_listener(static_cast&lt;EventType&amp;&gt;(e));\n });\n }\n</code></pre>\n\n<p>I can simplify this too:</p>\n\n<pre><code> m_event_listeners[event_type].push_back([&amp;event_listener](Event&amp; e) {\n event_listener(static_cast&lt;EventType&amp;&gt;(e));\n });\n</code></pre>\n\n<p>This is because <code>m_event_listeners</code> has <code>operator[]()</code> will automatically insert an empty vector if that value does not exist.</p>\n\n<hr>\n\n<p>To make this work you need to convert an <code>Event</code> object into the functions <code>EventType</code> so you use <code>static_cast</code> to achieve this:</p>\n\n<pre><code>[&amp;event_listener](Event&amp; e) { event_listener(static_cast&lt;EventType&amp;&gt;(e)); }\n</code></pre>\n\n<p>This should be fine in <strong>\"Simple\"</strong> situations. But there are situations were \"Simple\" is not going to work. In these case's you are going to need <code>dynamic_cast</code> to make this work in all situations.</p>\n\n<hr>\n\n<p>I don't see anything wrong <code>inject_event()</code> that I can complain about.</p>\n\n<hr>\n\n<p>The one thing I normally see in event driven applications is that some handlers can swallow the event preventing subsequent handlers from performing actions based on the event.</p>\n\n<p>Your code forces every event handler to handle the event. You could prevent this by adding a <code>handled</code> member to the <code>Event</code> base class. Then the lambda can check this value before calling the user provided haandler.</p>\n\n<pre><code> class Event\n {\n bool handeled;\n public:\n virtual ~Event() {}\n Event(): handeled(false) {}\n bool isHandeled() const {return handeled;}\n };\n\n // .....\n\n m_event_listeners[event_type].push_back([&amp;event_listener](Event&amp; e) {\n try {\n if (!e.isHandeled()) {\n event_listener(dynamic_cast&lt;EventType&amp;&gt;(e));\n }\n }\n catch(...) {\n // Event handlers are not written by me so I don't know how\n // they will work. I want to make sure exceptions in their\n // code don't cause the run() method to exit accidentally.\n\n // Do something to tell user there was an exception.\n }\n });\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T19:39:18.770", "Id": "450331", "Score": "0", "body": "Thanks a lot for your review. Could you explain in what situation will the static_cast not work? Maybe with an example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T20:41:31.993", "Id": "450339", "Score": "0", "body": "@LukeSkywalker no explicitly. But the rules for `static_cast` are very complex https://en.cppreference.com/w/cpp/language/static_cast and the results are usually UB which is hard to show that it is broken because UB can work on some compilers but not others." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T19:32:05.793", "Id": "231055", "ParentId": "231031", "Score": "3" } }, { "body": "<p>Don't know if you dislike \"not this-lang-onian\" comments...</p>\n\n<pre><code>typedef std::function&lt;void(Event&amp;)&gt; EventHandler;\n</code></pre>\n\n<p>should be </p>\n\n<pre><code>using EventHandler = std::function&lt;void(Event&amp;)&gt;;\n</code></pre>\n\n<hr>\n\n<pre><code>auto get_event_type() -&gt; std::type_index {\n return std::type_index(typeid(T));\n}\n</code></pre>\n\n<p>you already have type in <code>return</code> statement, no need for trailing return type</p>\n\n<hr>\n\n<pre><code> Message(EventType &amp;&amp;event, EventHandler event_handler) :\n m_event(std::make_unique&lt;EventType&gt;(std::move(event))),\n</code></pre>\n\n<p>you already input <code>event</code> as r-value reference. no need for <code>std::move</code></p>\n\n<hr>\n\n<pre><code>template &lt;typename EventType&gt;\nMessage(Message&amp;&amp; message) :\n m_event(std::move(message.m_event)),\n m_event_handler(message.m_event_handler) {}\n</code></pre>\n\n<p>1) doesn't depend on <code>EventType</code>, so doesn't need template wrapper<br>\n2) looks like standard move constructor for me, so </p>\n\n<pre><code>Message(Message&amp;&amp;) = default;\n</code></pre>\n\n<p>or even no mention of it would be enough</p>\n\n<p><strong>Also</strong><br>\nIf you do declare move constructor, by rule of five, you should say explicitly if you allow copy constructor, copy assignment and move assignment</p>\n\n<hr>\n\n<pre><code>void run() {\n...\nm_event_cv.notify_one();\n</code></pre>\n\n<p>I think I got the reason behind it - in case 2 events happens soon one after another (or, more probably, 2 messages from same event), the <code>run()</code> should loop over each of them...<br>\nBut it's not done via <code>notify_one</code>\nNoone is listening for it to be notified!</p>\n\n<p>Better approach probably would probably just copying queue, clearing the original and running <code>for_all</code> on local copy</p>\n\n<p><strong><code>lock.unlock();</code> here is critically important</strong>, as we don't want handlers that last long time to slow down event creators (that are waiting for <code>m_message_queue_mutex</code>)</p>\n\n<hr>\n\n<pre><code>message.m_event_handler(*message.m_event.get());\n</code></pre>\n\n<p>you're applying operator* to the inside raw pointer, while you can safely do that with unique_ptr too<br>\n(change <code>*message.m_event.get()</code> into <code>*message.m_event</code>)</p>\n\n<hr>\n\n<p>So far everything looks good. All mistakes are minor. Logic structure is in place </p>\n\n<p>Container for multiple derived classes in form of base class pointers is well known.<br>\nBut this is first time I've ever seen container for functions that use derived class via wrapping function that takes base reference<br>\nReally clever</p>\n\n<p>Thanks for experience! =)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T13:47:56.183", "Id": "450458", "Score": "0", "body": "An rvalue-reference is actually an lvalue. So it most definitely needs to be moved if passed on. [Have a look](https://wandbox.org/permlink/XNKxxXM1UHlM7noj)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T00:35:03.377", "Id": "450525", "Score": "0", "body": "@super TIL... i guess my intuition should've been \"it has name - it is l-reference\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T13:09:40.720", "Id": "231099", "ParentId": "231031", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T09:28:28.123", "Id": "231031", "Score": "9", "Tags": [ "c++", "reinventing-the-wheel", "event-handling" ], "Title": "Event loop in C++" }
231031
<p>I have implemented the <a href="https://youtu.be/spUNpyF58BY" rel="nofollow noreferrer">3Blue1Brown's description of Fourier transform</a> in Python+numpy for irregular and unsorted data, as described <a href="https://www.reddit.com/r/Python/comments/dk85ue/easy_fourier_transform_implementing_3blue1browns/?utm_source=share&amp;utm_medium=web2x" rel="nofollow noreferrer">here</a>. </p> <pre class="lang-py prettyprint-override"><code>import numpy as np import matplotlib.pyplot as plt def polarToRectangular(radii, angles): return radii * np.exp(1j * angles) def frequencyGenerator(time, steps = 100): = time.max() - time.min() M = np.arange(1, steps + 1)[:, np.newaxis] return M / def easyFourierTransform(time, values, frequency = None, steps = 100): if frequency is None: ft = frequencyGenerator(time, steps) frequency = ft.reshape(ft.shape[0]) else: ft = frequency[:, np.newaxis] # sorting the inputs order = np.argsort(time) ts = np.array(time)[order] Xs = np.array(values)[order] = (ts - time.min()) * 2 * np.pi * ft Y = polarToRectangular(Xs, )[:, :-1] * np.diff(ts) amplitude = np.abs(Y.sum(axis=1)) return frequency, amplitude </code></pre> <p>I'm thinking maybe I can suggest this to be added to numpy/scypy. However, I'm not sure if this small piece of code is qualified to be added upstream. I was wondering if you could help me know:</p> <ul> <li>Is this code correct? Does it actually return the Fourier transform? I want to be sure there are no logical errors.</li> <li>Is this a performant code or there is any way to improve performance?</li> <li>Is the formating good enough? Should I comply with PEP8 standard or numpy/scipy require different best practices?</li> <li>Is this novel or it has been done before? (not necessarily relevant to this forum but still my question)</li> </ul> <p><strong>Keywords:</strong> nonuniform, uniformly, unevenly, sampled, distributed</p> <p><strong>P.S.</strong> Updated version of the code plus examples in <a href="https://notebooks.azure.com/fsfarimani/projects/easy-fourier-transform" rel="nofollow noreferrer">this Jupyter notebook</a>. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T11:50:44.027", "Id": "450436", "Score": "1", "body": "scipy has [contribution guidelines](https://docs.scipy.org/doc/scipy/reference/hacking.html#contributing-new-code), describing what they expect from new code contributions. PEP8 conformance is one of the requirements listed there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-13T06:31:42.740", "Id": "525442", "Score": "0", "body": "How do you actually plot this?\nI'm interested in an example!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T10:50:41.380", "Id": "525657", "Score": "0", "body": "@FirasBejar you may use [this other post](https://stackoverflow.com/a/53772921/4999991) as an example." } ]
[ { "body": "<p>As I already mentioned in a comment below your question, scipy has <a href=\"https://docs.scipy.org/doc/scipy/reference/hacking.html#contributing-new-code\" rel=\"nofollow noreferrer\">contribution guidelines</a> that tell you what they expect from your code before even thinking about including it into scipy. The major keywords are:</p>\n\n<ol>\n<li>Unit tests</li>\n<li>Documentation</li>\n<li>Code style</li>\n</ol>\n\n<h1>Testing</h1>\n\n<p>The first point of this list would also help you to answer your question about the algorithm's correctness automatically. This <a href=\"https://dsp.stackexchange.com/a/635\">answers</a> to <a href=\"https://dsp.stackexchange.com/q/633\"><em>What data should I use to test an FFT implementation, and what accuracy should I expect?</em></a> on the Signal Processing Stack Exchange can help you to get an idea on how that might look like. The documentation of the relevant functions (e.g. <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fft.html\" rel=\"nofollow noreferrer\">numpy.fft.fft</a>) in the scipy stack and <a href=\"https://github.com/numpy/numpy/blob/master/numpy/fft/tests/test_pocketfft.py\" rel=\"nofollow noreferrer\">their associated tests</a> can provide further hints. Since my knowledge on FT, DFT, FFT, WTF (;-) ), and the likes is a bit \"rusty\", you maybe have to look for ressources more appropriately matching what you intend to do.</p>\n\n<h1>Documentation</h1>\n\n<p>The documentation part is comparatevely simple. Again, there are <a href=\"https://docs.scipy.org/doc/numpy/docs/howto_document.html\" rel=\"nofollow noreferrer\">guidelines</a> on how to document code associated with the scientific Python stack (everything surrounding numpy/scipy). An example:</p>\n\n<pre><code>def polar_to_complex(radii, angles):\n \"\"\"Return r-phi coordinates to complex numbers\n\n Parameters\n ----------\n radii, angles: array_like\n radial and angular component of the polar coordinates. Both input have\n to have the same shape\n\n Returns\n -------\n out: ndarray\n complex representation of the given r-phi coordinates\n \"\"\"\n return radii * np.exp(1j * angles)\n</code></pre>\n\n<p>This is also commonly called numpydoc oder NumPy-style documentation. It's a very feature rich style and I highly recommend to have a look at the ressource linked above to learn more.</p>\n\n<p>Regarding type annotations: they are just that, annotations or hints. They are not checked during runtime, i.e. the Python interpreter does not care about your carefully crafted type hints. Static code analysis tools like <a href=\"http://mypy-lang.org/\" rel=\"nofollow noreferrer\">mypy</a> and <a href=\"https://www.pylint.org/\" rel=\"nofollow noreferrer\">pylint</a> are the tools that would make use of them to tell you about flaws that can be checked without actually running your code, hence the name \"static code analysis\". If you really want to make sure that all the inputs are how you expect them to be, you will have to write your own validation code raising appropriate exceptions at runtime to tell whoever uses your library incorrectly that they're doing so.</p>\n\n<h1>Style</h1>\n\n<p>The contribution guidelines clearly describe that your code is supposed to conform to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> conventions. There is also a hint to use automatic tooling in order to check your code in that regard. In case you don't like there suggestion on what tool to use, fear not! This <a href=\"https://codereview.meta.stackexchange.com/a/5252/92478\">answer on Code Review meta</a> lists quite a few other tools that can help you in your endeavours to write beautiful Python code. Among others, they should tell you to use <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\"><code>lower_case_with_underscore</code> names for function and variable names</a>, <a href=\"https://www.python.org/dev/peps/pep-0008/#other-recommendations\" rel=\"nofollow noreferrer\">avoid whitespace around <code>=</code> when used in keyword-arguments</a>, and that there <a href=\"https://www.python.org/dev/peps/pep-0008/#blank-lines\" rel=\"nofollow noreferrer\">should be two blank lines between functions at the module level</a>.</p>\n\n<h1>Performance</h1>\n\n<p>I have not actively checked the performance of your implementation compared to what's already implemented in numpy/scipy, but from my experience and since Fourier transformations are a very widely used tool, I highly suspect that such a simple implementation will be no match for current state-of-the-art implementations likely present in numpy/scipy. As I said, I did not check, so I might be wrong here.</p>\n\n<p>If I were to guess, sorting is likely the single most costly operation in your algorithm, but again I have not measured it. If you are willing to look into this, <a href=\"https://docs.python.org/3/library/profile.html\" rel=\"nofollow noreferrer\"><code>cProfile</code></a> and <a href=\"https://docs.python.org/3/library/timeit.html\" rel=\"nofollow noreferrer\"><code>timeit</code></a> are likely the modules to look at.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T20:22:09.270", "Id": "231117", "ParentId": "231036", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T11:29:14.457", "Id": "231036", "Score": "5", "Tags": [ "python", "numpy", "signal-processing" ], "Title": "Implementing 3Blue1Brown's description of Fourier transform in Python+numpy" }
231036
<p>Hi friends i have this code for select input change, i need some good advice if this code is ok like that or is a way to optimize this code? thanks!</p> <p>This code is used for changing info's between selected input options.</p> <p>This code is for two select inputs "SECTIONS" and "AGE CATEGORY". If a user select a value from sections the age category will be changed regarding the value from Section option.</p> <p>Example: If i select from sections value "Solo" the Age category values will be changed to values for "Solo" such as (4-6 Years, 7-9 Years,and so on) Script is used for a dancing contest registration form.</p> <p>javascript:</p> <pre><code>$("select[name=sections]").on("change", function () { if ($(this).val() === 'Solo') { $('#mini,#copii,#juniori').hide(); $('#baby,#solo7,#solo8,#solo9,#solo10,#solo11,#solo12,#solo13,#solo14,#solo15,#seniori').show(); $("input[type='text'][name='numeformatie']").val('-'); $("input[type='text'][name='numeformatie']").prop('disabled', true); $("input[type='text'][name='nrdansatori']").val('1'); $("input[type='text'][name='dansator1']").val(''); $(".dansator1").show(); $("input[type='text'][name='nrdansatori']").prop('disabled', true);} else if ($(this).val() === 'Duo/Trio/Quartet') { $('#baby,#mini,#copii,#juniori,#seniori').show(); $('#solo7,#solo8,#solo9,#solo10,#solo11,#solo12,#solo13,#solo14,#solo15').hide(); $("input[type='text'][name='numeformatie']").val('-'); $("input[type='text'][name='numeformatie']").prop('disabled', true); $("input[type='text'][name='nrdansatori']").val(); $("input[type='text'][name='dansator1']").val(''); $(".dansator1").show(); $("input[type='text'][name='nrdansatori']").prop('disabled', false);} else if ($(this).val() === 'Grupuri') { $('#baby,#mini,#copii,#juniori,#seniori').show(); $('#solo7,#solo8,#solo9,#solo10,#solo11,#solo12,#solo13,#solo14,#solo15').hide(); $("input[type='text'][name='numeformatie']").val(); $("input[type='text'][name='numeformatie']").prop('disabled', false); $("input[type='text'][name='dansator1']").val('-'); $(".dansator1").hide();} else if ($(this).val() === 'Formatii') { $('#baby,#mini,#copii,#juniori,#seniori').show(); $('#solo7,#solo8,#solo9,#solo10,#solo11,#solo12,#solo13,#solo14,#solo15').hide(); $("input[type='text'][name='numeformatie']").val(''); $("input[type='text'][name='numeformatie']").prop('disabled', false); $("input[type='text'][name='dansator1']").val('-'); $("input[type='text'][name='nrdansatori']").prop('disabled', false); $(".dansator1").hide();} }).trigger('change'); </code></pre> <p>Html:</p> <pre><code>&lt;select name="sections" id="sections&lt;?php echo $id;?&gt;" class="form-control"&gt; &lt;option class="noselect" selected value="&lt;?php echo $sectiuni; ?&gt;"&gt;&lt;?php echo $sectiuni; ?&gt;&lt;/option&gt; &lt;option id="solo" value="Solo"&gt;Solo&lt;/option&gt; &lt;option id="duo" value="Duo/Trio/Quartet"&gt;Duo/Trio/Quartet&lt;/option&gt; &lt;option id="grupuri" value="Grupuri"&gt;Grupuri 5-12 dansatori&lt;/option&gt; &lt;option id="formatii" value="Formatii"&gt;Formaţii peste 13 dansatori&lt;/option&gt; &lt;/select&gt; &lt;select id="agecategory&lt;?php echo $id;?&gt;" name="agecategory" class="form-control"&gt; &lt;option class="noselect" selected value="&lt;?php echo $catvarsta; ?&gt;"&gt;&lt;?php echo $catvarsta; ?&gt;&lt;/option&gt; &lt;option id="baby" value="4-6 ani - BABY"&gt;4-6 years&lt;/option&gt; &lt;option id="mini" value="7-9 ani - MINI"&gt;7-9 years&lt;/option&gt; &lt;option id="solo7" value="7 ani"&gt;7 years - SOLO&lt;/option&gt; &lt;option id="solo8" value="8 ani"&gt;8 years - SOLO&lt;/option&gt; &lt;option id="solo9" value="9 ani"&gt;9 years- SOLO&lt;/option&gt; &lt;option id="copii" value="10-12 ani - COPII"&gt;10-12 years&lt;/option&gt; &lt;option id="solo10" value="10 ani"&gt;10 years - SOLO&lt;/option&gt; &lt;option id="solo11" value="11 ani"&gt;11 years- SOLO&lt;/option&gt; &lt;option id="solo12" value="12 ani"&gt;12 years- SOLO&lt;/option&gt; &lt;option id="juniori" value="13-15 ani - JUNIORI"&gt;13-15 years&lt;/option&gt; &lt;option id="solo13" value="13 ani"&gt;13 years - SOLO&lt;/option&gt; &lt;option id="solo14" value="14 ani"&gt;14 years - SOLO&lt;/option&gt; &lt;option id="solo15" value="15 ani"&gt;15 years - SOLO&lt;/option&gt; &lt;option id="seniori" value="+ 16 ANI - SENIORI"&gt;+ 16 years&lt;/option&gt; &lt;/select&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T10:29:59.493", "Id": "450560", "Score": "0", "body": "You could consider using [`<optgroup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup)-elements, which would simplify the code as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T15:48:04.417", "Id": "450598", "Score": "0", "body": "Can u show me how ?" } ]
[ { "body": "<p>This can only be an incomplete review, as the HTML is still missing, but it should point you in the direction of things to do.</p>\n\n<p>You have a lot of repetition in your code, here's how to do it with less repetition.</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>var $num= $(\"input[type='text'][name='numeformatie']\");\nvar $nrd= $(\"input[type='text'][name='nrdansatori']\");\nvar sol='#solo7,#solo8,#solo9,#solo10,#solo11,#solo12,#solo13,#solo14,#solo15',\n cases={\n Solo: {numv:'-',numdis:'true',nrdv:'1',dv1:'',nrddis:true,\n shw:'.dansador1,#baby,#seniori,'+sol, hid:'#mini,#copii,#juniori'},\n 'Duo/Trio/Quartet': {numv:'-',numdis:'true',nrdv:'1',dv1:'',nrddis:true,\n shw:'.dansador1,#baby,#mini,#copii,#juniori,#seniori', hid:sol},\n Grupuri: {numv:'-',numdis:'true',nrdv:'1',dv1:'',nrddis:true,\n shw:'#baby,#mini,#copii,#juniori,#seniori', hid:'.dansador1,'+sol},\n Formatii: {numv:'-',numdis:'true',nrdv:'1',dv1:'',nrddis:true,\n shw:'#baby,#mini,#copii,#juniori,#seniori', hid:'.dansador1,'+sol},\n};\n$(\"select[name=sectiuni]\").on(\"change\", function () {\n var c=cases[$(this).val()];\n $(c.hid).hide();\n $(c.shw).show();\n $num.val(c.numv).prop('disabled',c.numdis);\n $nrd.val(c.nrdv).prop('disabled',c.nrddis);\n}).trigger('change');</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T16:44:53.620", "Id": "450311", "Score": "4", "body": "I'd say that this is not a review at all but a code dump. Please tell us something about your recommendations so that we may learn from your thought process." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T16:46:47.437", "Id": "450313", "Score": "1", "body": "I didn't downvote, but I don't like your lack of naming standards. `c` is not very descriptive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T16:47:31.640", "Id": "450315", "Score": "0", "body": "Fair enough. I am new to Code review and wanted to quickly sketch, how things can be done with less redundancy and repetition. But as said before, my time is running out now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T19:03:28.767", "Id": "450329", "Score": "2", "body": "@cars10m Simply adding \"You have a lot of repetition in your code, here's how to do it with less repetition\" would make this answer better. I will be kind and edit it in for you this time." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T16:37:26.230", "Id": "231045", "ParentId": "231044", "Score": "1" } }, { "body": "<p>Use proper indentation for better readability.</p>\n\n<p>Hide all values first. This way you only need to keep track of which values you want shown.</p>\n\n<p>You can use parallel arrays or an object to better keep track of which values you want shown/hidden. For example:</p>\n\n<pre><code>const selectionOptions = {\n \"Solo\": { \n \"optionsToShow\": '#baby,#solo7,#solo8,#solo9,#solo10,#solo11,#solo12,#solo13,#solo14,#solo15,#seniori'\n }\n}\n</code></pre>\n\n<p>Here's a JSFiddle demonstration: <a href=\"https://jsfiddle.net/nxcpLaug/1/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/nxcpLaug/1/</a></p>\n\n<p>You can do the same to list the values you want reset:</p>\n\n<pre><code>const selectionOptions = {\n \"Solo\": { \n \"optionsToShow\": '#baby,#solo7,#solo8,#solo9,#solo10,#solo11,#solo12,#solo13,#solo14,#solo15,#seniori'\n \"elementsToResetValue\": \"#numeformatie,#numeformatie\"\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T08:27:07.090", "Id": "450400", "Score": "1", "body": "Thank you for your answer and support @dustytrash, i will test'it and i will come with a reply" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T08:46:37.613", "Id": "450405", "Score": "1", "body": "It works just fine, thank you for taking your time to help me, im new and i have so much to learn from you guys." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T23:42:54.843", "Id": "231069", "ParentId": "231044", "Score": "2" } } ]
{ "AcceptedAnswerId": "231069", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T16:02:43.250", "Id": "231044", "Score": "0", "Tags": [ "javascript", "html" ], "Title": "Javascript code for select input" }
231044
<p>I got a mixture of two languages ​​C and C ++</p> <p>The code finds the folder my documents and creates additional folders in it when the program starts, I found no other way to implement this better. I also did not find any ready-made example where all this has already been implemented so as not to make a bicycle, I like when the code looks compact, but it looks bad for me.</p> <pre><code>template &lt;typename T1, typename T2&gt; void knownFolder(T1&amp; setKnownFolderID, T2&amp; getDisplayName) { PWSTR pszFolderPath; for (;;) // !!!&gt; { if (FAILED(SHGetKnownFolderPath(setKnownFolderID, 0, nullptr, &amp;pszFolderPath))) continue; getDisplayName = pszFolderPath; CoTaskMemFree(pszFolderPath); break; // &lt;!! } } </code></pre> <p>/ </p> <pre><code>template &lt;typename T2&gt; void folderLink(T2&amp; setDisplayName, T2&amp; getDisplayName) { getDisplayName = setDisplayName + L"\\" + getDisplayName; for (;;) // !!!&gt; { if (!filesystem::exists(getDisplayName)) if (!filesystem::create_directory(getDisplayName)) continue; break; // &lt;!! } } </code></pre> <p>/ </p> <pre><code>wstring folder_Documents, // C:\ ... \Documents folder_Microsoft = L"Microsoft", // C:\ ... \Documents\Microsoft folder_XP = L"XP", folder_XP_Alpha = L"Alpha", folder_XP_Beta = L"Beta", folder_Win7 = L"Win7", folder_Win7_Alpha = L"Alpha", folder_Win7_Beta = L"Beta"; </code></pre> <p>/ </p> <pre><code>void foldersystem() { knownFolder(FOLDERID_Documents, folder_Documents); // Documents folderLink(folder_Documents, folder_Microsoft); // Microsoft folderLink(folder_Microsoft, folder_XP); // XP folderLink(folder_XP, folder_XP_Alpha); folderLink(folder_XP, folder_XP_Beta); folderLink(folder_Microsoft, folder_Win7); // Win7 folderLink(folder_Win7, folder_Win7_Alpha); folderLink(folder_Win7, folder_Win7_Beta); } </code></pre>
[]
[ { "body": "<h1>Use <code>std::filesystem::path</code> for paths</h1>\n\n<p>C++17 gives you a canonical type to represent filesystem paths, so use that. This avoids having to create templates of all your functions. It also allows you to combine paths together in a portable way:</p>\n\n<pre><code>void folderLink(std::filesystem::path &amp;setDisplayName, std::filesystem::path &amp;getDisplayName)\n{\n getDisplayName = setDisplayName / getDisplayName;\n ...\n}\n</code></pre>\n\n<h1>Use <code>std::filesytem::create_directories()</code></h1>\n\n<p>This function will create the desired directory <em>plus</em> all its parent directories if they do not yet exist. Also, it will not report an error if the desired directory already exists. So you could write:</p>\n\n<pre><code>void foldersystem()\n{\n std::filesystem::path folder_Documents = ...; // get known folder as a path here\n\n std::filesystem::create_directories(folder_Documents / \"Microsoft\" / \"XP\" / \"Alpha\");\n std::filesystem::create_directories(folder_Documents / \"Microsoft\" / \"XP\" / \"Beta\");\n std::filesystem::create_directories(folder_Documents / \"Microsoft\" / \"Win7\" / \"Alpha\");\n std::filesystem::create_directories(folder_Documents / \"Microsoft\" / \"Win7\" / \"Beta\");\n}\n</code></pre>\n\n<h1>Don't infinitely retry on errors</h1>\n\n<p>You are using a very weird pattern with infinite <code>for</code>-loops:</p>\n\n<pre><code>for(;;) {\n if (something_fails())\n continue;\n\n break;\n}\n</code></pre>\n\n<p>If the thing you are trying to do fails, you are retrying it indefinitely. But if it fails once, why do you expect it will work the next time? The right thing to do at this point is just to return an error.</p>\n\n<h1>Prefer returning results instead of using output parameters</h1>\n\n<p>If a function returns something, <code>return</code> that instead of passing a reference to an output parameter. Combined with the use of <code>std::filesystem::path</code>, <code>knownFolder()</code> then becomes:</p>\n\n<pre><code>std::filesystem::path knownFolder(KNOWNFOLDERID fodlerID)\n{\n PWSTR pszFolderPath;\n\n if (FAILED(SHGetKnownFolderPath(folderID, 0, nullptr, &amp;pszFolderPath)))\n throw std::runtime_error(\"Could not get known folder\");\n\n std::filesystem::path result = pszFolderPath;\n CoTaskMemFree(pszFolderPath);\n return result;\n}\n</code></pre>\n\n<h1>Use an array of paths if you have many of them</h1>\n\n<p>If you have many paths to create, then store them in an array, and use a <code>for</code>-loop to create them all. Here is an example:</p>\n\n<pre><code>static const std::filesystem::path required_subdirectories[] = {\n \"XP/Alpha\",\n \"XP/Beta\",\n \"Win7/Alpha\",\n \"Win7/Beta\",\n};\n\nvoid foldersystem()\n{\n std::filesystem::path folder_Documents = ...; // get known folder as a path here\n\n for (auto &amp;subdirectory: subdirectories) {\n std::filesystem::create_directories(folder_Documents / \"Microsoft\" / subdirectory);\n }\n}\n</code></pre>\n\n<p>Note that using the forward slash is perfectly fine here; the <code>std::filesystem</code> functions understand this as a directory separator.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T18:46:10.703", "Id": "450615", "Score": "0", "body": "thanks, I’m free to try to implement, but so far I have not understood how to keep the data in variables or in arrays" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T20:03:33.410", "Id": "450626", "Score": "0", "body": "@1221 So you want to know how to store the paths in an array, and use a loop to create those paths?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T03:32:28.950", "Id": "450664", "Score": "0", "body": "I am interested in how to access these paths, in my example I created a variable for each path." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T05:48:54.223", "Id": "450669", "Score": "0", "body": "I'm not sure what you mean by accessing. But maybe you can create a question on https://stackoverflow.com/ for this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T07:48:58.667", "Id": "450682", "Score": "0", "body": "You may want to add to the response the user of **std::filesystem::permissions** in order to avoid errors on the execution of the program in case the user can not create the directory" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T10:41:09.697", "Id": "231091", "ParentId": "231046", "Score": "2" } } ]
{ "AcceptedAnswerId": "231091", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T17:13:05.357", "Id": "231046", "Score": "2", "Tags": [ "c++", "c++17", "winapi" ], "Title": "filesystem create a folder" }
231046
<p>I am not a Docker guru or expert in Flask or Redis. However, I need to leverage these technologies. I managed to cobble something together that works and would like to submit it for review.</p> <p>The MWE repository <a href="https://gitlab.com/SumNeuron/docker-nuxt-flask-redis-rq" rel="nofollow noreferrer">here</a> has three main directories:</p> <ol> <li>backend: the task-based Flask API</li> <li>frontend: a Nuxt app</li> <li>pyapp: a custom python module used by backend</li> </ol> <p>In addition to the docker file, I fear the flask app and worker are not properly set up.</p> <h2>Flask</h2> <h3>backend/manage.py</h3> <pre><code>import redis from flask_script import Server, Manager from rq import Worker, Queue, Connection from uwsgi import app listen = ['high', 'default', 'low'] manager = Manager(app) manager.add_command( 'runserver', # Server(port=5000, use_debugger=True, use_reloader=True)) Server(port=9061, use_debugger=True, use_reloader=True)) # flask is on 9061 via docker @manager.command def runworker(): redis_url = app.config['REDIS_URL'] redis_connection = redis.from_url(redis_url) with Connection(redis_connection): #worker = Worker(app.config['QUEUES']) worker = Worker(map(Queue, listen)) worker.work() if __name__ == '__main__': manager.run() </code></pre> <h3>backend/uwsgi.py</h3> <pre><code>import os, sys from werkzeug.wsgi import DispatcherMiddleware from app.factory import create_app app = create_app() # application = DispatcherMiddleware(app) </code></pre> <h3>backend/deploy.sh</h3> <pre><code>exec gunicorn --bind 0.0.0.0:9061 --reload uwsgi:app </code></pre> <h3>backend/app/factory.py</h3> <pre><code>'''----------------------------------------------------------------------------- IMPORTS -----------------------------------------------------------------------------''' import os # for main flask app from flask import Flask from flask_cors import CORS # blueprints of the app from .api.views import (bp as bp_api) from . import settings from pyapp import __name__, __version__ def create_app(): app = Flask(__name__) app.register_blueprint(bp_api, url_prefix='/api') app.config.from_object(settings) CORS(app) return app </code></pre> <h3>backend/app/settings.py</h3> <pre><code>import os, sys APP_DIR = os.path.dirname(os.path.realpath(__file__)) SECRET_KEY = os.getenv('SECRET_KEY', 'not_secret') LISTEN = ['high', 'default', 'low'] REDIS_URL = os.getenv('REDIS_URL', 'redis://localhost:6379') MAX_TIME_TO_WAIT = 10 </code></pre> <hr> <h2>Docker</h2> <h3>docker-compose</h3> <p>My docker-compose file looks like:</p> <pre><code>version: '3' services: nuxt: # frontend image: frontend container_name: nuxt build: context: . dockerfile: ./frontend/Dockerfile restart: always ports: - "3000:3000" command: "npm run dev" environment: - HOST volumes: - ./frontend/assets:/src/assets - ./frontend/components:/src/components - ./frontend/layouts:/src/layouts - ./frontend/pages:/src/pages - ./frontend/plugins:/src/plugins - ./frontend/static:/src/static - ./frontend/store:/src/store nginx: image: nginx:1.17 container_name: ngx ports: - "80:80" volumes: - ./nginx:/etc/nginx/conf.d depends_on: - nuxt flask: # backend image: backend container_name: flask build: context: . dockerfile: ./backend/Dockerfile command: bash deploy.sh env_file: - .env environment: - REDIS_URL - PYTHONPATH volumes: - ./backend/app:/app/app/ - ./backend/manage.py:/app/manage.py ports: - '9061:9061' expose: - '9061' depends_on: - redis worker: image: backend container_name: worker command: python3 manage.py runworker depends_on: - redis env_file: - .env environment: - REDIS_URL - PYTHONPATH redis: # for workers image: redis:5.0.3-alpine ports: - "6379:6379" expose: - '6379' </code></pre> <h3>Flask service</h3> <p>The Flask docker file looks like:</p> <pre><code>FROM debian:jessie-slim RUN apt-get update &amp;&amp; apt-get install -y \ git \ python3 \ python3-pip # Layer requriments and install before copying files as # requirments are less likely to change ADD ./backend/requirements.pip /app/ RUN pip3 install -r /app/requirements.pip # add custom python module ADD ./pyapp /pyapp RUN pip3 install -e /pyapp # Change into app WORKDIR /app # Add contents of "flask_app" sub-project dir to /app/ ADD ./backend /app/ </code></pre> <h3>Nuxt service</h3> <p>The Nuxt dockerfile looks like:</p> <pre><code>FROM node:10.15 ENV APP_ROOT /src RUN mkdir ${APP_ROOT} WORKDIR ${APP_ROOT} # changed context from inside nuxt_app to this repo's root # ADD . ${APP_ROOT} ADD ./frontend ${APP_ROOT} RUN npm install RUN npm run build </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-01T01:34:59.560", "Id": "451925", "Score": "0", "body": "Your repository diverged a little since this post was done. I'll review this based on what's posted here noting that splitting the `docker-compose` for different environments like you've done is part of the review." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T18:24:05.997", "Id": "231048", "Score": "5", "Tags": [ "python", "flask", "redis", "dockerfile", "docker" ], "Title": "Docker-compose for task-based Flask API with Redis and rq" }
231048
<p>I'm trying to create a generic class for decorator pattern.</p> <p>I successfully did it with the example code by metaprogramming:</p> <pre><code>#include &lt;iostream&gt; struct Action1 { }; struct Action2 { }; class Classe { public: // Default template. template&lt;class U, class ...Args&gt; auto go(Args ...args) { //static_assert(false); } }; // Action 1. template&lt;&gt; auto Classe::go&lt;Action1&gt;() { std::cout &lt;&lt; "coucouGo1" &lt;&lt; std::endl; } // Action 2. template&lt;&gt; auto Classe::go&lt;Action2&gt;(int i) { std::cout &lt;&lt; "coucouGo2 : " &lt;&lt; i &lt;&lt; std::endl; return i; } template &lt;class T&gt; class Decorator { public: template&lt;class U, class... Args&gt; auto go(Args ...args) { std::cout &lt;&lt; "coucouDecorator" &lt;&lt; std::endl; return classe.template go&lt;U&gt;(args...); } private: T classe; }; class DecoreClasse : public Decorator&lt;Classe&gt; { }; int main() { DecoreClasse c; c.go&lt;Action1&gt;(); c.go&lt;Action2&gt;(2); } </code></pre> <p>There is different functions "Action" and the pattern template decorator add a "coucouDecorator" before all call.</p> <p>But the thing I don't like is the "auto" return type.</p> <p>How can I replace <code>auto</code> to <code>int</code> or <code>char</code> in template specialization. I know I can do</p> <pre><code>struct Action1 { typedef retval int }; struct Action2 { typedef retval char }; template&lt;&gt; Action1::retval Classe::go&lt;Action1&gt;() </code></pre> <p>and add a class template to the decorator</p> <pre><code> template&lt;class U, class T, class... Args&gt; T go(Args ...args) { </code></pre> <p>but I prefer not to add return type in the struct.</p> <p>Do you have a better idea ? Sometimes I'm not very understandable in English so do not hesitate to ask question.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T18:33:05.603", "Id": "450320", "Score": "2", "body": "This code looks very hypothetical. Can yyou give a real life working example please?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T18:37:39.547", "Id": "450321", "Score": "0", "body": "The \"main\" example are here. In the Classe, I implement lots of functions go<Action*> and I would like to benchmark the time between the start and the return time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T18:45:09.317", "Id": "450322", "Score": "2", "body": "And what's so wrong about `auto`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T18:52:05.943", "Id": "450325", "Score": "0", "body": "I would like to say \"return 1\" instead of \"return static_cast<char>(1)\". This is like a POC: a very basic example to be implemented in a real situation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T13:44:48.497", "Id": "450455", "Score": "0", "body": "I think you are stuck with the `auto` and being explicit about the return value. Any other approach will involve more boiler plate in each specialization or wrapping each specialization in a class." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T18:29:14.497", "Id": "231049", "Score": "1", "Tags": [ "c++", "design-patterns" ], "Title": "Pattern decorator with template class" }
231049
<p>I'm very new to programming and C# and had some homework this weekend to create a simple string check. I've expanded upon that and came up with this. This is way more complex than what was asked but I wanted to push myself and see what I can learn.</p> <p>I would like feedback and criticism for what I am doing right and wrong. This script is a basic login and register an account in C# console app and it saves a text file to remember users.</p> <pre><code>using System; using System.Collections; using System.Linq; using System.Text; using System.IO; namespace additionalProgramming2_ { class Program { static void Main(string[] args) { string input; string savePath = (@"F:\nick Programing\additionalProgramming2 +\Save\"); int ID = 0; bool login = false; string[] usernameArray = File.ReadAllLines(@"F:\nick Programing\additionalProgramming2+\Save\username.txt");//loads a text file and sets it to an array ArrayList username = new ArrayList(usernameArray);//sets the array to an array list string[] passwordArray = File.ReadAllLines(@"F:\nick Programing\additionalProgramming2+\Save\password.txt"); ArrayList password = new ArrayList(passwordArray); string[] timeArray = File.ReadAllLines(@"F:\nick Programing\additionalProgramming2+\Save\time.txt"); ArrayList time = new ArrayList(timeArray); start: if (login == true) { goto menu; } Console.Clear(); Console.WriteLine(@"What would you like to do? 1 Login 2 Register 3 Shut Down"); input = Console.ReadLine(); switch(input) { case "1": case "login": Console.WriteLine("What is your user name?"); input = Console.ReadLine(); input = input.ToLower(); if (input =="default") { Console.WriteLine("Please try another user name"); Console.ReadKey(); goto start; } foreach (string name in username)//runs through the username list { if (name == input)//returns true if it finds a match in the list { int listNo = username.IndexOf(input);//sets the listNo to the index number of the password list that matched Console.WriteLine("What is your password?"); input = Console.ReadLine(); string passCheck = Convert.ToString(password[listNo]);//sets the passCheck var to the string index no found at the same index as the user name if (input == passCheck) //if the input and the passCheck are the same you logged in { ID = listNo;//sets the ID for the user string lastLogin = Convert.ToString(time[ID]);//gets the last login from the time list Console.WriteLine(@"You logged in! You last logged in at "+lastLogin ); time[ID] = (Convert.ToString(DateTime.Now));//sets a new login time using (TextWriter writer = File.CreateText(@"F:\nick Programing\additionalProgramming2+\Save\time.txt"))//creates a txt file called time { foreach (string date in time) { writer.WriteLine(date);//adds a new line to the txt file for time } } Console.ReadKey(); login = true; goto start; } } } Console.WriteLine("Sorry there was some error!"); Console.ReadKey(); goto start; case "2": case "register": Console.WriteLine("What would you like your user name to be?"); username: input = Console.ReadLine(); input = input.ToLower(); if (input == "") { Console.WriteLine("Please input a username"); goto username; } foreach(string name in username) { if(name == input)//checks if there is a user name called that already { Console.WriteLine("Sorry this username is taken"); Console.ReadKey(); goto start; } } username.Add(input);//adds the username to the username list Console.WriteLine("What would you like your password to be?"); password: input = Console.ReadLine(); if (input == "") { Console.WriteLine("Please enter a password"); goto password; } password.Add(input);//adds the password to the password list using (TextWriter writer = File.CreateText(@"F:\nick Programing\additionalProgramming2+\Save\username.txt"))//creates a txt file called username { foreach (string name in username) { writer.WriteLine(name);//adds a new line to the txt file for the user } } using (TextWriter writer = File.CreateText(@"F:\nick Programing\additionalProgramming2+\Save\password.txt")) { foreach (string pass in password) { writer.WriteLine(pass); } } time.Add(Convert.ToString(DateTime.Now)); using (TextWriter writer = File.CreateText(@"F:\nick Programing\additionalProgramming2+\Save\time.txt"))//creates a txt file called username { foreach (string date in time) { writer.WriteLine(date);//adds a new line to the txt file for the user } } Console.WriteLine("User created!"); Console.ReadKey(); break; case "3": case "shutdown": Console.Clear(); Console.WriteLine("Shutting down"); Console.ReadKey(); Environment.Exit(0);//closes down the console break; default: Console.WriteLine("Unexpected input"); Console.ReadKey(); break; } goto start; menu: Console.Clear(); string user = Convert.ToString(username[ID]); Console.WriteLine(@"Main menu Welcome back " + user); Console.WriteLine(@" 1 logout 2 ChangePassword 3 Shutdown"); input = Console.ReadLine(); input.ToLower(); switch(input) { case "1": case "logout": Console.WriteLine("Would you like to logout? y/n"); input = Console.ReadLine(); if (input == "y") { login = false; ID = 0; Console.WriteLine("Logged out"); Console.ReadKey(); } break; case "2": case "changepassword": Console.WriteLine("What would you like your new password to be?"); input = Console.ReadLine(); password[ID] = input; using (TextWriter writer = File.CreateText(@"F:\nick Programing\additionalProgramming2+\Save\password.txt")) { foreach (string pass in password) { writer.WriteLine(pass); } } Console.WriteLine("Password changed!"); Console.ReadKey(); break; case "3": case "shutdown": Console.Clear(); Console.WriteLine("Shutting down"); Console.ReadKey(); Environment.Exit(0);//closes down the console break; default: Console.WriteLine("Unexpected input"); Console.ReadKey(); break; } goto start; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T21:44:32.803", "Id": "450347", "Score": "0", "body": "Are we to guess exactly what this code is to accomplish? Please heed [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask)" } ]
[ { "body": "<p>Welcome to Code Review!</p>\n\n<p><strong>God function</strong><br>\nYou have all code in one function, the <code>main</code>. That's what sometimes is called a <a href=\"http://wiki.c2.com/?GodMethod\" rel=\"nofollow noreferrer\">God function</a>: It knows and does too much. Try splitting your code up into smaller, isolated pieces with clear tasks. If you look at the flow of your code, I'm sure you can find several of these tasks:</p>\n\n<ul>\n<li>Read values from a file into an array or list, </li>\n<li>Print the menu</li>\n<li>Register a user</li>\n<li>Login a user</li>\n</ul>\n\n<p><strong>Don't use goto</strong><br>\nGoto is mostly considered bad form. It's very easy to make so called <a href=\"https://en.wikipedia.org/wiki/Spaghetti_code\" rel=\"nofollow noreferrer\">spaghetti code</a>, which is very hard to maintain. There are a heap of other <a href=\"https://lonewolfonline.net/flow-control-control-structures/\" rel=\"nofollow noreferrer\">flow control</a> statements to use instead: for and while loops, switch statements, whatnot. For a CLI menu like you have, I'd say that the most common is to use a while loop:</p>\n\n<pre class=\"lang-c# prettyprint-override\"><code>var quit = false;\nwhile (!quit)\n{\n var input = readInput()\n if (\"exit\".eaquls(input))\n {\n quit = true;\n }\n}\n</code></pre>\n\n<p><strong>Generics are your friend</strong><br>\nYou use the namespace <code>System.Collections</code> for the <code>ArrayList</code> class. I'd use <code>List&lt;T&gt;</code> from <code>System.Collections.Generic</code> instead. It will let you specify the type of objects ending up in your list. User names for example are strings, but with ArrayList you can add numbers, other array lists, whatever. See e.g. <a href=\"https://stackoverflow.com/questions/2309694/arraylist-vs-list-in-c-sharp\">here</a> for more on generics. You probably don't want this:</p>\n\n<pre class=\"lang-c# prettyprint-override\"><code> ArrayList users = new ArrayList();\n users.Add(1);\n users.Add(new ArrayList());\n users.Add(\"test\");\n</code></pre>\n\n<p>This is better:</p>\n\n<pre class=\"lang-c# prettyprint-override\"><code>var better = new List&lt;string&gt;();\nbetter.Add(\"Alice\");\nbetter.Add(\"Bob\");\n</code></pre>\n\n<p>Now the compiler will warn you ahead of time, before you try using an ArrayList as a user name.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T07:38:11.327", "Id": "450385", "Score": "0", "body": "Thank you for taking the time to read though my code and give feedback. I will try and apply what you have said this week to new scripts I try and make.\n\nIt makes sense what you have said about the god code, i hadn't really known how to apply proper methods, i'v looked it up and i think i kinda understand it, i'v tried applying it to this code but I just mess everything up too much, Going forward ill try it out!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T20:05:40.223", "Id": "231058", "ParentId": "231050", "Score": "3" } } ]
{ "AcceptedAnswerId": "231058", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T18:33:38.240", "Id": "231050", "Score": "3", "Tags": [ "c#" ], "Title": "Simple login and register script with C# console app" }
231050
<p>I need an encryption algorithm that would be secure enough to store credit card data. So it should be reasonably secure.</p> <p>Here's what I've come up with. I'd appreciate any constructive criticism.</p> <pre><code>public class Encryption { // Algorithm meta sizes (in bits) private const int SaltSize = 256; private const int BlockSize = 256; private const int KeySize = 256; // Number of iterations for password bytes generation private const int DerivationIterations = 1000; /// &lt;summary&gt; /// Encrypts a string using the given password. /// &lt;/summary&gt; /// &lt;param name="s"&gt;String to encrypt.&lt;/param&gt; /// &lt;param name="password"&gt;Encryption password.&lt;/param&gt; /// &lt;returns&gt;Encrypted string.&lt;/returns&gt; public string Encrypt(string s, string password) { if (s == null) throw new ArgumentNullException(nameof(s)); if (password == null) throw new ArgumentNullException(nameof(password)); if (password.Length == 0) throw new ArgumentException("Password cannot be empty", nameof(password)); var salt = GetRandomBytes(SaltSize); var iv = GetRandomBytes(BlockSize); var data = Encoding.UTF8.GetBytes(s); using (Rfc2898DeriveBytes derivedKey = new Rfc2898DeriveBytes(password, salt, DerivationIterations)) { var keyBytes = derivedKey.GetBytes(KeySize / 8); using (var encrypt = new RijndaelManaged()) { encrypt.BlockSize = BlockSize; encrypt.Mode = CipherMode.CBC; encrypt.Padding = PaddingMode.PKCS7; using (var encryptor = encrypt.CreateEncryptor(keyBytes, iv)) { using (var stream = new MemoryStream()) { stream.Write(salt, 0, salt.Length); stream.Write(iv, 0, iv.Length); using (var cryptoStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(data, 0, data.Length); cryptoStream.FlushFinalBlock(); } return Convert.ToBase64String(stream.ToArray()); } } } } } /// &lt;summary&gt; /// Decrypts a string previously encrypted by &lt;see cref="Encrypt"&gt;&lt;/see&gt;. /// &lt;/summary&gt; /// &lt;param name="s"&gt;The text to decrypt.&lt;/param&gt; /// &lt;param name="password"&gt;The decryption password.&lt;/param&gt; /// &lt;returns&gt;The decrypted string.&lt;/returns&gt; public string Decrypt(string s, string password) { if (s == null) throw new ArgumentNullException(nameof(s)); if (password == null) throw new ArgumentNullException(nameof(password)); if (password.Length == 0) throw new ArgumentException("Password cannot be empty", nameof(password)); try { // Get data plus salt and IV byte[] allData = Convert.FromBase64String(s); byte[] salt = new byte[SaltSize / 8]; byte[] iv = new byte[BlockSize / 8]; byte[] data = new byte[allData.Length - (salt.Length + iv.Length)]; Buffer.BlockCopy(allData, 0, salt, 0, salt.Length); Buffer.BlockCopy(allData, salt.Length, iv, 0, iv.Length); Buffer.BlockCopy(allData, salt.Length + iv.Length, data, 0, data.Length); using (Rfc2898DeriveBytes derivedBytes = new Rfc2898DeriveBytes(password, salt, DerivationIterations)) { var keyBytes = derivedBytes.GetBytes(KeySize / 8); using (var symmetricKey = new RijndaelManaged()) { symmetricKey.BlockSize = BlockSize; symmetricKey.Mode = CipherMode.CBC; symmetricKey.Padding = PaddingMode.PKCS7; using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, iv)) { using (var memoryStream = new MemoryStream(data)) using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) { var plainTextBytes = new byte[data.Length]; var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount); } } } } } catch (Exception) { return string.Empty; } } private byte[] GetRandomBytes(int bits) { byte[] bytes = new byte[bits / 8]; using (var provider = new RNGCryptoServiceProvider()) { provider.GetBytes(bytes); } return bytes; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T20:03:44.403", "Id": "450332", "Score": "1", "body": "If you're actually going to use this to store credit card details, would I be correct in assuming that the entire system is going to have to pass a PCI-DSS audit?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T20:07:14.097", "Id": "450333", "Score": "0", "body": "I don't know. It's been a while since I processed credit cards. Why? Do you see an issue there?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T21:11:18.813", "Id": "450340", "Score": "1", "body": "It seems a bit odd to ask for a review of this code on two counts: firstly, it's arguably the least important part - certainly less important than the key management; and secondly, there seems to be a not inconsiderable risk that specialist auditors are going to come in and tell you not to roll your own crypto code, making the review pointless." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T21:15:17.187", "Id": "450341", "Score": "0", "body": "@PeterTaylor: Well, that seems like an odd response to a review request. I've got two upvotes on my post and I think a lot of people are curious about stuff like this. If you think the topic is unimportant, then why would you even comment? If you don't see any value, you could just move on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T19:22:56.927", "Id": "450497", "Score": "0", "body": "You might want to [ask a cryptography expert](https://crypto.stackexchange.com/) then. Just to quote from the documentation though: [\"The Rijndael class is the predecessor of the Aes algorithm. You should use the Aes algorithm instead of Rijndael.\"](https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.rijndael?view=netframework-4.8) So right from the start the answer would be \"no\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T19:24:15.807", "Id": "450499", "Score": "0", "body": "@ferada: I don't know any cryptography experts other than any who might hang out on stackoverflow. Thus the reason for posting it here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T19:25:14.053", "Id": "450500", "Score": "0", "body": "Had to add the link in an edit, I'd try https://crypto.stackexchange.com/ too." } ]
[ { "body": "<p>I'll do a full answer then: The algorithm choice seems <del>bad</del> suboptimal, or at least strange at first view: <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.rijndael?view=netframework-4.8\" rel=\"nofollow noreferrer\">\"The Rijndael class is the predecessor of the Aes algorithm. You should use the Aes algorithm instead of Rijndael.\"</a></p>\n\n<p>Even then the general advice would be not to <del>make up your own crypto scheme</del> do these choices on your own from scratch. I usually look at <a href=\"https://latacora.micro.blog/2018/04/03/cryptographic-right-answers.html\" rel=\"nofollow noreferrer\">this article</a> every once in a while. Also of course <a href=\"https://crypto.stackexchange.com/\">https://crypto.stackexchange.com/</a> for detailed questions and answers. <a href=\"https://crypto.stackexchange.com/questions/75078/using-different-iv-and-salt-with-aes-cbc-but-same-key\">This answer</a> might be a start.</p>\n\n<p>Long story short would probably be that there are better options than the choice of algorithms that are present in the code and if you're not sure what to use, some good library that has already done those choices for you would be preferable, like NaCl (for .NET of course). I've seen some bindings for that, but I would hesitate to suggest which one is to be recommended at all.</p>\n\n<p>Apart from algorithm choice a library might also be taking care of properly clearing any memory that was used (so some plaintext doesn't remain readable in memory) and prevents other problems (non-cryptographic random number generator, IV reuse, ... there's lots of things that can go wrong).</p>\n\n<p>Also make sure to use of some form of authentication encryption so that you can be sure before decryption that the data hasn't been tampered with, c.f. <a href=\"https://en.wikipedia.org/wiki/Padding_oracle_attack\" rel=\"nofollow noreferrer\">Padding Oracle</a>.</p>\n\n<p>Finally, credit card data is probably also more of a regulatory problem, <a href=\"https://en.wikipedia.org/wiki/Payment_Card_Industry_Data_Security_Standard\" rel=\"nofollow noreferrer\">PCI DSS</a> was mentioned.</p>\n\n<hr>\n\n<p>Okay, so keeping this specific code in mind:</p>\n\n<ul>\n<li>Depending on how it's stored (in a database at rest?) it might be good to also store the other parameters, like number of iterations (then again, the lengths could just also be stored, it's not a lot of data after all), as part of the data package, that way the parameters can be later increased without having to reprocess all stored data.</li>\n<li>The exception should probably at least be logged so someone can check what's up in production.</li>\n<li><code>new RNGCryptoServiceProvider()</code> gets run too often, should be enough to keep one instance around?</li>\n<li>The password check is just to make sure there was no coding error, right? Otherwise the minimum length should be a bit more, plus some dictionary checks etc. would be required. But then again, where's this password coming from, is it user-chosen or the global password for the whole database?</li>\n<li>1000 iterations seems low, but I also haven't (can't) checked what the actual run time of it is. To prevent attacks based on that it should probably be high enough to be noticeable when doing the password derivation. In any case there's a few better functions for this as mentioned in the linked documents.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T19:42:45.640", "Id": "450501", "Score": "0", "body": "Thanks, but AES is not my own crypto scheme. Regarding Rijndael vs AES, it looks like Rijndael is an implementation of AES. And there are tips for settings to make it like standard AES. The main difference appears to be restrictions AES puts on the block size. I've also posted on crypto.stackexchange.com as suggested." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T19:46:51.817", "Id": "450506", "Score": "0", "body": "Okay, rephrased it. But why would you have readers look that up if there's standard AES? Yes, also not made up, I've changed it, point being that it's easier to make unsafe choices if it's done from scratch without being vetted.\n\nLike, I think it actually looks safe (on its own! I've no idea how this is stored, if the password is randomised per entry etc.), but I wouldn't bet my money (well, credit card) on it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T20:12:33.460", "Id": "450509", "Score": "0", "body": "Not sure I follow. Have readers look up what? I just see a lot of encryption examples using Rijndael, and after reading your comments and I looked around, it seemed that Rijndael implements AES. I'm not clear on what you think I missed there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T20:53:49.223", "Id": "450510", "Score": "0", "body": "I mean that readers will now have look up what AES vs. Rijndael means. While that's valuable knowledge, it distracts from checking whether the code makes sense, or potentially has problems. And since [everyone](https://github.com/openssl/openssl/tree/master/crypto/aes) [calls](https://golang.org/pkg/crypto/aes/) [it](https://pypi.org/project/pycrypto/) [AES](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/javax/crypto/Cipher.html) it makes sense to stick to that naming." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T19:36:50.127", "Id": "231115", "ParentId": "231056", "Score": "2" } } ]
{ "AcceptedAnswerId": "231115", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T19:32:08.850", "Id": "231056", "Score": "5", "Tags": [ "c#", ".net", "cryptography" ], "Title": "Encrypting credit card data" }
231056
<p>Problem: Given a vector of strings, I want to print out all possible permutations where the strings may contain an OR operator (the <code>|</code> character, as in regular expressions).</p> <p>Example Input: the strings <code>race</code> and <code>car|horse</code></p> <p>Example Output:</p> <pre><code>race car race horse car race horse race </code></pre> <p>This code uses <code>-std=c++17</code> and helper code from other programmers (if this makes it off topic, I will recode these parts).</p> <p>This is faster than the <a href="https://stackoverflow.com/a/55318930/10976976">Python version</a> from one of my questions on a sibling site.</p> <p>Code:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;vector&gt; // Begin helper function from https://stackoverflow.com/a/236803/10976976 template &lt;typename Out&gt; void split(const std::string &amp;s, char delim, Out result) { std::istringstream iss(s); std::string item; while (std::getline(iss, item, delim)) { *result++ = item; } } std::vector&lt;std::string&gt; split(const std::string &amp;s, char delim) { std::vector&lt;std::string&gt; elems; split(s, delim, std::back_inserter(elems)); return elems; } // End helper function from https://stackoverflow.com/a/236803/10976976 // Begin helper function from https://stackoverflow.com/a/17050528/10976976 std::vector&lt;std::vector&lt;std::string&gt;&gt; cart_product (const std::vector&lt;std::vector&lt;std::string&gt;&gt;&amp; v) { std::vector&lt;std::vector&lt;std::string&gt;&gt; s = {{}}; for (const auto&amp; u : v) { std::vector&lt;std::vector&lt;std::string&gt;&gt; r; for (const auto&amp; x : s) { for (const auto y : u) { r.push_back(x); r.back().push_back(y); } } s = std::move(r); } return s; } // End helper function from https://stackoverflow.com/a/17050528/10976976 int main() { std::vector vector_of_strings{"C++|Python|PHP", "Is|Is Not", "Good|Great|Excellent|Exceptional"}; std::vector&lt;std::vector&lt;std::string&gt;&gt; vector_of_vector_of_strings; for (auto&amp; word_possibilities_string : vector_of_strings) { auto word_possibilities = split(word_possibilities_string, '|'); vector_of_vector_of_strings.push_back(word_possibilities); } // vector_of_vector_of_strings is now {{C++, Python, PHP}, {Is, Is Not}, {Good, Great, Excellent, Exceptional}} auto sentences = cart_product(vector_of_vector_of_strings); for (auto&amp; sentence : sentences) { std::sort(sentence.begin(), sentence.end()); do { const auto seperator = " "; const auto* sep = ""; for (const auto&amp; word : sentence) { std::cout &lt;&lt; sep &lt;&lt; word; sep = seperator; } std::cout &lt;&lt; "\n"; } while(std::next_permutation(sentence.begin(), sentence.end())); } } </code></pre> <p>Output (I'm sure you'll agree with the statements below):</p> <pre><code>C++ Good Is C++ Is Good Good C++ Is Good Is C++ Is C++ Good Is Good C++ ... Exceptional Is Not PHP Exceptional PHP Is Not Is Not Exceptional PHP Is Not PHP Exceptional PHP Exceptional Is Not PHP Is Not Exceptional </code></pre> <p>In the future, I will be reading in <code>vector_of_strings</code> from a file and passing in the starting permutation as arguments.</p> <p>For example: <code>./permutation_generator words.txt PHP Exceptional "Is Not"</code> will output:</p> <pre><code>PHP Exceptional Is Not PHP Is Not Exceptional </code></pre>
[]
[ { "body": "<p>That's a lot of unnecessary string copying.</p>\n\n<p>If you change all the <code>std::string</code>s to <code>std::string_view</code> and write your own <code>split</code> function (simple enough using <code>std::find</code>) it will be much faster.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T20:29:18.553", "Id": "231060", "ParentId": "231057", "Score": "0" } }, { "body": "<p>user673679 already mentioned that a lot of string copying is going on. Indeed, <code>std::string_view</code> could be used here to just keep references to the original input strings, saving both time and space.</p>\n\n<h1>Give your variables meaningful names</h1>\n\n<p>Your variable names should tell you something about the <em>contents</em> of the variable, not of the <em>type</em> of the variable. So don't write <code>std::vector&lt;std::string&gt; vector_of_strings</code>, but give it a more descriptive name such as <code>input</code> if it's the input to your program, and <code>possibilities</code> instead of <code>vector_of_vector_of_strings</code>.</p>\n\n<p>Also avoid variable names that are too alike, such as <code>separator</code> and <code>sep</code> in your <code>main()</code> function. In this case, you can avoid it by writing the code like so:</p>\n\n<pre><code>bool first = true;\n\nfor (const auto &amp;word: sentence) {\n if (first)\n first = false;\n else\n std::cout &lt;&lt; \" \";\n\n std::cout &lt;&lt; word;\n}\n</code></pre>\n\n<p>Don't abbreviate too much, just write <code>carthesian_product</code> instead of <code>cart_product</code>. The latter abbreviation is not common and might confuse others that do not know that you mean Carthesian product here.</p>\n\n<h1>Use more algorithms?</h1>\n\n<p>Since you are already using some of the C++ standard library algorithms, why not use more? For example, instead of writing a <code>for</code>-loop to create the vector of vector of strings, write:</p>\n\n<pre><code>std::transform(input.begin(), input.end(),\n std::back_inserter(possibilities),\n [](std::string words){\n return split(words, '|');\n });\n</code></pre>\n\n<p>Although arguably, it doesn't improve readability much here.</p>\n\n<h1>Split off more functionality into their own functions</h1>\n\n<p>The <code>main()</code> function could be cleaned up and made more readable if you moved some of its parts to properly named functions. For example, instead of creating the vector of vector of strings inline, it would be nice it you could just write:</p>\n\n<pre><code>auto possibilities = split_possibilities(input);\n</code></pre>\n\n<p>Also, consider creating a <code>join()</code> function, so writing out all the permutations could be written as:</p>\n\n<pre><code>for (auto &amp;sentence: sentences) {\n std::sort(sentence.begin(), sentence.end());\n\n do {\n std::cout &lt;&lt; join(sentence, \" \") &lt;&lt; '\\n';\n } while(std::next_permutation(sentence.begin(), sentence.end());\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T14:44:24.213", "Id": "231105", "ParentId": "231057", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T19:41:03.463", "Id": "231057", "Score": "2", "Tags": [ "c++", "performance", "beginner", "algorithm", "c++17" ], "Title": "Permutation generator with OR operator" }
231057
<blockquote> <p>Note: The topics of performance and Selenium/BS4 have not yet been addressed, so this question can still receive a better answer!</p> <p>Chat Room: <a href="https://chat.stackexchange.com/rooms/100275/anipop-discussion">https://chat.stackexchange.com/rooms/100275/anipop-discussion</a></p> </blockquote> <p>This is a recreational script made to update my home server w/ the latest season of anime from <a href="https://horriblesubs.info/" rel="nofollow noreferrer">HorribleSubs</a>. I'd like to know if there are any obvious syntactical and performance improvements, details on my usage of Selenium and BS4 and whether or not this usage is proper.</p> <h3>Windows Setup</h3> <ol> <li>Install <a href="https://scoop.sh/" rel="nofollow noreferrer">Scoop</a> to install any necessary programs.</li> <li>Run the following commands for whatever you don't have installed:</li> </ol> <pre class="lang-bsh prettyprint-override"><code>scoop bucket add extras scoop install python geckodriver qbittorrent pip install beautifulsoup4 selenium python-qbittorrent </code></pre> <ol start="3"> <li>Enable the qBittorrent <a href="https://github.com/lgallard/qBittorrent-Controller/wiki/How-to-enable-the-qBittorrent-Web-UI" rel="nofollow noreferrer">web interface</a>.</li> <li>Enjoy, and don't forget to seed your favorites!</li> </ol> <h3>Le Code</h3> <pre class="lang-py prettyprint-override"><code>import os import traceback from sys import platform from shutil import rmtree from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import NoSuchElementException import urllib.request as Web from bs4 import BeautifulSoup as Soup from qbittorrent import Client as qBittorrent from wget import download from collections import defaultdict def get_dl_path(): # TODO: Check if this drive has space, else check another drive # if there's no free space, crash return 'E:/Torrents/' def get_addons_path(): path = os.getcwd() if platform == 'win32': path += '\\addons\\' else: path += '/addons/' if not os.path.exists(path): os.mkdir(path) return path dl_path = get_dl_path() addons_path = get_addons_path() profile = webdriver.FirefoxProfile() # Run the browser in private mode profile.set_preference('extensions.allowPrivateBrowsingByDefault', True) profile.set_preference('browser.privatebrowsing.autostart', True) # Privacy settings (https://www.privacytools.io/) profile.set_preference('media.peerconnection.turn.disable', True) profile.set_preference('media.peerconnection.use_document_iceservers', False) profile.set_preference('media.peerconnection.video.enabled', False) profile.set_preference('media.peerconnection.identity.timeout', 1) profile.set_preference('privacy.firstparty.isolate', True) profile.set_preference('privacy.resistFingerprinting', True) profile.set_preference('privacy.trackingprotection.fingerprinting.enabled', True) profile.set_preference('privacy.trackingprotection.cryptomining.enabled', True) profile.set_preference('privacy.trackingprotection.enabled', True) profile.set_preference('browser.send_pings', False) profile.set_preference('browser.sessionstore.max_tabs_undo', 0) profile.set_preference('browser.sessionstore.privacy_level', 2) profile.set_preference('browser.urlbar.speculativeConnect.enabled', False) profile.set_preference('dom.event.clipboardevents.enabled', False) profile.set_preference('media.eme.enabled', False) profile.set_preference('media.gmp-widevinecdm.enabled', False) profile.set_preference('media.navigator.enabled', False) profile.set_preference('network.cookie.cookieBehavior', 2) profile.set_preference('network.cookie.lifetimePolicy', 2) profile.set_preference('network.http.referer.XOriginPolicy', 2) profile.set_preference('network.http.referer.XOriginTrimmingPolicy', 2) profile.set_preference('network.IDN_show_punycode', True) profile.set_preference('webgl.disabled', True) # Settings unique to https://restoreprivacy.com/firefox-privacy/ profile.set_preference('geo.enabled', False) profile.set_preference('media.peerconnection.enabled', False) profile.set_preference('network.dns.disablePrefetch', True) profile.set_preference('network.prefetch-next', False) options = webdriver.FirefoxOptions() options.headless = True browser = webdriver.Firefox(firefox_profile=profile, options=options) ext_prefix = 'https://addons.mozilla.org/en-US/firefox/addon/' exts = [ # 'ublock-origin', # Blocks ads &amp; such # 'https-everywhere', # TODO: Figure out how to enable 'Encryt All Sites Eligble' # 'decentraleyes', # Blocks Content Management Systems and handles their abilities locally 'umatrix' # Will block Disqus on HorribleSubs automatically ] for ext in exts: browser.get(ext_prefix + ext) btn = browser.find_element_by_class_name('AMInstallButton') ref = btn.find_element_by_tag_name('a').get_attribute('href') url = ref.split('?')[0] addon = download(url, out=addons_path).replace('/', '') browser.install_addon(addon, temporary=True) browser.get('https://horriblesubs.info/current-season/') src = browser.page_source parser = Soup(src, features='html.parser') divs = parser.body.find_all('div', attrs={'class': 'ind-show'}) size = len(divs) season = defaultdict(list) print('\nDownloading', size, 'shows') try: for i, div in enumerate(divs): browser.get('https://horriblesubs.info' + div.a['href']) # Wait to dodge `selenium.common.exceptions.ElementNotInteractableException: Message: Element could not be scrolled into view` WebDriverWait(browser, 15).until(EC.element_to_be_clickable((By.CLASS_NAME, 'more-button'))) # Expand the whole listing to get all the episodes if not browser.find_elements_by_id('01'): try: while True: browser.find_element_by_class_name('more-button').click() except NoSuchElementException: pass src = browser.page_source parser = Soup(src, features='html.parser') episodes = parser.body\ .find('div', attrs={'class': 'hs-shows'})\ .find_all('div', attrs={'class': 'rls-info-container'}) for episode in episodes: links = [ episode.find('div', attrs={'class': 'rls-link link-480p'}), episode.find('div', attrs={'class': 'rls-link link-720p'}), episode.find('div', attrs={'class': 'rls-link link-1080p'}) ] magnet = None for link in links: if link is not None: a = link.find('a', attrs={'title': 'Magnet Link'}) if a is not None: magnet = a['href'] if magnet is not None: season[dl_path + div.a.text].append(magnet) print('[%]', round(((i + 1) / size) * 100, 2)) except Exception: print(traceback.print_exc()) finally: browser.quit() rmtree(addons_path) try: # Web UI -&gt; 'Bypass authentication for hosts on localhost' should be enabled # Downloads -&gt; 'Do not start download automatically' should be enabled qb = qBittorrent('http://127.0.0.1:8080/') # Use DP to decrease show fetch time for path, magnets in season.items(): for magnet in magnets: qb.download_from_link(magnet, savepath=path, category='anime') qb.resume_all() except ConnectionError: print('[!] qBittorrent not active!') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T21:47:25.403", "Id": "450348", "Score": "0", "body": "If this is a follow-up to your [previous question](https://codereview.stackexchange.com/q/230793), don't forget to include a link. See also [*How to post a follow-up question?*](https://codereview.meta.stackexchange.com/q/1065) on meta." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T21:48:45.997", "Id": "450349", "Score": "1", "body": "@AlexV I'd say it's related but not a follow-up, since a) the previous had no answers and b) this is a significantly updated version." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T09:48:18.503", "Id": "450414", "Score": "3", "body": "@AlexV Best thing would've been for the original question to be edited really, since now there's a question out there that nobody cares about, doesn't need an answer anymore and has no valuable answers for future reference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-25T01:35:25.657", "Id": "451001", "Score": "0", "body": "Are you still looking for answers/feedback on this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-25T01:44:38.357", "Id": "451002", "Score": "0", "body": "@AlexanderCécile Yes; I've left a note above stating what hasn't been addressed yet, if anyone is interested." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-25T02:08:22.923", "Id": "451005", "Score": "0", "body": "Would you be willing to discuss things in a chat room? I don't want to spam comments if I have any questions :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-25T11:27:28.190", "Id": "451045", "Score": "0", "body": "@AlexanderCécile Like this? https://chat.stackexchange.com/rooms/info/100275/anipop-discussion?tab=general" } ]
[ { "body": "<p>I have no familiarity with any of the libraries used here, so I can't comment on their usage.</p>\n\n<p>What I will mention though is the giant chunk of <code>profile.set_preference</code> calls in the middle of the script. It would be much cleaner and less repetitive to save the string/bool pairs of options as a dictionary (or another \"paired\" structure), then just iterate over it. Example (partial):</p>\n\n<pre><code># Just so we can help prevent bad data entry into the dictionary\nfrom typing import Dict, Any\n\n# The \\ is just so I can stick {} on the next line for neatness\nprofile_settings: Dict[str, Any] = \\\n {'extensions.allowPrivateBrowsingByDefault': True,\n 'browser.privatebrowsing.autostart': True,\n\n 'media.peerconnection.turn.disable': True,\n 'media.peerconnection.use_document_iceservers': False\n\n # And the rest of pairs \n }\n\nfor setting_name, setting_value in profile_settings.items():\n profile.set_preference(setting_name, setting_value)\n</code></pre>\n\n<p>Now you don't need to copy and paste <code>profile.set_preference</code> a hundred times. This also allows you to easily save <code>profile_settings</code> into a config file so you can edit settings without needing to edit the code. When needed, you can just read the settings and iterate over them.</p>\n\n<p>And to clarify why I'm specifying <code>profile_settings</code> as being of type <code>Dict[str, Any]</code> using <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a>: telling the IDE what type your variable is can help it catch mistakes you make. Let's say you have a dictionary of strings to ints, and you accidentally pass it the wrong piece of data:</p>\n\n<pre><code>the_data_I_want = 1\nthe_data_I_dont_want = \"some stuff\"\n\nd: Dict[str, int] = {\"a\": the_data_I_dont_want} # Whoops\n</code></pre>\n\n<p>The last line will raise a warning</p>\n\n<blockquote>\n <p>Expected type Dict[str, int], got Dict[str, str] instead.</p>\n</blockquote>\n\n<p>With how you currently have it, it's unlikely that you'd accidentally give it a key of a type other than a string. If you start reading that data from elsewhere though, or begin pulling keys from variables, it's nice to have the IDE able to catch you when you've made a typo (like a bad auto-complete).</p>\n\n<hr>\n\n<p>You also have at the bottom</p>\n\n<pre><code>except Exception:\n print(traceback.print_exc())\n</code></pre>\n\n<p>It's good that you're printing out a stack trace so at least you aren't muting any useful debugging information, but I don't see why you're catching in the first place. </p>\n\n<p>If you just want to use the <code>finally</code>, you don't need to specify an <code>except</code>:</p>\n\n<pre><code>try:\n . . .\n\nfinally:\n browser.quit()\n rmtree(addons_path)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T00:02:48.960", "Id": "450353", "Score": "0", "body": "Hey, any input is better that none, so thank you! I'm curious as to what you mean by `Just so we can help prevent bad data entry into the dictionary`; may you elaborate? The try-catch block around the main gathering logic is just to fall into the finally if anything bad happens, just so I don't have to manually delete files. As for the listing expansion, it runs until the \"more-button\" element is gone. If you examine some of the HTML on a show listing page you'll get a better idea of what's happening. Or just remove the setting that makes it headless and watch :p" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T00:11:52.187", "Id": "450354", "Score": "0", "body": "By \"Just so we can help prevent bad data entry into the dictionary\", I meant that if you tell Python that `profile_settings` is a `Dict[str, bool]` (a dictionary mapping strings to bools), you'll get a warning if you accidentally try to put something other than a string or bool into it. I'll clarify that in the answer. And I'll just note that you don't need a `except` in a try. You only need either a `except` *or* a `finally`. `try: ... finally: stuff()` is fine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T00:19:23.083", "Id": "450355", "Score": "1", "body": "@T145 See my edit mid-to-bottom. I changed some stuff." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T17:12:00.743", "Id": "450481", "Score": "0", "body": "What kind of construction is this called: `profile_settings: Dict[str, Any] = ...`? That looks pretty neat and I'm learning Python and would like to learn more on how that bit works/is used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T17:33:23.547", "Id": "450484", "Score": "1", "body": "@BruceWayne The `: Dict[str, Any]` part is [type hinting](https://docs.python.org/3/library/typing.html). Unlike in a statically typed language, type hints are entirely for aesthetics, and for the IDE. It does not cause actual enforment of types. They're still very helpful for documentation purposes and to catch typos though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T17:48:32.770", "Id": "450485", "Score": "0", "body": "@Carcigenicate - Ooh, thanks for that. So it's the same as doing `profile_settings = {'extensions.allowPrivateBrowsingByDefault': True, 'browser.privatebrowsing.autostart': True}`, but the \"Hint\" allows us (the programmer) to see what we expect to have as the variable type? (I'm reading through that page you linked now, but does the type hint `Dict[str, Any]` actually force that variable type? Or no, it's primarily for documentation?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T17:52:39.990", "Id": "450486", "Score": "0", "body": "@BruceWayne Yes. But it also allows the IDE to know as well. Note my example under \"and you accidentally pass it the wrong piece of data:\". The IDE can catch type errors if you use them. If you look over my other reviews, you'll see that I use them extensively. If you're new to Python, I'm not sure that I'd say they're what you should be focusing your efforts on to learn, but once you're comfortable with the language, they can be quite helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T18:01:29.263", "Id": "450488", "Score": "0", "body": "@BruceWayne And absolutely no enforcement. You may get type warnings, but the code will still run. I have my IDE treat some as actual errors, but that's my personal choice" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T18:30:34.590", "Id": "450494", "Score": "1", "body": "@Carcigenicate - Thanks so much for your comments! I'll start using these, I'm not fluent in Python but I'm pretty comfortable these days, so this type of information is much welcomed :)" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T23:14:54.897", "Id": "231067", "ParentId": "231064", "Score": "9" } }, { "body": "<p>Firstly good to learn about Scoop, very useful.</p>\n\n<p><del>Secondly, as a big change, which you might not want to do now that\nyou've already built it: Consider not using a full browser for this. I\nopened up the website with JavaScript blocked and it worked absolutely\nfine, in fact I imagine the HTML will be parseable by just about any\nlibrary. Why make that change? Well, it will likely reduce your\nresource usage by quite a bit and very probably make it much faster, not\nto mention being able to do things concurrently, so you'll see results\nmuch quicker.</del> Edit: I missed the bit where at least one button, \"Show more\", does run via JavaScript. Could probably still be worked around by generating the requested URLs programmatically, otherwise Selenium is probably required.</p>\n\n<p>Right, so after that, the pathname handling should probably use\n<a href=\"https://docs.python.org/3/library/pathlib.html#module-pathlib\" rel=\"nofollow noreferrer\"><code>pathlib</code></a>\nto be more robust.</p>\n\n<p>The querying for HTML content I'd rather suggest using\n<a href=\"https://stackoverflow.com/questions/11465555/can-we-use-xpath-with-beautifulsoup\">XPath</a>\nor <a href=\"https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors\" rel=\"nofollow noreferrer\">CSS query syntax</a>\nto make things more expressive. Like\n<code>div[class~=hs-shows] div[class~=rls-info-container]</code> etc. Fewer\nfunction calls, easier to understand if you already know XPath or CSS.\nPlus, you can easily\n<a href=\"https://developer.mozilla.org/en-US/docs/Tools/Web_Console/Helpers\" rel=\"nofollow noreferrer\">try it in the browser first</a>.</p>\n\n<p>What else? Well once this gets bigger consider\n<a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\"><code>if __name__ == \"__main__\"</code></a>\nand having a <code>main</code> function.</p>\n\n<p>You could also consider some concurrency by immediately passing content\nto qBittorrent? But maybe that was also intentionally done later.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T11:31:54.447", "Id": "450433", "Score": "1", "body": "I'd certainly like to not use Selenium, but other scrapers don't seem to support dynamic page content. The big problem is the \"show more\" element, otherwise I'd just use pure BS4. Originally I had a main ftn & passed shows concurrently to QB. Ditched the first since this is relatively short and used DP to pass shows at the end to avoid having to wait on QB receiving shows in order to move to the next show." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T12:15:37.847", "Id": "450439", "Score": "0", "body": "Ooops. Yes, sorry, in that case you'd obviously have to require a bit more knowledge about how the URLs are generated. Even though I'd guess that's still doable. Anyway, I'll mark that as such in the answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T09:49:33.440", "Id": "231087", "ParentId": "231064", "Score": "1" } }, { "body": "<p>Instead of:</p>\n\n<pre><code>if platform == 'win32':\n path += '\\\\addons\\\\'\nelse:\n path += '/addons/'\n</code></pre>\n\n<p>You could use <a href=\"https://docs.python.org/3/library/os.html#os.sep\" rel=\"nofollow noreferrer\"><code>os.sep</code></a> or even better: <a href=\"https://docs.python.org/3/library/os.path.html#os.path.join\" rel=\"nofollow noreferrer\"><code>os.path.join</code></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T18:07:39.830", "Id": "450490", "Score": "0", "body": "Good to know more about relative addressing in Python; thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T18:18:45.300", "Id": "450493", "Score": "0", "body": "Should be noted that using this technique requires the path over @ `addon` to be normalized: https://docs.python.org/3/library/os.path.html#os.path.normpath" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T12:49:14.513", "Id": "231097", "ParentId": "231064", "Score": "1" } } ]
{ "AcceptedAnswerId": "231067", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T21:42:18.957", "Id": "231064", "Score": "13", "Tags": [ "python", "python-3.x", "web-scraping", "beautifulsoup", "selenium" ], "Title": "AniPop - The anime downloader" }
231064
<p>If the <code>default</code> task is executed here, the file name to be compiled is passed to the argument of the <code>CompileSass</code> function. When the <code>sass</code> task is executed, the callback function to be executed at the end is passed by gulp.</p> <p>The <code>CompileSass</code> function logs the file name when it is passed. Also, when anything other than the file name is passed, the log output will not be performed with the <code>CompileSass</code> function.</p> <p>This is easily done by determining the argument with the <code>typeof</code> operator.</p> <pre><code>function CompileSass(filePath) { const time = process.hrtime(); const isFilePath = typeof filePath === "string"; if (isFilePath) { // same if condition console.log("compiling now"); } return src(path["sass"]) .pipe(sass({outputStyle: "expanded"})) .on("end", () =&gt; { if (isFilePath) { // same if condition console.log(`Compiled '${filePath}' now`); } }) .pipe(dest("css")) .on("end", () =&gt; { if (isFilePath) { // same if condition const TaskTime = prettyTime(process.hrtime(time)); console.log(`Finished compiled ${TaskTime}`); } }); } exports.default = () =&gt; { watch(dir).on("all", (directory) =&gt; { CompileSass(directory); }); }; exports.sass = series(CompileSass); // in fact, there is other tasks in series function's argument </code></pre> <p>However, this <code>if</code> statement is repeated even though the log output conditions are the same. I wanted to consolidate this <code>if</code> statement in one place. But I couldn't come up with a good idea for that. I believe that increasing package dependencies leads to management complexity, so I am reluctant to introduce new packages whenever possible.</p> <p>Is there a good way to make the conditional branch for log output common in the gulp method chain?</p>
[]
[ { "body": "<p>Interesting question;</p>\n\n<p>some review remarks before addressing your actual question:</p>\n\n<ul>\n<li>You never seem to pass <code>filePath</code> to <code>src</code> but use <code>path[\"sass\"]</code> instead</li>\n<li>I always suggest to pipe your <code>console.log</code> calls through a <code>log</code> function that accepts a severity parameter so that you can customize the level of logging, but that's probably overkill for Gulp</li>\n</ul>\n\n<p>I would add a new function that does nothing, called <code>doNothing()</code> and then up front point an <code>output</code> function to either <code>doNothing()</code> or <code>console.log()</code>.</p>\n\n<pre><code>function doNothing(){\n //Do nothing\n}\n\nfunction CompileSass(filePath) {\n const time = process.hrtime();\n const out = (filePath === \"string\") ? console.log : doNothing;\n out(\"compiling now\");\n\n return src(path[\"sass\"])\n .pipe(sass({outputStyle: \"expanded\"}))\n .on(\"end\", () =&gt; {\n out(`Compiled '${filePath}' now`);\n })\n .pipe(dest(\"css\"))\n .on(\"end\", () =&gt; {\n out(`Finished compiling ${prettyTime(process.hrtime(time))}`);\n });\n}\n\nexports.default = () =&gt; {\n watch(dir).on(\"all\", (directory) =&gt; {\n CompileSass(directory);\n });\n};\n\nexports.sass = series(CompileSass); // in fact, there is other tasks in series function's argument\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T21:40:49.397", "Id": "450512", "Score": "0", "body": "Thank you for your excellent feedback Konijn. This time, instead of creating a new function `doNothing`, i decided to create an empty function using `new Function`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T21:41:10.610", "Id": "450513", "Score": "0", "body": "`You never seem to pass filePath to src but use path [\" sass \"] instead`> \nDoes this mean using `path [\" sass \"]` instead of `filePath`? If so, it is difficult. / \n\nThis is because `path [\"sass\"]` is a glob path (e.g `./sass/*/*.scss`), whereas `filePath` is the actual compiled file name(e.g. `./sass/utility/button.sass`), so it's difficult to replace each other." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T16:56:08.457", "Id": "231108", "ParentId": "231068", "Score": "2" } } ]
{ "AcceptedAnswerId": "231108", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T23:24:03.753", "Id": "231068", "Score": "4", "Tags": [ "javascript", "node.js", "logging", "sass", "gulp.js" ], "Title": "Compile SASS files in a directory via Gulp.js tasks, one of which produces logging output" }
231068
<p>I would like feedback on my benchmark script, for use on Linux. What's another method for benchmarking that might be better/easier? </p> <h2>Overhead</h2> <p>I've found that <code>subprocess.run</code> has an overhead of about 0.01 seconds by using this test function.</p> <pre class="lang-py prettyprint-override"><code>import time import subprocess def overhead(): start = time.time() process = subprocess.run("", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, executable="/bin/bash") print(time.time() - start) overhead() </code></pre> <p>To reduce this I'm running the programs I want to benchmark in batches using a Bash loop like below. The <code>$iterations</code> variable is the batch size and <code>$command</code> is the program I want to benchmark.</p> <pre class="lang-cpp prettyprint-override"><code>loop = """ iterations={} command=\"{}\" for ((i = 0; i &lt; $iterations; ++i)) do $command done """ </code></pre> <h2>How it works</h2> <p>My benchmark program is run like <code>python3 benchmark.py "[executable name] [arguments separated by a space]"</code>. Each program must print its own runtime as the only output to <code>stdout</code>. The executable name is expected to have a source file name that's the same but ends in .cpp. Here are test files and the benchmark script.</p> <h2>count_down.cpp</h2> <pre class="lang-cpp prettyprint-override"><code>#include "./Clock.hpp" #include &lt;iostream&gt; int main(int argc, char ** argv){ unsigned long iterations = 10000000; Clock clock; clock.tick(); unsigned long sum = 0; for(unsigned long i = iterations; i &gt; 0 ; --i){ sum += i % 10 == 0; } float elapsed = clock.tock(); std::cout &lt;&lt; elapsed &lt;&lt; std::endl; return sum; } </code></pre> <h2>count_up.cpp</h2> <pre class="lang-cpp prettyprint-override"><code>#include "./Clock.hpp" #include &lt;iostream&gt; int main(int argc, char ** argv){ unsigned long iterations = 10000000; Clock clock; clock.tick(); unsigned long sum = 0; for(unsigned long i = 0; i &lt; iterations ; ++i){ sum += i % 10 == 0; } float elapsed = clock.tock(); std::cout &lt;&lt; elapsed &lt;&lt; std::endl; return sum; } </code></pre> <h2>Clock.hpp</h2> <pre class="lang-cpp prettyprint-override"><code>#ifndef _CLOCK_HPP #define _CLOCK_HPP #include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;chrono&gt; class Clock { protected: std::chrono::steady_clock::time_point start_time; public: Clock() { tick(); } void tick() { start_time = std::chrono::steady_clock::now(); } float tock() { std::chrono::steady_clock::time_point end_time = std::chrono::steady_clock::now(); return float( std::chrono::duration_cast&lt;std::chrono::microseconds&gt;( end_time - start_time ).count() ) / 1e6f; } // Print elapsed time with newline void ptock() { float elapsed = tock(); std::cout &lt;&lt; "Took " &lt;&lt; elapsed &lt;&lt; " seconds" &lt;&lt; std::endl; } }; #endif </code></pre> <h2>benchmark.py</h2> <pre class="lang-py prettyprint-override"><code>import numpy as np import subprocess import sys import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation class Benchmark(object): def __init__(self): self.shell = "/bin/bash" self.batch_size = 10 self.programs = self.parse_args() self.compile() self.make_scripts() self.animate() def animate(self): figure = plt.figure() delay_ms = 1 animation = FuncAnimation(figure, self.run_and_graph, interval=delay_ms, init_func=self.setup_plot) plt.show() def setup_plot(self): one_plot = 111 axis = plt.subplot(one_plot) sides = ["top", "bottom", "left", "right"] for side in sides: axis.spines[side].set_visible(False) x_label = "Programs" y_label = "Relative Runtimes" plt.xlabel(x_label) plt.ylabel(y_label) def run_and_graph(self, i): unicode = "utf8" for program in self.programs: script = program["script"] process = subprocess.run(script, shell=True, executable=self.shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return_code = process.returncode stderr = process.stderr.decode(unicode).split() stdout = process.stdout.decode(unicode).split() runtimes = np.loadtxt(stdout) program["runtime"] += np.sum(runtimes) by_runtime = lambda program: program["runtime"] self.programs.sort(key=by_runtime) max_time = self.programs[-1]["runtime"] min_time = self.programs[0]["runtime"] plt.cla() for program in self.programs: name = program["name"] x_label = program["label"] command = program["command"] legend = "{}\n{}".format(x_label, command) runtime = program["runtime"] ratio = runtime / max_time plt.bar(x_label, ratio, label=legend) iterations = i * self.batch_size + self.batch_size title = "{} Iterations".format(iterations) plt.title(title, loc="left") legend_coordinates = 1, 1 plt.legend(bbox_to_anchor=legend_coordinates, frameon=False) min_ratio = min_time / max_time y_range = 1 - min_ratio scale = 0.1 buffer = y_range * scale y_min = min_ratio - buffer y_min = max(0, y_min) y_max = 1 + buffer plt.ylim(y_min, y_max) plt.tight_layout() def make_scripts(self): script_template = """ iterations={} command=\"{}\" for ((i = 0; i &lt; $iterations; ++i)) do $command done """ for program in self.programs: command = program["command"] program["script"] = script_template.format(self.batch_size, command) def compile(self): for program in self.programs: name = program["name"] command = "g++ -O3 -march=native -std=c++11 -o {0} {0}.cpp".format(name) subprocess.run(command, shell=True, executable=self.shell) def parse_args(self): arguments = sys.argv[1:] current_folder = "./" commands = [command.strip(current_folder) for command in arguments] names = [command.split()[0] for command in commands] commands = [current_folder + command for command in commands] programs = [ { "name": name, "label": "{} {}".format(name, i + 1), "command": command, "runtime": 0, } for i, (name, command) in enumerate(zip(names, commands)) ] return programs if __name__ == "__main__": Benchmark() </code></pre> <h2>Output</h2> <p>The output is a live animation of the cumulative runtime of all programs specified. The legend shows the program name, a number that allows the same program with different arguments to be used, and the command sent to Bash including any arguments given. This graph was made by running <code>python3 benchmark.py "count_up dummy_arg" "count_down dummy_arg dummy arg_2" count_down</code>.</p> <p><a href="https://i.stack.imgur.com/5aety.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5aety.png" alt="enter image description here"></a></p>
[]
[ { "body": "<h1>Use differential measurements to eliminate the contribution of overhead</h1>\n\n<p>By starting a bash script that runs the desired command multiple times, you are adding even more overhead (namely, starting the shell, which has to interpret the shell script, which then still has some overheads each time it executes the command). You are getting rid of only parts of the overhead by running many iterations in a batch, and only if the number of iterations is very high.</p>\n\n<p>The easiest way to remove the overhead of starting a subprocess from the measurement is to measure twice, once with the actual process you want to benchmark, and once with a dummy process that doesn't do anything, and then use the difference of the two measurements.</p>\n\n<h1>Avoid adding more programming languages</h1>\n\n<p>Adding bash scripts doesn't help solve your problem, it only increases the number of programming languages and runtime dependencies, making your benchmark more complex than it needs to be.</p>\n\n<p>If the goal was just to perform benchmarks of C++ code, I would recommend that you just use a C++ benchmark library, such as <a href=\"https://github.com/google/benchmark\" rel=\"noreferrer\">Google Benchmark</a>. It won't give you fancy live graphs, but if you are just interested in the numbers, it's more than enough. Alternatively:</p>\n\n<h1>Split the problem into smaller pieces</h1>\n\n<p>Your Python code tries to do multiple things at once:</p>\n\n<ol>\n<li>It compiles the C++ code.</li>\n<li>It benchmarks the resulting executables.</li>\n<li>It displays a (live) graph of the results.</li>\n</ol>\n\n<p>I would try to split your problem into these parts, and solve them independently. In particular, compiling the code is typically something you would let a build system solve. It can be something as simple as <code>make</code> in this case. Just write a <code>Makefile</code> that compiles the C++ code. You can even add a target to the <code>Makefile</code> that starts the benchmark if you want.</p>\n\n<p>Second, use an existing benchmarking library to do the actual measurements. Google Benchmark for example will take care of running multiple iterations while removing unwanted overhead from the measurement results.</p>\n\n<p>Finally, the Python script can be reduced to just starting the benchmarks and drawing the results, without having to worry about anything else.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T13:45:39.450", "Id": "231101", "ParentId": "231071", "Score": "6" } } ]
{ "AcceptedAnswerId": "231101", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-20T23:56:58.717", "Id": "231071", "Score": "3", "Tags": [ "python", "c++", "python-3.x", "c++11", "benchmarking" ], "Title": "A runtime benchmark for multiple programs using the Python subprocess module" }
231071
<p>I wrote this to teach myself how to make a menu with buttons and I want to know if I've done well and if there's any way to make it shorter and/or more efficient.</p> <pre><code>import pygame, sys from pygame import * run = True global newBG newBG = False #------------------------------------------------------------------------------- def mainLoop(): global win, newW, newH, newBG newW, newH = (960 , 508) win = pygame.display.set_mode ((newW, newH) , pygame.RESIZABLE) pygame.display.set_caption("SMC") backGround = 0 while run: global mouse, currentScreen mouse = pygame.mouse.get_pos() currentScreen() while newBG: drawBackground() newBG = False for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.VIDEORESIZE: win = pygame.display.set_mode ( (event.w, event.h) , pygame.RESIZABLE ) newW, newH = event.w, event.h drawBackground() uiPlate() if event.type == pygame.MOUSEBUTTONDOWN: for b in buttonList: b.click() pygame.display.update() #------------------------------------------------------------------------------ def mainMenu(): global backGroundImage, buttonList, currentScreen backGroundImage = pygame.image.load('Background.jpg') ButtonPic = pygame.image.load('Button.jpg') ButtonHoverPic = pygame.image.load('ButtonHover.jpg') ButtonPressPic = pygame.image.load('ButtonPress.jpg') buttonList = [ button(screenSwap, secondMenu, ButtonPic, ButtonHoverPic, ButtonPressPic, .1, .1, .1, .1), button('Hello', None, ButtonPic, ButtonHoverPic, ButtonPressPic, .1, .25, .1, .1), button('Hello to you!', None, ButtonPic, ButtonHoverPic, ButtonPressPic, .1, .50, .1, .1) ] for b in buttonList: b.drawButton() #------------------------------------------------------------------------------ def secondMenu(): global backGroundImage, buttonList backGroundImage = pygame.image.load('Button.jpg') ButtonPic = pygame.image.load('Background.jpg') ButtonHoverPic = pygame.image.load('ButtonHover.jpg') ButtonPressPic = pygame.image.load('ButtonPress.jpg') buttonList = [ button(screenSwap, mainMenu, ButtonPic, ButtonHoverPic, ButtonPressPic, .75, .1, .1, .1), button('Goodbye', None, ButtonPic, ButtonHoverPic, ButtonPressPic, .75, .25, .1, .1), button('Goodbye to you friend!', None, ButtonPic, ButtonHoverPic, ButtonPressPic, .75, .50, .1, .1) ] for b in buttonList: b.drawButton() #------------------------------------------------------------------------------ uiX = 0 uiY = 0 uiW = 960 uiH = 508 def uiPlate(): global uiW, uiH, uiX, uiY uiW = (int(newW)) uiH = (int(uiW*0.5296875)) if uiH &gt; newH: uiH = int(newH) uiW = (int(uiH/0.5296875)) uiX = (int((newW - uiW)/2)) uiY = (int((newH - uiH)/2)) ## pygame.draw.rect(win, (100, 255, 100,), (uiX, uiY, uiW, uiH)) ## print(uiW, uiH, uiX, uiY) #------------------------------------------------------------------------------ def drawBackground(): global backGround backGround = pygame.transform.scale(backGroundImage, (newW, newH)) win.blit((backGround), (0,0)) #------------------------------------------------------------------------------ class button: global uiX, uiY, uiW, uiH def __init__(self, action, actionProps, ButtonPic, ButtonHoverPic, ButtonPressPic, x, y, w, h): self.ButtonPic = ButtonPic self.ButtonHoverPic = ButtonHoverPic self.ButtonPressPic = ButtonPressPic self.bx = int(uiX + (x * uiW)) self.by = int(uiY + (y * uiH)) self.bw = int(w * uiW) self.bh = int(h * uiH) self.action = action self.actionProps = actionProps def drawButton(self): click = pygame.mouse.get_pressed() ButtonPic = pygame.transform.scale(self.ButtonPic, (self.bw, self.bh)) ButtonHoverPic = pygame.transform.scale(self.ButtonHoverPic, (self.bw, self.bh)) ButtonPressPic = pygame.transform.scale(self.ButtonPressPic, (self.bw, self.bh)) win.blit(ButtonPic, (self.bx, self.by)) if ((self.bx &lt; mouse[0] &lt; (self.bx + self.bw)) and (self.by &lt; mouse[1] &lt; (self.by + self.bh))): win.blit(ButtonHoverPic, (self.bx, self.by)) if click[0]: win.blit(ButtonPressPic, (self.bx, self.by)) def click(self): if ((self.bx &lt; mouse[0] &lt; (self.bx + self.bw)) and (self.by &lt; mouse[1] &lt; (self.by + self.bh))): if self.actionProps != None: self.action(self.actionProps) else: print(self.action) #------------------------------------------------------------------------------ def screenSwap(screen): global currentScreen, newBG currentScreen = screen newBG = True #------------------------------------------------------------------------------ currentScreen = mainMenu mainLoop() </code></pre> <p>Sorry about the length, if it's too much to bother looking through, I'd like to be shown some code for a well-made menu system that I can compare to.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T03:13:02.720", "Id": "450369", "Score": "1", "body": "`mainMenu` and `secondMenu` are incorrectly indented. Please fix this before review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T07:20:58.130", "Id": "450379", "Score": "0", "body": "Not sure what you mean." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T12:52:17.737", "Id": "450446", "Score": "0", "body": "Try copying your code from here and running it. It'll show you where you have syntax failures due to indentation." } ]
[ { "body": "<h2>PEP-0008</h2>\n\n<p>Follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-0008</a> guidelines. Use an automated checker (pylint, pyflakes, ...) to check your code for violations.</p>\n\n<p>Issues include:</p>\n\n<ul>\n<li>Variable, function, and method names should be <code>snake_case</code>. For example <code>newBG</code> should be <code>new_background</code>, <code>mainLoop</code> should be <code>main_loop</code>, and <code>drawButton</code> should be <code>draw_button</code>.</li>\n<li>No space between a function/method name and the opening parentheses. <code>set_mode (</code> should be <code>set_mode(</code>.</li>\n<li>No spaces before commas, and no spaces between adjacent parenthesis, or after opening parenthesis or before closing parenthesis. <code>set_mode ( (event.w, event.h) , pygame.RESIZABLE )</code> should be <code>set_mode((event.w, event.h), pygame.RESIZABLE)</code>.</li>\n<li>Class names should begin with uppercase letters. So <code>Button</code> instead of <code>button</code>.</li>\n</ul>\n\n<p>to name a few. Run a checker to see all of them.</p>\n\n<h2>Import *</h2>\n\n<pre><code>import pygame, sys\nfrom pygame import *\n</code></pre>\n\n<p>Are you importing <code>pygame</code>, or are you importing everything from inside <code>pygame</code>? Do one or the other, preferably the former, but definitely not both!</p>\n\n<h2>Global variables are Global</h2>\n\n<pre><code>global newBG\nnewBG = False\n</code></pre>\n\n<p><code>newBG</code> is being defined in the global scope. <code>global newBG</code> is not needed, and is useless.</p>\n\n<h2>Type Consistency</h2>\n\n<p>What is the type of <code>backGround</code>? Is it an image? If so, then explain:</p>\n\n<pre><code> backGround = 0\n</code></pre>\n\n<p>It looks like you are trying to assign an integer to something which normally holds an image. But wait! It is a local variable, and is not used anywhere.</p>\n\n<h2>While is not If</h2>\n\n<p>Is this a loop or an if statement?</p>\n\n<pre><code> while newBG:\n drawBackground()\n newBG = False\n</code></pre>\n\n<p>It can never execute more than once, because it sets the loop condition to <code>False</code>. The following is clearer:</p>\n\n<pre><code> if newBG:\n drawBackground()\n newBG = False\n</code></pre>\n\n<h2>Integer Arithmetic</h2>\n\n<p>If you don't want floating point values, don't divided by two. Instead <em>integer-divide</em> by two!</p>\n\n<p>Instead of this:</p>\n\n<pre><code>uiX = (int((newW - uiW)/2))\nuiY = (int((newH - uiH)/2))\n</code></pre>\n\n<p>write this:</p>\n\n<pre><code>uiX = (newW - uiW) // 2\nuiY = (newH - uiH) // 2\n</code></pre>\n\n<h2>Persistance</h2>\n\n<p>Your main loop reads roughly:</p>\n\n<pre><code>while run:\n\n currentScreen()\n\n # Handle events\n\n pygame.display.update()\n</code></pre>\n\n<p><code>currentScreen()</code> either calls <code>mainMenu()</code> or <code>secondMenu()</code>:</p>\n\n<pre><code>def mainMenu():\n # load 4 images\n # create 3 button objects in a list\n # draw button objects\n\ndef secondMenu():\n # load 4 images\n # create 3 button objects in a list\n # draw button objects\n</code></pre>\n\n<p>So ... every iteration of your main event loop (say, 30 to 60 times a second), you are:</p>\n\n<ul>\n<li><strong>LOADING MULTIPLE IMAGES</strong></li>\n<li><strong>CREATING UI ELEMENTS</strong></li>\n<li>drawing some stuff</li>\n<li><strong>DISCARDING THE IMAGES AND UI ELEMENTS</strong></li>\n</ul>\n\n<p>Forgive the above screaming. You don't want to waste time while painting your UI doing repetitive, redundant file I/O. Load the images once, at startup or the first time they are used. Create your buttons once, or at the very most, create them only when you swap to the new screen. Populate the button list when switching to this new screen. As this button list must maintain its value across multiple iterations of the event loop, you'll want this as a global variable, or ...</p>\n\n<h2>Stop Using Global Variables</h2>\n\n<p>Create a main class for your application, and store your \"global\" information as main class <code>self</code> members.</p>\n\n<p>Create a screen class, and create two instances of it: one for your main menu screen, the other for your second menu. The screen class would hold:</p>\n\n<ul>\n<li>the button list for that screen.</li>\n<li>the background image for that screen.</li>\n<li>a scaled copy of the background image (so you don't have to rescale it each iteration of the event loop!)</li>\n</ul>\n\n<p>If the application detects <code>VIDEORESIZE</code>, and when changing screens, it would tell the screen object, so the screen object can re-layout its objects and rescale the background image.</p>\n\n<h2>Single-Coat Paint</h2>\n\n<p>What does this do?</p>\n\n<pre><code> win.blit(ButtonPic, (self.bx, self.by))\n if ...:\n win.blit(ButtonHoverPic, (self.bx, self.by))\n if ...:\n win.blit(ButtonPressPic, (self.bx, self.by))\n</code></pre>\n\n<p>Unless <code>ButtonPic</code>, <code>ButtonHoverPic</code> and <code>ButtonPressPic</code> are not all the same size, or if <code>ButtonHoverPic</code> or <code>ButtonPressPic</code> have transparent areas, the above code can paint the button only to immediately repaint the button, and perhaps immediately repaint it a third time. Given that Premium One-Coat Guaranteed Paint™ is likely being used, this is doubling or tripling the cost of painting for no gain.</p>\n\n<p>Instead, I'd recommend something more like:</p>\n\n<pre><code> image = self._image\n if ...:\n if ...:\n image = self._press_image\n else:\n image = self._hover_image\n win.blit(image, (self.bx, self.by)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T17:51:47.620", "Id": "231109", "ParentId": "231072", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T00:28:08.733", "Id": "231072", "Score": "6", "Tags": [ "python", "beginner", "python-3.x", "pygame" ], "Title": "Menu with buttons using pygame" }
231072
<p>So I'm working on an implementation of the Atbash Cipher for Rust - it is an exercise on exercism.io. I come from a little C experience and found my code to be rather round about and kind of tortured. Doing <code>str</code> and <code>String</code> manipulation in Rust is something I haven't really grokked yet. It seems like this would take up fewer lines of code in C.</p> <p>Below is my code - am I going about this in the right way for Rust, or am I missing some important concept or way of manipulating the data? Is this as simple as it should be?</p> <p>The exercise involves getting an input <code>&amp;str</code> and outputting a <code>String</code>, with each character changed as per the Atbash cipher, adding a space every 5 characters. Included is also a <code>decode</code> function. This all goes in a <code>lib.rs</code>.</p> <pre><code>// "Encipher" with the Atbash cipher. pub fn encode(plain: &amp;str) -&gt; String { let mut coded: String = plain.to_string(); coded.retain(|c| c.is_ascii_alphanumeric()); coded.make_ascii_lowercase(); let coded_no_spacing = String::from_utf8( coded .bytes() .map(|c| { if c.is_ascii_alphabetic() { 122 - c + 97 } else { c } }) .collect(), ) .unwrap(); spacer(coded_no_spacing) } /// "Decipher" with the Atbash cipher. pub fn decode(cipher: &amp;str) -&gt; String { let mut out = encode(cipher); out.retain(|c| c.is_ascii_alphanumeric()); out } fn spacer(coded_no_spacing: String) -&gt; String { let mut coded_no_spacing = coded_no_spacing.chars(); let mut temp_char = coded_no_spacing.next(); let mut counter = 0; let mut coded_with_spaces = "".to_string(); while temp_char.is_some() { if counter % 5 == 0 &amp;&amp; counter != 0 { coded_with_spaces.push(' '); } coded_with_spaces.push(temp_char.unwrap()); temp_char = coded_no_spacing.next(); counter += 1; } coded_with_spaces } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T20:39:13.317", "Id": "450631", "Score": "0", "body": "Welcome to Code Review! Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 3 → 2" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T20:54:03.493", "Id": "450632", "Score": "0", "body": "Is there any way for me to get a copy of the edit I made in Rev 3? I'd like to write it in to a self answer if that is a more appropriate way to share the updated code with analysis." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T20:55:06.550", "Id": "450633", "Score": "1", "body": "Yes - check out [the revision history](https://codereview.stackexchange.com/posts/231076/revisions) (which is linked above the last editor's avatar, to the right of yours)" } ]
[ { "body": "<pre><code>// \"Encipher\" with the Atbash cipher.\npub fn encode(plain: &amp;str) -&gt; String {\n let mut coded: String = plain.to_string();\n\n coded.retain(|c| c.is_ascii_alphanumeric());\n coded.make_ascii_lowercase();\n\n let coded_no_spacing = String::from_utf8(\n coded\n .bytes()\n .map(|c| {\n if c.is_ascii_alphabetic() {\n 122 - c + 97\n</code></pre>\n\n<p>You can <code>b'z'</code> and <code>b'a'</code> to refer to the ascii codes of the letters.</p>\n\n<pre><code> } else {\n c\n }\n })\n .collect(),\n )\n .unwrap();\n\n spacer(coded_no_spacing)\n}\n</code></pre>\n\n<p>You are mixing two different approaches here. Firstly, you make a string out of the input and then modify it. Secondly, you use an iterator over the bytes of the string. This code would be more straightforward if you just iterated over the letters.</p>\n\n<p>Here is my approach:</p>\n\n<pre><code>plain\n .chars()\n .filter_map(|c| {\n if c.is_ascii_alphabetic() {\n let letter = c.to_ascii_lowercase() as u8;\n Some(char::from(b'z' - letter + b'a'))\n } else if c.is_ascii_alphanumeric() {\n Some(c)\n } else {\n None\n }\n })\n .collect()\n</code></pre>\n\n<p>If you haven't seen it before, the <code>filter_map</code> function combines filtering and mapping. The closure can return either None, to remove the element or Some(x) to provide an element in the output.</p>\n\n<pre><code>/// \"Decipher\" with the Atbash cipher.\npub fn decode(cipher: &amp;str) -&gt; String {\n let mut out = encode(cipher);\n out.retain(|c| c.is_ascii_alphanumeric());\n out\n}\n</code></pre>\n\n<p>It took me a bit to figure out why you were filtering the chars again. But I see it is remove the spacing. It would make more sense to split the basic ciphering and into its own function so you can call that without adding the spacing. Then you wouldn't have to filter it.</p>\n\n<pre><code>fn spacer(coded_no_spacing: String) -&gt; String {\n let mut coded_no_spacing = coded_no_spacing.chars();\n\n let mut temp_char = coded_no_spacing.next();\n let mut counter = 0;\n let mut coded_with_spaces = \"\".to_string();\n</code></pre>\n\n<p>I would use <code>String::new()</code> to create an empty string. For \"extra credit\", you could use String::with_capacity to reserve the correct amount of space for the string, something like:</p>\n\n<pre><code>String::with_capacity(coded_no_spacing.len() + coded_no_spacing.len() / 5);\n</code></pre>\n\n<p>That's dubiously worthwhile, but sometimes it can be a helpful optimization.</p>\n\n<p>Onwards:</p>\n\n<pre><code> while temp_char.is_some() {\n</code></pre>\n\n<p>Firstly, there is a construct you can use when you want to iterate as long as something return Some instead of None.</p>\n\n<pre><code>while let Some(temp_char) = coded_no_spacing.next()\n</code></pre>\n\n<p>But in this case, this is just iterating over for the chars, so you should use a forloop</p>\n\n<pre><code>for temp_char in coded_no_spacing.chars()\n\n if counter % 5 == 0 &amp;&amp; counter != 0 {\n coded_with_spaces.push(' ');\n }\n coded_with_spaces.push(temp_char.unwrap());\n temp_char = coded_no_spacing.next();\n counter += 1;\n</code></pre>\n\n<p>Instead of counting, use the enumerate() method on iterator. It will give you an index.</p>\n\n<pre><code> }\n coded_with_spaces\n}\n</code></pre>\n\n<p>Here is my version:</p>\n\n<pre><code>fn spacer(coded_no_spacing: &amp;str) -&gt; String {\n let mut coded_with_spaces = String::new();\n\n for (index, char) in coded_no_spacing.chars().enumerate() {\n if index % 5 == 0 &amp;&amp; index != 0 {\n coded_with_spaces.push(' ');\n }\n coded_with_spaces.push(char);\n }\n\n coded_with_spaces\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T19:38:35.070", "Id": "450622", "Score": "0", "body": "Thank you so much for this detailed description of your suggestions! I incorporate your changes in the edit above, and describe why I think they are an improvement over already very helpful suggestions from user.rustlang.org in a post I made there." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T16:23:22.860", "Id": "231149", "ParentId": "231076", "Score": "3" } }, { "body": "<p>Since posting this here I received some feedback on users.rustlang.org in <a href=\"https://users.rust-lang.org/t/good-needs-work-atbash-cipher-for-exercism/33839\" rel=\"nofollow noreferrer\">this post</a>. I will post the iteration made by incorporating the suggestions in users.rustlang.org, comment on those, and add more changes by using Winston Ewert's suggestions made on this site. I'll try to use the best suggestions from both the rustlang post and Winston Ewert, but certainly appreciate feedback as to whether or not I am using the best changes. At the end I post my improved code from all suggestions.</p>\n\n<p>Spoiler alert - the suggestions made here by Winston Ewert are all around improvements on the already super helpful suggestions from users.rustlang.org.</p>\n\n<h2>1. Code after users.rustlang.org post</h2>\n\n<pre><code>/// \"Encipher\" with the Atbash cipher.\npub fn encode(plain: &amp;str) -&gt; String {\n let mut coded: String = plain.to_string();\n\n coded.retain(|c| c.is_ascii_alphanumeric());\n coded.make_ascii_lowercase();\n\n let coded_no_spacing = coded.bytes()\n .map(|c| {\n if c.is_ascii_alphabetic() {\n (122 - c + 97) as char\n } else {\n c as char\n }\n })\n .collect::&lt;String&gt;();\n\n let mut coded_no_spacing = coded_no_spacing.chars().enumerate();\n let mut coded_with_spaces = String::new();\n while let Some((counter, ch)) = coded_no_spacing.next() {\n if counter % 5 == 0 &amp;&amp; counter != 0 {\n coded_with_spaces.push(' ');\n }\n coded_with_spaces.push(ch);\n }\n coded_with_spaces\n}\n\n/// \"Decipher\" with the Atbash cipher.\npub fn decode(cipher: &amp;str) -&gt; String {\n let mut out = encode(cipher);\n out.retain(|c| c.is_ascii_alphanumeric());\n out\n}\n</code></pre>\n\n<h2>2. Comments on code above</h2>\n\n<p>Three basic changes here:</p>\n\n<p><strong>a.</strong> <code>let coded_no_spacing</code> declaration changed to make use of <code>as char</code> instead of <code>String::from_utf8</code>. Also using <code>collect::&lt;String&gt;()</code> to allow code to reflect logic and avoid unnecessary <code>unwrap</code> from first iteration.</p>\n\n<p><strong>b.</strong> <code>enumerate</code> instead of declaring extraneous <code>counter</code> variable.</p>\n\n<p><strong>c.</strong> <code>while let</code> makes use of the <code>enumerate</code> to streamline use of temporary <code>counter</code> and <code>ch</code>.</p>\n\n<h2>3. Best of both</h2>\n\n<p>Looking at the suggestions of both posts, I think that the changes suggested here are all around improvements and have decided to incorporate these suggestions over those made at my users.rustlang.org <a href=\"https://users.rust-lang.org/t/good-needs-work-atbash-cipher-for-exercism/33839\" rel=\"nofollow noreferrer\">post</a>. These are my reasons:</p>\n\n<p><strong>a.</strong> <code>filter_map</code> vs separate filtering and mapping: <code>filter_map</code> streamlines the process required, utilizing the standard library to better effect in fewer lines with clear logic. While writing this code I saw <code>filter_map</code> in the documentation but couldn't get a handle on it, but thanks to the example provided in the post here I am starting to get it. Thanks!</p>\n\n<p><strong>b.</strong> <code>for</code> vs <code>while let</code>: I think the <code>for</code> works a little better here because it is more concise. Using <code>while let</code> would require one step to declare an iterator and another to set the loop running, whereas the <code>for</code> loop allows the iterator to be created within the construction of the loop. I'm not sure this is an important distinction but the <code>for</code> loop seems cleaner.</p>\n\n<hr>\n\n<p><strong>Miscellaneous</strong></p>\n\n<p>Nice tip about the little optimization with the <code>String</code> capacity. I guess depending on the size of the input string this could lead to many fewer runs from stack to heap and back, which is my understanding of why it might be a good one to use. I include this in my solution.</p>\n\n<p>As to separating <code>spacer</code> into its own function and removing the filter from <code>decode</code> - I should have mentioned above that because I am writing this for Exercism it has to pass tests by only calling <code>encode</code> and <code>decode</code>, and so I have to leave it in. However it does seem a good suggestion to keep a separate function for <code>spacer</code>, and will call it in <code>encode</code> and keep the filter in <code>decode</code>. </p>\n\n<p><strong>Final Version</strong></p>\n\n<pre><code>/// \"Encipher\" with the Atbash cipher.\npub fn encode(plain: &amp;str) -&gt; String {\n let coded_no_spacing = plain.chars()\n .filter_map(|c| {\n if c.is_ascii_alphabetic() {\n let letter = c.to_ascii_lowercase() as u8;\n Some(char::from(b'z' - letter + b'a'))\n } else if c.is_ascii_alphanumeric() {\n Some(c)\n } else {\n None\n }\n })\n .collect();\n\n spacer(coded_no_spacing)\n}\n\n/// \"Decipher\" with the Atbash cipher.\npub fn decode(cipher: &amp;str) -&gt; String {\n let mut out = encode(cipher);\n out.retain(|c| c.is_ascii_alphanumeric());\n out\n}\n\n/// Spacer adds one space every five characters to help encode function.\nfn spacer(coded_no_spacing: String) -&gt; String {\n let mut coded_with_spaces = String::with_capacity(\n coded_no_spacing.len() + coded_no_spacing.len() / 5);\n\n for (index, ch) in coded_no_spacing.chars().enumerate() {\n if index % 5 == 0 &amp;&amp; index != 0 {\n coded_with_spaces.push(' ');\n }\n coded_with_spaces.push(ch);\n }\n\n coded_with_spaces\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T21:00:06.770", "Id": "231158", "ParentId": "231076", "Score": "0" } } ]
{ "AcceptedAnswerId": "231149", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T05:07:18.540", "Id": "231076", "Score": "6", "Tags": [ "beginner", "programming-challenge", "rust" ], "Title": "Atbash Cipher in Rust - Exercism exercise" }
231076
<p>I have a <code>DataFrame</code> of size 3,745,802 rows and 30 columns. I would like to perform certain <code>groupby</code> and <code>transpose</code> operations which will finally end up with more (unimaginable) columns/features.</p> <p>I also tried <code>parallel processing</code>,<code>Dask</code>,<code>Modin</code> and the <code>pandarallel</code> package, but couldn't do this because all these packages don't support <code>unstack</code> operation yet. The sample dataframe is the same as my real dataframe but the record count is small (as I cannot share the real data).</p> <p>Please find the sample dataframe (subset of real dataframe)</p> <pre><code>df = pd.DataFrame({ 'subject_id':[1,1,1,1,2,2,2,2,3,3,4,4,4,4,4], 'readings' : ['READ_1','READ_2','READ_1','READ_3','READ_1','READ_5','READ_6','READ_8','READ_10','READ_12','READ_11','READ_14','READ_09','READ_08','READ_07'], 'val' :[5,6,7,11,5,7,16,12,13,56,32,13,45,43,46], }) N=2 # dividing into two dataframes for parallel processing. dfs = [x for _,x in df.groupby(pd.factorize(df['subject_id'])[0] // N)] </code></pre> <p>Please find dummy huge dataframe for testing (only the column names match but the data inside is random)</p> <pre><code>df_size = int(3e7) N = 30000000 s_arr = pd.util.testing.rands_array(10, N) df = pd.DataFrame(dict(subject_id=np.random.randint(1, 1000, df_size), readings = s_arr, val=np.random.rand(df_size) )) </code></pre> <p>Code (with the help of SO users)</p> <pre><code>import multiprocessing as mp def transpose_ope(df): #this function does the transformation like I want df_op = (df.groupby(['subject_id','readings'])['val'] .describe() .unstack() .swaplevel(0,1,axis=1) .reindex(df['readings'].unique(), axis=1, level=0)) df_op.columns = df_op.columns.map('_'.join) df_op = df_op.reset_index() return df_op def main(): with mp.Pool(mp.cpu_count()) as pool: res = pool.map(transpose_ope, [df for df in dfs]) if __name__=='__main__': main() </code></pre> <p><strong>What transpose_ope does?</strong></p> <p>It works like this. A subject can have n number of readings. Instead of having his n readings as row, I would like to create the summary statistics of each unique reading as a column. So, subject_id = 1 has 4 readings in total (but 3 unique readings). So, instead of having 4 rows for 1 subject, I would like create features/columns for the readings. But again, instead of readings, I would like to have summary statistics of the readings (MIN,MAX,STDDEV,COUNT,MEAN) etc. So each reading will have 5 columns. So subject_id = 1 will have 15 column in total</p> <p>Though this code works fine on the sample dataframe, in real life my data has more than four million rows and 30 columns. Moreover, when I apply the transformation of my interest as shown in the code, the column count can go up to 955,500. I'm basically trying to reduce the row count (but increasing the column count).</p> <p>Can you help?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T06:37:41.120", "Id": "231078", "Score": "6", "Tags": [ "python", "performance", "python-3.x", "pandas", "vectorization" ], "Title": "How to make my groupby and transpose operations efficient?" }
231078
<p>I have written a function to get the actual page range to display that page range in pagination.</p> <p>My function is working properly. But I think that I have written bad code. Can someone review my code and give me some feedback to improve my code?</p> <p>Here is the code:</p> <pre><code>const pageRange = (() =&gt; { let startPage = activePage &lt; pageNeighbours + 1 ? 1 : activePage - pageNeighbours; const endPage = totalPages &lt; (pageNeighbours * 2) + startPage ? totalPages : (pageNeighbours * 2) + startPage; const diff = (startPage - endPage) + (pageNeighbours * 2); startPage -= (startPage - diff &gt; 0 ? diff : 0); let actualPageRange = new Array((endPage - startPage) + 1) .fill().map((_, i) =&gt; i + startPage); if (actualPageRange[0] !== 1) actualPageRange = [1, ...actualPageRange]; if (actualPageRange[1] !== 2) actualPageRange = [1, '...', ...actualPageRange.slice(1)]; if (actualPageRange[actualPageRange.length - 1] !== totalPages) { actualPageRange = [...actualPageRange, totalPages]; } if (actualPageRange[actualPageRange.length - 2] !== totalPages - 1) { actualPageRange = [...actualPageRange.slice(0, actualPageRange.length - 1), '...', totalPages]; } return actualPageRange; })(); </code></pre> <p>In the above code:</p> <p><code>activePage</code> refers to the current page number.</p> <p><code>pageNeighbours</code> refers to the number of pages that should be shown besides active page</p> <p><code>totalPages</code> is self-explanatory</p> <p><strong>Update</strong></p> <p>After this function execution, I will use pageRange to create output like:</p> <p><a href="https://i.stack.imgur.com/uB6Q2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uB6Q2.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T11:17:50.040", "Id": "450430", "Score": "0", "body": "Greetings, please roll back your changes (the updated code part). On this site, one should not update the question because of provided answers. Though the explanation of your variables helps and should be kept." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T11:29:48.890", "Id": "450431", "Score": "2", "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)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T11:57:57.713", "Id": "450438", "Score": "0", "body": "@konijn and Heslacher Sorry, I was not aware of that. Since Heslacher and konijn has already removed the update, I don't have to make any changes. Thank you. I will never do that again." } ]
[ { "body": "<p>From a short review;</p>\n\n<ul>\n<li>You use globals instead of parameters for <code>activePage</code> and <code>pageNeighbours</code></li>\n<li>You need at least one comment stating what <code>pageNeighbours</code> stands for, without knowing this the code looks meaningless to me</li>\n<li>You need at least one comment on the top explaining what the range is supposed to contain</li>\n<li>On the whole I think this could use more comments</li>\n<li>Why <code>actualPageRange</code> instead of simply <code>pageRange</code>, or even <code>range</code> since it would be clear from context what <code>range</code> we're reading about</li>\n</ul>\n\n<p>Okay, so since the code does not work, expect this question to be closed.\nThat doesn't mean that functionally this isn't a great question.</p>\n\n<p>This is my approach to what I believe you are looking for:</p>\n\n<pre><code>const pageRange = ((activePage, pageNeighbours, totalPages) =&gt; {\n\n let range = [];\n //Add active page and neighbouring pages\n for(let page = activePage - pageNeighbours; page &lt;= activePage + pageNeighbours; page++)\n range.push(page);\n //Make sure we dont show pages that dont exist\n range = range.filter(page=&gt; page &gt; 0 &amp;&amp; page &lt;= totalPages);\n //Allow user to go to the first page if need be\n //The second entry should be either 2 or ellipsis(...)\n if(range[0]!=1){\n if(range[1]!=2){\n range.unshift('...');\n }\n range.unshift(1);\n }\n //Allow user to go the last page, second last entry should be second last page or ellipsis\n if(range[range.length-1] != totalPages){\n if(range[range.length-2]!= totalPages-1){\n range.push('...');\n } \n range.push(totalPages);\n }\n\n return range;\n})(activePage, pageNeighbours, totalPages);\n</code></pre>\n\n<p>Note that this avoids accessing <code>activePage</code> etc. as a global.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T11:08:42.883", "Id": "450428", "Score": "0", "body": "Thank you konijn. I will try to improve my code as per your suggestions. Actually, I am using React.js, where the function is defined in local scope. So, `activePage` and `pageNeighbours` are the props of the component. Since, my function is defined inside the component, this function does not need both of them as parameters. `pageNeighbours` property is used to decide how many pages should be shown besides active page number." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T12:27:05.797", "Id": "450440", "Score": "0", "body": "I didn't notice an update in your question. I think that's a bug in my code. It should not print `4` in the first case. second case looks good though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T12:32:35.563", "Id": "450442", "Score": "0", "body": "It's not arbitrary. It should return `[ 1,...,5,6,7,8,9,10 ]` in the first case. While it should return `[ 1,...,6,7,8,9,10 ]` in the second case. I will update the question with the image in a moment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T12:34:21.180", "Id": "450443", "Score": "0", "body": "Please look at the update part of the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T12:58:57.810", "Id": "450449", "Score": "0", "body": "yes its true. There are some bugs. I never knew there were such bugs, that you found. I will try to fix them and then will give you the updated code. Most probably there is only 1 bug that I can see. If you have items less than pageNeighbours on the left of your current page, then it will add 1 more on the right side. Similar for vice-versa. I will fix that soon." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T13:48:20.620", "Id": "450459", "Score": "0", "body": "Thank you for posting the correct code. But after thinking about the requirements, I feel that in my case, my function is working fine. But for general purpose, your function can be used. Also, I got how to write good code by looking at your code." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T11:00:59.120", "Id": "231094", "ParentId": "231080", "Score": "4" } } ]
{ "AcceptedAnswerId": "231094", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T07:29:24.330", "Id": "231080", "Score": "3", "Tags": [ "javascript", "pagination" ], "Title": "Pagination calculation" }
231080
<p>Recently, I applied for a job that required skills in object-oriented programming. Although I have coded in Java at odd times, those were very small assignments. I have been mostly programming in C language. Recently I applied for a job that required object-oriented programming skills. They gave me a pre-interview assessment to find out over overlapped boxes in a view. Following is what they asked me to code:</p> <blockquote> <p>Imagine you are working in the team responsible for rendering charts. A chart represents an area on a map (similar to Google maps). For the purpose of this exercise assume that a map consists of multiple charts drawn on top of each other, similar to the picture below. <a href="https://i.stack.imgur.com/rPBMX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rPBMX.png" alt="enter image description here"></a></p> <p>Assume a chart has the following attributes. • Position in space and size is specified by its top left coordinate (x1,y1) and its bottom right coordinate (x2,y2). • Colour of the chart is specified in RGB, with each value between 0 – 255 (e.g. R=255, G=0, B=0 would imply a red chart)</p> <p>Write a class called Chart that represents the above. B. Write a class called View that can contain a maximum of 2 charts at a time C. Implement a method DoChartsOverlap() in the View class which checks if the charts overlap. D. Implement a method GetColour(X,Y) in the View class that will return the RGB colour of a given coordinate. If two charts overlap the colour of the point should be the average of the two colours. You may assume the X and Y axis starts at 0 and has a maximum value of 100 for all of the above tasks.</p> </blockquote> <p>Following was my solution that I submitted. It passed unit tests I wrote for it.</p> <p><strong>Chart Class:</strong></p> <pre><code>package Foo; import java.awt.Color; import java.awt.Point; public class Chart { private Point topLeftCord = new Point(); private Point bottomRightCord = new Point(); private Color chartColor; public Chart(Color color, int topX, int topY, int bottomX, int bottomY ) { this.topLeftCord.x = topX; this.topLeftCord.y = topY; this.bottomRightCord.x = bottomX; this.bottomRightCord.y = bottomY; this.chartColor = color; } public boolean hasCoordinate(int x, int y) { return x &gt;= this.topLeftCord.x &amp;&amp; x &lt;= this.bottomRightCord.x &amp;&amp; y &gt;= this.topLeftCord.y &amp;&amp; y &lt;= this.bottomRightCord.y; } public Point getTopLeftCord() { return topLeftCord; } public Point getBottomRightCord() { return bottomRightCord; } public Color getChartColor() { return chartColor; } } </code></pre> <p><strong>View Class</strong></p> <pre><code>package Foo; import java.awt.Color; public class View { private final int BG_COLOR = 0xFFFFFF; private Chart c1; private Chart c2; private Color bgColor; public View(Chart chart1, Chart chart2) { c1 = chart1; c2 = chart2; bgColor = new Color(BG_COLOR); //set background color to white } public boolean doChartsOverLap() { if(c1.getTopLeftCord().x &gt; c2.getBottomRightCord().x || // if true, c1 is located on the right side of c2 c1.getBottomRightCord().x &lt; c2.getTopLeftCord().x || // if true, c1 is located on the left side of c2 c1.getTopLeftCord().y &gt; c2.getBottomRightCord().y || // if true, c1 is located on the under the c2 c1.getBottomRightCord().y &lt; c2.getTopLeftCord().y) // if true, c1 is located on the over the c2 return false; return true; } public Color getColor(int x, int y) { Color color = null; if(c1.hasCoordinate(x, y) &amp;&amp; c2.hasCoordinate(x, y)) { // The coordinate lies in an overlapped area int r = 0, g = 0, b = 0; r = (c1.getChartColor().getRed() + c2.getChartColor().getRed()) / 2; g = (c1.getChartColor().getGreen() + c2.getChartColor().getGreen()) / 2; b = (c1.getChartColor().getBlue() + c2.getChartColor().getBlue()) / 2; color = new Color(r, g, b); } else if(c1.hasCoordinate(x, y)) color = c1.getChartColor(); else if(c2.hasCoordinate(x, y)) color = c2.getChartColor(); else color = bgColor; // The coordinates lies outside the area occupied by the charts, // thus returning default color of the View. However this will be invalid // if there is another chart occupying this area. return color; } } </code></pre> <p><strong>Main class:</strong></p> <pre><code>package Foo; import java.awt.Color; public class Foo { public static void main(String[] args) { Chart c1 = new Chart((new Color(255, 0, 0)), 10, 10, 50, 50); Chart c2 = new Chart(new Color(0, 255, 0), 10, 10, 50, 50); View view = new View(c1, c2); System.out.println(c1.hasCoordinate(60, 60)); // just to test System.out.println(view.doChartsOverLap()); System.out.println(view.getColor(50, 50)); } } </code></pre> <p>After a week, I have got a vague reply that <em>"It does not appear that you have got strong application-level skills"</em>. Is this code that bad? Can you point out improvements in this code? Have I missed out on some important object oriented concepts?</p> <p>Any help would be appreciated. I need it for closure. </p>
[]
[ { "body": "<p>I like the code, what you can do more is to add interfaces. Lets say Chart can be an interface and RectangularChart implement it and used in your application. In main you will declare variable as Chart and instantiate with RectangularChart.\nAlso don't be afraid to try to other jobs, if you trust yourself then don't pay attentions to the answer(this can hide other things in back: they like other candidates, they don't like you because you are smart ...).\nThink lie this: your story doesn't fit to their story, go on ;)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T12:36:49.237", "Id": "450444", "Score": "1", "body": "Assuming that the hiring company had other motives than skill is self-deception." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T07:15:23.837", "Id": "450539", "Score": "0", "body": "OK, I will take this into consideration next time. Thank you!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T10:52:54.577", "Id": "231093", "ParentId": "231081", "Score": "0" } }, { "body": "<p>First of all, it is great that you wrote this algorithm and that it works. I'll try to collect all remarks that I would normally note while reviewing this code having the formal task.</p>\n\n<p><strong>Package naming</strong></p>\n\n<p>According to <a href=\"https://www.oracle.com/technetwork/java/codeconventions-150003.pdf\" rel=\"nofollow noreferrer\">Java style guides</a> you are not allowed to name a package using capitals letters. The correct package name will be <code>foo</code>. However, <code>foo</code> is an extremely bad package name. It doesn't carry any meaningful information. Taking into account that you are given a charts API your package could have been <code>com.yourcompanyname.charts</code>.</p>\n\n<p><strong>Why do you use <code>java.awt</code> API?</strong></p>\n\n<p>The task doesn't say that you should rely on the <code>java.awt</code> API. It might be that your app will expose its API through HTTP, have a CLI API, or have no UI. Using these APIs you explicitly force clients to stick to <code>java.awt</code>.</p>\n\n<p><strong>Define your own domain classes</strong></p>\n\n<p>Instead of the provided <code>Color</code> and <code>Point</code>, you could use your specific implementations that are designed to solve your business task. </p>\n\n<p><strong>Initialization of points</strong></p>\n\n<p>Initialization of points <code>topLeftCord</code>, <code>bottomRightCor</code> is broken in two steps. You assign a point in the field declaration and you set up coordinates in the constructor. Instead, it is better to perform initialization in one place.</p>\n\n<p><strong>Boolean operations</strong></p>\n\n<p>The following considered a code smell:</p>\n\n<pre><code>if (condition) {\n return false;\n}\nreturn true;\n</code></pre>\n\n<p>Instead you can just:</p>\n\n<pre><code>return !condition;\n</code></pre>\n\n<p><strong>Too much comments</strong></p>\n\n<p>Often if you face a need to explain the code you are writing in a comment, it means that you can extract/structure your code in the way that your code will be self-explaining. Try to break up your complex conditions into methods/classes and use them so that a reader won't have to 'parse' blocks of 'if' conditions that carry 5 or more statements.</p>\n\n<p><strong>Immutability</strong></p>\n\n<p>Many places in your code are not designed to be mutable. For instance, points and color in the <code>Chart</code>. Make them final.</p>\n\n<p><strong>Color declaration</strong></p>\n\n<p>Why <code>BG_COLOR</code> is a constant? Why do you need this declaration in the first place? I would remove it. Also, the name violates <a href=\"https://www.oracle.com/technetwork/java/codeconventions-150003.pdf\" rel=\"nofollow noreferrer\">the Java style convention</a>.</p>\n\n<p><strong>Do not create a <code>main</code> class</strong></p>\n\n<p>Instead, you are supposed to cover your API with unit tests that prove that it works the way it is defined in the tasks. Not to say, it shouldn't be called <code>Foo</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T11:14:26.977", "Id": "231095", "ParentId": "231081", "Score": "6" } }, { "body": "<p>There are a few holes in the specification for which you have implemented code. E.g. the color outside the charts. The picture has white color but you used black. If you didn't ask clarification for those, that might have a negative effect on your evaluation.</p>\n\n<p>On the other hand, the specification says that the view can have \"maximum of two charts\" meaning that it can also have zero or one charts. You did not account for those and introduced NullPointerExceptions.</p>\n\n<p>You can always thank them for the opportunity and what specifically made them consider you to not have \"strong application-level skills\" (whatever that means)...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T12:53:32.440", "Id": "231098", "ParentId": "231081", "Score": "2" } } ]
{ "AcceptedAnswerId": "231095", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T08:30:50.770", "Id": "231081", "Score": "3", "Tags": [ "java", "object-oriented", "design-patterns" ], "Title": "Detecting overlapped boxes and the color of overlapped area in a View" }
231081
<p>I'm hoping someone can help me here, I'm working with a file which has about 38000 rows and 180 columns. I'm using a macro to update the fields in the one workbook with the values in the other workbook, but it takes about 2 minutes to run. I'm looking for a way to reduce this time, I've tried everything I could find on previous questions but it's still too long.</p> <p>As you can see in the code below, the macro checks to see the # of rows are the same in each workbook (note the one has 1 more row, hence the lastrow temp having +1) and then I want to check if the field in the temp file is a certain colour, if not then change it if etc... I use this colour to keep track of the values that have changed from the raw file, as I don't want these values to be overwritten again once they have been changed once. I use ranges so that I don't need to access the worksheets the entire time as this increases the execution time. Any help will be appreciated. </p> <pre><code>Sub SavetoTemp() StartTime = Timer Set wb = ThisWorkbook Set DT = wb.Worksheets("Data Table") With Application .Calculation = xlCalculationManual .ScreenUpdating = False .DisplayStatusBar = False .EnableEvents = False .ActiveSheet.DisplayPageBreaks = False DT.DisplayPageBreaks = False End With Dim TempFile As Workbook Dim TempSheet As Worksheet Dim LastCol As Long Dim colLetEnd As String If wb.Worksheets("Steering Wheel").Range("M30").Value = "" Then MsgBox "Please Select a Temporary File First" Exit Sub Else Set TempFile = Workbooks.Open(Range("M30").Value) Set TempSheet = TempFile.Worksheets(1) Dim LastRowDT As Long LastRowDT = DT.Cells(Rows.Count, "A").End(xlUp).row LastCol = DT.Cells(1, Columns.Count).End(xlToLeft).Column Dim LastRowTemp As Long LastRowTemp = TempSheet.Cells(Rows.Count, "A").End(xlUp).row + 1 Dim tempCell As Range Dim r As Long Dim c As Long Dim rngDT As String Dim rngTemp As Range colLetEnd = Split(Cells(1, LastCol).Address, "$")(1) Set rngTemp = TempSheet.UsedRange rngDT = "A" &amp; 3 &amp; ":" &amp; colLetEnd &amp; LastRowDT If (LastRowTemp = LastRowDT) Then For Each cell In DT.Range(rngDT) Set tempCell = rngTemp.Cells(cell.row - 1, cell.Column) If Not tempCell.Interior.Color = RGB(188, 146, 49) Then If IsNumeric(cell) And Not IsEmpty(cell) Then If (Not cell = tempCell) Or (IsEmpty(tempCell)) Then tempCell.Interior.Color = RGB(188, 146, 49) tempCell = cell End If Else If Not (StrComp(cell, tempCell, vbTextCompare) = 0) Then tempCell.Interior.Color = RGB(188, 146, 49) tempCell = cell End If End If End If Next cell TempSheet.Cells.EntireColumn.AutoFit TempFile.Save TempFile.Close MsgBox "All Records Saved to Temp File Successfully!" wb.Worksheets("Steering Wheel").Activate MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss") wb.Worksheets("Steering Wheel").Range("E48").Value = MinutesElapsed With Application .Calculation = xlCalculationAutomatic .ScreenUpdating = True .DisplayStatusBar = True .EnableEvents = True End With Else MsgBox "Please load the raw data file into your temp file before saving to it." With Application .Calculation = xlCalculationAutomatic .ScreenUpdating = True .DisplayStatusBar = True .EnableEvents = True End With Exit Sub End If End If End Sub </code></pre> <p>Any improvement to the code to reduce execution time is my ultimate goal.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T09:18:01.393", "Id": "450407", "Score": "1", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly." } ]
[ { "body": "<p>I will start off with an advice on performance and then comment on a few more general topics.</p>\n\n<h2>Performance</h2>\n\n<p>Your general performance problem is probably that you make too many sheet accesses. These are slow. Instead, you could read in all values in a range in one go. Used on a range containing more than a single cell, the <code>Value</code> property returns a <code>Variant</code> containing a 2-dim array of the values in the first area of the range. </p>\n\n<p>You could simply read in the values of both ranges, do the comparison and write the value from the data sheet if the values do not agree and your flag colour is not set. Unfortunately, you cannot avoid the single cell accesses for writing because you save whether the value is to be updated via the cell colour.</p>\n\n<h2>Unqualified Member Calls</h2>\n\n<p>Please note that every unqualified use of the <code>Cells</code> member does resolve to <code>ActiveSheet.Cells</code>. The same is true for <code>Rows</code> and <code>Columns</code>. For your code, this does not really make a difference since you use these methods to calculate things that do not depend on a specific worksheet. However, it looks like an error at first.</p>\n\n<h2>Use of Default Members</h2>\n\n<p>Using default members to shorten the code, usually is good for readability. Any future maintainer of the code will thank you if you are more explicit about what you do. Thus, it would be helpful to replace the implicit default member calls in statements like <code>tempCell = cell</code> with the equivalent version <code>tempCell.Value = cell.Value</code>.</p>\n\n<h2>Code Names for Sheet Access</h2>\n\n<p>You can change the code name of sheets in the workbook containing the code in the properties window for the sheet. These names allow you to access the sheet directly via this name without requiring the stringly-typed access via <code>Worksheets</code>. E.g. if you set the code name of the sheet named <code>\"Steering Wheel\"</code> to <code>SteeringWheel</code>, you can access cell M30 via <code>SteeringWheel.Range(\"M30\")</code>. </p>\n\n<h2>Avoiding Magic Numbers</h2>\n\n<p>In general, using the same explicit number in several places inside a program is a mistake waiting to happen. When the value needs to be changed later, one has to find all occurrences in the code and replace them all. To avoid this, it makes sense to give the value a name and save it in one place, e.g. as a constant. Here, this applies to the colour used as marker colour. </p>\n\n<h2>Named Ranges</h2>\n\n<p>Accessing data from a worksheet via its address means that whenever the layout changes, the code has to be adapted as well. This can be avoided using named ranges. If you introduced a named range <code>TempFilePathRange</code> for cell M30 scoped to the steering wheel worksheet, you could get the file path via <code>SteeringWheel.Range(\"TempFilePathRange\").Value</code>, which does not only work after layout changes, but also conveys much better what it does. </p>\n\n<h2>Single Responsibility Principle</h2>\n\n<p>For maintainability, it is generally a good idea to follow the <em>single responsibility principle</em> (SRP), which basically says that each method should be responsible for one and only one thing. The hard thing about it is to find a good definition of responsibility for the given situation.</p>\n\n<p>You procedure definitely has a lot of responsibilities: Disabling and enabling all automatic updates, getting the temporary file path, opening and closing the temporary file, getting the data worksheet, extracting the ranges to compare and executing the comparison.</p>\n\n<p>You could split this into several procedures and functions. The outermost could simply do the enabling and disabling of Excel features and call a private procedure doing the comparison in between. The inner one could call a function that returns a reference to the temporary file (and <code>Nothing</code> if it does not exist), which calls another function responsible for determining the file name. Next, it could call a function that extracts the range used for comparison from the temporary file and one that returns the reference range. Then these could be sent to a procedure executing the actual comparisons and updates. Finally, the procedure would close the temporary file. Similarly, the comparison operation could also e extracted into its own function. </p>\n\n<p>After such a split, each sub-procedure or function would do a short sequence of simple actions with the details hidden in the functions and procedures it calls. This is generally much easier to digest then having to deal with all details at once. In addition, this approach this basically documents you code automatically, provided you use meaningful names for the functions and procedures.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T13:15:05.310", "Id": "231100", "ParentId": "231084", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T09:09:29.683", "Id": "231084", "Score": "2", "Tags": [ "performance", "vba", "excel" ], "Title": "Sluggish Performance when using ranges from two workbooks to update the one" }
231084
<p>I was tasked with writing a function, that checks whether a date is valid in the following format: <em>DD.MM.YYYY</em>. Here's what I wrote: </p> <pre><code>bool isValidDate(const char* date) { int a, b, c; size_t len = strnlen(date, 255); for (size_t i = 0; i &lt; len; i++) { if (!isdigit(date[i]) &amp;&amp; date[i] != '.') return false; } int validConversions = sscanf_s(date, "%2d.%2d.%4d", &amp;a, &amp;b, &amp;c); return validConversions == 3 ? true : false; } </code></pre> <p>From my testing I can conclude that this function does reasonably well: it doesn't accept anything except dots and digits, it expects to read exactly 3 numbers and it knows how many digits to read for the days and months. </p> <p>Something it doesn't check however, is whether the days are less than 31 or the months are less than 12. Another thing it doesn't do is that it doesn't check correct looking, but invalid dates such as 30.02.2013 or 31.06.2012. </p> <p>Solving that problem is trivial, but I don't wanna write 12 <code>if</code>s for each month to check the dates. I'm starting to think I should just generate a data structure of valid dates and use that to check, i.e. if the passed date is there, then it's valid. </p> <p>Is that the best way to do it or are there other ways?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T09:33:04.093", "Id": "450410", "Score": "0", "body": "One quick remark is that you should probably use `strnlen` instead of `strlen`. If you get a string that does not contain a '\\0', your function will have an undefined behavior." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T09:43:08.830", "Id": "450412", "Score": "0", "body": "@LukeSkywalker changed to `strnlen`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T09:51:29.313", "Id": "450415", "Score": "1", "body": "`strnlen(date, 0)` will *always* return `0`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T11:31:26.283", "Id": "450432", "Score": "0", "body": "\"Solving that problem is trivial, but I don't wanna write\" What *do* you want? And what date range do you consider valid? Your specification is unclear, yet it appears you ask us to fix the problem for you while you haven't fixed it entirely yourself yet. That smells an awful lot like a feature request. Please clarify after reading the [help/on-topic]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T11:40:08.940", "Id": "450434", "Score": "1", "body": "@SergeyTeryan You can learn more about strnlen [here](https://linux.die.net/man/3/strnlen) but to summarize, `strnlen` takes a maximun length. `strnlen(date, 9)` means that it will go up to 9 character to find '\\0'. So if your date is 6 bytes long for example, it will return 6. If your date is 12 bytes long, it will return 9 anyway. This prevent your code to read memory \"indefinitely\" if the string passed to your function is corrupted and does not contain a '\\0'." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T13:29:07.467", "Id": "450452", "Score": "1", "body": "I'm voting to close this question as off-topic due to code not working since the function will always return false (strnlen will always return zero)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T14:31:44.350", "Id": "450469", "Score": "0", "body": "@pacmaninbw No need to, I'll edit it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T14:36:46.867", "Id": "450470", "Score": "0", "body": "The edit is ok this time, but editing after the question has been answered is generally not allowed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T18:10:29.800", "Id": "450491", "Score": "0", "body": "@Luke Using `strnlen` without passing in the length of the string to the function will invoke just as much undefined behavior as using `strlen`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T21:47:15.790", "Id": "450514", "Score": "0", "body": "Don't use any `_s`-prefixed functions. Even though MS says the functions are \"safer\", in reality all the functions are just dumping a whole bunch of not-portable BS on your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T11:00:10.730", "Id": "450571", "Score": "0", "body": "\"Solving that problem is trivial\" Hoo, boy, let me show you a little something: http://infiniteundo.com/post/25326999628/falsehoods-programmers-believe-about-time And then another one: http://infiniteundo.com/post/25509354022/more-falsehoods-programmers-believe-about-time" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-26T19:54:41.633", "Id": "451206", "Score": "0", "body": "@LukeSkywalker In C, all _strings_ contain a _null character_, else by definition, it is not a string. To suggest \"If you get a string that does not contain a '\\0'\" misleads as to what is a _string_. Even if it is possible `char* date` does not point to a string." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-26T19:58:49.027", "Id": "451207", "Score": "0", "body": "SergeyTeryan Is input like `\" 12. 25. 2000\"` acceptable (spaces before) or an error? How about `\"12 .25 .2000\"` (spaces after)?" } ]
[ { "body": "<h1>Use descriptive variable names</h1>\n\n<p>Instead of <code>int a, b, c</code>, give them more descriptive names:</p>\n\n<pre><code>int day, month year;\n</code></pre>\n\n<h1><code>sscanf()</code> will ignore trailing garbage</h1>\n\n<p>The function <code>sscanf()</code> will stop parsing after the last conversion. So the string <code>\"1.2.3....\"</code> will be cleared by your check for digits and period characters, and then <code>sscanf()</code> will read 3 integers, and returns 3. But obviously, this is an invalid date.</p>\n\n<p>It would be best if you could have <code>sscanf()</code> determine the validity of the whole input string. One way is to use the <code>%n</code> conversion to check how many characters of the string were parsed so far, and then check that this corresponds to the whole string. This is how you can do that:</p>\n\n<pre><code>int day, month, year, chars_parsed;\n\nif (sscanf(date, \"%2d.%2d.%4d%n\", &amp;day, &amp;month, &amp;year, &amp;chars_parsed) != 3)\n return false;\n\n/* If the whole string is parsed, chars_parsed points to the NUL-byte\n after the last character in the string.\n */\nif (date[chars_parsed] != 0)\n return false;\n</code></pre>\n\n<h1>You don't need 12 <code>if</code>s to check the month</h1>\n\n<p>You can just write:</p>\n\n<pre><code>if (month &lt; 1 || month &gt; 12)\n return false;\n</code></pre>\n\n<p>And similar for days and perhaps even years if you want to limit the allowed range.</p>\n\n<h1>Avoid redundant checks</h1>\n\n<p>It is likely that your program will normally handle valid date strings. So you want to optimize for this case. In your code, you are checking for the string to be empty at the start, but this is not necessary; if the input string is empty, then <code>sscanf()</code> will not return 3, so it will already correctly return false. Since most input strings will be valid, checking the string length is just a waste of CPU cycles.</p>\n\n<p>Similarly, checking for each character to be a digit or a period is redundant if you just use <code>sscanf()</code> with the <code>%n</code> method to check that there was no trailing garbage after the year.</p>\n\n<h1>Better date checking</h1>\n\n<p>Just checking whether the month is between 1 and 12 and day between 1 and 31 is not enough. A given month might have less than 31 days. There are also leap years to consider. And if you want to allow dates far in the past, you run into the problem that we have had different calenders. To give an idea of how difficult the problem is, watch: <a href=\"https://www.youtube.com/watch?v=-5wpm-gesOY\" rel=\"noreferrer\">https://www.youtube.com/watch?v=-5wpm-gesOY</a></p>\n\n<p>One way to validate the date is to use the C library's date and time conversion routines. After scanning the day, month and year, create a <code>struct tm</code> from that, then convert it to seconds since epoch using <code>mktime()</code>. This might still accept invalid dates, but if you convert that back to a <code>struct tm</code>, you can check whether that conversion matched the original input:</p>\n\n<pre><code>int day, month, year,\nsscanf(date, \"%2d.%2d.%4d\", &amp;day, &amp;month, &amp;year);\n\nstruct tm input = {\n .tm_mday = day,\n .tm_mon = month - 1,\n .tm_year = year - 1900,\n};\n\ntime_t t = mktime(&amp;input); /* note, this might modify input */\nstruct tm *output = localtime(&amp;t); /* prefer localtime_r() on systems that support it */\n\nif (day != output-&gt;tm_mday || month != output-&gt;tm_mon + 1|| year != output-&gt;tm_year + 1900)\n return false;\n</code></pre>\n\n<p>These routines will probably still not handle dates hundreds of years in the past correctly, but it should suffice for recent dates.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T09:59:27.220", "Id": "450417", "Score": "2", "body": "How do we handle cases like _31.02.2019_ which are syntactically valid?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T10:05:35.297", "Id": "450418", "Score": "0", "body": "I thought `mktime()` would return an error if the date was invalid, but it does not. Perhaps using a roundtrip would work: create a `struct tm`, convert it to seconds with `mktime()`, then convert that back to `struct tm` using `localtime_r()`, and then checking whether the day/month/year match the results you got from `sscanf()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T10:34:19.277", "Id": "450420", "Score": "0", "body": "I'll accept that, but I have no way of testing it, as there's no `localtime_r` on windows." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T10:44:00.097", "Id": "450424", "Score": "0", "body": "Ah, but there is `localtime()`. It might be unsafe to use in threaded programs though, unless it uses thread-local storage internally." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T11:01:04.493", "Id": "450427", "Score": "1", "body": "btw the function still accepts bogus dates like _31.02.2019_" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T11:44:00.660", "Id": "450435", "Score": "0", "body": "Indeed, it seems `mktime()` actually modifies the input. I changed the code to avoid comparing `input` to `output`. The manual page of `mktime()` says the input is normalized, so maybe you don't need to call `localtime()` at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T13:38:27.997", "Id": "450454", "Score": "0", "body": "Try not to answer questions that are off-topic. You have answered 2 questions today that would be considered off-topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T13:47:32.977", "Id": "450457", "Score": "0", "body": "@pacmaninbw I answered it before you decided it was off-topic. Originally the code was not always returning `false`, but the poster changed it based on the comment from Luke Skywalker." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T13:55:45.703", "Id": "450460", "Score": "0", "body": "Yes, but I wasn't the first one to decide it was off-topic. This question is off-topic for at least 3 reasons. and the original version was off-topic for two. Lack of Concrete Context, What are you asking." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T14:00:39.447", "Id": "450461", "Score": "3", "body": "@pacmaninbw Hm, I don't see any mention of off-topic or Lack of Concrete Context on this page. I only see your comment from half an hour ago about voting to make it off-topic. Am I missing something? Also, I think these comments are getting completely off-topic..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T19:23:45.600", "Id": "450498", "Score": "1", "body": "An alternative all-in-one check (for the \"syntactical correctness\" part) could be `if sscanf(date, \"%2d.%2d.%4d%c\", &day, &month, &year, &dummy_char) != 3`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T21:47:58.630", "Id": "450515", "Score": "0", "body": "That `%n` trick is wonderful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T12:25:12.940", "Id": "450578", "Score": "0", "body": "@SergeyTeryan : not only that, but for February we have to check for leap years too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-26T20:08:16.793", "Id": "451210", "Score": "0", "body": "Better code would test `mktime(&input)` for a error return of -1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-26T20:20:38.320", "Id": "451212", "Score": "0", "body": "Pedantically the `mktime(&input); localtime(&t);` trick - which used local time - fails select timezone cases that involve a timezone not having a valid time for the date and 0:0:0 hour. I am thinking of cases where a Pacific timezone lost/gain a day switching which side of the IDL it was on. Better to use `UTC` - if there was a convenient counter to `gmtime()`." } ], "meta_data": { "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T09:46:20.350", "Id": "231086", "ParentId": "231085", "Score": "9" } } ]
{ "AcceptedAnswerId": "231086", "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T09:27:27.463", "Id": "231085", "Score": "9", "Tags": [ "c", "datetime", "validation" ], "Title": "C function to check the validity of a date in DD.MM.YYYY format" }
231085
<p>I am new to rust and wanted to get going with a medium-sized project to help learn. I've settled on creating some basic quantum mechanics code which starts with this bare-bones file reader. It takes a pdb file which is just a list of atom coordinates and the connections between them - with some extra information. I've included a basic pdb for testing below, the location string for the file requires changing.</p> <p>I'm trying to use rust style as much as possible. Any suggestions on code/style improvement, no matter how small, are very welcome, thanks.</p> <p><code>methanol.pdb</code>:</p> <pre><code>COMPND methanol HETATM 1 C UNL 1 -0.372 0.002 0.003 1.00 0.00 C HETATM 2 O UNL 1 0.898 -0.575 -0.119 1.00 0.00 O HETATM 3 H UNL 1 -0.674 -0.119 1.051 1.00 0.00 H HETATM 4 H UNL 1 -0.314 1.066 -0.315 1.00 0.00 H HETATM 5 H UNL 1 -1.083 -0.525 -0.643 1.00 0.00 H HETATM 6 H UNL 1 1.545 0.150 0.024 1.00 0.00 H CONECT 1 2 3 4 5 CONECT 2 6 END </code></pre> <p><code>file_readers.rs</code>:</p> <pre class="lang-rust prettyprint-override"><code>use std::fs; #[derive(Debug)] struct Atom { /// May include atomic charges, masses etc in future atomic_symbol: String, index: i16, coords: (f64, f64, f64), } #[derive(Debug)] struct Bond { atom_1_index: i16, atom_2_index: i16, } pub fn read_pdb() { /// Iterates over lines in any pdb file to produce vec of Atom structs /// Will be expanded in future to build graph of molecule as well let data = fs::read_to_string( "/home/b8009890/Documents/rusty_rockets/src/bin/euler_000_099/methanol.pdb") .expect("Unable to read file"); // vec of strings where each element in vec is a line in the file let lines: Vec&lt;&amp;str&gt; = data.lines().collect(); let name: &amp;str = &amp;lines[0][10..]; let mut molecule = Vec::new(); let mut bonds = Vec::new(); // loop over each element in the vec, starting from the 1st (not 0th) for line in lines[1..].iter() { if &amp;line[..3] == "HET" { // atomic_symbol may be 1/2 chars so it's defined over a range not a specific index let atom = Atom { atomic_symbol: line[13..15].trim().parse::&lt;String&gt;().unwrap(), // pdbs count from 1, hence the -1 index: line[10..13].trim().parse::&lt;i16&gt;().unwrap() - 1, // trim removes whitespace when there isn't a minus sign coords: ( line[32..38].trim().parse::&lt;f64&gt;().unwrap(), line[40..46].trim().parse::&lt;f64&gt;().unwrap(), line[48..54].trim().parse::&lt;f64&gt;().unwrap(), ) }; molecule.push(atom); } else if &amp;line[..3] == "CON" { let parent_index = line[10..13].trim().parse::&lt;usize&gt;().unwrap() - 1; for atom_index in line[14..].split_whitespace() { let child_index = atom_index.parse::&lt;usize&gt;().unwrap() - 1; let bond = Bond { atom_1_index: molecule[parent_index].index, atom_2_index: molecule[child_index].index, }; bonds.push(bond); } } else { break } } println!("{:?}\n{:?}\n{:?}\n", molecule, name, bonds); } </code></pre> <p>Please be aware the very specific ranges for extracting the coords and such are from the official pdb format guide. Occasionally coords can overlap if using high precision e.g. <code>-0.56789-0.12345</code> so generally slicing is used instead of splitting over whitespace.</p> <p>EDIT: After trying to implement a graph structure using petgraph for the molecule, I instead just added a Vec of tuples for my bonds. This seems much easier than a (potentially) cyclic graph; I know they cause issues with the borrowing system. Anyway, the code is updated and now slightly longer than before but not really anymore complex.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T10:22:56.627", "Id": "231090", "Score": "4", "Tags": [ "beginner", "io", "rust" ], "Title": "Molecular .pdb File Reader in Rust" }
231090
<p>I'm trying to follow MVVM pattern in a VB.net WPF application, and I would like to implement <code>IEditableObject</code>. </p> <p>Is this code acceptable for an MVVM application? In particular is it okay to have the <code>IEditableObject</code> implemented here on the Model rather than the ViewModel?</p> <pre><code>Public Class Component : Implements IEditableObject Property Name As String Property Part_Number As String Property Position_Count As Integer Property Stage as Integer Private _stored_properties As Hashtable = Nothing ReadOnly Property Full_Name As String Get Return Name + " " + Stage.ToString() End Get End Property Public Sub BeginEdit() Implements IEditableObject.BeginEdit Dim properties = Me.GetType.GetProperties _stored_properties = New Hashtable(properties.Length - 1) For Each prop In properties If prop.GetSetMethod IsNot Nothing Then _stored_properties.Add(prop.Name, prop.GetValue(Me, Nothing)) Next End Sub Public Sub EndEdit() Implements IEditableObject.EndEdit _stored_properties = Nothing End Sub Public Sub CancelEdit() Implements IEditableObject.CancelEdit If _stored_properties Is Nothing Then Return Dim properties = Me.GetType.GetProperties For Each prop In properties If prop.GetSetMethod IsNot Nothing Then prop.SetValue(Me, _stored_properties(prop.Name)) Next End Sub End Class </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T14:18:24.890", "Id": "450464", "Score": "0", "body": "Do you want a code review, or just an answer to your question? If you just want an answer it might be better to ask on Stack Overflow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T14:25:32.847", "Id": "450466", "Score": "0", "body": "@pacmaninbw Sorry quite inexperienced on this part of SE, I take it both isn't an acceptable answer? I can edit it to just be code review if required?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T14:29:22.960", "Id": "450467", "Score": "0", "body": "No, now that you've clarified what you are looking for it's fine." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T14:03:09.330", "Id": "231102", "Score": "2", "Tags": [ "design-patterns", "vb.net", "wpf", "mvvm" ], "Title": "Is this an acceptable MVVM Model with IEditableObject implementation?" }
231102
<p><a href="https://leetcode.com/problems/shortest-common-supersequence/" rel="nofollow noreferrer">https://leetcode.com/problems/shortest-common-supersequence/</a></p> <blockquote> <p>Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If multiple answers exist, you may return any of them. (A string S is a subsequence of string T if deleting some number of characters from T (possibly 0, and the characters are chosen anywhere from T) results in the string S.)</p> <pre><code>Example 1: Input: str1 = "abac", str2 = "cab" Output: "cabac" Explanation: str1 = "abac" is a subsequence of "cabac" because we can delete the first "c". str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac". The answer provided is the shortest such string that satisfies these properties. Note: 1 &lt;= str1.length, str2.length &lt;= 1000 str1 and str2 consist of lowercase English letters. </code></pre> </blockquote> <p>Please review for performance, I am especially interested about the string concatenation part</p> <pre><code>using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace StringQuestions { /// &lt;summary&gt; /// https://leetcode.com/problems/shortest-common-supersequence/ /// &lt;/summary&gt; [TestClass] public class ShortestCommonSuperSequenceTest { [TestMethod] public void TestMethod1() { string str1 = "abac"; string str2 = "cab"; string expected = "cabac"; Assert.AreEqual(expected, ShortestCommonSuperSequenceClass.ShortestCommonSupersequence(str1, str2)); } [TestMethod] public void TestMethod2() { string str1 = "xxx"; string str2 = "xx"; string expected = "xxx"; Assert.AreEqual(expected, ShortestCommonSuperSequenceClass.ShortestCommonSupersequence(str1, str2)); } [TestMethod] public void TestMethod3() { string str1 = "xxxc"; string str2 = "xxa"; string expected = "xxxca"; Assert.AreEqual(expected, ShortestCommonSuperSequenceClass.ShortestCommonSupersequence(str1, str2)); } } public class ShortestCommonSuperSequenceClass { public static string ShortestCommonSupersequence(string str1, string str2) { if (string.IsNullOrEmpty(str1) || string.IsNullOrEmpty(str2)) { return string.Empty; } int i = 0; int j = 0; string lcs = FindLCS(str1, str2); StringBuilder res = new StringBuilder(); foreach (var letter in lcs) { while (str1[i] != letter) { res.Append(str1[i]); i++; } while (str2[j] != letter) { res.Append(str2[j]); j++; } res.Append(letter); i++; j++; } return res + str1.Substring(i) + str2.Substring(j); } private static string FindLCS(string str1, string str2) { string[,] dp = new string[str1.Length + 1, str2.Length + 1]; for (int i = 0; i &lt; str1.Length+1; i++) { for (int j = 0; j &lt; str2.Length+1; j++) { dp[i, j] = string.Empty; } } for (int i = 0; i &lt; str1.Length; i++) { for (int j = 0; j &lt; str2.Length; j++) { //remember 0 is 0 always if (str1[i] == str2[j]) { dp[i+1, j+1] = dp[i, j] + str1[i]; } else { if (dp[i + 1, j].Length &gt; dp[i, j + 1].Length) { dp[i + 1, j + 1] = dp[i + 1, j]; } else { dp[i + 1, j + 1] = dp[i, j + 1]; } } } } return dp[str1.Length, str2.Length]; } } } </code></pre>
[]
[ { "body": "<p>There are a few places for improvement (in my opinion), but remember - measure! This was written under an assumption that the code works correctly and we do not need any fancy data structures to perform this task. </p>\n\n<h1>Arrays</h1>\n\n<h3>Declaration </h3>\n\n<p>As far as I remember, jagged arrays (<code>[][]</code>) have a better performance than multi dimensional ones (<code>[,]</code>) you could try to measure performance with creating <code>dp</code> as <code>string[][]</code> instead.</p>\n\n<h1>String building </h1>\n\n<h3>Allocation</h3>\n\n<p><code>StringBuilder</code> allocates more memory when it doesn't have any more space to fill. Consider passing an <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.-ctor?view=netframework-4.8#System_Text_StringBuilder__ctor_System_Int32_\" rel=\"nofollow noreferrer\">argument to it's constructor</a> to pre allocate needed size. You can easily get an upper bound but average size (optimal?) would require some testing. </p>\n\n<h3>Building</h3>\n\n<p>For a short strings, string concatenation is faster than using a string builder due to memory allocations. You can take a look <a href=\"https://support.microsoft.com/en-us/help/306822/how-to-improve-string-concatenation-performance-in-visual-c\" rel=\"nofollow noreferrer\">here</a> for some <em>magical</em> guidance. </p>\n\n<h1>Misc</h1>\n\n<h3>Split vs Substring</h3>\n\n<p>Consider using <code>.Split</code> method instead of <code>Substring</code>, I've never personally see any difference but there is <a href=\"https://codereview.stackexchange.com/a/194974/138806\">some evidence</a> that it might actually speed up the execution. </p>\n\n<h3>Unsafe</h3>\n\n<p>You can try to mark your methods as <code>unsafe</code> this will request from the compiler to not check boundaries of the arrays and also will give you access to pointer manipulation. I've seen cases where this improved performance. This might give you a significant performance only with a large number of calls. </p>\n\n<h1>General notes</h1>\n\n<p>Remember, all <code>Substring</code> or string concatenation allocates a new string. I think you should try to figure out how to do this without strings at all! Remember that in reality, characters are just numbers. In my opinion, the main killer here is string concatenation (as you probably guessed). </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-24T14:26:41.587", "Id": "450949", "Score": "0", "body": "@ManLiN2223 thanks a lot, wonderful" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T19:41:47.573", "Id": "231116", "ParentId": "231111", "Score": "3" } }, { "body": "<h3>Review of your code</h3>\n\n<p>The code is written clearly, I have only a few remarks.</p>\n\n<p>The LeetCode problem description states that both <code>str1</code> and <code>str2</code> are <em>non-empty</em> strings, so that this</p>\n\n<pre><code>if (string.IsNullOrEmpty(str1) || string.IsNullOrEmpty(str2))\n{\n return string.Empty;\n}\n</code></pre>\n\n<p>is not necessary. On the other hand, <em>if</em> you want to handle empty strings then the above is not correct: The shortest common supersequence of the empty string and <code>\"abc\"</code> is <code>\"abc\"</code>, not the empty string. So that should be</p>\n\n<pre><code>if (string.IsNullOrEmpty(str1))\n{\n return str2;\n}\nif (string.IsNullOrEmpty(str2))\n{\n return str1;\n}\n</code></pre>\n\n<p>Here</p>\n\n<pre><code>int i = 0;\nint j = 0;\nstring lcs = FindLCS(str1, str2);\nStringBuilder res = new StringBuilder();\nforeach (var letter in lcs) \n{ // ...\n</code></pre>\n\n<p>I would move the declarations of <code>i</code> and <code>j</code> down to where the variables are needed, i.e. directly before the <code>foreach</code> loop.</p>\n\n<p>The attentive reader of your code will of course quickly figure out that</p>\n\n<pre><code>private static string FindLCS(string str1, string str2)\n</code></pre>\n\n<p>determines the “longest common subsequence” but I would use a more verbose function name (or add an explaining comment).</p>\n\n<p>Explaining the used algorithm shortly would also be helpful to understand the code, something like</p>\n\n<pre><code>/*\n The longest common subsequence (LCS) of str1 and str2 is computed with \n dynamic programming. \n\n dp[i, j] is determined as the LCS of the initial i characters of str1\n and the initial j characters of str2.\n\n dp[str1.Length, str2.Length] is then the final result.\n */\n</code></pre>\n\n<p>On the other hand, this comment is mysterious to me:</p>\n\n<pre><code>//remember 0 is 0 always\nif (str1[i] == str2[j])\n</code></pre>\n\n<h3>Performance improvements</h3>\n\n<p><code>str1.Length * str2.Length</code> strings are computed in <code>FindLCS()</code>, and that can be avoided. As explained in <a href=\"https://en.wikipedia.org/wiki/Longest_common_subsequence_problem\" rel=\"nofollow noreferrer\">Wikipedia: Longest common subsequence problem</a>, is is sufficient to store in <code>dp[i, j]</code> the <em>length</em> of the corresponding longest common subsequence, and not the subsequence itself. When the <code>dp</code> array is filled then the longest common subsequence can be determined by deducing the characters in a “traceback” procedure, starting at <code>dp[str1.Length, str2.Length]</code>.</p>\n\n<p>This saves both memory and the time for the string operations.</p>\n\n<p>And this approach can easily be modified to collect the shortest common supersequence instead of the longest common subsequence. That makes your “post processing” in your <code>ShortestCommonSupersequence()</code> function obsolete.</p>\n\n<p>The maximum possible length of the shortest common supersequence is known. Therefore the characters can be collected in an array first, so that string operations and a final string reversing is avoided.</p>\n\n<p>Putting it all together, an implementation could look like this:</p>\n\n<pre><code>public static string ShortestCommonSupersequence(string str1, string str2)\n{\n // Handle empty strings:\n if (string.IsNullOrEmpty(str1))\n {\n return str2;\n }\n if (string.IsNullOrEmpty(str2))\n {\n return str1;\n }\n\n // Dynamic programming: dp[i, j] is computed as the length of the\n // longest common subsequence of str1.Substring(0, i) and\n // str2.SubString(0, j).\n\n int[,] dp = new int[str1.Length + 1, str2.Length + 1];\n for (int i = 0; i &lt; str1.Length; i++)\n {\n for (int j = 0; j &lt; str2.Length; j++)\n {\n if (str1[i] == str2[j])\n {\n dp[i+1, j+1] = dp[i, j] + 1;\n }\n else\n {\n dp[i + 1, j + 1] = Math.Max(dp[i + 1, j], dp[i, j + 1]);\n }\n }\n }\n\n // Traceback: Collect shortest common supersequence. Since the\n // characters are found in reverse order we put them into an array\n // first.\n\n char [] resultBuffer = new char[str1.Length + str2.Length];\n int resultIndex = resultBuffer.Length;\n {\n int i = str1.Length;\n int j = str2.Length;\n while (i &gt; 0 &amp;&amp; j &gt; 0)\n {\n if (str1[i - 1] == str2[j - 1])\n {\n // Common character:\n resultBuffer[--resultIndex] = str1[i - 1];\n i--;\n j--;\n }\n else if (dp[i - 1, j] &gt; dp[i, j - 1])\n {\n // Character from str1:\n resultBuffer[--resultIndex] = str1[i - 1];\n i--;\n }\n else\n {\n // Character from str2:\n resultBuffer[--resultIndex] = str2[j - 1];\n j--;\n }\n }\n // Prepend remaining characters from str1:\n while (i &gt; 0)\n {\n resultBuffer[--resultIndex] = str1[i - 1];\n i--;\n }\n // Prepend remaining characters from str2:\n while (j &gt; 0)\n {\n resultBuffer[--resultIndex] = str2[j - 1];\n j--;\n }\n }\n\n // Create and return result string from buffer.\n return new string(resultBuffer, resultIndex, resultBuffer.Length - resultIndex);\n}\n</code></pre>\n\n<p><em>Comparison:</em> I ran both implementations on LeetCode</p>\n\n<ul>\n<li>Original code: Runtime 372 ms, Memory 48.9 MB.</li>\n<li>Improved code: Runtime 92 ms, Memory 26.1 MB.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-24T14:26:21.437", "Id": "450948", "Score": "0", "body": "thank you very much! as always I appreciate it very much" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T20:22:52.467", "Id": "231230", "ParentId": "231111", "Score": "4" } } ]
{ "AcceptedAnswerId": "231230", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T18:05:04.770", "Id": "231111", "Score": "3", "Tags": [ "c#", "programming-challenge", "dynamic-programming" ], "Title": "LeetCode: Shortest Common Supersequence C#" }
231111
<p>I have implemented a class Vector to learn about data structures and algorithms and how to implement them using C++. I have yet to implement some std::vector functionalities e.g. custom allocator template parameter, iterator/const_iterator classes.</p> <p>I'm learning C++ through a C++11 book and trying to learn C++14 and C++17 best practices on the fly. I would appreciate any advice on how to improve or make it more compatible with modern best practices. I'm using g++ compiler with -std=c++17 flag.</p> <p>One specific issue that I was in doubt was about the move assignment operator. I saw some code around the internet using a unified assignment operator for both copy and move assignment operators using swap, but <a href="http://scottmeyers.blogspot.com/2014/06/the-drawbacks-of-implementing-move.html" rel="noreferrer">this link</a> made me think that it wasn't the best way to do it. Any thoughts?</p> <p>Vector.h</p> <pre><code>namespace algorithms { template&lt;typename T&gt; class Vector { public: using size_type = std::size_t; using iterator = T*; using const_iterator = const T*; using reference = T&amp;; using const_reference = const T&amp;; // Constructors and Destructor Vector(); Vector(size_type initial_size, const T&amp; value); explicit Vector(size_type initial_size); Vector(std::initializer_list&lt;T&gt; initializer); Vector(const Vector&lt;T&gt;&amp; vector); Vector(Vector&lt;T&gt;&amp;&amp; vector) noexcept; Vector&amp; operator=(const Vector&lt;T&gt;&amp; vector); Vector&amp; operator=(Vector&lt;T&gt;&amp;&amp; vector) noexcept; ~Vector(); // Iterators /// TODO: Replace pointers by an iterator class iterator begin() noexcept; const_iterator begin() const noexcept; const_iterator cbegin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; const_iterator cend() const noexcept; // Capacity size_type size() const noexcept; bool empty() const noexcept; size_type capacity() const noexcept; void reserve(size_type new_capacity); void resize(size_type new_size, const T&amp; value); void resize(size_type new_size); void shrink_to_fit(); // Modifiers template&lt;typename... Args&gt; reference emplace_back(Args&amp;&amp;... args); template&lt;typename... Args&gt; iterator emplace(iterator position, Args&amp;&amp;... args); void push_back(const T&amp; value); void push_back(T&amp;&amp; value); void pop_back(); iterator erase(iterator position); iterator erase(iterator first, iterator last); void clear() noexcept; void swap(Vector&lt;T&gt;&amp; vector) noexcept; // Accessors reference operator[](size_type index); const_reference operator[](size_type index) const; reference at(size_type index); const_reference at(size_type index) const; reference back(); const_reference back() const; private: using Alloc = std::allocator&lt;T&gt;; Alloc allocator; T* dynamic_array; T* end_position; // points to one past the last constructed element in the array T* capacity_limit; // points to one past the end of the array void reallocate(size_type new_capacity); void reallocate_if_full(); void deallocate(); void allocate_and_copy(const_iterator begin, const_iterator end); }; // Non-member swap template&lt;typename T&gt; void swap(Vector&lt;T&gt;&amp; left, Vector&lt;T&gt;&amp; right); } </code></pre> <p>Vector.inl</p> <pre><code>namespace algorithms { // Constructors template&lt;typename T&gt; Vector&lt;T&gt;::Vector(): dynamic_array(nullptr), end_position(nullptr), capacity_limit(nullptr) {} template&lt;typename T&gt; Vector&lt;T&gt;::Vector(size_type initial_size, const T&amp; value) { dynamic_array = allocator.allocate(initial_size); end_position = std::uninitialized_fill_n(dynamic_array, initial_size, value); capacity_limit = dynamic_array + initial_size; } template&lt;typename T&gt; Vector&lt;T&gt;::Vector(size_type initial_size): Vector&lt;T&gt;(initial_size, T()) {} template&lt;typename T&gt; Vector&lt;T&gt;::Vector(std::initializer_list&lt;T&gt; initializer) { allocate_and_copy(initializer.begin(), initializer.end()); } template&lt;typename T&gt; Vector&lt;T&gt;::Vector(const Vector&lt;T&gt;&amp; vector) { allocate_and_copy(vector.cbegin(), vector.cend()); } template&lt;typename T&gt; Vector&lt;T&gt;::Vector(Vector&lt;T&gt;&amp;&amp; vector) noexcept: dynamic_array(vector.dynamic_array), end_position(vector.end_position), capacity_limit(vector.capacity_limit) { vector.dynamic_array = nullptr; vector.end_position = nullptr; vector.capacity_limit = nullptr; } template&lt;typename T&gt; Vector&lt;T&gt;&amp; Vector&lt;T&gt;::operator=(const Vector&lt;T&gt;&amp; vector) { Vector&lt;T&gt; temp(vector); swap(temp); return *this; } template&lt;typename T&gt; Vector&lt;T&gt;&amp; Vector&lt;T&gt;::operator=(Vector&lt;T&gt;&amp;&amp; vector) noexcept { if (this != &amp;vector) // protection against self-assignment { deallocate(); dynamic_array = vector.dynamic_array; end_position = vector.end_position; capacity_limit = vector.capacity_limit; vector.dynamic_array = nullptr; vector.end_position = nullptr; vector.capacity_limit = nullptr; } return *this; } template&lt;typename T&gt; Vector&lt;T&gt;::~Vector() { deallocate(); } // Iterators template&lt;typename T&gt; typename Vector&lt;T&gt;::iterator Vector&lt;T&gt;::begin() noexcept { return dynamic_array; } template&lt;typename T&gt; typename Vector&lt;T&gt;::const_iterator Vector&lt;T&gt;::begin() const noexcept { return dynamic_array; } template&lt;typename T&gt; typename Vector&lt;T&gt;::const_iterator Vector&lt;T&gt;::cbegin() const noexcept { return dynamic_array; } template&lt;typename T&gt; typename Vector&lt;T&gt;::iterator Vector&lt;T&gt;::end() noexcept { return end_position; } template&lt;typename T&gt; typename Vector&lt;T&gt;::const_iterator Vector&lt;T&gt;::end() const noexcept { return end_position; } template&lt;typename T&gt; typename Vector&lt;T&gt;::const_iterator Vector&lt;T&gt;::cend() const noexcept { return end_position; } // Capacity template&lt;typename T&gt; typename Vector&lt;T&gt;::size_type Vector&lt;T&gt;::size() const noexcept { return static_cast&lt;size_type&gt;(end_position - dynamic_array); } template&lt;typename T&gt; bool Vector&lt;T&gt;::empty() const noexcept { return size() == 0; } template&lt;typename T&gt; typename Vector&lt;T&gt;::size_type Vector&lt;T&gt;::capacity() const noexcept { return static_cast&lt;size_type&gt;(capacity_limit - dynamic_array); } template&lt;typename T&gt; void Vector&lt;T&gt;::reserve(size_type new_capacity) { if (new_capacity &lt;= capacity()) { return; } reallocate(new_capacity); } template&lt;typename T&gt; void Vector&lt;T&gt;::resize(size_type new_size, const T&amp; value) { if (new_size &gt; capacity()) { reallocate(2 * new_size); end_position = std::uninitialized_fill_n(end_position, new_size - size(), value); } else if (new_size &gt; size()) { end_position = std::uninitialized_fill_n(end_position, new_size - size(), value); } else if (new_size &lt; size()) { for (size_type i = 0; i &lt; size() - new_size; ++i) { --end_position; std::allocator_traits&lt;Alloc&gt;::destroy(allocator, end_position); } } } template&lt;typename T&gt; void Vector&lt;T&gt;::resize(size_type new_size) { resize(new_size, T()); } template&lt;typename T&gt; void Vector&lt;T&gt;::shrink_to_fit() { reallocate(size()); } // Modifiers template&lt;typename T&gt; template&lt;typename... Args&gt; typename Vector&lt;T&gt;::reference Vector&lt;T&gt;::emplace_back(Args&amp;&amp;... args) { reallocate_if_full(); std::allocator_traits&lt;Alloc&gt;::construct(allocator, end_position, std::forward&lt;Args&gt;(args)...); ++end_position; } template&lt;typename T&gt; template&lt;typename... Args&gt; typename Vector&lt;T&gt;::iterator Vector&lt;T&gt;::emplace(iterator position, Args&amp;&amp;... args) { const size_type distance = std::distance(begin(), position); if (position == end_position) { emplace_back(std::forward&lt;Args&gt;(args)...); } else { reallocate_if_full(); std::move_backward(begin() + distance, end_position, end_position + 1); std::allocator_traits&lt;Alloc&gt;::construct(allocator, begin() + distance, std::forward&lt;Args&gt;(args)...); ++end_position; } return begin() + distance; } template&lt;typename T&gt; void Vector&lt;T&gt;::push_back(const T&amp; value) { emplace_back(value); } template&lt;typename T&gt; void Vector&lt;T&gt;::push_back(T&amp;&amp; value) { emplace_back(std::move(value)); } template&lt;typename T&gt; void Vector&lt;T&gt;::pop_back() { --end_position; std::allocator_traits&lt;Alloc&gt;::destroy(allocator, end_position); } template&lt;typename T&gt; typename Vector&lt;T&gt;::iterator Vector&lt;T&gt;::erase(iterator position) { std::move(position + 1, end(), position); --end_position; std::allocator_traits&lt;Alloc&gt;::destroy(allocator, end_position); return position; } template&lt;typename T&gt; typename Vector&lt;T&gt;::iterator Vector&lt;T&gt;::erase(iterator first, iterator last) { if (first == last) { return begin(); } auto new_end_position = std::move(last, end(), first); for (auto iterator = new_end_position; iterator != end_position; ++iterator) { std::allocator_traits&lt;Alloc&gt;::destroy(allocator, iterator); } end_position = new_end_position; return first; } template&lt;typename T&gt; void Vector&lt;T&gt;::clear() noexcept { deallocate(); dynamic_array = nullptr; end_position = nullptr; capacity_limit = nullptr; } template&lt;typename T&gt; void Vector&lt;T&gt;::swap(Vector&lt;T&gt;&amp; vector) noexcept { using std::swap; swap(this-&gt;dynamic_array, vector.dynamic_array); swap(this-&gt;end_position, vector.end_position); swap(this-&gt;capacity_limit, vector.capacity_limit); } // Accessors template&lt;typename T&gt; typename Vector&lt;T&gt;::reference Vector&lt;T&gt;::operator[](size_type index) { return dynamic_array[index]; } template&lt;typename T&gt; typename Vector&lt;T&gt;::const_reference Vector&lt;T&gt;::operator[](size_type index) const { return dynamic_array[index]; } template&lt;typename T&gt; typename Vector&lt;T&gt;::reference Vector&lt;T&gt;::at(size_type index) { if (index &lt; 0 || index &gt;= size()) { throw std::out_of_range("Invalid index"); } return dynamic_array[index]; } template&lt;typename T&gt; typename Vector&lt;T&gt;::const_reference Vector&lt;T&gt;::at(size_type index) const { if (index &lt; 0 || index &gt;= size()) { throw std::out_of_range("Invalid index"); } return dynamic_array[index]; } template&lt;typename T&gt; typename Vector&lt;T&gt;::reference Vector&lt;T&gt;::back() { return dynamic_array[size() - 1]; } template&lt;typename T&gt; typename Vector&lt;T&gt;::const_reference Vector&lt;T&gt;::back() const { return dynamic_array[size() - 1]; } // Private template&lt;typename T&gt; void Vector&lt;T&gt;::reallocate(size_type new_capacity) { auto new_array = allocator.allocate(new_capacity); auto new_end_position = std::uninitialized_copy(std::make_move_iterator(begin()), std::make_move_iterator(end()), new_array); deallocate(); dynamic_array = new_array; end_position = new_end_position; capacity_limit = dynamic_array + new_capacity; } template&lt;typename T&gt; void Vector&lt;T&gt;::reallocate_if_full() { if (size() == capacity()) { size_type new_capacity = (size() != 0) ? 2 * size() : 1; reallocate(new_capacity); } } template&lt;typename T&gt; void Vector&lt;T&gt;::deallocate() { if (dynamic_array) { std::for_each(dynamic_array, end_position, [&amp;allocator = allocator](T&amp; value) { std::allocator_traits&lt;Alloc&gt;::destroy(allocator, &amp;value); }); allocator.deallocate(dynamic_array, capacity_limit - dynamic_array); } } template&lt;typename T&gt; void Vector&lt;T&gt;::allocate_and_copy(const_iterator begin, const_iterator end) { size_type new_capacity = end - begin; dynamic_array = allocator.allocate(new_capacity); end_position = std::uninitialized_copy(begin, end, dynamic_array); capacity_limit = end_position; } // Non-member swap function template&lt;typename T&gt; void swap(Vector&lt;T&gt;&amp; left, Vector&lt;T&gt;&amp; right) { left.swap(right); } } </code></pre>
[]
[ { "body": "<p>Good effort. Still, there are many points even without going into allocator-support:</p>\n\n<ol>\n<li><p>You are missing a very important ctor (and the corresponding deduction guide):</p>\n\n<pre><code>template &lt;class InputIt, SFINAE_here&gt;\nvector(InputIt first, InputIt last);\n</code></pre>\n\n<p>Not only is it very useful in its own right, but copy-ctor and initializer_list-ctor can be trivially implemented in terms of it.</p></li>\n<li><p>You are missing <code>.assign()</code>. The version using an iterator-range would be the preferred building-block for construction from an iterator-range which has to be counted for getting the size.</p></li>\n<li><p>You are missing assignment from initializer_list, <code>.insert()</code>, <code>.data()</code>, and reverse-iterator-support.</p></li>\n<li><p>Members should accept <code>const_iterator</code>s as inputs and return <code>iterator</code>s.</p></li>\n<li><p>You can use the injected class-name (<code>Vector</code>) instead of specifying the template-parameters (<code>Vector&lt;T&gt;</code>). As a bonus, that is future-proof in case you later decide to add the allocator-support.</p></li>\n<li><p><code>std::allocator&lt;T&gt;</code> is a trivial empty class. As such, any space it uses is wasted. Either use empty base optimization or just create it on-demand.</p></li>\n<li><p>You are missing comparison operators.</p></li>\n<li><p>Using in-class-initializers allows you to simplify your ctors. The default ctor can then even be made trivial by <code>= default;</code>-ing it in-class.</p></li>\n<li><p><code>Vector&lt;T&gt;::Vector(size_type initial_size, const T&amp; value)</code> is unsafe. If an exception gets thrown when allocating, all pointer-members are still indeterminate on entrance to the dtor. If one gets thrown later, all but <code>.dynamic_array</code> will be indeterminate, with equally bad results.</p></li>\n<li><p><code>Vector&lt;T&gt;::Vector(size_type initial_size)</code> creates an ephemeral <code>T</code> and then copy-constructs all members using the previous ctor. While that works for many types, for some it is silently wrong, inefficient, or won't even compile.</p></li>\n<li><p>Don't pessimize the common case by checking for self-assignment. Simply swap everything.</p></li>\n<li><p><code>void Vector&lt;T&gt;::resize(size_type new_size, const T&amp; value)</code> really should go for just enough if it has to reallocate.</p></li>\n<li><p>Point 10 also applies to <code>void Vector&lt;T&gt;::resize(size_type new_size)</code>.</p></li>\n<li><p><code>.insert()</code>, <code>.push_back()</code>, and <code>.resize()</code> from a <code>const&amp;</code> must work right even if passed an element of the container!</p></li>\n<li><p><code>.erase(Iter, Iter)</code> should return the passed iterator if the range is empty, not anything else.</p></li>\n<li><p><code>std::uninitialized_move()</code> was introduced in C++17, no need for <code>std::uninitialized_copy()</code> + move-iterators.</p></li>\n<li><p>There is a good reason to avoid doubling capacity on reallocation: If you stay below that, re-use of returned memory becomes possible.</p></li>\n<li><p>Non-member <code>swap()</code> should also be <code>nowxcept</code>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T03:28:16.193", "Id": "450535", "Score": "1", "body": "Thanks for all the suggestions. Really helpful, I'll fix it. Specially 10 and 13, I didn't thought about that; Vector<std::unique_ptr<int>> vector(10) doesn't compile since unique_ptr does not have a copy ctor, right? About the many missing member functions, I will add them progressively; I wanted to see if I was at least starting correctly." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T23:37:42.397", "Id": "231124", "ParentId": "231112", "Score": "4" } } ]
{ "AcceptedAnswerId": "231124", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T18:33:34.840", "Id": "231112", "Score": "6", "Tags": [ "c++", "beginner", "reinventing-the-wheel", "c++17" ], "Title": "Simplified Vector Implementation in C++" }
231112
<p>I'd like some input on my implementation of <code>bst-range</code>, which follows below.</p> <p>Before we can get to bst-range, we first need some setup code to build the BST.</p> <p>(You can imagine that node label <code>count</code> didn't exist if you want, as it's not used for range search).</p> <h2>Setup</h2> <pre class="lang-lisp prettyprint-override"><code>(defstruct (node (:print-function (lambda (n s d) (format s "#&lt;~A ~A ~A ~A&gt;" (node-elt n) (node-l n) (node-r n) (node-count n))))) elt count (l nil) (r nil)) (defun node-size (node) (if (null node) 0 (node-count node))) (defun bst-insert (obj bst &lt;) (if (null bst) (make-node :elt obj :count 1) (let ((elt (node-elt bst))) (if (eql obj elt) bst (if (funcall &lt; obj elt) (let ((new-l (bst-insert obj (node-l bst) &lt;))) (make-node :elt elt :count (+ (node-size new-l) (node-size (node-r bst)) 1) :l new-l :r (node-r bst))) (let ((new-r (bst-insert obj (node-r bst) &lt;))) (make-node :elt elt :count (+ (node-size (node-l bst)) (node-size new-r) 1) :l (node-l bst) :r new-r))))))) </code></pre> <p>The above code was the subject of my <a href="https://codereview.stackexchange.com/questions/230855/bst-with-node-count">earlier question</a> and is working fine. It's assumed here.</p> <h2>Range search</h2> <p>I implemented <code>bst-range</code> by translating the code <a href="https://algs4.cs.princeton.edu/32bst/BST.java.html" rel="nofollow noreferrer">here</a> (where it is referred to as the function <code>keys</code>), and described <a href="https://algs4.cs.princeton.edu/32bst/" rel="nofollow noreferrer">here</a> under the heading "range search".</p> <pre class="lang-lisp prettyprint-override"><code>(defun bst-range (min max bst &lt;) (if (null bst) nil (let ((elt (node-elt bst))) (when (funcall &lt; min elt) (bst-range min max (node-l bst) &lt;)) (when (and (or (eql min elt) (funcall &lt; min elt)) (or (eql max elt) (funcall &lt; elt max))) (setf *result* (cons elt *result*))) (when (funcall &lt; elt max) (bst-range min max (node-r bst) &lt;))))) </code></pre> <p>It runs like this</p> <pre class="lang-lisp prettyprint-override"><code>(defparameter *bst* nil) ; [1] (dolist (x '(1 6 3 7 21 40)) (setf *bst* (bst-insert x *bst* #'&lt;))) [25]&gt; (defparameter *result* nil) ; [2] *RESULT* [26]&gt; (bst-range 5 10 *bst* #'&lt;) ; [3] NIL [27]&gt; *result* ; [4] (7 6) [28]&gt; ;; [1] first build a BST ;; [2] use global var to store result of range search (seems ugly) ;; [3] call the range search ;; [4] see the result ;; Here we are searching for all the entries in the bst between ;; 5 and 10, which are, as we can see from what we inserted, just 6 &amp; 7. </code></pre> <h2>Questions</h2> <ol> <li><p>Is there a nice way to accumulate the result via an optional parameter? I tried (and failed) on that, which is why I ended up with defparameter. Not certain the accumulator is the right path for this function though. Is it? If not, why?</p></li> <li><p>Would some datastructure for result other than a list be better here? If so, why?</p></li> </ol> <h2>Update</h2> <p>Here's another idea for <code>bst-range</code>, implemented via a higher order function.</p> <pre class="lang-lisp prettyprint-override"><code>(defun bst-traverse (fn bst) (when bst (bst-traverse fn (node-l bst)) (funcall fn (node-elt bst)) (bst-traverse fn (node-r bst)))) (defun bst-range (min max bst &lt;) (bst-traverse (lambda (elt) (when (&lt;= min elt max) (princ elt))) ; [1] bst)) ;; [1] We need to enqueue onto some ds here instead of princ. ;; Wondering how best to organise this code... </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T19:27:01.850", "Id": "231114", "Score": "1", "Tags": [ "tree", "binary-search", "common-lisp" ], "Title": "BST range search" }
231114
<p>I'm beginning to learn Go. I've decided to write some file utilities to help me with some bigger projects I intend to write. Coming from mainly a Python background, I'm sure there are plenty of stylistic and efficiency improvements to be made. I'm looking for general feedback, as I want to kick bad habits to the curb before they set it. Feedback such as:</p> <ul> <li>Error Reporting</li> <li>Use of <code>defer</code> in <code>appendContent</code> function</li> <li>Testing Functions: Are there any libraries to help accomplish this, like how Python has <code>unittest</code>?</li> </ul> <p>I use more comments than I usually would when programming because I'm still learning the language. The <code>Usage:</code> comments help me remember why I'm importing these libraries. Besides the specifically requested feedback, any and all criticism is welcome and appreciated!</p> <h1>Utilities</h1> <pre><code>package main import ( "fmt" // Usage: Printing errors and content of the files "io/ioutil" // Usage: Reading and writing files "os" // Usage: Opening files and appending to them ) func main() { testFunctions() } func testFunctions() { /* This method is solely for the purpose of testing the below methods */ writeContent("test.txt", "Test Content") fmt.Println(getContent("test.txt")) appendContent("test.txt", "Test Content 2") fmt.Println(getContent("test.txt")) } func getContent(file string) string { /* Gets the content from the passed `file` */ content, err := ioutil.ReadFile(file) if err != nil { fmt.Println(err) return "[NOT CONTENT]: AN ERROR OCCURED" } return string(content) } func writeContent(file string, content string) { /* Writes the passed `content`, creating a new file at `file` */ formattedContent := []byte(content) err := ioutil.WriteFile(file, formattedContent, 0777) if err != nil { fmt.Println(err) } } func appendContent(file string, content string) { /* Appends the passed `content` to the end of the passed `file` */ fileToAppend, err := os.OpenFile(file, os.O_APPEND|os.O_WRONLY, 0600) if err != nil { panic(err) } defer fileToAppend.Close() _, err = fileToAppend.WriteString(content) if err != nil { panic(err) } } </code></pre>
[]
[ { "body": "<p>Regarding testing: Yes, it's <a href=\"https://golang.org/pkg/testing/\" rel=\"nofollow noreferrer\">in the standard library</a>. There are of course more libraries to help out more, but that's where you should likely start your journey.</p>\n\n<hr>\n\n<p>For error reporting, well, it's a bit inconsistent at the moment? There's both returning a value (<code>[NOT CONTENT]...</code>) as well as <code>fmt.Println</code> <em>and</em> <code>panic</code> too, all of which are not very appropriate for production usage.</p>\n\n<p>The first of which can lead to <em>serious</em> debugging nightmares: How do you know the file didn't contain that exact string for one? This is always a problem if the valid values are mixed with error values (like how in most C APIs there are <code>int</code> return values with <code>-1</code> for errors, while everything <span class=\"math-container\">\\$&gt;= 0\\$</span> are the \"actual\" return values in the non-error case)! It's much better to keep them separate, which in Go could be done with separate types, or separate return values (which is what's done for errors).</p>\n\n<p>The second one is perhaps less bad, but again, the error situation is just hidden, not actually dealt with.</p>\n\n<p>The third one can be done, however it's usually reserved for programming errors, since not catching a <code>panic</code> call will simply abort the program (which is rarely what you want).</p>\n\n<p>If in doubt, return an <code>error</code> in addition to any values: <code>func getContent(string) (string, error)</code> and <code>writeContent/appendContent(string, string) error</code> would be fine. Maybe also <a href=\"https://blog.golang.org/error-handling-and-go\" rel=\"nofollow noreferrer\">see this blog post</a> and <a href=\"https://blog.golang.org/go1.13-errors\" rel=\"nofollow noreferrer\">this newer one</a> for 1.13.</p>\n\n<hr>\n\n<p>The <code>defer</code> to close files is pretty much required in my opinion. Unless you can prove that nothing else between the opening of the file and the <code>Close</code> call can raise a <code>panic</code>, you pretty much <em>have</em> to use <code>defer ...Close()</code>, otherwise you risk leaking resources (open file handles).</p>\n\n<p>For the comments, please <a href=\"https://blog.golang.org/godoc-documenting-go-code\" rel=\"nofollow noreferrer\">have a look here</a>: Instead of comments simply add proper docstrings to the functions, that is good practice anyway and would certainly be appreciated by colleagues on bigger projects.</p>\n\n<p>Maybe as a last note: The permissions <code>0777</code> and <code>0600</code> are okay if those are the ones you want. However, that might not be true in general. Exactly how <code>ioutil.WriteFile</code> lets you specify them would be likely what you want in general. If not, consider creating constants so that you don't have magic numbers inline with the code (e.g. <code>const defaultFilePermissions = 0777</code> or something similar).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T10:17:27.750", "Id": "231134", "ParentId": "231118", "Score": "2" } } ]
{ "AcceptedAnswerId": "231134", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T21:21:43.283", "Id": "231118", "Score": "3", "Tags": [ "beginner", "file", "go" ], "Title": "File Utilities in Go" }
231118